diff --git a/.gitattributes b/.gitattributes index a6344aac8c09253b3b630fb776ae94478aa0275b..374ccc52ebb7b80c199ddd63eb894000665fe0de 100644 --- a/.gitattributes +++ b/.gitattributes @@ -33,3 +33,13 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text *.zip filter=lfs diff=lfs merge=lfs -text *.zst filter=lfs diff=lfs merge=lfs -text *tfevents* filter=lfs diff=lfs merge=lfs -text +dist/fonts/JetBrains/JetBrainsMono-Italic-VariableFont_wght.ttf filter=lfs diff=lfs merge=lfs -text +dist/fonts/JetBrains/JetBrainsMono-VariableFont_wght.ttf filter=lfs diff=lfs merge=lfs -text +dist/fonts/Söhne/Söhne-Buch.otf filter=lfs diff=lfs merge=lfs -text +dist/fonts/Söhne/Söhne-Kräftig.otf filter=lfs diff=lfs merge=lfs -text +dist/fonts/Söhne/Söhne-Leicht.otf filter=lfs diff=lfs merge=lfs -text +public/fonts/JetBrains/JetBrainsMono-Italic-VariableFont_wght.ttf filter=lfs diff=lfs merge=lfs -text +public/fonts/JetBrains/JetBrainsMono-VariableFont_wght.ttf filter=lfs diff=lfs merge=lfs -text +public/fonts/Söhne/Söhne-Buch.otf filter=lfs diff=lfs merge=lfs -text +public/fonts/Söhne/Söhne-Kräftig.otf filter=lfs diff=lfs merge=lfs -text +public/fonts/Söhne/Söhne-Leicht.otf filter=lfs diff=lfs merge=lfs -text diff --git a/README.md b/README.md index 7b3bbe125c10b6cc03621653afc3374ec1b3db0b..55af7bc2f1a75f4a429a1ff87cb806e51bf1ab36 100644 --- a/README.md +++ b/README.md @@ -1,10 +1,16 @@ --- title: LFM2 VL WebGPU -emoji: 🌍 +emoji: 📹 colorFrom: blue colorTo: purple sdk: static pinned: false +short_description: Real-time video captioning in your browser +models: +- LiquidAI/LFM2-VL-450M +- onnx-community/LFM2-VL-450M-ONNX +thumbnail: https://cdn-uploads.huggingface.co/production/uploads/61b253b7ac5ecaae3d1efe0c/Obs_kK1de825UGpsBIuAI.png +app_file: dist/index.html --- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference diff --git a/dist/assets/index-BD4hRAJu.js b/dist/assets/index-BD4hRAJu.js new file mode 100644 index 0000000000000000000000000000000000000000..2784d8f6199e2090c596ba91d6352efc5fe1998a --- /dev/null +++ b/dist/assets/index-BD4hRAJu.js @@ -0,0 +1,4805 @@ +var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),s=(e,n)=>{let r={};for(var i in e)t(r,i,{get:e[i],enumerable:!0});return n||t(r,Symbol.toStringTag,{value:`Module`}),r},c=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;li[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},l=(n,r,a)=>(a=n==null?{}:e(i(n)),c(r||!n||!n.__esModule?t(a,`default`,{value:n,enumerable:!0}):a,n)),u=(e=>typeof require<`u`?require:typeof Proxy<`u`?new Proxy(e,{get:(e,t)=>(typeof require<`u`?require:e)[t]}):e)(function(e){if(typeof require<`u`)return require.apply(this,arguments);throw Error('Calling `require` for "'+e+"\" in an environment that doesn't expose the `require` function. See https://rolldown.rs/in-depth/bundling-cjs#require-external-modules for more details.")});(function(){let e=document.createElement(`link`).relList;if(e&&e.supports&&e.supports(`modulepreload`))return;for(let e of document.querySelectorAll(`link[rel="modulepreload"]`))n(e);new MutationObserver(e=>{for(let t of e)if(t.type===`childList`)for(let e of t.addedNodes)e.tagName===`LINK`&&e.rel===`modulepreload`&&n(e)}).observe(document,{childList:!0,subtree:!0});function t(e){let t={};return e.integrity&&(t.integrity=e.integrity),e.referrerPolicy&&(t.referrerPolicy=e.referrerPolicy),e.crossOrigin===`use-credentials`?t.credentials=`include`:e.crossOrigin===`anonymous`?t.credentials=`omit`:t.credentials=`same-origin`,t}function n(e){if(e.ep)return;e.ep=!0;let n=t(e);fetch(e.href,n)}})();var d=o((e=>{var t=Symbol.for(`react.transitional.element`),n=Symbol.for(`react.portal`),r=Symbol.for(`react.fragment`),i=Symbol.for(`react.strict_mode`),a=Symbol.for(`react.profiler`),o=Symbol.for(`react.consumer`),s=Symbol.for(`react.context`),c=Symbol.for(`react.forward_ref`),l=Symbol.for(`react.suspense`),u=Symbol.for(`react.memo`),d=Symbol.for(`react.lazy`),f=Symbol.for(`react.activity`),p=Symbol.iterator;function m(e){return typeof e!=`object`||!e?null:(e=p&&e[p]||e[`@@iterator`],typeof e==`function`?e:null)}var h={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},g=Object.assign,_={};function v(e,t,n){this.props=e,this.context=t,this.refs=_,this.updater=n||h}v.prototype.isReactComponent={},v.prototype.setState=function(e,t){if(typeof e!=`object`&&typeof e!=`function`&&e!=null)throw Error(`takes an object of state variables to update or a function which returns an object of state variables.`);this.updater.enqueueSetState(this,e,t,`setState`)},v.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,`forceUpdate`)};function y(){}y.prototype=v.prototype;function b(e,t,n){this.props=e,this.context=t,this.refs=_,this.updater=n||h}var x=b.prototype=new y;x.constructor=b,g(x,v.prototype),x.isPureReactComponent=!0;var S=Array.isArray;function C(){}var w={H:null,A:null,T:null,S:null},T=Object.prototype.hasOwnProperty;function E(e,n,r){var i=r.ref;return{$$typeof:t,type:e,key:n,ref:i===void 0?null:i,props:r}}function D(e,t){return E(e.type,t,e.props)}function O(e){return typeof e==`object`&&!!e&&e.$$typeof===t}function k(e){var t={"=":`=0`,":":`=2`};return`$`+e.replace(/[=:]/g,function(e){return t[e]})}var A=/\/+/g;function j(e,t){return typeof e==`object`&&e&&e.key!=null?k(``+e.key):t.toString(36)}function ee(e){switch(e.status){case`fulfilled`:return e.value;case`rejected`:throw e.reason;default:switch(typeof e.status==`string`?e.then(C,C):(e.status=`pending`,e.then(function(t){e.status===`pending`&&(e.status=`fulfilled`,e.value=t)},function(t){e.status===`pending`&&(e.status=`rejected`,e.reason=t)})),e.status){case`fulfilled`:return e.value;case`rejected`:throw e.reason}}throw e}function M(e,r,i,a,o){var s=typeof e;(s===`undefined`||s===`boolean`)&&(e=null);var c=!1;if(e===null)c=!0;else switch(s){case`bigint`:case`string`:case`number`:c=!0;break;case`object`:switch(e.$$typeof){case t:case n:c=!0;break;case d:return c=e._init,M(c(e._payload),r,i,a,o)}}if(c)return o=o(e),c=a===``?`.`+j(e,0):a,S(o)?(i=``,c!=null&&(i=c.replace(A,`$&/`)+`/`),M(o,r,i,``,function(e){return e})):o!=null&&(O(o)&&(o=D(o,i+(o.key==null||e&&e.key===o.key?``:(``+o.key).replace(A,`$&/`)+`/`)+c)),r.push(o)),1;c=0;var l=a===``?`.`:a+`:`;if(S(e))for(var u=0;u{t.exports=d()})),p=o((e=>{function t(e,t){var n=e.length;e.push(t);a:for(;0>>1,a=e[r];if(0>>1;ri(c,n))li(u,c)?(e[r]=u,e[l]=n,r=l):(e[r]=c,e[s]=n,r=s);else if(li(u,n))e[r]=u,e[l]=n,r=l;else break a}}return t}function i(e,t){var n=e.sortIndex-t.sortIndex;return n===0?e.id-t.id:n}if(e.unstable_now=void 0,typeof performance==`object`&&typeof performance.now==`function`){var a=performance;e.unstable_now=function(){return a.now()}}else{var o=Date,s=o.now();e.unstable_now=function(){return o.now()-s}}var c=[],l=[],u=1,d=null,f=3,p=!1,m=!1,h=!1,g=!1,_=typeof setTimeout==`function`?setTimeout:null,v=typeof clearTimeout==`function`?clearTimeout:null,y=typeof setImmediate<`u`?setImmediate:null;function b(e){for(var i=n(l);i!==null;){if(i.callback===null)r(l);else if(i.startTime<=e)r(l),i.sortIndex=i.expirationTime,t(c,i);else break;i=n(l)}}function x(e){if(h=!1,b(e),!m)if(n(c)!==null)m=!0,S||(S=!0,O());else{var t=n(l);t!==null&&j(x,t.startTime-e)}}var S=!1,C=-1,w=5,T=-1;function E(){return g?!0:!(e.unstable_now()-Tt&&E());){var o=d.callback;if(typeof o==`function`){d.callback=null,f=d.priorityLevel;var s=o(d.expirationTime<=t);if(t=e.unstable_now(),typeof s==`function`){d.callback=s,b(t),i=!0;break b}d===n(c)&&r(c),b(t)}else r(c);d=n(c)}if(d!==null)i=!0;else{var u=n(l);u!==null&&j(x,u.startTime-t),i=!1}}break a}finally{d=null,f=a,p=!1}i=void 0}}finally{i?O():S=!1}}}var O;if(typeof y==`function`)O=function(){y(D)};else if(typeof MessageChannel<`u`){var k=new MessageChannel,A=k.port2;k.port1.onmessage=D,O=function(){A.postMessage(null)}}else O=function(){_(D,0)};function j(t,n){C=_(function(){t(e.unstable_now())},n)}e.unstable_IdlePriority=5,e.unstable_ImmediatePriority=1,e.unstable_LowPriority=4,e.unstable_NormalPriority=3,e.unstable_Profiling=null,e.unstable_UserBlockingPriority=2,e.unstable_cancelCallback=function(e){e.callback=null},e.unstable_forceFrameRate=function(e){0>e||125o?(r.sortIndex=a,t(l,r),n(c)===null&&r===n(l)&&(h?(v(C),C=-1):h=!0,j(x,a-o))):(r.sortIndex=s,t(c,r),m||p||(m=!0,S||(S=!0,O()))),r},e.unstable_shouldYield=E,e.unstable_wrapCallback=function(e){var t=f;return function(){var n=f;f=t;try{return e.apply(this,arguments)}finally{f=n}}}})),m=o(((e,t)=>{t.exports=p()})),h=o((e=>{var t=f();function n(e){var t=`https://react.dev/errors/`+e;if(1{function n(){if(!(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>`u`||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!=`function`))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(n)}catch(e){console.error(e)}}n(),t.exports=h()})),_=o((e=>{var t=m(),n=f(),r=g();function i(e){var t=`https://react.dev/errors/`+e;if(1ie||(e.current=re[ie],re[ie]=null,ie--)}function se(e,t){ie++,re[ie]=e.current,e.current=t}var ce=ae(null),le=ae(null),ue=ae(null),de=ae(null);function fe(e,t){switch(se(ue,t),se(le,e),se(ce,null),t.nodeType){case 9:case 11:e=(e=t.documentElement)&&(e=e.namespaceURI)?qd(e):0;break;default:if(e=t.tagName,t=t.namespaceURI)t=qd(t),e=Jd(t,e);else switch(e){case`svg`:e=1;break;case`math`:e=2;break;default:e=0}}oe(ce),se(ce,e)}function pe(){oe(ce),oe(le),oe(ue)}function me(e){e.memoizedState!==null&&se(de,e);var t=ce.current,n=Jd(t,e.type);t!==n&&(se(le,e),se(ce,n))}function he(e){le.current===e&&(oe(ce),oe(le)),de.current===e&&(oe(de),ip._currentValue=ne)}var ge,I;function _e(e){if(ge===void 0)try{throw Error()}catch(e){var t=e.stack.trim().match(/\n( *(at )?)/);ge=t&&t[1]||``,I=-1)`:-1i||c[r]!==l[i]){var u=` +`+c[r].replace(` at new `,` at `);return e.displayName&&u.includes(``)&&(u=u.replace(``,e.displayName)),u}while(1<=r&&0<=i);break}}}finally{ve=!1,Error.prepareStackTrace=n}return(n=e?e.displayName||e.name:``)?_e(n):``}function L(e,t){switch(e.tag){case 26:case 27:case 5:return _e(e.type);case 16:return _e(`Lazy`);case 13:return e.child!==t&&t!==null?_e(`Suspense Fallback`):_e(`Suspense`);case 19:return _e(`SuspenseList`);case 0:case 15:return ye(e.type,!1);case 11:return ye(e.type.render,!1);case 1:return ye(e.type,!0);case 31:return _e(`Activity`);default:return``}}function R(e){try{var t=``,n=null;do t+=L(e,n),n=e,e=e.return;while(e);return t}catch(e){return` +Error generating stack: `+e.message+` +`+e.stack}}var z=Object.prototype.hasOwnProperty,be=t.unstable_scheduleCallback,xe=t.unstable_cancelCallback,Se=t.unstable_shouldYield,Ce=t.unstable_requestPaint,we=t.unstable_now,Te=t.unstable_getCurrentPriorityLevel,Ee=t.unstable_ImmediatePriority,De=t.unstable_UserBlockingPriority,Oe=t.unstable_NormalPriority,ke=t.unstable_LowPriority,Ae=t.unstable_IdlePriority,je=t.log,Me=t.unstable_setDisableYieldValue,Ne=null,Pe=null;function Fe(e){if(typeof je==`function`&&Me(e),Pe&&typeof Pe.setStrictMode==`function`)try{Pe.setStrictMode(Ne,e)}catch{}}var Ie=Math.clz32?Math.clz32:ze,Le=Math.log,Re=Math.LN2;function ze(e){return e>>>=0,e===0?32:31-(Le(e)/Re|0)|0}var Be=256,Ve=262144,He=4194304;function Ue(e){var t=e&42;if(t!==0)return t;switch(e&-e){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:return 64;case 128:return 128;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:return e&261888;case 262144:case 524288:case 1048576:case 2097152:return e&3932160;case 4194304:case 8388608:case 16777216:case 33554432:return e&62914560;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return e}}function We(e,t,n){var r=e.pendingLanes;if(r===0)return 0;var i=0,a=e.suspendedLanes,o=e.pingedLanes;e=e.warmLanes;var s=r&134217727;return s===0?(s=r&~a,s===0?o===0?n||(n=r&~e,n!==0&&(i=Ue(n))):i=Ue(o):i=Ue(s)):(r=s&~a,r===0?(o&=s,o===0?n||(n=s&~e,n!==0&&(i=Ue(n))):i=Ue(o)):i=Ue(r)),i===0?0:t!==0&&t!==i&&(t&a)===0&&(a=i&-i,n=t&-t,a>=n||a===32&&n&4194048)?t:i}function Ge(e,t){return(e.pendingLanes&~(e.suspendedLanes&~e.pingedLanes)&t)===0}function Ke(e,t){switch(e){case 1:case 2:case 4:case 8:case 64:return t+250;case 16:case 32:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return t+5e3;case 4194304:case 8388608:case 16777216:case 33554432:return-1;case 67108864:case 134217728:case 268435456:case 536870912:case 1073741824:return-1;default:return-1}}function qe(){var e=He;return He<<=1,!(He&62914560)&&(He=4194304),e}function Je(e){for(var t=[],n=0;31>n;n++)t.push(e);return t}function Ye(e,t){e.pendingLanes|=t,t!==268435456&&(e.suspendedLanes=0,e.pingedLanes=0,e.warmLanes=0)}function Xe(e,t,n,r,i,a){var o=e.pendingLanes;e.pendingLanes=n,e.suspendedLanes=0,e.pingedLanes=0,e.warmLanes=0,e.expiredLanes&=n,e.entangledLanes&=n,e.errorRecoveryDisabledLanes&=n,e.shellSuspendCounter=0;var s=e.entanglements,c=e.expirationTimes,l=e.hiddenUpdates;for(n=o&~n;0`u`||window.document===void 0||window.document.createElement===void 0),ln=!1;if(cn)try{var un={};Object.defineProperty(un,`passive`,{get:function(){ln=!0}}),window.addEventListener(`test`,un,un),window.removeEventListener(`test`,un,un)}catch{ln=!1}var dn=null,fn=null,pn=null;function mn(){if(pn)return pn;var e,t=fn,n=t.length,r,i=`value`in dn?dn.value:dn.textContent,a=i.length;for(e=0;e=Gn),Jn=` `,Yn=!1;function Xn(e,t){switch(e){case`keyup`:return Un.indexOf(t.keyCode)!==-1;case`keydown`:return t.keyCode!==229;case`keypress`:case`mousedown`:case`focusout`:return!0;default:return!1}}function Zn(e){return e=e.detail,typeof e==`object`&&`data`in e?e.data:null}var Qn=!1;function $n(e,t){switch(e){case`compositionend`:return Zn(t);case`keypress`:return t.which===32?(Yn=!0,Jn):null;case`textInput`:return e=t.data,e===Jn&&Yn?null:e;default:return null}}function er(e,t){if(Qn)return e===`compositionend`||!Wn&&Xn(e,t)?(e=mn(),pn=fn=dn=null,Qn=!1,e):null;switch(e){case`paste`:return null;case`keypress`:if(!(t.ctrlKey||t.altKey||t.metaKey)||t.ctrlKey&&t.altKey){if(t.char&&1=t)return{node:n,offset:t-e};e=r}a:{for(;n;){if(n.nextSibling){n=n.nextSibling;break a}n=n.parentNode}n=void 0}n=br(n)}}function Sr(e,t){return e&&t?e===t?!0:e&&e.nodeType===3?!1:t&&t.nodeType===3?Sr(e,t.parentNode):`contains`in e?e.contains(t):e.compareDocumentPosition?!!(e.compareDocumentPosition(t)&16):!1:!1}function Cr(e){e=e!=null&&e.ownerDocument!=null&&e.ownerDocument.defaultView!=null?e.ownerDocument.defaultView:window;for(var t=Ft(e.document);t instanceof e.HTMLIFrameElement;){try{var n=typeof t.contentWindow.location.href==`string`}catch{n=!1}if(n)e=t.contentWindow;else break;t=Ft(e.document)}return t}function wr(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t&&(t===`input`&&(e.type===`text`||e.type===`search`||e.type===`tel`||e.type===`url`||e.type===`password`)||t===`textarea`||e.contentEditable===`true`)}var Tr=cn&&`documentMode`in document&&11>=document.documentMode,Er=null,Dr=null,Or=null,kr=!1;function Ar(e,t,n){var r=n.window===n?n.document:n.nodeType===9?n:n.ownerDocument;kr||Er==null||Er!==Ft(r)||(r=Er,`selectionStart`in r&&wr(r)?r={start:r.selectionStart,end:r.selectionEnd}:(r=(r.ownerDocument&&r.ownerDocument.defaultView||window).getSelection(),r={anchorNode:r.anchorNode,anchorOffset:r.anchorOffset,focusNode:r.focusNode,focusOffset:r.focusOffset}),Or&&yr(Or,r)||(Or=r,r=jd(Dr,`onSelect`),0>=o,i-=o,xi=1<<32-Ie(t)+i|n<h?(g=d,d=null):g=d.sibling;var _=p(i,d,s[h],c);if(_===null){d===null&&(d=g);break}e&&d&&_.alternate===null&&t(i,d),a=o(_,a,h),u===null?l=_:u.sibling=_,u=_,d=g}if(h===s.length)return n(i,d),Ai&&Ci(i,h),l;if(d===null){for(;hg?(_=h,h=null):_=h.sibling;var y=p(a,h,v.value,l);if(y===null){h===null&&(h=_);break}e&&h&&y.alternate===null&&t(a,h),s=o(y,s,g),d===null?u=y:d.sibling=y,d=y,h=_}if(v.done)return n(a,h),Ai&&Ci(a,g),u;if(h===null){for(;!v.done;g++,v=c.next())v=f(a,v.value,l),v!==null&&(s=o(v,s,g),d===null?u=v:d.sibling=v,d=v);return Ai&&Ci(a,g),u}for(h=r(h);!v.done;g++,v=c.next())v=m(h,a,g,v.value,l),v!==null&&(e&&v.alternate!==null&&h.delete(v.key===null?g:v.key),s=o(v,s,g),d===null?u=v:d.sibling=v,d=v);return e&&h.forEach(function(e){return t(a,e)}),Ai&&Ci(a,g),u}function b(e,r,o,c){if(typeof o==`object`&&o&&o.type===y&&o.key===null&&(o=o.props.children),typeof o==`object`&&o){switch(o.$$typeof){case _:a:{for(var l=o.key;r!==null;){if(r.key===l){if(l=o.type,l===y){if(r.tag===7){n(e,r.sibling),c=a(r,o.props.children),c.return=e,e=c;break a}}else if(r.elementType===l||typeof l==`object`&&l&&l.$$typeof===O&&xa(l)===r.type){n(e,r.sibling),c=a(r,o.props),Oa(c,o),c.return=e,e=c;break a}n(e,r);break}else t(e,r);r=r.sibling}o.type===y?(c=li(o.props.children,e.mode,c,o.key),c.return=e,e=c):(c=ci(o.type,o.key,o.props,null,e.mode,c),Oa(c,o),c.return=e,e=c)}return s(e);case v:a:{for(l=o.key;r!==null;){if(r.key===l)if(r.tag===4&&r.stateNode.containerInfo===o.containerInfo&&r.stateNode.implementation===o.implementation){n(e,r.sibling),c=a(r,o.children||[]),c.return=e,e=c;break a}else{n(e,r);break}else t(e,r);r=r.sibling}c=fi(o,e.mode,c),c.return=e,e=c}return s(e);case O:return o=xa(o),b(e,r,o,c)}if(P(o))return h(e,r,o,c);if(ee(o)){if(l=ee(o),typeof l!=`function`)throw Error(i(150));return o=l.call(o),g(e,r,o,c)}if(typeof o.then==`function`)return b(e,r,Da(o),c);if(o.$$typeof===C)return b(e,r,Zi(e,o),c);ka(e,o)}return typeof o==`string`&&o!==``||typeof o==`number`||typeof o==`bigint`?(o=``+o,r!==null&&r.tag===6?(n(e,r.sibling),c=a(r,o),c.return=e,e=c):(n(e,r),c=ui(o,e.mode,c),c.return=e,e=c),s(e)):n(e,r)}return function(e,t,n,r){try{Ea=0;var i=b(e,t,n,r);return Ta=null,i}catch(t){if(t===ha||t===_a)throw t;var a=ii(29,t,null,e.mode);return a.lanes=r,a.return=e,a}}}var ja=Aa(!0),Ma=Aa(!1),Na=!1;function Pa(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function Fa(e,t){e=e.updateQueue,t.updateQueue===e&&(t.updateQueue={baseState:e.baseState,firstBaseUpdate:e.firstBaseUpdate,lastBaseUpdate:e.lastBaseUpdate,shared:e.shared,callbacks:null})}function Ia(e){return{lane:e,tag:0,payload:null,callback:null,next:null}}function La(e,t,n){var r=e.updateQueue;if(r===null)return null;if(r=r.shared,Rl&2){var i=r.pending;return i===null?t.next=t:(t.next=i.next,i.next=t),r.pending=t,t=ti(e),ei(e,null,n),t}return Zr(e,r,t,n),ti(e)}function Ra(e,t,n){if(t=t.updateQueue,t!==null&&(t=t.shared,n&4194048)){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,Qe(e,n)}}function za(e,t){var n=e.updateQueue,r=e.alternate;if(r!==null&&(r=r.updateQueue,n===r)){var i=null,a=null;if(n=n.firstBaseUpdate,n!==null){do{var o={lane:n.lane,tag:n.tag,payload:n.payload,callback:null,next:null};a===null?i=a=o:a=a.next=o,n=n.next}while(n!==null);a===null?i=a=t:a=a.next=t}else i=a=t;n={baseState:r.baseState,firstBaseUpdate:i,lastBaseUpdate:a,shared:r.shared,callbacks:r.callbacks},e.updateQueue=n;return}e=n.lastBaseUpdate,e===null?n.firstBaseUpdate=t:e.next=t,n.lastBaseUpdate=t}var Ba=!1;function Va(){if(Ba){var e=sa;if(e!==null)throw e}}function Ha(e,t,n,r){Ba=!1;var i=e.updateQueue;Na=!1;var a=i.firstBaseUpdate,o=i.lastBaseUpdate,s=i.shared.pending;if(s!==null){i.shared.pending=null;var c=s,l=c.next;c.next=null,o===null?a=l:o.next=l,o=c;var u=e.alternate;u!==null&&(u=u.updateQueue,s=u.lastBaseUpdate,s!==o&&(s===null?u.firstBaseUpdate=l:s.next=l,u.lastBaseUpdate=c))}if(a!==null){var d=i.baseState;o=0,u=l=c=null,s=a;do{var f=s.lane&-536870913,m=f!==s.lane;if(m?(Vl&f)===f:(r&f)===f){f!==0&&f===oa&&(Ba=!0),u!==null&&(u=u.next={lane:0,tag:s.tag,payload:s.payload,callback:null,next:null});a:{var h=e,g=s;f=t;var _=n;switch(g.tag){case 1:if(h=g.payload,typeof h==`function`){d=h.call(_,d,f);break a}d=h;break a;case 3:h.flags=h.flags&-65537|128;case 0:if(h=g.payload,f=typeof h==`function`?h.call(_,d,f):h,f==null)break a;d=p({},d,f);break a;case 2:Na=!0}}f=s.callback,f!==null&&(e.flags|=64,m&&(e.flags|=8192),m=i.callbacks,m===null?i.callbacks=[f]:m.push(f))}else m={lane:f,tag:s.tag,payload:s.payload,callback:s.callback,next:null},u===null?(l=u=m,c=d):u=u.next=m,o|=f;if(s=s.next,s===null){if(s=i.shared.pending,s===null)break;m=s,s=m.next,m.next=null,i.lastBaseUpdate=m,i.shared.pending=null}}while(1);u===null&&(c=d),i.baseState=c,i.firstBaseUpdate=l,i.lastBaseUpdate=u,a===null&&(i.shared.lanes=0),Jl|=o,e.lanes=o,e.memoizedState=d}}function Ua(e,t){if(typeof e!=`function`)throw Error(i(191,e));e.call(t)}function Wa(e,t){var n=e.callbacks;if(n!==null)for(e.callbacks=null,e=0;ea?a:8;var o=F.T,s={};F.T=s,js(e,!1,t,n);try{var c=i(),l=F.S;l!==null&&l(s,c),typeof c==`object`&&c&&typeof c.then==`function`?As(e,t,la(c,r),gu(e)):As(e,t,r,gu(e))}catch(n){As(e,t,{then:function(){},status:`rejected`,reason:n},gu())}finally{te.p=a,o!==null&&s.types!==null&&(o.types=s.types),F.T=o}}function bs(){}function xs(e,t,n,r){if(e.tag!==5)throw Error(i(476));var a=Ss(e).queue;ys(e,a,t,ne,n===null?bs:function(){return Cs(e),n(r)})}function Ss(e){var t=e.memoizedState;if(t!==null)return t;t={memoizedState:ne,baseState:ne,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:Mo,lastRenderedState:ne},next:null};var n={};return t.next={memoizedState:n,baseState:n,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:Mo,lastRenderedState:n},next:null},e.memoizedState=t,e=e.alternate,e!==null&&(e.memoizedState=t),t}function Cs(e){var t=Ss(e);t.next===null&&(t=e.alternate.memoizedState),As(e,t.next.queue,{},gu())}function ws(){return W(ip)}function Ts(){return Do().memoizedState}function Es(){return Do().memoizedState}function Ds(e){for(var t=e.return;t!==null;){switch(t.tag){case 24:case 3:var n=gu();e=Ia(n);var r=La(t,e,n);r!==null&&(vu(r,t,n),Ra(r,t,n)),t={cache:na()},e.payload=t;return}t=t.return}}function Os(e,t,n){var r=gu();n={lane:r,revertLane:0,gesture:null,action:n,hasEagerState:!1,eagerState:null,next:null},Ms(e)?Ns(t,n):(n=Qr(e,t,n,r),n!==null&&(vu(n,e,r),Ps(n,t,r)))}function ks(e,t,n){As(e,t,n,gu())}function As(e,t,n,r){var i={lane:r,revertLane:0,gesture:null,action:n,hasEagerState:!1,eagerState:null,next:null};if(Ms(e))Ns(t,i);else{var a=e.alternate;if(e.lanes===0&&(a===null||a.lanes===0)&&(a=t.lastRenderedReducer,a!==null))try{var o=t.lastRenderedState,s=a(o,n);if(i.hasEagerState=!0,i.eagerState=s,vr(s,o))return Zr(e,t,i,0),zl===null&&Xr(),!1}catch{}if(n=Qr(e,t,i,r),n!==null)return vu(n,e,r),Ps(n,t,r),!0}return!1}function js(e,t,n,r){if(r={lane:2,revertLane:hd(),gesture:null,action:r,hasEagerState:!1,eagerState:null,next:null},Ms(e)){if(t)throw Error(i(479))}else t=Qr(e,n,r,2),t!==null&&vu(t,e,2)}function Ms(e){var t=e.alternate;return e===oo||t!==null&&t===oo}function Ns(e,t){uo=lo=!0;var n=e.pending;n===null?t.next=t:(t.next=n.next,n.next=t),e.pending=t}function Ps(e,t,n){if(n&4194048){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,Qe(e,n)}}var Fs={readContext:W,use:Ao,useCallback:_o,useContext:_o,useEffect:_o,useImperativeHandle:_o,useLayoutEffect:_o,useInsertionEffect:_o,useMemo:_o,useReducer:_o,useRef:_o,useState:_o,useDebugValue:_o,useDeferredValue:_o,useTransition:_o,useSyncExternalStore:_o,useId:_o,useHostTransitionStatus:_o,useFormState:_o,useActionState:_o,useOptimistic:_o,useMemoCache:_o,useCacheRefresh:_o};Fs.useEffectEvent=_o;var Is={readContext:W,use:Ao,useCallback:function(e,t){return Eo().memoizedState=[e,t===void 0?null:t],e},useContext:W,useEffect:os,useImperativeHandle:function(e,t,n){n=n==null?null:n.concat([e]),is(4194308,4,fs.bind(null,t,e),n)},useLayoutEffect:function(e,t){return is(4194308,4,e,t)},useInsertionEffect:function(e,t){is(4,2,e,t)},useMemo:function(e,t){var n=Eo();t=t===void 0?null:t;var r=e();if(fo){Fe(!0);try{e()}finally{Fe(!1)}}return n.memoizedState=[r,t],r},useReducer:function(e,t,n){var r=Eo();if(n!==void 0){var i=n(t);if(fo){Fe(!0);try{n(t)}finally{Fe(!1)}}}else i=t;return r.memoizedState=r.baseState=i,e={pending:null,lanes:0,dispatch:null,lastRenderedReducer:e,lastRenderedState:i},r.queue=e,e=e.dispatch=Os.bind(null,oo,e),[r.memoizedState,e]},useRef:function(e){var t=Eo();return e={current:e},t.memoizedState=e},useState:function(e){e=Ho(e);var t=e.queue,n=ks.bind(null,oo,t);return t.dispatch=n,[e.memoizedState,n]},useDebugValue:ms,useDeferredValue:function(e,t){return _s(Eo(),e,t)},useTransition:function(){var e=Ho(!1);return e=ys.bind(null,oo,e.queue,!0,!1),Eo().memoizedState=e,[!1,e]},useSyncExternalStore:function(e,t,n){var r=oo,a=Eo();if(Ai){if(n===void 0)throw Error(i(407));n=n()}else{if(n=t(),zl===null)throw Error(i(349));Vl&127||Lo(r,t,n)}a.memoizedState=n;var o={value:n,getSnapshot:t};return a.queue=o,os(zo.bind(null,r,o,e),[e]),r.flags|=2048,ns(9,{destroy:void 0},Ro.bind(null,r,o,n,t),null),n},useId:function(){var e=Eo(),t=zl.identifierPrefix;if(Ai){var n=Si,r=xi;n=(r&~(1<<32-Ie(r)-1)).toString(32)+n,t=`_`+t+`R_`+n,n=po++,0<\/script>`,o=o.removeChild(o.firstChild);break;case`select`:o=typeof r.is==`string`?s.createElement(`select`,{is:r.is}):s.createElement(`select`),r.multiple?o.multiple=!0:r.size&&(o.size=r.size);break;default:o=typeof r.is==`string`?s.createElement(a,{is:r.is}):s.createElement(a)}}o[at]=t,o[ot]=r;a:for(s=t.child;s!==null;){if(s.tag===5||s.tag===6)o.appendChild(s.stateNode);else if(s.tag!==4&&s.tag!==27&&s.child!==null){s.child.return=s,s=s.child;continue}if(s===t)break a;for(;s.sibling===null;){if(s.return===null||s.return===t)break a;s=s.return}s.sibling.return=s.return,s=s.sibling}t.stateNode=o;a:switch(Bd(o,a,r),a){case`button`:case`input`:case`select`:case`textarea`:r=!!r.autoFocus;break a;case`img`:r=!0;break a;default:r=!1}r&&Ac(t)}}return Fc(t),jc(t,t.type,e===null?null:e.memoizedProps,t.pendingProps,n),null;case 6:if(e&&t.stateNode!=null)e.memoizedProps!==r&&Ac(t);else{if(typeof r!=`string`&&t.stateNode===null)throw Error(i(166));if(e=ue.current,Li(t)){if(e=t.stateNode,n=t.memoizedProps,r=null,a=Oi,a!==null)switch(a.tag){case 27:case 5:r=a.memoizedProps}e[at]=t,e=!!(e.nodeValue===n||r!==null&&!0===r.suppressHydrationWarning||Ld(e.nodeValue,n)),e||Pi(t,!0)}else e=Kd(e).createTextNode(r),e[at]=t,t.stateNode=e}return Fc(t),null;case 31:if(n=t.memoizedState,e===null||e.memoizedState!==null){if(r=Li(t),n!==null){if(e===null){if(!r)throw Error(i(318));if(e=t.memoizedState,e=e===null?null:e.dehydrated,!e)throw Error(i(557));e[at]=t}else Ri(),!(t.flags&128)&&(t.memoizedState=null),t.flags|=4;Fc(t),e=!1}else n=zi(),e!==null&&e.memoizedState!==null&&(e.memoizedState.hydrationErrors=n),e=!0;if(!e)return t.flags&256?(no(t),t):(no(t),null);if(t.flags&128)throw Error(i(558))}return Fc(t),null;case 13:if(r=t.memoizedState,e===null||e.memoizedState!==null&&e.memoizedState.dehydrated!==null){if(a=Li(t),r!==null&&r.dehydrated!==null){if(e===null){if(!a)throw Error(i(318));if(a=t.memoizedState,a=a===null?null:a.dehydrated,!a)throw Error(i(317));a[at]=t}else Ri(),!(t.flags&128)&&(t.memoizedState=null),t.flags|=4;Fc(t),a=!1}else a=zi(),e!==null&&e.memoizedState!==null&&(e.memoizedState.hydrationErrors=a),a=!0;if(!a)return t.flags&256?(no(t),t):(no(t),null)}return no(t),t.flags&128?(t.lanes=n,t):(n=r!==null,e=e!==null&&e.memoizedState!==null,n&&(r=t.child,a=null,r.alternate!==null&&r.alternate.memoizedState!==null&&r.alternate.memoizedState.cachePool!==null&&(a=r.alternate.memoizedState.cachePool.pool),o=null,r.memoizedState!==null&&r.memoizedState.cachePool!==null&&(o=r.memoizedState.cachePool.pool),o!==a&&(r.flags|=2048)),n!==e&&n&&(t.child.flags|=8192),Nc(t,t.updateQueue),Fc(t),null);case 4:return pe(),e===null&&Dd(t.stateNode.containerInfo),Fc(t),null;case 10:return Gi(t.type),Fc(t),null;case 19:if(oe(ro),r=t.memoizedState,r===null)return Fc(t),null;if(a=(t.flags&128)!=0,o=r.rendering,o===null)if(a)Pc(r,!1);else{if(ql!==0||e!==null&&e.flags&128)for(e=t.child;e!==null;){if(o=io(e),o!==null){for(t.flags|=128,Pc(r,!1),e=o.updateQueue,t.updateQueue=e,Nc(t,e),t.subtreeFlags=0,e=n,n=t.child;n!==null;)si(n,e),n=n.sibling;return se(ro,ro.current&1|2),Ai&&Ci(t,r.treeForkCount),t.child}e=e.sibling}r.tail!==null&&we()>iu&&(t.flags|=128,a=!0,Pc(r,!1),t.lanes=4194304)}else{if(!a)if(e=io(o),e!==null){if(t.flags|=128,a=!0,e=e.updateQueue,t.updateQueue=e,Nc(t,e),Pc(r,!0),r.tail===null&&r.tailMode===`hidden`&&!o.alternate&&!Ai)return Fc(t),null}else 2*we()-r.renderingStartTime>iu&&n!==536870912&&(t.flags|=128,a=!0,Pc(r,!1),t.lanes=4194304);r.isBackwards?(o.sibling=t.child,t.child=o):(e=r.last,e===null?t.child=o:e.sibling=o,r.last=o)}return r.tail===null?(Fc(t),null):(e=r.tail,r.rendering=e,r.tail=e.sibling,r.renderingStartTime=we(),e.sibling=null,n=ro.current,se(ro,a?n&1|2:n&1),Ai&&Ci(t,r.treeForkCount),e);case 22:case 23:return no(t),Ya(),r=t.memoizedState!==null,e===null?r&&(t.flags|=8192):e.memoizedState!==null!==r&&(t.flags|=8192),r?n&536870912&&!(t.flags&128)&&(Fc(t),t.subtreeFlags&6&&(t.flags|=8192)):Fc(t),n=t.updateQueue,n!==null&&Nc(t,n.retryQueue),n=null,e!==null&&e.memoizedState!==null&&e.memoizedState.cachePool!==null&&(n=e.memoizedState.cachePool.pool),r=null,t.memoizedState!==null&&t.memoizedState.cachePool!==null&&(r=t.memoizedState.cachePool.pool),r!==n&&(t.flags|=2048),e!==null&&oe(da),null;case 24:return n=null,e!==null&&(n=e.memoizedState.cache),t.memoizedState.cache!==n&&(t.flags|=2048),Gi(ta),Fc(t),null;case 25:return null;case 30:return null}throw Error(i(156,t.tag))}function Lc(e,t){switch(Ei(t),t.tag){case 1:return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return Gi(ta),pe(),e=t.flags,e&65536&&!(e&128)?(t.flags=e&-65537|128,t):null;case 26:case 27:case 5:return he(t),null;case 31:if(t.memoizedState!==null){if(no(t),t.alternate===null)throw Error(i(340));Ri()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 13:if(no(t),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(i(340));Ri()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return oe(ro),null;case 4:return pe(),null;case 10:return Gi(t.type),null;case 22:case 23:return no(t),Ya(),e!==null&&oe(da),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 24:return Gi(ta),null;case 25:return null;default:return null}}function Rc(e,t){switch(Ei(t),t.tag){case 3:Gi(ta),pe();break;case 26:case 27:case 5:he(t);break;case 4:pe();break;case 31:t.memoizedState!==null&&no(t);break;case 13:no(t);break;case 19:oe(ro);break;case 10:Gi(t.type);break;case 22:case 23:no(t),Ya(),e!==null&&oe(da);break;case 24:Gi(ta)}}function zc(e,t){try{var n=t.updateQueue,r=n===null?null:n.lastEffect;if(r!==null){var i=r.next;n=i;do{if((n.tag&e)===e){r=void 0;var a=n.create,o=n.inst;r=a(),o.destroy=r}n=n.next}while(n!==i)}}catch(e){Ju(t,t.return,e)}}function Bc(e,t,n){try{var r=t.updateQueue,i=r===null?null:r.lastEffect;if(i!==null){var a=i.next;r=a;do{if((r.tag&e)===e){var o=r.inst,s=o.destroy;if(s!==void 0){o.destroy=void 0,i=t;var c=n,l=s;try{l()}catch(e){Ju(i,c,e)}}}r=r.next}while(r!==a)}}catch(e){Ju(t,t.return,e)}}function Vc(e){var t=e.updateQueue;if(t!==null){var n=e.stateNode;try{Wa(t,n)}catch(t){Ju(e,e.return,t)}}}function Hc(e,t,n){n.props=Us(e.type,e.memoizedProps),n.state=e.memoizedState;try{n.componentWillUnmount()}catch(n){Ju(e,t,n)}}function Uc(e,t){try{var n=e.ref;if(n!==null){switch(e.tag){case 26:case 27:case 5:var r=e.stateNode;break;case 30:r=e.stateNode;break;default:r=e.stateNode}typeof n==`function`?e.refCleanup=n(r):n.current=r}}catch(n){Ju(e,t,n)}}function Wc(e,t){var n=e.ref,r=e.refCleanup;if(n!==null)if(typeof r==`function`)try{r()}catch(n){Ju(e,t,n)}finally{e.refCleanup=null,e=e.alternate,e!=null&&(e.refCleanup=null)}else if(typeof n==`function`)try{n(null)}catch(n){Ju(e,t,n)}else n.current=null}function Gc(e){var t=e.type,n=e.memoizedProps,r=e.stateNode;try{a:switch(t){case`button`:case`input`:case`select`:case`textarea`:n.autoFocus&&r.focus();break a;case`img`:n.src?r.src=n.src:n.srcSet&&(r.srcset=n.srcSet)}}catch(t){Ju(e,e.return,t)}}function Kc(e,t,n){try{var r=e.stateNode;Vd(r,e.type,n,t),r[ot]=t}catch(t){Ju(e,e.return,t)}}function qc(e){return e.tag===5||e.tag===3||e.tag===26||e.tag===27&&rf(e.type)||e.tag===4}function Jc(e){a:for(;;){for(;e.sibling===null;){if(e.return===null||qc(e.return))return null;e=e.return}for(e.sibling.return=e.return,e=e.sibling;e.tag!==5&&e.tag!==6&&e.tag!==18;){if(e.tag===27&&rf(e.type)||e.flags&2||e.child===null||e.tag===4)continue a;e.child.return=e,e=e.child}if(!(e.flags&2))return e.stateNode}}function Yc(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?(n.nodeType===9?n.body:n.nodeName===`HTML`?n.ownerDocument.body:n).insertBefore(e,t):(t=n.nodeType===9?n.body:n.nodeName===`HTML`?n.ownerDocument.body:n,t.appendChild(e),n=n._reactRootContainer,n!=null||t.onclick!==null||(t.onclick=Qt));else if(r!==4&&(r===27&&rf(e.type)&&(n=e.stateNode,t=null),e=e.child,e!==null))for(Yc(e,t,n),e=e.sibling;e!==null;)Yc(e,t,n),e=e.sibling}function Xc(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.insertBefore(e,t):n.appendChild(e);else if(r!==4&&(r===27&&rf(e.type)&&(n=e.stateNode),e=e.child,e!==null))for(Xc(e,t,n),e=e.sibling;e!==null;)Xc(e,t,n),e=e.sibling}function Zc(e){var t=e.stateNode,n=e.memoizedProps;try{for(var r=e.type,i=t.attributes;i.length;)t.removeAttributeNode(i[0]);Bd(t,r,n),t[at]=e,t[ot]=n}catch(t){Ju(e,e.return,t)}}var Qc=!1,$c=!1,el=!1,tl=typeof WeakSet==`function`?WeakSet:Set,nl=null;function rl(e,t){if(e=e.containerInfo,Wd=pp,e=Cr(e),wr(e)){if(`selectionStart`in e)var n={start:e.selectionStart,end:e.selectionEnd};else a:{n=(n=e.ownerDocument)&&n.defaultView||window;var r=n.getSelection&&n.getSelection();if(r&&r.rangeCount!==0){n=r.anchorNode;var a=r.anchorOffset,o=r.focusNode;r=r.focusOffset;try{n.nodeType,o.nodeType}catch{n=null;break a}var s=0,c=-1,l=-1,u=0,d=0,f=e,p=null;b:for(;;){for(var m;f!==n||a!==0&&f.nodeType!==3||(c=s+a),f!==o||r!==0&&f.nodeType!==3||(l=s+r),f.nodeType===3&&(s+=f.nodeValue.length),(m=f.firstChild)!==null;)p=f,f=m;for(;;){if(f===e)break b;if(p===n&&++u===a&&(c=s),p===o&&++d===r&&(l=s),(m=f.nextSibling)!==null)break;f=p,p=f.parentNode}f=m}n=c===-1||l===-1?null:{start:c,end:l}}else n=null}n||={start:0,end:0}}else n=null;for(Gd={focusedElem:e,selectionRange:n},pp=!1,nl=t;nl!==null;)if(t=nl,e=t.child,t.subtreeFlags&1028&&e!==null)e.return=t,nl=e;else for(;nl!==null;){switch(t=nl,o=t.alternate,e=t.flags,t.tag){case 0:if(e&4&&(e=t.updateQueue,e=e===null?null:e.events,e!==null))for(n=0;n title`))),Bd(o,r,n),o[at]=e,vt(o),r=o;break a;case`link`:var s=qf(`link`,`href`,a).get(r+(n.href||``));if(s){for(var c=0;cg&&(o=g,g=h,h=o);var _=xr(s,h),v=xr(s,g);if(_&&v&&(p.rangeCount!==1||p.anchorNode!==_.node||p.anchorOffset!==_.offset||p.focusNode!==v.node||p.focusOffset!==v.offset)){var y=d.createRange();y.setStart(_.node,_.offset),p.removeAllRanges(),h>g?(p.addRange(y),p.extend(v.node,v.offset)):(y.setEnd(v.node,v.offset),p.addRange(y))}}}}for(d=[],p=s;p=p.parentNode;)p.nodeType===1&&d.push({element:p,left:p.scrollLeft,top:p.scrollTop});for(typeof s.focus==`function`&&s.focus(),s=0;sn?32:n,F.T=null,n=fu,fu=null;var o=cu,s=uu;if(su=0,lu=cu=null,uu=0,Rl&6)throw Error(i(331));var c=Rl;if(Rl|=4,Nl(o.current),Tl(o,o.current,s,n),Rl=c,cd(0,!1),Pe&&typeof Pe.onPostCommitFiberRoot==`function`)try{Pe.onPostCommitFiberRoot(Ne,o)}catch{}return!0}finally{te.p=a,F.T=r,Wu(e,t)}}function qu(e,t,n){t=mi(n,t),t=Ys(e.stateNode,t,2),e=La(e,t,2),e!==null&&(Ye(e,2),sd(e))}function Ju(e,t,n){if(e.tag===3)qu(e,e,n);else for(;t!==null;){if(t.tag===3){qu(t,e,n);break}else if(t.tag===1){var r=t.stateNode;if(typeof t.type.getDerivedStateFromError==`function`||typeof r.componentDidCatch==`function`&&(ou===null||!ou.has(r))){e=mi(n,e),n=Xs(2),r=La(t,n,2),r!==null&&(Zs(n,r,t,e),Ye(r,2),sd(r));break}}t=t.return}}function Yu(e,t,n){var r=e.pingCache;if(r===null){r=e.pingCache=new Ll;var i=new Set;r.set(t,i)}else i=r.get(t),i===void 0&&(i=new Set,r.set(t,i));i.has(n)||(Gl=!0,i.add(n),e=Xu.bind(null,e,t,n),t.then(e,e))}function Xu(e,t,n){var r=e.pingCache;r!==null&&r.delete(t),e.pingedLanes|=e.suspendedLanes&n,e.warmLanes&=~n,zl===e&&(Vl&n)===n&&(ql===4||ql===3&&(Vl&62914560)===Vl&&300>we()-nu?!(Rl&2)&&Tu(e,0):Xl|=n,Ql===Vl&&(Ql=0)),sd(e)}function Zu(e,t){t===0&&(t=qe()),e=$r(e,t),e!==null&&(Ye(e,t),sd(e))}function Qu(e){var t=e.memoizedState,n=0;t!==null&&(n=t.retryLane),Zu(e,n)}function $u(e,t){var n=0;switch(e.tag){case 31:case 13:var r=e.stateNode,a=e.memoizedState;a!==null&&(n=a.retryLane);break;case 19:r=e.stateNode;break;case 22:r=e.stateNode._retryCache;break;default:throw Error(i(314))}r!==null&&r.delete(t),Zu(e,n)}function ed(e,t){return be(e,t)}var td=null,nd=null,rd=!1,id=!1,ad=!1,od=0;function sd(e){e!==nd&&e.next===null&&(nd===null?td=nd=e:nd=nd.next=e),id=!0,rd||(rd=!0,md())}function cd(e,t){if(!ad&&id){ad=!0;do for(var n=!1,r=td;r!==null;){if(!t)if(e!==0){var i=r.pendingLanes;if(i===0)var a=0;else{var o=r.suspendedLanes,s=r.pingedLanes;a=(1<<31-Ie(42|e)+1)-1,a&=i&~(o&~s),a=a&201326741?a&201326741|1:a?a|2:0}a!==0&&(n=!0,pd(r,a))}else a=Vl,a=We(r,r===zl?a:0,r.cancelPendingCommit!==null||r.timeoutHandle!==-1),!(a&3)||Ge(r,a)||(n=!0,pd(r,a));r=r.next}while(n);ad=!1}}function ld(){ud()}function ud(){id=rd=!1;var e=0;od!==0&&Zd()&&(e=od);for(var t=we(),n=null,r=td;r!==null;){var i=r.next,a=dd(r,t);a===0?(r.next=null,n===null?td=i:n.next=i,i===null&&(nd=n)):(n=r,(e!==0||a&3)&&(id=!0)),r=i}su!==0&&su!==5||cd(e,!1),od!==0&&(od=0)}function dd(e,t){for(var n=e.suspendedLanes,r=e.pingedLanes,i=e.expirationTimes,a=e.pendingLanes&-62914561;0s)break;var u=c.transferSize,d=c.initiatorType;u&&Hd(d)&&(c=c.responseEnd,o+=u*(c`u`?null:document;function Df(e,t,n){var r=Ef;if(r&&typeof t==`string`&&t){var i=Lt(t);i=`link[rel="`+e+`"][href="`+i+`"]`,typeof n==`string`&&(i+=`[crossorigin="`+n+`"]`),xf.has(i)||(xf.add(i),e={rel:e,crossOrigin:n,href:t},r.querySelector(i)===null&&(t=r.createElement(`link`),Bd(t,`link`,e),vt(t),r.head.appendChild(t)))}}function Of(e){Cf.D(e),Df(`dns-prefetch`,e,null)}function kf(e,t){Cf.C(e,t),Df(`preconnect`,e,t)}function Af(e,t,n){Cf.L(e,t,n);var r=Ef;if(r&&e&&t){var i=`link[rel="preload"][as="`+Lt(t)+`"]`;t===`image`&&n&&n.imageSrcSet?(i+=`[imagesrcset="`+Lt(n.imageSrcSet)+`"]`,typeof n.imageSizes==`string`&&(i+=`[imagesizes="`+Lt(n.imageSizes)+`"]`)):i+=`[href="`+Lt(e)+`"]`;var a=i;switch(t){case`style`:a=If(e);break;case`script`:a=Bf(e)}bf.has(a)||(e=p({rel:`preload`,href:t===`image`&&n&&n.imageSrcSet?void 0:e,as:t},n),bf.set(a,e),r.querySelector(i)!==null||t===`style`&&r.querySelector(Lf(a))||t===`script`&&r.querySelector(Vf(a))||(t=r.createElement(`link`),Bd(t,`link`,e),vt(t),r.head.appendChild(t)))}}function jf(e,t){Cf.m(e,t);var n=Ef;if(n&&e){var r=t&&typeof t.as==`string`?t.as:`script`,i=`link[rel="modulepreload"][as="`+Lt(r)+`"][href="`+Lt(e)+`"]`,a=i;switch(r){case`audioworklet`:case`paintworklet`:case`serviceworker`:case`sharedworker`:case`worker`:case`script`:a=Bf(e)}if(!bf.has(a)&&(e=p({rel:`modulepreload`,href:e},t),bf.set(a,e),n.querySelector(i)===null)){switch(r){case`audioworklet`:case`paintworklet`:case`serviceworker`:case`sharedworker`:case`worker`:case`script`:if(n.querySelector(Vf(a)))return}r=n.createElement(`link`),Bd(r,`link`,e),vt(r),n.head.appendChild(r)}}}function Mf(e,t,n){Cf.S(e,t,n);var r=Ef;if(r&&e){var i=_t(r).hoistableStyles,a=If(e);t||=`default`;var o=i.get(a);if(!o){var s={loading:0,preload:null};if(o=r.querySelector(Lf(a)))s.loading=5;else{e=p({rel:`stylesheet`,href:e,"data-precedence":t},n),(n=bf.get(a))&&Wf(e,n);var c=o=r.createElement(`link`);vt(c),Bd(c,`link`,e),c._p=new Promise(function(e,t){c.onload=e,c.onerror=t}),c.addEventListener(`load`,function(){s.loading|=1}),c.addEventListener(`error`,function(){s.loading|=2}),s.loading|=4,Uf(o,t,r)}o={type:`stylesheet`,instance:o,count:1,state:s},i.set(a,o)}}}function Nf(e,t){Cf.X(e,t);var n=Ef;if(n&&e){var r=_t(n).hoistableScripts,i=Bf(e),a=r.get(i);a||(a=n.querySelector(Vf(i)),a||(e=p({src:e,async:!0},t),(t=bf.get(i))&&Gf(e,t),a=n.createElement(`script`),vt(a),Bd(a,`link`,e),n.head.appendChild(a)),a={type:`script`,instance:a,count:1,state:null},r.set(i,a))}}function Pf(e,t){Cf.M(e,t);var n=Ef;if(n&&e){var r=_t(n).hoistableScripts,i=Bf(e),a=r.get(i);a||(a=n.querySelector(Vf(i)),a||(e=p({src:e,async:!0,type:`module`},t),(t=bf.get(i))&&Gf(e,t),a=n.createElement(`script`),vt(a),Bd(a,`link`,e),n.head.appendChild(a)),a={type:`script`,instance:a,count:1,state:null},r.set(i,a))}}function Ff(e,t,n,r){var a=(a=ue.current)?Sf(a):null;if(!a)throw Error(i(446));switch(e){case`meta`:case`title`:return null;case`style`:return typeof n.precedence==`string`&&typeof n.href==`string`?(t=If(n.href),n=_t(a).hoistableStyles,r=n.get(t),r||(r={type:`style`,instance:null,count:0,state:null},n.set(t,r)),r):{type:`void`,instance:null,count:0,state:null};case`link`:if(n.rel===`stylesheet`&&typeof n.href==`string`&&typeof n.precedence==`string`){e=If(n.href);var o=_t(a).hoistableStyles,s=o.get(e);if(s||(a=a.ownerDocument||a,s={type:`stylesheet`,instance:null,count:0,state:{loading:0,preload:null}},o.set(e,s),(o=a.querySelector(Lf(e)))&&!o._p&&(s.instance=o,s.state.loading=5),bf.has(e)||(n={rel:`preload`,as:`style`,href:n.href,crossOrigin:n.crossOrigin,integrity:n.integrity,media:n.media,hrefLang:n.hrefLang,referrerPolicy:n.referrerPolicy},bf.set(e,n),o||zf(a,e,n,s.state))),t&&r===null)throw Error(i(528,``));return s}if(t&&r!==null)throw Error(i(529,``));return null;case`script`:return t=n.async,n=n.src,typeof n==`string`&&t&&typeof t!=`function`&&typeof t!=`symbol`?(t=Bf(n),n=_t(a).hoistableScripts,r=n.get(t),r||(r={type:`script`,instance:null,count:0,state:null},n.set(t,r)),r):{type:`void`,instance:null,count:0,state:null};default:throw Error(i(444,e))}}function If(e){return`href="`+Lt(e)+`"`}function Lf(e){return`link[rel="stylesheet"][`+e+`]`}function Rf(e){return p({},e,{"data-precedence":e.precedence,precedence:null})}function zf(e,t,n,r){e.querySelector(`link[rel="preload"][as="style"][`+t+`]`)?r.loading=1:(t=e.createElement(`link`),r.preload=t,t.addEventListener(`load`,function(){return r.loading|=1}),t.addEventListener(`error`,function(){return r.loading|=2}),Bd(t,`link`,n),vt(t),e.head.appendChild(t))}function Bf(e){return`[src="`+Lt(e)+`"]`}function Vf(e){return`script[async]`+e}function Hf(e,t,n){if(t.count++,t.instance===null)switch(t.type){case`style`:var r=e.querySelector(`style[data-href~="`+Lt(n.href)+`"]`);if(r)return t.instance=r,vt(r),r;var a=p({},n,{"data-href":n.href,"data-precedence":n.precedence,href:null,precedence:null});return r=(e.ownerDocument||e).createElement(`style`),vt(r),Bd(r,`style`,a),Uf(r,n.precedence,e),t.instance=r;case`stylesheet`:a=If(n.href);var o=e.querySelector(Lf(a));if(o)return t.state.loading|=4,t.instance=o,vt(o),o;r=Rf(n),(a=bf.get(a))&&Wf(r,a),o=(e.ownerDocument||e).createElement(`link`),vt(o);var s=o;return s._p=new Promise(function(e,t){s.onload=e,s.onerror=t}),Bd(o,`link`,r),t.state.loading|=4,Uf(o,n.precedence,e),t.instance=o;case`script`:return o=Bf(n.src),(a=e.querySelector(Vf(o)))?(t.instance=a,vt(a),a):(r=n,(a=bf.get(o))&&(r=p({},n),Gf(r,a)),e=e.ownerDocument||e,a=e.createElement(`script`),vt(a),Bd(a,`link`,r),e.head.appendChild(a),t.instance=a);case`void`:return null;default:throw Error(i(443,t.type))}else t.type===`stylesheet`&&!(t.state.loading&4)&&(r=t.instance,t.state.loading|=4,Uf(r,n.precedence,e));return t.instance}function Uf(e,t,n){for(var r=n.querySelectorAll(`link[rel="stylesheet"][data-precedence],style[data-precedence]`),i=r.length?r[r.length-1]:null,a=i,o=0;o title`):null)}function Yf(e,t,n){if(n===1||t.itemProp!=null)return!1;switch(e){case`meta`:case`title`:return!0;case`style`:if(typeof t.precedence!=`string`||typeof t.href!=`string`||t.href===``)break;return!0;case`link`:if(typeof t.rel!=`string`||typeof t.href!=`string`||t.href===``||t.onLoad||t.onError)break;switch(t.rel){case`stylesheet`:return e=t.disabled,typeof t.precedence==`string`&&e==null;default:return!0}case`script`:if(t.async&&typeof t.async!=`function`&&typeof t.async!=`symbol`&&!t.onLoad&&!t.onError&&t.src&&typeof t.src==`string`)return!0}return!1}function Xf(e){return!(e.type===`stylesheet`&&!(e.state.loading&3))}function Zf(e,t,n,r){if(n.type===`stylesheet`&&(typeof r.media!=`string`||!1!==matchMedia(r.media).matches)&&!(n.state.loading&4)){if(n.instance===null){var i=If(r.href),a=t.querySelector(Lf(i));if(a){t=a._p,typeof t==`object`&&t&&typeof t.then==`function`&&(e.count++,e=ep.bind(e),t.then(e,e)),n.state.loading|=4,n.instance=a,vt(a);return}a=t.ownerDocument||t,r=Rf(r),(i=bf.get(i))&&Wf(r,i),a=a.createElement(`link`),vt(a);var o=a;o._p=new Promise(function(e,t){o.onload=e,o.onerror=t}),Bd(a,`link`,r),n.instance=a}e.stylesheets===null&&(e.stylesheets=new Map),e.stylesheets.set(n,t),(t=n.state.preload)&&!(n.state.loading&3)&&(e.count++,n=ep.bind(e),t.addEventListener(`load`,n),t.addEventListener(`error`,n))}}var Qf=0;function $f(e,t){return e.stylesheets&&e.count===0&&np(e,e.stylesheets),0Qf?50:800)+t);return e.unsuspend=n,function(){e.unsuspend=null,clearTimeout(r),clearTimeout(i)}}:null}function ep(){if(this.count--,this.count===0&&(this.imgCount===0||!this.waitingForImages)){if(this.stylesheets)np(this,this.stylesheets);else if(this.unsuspend){var e=this.unsuspend;this.unsuspend=null,e()}}}var tp=null;function np(e,t){e.stylesheets=null,e.unsuspend!==null&&(e.count++,tp=new Map,t.forEach(rp,e),tp=null,ep.call(e))}function rp(e,t){if(!(t.state.loading&4)){var n=tp.get(e);if(n)var r=n.get(null);else{n=new Map,tp.set(e,n);for(var i=e.querySelectorAll(`link[data-precedence],style[data-precedence]`),a=0;a{function n(){if(!(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>`u`||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!=`function`))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(n)}catch(e){console.error(e)}}n(),t.exports=_()}))(),1),y=l(f()),b=(...e)=>e.filter((e,t,n)=>!!e&&e.trim()!==``&&n.indexOf(e)===t).join(` `).trim(),x=e=>e.replace(/([a-z0-9])([A-Z])/g,`$1-$2`).toLowerCase(),S=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(e,t,n)=>n?n.toUpperCase():t.toLowerCase()),C=e=>{let t=S(e);return t.charAt(0).toUpperCase()+t.slice(1)},w={xmlns:`http://www.w3.org/2000/svg`,width:24,height:24,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:2,strokeLinecap:`round`,strokeLinejoin:`round`},T=e=>{for(let t in e)if(t.startsWith(`aria-`)||t===`role`||t===`title`)return!0;return!1},E=(0,y.forwardRef)(({color:e=`currentColor`,size:t=24,strokeWidth:n=2,absoluteStrokeWidth:r,className:i=``,children:a,iconNode:o,...s},c)=>(0,y.createElement)(`svg`,{ref:c,...w,width:t,height:t,stroke:e,strokeWidth:r?Number(n)*24/Number(t):n,className:b(`lucide`,i),...!a&&!T(s)&&{"aria-hidden":`true`},...s},[...o.map(([e,t])=>(0,y.createElement)(e,t)),...Array.isArray(a)?a:[a]])),D=(e,t)=>{let n=(0,y.forwardRef)(({className:n,...r},i)=>(0,y.createElement)(E,{ref:i,iconNode:t,className:b(`lucide-${x(C(e))}`,`lucide-${e}`,n),...r}));return n.displayName=C(e),n},O=D(`arrow-left`,[[`path`,{d:`m12 19-7-7 7-7`,key:`1l729n`}],[`path`,{d:`M19 12H5`,key:`x3x0zl`}]]),k=D(`camera`,[[`path`,{d:`M13.997 4a2 2 0 0 1 1.76 1.05l.486.9A2 2 0 0 0 18.003 7H20a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V9a2 2 0 0 1 2-2h1.997a2 2 0 0 0 1.759-1.048l.489-.904A2 2 0 0 1 10.004 4z`,key:`18u6gg`}],[`circle`,{cx:`12`,cy:`13`,r:`3`,key:`1vg3eu`}]]),A=D(`film`,[[`rect`,{width:`18`,height:`18`,x:`3`,y:`3`,rx:`2`,key:`afitv7`}],[`path`,{d:`M7 3v18`,key:`bbkbws`}],[`path`,{d:`M3 7.5h4`,key:`zfgn84`}],[`path`,{d:`M3 12h18`,key:`1i2n21`}],[`path`,{d:`M3 16.5h4`,key:`1230mu`}],[`path`,{d:`M17 3v18`,key:`in4fa5`}],[`path`,{d:`M17 7.5h4`,key:`myr1c1`}],[`path`,{d:`M17 16.5h4`,key:`go4c1d`}]]),j=D(`pause`,[[`rect`,{x:`14`,y:`3`,width:`5`,height:`18`,rx:`1`,key:`kaeet6`}],[`rect`,{x:`5`,y:`3`,width:`5`,height:`18`,rx:`1`,key:`1wsw3u`}]]),ee=D(`play`,[[`path`,{d:`M5 5a2 2 0 0 1 3.008-1.728l11.997 6.998a2 2 0 0 1 .003 3.458l-12 7A2 2 0 0 1 5 19z`,key:`10ikf1`}]]),M=o((e=>{var t=Symbol.for(`react.transitional.element`),n=Symbol.for(`react.fragment`);function r(e,n,r){var i=null;if(r!==void 0&&(i=``+r),n.key!==void 0&&(i=``+n.key),`key`in n)for(var a in r={},n)a!==`key`&&(r[a]=n[a]);else r=n;return n=r.ref,{$$typeof:t,type:e,key:i,ref:n===void 0?null:n,props:r}}e.Fragment=n,e.jsx=r,e.jsxs=r})),N=o(((e,t)=>{t.exports=M()}))();function P(){return(0,N.jsxs)(`div`,{className:`brand-mark`,children:[(0,N.jsx)(`img`,{alt:`Liquid AI icon`,className:`brand-logo`,src:`/logo-light.webp`}),(0,N.jsxs)(`div`,{className:`brand-copy`,children:[(0,N.jsx)(`span`,{children:`Liquid AI`}),(0,N.jsx)(`strong`,{children:`LFM2-VL WebGPU`})]})]})}var F=(0,y.createContext)(null);function te(){let e=(0,y.useContext)(F);if(!e)throw Error(`useVLM must be used within a VLMProvider.`);return e}var ne=4;function re(e){return new Promise(t=>{window.setTimeout(t,e)})}function ie(){return globalThis.crypto?.randomUUID?.()??`caption-${Date.now()}-${Math.random()}`}function ae(e){return e.replace(/\s+/g,` `).trim()}function oe(e){return e instanceof Error?e.message:`Something went wrong while captioning the current frame.`}function se({mediaError:e,onChooseVideo:t,onChooseWebcam:n,onDismissMediaError:r,onExit:i,onPromptChange:a,prompt:o,promptPresets:s,source:c}){let{generateCaption:l}=te(),u=(0,y.useRef)(null),d=(0,y.useRef)(null),f=(0,y.useRef)(0),[p,m]=(0,y.useState)(``),[h,g]=(0,y.useState)([]),[_,v]=(0,y.useState)(!1),[b,x]=(0,y.useState)(!1),[S,C]=(0,y.useState)(null),[w,T]=(0,y.useState)(!1),E=(0,y.useDeferredValue)(ae(o)||s[0].prompt);(0,y.useEffect)(()=>{let e=u.current;if(e)return T(!1),C(null),c.kind===`webcam`?(e.srcObject=c.stream,e.removeAttribute(`src`),e.play().catch(()=>void 0),()=>{e.pause(),e.srcObject=null}):(e.srcObject=null,e.src=c.url,e.load(),e.play().catch(()=>void 0),()=>{e.pause(),e.removeAttribute(`src`),e.load()})},[c]),(0,y.useEffect)(()=>{g([]),m(``),v(!1),x(!1)},[c]),(0,y.useEffect)(()=>{b&&(m(``),v(!1))},[b]);let D=()=>{T(!0),u.current?.play().catch(()=>void 0)},M=(0,y.useEffectEvent)(()=>{let e=u.current,t=d.current;if(!e||!t||!w||e.paused||e.ended||e.readyState{if(b){await re(120);return}let t=M();if(!t){await re(120);return}C(null),v(!0),m(``);try{let n=await l({frame:t,onStream:t=>{f.current===e&&m(t)},prompt:E});if(f.current!==e)return;let r=ae(n);if(r.length===0)return;(0,y.startTransition)(()=>{g(e=>e[0]?.text===r?e:[{id:ie(),text:r},...e].slice(0,ne))})}catch(t){if(f.current!==e)return;C(oe(t)),await re(240)}finally{f.current===e&&(m(``),v(!1))}});(0,y.useEffect)(()=>{f.current+=1;let e=f.current,t=!0;return(async()=>{for(;t&&f.current===e;)await F(e),await re(72)})(),()=>{t=!1,f.current+=1}},[c]);let se=[...h].reverse();return(0,N.jsxs)(`main`,{className:`capture-scene`,children:[(0,N.jsx)(`video`,{ref:u,autoPlay:!0,className:`capture-video`,loop:c.kind===`file`,muted:!0,onCanPlay:D,playsInline:!0}),(0,N.jsx)(`canvas`,{ref:d,className:`capture-canvas`}),(0,N.jsx)(`div`,{className:`capture-scrim`}),(0,N.jsx)(`header`,{className:`capture-toolbar`,children:(0,N.jsxs)(`div`,{className:`capture-toolbar__left`,children:[(0,N.jsx)(P,{}),(0,N.jsxs)(`div`,{className:`status-pill`,children:[(0,N.jsx)(`span`,{className:`status-dot ${w?`is-live`:``}`}),c.kind===`webcam`?`Webcam`:c.label]})]})}),e?(0,N.jsxs)(`div`,{className:`floating-alert`,role:`alert`,children:[(0,N.jsx)(`span`,{children:e}),(0,N.jsx)(`button`,{className:`ghost-button ghost-button--small`,onClick:r,type:`button`,children:`Dismiss`})]}):null,S?(0,N.jsx)(`div`,{className:`floating-alert floating-alert--secondary`,role:`alert`,children:(0,N.jsx)(`span`,{children:S})}):null,(0,N.jsxs)(`section`,{className:`prompt-dock`,children:[(0,N.jsx)(`span`,{className:`dock-label`,children:`Prompt`}),(0,N.jsx)(`div`,{className:`prompt-chip-row`,children:s.map(e=>(0,N.jsx)(`button`,{className:`prompt-chip ${o===e.prompt?`is-active`:``}`,onClick:()=>a(e.prompt),type:`button`,children:e.display},e.display))}),(0,N.jsx)(`textarea`,{className:`prompt-input`,onChange:e=>a(e.target.value),placeholder:`Ask the model anything about the current frame.`,rows:3,spellCheck:!1,value:o})]}),(0,N.jsxs)(`section`,{className:`capture-side-rail`,children:[(0,N.jsxs)(`div`,{className:`capture-actions`,children:[(0,N.jsxs)(`button`,{className:`ghost-button`,onClick:()=>x(e=>!e),type:`button`,children:[b?(0,N.jsx)(ee,{className:`button-icon`,size:16,strokeWidth:1.8}):(0,N.jsx)(j,{className:`button-icon`,size:16,strokeWidth:1.8}),b?`Resume`:`Pause`]}),(0,N.jsxs)(`button`,{className:`ghost-button`,onClick:()=>void n(),type:`button`,children:[(0,N.jsx)(k,{className:`button-icon`,size:16,strokeWidth:1.8}),`Webcam`]}),(0,N.jsxs)(`button`,{className:`ghost-button`,onClick:t,type:`button`,children:[(0,N.jsx)(A,{className:`button-icon`,size:16,strokeWidth:1.8}),`Video file`]}),(0,N.jsxs)(`button`,{className:`ghost-button`,onClick:i,type:`button`,children:[(0,N.jsx)(O,{className:`button-icon`,size:16,strokeWidth:1.8}),`Back`]})]}),(0,N.jsxs)(`section`,{className:`caption-dock`,children:[se.map((e,t)=>{let n=se.length-t,r=Math.max(.18,1-n*.18),i=1-n*.04;return(0,N.jsx)(`article`,{className:`caption-bubble caption-bubble--history`,style:{opacity:r,transform:`translateY(${-n*8}px) scale(${i})`},children:e.text},e.id)}),p||_?(0,N.jsxs)(`article`,{className:`caption-bubble caption-bubble--active`,children:[(0,N.jsx)(`div`,{className:`caption-meta`,children:`Live caption`}),p||(0,N.jsx)(`span`,{className:`caption-placeholder`,children:`Scanning current frame...`})]}):null]})]})]})}function ce(){return ce=Object.assign?Object.assign.bind():function(e){for(var t=1;t=0;--t)if(e[t]>=65535)return!0;return!1}var yn={Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array};function bn(e,t){return new yn[e](t)}function xn(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}function Sn(e){return document.createElementNS(`http://www.w3.org/1999/xhtml`,e)}function Cn(){let e=Sn(`canvas`);return e.style.display=`block`,e}var wn={},Tn=null;function En(e){Tn=e}function Dn(){return Tn}function On(...e){let t=`THREE.`+e.shift();Tn?Tn(`log`,t,...e):console.log(t,...e)}function kn(e){let t=e[0];if(typeof t==`string`&&t.startsWith(`TSL:`)){let t=e[1];t&&t.isStackTrace?e[0]+=` `+t.getLocation():e[1]=`Stack trace not available. Enable "THREE.Node.captureStackTrace" to capture stack traces.`}return e}function B(...e){e=kn(e);let t=`THREE.`+e.shift();if(Tn)Tn(`warn`,t,...e);else{let n=e[0];n&&n.isStackTrace?console.warn(n.getError(t)):console.warn(t,...e)}}function An(...e){e=kn(e);let t=`THREE.`+e.shift();if(Tn)Tn(`error`,t,...e);else{let n=e[0];n&&n.isStackTrace?console.error(n.getError(t)):console.error(t,...e)}}function jn(...e){let t=e.join(` `);t in wn||(wn[t]=!0,B(...e))}function Mn(e,t,n){return new Promise(function(r,i){function a(){switch(e.clientWaitSync(t,e.SYNC_FLUSH_COMMANDS_BIT,0)){case e.WAIT_FAILED:i();break;case e.TIMEOUT_EXPIRED:setTimeout(a,n);break;default:r()}}setTimeout(a,n)})}var Nn={0:1,2:6,4:7,3:5,1:0,6:2,7:4,5:3},Pn=class{addEventListener(e,t){this._listeners===void 0&&(this._listeners={});let n=this._listeners;n[e]===void 0&&(n[e]=[]),n[e].indexOf(t)===-1&&n[e].push(t)}hasEventListener(e,t){let n=this._listeners;return n===void 0?!1:n[e]!==void 0&&n[e].indexOf(t)!==-1}removeEventListener(e,t){let n=this._listeners;if(n===void 0)return;let r=n[e];if(r!==void 0){let e=r.indexOf(t);e!==-1&&r.splice(e,1)}}dispatchEvent(e){let t=this._listeners;if(t===void 0)return;let n=t[e.type];if(n!==void 0){e.target=this;let t=n.slice(0);for(let n=0,r=t.length;n>8&255]+Fn[e>>16&255]+Fn[e>>24&255]+`-`+Fn[t&255]+Fn[t>>8&255]+`-`+Fn[t>>16&15|64]+Fn[t>>24&255]+`-`+Fn[n&63|128]+Fn[n>>8&255]+`-`+Fn[n>>16&255]+Fn[n>>24&255]+Fn[r&255]+Fn[r>>8&255]+Fn[r>>16&255]+Fn[r>>24&255]).toLowerCase()}function Bn(e,t,n){return Math.max(t,Math.min(n,e))}function Vn(e,t){return(e%t+t)%t}function Hn(e,t,n,r,i){return r+(e-t)*(i-r)/(n-t)}function Un(e,t,n){return e===t?0:(n-e)/(t-e)}function Wn(e,t,n){return(1-n)*e+n*t}function Gn(e,t,n,r){return Wn(e,t,1-Math.exp(-n*r))}function Kn(e,t=1){return t-Math.abs(Vn(e,t*2)-t)}function qn(e,t,n){return e<=t?0:e>=n?1:(e=(e-t)/(n-t),e*e*(3-2*e))}function Jn(e,t,n){return e<=t?0:e>=n?1:(e=(e-t)/(n-t),e*e*e*(e*(e*6-15)+10))}function Yn(e,t){return e+Math.floor(Math.random()*(t-e+1))}function Xn(e,t){return e+Math.random()*(t-e)}function Zn(e){return e*(.5-Math.random())}function Qn(e){e!==void 0&&(In=e);let t=In+=1831565813;return t=Math.imul(t^t>>>15,t|1),t^=t+Math.imul(t^t>>>7,t|61),((t^t>>>14)>>>0)/4294967296}function $n(e){return e*Ln}function er(e){return e*Rn}function tr(e){return(e&e-1)==0&&e!==0}function nr(e){return 2**Math.ceil(Math.log(e)/Math.LN2)}function rr(e){return 2**Math.floor(Math.log(e)/Math.LN2)}function ir(e,t,n,r,i){let a=Math.cos,o=Math.sin,s=a(n/2),c=o(n/2),l=a((t+r)/2),u=o((t+r)/2),d=a((t-r)/2),f=o((t-r)/2),p=a((r-t)/2),m=o((r-t)/2);switch(i){case`XYX`:e.set(s*u,c*d,c*f,s*l);break;case`YZY`:e.set(c*f,s*u,c*d,s*l);break;case`ZXZ`:e.set(c*d,c*f,s*u,s*l);break;case`XZX`:e.set(s*u,c*m,c*p,s*l);break;case`YXY`:e.set(c*p,s*u,c*m,s*l);break;case`ZYZ`:e.set(c*m,c*p,s*u,s*l);break;default:B(`MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: `+i)}}function ar(e,t){switch(t.constructor){case Float32Array:return e;case Uint32Array:return e/4294967295;case Uint16Array:return e/65535;case Uint8Array:return e/255;case Int32Array:return Math.max(e/2147483647,-1);case Int16Array:return Math.max(e/32767,-1);case Int8Array:return Math.max(e/127,-1);default:throw Error(`Invalid component type.`)}}function or(e,t){switch(t.constructor){case Float32Array:return e;case Uint32Array:return Math.round(e*4294967295);case Uint16Array:return Math.round(e*65535);case Uint8Array:return Math.round(e*255);case Int32Array:return Math.round(e*2147483647);case Int16Array:return Math.round(e*32767);case Int8Array:return Math.round(e*127);default:throw Error(`Invalid component type.`)}}var sr={DEG2RAD:Ln,RAD2DEG:Rn,generateUUID:zn,clamp:Bn,euclideanModulo:Vn,mapLinear:Hn,inverseLerp:Un,lerp:Wn,damp:Gn,pingpong:Kn,smoothstep:qn,smootherstep:Jn,randInt:Yn,randFloat:Xn,randFloatSpread:Zn,seededRandom:Qn,degToRad:$n,radToDeg:er,isPowerOfTwo:tr,ceilPowerOfTwo:nr,floorPowerOfTwo:rr,setQuaternionFromProperEuler:ir,normalize:or,denormalize:ar},V=class e{constructor(t=0,n=0){e.prototype.isVector2=!0,this.x=t,this.y=n}get width(){return this.x}set width(e){this.x=e}get height(){return this.y}set height(e){this.y=e}set(e,t){return this.x=e,this.y=t,this}setScalar(e){return this.x=e,this.y=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;default:throw Error(`index is out of range: `+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;default:throw Error(`index is out of range: `+e)}}clone(){return new this.constructor(this.x,this.y)}copy(e){return this.x=e.x,this.y=e.y,this}add(e){return this.x+=e.x,this.y+=e.y,this}addScalar(e){return this.x+=e,this.y+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this}subScalar(e){return this.x-=e,this.y-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this}multiply(e){return this.x*=e.x,this.y*=e.y,this}multiplyScalar(e){return this.x*=e,this.y*=e,this}divide(e){return this.x/=e.x,this.y/=e.y,this}divideScalar(e){return this.multiplyScalar(1/e)}applyMatrix3(e){let t=this.x,n=this.y,r=e.elements;return this.x=r[0]*t+r[3]*n+r[6],this.y=r[1]*t+r[4]*n+r[7],this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this}clamp(e,t){return this.x=Bn(this.x,e.x,t.x),this.y=Bn(this.y,e.y,t.y),this}clampScalar(e,t){return this.x=Bn(this.x,e,t),this.y=Bn(this.y,e,t),this}clampLength(e,t){let n=this.length();return this.divideScalar(n||1).multiplyScalar(Bn(n,e,t))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this}negate(){return this.x=-this.x,this.y=-this.y,this}dot(e){return this.x*e.x+this.y*e.y}cross(e){return this.x*e.y-this.y*e.x}lengthSq(){return this.x*this.x+this.y*this.y}length(){return Math.sqrt(this.x*this.x+this.y*this.y)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)}normalize(){return this.divideScalar(this.length()||1)}angle(){return Math.atan2(-this.y,-this.x)+Math.PI}angleTo(e){let t=Math.sqrt(this.lengthSq()*e.lengthSq());if(t===0)return Math.PI/2;let n=this.dot(e)/t;return Math.acos(Bn(n,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){let t=this.x-e.x,n=this.y-e.y;return t*t+n*n}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this}lerpVectors(e,t,n){return this.x=e.x+(t.x-e.x)*n,this.y=e.y+(t.y-e.y)*n,this}equals(e){return e.x===this.x&&e.y===this.y}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this}rotateAround(e,t){let n=Math.cos(t),r=Math.sin(t),i=this.x-e.x,a=this.y-e.y;return this.x=i*n-a*r+e.x,this.y=i*r+a*n+e.y,this}random(){return this.x=Math.random(),this.y=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y}},cr=class{constructor(e=0,t=0,n=0,r=1){this.isQuaternion=!0,this._x=e,this._y=t,this._z=n,this._w=r}static slerpFlat(e,t,n,r,i,a,o){let s=n[r+0],c=n[r+1],l=n[r+2],u=n[r+3],d=i[a+0],f=i[a+1],p=i[a+2],m=i[a+3];if(u!==m||s!==d||c!==f||l!==p){let e=s*d+c*f+l*p+u*m;e<0&&(d=-d,f=-f,p=-p,m=-m,e=-e);let t=1-o;if(e<.9995){let n=Math.acos(e),r=Math.sin(n);t=Math.sin(t*n)/r,o=Math.sin(o*n)/r,s=s*t+d*o,c=c*t+f*o,l=l*t+p*o,u=u*t+m*o}else{s=s*t+d*o,c=c*t+f*o,l=l*t+p*o,u=u*t+m*o;let e=1/Math.sqrt(s*s+c*c+l*l+u*u);s*=e,c*=e,l*=e,u*=e}}e[t]=s,e[t+1]=c,e[t+2]=l,e[t+3]=u}static multiplyQuaternionsFlat(e,t,n,r,i,a){let o=n[r],s=n[r+1],c=n[r+2],l=n[r+3],u=i[a],d=i[a+1],f=i[a+2],p=i[a+3];return e[t]=o*p+l*u+s*f-c*d,e[t+1]=s*p+l*d+c*u-o*f,e[t+2]=c*p+l*f+o*d-s*u,e[t+3]=l*p-o*u-s*d-c*f,e}get x(){return this._x}set x(e){this._x=e,this._onChangeCallback()}get y(){return this._y}set y(e){this._y=e,this._onChangeCallback()}get z(){return this._z}set z(e){this._z=e,this._onChangeCallback()}get w(){return this._w}set w(e){this._w=e,this._onChangeCallback()}set(e,t,n,r){return this._x=e,this._y=t,this._z=n,this._w=r,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._w)}copy(e){return this._x=e.x,this._y=e.y,this._z=e.z,this._w=e.w,this._onChangeCallback(),this}setFromEuler(e,t=!0){let n=e._x,r=e._y,i=e._z,a=e._order,o=Math.cos,s=Math.sin,c=o(n/2),l=o(r/2),u=o(i/2),d=s(n/2),f=s(r/2),p=s(i/2);switch(a){case`XYZ`:this._x=d*l*u+c*f*p,this._y=c*f*u-d*l*p,this._z=c*l*p+d*f*u,this._w=c*l*u-d*f*p;break;case`YXZ`:this._x=d*l*u+c*f*p,this._y=c*f*u-d*l*p,this._z=c*l*p-d*f*u,this._w=c*l*u+d*f*p;break;case`ZXY`:this._x=d*l*u-c*f*p,this._y=c*f*u+d*l*p,this._z=c*l*p+d*f*u,this._w=c*l*u-d*f*p;break;case`ZYX`:this._x=d*l*u-c*f*p,this._y=c*f*u+d*l*p,this._z=c*l*p-d*f*u,this._w=c*l*u+d*f*p;break;case`YZX`:this._x=d*l*u+c*f*p,this._y=c*f*u+d*l*p,this._z=c*l*p-d*f*u,this._w=c*l*u-d*f*p;break;case`XZY`:this._x=d*l*u-c*f*p,this._y=c*f*u-d*l*p,this._z=c*l*p+d*f*u,this._w=c*l*u+d*f*p;break;default:B(`Quaternion: .setFromEuler() encountered an unknown order: `+a)}return t===!0&&this._onChangeCallback(),this}setFromAxisAngle(e,t){let n=t/2,r=Math.sin(n);return this._x=e.x*r,this._y=e.y*r,this._z=e.z*r,this._w=Math.cos(n),this._onChangeCallback(),this}setFromRotationMatrix(e){let t=e.elements,n=t[0],r=t[4],i=t[8],a=t[1],o=t[5],s=t[9],c=t[2],l=t[6],u=t[10],d=n+o+u;if(d>0){let e=.5/Math.sqrt(d+1);this._w=.25/e,this._x=(l-s)*e,this._y=(i-c)*e,this._z=(a-r)*e}else if(n>o&&n>u){let e=2*Math.sqrt(1+n-o-u);this._w=(l-s)/e,this._x=.25*e,this._y=(r+a)/e,this._z=(i+c)/e}else if(o>u){let e=2*Math.sqrt(1+o-n-u);this._w=(i-c)/e,this._x=(r+a)/e,this._y=.25*e,this._z=(s+l)/e}else{let e=2*Math.sqrt(1+u-n-o);this._w=(a-r)/e,this._x=(i+c)/e,this._y=(s+l)/e,this._z=.25*e}return this._onChangeCallback(),this}setFromUnitVectors(e,t){let n=e.dot(t)+1;return n<1e-8?(n=0,Math.abs(e.x)>Math.abs(e.z)?(this._x=-e.y,this._y=e.x,this._z=0,this._w=n):(this._x=0,this._y=-e.z,this._z=e.y,this._w=n)):(this._x=e.y*t.z-e.z*t.y,this._y=e.z*t.x-e.x*t.z,this._z=e.x*t.y-e.y*t.x,this._w=n),this.normalize()}angleTo(e){return 2*Math.acos(Math.abs(Bn(this.dot(e),-1,1)))}rotateTowards(e,t){let n=this.angleTo(e);if(n===0)return this;let r=Math.min(1,t/n);return this.slerp(e,r),this}identity(){return this.set(0,0,0,1)}invert(){return this.conjugate()}conjugate(){return this._x*=-1,this._y*=-1,this._z*=-1,this._onChangeCallback(),this}dot(e){return this._x*e._x+this._y*e._y+this._z*e._z+this._w*e._w}lengthSq(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w}length(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w)}normalize(){let e=this.length();return e===0?(this._x=0,this._y=0,this._z=0,this._w=1):(e=1/e,this._x*=e,this._y*=e,this._z*=e,this._w*=e),this._onChangeCallback(),this}multiply(e){return this.multiplyQuaternions(this,e)}premultiply(e){return this.multiplyQuaternions(e,this)}multiplyQuaternions(e,t){let n=e._x,r=e._y,i=e._z,a=e._w,o=t._x,s=t._y,c=t._z,l=t._w;return this._x=n*l+a*o+r*c-i*s,this._y=r*l+a*s+i*o-n*c,this._z=i*l+a*c+n*s-r*o,this._w=a*l-n*o-r*s-i*c,this._onChangeCallback(),this}slerp(e,t){let n=e._x,r=e._y,i=e._z,a=e._w,o=this.dot(e);o<0&&(n=-n,r=-r,i=-i,a=-a,o=-o);let s=1-t;if(o<.9995){let e=Math.acos(o),c=Math.sin(e);s=Math.sin(s*e)/c,t=Math.sin(t*e)/c,this._x=this._x*s+n*t,this._y=this._y*s+r*t,this._z=this._z*s+i*t,this._w=this._w*s+a*t,this._onChangeCallback()}else this._x=this._x*s+n*t,this._y=this._y*s+r*t,this._z=this._z*s+i*t,this._w=this._w*s+a*t,this.normalize();return this}slerpQuaternions(e,t,n){return this.copy(e).slerp(t,n)}random(){let e=2*Math.PI*Math.random(),t=2*Math.PI*Math.random(),n=Math.random(),r=Math.sqrt(1-n),i=Math.sqrt(n);return this.set(r*Math.sin(e),r*Math.cos(e),i*Math.sin(t),i*Math.cos(t))}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._w===this._w}fromArray(e,t=0){return this._x=e[t],this._y=e[t+1],this._z=e[t+2],this._w=e[t+3],this._onChangeCallback(),this}toArray(e=[],t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._w,e}fromBufferAttribute(e,t){return this._x=e.getX(t),this._y=e.getY(t),this._z=e.getZ(t),this._w=e.getW(t),this._onChangeCallback(),this}toJSON(){return this.toArray()}_onChange(e){return this._onChangeCallback=e,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._w}},H=class e{constructor(t=0,n=0,r=0){e.prototype.isVector3=!0,this.x=t,this.y=n,this.z=r}set(e,t,n){return n===void 0&&(n=this.z),this.x=e,this.y=t,this.z=n,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;case 2:this.z=t;break;default:throw Error(`index is out of range: `+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;default:throw Error(`index is out of range: `+e)}}clone(){return new this.constructor(this.x,this.y,this.z)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this}multiplyVectors(e,t){return this.x=e.x*t.x,this.y=e.y*t.y,this.z=e.z*t.z,this}applyEuler(e){return this.applyQuaternion(ur.setFromEuler(e))}applyAxisAngle(e,t){return this.applyQuaternion(ur.setFromAxisAngle(e,t))}applyMatrix3(e){let t=this.x,n=this.y,r=this.z,i=e.elements;return this.x=i[0]*t+i[3]*n+i[6]*r,this.y=i[1]*t+i[4]*n+i[7]*r,this.z=i[2]*t+i[5]*n+i[8]*r,this}applyNormalMatrix(e){return this.applyMatrix3(e).normalize()}applyMatrix4(e){let t=this.x,n=this.y,r=this.z,i=e.elements,a=1/(i[3]*t+i[7]*n+i[11]*r+i[15]);return this.x=(i[0]*t+i[4]*n+i[8]*r+i[12])*a,this.y=(i[1]*t+i[5]*n+i[9]*r+i[13])*a,this.z=(i[2]*t+i[6]*n+i[10]*r+i[14])*a,this}applyQuaternion(e){let t=this.x,n=this.y,r=this.z,i=e.x,a=e.y,o=e.z,s=e.w,c=2*(a*r-o*n),l=2*(o*t-i*r),u=2*(i*n-a*t);return this.x=t+s*c+a*u-o*l,this.y=n+s*l+o*c-i*u,this.z=r+s*u+i*l-a*c,this}project(e){return this.applyMatrix4(e.matrixWorldInverse).applyMatrix4(e.projectionMatrix)}unproject(e){return this.applyMatrix4(e.projectionMatrixInverse).applyMatrix4(e.matrixWorld)}transformDirection(e){let t=this.x,n=this.y,r=this.z,i=e.elements;return this.x=i[0]*t+i[4]*n+i[8]*r,this.y=i[1]*t+i[5]*n+i[9]*r,this.z=i[2]*t+i[6]*n+i[10]*r,this.normalize()}divide(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this}divideScalar(e){return this.multiplyScalar(1/e)}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this}clamp(e,t){return this.x=Bn(this.x,e.x,t.x),this.y=Bn(this.y,e.y,t.y),this.z=Bn(this.z,e.z,t.z),this}clampScalar(e,t){return this.x=Bn(this.x,e,t),this.y=Bn(this.y,e,t),this.z=Bn(this.z,e,t),this}clampLength(e,t){let n=this.length();return this.divideScalar(n||1).multiplyScalar(Bn(n,e,t))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)}normalize(){return this.divideScalar(this.length()||1)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this.z+=(e.z-this.z)*t,this}lerpVectors(e,t,n){return this.x=e.x+(t.x-e.x)*n,this.y=e.y+(t.y-e.y)*n,this.z=e.z+(t.z-e.z)*n,this}cross(e){return this.crossVectors(this,e)}crossVectors(e,t){let n=e.x,r=e.y,i=e.z,a=t.x,o=t.y,s=t.z;return this.x=r*s-i*o,this.y=i*a-n*s,this.z=n*o-r*a,this}projectOnVector(e){let t=e.lengthSq();if(t===0)return this.set(0,0,0);let n=e.dot(this)/t;return this.copy(e).multiplyScalar(n)}projectOnPlane(e){return lr.copy(this).projectOnVector(e),this.sub(lr)}reflect(e){return this.sub(lr.copy(e).multiplyScalar(2*this.dot(e)))}angleTo(e){let t=Math.sqrt(this.lengthSq()*e.lengthSq());if(t===0)return Math.PI/2;let n=this.dot(e)/t;return Math.acos(Bn(n,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){let t=this.x-e.x,n=this.y-e.y,r=this.z-e.z;return t*t+n*n+r*r}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)+Math.abs(this.z-e.z)}setFromSpherical(e){return this.setFromSphericalCoords(e.radius,e.phi,e.theta)}setFromSphericalCoords(e,t,n){let r=Math.sin(t)*e;return this.x=r*Math.sin(n),this.y=Math.cos(t)*e,this.z=r*Math.cos(n),this}setFromCylindrical(e){return this.setFromCylindricalCoords(e.radius,e.theta,e.y)}setFromCylindricalCoords(e,t,n){return this.x=e*Math.sin(t),this.y=n,this.z=e*Math.cos(t),this}setFromMatrixPosition(e){let t=e.elements;return this.x=t[12],this.y=t[13],this.z=t[14],this}setFromMatrixScale(e){let t=this.setFromMatrixColumn(e,0).length(),n=this.setFromMatrixColumn(e,1).length(),r=this.setFromMatrixColumn(e,2).length();return this.x=t,this.y=n,this.z=r,this}setFromMatrixColumn(e,t){return this.fromArray(e.elements,t*4)}setFromMatrix3Column(e,t){return this.fromArray(e.elements,t*3)}setFromEuler(e){return this.x=e._x,this.y=e._y,this.z=e._z,this}setFromColor(e){return this.x=e.r,this.y=e.g,this.z=e.b,this}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this.z=e[t+2],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this.z=e.getZ(t),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this}randomDirection(){let e=Math.random()*Math.PI*2,t=Math.random()*2-1,n=Math.sqrt(1-t*t);return this.x=n*Math.cos(e),this.y=t,this.z=n*Math.sin(e),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z}},lr=new H,ur=new cr,dr=class e{constructor(t,n,r,i,a,o,s,c,l){e.prototype.isMatrix3=!0,this.elements=[1,0,0,0,1,0,0,0,1],t!==void 0&&this.set(t,n,r,i,a,o,s,c,l)}set(e,t,n,r,i,a,o,s,c){let l=this.elements;return l[0]=e,l[1]=r,l[2]=o,l[3]=t,l[4]=i,l[5]=s,l[6]=n,l[7]=a,l[8]=c,this}identity(){return this.set(1,0,0,0,1,0,0,0,1),this}copy(e){let t=this.elements,n=e.elements;return t[0]=n[0],t[1]=n[1],t[2]=n[2],t[3]=n[3],t[4]=n[4],t[5]=n[5],t[6]=n[6],t[7]=n[7],t[8]=n[8],this}extractBasis(e,t,n){return e.setFromMatrix3Column(this,0),t.setFromMatrix3Column(this,1),n.setFromMatrix3Column(this,2),this}setFromMatrix4(e){let t=e.elements;return this.set(t[0],t[4],t[8],t[1],t[5],t[9],t[2],t[6],t[10]),this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,t){let n=e.elements,r=t.elements,i=this.elements,a=n[0],o=n[3],s=n[6],c=n[1],l=n[4],u=n[7],d=n[2],f=n[5],p=n[8],m=r[0],h=r[3],g=r[6],_=r[1],v=r[4],y=r[7],b=r[2],x=r[5],S=r[8];return i[0]=a*m+o*_+s*b,i[3]=a*h+o*v+s*x,i[6]=a*g+o*y+s*S,i[1]=c*m+l*_+u*b,i[4]=c*h+l*v+u*x,i[7]=c*g+l*y+u*S,i[2]=d*m+f*_+p*b,i[5]=d*h+f*v+p*x,i[8]=d*g+f*y+p*S,this}multiplyScalar(e){let t=this.elements;return t[0]*=e,t[3]*=e,t[6]*=e,t[1]*=e,t[4]*=e,t[7]*=e,t[2]*=e,t[5]*=e,t[8]*=e,this}determinant(){let e=this.elements,t=e[0],n=e[1],r=e[2],i=e[3],a=e[4],o=e[5],s=e[6],c=e[7],l=e[8];return t*a*l-t*o*c-n*i*l+n*o*s+r*i*c-r*a*s}invert(){let e=this.elements,t=e[0],n=e[1],r=e[2],i=e[3],a=e[4],o=e[5],s=e[6],c=e[7],l=e[8],u=l*a-o*c,d=o*s-l*i,f=c*i-a*s,p=t*u+n*d+r*f;if(p===0)return this.set(0,0,0,0,0,0,0,0,0);let m=1/p;return e[0]=u*m,e[1]=(r*c-l*n)*m,e[2]=(o*n-r*a)*m,e[3]=d*m,e[4]=(l*t-r*s)*m,e[5]=(r*i-o*t)*m,e[6]=f*m,e[7]=(n*s-c*t)*m,e[8]=(a*t-n*i)*m,this}transpose(){let e,t=this.elements;return e=t[1],t[1]=t[3],t[3]=e,e=t[2],t[2]=t[6],t[6]=e,e=t[5],t[5]=t[7],t[7]=e,this}getNormalMatrix(e){return this.setFromMatrix4(e).invert().transpose()}transposeIntoArray(e){let t=this.elements;return e[0]=t[0],e[1]=t[3],e[2]=t[6],e[3]=t[1],e[4]=t[4],e[5]=t[7],e[6]=t[2],e[7]=t[5],e[8]=t[8],this}setUvTransform(e,t,n,r,i,a,o){let s=Math.cos(i),c=Math.sin(i);return this.set(n*s,n*c,-n*(s*a+c*o)+a+e,-r*c,r*s,-r*(-c*a+s*o)+o+t,0,0,1),this}scale(e,t){return this.premultiply(fr.makeScale(e,t)),this}rotate(e){return this.premultiply(fr.makeRotation(-e)),this}translate(e,t){return this.premultiply(fr.makeTranslation(e,t)),this}makeTranslation(e,t){return e.isVector2?this.set(1,0,e.x,0,1,e.y,0,0,1):this.set(1,0,e,0,1,t,0,0,1),this}makeRotation(e){let t=Math.cos(e),n=Math.sin(e);return this.set(t,-n,0,n,t,0,0,0,1),this}makeScale(e,t){return this.set(e,0,0,0,t,0,0,0,1),this}equals(e){let t=this.elements,n=e.elements;for(let e=0;e<9;e++)if(t[e]!==n[e])return!1;return!0}fromArray(e,t=0){for(let n=0;n<9;n++)this.elements[n]=e[n+t];return this}toArray(e=[],t=0){let n=this.elements;return e[t]=n[0],e[t+1]=n[1],e[t+2]=n[2],e[t+3]=n[3],e[t+4]=n[4],e[t+5]=n[5],e[t+6]=n[6],e[t+7]=n[7],e[t+8]=n[8],e}clone(){return new this.constructor().fromArray(this.elements)}},fr=new dr,pr=new dr().set(.4123908,.3575843,.1804808,.212639,.7151687,.0721923,.0193308,.1191948,.9505322),mr=new dr().set(3.2409699,-1.5373832,-.4986108,-.9692436,1.8759675,.0415551,.0556301,-.203977,1.0569715);function hr(){let e={enabled:!0,workingColorSpace:Gt,spaces:{},convert:function(e,t,n){return this.enabled===!1||t===n||!t||!n?e:(this.spaces[t].transfer===`srgb`&&(e.r=_r(e.r),e.g=_r(e.g),e.b=_r(e.b)),this.spaces[t].primaries!==this.spaces[n].primaries&&(e.applyMatrix3(this.spaces[t].toXYZ),e.applyMatrix3(this.spaces[n].fromXYZ)),this.spaces[n].transfer===`srgb`&&(e.r=vr(e.r),e.g=vr(e.g),e.b=vr(e.b)),e)},workingToColorSpace:function(e,t){return this.convert(e,this.workingColorSpace,t)},colorSpaceToWorking:function(e,t){return this.convert(e,t,this.workingColorSpace)},getPrimaries:function(e){return this.spaces[e].primaries},getTransfer:function(e){return e===``?Kt:this.spaces[e].transfer},getToneMappingMode:function(e){return this.spaces[e].outputColorSpaceConfig.toneMappingMode||`standard`},getLuminanceCoefficients:function(e,t=this.workingColorSpace){return e.fromArray(this.spaces[t].luminanceCoefficients)},define:function(e){Object.assign(this.spaces,e)},_getMatrix:function(e,t,n){return e.copy(this.spaces[t].toXYZ).multiply(this.spaces[n].fromXYZ)},_getDrawingBufferColorSpace:function(e){return this.spaces[e].outputColorSpaceConfig.drawingBufferColorSpace},_getUnpackColorSpace:function(e=this.workingColorSpace){return this.spaces[e].workingColorSpaceConfig.unpackColorSpace},fromWorkingColorSpace:function(t,n){return jn(`ColorManagement: .fromWorkingColorSpace() has been renamed to .workingToColorSpace().`),e.workingToColorSpace(t,n)},toWorkingColorSpace:function(t,n){return jn(`ColorManagement: .toWorkingColorSpace() has been renamed to .colorSpaceToWorking().`),e.colorSpaceToWorking(t,n)}},t=[.64,.33,.3,.6,.15,.06],n=[.2126,.7152,.0722],r=[.3127,.329];return e.define({[Gt]:{primaries:t,whitePoint:r,transfer:Kt,toXYZ:pr,fromXYZ:mr,luminanceCoefficients:n,workingColorSpaceConfig:{unpackColorSpace:Wt},outputColorSpaceConfig:{drawingBufferColorSpace:Wt}},[Wt]:{primaries:t,whitePoint:r,transfer:qt,toXYZ:pr,fromXYZ:mr,luminanceCoefficients:n,outputColorSpaceConfig:{drawingBufferColorSpace:Wt}}}),e}var gr=hr();function _r(e){return e<.04045?e*.0773993808:(e*.9478672986+.0521327014)**2.4}function vr(e){return e<.0031308?e*12.92:1.055*e**.41666-.055}var yr,br=class{static getDataURL(e,t=`image/png`){if(/^data:/i.test(e.src)||typeof HTMLCanvasElement>`u`)return e.src;let n;if(e instanceof HTMLCanvasElement)n=e;else{yr===void 0&&(yr=Sn(`canvas`)),yr.width=e.width,yr.height=e.height;let t=yr.getContext(`2d`);e instanceof ImageData?t.putImageData(e,0,0):t.drawImage(e,0,0,e.width,e.height),n=yr}return n.toDataURL(t)}static sRGBToLinear(e){if(typeof HTMLImageElement<`u`&&e instanceof HTMLImageElement||typeof HTMLCanvasElement<`u`&&e instanceof HTMLCanvasElement||typeof ImageBitmap<`u`&&e instanceof ImageBitmap){let t=Sn(`canvas`);t.width=e.width,t.height=e.height;let n=t.getContext(`2d`);n.drawImage(e,0,0,e.width,e.height);let r=n.getImageData(0,0,e.width,e.height),i=r.data;for(let e=0;e1),this.pmremVersion=0}get width(){return this.source.getSize(Tr).x}get height(){return this.source.getSize(Tr).y}get depth(){return this.source.getSize(Tr).z}get image(){return this.source.data}set image(e=null){this.source.data=e}updateMatrix(){this.matrix.setUvTransform(this.offset.x,this.offset.y,this.repeat.x,this.repeat.y,this.rotation,this.center.x,this.center.y)}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}clone(){return new this.constructor().copy(this)}copy(e){return this.name=e.name,this.source=e.source,this.mipmaps=e.mipmaps.slice(0),this.mapping=e.mapping,this.channel=e.channel,this.wrapS=e.wrapS,this.wrapT=e.wrapT,this.magFilter=e.magFilter,this.minFilter=e.minFilter,this.anisotropy=e.anisotropy,this.format=e.format,this.internalFormat=e.internalFormat,this.type=e.type,this.offset.copy(e.offset),this.repeat.copy(e.repeat),this.center.copy(e.center),this.rotation=e.rotation,this.matrixAutoUpdate=e.matrixAutoUpdate,this.matrix.copy(e.matrix),this.generateMipmaps=e.generateMipmaps,this.premultiplyAlpha=e.premultiplyAlpha,this.flipY=e.flipY,this.unpackAlignment=e.unpackAlignment,this.colorSpace=e.colorSpace,this.renderTarget=e.renderTarget,this.isRenderTargetTexture=e.isRenderTargetTexture,this.isArrayTexture=e.isArrayTexture,this.userData=JSON.parse(JSON.stringify(e.userData)),this.needsUpdate=!0,this}setValues(e){for(let t in e){let n=e[t];if(n===void 0){B(`Texture.setValues(): parameter '${t}' has value of undefined.`);continue}let r=this[t];if(r===void 0){B(`Texture.setValues(): property '${t}' does not exist.`);continue}r&&n&&r.isVector2&&n.isVector2||r&&n&&r.isVector3&&n.isVector3||r&&n&&r.isMatrix3&&n.isMatrix3?r.copy(n):this[t]=n}}toJSON(e){let t=e===void 0||typeof e==`string`;if(!t&&e.textures[this.uuid]!==void 0)return e.textures[this.uuid];let n={metadata:{version:4.7,type:`Texture`,generator:`Texture.toJSON`},uuid:this.uuid,name:this.name,image:this.source.toJSON(e).uuid,mapping:this.mapping,channel:this.channel,repeat:[this.repeat.x,this.repeat.y],offset:[this.offset.x,this.offset.y],center:[this.center.x,this.center.y],rotation:this.rotation,wrap:[this.wrapS,this.wrapT],format:this.format,internalFormat:this.internalFormat,type:this.type,colorSpace:this.colorSpace,minFilter:this.minFilter,magFilter:this.magFilter,anisotropy:this.anisotropy,flipY:this.flipY,generateMipmaps:this.generateMipmaps,premultiplyAlpha:this.premultiplyAlpha,unpackAlignment:this.unpackAlignment};return Object.keys(this.userData).length>0&&(n.userData=this.userData),t||(e.textures[this.uuid]=n),n}dispose(){this.dispatchEvent({type:`dispose`})}transformUv(e){if(this.mapping!==300)return e;if(e.applyMatrix3(this.matrix),e.x<0||e.x>1)switch(this.wrapS){case pe:e.x-=Math.floor(e.x);break;case me:e.x=e.x<0?0:1;break;case he:Math.abs(Math.floor(e.x)%2)===1?e.x=Math.ceil(e.x)-e.x:e.x-=Math.floor(e.x);break}if(e.y<0||e.y>1)switch(this.wrapT){case pe:e.y-=Math.floor(e.y);break;case me:e.y=e.y<0?0:1;break;case he:Math.abs(Math.floor(e.y)%2)===1?e.y=Math.ceil(e.y)-e.y:e.y-=Math.floor(e.y);break}return this.flipY&&(e.y=1-e.y),e}set needsUpdate(e){e===!0&&(this.version++,this.source.needsUpdate=!0)}set needsPMREMUpdate(e){e===!0&&this.pmremVersion++}};Er.DEFAULT_IMAGE=null,Er.DEFAULT_MAPPING=300,Er.DEFAULT_ANISOTROPY=1;var Dr=class e{constructor(t=0,n=0,r=0,i=1){e.prototype.isVector4=!0,this.x=t,this.y=n,this.z=r,this.w=i}get width(){return this.z}set width(e){this.z=e}get height(){return this.w}set height(e){this.w=e}set(e,t,n,r){return this.x=e,this.y=t,this.z=n,this.w=r,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this.w=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setW(e){return this.w=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;case 2:this.z=t;break;case 3:this.w=t;break;default:throw Error(`index is out of range: `+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;case 3:return this.w;default:throw Error(`index is out of range: `+e)}}clone(){return new this.constructor(this.x,this.y,this.z,this.w)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this.w=e.w===void 0?1:e.w,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this.w+=e.w,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this.w+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this.w=e.w+t.w,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this.w+=e.w*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this.w-=e.w,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this.w-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this.w=e.w-t.w,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this.w*=e.w,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this.w*=e,this}applyMatrix4(e){let t=this.x,n=this.y,r=this.z,i=this.w,a=e.elements;return this.x=a[0]*t+a[4]*n+a[8]*r+a[12]*i,this.y=a[1]*t+a[5]*n+a[9]*r+a[13]*i,this.z=a[2]*t+a[6]*n+a[10]*r+a[14]*i,this.w=a[3]*t+a[7]*n+a[11]*r+a[15]*i,this}divide(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this.w/=e.w,this}divideScalar(e){return this.multiplyScalar(1/e)}setAxisAngleFromQuaternion(e){this.w=2*Math.acos(e.w);let t=Math.sqrt(1-e.w*e.w);return t<1e-4?(this.x=1,this.y=0,this.z=0):(this.x=e.x/t,this.y=e.y/t,this.z=e.z/t),this}setAxisAngleFromRotationMatrix(e){let t,n,r,i,a=.01,o=.1,s=e.elements,c=s[0],l=s[4],u=s[8],d=s[1],f=s[5],p=s[9],m=s[2],h=s[6],g=s[10];if(Math.abs(l-d)s&&e>_?e_?s1);this.dispose()}this.viewport.set(0,0,e,t),this.scissor.set(0,0,e,t)}clone(){return new this.constructor().copy(this)}copy(e){this.width=e.width,this.height=e.height,this.depth=e.depth,this.scissor.copy(e.scissor),this.scissorTest=e.scissorTest,this.viewport.copy(e.viewport),this.textures.length=0;for(let t=0,n=e.textures.length;t>>0}enable(e){this.mask|=1<1){for(let e=0;e1){for(let e=0;e0&&(r.userData=this.userData),r.layers=this.layers.mask,r.matrix=this.matrix.toArray(),r.up=this.up.toArray(),this.pivot!==null&&(r.pivot=this.pivot.toArray()),this.matrixAutoUpdate===!1&&(r.matrixAutoUpdate=!1),this.morphTargetDictionary!==void 0&&(r.morphTargetDictionary=Object.assign({},this.morphTargetDictionary)),this.morphTargetInfluences!==void 0&&(r.morphTargetInfluences=this.morphTargetInfluences.slice()),this.isInstancedMesh&&(r.type=`InstancedMesh`,r.count=this.count,r.instanceMatrix=this.instanceMatrix.toJSON(),this.instanceColor!==null&&(r.instanceColor=this.instanceColor.toJSON())),this.isBatchedMesh&&(r.type=`BatchedMesh`,r.perObjectFrustumCulled=this.perObjectFrustumCulled,r.sortObjects=this.sortObjects,r.drawRanges=this._drawRanges,r.reservedRanges=this._reservedRanges,r.geometryInfo=this._geometryInfo.map(e=>({...e,boundingBox:e.boundingBox?e.boundingBox.toJSON():void 0,boundingSphere:e.boundingSphere?e.boundingSphere.toJSON():void 0})),r.instanceInfo=this._instanceInfo.map(e=>({...e})),r.availableInstanceIds=this._availableInstanceIds.slice(),r.availableGeometryIds=this._availableGeometryIds.slice(),r.nextIndexStart=this._nextIndexStart,r.nextVertexStart=this._nextVertexStart,r.geometryCount=this._geometryCount,r.maxInstanceCount=this._maxInstanceCount,r.maxVertexCount=this._maxVertexCount,r.maxIndexCount=this._maxIndexCount,r.geometryInitialized=this._geometryInitialized,r.matricesTexture=this._matricesTexture.toJSON(e),r.indirectTexture=this._indirectTexture.toJSON(e),this._colorsTexture!==null&&(r.colorsTexture=this._colorsTexture.toJSON(e)),this.boundingSphere!==null&&(r.boundingSphere=this.boundingSphere.toJSON()),this.boundingBox!==null&&(r.boundingBox=this.boundingBox.toJSON()));function i(t,n){return t[n.uuid]===void 0&&(t[n.uuid]=n.toJSON(e)),n.uuid}if(this.isScene)this.background&&(this.background.isColor?r.background=this.background.toJSON():this.background.isTexture&&(r.background=this.background.toJSON(e).uuid)),this.environment&&this.environment.isTexture&&this.environment.isRenderTargetTexture!==!0&&(r.environment=this.environment.toJSON(e).uuid);else if(this.isMesh||this.isLine||this.isPoints){r.geometry=i(e.geometries,this.geometry);let t=this.geometry.parameters;if(t!==void 0&&t.shapes!==void 0){let n=t.shapes;if(Array.isArray(n))for(let t=0,r=n.length;t0){r.children=[];for(let t=0;t0){r.animations=[];for(let t=0;t0&&(n.geometries=t),r.length>0&&(n.materials=r),i.length>0&&(n.textures=i),o.length>0&&(n.images=o),s.length>0&&(n.shapes=s),c.length>0&&(n.skeletons=c),l.length>0&&(n.animations=l),u.length>0&&(n.nodes=u)}return n.object=r,n;function a(e){let t=[];for(let n in e){let r=e[n];delete r.metadata,t.push(r)}return t}}clone(e){return new this.constructor().copy(this,e)}copy(e,t=!0){if(this.name=e.name,this.up.copy(e.up),this.position.copy(e.position),this.rotation.order=e.rotation.order,this.quaternion.copy(e.quaternion),this.scale.copy(e.scale),e.pivot!==null&&(this.pivot=e.pivot.clone()),this.matrix.copy(e.matrix),this.matrixWorld.copy(e.matrixWorld),this.matrixAutoUpdate=e.matrixAutoUpdate,this.matrixWorldAutoUpdate=e.matrixWorldAutoUpdate,this.matrixWorldNeedsUpdate=e.matrixWorldNeedsUpdate,this.layers.mask=e.layers.mask,this.visible=e.visible,this.castShadow=e.castShadow,this.receiveShadow=e.receiveShadow,this.frustumCulled=e.frustumCulled,this.renderOrder=e.renderOrder,this.static=e.static,this.animations=e.animations.slice(),this.userData=JSON.parse(JSON.stringify(e.userData)),t===!0)for(let t=0;ts+l?(c.inputState.pinching=!1,this.dispatchEvent({type:`pinchend`,handedness:e.handedness,target:this})):!c.inputState.pinching&&o<=s-l&&(c.inputState.pinching=!0,this.dispatchEvent({type:`pinchstart`,handedness:e.handedness,target:this}))}else s!==null&&e.gripSpace&&(i=t.getPose(e.gripSpace,n),i!==null&&(s.matrix.fromArray(i.transform.matrix),s.matrix.decompose(s.position,s.rotation,s.scale),s.matrixWorldNeedsUpdate=!0,i.linearVelocity?(s.hasLinearVelocity=!0,s.linearVelocity.copy(i.linearVelocity)):s.hasLinearVelocity=!1,i.angularVelocity?(s.hasAngularVelocity=!0,s.angularVelocity.copy(i.angularVelocity)):s.hasAngularVelocity=!1));o!==null&&(r=t.getPose(e.targetRaySpace,n),r===null&&i!==null&&(r=i),r!==null&&(o.matrix.fromArray(r.transform.matrix),o.matrix.decompose(o.position,o.rotation,o.scale),o.matrixWorldNeedsUpdate=!0,r.linearVelocity?(o.hasLinearVelocity=!0,o.linearVelocity.copy(r.linearVelocity)):o.hasLinearVelocity=!1,r.angularVelocity?(o.hasAngularVelocity=!0,o.angularVelocity.copy(r.angularVelocity)):o.hasAngularVelocity=!1,this.dispatchEvent(li)))}return o!==null&&(o.visible=r!==null),s!==null&&(s.visible=i!==null),c!==null&&(c.visible=a!==null),this}_getHandJoint(e,t){if(e.joints[t.jointName]===void 0){let n=new ci;n.matrixAutoUpdate=!1,n.visible=!1,e.joints[t.jointName]=n,e.add(n)}return e.joints[t.jointName]}},di={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074},fi={h:0,s:0,l:0},pi={h:0,s:0,l:0};function mi(e,t,n){return n<0&&(n+=1),n>1&&--n,n<1/6?e+(t-e)*6*n:n<1/2?t:n<2/3?e+(t-e)*6*(2/3-n):e}var U=class{constructor(e,t,n){return this.isColor=!0,this.r=1,this.g=1,this.b=1,this.set(e,t,n)}set(e,t,n){if(t===void 0&&n===void 0){let t=e;t&&t.isColor?this.copy(t):typeof t==`number`?this.setHex(t):typeof t==`string`&&this.setStyle(t)}else this.setRGB(e,t,n);return this}setScalar(e){return this.r=e,this.g=e,this.b=e,this}setHex(e,t=Wt){return e=Math.floor(e),this.r=(e>>16&255)/255,this.g=(e>>8&255)/255,this.b=(e&255)/255,gr.colorSpaceToWorking(this,t),this}setRGB(e,t,n,r=gr.workingColorSpace){return this.r=e,this.g=t,this.b=n,gr.colorSpaceToWorking(this,r),this}setHSL(e,t,n,r=gr.workingColorSpace){if(e=Vn(e,1),t=Bn(t,0,1),n=Bn(n,0,1),t===0)this.r=this.g=this.b=n;else{let r=n<=.5?n*(1+t):n+t-n*t,i=2*n-r;this.r=mi(i,r,e+1/3),this.g=mi(i,r,e),this.b=mi(i,r,e-1/3)}return gr.colorSpaceToWorking(this,r),this}setStyle(e,t=Wt){function n(t){t!==void 0&&parseFloat(t)<1&&B(`Color: Alpha component of `+e+` will be ignored.`)}let r;if(r=/^(\w+)\(([^\)]*)\)/.exec(e)){let i,a=r[1],o=r[2];switch(a){case`rgb`:case`rgba`:if(i=/^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return n(i[4]),this.setRGB(Math.min(255,parseInt(i[1],10))/255,Math.min(255,parseInt(i[2],10))/255,Math.min(255,parseInt(i[3],10))/255,t);if(i=/^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return n(i[4]),this.setRGB(Math.min(100,parseInt(i[1],10))/100,Math.min(100,parseInt(i[2],10))/100,Math.min(100,parseInt(i[3],10))/100,t);break;case`hsl`:case`hsla`:if(i=/^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return n(i[4]),this.setHSL(parseFloat(i[1])/360,parseFloat(i[2])/100,parseFloat(i[3])/100,t);break;default:B(`Color: Unknown color model `+e)}}else if(r=/^\#([A-Fa-f\d]+)$/.exec(e)){let n=r[1],i=n.length;if(i===3)return this.setRGB(parseInt(n.charAt(0),16)/15,parseInt(n.charAt(1),16)/15,parseInt(n.charAt(2),16)/15,t);if(i===6)return this.setHex(parseInt(n,16),t);B(`Color: Invalid hex color `+e)}else if(e&&e.length>0)return this.setColorName(e,t);return this}setColorName(e,t=Wt){let n=di[e.toLowerCase()];return n===void 0?B(`Color: Unknown color `+e):this.setHex(n,t),this}clone(){return new this.constructor(this.r,this.g,this.b)}copy(e){return this.r=e.r,this.g=e.g,this.b=e.b,this}copySRGBToLinear(e){return this.r=_r(e.r),this.g=_r(e.g),this.b=_r(e.b),this}copyLinearToSRGB(e){return this.r=vr(e.r),this.g=vr(e.g),this.b=vr(e.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(e=Wt){return gr.workingToColorSpace(hi.copy(this),e),Math.round(Bn(hi.r*255,0,255))*65536+Math.round(Bn(hi.g*255,0,255))*256+Math.round(Bn(hi.b*255,0,255))}getHexString(e=Wt){return(`000000`+this.getHex(e).toString(16)).slice(-6)}getHSL(e,t=gr.workingColorSpace){gr.workingToColorSpace(hi.copy(this),t);let n=hi.r,r=hi.g,i=hi.b,a=Math.max(n,r,i),o=Math.min(n,r,i),s,c,l=(o+a)/2;if(o===a)s=0,c=0;else{let e=a-o;switch(c=l<=.5?e/(a+o):e/(2-a-o),a){case n:s=(r-i)/e+(r0&&(t.object.backgroundBlurriness=this.backgroundBlurriness),this.backgroundIntensity!==1&&(t.object.backgroundIntensity=this.backgroundIntensity),t.object.backgroundRotation=this.backgroundRotation.toArray(),this.environmentIntensity!==1&&(t.object.environmentIntensity=this.environmentIntensity),t.object.environmentRotation=this.environmentRotation.toArray(),t}},yi=new H,bi=new H,xi=new H,Si=new H,Ci=new H,wi=new H,Ti=new H,Ei=new H,Di=new H,Oi=new H,ki=new Dr,Ai=new Dr,ji=new Dr,Mi=class e{constructor(e=new H,t=new H,n=new H){this.a=e,this.b=t,this.c=n}static getNormal(e,t,n,r){r.subVectors(n,t),yi.subVectors(e,t),r.cross(yi);let i=r.lengthSq();return i>0?r.multiplyScalar(1/Math.sqrt(i)):r.set(0,0,0)}static getBarycoord(e,t,n,r,i){yi.subVectors(r,t),bi.subVectors(n,t),xi.subVectors(e,t);let a=yi.dot(yi),o=yi.dot(bi),s=yi.dot(xi),c=bi.dot(bi),l=bi.dot(xi),u=a*c-o*o;if(u===0)return i.set(0,0,0),null;let d=1/u,f=(c*s-o*l)*d,p=(a*l-o*s)*d;return i.set(1-f-p,p,f)}static containsPoint(e,t,n,r){return this.getBarycoord(e,t,n,r,Si)===null?!1:Si.x>=0&&Si.y>=0&&Si.x+Si.y<=1}static getInterpolation(e,t,n,r,i,a,o,s){return this.getBarycoord(e,t,n,r,Si)===null?(s.x=0,s.y=0,`z`in s&&(s.z=0),`w`in s&&(s.w=0),null):(s.setScalar(0),s.addScaledVector(i,Si.x),s.addScaledVector(a,Si.y),s.addScaledVector(o,Si.z),s)}static getInterpolatedAttribute(e,t,n,r,i,a){return ki.setScalar(0),Ai.setScalar(0),ji.setScalar(0),ki.fromBufferAttribute(e,t),Ai.fromBufferAttribute(e,n),ji.fromBufferAttribute(e,r),a.setScalar(0),a.addScaledVector(ki,i.x),a.addScaledVector(Ai,i.y),a.addScaledVector(ji,i.z),a}static isFrontFacing(e,t,n,r){return yi.subVectors(n,t),bi.subVectors(e,t),yi.cross(bi).dot(r)<0}set(e,t,n){return this.a.copy(e),this.b.copy(t),this.c.copy(n),this}setFromPointsAndIndices(e,t,n,r){return this.a.copy(e[t]),this.b.copy(e[n]),this.c.copy(e[r]),this}setFromAttributeAndIndices(e,t,n,r){return this.a.fromBufferAttribute(e,t),this.b.fromBufferAttribute(e,n),this.c.fromBufferAttribute(e,r),this}clone(){return new this.constructor().copy(this)}copy(e){return this.a.copy(e.a),this.b.copy(e.b),this.c.copy(e.c),this}getArea(){return yi.subVectors(this.c,this.b),bi.subVectors(this.a,this.b),yi.cross(bi).length()*.5}getMidpoint(e){return e.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)}getNormal(t){return e.getNormal(this.a,this.b,this.c,t)}getPlane(e){return e.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(t,n){return e.getBarycoord(t,this.a,this.b,this.c,n)}getInterpolation(t,n,r,i,a){return e.getInterpolation(t,this.a,this.b,this.c,n,r,i,a)}containsPoint(t){return e.containsPoint(t,this.a,this.b,this.c)}isFrontFacing(t){return e.isFrontFacing(this.a,this.b,this.c,t)}intersectsBox(e){return e.intersectsTriangle(this)}closestPointToPoint(e,t){let n=this.a,r=this.b,i=this.c,a,o;Ci.subVectors(r,n),wi.subVectors(i,n),Ei.subVectors(e,n);let s=Ci.dot(Ei),c=wi.dot(Ei);if(s<=0&&c<=0)return t.copy(n);Di.subVectors(e,r);let l=Ci.dot(Di),u=wi.dot(Di);if(l>=0&&u<=l)return t.copy(r);let d=s*u-l*c;if(d<=0&&s>=0&&l<=0)return a=s/(s-l),t.copy(n).addScaledVector(Ci,a);Oi.subVectors(e,i);let f=Ci.dot(Oi),p=wi.dot(Oi);if(p>=0&&f<=p)return t.copy(i);let m=f*c-s*p;if(m<=0&&c>=0&&p<=0)return o=c/(c-p),t.copy(n).addScaledVector(wi,o);let h=l*p-f*u;if(h<=0&&u-l>=0&&f-p>=0)return Ti.subVectors(i,r),o=(u-l)/(u-l+(f-p)),t.copy(r).addScaledVector(Ti,o);let g=1/(h+m+d);return a=m*g,o=d*g,t.copy(n).addScaledVector(Ci,a).addScaledVector(wi,o)}equals(e){return e.a.equals(this.a)&&e.b.equals(this.b)&&e.c.equals(this.c)}},Ni=class{constructor(e=new H(1/0,1/0,1/0),t=new H(-1/0,-1/0,-1/0)){this.isBox3=!0,this.min=e,this.max=t}set(e,t){return this.min.copy(e),this.max.copy(t),this}setFromArray(e){this.makeEmpty();for(let t=0,n=e.length;t=this.min.x&&e.x<=this.max.x&&e.y>=this.min.y&&e.y<=this.max.y&&e.z>=this.min.z&&e.z<=this.max.z}containsBox(e){return this.min.x<=e.min.x&&e.max.x<=this.max.x&&this.min.y<=e.min.y&&e.max.y<=this.max.y&&this.min.z<=e.min.z&&e.max.z<=this.max.z}getParameter(e,t){return t.set((e.x-this.min.x)/(this.max.x-this.min.x),(e.y-this.min.y)/(this.max.y-this.min.y),(e.z-this.min.z)/(this.max.z-this.min.z))}intersectsBox(e){return e.max.x>=this.min.x&&e.min.x<=this.max.x&&e.max.y>=this.min.y&&e.min.y<=this.max.y&&e.max.z>=this.min.z&&e.min.z<=this.max.z}intersectsSphere(e){return this.clampPoint(e.center,Fi),Fi.distanceToSquared(e.center)<=e.radius*e.radius}intersectsPlane(e){let t,n;return e.normal.x>0?(t=e.normal.x*this.min.x,n=e.normal.x*this.max.x):(t=e.normal.x*this.max.x,n=e.normal.x*this.min.x),e.normal.y>0?(t+=e.normal.y*this.min.y,n+=e.normal.y*this.max.y):(t+=e.normal.y*this.max.y,n+=e.normal.y*this.min.y),e.normal.z>0?(t+=e.normal.z*this.min.z,n+=e.normal.z*this.max.z):(t+=e.normal.z*this.max.z,n+=e.normal.z*this.min.z),t<=-e.constant&&n>=-e.constant}intersectsTriangle(e){if(this.isEmpty())return!1;this.getCenter(Ui),Wi.subVectors(this.max,Ui),Li.subVectors(e.a,Ui),Ri.subVectors(e.b,Ui),zi.subVectors(e.c,Ui),Bi.subVectors(Ri,Li),Vi.subVectors(zi,Ri),Hi.subVectors(Li,zi);let t=[0,-Bi.z,Bi.y,0,-Vi.z,Vi.y,0,-Hi.z,Hi.y,Bi.z,0,-Bi.x,Vi.z,0,-Vi.x,Hi.z,0,-Hi.x,-Bi.y,Bi.x,0,-Vi.y,Vi.x,0,-Hi.y,Hi.x,0];return!qi(t,Li,Ri,zi,Wi)||(t=[1,0,0,0,1,0,0,0,1],!qi(t,Li,Ri,zi,Wi))?!1:(Gi.crossVectors(Bi,Vi),t=[Gi.x,Gi.y,Gi.z],qi(t,Li,Ri,zi,Wi))}clampPoint(e,t){return t.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return this.clampPoint(e,Fi).distanceTo(e)}getBoundingSphere(e){return this.isEmpty()?e.makeEmpty():(this.getCenter(e.center),e.radius=this.getSize(Fi).length()*.5),e}intersect(e){return this.min.max(e.min),this.max.min(e.max),this.isEmpty()&&this.makeEmpty(),this}union(e){return this.min.min(e.min),this.max.max(e.max),this}applyMatrix4(e){return this.isEmpty()?this:(Pi[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(e),Pi[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(e),Pi[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(e),Pi[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(e),Pi[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(e),Pi[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(e),Pi[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(e),Pi[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(e),this.setFromPoints(Pi),this)}translate(e){return this.min.add(e),this.max.add(e),this}equals(e){return e.min.equals(this.min)&&e.max.equals(this.max)}toJSON(){return{min:this.min.toArray(),max:this.max.toArray()}}fromJSON(e){return this.min.fromArray(e.min),this.max.fromArray(e.max),this}},Pi=[new H,new H,new H,new H,new H,new H,new H,new H],Fi=new H,Ii=new Ni,Li=new H,Ri=new H,zi=new H,Bi=new H,Vi=new H,Hi=new H,Ui=new H,Wi=new H,Gi=new H,Ki=new H;function qi(e,t,n,r,i){for(let a=0,o=e.length-3;a<=o;a+=3){Ki.fromArray(e,a);let o=i.x*Math.abs(Ki.x)+i.y*Math.abs(Ki.y)+i.z*Math.abs(Ki.z),s=t.dot(Ki),c=n.dot(Ki),l=r.dot(Ki);if(Math.max(-Math.max(s,c,l),Math.min(s,c,l))>o)return!1}return!0}var Ji=Yi();function Yi(){let e=new ArrayBuffer(4),t=new Float32Array(e),n=new Uint32Array(e),r=new Uint32Array(512),i=new Uint32Array(512);for(let e=0;e<256;++e){let t=e-127;t<-27?(r[e]=0,r[e|256]=32768,i[e]=24,i[e|256]=24):t<-14?(r[e]=1024>>-t-14,r[e|256]=1024>>-t-14|32768,i[e]=-t-1,i[e|256]=-t-1):t<=15?(r[e]=t+15<<10,r[e|256]=t+15<<10|32768,i[e]=13,i[e|256]=13):t<128?(r[e]=31744,r[e|256]=64512,i[e]=24,i[e|256]=24):(r[e]=31744,r[e|256]=64512,i[e]=13,i[e|256]=13)}let a=new Uint32Array(2048),o=new Uint32Array(64),s=new Uint32Array(64);for(let e=1;e<1024;++e){let t=e<<13,n=0;for(;!(t&8388608);)t<<=1,n-=8388608;t&=-8388609,n+=947912704,a[e]=t|n}for(let e=1024;e<2048;++e)a[e]=939524096+(e-1024<<13);for(let e=1;e<31;++e)o[e]=e<<23;o[31]=1199570944,o[32]=2147483648;for(let e=33;e<63;++e)o[e]=2147483648+(e-32<<23);o[63]=3347054592;for(let e=1;e<64;++e)e!==32&&(s[e]=1024);return{floatView:t,uint32View:n,baseTable:r,shiftTable:i,mantissaTable:a,exponentTable:o,offsetTable:s}}function Xi(e){Math.abs(e)>65504&&B(`DataUtils.toHalfFloat(): Value out of range.`),e=Bn(e,-65504,65504),Ji.floatView[0]=e;let t=Ji.uint32View[0],n=t>>23&511;return Ji.baseTable[n]+((t&8388607)>>Ji.shiftTable[n])}function W(e){let t=e>>10;return Ji.uint32View[0]=Ji.mantissaTable[Ji.offsetTable[t]+(e&1023)]+Ji.exponentTable[t],Ji.floatView[0]}var Zi=class{static toHalfFloat(e){return Xi(e)}static fromHalfFloat(e){return W(e)}},G=new H,Qi=new V,$i=0,ea=class{constructor(e,t,n=!1){if(Array.isArray(e))throw TypeError(`THREE.BufferAttribute: array should be a Typed Array.`);this.isBufferAttribute=!0,Object.defineProperty(this,`id`,{value:$i++}),this.name=``,this.array=e,this.itemSize=t,this.count=e===void 0?0:e.length/t,this.normalized=n,this.usage=tn,this.updateRanges=[],this.gpuType=Oe,this.version=0}onUploadCallback(){}set needsUpdate(e){e===!0&&this.version++}setUsage(e){return this.usage=e,this}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}copy(e){return this.name=e.name,this.array=new e.array.constructor(e.array),this.itemSize=e.itemSize,this.count=e.count,this.normalized=e.normalized,this.usage=e.usage,this.gpuType=e.gpuType,this}copyAt(e,t,n){e*=this.itemSize,n*=t.itemSize;for(let r=0,i=this.itemSize;rthis.radius*this.radius&&(t.sub(this.center).normalize(),t.multiplyScalar(this.radius).add(this.center)),t}getBoundingBox(e){return this.isEmpty()?(e.makeEmpty(),e):(e.set(this.center,this.center),e.expandByScalar(this.radius),e)}applyMatrix4(e){return this.center.applyMatrix4(e),this.radius*=e.getMaxScaleOnAxis(),this}translate(e){return this.center.add(e),this}expandByPoint(e){if(this.isEmpty())return this.center.copy(e),this.radius=0,this;ua.subVectors(e,this.center);let t=ua.lengthSq();if(t>this.radius*this.radius){let e=Math.sqrt(t),n=(e-this.radius)*.5;this.center.addScaledVector(ua,n/e),this.radius+=n}return this}union(e){return e.isEmpty()?this:this.isEmpty()?(this.copy(e),this):(this.center.equals(e.center)===!0?this.radius=Math.max(this.radius,e.radius):(da.subVectors(e.center,this.center).setLength(e.radius),this.expandByPoint(ua.copy(e.center).add(da)),this.expandByPoint(ua.copy(e.center).sub(da))),this)}equals(e){return e.center.equals(this.center)&&e.radius===this.radius}clone(){return new this.constructor().copy(this)}toJSON(){return{radius:this.radius,center:this.center.toArray()}}fromJSON(e){return this.radius=e.radius,this.center.fromArray(e.center),this}},pa=0,ma=new Pr,ha=new si,ga=new H,_a=new Ni,va=new Ni,ya=new H,ba=class e extends Pn{constructor(){super(),this.isBufferGeometry=!0,Object.defineProperty(this,`id`,{value:pa++}),this.uuid=zn(),this.name=``,this.type=`BufferGeometry`,this.index=null,this.indirect=null,this.indirectOffset=0,this.attributes={},this.morphAttributes={},this.morphTargetsRelative=!1,this.groups=[],this.boundingBox=null,this.boundingSphere=null,this.drawRange={start:0,count:1/0},this.userData={}}getIndex(){return this.index}setIndex(e){return Array.isArray(e)?this.index=new(vn(e)?sa:aa)(e,1):this.index=e,this}setIndirect(e,t=0){return this.indirect=e,this.indirectOffset=t,this}getIndirect(){return this.indirect}getAttribute(e){return this.attributes[e]}setAttribute(e,t){return this.attributes[e]=t,this}deleteAttribute(e){return delete this.attributes[e],this}hasAttribute(e){return this.attributes[e]!==void 0}addGroup(e,t,n=0){this.groups.push({start:e,count:t,materialIndex:n})}clearGroups(){this.groups=[]}setDrawRange(e,t){this.drawRange.start=e,this.drawRange.count=t}applyMatrix4(e){let t=this.attributes.position;t!==void 0&&(t.applyMatrix4(e),t.needsUpdate=!0);let n=this.attributes.normal;if(n!==void 0){let t=new dr().getNormalMatrix(e);n.applyNormalMatrix(t),n.needsUpdate=!0}let r=this.attributes.tangent;return r!==void 0&&(r.transformDirection(e),r.needsUpdate=!0),this.boundingBox!==null&&this.computeBoundingBox(),this.boundingSphere!==null&&this.computeBoundingSphere(),this}applyQuaternion(e){return ma.makeRotationFromQuaternion(e),this.applyMatrix4(ma),this}rotateX(e){return ma.makeRotationX(e),this.applyMatrix4(ma),this}rotateY(e){return ma.makeRotationY(e),this.applyMatrix4(ma),this}rotateZ(e){return ma.makeRotationZ(e),this.applyMatrix4(ma),this}translate(e,t,n){return ma.makeTranslation(e,t,n),this.applyMatrix4(ma),this}scale(e,t,n){return ma.makeScale(e,t,n),this.applyMatrix4(ma),this}lookAt(e){return ha.lookAt(e),ha.updateMatrix(),this.applyMatrix4(ha.matrix),this}center(){return this.computeBoundingBox(),this.boundingBox.getCenter(ga).negate(),this.translate(ga.x,ga.y,ga.z),this}setFromPoints(e){let t=this.getAttribute(`position`);if(t===void 0){let t=[];for(let n=0,r=e.length;nt.count&&B(`BufferGeometry: Buffer size too small for points data. Use .dispose() and create a new geometry.`),t.needsUpdate=!0}return this}computeBoundingBox(){this.boundingBox===null&&(this.boundingBox=new Ni);let e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute){An(`BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.`,this),this.boundingBox.set(new H(-1/0,-1/0,-1/0),new H(1/0,1/0,1/0));return}if(e!==void 0){if(this.boundingBox.setFromBufferAttribute(e),t)for(let e=0,n=t.length;e0&&(e.userData=this.userData),this.parameters!==void 0){let t=this.parameters;for(let n in t)t[n]!==void 0&&(e[n]=t[n]);return e}e.data={attributes:{}};let t=this.index;t!==null&&(e.data.index={type:t.array.constructor.name,array:Array.prototype.slice.call(t.array)});let n=this.attributes;for(let t in n){let r=n[t];e.data.attributes[t]=r.toJSON(e.data)}let r={},i=!1;for(let t in this.morphAttributes){let n=this.morphAttributes[t],a=[];for(let t=0,r=n.length;t0&&(r[t]=a,i=!0)}i&&(e.data.morphAttributes=r,e.data.morphTargetsRelative=this.morphTargetsRelative);let a=this.groups;a.length>0&&(e.data.groups=JSON.parse(JSON.stringify(a)));let o=this.boundingSphere;return o!==null&&(e.data.boundingSphere=o.toJSON()),e}clone(){return new this.constructor().copy(this)}copy(e){this.index=null,this.attributes={},this.morphAttributes={},this.groups=[],this.boundingBox=null,this.boundingSphere=null;let t={};this.name=e.name;let n=e.index;n!==null&&this.setIndex(n.clone());let r=e.attributes;for(let e in r){let n=r[e];this.setAttribute(e,n.clone(t))}let i=e.morphAttributes;for(let e in i){let n=[],r=i[e];for(let e=0,i=r.length;e0!=e>0&&this.version++,this._alphaTest=e}onBeforeRender(){}onBeforeCompile(){}customProgramCacheKey(){return this.onBeforeCompile.toString()}setValues(e){if(e!==void 0)for(let t in e){let n=e[t];if(n===void 0){B(`Material: parameter '${t}' has value of undefined.`);continue}let r=this[t];if(r===void 0){B(`Material: '${t}' is not a property of THREE.${this.type}.`);continue}r&&r.isColor?r.set(n):r&&r.isVector3&&n&&n.isVector3?r.copy(n):this[t]=n}}toJSON(e){let t=e===void 0||typeof e==`string`;t&&(e={textures:{},images:{}});let n={metadata:{version:4.7,type:`Material`,generator:`Material.toJSON`}};n.uuid=this.uuid,n.type=this.type,this.name!==``&&(n.name=this.name),this.color&&this.color.isColor&&(n.color=this.color.getHex()),this.roughness!==void 0&&(n.roughness=this.roughness),this.metalness!==void 0&&(n.metalness=this.metalness),this.sheen!==void 0&&(n.sheen=this.sheen),this.sheenColor&&this.sheenColor.isColor&&(n.sheenColor=this.sheenColor.getHex()),this.sheenRoughness!==void 0&&(n.sheenRoughness=this.sheenRoughness),this.emissive&&this.emissive.isColor&&(n.emissive=this.emissive.getHex()),this.emissiveIntensity!==void 0&&this.emissiveIntensity!==1&&(n.emissiveIntensity=this.emissiveIntensity),this.specular&&this.specular.isColor&&(n.specular=this.specular.getHex()),this.specularIntensity!==void 0&&(n.specularIntensity=this.specularIntensity),this.specularColor&&this.specularColor.isColor&&(n.specularColor=this.specularColor.getHex()),this.shininess!==void 0&&(n.shininess=this.shininess),this.clearcoat!==void 0&&(n.clearcoat=this.clearcoat),this.clearcoatRoughness!==void 0&&(n.clearcoatRoughness=this.clearcoatRoughness),this.clearcoatMap&&this.clearcoatMap.isTexture&&(n.clearcoatMap=this.clearcoatMap.toJSON(e).uuid),this.clearcoatRoughnessMap&&this.clearcoatRoughnessMap.isTexture&&(n.clearcoatRoughnessMap=this.clearcoatRoughnessMap.toJSON(e).uuid),this.clearcoatNormalMap&&this.clearcoatNormalMap.isTexture&&(n.clearcoatNormalMap=this.clearcoatNormalMap.toJSON(e).uuid,n.clearcoatNormalScale=this.clearcoatNormalScale.toArray()),this.sheenColorMap&&this.sheenColorMap.isTexture&&(n.sheenColorMap=this.sheenColorMap.toJSON(e).uuid),this.sheenRoughnessMap&&this.sheenRoughnessMap.isTexture&&(n.sheenRoughnessMap=this.sheenRoughnessMap.toJSON(e).uuid),this.dispersion!==void 0&&(n.dispersion=this.dispersion),this.iridescence!==void 0&&(n.iridescence=this.iridescence),this.iridescenceIOR!==void 0&&(n.iridescenceIOR=this.iridescenceIOR),this.iridescenceThicknessRange!==void 0&&(n.iridescenceThicknessRange=this.iridescenceThicknessRange),this.iridescenceMap&&this.iridescenceMap.isTexture&&(n.iridescenceMap=this.iridescenceMap.toJSON(e).uuid),this.iridescenceThicknessMap&&this.iridescenceThicknessMap.isTexture&&(n.iridescenceThicknessMap=this.iridescenceThicknessMap.toJSON(e).uuid),this.anisotropy!==void 0&&(n.anisotropy=this.anisotropy),this.anisotropyRotation!==void 0&&(n.anisotropyRotation=this.anisotropyRotation),this.anisotropyMap&&this.anisotropyMap.isTexture&&(n.anisotropyMap=this.anisotropyMap.toJSON(e).uuid),this.map&&this.map.isTexture&&(n.map=this.map.toJSON(e).uuid),this.matcap&&this.matcap.isTexture&&(n.matcap=this.matcap.toJSON(e).uuid),this.alphaMap&&this.alphaMap.isTexture&&(n.alphaMap=this.alphaMap.toJSON(e).uuid),this.lightMap&&this.lightMap.isTexture&&(n.lightMap=this.lightMap.toJSON(e).uuid,n.lightMapIntensity=this.lightMapIntensity),this.aoMap&&this.aoMap.isTexture&&(n.aoMap=this.aoMap.toJSON(e).uuid,n.aoMapIntensity=this.aoMapIntensity),this.bumpMap&&this.bumpMap.isTexture&&(n.bumpMap=this.bumpMap.toJSON(e).uuid,n.bumpScale=this.bumpScale),this.normalMap&&this.normalMap.isTexture&&(n.normalMap=this.normalMap.toJSON(e).uuid,n.normalMapType=this.normalMapType,n.normalScale=this.normalScale.toArray()),this.displacementMap&&this.displacementMap.isTexture&&(n.displacementMap=this.displacementMap.toJSON(e).uuid,n.displacementScale=this.displacementScale,n.displacementBias=this.displacementBias),this.roughnessMap&&this.roughnessMap.isTexture&&(n.roughnessMap=this.roughnessMap.toJSON(e).uuid),this.metalnessMap&&this.metalnessMap.isTexture&&(n.metalnessMap=this.metalnessMap.toJSON(e).uuid),this.emissiveMap&&this.emissiveMap.isTexture&&(n.emissiveMap=this.emissiveMap.toJSON(e).uuid),this.specularMap&&this.specularMap.isTexture&&(n.specularMap=this.specularMap.toJSON(e).uuid),this.specularIntensityMap&&this.specularIntensityMap.isTexture&&(n.specularIntensityMap=this.specularIntensityMap.toJSON(e).uuid),this.specularColorMap&&this.specularColorMap.isTexture&&(n.specularColorMap=this.specularColorMap.toJSON(e).uuid),this.envMap&&this.envMap.isTexture&&(n.envMap=this.envMap.toJSON(e).uuid,this.combine!==void 0&&(n.combine=this.combine)),this.envMapRotation!==void 0&&(n.envMapRotation=this.envMapRotation.toArray()),this.envMapIntensity!==void 0&&(n.envMapIntensity=this.envMapIntensity),this.reflectivity!==void 0&&(n.reflectivity=this.reflectivity),this.refractionRatio!==void 0&&(n.refractionRatio=this.refractionRatio),this.gradientMap&&this.gradientMap.isTexture&&(n.gradientMap=this.gradientMap.toJSON(e).uuid),this.transmission!==void 0&&(n.transmission=this.transmission),this.transmissionMap&&this.transmissionMap.isTexture&&(n.transmissionMap=this.transmissionMap.toJSON(e).uuid),this.thickness!==void 0&&(n.thickness=this.thickness),this.thicknessMap&&this.thicknessMap.isTexture&&(n.thicknessMap=this.thicknessMap.toJSON(e).uuid),this.attenuationDistance!==void 0&&this.attenuationDistance!==1/0&&(n.attenuationDistance=this.attenuationDistance),this.attenuationColor!==void 0&&(n.attenuationColor=this.attenuationColor.getHex()),this.size!==void 0&&(n.size=this.size),this.shadowSide!==null&&(n.shadowSide=this.shadowSide),this.sizeAttenuation!==void 0&&(n.sizeAttenuation=this.sizeAttenuation),this.blending!==1&&(n.blending=this.blending),this.side!==0&&(n.side=this.side),this.vertexColors===!0&&(n.vertexColors=!0),this.opacity<1&&(n.opacity=this.opacity),this.transparent===!0&&(n.transparent=!0),this.blendSrc!==204&&(n.blendSrc=this.blendSrc),this.blendDst!==205&&(n.blendDst=this.blendDst),this.blendEquation!==100&&(n.blendEquation=this.blendEquation),this.blendSrcAlpha!==null&&(n.blendSrcAlpha=this.blendSrcAlpha),this.blendDstAlpha!==null&&(n.blendDstAlpha=this.blendDstAlpha),this.blendEquationAlpha!==null&&(n.blendEquationAlpha=this.blendEquationAlpha),this.blendColor&&this.blendColor.isColor&&(n.blendColor=this.blendColor.getHex()),this.blendAlpha!==0&&(n.blendAlpha=this.blendAlpha),this.depthFunc!==3&&(n.depthFunc=this.depthFunc),this.depthTest===!1&&(n.depthTest=this.depthTest),this.depthWrite===!1&&(n.depthWrite=this.depthWrite),this.colorWrite===!1&&(n.colorWrite=this.colorWrite),this.stencilWriteMask!==255&&(n.stencilWriteMask=this.stencilWriteMask),this.stencilFunc!==519&&(n.stencilFunc=this.stencilFunc),this.stencilRef!==0&&(n.stencilRef=this.stencilRef),this.stencilFuncMask!==255&&(n.stencilFuncMask=this.stencilFuncMask),this.stencilFail!==7680&&(n.stencilFail=this.stencilFail),this.stencilZFail!==7680&&(n.stencilZFail=this.stencilZFail),this.stencilZPass!==7680&&(n.stencilZPass=this.stencilZPass),this.stencilWrite===!0&&(n.stencilWrite=this.stencilWrite),this.rotation!==void 0&&this.rotation!==0&&(n.rotation=this.rotation),this.polygonOffset===!0&&(n.polygonOffset=!0),this.polygonOffsetFactor!==0&&(n.polygonOffsetFactor=this.polygonOffsetFactor),this.polygonOffsetUnits!==0&&(n.polygonOffsetUnits=this.polygonOffsetUnits),this.linewidth!==void 0&&this.linewidth!==1&&(n.linewidth=this.linewidth),this.dashSize!==void 0&&(n.dashSize=this.dashSize),this.gapSize!==void 0&&(n.gapSize=this.gapSize),this.scale!==void 0&&(n.scale=this.scale),this.dithering===!0&&(n.dithering=!0),this.alphaTest>0&&(n.alphaTest=this.alphaTest),this.alphaHash===!0&&(n.alphaHash=!0),this.alphaToCoverage===!0&&(n.alphaToCoverage=!0),this.premultipliedAlpha===!0&&(n.premultipliedAlpha=!0),this.forceSinglePass===!0&&(n.forceSinglePass=!0),this.allowOverride===!1&&(n.allowOverride=!1),this.wireframe===!0&&(n.wireframe=!0),this.wireframeLinewidth>1&&(n.wireframeLinewidth=this.wireframeLinewidth),this.wireframeLinecap!==`round`&&(n.wireframeLinecap=this.wireframeLinecap),this.wireframeLinejoin!==`round`&&(n.wireframeLinejoin=this.wireframeLinejoin),this.flatShading===!0&&(n.flatShading=!0),this.visible===!1&&(n.visible=!1),this.toneMapped===!1&&(n.toneMapped=!1),this.fog===!1&&(n.fog=!1),Object.keys(this.userData).length>0&&(n.userData=this.userData);function r(e){let t=[];for(let n in e){let r=e[n];delete r.metadata,t.push(r)}return t}if(t){let t=r(e.textures),i=r(e.images);t.length>0&&(n.textures=t),i.length>0&&(n.images=i)}return n}clone(){return new this.constructor().copy(this)}copy(e){this.name=e.name,this.blending=e.blending,this.side=e.side,this.vertexColors=e.vertexColors,this.opacity=e.opacity,this.transparent=e.transparent,this.blendSrc=e.blendSrc,this.blendDst=e.blendDst,this.blendEquation=e.blendEquation,this.blendSrcAlpha=e.blendSrcAlpha,this.blendDstAlpha=e.blendDstAlpha,this.blendEquationAlpha=e.blendEquationAlpha,this.blendColor.copy(e.blendColor),this.blendAlpha=e.blendAlpha,this.depthFunc=e.depthFunc,this.depthTest=e.depthTest,this.depthWrite=e.depthWrite,this.stencilWriteMask=e.stencilWriteMask,this.stencilFunc=e.stencilFunc,this.stencilRef=e.stencilRef,this.stencilFuncMask=e.stencilFuncMask,this.stencilFail=e.stencilFail,this.stencilZFail=e.stencilZFail,this.stencilZPass=e.stencilZPass,this.stencilWrite=e.stencilWrite;let t=e.clippingPlanes,n=null;if(t!==null){let e=t.length;n=Array(e);for(let r=0;r!==e;++r)n[r]=t[r].clone()}return this.clippingPlanes=n,this.clipIntersection=e.clipIntersection,this.clipShadows=e.clipShadows,this.shadowSide=e.shadowSide,this.colorWrite=e.colorWrite,this.precision=e.precision,this.polygonOffset=e.polygonOffset,this.polygonOffsetFactor=e.polygonOffsetFactor,this.polygonOffsetUnits=e.polygonOffsetUnits,this.dithering=e.dithering,this.alphaTest=e.alphaTest,this.alphaHash=e.alphaHash,this.alphaToCoverage=e.alphaToCoverage,this.premultipliedAlpha=e.premultipliedAlpha,this.forceSinglePass=e.forceSinglePass,this.allowOverride=e.allowOverride,this.visible=e.visible,this.toneMapped=e.toneMapped,this.userData=JSON.parse(JSON.stringify(e.userData)),this}dispose(){this.dispatchEvent({type:`dispose`})}set needsUpdate(e){e===!0&&this.version++}},Ea=class extends Ta{constructor(e){super(),this.isSpriteMaterial=!0,this.type=`SpriteMaterial`,this.color=new U(16777215),this.map=null,this.alphaMap=null,this.rotation=0,this.sizeAttenuation=!0,this.transparent=!0,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.alphaMap=e.alphaMap,this.rotation=e.rotation,this.sizeAttenuation=e.sizeAttenuation,this.fog=e.fog,this}},Da,Oa=new H,ka=new H,Aa=new H,ja=new V,Ma=new V,Na=new Pr,Pa=new H,Fa=new H,Ia=new H,La=new V,Ra=new V,za=new V,Ba=class extends si{constructor(e=new Ea){if(super(),this.isSprite=!0,this.type=`Sprite`,Da===void 0){Da=new ba;let e=new xa(new Float32Array([-.5,-.5,0,0,0,.5,-.5,0,1,0,.5,.5,0,1,1,-.5,.5,0,0,1]),5);Da.setIndex([0,1,2,0,2,3]),Da.setAttribute(`position`,new Ca(e,3,0,!1)),Da.setAttribute(`uv`,new Ca(e,2,3,!1))}this.geometry=Da,this.material=e,this.center=new V(.5,.5),this.count=1}raycast(e,t){e.camera===null&&An(`Sprite: "Raycaster.camera" needs to be set in order to raycast against sprites.`),ka.setFromMatrixScale(this.matrixWorld),Na.copy(e.camera.matrixWorld),this.modelViewMatrix.multiplyMatrices(e.camera.matrixWorldInverse,this.matrixWorld),Aa.setFromMatrixPosition(this.modelViewMatrix),e.camera.isPerspectiveCamera&&this.material.sizeAttenuation===!1&&ka.multiplyScalar(-Aa.z);let n=this.material.rotation,r,i;n!==0&&(i=Math.cos(n),r=Math.sin(n));let a=this.center;Va(Pa.set(-.5,-.5,0),Aa,a,ka,r,i),Va(Fa.set(.5,-.5,0),Aa,a,ka,r,i),Va(Ia.set(.5,.5,0),Aa,a,ka,r,i),La.set(0,0),Ra.set(1,0),za.set(1,1);let o=e.ray.intersectTriangle(Pa,Fa,Ia,!1,Oa);if(o===null&&(Va(Fa.set(-.5,.5,0),Aa,a,ka,r,i),Ra.set(0,1),o=e.ray.intersectTriangle(Pa,Ia,Fa,!1,Oa),o===null))return;let s=e.ray.origin.distanceTo(Oa);se.far||t.push({distance:s,point:Oa.clone(),uv:Mi.getInterpolation(Oa,Pa,Fa,Ia,La,Ra,za,new V),face:null,object:this})}copy(e,t){return super.copy(e,t),e.center!==void 0&&this.center.copy(e.center),this.material=e.material,this}};function Va(e,t,n,r,i,a){ja.subVectors(e,n).addScalar(.5).multiply(r),i===void 0?Ma.copy(ja):(Ma.x=a*ja.x-i*ja.y,Ma.y=i*ja.x+a*ja.y),e.copy(t),e.x+=Ma.x,e.y+=Ma.y,e.applyMatrix4(Na)}var Ha=new H,Ua=new H,Wa=class extends si{constructor(){super(),this.isLOD=!0,this._currentLevel=0,this.type=`LOD`,Object.defineProperties(this,{levels:{enumerable:!0,value:[]}}),this.autoUpdate=!0}copy(e){super.copy(e,!1);let t=e.levels;for(let e=0,n=t.length;e0){let n,r;for(n=1,r=t.length;n0){Ha.setFromMatrixPosition(this.matrixWorld);let n=e.ray.origin.distanceTo(Ha);this.getObjectForDistance(n).raycast(e,t)}}update(e){let t=this.levels;if(t.length>1){Ha.setFromMatrixPosition(e.matrixWorld),Ua.setFromMatrixPosition(this.matrixWorld);let n=Ha.distanceTo(Ua)/e.zoom;t[0].object.visible=!0;let r,i;for(r=1,i=t.length;r=e)t[r-1].object.visible=!1,t[r].object.visible=!0;else break}for(this._currentLevel=r-1;r0)if(u=a*s-o,d=a*o-s,p=i*l,u>=0)if(d>=-p)if(d<=p){let e=1/l;u*=e,d*=e,f=u*(u+a*d+2*o)+d*(a*u+d+2*s)+c}else d=i,u=Math.max(0,-(a*d+o)),f=-u*u+d*(d+2*s)+c;else d=-i,u=Math.max(0,-(a*d+o)),f=-u*u+d*(d+2*s)+c;else d<=-p?(u=Math.max(0,-(-a*i+o)),d=u>0?-i:Math.min(Math.max(-i,-s),i),f=-u*u+d*(d+2*s)+c):d<=p?(u=0,d=Math.min(Math.max(-i,-s),i),f=d*(d+2*s)+c):(u=Math.max(0,-(a*i+o)),d=u>0?i:Math.min(Math.max(-i,-s),i),f=-u*u+d*(d+2*s)+c);else d=a>0?-i:i,u=Math.max(0,-(a*d+o)),f=-u*u+d*(d+2*s)+c;return n&&n.copy(this.origin).addScaledVector(this.direction,u),r&&r.copy(Ka).addScaledVector(qa,d),f}intersectSphere(e,t){Ga.subVectors(e.center,this.origin);let n=Ga.dot(this.direction),r=Ga.dot(Ga)-n*n,i=e.radius*e.radius;if(r>i)return null;let a=Math.sqrt(i-r),o=n-a,s=n+a;return s<0?null:o<0?this.at(s,t):this.at(o,t)}intersectsSphere(e){return e.radius<0?!1:this.distanceSqToPoint(e.center)<=e.radius*e.radius}distanceToPlane(e){let t=e.normal.dot(this.direction);if(t===0)return e.distanceToPoint(this.origin)===0?0:null;let n=-(this.origin.dot(e.normal)+e.constant)/t;return n>=0?n:null}intersectPlane(e,t){let n=this.distanceToPlane(e);return n===null?null:this.at(n,t)}intersectsPlane(e){let t=e.distanceToPoint(this.origin);return t===0||e.normal.dot(this.direction)*t<0}intersectBox(e,t){let n,r,i,a,o,s,c=1/this.direction.x,l=1/this.direction.y,u=1/this.direction.z,d=this.origin;return c>=0?(n=(e.min.x-d.x)*c,r=(e.max.x-d.x)*c):(n=(e.max.x-d.x)*c,r=(e.min.x-d.x)*c),l>=0?(i=(e.min.y-d.y)*l,a=(e.max.y-d.y)*l):(i=(e.max.y-d.y)*l,a=(e.min.y-d.y)*l),n>a||i>r||((i>n||isNaN(n))&&(n=i),(a=0?(o=(e.min.z-d.z)*u,s=(e.max.z-d.z)*u):(o=(e.max.z-d.z)*u,s=(e.min.z-d.z)*u),n>s||o>r)||((o>n||n!==n)&&(n=o),(s=0?n:r,t)}intersectsBox(e){return this.intersectBox(e,Ga)!==null}intersectTriangle(e,t,n,r,i){Ya.subVectors(t,e),Xa.subVectors(n,e),Za.crossVectors(Ya,Xa);let a=this.direction.dot(Za),o;if(a>0){if(r)return null;o=1}else if(a<0)o=-1,a=-a;else return null;Ja.subVectors(this.origin,e);let s=o*this.direction.dot(Xa.crossVectors(Ja,Xa));if(s<0)return null;let c=o*this.direction.dot(Ya.cross(Ja));if(c<0||s+c>a)return null;let l=-o*Ja.dot(Za);return l<0?null:this.at(l/a,i)}applyMatrix4(e){return this.origin.applyMatrix4(e),this.direction.transformDirection(e),this}equals(e){return e.origin.equals(this.origin)&&e.direction.equals(this.direction)}clone(){return new this.constructor().copy(this)}},$a=class extends Ta{constructor(e){super(),this.isMeshBasicMaterial=!0,this.type=`MeshBasicMaterial`,this.color=new U(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new Wr,this.combine=0,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap=`round`,this.wireframeLinejoin=`round`,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.combine=e.combine,this.reflectivity=e.reflectivity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.fog=e.fog,this}},eo=new Pr,to=new Qa,no=new fa,ro=new H,io=new H,ao=new H,oo=new H,so=new H,co=new H,lo=new H,uo=new H,fo=class extends si{constructor(e=new ba,t=new $a){super(),this.isMesh=!0,this.type=`Mesh`,this.geometry=e,this.material=t,this.morphTargetDictionary=void 0,this.morphTargetInfluences=void 0,this.count=1,this.updateMorphTargets()}copy(e,t){return super.copy(e,t),e.morphTargetInfluences!==void 0&&(this.morphTargetInfluences=e.morphTargetInfluences.slice()),e.morphTargetDictionary!==void 0&&(this.morphTargetDictionary=Object.assign({},e.morphTargetDictionary)),this.material=Array.isArray(e.material)?e.material.slice():e.material,this.geometry=e.geometry,this}updateMorphTargets(){let e=this.geometry.morphAttributes,t=Object.keys(e);if(t.length>0){let n=e[t[0]];if(n!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let e=0,t=n.length;e(e.far-e.near)**2))&&(eo.copy(i).invert(),to.copy(e.ray).applyMatrix4(eo),!(n.boundingBox!==null&&to.intersectsBox(n.boundingBox)===!1)&&this._computeIntersections(e,t,to)))}_computeIntersections(e,t,n){let r,i=this.geometry,a=this.material,o=i.index,s=i.attributes.position,c=i.attributes.uv,l=i.attributes.uv1,u=i.attributes.normal,d=i.groups,f=i.drawRange;if(o!==null)if(Array.isArray(a))for(let i=0,s=d.length;in.far?null:{distance:l,point:uo.clone(),object:e}}function mo(e,t,n,r,i,a,o,s,c,l){e.getVertexPosition(s,io),e.getVertexPosition(c,ao),e.getVertexPosition(l,oo);let u=po(e,t,n,r,io,ao,oo,lo);if(u){let e=new H;Mi.getBarycoord(lo,io,ao,oo,e),i&&(u.uv=Mi.getInterpolatedAttribute(i,s,c,l,e,new V)),a&&(u.uv1=Mi.getInterpolatedAttribute(a,s,c,l,e,new V)),o&&(u.normal=Mi.getInterpolatedAttribute(o,s,c,l,e,new H),u.normal.dot(r.direction)>0&&u.normal.multiplyScalar(-1));let t={a:s,b:c,c:l,normal:new H,materialIndex:0};Mi.getNormal(io,ao,oo,t.normal),u.face=t,u.barycoord=e}return u}var ho=new H,go=new Dr,_o=new Dr,vo=new H,yo=new Pr,bo=new H,xo=new fa,So=new Pr,Co=new Qa,wo=class extends fo{constructor(e,t){super(e,t),this.isSkinnedMesh=!0,this.type=`SkinnedMesh`,this.bindMode=de,this.bindMatrix=new Pr,this.bindMatrixInverse=new Pr,this.boundingBox=null,this.boundingSphere=null}computeBoundingBox(){let e=this.geometry;this.boundingBox===null&&(this.boundingBox=new Ni),this.boundingBox.makeEmpty();let t=e.getAttribute(`position`);for(let e=0;e1?null:t.copy(e.start).addScaledVector(n,i)}intersectsLine(e){let t=this.distanceToPoint(e.start),n=this.distanceToPoint(e.end);return t<0&&n>0||n<0&&t>0}intersectsBox(e){return e.intersectsPlane(this)}intersectsSphere(e){return e.intersectsPlane(this)}coplanarPoint(e){return e.copy(this.normal).multiplyScalar(-this.constant)}applyMatrix4(e,t){let n=t||Vo.getNormalMatrix(e),r=this.coplanarPoint(zo).applyMatrix4(e),i=this.normal.applyMatrix3(n).normalize();return this.constant=-r.dot(i),this}translate(e){return this.constant-=e.dot(this.normal),this}equals(e){return e.normal.equals(this.normal)&&e.constant===this.constant}clone(){return new this.constructor().copy(this)}},Uo=new fa,Wo=new V(.5,.5),Go=new H,Ko=class{constructor(e=new Ho,t=new Ho,n=new Ho,r=new Ho,i=new Ho,a=new Ho){this.planes=[e,t,n,r,i,a]}set(e,t,n,r,i,a){let o=this.planes;return o[0].copy(e),o[1].copy(t),o[2].copy(n),o[3].copy(r),o[4].copy(i),o[5].copy(a),this}copy(e){let t=this.planes;for(let n=0;n<6;n++)t[n].copy(e.planes[n]);return this}setFromProjectionMatrix(e,t=fn,n=!1){let r=this.planes,i=e.elements,a=i[0],o=i[1],s=i[2],c=i[3],l=i[4],u=i[5],d=i[6],f=i[7],p=i[8],m=i[9],h=i[10],g=i[11],_=i[12],v=i[13],y=i[14],b=i[15];if(r[0].setComponents(c-a,f-l,g-p,b-_).normalize(),r[1].setComponents(c+a,f+l,g+p,b+_).normalize(),r[2].setComponents(c+o,f+u,g+m,b+v).normalize(),r[3].setComponents(c-o,f-u,g-m,b-v).normalize(),n)r[4].setComponents(s,d,h,y).normalize(),r[5].setComponents(c-s,f-d,g-h,b-y).normalize();else if(r[4].setComponents(c-s,f-d,g-h,b-y).normalize(),t===2e3)r[5].setComponents(c+s,f+d,g+h,b+y).normalize();else if(t===2001)r[5].setComponents(s,d,h,y).normalize();else throw Error(`THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: `+t);return this}intersectsObject(e){if(e.boundingSphere!==void 0)e.boundingSphere===null&&e.computeBoundingSphere(),Uo.copy(e.boundingSphere).applyMatrix4(e.matrixWorld);else{let t=e.geometry;t.boundingSphere===null&&t.computeBoundingSphere(),Uo.copy(t.boundingSphere).applyMatrix4(e.matrixWorld)}return this.intersectsSphere(Uo)}intersectsSprite(e){return Uo.center.set(0,0,0),Uo.radius=.7071067811865476+Wo.distanceTo(e.center),Uo.applyMatrix4(e.matrixWorld),this.intersectsSphere(Uo)}intersectsSphere(e){let t=this.planes,n=e.center,r=-e.radius;for(let e=0;e<6;e++)if(t[e].distanceToPoint(n)0?e.max.x:e.min.x,Go.y=r.normal.y>0?e.max.y:e.min.y,Go.z=r.normal.z>0?e.max.z:e.min.z,r.distanceToPoint(Go)<0)return!1}return!0}containsPoint(e){let t=this.planes;for(let n=0;n<6;n++)if(t[n].distanceToPoint(e)<0)return!1;return!0}clone(){return new this.constructor().copy(this)}},qo=new Pr,Jo=new Ko,Yo=class e{constructor(){this.coordinateSystem=fn}intersectsObject(e,t){if(!t.isArrayCamera||t.cameras.length===0)return!1;for(let n=0;n=i.length&&i.push({start:-1,count:-1,z:-1,index:-1});let o=i[this.index];a.push(o),this.index++,o.start=e,o.count=t,o.z=n,o.index=r}reset(){this.list.length=0,this.index=0}},es=new Pr,ts=new U(1,1,1),ns=new Ko,rs=new Yo,is=new Ni,as=new fa,os=new H,ss=new H,cs=new H,ls=new $o,us=new fo,ds=[];function fs(e,t,n=0){let r=t.itemSize;if(e.isInterleavedBufferAttribute||e.array.constructor!==t.array.constructor){let i=e.count;for(let a=0;a65535?new Uint32Array(r):new Uint16Array(r);t.setIndex(new ea(e,1))}this._geometryInitialized=!0}}_validateGeometry(e){let t=this.geometry;if(!!e.getIndex()!=!!t.getIndex())throw Error(`THREE.BatchedMesh: All geometries must consistently have "index".`);for(let n in t.attributes){if(!e.hasAttribute(n))throw Error(`THREE.BatchedMesh: Added geometry missing "${n}". All geometries must have consistent attributes.`);let r=e.getAttribute(n),i=t.getAttribute(n);if(r.itemSize!==i.itemSize||r.normalized!==i.normalized)throw Error(`THREE.BatchedMesh: All attributes must have a consistent itemSize and normalized value.`)}}validateInstanceId(e){let t=this._instanceInfo;if(e<0||e>=t.length||t[e].active===!1)throw Error(`THREE.BatchedMesh: Invalid instanceId ${e}. Instance is either out of range or has been deleted.`)}validateGeometryId(e){let t=this._geometryInfo;if(e<0||e>=t.length||t[e].active===!1)throw Error(`THREE.BatchedMesh: Invalid geometryId ${e}. Geometry is either out of range or has been deleted.`)}setCustomSort(e){return this.customSort=e,this}computeBoundingBox(){this.boundingBox===null&&(this.boundingBox=new Ni);let e=this.boundingBox,t=this._instanceInfo;e.makeEmpty();for(let n=0,r=t.length;n=this.maxInstanceCount&&this._availableInstanceIds.length===0)throw Error(`THREE.BatchedMesh: Maximum item count reached.`);let t={visible:!0,active:!0,geometryIndex:e},n=null;this._availableInstanceIds.length>0?(this._availableInstanceIds.sort(Xo),n=this._availableInstanceIds.shift(),this._instanceInfo[n]=t):(n=this._instanceInfo.length,this._instanceInfo.push(t));let r=this._matricesTexture;es.identity().toArray(r.image.data,n*16),r.needsUpdate=!0;let i=this._colorsTexture;return i&&(ts.toArray(i.image.data,n*4),i.needsUpdate=!0),this._visibilityChanged=!0,n}addGeometry(e,t=-1,n=-1){this._initializeGeometry(e),this._validateGeometry(e);let r={vertexStart:-1,vertexCount:-1,reservedVertexCount:-1,indexStart:-1,indexCount:-1,reservedIndexCount:-1,start:-1,count:-1,boundingBox:null,boundingSphere:null,active:!0},i=this._geometryInfo;r.vertexStart=this._nextVertexStart,r.reservedVertexCount=t===-1?e.getAttribute(`position`).count:t;let a=e.getIndex();if(a!==null&&(r.indexStart=this._nextIndexStart,r.reservedIndexCount=n===-1?a.count:n),r.indexStart!==-1&&r.indexStart+r.reservedIndexCount>this._maxIndexCount||r.vertexStart+r.reservedVertexCount>this._maxVertexCount)throw Error(`THREE.BatchedMesh: Reserved space request exceeds the maximum buffer size.`);let o;return this._availableGeometryIds.length>0?(this._availableGeometryIds.sort(Xo),o=this._availableGeometryIds.shift(),i[o]=r):(o=this._geometryCount,this._geometryCount++,i.push(r)),this.setGeometryAt(o,e),this._nextIndexStart=r.indexStart+r.reservedIndexCount,this._nextVertexStart=r.vertexStart+r.reservedVertexCount,o}setGeometryAt(e,t){if(e>=this._geometryCount)throw Error(`THREE.BatchedMesh: Maximum geometry count reached.`);this._validateGeometry(t);let n=this.geometry,r=n.getIndex()!==null,i=n.getIndex(),a=t.getIndex(),o=this._geometryInfo[e];if(r&&a.count>o.reservedIndexCount||t.attributes.position.count>o.reservedVertexCount)throw Error(`THREE.BatchedMesh: Reserved space not large enough for provided geometry.`);let s=o.vertexStart,c=o.reservedVertexCount;o.vertexCount=t.getAttribute(`position`).count;for(let e in n.attributes){let r=t.getAttribute(e),i=n.getAttribute(e);fs(r,i,s);let a=r.itemSize;for(let e=r.count,t=c;e=t.length||t[e].active===!1)return this;let n=this._instanceInfo;for(let t=0,r=n.length;tt).sort((e,t)=>n[e].vertexStart-n[t].vertexStart),i=this.geometry;for(let a=0,o=n.length;a=this._geometryCount)return null;let n=this.geometry,r=this._geometryInfo[e];if(r.boundingBox===null){let e=new Ni,t=n.index,i=n.attributes.position;for(let n=r.start,a=r.start+r.count;n=this._geometryCount)return null;let n=this.geometry,r=this._geometryInfo[e];if(r.boundingSphere===null){let t=new fa;this.getBoundingBoxAt(e,is),is.getCenter(t.center);let i=n.index,a=n.attributes.position,o=0;for(let e=r.start,n=r.start+r.count;ee.active);if(Math.max(...n.map(e=>e.vertexStart+e.reservedVertexCount))>e)throw Error(`BatchedMesh: Geometry vertex values are being used outside the range ${t}. Cannot shrink further.`);if(this.geometry.index&&Math.max(...n.map(e=>e.indexStart+e.reservedIndexCount))>t)throw Error(`BatchedMesh: Geometry index values are being used outside the range ${t}. Cannot shrink further.`);let r=this.geometry;r.dispose(),this._maxVertexCount=e,this._maxIndexCount=t,this._geometryInitialized&&(this._geometryInitialized=!1,this.geometry=new ba,this._initializeGeometry(r));let i=this.geometry;r.index&&ps(r.index.array,i.index.array);for(let e in r.attributes)ps(r.attributes[e].array,i.attributes[e].array)}raycast(e,t){let n=this._instanceInfo,r=this._geometryInfo,i=this.matrixWorld,a=this.geometry;us.material=this.material,us.geometry.index=a.index,us.geometry.attributes=a.attributes,us.geometry.boundingBox===null&&(us.geometry.boundingBox=new Ni),us.geometry.boundingSphere===null&&(us.geometry.boundingSphere=new fa);for(let a=0,o=n.length;a({...e,boundingBox:e.boundingBox===null?null:e.boundingBox.clone(),boundingSphere:e.boundingSphere===null?null:e.boundingSphere.clone()})),this._instanceInfo=e._instanceInfo.map(e=>({...e})),this._availableInstanceIds=e._availableInstanceIds.slice(),this._availableGeometryIds=e._availableGeometryIds.slice(),this._nextIndexStart=e._nextIndexStart,this._nextVertexStart=e._nextVertexStart,this._geometryCount=e._geometryCount,this._maxInstanceCount=e._maxInstanceCount,this._maxVertexCount=e._maxVertexCount,this._maxIndexCount=e._maxIndexCount,this._geometryInitialized=e._geometryInitialized,this._multiDrawCounts=e._multiDrawCounts.slice(),this._multiDrawStarts=e._multiDrawStarts.slice(),this._indirectTexture=e._indirectTexture.clone(),this._indirectTexture.image.data=this._indirectTexture.image.data.slice(),this._matricesTexture=e._matricesTexture.clone(),this._matricesTexture.image.data=this._matricesTexture.image.data.slice(),this._colorsTexture!==null&&(this._colorsTexture=e._colorsTexture.clone(),this._colorsTexture.image.data=this._colorsTexture.image.data.slice()),this}dispose(){this.geometry.dispose(),this._matricesTexture.dispose(),this._matricesTexture=null,this._indirectTexture.dispose(),this._indirectTexture=null,this._colorsTexture!==null&&(this._colorsTexture.dispose(),this._colorsTexture=null)}onBeforeRender(e,t,n,r,i){if(!this._visibilityChanged&&!this.perObjectFrustumCulled&&!this.sortObjects)return;let a=r.getIndex(),o=a===null?1:a.array.BYTES_PER_ELEMENT,s=1;i.wireframe&&(s=2,o=r.attributes.position.count>65535?4:2);let c=this._instanceInfo,l=this._multiDrawStarts,u=this._multiDrawCounts,d=this._geometryInfo,f=this.perObjectFrustumCulled,p=this._indirectTexture,m=p.image.data,h=n.isArrayCamera?rs:ns;f&&!n.isArrayCamera&&(es.multiplyMatrices(n.projectionMatrix,n.matrixWorldInverse).multiply(this.matrixWorld),ns.setFromProjectionMatrix(es,n.coordinateSystem,n.reversedDepth));let g=0;if(this.sortObjects){es.copy(this.matrixWorld).invert(),os.setFromMatrixPosition(n.matrixWorld).applyMatrix4(es),ss.set(0,0,-1).transformDirection(n.matrixWorld).transformDirection(es);for(let e=0,t=c.length;e0){let n=e[t[0]];if(n!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let e=0,t=n.length;er)return;xs.applyMatrix4(e.matrixWorld);let c=t.ray.origin.distanceTo(xs);if(!(ct.far))return{distance:c,point:Ss.clone().applyMatrix4(e.matrixWorld),index:o,face:null,faceIndex:null,barycoord:null,object:e}}var Ts=new H,Es=new H,Ds=class extends Cs{constructor(e,t){super(e,t),this.isLineSegments=!0,this.type=`LineSegments`}computeLineDistances(){let e=this.geometry;if(e.index===null){let t=e.attributes.position,n=[];for(let e=0,r=t.count;e0){let n=e[t[0]];if(n!==void 0){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let e=0,t=n.length;ei.far)return;a.push({distance:c,distanceToRay:Math.sqrt(s),point:n,index:t,face:null,faceIndex:null,barycoord:null,object:o})}}var Is=class extends Er{constructor(e,t,n,r,i=L,a=L,o,s,c){super(e,t,n,r,i,a,o,s,c),this.isVideoTexture=!0,this.generateMipmaps=!1,this._requestVideoFrameCallbackId=0;let l=this;function u(){l.needsUpdate=!0,l._requestVideoFrameCallbackId=e.requestVideoFrameCallback(u)}`requestVideoFrameCallback`in e&&(this._requestVideoFrameCallbackId=e.requestVideoFrameCallback(u))}clone(){return new this.constructor(this.image).copy(this)}update(){let e=this.image;!(`requestVideoFrameCallback`in e)&&e.readyState>=e.HAVE_CURRENT_DATA&&(this.needsUpdate=!0)}dispose(){this._requestVideoFrameCallbackId!==0&&(this.source.data.cancelVideoFrameCallback(this._requestVideoFrameCallbackId),this._requestVideoFrameCallbackId=0),super.dispose()}},Ls=class extends Is{constructor(e,t,n,r,i,a,o,s){super({},e,t,n,r,i,a,o,s),this.isVideoFrameTexture=!0}update(){}clone(){return new this.constructor().copy(this)}setFrame(e){this.image=e,this.needsUpdate=!0}},Rs=class extends Er{constructor(e,t){super({width:e,height:t}),this.isFramebufferTexture=!0,this.magFilter=ge,this.minFilter=ge,this.generateMipmaps=!1,this.needsUpdate=!0}},zs=class extends Er{constructor(e,t,n,r,i,a,o,s,c,l,u,d){super(null,a,o,s,c,l,r,i,u,d),this.isCompressedTexture=!0,this.image={width:t,height:n},this.mipmaps=e,this.flipY=!1,this.generateMipmaps=!1}},Bs=class extends zs{constructor(e,t,n,r,i,a){super(e,t,n,i,a),this.isCompressedArrayTexture=!0,this.image.depth=r,this.wrapR=me,this.layerUpdates=new Set}addLayerUpdate(e){this.layerUpdates.add(e)}clearLayerUpdates(){this.layerUpdates.clear()}},Vs=class extends zs{constructor(e,t,n){super(void 0,e[0].width,e[0].height,t,n,301),this.isCompressedCubeTexture=!0,this.isCubeTexture=!0,this.image=e}},Hs=class extends Er{constructor(e=[],t=301,n,r,i,a,o,s,c,l){super(e,t,n,r,i,a,o,s,c,l),this.isCubeTexture=!0,this.flipY=!1}get images(){return this.image}set images(e){this.image=e}},Us=class extends Er{constructor(e,t,n,r,i,a,o,s,c){super(e,t,n,r,i,a,o,s,c),this.isCanvasTexture=!0,this.needsUpdate=!0}},Ws=class extends Er{constructor(e,t,n=De,r,i,a,o=ge,s=ge,c,l=Re,u=1){if(l!==1026&&l!==1027)throw Error(`DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat`);super({width:e,height:t,depth:u},r,i,a,o,s,l,n,c),this.isDepthTexture=!0,this.flipY=!1,this.generateMipmaps=!1,this.compareFunction=null}copy(e){return super.copy(e),this.source=new Sr(Object.assign({},e.image)),this.compareFunction=e.compareFunction,this}toJSON(e){let t=super.toJSON(e);return this.compareFunction!==null&&(t.compareFunction=this.compareFunction),t}},Gs=class extends Ws{constructor(e,t=De,n=301,r,i,a=ge,o=ge,s,c=Re){let l={width:e,height:e,depth:1},u=[l,l,l,l,l,l];super(e,e,t,n,r,i,a,o,s,c),this.image=u,this.isCubeDepthTexture=!0,this.isCubeTexture=!0}get images(){return this.image}set images(e){this.image=e}},Ks=class extends Er{constructor(e=null){super(),this.sourceTexture=e,this.isExternalTexture=!0}copy(e){return super.copy(e),this.sourceTexture=e.sourceTexture,this}},qs=class e extends ba{constructor(e=1,t=1,n=1,r=1,i=1,a=1){super(),this.type=`BoxGeometry`,this.parameters={width:e,height:t,depth:n,widthSegments:r,heightSegments:i,depthSegments:a};let o=this;r=Math.floor(r),i=Math.floor(i),a=Math.floor(a);let s=[],c=[],l=[],u=[],d=0,f=0;p(`z`,`y`,`x`,-1,-1,n,t,e,a,i,0),p(`z`,`y`,`x`,1,-1,n,t,-e,a,i,1),p(`x`,`z`,`y`,1,1,e,n,t,r,a,2),p(`x`,`z`,`y`,1,-1,e,n,-t,r,a,3),p(`x`,`y`,`z`,1,-1,e,t,n,r,i,4),p(`x`,`y`,`z`,-1,-1,e,t,-n,r,i,5),this.setIndex(s),this.setAttribute(`position`,new K(c,3)),this.setAttribute(`normal`,new K(l,3)),this.setAttribute(`uv`,new K(u,2));function p(e,t,n,r,i,a,p,m,h,g,_){let v=a/h,y=p/g,b=a/2,x=p/2,S=m/2,C=h+1,w=g+1,T=0,E=0,D=new H;for(let a=0;a0?1:-1,l.push(D.x,D.y,D.z),u.push(s/h),u.push(1-a/g),T+=1}for(let e=0;e0){let e=(_-1)*m;for(let t=0;t0&&v(!0),t>0&&v(!1)),this.setIndex(l),this.setAttribute(`position`,new K(u,3)),this.setAttribute(`normal`,new K(d,3)),this.setAttribute(`uv`,new K(f,2));function _(){let a=new H,_=new H,v=0,y=(t-e)/n;for(let c=0;c<=i;c++){let l=[],g=c/i,v=g*(t-e)+e;for(let e=0;e<=r;e++){let t=e/r,i=t*s+o,c=Math.sin(i),m=Math.cos(i);_.x=v*c,_.y=-g*n+h,_.z=v*m,u.push(_.x,_.y,_.z),a.set(c,y,m).normalize(),d.push(a.x,a.y,a.z),f.push(t,1-g),l.push(p++)}m.push(l)}for(let n=0;n0||r!==0)&&(l.push(a,o,c),v+=3),(t>0||r!==i-1)&&(l.push(o,s,c),v+=3)}c.addGroup(g,v,0),g+=v}function v(n){let i=p,a=new V,m=new H,_=0,v=n===!0?e:t,y=n===!0?1:-1;for(let e=1;e<=r;e++)u.push(0,h*y,0),d.push(0,y,0),f.push(.5,.5),p++;let b=p;for(let e=0;e<=r;e++){let t=e/r*s+o,n=Math.cos(t),i=Math.sin(t);m.x=v*i,m.y=h*y,m.z=v*n,u.push(m.x,m.y,m.z),d.push(0,y,0),a.x=n*.5+.5,a.y=i*.5*y+.5,f.push(a.x,a.y),p++}for(let e=0;e.9&&Math.min(t,n,r)<.1&&(t<.2&&(a[e+0]+=1),n<.2&&(a[e+2]+=1),r<.2&&(a[e+4]+=1))}}function d(e){i.push(e.x,e.y,e.z)}function f(t,n){let r=t*3;n.x=e[r+0],n.y=e[r+1],n.z=e[r+2]}function p(){let e=new H,t=new H,n=new H,r=new H,o=new V,s=new V,c=new V;for(let l=0,u=0;l0)s=r-1;else{s=r;break}if(r=s,n[r]===a)return r/(i-1);let l=n[r],u=n[r+1]-l,d=(a-l)/u;return(r+d)/(i-1)}getTangent(e,t){let n=1e-4,r=e-n,i=e+n;r<0&&(r=0),i>1&&(i=1);let a=this.getPoint(r),o=this.getPoint(i),s=t||(a.isVector2?new V:new H);return s.copy(o).sub(a).normalize(),s}getTangentAt(e,t){let n=this.getUtoTmapping(e);return this.getTangent(n,t)}computeFrenetFrames(e,t=!1){let n=new H,r=[],i=[],a=[],o=new H,s=new Pr;for(let t=0;t<=e;t++){let n=t/e;r[t]=this.getTangentAt(n,new H)}i[0]=new H,a[0]=new H;let c=Number.MAX_VALUE,l=Math.abs(r[0].x),u=Math.abs(r[0].y),d=Math.abs(r[0].z);l<=c&&(c=l,n.set(1,0,0)),u<=c&&(c=u,n.set(0,1,0)),d<=c&&n.set(0,0,1),o.crossVectors(r[0],n).normalize(),i[0].crossVectors(r[0],o),a[0].crossVectors(r[0],i[0]);for(let t=1;t<=e;t++){if(i[t]=i[t-1].clone(),a[t]=a[t-1].clone(),o.crossVectors(r[t-1],r[t]),o.length()>2**-52){o.normalize();let e=Math.acos(Bn(r[t-1].dot(r[t]),-1,1));i[t].applyMatrix4(s.makeRotationAxis(o,e))}a[t].crossVectors(r[t],i[t])}if(t===!0){let t=Math.acos(Bn(i[0].dot(i[e]),-1,1));t/=e,r[0].dot(o.crossVectors(i[0],i[e]))>0&&(t=-t);for(let n=1;n<=e;n++)i[n].applyMatrix4(s.makeRotationAxis(r[n],t*n)),a[n].crossVectors(r[n],i[n])}return{tangents:r,normals:i,binormals:a}}clone(){return new this.constructor().copy(this)}copy(e){return this.arcLengthDivisions=e.arcLengthDivisions,this}toJSON(){let e={metadata:{version:4.7,type:`Curve`,generator:`Curve.toJSON`}};return e.arcLengthDivisions=this.arcLengthDivisions,e.type=this.type,e}fromJSON(e){return this.arcLengthDivisions=e.arcLengthDivisions,this}},oc=class extends ac{constructor(e=0,t=0,n=1,r=1,i=0,a=Math.PI*2,o=!1,s=0){super(),this.isEllipseCurve=!0,this.type=`EllipseCurve`,this.aX=e,this.aY=t,this.xRadius=n,this.yRadius=r,this.aStartAngle=i,this.aEndAngle=a,this.aClockwise=o,this.aRotation=s}getPoint(e,t=new V){let n=t,r=Math.PI*2,i=this.aEndAngle-this.aStartAngle,a=Math.abs(i)<2**-52;for(;i<0;)i+=r;for(;i>r;)i-=r;i<2**-52&&(i=a?0:r),this.aClockwise===!0&&!a&&(i===r?i=-r:i-=r);let o=this.aStartAngle+e*i,s=this.aX+this.xRadius*Math.cos(o),c=this.aY+this.yRadius*Math.sin(o);if(this.aRotation!==0){let e=Math.cos(this.aRotation),t=Math.sin(this.aRotation),n=s-this.aX,r=c-this.aY;s=n*e-r*t+this.aX,c=n*t+r*e+this.aY}return n.set(s,c)}copy(e){return super.copy(e),this.aX=e.aX,this.aY=e.aY,this.xRadius=e.xRadius,this.yRadius=e.yRadius,this.aStartAngle=e.aStartAngle,this.aEndAngle=e.aEndAngle,this.aClockwise=e.aClockwise,this.aRotation=e.aRotation,this}toJSON(){let e=super.toJSON();return e.aX=this.aX,e.aY=this.aY,e.xRadius=this.xRadius,e.yRadius=this.yRadius,e.aStartAngle=this.aStartAngle,e.aEndAngle=this.aEndAngle,e.aClockwise=this.aClockwise,e.aRotation=this.aRotation,e}fromJSON(e){return super.fromJSON(e),this.aX=e.aX,this.aY=e.aY,this.xRadius=e.xRadius,this.yRadius=e.yRadius,this.aStartAngle=e.aStartAngle,this.aEndAngle=e.aEndAngle,this.aClockwise=e.aClockwise,this.aRotation=e.aRotation,this}},sc=class extends oc{constructor(e,t,n,r,i,a){super(e,t,n,n,r,i,a),this.isArcCurve=!0,this.type=`ArcCurve`}};function cc(){let e=0,t=0,n=0,r=0;function i(i,a,o,s){e=i,t=o,n=-3*i+3*a-2*o-s,r=2*i-2*a+o+s}return{initCatmullRom:function(e,t,n,r,a){i(t,n,a*(n-e),a*(r-t))},initNonuniformCatmullRom:function(e,t,n,r,a,o,s){let c=(t-e)/a-(n-e)/(a+o)+(n-t)/o,l=(n-t)/o-(r-t)/(o+s)+(r-n)/s;c*=o,l*=o,i(t,n,c,l)},calc:function(i){let a=i*i,o=a*i;return e+t*i+n*a+r*o}}}var lc=new H,uc=new cc,dc=new cc,fc=new cc,pc=class extends ac{constructor(e=[],t=!1,n=`centripetal`,r=.5){super(),this.isCatmullRomCurve3=!0,this.type=`CatmullRomCurve3`,this.points=e,this.closed=t,this.curveType=n,this.tension=r}getPoint(e,t=new H){let n=t,r=this.points,i=r.length,a=(i-(this.closed?0:1))*e,o=Math.floor(a),s=a-o;this.closed?o+=o>0?0:(Math.floor(Math.abs(o)/i)+1)*i:s===0&&o===i-1&&(o=i-2,s=1);let c,l;this.closed||o>0?c=r[(o-1)%i]:(lc.subVectors(r[0],r[1]).add(r[0]),c=lc);let u=r[o%i],d=r[(o+1)%i];if(this.closed||o+2r.length-2?r.length-1:a+1],u=r[a>r.length-3?r.length-1:a+2];return n.set(mc(o,s.x,c.x,l.x,u.x),mc(o,s.y,c.y,l.y,u.y)),n}copy(e){super.copy(e),this.points=[];for(let t=0,n=e.points.length;t=n){let e=r[i]-n,a=this.curves[i],o=a.getLength(),s=o===0?0:1-e/o;return a.getPointAt(s,t)}i++}return null}getLength(){let e=this.getCurveLengths();return e[e.length-1]}updateArcLengths(){this.needsUpdate=!0,this.cacheLengths=null,this.getCurveLengths()}getCurveLengths(){if(this.cacheLengths&&this.cacheLengths.length===this.curves.length)return this.cacheLengths;let e=[],t=0;for(let n=0,r=this.curves.length;n1&&!t[t.length-1].equals(t[0])&&t.push(t[0]),t}copy(e){super.copy(e),this.curves=[];for(let t=0,n=e.curves.length;t0){let e=c.getPoint(0);e.equals(this.currentPoint)||this.lineTo(e.x,e.y)}this.curves.push(c);let l=c.getPoint(1);return this.currentPoint.copy(l),this}copy(e){return super.copy(e),this.currentPoint.copy(e.currentPoint),this}toJSON(){let e=super.toJSON();return e.currentPoint=this.currentPoint.toArray(),e}fromJSON(e){return super.fromJSON(e),this.currentPoint.fromArray(e.currentPoint),this}},Pc=class extends Nc{constructor(e){super(e),this.uuid=zn(),this.type=`Shape`,this.holes=[]}getPointsHoles(e){let t=[];for(let n=0,r=this.holes.length;n80*n){s=e[0],c=e[1];let t=s,r=c;for(let a=n;at&&(t=n),i>r&&(r=i)}l=Math.max(t-s,r-c),l=l===0?0:32767/l}return Rc(a,o,n,s,c,l,0),o}function Ic(e,t,n,r,i){let a;if(i===pl(e,t,n,r)>0)for(let i=t;i=t;i-=r)a=ul(i/r|0,e[i],e[i+1],a);return a&&nl(a,a.next)&&(dl(a),a=a.next),a}function Lc(e,t){if(!e)return e;t||=e;let n=e,r;do if(r=!1,!n.steiner&&(nl(n,n.next)||tl(n.prev,n,n.next)===0)){if(dl(n),n=t=n.prev,n===n.next)break;r=!0}else n=n.next;while(r||n!==t);return t}function Rc(e,t,n,r,i,a,o){if(!e)return;!o&&a&&Jc(e,r,i,a);let s=e;for(;e.prev!==e.next;){let c=e.prev,l=e.next;if(a?Bc(e,r,i,a):zc(e)){t.push(c.i,e.i,l.i),dl(e),e=l.next,s=l.next;continue}if(e=l,e===s){o?o===1?(e=Vc(Lc(e),t),Rc(e,t,n,r,i,a,2)):o===2&&Hc(e,t,n,r,i,a):Rc(Lc(e),t,n,r,i,a,1);break}}}function zc(e){let t=e.prev,n=e,r=e.next;if(tl(t,n,r)>=0)return!1;let i=t.x,a=n.x,o=r.x,s=t.y,c=n.y,l=r.y,u=Math.min(i,a,o),d=Math.min(s,c,l),f=Math.max(i,a,o),p=Math.max(s,c,l),m=r.next;for(;m!==t;){if(m.x>=u&&m.x<=f&&m.y>=d&&m.y<=p&&$c(i,s,a,c,o,l,m.x,m.y)&&tl(m.prev,m,m.next)>=0)return!1;m=m.next}return!0}function Bc(e,t,n,r){let i=e.prev,a=e,o=e.next;if(tl(i,a,o)>=0)return!1;let s=i.x,c=a.x,l=o.x,u=i.y,d=a.y,f=o.y,p=Math.min(s,c,l),m=Math.min(u,d,f),h=Math.max(s,c,l),g=Math.max(u,d,f),_=Xc(p,m,t,n,r),v=Xc(h,g,t,n,r),y=e.prevZ,b=e.nextZ;for(;y&&y.z>=_&&b&&b.z<=v;){if(y.x>=p&&y.x<=h&&y.y>=m&&y.y<=g&&y!==i&&y!==o&&$c(s,u,c,d,l,f,y.x,y.y)&&tl(y.prev,y,y.next)>=0||(y=y.prevZ,b.x>=p&&b.x<=h&&b.y>=m&&b.y<=g&&b!==i&&b!==o&&$c(s,u,c,d,l,f,b.x,b.y)&&tl(b.prev,b,b.next)>=0))return!1;b=b.nextZ}for(;y&&y.z>=_;){if(y.x>=p&&y.x<=h&&y.y>=m&&y.y<=g&&y!==i&&y!==o&&$c(s,u,c,d,l,f,y.x,y.y)&&tl(y.prev,y,y.next)>=0)return!1;y=y.prevZ}for(;b&&b.z<=v;){if(b.x>=p&&b.x<=h&&b.y>=m&&b.y<=g&&b!==i&&b!==o&&$c(s,u,c,d,l,f,b.x,b.y)&&tl(b.prev,b,b.next)>=0)return!1;b=b.nextZ}return!0}function Vc(e,t){let n=e;do{let r=n.prev,i=n.next.next;!nl(r,i)&&rl(r,n,n.next,i)&&sl(r,i)&&sl(i,r)&&(t.push(r.i,n.i,i.i),dl(n),dl(n.next),n=e=i),n=n.next}while(n!==e);return Lc(n)}function Hc(e,t,n,r,i,a){let o=e;do{let e=o.next.next;for(;e!==o.prev;){if(o.i!==e.i&&el(o,e)){let s=ll(o,e);o=Lc(o,o.next),s=Lc(s,s.next),Rc(o,t,n,r,i,a,0),Rc(s,t,n,r,i,a,0);return}e=e.next}o=o.next}while(o!==e)}function Uc(e,t,n,r){let i=[];for(let n=0,a=t.length;n=n.next.y&&n.next.y!==n.y){let e=n.x+(i-n.y)*(n.next.x-n.x)/(n.next.y-n.y);if(e<=r&&e>a&&(a=e,o=n.x=n.x&&n.x>=c&&r!==n.x&&Qc(io.x||n.x===o.x&&qc(o,n)))&&(o=n,u=t)}n=n.next}while(n!==s);return o}function qc(e,t){return tl(e.prev,e,t.prev)<0&&tl(t.next,e,e.next)<0}function Jc(e,t,n,r){let i=e;do i.z===0&&(i.z=Xc(i.x,i.y,t,n,r)),i.prevZ=i.prev,i.nextZ=i.next,i=i.next;while(i!==e);i.prevZ.nextZ=null,i.prevZ=null,Yc(i)}function Yc(e){let t,n=1;do{let r=e,i;e=null;let a=null;for(t=0;r;){t++;let o=r,s=0;for(let e=0;e0||c>0&&o;)s!==0&&(c===0||!o||r.z<=o.z)?(i=r,r=r.nextZ,s--):(i=o,o=o.nextZ,c--),a?a.nextZ=i:e=i,i.prevZ=a,a=i;r=o}a.nextZ=null,n*=2}while(t>1);return e}function Xc(e,t,n,r,i){return e=(e-n)*i|0,t=(t-r)*i|0,e=(e|e<<8)&16711935,e=(e|e<<4)&252645135,e=(e|e<<2)&858993459,e=(e|e<<1)&1431655765,t=(t|t<<8)&16711935,t=(t|t<<4)&252645135,t=(t|t<<2)&858993459,t=(t|t<<1)&1431655765,e|t<<1}function Zc(e){let t=e,n=e;do(t.x=(e-o)*(a-s)&&(e-o)*(r-s)>=(n-o)*(t-s)&&(n-o)*(a-s)>=(i-o)*(r-s)}function $c(e,t,n,r,i,a,o,s){return!(e===o&&t===s)&&Qc(e,t,n,r,i,a,o,s)}function el(e,t){return e.next.i!==t.i&&e.prev.i!==t.i&&!ol(e,t)&&(sl(e,t)&&sl(t,e)&&cl(e,t)&&(tl(e.prev,e,t.prev)||tl(e,t.prev,t))||nl(e,t)&&tl(e.prev,e,e.next)>0&&tl(t.prev,t,t.next)>0)}function tl(e,t,n){return(t.y-e.y)*(n.x-t.x)-(t.x-e.x)*(n.y-t.y)}function nl(e,t){return e.x===t.x&&e.y===t.y}function rl(e,t,n,r){let i=al(tl(e,t,n)),a=al(tl(e,t,r)),o=al(tl(n,r,e)),s=al(tl(n,r,t));return!!(i!==a&&o!==s||i===0&&il(e,n,t)||a===0&&il(e,r,t)||o===0&&il(n,e,r)||s===0&&il(n,t,r))}function il(e,t,n){return t.x<=Math.max(e.x,n.x)&&t.x>=Math.min(e.x,n.x)&&t.y<=Math.max(e.y,n.y)&&t.y>=Math.min(e.y,n.y)}function al(e){return e>0?1:e<0?-1:0}function ol(e,t){let n=e;do{if(n.i!==e.i&&n.next.i!==e.i&&n.i!==t.i&&n.next.i!==t.i&&rl(n,n.next,e,t))return!0;n=n.next}while(n!==e);return!1}function sl(e,t){return tl(e.prev,e,e.next)<0?tl(e,t,e.next)>=0&&tl(e,e.prev,t)>=0:tl(e,t,e.prev)<0||tl(e,e.next,t)<0}function cl(e,t){let n=e,r=!1,i=(e.x+t.x)/2,a=(e.y+t.y)/2;do n.y>a!=n.next.y>a&&n.next.y!==n.y&&i<(n.next.x-n.x)*(a-n.y)/(n.next.y-n.y)+n.x&&(r=!r),n=n.next;while(n!==e);return r}function ll(e,t){let n=fl(e.i,e.x,e.y),r=fl(t.i,t.x,t.y),i=e.next,a=t.prev;return e.next=t,t.prev=e,n.next=i,i.prev=n,r.next=n,n.prev=r,a.next=r,r.prev=a,r}function ul(e,t,n,r){let i=fl(e,t,n);return r?(i.next=r.next,i.prev=r,r.next.prev=i,r.next=i):(i.prev=i,i.next=i),i}function dl(e){e.next.prev=e.prev,e.prev.next=e.next,e.prevZ&&(e.prevZ.nextZ=e.nextZ),e.nextZ&&(e.nextZ.prevZ=e.prevZ)}function fl(e,t,n){return{i:e,x:t,y:n,prev:null,next:null,z:0,prevZ:null,nextZ:null,steiner:!1}}function pl(e,t,n,r){let i=0;for(let a=t,o=n-r;a2&&e[t-1].equals(e[0])&&e.pop()}function _l(e,t){for(let n=0;n2**-52){let d=Math.sqrt(u),f=Math.sqrt(c*c+l*l),p=t.x-s/d,m=t.y+o/d,h=n.x-l/f,g=n.y+c/f,_=((h-p)*l-(g-m)*c)/(o*l-s*c);r=p+o*_-e.x,i=m+s*_-e.y;let v=r*r+i*i;if(v<=2)return new V(r,i);a=Math.sqrt(v/2)}else{let e=!1;o>2**-52?c>2**-52&&(e=!0):o<-(2**-52)?c<-(2**-52)&&(e=!0):Math.sign(s)===Math.sign(l)&&(e=!0),e?(r=-s,i=o,a=Math.sqrt(u)):(r=o,i=s,a=Math.sqrt(u/2))}return new V(r/a,i/a)}let j=[];for(let e=0,t=D.length,n=t-1,r=e+1;e=0;e--){let t=e/p,n=u*Math.cos(t*Math.PI/2),r=d*Math.sin(t*Math.PI/2)+f;for(let e=0,t=D.length;e=0;){let r=n,i=n-1;i<0&&(i=e.length-1);for(let e=0,n=s+p*2;e0)&&f.push(t,i,c),(e!==n-1||s0&&(t.defines=this.defines),t.vertexShader=this.vertexShader,t.fragmentShader=this.fragmentShader,t.lights=this.lights,t.clipping=this.clipping;let n={};for(let e in this.extensions)this.extensions[e]===!0&&(n[e]=!0);return Object.keys(n).length>0&&(t.extensions=n),t}},Wl=class extends q{constructor(e){super(e),this.isRawShaderMaterial=!0,this.type=`RawShaderMaterial`}},Gl=class extends Ta{constructor(e){super(),this.isMeshStandardMaterial=!0,this.type=`MeshStandardMaterial`,this.defines={STANDARD:``},this.color=new U(16777215),this.roughness=1,this.metalness=0,this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new U(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new V(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.roughnessMap=null,this.metalnessMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new Wr,this.envMapIntensity=1,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap=`round`,this.wireframeLinejoin=`round`,this.flatShading=!1,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.defines={STANDARD:``},this.color.copy(e.color),this.roughness=e.roughness,this.metalness=e.metalness,this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.emissive.copy(e.emissive),this.emissiveMap=e.emissiveMap,this.emissiveIntensity=e.emissiveIntensity,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.roughnessMap=e.roughnessMap,this.metalnessMap=e.metalnessMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.envMapIntensity=e.envMapIntensity,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.flatShading=e.flatShading,this.fog=e.fog,this}},Kl=class extends Gl{constructor(e){super(),this.isMeshPhysicalMaterial=!0,this.defines={STANDARD:``,PHYSICAL:``},this.type=`MeshPhysicalMaterial`,this.anisotropyRotation=0,this.anisotropyMap=null,this.clearcoatMap=null,this.clearcoatRoughness=0,this.clearcoatRoughnessMap=null,this.clearcoatNormalScale=new V(1,1),this.clearcoatNormalMap=null,this.ior=1.5,Object.defineProperty(this,`reflectivity`,{get:function(){return Bn(2.5*(this.ior-1)/(this.ior+1),0,1)},set:function(e){this.ior=(1+.4*e)/(1-.4*e)}}),this.iridescenceMap=null,this.iridescenceIOR=1.3,this.iridescenceThicknessRange=[100,400],this.iridescenceThicknessMap=null,this.sheenColor=new U(0),this.sheenColorMap=null,this.sheenRoughness=1,this.sheenRoughnessMap=null,this.transmissionMap=null,this.thickness=0,this.thicknessMap=null,this.attenuationDistance=1/0,this.attenuationColor=new U(1,1,1),this.specularIntensity=1,this.specularIntensityMap=null,this.specularColor=new U(1,1,1),this.specularColorMap=null,this._anisotropy=0,this._clearcoat=0,this._dispersion=0,this._iridescence=0,this._sheen=0,this._transmission=0,this.setValues(e)}get anisotropy(){return this._anisotropy}set anisotropy(e){this._anisotropy>0!=e>0&&this.version++,this._anisotropy=e}get clearcoat(){return this._clearcoat}set clearcoat(e){this._clearcoat>0!=e>0&&this.version++,this._clearcoat=e}get iridescence(){return this._iridescence}set iridescence(e){this._iridescence>0!=e>0&&this.version++,this._iridescence=e}get dispersion(){return this._dispersion}set dispersion(e){this._dispersion>0!=e>0&&this.version++,this._dispersion=e}get sheen(){return this._sheen}set sheen(e){this._sheen>0!=e>0&&this.version++,this._sheen=e}get transmission(){return this._transmission}set transmission(e){this._transmission>0!=e>0&&this.version++,this._transmission=e}copy(e){return super.copy(e),this.defines={STANDARD:``,PHYSICAL:``},this.anisotropy=e.anisotropy,this.anisotropyRotation=e.anisotropyRotation,this.anisotropyMap=e.anisotropyMap,this.clearcoat=e.clearcoat,this.clearcoatMap=e.clearcoatMap,this.clearcoatRoughness=e.clearcoatRoughness,this.clearcoatRoughnessMap=e.clearcoatRoughnessMap,this.clearcoatNormalMap=e.clearcoatNormalMap,this.clearcoatNormalScale.copy(e.clearcoatNormalScale),this.dispersion=e.dispersion,this.ior=e.ior,this.iridescence=e.iridescence,this.iridescenceMap=e.iridescenceMap,this.iridescenceIOR=e.iridescenceIOR,this.iridescenceThicknessRange=[...e.iridescenceThicknessRange],this.iridescenceThicknessMap=e.iridescenceThicknessMap,this.sheen=e.sheen,this.sheenColor.copy(e.sheenColor),this.sheenColorMap=e.sheenColorMap,this.sheenRoughness=e.sheenRoughness,this.sheenRoughnessMap=e.sheenRoughnessMap,this.transmission=e.transmission,this.transmissionMap=e.transmissionMap,this.thickness=e.thickness,this.thicknessMap=e.thicknessMap,this.attenuationDistance=e.attenuationDistance,this.attenuationColor.copy(e.attenuationColor),this.specularIntensity=e.specularIntensity,this.specularIntensityMap=e.specularIntensityMap,this.specularColor.copy(e.specularColor),this.specularColorMap=e.specularColorMap,this}},ql=class extends Ta{constructor(e){super(),this.isMeshPhongMaterial=!0,this.type=`MeshPhongMaterial`,this.color=new U(16777215),this.specular=new U(1118481),this.shininess=30,this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new U(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new V(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new Wr,this.combine=0,this.reflectivity=1,this.envMapIntensity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap=`round`,this.wireframeLinejoin=`round`,this.flatShading=!1,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.specular.copy(e.specular),this.shininess=e.shininess,this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.emissive.copy(e.emissive),this.emissiveMap=e.emissiveMap,this.emissiveIntensity=e.emissiveIntensity,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.combine=e.combine,this.reflectivity=e.reflectivity,this.envMapIntensity=e.envMapIntensity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.flatShading=e.flatShading,this.fog=e.fog,this}},Jl=class extends Ta{constructor(e){super(),this.isMeshToonMaterial=!0,this.defines={TOON:``},this.type=`MeshToonMaterial`,this.color=new U(16777215),this.map=null,this.gradientMap=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new U(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new V(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.alphaMap=null,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap=`round`,this.wireframeLinejoin=`round`,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.gradientMap=e.gradientMap,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.emissive.copy(e.emissive),this.emissiveMap=e.emissiveMap,this.emissiveIntensity=e.emissiveIntensity,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.alphaMap=e.alphaMap,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.fog=e.fog,this}},Yl=class extends Ta{constructor(e){super(),this.isMeshNormalMaterial=!0,this.type=`MeshNormalMaterial`,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new V(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.wireframe=!1,this.wireframeLinewidth=1,this.flatShading=!1,this.setValues(e)}copy(e){return super.copy(e),this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.flatShading=e.flatShading,this}},Xl=class extends Ta{constructor(e){super(),this.isMeshLambertMaterial=!0,this.type=`MeshLambertMaterial`,this.color=new U(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new U(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new V(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new Wr,this.combine=0,this.reflectivity=1,this.envMapIntensity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap=`round`,this.wireframeLinejoin=`round`,this.flatShading=!1,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.emissive.copy(e.emissive),this.emissiveMap=e.emissiveMap,this.emissiveIntensity=e.emissiveIntensity,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.combine=e.combine,this.reflectivity=e.reflectivity,this.envMapIntensity=e.envMapIntensity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.flatShading=e.flatShading,this.fog=e.fog,this}},Zl=class extends Ta{constructor(e){super(),this.isMeshDepthMaterial=!0,this.type=`MeshDepthMaterial`,this.depthPacking=Bt,this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.wireframe=!1,this.wireframeLinewidth=1,this.setValues(e)}copy(e){return super.copy(e),this.depthPacking=e.depthPacking,this.map=e.map,this.alphaMap=e.alphaMap,this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this}},Ql=class extends Ta{constructor(e){super(),this.isMeshDistanceMaterial=!0,this.type=`MeshDistanceMaterial`,this.map=null,this.alphaMap=null,this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.setValues(e)}copy(e){return super.copy(e),this.map=e.map,this.alphaMap=e.alphaMap,this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this}},$l=class extends Ta{constructor(e){super(),this.isMeshMatcapMaterial=!0,this.defines={MATCAP:``},this.type=`MeshMatcapMaterial`,this.color=new U(16777215),this.matcap=null,this.map=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new V(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.alphaMap=null,this.wireframe=!1,this.wireframeLinewidth=1,this.flatShading=!1,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.defines={MATCAP:``},this.color.copy(e.color),this.matcap=e.matcap,this.map=e.map,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.alphaMap=e.alphaMap,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.flatShading=e.flatShading,this.fog=e.fog,this}},eu=class extends hs{constructor(e){super(),this.isLineDashedMaterial=!0,this.type=`LineDashedMaterial`,this.scale=1,this.dashSize=3,this.gapSize=1,this.setValues(e)}copy(e){return super.copy(e),this.scale=e.scale,this.dashSize=e.dashSize,this.gapSize=e.gapSize,this}};function tu(e,t){return!e||e.constructor===t?e:typeof t.BYTES_PER_ELEMENT==`number`?new t(e):Array.prototype.slice.call(e)}function nu(e){function t(t,n){return e[t]-e[n]}let n=e.length,r=Array(n);for(let e=0;e!==n;++e)r[e]=e;return r.sort(t),r}function ru(e,t,n){let r=e.length,i=new e.constructor(r);for(let a=0,o=0;o!==r;++a){let r=n[a]*t;for(let n=0;n!==t;++n)i[o++]=e[r+n]}return i}function iu(e,t,n,r){let i=1,a=e[0];for(;a!==void 0&&a[r]===void 0;)a=e[i++];if(a===void 0)return;let o=a[r];if(o!==void 0)if(Array.isArray(o))do o=a[r],o!==void 0&&(t.push(a.time),n.push(...o)),a=e[i++];while(a!==void 0);else if(o.toArray!==void 0)do o=a[r],o!==void 0&&(t.push(a.time),o.toArray(n,n.length)),a=e[i++];while(a!==void 0);else do o=a[r],o!==void 0&&(t.push(a.time),n.push(o)),a=e[i++];while(a!==void 0)}function au(e,t,n,r,i=30){let a=e.clone();a.name=t;let o=[];for(let e=0;e=r)){c.push(t.times[e]);for(let n=0;na.tracks[e].times[0]&&(s=a.tracks[e].times[0]);for(let e=0;e=r.times[d]){let e=d*c+s,t=e+c-s;f=r.values.slice(e,t)}else{let e=r.createInterpolant(),t=s,n=c-s;e.evaluate(a),f=e.resultBuffer.slice(t,n)}i===`quaternion`&&new cr().fromArray(f).normalize().conjugate().toArray(f);let p=o.times.length;for(let e=0;e=i)){let o=t[1];e=i)break seek}a=n,n=0;break linear_scan}break validate_interval}for(;n>>1;et;)--a;if(++a,i!==0||a!==r){i>=a&&(a=Math.max(a,1),i=a-1);let e=this.getValueSize();this.times=n.slice(i,a),this.values=this.values.slice(i*e,a*e)}return this}validate(){let e=!0,t=this.getValueSize();t-Math.floor(t)!==0&&(An(`KeyframeTrack: Invalid value size in track.`,this),e=!1);let n=this.times,r=this.values,i=n.length;i===0&&(An(`KeyframeTrack: Track is empty.`,this),e=!1);let a=null;for(let t=0;t!==i;t++){let r=n[t];if(typeof r==`number`&&isNaN(r)){An(`KeyframeTrack: Time is not a valid number.`,this,t,r),e=!1;break}if(a!==null&&a>r){An(`KeyframeTrack: Out of order keys.`,this,t,r,a),e=!1;break}a=r}if(r!==void 0&&xn(r))for(let t=0,n=r.length;t!==n;++t){let n=r[t];if(isNaN(n)){An(`KeyframeTrack: Value is not a valid number.`,this,t,n),e=!1;break}}return e}optimize(){let e=this.times.slice(),t=this.values.slice(),n=this.getValueSize(),r=this.getInterpolation()===Nt,i=e.length-1,a=1;for(let o=1;o0){e[a]=e[i];for(let e=i*n,r=a*n,o=0;o!==n;++o)t[r+o]=t[e+o];++a}return a===e.length?(this.times=e,this.values=t):(this.times=e.slice(0,a),this.values=t.slice(0,a*n)),this}clone(){let e=this.times.slice(),t=this.values.slice(),n=this.constructor,r=new n(this.name,e,t);return r.createInterpolant=this.createInterpolant,r}};pu.prototype.ValueTypeName=``,pu.prototype.TimeBufferType=Float32Array,pu.prototype.ValueBufferType=Float32Array,pu.prototype.DefaultInterpolation=Mt;var mu=class extends pu{constructor(e,t,n){super(e,t,n)}};mu.prototype.ValueTypeName=`bool`,mu.prototype.ValueBufferType=Array,mu.prototype.DefaultInterpolation=jt,mu.prototype.InterpolantFactoryMethodLinear=void 0,mu.prototype.InterpolantFactoryMethodSmooth=void 0;var hu=class extends pu{constructor(e,t,n,r){super(e,t,n,r)}};hu.prototype.ValueTypeName=`color`;var gu=class extends pu{constructor(e,t,n,r){super(e,t,n,r)}};gu.prototype.ValueTypeName=`number`;var _u=class extends cu{constructor(e,t,n,r){super(e,t,n,r)}interpolate_(e,t,n,r){let i=this.resultBuffer,a=this.sampleValues,o=this.valueSize,s=(n-t)/(r-t),c=e*o;for(let e=c+o;c!==e;c+=4)cr.slerpFlat(i,0,a,c-o,a,c,s);return i}},vu=class extends pu{constructor(e,t,n,r){super(e,t,n,r)}InterpolantFactoryMethodLinear(e){return new _u(this.times,this.values,this.getValueSize(),e)}};vu.prototype.ValueTypeName=`quaternion`,vu.prototype.InterpolantFactoryMethodSmooth=void 0;var yu=class extends pu{constructor(e,t,n){super(e,t,n)}};yu.prototype.ValueTypeName=`string`,yu.prototype.ValueBufferType=Array,yu.prototype.DefaultInterpolation=jt,yu.prototype.InterpolantFactoryMethodLinear=void 0,yu.prototype.InterpolantFactoryMethodSmooth=void 0;var bu=class extends pu{constructor(e,t,n,r){super(e,t,n,r)}};bu.prototype.ValueTypeName=`vector`;var xu=class{constructor(e=``,t=-1,n=[],r=Rt){this.name=e,this.tracks=n,this.duration=t,this.blendMode=r,this.uuid=zn(),this.userData={},this.duration<0&&this.resetDuration()}static parse(e){let t=[],n=e.tracks,r=1/(e.fps||1);for(let e=0,i=n.length;e!==i;++e)t.push(Cu(n[e]).scale(r));let i=new this(e.name,e.duration,t,e.blendMode);return i.uuid=e.uuid,i.userData=JSON.parse(e.userData||`{}`),i}static toJSON(e){let t=[],n=e.tracks,r={name:e.name,duration:e.duration,tracks:t,uuid:e.uuid,blendMode:e.blendMode,userData:JSON.stringify(e.userData)};for(let e=0,r=n.length;e!==r;++e)t.push(pu.toJSON(n[e]));return r}static CreateFromMorphTargetSequence(e,t,n,r){let i=t.length,a=[];for(let e=0;e1){let e=a[1],t=r[e];t||(r[e]=t=[]),t.push(n)}}let a=[];for(let e in r)a.push(this.CreateFromMorphTargetSequence(e,r[e],t,n));return a}static parseAnimation(e,t){if(B(`AnimationClip: parseAnimation() is deprecated and will be removed with r185`),!e)return An(`AnimationClip: No animation in JSONLoader data.`),null;let n=function(e,t,n,r,i){if(n.length!==0){let a=[],o=[];iu(n,a,o,r),a.length!==0&&i.push(new e(t,a,o))}},r=[],i=e.name||`default`,a=e.fps||30,o=e.blendMode,s=e.length||-1,c=e.hierarchy||[];for(let e=0;e{t&&t(i),this.manager.itemEnd(e)},0),i;if(ku[e]!==void 0){ku[e].push({onLoad:t,onProgress:n,onError:r});return}ku[e]=[],ku[e].push({onLoad:t,onProgress:n,onError:r});let a=new Request(e,{headers:new Headers(this.requestHeader),credentials:this.withCredentials?`include`:`same-origin`,signal:typeof AbortSignal.any==`function`?AbortSignal.any([this._abortController.signal,this.manager.abortController.signal]):this._abortController.signal}),o=this.mimeType,s=this.responseType;fetch(a).then(t=>{if(t.status===200||t.status===0){if(t.status===0&&B(`FileLoader: HTTP Status 0 received.`),typeof ReadableStream>`u`||t.body===void 0||t.body.getReader===void 0)return t;let n=ku[e],r=t.body.getReader(),i=t.headers.get(`X-File-Size`)||t.headers.get(`Content-Length`),a=i?parseInt(i):0,o=a!==0,s=0,c=new ReadableStream({start(e){t();function t(){r.read().then(({done:r,value:i})=>{if(r)e.close();else{s+=i.byteLength;let r=new ProgressEvent(`progress`,{lengthComputable:o,loaded:s,total:a});for(let e=0,t=n.length;e{e.error(t)})}}});return new Response(c)}else throw new Au(`fetch for "${t.url}" responded with ${t.status}: ${t.statusText}`,t)}).then(e=>{switch(s){case`arraybuffer`:return e.arrayBuffer();case`blob`:return e.blob();case`document`:return e.text().then(e=>new DOMParser().parseFromString(e,o));case`json`:return e.json();default:if(o===``)return e.text();{let t=/charset="?([^;"\s]*)"?/i.exec(o),n=t&&t[1]?t[1].toLowerCase():void 0,r=new TextDecoder(n);return e.arrayBuffer().then(e=>r.decode(e))}}}).then(t=>{wu.add(`file:${e}`,t);let n=ku[e];delete ku[e];for(let e=0,r=n.length;e{let n=ku[e];if(n===void 0)throw this.manager.itemError(e),t;delete ku[e];for(let e=0,r=n.length;e{this.manager.itemEnd(e)}),this.manager.itemStart(e)}setResponseType(e){return this.responseType=e,this}setMimeType(e){return this.mimeType=e,this}abort(){return this._abortController.abort(),this._abortController=new AbortController,this}},Mu=class extends Ou{constructor(e){super(e)}load(e,t,n,r){let i=this,a=new ju(this.manager);a.setPath(this.path),a.setRequestHeader(this.requestHeader),a.setWithCredentials(this.withCredentials),a.load(e,function(n){try{t(i.parse(JSON.parse(n)))}catch(t){r?r(t):An(t),i.manager.itemError(e)}},n,r)}parse(e){let t=[];for(let n=0;n0:r.vertexColors=e.vertexColors),e.uniforms!==void 0)for(let t in e.uniforms){let i=e.uniforms[t];switch(r.uniforms[t]={},i.type){case`t`:r.uniforms[t].value=n(i.value);break;case`c`:r.uniforms[t].value=new U().setHex(i.value);break;case`v2`:r.uniforms[t].value=new V().fromArray(i.value);break;case`v3`:r.uniforms[t].value=new H().fromArray(i.value);break;case`v4`:r.uniforms[t].value=new Dr().fromArray(i.value);break;case`m3`:r.uniforms[t].value=new dr().fromArray(i.value);break;case`m4`:r.uniforms[t].value=new Pr().fromArray(i.value);break;default:r.uniforms[t].value=i.value}}if(e.defines!==void 0&&(r.defines=e.defines),e.vertexShader!==void 0&&(r.vertexShader=e.vertexShader),e.fragmentShader!==void 0&&(r.fragmentShader=e.fragmentShader),e.glslVersion!==void 0&&(r.glslVersion=e.glslVersion),e.extensions!==void 0)for(let t in e.extensions)r.extensions[t]=e.extensions[t];if(e.lights!==void 0&&(r.lights=e.lights),e.clipping!==void 0&&(r.clipping=e.clipping),e.size!==void 0&&(r.size=e.size),e.sizeAttenuation!==void 0&&(r.sizeAttenuation=e.sizeAttenuation),e.map!==void 0&&(r.map=n(e.map)),e.matcap!==void 0&&(r.matcap=n(e.matcap)),e.alphaMap!==void 0&&(r.alphaMap=n(e.alphaMap)),e.bumpMap!==void 0&&(r.bumpMap=n(e.bumpMap)),e.bumpScale!==void 0&&(r.bumpScale=e.bumpScale),e.normalMap!==void 0&&(r.normalMap=n(e.normalMap)),e.normalMapType!==void 0&&(r.normalMapType=e.normalMapType),e.normalScale!==void 0){let t=e.normalScale;Array.isArray(t)===!1&&(t=[t,t]),r.normalScale=new V().fromArray(t)}return e.displacementMap!==void 0&&(r.displacementMap=n(e.displacementMap)),e.displacementScale!==void 0&&(r.displacementScale=e.displacementScale),e.displacementBias!==void 0&&(r.displacementBias=e.displacementBias),e.roughnessMap!==void 0&&(r.roughnessMap=n(e.roughnessMap)),e.metalnessMap!==void 0&&(r.metalnessMap=n(e.metalnessMap)),e.emissiveMap!==void 0&&(r.emissiveMap=n(e.emissiveMap)),e.emissiveIntensity!==void 0&&(r.emissiveIntensity=e.emissiveIntensity),e.specularMap!==void 0&&(r.specularMap=n(e.specularMap)),e.specularIntensityMap!==void 0&&(r.specularIntensityMap=n(e.specularIntensityMap)),e.specularColorMap!==void 0&&(r.specularColorMap=n(e.specularColorMap)),e.envMap!==void 0&&(r.envMap=n(e.envMap)),e.envMapRotation!==void 0&&r.envMapRotation.fromArray(e.envMapRotation),e.envMapIntensity!==void 0&&(r.envMapIntensity=e.envMapIntensity),e.reflectivity!==void 0&&(r.reflectivity=e.reflectivity),e.refractionRatio!==void 0&&(r.refractionRatio=e.refractionRatio),e.lightMap!==void 0&&(r.lightMap=n(e.lightMap)),e.lightMapIntensity!==void 0&&(r.lightMapIntensity=e.lightMapIntensity),e.aoMap!==void 0&&(r.aoMap=n(e.aoMap)),e.aoMapIntensity!==void 0&&(r.aoMapIntensity=e.aoMapIntensity),e.gradientMap!==void 0&&(r.gradientMap=n(e.gradientMap)),e.clearcoatMap!==void 0&&(r.clearcoatMap=n(e.clearcoatMap)),e.clearcoatRoughnessMap!==void 0&&(r.clearcoatRoughnessMap=n(e.clearcoatRoughnessMap)),e.clearcoatNormalMap!==void 0&&(r.clearcoatNormalMap=n(e.clearcoatNormalMap)),e.clearcoatNormalScale!==void 0&&(r.clearcoatNormalScale=new V().fromArray(e.clearcoatNormalScale)),e.iridescenceMap!==void 0&&(r.iridescenceMap=n(e.iridescenceMap)),e.iridescenceThicknessMap!==void 0&&(r.iridescenceThicknessMap=n(e.iridescenceThicknessMap)),e.transmissionMap!==void 0&&(r.transmissionMap=n(e.transmissionMap)),e.thicknessMap!==void 0&&(r.thicknessMap=n(e.thicknessMap)),e.anisotropyMap!==void 0&&(r.anisotropyMap=n(e.anisotropyMap)),e.sheenColorMap!==void 0&&(r.sheenColorMap=n(e.sheenColorMap)),e.sheenRoughnessMap!==void 0&&(r.sheenRoughnessMap=n(e.sheenRoughnessMap)),r}setTextures(e){return this.textures=e,this}createMaterialFromType(t){return e.createMaterialFromType(t)}static createMaterialFromType(e){return new{ShadowMaterial:Il,SpriteMaterial:Ea,RawShaderMaterial:Wl,ShaderMaterial:q,PointsMaterial:ks,MeshPhysicalMaterial:Kl,MeshStandardMaterial:Gl,MeshPhongMaterial:ql,MeshToonMaterial:Jl,MeshNormalMaterial:Yl,MeshLambertMaterial:Xl,MeshDepthMaterial:Zl,MeshDistanceMaterial:Ql,MeshBasicMaterial:$a,MeshMatcapMaterial:$l,LineDashedMaterial:eu,LineBasicMaterial:hs,Material:Ta}[e]}},dd=class{static extractUrlBase(e){let t=e.lastIndexOf(`/`);return t===-1?`./`:e.slice(0,t+1)}static resolveURL(e,t){return typeof e!=`string`||e===``?``:(/^https?:\/\//i.test(t)&&/^\//.test(e)&&(t=t.replace(/(^https?:\/\/[^\/]+).*/i,`$1`)),/^(https?:)?\/\//i.test(e)||/^data:.*,.*$/i.test(e)||/^blob:.*$/i.test(e)?e:t+e)}},fd=class extends ba{constructor(){super(),this.isInstancedBufferGeometry=!0,this.type=`InstancedBufferGeometry`,this.instanceCount=1/0}copy(e){return super.copy(e),this.instanceCount=e.instanceCount,this}toJSON(){let e=super.toJSON();return e.instanceCount=this.instanceCount,e.isInstancedBufferGeometry=!0,e}},pd=class extends Ou{constructor(e){super(e)}load(e,t,n,r){let i=this,a=new ju(i.manager);a.setPath(i.path),a.setRequestHeader(i.requestHeader),a.setWithCredentials(i.withCredentials),a.load(e,function(n){try{t(i.parse(JSON.parse(n)))}catch(t){r?r(t):An(t),i.manager.itemError(e)}},n,r)}parse(e){let t={},n={};function r(e,n){if(t[n]!==void 0)return t[n];let r=e.interleavedBuffers[n],a=i(e,r.buffer),o=new xa(bn(r.type,a),r.stride);return o.uuid=r.uuid,t[n]=o,o}function i(e,t){if(n[t]!==void 0)return n[t];let r=e.arrayBuffers[t],i=new Uint32Array(r).buffer;return n[t]=i,i}let a=e.isInstancedBufferGeometry?new fd:new ba,o=e.data.index;if(o!==void 0){let e=bn(o.type,o.array);a.setIndex(new ea(e,1))}let s=e.data.attributes;for(let t in s){let n=s[t],i;if(n.isInterleavedBufferAttribute)i=new Ca(r(e.data,n.data),n.itemSize,n.offset,n.normalized);else{let e=bn(n.type,n.array);i=new(n.isInstancedBufferAttribute?Ao:ea)(e,n.itemSize,n.normalized)}n.name!==void 0&&(i.name=n.name),n.usage!==void 0&&i.setUsage(n.usage),a.setAttribute(t,i)}let c=e.data.morphAttributes;if(c)for(let t in c){let n=c[t],i=[];for(let t=0,a=n.length;t0){i=new Fu(new Eu(t)),i.setCrossOrigin(this.crossOrigin);for(let t=0,n=e.length;t0){r=new Fu(this.manager),r.setCrossOrigin(this.crossOrigin);for(let t=0,r=e.length;t{let t=null,n=null;return e.boundingBox!==void 0&&(t=new Ni().fromJSON(e.boundingBox)),e.boundingSphere!==void 0&&(n=new fa().fromJSON(e.boundingSphere)),{...e,boundingBox:t,boundingSphere:n}}),a._instanceInfo=e.instanceInfo,a._availableInstanceIds=e._availableInstanceIds,a._availableGeometryIds=e._availableGeometryIds,a._nextIndexStart=e.nextIndexStart,a._nextVertexStart=e.nextVertexStart,a._geometryCount=e.geometryCount,a._maxInstanceCount=e.maxInstanceCount,a._maxVertexCount=e.maxVertexCount,a._maxIndexCount=e.maxIndexCount,a._geometryInitialized=e.geometryInitialized,a._matricesTexture=c(e.matricesTexture.uuid),a._indirectTexture=c(e.indirectTexture.uuid),e.colorsTexture!==void 0&&(a._colorsTexture=c(e.colorsTexture.uuid)),e.boundingSphere!==void 0&&(a.boundingSphere=new fa().fromJSON(e.boundingSphere)),e.boundingBox!==void 0&&(a.boundingBox=new Ni().fromJSON(e.boundingBox));break;case`LOD`:a=new Wa;break;case`Line`:a=new Cs(o(e.geometry),s(e.material));break;case`LineLoop`:a=new Os(o(e.geometry),s(e.material));break;case`LineSegments`:a=new Ds(o(e.geometry),s(e.material));break;case`PointCloud`:case`Points`:a=new Ps(o(e.geometry),s(e.material));break;case`Sprite`:a=new Ba(s(e.material));break;case`Group`:a=new ci;break;case`Bone`:a=new To;break;default:a=new si}if(a.uuid=e.uuid,e.name!==void 0&&(a.name=e.name),e.matrix===void 0?(e.position!==void 0&&a.position.fromArray(e.position),e.rotation!==void 0&&a.rotation.fromArray(e.rotation),e.quaternion!==void 0&&a.quaternion.fromArray(e.quaternion),e.scale!==void 0&&a.scale.fromArray(e.scale)):(a.matrix.fromArray(e.matrix),e.matrixAutoUpdate!==void 0&&(a.matrixAutoUpdate=e.matrixAutoUpdate),a.matrixAutoUpdate&&a.matrix.decompose(a.position,a.quaternion,a.scale)),e.up!==void 0&&a.up.fromArray(e.up),e.pivot!==void 0&&(a.pivot=new H().fromArray(e.pivot)),e.morphTargetDictionary!==void 0&&(a.morphTargetDictionary=Object.assign({},e.morphTargetDictionary)),e.morphTargetInfluences!==void 0&&(a.morphTargetInfluences=e.morphTargetInfluences.slice()),e.castShadow!==void 0&&(a.castShadow=e.castShadow),e.receiveShadow!==void 0&&(a.receiveShadow=e.receiveShadow),e.shadow&&(e.shadow.intensity!==void 0&&(a.shadow.intensity=e.shadow.intensity),e.shadow.bias!==void 0&&(a.shadow.bias=e.shadow.bias),e.shadow.normalBias!==void 0&&(a.shadow.normalBias=e.shadow.normalBias),e.shadow.radius!==void 0&&(a.shadow.radius=e.shadow.radius),e.shadow.mapSize!==void 0&&a.shadow.mapSize.fromArray(e.shadow.mapSize),e.shadow.camera!==void 0&&(a.shadow.camera=this.parseObject(e.shadow.camera))),e.visible!==void 0&&(a.visible=e.visible),e.frustumCulled!==void 0&&(a.frustumCulled=e.frustumCulled),e.renderOrder!==void 0&&(a.renderOrder=e.renderOrder),e.static!==void 0&&(a.static=e.static),e.userData!==void 0&&(a.userData=e.userData),e.layers!==void 0&&(a.layers.mask=e.layers),e.children!==void 0){let o=e.children;for(let e=0;e`u`&&B(`ImageBitmapLoader: createImageBitmap() not supported.`),typeof fetch>`u`&&B(`ImageBitmapLoader: fetch() not supported.`),this.options={premultiplyAlpha:`none`},this._abortController=new AbortController}setOptions(e){return this.options=e,this}load(e,t,n,r){e===void 0&&(e=``),this.path!==void 0&&(e=this.path+e),e=this.manager.resolveURL(e);let i=this,a=wu.get(`image-bitmap:${e}`);if(a!==void 0){if(i.manager.itemStart(e),a.then){a.then(n=>{if(vd.has(a)===!0)r&&r(vd.get(a)),i.manager.itemError(e),i.manager.itemEnd(e);else return t&&t(n),i.manager.itemEnd(e),n});return}return setTimeout(function(){t&&t(a),i.manager.itemEnd(e)},0),a}let o={};o.credentials=this.crossOrigin===`anonymous`?`same-origin`:`include`,o.headers=this.requestHeader,o.signal=typeof AbortSignal.any==`function`?AbortSignal.any([this._abortController.signal,this.manager.abortController.signal]):this._abortController.signal;let s=fetch(e,o).then(function(e){return e.blob()}).then(function(e){return createImageBitmap(e,Object.assign(i.options,{colorSpaceConversion:`none`}))}).then(function(n){return wu.add(`image-bitmap:${e}`,n),t&&t(n),i.manager.itemEnd(e),n}).catch(function(t){r&&r(t),vd.set(s,t),wu.remove(`image-bitmap:${e}`),i.manager.itemError(e),i.manager.itemEnd(e)});wu.add(`image-bitmap:${e}`,s),i.manager.itemStart(e)}abort(){return this._abortController.abort(),this._abortController=new AbortController,this}},bd,xd=class{static getContext(){return bd===void 0&&(bd=new(window.AudioContext||window.webkitAudioContext)),bd}static setContext(e){bd=e}},Sd=class extends Ou{constructor(e){super(e)}load(e,t,n,r){let i=this,a=new ju(this.manager);a.setResponseType(`arraybuffer`),a.setPath(this.path),a.setRequestHeader(this.requestHeader),a.setWithCredentials(this.withCredentials),a.load(e,function(e){try{let n=e.slice(0);xd.getContext().decodeAudioData(n,function(e){t(e)}).catch(o)}catch(e){o(e)}},n,r);function o(t){r?r(t):An(t),i.manager.itemError(e)}}},Cd=new Pr,wd=new Pr,Td=new Pr,Ed=class{constructor(){this.type=`StereoCamera`,this.aspect=1,this.eyeSep=.064,this.cameraL=new Qu,this.cameraL.layers.enable(1),this.cameraL.matrixAutoUpdate=!1,this.cameraR=new Qu,this.cameraR.layers.enable(2),this.cameraR.matrixAutoUpdate=!1,this._cache={focus:null,fov:null,aspect:null,near:null,far:null,zoom:null,eyeSep:null}}update(e){let t=this._cache;if(t.focus!==e.focus||t.fov!==e.fov||t.aspect!==e.aspect*this.aspect||t.near!==e.near||t.far!==e.far||t.zoom!==e.zoom||t.eyeSep!==this.eyeSep){t.focus=e.focus,t.fov=e.fov,t.aspect=e.aspect*this.aspect,t.near=e.near,t.far=e.far,t.zoom=e.zoom,t.eyeSep=this.eyeSep,Td.copy(e.projectionMatrix);let n=t.eyeSep/2,r=n*t.near/t.focus,i=t.near*Math.tan(Ln*t.fov*.5)/t.zoom,a,o;wd.elements[12]=-n,Cd.elements[12]=n,a=-i*t.aspect+r,o=i*t.aspect+r,Td.elements[0]=2*t.near/(o-a),Td.elements[8]=(o+a)/(o-a),this.cameraL.projectionMatrix.copy(Td),a=-i*t.aspect-r,o=i*t.aspect-r,Td.elements[0]=2*t.near/(o-a),Td.elements[8]=(o+a)/(o-a),this.cameraR.projectionMatrix.copy(Td)}this.cameraL.matrixWorld.copy(e.matrixWorld).multiply(wd),this.cameraR.matrixWorld.copy(e.matrixWorld).multiply(Cd)}},Dd=-90,Od=1,kd=class extends si{constructor(e,t,n){super(),this.type=`CubeCamera`,this.renderTarget=n,this.coordinateSystem=null,this.activeMipmapLevel=0;let r=new Qu(Dd,Od,e,t);r.layers=this.layers,this.add(r);let i=new Qu(Dd,Od,e,t);i.layers=this.layers,this.add(i);let a=new Qu(Dd,Od,e,t);a.layers=this.layers,this.add(a);let o=new Qu(Dd,Od,e,t);o.layers=this.layers,this.add(o);let s=new Qu(Dd,Od,e,t);s.layers=this.layers,this.add(s);let c=new Qu(Dd,Od,e,t);c.layers=this.layers,this.add(c)}updateCoordinateSystem(){let e=this.coordinateSystem,t=this.children.concat(),[n,r,i,a,o,s]=t;for(let e of t)this.remove(e);if(e===2e3)n.up.set(0,1,0),n.lookAt(1,0,0),r.up.set(0,1,0),r.lookAt(-1,0,0),i.up.set(0,0,-1),i.lookAt(0,1,0),a.up.set(0,0,1),a.lookAt(0,-1,0),o.up.set(0,1,0),o.lookAt(0,0,1),s.up.set(0,1,0),s.lookAt(0,0,-1);else if(e===2001)n.up.set(0,-1,0),n.lookAt(-1,0,0),r.up.set(0,-1,0),r.lookAt(1,0,0),i.up.set(0,0,1),i.lookAt(0,1,0),a.up.set(0,0,-1),a.lookAt(0,-1,0),o.up.set(0,-1,0),o.lookAt(0,0,1),s.up.set(0,-1,0),s.lookAt(0,0,-1);else throw Error(`THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: `+e);for(let e of t)this.add(e),e.updateMatrixWorld()}update(e,t){this.parent===null&&this.updateMatrixWorld();let{renderTarget:n,activeMipmapLevel:r}=this;this.coordinateSystem!==e.coordinateSystem&&(this.coordinateSystem=e.coordinateSystem,this.updateCoordinateSystem());let[i,a,o,s,c,l]=this.children,u=e.getRenderTarget(),d=e.getActiveCubeFace(),f=e.getActiveMipmapLevel(),p=e.xr.enabled;e.xr.enabled=!1;let m=n.texture.generateMipmaps;n.texture.generateMipmaps=!1;let h=!1;h=e.isWebGLRenderer===!0?e.state.buffers.depth.getReversed():e.reversedDepthBuffer,e.setRenderTarget(n,0,r),h&&e.autoClear===!1&&e.clearDepth(),e.render(t,i),e.setRenderTarget(n,1,r),h&&e.autoClear===!1&&e.clearDepth(),e.render(t,a),e.setRenderTarget(n,2,r),h&&e.autoClear===!1&&e.clearDepth(),e.render(t,o),e.setRenderTarget(n,3,r),h&&e.autoClear===!1&&e.clearDepth(),e.render(t,s),e.setRenderTarget(n,4,r),h&&e.autoClear===!1&&e.clearDepth(),e.render(t,c),n.texture.generateMipmaps=m,e.setRenderTarget(n,5,r),h&&e.autoClear===!1&&e.clearDepth(),e.render(t,l),e.setRenderTarget(u,d,f),e.xr.enabled=p,n.texture.needsPMREMUpdate=!0}},Ad=class extends Qu{constructor(e=[]){super(),this.isArrayCamera=!0,this.isMultiViewCamera=!1,this.cameras=e}},jd=class{constructor(){this._previousTime=0,this._currentTime=0,this._startTime=performance.now(),this._delta=0,this._elapsed=0,this._timescale=1,this._document=null,this._pageVisibilityHandler=null}connect(e){this._document=e,e.hidden!==void 0&&(this._pageVisibilityHandler=Md.bind(this),e.addEventListener(`visibilitychange`,this._pageVisibilityHandler,!1))}disconnect(){this._pageVisibilityHandler!==null&&(this._document.removeEventListener(`visibilitychange`,this._pageVisibilityHandler),this._pageVisibilityHandler=null),this._document=null}getDelta(){return this._delta/1e3}getElapsed(){return this._elapsed/1e3}getTimescale(){return this._timescale}setTimescale(e){return this._timescale=e,this}reset(){return this._currentTime=performance.now()-this._startTime,this}dispose(){this.disconnect()}update(e){return this._pageVisibilityHandler!==null&&this._document.hidden===!0?this._delta=0:(this._previousTime=this._currentTime,this._currentTime=(e===void 0?performance.now():e)-this._startTime,this._delta=(this._currentTime-this._previousTime)*this._timescale,this._elapsed+=this._delta),this}};function Md(){this._document.hidden===!1&&this.reset()}var Nd=new H,Pd=new cr,Fd=new H,Id=new H,Ld=new H,Rd=class extends si{constructor(){super(),this.type=`AudioListener`,this.context=xd.getContext(),this.gain=this.context.createGain(),this.gain.connect(this.context.destination),this.filter=null,this.timeDelta=0,this._timer=new jd}getInput(){return this.gain}removeFilter(){return this.filter!==null&&(this.gain.disconnect(this.filter),this.filter.disconnect(this.context.destination),this.gain.connect(this.context.destination),this.filter=null),this}getFilter(){return this.filter}setFilter(e){return this.filter===null?this.gain.disconnect(this.context.destination):(this.gain.disconnect(this.filter),this.filter.disconnect(this.context.destination)),this.filter=e,this.gain.connect(this.filter),this.filter.connect(this.context.destination),this}getMasterVolume(){return this.gain.gain.value}setMasterVolume(e){return this.gain.gain.setTargetAtTime(e,this.context.currentTime,.01),this}updateMatrixWorld(e){super.updateMatrixWorld(e),this._timer.update();let t=this.context.listener;if(this.timeDelta=this._timer.getDelta(),this.matrixWorld.decompose(Nd,Pd,Fd),Id.set(0,0,-1).applyQuaternion(Pd),Ld.set(0,1,0).applyQuaternion(Pd),t.positionX){let e=this.context.currentTime+this.timeDelta;t.positionX.linearRampToValueAtTime(Nd.x,e),t.positionY.linearRampToValueAtTime(Nd.y,e),t.positionZ.linearRampToValueAtTime(Nd.z,e),t.forwardX.linearRampToValueAtTime(Id.x,e),t.forwardY.linearRampToValueAtTime(Id.y,e),t.forwardZ.linearRampToValueAtTime(Id.z,e),t.upX.linearRampToValueAtTime(Ld.x,e),t.upY.linearRampToValueAtTime(Ld.y,e),t.upZ.linearRampToValueAtTime(Ld.z,e)}else t.setPosition(Nd.x,Nd.y,Nd.z),t.setOrientation(Id.x,Id.y,Id.z,Ld.x,Ld.y,Ld.z)}},zd=class extends si{constructor(e){super(),this.type=`Audio`,this.listener=e,this.context=e.context,this.gain=this.context.createGain(),this.gain.connect(e.getInput()),this.autoplay=!1,this.buffer=null,this.detune=0,this.loop=!1,this.loopStart=0,this.loopEnd=0,this.offset=0,this.duration=void 0,this.playbackRate=1,this.isPlaying=!1,this.hasPlaybackControl=!0,this.source=null,this.sourceType=`empty`,this._startedAt=0,this._progress=0,this._connected=!1,this.filters=[]}getOutput(){return this.gain}setNodeSource(e){return this.hasPlaybackControl=!1,this.sourceType=`audioNode`,this.source=e,this.connect(),this}setMediaElementSource(e){return this.hasPlaybackControl=!1,this.sourceType=`mediaNode`,this.source=this.context.createMediaElementSource(e),this.connect(),this}setMediaStreamSource(e){return this.hasPlaybackControl=!1,this.sourceType=`mediaStreamNode`,this.source=this.context.createMediaStreamSource(e),this.connect(),this}setBuffer(e){return this.buffer=e,this.sourceType=`buffer`,this.autoplay&&this.play(),this}play(e=0){if(this.isPlaying===!0){B(`Audio: Audio is already playing.`);return}if(this.hasPlaybackControl===!1){B(`Audio: this Audio has no playback control.`);return}this._startedAt=this.context.currentTime+e;let t=this.context.createBufferSource();return t.buffer=this.buffer,t.loop=this.loop,t.loopStart=this.loopStart,t.loopEnd=this.loopEnd,t.onended=this.onEnded.bind(this),t.start(this._startedAt,this._progress+this.offset,this.duration),this.isPlaying=!0,this.source=t,this.setDetune(this.detune),this.setPlaybackRate(this.playbackRate),this.connect()}pause(){if(this.hasPlaybackControl===!1){B(`Audio: this Audio has no playback control.`);return}return this.isPlaying===!0&&(this._progress+=Math.max(this.context.currentTime-this._startedAt,0)*this.playbackRate,this.loop===!0&&(this._progress%=this.duration||this.buffer.duration),this.source.stop(),this.source.onended=null,this.isPlaying=!1),this}stop(e=0){if(this.hasPlaybackControl===!1){B(`Audio: this Audio has no playback control.`);return}return this._progress=0,this.source!==null&&(this.source.stop(this.context.currentTime+e),this.source.onended=null),this.isPlaying=!1,this}connect(){if(this.filters.length>0){this.source.connect(this.filters[0]);for(let e=1,t=this.filters.length;e0){this.source.disconnect(this.filters[0]);for(let e=1,t=this.filters.length;e0&&this._mixBufferRegionAdditive(n,r,this._addIndex*t,1,t);for(let e=t,i=t+t;e!==i;++e)if(n[e]!==n[e+t]){o.setValue(n,r);break}}saveOriginalState(){let e=this.binding,t=this.buffer,n=this.valueSize,r=n*this._origIndex;e.getValue(t,r);for(let e=n,i=r;e!==i;++e)t[e]=t[r+e%n];this._setIdentity(),this.cumulativeWeight=0,this.cumulativeWeightAdditive=0}restoreOriginalState(){let e=this.valueSize*3;this.binding.setValue(this.buffer,e)}_setAdditiveIdentityNumeric(){let e=this._addIndex*this.valueSize,t=e+this.valueSize;for(let n=e;n=.5)for(let r=0;r!==i;++r)e[t+r]=e[n+r]}_slerp(e,t,n,r){cr.slerpFlat(e,t,e,t,e,n,r)}_slerpAdditive(e,t,n,r,i){let a=this._workIndex*i;cr.multiplyQuaternionsFlat(e,a,e,t,e,n),cr.slerpFlat(e,t,e,t,e,a,r)}_lerp(e,t,n,r,i){let a=1-r;for(let o=0;o!==i;++o){let i=t+o;e[i]=e[i]*a+e[n+o]*r}}_lerpAdditive(e,t,n,r,i){for(let a=0;a!==i;++a){let i=t+a;e[i]=e[i]+e[n+a]*r}}},qd=`\\[\\]\\.:\\/`,Jd=RegExp(`[`+qd+`]`,`g`),Yd=`[^`+qd+`]`,Xd=`[^`+qd.replace(`\\.`,``)+`]`,Zd=`((?:WC+[\\/:])*)`.replace(`WC`,Yd),Qd=`(WCOD+)?`.replace(`WCOD`,Xd),$d=`(?:\\.(WC+)(?:\\[(.+)\\])?)?`.replace(`WC`,Yd),ef=`\\.(WC+)(?:\\[(.+)\\])?`.replace(`WC`,Yd),tf=RegExp(`^`+Zd+Qd+$d+ef+`$`),nf=[`material`,`materials`,`bones`,`map`],rf=class{constructor(e,t,n){let r=n||af.parseTrackName(t);this._targetGroup=e,this._bindings=e.subscribe_(t,r)}getValue(e,t){this.bind();let n=this._targetGroup.nCachedObjects_,r=this._bindings[n];r!==void 0&&r.getValue(e,t)}setValue(e,t){let n=this._bindings;for(let r=this._targetGroup.nCachedObjects_,i=n.length;r!==i;++r)n[r].setValue(e,t)}bind(){let e=this._bindings;for(let t=this._targetGroup.nCachedObjects_,n=e.length;t!==n;++t)e[t].bind()}unbind(){let e=this._bindings;for(let t=this._targetGroup.nCachedObjects_,n=e.length;t!==n;++t)e[t].unbind()}},af=class e{constructor(t,n,r){this.path=n,this.parsedPath=r||e.parseTrackName(n),this.node=e.findNode(t,this.parsedPath.nodeName),this.rootNode=t,this.getValue=this._getValue_unbound,this.setValue=this._setValue_unbound}static create(t,n,r){return t&&t.isAnimationObjectGroup?new e.Composite(t,n,r):new e(t,n,r)}static sanitizeNodeName(e){return e.replace(/\s/g,`_`).replace(Jd,``)}static parseTrackName(e){let t=tf.exec(e);if(t===null)throw Error(`PropertyBinding: Cannot parse trackName: `+e);let n={nodeName:t[2],objectName:t[3],objectIndex:t[4],propertyName:t[5],propertyIndex:t[6]},r=n.nodeName&&n.nodeName.lastIndexOf(`.`);if(r!==void 0&&r!==-1){let e=n.nodeName.substring(r+1);nf.indexOf(e)!==-1&&(n.nodeName=n.nodeName.substring(0,r),n.objectName=e)}if(n.propertyName===null||n.propertyName.length===0)throw Error(`PropertyBinding: can not parse propertyName from trackName: `+e);return n}static findNode(e,t){if(t===void 0||t===``||t===`.`||t===-1||t===e.name||t===e.uuid)return e;if(e.skeleton){let n=e.skeleton.getBoneByName(t);if(n!==void 0)return n}if(e.children){let n=function(e){for(let r=0;r=i){let a=i++,l=e[a];t[l.uuid]=c,e[c]=l,t[s]=a,e[a]=o;for(let e=0,t=r;e!==t;++e){let t=n[e],r=t[a],i=t[c];t[c]=r,t[a]=i}}}this.nCachedObjects_=i}uncache(){let e=this._objects,t=this._indicesByUUID,n=this._bindings,r=n.length,i=this.nCachedObjects_,a=e.length;for(let o=0,s=arguments.length;o!==s;++o){let s=arguments[o].uuid,c=t[s];if(c!==void 0)if(delete t[s],c0&&(t[o.uuid]=c),e[c]=o,e.pop();for(let e=0,t=r;e!==t;++e){let t=n[e];t[c]=t[i],t.pop()}}}this.nCachedObjects_=i}subscribe_(e,t){let n=this._bindingsIndicesByPath,r=n[e],i=this._bindings;if(r!==void 0)return i[r];let a=this._paths,o=this._parsedPaths,s=this._objects,c=s.length,l=this.nCachedObjects_,u=Array(c);r=i.length,n[e]=r,a.push(e),o.push(t),i.push(u);for(let n=l,r=s.length;n!==r;++n){let r=s[n];u[n]=new af(r,e,t)}return u}unsubscribe_(e){let t=this._bindingsIndicesByPath,n=t[e];if(n!==void 0){let r=this._paths,i=this._parsedPaths,a=this._bindings,o=a.length-1,s=a[o],c=e[o];t[c]=n,a[n]=s,a.pop(),i[n]=i[o],i.pop(),r[n]=r[o],r.pop()}}},sf=class{constructor(e,t,n=null,r=t.blendMode){this._mixer=e,this._clip=t,this._localRoot=n,this.blendMode=r;let i=t.tracks,a=i.length,o=Array(a),s={endingStart:Ft,endingEnd:Ft};for(let e=0;e!==a;++e){let t=i[e].createInterpolant(null);o[e]=t,t.settings=s}this._interpolantSettings=s,this._interpolants=o,this._propertyBindings=Array(a),this._cacheIndex=null,this._byClipCacheIndex=null,this._timeScaleInterpolant=null,this._weightInterpolant=null,this.loop=kt,this._loopCount=-1,this._startTime=null,this.time=0,this.timeScale=1,this._effectiveTimeScale=1,this.weight=1,this._effectiveWeight=1,this.repetitions=1/0,this.paused=!1,this.enabled=!0,this.clampWhenFinished=!1,this.zeroSlopeAtStart=!0,this.zeroSlopeAtEnd=!0}play(){return this._mixer._activateAction(this),this}stop(){return this._mixer._deactivateAction(this),this.reset()}reset(){return this.paused=!1,this.enabled=!0,this.time=0,this._loopCount=-1,this._startTime=null,this.stopFading().stopWarping()}isRunning(){return this.enabled&&!this.paused&&this.timeScale!==0&&this._startTime===null&&this._mixer._isActiveAction(this)}isScheduled(){return this._mixer._isActiveAction(this)}startAt(e){return this._startTime=e,this}setLoop(e,t){return this.loop=e,this.repetitions=t,this}setEffectiveWeight(e){return this.weight=e,this._effectiveWeight=this.enabled?e:0,this.stopFading()}getEffectiveWeight(){return this._effectiveWeight}fadeIn(e){return this._scheduleFading(e,0,1)}fadeOut(e){return this._scheduleFading(e,1,0)}crossFadeFrom(e,t,n=!1){if(e.fadeOut(t),this.fadeIn(t),n===!0){let n=this._clip.duration,r=e._clip.duration,i=r/n,a=n/r;e.warp(1,i,t),this.warp(a,1,t)}return this}crossFadeTo(e,t,n=!1){return e.crossFadeFrom(this,t,n)}stopFading(){let e=this._weightInterpolant;return e!==null&&(this._weightInterpolant=null,this._mixer._takeBackControlInterpolant(e)),this}setEffectiveTimeScale(e){return this.timeScale=e,this._effectiveTimeScale=this.paused?0:e,this.stopWarping()}getEffectiveTimeScale(){return this._effectiveTimeScale}setDuration(e){return this.timeScale=this._clip.duration/e,this.stopWarping()}syncWith(e){return this.time=e.time,this.timeScale=e.timeScale,this.stopWarping()}halt(e){return this.warp(this._effectiveTimeScale,0,e)}warp(e,t,n){let r=this._mixer,i=r.time,a=this.timeScale,o=this._timeScaleInterpolant;o===null&&(o=r._lendControlInterpolant(),this._timeScaleInterpolant=o);let s=o.parameterPositions,c=o.sampleValues;return s[0]=i,s[1]=i+n,c[0]=e/a,c[1]=t/a,this}stopWarping(){let e=this._timeScaleInterpolant;return e!==null&&(this._timeScaleInterpolant=null,this._mixer._takeBackControlInterpolant(e)),this}getMixer(){return this._mixer}getClip(){return this._clip}getRoot(){return this._localRoot||this._mixer._root}_update(e,t,n,r){if(!this.enabled){this._updateWeight(e);return}let i=this._startTime;if(i!==null){let r=(e-i)*n;r<0||n===0?t=0:(this._startTime=null,t=n*r)}t*=this._updateTimeScale(e);let a=this._updateTime(t),o=this._updateWeight(e);if(o>0){let e=this._interpolants,t=this._propertyBindings;switch(this.blendMode){case zt:for(let n=0,r=e.length;n!==r;++n)e[n].evaluate(a),t[n].accumulateAdditive(o);break;case Rt:default:for(let n=0,i=e.length;n!==i;++n)e[n].evaluate(a),t[n].accumulate(r,o)}}}_updateWeight(e){let t=0;if(this.enabled){t=this.weight;let n=this._weightInterpolant;if(n!==null){let r=n.evaluate(e)[0];t*=r,e>n.parameterPositions[1]&&(this.stopFading(),r===0&&(this.enabled=!1))}}return this._effectiveWeight=t,t}_updateTimeScale(e){let t=0;if(!this.paused){t=this.timeScale;let n=this._timeScaleInterpolant;if(n!==null){let r=n.evaluate(e)[0];t*=r,e>n.parameterPositions[1]&&(this.stopWarping(),t===0?this.paused=!0:this.timeScale=t)}}return this._effectiveTimeScale=t,t}_updateTime(e){let t=this._clip.duration,n=this.loop,r=this.time+e,i=this._loopCount,a=n===At;if(e===0)return i===-1?r:a&&(i&1)==1?t-r:r;if(n===2200){i===-1&&(this._loopCount=0,this._setEndings(!0,!0,!1));handle_stop:{if(r>=t)r=t;else if(r<0)r=0;else{this.time=r;break handle_stop}this.clampWhenFinished?this.paused=!0:this.enabled=!1,this.time=r,this._mixer.dispatchEvent({type:`finished`,action:this,direction:e<0?-1:1})}}else{if(i===-1&&(e>=0?(i=0,this._setEndings(!0,this.repetitions===0,a)):this._setEndings(this.repetitions===0,!0,a)),r>=t||r<0){let n=Math.floor(r/t);r-=t*n,i+=Math.abs(n);let o=this.repetitions-i;if(o<=0)this.clampWhenFinished?this.paused=!0:this.enabled=!1,r=e>0?t:0,this.time=r,this._mixer.dispatchEvent({type:`finished`,action:this,direction:e>0?1:-1});else{if(o===1){let t=e<0;this._setEndings(t,!t,a)}else this._setEndings(!1,!1,a);this._loopCount=i,this.time=r,this._mixer.dispatchEvent({type:`loop`,action:this,loopDelta:n})}}else this.time=r;if(a&&(i&1)==1)return t-r}return r}_setEndings(e,t,n){let r=this._interpolantSettings;n?(r.endingStart=It,r.endingEnd=It):(e?r.endingStart=this.zeroSlopeAtStart?It:Ft:r.endingStart=Lt,t?r.endingEnd=this.zeroSlopeAtEnd?It:Ft:r.endingEnd=Lt)}_scheduleFading(e,t,n){let r=this._mixer,i=r.time,a=this._weightInterpolant;a===null&&(a=r._lendControlInterpolant(),this._weightInterpolant=a);let o=a.parameterPositions,s=a.sampleValues;return o[0]=i,s[0]=t,o[1]=i+e,s[1]=n,this}},cf=new Float32Array(1),lf=class extends Pn{constructor(e){super(),this._root=e,this._initMemoryManager(),this._accuIndex=0,this.time=0,this.timeScale=1,typeof __THREE_DEVTOOLS__<`u`&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent(`observe`,{detail:this}))}_bindAction(e,t){let n=e._localRoot||this._root,r=e._clip.tracks,i=r.length,a=e._propertyBindings,o=e._interpolants,s=n.uuid,c=this._bindingsByRootAndName,l=c[s];l===void 0&&(l={},c[s]=l);for(let e=0;e!==i;++e){let i=r[e],c=i.name,u=l[c];if(u!==void 0)++u.referenceCount,a[e]=u;else{if(u=a[e],u!==void 0){u._cacheIndex===null&&(++u.referenceCount,this._addInactiveBinding(u,s,c));continue}let r=t&&t._propertyBindings[e].binding.parsedPath;u=new Kd(af.create(n,c,r),i.ValueTypeName,i.getValueSize()),++u.referenceCount,this._addInactiveBinding(u,s,c),a[e]=u}o[e].resultBuffer=u.buffer}}_activateAction(e){if(!this._isActiveAction(e)){if(e._cacheIndex===null){let t=(e._localRoot||this._root).uuid,n=e._clip.uuid,r=this._actionsByClip[n];this._bindAction(e,r&&r.knownActions[0]),this._addInactiveAction(e,n,t)}let t=e._propertyBindings;for(let e=0,n=t.length;e!==n;++e){let n=t[e];n.useCount++===0&&(this._lendBinding(n),n.saveOriginalState())}this._lendAction(e)}}_deactivateAction(e){if(this._isActiveAction(e)){let t=e._propertyBindings;for(let e=0,n=t.length;e!==n;++e){let n=t[e];--n.useCount===0&&(n.restoreOriginalState(),this._takeBackBinding(n))}this._takeBackAction(e)}}_initMemoryManager(){this._actions=[],this._nActiveActions=0,this._actionsByClip={},this._bindings=[],this._nActiveBindings=0,this._bindingsByRootAndName={},this._controlInterpolants=[],this._nActiveControlInterpolants=0;let e=this;this.stats={actions:{get total(){return e._actions.length},get inUse(){return e._nActiveActions}},bindings:{get total(){return e._bindings.length},get inUse(){return e._nActiveBindings}},controlInterpolants:{get total(){return e._controlInterpolants.length},get inUse(){return e._nActiveControlInterpolants}}}}_isActiveAction(e){let t=e._cacheIndex;return t!==null&&t=0;--n)e[n].stop();return this}update(e){e*=this.timeScale;let t=this._actions,n=this._nActiveActions,r=this.time+=e,i=Math.sign(e),a=this._accuIndex^=1;for(let o=0;o!==n;++o)t[o]._update(r,e,i,a);let o=this._bindings,s=this._nActiveBindings;for(let e=0;e!==s;++e)o[e].apply(a);return this}setTime(e){this.time=0;for(let e=0;e=this.min.x&&e.x<=this.max.x&&e.y>=this.min.y&&e.y<=this.max.y}containsBox(e){return this.min.x<=e.min.x&&e.max.x<=this.max.x&&this.min.y<=e.min.y&&e.max.y<=this.max.y}getParameter(e,t){return t.set((e.x-this.min.x)/(this.max.x-this.min.x),(e.y-this.min.y)/(this.max.y-this.min.y))}intersectsBox(e){return e.max.x>=this.min.x&&e.min.x<=this.max.x&&e.max.y>=this.min.y&&e.min.y<=this.max.y}clampPoint(e,t){return t.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return this.clampPoint(e,wf).distanceTo(e)}intersect(e){return this.min.max(e.min),this.max.min(e.max),this.isEmpty()&&this.makeEmpty(),this}union(e){return this.min.min(e.min),this.max.max(e.max),this}translate(e){return this.min.add(e),this.max.add(e),this}equals(e){return e.min.equals(this.min)&&e.max.equals(this.max)}},Ef=new H,Df=new H,Of=new H,kf=new H,Af=new H,jf=new H,Mf=new H,Nf=class{constructor(e=new H,t=new H){this.start=e,this.end=t}set(e,t){return this.start.copy(e),this.end.copy(t),this}copy(e){return this.start.copy(e.start),this.end.copy(e.end),this}getCenter(e){return e.addVectors(this.start,this.end).multiplyScalar(.5)}delta(e){return e.subVectors(this.end,this.start)}distanceSq(){return this.start.distanceToSquared(this.end)}distance(){return this.start.distanceTo(this.end)}at(e,t){return this.delta(t).multiplyScalar(e).add(this.start)}closestPointToPointParameter(e,t){Ef.subVectors(e,this.start),Df.subVectors(this.end,this.start);let n=Df.dot(Df),r=Df.dot(Ef)/n;return t&&(r=Bn(r,0,1)),r}closestPointToPoint(e,t,n){let r=this.closestPointToPointParameter(e,t);return this.delta(n).multiplyScalar(r).add(this.start)}distanceSqToLine3(e,t=jf,n=Mf){let r=1e-8*1e-8,i,a,o=this.start,s=e.start,c=this.end,l=e.end;Of.subVectors(c,o),kf.subVectors(l,s),Af.subVectors(o,s);let u=Of.dot(Of),d=kf.dot(kf),f=kf.dot(Af);if(u<=r&&d<=r)return t.copy(o),n.copy(s),t.sub(n),t.dot(t);if(u<=r)i=0,a=f/d,a=Bn(a,0,1);else{let e=Of.dot(Af);if(d<=r)a=0,i=Bn(-e/u,0,1);else{let t=Of.dot(kf),n=u*d-t*t;i=n===0?0:Bn((t*f-e*d)/n,0,1),a=(t*i+f)/d,a<0?(a=0,i=Bn(-e/u,0,1)):a>1&&(a=1,i=Bn((t-e)/u,0,1))}}return t.copy(o).addScaledVector(Of,i),n.copy(s).addScaledVector(kf,a),t.distanceToSquared(n)}applyMatrix4(e){return this.start.applyMatrix4(e),this.end.applyMatrix4(e),this}equals(e){return e.start.equals(this.start)&&e.end.equals(this.end)}clone(){return new this.constructor().copy(this)}},Pf=new H,Ff=class extends si{constructor(e,t){super(),this.light=e,this.matrixAutoUpdate=!1,this.color=t,this.type=`SpotLightHelper`;let n=new ba,r=[0,0,0,0,0,1,0,0,0,1,0,1,0,0,0,-1,0,1,0,0,0,0,1,1,0,0,0,0,-1,1];for(let e=0,t=1;e<32;e++,t++){let n=e/32*Math.PI*2,i=t/32*Math.PI*2;r.push(Math.cos(n),Math.sin(n),1,Math.cos(i),Math.sin(i),1)}n.setAttribute(`position`,new K(r,3)),this.cone=new Ds(n,new hs({fog:!1,toneMapped:!1})),this.add(this.cone),this.update()}dispose(){this.cone.geometry.dispose(),this.cone.material.dispose()}update(){this.light.updateWorldMatrix(!0,!1),this.light.target.updateWorldMatrix(!0,!1),this.parent?(this.parent.updateWorldMatrix(!0),this.matrix.copy(this.parent.matrixWorld).invert().multiply(this.light.matrixWorld)):this.matrix.copy(this.light.matrixWorld),this.matrixWorld.copy(this.light.matrixWorld);let e=this.light.distance?this.light.distance:1e3,t=e*Math.tan(this.light.angle);this.cone.scale.set(t,t,e),Pf.setFromMatrixPosition(this.light.target.matrixWorld),this.cone.lookAt(Pf),this.color===void 0?this.cone.material.color.copy(this.light.color):this.cone.material.color.set(this.color)}},If=new H,Lf=new Pr,Rf=new Pr,zf=class extends Ds{constructor(e){let t=Bf(e),n=new ba,r=[],i=[];for(let e=0;e1)for(let n=0;n.99999)this.quaternion.set(0,0,0,1);else if(e.y<-.99999)this.quaternion.set(1,0,0,0);else{op.set(e.z,0,-e.x).normalize();let t=Math.acos(e.y);this.quaternion.setFromAxisAngle(op,t)}}setLength(e,t=e*.2,n=t*.2){this.line.scale.set(1,Math.max(1e-4,e-t),1),this.line.updateMatrix(),this.cone.scale.set(n,t,n),this.cone.position.y=e,this.cone.updateMatrix()}setColor(e){this.line.material.color.set(e),this.cone.material.color.set(e)}copy(e){return super.copy(e,!1),this.line.copy(e.line),this.cone.copy(e.cone),this}dispose(){this.line.geometry.dispose(),this.line.material.dispose(),this.cone.geometry.dispose(),this.cone.material.dispose()}},up=class extends Ds{constructor(e=1){let t=[0,0,0,e,0,0,0,0,0,0,e,0,0,0,0,0,0,e],n=[1,0,0,1,.6,0,0,1,0,.6,1,0,0,0,1,0,.6,1],r=new ba;r.setAttribute(`position`,new K(t,3)),r.setAttribute(`color`,new K(n,3));let i=new hs({vertexColors:!0,toneMapped:!1});super(r,i),this.type=`AxesHelper`}setColors(e,t,n){let r=new U,i=this.geometry.attributes.color.array;return r.set(e),r.toArray(i,0),r.toArray(i,3),r.set(t),r.toArray(i,6),r.toArray(i,9),r.set(n),r.toArray(i,12),r.toArray(i,15),this.geometry.attributes.color.needsUpdate=!0,this}dispose(){this.geometry.dispose(),this.material.dispose()}},dp=class{constructor(){this.type=`ShapePath`,this.color=new U,this.subPaths=[],this.currentPath=null}moveTo(e,t){return this.currentPath=new Nc,this.subPaths.push(this.currentPath),this.currentPath.moveTo(e,t),this}lineTo(e,t){return this.currentPath.lineTo(e,t),this}quadraticCurveTo(e,t,n,r){return this.currentPath.quadraticCurveTo(e,t,n,r),this}bezierCurveTo(e,t,n,r,i,a){return this.currentPath.bezierCurveTo(e,t,n,r,i,a),this}splineThru(e){return this.currentPath.splineThru(e),this}toShapes(e){function t(e){let t=[];for(let n=0,r=e.length;n2**-52){if(c<0&&(n=t[a],s=-s,o=t[i],c=-c),e.yo.y)continue;if(e.y===n.y){if(e.x===n.x)return!0}else{let t=c*(e.x-n.x)-s*(e.y-n.y);if(t===0)return!0;if(t<0)continue;r=!r}}else{if(e.y!==n.y)continue;if(o.x<=e.x&&e.x<=n.x||n.x<=e.x&&e.x<=o.x)return!0}}return r}let r=hl.isClockWise,i=this.subPaths;if(i.length===0)return[];let a,o,s,c=[];if(i.length===1)return o=i[0],s=new Pc,s.curves=o.curves,c.push(s),c;let l=!r(i[0].getPoints());l=e?!l:l;let u=[],d=[],f=[],p=0,m;d[p]=void 0,f[p]=[];for(let t=0,n=i.length;t1){let e=!1,t=0;for(let e=0,t=d.length;e0&&e===!1&&(f=u)}let h;for(let e=0,t=d.length;et?(e.repeat.x=1,e.repeat.y=n/t,e.offset.x=0,e.offset.y=(1-e.repeat.y)/2):(e.repeat.x=t/n,e.repeat.y=1,e.offset.x=(1-e.repeat.x)/2,e.offset.y=0),e}function mp(e,t){let n=e.image&&e.image.width?e.image.width/e.image.height:1;return n>t?(e.repeat.x=t/n,e.repeat.y=1,e.offset.x=(1-e.repeat.x)/2,e.offset.y=0):(e.repeat.x=1,e.repeat.y=n/t,e.offset.x=0,e.offset.y=(1-e.repeat.y)/2),e}function hp(e){return e.repeat.x=1,e.repeat.y=1,e.offset.x=0,e.offset.y=0,e}function gp(e,t,n,r){let i=_p(r);switch(n){case Fe:return e*t;case Be:return e*t/i.components*i.byteLength;case Ve:return e*t/i.components*i.byteLength;case He:return e*t*2/i.components*i.byteLength;case Ue:return e*t*2/i.components*i.byteLength;case Ie:return e*t*3/i.components*i.byteLength;case Le:return e*t*4/i.components*i.byteLength;case Ge:return e*t*4/i.components*i.byteLength;case Ke:case qe:return Math.floor((e+3)/4)*Math.floor((t+3)/4)*8;case Je:case Ye:return Math.floor((e+3)/4)*Math.floor((t+3)/4)*16;case Ze:case $e:return Math.max(e,16)*Math.max(t,8)/4;case Xe:case Qe:return Math.max(e,8)*Math.max(t,8)/2;case et:case tt:case rt:case it:return Math.floor((e+3)/4)*Math.floor((t+3)/4)*8;case nt:case at:case ot:return Math.floor((e+3)/4)*Math.floor((t+3)/4)*16;case st:return Math.floor((e+3)/4)*Math.floor((t+3)/4)*16;case ct:return Math.floor((e+4)/5)*Math.floor((t+3)/4)*16;case lt:return Math.floor((e+4)/5)*Math.floor((t+4)/5)*16;case ut:return Math.floor((e+5)/6)*Math.floor((t+4)/5)*16;case dt:return Math.floor((e+5)/6)*Math.floor((t+5)/6)*16;case ft:return Math.floor((e+7)/8)*Math.floor((t+4)/5)*16;case pt:return Math.floor((e+7)/8)*Math.floor((t+5)/6)*16;case mt:return Math.floor((e+7)/8)*Math.floor((t+7)/8)*16;case ht:return Math.floor((e+9)/10)*Math.floor((t+4)/5)*16;case gt:return Math.floor((e+9)/10)*Math.floor((t+5)/6)*16;case _t:return Math.floor((e+9)/10)*Math.floor((t+7)/8)*16;case vt:return Math.floor((e+9)/10)*Math.floor((t+9)/10)*16;case yt:return Math.floor((e+11)/12)*Math.floor((t+9)/10)*16;case bt:return Math.floor((e+11)/12)*Math.floor((t+11)/12)*16;case xt:case St:case Ct:return Math.ceil(e/4)*Math.ceil(t/4)*16;case wt:case Tt:return Math.ceil(e/4)*Math.ceil(t/4)*8;case Et:case Dt:return Math.ceil(e/4)*Math.ceil(t/4)*16}throw Error(`Unable to determine texture byte length for ${n} format.`)}function _p(e){switch(e){case Se:case Ce:return{byteLength:1,components:1};case Te:case we:case ke:return{byteLength:2,components:1};case Ae:case je:return{byteLength:2,components:4};case De:case Ee:case Oe:return{byteLength:4,components:1};case Ne:case Pe:return{byteLength:4,components:3}}throw Error(`Unknown texture type ${e}.`)}var vp=class{static contain(e,t){return pp(e,t)}static cover(e,t){return mp(e,t)}static fill(e){return hp(e)}static getByteLength(e,t,n,r){return gp(e,t,n,r)}};typeof __THREE_DEVTOOLS__<`u`&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent(`register`,{detail:{revision:`183`}})),typeof window<`u`&&(window.__THREE__?B(`WARNING: Multiple instances of Three.js being imported.`):window.__THREE__=`183`);var yp=s({ACESFilmicToneMapping:()=>4,AddEquation:()=>100,AddOperation:()=>2,AdditiveAnimationBlendMode:()=>zt,AdditiveBlending:()=>2,AgXToneMapping:()=>6,AlphaFormat:()=>Fe,AlwaysCompare:()=>519,AlwaysDepth:()=>1,AlwaysStencilFunc:()=>519,AmbientLight:()=>od,AnimationAction:()=>sf,AnimationClip:()=>xu,AnimationLoader:()=>Mu,AnimationMixer:()=>lf,AnimationObjectGroup:()=>of,AnimationUtils:()=>su,ArcCurve:()=>sc,ArrayCamera:()=>Ad,ArrowHelper:()=>lp,AttachedBindMode:()=>de,Audio:()=>zd,AudioAnalyser:()=>Gd,AudioContext:()=>xd,AudioListener:()=>Rd,AudioLoader:()=>Sd,AxesHelper:()=>up,BackSide:()=>1,BasicDepthPacking:()=>Bt,BasicShadowMap:()=>0,BatchedMesh:()=>ms,BezierInterpolant:()=>fu,Bone:()=>To,BooleanKeyframeTrack:()=>mu,Box2:()=>Tf,Box3:()=>Ni,Box3Helper:()=>ip,BoxGeometry:()=>qs,BoxHelper:()=>rp,BufferAttribute:()=>ea,BufferGeometry:()=>ba,BufferGeometryLoader:()=>pd,ByteType:()=>Ce,Cache:()=>wu,Camera:()=>Ju,CameraHelper:()=>ep,CanvasTexture:()=>Us,CapsuleGeometry:()=>Js,CatmullRomCurve3:()=>pc,CineonToneMapping:()=>3,CircleGeometry:()=>Ys,ClampToEdgeWrapping:()=>me,Clock:()=>bf,Color:()=>U,ColorKeyframeTrack:()=>hu,ColorManagement:()=>gr,Compatibility:()=>_n,CompressedArrayTexture:()=>Bs,CompressedCubeTexture:()=>Vs,CompressedTexture:()=>zs,CompressedTextureLoader:()=>Nu,ConeGeometry:()=>Zs,ConstantAlphaFactor:()=>213,ConstantColorFactor:()=>211,Controls:()=>fp,CubeCamera:()=>kd,CubeDepthTexture:()=>Gs,CubeReflectionMapping:()=>301,CubeRefractionMapping:()=>302,CubeTexture:()=>Hs,CubeTextureLoader:()=>Iu,CubeUVReflectionMapping:()=>306,CubicBezierCurve:()=>wc,CubicBezierCurve3:()=>Tc,CubicInterpolant:()=>lu,CullFaceBack:()=>1,CullFaceFront:()=>2,CullFaceFrontBack:()=>3,CullFaceNone:()=>0,Curve:()=>ac,CurvePath:()=>Mc,CustomBlending:()=>5,CustomToneMapping:()=>5,CylinderGeometry:()=>Xs,Cylindrical:()=>Sf,Data3DTexture:()=>Mr,DataArrayTexture:()=>Ar,DataTexture:()=>Eo,DataTextureLoader:()=>Lu,DataUtils:()=>Zi,DecrementStencilOp:()=>Zt,DecrementWrapStencilOp:()=>$t,DefaultLoadingManager:()=>Du,DepthFormat:()=>Re,DepthStencilFormat:()=>ze,DepthTexture:()=>Ws,DetachedBindMode:()=>fe,DirectionalLight:()=>ad,DirectionalLightHelper:()=>Zf,DiscreteInterpolant:()=>du,DodecahedronGeometry:()=>$s,DoubleSide:()=>2,DstAlphaFactor:()=>206,DstColorFactor:()=>208,DynamicCopyUsage:()=>ln,DynamicDrawUsage:()=>nn,DynamicReadUsage:()=>on,EdgesGeometry:()=>ic,EllipseCurve:()=>oc,EqualCompare:()=>514,EqualDepth:()=>4,EqualStencilFunc:()=>514,EquirectangularReflectionMapping:()=>303,EquirectangularRefractionMapping:()=>304,Euler:()=>Wr,EventDispatcher:()=>Pn,ExternalTexture:()=>Ks,ExtrudeGeometry:()=>vl,FileLoader:()=>ju,Float16BufferAttribute:()=>ca,Float32BufferAttribute:()=>K,FloatType:()=>Oe,Fog:()=>_i,FogExp2:()=>gi,FramebufferTexture:()=>Rs,FrontSide:()=>0,Frustum:()=>Ko,FrustumArray:()=>Yo,GLBufferAttribute:()=>hf,GLSL1:()=>`100`,GLSL3:()=>dn,GreaterCompare:()=>516,GreaterDepth:()=>6,GreaterEqualCompare:()=>518,GreaterEqualDepth:()=>5,GreaterEqualStencilFunc:()=>518,GreaterStencilFunc:()=>516,GridHelper:()=>Kf,Group:()=>ci,HalfFloatType:()=>ke,HemisphereLight:()=>Bu,HemisphereLightHelper:()=>Gf,IcosahedronGeometry:()=>xl,ImageBitmapLoader:()=>yd,ImageLoader:()=>Fu,ImageUtils:()=>br,IncrementStencilOp:()=>Xt,IncrementWrapStencilOp:()=>Qt,InstancedBufferAttribute:()=>Ao,InstancedBufferGeometry:()=>fd,InstancedInterleavedBuffer:()=>mf,InstancedMesh:()=>Ro,Int16BufferAttribute:()=>ia,Int32BufferAttribute:()=>oa,Int8BufferAttribute:()=>ta,IntType:()=>Ee,InterleavedBuffer:()=>xa,InterleavedBufferAttribute:()=>Ca,Interpolant:()=>cu,InterpolateBezier:()=>Pt,InterpolateDiscrete:()=>jt,InterpolateLinear:()=>Mt,InterpolateSmooth:()=>Nt,InterpolationSamplingMode:()=>gn,InterpolationSamplingType:()=>hn,InvertStencilOp:()=>en,KeepStencilOp:()=>Jt,KeyframeTrack:()=>pu,LOD:()=>Wa,LatheGeometry:()=>Sl,Layers:()=>Gr,LessCompare:()=>513,LessDepth:()=>2,LessEqualCompare:()=>515,LessEqualDepth:()=>3,LessEqualStencilFunc:()=>515,LessStencilFunc:()=>513,Light:()=>zu,LightProbe:()=>ld,Line:()=>Cs,Line3:()=>Nf,LineBasicMaterial:()=>hs,LineCurve:()=>Ec,LineCurve3:()=>Dc,LineDashedMaterial:()=>eu,LineLoop:()=>Os,LineSegments:()=>Ds,LinearFilter:()=>L,LinearInterpolant:()=>uu,LinearMipMapLinearFilter:()=>xe,LinearMipMapNearestFilter:()=>z,LinearMipmapLinearFilter:()=>be,LinearMipmapNearestFilter:()=>R,LinearSRGBColorSpace:()=>Gt,LinearToneMapping:()=>1,LinearTransfer:()=>Kt,Loader:()=>Ou,LoaderUtils:()=>dd,LoadingManager:()=>Eu,LoopOnce:()=>Ot,LoopPingPong:()=>At,LoopRepeat:()=>kt,MOUSE:()=>le,Material:()=>Ta,MaterialBlending:()=>6,MaterialLoader:()=>ud,MathUtils:()=>sr,Matrix2:()=>Cf,Matrix3:()=>dr,Matrix4:()=>Pr,MaxEquation:()=>104,Mesh:()=>fo,MeshBasicMaterial:()=>$a,MeshDepthMaterial:()=>Zl,MeshDistanceMaterial:()=>Ql,MeshLambertMaterial:()=>Xl,MeshMatcapMaterial:()=>$l,MeshNormalMaterial:()=>Yl,MeshPhongMaterial:()=>ql,MeshPhysicalMaterial:()=>Kl,MeshStandardMaterial:()=>Gl,MeshToonMaterial:()=>Jl,MinEquation:()=>103,MirroredRepeatWrapping:()=>he,MixOperation:()=>1,MultiplyBlending:()=>4,MultiplyOperation:()=>0,NearestFilter:()=>ge,NearestMipMapLinearFilter:()=>ye,NearestMipMapNearestFilter:()=>_e,NearestMipmapLinearFilter:()=>ve,NearestMipmapNearestFilter:()=>I,NeutralToneMapping:()=>7,NeverCompare:()=>512,NeverDepth:()=>0,NeverStencilFunc:()=>512,NoBlending:()=>0,NoColorSpace:()=>``,NoNormalPacking:()=>``,NoToneMapping:()=>0,NormalAnimationBlendMode:()=>Rt,NormalBlending:()=>1,NormalGAPacking:()=>`ga`,NormalRGPacking:()=>`rg`,NotEqualCompare:()=>517,NotEqualDepth:()=>7,NotEqualStencilFunc:()=>517,NumberKeyframeTrack:()=>gu,Object3D:()=>si,ObjectLoader:()=>md,ObjectSpaceNormalMap:()=>1,OctahedronGeometry:()=>Cl,OneFactor:()=>201,OneMinusConstantAlphaFactor:()=>214,OneMinusConstantColorFactor:()=>212,OneMinusDstAlphaFactor:()=>207,OneMinusDstColorFactor:()=>209,OneMinusSrcAlphaFactor:()=>205,OneMinusSrcColorFactor:()=>203,OrthographicCamera:()=>rd,PCFShadowMap:()=>1,PCFSoftShadowMap:()=>2,PMREMGenerator:()=>Up,Path:()=>Nc,PerspectiveCamera:()=>Qu,Plane:()=>Ho,PlaneGeometry:()=>wl,PlaneHelper:()=>ap,PointLight:()=>nd,PointLightHelper:()=>Vf,Points:()=>Ps,PointsMaterial:()=>ks,PolarGridHelper:()=>qf,PolyhedronGeometry:()=>Qs,PositionalAudio:()=>Wd,PropertyBinding:()=>af,PropertyMixer:()=>Kd,QuadraticBezierCurve:()=>Oc,QuadraticBezierCurve3:()=>kc,Quaternion:()=>cr,QuaternionKeyframeTrack:()=>vu,QuaternionLinearInterpolant:()=>_u,R11_EAC_Format:()=>rt,RED_GREEN_RGTC2_Format:()=>Et,RED_RGTC1_Format:()=>wt,REVISION:()=>`183`,RG11_EAC_Format:()=>at,RGBADepthPacking:()=>Vt,RGBAFormat:()=>Le,RGBAIntegerFormat:()=>Ge,RGBA_ASTC_10x10_Format:()=>vt,RGBA_ASTC_10x5_Format:()=>ht,RGBA_ASTC_10x6_Format:()=>gt,RGBA_ASTC_10x8_Format:()=>_t,RGBA_ASTC_12x10_Format:()=>yt,RGBA_ASTC_12x12_Format:()=>bt,RGBA_ASTC_4x4_Format:()=>st,RGBA_ASTC_5x4_Format:()=>ct,RGBA_ASTC_5x5_Format:()=>lt,RGBA_ASTC_6x5_Format:()=>ut,RGBA_ASTC_6x6_Format:()=>dt,RGBA_ASTC_8x5_Format:()=>ft,RGBA_ASTC_8x6_Format:()=>pt,RGBA_ASTC_8x8_Format:()=>mt,RGBA_BPTC_Format:()=>xt,RGBA_ETC2_EAC_Format:()=>nt,RGBA_PVRTC_2BPPV1_Format:()=>$e,RGBA_PVRTC_4BPPV1_Format:()=>Qe,RGBA_S3TC_DXT1_Format:()=>qe,RGBA_S3TC_DXT3_Format:()=>Je,RGBA_S3TC_DXT5_Format:()=>Ye,RGBDepthPacking:()=>Ht,RGBFormat:()=>Ie,RGBIntegerFormat:()=>We,RGB_BPTC_SIGNED_Format:()=>St,RGB_BPTC_UNSIGNED_Format:()=>Ct,RGB_ETC1_Format:()=>et,RGB_ETC2_Format:()=>tt,RGB_PVRTC_2BPPV1_Format:()=>Ze,RGB_PVRTC_4BPPV1_Format:()=>Xe,RGB_S3TC_DXT1_Format:()=>Ke,RGDepthPacking:()=>Ut,RGFormat:()=>He,RGIntegerFormat:()=>Ue,RawShaderMaterial:()=>Wl,Ray:()=>Qa,Raycaster:()=>_f,RectAreaLight:()=>sd,RedFormat:()=>Be,RedIntegerFormat:()=>Ve,ReinhardToneMapping:()=>2,RenderTarget:()=>Or,RenderTarget3D:()=>uf,RepeatWrapping:()=>pe,ReplaceStencilOp:()=>Yt,ReverseSubtractEquation:()=>102,RingGeometry:()=>Tl,SIGNED_R11_EAC_Format:()=>it,SIGNED_RED_GREEN_RGTC2_Format:()=>Dt,SIGNED_RED_RGTC1_Format:()=>Tt,SIGNED_RG11_EAC_Format:()=>ot,SRGBColorSpace:()=>Wt,SRGBTransfer:()=>qt,Scene:()=>vi,ShaderChunk:()=>Sp,ShaderLib:()=>Cp,ShaderMaterial:()=>q,ShadowMaterial:()=>Il,Shape:()=>Pc,ShapeGeometry:()=>El,ShapePath:()=>dp,ShapeUtils:()=>hl,ShortType:()=>we,Skeleton:()=>ko,SkeletonHelper:()=>zf,SkinnedMesh:()=>wo,Source:()=>Sr,Sphere:()=>fa,SphereGeometry:()=>Ol,Spherical:()=>xf,SphericalHarmonics3:()=>cd,SplineCurve:()=>Ac,SpotLight:()=>ed,SpotLightHelper:()=>Ff,Sprite:()=>Ba,SpriteMaterial:()=>Ea,SrcAlphaFactor:()=>204,SrcAlphaSaturateFactor:()=>210,SrcColorFactor:()=>202,StaticCopyUsage:()=>cn,StaticDrawUsage:()=>tn,StaticReadUsage:()=>an,StereoCamera:()=>Ed,StreamCopyUsage:()=>un,StreamDrawUsage:()=>rn,StreamReadUsage:()=>sn,StringKeyframeTrack:()=>yu,SubtractEquation:()=>101,SubtractiveBlending:()=>3,TOUCH:()=>ue,TangentSpaceNormalMap:()=>0,TetrahedronGeometry:()=>kl,Texture:()=>Er,TextureLoader:()=>Ru,TextureUtils:()=>vp,Timer:()=>jd,TimestampQuery:()=>mn,TorusGeometry:()=>Al,TorusKnotGeometry:()=>jl,Triangle:()=>Mi,TriangleFanDrawMode:()=>2,TriangleStripDrawMode:()=>1,TrianglesDrawMode:()=>0,TubeGeometry:()=>Ml,UVMapping:()=>300,Uint16BufferAttribute:()=>aa,Uint32BufferAttribute:()=>sa,Uint8BufferAttribute:()=>na,Uint8ClampedBufferAttribute:()=>ra,Uniform:()=>df,UniformsGroup:()=>pf,UniformsLib:()=>J,UniformsUtils:()=>Vl,UnsignedByteType:()=>Se,UnsignedInt101111Type:()=>Pe,UnsignedInt248Type:()=>Me,UnsignedInt5999Type:()=>Ne,UnsignedIntType:()=>De,UnsignedShort4444Type:()=>Ae,UnsignedShort5551Type:()=>je,UnsignedShortType:()=>Te,VSMShadowMap:()=>3,Vector2:()=>V,Vector3:()=>H,Vector4:()=>Dr,VectorKeyframeTrack:()=>bu,VideoFrameTexture:()=>Ls,VideoTexture:()=>Is,WebGL3DRenderTarget:()=>Nr,WebGLArrayRenderTarget:()=>jr,WebGLCoordinateSystem:()=>fn,WebGLCubeRenderTarget:()=>Qp,WebGLRenderTarget:()=>kr,WebGLRenderer:()=>Fg,WebGLUtils:()=>Cg,WebGPUCoordinateSystem:()=>pn,WebXRController:()=>ui,WireframeGeometry:()=>Nl,WrapAroundEnding:()=>Lt,ZeroCurvatureEnding:()=>Ft,ZeroFactor:()=>200,ZeroSlopeEnding:()=>It,ZeroStencilOp:()=>0,createCanvasElement:()=>Cn,error:()=>An,getConsoleFunction:()=>Dn,log:()=>On,setConsoleFunction:()=>En,warn:()=>B,warnOnce:()=>jn});function bp(){let e=null,t=!1,n=null,r=null;function i(t,a){n(t,a),r=e.requestAnimationFrame(i)}return{start:function(){t!==!0&&n!==null&&(r=e.requestAnimationFrame(i),t=!0)},stop:function(){e.cancelAnimationFrame(r),t=!1},setAnimationLoop:function(e){n=e},setContext:function(t){e=t}}}function xp(e){let t=new WeakMap;function n(t,n){let r=t.array,i=t.usage,a=r.byteLength,o=e.createBuffer();e.bindBuffer(n,o),e.bufferData(n,r,i),t.onUploadCallback();let s;if(r instanceof Float32Array)s=e.FLOAT;else if(typeof Float16Array<`u`&&r instanceof Float16Array)s=e.HALF_FLOAT;else if(r instanceof Uint16Array)s=t.isFloat16BufferAttribute?e.HALF_FLOAT:e.UNSIGNED_SHORT;else if(r instanceof Int16Array)s=e.SHORT;else if(r instanceof Uint32Array)s=e.UNSIGNED_INT;else if(r instanceof Int32Array)s=e.INT;else if(r instanceof Int8Array)s=e.BYTE;else if(r instanceof Uint8Array)s=e.UNSIGNED_BYTE;else if(r instanceof Uint8ClampedArray)s=e.UNSIGNED_BYTE;else throw Error(`THREE.WebGLAttributes: Unsupported buffer data format: `+r);return{buffer:o,type:s,bytesPerElement:r.BYTES_PER_ELEMENT,version:t.version,size:a}}function r(t,n,r){let i=n.array,a=n.updateRanges;if(e.bindBuffer(r,t),a.length===0)e.bufferSubData(r,0,i);else{a.sort((e,t)=>e.start-t.start);let t=0;for(let e=1;e 0 + vec4 plane; + #ifdef ALPHA_TO_COVERAGE + float distanceToPlane, distanceGradient; + float clipOpacity = 1.0; + #pragma unroll_loop_start + for ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) { + plane = clippingPlanes[ i ]; + distanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w; + distanceGradient = fwidth( distanceToPlane ) / 2.0; + clipOpacity *= smoothstep( - distanceGradient, distanceGradient, distanceToPlane ); + if ( clipOpacity == 0.0 ) discard; + } + #pragma unroll_loop_end + #if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES + float unionClipOpacity = 1.0; + #pragma unroll_loop_start + for ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) { + plane = clippingPlanes[ i ]; + distanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w; + distanceGradient = fwidth( distanceToPlane ) / 2.0; + unionClipOpacity *= 1.0 - smoothstep( - distanceGradient, distanceGradient, distanceToPlane ); + } + #pragma unroll_loop_end + clipOpacity *= 1.0 - unionClipOpacity; + #endif + diffuseColor.a *= clipOpacity; + if ( diffuseColor.a == 0.0 ) discard; + #else + #pragma unroll_loop_start + for ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) { + plane = clippingPlanes[ i ]; + if ( dot( vClipPosition, plane.xyz ) > plane.w ) discard; + } + #pragma unroll_loop_end + #if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES + bool clipped = true; + #pragma unroll_loop_start + for ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) { + plane = clippingPlanes[ i ]; + clipped = ( dot( vClipPosition, plane.xyz ) > plane.w ) && clipped; + } + #pragma unroll_loop_end + if ( clipped ) discard; + #endif + #endif +#endif`,clipping_planes_pars_fragment:`#if NUM_CLIPPING_PLANES > 0 + varying vec3 vClipPosition; + uniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ]; +#endif`,clipping_planes_pars_vertex:`#if NUM_CLIPPING_PLANES > 0 + varying vec3 vClipPosition; +#endif`,clipping_planes_vertex:`#if NUM_CLIPPING_PLANES > 0 + vClipPosition = - mvPosition.xyz; +#endif`,color_fragment:`#if defined( USE_COLOR ) || defined( USE_COLOR_ALPHA ) + diffuseColor *= vColor; +#endif`,color_pars_fragment:`#if defined( USE_COLOR ) || defined( USE_COLOR_ALPHA ) + varying vec4 vColor; +#endif`,color_pars_vertex:`#if defined( USE_COLOR ) || defined( USE_COLOR_ALPHA ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR ) + varying vec4 vColor; +#endif`,color_vertex:`#if defined( USE_COLOR ) || defined( USE_COLOR_ALPHA ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR ) + vColor = vec4( 1.0 ); +#endif +#ifdef USE_COLOR_ALPHA + vColor *= color; +#elif defined( USE_COLOR ) + vColor.rgb *= color; +#endif +#ifdef USE_INSTANCING_COLOR + vColor.rgb *= instanceColor.rgb; +#endif +#ifdef USE_BATCHING_COLOR + vColor *= getBatchingColor( getIndirectIndex( gl_DrawID ) ); +#endif`,common:`#define PI 3.141592653589793 +#define PI2 6.283185307179586 +#define PI_HALF 1.5707963267948966 +#define RECIPROCAL_PI 0.3183098861837907 +#define RECIPROCAL_PI2 0.15915494309189535 +#define EPSILON 1e-6 +#ifndef saturate +#define saturate( a ) clamp( a, 0.0, 1.0 ) +#endif +#define whiteComplement( a ) ( 1.0 - saturate( a ) ) +float pow2( const in float x ) { return x*x; } +vec3 pow2( const in vec3 x ) { return x*x; } +float pow3( const in float x ) { return x*x*x; } +float pow4( const in float x ) { float x2 = x*x; return x2*x2; } +float max3( const in vec3 v ) { return max( max( v.x, v.y ), v.z ); } +float average( const in vec3 v ) { return dot( v, vec3( 0.3333333 ) ); } +highp float rand( const in vec2 uv ) { + const highp float a = 12.9898, b = 78.233, c = 43758.5453; + highp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI ); + return fract( sin( sn ) * c ); +} +#ifdef HIGH_PRECISION + float precisionSafeLength( vec3 v ) { return length( v ); } +#else + float precisionSafeLength( vec3 v ) { + float maxComponent = max3( abs( v ) ); + return length( v / maxComponent ) * maxComponent; + } +#endif +struct IncidentLight { + vec3 color; + vec3 direction; + bool visible; +}; +struct ReflectedLight { + vec3 directDiffuse; + vec3 directSpecular; + vec3 indirectDiffuse; + vec3 indirectSpecular; +}; +#ifdef USE_ALPHAHASH + varying vec3 vPosition; +#endif +vec3 transformDirection( in vec3 dir, in mat4 matrix ) { + return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz ); +} +vec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) { + return normalize( ( vec4( dir, 0.0 ) * matrix ).xyz ); +} +bool isPerspectiveMatrix( mat4 m ) { + return m[ 2 ][ 3 ] == - 1.0; +} +vec2 equirectUv( in vec3 dir ) { + float u = atan( dir.z, dir.x ) * RECIPROCAL_PI2 + 0.5; + float v = asin( clamp( dir.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5; + return vec2( u, v ); +} +vec3 BRDF_Lambert( const in vec3 diffuseColor ) { + return RECIPROCAL_PI * diffuseColor; +} +vec3 F_Schlick( const in vec3 f0, const in float f90, const in float dotVH ) { + float fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH ); + return f0 * ( 1.0 - fresnel ) + ( f90 * fresnel ); +} +float F_Schlick( const in float f0, const in float f90, const in float dotVH ) { + float fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH ); + return f0 * ( 1.0 - fresnel ) + ( f90 * fresnel ); +} // validated`,cube_uv_reflection_fragment:`#ifdef ENVMAP_TYPE_CUBE_UV + #define cubeUV_minMipLevel 4.0 + #define cubeUV_minTileSize 16.0 + float getFace( vec3 direction ) { + vec3 absDirection = abs( direction ); + float face = - 1.0; + if ( absDirection.x > absDirection.z ) { + if ( absDirection.x > absDirection.y ) + face = direction.x > 0.0 ? 0.0 : 3.0; + else + face = direction.y > 0.0 ? 1.0 : 4.0; + } else { + if ( absDirection.z > absDirection.y ) + face = direction.z > 0.0 ? 2.0 : 5.0; + else + face = direction.y > 0.0 ? 1.0 : 4.0; + } + return face; + } + vec2 getUV( vec3 direction, float face ) { + vec2 uv; + if ( face == 0.0 ) { + uv = vec2( direction.z, direction.y ) / abs( direction.x ); + } else if ( face == 1.0 ) { + uv = vec2( - direction.x, - direction.z ) / abs( direction.y ); + } else if ( face == 2.0 ) { + uv = vec2( - direction.x, direction.y ) / abs( direction.z ); + } else if ( face == 3.0 ) { + uv = vec2( - direction.z, direction.y ) / abs( direction.x ); + } else if ( face == 4.0 ) { + uv = vec2( - direction.x, direction.z ) / abs( direction.y ); + } else { + uv = vec2( direction.x, direction.y ) / abs( direction.z ); + } + return 0.5 * ( uv + 1.0 ); + } + vec3 bilinearCubeUV( sampler2D envMap, vec3 direction, float mipInt ) { + float face = getFace( direction ); + float filterInt = max( cubeUV_minMipLevel - mipInt, 0.0 ); + mipInt = max( mipInt, cubeUV_minMipLevel ); + float faceSize = exp2( mipInt ); + highp vec2 uv = getUV( direction, face ) * ( faceSize - 2.0 ) + 1.0; + if ( face > 2.0 ) { + uv.y += faceSize; + face -= 3.0; + } + uv.x += face * faceSize; + uv.x += filterInt * 3.0 * cubeUV_minTileSize; + uv.y += 4.0 * ( exp2( CUBEUV_MAX_MIP ) - faceSize ); + uv.x *= CUBEUV_TEXEL_WIDTH; + uv.y *= CUBEUV_TEXEL_HEIGHT; + #ifdef texture2DGradEXT + return texture2DGradEXT( envMap, uv, vec2( 0.0 ), vec2( 0.0 ) ).rgb; + #else + return texture2D( envMap, uv ).rgb; + #endif + } + #define cubeUV_r0 1.0 + #define cubeUV_m0 - 2.0 + #define cubeUV_r1 0.8 + #define cubeUV_m1 - 1.0 + #define cubeUV_r4 0.4 + #define cubeUV_m4 2.0 + #define cubeUV_r5 0.305 + #define cubeUV_m5 3.0 + #define cubeUV_r6 0.21 + #define cubeUV_m6 4.0 + float roughnessToMip( float roughness ) { + float mip = 0.0; + if ( roughness >= cubeUV_r1 ) { + mip = ( cubeUV_r0 - roughness ) * ( cubeUV_m1 - cubeUV_m0 ) / ( cubeUV_r0 - cubeUV_r1 ) + cubeUV_m0; + } else if ( roughness >= cubeUV_r4 ) { + mip = ( cubeUV_r1 - roughness ) * ( cubeUV_m4 - cubeUV_m1 ) / ( cubeUV_r1 - cubeUV_r4 ) + cubeUV_m1; + } else if ( roughness >= cubeUV_r5 ) { + mip = ( cubeUV_r4 - roughness ) * ( cubeUV_m5 - cubeUV_m4 ) / ( cubeUV_r4 - cubeUV_r5 ) + cubeUV_m4; + } else if ( roughness >= cubeUV_r6 ) { + mip = ( cubeUV_r5 - roughness ) * ( cubeUV_m6 - cubeUV_m5 ) / ( cubeUV_r5 - cubeUV_r6 ) + cubeUV_m5; + } else { + mip = - 2.0 * log2( 1.16 * roughness ); } + return mip; + } + vec4 textureCubeUV( sampler2D envMap, vec3 sampleDir, float roughness ) { + float mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP ); + float mipF = fract( mip ); + float mipInt = floor( mip ); + vec3 color0 = bilinearCubeUV( envMap, sampleDir, mipInt ); + if ( mipF == 0.0 ) { + return vec4( color0, 1.0 ); + } else { + vec3 color1 = bilinearCubeUV( envMap, sampleDir, mipInt + 1.0 ); + return vec4( mix( color0, color1, mipF ), 1.0 ); + } + } +#endif`,defaultnormal_vertex:`vec3 transformedNormal = objectNormal; +#ifdef USE_TANGENT + vec3 transformedTangent = objectTangent; +#endif +#ifdef USE_BATCHING + mat3 bm = mat3( batchingMatrix ); + transformedNormal /= vec3( dot( bm[ 0 ], bm[ 0 ] ), dot( bm[ 1 ], bm[ 1 ] ), dot( bm[ 2 ], bm[ 2 ] ) ); + transformedNormal = bm * transformedNormal; + #ifdef USE_TANGENT + transformedTangent = bm * transformedTangent; + #endif +#endif +#ifdef USE_INSTANCING + mat3 im = mat3( instanceMatrix ); + transformedNormal /= vec3( dot( im[ 0 ], im[ 0 ] ), dot( im[ 1 ], im[ 1 ] ), dot( im[ 2 ], im[ 2 ] ) ); + transformedNormal = im * transformedNormal; + #ifdef USE_TANGENT + transformedTangent = im * transformedTangent; + #endif +#endif +transformedNormal = normalMatrix * transformedNormal; +#ifdef FLIP_SIDED + transformedNormal = - transformedNormal; +#endif +#ifdef USE_TANGENT + transformedTangent = ( modelViewMatrix * vec4( transformedTangent, 0.0 ) ).xyz; + #ifdef FLIP_SIDED + transformedTangent = - transformedTangent; + #endif +#endif`,displacementmap_pars_vertex:`#ifdef USE_DISPLACEMENTMAP + uniform sampler2D displacementMap; + uniform float displacementScale; + uniform float displacementBias; +#endif`,displacementmap_vertex:`#ifdef USE_DISPLACEMENTMAP + transformed += normalize( objectNormal ) * ( texture2D( displacementMap, vDisplacementMapUv ).x * displacementScale + displacementBias ); +#endif`,emissivemap_fragment:`#ifdef USE_EMISSIVEMAP + vec4 emissiveColor = texture2D( emissiveMap, vEmissiveMapUv ); + #ifdef DECODE_VIDEO_TEXTURE_EMISSIVE + emissiveColor = sRGBTransferEOTF( emissiveColor ); + #endif + totalEmissiveRadiance *= emissiveColor.rgb; +#endif`,emissivemap_pars_fragment:`#ifdef USE_EMISSIVEMAP + uniform sampler2D emissiveMap; +#endif`,colorspace_fragment:`gl_FragColor = linearToOutputTexel( gl_FragColor );`,colorspace_pars_fragment:`vec4 LinearTransferOETF( in vec4 value ) { + return value; +} +vec4 sRGBTransferEOTF( in vec4 value ) { + return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.a ); +} +vec4 sRGBTransferOETF( in vec4 value ) { + return vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.a ); +}`,envmap_fragment:`#ifdef USE_ENVMAP + #ifdef ENV_WORLDPOS + vec3 cameraToFrag; + if ( isOrthographic ) { + cameraToFrag = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) ); + } else { + cameraToFrag = normalize( vWorldPosition - cameraPosition ); + } + vec3 worldNormal = inverseTransformDirection( normal, viewMatrix ); + #ifdef ENVMAP_MODE_REFLECTION + vec3 reflectVec = reflect( cameraToFrag, worldNormal ); + #else + vec3 reflectVec = refract( cameraToFrag, worldNormal, refractionRatio ); + #endif + #else + vec3 reflectVec = vReflect; + #endif + #ifdef ENVMAP_TYPE_CUBE + vec4 envColor = textureCube( envMap, envMapRotation * vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) ); + #ifdef ENVMAP_BLENDING_MULTIPLY + outgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity ); + #elif defined( ENVMAP_BLENDING_MIX ) + outgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity ); + #elif defined( ENVMAP_BLENDING_ADD ) + outgoingLight += envColor.xyz * specularStrength * reflectivity; + #endif + #endif +#endif`,envmap_common_pars_fragment:`#ifdef USE_ENVMAP + uniform float envMapIntensity; + uniform float flipEnvMap; + uniform mat3 envMapRotation; + #ifdef ENVMAP_TYPE_CUBE + uniform samplerCube envMap; + #else + uniform sampler2D envMap; + #endif +#endif`,envmap_pars_fragment:`#ifdef USE_ENVMAP + uniform float reflectivity; + #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT ) + #define ENV_WORLDPOS + #endif + #ifdef ENV_WORLDPOS + varying vec3 vWorldPosition; + uniform float refractionRatio; + #else + varying vec3 vReflect; + #endif +#endif`,envmap_pars_vertex:`#ifdef USE_ENVMAP + #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT ) + #define ENV_WORLDPOS + #endif + #ifdef ENV_WORLDPOS + + varying vec3 vWorldPosition; + #else + varying vec3 vReflect; + uniform float refractionRatio; + #endif +#endif`,envmap_physical_pars_fragment:`#ifdef USE_ENVMAP + vec3 getIBLIrradiance( const in vec3 normal ) { + #ifdef ENVMAP_TYPE_CUBE_UV + vec3 worldNormal = inverseTransformDirection( normal, viewMatrix ); + vec4 envMapColor = textureCubeUV( envMap, envMapRotation * worldNormal, 1.0 ); + return PI * envMapColor.rgb * envMapIntensity; + #else + return vec3( 0.0 ); + #endif + } + vec3 getIBLRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness ) { + #ifdef ENVMAP_TYPE_CUBE_UV + vec3 reflectVec = reflect( - viewDir, normal ); + reflectVec = normalize( mix( reflectVec, normal, pow4( roughness ) ) ); + reflectVec = inverseTransformDirection( reflectVec, viewMatrix ); + vec4 envMapColor = textureCubeUV( envMap, envMapRotation * reflectVec, roughness ); + return envMapColor.rgb * envMapIntensity; + #else + return vec3( 0.0 ); + #endif + } + #ifdef USE_ANISOTROPY + vec3 getIBLAnisotropyRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness, const in vec3 bitangent, const in float anisotropy ) { + #ifdef ENVMAP_TYPE_CUBE_UV + vec3 bentNormal = cross( bitangent, viewDir ); + bentNormal = normalize( cross( bentNormal, bitangent ) ); + bentNormal = normalize( mix( bentNormal, normal, pow2( pow2( 1.0 - anisotropy * ( 1.0 - roughness ) ) ) ) ); + return getIBLRadiance( viewDir, bentNormal, roughness ); + #else + return vec3( 0.0 ); + #endif + } + #endif +#endif`,envmap_vertex:`#ifdef USE_ENVMAP + #ifdef ENV_WORLDPOS + vWorldPosition = worldPosition.xyz; + #else + vec3 cameraToVertex; + if ( isOrthographic ) { + cameraToVertex = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) ); + } else { + cameraToVertex = normalize( worldPosition.xyz - cameraPosition ); + } + vec3 worldNormal = inverseTransformDirection( transformedNormal, viewMatrix ); + #ifdef ENVMAP_MODE_REFLECTION + vReflect = reflect( cameraToVertex, worldNormal ); + #else + vReflect = refract( cameraToVertex, worldNormal, refractionRatio ); + #endif + #endif +#endif`,fog_vertex:`#ifdef USE_FOG + vFogDepth = - mvPosition.z; +#endif`,fog_pars_vertex:`#ifdef USE_FOG + varying float vFogDepth; +#endif`,fog_fragment:`#ifdef USE_FOG + #ifdef FOG_EXP2 + float fogFactor = 1.0 - exp( - fogDensity * fogDensity * vFogDepth * vFogDepth ); + #else + float fogFactor = smoothstep( fogNear, fogFar, vFogDepth ); + #endif + gl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor ); +#endif`,fog_pars_fragment:`#ifdef USE_FOG + uniform vec3 fogColor; + varying float vFogDepth; + #ifdef FOG_EXP2 + uniform float fogDensity; + #else + uniform float fogNear; + uniform float fogFar; + #endif +#endif`,gradientmap_pars_fragment:`#ifdef USE_GRADIENTMAP + uniform sampler2D gradientMap; +#endif +vec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) { + float dotNL = dot( normal, lightDirection ); + vec2 coord = vec2( dotNL * 0.5 + 0.5, 0.0 ); + #ifdef USE_GRADIENTMAP + return vec3( texture2D( gradientMap, coord ).r ); + #else + vec2 fw = fwidth( coord ) * 0.5; + return mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( 0.7 - fw.x, 0.7 + fw.x, coord.x ) ); + #endif +}`,lightmap_pars_fragment:`#ifdef USE_LIGHTMAP + uniform sampler2D lightMap; + uniform float lightMapIntensity; +#endif`,lights_lambert_fragment:`LambertMaterial material; +material.diffuseColor = diffuseColor.rgb; +material.specularStrength = specularStrength;`,lights_lambert_pars_fragment:`varying vec3 vViewPosition; +struct LambertMaterial { + vec3 diffuseColor; + float specularStrength; +}; +void RE_Direct_Lambert( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in LambertMaterial material, inout ReflectedLight reflectedLight ) { + float dotNL = saturate( dot( geometryNormal, directLight.direction ) ); + vec3 irradiance = dotNL * directLight.color; + reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); +} +void RE_IndirectDiffuse_Lambert( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in LambertMaterial material, inout ReflectedLight reflectedLight ) { + reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); +} +#define RE_Direct RE_Direct_Lambert +#define RE_IndirectDiffuse RE_IndirectDiffuse_Lambert`,lights_pars_begin:`uniform bool receiveShadow; +uniform vec3 ambientLightColor; +#if defined( USE_LIGHT_PROBES ) + uniform vec3 lightProbe[ 9 ]; +#endif +vec3 shGetIrradianceAt( in vec3 normal, in vec3 shCoefficients[ 9 ] ) { + float x = normal.x, y = normal.y, z = normal.z; + vec3 result = shCoefficients[ 0 ] * 0.886227; + result += shCoefficients[ 1 ] * 2.0 * 0.511664 * y; + result += shCoefficients[ 2 ] * 2.0 * 0.511664 * z; + result += shCoefficients[ 3 ] * 2.0 * 0.511664 * x; + result += shCoefficients[ 4 ] * 2.0 * 0.429043 * x * y; + result += shCoefficients[ 5 ] * 2.0 * 0.429043 * y * z; + result += shCoefficients[ 6 ] * ( 0.743125 * z * z - 0.247708 ); + result += shCoefficients[ 7 ] * 2.0 * 0.429043 * x * z; + result += shCoefficients[ 8 ] * 0.429043 * ( x * x - y * y ); + return result; +} +vec3 getLightProbeIrradiance( const in vec3 lightProbe[ 9 ], const in vec3 normal ) { + vec3 worldNormal = inverseTransformDirection( normal, viewMatrix ); + vec3 irradiance = shGetIrradianceAt( worldNormal, lightProbe ); + return irradiance; +} +vec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) { + vec3 irradiance = ambientLightColor; + return irradiance; +} +float getDistanceAttenuation( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) { + float distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 ); + if ( cutoffDistance > 0.0 ) { + distanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) ); + } + return distanceFalloff; +} +float getSpotAttenuation( const in float coneCosine, const in float penumbraCosine, const in float angleCosine ) { + return smoothstep( coneCosine, penumbraCosine, angleCosine ); +} +#if NUM_DIR_LIGHTS > 0 + struct DirectionalLight { + vec3 direction; + vec3 color; + }; + uniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ]; + void getDirectionalLightInfo( const in DirectionalLight directionalLight, out IncidentLight light ) { + light.color = directionalLight.color; + light.direction = directionalLight.direction; + light.visible = true; + } +#endif +#if NUM_POINT_LIGHTS > 0 + struct PointLight { + vec3 position; + vec3 color; + float distance; + float decay; + }; + uniform PointLight pointLights[ NUM_POINT_LIGHTS ]; + void getPointLightInfo( const in PointLight pointLight, const in vec3 geometryPosition, out IncidentLight light ) { + vec3 lVector = pointLight.position - geometryPosition; + light.direction = normalize( lVector ); + float lightDistance = length( lVector ); + light.color = pointLight.color; + light.color *= getDistanceAttenuation( lightDistance, pointLight.distance, pointLight.decay ); + light.visible = ( light.color != vec3( 0.0 ) ); + } +#endif +#if NUM_SPOT_LIGHTS > 0 + struct SpotLight { + vec3 position; + vec3 direction; + vec3 color; + float distance; + float decay; + float coneCos; + float penumbraCos; + }; + uniform SpotLight spotLights[ NUM_SPOT_LIGHTS ]; + void getSpotLightInfo( const in SpotLight spotLight, const in vec3 geometryPosition, out IncidentLight light ) { + vec3 lVector = spotLight.position - geometryPosition; + light.direction = normalize( lVector ); + float angleCos = dot( light.direction, spotLight.direction ); + float spotAttenuation = getSpotAttenuation( spotLight.coneCos, spotLight.penumbraCos, angleCos ); + if ( spotAttenuation > 0.0 ) { + float lightDistance = length( lVector ); + light.color = spotLight.color * spotAttenuation; + light.color *= getDistanceAttenuation( lightDistance, spotLight.distance, spotLight.decay ); + light.visible = ( light.color != vec3( 0.0 ) ); + } else { + light.color = vec3( 0.0 ); + light.visible = false; + } + } +#endif +#if NUM_RECT_AREA_LIGHTS > 0 + struct RectAreaLight { + vec3 color; + vec3 position; + vec3 halfWidth; + vec3 halfHeight; + }; + uniform sampler2D ltc_1; uniform sampler2D ltc_2; + uniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ]; +#endif +#if NUM_HEMI_LIGHTS > 0 + struct HemisphereLight { + vec3 direction; + vec3 skyColor; + vec3 groundColor; + }; + uniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ]; + vec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in vec3 normal ) { + float dotNL = dot( normal, hemiLight.direction ); + float hemiDiffuseWeight = 0.5 * dotNL + 0.5; + vec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight ); + return irradiance; + } +#endif`,lights_toon_fragment:`ToonMaterial material; +material.diffuseColor = diffuseColor.rgb;`,lights_toon_pars_fragment:`varying vec3 vViewPosition; +struct ToonMaterial { + vec3 diffuseColor; +}; +void RE_Direct_Toon( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in ToonMaterial material, inout ReflectedLight reflectedLight ) { + vec3 irradiance = getGradientIrradiance( geometryNormal, directLight.direction ) * directLight.color; + reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); +} +void RE_IndirectDiffuse_Toon( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in ToonMaterial material, inout ReflectedLight reflectedLight ) { + reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); +} +#define RE_Direct RE_Direct_Toon +#define RE_IndirectDiffuse RE_IndirectDiffuse_Toon`,lights_phong_fragment:`BlinnPhongMaterial material; +material.diffuseColor = diffuseColor.rgb; +material.specularColor = specular; +material.specularShininess = shininess; +material.specularStrength = specularStrength;`,lights_phong_pars_fragment:`varying vec3 vViewPosition; +struct BlinnPhongMaterial { + vec3 diffuseColor; + vec3 specularColor; + float specularShininess; + float specularStrength; +}; +void RE_Direct_BlinnPhong( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) { + float dotNL = saturate( dot( geometryNormal, directLight.direction ) ); + vec3 irradiance = dotNL * directLight.color; + reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); + reflectedLight.directSpecular += irradiance * BRDF_BlinnPhong( directLight.direction, geometryViewDir, geometryNormal, material.specularColor, material.specularShininess ) * material.specularStrength; +} +void RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) { + reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); +} +#define RE_Direct RE_Direct_BlinnPhong +#define RE_IndirectDiffuse RE_IndirectDiffuse_BlinnPhong`,lights_physical_fragment:`PhysicalMaterial material; +material.diffuseColor = diffuseColor.rgb; +material.diffuseContribution = diffuseColor.rgb * ( 1.0 - metalnessFactor ); +material.metalness = metalnessFactor; +vec3 dxy = max( abs( dFdx( nonPerturbedNormal ) ), abs( dFdy( nonPerturbedNormal ) ) ); +float geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z ); +material.roughness = max( roughnessFactor, 0.0525 );material.roughness += geometryRoughness; +material.roughness = min( material.roughness, 1.0 ); +#ifdef IOR + material.ior = ior; + #ifdef USE_SPECULAR + float specularIntensityFactor = specularIntensity; + vec3 specularColorFactor = specularColor; + #ifdef USE_SPECULAR_COLORMAP + specularColorFactor *= texture2D( specularColorMap, vSpecularColorMapUv ).rgb; + #endif + #ifdef USE_SPECULAR_INTENSITYMAP + specularIntensityFactor *= texture2D( specularIntensityMap, vSpecularIntensityMapUv ).a; + #endif + material.specularF90 = mix( specularIntensityFactor, 1.0, metalnessFactor ); + #else + float specularIntensityFactor = 1.0; + vec3 specularColorFactor = vec3( 1.0 ); + material.specularF90 = 1.0; + #endif + material.specularColor = min( pow2( ( material.ior - 1.0 ) / ( material.ior + 1.0 ) ) * specularColorFactor, vec3( 1.0 ) ) * specularIntensityFactor; + material.specularColorBlended = mix( material.specularColor, diffuseColor.rgb, metalnessFactor ); +#else + material.specularColor = vec3( 0.04 ); + material.specularColorBlended = mix( material.specularColor, diffuseColor.rgb, metalnessFactor ); + material.specularF90 = 1.0; +#endif +#ifdef USE_CLEARCOAT + material.clearcoat = clearcoat; + material.clearcoatRoughness = clearcoatRoughness; + material.clearcoatF0 = vec3( 0.04 ); + material.clearcoatF90 = 1.0; + #ifdef USE_CLEARCOATMAP + material.clearcoat *= texture2D( clearcoatMap, vClearcoatMapUv ).x; + #endif + #ifdef USE_CLEARCOAT_ROUGHNESSMAP + material.clearcoatRoughness *= texture2D( clearcoatRoughnessMap, vClearcoatRoughnessMapUv ).y; + #endif + material.clearcoat = saturate( material.clearcoat ); material.clearcoatRoughness = max( material.clearcoatRoughness, 0.0525 ); + material.clearcoatRoughness += geometryRoughness; + material.clearcoatRoughness = min( material.clearcoatRoughness, 1.0 ); +#endif +#ifdef USE_DISPERSION + material.dispersion = dispersion; +#endif +#ifdef USE_IRIDESCENCE + material.iridescence = iridescence; + material.iridescenceIOR = iridescenceIOR; + #ifdef USE_IRIDESCENCEMAP + material.iridescence *= texture2D( iridescenceMap, vIridescenceMapUv ).r; + #endif + #ifdef USE_IRIDESCENCE_THICKNESSMAP + material.iridescenceThickness = (iridescenceThicknessMaximum - iridescenceThicknessMinimum) * texture2D( iridescenceThicknessMap, vIridescenceThicknessMapUv ).g + iridescenceThicknessMinimum; + #else + material.iridescenceThickness = iridescenceThicknessMaximum; + #endif +#endif +#ifdef USE_SHEEN + material.sheenColor = sheenColor; + #ifdef USE_SHEEN_COLORMAP + material.sheenColor *= texture2D( sheenColorMap, vSheenColorMapUv ).rgb; + #endif + material.sheenRoughness = clamp( sheenRoughness, 0.0001, 1.0 ); + #ifdef USE_SHEEN_ROUGHNESSMAP + material.sheenRoughness *= texture2D( sheenRoughnessMap, vSheenRoughnessMapUv ).a; + #endif +#endif +#ifdef USE_ANISOTROPY + #ifdef USE_ANISOTROPYMAP + mat2 anisotropyMat = mat2( anisotropyVector.x, anisotropyVector.y, - anisotropyVector.y, anisotropyVector.x ); + vec3 anisotropyPolar = texture2D( anisotropyMap, vAnisotropyMapUv ).rgb; + vec2 anisotropyV = anisotropyMat * normalize( 2.0 * anisotropyPolar.rg - vec2( 1.0 ) ) * anisotropyPolar.b; + #else + vec2 anisotropyV = anisotropyVector; + #endif + material.anisotropy = length( anisotropyV ); + if( material.anisotropy == 0.0 ) { + anisotropyV = vec2( 1.0, 0.0 ); + } else { + anisotropyV /= material.anisotropy; + material.anisotropy = saturate( material.anisotropy ); + } + material.alphaT = mix( pow2( material.roughness ), 1.0, pow2( material.anisotropy ) ); + material.anisotropyT = tbn[ 0 ] * anisotropyV.x + tbn[ 1 ] * anisotropyV.y; + material.anisotropyB = tbn[ 1 ] * anisotropyV.x - tbn[ 0 ] * anisotropyV.y; +#endif`,lights_physical_pars_fragment:`uniform sampler2D dfgLUT; +struct PhysicalMaterial { + vec3 diffuseColor; + vec3 diffuseContribution; + vec3 specularColor; + vec3 specularColorBlended; + float roughness; + float metalness; + float specularF90; + float dispersion; + #ifdef USE_CLEARCOAT + float clearcoat; + float clearcoatRoughness; + vec3 clearcoatF0; + float clearcoatF90; + #endif + #ifdef USE_IRIDESCENCE + float iridescence; + float iridescenceIOR; + float iridescenceThickness; + vec3 iridescenceFresnel; + vec3 iridescenceF0; + vec3 iridescenceFresnelDielectric; + vec3 iridescenceFresnelMetallic; + #endif + #ifdef USE_SHEEN + vec3 sheenColor; + float sheenRoughness; + #endif + #ifdef IOR + float ior; + #endif + #ifdef USE_TRANSMISSION + float transmission; + float transmissionAlpha; + float thickness; + float attenuationDistance; + vec3 attenuationColor; + #endif + #ifdef USE_ANISOTROPY + float anisotropy; + float alphaT; + vec3 anisotropyT; + vec3 anisotropyB; + #endif +}; +vec3 clearcoatSpecularDirect = vec3( 0.0 ); +vec3 clearcoatSpecularIndirect = vec3( 0.0 ); +vec3 sheenSpecularDirect = vec3( 0.0 ); +vec3 sheenSpecularIndirect = vec3(0.0 ); +vec3 Schlick_to_F0( const in vec3 f, const in float f90, const in float dotVH ) { + float x = clamp( 1.0 - dotVH, 0.0, 1.0 ); + float x2 = x * x; + float x5 = clamp( x * x2 * x2, 0.0, 0.9999 ); + return ( f - vec3( f90 ) * x5 ) / ( 1.0 - x5 ); +} +float V_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) { + float a2 = pow2( alpha ); + float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) ); + float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) ); + return 0.5 / max( gv + gl, EPSILON ); +} +float D_GGX( const in float alpha, const in float dotNH ) { + float a2 = pow2( alpha ); + float denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0; + return RECIPROCAL_PI * a2 / pow2( denom ); +} +#ifdef USE_ANISOTROPY + float V_GGX_SmithCorrelated_Anisotropic( const in float alphaT, const in float alphaB, const in float dotTV, const in float dotBV, const in float dotTL, const in float dotBL, const in float dotNV, const in float dotNL ) { + float gv = dotNL * length( vec3( alphaT * dotTV, alphaB * dotBV, dotNV ) ); + float gl = dotNV * length( vec3( alphaT * dotTL, alphaB * dotBL, dotNL ) ); + float v = 0.5 / ( gv + gl ); + return v; + } + float D_GGX_Anisotropic( const in float alphaT, const in float alphaB, const in float dotNH, const in float dotTH, const in float dotBH ) { + float a2 = alphaT * alphaB; + highp vec3 v = vec3( alphaB * dotTH, alphaT * dotBH, a2 * dotNH ); + highp float v2 = dot( v, v ); + float w2 = a2 / v2; + return RECIPROCAL_PI * a2 * pow2 ( w2 ); + } +#endif +#ifdef USE_CLEARCOAT + vec3 BRDF_GGX_Clearcoat( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material) { + vec3 f0 = material.clearcoatF0; + float f90 = material.clearcoatF90; + float roughness = material.clearcoatRoughness; + float alpha = pow2( roughness ); + vec3 halfDir = normalize( lightDir + viewDir ); + float dotNL = saturate( dot( normal, lightDir ) ); + float dotNV = saturate( dot( normal, viewDir ) ); + float dotNH = saturate( dot( normal, halfDir ) ); + float dotVH = saturate( dot( viewDir, halfDir ) ); + vec3 F = F_Schlick( f0, f90, dotVH ); + float V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV ); + float D = D_GGX( alpha, dotNH ); + return F * ( V * D ); + } +#endif +vec3 BRDF_GGX( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material ) { + vec3 f0 = material.specularColorBlended; + float f90 = material.specularF90; + float roughness = material.roughness; + float alpha = pow2( roughness ); + vec3 halfDir = normalize( lightDir + viewDir ); + float dotNL = saturate( dot( normal, lightDir ) ); + float dotNV = saturate( dot( normal, viewDir ) ); + float dotNH = saturate( dot( normal, halfDir ) ); + float dotVH = saturate( dot( viewDir, halfDir ) ); + vec3 F = F_Schlick( f0, f90, dotVH ); + #ifdef USE_IRIDESCENCE + F = mix( F, material.iridescenceFresnel, material.iridescence ); + #endif + #ifdef USE_ANISOTROPY + float dotTL = dot( material.anisotropyT, lightDir ); + float dotTV = dot( material.anisotropyT, viewDir ); + float dotTH = dot( material.anisotropyT, halfDir ); + float dotBL = dot( material.anisotropyB, lightDir ); + float dotBV = dot( material.anisotropyB, viewDir ); + float dotBH = dot( material.anisotropyB, halfDir ); + float V = V_GGX_SmithCorrelated_Anisotropic( material.alphaT, alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL ); + float D = D_GGX_Anisotropic( material.alphaT, alpha, dotNH, dotTH, dotBH ); + #else + float V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV ); + float D = D_GGX( alpha, dotNH ); + #endif + return F * ( V * D ); +} +vec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) { + const float LUT_SIZE = 64.0; + const float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE; + const float LUT_BIAS = 0.5 / LUT_SIZE; + float dotNV = saturate( dot( N, V ) ); + vec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) ); + uv = uv * LUT_SCALE + LUT_BIAS; + return uv; +} +float LTC_ClippedSphereFormFactor( const in vec3 f ) { + float l = length( f ); + return max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 ); +} +vec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) { + float x = dot( v1, v2 ); + float y = abs( x ); + float a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y; + float b = 3.4175940 + ( 4.1616724 + y ) * y; + float v = a / b; + float theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v; + return cross( v1, v2 ) * theta_sintheta; +} +vec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) { + vec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ]; + vec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ]; + vec3 lightNormal = cross( v1, v2 ); + if( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 ); + vec3 T1, T2; + T1 = normalize( V - N * dot( V, N ) ); + T2 = - cross( N, T1 ); + mat3 mat = mInv * transpose( mat3( T1, T2, N ) ); + vec3 coords[ 4 ]; + coords[ 0 ] = mat * ( rectCoords[ 0 ] - P ); + coords[ 1 ] = mat * ( rectCoords[ 1 ] - P ); + coords[ 2 ] = mat * ( rectCoords[ 2 ] - P ); + coords[ 3 ] = mat * ( rectCoords[ 3 ] - P ); + coords[ 0 ] = normalize( coords[ 0 ] ); + coords[ 1 ] = normalize( coords[ 1 ] ); + coords[ 2 ] = normalize( coords[ 2 ] ); + coords[ 3 ] = normalize( coords[ 3 ] ); + vec3 vectorFormFactor = vec3( 0.0 ); + vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] ); + vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] ); + vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] ); + vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] ); + float result = LTC_ClippedSphereFormFactor( vectorFormFactor ); + return vec3( result ); +} +#if defined( USE_SHEEN ) +float D_Charlie( float roughness, float dotNH ) { + float alpha = pow2( roughness ); + float invAlpha = 1.0 / alpha; + float cos2h = dotNH * dotNH; + float sin2h = max( 1.0 - cos2h, 0.0078125 ); + return ( 2.0 + invAlpha ) * pow( sin2h, invAlpha * 0.5 ) / ( 2.0 * PI ); +} +float V_Neubelt( float dotNV, float dotNL ) { + return saturate( 1.0 / ( 4.0 * ( dotNL + dotNV - dotNL * dotNV ) ) ); +} +vec3 BRDF_Sheen( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, vec3 sheenColor, const in float sheenRoughness ) { + vec3 halfDir = normalize( lightDir + viewDir ); + float dotNL = saturate( dot( normal, lightDir ) ); + float dotNV = saturate( dot( normal, viewDir ) ); + float dotNH = saturate( dot( normal, halfDir ) ); + float D = D_Charlie( sheenRoughness, dotNH ); + float V = V_Neubelt( dotNV, dotNL ); + return sheenColor * ( D * V ); +} +#endif +float IBLSheenBRDF( const in vec3 normal, const in vec3 viewDir, const in float roughness ) { + float dotNV = saturate( dot( normal, viewDir ) ); + float r2 = roughness * roughness; + float rInv = 1.0 / ( roughness + 0.1 ); + float a = -1.9362 + 1.0678 * roughness + 0.4573 * r2 - 0.8469 * rInv; + float b = -0.6014 + 0.5538 * roughness - 0.4670 * r2 - 0.1255 * rInv; + float DG = exp( a * dotNV + b ); + return saturate( DG ); +} +vec3 EnvironmentBRDF( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness ) { + float dotNV = saturate( dot( normal, viewDir ) ); + vec2 fab = texture2D( dfgLUT, vec2( roughness, dotNV ) ).rg; + return specularColor * fab.x + specularF90 * fab.y; +} +#ifdef USE_IRIDESCENCE +void computeMultiscatteringIridescence( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float iridescence, const in vec3 iridescenceF0, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) { +#else +void computeMultiscattering( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) { +#endif + float dotNV = saturate( dot( normal, viewDir ) ); + vec2 fab = texture2D( dfgLUT, vec2( roughness, dotNV ) ).rg; + #ifdef USE_IRIDESCENCE + vec3 Fr = mix( specularColor, iridescenceF0, iridescence ); + #else + vec3 Fr = specularColor; + #endif + vec3 FssEss = Fr * fab.x + specularF90 * fab.y; + float Ess = fab.x + fab.y; + float Ems = 1.0 - Ess; + vec3 Favg = Fr + ( 1.0 - Fr ) * 0.047619; vec3 Fms = FssEss * Favg / ( 1.0 - Ems * Favg ); + singleScatter += FssEss; + multiScatter += Fms * Ems; +} +vec3 BRDF_GGX_Multiscatter( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material ) { + vec3 singleScatter = BRDF_GGX( lightDir, viewDir, normal, material ); + float dotNL = saturate( dot( normal, lightDir ) ); + float dotNV = saturate( dot( normal, viewDir ) ); + vec2 dfgV = texture2D( dfgLUT, vec2( material.roughness, dotNV ) ).rg; + vec2 dfgL = texture2D( dfgLUT, vec2( material.roughness, dotNL ) ).rg; + vec3 FssEss_V = material.specularColorBlended * dfgV.x + material.specularF90 * dfgV.y; + vec3 FssEss_L = material.specularColorBlended * dfgL.x + material.specularF90 * dfgL.y; + float Ess_V = dfgV.x + dfgV.y; + float Ess_L = dfgL.x + dfgL.y; + float Ems_V = 1.0 - Ess_V; + float Ems_L = 1.0 - Ess_L; + vec3 Favg = material.specularColorBlended + ( 1.0 - material.specularColorBlended ) * 0.047619; + vec3 Fms = FssEss_V * FssEss_L * Favg / ( 1.0 - Ems_V * Ems_L * Favg + EPSILON ); + float compensationFactor = Ems_V * Ems_L; + vec3 multiScatter = Fms * compensationFactor; + return singleScatter + multiScatter; +} +#if NUM_RECT_AREA_LIGHTS > 0 + void RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) { + vec3 normal = geometryNormal; + vec3 viewDir = geometryViewDir; + vec3 position = geometryPosition; + vec3 lightPos = rectAreaLight.position; + vec3 halfWidth = rectAreaLight.halfWidth; + vec3 halfHeight = rectAreaLight.halfHeight; + vec3 lightColor = rectAreaLight.color; + float roughness = material.roughness; + vec3 rectCoords[ 4 ]; + rectCoords[ 0 ] = lightPos + halfWidth - halfHeight; rectCoords[ 1 ] = lightPos - halfWidth - halfHeight; + rectCoords[ 2 ] = lightPos - halfWidth + halfHeight; + rectCoords[ 3 ] = lightPos + halfWidth + halfHeight; + vec2 uv = LTC_Uv( normal, viewDir, roughness ); + vec4 t1 = texture2D( ltc_1, uv ); + vec4 t2 = texture2D( ltc_2, uv ); + mat3 mInv = mat3( + vec3( t1.x, 0, t1.y ), + vec3( 0, 1, 0 ), + vec3( t1.z, 0, t1.w ) + ); + vec3 fresnel = ( material.specularColorBlended * t2.x + ( material.specularF90 - material.specularColorBlended ) * t2.y ); + reflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords ); + reflectedLight.directDiffuse += lightColor * material.diffuseContribution * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords ); + #ifdef USE_CLEARCOAT + vec3 Ncc = geometryClearcoatNormal; + vec2 uvClearcoat = LTC_Uv( Ncc, viewDir, material.clearcoatRoughness ); + vec4 t1Clearcoat = texture2D( ltc_1, uvClearcoat ); + vec4 t2Clearcoat = texture2D( ltc_2, uvClearcoat ); + mat3 mInvClearcoat = mat3( + vec3( t1Clearcoat.x, 0, t1Clearcoat.y ), + vec3( 0, 1, 0 ), + vec3( t1Clearcoat.z, 0, t1Clearcoat.w ) + ); + vec3 fresnelClearcoat = material.clearcoatF0 * t2Clearcoat.x + ( material.clearcoatF90 - material.clearcoatF0 ) * t2Clearcoat.y; + clearcoatSpecularDirect += lightColor * fresnelClearcoat * LTC_Evaluate( Ncc, viewDir, position, mInvClearcoat, rectCoords ); + #endif + } +#endif +void RE_Direct_Physical( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) { + float dotNL = saturate( dot( geometryNormal, directLight.direction ) ); + vec3 irradiance = dotNL * directLight.color; + #ifdef USE_CLEARCOAT + float dotNLcc = saturate( dot( geometryClearcoatNormal, directLight.direction ) ); + vec3 ccIrradiance = dotNLcc * directLight.color; + clearcoatSpecularDirect += ccIrradiance * BRDF_GGX_Clearcoat( directLight.direction, geometryViewDir, geometryClearcoatNormal, material ); + #endif + #ifdef USE_SHEEN + + sheenSpecularDirect += irradiance * BRDF_Sheen( directLight.direction, geometryViewDir, geometryNormal, material.sheenColor, material.sheenRoughness ); + + float sheenAlbedoV = IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness ); + float sheenAlbedoL = IBLSheenBRDF( geometryNormal, directLight.direction, material.sheenRoughness ); + + float sheenEnergyComp = 1.0 - max3( material.sheenColor ) * max( sheenAlbedoV, sheenAlbedoL ); + + irradiance *= sheenEnergyComp; + + #endif + reflectedLight.directSpecular += irradiance * BRDF_GGX_Multiscatter( directLight.direction, geometryViewDir, geometryNormal, material ); + reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseContribution ); +} +void RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) { + vec3 diffuse = irradiance * BRDF_Lambert( material.diffuseContribution ); + #ifdef USE_SHEEN + float sheenAlbedo = IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness ); + float sheenEnergyComp = 1.0 - max3( material.sheenColor ) * sheenAlbedo; + diffuse *= sheenEnergyComp; + #endif + reflectedLight.indirectDiffuse += diffuse; +} +void RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 irradiance, const in vec3 clearcoatRadiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight) { + #ifdef USE_CLEARCOAT + clearcoatSpecularIndirect += clearcoatRadiance * EnvironmentBRDF( geometryClearcoatNormal, geometryViewDir, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness ); + #endif + #ifdef USE_SHEEN + sheenSpecularIndirect += irradiance * material.sheenColor * IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness ) * RECIPROCAL_PI; + #endif + vec3 singleScatteringDielectric = vec3( 0.0 ); + vec3 multiScatteringDielectric = vec3( 0.0 ); + vec3 singleScatteringMetallic = vec3( 0.0 ); + vec3 multiScatteringMetallic = vec3( 0.0 ); + #ifdef USE_IRIDESCENCE + computeMultiscatteringIridescence( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.iridescence, material.iridescenceFresnelDielectric, material.roughness, singleScatteringDielectric, multiScatteringDielectric ); + computeMultiscatteringIridescence( geometryNormal, geometryViewDir, material.diffuseColor, material.specularF90, material.iridescence, material.iridescenceFresnelMetallic, material.roughness, singleScatteringMetallic, multiScatteringMetallic ); + #else + computeMultiscattering( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.roughness, singleScatteringDielectric, multiScatteringDielectric ); + computeMultiscattering( geometryNormal, geometryViewDir, material.diffuseColor, material.specularF90, material.roughness, singleScatteringMetallic, multiScatteringMetallic ); + #endif + vec3 singleScattering = mix( singleScatteringDielectric, singleScatteringMetallic, material.metalness ); + vec3 multiScattering = mix( multiScatteringDielectric, multiScatteringMetallic, material.metalness ); + vec3 totalScatteringDielectric = singleScatteringDielectric + multiScatteringDielectric; + vec3 diffuse = material.diffuseContribution * ( 1.0 - totalScatteringDielectric ); + vec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI; + vec3 indirectSpecular = radiance * singleScattering; + indirectSpecular += multiScattering * cosineWeightedIrradiance; + vec3 indirectDiffuse = diffuse * cosineWeightedIrradiance; + #ifdef USE_SHEEN + float sheenAlbedo = IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness ); + float sheenEnergyComp = 1.0 - max3( material.sheenColor ) * sheenAlbedo; + indirectSpecular *= sheenEnergyComp; + indirectDiffuse *= sheenEnergyComp; + #endif + reflectedLight.indirectSpecular += indirectSpecular; + reflectedLight.indirectDiffuse += indirectDiffuse; +} +#define RE_Direct RE_Direct_Physical +#define RE_Direct_RectArea RE_Direct_RectArea_Physical +#define RE_IndirectDiffuse RE_IndirectDiffuse_Physical +#define RE_IndirectSpecular RE_IndirectSpecular_Physical +float computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) { + return saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion ); +}`,lights_fragment_begin:` +vec3 geometryPosition = - vViewPosition; +vec3 geometryNormal = normal; +vec3 geometryViewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition ); +vec3 geometryClearcoatNormal = vec3( 0.0 ); +#ifdef USE_CLEARCOAT + geometryClearcoatNormal = clearcoatNormal; +#endif +#ifdef USE_IRIDESCENCE + float dotNVi = saturate( dot( normal, geometryViewDir ) ); + if ( material.iridescenceThickness == 0.0 ) { + material.iridescence = 0.0; + } else { + material.iridescence = saturate( material.iridescence ); + } + if ( material.iridescence > 0.0 ) { + material.iridescenceFresnelDielectric = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.specularColor ); + material.iridescenceFresnelMetallic = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.diffuseColor ); + material.iridescenceFresnel = mix( material.iridescenceFresnelDielectric, material.iridescenceFresnelMetallic, material.metalness ); + material.iridescenceF0 = Schlick_to_F0( material.iridescenceFresnel, 1.0, dotNVi ); + } +#endif +IncidentLight directLight; +#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct ) + PointLight pointLight; + #if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0 + PointLightShadow pointLightShadow; + #endif + #pragma unroll_loop_start + for ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) { + pointLight = pointLights[ i ]; + getPointLightInfo( pointLight, geometryPosition, directLight ); + #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS ) && ( defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_BASIC ) ) + pointLightShadow = pointLightShadows[ i ]; + directLight.color *= ( directLight.visible && receiveShadow ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowIntensity, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0; + #endif + RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); + } + #pragma unroll_loop_end +#endif +#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct ) + SpotLight spotLight; + vec4 spotColor; + vec3 spotLightCoord; + bool inSpotLightMap; + #if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0 + SpotLightShadow spotLightShadow; + #endif + #pragma unroll_loop_start + for ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) { + spotLight = spotLights[ i ]; + getSpotLightInfo( spotLight, geometryPosition, directLight ); + #if ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS ) + #define SPOT_LIGHT_MAP_INDEX UNROLLED_LOOP_INDEX + #elif ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS ) + #define SPOT_LIGHT_MAP_INDEX NUM_SPOT_LIGHT_MAPS + #else + #define SPOT_LIGHT_MAP_INDEX ( UNROLLED_LOOP_INDEX - NUM_SPOT_LIGHT_SHADOWS + NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS ) + #endif + #if ( SPOT_LIGHT_MAP_INDEX < NUM_SPOT_LIGHT_MAPS ) + spotLightCoord = vSpotLightCoord[ i ].xyz / vSpotLightCoord[ i ].w; + inSpotLightMap = all( lessThan( abs( spotLightCoord * 2. - 1. ), vec3( 1.0 ) ) ); + spotColor = texture2D( spotLightMap[ SPOT_LIGHT_MAP_INDEX ], spotLightCoord.xy ); + directLight.color = inSpotLightMap ? directLight.color * spotColor.rgb : directLight.color; + #endif + #undef SPOT_LIGHT_MAP_INDEX + #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS ) + spotLightShadow = spotLightShadows[ i ]; + directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowIntensity, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotLightCoord[ i ] ) : 1.0; + #endif + RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); + } + #pragma unroll_loop_end +#endif +#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct ) + DirectionalLight directionalLight; + #if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0 + DirectionalLightShadow directionalLightShadow; + #endif + #pragma unroll_loop_start + for ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) { + directionalLight = directionalLights[ i ]; + getDirectionalLightInfo( directionalLight, directLight ); + #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS ) + directionalLightShadow = directionalLightShadows[ i ]; + directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowIntensity, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0; + #endif + RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); + } + #pragma unroll_loop_end +#endif +#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea ) + RectAreaLight rectAreaLight; + #pragma unroll_loop_start + for ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) { + rectAreaLight = rectAreaLights[ i ]; + RE_Direct_RectArea( rectAreaLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); + } + #pragma unroll_loop_end +#endif +#if defined( RE_IndirectDiffuse ) + vec3 iblIrradiance = vec3( 0.0 ); + vec3 irradiance = getAmbientLightIrradiance( ambientLightColor ); + #if defined( USE_LIGHT_PROBES ) + irradiance += getLightProbeIrradiance( lightProbe, geometryNormal ); + #endif + #if ( NUM_HEMI_LIGHTS > 0 ) + #pragma unroll_loop_start + for ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) { + irradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometryNormal ); + } + #pragma unroll_loop_end + #endif +#endif +#if defined( RE_IndirectSpecular ) + vec3 radiance = vec3( 0.0 ); + vec3 clearcoatRadiance = vec3( 0.0 ); +#endif`,lights_fragment_maps:`#if defined( RE_IndirectDiffuse ) + #ifdef USE_LIGHTMAP + vec4 lightMapTexel = texture2D( lightMap, vLightMapUv ); + vec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity; + irradiance += lightMapIrradiance; + #endif + #if defined( USE_ENVMAP ) && defined( ENVMAP_TYPE_CUBE_UV ) + #if defined( STANDARD ) || defined( LAMBERT ) || defined( PHONG ) + iblIrradiance += getIBLIrradiance( geometryNormal ); + #endif + #endif +#endif +#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular ) + #ifdef USE_ANISOTROPY + radiance += getIBLAnisotropyRadiance( geometryViewDir, geometryNormal, material.roughness, material.anisotropyB, material.anisotropy ); + #else + radiance += getIBLRadiance( geometryViewDir, geometryNormal, material.roughness ); + #endif + #ifdef USE_CLEARCOAT + clearcoatRadiance += getIBLRadiance( geometryViewDir, geometryClearcoatNormal, material.clearcoatRoughness ); + #endif +#endif`,lights_fragment_end:`#if defined( RE_IndirectDiffuse ) + #if defined( LAMBERT ) || defined( PHONG ) + irradiance += iblIrradiance; + #endif + RE_IndirectDiffuse( irradiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); +#endif +#if defined( RE_IndirectSpecular ) + RE_IndirectSpecular( radiance, iblIrradiance, clearcoatRadiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); +#endif`,logdepthbuf_fragment:`#if defined( USE_LOGARITHMIC_DEPTH_BUFFER ) + gl_FragDepth = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5; +#endif`,logdepthbuf_pars_fragment:`#if defined( USE_LOGARITHMIC_DEPTH_BUFFER ) + uniform float logDepthBufFC; + varying float vFragDepth; + varying float vIsPerspective; +#endif`,logdepthbuf_pars_vertex:`#ifdef USE_LOGARITHMIC_DEPTH_BUFFER + varying float vFragDepth; + varying float vIsPerspective; +#endif`,logdepthbuf_vertex:`#ifdef USE_LOGARITHMIC_DEPTH_BUFFER + vFragDepth = 1.0 + gl_Position.w; + vIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) ); +#endif`,map_fragment:`#ifdef USE_MAP + vec4 sampledDiffuseColor = texture2D( map, vMapUv ); + #ifdef DECODE_VIDEO_TEXTURE + sampledDiffuseColor = sRGBTransferEOTF( sampledDiffuseColor ); + #endif + diffuseColor *= sampledDiffuseColor; +#endif`,map_pars_fragment:`#ifdef USE_MAP + uniform sampler2D map; +#endif`,map_particle_fragment:`#if defined( USE_MAP ) || defined( USE_ALPHAMAP ) + #if defined( USE_POINTS_UV ) + vec2 uv = vUv; + #else + vec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy; + #endif +#endif +#ifdef USE_MAP + diffuseColor *= texture2D( map, uv ); +#endif +#ifdef USE_ALPHAMAP + diffuseColor.a *= texture2D( alphaMap, uv ).g; +#endif`,map_particle_pars_fragment:`#if defined( USE_POINTS_UV ) + varying vec2 vUv; +#else + #if defined( USE_MAP ) || defined( USE_ALPHAMAP ) + uniform mat3 uvTransform; + #endif +#endif +#ifdef USE_MAP + uniform sampler2D map; +#endif +#ifdef USE_ALPHAMAP + uniform sampler2D alphaMap; +#endif`,metalnessmap_fragment:`float metalnessFactor = metalness; +#ifdef USE_METALNESSMAP + vec4 texelMetalness = texture2D( metalnessMap, vMetalnessMapUv ); + metalnessFactor *= texelMetalness.b; +#endif`,metalnessmap_pars_fragment:`#ifdef USE_METALNESSMAP + uniform sampler2D metalnessMap; +#endif`,morphinstance_vertex:`#ifdef USE_INSTANCING_MORPH + float morphTargetInfluences[ MORPHTARGETS_COUNT ]; + float morphTargetBaseInfluence = texelFetch( morphTexture, ivec2( 0, gl_InstanceID ), 0 ).r; + for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) { + morphTargetInfluences[i] = texelFetch( morphTexture, ivec2( i + 1, gl_InstanceID ), 0 ).r; + } +#endif`,morphcolor_vertex:`#if defined( USE_MORPHCOLORS ) + vColor *= morphTargetBaseInfluence; + for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) { + #if defined( USE_COLOR_ALPHA ) + if ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ) * morphTargetInfluences[ i ]; + #elif defined( USE_COLOR ) + if ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ).rgb * morphTargetInfluences[ i ]; + #endif + } +#endif`,morphnormal_vertex:`#ifdef USE_MORPHNORMALS + objectNormal *= morphTargetBaseInfluence; + for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) { + if ( morphTargetInfluences[ i ] != 0.0 ) objectNormal += getMorph( gl_VertexID, i, 1 ).xyz * morphTargetInfluences[ i ]; + } +#endif`,morphtarget_pars_vertex:`#ifdef USE_MORPHTARGETS + #ifndef USE_INSTANCING_MORPH + uniform float morphTargetBaseInfluence; + uniform float morphTargetInfluences[ MORPHTARGETS_COUNT ]; + #endif + uniform sampler2DArray morphTargetsTexture; + uniform ivec2 morphTargetsTextureSize; + vec4 getMorph( const in int vertexIndex, const in int morphTargetIndex, const in int offset ) { + int texelIndex = vertexIndex * MORPHTARGETS_TEXTURE_STRIDE + offset; + int y = texelIndex / morphTargetsTextureSize.x; + int x = texelIndex - y * morphTargetsTextureSize.x; + ivec3 morphUV = ivec3( x, y, morphTargetIndex ); + return texelFetch( morphTargetsTexture, morphUV, 0 ); + } +#endif`,morphtarget_vertex:`#ifdef USE_MORPHTARGETS + transformed *= morphTargetBaseInfluence; + for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) { + if ( morphTargetInfluences[ i ] != 0.0 ) transformed += getMorph( gl_VertexID, i, 0 ).xyz * morphTargetInfluences[ i ]; + } +#endif`,normal_fragment_begin:`float faceDirection = gl_FrontFacing ? 1.0 : - 1.0; +#ifdef FLAT_SHADED + vec3 fdx = dFdx( vViewPosition ); + vec3 fdy = dFdy( vViewPosition ); + vec3 normal = normalize( cross( fdx, fdy ) ); +#else + vec3 normal = normalize( vNormal ); + #ifdef DOUBLE_SIDED + normal *= faceDirection; + #endif +#endif +#if defined( USE_NORMALMAP_TANGENTSPACE ) || defined( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY ) + #ifdef USE_TANGENT + mat3 tbn = mat3( normalize( vTangent ), normalize( vBitangent ), normal ); + #else + mat3 tbn = getTangentFrame( - vViewPosition, normal, + #if defined( USE_NORMALMAP ) + vNormalMapUv + #elif defined( USE_CLEARCOAT_NORMALMAP ) + vClearcoatNormalMapUv + #else + vUv + #endif + ); + #endif + #if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED ) + tbn[0] *= faceDirection; + tbn[1] *= faceDirection; + #endif +#endif +#ifdef USE_CLEARCOAT_NORMALMAP + #ifdef USE_TANGENT + mat3 tbn2 = mat3( normalize( vTangent ), normalize( vBitangent ), normal ); + #else + mat3 tbn2 = getTangentFrame( - vViewPosition, normal, vClearcoatNormalMapUv ); + #endif + #if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED ) + tbn2[0] *= faceDirection; + tbn2[1] *= faceDirection; + #endif +#endif +vec3 nonPerturbedNormal = normal;`,normal_fragment_maps:`#ifdef USE_NORMALMAP_OBJECTSPACE + normal = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0; + #ifdef FLIP_SIDED + normal = - normal; + #endif + #ifdef DOUBLE_SIDED + normal = normal * faceDirection; + #endif + normal = normalize( normalMatrix * normal ); +#elif defined( USE_NORMALMAP_TANGENTSPACE ) + vec3 mapN = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0; + mapN.xy *= normalScale; + normal = normalize( tbn * mapN ); +#elif defined( USE_BUMPMAP ) + normal = perturbNormalArb( - vViewPosition, normal, dHdxy_fwd(), faceDirection ); +#endif`,normal_pars_fragment:`#ifndef FLAT_SHADED + varying vec3 vNormal; + #ifdef USE_TANGENT + varying vec3 vTangent; + varying vec3 vBitangent; + #endif +#endif`,normal_pars_vertex:`#ifndef FLAT_SHADED + varying vec3 vNormal; + #ifdef USE_TANGENT + varying vec3 vTangent; + varying vec3 vBitangent; + #endif +#endif`,normal_vertex:`#ifndef FLAT_SHADED + vNormal = normalize( transformedNormal ); + #ifdef USE_TANGENT + vTangent = normalize( transformedTangent ); + vBitangent = normalize( cross( vNormal, vTangent ) * tangent.w ); + #endif +#endif`,normalmap_pars_fragment:`#ifdef USE_NORMALMAP + uniform sampler2D normalMap; + uniform vec2 normalScale; +#endif +#ifdef USE_NORMALMAP_OBJECTSPACE + uniform mat3 normalMatrix; +#endif +#if ! defined ( USE_TANGENT ) && ( defined ( USE_NORMALMAP_TANGENTSPACE ) || defined ( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY ) ) + mat3 getTangentFrame( vec3 eye_pos, vec3 surf_norm, vec2 uv ) { + vec3 q0 = dFdx( eye_pos.xyz ); + vec3 q1 = dFdy( eye_pos.xyz ); + vec2 st0 = dFdx( uv.st ); + vec2 st1 = dFdy( uv.st ); + vec3 N = surf_norm; + vec3 q1perp = cross( q1, N ); + vec3 q0perp = cross( N, q0 ); + vec3 T = q1perp * st0.x + q0perp * st1.x; + vec3 B = q1perp * st0.y + q0perp * st1.y; + float det = max( dot( T, T ), dot( B, B ) ); + float scale = ( det == 0.0 ) ? 0.0 : inversesqrt( det ); + return mat3( T * scale, B * scale, N ); + } +#endif`,clearcoat_normal_fragment_begin:`#ifdef USE_CLEARCOAT + vec3 clearcoatNormal = nonPerturbedNormal; +#endif`,clearcoat_normal_fragment_maps:`#ifdef USE_CLEARCOAT_NORMALMAP + vec3 clearcoatMapN = texture2D( clearcoatNormalMap, vClearcoatNormalMapUv ).xyz * 2.0 - 1.0; + clearcoatMapN.xy *= clearcoatNormalScale; + clearcoatNormal = normalize( tbn2 * clearcoatMapN ); +#endif`,clearcoat_pars_fragment:`#ifdef USE_CLEARCOATMAP + uniform sampler2D clearcoatMap; +#endif +#ifdef USE_CLEARCOAT_NORMALMAP + uniform sampler2D clearcoatNormalMap; + uniform vec2 clearcoatNormalScale; +#endif +#ifdef USE_CLEARCOAT_ROUGHNESSMAP + uniform sampler2D clearcoatRoughnessMap; +#endif`,iridescence_pars_fragment:`#ifdef USE_IRIDESCENCEMAP + uniform sampler2D iridescenceMap; +#endif +#ifdef USE_IRIDESCENCE_THICKNESSMAP + uniform sampler2D iridescenceThicknessMap; +#endif`,opaque_fragment:`#ifdef OPAQUE +diffuseColor.a = 1.0; +#endif +#ifdef USE_TRANSMISSION +diffuseColor.a *= material.transmissionAlpha; +#endif +gl_FragColor = vec4( outgoingLight, diffuseColor.a );`,packing:`vec3 packNormalToRGB( const in vec3 normal ) { + return normalize( normal ) * 0.5 + 0.5; +} +vec3 unpackRGBToNormal( const in vec3 rgb ) { + return 2.0 * rgb.xyz - 1.0; +} +const float PackUpscale = 256. / 255.;const float UnpackDownscale = 255. / 256.;const float ShiftRight8 = 1. / 256.; +const float Inv255 = 1. / 255.; +const vec4 PackFactors = vec4( 1.0, 256.0, 256.0 * 256.0, 256.0 * 256.0 * 256.0 ); +const vec2 UnpackFactors2 = vec2( UnpackDownscale, 1.0 / PackFactors.g ); +const vec3 UnpackFactors3 = vec3( UnpackDownscale / PackFactors.rg, 1.0 / PackFactors.b ); +const vec4 UnpackFactors4 = vec4( UnpackDownscale / PackFactors.rgb, 1.0 / PackFactors.a ); +vec4 packDepthToRGBA( const in float v ) { + if( v <= 0.0 ) + return vec4( 0., 0., 0., 0. ); + if( v >= 1.0 ) + return vec4( 1., 1., 1., 1. ); + float vuf; + float af = modf( v * PackFactors.a, vuf ); + float bf = modf( vuf * ShiftRight8, vuf ); + float gf = modf( vuf * ShiftRight8, vuf ); + return vec4( vuf * Inv255, gf * PackUpscale, bf * PackUpscale, af ); +} +vec3 packDepthToRGB( const in float v ) { + if( v <= 0.0 ) + return vec3( 0., 0., 0. ); + if( v >= 1.0 ) + return vec3( 1., 1., 1. ); + float vuf; + float bf = modf( v * PackFactors.b, vuf ); + float gf = modf( vuf * ShiftRight8, vuf ); + return vec3( vuf * Inv255, gf * PackUpscale, bf ); +} +vec2 packDepthToRG( const in float v ) { + if( v <= 0.0 ) + return vec2( 0., 0. ); + if( v >= 1.0 ) + return vec2( 1., 1. ); + float vuf; + float gf = modf( v * 256., vuf ); + return vec2( vuf * Inv255, gf ); +} +float unpackRGBAToDepth( const in vec4 v ) { + return dot( v, UnpackFactors4 ); +} +float unpackRGBToDepth( const in vec3 v ) { + return dot( v, UnpackFactors3 ); +} +float unpackRGToDepth( const in vec2 v ) { + return v.r * UnpackFactors2.r + v.g * UnpackFactors2.g; +} +vec4 pack2HalfToRGBA( const in vec2 v ) { + vec4 r = vec4( v.x, fract( v.x * 255.0 ), v.y, fract( v.y * 255.0 ) ); + return vec4( r.x - r.y / 255.0, r.y, r.z - r.w / 255.0, r.w ); +} +vec2 unpackRGBATo2Half( const in vec4 v ) { + return vec2( v.x + ( v.y / 255.0 ), v.z + ( v.w / 255.0 ) ); +} +float viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) { + return ( viewZ + near ) / ( near - far ); +} +float orthographicDepthToViewZ( const in float depth, const in float near, const in float far ) { + #ifdef USE_REVERSED_DEPTH_BUFFER + + return depth * ( far - near ) - far; + #else + return depth * ( near - far ) - near; + #endif +} +float viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) { + return ( ( near + viewZ ) * far ) / ( ( far - near ) * viewZ ); +} +float perspectiveDepthToViewZ( const in float depth, const in float near, const in float far ) { + + #ifdef USE_REVERSED_DEPTH_BUFFER + return ( near * far ) / ( ( near - far ) * depth - near ); + #else + return ( near * far ) / ( ( far - near ) * depth - far ); + #endif +}`,premultiplied_alpha_fragment:`#ifdef PREMULTIPLIED_ALPHA + gl_FragColor.rgb *= gl_FragColor.a; +#endif`,project_vertex:`vec4 mvPosition = vec4( transformed, 1.0 ); +#ifdef USE_BATCHING + mvPosition = batchingMatrix * mvPosition; +#endif +#ifdef USE_INSTANCING + mvPosition = instanceMatrix * mvPosition; +#endif +mvPosition = modelViewMatrix * mvPosition; +gl_Position = projectionMatrix * mvPosition;`,dithering_fragment:`#ifdef DITHERING + gl_FragColor.rgb = dithering( gl_FragColor.rgb ); +#endif`,dithering_pars_fragment:`#ifdef DITHERING + vec3 dithering( vec3 color ) { + float grid_position = rand( gl_FragCoord.xy ); + vec3 dither_shift_RGB = vec3( 0.25 / 255.0, -0.25 / 255.0, 0.25 / 255.0 ); + dither_shift_RGB = mix( 2.0 * dither_shift_RGB, -2.0 * dither_shift_RGB, grid_position ); + return color + dither_shift_RGB; + } +#endif`,roughnessmap_fragment:`float roughnessFactor = roughness; +#ifdef USE_ROUGHNESSMAP + vec4 texelRoughness = texture2D( roughnessMap, vRoughnessMapUv ); + roughnessFactor *= texelRoughness.g; +#endif`,roughnessmap_pars_fragment:`#ifdef USE_ROUGHNESSMAP + uniform sampler2D roughnessMap; +#endif`,shadowmap_pars_fragment:`#if NUM_SPOT_LIGHT_COORDS > 0 + varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ]; +#endif +#if NUM_SPOT_LIGHT_MAPS > 0 + uniform sampler2D spotLightMap[ NUM_SPOT_LIGHT_MAPS ]; +#endif +#ifdef USE_SHADOWMAP + #if NUM_DIR_LIGHT_SHADOWS > 0 + #if defined( SHADOWMAP_TYPE_PCF ) + uniform sampler2DShadow directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ]; + #else + uniform sampler2D directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ]; + #endif + varying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ]; + struct DirectionalLightShadow { + float shadowIntensity; + float shadowBias; + float shadowNormalBias; + float shadowRadius; + vec2 shadowMapSize; + }; + uniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ]; + #endif + #if NUM_SPOT_LIGHT_SHADOWS > 0 + #if defined( SHADOWMAP_TYPE_PCF ) + uniform sampler2DShadow spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ]; + #else + uniform sampler2D spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ]; + #endif + struct SpotLightShadow { + float shadowIntensity; + float shadowBias; + float shadowNormalBias; + float shadowRadius; + vec2 shadowMapSize; + }; + uniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ]; + #endif + #if NUM_POINT_LIGHT_SHADOWS > 0 + #if defined( SHADOWMAP_TYPE_PCF ) + uniform samplerCubeShadow pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ]; + #elif defined( SHADOWMAP_TYPE_BASIC ) + uniform samplerCube pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ]; + #endif + varying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ]; + struct PointLightShadow { + float shadowIntensity; + float shadowBias; + float shadowNormalBias; + float shadowRadius; + vec2 shadowMapSize; + float shadowCameraNear; + float shadowCameraFar; + }; + uniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ]; + #endif + #if defined( SHADOWMAP_TYPE_PCF ) + float interleavedGradientNoise( vec2 position ) { + return fract( 52.9829189 * fract( dot( position, vec2( 0.06711056, 0.00583715 ) ) ) ); + } + vec2 vogelDiskSample( int sampleIndex, int samplesCount, float phi ) { + const float goldenAngle = 2.399963229728653; + float r = sqrt( ( float( sampleIndex ) + 0.5 ) / float( samplesCount ) ); + float theta = float( sampleIndex ) * goldenAngle + phi; + return vec2( cos( theta ), sin( theta ) ) * r; + } + #endif + #if defined( SHADOWMAP_TYPE_PCF ) + float getShadow( sampler2DShadow shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord ) { + float shadow = 1.0; + shadowCoord.xyz /= shadowCoord.w; + shadowCoord.z += shadowBias; + bool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0; + bool frustumTest = inFrustum && shadowCoord.z <= 1.0; + if ( frustumTest ) { + vec2 texelSize = vec2( 1.0 ) / shadowMapSize; + float radius = shadowRadius * texelSize.x; + float phi = interleavedGradientNoise( gl_FragCoord.xy ) * PI2; + shadow = ( + texture( shadowMap, vec3( shadowCoord.xy + vogelDiskSample( 0, 5, phi ) * radius, shadowCoord.z ) ) + + texture( shadowMap, vec3( shadowCoord.xy + vogelDiskSample( 1, 5, phi ) * radius, shadowCoord.z ) ) + + texture( shadowMap, vec3( shadowCoord.xy + vogelDiskSample( 2, 5, phi ) * radius, shadowCoord.z ) ) + + texture( shadowMap, vec3( shadowCoord.xy + vogelDiskSample( 3, 5, phi ) * radius, shadowCoord.z ) ) + + texture( shadowMap, vec3( shadowCoord.xy + vogelDiskSample( 4, 5, phi ) * radius, shadowCoord.z ) ) + ) * 0.2; + } + return mix( 1.0, shadow, shadowIntensity ); + } + #elif defined( SHADOWMAP_TYPE_VSM ) + float getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord ) { + float shadow = 1.0; + shadowCoord.xyz /= shadowCoord.w; + #ifdef USE_REVERSED_DEPTH_BUFFER + shadowCoord.z -= shadowBias; + #else + shadowCoord.z += shadowBias; + #endif + bool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0; + bool frustumTest = inFrustum && shadowCoord.z <= 1.0; + if ( frustumTest ) { + vec2 distribution = texture2D( shadowMap, shadowCoord.xy ).rg; + float mean = distribution.x; + float variance = distribution.y * distribution.y; + #ifdef USE_REVERSED_DEPTH_BUFFER + float hard_shadow = step( mean, shadowCoord.z ); + #else + float hard_shadow = step( shadowCoord.z, mean ); + #endif + + if ( hard_shadow == 1.0 ) { + shadow = 1.0; + } else { + variance = max( variance, 0.0000001 ); + float d = shadowCoord.z - mean; + float p_max = variance / ( variance + d * d ); + p_max = clamp( ( p_max - 0.3 ) / 0.65, 0.0, 1.0 ); + shadow = max( hard_shadow, p_max ); + } + } + return mix( 1.0, shadow, shadowIntensity ); + } + #else + float getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord ) { + float shadow = 1.0; + shadowCoord.xyz /= shadowCoord.w; + #ifdef USE_REVERSED_DEPTH_BUFFER + shadowCoord.z -= shadowBias; + #else + shadowCoord.z += shadowBias; + #endif + bool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0; + bool frustumTest = inFrustum && shadowCoord.z <= 1.0; + if ( frustumTest ) { + float depth = texture2D( shadowMap, shadowCoord.xy ).r; + #ifdef USE_REVERSED_DEPTH_BUFFER + shadow = step( depth, shadowCoord.z ); + #else + shadow = step( shadowCoord.z, depth ); + #endif + } + return mix( 1.0, shadow, shadowIntensity ); + } + #endif + #if NUM_POINT_LIGHT_SHADOWS > 0 + #if defined( SHADOWMAP_TYPE_PCF ) + float getPointShadow( samplerCubeShadow shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) { + float shadow = 1.0; + vec3 lightToPosition = shadowCoord.xyz; + vec3 bd3D = normalize( lightToPosition ); + vec3 absVec = abs( lightToPosition ); + float viewSpaceZ = max( max( absVec.x, absVec.y ), absVec.z ); + if ( viewSpaceZ - shadowCameraFar <= 0.0 && viewSpaceZ - shadowCameraNear >= 0.0 ) { + #ifdef USE_REVERSED_DEPTH_BUFFER + float dp = ( shadowCameraNear * ( shadowCameraFar - viewSpaceZ ) ) / ( viewSpaceZ * ( shadowCameraFar - shadowCameraNear ) ); + dp -= shadowBias; + #else + float dp = ( shadowCameraFar * ( viewSpaceZ - shadowCameraNear ) ) / ( viewSpaceZ * ( shadowCameraFar - shadowCameraNear ) ); + dp += shadowBias; + #endif + float texelSize = shadowRadius / shadowMapSize.x; + vec3 absDir = abs( bd3D ); + vec3 tangent = absDir.x > absDir.z ? vec3( 0.0, 1.0, 0.0 ) : vec3( 1.0, 0.0, 0.0 ); + tangent = normalize( cross( bd3D, tangent ) ); + vec3 bitangent = cross( bd3D, tangent ); + float phi = interleavedGradientNoise( gl_FragCoord.xy ) * PI2; + vec2 sample0 = vogelDiskSample( 0, 5, phi ); + vec2 sample1 = vogelDiskSample( 1, 5, phi ); + vec2 sample2 = vogelDiskSample( 2, 5, phi ); + vec2 sample3 = vogelDiskSample( 3, 5, phi ); + vec2 sample4 = vogelDiskSample( 4, 5, phi ); + shadow = ( + texture( shadowMap, vec4( bd3D + ( tangent * sample0.x + bitangent * sample0.y ) * texelSize, dp ) ) + + texture( shadowMap, vec4( bd3D + ( tangent * sample1.x + bitangent * sample1.y ) * texelSize, dp ) ) + + texture( shadowMap, vec4( bd3D + ( tangent * sample2.x + bitangent * sample2.y ) * texelSize, dp ) ) + + texture( shadowMap, vec4( bd3D + ( tangent * sample3.x + bitangent * sample3.y ) * texelSize, dp ) ) + + texture( shadowMap, vec4( bd3D + ( tangent * sample4.x + bitangent * sample4.y ) * texelSize, dp ) ) + ) * 0.2; + } + return mix( 1.0, shadow, shadowIntensity ); + } + #elif defined( SHADOWMAP_TYPE_BASIC ) + float getPointShadow( samplerCube shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) { + float shadow = 1.0; + vec3 lightToPosition = shadowCoord.xyz; + vec3 absVec = abs( lightToPosition ); + float viewSpaceZ = max( max( absVec.x, absVec.y ), absVec.z ); + if ( viewSpaceZ - shadowCameraFar <= 0.0 && viewSpaceZ - shadowCameraNear >= 0.0 ) { + float dp = ( shadowCameraFar * ( viewSpaceZ - shadowCameraNear ) ) / ( viewSpaceZ * ( shadowCameraFar - shadowCameraNear ) ); + dp += shadowBias; + vec3 bd3D = normalize( lightToPosition ); + float depth = textureCube( shadowMap, bd3D ).r; + #ifdef USE_REVERSED_DEPTH_BUFFER + depth = 1.0 - depth; + #endif + shadow = step( dp, depth ); + } + return mix( 1.0, shadow, shadowIntensity ); + } + #endif + #endif +#endif`,shadowmap_pars_vertex:`#if NUM_SPOT_LIGHT_COORDS > 0 + uniform mat4 spotLightMatrix[ NUM_SPOT_LIGHT_COORDS ]; + varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ]; +#endif +#ifdef USE_SHADOWMAP + #if NUM_DIR_LIGHT_SHADOWS > 0 + uniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHT_SHADOWS ]; + varying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ]; + struct DirectionalLightShadow { + float shadowIntensity; + float shadowBias; + float shadowNormalBias; + float shadowRadius; + vec2 shadowMapSize; + }; + uniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ]; + #endif + #if NUM_SPOT_LIGHT_SHADOWS > 0 + struct SpotLightShadow { + float shadowIntensity; + float shadowBias; + float shadowNormalBias; + float shadowRadius; + vec2 shadowMapSize; + }; + uniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ]; + #endif + #if NUM_POINT_LIGHT_SHADOWS > 0 + uniform mat4 pointShadowMatrix[ NUM_POINT_LIGHT_SHADOWS ]; + varying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ]; + struct PointLightShadow { + float shadowIntensity; + float shadowBias; + float shadowNormalBias; + float shadowRadius; + vec2 shadowMapSize; + float shadowCameraNear; + float shadowCameraFar; + }; + uniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ]; + #endif +#endif`,shadowmap_vertex:`#if ( defined( USE_SHADOWMAP ) && ( NUM_DIR_LIGHT_SHADOWS > 0 || NUM_POINT_LIGHT_SHADOWS > 0 ) ) || ( NUM_SPOT_LIGHT_COORDS > 0 ) + vec3 shadowWorldNormal = inverseTransformDirection( transformedNormal, viewMatrix ); + vec4 shadowWorldPosition; +#endif +#if defined( USE_SHADOWMAP ) + #if NUM_DIR_LIGHT_SHADOWS > 0 + #pragma unroll_loop_start + for ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) { + shadowWorldPosition = worldPosition + vec4( shadowWorldNormal * directionalLightShadows[ i ].shadowNormalBias, 0 ); + vDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * shadowWorldPosition; + } + #pragma unroll_loop_end + #endif + #if NUM_POINT_LIGHT_SHADOWS > 0 + #pragma unroll_loop_start + for ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) { + shadowWorldPosition = worldPosition + vec4( shadowWorldNormal * pointLightShadows[ i ].shadowNormalBias, 0 ); + vPointShadowCoord[ i ] = pointShadowMatrix[ i ] * shadowWorldPosition; + } + #pragma unroll_loop_end + #endif +#endif +#if NUM_SPOT_LIGHT_COORDS > 0 + #pragma unroll_loop_start + for ( int i = 0; i < NUM_SPOT_LIGHT_COORDS; i ++ ) { + shadowWorldPosition = worldPosition; + #if ( defined( USE_SHADOWMAP ) && UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS ) + shadowWorldPosition.xyz += shadowWorldNormal * spotLightShadows[ i ].shadowNormalBias; + #endif + vSpotLightCoord[ i ] = spotLightMatrix[ i ] * shadowWorldPosition; + } + #pragma unroll_loop_end +#endif`,shadowmask_pars_fragment:`float getShadowMask() { + float shadow = 1.0; + #ifdef USE_SHADOWMAP + #if NUM_DIR_LIGHT_SHADOWS > 0 + DirectionalLightShadow directionalLight; + #pragma unroll_loop_start + for ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) { + directionalLight = directionalLightShadows[ i ]; + shadow *= receiveShadow ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowIntensity, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0; + } + #pragma unroll_loop_end + #endif + #if NUM_SPOT_LIGHT_SHADOWS > 0 + SpotLightShadow spotLight; + #pragma unroll_loop_start + for ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) { + spotLight = spotLightShadows[ i ]; + shadow *= receiveShadow ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowIntensity, spotLight.shadowBias, spotLight.shadowRadius, vSpotLightCoord[ i ] ) : 1.0; + } + #pragma unroll_loop_end + #endif + #if NUM_POINT_LIGHT_SHADOWS > 0 && ( defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_BASIC ) ) + PointLightShadow pointLight; + #pragma unroll_loop_start + for ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) { + pointLight = pointLightShadows[ i ]; + shadow *= receiveShadow ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowIntensity, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0; + } + #pragma unroll_loop_end + #endif + #endif + return shadow; +}`,skinbase_vertex:`#ifdef USE_SKINNING + mat4 boneMatX = getBoneMatrix( skinIndex.x ); + mat4 boneMatY = getBoneMatrix( skinIndex.y ); + mat4 boneMatZ = getBoneMatrix( skinIndex.z ); + mat4 boneMatW = getBoneMatrix( skinIndex.w ); +#endif`,skinning_pars_vertex:`#ifdef USE_SKINNING + uniform mat4 bindMatrix; + uniform mat4 bindMatrixInverse; + uniform highp sampler2D boneTexture; + mat4 getBoneMatrix( const in float i ) { + int size = textureSize( boneTexture, 0 ).x; + int j = int( i ) * 4; + int x = j % size; + int y = j / size; + vec4 v1 = texelFetch( boneTexture, ivec2( x, y ), 0 ); + vec4 v2 = texelFetch( boneTexture, ivec2( x + 1, y ), 0 ); + vec4 v3 = texelFetch( boneTexture, ivec2( x + 2, y ), 0 ); + vec4 v4 = texelFetch( boneTexture, ivec2( x + 3, y ), 0 ); + return mat4( v1, v2, v3, v4 ); + } +#endif`,skinning_vertex:`#ifdef USE_SKINNING + vec4 skinVertex = bindMatrix * vec4( transformed, 1.0 ); + vec4 skinned = vec4( 0.0 ); + skinned += boneMatX * skinVertex * skinWeight.x; + skinned += boneMatY * skinVertex * skinWeight.y; + skinned += boneMatZ * skinVertex * skinWeight.z; + skinned += boneMatW * skinVertex * skinWeight.w; + transformed = ( bindMatrixInverse * skinned ).xyz; +#endif`,skinnormal_vertex:`#ifdef USE_SKINNING + mat4 skinMatrix = mat4( 0.0 ); + skinMatrix += skinWeight.x * boneMatX; + skinMatrix += skinWeight.y * boneMatY; + skinMatrix += skinWeight.z * boneMatZ; + skinMatrix += skinWeight.w * boneMatW; + skinMatrix = bindMatrixInverse * skinMatrix * bindMatrix; + objectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz; + #ifdef USE_TANGENT + objectTangent = vec4( skinMatrix * vec4( objectTangent, 0.0 ) ).xyz; + #endif +#endif`,specularmap_fragment:`float specularStrength; +#ifdef USE_SPECULARMAP + vec4 texelSpecular = texture2D( specularMap, vSpecularMapUv ); + specularStrength = texelSpecular.r; +#else + specularStrength = 1.0; +#endif`,specularmap_pars_fragment:`#ifdef USE_SPECULARMAP + uniform sampler2D specularMap; +#endif`,tonemapping_fragment:`#if defined( TONE_MAPPING ) + gl_FragColor.rgb = toneMapping( gl_FragColor.rgb ); +#endif`,tonemapping_pars_fragment:`#ifndef saturate +#define saturate( a ) clamp( a, 0.0, 1.0 ) +#endif +uniform float toneMappingExposure; +vec3 LinearToneMapping( vec3 color ) { + return saturate( toneMappingExposure * color ); +} +vec3 ReinhardToneMapping( vec3 color ) { + color *= toneMappingExposure; + return saturate( color / ( vec3( 1.0 ) + color ) ); +} +vec3 CineonToneMapping( vec3 color ) { + color *= toneMappingExposure; + color = max( vec3( 0.0 ), color - 0.004 ); + return pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) ); +} +vec3 RRTAndODTFit( vec3 v ) { + vec3 a = v * ( v + 0.0245786 ) - 0.000090537; + vec3 b = v * ( 0.983729 * v + 0.4329510 ) + 0.238081; + return a / b; +} +vec3 ACESFilmicToneMapping( vec3 color ) { + const mat3 ACESInputMat = mat3( + vec3( 0.59719, 0.07600, 0.02840 ), vec3( 0.35458, 0.90834, 0.13383 ), + vec3( 0.04823, 0.01566, 0.83777 ) + ); + const mat3 ACESOutputMat = mat3( + vec3( 1.60475, -0.10208, -0.00327 ), vec3( -0.53108, 1.10813, -0.07276 ), + vec3( -0.07367, -0.00605, 1.07602 ) + ); + color *= toneMappingExposure / 0.6; + color = ACESInputMat * color; + color = RRTAndODTFit( color ); + color = ACESOutputMat * color; + return saturate( color ); +} +const mat3 LINEAR_REC2020_TO_LINEAR_SRGB = mat3( + vec3( 1.6605, - 0.1246, - 0.0182 ), + vec3( - 0.5876, 1.1329, - 0.1006 ), + vec3( - 0.0728, - 0.0083, 1.1187 ) +); +const mat3 LINEAR_SRGB_TO_LINEAR_REC2020 = mat3( + vec3( 0.6274, 0.0691, 0.0164 ), + vec3( 0.3293, 0.9195, 0.0880 ), + vec3( 0.0433, 0.0113, 0.8956 ) +); +vec3 agxDefaultContrastApprox( vec3 x ) { + vec3 x2 = x * x; + vec3 x4 = x2 * x2; + return + 15.5 * x4 * x2 + - 40.14 * x4 * x + + 31.96 * x4 + - 6.868 * x2 * x + + 0.4298 * x2 + + 0.1191 * x + - 0.00232; +} +vec3 AgXToneMapping( vec3 color ) { + const mat3 AgXInsetMatrix = mat3( + vec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ), + vec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ), + vec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 ) + ); + const mat3 AgXOutsetMatrix = mat3( + vec3( 1.1271005818144368, - 0.1413297634984383, - 0.14132976349843826 ), + vec3( - 0.11060664309660323, 1.157823702216272, - 0.11060664309660294 ), + vec3( - 0.016493938717834573, - 0.016493938717834257, 1.2519364065950405 ) + ); + const float AgxMinEv = - 12.47393; const float AgxMaxEv = 4.026069; + color *= toneMappingExposure; + color = LINEAR_SRGB_TO_LINEAR_REC2020 * color; + color = AgXInsetMatrix * color; + color = max( color, 1e-10 ); color = log2( color ); + color = ( color - AgxMinEv ) / ( AgxMaxEv - AgxMinEv ); + color = clamp( color, 0.0, 1.0 ); + color = agxDefaultContrastApprox( color ); + color = AgXOutsetMatrix * color; + color = pow( max( vec3( 0.0 ), color ), vec3( 2.2 ) ); + color = LINEAR_REC2020_TO_LINEAR_SRGB * color; + color = clamp( color, 0.0, 1.0 ); + return color; +} +vec3 NeutralToneMapping( vec3 color ) { + const float StartCompression = 0.8 - 0.04; + const float Desaturation = 0.15; + color *= toneMappingExposure; + float x = min( color.r, min( color.g, color.b ) ); + float offset = x < 0.08 ? x - 6.25 * x * x : 0.04; + color -= offset; + float peak = max( color.r, max( color.g, color.b ) ); + if ( peak < StartCompression ) return color; + float d = 1. - StartCompression; + float newPeak = 1. - d * d / ( peak + d - StartCompression ); + color *= newPeak / peak; + float g = 1. - 1. / ( Desaturation * ( peak - newPeak ) + 1. ); + return mix( color, vec3( newPeak ), g ); +} +vec3 CustomToneMapping( vec3 color ) { return color; }`,transmission_fragment:`#ifdef USE_TRANSMISSION + material.transmission = transmission; + material.transmissionAlpha = 1.0; + material.thickness = thickness; + material.attenuationDistance = attenuationDistance; + material.attenuationColor = attenuationColor; + #ifdef USE_TRANSMISSIONMAP + material.transmission *= texture2D( transmissionMap, vTransmissionMapUv ).r; + #endif + #ifdef USE_THICKNESSMAP + material.thickness *= texture2D( thicknessMap, vThicknessMapUv ).g; + #endif + vec3 pos = vWorldPosition; + vec3 v = normalize( cameraPosition - pos ); + vec3 n = inverseTransformDirection( normal, viewMatrix ); + vec4 transmitted = getIBLVolumeRefraction( + n, v, material.roughness, material.diffuseContribution, material.specularColorBlended, material.specularF90, + pos, modelMatrix, viewMatrix, projectionMatrix, material.dispersion, material.ior, material.thickness, + material.attenuationColor, material.attenuationDistance ); + material.transmissionAlpha = mix( material.transmissionAlpha, transmitted.a, material.transmission ); + totalDiffuse = mix( totalDiffuse, transmitted.rgb, material.transmission ); +#endif`,transmission_pars_fragment:`#ifdef USE_TRANSMISSION + uniform float transmission; + uniform float thickness; + uniform float attenuationDistance; + uniform vec3 attenuationColor; + #ifdef USE_TRANSMISSIONMAP + uniform sampler2D transmissionMap; + #endif + #ifdef USE_THICKNESSMAP + uniform sampler2D thicknessMap; + #endif + uniform vec2 transmissionSamplerSize; + uniform sampler2D transmissionSamplerMap; + uniform mat4 modelMatrix; + uniform mat4 projectionMatrix; + varying vec3 vWorldPosition; + float w0( float a ) { + return ( 1.0 / 6.0 ) * ( a * ( a * ( - a + 3.0 ) - 3.0 ) + 1.0 ); + } + float w1( float a ) { + return ( 1.0 / 6.0 ) * ( a * a * ( 3.0 * a - 6.0 ) + 4.0 ); + } + float w2( float a ){ + return ( 1.0 / 6.0 ) * ( a * ( a * ( - 3.0 * a + 3.0 ) + 3.0 ) + 1.0 ); + } + float w3( float a ) { + return ( 1.0 / 6.0 ) * ( a * a * a ); + } + float g0( float a ) { + return w0( a ) + w1( a ); + } + float g1( float a ) { + return w2( a ) + w3( a ); + } + float h0( float a ) { + return - 1.0 + w1( a ) / ( w0( a ) + w1( a ) ); + } + float h1( float a ) { + return 1.0 + w3( a ) / ( w2( a ) + w3( a ) ); + } + vec4 bicubic( sampler2D tex, vec2 uv, vec4 texelSize, float lod ) { + uv = uv * texelSize.zw + 0.5; + vec2 iuv = floor( uv ); + vec2 fuv = fract( uv ); + float g0x = g0( fuv.x ); + float g1x = g1( fuv.x ); + float h0x = h0( fuv.x ); + float h1x = h1( fuv.x ); + float h0y = h0( fuv.y ); + float h1y = h1( fuv.y ); + vec2 p0 = ( vec2( iuv.x + h0x, iuv.y + h0y ) - 0.5 ) * texelSize.xy; + vec2 p1 = ( vec2( iuv.x + h1x, iuv.y + h0y ) - 0.5 ) * texelSize.xy; + vec2 p2 = ( vec2( iuv.x + h0x, iuv.y + h1y ) - 0.5 ) * texelSize.xy; + vec2 p3 = ( vec2( iuv.x + h1x, iuv.y + h1y ) - 0.5 ) * texelSize.xy; + return g0( fuv.y ) * ( g0x * textureLod( tex, p0, lod ) + g1x * textureLod( tex, p1, lod ) ) + + g1( fuv.y ) * ( g0x * textureLod( tex, p2, lod ) + g1x * textureLod( tex, p3, lod ) ); + } + vec4 textureBicubic( sampler2D sampler, vec2 uv, float lod ) { + vec2 fLodSize = vec2( textureSize( sampler, int( lod ) ) ); + vec2 cLodSize = vec2( textureSize( sampler, int( lod + 1.0 ) ) ); + vec2 fLodSizeInv = 1.0 / fLodSize; + vec2 cLodSizeInv = 1.0 / cLodSize; + vec4 fSample = bicubic( sampler, uv, vec4( fLodSizeInv, fLodSize ), floor( lod ) ); + vec4 cSample = bicubic( sampler, uv, vec4( cLodSizeInv, cLodSize ), ceil( lod ) ); + return mix( fSample, cSample, fract( lod ) ); + } + vec3 getVolumeTransmissionRay( const in vec3 n, const in vec3 v, const in float thickness, const in float ior, const in mat4 modelMatrix ) { + vec3 refractionVector = refract( - v, normalize( n ), 1.0 / ior ); + vec3 modelScale; + modelScale.x = length( vec3( modelMatrix[ 0 ].xyz ) ); + modelScale.y = length( vec3( modelMatrix[ 1 ].xyz ) ); + modelScale.z = length( vec3( modelMatrix[ 2 ].xyz ) ); + return normalize( refractionVector ) * thickness * modelScale; + } + float applyIorToRoughness( const in float roughness, const in float ior ) { + return roughness * clamp( ior * 2.0 - 2.0, 0.0, 1.0 ); + } + vec4 getTransmissionSample( const in vec2 fragCoord, const in float roughness, const in float ior ) { + float lod = log2( transmissionSamplerSize.x ) * applyIorToRoughness( roughness, ior ); + return textureBicubic( transmissionSamplerMap, fragCoord.xy, lod ); + } + vec3 volumeAttenuation( const in float transmissionDistance, const in vec3 attenuationColor, const in float attenuationDistance ) { + if ( isinf( attenuationDistance ) ) { + return vec3( 1.0 ); + } else { + vec3 attenuationCoefficient = -log( attenuationColor ) / attenuationDistance; + vec3 transmittance = exp( - attenuationCoefficient * transmissionDistance ); return transmittance; + } + } + vec4 getIBLVolumeRefraction( const in vec3 n, const in vec3 v, const in float roughness, const in vec3 diffuseColor, + const in vec3 specularColor, const in float specularF90, const in vec3 position, const in mat4 modelMatrix, + const in mat4 viewMatrix, const in mat4 projMatrix, const in float dispersion, const in float ior, const in float thickness, + const in vec3 attenuationColor, const in float attenuationDistance ) { + vec4 transmittedLight; + vec3 transmittance; + #ifdef USE_DISPERSION + float halfSpread = ( ior - 1.0 ) * 0.025 * dispersion; + vec3 iors = vec3( ior - halfSpread, ior, ior + halfSpread ); + for ( int i = 0; i < 3; i ++ ) { + vec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, iors[ i ], modelMatrix ); + vec3 refractedRayExit = position + transmissionRay; + vec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 ); + vec2 refractionCoords = ndcPos.xy / ndcPos.w; + refractionCoords += 1.0; + refractionCoords /= 2.0; + vec4 transmissionSample = getTransmissionSample( refractionCoords, roughness, iors[ i ] ); + transmittedLight[ i ] = transmissionSample[ i ]; + transmittedLight.a += transmissionSample.a; + transmittance[ i ] = diffuseColor[ i ] * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance )[ i ]; + } + transmittedLight.a /= 3.0; + #else + vec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix ); + vec3 refractedRayExit = position + transmissionRay; + vec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 ); + vec2 refractionCoords = ndcPos.xy / ndcPos.w; + refractionCoords += 1.0; + refractionCoords /= 2.0; + transmittedLight = getTransmissionSample( refractionCoords, roughness, ior ); + transmittance = diffuseColor * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ); + #endif + vec3 attenuatedColor = transmittance * transmittedLight.rgb; + vec3 F = EnvironmentBRDF( n, v, specularColor, specularF90, roughness ); + float transmittanceFactor = ( transmittance.r + transmittance.g + transmittance.b ) / 3.0; + return vec4( ( 1.0 - F ) * attenuatedColor, 1.0 - ( 1.0 - transmittedLight.a ) * transmittanceFactor ); + } +#endif`,uv_pars_fragment:`#if defined( USE_UV ) || defined( USE_ANISOTROPY ) + varying vec2 vUv; +#endif +#ifdef USE_MAP + varying vec2 vMapUv; +#endif +#ifdef USE_ALPHAMAP + varying vec2 vAlphaMapUv; +#endif +#ifdef USE_LIGHTMAP + varying vec2 vLightMapUv; +#endif +#ifdef USE_AOMAP + varying vec2 vAoMapUv; +#endif +#ifdef USE_BUMPMAP + varying vec2 vBumpMapUv; +#endif +#ifdef USE_NORMALMAP + varying vec2 vNormalMapUv; +#endif +#ifdef USE_EMISSIVEMAP + varying vec2 vEmissiveMapUv; +#endif +#ifdef USE_METALNESSMAP + varying vec2 vMetalnessMapUv; +#endif +#ifdef USE_ROUGHNESSMAP + varying vec2 vRoughnessMapUv; +#endif +#ifdef USE_ANISOTROPYMAP + varying vec2 vAnisotropyMapUv; +#endif +#ifdef USE_CLEARCOATMAP + varying vec2 vClearcoatMapUv; +#endif +#ifdef USE_CLEARCOAT_NORMALMAP + varying vec2 vClearcoatNormalMapUv; +#endif +#ifdef USE_CLEARCOAT_ROUGHNESSMAP + varying vec2 vClearcoatRoughnessMapUv; +#endif +#ifdef USE_IRIDESCENCEMAP + varying vec2 vIridescenceMapUv; +#endif +#ifdef USE_IRIDESCENCE_THICKNESSMAP + varying vec2 vIridescenceThicknessMapUv; +#endif +#ifdef USE_SHEEN_COLORMAP + varying vec2 vSheenColorMapUv; +#endif +#ifdef USE_SHEEN_ROUGHNESSMAP + varying vec2 vSheenRoughnessMapUv; +#endif +#ifdef USE_SPECULARMAP + varying vec2 vSpecularMapUv; +#endif +#ifdef USE_SPECULAR_COLORMAP + varying vec2 vSpecularColorMapUv; +#endif +#ifdef USE_SPECULAR_INTENSITYMAP + varying vec2 vSpecularIntensityMapUv; +#endif +#ifdef USE_TRANSMISSIONMAP + uniform mat3 transmissionMapTransform; + varying vec2 vTransmissionMapUv; +#endif +#ifdef USE_THICKNESSMAP + uniform mat3 thicknessMapTransform; + varying vec2 vThicknessMapUv; +#endif`,uv_pars_vertex:`#if defined( USE_UV ) || defined( USE_ANISOTROPY ) + varying vec2 vUv; +#endif +#ifdef USE_MAP + uniform mat3 mapTransform; + varying vec2 vMapUv; +#endif +#ifdef USE_ALPHAMAP + uniform mat3 alphaMapTransform; + varying vec2 vAlphaMapUv; +#endif +#ifdef USE_LIGHTMAP + uniform mat3 lightMapTransform; + varying vec2 vLightMapUv; +#endif +#ifdef USE_AOMAP + uniform mat3 aoMapTransform; + varying vec2 vAoMapUv; +#endif +#ifdef USE_BUMPMAP + uniform mat3 bumpMapTransform; + varying vec2 vBumpMapUv; +#endif +#ifdef USE_NORMALMAP + uniform mat3 normalMapTransform; + varying vec2 vNormalMapUv; +#endif +#ifdef USE_DISPLACEMENTMAP + uniform mat3 displacementMapTransform; + varying vec2 vDisplacementMapUv; +#endif +#ifdef USE_EMISSIVEMAP + uniform mat3 emissiveMapTransform; + varying vec2 vEmissiveMapUv; +#endif +#ifdef USE_METALNESSMAP + uniform mat3 metalnessMapTransform; + varying vec2 vMetalnessMapUv; +#endif +#ifdef USE_ROUGHNESSMAP + uniform mat3 roughnessMapTransform; + varying vec2 vRoughnessMapUv; +#endif +#ifdef USE_ANISOTROPYMAP + uniform mat3 anisotropyMapTransform; + varying vec2 vAnisotropyMapUv; +#endif +#ifdef USE_CLEARCOATMAP + uniform mat3 clearcoatMapTransform; + varying vec2 vClearcoatMapUv; +#endif +#ifdef USE_CLEARCOAT_NORMALMAP + uniform mat3 clearcoatNormalMapTransform; + varying vec2 vClearcoatNormalMapUv; +#endif +#ifdef USE_CLEARCOAT_ROUGHNESSMAP + uniform mat3 clearcoatRoughnessMapTransform; + varying vec2 vClearcoatRoughnessMapUv; +#endif +#ifdef USE_SHEEN_COLORMAP + uniform mat3 sheenColorMapTransform; + varying vec2 vSheenColorMapUv; +#endif +#ifdef USE_SHEEN_ROUGHNESSMAP + uniform mat3 sheenRoughnessMapTransform; + varying vec2 vSheenRoughnessMapUv; +#endif +#ifdef USE_IRIDESCENCEMAP + uniform mat3 iridescenceMapTransform; + varying vec2 vIridescenceMapUv; +#endif +#ifdef USE_IRIDESCENCE_THICKNESSMAP + uniform mat3 iridescenceThicknessMapTransform; + varying vec2 vIridescenceThicknessMapUv; +#endif +#ifdef USE_SPECULARMAP + uniform mat3 specularMapTransform; + varying vec2 vSpecularMapUv; +#endif +#ifdef USE_SPECULAR_COLORMAP + uniform mat3 specularColorMapTransform; + varying vec2 vSpecularColorMapUv; +#endif +#ifdef USE_SPECULAR_INTENSITYMAP + uniform mat3 specularIntensityMapTransform; + varying vec2 vSpecularIntensityMapUv; +#endif +#ifdef USE_TRANSMISSIONMAP + uniform mat3 transmissionMapTransform; + varying vec2 vTransmissionMapUv; +#endif +#ifdef USE_THICKNESSMAP + uniform mat3 thicknessMapTransform; + varying vec2 vThicknessMapUv; +#endif`,uv_vertex:`#if defined( USE_UV ) || defined( USE_ANISOTROPY ) + vUv = vec3( uv, 1 ).xy; +#endif +#ifdef USE_MAP + vMapUv = ( mapTransform * vec3( MAP_UV, 1 ) ).xy; +#endif +#ifdef USE_ALPHAMAP + vAlphaMapUv = ( alphaMapTransform * vec3( ALPHAMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_LIGHTMAP + vLightMapUv = ( lightMapTransform * vec3( LIGHTMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_AOMAP + vAoMapUv = ( aoMapTransform * vec3( AOMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_BUMPMAP + vBumpMapUv = ( bumpMapTransform * vec3( BUMPMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_NORMALMAP + vNormalMapUv = ( normalMapTransform * vec3( NORMALMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_DISPLACEMENTMAP + vDisplacementMapUv = ( displacementMapTransform * vec3( DISPLACEMENTMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_EMISSIVEMAP + vEmissiveMapUv = ( emissiveMapTransform * vec3( EMISSIVEMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_METALNESSMAP + vMetalnessMapUv = ( metalnessMapTransform * vec3( METALNESSMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_ROUGHNESSMAP + vRoughnessMapUv = ( roughnessMapTransform * vec3( ROUGHNESSMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_ANISOTROPYMAP + vAnisotropyMapUv = ( anisotropyMapTransform * vec3( ANISOTROPYMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_CLEARCOATMAP + vClearcoatMapUv = ( clearcoatMapTransform * vec3( CLEARCOATMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_CLEARCOAT_NORMALMAP + vClearcoatNormalMapUv = ( clearcoatNormalMapTransform * vec3( CLEARCOAT_NORMALMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_CLEARCOAT_ROUGHNESSMAP + vClearcoatRoughnessMapUv = ( clearcoatRoughnessMapTransform * vec3( CLEARCOAT_ROUGHNESSMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_IRIDESCENCEMAP + vIridescenceMapUv = ( iridescenceMapTransform * vec3( IRIDESCENCEMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_IRIDESCENCE_THICKNESSMAP + vIridescenceThicknessMapUv = ( iridescenceThicknessMapTransform * vec3( IRIDESCENCE_THICKNESSMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_SHEEN_COLORMAP + vSheenColorMapUv = ( sheenColorMapTransform * vec3( SHEEN_COLORMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_SHEEN_ROUGHNESSMAP + vSheenRoughnessMapUv = ( sheenRoughnessMapTransform * vec3( SHEEN_ROUGHNESSMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_SPECULARMAP + vSpecularMapUv = ( specularMapTransform * vec3( SPECULARMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_SPECULAR_COLORMAP + vSpecularColorMapUv = ( specularColorMapTransform * vec3( SPECULAR_COLORMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_SPECULAR_INTENSITYMAP + vSpecularIntensityMapUv = ( specularIntensityMapTransform * vec3( SPECULAR_INTENSITYMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_TRANSMISSIONMAP + vTransmissionMapUv = ( transmissionMapTransform * vec3( TRANSMISSIONMAP_UV, 1 ) ).xy; +#endif +#ifdef USE_THICKNESSMAP + vThicknessMapUv = ( thicknessMapTransform * vec3( THICKNESSMAP_UV, 1 ) ).xy; +#endif`,worldpos_vertex:`#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP ) || defined ( USE_TRANSMISSION ) || NUM_SPOT_LIGHT_COORDS > 0 + vec4 worldPosition = vec4( transformed, 1.0 ); + #ifdef USE_BATCHING + worldPosition = batchingMatrix * worldPosition; + #endif + #ifdef USE_INSTANCING + worldPosition = instanceMatrix * worldPosition; + #endif + worldPosition = modelMatrix * worldPosition; +#endif`,background_vert:`varying vec2 vUv; +uniform mat3 uvTransform; +void main() { + vUv = ( uvTransform * vec3( uv, 1 ) ).xy; + gl_Position = vec4( position.xy, 1.0, 1.0 ); +}`,background_frag:`uniform sampler2D t2D; +uniform float backgroundIntensity; +varying vec2 vUv; +void main() { + vec4 texColor = texture2D( t2D, vUv ); + #ifdef DECODE_VIDEO_TEXTURE + texColor = vec4( mix( pow( texColor.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), texColor.rgb * 0.0773993808, vec3( lessThanEqual( texColor.rgb, vec3( 0.04045 ) ) ) ), texColor.w ); + #endif + texColor.rgb *= backgroundIntensity; + gl_FragColor = texColor; + #include + #include +}`,backgroundCube_vert:`varying vec3 vWorldDirection; +#include +void main() { + vWorldDirection = transformDirection( position, modelMatrix ); + #include + #include + gl_Position.z = gl_Position.w; +}`,backgroundCube_frag:`#ifdef ENVMAP_TYPE_CUBE + uniform samplerCube envMap; +#elif defined( ENVMAP_TYPE_CUBE_UV ) + uniform sampler2D envMap; +#endif +uniform float flipEnvMap; +uniform float backgroundBlurriness; +uniform float backgroundIntensity; +uniform mat3 backgroundRotation; +varying vec3 vWorldDirection; +#include +void main() { + #ifdef ENVMAP_TYPE_CUBE + vec4 texColor = textureCube( envMap, backgroundRotation * vec3( flipEnvMap * vWorldDirection.x, vWorldDirection.yz ) ); + #elif defined( ENVMAP_TYPE_CUBE_UV ) + vec4 texColor = textureCubeUV( envMap, backgroundRotation * vWorldDirection, backgroundBlurriness ); + #else + vec4 texColor = vec4( 0.0, 0.0, 0.0, 1.0 ); + #endif + texColor.rgb *= backgroundIntensity; + gl_FragColor = texColor; + #include + #include +}`,cube_vert:`varying vec3 vWorldDirection; +#include +void main() { + vWorldDirection = transformDirection( position, modelMatrix ); + #include + #include + gl_Position.z = gl_Position.w; +}`,cube_frag:`uniform samplerCube tCube; +uniform float tFlip; +uniform float opacity; +varying vec3 vWorldDirection; +void main() { + vec4 texColor = textureCube( tCube, vec3( tFlip * vWorldDirection.x, vWorldDirection.yz ) ); + gl_FragColor = texColor; + gl_FragColor.a *= opacity; + #include + #include +}`,depth_vert:`#include +#include +#include +#include +#include +#include +#include +#include +varying vec2 vHighPrecisionZW; +void main() { + #include + #include + #include + #include + #ifdef USE_DISPLACEMENTMAP + #include + #include + #include + #endif + #include + #include + #include + #include + #include + #include + #include + vHighPrecisionZW = gl_Position.zw; +}`,depth_frag:`#if DEPTH_PACKING == 3200 + uniform float opacity; +#endif +#include +#include +#include +#include +#include +#include +#include +#include +#include +varying vec2 vHighPrecisionZW; +void main() { + vec4 diffuseColor = vec4( 1.0 ); + #include + #if DEPTH_PACKING == 3200 + diffuseColor.a = opacity; + #endif + #include + #include + #include + #include + #include + #ifdef USE_REVERSED_DEPTH_BUFFER + float fragCoordZ = vHighPrecisionZW[ 0 ] / vHighPrecisionZW[ 1 ]; + #else + float fragCoordZ = 0.5 * vHighPrecisionZW[ 0 ] / vHighPrecisionZW[ 1 ] + 0.5; + #endif + #if DEPTH_PACKING == 3200 + gl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity ); + #elif DEPTH_PACKING == 3201 + gl_FragColor = packDepthToRGBA( fragCoordZ ); + #elif DEPTH_PACKING == 3202 + gl_FragColor = vec4( packDepthToRGB( fragCoordZ ), 1.0 ); + #elif DEPTH_PACKING == 3203 + gl_FragColor = vec4( packDepthToRG( fragCoordZ ), 0.0, 1.0 ); + #endif +}`,distance_vert:`#define DISTANCE +varying vec3 vWorldPosition; +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #ifdef USE_DISPLACEMENTMAP + #include + #include + #include + #endif + #include + #include + #include + #include + #include + #include + #include + vWorldPosition = worldPosition.xyz; +}`,distance_frag:`#define DISTANCE +uniform vec3 referencePosition; +uniform float nearDistance; +uniform float farDistance; +varying vec3 vWorldPosition; +#include +#include +#include +#include +#include +#include +#include +void main () { + vec4 diffuseColor = vec4( 1.0 ); + #include + #include + #include + #include + #include + float dist = length( vWorldPosition - referencePosition ); + dist = ( dist - nearDistance ) / ( farDistance - nearDistance ); + dist = saturate( dist ); + gl_FragColor = vec4( dist, 0.0, 0.0, 1.0 ); +}`,equirect_vert:`varying vec3 vWorldDirection; +#include +void main() { + vWorldDirection = transformDirection( position, modelMatrix ); + #include + #include +}`,equirect_frag:`uniform sampler2D tEquirect; +varying vec3 vWorldDirection; +#include +void main() { + vec3 direction = normalize( vWorldDirection ); + vec2 sampleUV = equirectUv( direction ); + gl_FragColor = texture2D( tEquirect, sampleUV ); + #include + #include +}`,linedashed_vert:`uniform float scale; +attribute float lineDistance; +varying float vLineDistance; +#include +#include +#include +#include +#include +#include +#include +void main() { + vLineDistance = scale * lineDistance; + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include +}`,linedashed_frag:`uniform vec3 diffuse; +uniform float opacity; +uniform float dashSize; +uniform float totalSize; +varying float vLineDistance; +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + if ( mod( vLineDistance, totalSize ) > dashSize ) { + discard; + } + vec3 outgoingLight = vec3( 0.0 ); + #include + #include + #include + outgoingLight = diffuseColor.rgb; + #include + #include + #include + #include + #include +}`,meshbasic_vert:`#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #if defined ( USE_ENVMAP ) || defined ( USE_SKINNING ) + #include + #include + #include + #include + #include + #endif + #include + #include + #include + #include + #include + #include + #include + #include + #include +}`,meshbasic_frag:`uniform vec3 diffuse; +uniform float opacity; +#ifndef FLAT_SHADED + varying vec3 vNormal; +#endif +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + #include + #include + #include + #include + #include + #include + #include + ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); + #ifdef USE_LIGHTMAP + vec4 lightMapTexel = texture2D( lightMap, vLightMapUv ); + reflectedLight.indirectDiffuse += lightMapTexel.rgb * lightMapIntensity * RECIPROCAL_PI; + #else + reflectedLight.indirectDiffuse += vec3( 1.0 ); + #endif + #include + reflectedLight.indirectDiffuse *= diffuseColor.rgb; + vec3 outgoingLight = reflectedLight.indirectDiffuse; + #include + #include + #include + #include + #include + #include + #include +}`,meshlambert_vert:`#define LAMBERT +varying vec3 vViewPosition; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vViewPosition = - mvPosition.xyz; + #include + #include + #include + #include +}`,meshlambert_frag:`#define LAMBERT +uniform vec3 diffuse; +uniform vec3 emissive; +uniform float opacity; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); + vec3 totalEmissiveRadiance = emissive; + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance; + #include + #include + #include + #include + #include + #include + #include +}`,meshmatcap_vert:`#define MATCAP +varying vec3 vViewPosition; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vViewPosition = - mvPosition.xyz; +}`,meshmatcap_frag:`#define MATCAP +uniform vec3 diffuse; +uniform float opacity; +uniform sampler2D matcap; +varying vec3 vViewPosition; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + #include + #include + #include + #include + #include + #include + #include + #include + vec3 viewDir = normalize( vViewPosition ); + vec3 x = normalize( vec3( viewDir.z, 0.0, - viewDir.x ) ); + vec3 y = cross( viewDir, x ); + vec2 uv = vec2( dot( x, normal ), dot( y, normal ) ) * 0.495 + 0.5; + #ifdef USE_MATCAP + vec4 matcapColor = texture2D( matcap, uv ); + #else + vec4 matcapColor = vec4( vec3( mix( 0.2, 0.8, uv.y ) ), 1.0 ); + #endif + vec3 outgoingLight = diffuseColor.rgb * matcapColor.rgb; + #include + #include + #include + #include + #include + #include +}`,meshnormal_vert:`#define NORMAL +#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE ) + varying vec3 vViewPosition; +#endif +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include +#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE ) + vViewPosition = - mvPosition.xyz; +#endif +}`,meshnormal_frag:`#define NORMAL +uniform float opacity; +#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE ) + varying vec3 vViewPosition; +#endif +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( 0.0, 0.0, 0.0, opacity ); + #include + #include + #include + #include + gl_FragColor = vec4( normalize( normal ) * 0.5 + 0.5, diffuseColor.a ); + #ifdef OPAQUE + gl_FragColor.a = 1.0; + #endif +}`,meshphong_vert:`#define PHONG +varying vec3 vViewPosition; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vViewPosition = - mvPosition.xyz; + #include + #include + #include + #include +}`,meshphong_frag:`#define PHONG +uniform vec3 diffuse; +uniform vec3 emissive; +uniform vec3 specular; +uniform float shininess; +uniform float opacity; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); + vec3 totalEmissiveRadiance = emissive; + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance; + #include + #include + #include + #include + #include + #include + #include +}`,meshphysical_vert:`#define STANDARD +varying vec3 vViewPosition; +#ifdef USE_TRANSMISSION + varying vec3 vWorldPosition; +#endif +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vViewPosition = - mvPosition.xyz; + #include + #include + #include +#ifdef USE_TRANSMISSION + vWorldPosition = worldPosition.xyz; +#endif +}`,meshphysical_frag:`#define STANDARD +#ifdef PHYSICAL + #define IOR + #define USE_SPECULAR +#endif +uniform vec3 diffuse; +uniform vec3 emissive; +uniform float roughness; +uniform float metalness; +uniform float opacity; +#ifdef IOR + uniform float ior; +#endif +#ifdef USE_SPECULAR + uniform float specularIntensity; + uniform vec3 specularColor; + #ifdef USE_SPECULAR_COLORMAP + uniform sampler2D specularColorMap; + #endif + #ifdef USE_SPECULAR_INTENSITYMAP + uniform sampler2D specularIntensityMap; + #endif +#endif +#ifdef USE_CLEARCOAT + uniform float clearcoat; + uniform float clearcoatRoughness; +#endif +#ifdef USE_DISPERSION + uniform float dispersion; +#endif +#ifdef USE_IRIDESCENCE + uniform float iridescence; + uniform float iridescenceIOR; + uniform float iridescenceThicknessMinimum; + uniform float iridescenceThicknessMaximum; +#endif +#ifdef USE_SHEEN + uniform vec3 sheenColor; + uniform float sheenRoughness; + #ifdef USE_SHEEN_COLORMAP + uniform sampler2D sheenColorMap; + #endif + #ifdef USE_SHEEN_ROUGHNESSMAP + uniform sampler2D sheenRoughnessMap; + #endif +#endif +#ifdef USE_ANISOTROPY + uniform vec2 anisotropyVector; + #ifdef USE_ANISOTROPYMAP + uniform sampler2D anisotropyMap; + #endif +#endif +varying vec3 vViewPosition; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); + vec3 totalEmissiveRadiance = emissive; + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vec3 totalDiffuse = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse; + vec3 totalSpecular = reflectedLight.directSpecular + reflectedLight.indirectSpecular; + #include + vec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance; + #ifdef USE_SHEEN + + outgoingLight = outgoingLight + sheenSpecularDirect + sheenSpecularIndirect; + + #endif + #ifdef USE_CLEARCOAT + float dotNVcc = saturate( dot( geometryClearcoatNormal, geometryViewDir ) ); + vec3 Fcc = F_Schlick( material.clearcoatF0, material.clearcoatF90, dotNVcc ); + outgoingLight = outgoingLight * ( 1.0 - material.clearcoat * Fcc ) + ( clearcoatSpecularDirect + clearcoatSpecularIndirect ) * material.clearcoat; + #endif + #include + #include + #include + #include + #include + #include +}`,meshtoon_vert:`#define TOON +varying vec3 vViewPosition; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vViewPosition = - mvPosition.xyz; + #include + #include + #include +}`,meshtoon_frag:`#define TOON +uniform vec3 diffuse; +uniform vec3 emissive; +uniform float opacity; +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); + vec3 totalEmissiveRadiance = emissive; + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance; + #include + #include + #include + #include + #include + #include +}`,points_vert:`uniform float size; +uniform float scale; +#include +#include +#include +#include +#include +#include +#ifdef USE_POINTS_UV + varying vec2 vUv; + uniform mat3 uvTransform; +#endif +void main() { + #ifdef USE_POINTS_UV + vUv = ( uvTransform * vec3( uv, 1 ) ).xy; + #endif + #include + #include + #include + #include + #include + #include + gl_PointSize = size; + #ifdef USE_SIZEATTENUATION + bool isPerspective = isPerspectiveMatrix( projectionMatrix ); + if ( isPerspective ) gl_PointSize *= ( scale / - mvPosition.z ); + #endif + #include + #include + #include + #include +}`,points_frag:`uniform vec3 diffuse; +uniform float opacity; +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + vec3 outgoingLight = vec3( 0.0 ); + #include + #include + #include + #include + #include + outgoingLight = diffuseColor.rgb; + #include + #include + #include + #include + #include +}`,shadow_vert:`#include +#include +#include +#include +#include +#include +#include +void main() { + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include + #include +}`,shadow_frag:`uniform vec3 color; +uniform float opacity; +#include +#include +#include +#include +#include +#include +#include +void main() { + #include + gl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) ); + #include + #include + #include + #include +}`,sprite_vert:`uniform float rotation; +uniform vec2 center; +#include +#include +#include +#include +#include +void main() { + #include + vec4 mvPosition = modelViewMatrix[ 3 ]; + vec2 scale = vec2( length( modelMatrix[ 0 ].xyz ), length( modelMatrix[ 1 ].xyz ) ); + #ifndef USE_SIZEATTENUATION + bool isPerspective = isPerspectiveMatrix( projectionMatrix ); + if ( isPerspective ) scale *= - mvPosition.z; + #endif + vec2 alignedPosition = ( position.xy - ( center - vec2( 0.5 ) ) ) * scale; + vec2 rotatedPosition; + rotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y; + rotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y; + mvPosition.xy += rotatedPosition; + gl_Position = projectionMatrix * mvPosition; + #include + #include + #include +}`,sprite_frag:`uniform vec3 diffuse; +uniform float opacity; +#include +#include +#include +#include +#include +#include +#include +#include +#include +void main() { + vec4 diffuseColor = vec4( diffuse, opacity ); + #include + vec3 outgoingLight = vec3( 0.0 ); + #include + #include + #include + #include + #include + outgoingLight = diffuseColor.rgb; + #include + #include + #include + #include +}`},J={common:{diffuse:{value:new U(16777215)},opacity:{value:1},map:{value:null},mapTransform:{value:new dr},alphaMap:{value:null},alphaMapTransform:{value:new dr},alphaTest:{value:0}},specularmap:{specularMap:{value:null},specularMapTransform:{value:new dr}},envmap:{envMap:{value:null},envMapRotation:{value:new dr},flipEnvMap:{value:-1},reflectivity:{value:1},ior:{value:1.5},refractionRatio:{value:.98},dfgLUT:{value:null}},aomap:{aoMap:{value:null},aoMapIntensity:{value:1},aoMapTransform:{value:new dr}},lightmap:{lightMap:{value:null},lightMapIntensity:{value:1},lightMapTransform:{value:new dr}},bumpmap:{bumpMap:{value:null},bumpMapTransform:{value:new dr},bumpScale:{value:1}},normalmap:{normalMap:{value:null},normalMapTransform:{value:new dr},normalScale:{value:new V(1,1)}},displacementmap:{displacementMap:{value:null},displacementMapTransform:{value:new dr},displacementScale:{value:1},displacementBias:{value:0}},emissivemap:{emissiveMap:{value:null},emissiveMapTransform:{value:new dr}},metalnessmap:{metalnessMap:{value:null},metalnessMapTransform:{value:new dr}},roughnessmap:{roughnessMap:{value:null},roughnessMapTransform:{value:new dr}},gradientmap:{gradientMap:{value:null}},fog:{fogDensity:{value:25e-5},fogNear:{value:1},fogFar:{value:2e3},fogColor:{value:new U(16777215)}},lights:{ambientLightColor:{value:[]},lightProbe:{value:[]},directionalLights:{value:[],properties:{direction:{},color:{}}},directionalLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},directionalShadowMatrix:{value:[]},spotLights:{value:[],properties:{color:{},position:{},direction:{},distance:{},coneCos:{},penumbraCos:{},decay:{}}},spotLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{}}},spotLightMap:{value:[]},spotLightMatrix:{value:[]},pointLights:{value:[],properties:{color:{},position:{},decay:{},distance:{}}},pointLightShadows:{value:[],properties:{shadowIntensity:1,shadowBias:{},shadowNormalBias:{},shadowRadius:{},shadowMapSize:{},shadowCameraNear:{},shadowCameraFar:{}}},pointShadowMatrix:{value:[]},hemisphereLights:{value:[],properties:{direction:{},skyColor:{},groundColor:{}}},rectAreaLights:{value:[],properties:{color:{},position:{},width:{},height:{}}},ltc_1:{value:null},ltc_2:{value:null}},points:{diffuse:{value:new U(16777215)},opacity:{value:1},size:{value:1},scale:{value:1},map:{value:null},alphaMap:{value:null},alphaMapTransform:{value:new dr},alphaTest:{value:0},uvTransform:{value:new dr}},sprite:{diffuse:{value:new U(16777215)},opacity:{value:1},center:{value:new V(.5,.5)},rotation:{value:0},map:{value:null},mapTransform:{value:new dr},alphaMap:{value:null},alphaMapTransform:{value:new dr},alphaTest:{value:0}}},Cp={basic:{uniforms:Rl([J.common,J.specularmap,J.envmap,J.aomap,J.lightmap,J.fog]),vertexShader:Sp.meshbasic_vert,fragmentShader:Sp.meshbasic_frag},lambert:{uniforms:Rl([J.common,J.specularmap,J.envmap,J.aomap,J.lightmap,J.emissivemap,J.bumpmap,J.normalmap,J.displacementmap,J.fog,J.lights,{emissive:{value:new U(0)},envMapIntensity:{value:1}}]),vertexShader:Sp.meshlambert_vert,fragmentShader:Sp.meshlambert_frag},phong:{uniforms:Rl([J.common,J.specularmap,J.envmap,J.aomap,J.lightmap,J.emissivemap,J.bumpmap,J.normalmap,J.displacementmap,J.fog,J.lights,{emissive:{value:new U(0)},specular:{value:new U(1118481)},shininess:{value:30},envMapIntensity:{value:1}}]),vertexShader:Sp.meshphong_vert,fragmentShader:Sp.meshphong_frag},standard:{uniforms:Rl([J.common,J.envmap,J.aomap,J.lightmap,J.emissivemap,J.bumpmap,J.normalmap,J.displacementmap,J.roughnessmap,J.metalnessmap,J.fog,J.lights,{emissive:{value:new U(0)},roughness:{value:1},metalness:{value:0},envMapIntensity:{value:1}}]),vertexShader:Sp.meshphysical_vert,fragmentShader:Sp.meshphysical_frag},toon:{uniforms:Rl([J.common,J.aomap,J.lightmap,J.emissivemap,J.bumpmap,J.normalmap,J.displacementmap,J.gradientmap,J.fog,J.lights,{emissive:{value:new U(0)}}]),vertexShader:Sp.meshtoon_vert,fragmentShader:Sp.meshtoon_frag},matcap:{uniforms:Rl([J.common,J.bumpmap,J.normalmap,J.displacementmap,J.fog,{matcap:{value:null}}]),vertexShader:Sp.meshmatcap_vert,fragmentShader:Sp.meshmatcap_frag},points:{uniforms:Rl([J.points,J.fog]),vertexShader:Sp.points_vert,fragmentShader:Sp.points_frag},dashed:{uniforms:Rl([J.common,J.fog,{scale:{value:1},dashSize:{value:1},totalSize:{value:2}}]),vertexShader:Sp.linedashed_vert,fragmentShader:Sp.linedashed_frag},depth:{uniforms:Rl([J.common,J.displacementmap]),vertexShader:Sp.depth_vert,fragmentShader:Sp.depth_frag},normal:{uniforms:Rl([J.common,J.bumpmap,J.normalmap,J.displacementmap,{opacity:{value:1}}]),vertexShader:Sp.meshnormal_vert,fragmentShader:Sp.meshnormal_frag},sprite:{uniforms:Rl([J.sprite,J.fog]),vertexShader:Sp.sprite_vert,fragmentShader:Sp.sprite_frag},background:{uniforms:{uvTransform:{value:new dr},t2D:{value:null},backgroundIntensity:{value:1}},vertexShader:Sp.background_vert,fragmentShader:Sp.background_frag},backgroundCube:{uniforms:{envMap:{value:null},flipEnvMap:{value:-1},backgroundBlurriness:{value:0},backgroundIntensity:{value:1},backgroundRotation:{value:new dr}},vertexShader:Sp.backgroundCube_vert,fragmentShader:Sp.backgroundCube_frag},cube:{uniforms:{tCube:{value:null},tFlip:{value:-1},opacity:{value:1}},vertexShader:Sp.cube_vert,fragmentShader:Sp.cube_frag},equirect:{uniforms:{tEquirect:{value:null}},vertexShader:Sp.equirect_vert,fragmentShader:Sp.equirect_frag},distance:{uniforms:Rl([J.common,J.displacementmap,{referencePosition:{value:new H},nearDistance:{value:1},farDistance:{value:1e3}}]),vertexShader:Sp.distance_vert,fragmentShader:Sp.distance_frag},shadow:{uniforms:Rl([J.lights,J.fog,{color:{value:new U(0)},opacity:{value:1}}]),vertexShader:Sp.shadow_vert,fragmentShader:Sp.shadow_frag}};Cp.physical={uniforms:Rl([Cp.standard.uniforms,{clearcoat:{value:0},clearcoatMap:{value:null},clearcoatMapTransform:{value:new dr},clearcoatNormalMap:{value:null},clearcoatNormalMapTransform:{value:new dr},clearcoatNormalScale:{value:new V(1,1)},clearcoatRoughness:{value:0},clearcoatRoughnessMap:{value:null},clearcoatRoughnessMapTransform:{value:new dr},dispersion:{value:0},iridescence:{value:0},iridescenceMap:{value:null},iridescenceMapTransform:{value:new dr},iridescenceIOR:{value:1.3},iridescenceThicknessMinimum:{value:100},iridescenceThicknessMaximum:{value:400},iridescenceThicknessMap:{value:null},iridescenceThicknessMapTransform:{value:new dr},sheen:{value:0},sheenColor:{value:new U(0)},sheenColorMap:{value:null},sheenColorMapTransform:{value:new dr},sheenRoughness:{value:1},sheenRoughnessMap:{value:null},sheenRoughnessMapTransform:{value:new dr},transmission:{value:0},transmissionMap:{value:null},transmissionMapTransform:{value:new dr},transmissionSamplerSize:{value:new V},transmissionSamplerMap:{value:null},thickness:{value:0},thicknessMap:{value:null},thicknessMapTransform:{value:new dr},attenuationDistance:{value:0},attenuationColor:{value:new U(0)},specularColor:{value:new U(1,1,1)},specularColorMap:{value:null},specularColorMapTransform:{value:new dr},specularIntensity:{value:1},specularIntensityMap:{value:null},specularIntensityMapTransform:{value:new dr},anisotropyVector:{value:new V},anisotropyMap:{value:null},anisotropyMapTransform:{value:new dr}}]),vertexShader:Sp.meshphysical_vert,fragmentShader:Sp.meshphysical_frag};var wp={r:0,b:0,g:0},Tp=new Wr,Ep=new Pr;function Dp(e,t,n,r,i,a){let o=new U(0),s=i===!0?0:1,c,l,u=null,d=0,f=null;function p(e){let n=e.isScene===!0?e.background:null;if(n&&n.isTexture){let r=e.backgroundBlurriness>0;n=t.get(n,r)}return n}function m(t){let r=!1,i=p(t);i===null?g(o,s):i&&i.isColor&&(g(i,1),r=!0);let c=e.xr.getEnvironmentBlendMode();c===`additive`?n.buffers.color.setClear(0,0,0,1,a):c===`alpha-blend`&&n.buffers.color.setClear(0,0,0,0,a),(e.autoClear||r)&&(n.buffers.depth.setTest(!0),n.buffers.depth.setMask(!0),n.buffers.color.setMask(!0),e.clear(e.autoClearColor,e.autoClearDepth,e.autoClearStencil))}function h(t,n){let i=p(n);i&&(i.isCubeTexture||i.mapping===306)?(l===void 0&&(l=new fo(new qs(1,1,1),new q({name:`BackgroundCubeMaterial`,uniforms:Ll(Cp.backgroundCube.uniforms),vertexShader:Cp.backgroundCube.vertexShader,fragmentShader:Cp.backgroundCube.fragmentShader,side:1,depthTest:!1,depthWrite:!1,fog:!1,allowOverride:!1})),l.geometry.deleteAttribute(`normal`),l.geometry.deleteAttribute(`uv`),l.onBeforeRender=function(e,t,n){this.matrixWorld.copyPosition(n.matrixWorld)},Object.defineProperty(l.material,`envMap`,{get:function(){return this.uniforms.envMap.value}}),r.update(l)),Tp.copy(n.backgroundRotation),Tp.x*=-1,Tp.y*=-1,Tp.z*=-1,i.isCubeTexture&&i.isRenderTargetTexture===!1&&(Tp.y*=-1,Tp.z*=-1),l.material.uniforms.envMap.value=i,l.material.uniforms.flipEnvMap.value=i.isCubeTexture&&i.isRenderTargetTexture===!1?-1:1,l.material.uniforms.backgroundBlurriness.value=n.backgroundBlurriness,l.material.uniforms.backgroundIntensity.value=n.backgroundIntensity,l.material.uniforms.backgroundRotation.value.setFromMatrix4(Ep.makeRotationFromEuler(Tp)),l.material.toneMapped=gr.getTransfer(i.colorSpace)!==qt,(u!==i||d!==i.version||f!==e.toneMapping)&&(l.material.needsUpdate=!0,u=i,d=i.version,f=e.toneMapping),l.layers.enableAll(),t.unshift(l,l.geometry,l.material,0,0,null)):i&&i.isTexture&&(c===void 0&&(c=new fo(new wl(2,2),new q({name:`BackgroundMaterial`,uniforms:Ll(Cp.background.uniforms),vertexShader:Cp.background.vertexShader,fragmentShader:Cp.background.fragmentShader,side:0,depthTest:!1,depthWrite:!1,fog:!1,allowOverride:!1})),c.geometry.deleteAttribute(`normal`),Object.defineProperty(c.material,`map`,{get:function(){return this.uniforms.t2D.value}}),r.update(c)),c.material.uniforms.t2D.value=i,c.material.uniforms.backgroundIntensity.value=n.backgroundIntensity,c.material.toneMapped=gr.getTransfer(i.colorSpace)!==qt,i.matrixAutoUpdate===!0&&i.updateMatrix(),c.material.uniforms.uvTransform.value.copy(i.matrix),(u!==i||d!==i.version||f!==e.toneMapping)&&(c.material.needsUpdate=!0,u=i,d=i.version,f=e.toneMapping),c.layers.enableAll(),t.unshift(c,c.geometry,c.material,0,0,null))}function g(t,r){t.getRGB(wp,Bl(e)),n.buffers.color.setClear(wp.r,wp.g,wp.b,r,a)}function _(){l!==void 0&&(l.geometry.dispose(),l.material.dispose(),l=void 0),c!==void 0&&(c.geometry.dispose(),c.material.dispose(),c=void 0)}return{getClearColor:function(){return o},setClearColor:function(e,t=1){o.set(e),s=t,g(o,s)},getClearAlpha:function(){return s},setClearAlpha:function(e){s=e,g(o,s)},render:m,addToRenderList:h,dispose:_}}function Op(e,t){let n=e.getParameter(e.MAX_VERTEX_ATTRIBS),r={},i=f(null),a=i,o=!1;function s(n,r,i,s,c){let u=!1,f=d(n,s,i,r);a!==f&&(a=f,l(a.object)),u=p(n,s,i,c),u&&m(n,s,i,c),c!==null&&t.update(c,e.ELEMENT_ARRAY_BUFFER),(u||o)&&(o=!1,b(n,r,i,s),c!==null&&e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,t.get(c).buffer))}function c(){return e.createVertexArray()}function l(t){return e.bindVertexArray(t)}function u(t){return e.deleteVertexArray(t)}function d(e,t,n,i){let a=i.wireframe===!0,o=r[t.id];o===void 0&&(o={},r[t.id]=o);let s=e.isInstancedMesh===!0?e.id:0,l=o[s];l===void 0&&(l={},o[s]=l);let u=l[n.id];u===void 0&&(u={},l[n.id]=u);let d=u[a];return d===void 0&&(d=f(c()),u[a]=d),d}function f(e){let t=[],r=[],i=[];for(let e=0;e=0){let n=i[t],r=o[t];if(r===void 0&&(t===`instanceMatrix`&&e.instanceMatrix&&(r=e.instanceMatrix),t===`instanceColor`&&e.instanceColor&&(r=e.instanceColor)),n===void 0||n.attribute!==r||r&&n.data!==r.data)return!0;s++}return a.attributesNum!==s||a.index!==r}function m(e,t,n,r){let i={},o=t.attributes,s=0,c=n.getAttributes();for(let t in c)if(c[t].location>=0){let n=o[t];n===void 0&&(t===`instanceMatrix`&&e.instanceMatrix&&(n=e.instanceMatrix),t===`instanceColor`&&e.instanceColor&&(n=e.instanceColor));let r={};r.attribute=n,n&&n.data&&(r.data=n.data),i[t]=r,s++}a.attributes=i,a.attributesNum=s,a.index=r}function h(){let e=a.newAttributes;for(let t=0,n=e.length;t=0){let s=o[r];if(s===void 0&&(r===`instanceMatrix`&&n.instanceMatrix&&(s=n.instanceMatrix),r===`instanceColor`&&n.instanceColor&&(s=n.instanceColor)),s!==void 0){let r=s.normalized,o=s.itemSize,c=t.get(s);if(c===void 0)continue;let l=c.buffer,u=c.type,d=c.bytesPerElement,f=u===e.INT||u===e.UNSIGNED_INT||s.gpuType===1013;if(s.isInterleavedBufferAttribute){let t=s.data,c=t.stride,p=s.offset;if(t.isInstancedInterleavedBuffer){for(let e=0;e0&&e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.HIGH_FLOAT).precision>0)return`highp`;t=`mediump`}return t===`mediump`&&e.getShaderPrecisionFormat(e.VERTEX_SHADER,e.MEDIUM_FLOAT).precision>0&&e.getShaderPrecisionFormat(e.FRAGMENT_SHADER,e.MEDIUM_FLOAT).precision>0?`mediump`:`lowp`}let l=n.precision===void 0?`highp`:n.precision,u=c(l);u!==l&&(B(`WebGLRenderer:`,l,`not supported, using`,u,`instead.`),l=u);let d=n.logarithmicDepthBuffer===!0,f=n.reversedDepthBuffer===!0&&t.has(`EXT_clip_control`),p=e.getParameter(e.MAX_TEXTURE_IMAGE_UNITS),m=e.getParameter(e.MAX_VERTEX_TEXTURE_IMAGE_UNITS),h=e.getParameter(e.MAX_TEXTURE_SIZE),g=e.getParameter(e.MAX_CUBE_MAP_TEXTURE_SIZE),_=e.getParameter(e.MAX_VERTEX_ATTRIBS),v=e.getParameter(e.MAX_VERTEX_UNIFORM_VECTORS),y=e.getParameter(e.MAX_VARYING_VECTORS),b=e.getParameter(e.MAX_FRAGMENT_UNIFORM_VECTORS),x=e.getParameter(e.MAX_SAMPLES),S=e.getParameter(e.SAMPLES);return{isWebGL2:!0,getMaxAnisotropy:a,getMaxPrecision:c,textureFormatReadable:o,textureTypeReadable:s,precision:l,logarithmicDepthBuffer:d,reversedDepthBuffer:f,maxTextures:p,maxVertexTextures:m,maxTextureSize:h,maxCubemapSize:g,maxAttributes:_,maxVertexUniforms:v,maxVaryings:y,maxFragmentUniforms:b,maxSamples:x,samples:S}}function jp(e){let t=this,n=null,r=0,i=!1,a=!1,o=new Ho,s=new dr,c={value:null,needsUpdate:!1};this.uniform=c,this.numPlanes=0,this.numIntersection=0,this.init=function(e,t){let n=e.length!==0||t||r!==0||i;return i=t,r=e.length,n},this.beginShadows=function(){a=!0,u(null)},this.endShadows=function(){a=!1},this.setGlobalState=function(e,t){n=u(e,t,0)},this.setState=function(t,o,s){let d=t.clippingPlanes,f=t.clipIntersection,p=t.clipShadows,m=e.get(t);if(!i||d===null||d.length===0||a&&!p)a?u(null):l();else{let e=a?0:r,t=e*4,i=m.clippingState||null;c.value=i,i=u(d,o,t,s);for(let e=0;e!==t;++e)i[e]=n[e];m.clippingState=i,this.numIntersection=f?this.numPlanes:0,this.numPlanes+=e}};function l(){c.value!==n&&(c.value=n,c.needsUpdate=r>0),t.numPlanes=r,t.numIntersection=0}function u(e,n,r,i){let a=e===null?0:e.length,l=null;if(a!==0){if(l=c.value,i!==!0||l===null){let t=r+a*4,i=n.matrixWorldInverse;s.getNormalMatrix(i),(l===null||l.length0&&this._blur(s,0,0,t),this._applyPMREM(s),this._cleanup(s),s}fromEquirectangular(e,t=null){return this._fromTexture(e,t)}fromCubemap(e,t=null){return this._fromTexture(e,t)}compileCubemapShader(){this._cubemapMaterial===null&&(this._cubemapMaterial=Xp(),this._compileMaterial(this._cubemapMaterial))}compileEquirectangularShader(){this._equirectMaterial===null&&(this._equirectMaterial=Yp(),this._compileMaterial(this._equirectMaterial))}dispose(){this._dispose(),this._cubemapMaterial!==null&&this._cubemapMaterial.dispose(),this._equirectMaterial!==null&&this._equirectMaterial.dispose(),this._backgroundBox!==null&&(this._backgroundBox.geometry.dispose(),this._backgroundBox.material.dispose())}_setSize(e){this._lodMax=Math.floor(Math.log2(e)),this._cubeSize=2**this._lodMax}_dispose(){this._blurMaterial!==null&&this._blurMaterial.dispose(),this._ggxMaterial!==null&&this._ggxMaterial.dispose(),this._pingPongRenderTarget!==null&&this._pingPongRenderTarget.dispose();for(let e=0;e2?l:0,l,l),c.setRenderTarget(r),p&&c.render(d,a),c.render(e,a)}c.toneMapping=u,c.autoClear=l,e.background=m}_textureToCubeUV(e,t){let n=this._renderer,r=e.mapping===301||e.mapping===302;r?(this._cubemapMaterial===null&&(this._cubemapMaterial=Xp()),this._cubemapMaterial.uniforms.flipEnvMap.value=e.isRenderTargetTexture===!1?-1:1):this._equirectMaterial===null&&(this._equirectMaterial=Yp());let i=r?this._cubemapMaterial:this._equirectMaterial,a=this._lodMeshes[0];a.material=i;let o=i.uniforms;o.envMap.value=e;let s=this._cubeSize;Kp(t,0,0,3*s,2*s),n.setRenderTarget(t),n.render(a,Ip)}_applyPMREM(e){let t=this._renderer,n=t.autoClear;t.autoClear=!1;let r=this._lodMeshes.length;for(let t=1;td-Mp?n-d+Mp:0),m=4*(this._cubeSize-f);s.envMap.value=e.texture,s.roughness.value=u,s.mipInt.value=d-t,Kp(i,p,m,3*f,2*f),r.setRenderTarget(i),r.render(o,Ip),s.envMap.value=i.texture,s.roughness.value=0,s.mipInt.value=d-n,Kp(e,p,m,3*f,2*f),r.setRenderTarget(e),r.render(o,Ip)}_blur(e,t,n,r,i){let a=this._pingPongRenderTarget;this._halfBlur(e,a,t,n,r,`latitudinal`,i),this._halfBlur(a,e,n,n,r,`longitudinal`,i)}_halfBlur(e,t,n,r,i,a,o){let s=this._renderer,c=this._blurMaterial;a!==`latitudinal`&&a!==`longitudinal`&&An(`blur direction must be either latitudinal or longitudinal!`);let l=this._lodMeshes[r];l.material=c;let u=c.uniforms,d=this._sizeLods[n]-1,f=isFinite(i)?Math.PI/(2*d):2*Math.PI/(2*Pp-1),p=i/f,m=isFinite(i)?1+Math.floor(3*p):Pp;m>Pp&&B(`sigmaRadians, ${i}, is too large and will clip, as it requested ${m} samples when the maximum is set to ${Pp}`);let h=[],g=0;for(let e=0;e_-Mp?r-_+Mp:0),4*(this._cubeSize-v),3*v,2*v),s.setRenderTarget(t),s.render(l,Ip)}};function Wp(e){let t=[],n=[],r=[],i=e,a=e-Mp+1+Np.length;for(let o=0;oe-Mp?s=Np[o-e+Mp-1]:o===0&&(s=0),n.push(s);let c=1/(a-2),l=-c,u=1+c,d=[l,l,u,l,u,u,l,l,u,u,l,u],f=new Float32Array(108),p=new Float32Array(72),m=new Float32Array(36);for(let e=0;e<6;e++){let t=e%3*2/3-1,n=e>2?0:-1,r=[t,n,0,t+2/3,n,0,t+2/3,n+1,0,t,n,0,t+2/3,n+1,0,t,n+1,0];f.set(r,18*e),p.set(d,12*e);let i=[e,e,e,e,e,e];m.set(i,6*e)}let h=new ba;h.setAttribute(`position`,new ea(f,3)),h.setAttribute(`uv`,new ea(p,2)),h.setAttribute(`faceIndex`,new ea(m,1)),r.push(new fo(h,null)),i>Mp&&i--}return{lodMeshes:r,sizeLods:t,sigmas:n}}function Gp(e,t,n){let r=new kr(e,t,n);return r.texture.mapping=306,r.texture.name=`PMREM.cubeUv`,r.scissorTest=!0,r}function Kp(e,t,n,r,i){e.viewport.set(t,n,r,i),e.scissor.set(t,n,r,i)}function qp(e,t,n){return new q({name:`PMREMGGXConvolution`,defines:{GGX_SAMPLES:Fp,CUBEUV_TEXEL_WIDTH:1/t,CUBEUV_TEXEL_HEIGHT:1/n,CUBEUV_MAX_MIP:`${e}.0`},uniforms:{envMap:{value:null},roughness:{value:0},mipInt:{value:0}},vertexShader:Zp(),fragmentShader:` + + precision highp float; + precision highp int; + + varying vec3 vOutputDirection; + + uniform sampler2D envMap; + uniform float roughness; + uniform float mipInt; + + #define ENVMAP_TYPE_CUBE_UV + #include + + #define PI 3.14159265359 + + // Van der Corput radical inverse + float radicalInverse_VdC(uint bits) { + bits = (bits << 16u) | (bits >> 16u); + bits = ((bits & 0x55555555u) << 1u) | ((bits & 0xAAAAAAAAu) >> 1u); + bits = ((bits & 0x33333333u) << 2u) | ((bits & 0xCCCCCCCCu) >> 2u); + bits = ((bits & 0x0F0F0F0Fu) << 4u) | ((bits & 0xF0F0F0F0u) >> 4u); + bits = ((bits & 0x00FF00FFu) << 8u) | ((bits & 0xFF00FF00u) >> 8u); + return float(bits) * 2.3283064365386963e-10; // / 0x100000000 + } + + // Hammersley sequence + vec2 hammersley(uint i, uint N) { + return vec2(float(i) / float(N), radicalInverse_VdC(i)); + } + + // GGX VNDF importance sampling (Eric Heitz 2018) + // "Sampling the GGX Distribution of Visible Normals" + // https://jcgt.org/published/0007/04/01/ + vec3 importanceSampleGGX_VNDF(vec2 Xi, vec3 V, float roughness) { + float alpha = roughness * roughness; + + // Section 4.1: Orthonormal basis + vec3 T1 = vec3(1.0, 0.0, 0.0); + vec3 T2 = cross(V, T1); + + // Section 4.2: Parameterization of projected area + float r = sqrt(Xi.x); + float phi = 2.0 * PI * Xi.y; + float t1 = r * cos(phi); + float t2 = r * sin(phi); + float s = 0.5 * (1.0 + V.z); + t2 = (1.0 - s) * sqrt(1.0 - t1 * t1) + s * t2; + + // Section 4.3: Reprojection onto hemisphere + vec3 Nh = t1 * T1 + t2 * T2 + sqrt(max(0.0, 1.0 - t1 * t1 - t2 * t2)) * V; + + // Section 3.4: Transform back to ellipsoid configuration + return normalize(vec3(alpha * Nh.x, alpha * Nh.y, max(0.0, Nh.z))); + } + + void main() { + vec3 N = normalize(vOutputDirection); + vec3 V = N; // Assume view direction equals normal for pre-filtering + + vec3 prefilteredColor = vec3(0.0); + float totalWeight = 0.0; + + // For very low roughness, just sample the environment directly + if (roughness < 0.001) { + gl_FragColor = vec4(bilinearCubeUV(envMap, N, mipInt), 1.0); + return; + } + + // Tangent space basis for VNDF sampling + vec3 up = abs(N.z) < 0.999 ? vec3(0.0, 0.0, 1.0) : vec3(1.0, 0.0, 0.0); + vec3 tangent = normalize(cross(up, N)); + vec3 bitangent = cross(N, tangent); + + for(uint i = 0u; i < uint(GGX_SAMPLES); i++) { + vec2 Xi = hammersley(i, uint(GGX_SAMPLES)); + + // For PMREM, V = N, so in tangent space V is always (0, 0, 1) + vec3 H_tangent = importanceSampleGGX_VNDF(Xi, vec3(0.0, 0.0, 1.0), roughness); + + // Transform H back to world space + vec3 H = normalize(tangent * H_tangent.x + bitangent * H_tangent.y + N * H_tangent.z); + vec3 L = normalize(2.0 * dot(V, H) * H - V); + + float NdotL = max(dot(N, L), 0.0); + + if(NdotL > 0.0) { + // Sample environment at fixed mip level + // VNDF importance sampling handles the distribution filtering + vec3 sampleColor = bilinearCubeUV(envMap, L, mipInt); + + // Weight by NdotL for the split-sum approximation + // VNDF PDF naturally accounts for the visible microfacet distribution + prefilteredColor += sampleColor * NdotL; + totalWeight += NdotL; + } + } + + if (totalWeight > 0.0) { + prefilteredColor = prefilteredColor / totalWeight; + } + + gl_FragColor = vec4(prefilteredColor, 1.0); + } + `,blending:0,depthTest:!1,depthWrite:!1})}function Jp(e,t,n){let r=new Float32Array(Pp),i=new H(0,1,0);return new q({name:`SphericalGaussianBlur`,defines:{n:Pp,CUBEUV_TEXEL_WIDTH:1/t,CUBEUV_TEXEL_HEIGHT:1/n,CUBEUV_MAX_MIP:`${e}.0`},uniforms:{envMap:{value:null},samples:{value:1},weights:{value:r},latitudinal:{value:!1},dTheta:{value:0},mipInt:{value:0},poleAxis:{value:i}},vertexShader:Zp(),fragmentShader:` + + precision mediump float; + precision mediump int; + + varying vec3 vOutputDirection; + + uniform sampler2D envMap; + uniform int samples; + uniform float weights[ n ]; + uniform bool latitudinal; + uniform float dTheta; + uniform float mipInt; + uniform vec3 poleAxis; + + #define ENVMAP_TYPE_CUBE_UV + #include + + vec3 getSample( float theta, vec3 axis ) { + + float cosTheta = cos( theta ); + // Rodrigues' axis-angle rotation + vec3 sampleDirection = vOutputDirection * cosTheta + + cross( axis, vOutputDirection ) * sin( theta ) + + axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta ); + + return bilinearCubeUV( envMap, sampleDirection, mipInt ); + + } + + void main() { + + vec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection ); + + if ( all( equal( axis, vec3( 0.0 ) ) ) ) { + + axis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x ); + + } + + axis = normalize( axis ); + + gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 ); + gl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis ); + + for ( int i = 1; i < n; i++ ) { + + if ( i >= samples ) { + + break; + + } + + float theta = dTheta * float( i ); + gl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis ); + gl_FragColor.rgb += weights[ i ] * getSample( theta, axis ); + + } + + } + `,blending:0,depthTest:!1,depthWrite:!1})}function Yp(){return new q({name:`EquirectangularToCubeUV`,uniforms:{envMap:{value:null}},vertexShader:Zp(),fragmentShader:` + + precision mediump float; + precision mediump int; + + varying vec3 vOutputDirection; + + uniform sampler2D envMap; + + #include + + void main() { + + vec3 outputDirection = normalize( vOutputDirection ); + vec2 uv = equirectUv( outputDirection ); + + gl_FragColor = vec4( texture2D ( envMap, uv ).rgb, 1.0 ); + + } + `,blending:0,depthTest:!1,depthWrite:!1})}function Xp(){return new q({name:`CubemapToCubeUV`,uniforms:{envMap:{value:null},flipEnvMap:{value:-1}},vertexShader:Zp(),fragmentShader:` + + precision mediump float; + precision mediump int; + + uniform float flipEnvMap; + + varying vec3 vOutputDirection; + + uniform samplerCube envMap; + + void main() { + + gl_FragColor = textureCube( envMap, vec3( flipEnvMap * vOutputDirection.x, vOutputDirection.yz ) ); + + } + `,blending:0,depthTest:!1,depthWrite:!1})}function Zp(){return` + + precision mediump float; + precision mediump int; + + attribute float faceIndex; + + varying vec3 vOutputDirection; + + // RH coordinate system; PMREM face-indexing convention + vec3 getDirection( vec2 uv, float face ) { + + uv = 2.0 * uv - 1.0; + + vec3 direction = vec3( uv, 1.0 ); + + if ( face == 0.0 ) { + + direction = direction.zyx; // ( 1, v, u ) pos x + + } else if ( face == 1.0 ) { + + direction = direction.xzy; + direction.xz *= -1.0; // ( -u, 1, -v ) pos y + + } else if ( face == 2.0 ) { + + direction.x *= -1.0; // ( -u, v, 1 ) pos z + + } else if ( face == 3.0 ) { + + direction = direction.zyx; + direction.xz *= -1.0; // ( -1, v, -u ) neg x + + } else if ( face == 4.0 ) { + + direction = direction.xzy; + direction.xy *= -1.0; // ( -u, -1, v ) neg y + + } else if ( face == 5.0 ) { + + direction.z *= -1.0; // ( u, v, -1 ) neg z + + } + + return direction; + + } + + void main() { + + vOutputDirection = getDirection( uv, faceIndex ); + gl_Position = vec4( position, 1.0 ); + + } + `}var Qp=class extends kr{constructor(e=1,t={}){super(e,e,t),this.isWebGLCubeRenderTarget=!0;let n={width:e,height:e,depth:1};this.texture=new Hs([n,n,n,n,n,n]),this._setTextureOptions(t),this.texture.isRenderTargetTexture=!0}fromEquirectangularTexture(e,t){this.texture.type=t.type,this.texture.colorSpace=t.colorSpace,this.texture.generateMipmaps=t.generateMipmaps,this.texture.minFilter=t.minFilter,this.texture.magFilter=t.magFilter;let n={uniforms:{tEquirect:{value:null}},vertexShader:` + + varying vec3 vWorldDirection; + + vec3 transformDirection( in vec3 dir, in mat4 matrix ) { + + return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz ); + + } + + void main() { + + vWorldDirection = transformDirection( position, modelMatrix ); + + #include + #include + + } + `,fragmentShader:` + + uniform sampler2D tEquirect; + + varying vec3 vWorldDirection; + + #include + + void main() { + + vec3 direction = normalize( vWorldDirection ); + + vec2 sampleUV = equirectUv( direction ); + + gl_FragColor = texture2D( tEquirect, sampleUV ); + + } + `},r=new qs(5,5,5),i=new q({name:`CubemapFromEquirect`,uniforms:Ll(n.uniforms),vertexShader:n.vertexShader,fragmentShader:n.fragmentShader,side:1,blending:0});i.uniforms.tEquirect.value=t;let a=new fo(r,i),o=t.minFilter;return t.minFilter===1008&&(t.minFilter=L),new kd(1,10,this).update(e,a),t.minFilter=o,a.geometry.dispose(),a.material.dispose(),this}clear(e,t=!0,n=!0,r=!0){let i=e.getRenderTarget();for(let i=0;i<6;i++)e.setRenderTarget(this,i),e.clear(t,n,r);e.setRenderTarget(i)}};function $p(e){let t=new WeakMap,n=new WeakMap,r=null;function i(e,t=!1){return e==null?null:t?o(e):a(e)}function a(n){if(n&&n.isTexture){let r=n.mapping;if(r===303||r===304)if(t.has(n)){let e=t.get(n).texture;return s(e,n.mapping)}else{let r=n.image;if(r&&r.height>0){let i=new Qp(r.height);return i.fromEquirectangularTexture(e,n),t.set(n,i),n.addEventListener(`dispose`,l),s(i.texture,n.mapping)}else return null}}return n}function o(t){if(t&&t.isTexture){let i=t.mapping,a=i===303||i===304,o=i===301||i===302;if(a||o){let i=n.get(t),s=i===void 0?0:i.texture.pmremVersion;if(t.isRenderTargetTexture&&t.pmremVersion!==s)return r===null&&(r=new Up(e)),i=a?r.fromEquirectangular(t,i):r.fromCubemap(t,i),i.texture.pmremVersion=t.pmremVersion,n.set(t,i),i.texture;if(i!==void 0)return i.texture;{let s=t.image;return a&&s&&s.height>0||o&&s&&c(s)?(r===null&&(r=new Up(e)),i=a?r.fromEquirectangular(t):r.fromCubemap(t),i.texture.pmremVersion=t.pmremVersion,n.set(t,i),t.addEventListener(`dispose`,u),i.texture):null}}}return t}function s(e,t){return t===303?e.mapping=301:t===304&&(e.mapping=302),e}function c(e){let t=0;for(let n=0;n<6;n++)e[n]!==void 0&&t++;return t===6}function l(e){let n=e.target;n.removeEventListener(`dispose`,l);let r=t.get(n);r!==void 0&&(t.delete(n),r.dispose())}function u(e){let t=e.target;t.removeEventListener(`dispose`,u);let r=n.get(t);r!==void 0&&(n.delete(t),r.dispose())}function d(){t=new WeakMap,n=new WeakMap,r!==null&&(r.dispose(),r=null)}return{get:i,dispose:d}}function em(e){let t={};function n(n){if(t[n]!==void 0)return t[n];let r=e.getExtension(n);return t[n]=r,r}return{has:function(e){return n(e)!==null},init:function(){n(`EXT_color_buffer_float`),n(`WEBGL_clip_cull_distance`),n(`OES_texture_float_linear`),n(`EXT_color_buffer_half_float`),n(`WEBGL_multisampled_render_to_texture`),n(`WEBGL_render_shared_exponent`)},get:function(e){let t=n(e);return t===null&&jn(`WebGLRenderer: `+e+` extension not supported.`),t}}}function tm(e,t,n,r){let i={},a=new WeakMap;function o(e){let s=e.target;s.index!==null&&t.remove(s.index);for(let e in s.attributes)t.remove(s.attributes[e]);s.removeEventListener(`dispose`,o),delete i[s.id];let c=a.get(s);c&&(t.remove(c),a.delete(s)),r.releaseStatesOfGeometry(s),s.isInstancedBufferGeometry===!0&&delete s._maxInstanceCount,n.memory.geometries--}function s(e,t){return i[t.id]===!0?t:(t.addEventListener(`dispose`,o),i[t.id]=!0,n.memory.geometries++,t)}function c(n){let r=n.attributes;for(let n in r)t.update(r[n],e.ARRAY_BUFFER)}function l(e){let n=[],r=e.index,i=e.attributes.position,o=0;if(i===void 0)return;if(r!==null){let e=r.array;o=r.version;for(let t=0,r=e.length;t=65535?sa:aa)(n,1);s.version=o;let c=a.get(e);c&&t.remove(c),a.set(e,s)}function u(e){let t=a.get(e);if(t){let n=e.index;n!==null&&t.versiont.maxTextureSize&&(m=Math.ceil(p/t.maxTextureSize),p=t.maxTextureSize);let h=new Float32Array(p*m*4*u),g=new Ar(h,p,m,u);g.type=Oe,g.needsUpdate=!0;let _=f*4;for(let t=0;t + #include + + void main() { + gl_FragColor = texture2D( tDiffuse, vUv ); + + #ifdef LINEAR_TONE_MAPPING + gl_FragColor.rgb = LinearToneMapping( gl_FragColor.rgb ); + #elif defined( REINHARD_TONE_MAPPING ) + gl_FragColor.rgb = ReinhardToneMapping( gl_FragColor.rgb ); + #elif defined( CINEON_TONE_MAPPING ) + gl_FragColor.rgb = CineonToneMapping( gl_FragColor.rgb ); + #elif defined( ACES_FILMIC_TONE_MAPPING ) + gl_FragColor.rgb = ACESFilmicToneMapping( gl_FragColor.rgb ); + #elif defined( AGX_TONE_MAPPING ) + gl_FragColor.rgb = AgXToneMapping( gl_FragColor.rgb ); + #elif defined( NEUTRAL_TONE_MAPPING ) + gl_FragColor.rgb = NeutralToneMapping( gl_FragColor.rgb ); + #elif defined( CUSTOM_TONE_MAPPING ) + gl_FragColor.rgb = CustomToneMapping( gl_FragColor.rgb ); + #endif + + #ifdef SRGB_TRANSFER + gl_FragColor = sRGBTransferOETF( gl_FragColor ); + #endif + }`,depthTest:!1,depthWrite:!1}),l=new fo(s,c),u=new rd(-1,1,1,-1,0,1),d=null,f=null,p=!1,m,h=null,g=[],_=!1;this.setSize=function(e,t){a.setSize(e,t),o.setSize(e,t);for(let n=0;n0&&g[0].isRenderPass===!0;let t=a.width,n=a.height;for(let e=0;e0)return e;let i=t*n,a=pm[i];if(a===void 0&&(a=new Float32Array(i),pm[i]=a),t!==0){r.toArray(a,0);for(let r=1,i=0;r!==t;++r)i+=n,e[r].toArray(a,i)}return a}function ym(e,t){if(e.length!==t.length)return!1;for(let n=0,r=e.length;n0&&(this.seq=r.concat(i))}setValue(e,t,n,r){let i=this.map[t];i!==void 0&&i.setValue(e,n,r)}setOptional(e,t,n){let r=t[n];r!==void 0&&this.setValue(e,n,r)}static upload(e,t,n,r){for(let i=0,a=t.length;i!==a;++i){let a=t[i],o=n[a.id];o.needsUpdate!==!1&&a.setValue(e,o.value,r)}}static seqWithValue(e,t){let n=[];for(let r=0,i=e.length;r!==i;++r){let i=e[r];i.id in t&&n.push(i)}return n}};function hh(e,t,n){let r=e.createShader(t);return e.shaderSource(r,n),e.compileShader(r),r}var gh=37297,_h=0;function vh(e,t){let n=e.split(` +`),r=[],i=Math.max(t-6,0),a=Math.min(t+6,n.length);for(let e=i;e`:` `} ${i}: ${n[e]}`)}return r.join(` +`)}var yh=new dr;function bh(e){gr._getMatrix(yh,gr.workingColorSpace,e);let t=`mat3( ${yh.elements.map(e=>e.toFixed(4))} )`;switch(gr.getTransfer(e)){case Kt:return[t,`LinearTransferOETF`];case qt:return[t,`sRGBTransferOETF`];default:return B(`WebGLProgram: Unsupported color space: `,e),[t,`LinearTransferOETF`]}}function xh(e,t,n){let r=e.getShaderParameter(t,e.COMPILE_STATUS),i=(e.getShaderInfoLog(t)||``).trim();if(r&&i===``)return``;let a=/ERROR: 0:(\d+)/.exec(i);if(a){let r=parseInt(a[1]);return n.toUpperCase()+` + +`+i+` + +`+vh(e.getShaderSource(t),r)}else return i}function Sh(e,t){let n=bh(t);return[`vec4 ${e}( vec4 value ) {`,` return ${n[1]}( vec4( value.rgb * ${n[0]}, value.a ) );`,`}`].join(` +`)}var Ch={1:`Linear`,2:`Reinhard`,3:`Cineon`,4:`ACESFilmic`,6:`AgX`,7:`Neutral`,5:`Custom`};function wh(e,t){let n=Ch[t];return n===void 0?(B(`WebGLProgram: Unsupported toneMapping:`,t),`vec3 `+e+`( vec3 color ) { return LinearToneMapping( color ); }`):`vec3 `+e+`( vec3 color ) { return `+n+`ToneMapping( color ); }`}var Th=new H;function Eh(){return gr.getLuminanceCoefficients(Th),[`float luminance( const in vec3 rgb ) {`,` const vec3 weights = vec3( ${Th.x.toFixed(4)}, ${Th.y.toFixed(4)}, ${Th.z.toFixed(4)} );`,` return dot( weights, rgb );`,`}`].join(` +`)}function Dh(e){return[e.extensionClipCullDistance?`#extension GL_ANGLE_clip_cull_distance : require`:``,e.extensionMultiDraw?`#extension GL_ANGLE_multi_draw : require`:``].filter(Ah).join(` +`)}function Oh(e){let t=[];for(let n in e){let r=e[n];r!==!1&&t.push(`#define `+n+` `+r)}return t.join(` +`)}function kh(e,t){let n={},r=e.getProgramParameter(t,e.ACTIVE_ATTRIBUTES);for(let i=0;i/gm;function Ph(e){return e.replace(Nh,Ih)}var Fh=new Map;function Ih(e,t){let n=Sp[t];if(n===void 0){let e=Fh.get(t);if(e!==void 0)n=Sp[e],B(`WebGLRenderer: Shader chunk "%s" has been deprecated. Use "%s" instead.`,t,e);else throw Error(`Can not resolve #include <`+t+`>`)}return Ph(n)}var Lh=/#pragma unroll_loop_start\s+for\s*\(\s*int\s+i\s*=\s*(\d+)\s*;\s*i\s*<\s*(\d+)\s*;\s*i\s*\+\+\s*\)\s*{([\s\S]+?)}\s+#pragma unroll_loop_end/g;function Rh(e){return e.replace(Lh,zh)}function zh(e,t,n,r){let i=``;for(let e=parseInt(t);e0&&(g+=` +`),_=[`#define SHADER_TYPE `+n.shaderType,`#define SHADER_NAME `+n.shaderName,m].filter(Ah).join(` +`),_.length>0&&(_+=` +`)):(g=[Bh(n),`#define SHADER_TYPE `+n.shaderType,`#define SHADER_NAME `+n.shaderName,m,n.extensionClipCullDistance?`#define USE_CLIP_DISTANCE`:``,n.batching?`#define USE_BATCHING`:``,n.batchingColor?`#define USE_BATCHING_COLOR`:``,n.instancing?`#define USE_INSTANCING`:``,n.instancingColor?`#define USE_INSTANCING_COLOR`:``,n.instancingMorph?`#define USE_INSTANCING_MORPH`:``,n.useFog&&n.fog?`#define USE_FOG`:``,n.useFog&&n.fogExp2?`#define FOG_EXP2`:``,n.map?`#define USE_MAP`:``,n.envMap?`#define USE_ENVMAP`:``,n.envMap?`#define `+u:``,n.lightMap?`#define USE_LIGHTMAP`:``,n.aoMap?`#define USE_AOMAP`:``,n.bumpMap?`#define USE_BUMPMAP`:``,n.normalMap?`#define USE_NORMALMAP`:``,n.normalMapObjectSpace?`#define USE_NORMALMAP_OBJECTSPACE`:``,n.normalMapTangentSpace?`#define USE_NORMALMAP_TANGENTSPACE`:``,n.displacementMap?`#define USE_DISPLACEMENTMAP`:``,n.emissiveMap?`#define USE_EMISSIVEMAP`:``,n.anisotropy?`#define USE_ANISOTROPY`:``,n.anisotropyMap?`#define USE_ANISOTROPYMAP`:``,n.clearcoatMap?`#define USE_CLEARCOATMAP`:``,n.clearcoatRoughnessMap?`#define USE_CLEARCOAT_ROUGHNESSMAP`:``,n.clearcoatNormalMap?`#define USE_CLEARCOAT_NORMALMAP`:``,n.iridescenceMap?`#define USE_IRIDESCENCEMAP`:``,n.iridescenceThicknessMap?`#define USE_IRIDESCENCE_THICKNESSMAP`:``,n.specularMap?`#define USE_SPECULARMAP`:``,n.specularColorMap?`#define USE_SPECULAR_COLORMAP`:``,n.specularIntensityMap?`#define USE_SPECULAR_INTENSITYMAP`:``,n.roughnessMap?`#define USE_ROUGHNESSMAP`:``,n.metalnessMap?`#define USE_METALNESSMAP`:``,n.alphaMap?`#define USE_ALPHAMAP`:``,n.alphaHash?`#define USE_ALPHAHASH`:``,n.transmission?`#define USE_TRANSMISSION`:``,n.transmissionMap?`#define USE_TRANSMISSIONMAP`:``,n.thicknessMap?`#define USE_THICKNESSMAP`:``,n.sheenColorMap?`#define USE_SHEEN_COLORMAP`:``,n.sheenRoughnessMap?`#define USE_SHEEN_ROUGHNESSMAP`:``,n.mapUv?`#define MAP_UV `+n.mapUv:``,n.alphaMapUv?`#define ALPHAMAP_UV `+n.alphaMapUv:``,n.lightMapUv?`#define LIGHTMAP_UV `+n.lightMapUv:``,n.aoMapUv?`#define AOMAP_UV `+n.aoMapUv:``,n.emissiveMapUv?`#define EMISSIVEMAP_UV `+n.emissiveMapUv:``,n.bumpMapUv?`#define BUMPMAP_UV `+n.bumpMapUv:``,n.normalMapUv?`#define NORMALMAP_UV `+n.normalMapUv:``,n.displacementMapUv?`#define DISPLACEMENTMAP_UV `+n.displacementMapUv:``,n.metalnessMapUv?`#define METALNESSMAP_UV `+n.metalnessMapUv:``,n.roughnessMapUv?`#define ROUGHNESSMAP_UV `+n.roughnessMapUv:``,n.anisotropyMapUv?`#define ANISOTROPYMAP_UV `+n.anisotropyMapUv:``,n.clearcoatMapUv?`#define CLEARCOATMAP_UV `+n.clearcoatMapUv:``,n.clearcoatNormalMapUv?`#define CLEARCOAT_NORMALMAP_UV `+n.clearcoatNormalMapUv:``,n.clearcoatRoughnessMapUv?`#define CLEARCOAT_ROUGHNESSMAP_UV `+n.clearcoatRoughnessMapUv:``,n.iridescenceMapUv?`#define IRIDESCENCEMAP_UV `+n.iridescenceMapUv:``,n.iridescenceThicknessMapUv?`#define IRIDESCENCE_THICKNESSMAP_UV `+n.iridescenceThicknessMapUv:``,n.sheenColorMapUv?`#define SHEEN_COLORMAP_UV `+n.sheenColorMapUv:``,n.sheenRoughnessMapUv?`#define SHEEN_ROUGHNESSMAP_UV `+n.sheenRoughnessMapUv:``,n.specularMapUv?`#define SPECULARMAP_UV `+n.specularMapUv:``,n.specularColorMapUv?`#define SPECULAR_COLORMAP_UV `+n.specularColorMapUv:``,n.specularIntensityMapUv?`#define SPECULAR_INTENSITYMAP_UV `+n.specularIntensityMapUv:``,n.transmissionMapUv?`#define TRANSMISSIONMAP_UV `+n.transmissionMapUv:``,n.thicknessMapUv?`#define THICKNESSMAP_UV `+n.thicknessMapUv:``,n.vertexTangents&&n.flatShading===!1?`#define USE_TANGENT`:``,n.vertexColors?`#define USE_COLOR`:``,n.vertexAlphas?`#define USE_COLOR_ALPHA`:``,n.vertexUv1s?`#define USE_UV1`:``,n.vertexUv2s?`#define USE_UV2`:``,n.vertexUv3s?`#define USE_UV3`:``,n.pointsUvs?`#define USE_POINTS_UV`:``,n.flatShading?`#define FLAT_SHADED`:``,n.skinning?`#define USE_SKINNING`:``,n.morphTargets?`#define USE_MORPHTARGETS`:``,n.morphNormals&&n.flatShading===!1?`#define USE_MORPHNORMALS`:``,n.morphColors?`#define USE_MORPHCOLORS`:``,n.morphTargetsCount>0?`#define MORPHTARGETS_TEXTURE_STRIDE `+n.morphTextureStride:``,n.morphTargetsCount>0?`#define MORPHTARGETS_COUNT `+n.morphTargetsCount:``,n.doubleSided?`#define DOUBLE_SIDED`:``,n.flipSided?`#define FLIP_SIDED`:``,n.shadowMapEnabled?`#define USE_SHADOWMAP`:``,n.shadowMapEnabled?`#define `+c:``,n.sizeAttenuation?`#define USE_SIZEATTENUATION`:``,n.numLightProbes>0?`#define USE_LIGHT_PROBES`:``,n.logarithmicDepthBuffer?`#define USE_LOGARITHMIC_DEPTH_BUFFER`:``,n.reversedDepthBuffer?`#define USE_REVERSED_DEPTH_BUFFER`:``,`uniform mat4 modelMatrix;`,`uniform mat4 modelViewMatrix;`,`uniform mat4 projectionMatrix;`,`uniform mat4 viewMatrix;`,`uniform mat3 normalMatrix;`,`uniform vec3 cameraPosition;`,`uniform bool isOrthographic;`,`#ifdef USE_INSTANCING`,` attribute mat4 instanceMatrix;`,`#endif`,`#ifdef USE_INSTANCING_COLOR`,` attribute vec3 instanceColor;`,`#endif`,`#ifdef USE_INSTANCING_MORPH`,` uniform sampler2D morphTexture;`,`#endif`,`attribute vec3 position;`,`attribute vec3 normal;`,`attribute vec2 uv;`,`#ifdef USE_UV1`,` attribute vec2 uv1;`,`#endif`,`#ifdef USE_UV2`,` attribute vec2 uv2;`,`#endif`,`#ifdef USE_UV3`,` attribute vec2 uv3;`,`#endif`,`#ifdef USE_TANGENT`,` attribute vec4 tangent;`,`#endif`,`#if defined( USE_COLOR_ALPHA )`,` attribute vec4 color;`,`#elif defined( USE_COLOR )`,` attribute vec3 color;`,`#endif`,`#ifdef USE_SKINNING`,` attribute vec4 skinIndex;`,` attribute vec4 skinWeight;`,`#endif`,` +`].filter(Ah).join(` +`),_=[Bh(n),`#define SHADER_TYPE `+n.shaderType,`#define SHADER_NAME `+n.shaderName,m,n.useFog&&n.fog?`#define USE_FOG`:``,n.useFog&&n.fogExp2?`#define FOG_EXP2`:``,n.alphaToCoverage?`#define ALPHA_TO_COVERAGE`:``,n.map?`#define USE_MAP`:``,n.matcap?`#define USE_MATCAP`:``,n.envMap?`#define USE_ENVMAP`:``,n.envMap?`#define `+l:``,n.envMap?`#define `+u:``,n.envMap?`#define `+d:``,f?`#define CUBEUV_TEXEL_WIDTH `+f.texelWidth:``,f?`#define CUBEUV_TEXEL_HEIGHT `+f.texelHeight:``,f?`#define CUBEUV_MAX_MIP `+f.maxMip+`.0`:``,n.lightMap?`#define USE_LIGHTMAP`:``,n.aoMap?`#define USE_AOMAP`:``,n.bumpMap?`#define USE_BUMPMAP`:``,n.normalMap?`#define USE_NORMALMAP`:``,n.normalMapObjectSpace?`#define USE_NORMALMAP_OBJECTSPACE`:``,n.normalMapTangentSpace?`#define USE_NORMALMAP_TANGENTSPACE`:``,n.emissiveMap?`#define USE_EMISSIVEMAP`:``,n.anisotropy?`#define USE_ANISOTROPY`:``,n.anisotropyMap?`#define USE_ANISOTROPYMAP`:``,n.clearcoat?`#define USE_CLEARCOAT`:``,n.clearcoatMap?`#define USE_CLEARCOATMAP`:``,n.clearcoatRoughnessMap?`#define USE_CLEARCOAT_ROUGHNESSMAP`:``,n.clearcoatNormalMap?`#define USE_CLEARCOAT_NORMALMAP`:``,n.dispersion?`#define USE_DISPERSION`:``,n.iridescence?`#define USE_IRIDESCENCE`:``,n.iridescenceMap?`#define USE_IRIDESCENCEMAP`:``,n.iridescenceThicknessMap?`#define USE_IRIDESCENCE_THICKNESSMAP`:``,n.specularMap?`#define USE_SPECULARMAP`:``,n.specularColorMap?`#define USE_SPECULAR_COLORMAP`:``,n.specularIntensityMap?`#define USE_SPECULAR_INTENSITYMAP`:``,n.roughnessMap?`#define USE_ROUGHNESSMAP`:``,n.metalnessMap?`#define USE_METALNESSMAP`:``,n.alphaMap?`#define USE_ALPHAMAP`:``,n.alphaTest?`#define USE_ALPHATEST`:``,n.alphaHash?`#define USE_ALPHAHASH`:``,n.sheen?`#define USE_SHEEN`:``,n.sheenColorMap?`#define USE_SHEEN_COLORMAP`:``,n.sheenRoughnessMap?`#define USE_SHEEN_ROUGHNESSMAP`:``,n.transmission?`#define USE_TRANSMISSION`:``,n.transmissionMap?`#define USE_TRANSMISSIONMAP`:``,n.thicknessMap?`#define USE_THICKNESSMAP`:``,n.vertexTangents&&n.flatShading===!1?`#define USE_TANGENT`:``,n.vertexColors||n.instancingColor?`#define USE_COLOR`:``,n.vertexAlphas||n.batchingColor?`#define USE_COLOR_ALPHA`:``,n.vertexUv1s?`#define USE_UV1`:``,n.vertexUv2s?`#define USE_UV2`:``,n.vertexUv3s?`#define USE_UV3`:``,n.pointsUvs?`#define USE_POINTS_UV`:``,n.gradientMap?`#define USE_GRADIENTMAP`:``,n.flatShading?`#define FLAT_SHADED`:``,n.doubleSided?`#define DOUBLE_SIDED`:``,n.flipSided?`#define FLIP_SIDED`:``,n.shadowMapEnabled?`#define USE_SHADOWMAP`:``,n.shadowMapEnabled?`#define `+c:``,n.premultipliedAlpha?`#define PREMULTIPLIED_ALPHA`:``,n.numLightProbes>0?`#define USE_LIGHT_PROBES`:``,n.decodeVideoTexture?`#define DECODE_VIDEO_TEXTURE`:``,n.decodeVideoTextureEmissive?`#define DECODE_VIDEO_TEXTURE_EMISSIVE`:``,n.logarithmicDepthBuffer?`#define USE_LOGARITHMIC_DEPTH_BUFFER`:``,n.reversedDepthBuffer?`#define USE_REVERSED_DEPTH_BUFFER`:``,`uniform mat4 viewMatrix;`,`uniform vec3 cameraPosition;`,`uniform bool isOrthographic;`,n.toneMapping===0?``:`#define TONE_MAPPING`,n.toneMapping===0?``:Sp.tonemapping_pars_fragment,n.toneMapping===0?``:wh(`toneMapping`,n.toneMapping),n.dithering?`#define DITHERING`:``,n.opaque?`#define OPAQUE`:``,Sp.colorspace_pars_fragment,Sh(`linearToOutputTexel`,n.outputColorSpace),Eh(),n.useDepthPacking?`#define DEPTH_PACKING `+n.depthPacking:``,` +`].filter(Ah).join(` +`)),o=Ph(o),o=jh(o,n),o=Mh(o,n),s=Ph(s),s=jh(s,n),s=Mh(s,n),o=Rh(o),s=Rh(s),n.isRawShaderMaterial!==!0&&(v=`#version 300 es +`,g=[p,`#define attribute in`,`#define varying out`,`#define texture2D texture`].join(` +`)+` +`+g,_=[`#define varying in`,n.glslVersion===`300 es`?``:`layout(location = 0) out highp vec4 pc_fragColor;`,n.glslVersion===`300 es`?``:`#define gl_FragColor pc_fragColor`,`#define gl_FragDepthEXT gl_FragDepth`,`#define texture2D texture`,`#define textureCube texture`,`#define texture2DProj textureProj`,`#define texture2DLodEXT textureLod`,`#define texture2DProjLodEXT textureProjLod`,`#define textureCubeLodEXT textureLod`,`#define texture2DGradEXT textureGrad`,`#define texture2DProjGradEXT textureProjGrad`,`#define textureCubeGradEXT textureGrad`].join(` +`)+` +`+_);let y=v+g+o,b=v+_+s,x=hh(i,i.VERTEX_SHADER,y),S=hh(i,i.FRAGMENT_SHADER,b);i.attachShader(h,x),i.attachShader(h,S),n.index0AttributeName===void 0?n.morphTargets===!0&&i.bindAttribLocation(h,0,`position`):i.bindAttribLocation(h,0,n.index0AttributeName),i.linkProgram(h);function C(t){if(e.debug.checkShaderErrors){let n=i.getProgramInfoLog(h)||``,r=i.getShaderInfoLog(x)||``,a=i.getShaderInfoLog(S)||``,o=n.trim(),s=r.trim(),c=a.trim(),l=!0,u=!0;if(i.getProgramParameter(h,i.LINK_STATUS)===!1)if(l=!1,typeof e.debug.onShaderError==`function`)e.debug.onShaderError(i,h,x,S);else{let e=xh(i,x,`vertex`),n=xh(i,S,`fragment`);An(`THREE.WebGLProgram: Shader Error `+i.getError()+` - VALIDATE_STATUS `+i.getProgramParameter(h,i.VALIDATE_STATUS)+` + +Material Name: `+t.name+` +Material Type: `+t.type+` + +Program Info Log: `+o+` +`+e+` +`+n)}else o===``?(s===``||c===``)&&(u=!1):B(`WebGLProgram: Program Info Log:`,o);u&&(t.diagnostics={runnable:l,programLog:o,vertexShader:{log:s,prefix:g},fragmentShader:{log:c,prefix:_}})}i.deleteShader(x),i.deleteShader(S),w=new mh(i,h),T=kh(i,h)}let w;this.getUniforms=function(){return w===void 0&&C(this),w};let T;this.getAttributes=function(){return T===void 0&&C(this),T};let E=n.rendererExtensionParallelShaderCompile===!1;return this.isReady=function(){return E===!1&&(E=i.getProgramParameter(h,gh)),E},this.destroy=function(){r.releaseStatesOfProgram(this),i.deleteProgram(h),this.program=void 0},this.type=n.shaderType,this.name=n.shaderName,this.id=_h++,this.cacheKey=t,this.usedTimes=1,this.program=h,this.vertexShader=x,this.fragmentShader=S,this}var Zh=0,Qh=class{constructor(){this.shaderCache=new Map,this.materialCache=new Map}update(e){let t=e.vertexShader,n=e.fragmentShader,r=this._getShaderStage(t),i=this._getShaderStage(n),a=this._getShaderCacheForMaterial(e);return a.has(r)===!1&&(a.add(r),r.usedTimes++),a.has(i)===!1&&(a.add(i),i.usedTimes++),this}remove(e){let t=this.materialCache.get(e);for(let e of t)e.usedTimes--,e.usedTimes===0&&this.shaderCache.delete(e.code);return this.materialCache.delete(e),this}getVertexShaderID(e){return this._getShaderStage(e.vertexShader).id}getFragmentShaderID(e){return this._getShaderStage(e.fragmentShader).id}dispose(){this.shaderCache.clear(),this.materialCache.clear()}_getShaderCacheForMaterial(e){let t=this.materialCache,n=t.get(e);return n===void 0&&(n=new Set,t.set(e,n)),n}_getShaderStage(e){let t=this.shaderCache,n=t.get(e);return n===void 0&&(n=new $h(e),t.set(e,n)),n}},$h=class{constructor(e){this.id=Zh++,this.code=e,this.usedTimes=0}};function eg(e,t,n,r,i,a){let o=new Gr,s=new Qh,c=new Set,l=[],u=new Map,d=r.logarithmicDepthBuffer,f=r.precision,p={MeshDepthMaterial:`depth`,MeshDistanceMaterial:`distance`,MeshNormalMaterial:`normal`,MeshBasicMaterial:`basic`,MeshLambertMaterial:`lambert`,MeshPhongMaterial:`phong`,MeshToonMaterial:`toon`,MeshStandardMaterial:`physical`,MeshPhysicalMaterial:`physical`,MeshMatcapMaterial:`matcap`,LineBasicMaterial:`basic`,LineDashedMaterial:`dashed`,PointsMaterial:`points`,ShadowMaterial:`shadow`,SpriteMaterial:`sprite`};function m(e){return c.add(e),e===0?`uv`:`uv${e}`}function h(i,o,l,u,h){let g=u.fog,_=h.geometry,v=i.isMeshStandardMaterial||i.isMeshLambertMaterial||i.isMeshPhongMaterial?u.environment:null,y=i.isMeshStandardMaterial||i.isMeshLambertMaterial&&!i.envMap||i.isMeshPhongMaterial&&!i.envMap,b=t.get(i.envMap||v,y),x=b&&b.mapping===306?b.image.height:null,S=p[i.type];i.precision!==null&&(f=r.getMaxPrecision(i.precision),f!==i.precision&&B(`WebGLProgram.getParameters:`,i.precision,`not supported, using`,f,`instead.`));let C=_.morphAttributes.position||_.morphAttributes.normal||_.morphAttributes.color,w=C===void 0?0:C.length,T=0;_.morphAttributes.position!==void 0&&(T=1),_.morphAttributes.normal!==void 0&&(T=2),_.morphAttributes.color!==void 0&&(T=3);let E,D,O,k;if(S){let e=Cp[S];E=e.vertexShader,D=e.fragmentShader}else E=i.vertexShader,D=i.fragmentShader,s.update(i),O=s.getVertexShaderID(i),k=s.getFragmentShaderID(i);let A=e.getRenderTarget(),j=e.state.buffers.depth.getReversed(),ee=h.isInstancedMesh===!0,M=h.isBatchedMesh===!0,N=!!i.map,P=!!i.matcap,F=!!b,te=!!i.aoMap,ne=!!i.lightMap,re=!!i.bumpMap,ie=!!i.normalMap,ae=!!i.displacementMap,oe=!!i.emissiveMap,se=!!i.metalnessMap,ce=!!i.roughnessMap,le=i.anisotropy>0,ue=i.clearcoat>0,de=i.dispersion>0,fe=i.iridescence>0,pe=i.sheen>0,me=i.transmission>0,he=le&&!!i.anisotropyMap,ge=ue&&!!i.clearcoatMap,I=ue&&!!i.clearcoatNormalMap,_e=ue&&!!i.clearcoatRoughnessMap,ve=fe&&!!i.iridescenceMap,ye=fe&&!!i.iridescenceThicknessMap,L=pe&&!!i.sheenColorMap,R=pe&&!!i.sheenRoughnessMap,z=!!i.specularMap,be=!!i.specularColorMap,xe=!!i.specularIntensityMap,Se=me&&!!i.transmissionMap,Ce=me&&!!i.thicknessMap,we=!!i.gradientMap,Te=!!i.alphaMap,Ee=i.alphaTest>0,De=!!i.alphaHash,Oe=!!i.extensions,ke=0;i.toneMapped&&(A===null||A.isXRRenderTarget===!0)&&(ke=e.toneMapping);let Ae={shaderID:S,shaderType:i.type,shaderName:i.name,vertexShader:E,fragmentShader:D,defines:i.defines,customVertexShaderID:O,customFragmentShaderID:k,isRawShaderMaterial:i.isRawShaderMaterial===!0,glslVersion:i.glslVersion,precision:f,batching:M,batchingColor:M&&h._colorsTexture!==null,instancing:ee,instancingColor:ee&&h.instanceColor!==null,instancingMorph:ee&&h.morphTexture!==null,outputColorSpace:A===null?e.outputColorSpace:A.isXRRenderTarget===!0?A.texture.colorSpace:Gt,alphaToCoverage:!!i.alphaToCoverage,map:N,matcap:P,envMap:F,envMapMode:F&&b.mapping,envMapCubeUVHeight:x,aoMap:te,lightMap:ne,bumpMap:re,normalMap:ie,displacementMap:ae,emissiveMap:oe,normalMapObjectSpace:ie&&i.normalMapType===1,normalMapTangentSpace:ie&&i.normalMapType===0,metalnessMap:se,roughnessMap:ce,anisotropy:le,anisotropyMap:he,clearcoat:ue,clearcoatMap:ge,clearcoatNormalMap:I,clearcoatRoughnessMap:_e,dispersion:de,iridescence:fe,iridescenceMap:ve,iridescenceThicknessMap:ye,sheen:pe,sheenColorMap:L,sheenRoughnessMap:R,specularMap:z,specularColorMap:be,specularIntensityMap:xe,transmission:me,transmissionMap:Se,thicknessMap:Ce,gradientMap:we,opaque:i.transparent===!1&&i.blending===1&&i.alphaToCoverage===!1,alphaMap:Te,alphaTest:Ee,alphaHash:De,combine:i.combine,mapUv:N&&m(i.map.channel),aoMapUv:te&&m(i.aoMap.channel),lightMapUv:ne&&m(i.lightMap.channel),bumpMapUv:re&&m(i.bumpMap.channel),normalMapUv:ie&&m(i.normalMap.channel),displacementMapUv:ae&&m(i.displacementMap.channel),emissiveMapUv:oe&&m(i.emissiveMap.channel),metalnessMapUv:se&&m(i.metalnessMap.channel),roughnessMapUv:ce&&m(i.roughnessMap.channel),anisotropyMapUv:he&&m(i.anisotropyMap.channel),clearcoatMapUv:ge&&m(i.clearcoatMap.channel),clearcoatNormalMapUv:I&&m(i.clearcoatNormalMap.channel),clearcoatRoughnessMapUv:_e&&m(i.clearcoatRoughnessMap.channel),iridescenceMapUv:ve&&m(i.iridescenceMap.channel),iridescenceThicknessMapUv:ye&&m(i.iridescenceThicknessMap.channel),sheenColorMapUv:L&&m(i.sheenColorMap.channel),sheenRoughnessMapUv:R&&m(i.sheenRoughnessMap.channel),specularMapUv:z&&m(i.specularMap.channel),specularColorMapUv:be&&m(i.specularColorMap.channel),specularIntensityMapUv:xe&&m(i.specularIntensityMap.channel),transmissionMapUv:Se&&m(i.transmissionMap.channel),thicknessMapUv:Ce&&m(i.thicknessMap.channel),alphaMapUv:Te&&m(i.alphaMap.channel),vertexTangents:!!_.attributes.tangent&&(ie||le),vertexColors:i.vertexColors,vertexAlphas:i.vertexColors===!0&&!!_.attributes.color&&_.attributes.color.itemSize===4,pointsUvs:h.isPoints===!0&&!!_.attributes.uv&&(N||Te),fog:!!g,useFog:i.fog===!0,fogExp2:!!g&&g.isFogExp2,flatShading:i.wireframe===!1&&(i.flatShading===!0||_.attributes.normal===void 0&&ie===!1&&(i.isMeshLambertMaterial||i.isMeshPhongMaterial||i.isMeshStandardMaterial||i.isMeshPhysicalMaterial)),sizeAttenuation:i.sizeAttenuation===!0,logarithmicDepthBuffer:d,reversedDepthBuffer:j,skinning:h.isSkinnedMesh===!0,morphTargets:_.morphAttributes.position!==void 0,morphNormals:_.morphAttributes.normal!==void 0,morphColors:_.morphAttributes.color!==void 0,morphTargetsCount:w,morphTextureStride:T,numDirLights:o.directional.length,numPointLights:o.point.length,numSpotLights:o.spot.length,numSpotLightMaps:o.spotLightMap.length,numRectAreaLights:o.rectArea.length,numHemiLights:o.hemi.length,numDirLightShadows:o.directionalShadowMap.length,numPointLightShadows:o.pointShadowMap.length,numSpotLightShadows:o.spotShadowMap.length,numSpotLightShadowsWithMaps:o.numSpotLightShadowsWithMaps,numLightProbes:o.numLightProbes,numClippingPlanes:a.numPlanes,numClipIntersection:a.numIntersection,dithering:i.dithering,shadowMapEnabled:e.shadowMap.enabled&&l.length>0,shadowMapType:e.shadowMap.type,toneMapping:ke,decodeVideoTexture:N&&i.map.isVideoTexture===!0&&gr.getTransfer(i.map.colorSpace)===`srgb`,decodeVideoTextureEmissive:oe&&i.emissiveMap.isVideoTexture===!0&&gr.getTransfer(i.emissiveMap.colorSpace)===`srgb`,premultipliedAlpha:i.premultipliedAlpha,doubleSided:i.side===2,flipSided:i.side===1,useDepthPacking:i.depthPacking>=0,depthPacking:i.depthPacking||0,index0AttributeName:i.index0AttributeName,extensionClipCullDistance:Oe&&i.extensions.clipCullDistance===!0&&n.has(`WEBGL_clip_cull_distance`),extensionMultiDraw:(Oe&&i.extensions.multiDraw===!0||M)&&n.has(`WEBGL_multi_draw`),rendererExtensionParallelShaderCompile:n.has(`KHR_parallel_shader_compile`),customProgramCacheKey:i.customProgramCacheKey()};return Ae.vertexUv1s=c.has(1),Ae.vertexUv2s=c.has(2),Ae.vertexUv3s=c.has(3),c.clear(),Ae}function g(t){let n=[];if(t.shaderID?n.push(t.shaderID):(n.push(t.customVertexShaderID),n.push(t.customFragmentShaderID)),t.defines!==void 0)for(let e in t.defines)n.push(e),n.push(t.defines[e]);return t.isRawShaderMaterial===!1&&(_(n,t),v(n,t),n.push(e.outputColorSpace)),n.push(t.customProgramCacheKey),n.join()}function _(e,t){e.push(t.precision),e.push(t.outputColorSpace),e.push(t.envMapMode),e.push(t.envMapCubeUVHeight),e.push(t.mapUv),e.push(t.alphaMapUv),e.push(t.lightMapUv),e.push(t.aoMapUv),e.push(t.bumpMapUv),e.push(t.normalMapUv),e.push(t.displacementMapUv),e.push(t.emissiveMapUv),e.push(t.metalnessMapUv),e.push(t.roughnessMapUv),e.push(t.anisotropyMapUv),e.push(t.clearcoatMapUv),e.push(t.clearcoatNormalMapUv),e.push(t.clearcoatRoughnessMapUv),e.push(t.iridescenceMapUv),e.push(t.iridescenceThicknessMapUv),e.push(t.sheenColorMapUv),e.push(t.sheenRoughnessMapUv),e.push(t.specularMapUv),e.push(t.specularColorMapUv),e.push(t.specularIntensityMapUv),e.push(t.transmissionMapUv),e.push(t.thicknessMapUv),e.push(t.combine),e.push(t.fogExp2),e.push(t.sizeAttenuation),e.push(t.morphTargetsCount),e.push(t.morphAttributeCount),e.push(t.numDirLights),e.push(t.numPointLights),e.push(t.numSpotLights),e.push(t.numSpotLightMaps),e.push(t.numHemiLights),e.push(t.numRectAreaLights),e.push(t.numDirLightShadows),e.push(t.numPointLightShadows),e.push(t.numSpotLightShadows),e.push(t.numSpotLightShadowsWithMaps),e.push(t.numLightProbes),e.push(t.shadowMapType),e.push(t.toneMapping),e.push(t.numClippingPlanes),e.push(t.numClipIntersection),e.push(t.depthPacking)}function v(e,t){o.disableAll(),t.instancing&&o.enable(0),t.instancingColor&&o.enable(1),t.instancingMorph&&o.enable(2),t.matcap&&o.enable(3),t.envMap&&o.enable(4),t.normalMapObjectSpace&&o.enable(5),t.normalMapTangentSpace&&o.enable(6),t.clearcoat&&o.enable(7),t.iridescence&&o.enable(8),t.alphaTest&&o.enable(9),t.vertexColors&&o.enable(10),t.vertexAlphas&&o.enable(11),t.vertexUv1s&&o.enable(12),t.vertexUv2s&&o.enable(13),t.vertexUv3s&&o.enable(14),t.vertexTangents&&o.enable(15),t.anisotropy&&o.enable(16),t.alphaHash&&o.enable(17),t.batching&&o.enable(18),t.dispersion&&o.enable(19),t.batchingColor&&o.enable(20),t.gradientMap&&o.enable(21),e.push(o.mask),o.disableAll(),t.fog&&o.enable(0),t.useFog&&o.enable(1),t.flatShading&&o.enable(2),t.logarithmicDepthBuffer&&o.enable(3),t.reversedDepthBuffer&&o.enable(4),t.skinning&&o.enable(5),t.morphTargets&&o.enable(6),t.morphNormals&&o.enable(7),t.morphColors&&o.enable(8),t.premultipliedAlpha&&o.enable(9),t.shadowMapEnabled&&o.enable(10),t.doubleSided&&o.enable(11),t.flipSided&&o.enable(12),t.useDepthPacking&&o.enable(13),t.dithering&&o.enable(14),t.transmission&&o.enable(15),t.sheen&&o.enable(16),t.opaque&&o.enable(17),t.pointsUvs&&o.enable(18),t.decodeVideoTexture&&o.enable(19),t.decodeVideoTextureEmissive&&o.enable(20),t.alphaToCoverage&&o.enable(21),e.push(o.mask)}function y(e){let t=p[e.type],n;if(t){let e=Cp[t];n=Vl.clone(e.uniforms)}else n=e.uniforms;return n}function b(t,n){let r=u.get(n);return r===void 0?(r=new Xh(e,n,t,i),l.push(r),u.set(n,r)):++r.usedTimes,r}function x(e){if(--e.usedTimes===0){let t=l.indexOf(e);l[t]=l[l.length-1],l.pop(),u.delete(e.cacheKey),e.destroy()}}function S(e){s.remove(e)}function C(){s.dispose()}return{getParameters:h,getProgramCacheKey:g,getUniforms:y,acquireProgram:b,releaseProgram:x,releaseShaderCache:S,programs:l,dispose:C}}function tg(){let e=new WeakMap;function t(t){return e.has(t)}function n(t){let n=e.get(t);return n===void 0&&(n={},e.set(t,n)),n}function r(t){e.delete(t)}function i(t,n,r){e.get(t)[n]=r}function a(){e=new WeakMap}return{has:t,get:n,remove:r,update:i,dispose:a}}function ng(e,t){return e.groupOrder===t.groupOrder?e.renderOrder===t.renderOrder?e.material.id===t.material.id?e.materialVariant===t.materialVariant?e.z===t.z?e.id-t.id:e.z-t.z:e.materialVariant-t.materialVariant:e.material.id-t.material.id:e.renderOrder-t.renderOrder:e.groupOrder-t.groupOrder}function rg(e,t){return e.groupOrder===t.groupOrder?e.renderOrder===t.renderOrder?e.z===t.z?e.id-t.id:t.z-e.z:e.renderOrder-t.renderOrder:e.groupOrder-t.groupOrder}function ig(){let e=[],t=0,n=[],r=[],i=[];function a(){t=0,n.length=0,r.length=0,i.length=0}function o(e){let t=0;return e.isInstancedMesh&&(t+=2),e.isSkinnedMesh&&(t+=1),t}function s(n,r,i,a,s,c){let l=e[t];return l===void 0?(l={id:n.id,object:n,geometry:r,material:i,materialVariant:o(n),groupOrder:a,renderOrder:n.renderOrder,z:s,group:c},e[t]=l):(l.id=n.id,l.object=n,l.geometry=r,l.material=i,l.materialVariant=o(n),l.groupOrder=a,l.renderOrder=n.renderOrder,l.z=s,l.group=c),t++,l}function c(e,t,a,o,c,l){let u=s(e,t,a,o,c,l);a.transmission>0?r.push(u):a.transparent===!0?i.push(u):n.push(u)}function l(e,t,a,o,c,l){let u=s(e,t,a,o,c,l);a.transmission>0?r.unshift(u):a.transparent===!0?i.unshift(u):n.unshift(u)}function u(e,t){n.length>1&&n.sort(e||ng),r.length>1&&r.sort(t||rg),i.length>1&&i.sort(t||rg)}function d(){for(let n=t,r=e.length;n=r.length?(i=new ig,r.push(i)):i=r[n],i}function n(){e=new WeakMap}return{get:t,dispose:n}}function og(){let e={};return{get:function(t){if(e[t.id]!==void 0)return e[t.id];let n;switch(t.type){case`DirectionalLight`:n={direction:new H,color:new U};break;case`SpotLight`:n={position:new H,direction:new H,color:new U,distance:0,coneCos:0,penumbraCos:0,decay:0};break;case`PointLight`:n={position:new H,color:new U,distance:0,decay:0};break;case`HemisphereLight`:n={direction:new H,skyColor:new U,groundColor:new U};break;case`RectAreaLight`:n={color:new U,position:new H,halfWidth:new H,halfHeight:new H};break}return e[t.id]=n,n}}}function sg(){let e={};return{get:function(t){if(e[t.id]!==void 0)return e[t.id];let n;switch(t.type){case`DirectionalLight`:n={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new V};break;case`SpotLight`:n={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new V};break;case`PointLight`:n={shadowIntensity:1,shadowBias:0,shadowNormalBias:0,shadowRadius:1,shadowMapSize:new V,shadowCameraNear:1,shadowCameraFar:1e3};break}return e[t.id]=n,n}}}var cg=0;function lg(e,t){return(t.castShadow?2:0)-(e.castShadow?2:0)+(t.map?1:0)-(e.map?1:0)}function ug(e){let t=new og,n=sg(),r={version:0,hash:{directionalLength:-1,pointLength:-1,spotLength:-1,rectAreaLength:-1,hemiLength:-1,numDirectionalShadows:-1,numPointShadows:-1,numSpotShadows:-1,numSpotMaps:-1,numLightProbes:-1},ambient:[0,0,0],probe:[],directional:[],directionalShadow:[],directionalShadowMap:[],directionalShadowMatrix:[],spot:[],spotLightMap:[],spotShadow:[],spotShadowMap:[],spotLightMatrix:[],rectArea:[],rectAreaLTC1:null,rectAreaLTC2:null,point:[],pointShadow:[],pointShadowMap:[],pointShadowMatrix:[],hemi:[],numSpotLightShadowsWithMaps:0,numLightProbes:0};for(let e=0;e<9;e++)r.probe.push(new H);let i=new H,a=new Pr,o=new Pr;function s(i){let a=0,o=0,s=0;for(let e=0;e<9;e++)r.probe[e].set(0,0,0);let c=0,l=0,u=0,d=0,f=0,p=0,m=0,h=0,g=0,_=0,v=0;i.sort(lg);for(let e=0,y=i.length;e0&&(e.has(`OES_texture_float_linear`)===!0?(r.rectAreaLTC1=J.LTC_FLOAT_1,r.rectAreaLTC2=J.LTC_FLOAT_2):(r.rectAreaLTC1=J.LTC_HALF_1,r.rectAreaLTC2=J.LTC_HALF_2)),r.ambient[0]=a,r.ambient[1]=o,r.ambient[2]=s;let y=r.hash;(y.directionalLength!==c||y.pointLength!==l||y.spotLength!==u||y.rectAreaLength!==d||y.hemiLength!==f||y.numDirectionalShadows!==p||y.numPointShadows!==m||y.numSpotShadows!==h||y.numSpotMaps!==g||y.numLightProbes!==v)&&(r.directional.length=c,r.spot.length=u,r.rectArea.length=d,r.point.length=l,r.hemi.length=f,r.directionalShadow.length=p,r.directionalShadowMap.length=p,r.pointShadow.length=m,r.pointShadowMap.length=m,r.spotShadow.length=h,r.spotShadowMap.length=h,r.directionalShadowMatrix.length=p,r.pointShadowMatrix.length=m,r.spotLightMatrix.length=h+g-_,r.spotLightMap.length=g,r.numSpotLightShadowsWithMaps=_,r.numLightProbes=v,y.directionalLength=c,y.pointLength=l,y.spotLength=u,y.rectAreaLength=d,y.hemiLength=f,y.numDirectionalShadows=p,y.numPointShadows=m,y.numSpotShadows=h,y.numSpotMaps=g,y.numLightProbes=v,r.version=cg++)}function c(e,t){let n=0,s=0,c=0,l=0,u=0,d=t.matrixWorldInverse;for(let t=0,f=e.length;t=i.length?(a=new dg(e),i.push(a)):a=i[r],a}function r(){t=new WeakMap}return{get:n,dispose:r}}var pg=`void main() { + gl_Position = vec4( position, 1.0 ); +}`,mg=`uniform sampler2D shadow_pass; +uniform vec2 resolution; +uniform float radius; +void main() { + const float samples = float( VSM_SAMPLES ); + float mean = 0.0; + float squared_mean = 0.0; + float uvStride = samples <= 1.0 ? 0.0 : 2.0 / ( samples - 1.0 ); + float uvStart = samples <= 1.0 ? 0.0 : - 1.0; + for ( float i = 0.0; i < samples; i ++ ) { + float uvOffset = uvStart + i * uvStride; + #ifdef HORIZONTAL_PASS + vec2 distribution = texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( uvOffset, 0.0 ) * radius ) / resolution ).rg; + mean += distribution.x; + squared_mean += distribution.y * distribution.y + distribution.x * distribution.x; + #else + float depth = texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( 0.0, uvOffset ) * radius ) / resolution ).r; + mean += depth; + squared_mean += depth * depth; + #endif + } + mean = mean / samples; + squared_mean = squared_mean / samples; + float std_dev = sqrt( max( 0.0, squared_mean - mean * mean ) ); + gl_FragColor = vec4( mean, std_dev, 0.0, 1.0 ); +}`,hg=[new H(1,0,0),new H(-1,0,0),new H(0,1,0),new H(0,-1,0),new H(0,0,1),new H(0,0,-1)],gg=[new H(0,-1,0),new H(0,-1,0),new H(0,0,1),new H(0,0,-1),new H(0,-1,0),new H(0,-1,0)],_g=new Pr,vg=new H,yg=new H;function bg(e,t,n){let r=new Ko,i=new V,a=new V,o=new Dr,s=new Zl,c=new Ql,l={},u=n.maxTextureSize,d={0:1,1:0,2:2},f=new q({defines:{VSM_SAMPLES:8},uniforms:{shadow_pass:{value:null},resolution:{value:new V},radius:{value:4}},vertexShader:pg,fragmentShader:mg}),p=f.clone();p.defines.HORIZONTAL_PASS=1;let m=new ba;m.setAttribute(`position`,new ea(new Float32Array([-1,-1,.5,3,-1,.5,-1,3,.5]),3));let h=new fo(m,f),g=this;this.enabled=!1,this.autoUpdate=!0,this.needsUpdate=!1,this.type=1;let _=this.type;this.render=function(t,n,s){if(g.enabled===!1||g.autoUpdate===!1&&g.needsUpdate===!1||t.length===0)return;this.type===2&&(B(`WebGLShadowMap: PCFSoftShadowMap has been deprecated. Using PCFShadowMap instead.`),this.type=1);let c=e.getRenderTarget(),l=e.getActiveCubeFace(),d=e.getActiveMipmapLevel(),f=e.state;f.setBlending(0),f.buffers.depth.getReversed()===!0?f.buffers.color.setClear(0,0,0,0):f.buffers.color.setClear(1,1,1,1),f.buffers.depth.setTest(!0),f.setScissorTest(!1);let p=_!==this.type;p&&n.traverse(function(e){e.material&&(Array.isArray(e.material)?e.material.forEach(e=>e.needsUpdate=!0):e.material.needsUpdate=!0)});for(let c=0,l=t.length;cu||i.y>u)&&(i.x>u&&(a.x=Math.floor(u/m.x),i.x=a.x*m.x,d.mapSize.x=a.x),i.y>u&&(a.y=Math.floor(u/m.y),i.y=a.y*m.y,d.mapSize.y=a.y));let h=e.state.buffers.depth.getReversed();if(d.camera._reversedDepth=h,d.map===null||p===!0){if(d.map!==null&&(d.map.depthTexture!==null&&(d.map.depthTexture.dispose(),d.map.depthTexture=null),d.map.dispose()),this.type===3){if(l.isPointLight){B(`WebGLShadowMap: VSM shadow maps are not supported for PointLights. Use PCF or BasicShadowMap instead.`);continue}d.map=new kr(i.x,i.y,{format:He,type:ke,minFilter:L,magFilter:L,generateMipmaps:!1}),d.map.texture.name=l.name+`.shadowMap`,d.map.depthTexture=new Ws(i.x,i.y,Oe),d.map.depthTexture.name=l.name+`.shadowMapDepth`,d.map.depthTexture.format=Re,d.map.depthTexture.compareFunction=null,d.map.depthTexture.minFilter=ge,d.map.depthTexture.magFilter=ge}else l.isPointLight?(d.map=new Qp(i.x),d.map.depthTexture=new Gs(i.x,De)):(d.map=new kr(i.x,i.y),d.map.depthTexture=new Ws(i.x,i.y,De)),d.map.depthTexture.name=l.name+`.shadowMap`,d.map.depthTexture.format=Re,this.type===1?(d.map.depthTexture.compareFunction=h?518:515,d.map.depthTexture.minFilter=L,d.map.depthTexture.magFilter=L):(d.map.depthTexture.compareFunction=null,d.map.depthTexture.minFilter=ge,d.map.depthTexture.magFilter=ge);d.camera.updateProjectionMatrix()}let g=d.map.isWebGLCubeRenderTarget?6:1;for(let t=0;t0||n.map&&n.alphaTest>0||n.alphaToCoverage===!0){let e=a.uuid,t=n.uuid,r=l[e];r===void 0&&(r={},l[e]=r);let i=r[t];i===void 0&&(i=a.clone(),r[t]=i,n.addEventListener(`dispose`,x)),a=i}if(a.visible=n.visible,a.wireframe=n.wireframe,i===3?a.side=n.shadowSide===null?n.side:n.shadowSide:a.side=n.shadowSide===null?d[n.side]:n.shadowSide,a.alphaMap=n.alphaMap,a.alphaTest=n.alphaToCoverage===!0?.5:n.alphaTest,a.map=n.map,a.clipShadows=n.clipShadows,a.clippingPlanes=n.clippingPlanes,a.clipIntersection=n.clipIntersection,a.displacementMap=n.displacementMap,a.displacementScale=n.displacementScale,a.displacementBias=n.displacementBias,a.wireframeLinewidth=n.wireframeLinewidth,a.linewidth=n.linewidth,r.isPointLight===!0&&a.isMeshDistanceMaterial===!0){let t=e.properties.get(a);t.light=r}return a}function b(n,i,a,o,s){if(n.visible===!1)return;if(n.layers.test(i.layers)&&(n.isMesh||n.isLine||n.isPoints)&&(n.castShadow||n.receiveShadow&&s===3)&&(!n.frustumCulled||r.intersectsObject(n))){n.modelViewMatrix.multiplyMatrices(a.matrixWorldInverse,n.matrixWorld);let r=t.update(n),c=n.material;if(Array.isArray(c)){let t=r.groups;for(let l=0,u=t.length;l=2):(M=parseFloat(/^WebGL (\d)/.exec(N)[1]),ee=M>=1);let P=null,F={},te=e.getParameter(e.SCISSOR_BOX),ne=e.getParameter(e.VIEWPORT),re=new Dr().fromArray(te),ie=new Dr().fromArray(ne);function ae(t,n,r,i){let a=new Uint8Array(4),o=e.createTexture();e.bindTexture(t,o),e.texParameteri(t,e.TEXTURE_MIN_FILTER,e.NEAREST),e.texParameteri(t,e.TEXTURE_MAG_FILTER,e.NEAREST);for(let o=0;o`u`?!1:/OculusBrowser/g.test(navigator.userAgent),l=new V,u=new WeakMap,d,f=new WeakMap,p=!1;try{p=typeof OffscreenCanvas<`u`&&new OffscreenCanvas(1,1).getContext(`2d`)!==null}catch{}function m(e,t){return p?new OffscreenCanvas(e,t):Sn(`canvas`)}function h(e,t,n){let r=1,i=De(e);if((i.width>n||i.height>n)&&(r=n/Math.max(i.width,i.height)),r<1)if(typeof HTMLImageElement<`u`&&e instanceof HTMLImageElement||typeof HTMLCanvasElement<`u`&&e instanceof HTMLCanvasElement||typeof ImageBitmap<`u`&&e instanceof ImageBitmap||typeof VideoFrame<`u`&&e instanceof VideoFrame){let n=Math.floor(r*i.width),a=Math.floor(r*i.height);d===void 0&&(d=m(n,a));let o=t?m(n,a):d;return o.width=n,o.height=a,o.getContext(`2d`).drawImage(e,0,0,n,a),B(`WebGLRenderer: Texture has been resized from (`+i.width+`x`+i.height+`) to (`+n+`x`+a+`).`),o}else return`data`in e&&B(`WebGLRenderer: Image in DataTexture is too big (`+i.width+`x`+i.height+`).`),e;return e}function g(e){return e.generateMipmaps}function _(t){e.generateMipmap(t)}function v(t){return t.isWebGLCubeRenderTarget?e.TEXTURE_CUBE_MAP:t.isWebGL3DRenderTarget?e.TEXTURE_3D:t.isWebGLArrayRenderTarget||t.isCompressedArrayTexture?e.TEXTURE_2D_ARRAY:e.TEXTURE_2D}function y(n,r,i,a,o=!1){if(n!==null){if(e[n]!==void 0)return e[n];B(`WebGLRenderer: Attempt to use non-existing WebGL internal format '`+n+`'`)}let s=r;if(r===e.RED&&(i===e.FLOAT&&(s=e.R32F),i===e.HALF_FLOAT&&(s=e.R16F),i===e.UNSIGNED_BYTE&&(s=e.R8)),r===e.RED_INTEGER&&(i===e.UNSIGNED_BYTE&&(s=e.R8UI),i===e.UNSIGNED_SHORT&&(s=e.R16UI),i===e.UNSIGNED_INT&&(s=e.R32UI),i===e.BYTE&&(s=e.R8I),i===e.SHORT&&(s=e.R16I),i===e.INT&&(s=e.R32I)),r===e.RG&&(i===e.FLOAT&&(s=e.RG32F),i===e.HALF_FLOAT&&(s=e.RG16F),i===e.UNSIGNED_BYTE&&(s=e.RG8)),r===e.RG_INTEGER&&(i===e.UNSIGNED_BYTE&&(s=e.RG8UI),i===e.UNSIGNED_SHORT&&(s=e.RG16UI),i===e.UNSIGNED_INT&&(s=e.RG32UI),i===e.BYTE&&(s=e.RG8I),i===e.SHORT&&(s=e.RG16I),i===e.INT&&(s=e.RG32I)),r===e.RGB_INTEGER&&(i===e.UNSIGNED_BYTE&&(s=e.RGB8UI),i===e.UNSIGNED_SHORT&&(s=e.RGB16UI),i===e.UNSIGNED_INT&&(s=e.RGB32UI),i===e.BYTE&&(s=e.RGB8I),i===e.SHORT&&(s=e.RGB16I),i===e.INT&&(s=e.RGB32I)),r===e.RGBA_INTEGER&&(i===e.UNSIGNED_BYTE&&(s=e.RGBA8UI),i===e.UNSIGNED_SHORT&&(s=e.RGBA16UI),i===e.UNSIGNED_INT&&(s=e.RGBA32UI),i===e.BYTE&&(s=e.RGBA8I),i===e.SHORT&&(s=e.RGBA16I),i===e.INT&&(s=e.RGBA32I)),r===e.RGB&&(i===e.UNSIGNED_INT_5_9_9_9_REV&&(s=e.RGB9_E5),i===e.UNSIGNED_INT_10F_11F_11F_REV&&(s=e.R11F_G11F_B10F)),r===e.RGBA){let t=o?Kt:gr.getTransfer(a);i===e.FLOAT&&(s=e.RGBA32F),i===e.HALF_FLOAT&&(s=e.RGBA16F),i===e.UNSIGNED_BYTE&&(s=t===`srgb`?e.SRGB8_ALPHA8:e.RGBA8),i===e.UNSIGNED_SHORT_4_4_4_4&&(s=e.RGBA4),i===e.UNSIGNED_SHORT_5_5_5_1&&(s=e.RGB5_A1)}return(s===e.R16F||s===e.R32F||s===e.RG16F||s===e.RG32F||s===e.RGBA16F||s===e.RGBA32F)&&t.get(`EXT_color_buffer_float`),s}function b(t,n){let r;return t?n===null||n===1014||n===1020?r=e.DEPTH24_STENCIL8:n===1015?r=e.DEPTH32F_STENCIL8:n===1012&&(r=e.DEPTH24_STENCIL8,B(`DepthTexture: 16 bit depth attachment is not supported with stencil. Using 24-bit attachment.`)):n===null||n===1014||n===1020?r=e.DEPTH_COMPONENT24:n===1015?r=e.DEPTH_COMPONENT32F:n===1012&&(r=e.DEPTH_COMPONENT16),r}function x(e,t){return g(e)===!0||e.isFramebufferTexture&&e.minFilter!==1003&&e.minFilter!==1006?Math.log2(Math.max(t.width,t.height))+1:e.mipmaps!==void 0&&e.mipmaps.length>0?e.mipmaps.length:e.isCompressedTexture&&Array.isArray(e.image)?t.mipmaps.length:1}function S(e){let t=e.target;t.removeEventListener(`dispose`,S),w(t),t.isVideoTexture&&u.delete(t)}function C(e){let t=e.target;t.removeEventListener(`dispose`,C),E(t)}function w(e){let t=r.get(e);if(t.__webglInit===void 0)return;let n=e.source,i=f.get(n);if(i){let r=i[t.__cacheKey];r.usedTimes--,r.usedTimes===0&&T(e),Object.keys(i).length===0&&f.delete(n)}r.remove(e)}function T(t){let n=r.get(t);e.deleteTexture(n.__webglTexture);let i=t.source,a=f.get(i);delete a[n.__cacheKey],o.memory.textures--}function E(t){let n=r.get(t);if(t.depthTexture&&(t.depthTexture.dispose(),r.remove(t.depthTexture)),t.isWebGLCubeRenderTarget)for(let t=0;t<6;t++){if(Array.isArray(n.__webglFramebuffer[t]))for(let r=0;r=i.maxTextures&&B(`WebGLTextures: Trying to use `+e+` texture units while this GPU supports only `+i.maxTextures),D+=1,e}function A(e){let t=[];return t.push(e.wrapS),t.push(e.wrapT),t.push(e.wrapR||0),t.push(e.magFilter),t.push(e.minFilter),t.push(e.anisotropy),t.push(e.internalFormat),t.push(e.format),t.push(e.type),t.push(e.generateMipmaps),t.push(e.premultiplyAlpha),t.push(e.flipY),t.push(e.unpackAlignment),t.push(e.colorSpace),t.join()}function j(t,i){let a=r.get(t);if(t.isVideoTexture&&Te(t),t.isRenderTargetTexture===!1&&t.isExternalTexture!==!0&&t.version>0&&a.__version!==t.version){let e=t.image;if(e===null)B(`WebGLRenderer: Texture marked for update but no image data found.`);else if(e.complete===!1)B(`WebGLRenderer: Texture marked for update but image is incomplete`);else{oe(a,t,i);return}}else t.isExternalTexture&&(a.__webglTexture=t.sourceTexture?t.sourceTexture:null);n.bindTexture(e.TEXTURE_2D,a.__webglTexture,e.TEXTURE0+i)}function ee(t,i){let a=r.get(t);if(t.isRenderTargetTexture===!1&&t.version>0&&a.__version!==t.version){oe(a,t,i);return}else t.isExternalTexture&&(a.__webglTexture=t.sourceTexture?t.sourceTexture:null);n.bindTexture(e.TEXTURE_2D_ARRAY,a.__webglTexture,e.TEXTURE0+i)}function M(t,i){let a=r.get(t);if(t.isRenderTargetTexture===!1&&t.version>0&&a.__version!==t.version){oe(a,t,i);return}n.bindTexture(e.TEXTURE_3D,a.__webglTexture,e.TEXTURE0+i)}function N(t,i){let a=r.get(t);if(t.isCubeDepthTexture!==!0&&t.version>0&&a.__version!==t.version){se(a,t,i);return}n.bindTexture(e.TEXTURE_CUBE_MAP,a.__webglTexture,e.TEXTURE0+i)}let P={[pe]:e.REPEAT,[me]:e.CLAMP_TO_EDGE,[he]:e.MIRRORED_REPEAT},F={[ge]:e.NEAREST,[I]:e.NEAREST_MIPMAP_NEAREST,[ve]:e.NEAREST_MIPMAP_LINEAR,[L]:e.LINEAR,[R]:e.LINEAR_MIPMAP_NEAREST,[be]:e.LINEAR_MIPMAP_LINEAR},te={512:e.NEVER,519:e.ALWAYS,513:e.LESS,515:e.LEQUAL,514:e.EQUAL,518:e.GEQUAL,516:e.GREATER,517:e.NOTEQUAL};function ne(n,a){if(a.type===1015&&t.has(`OES_texture_float_linear`)===!1&&(a.magFilter===1006||a.magFilter===1007||a.magFilter===1005||a.magFilter===1008||a.minFilter===1006||a.minFilter===1007||a.minFilter===1005||a.minFilter===1008)&&B(`WebGLRenderer: Unable to use linear filtering with floating point textures. OES_texture_float_linear not supported on this device.`),e.texParameteri(n,e.TEXTURE_WRAP_S,P[a.wrapS]),e.texParameteri(n,e.TEXTURE_WRAP_T,P[a.wrapT]),(n===e.TEXTURE_3D||n===e.TEXTURE_2D_ARRAY)&&e.texParameteri(n,e.TEXTURE_WRAP_R,P[a.wrapR]),e.texParameteri(n,e.TEXTURE_MAG_FILTER,F[a.magFilter]),e.texParameteri(n,e.TEXTURE_MIN_FILTER,F[a.minFilter]),a.compareFunction&&(e.texParameteri(n,e.TEXTURE_COMPARE_MODE,e.COMPARE_REF_TO_TEXTURE),e.texParameteri(n,e.TEXTURE_COMPARE_FUNC,te[a.compareFunction])),t.has(`EXT_texture_filter_anisotropic`)===!0){if(a.magFilter===1003||a.minFilter!==1005&&a.minFilter!==1008||a.type===1015&&t.has(`OES_texture_float_linear`)===!1)return;if(a.anisotropy>1||r.get(a).__currentAnisotropy){let o=t.get(`EXT_texture_filter_anisotropic`);e.texParameterf(n,o.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(a.anisotropy,i.getMaxAnisotropy())),r.get(a).__currentAnisotropy=a.anisotropy}}}function re(t,n){let r=!1;t.__webglInit===void 0&&(t.__webglInit=!0,n.addEventListener(`dispose`,S));let i=n.source,a=f.get(i);a===void 0&&(a={},f.set(i,a));let s=A(n);if(s!==t.__cacheKey){a[s]===void 0&&(a[s]={texture:e.createTexture(),usedTimes:0},o.memory.textures++,r=!0),a[s].usedTimes++;let i=a[t.__cacheKey];i!==void 0&&(a[t.__cacheKey].usedTimes--,i.usedTimes===0&&T(n)),t.__cacheKey=s,t.__webglTexture=a[s].texture}return r}function ie(e,t,n){return Math.floor(Math.floor(e/n)/t)}function ae(t,r,i,a){let o=t.updateRanges;if(o.length===0)n.texSubImage2D(e.TEXTURE_2D,0,0,0,r.width,r.height,i,a,r.data);else{o.sort((e,t)=>e.start-t.start);let s=0;for(let e=1;e0){T&&E&&n.texStorage2D(e.TEXTURE_2D,O,S,w[0].width,w[0].height);for(let t=0,r=w.length;t0){let r=gp(C.width,C.height,o.format,o.type);for(let i of o.layerUpdates){let a=C.data.subarray(i*r/C.data.BYTES_PER_ELEMENT,(i+1)*r/C.data.BYTES_PER_ELEMENT);n.compressedTexSubImage3D(e.TEXTURE_2D_ARRAY,t,0,0,i,C.width,C.height,1,m,a)}o.clearLayerUpdates()}else n.compressedTexSubImage3D(e.TEXTURE_2D_ARRAY,t,0,0,0,C.width,C.height,p.depth,m,C.data)}else n.compressedTexImage3D(e.TEXTURE_2D_ARRAY,t,S,C.width,C.height,p.depth,0,C.data,0,0);else B(`WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()`);else T?D&&n.texSubImage3D(e.TEXTURE_2D_ARRAY,t,0,0,0,C.width,C.height,p.depth,m,v,C.data):n.texImage3D(e.TEXTURE_2D_ARRAY,t,S,C.width,C.height,p.depth,0,m,v,C.data)}else{T&&E&&n.texStorage2D(e.TEXTURE_2D,O,S,w[0].width,w[0].height);for(let t=0,r=w.length;t0){let t=gp(p.width,p.height,o.format,o.type);for(let r of o.layerUpdates){let i=p.data.subarray(r*t/p.data.BYTES_PER_ELEMENT,(r+1)*t/p.data.BYTES_PER_ELEMENT);n.texSubImage3D(e.TEXTURE_2D_ARRAY,0,0,0,r,p.width,p.height,1,m,v,i)}o.clearLayerUpdates()}else n.texSubImage3D(e.TEXTURE_2D_ARRAY,0,0,0,0,p.width,p.height,p.depth,m,v,p.data)}else n.texImage3D(e.TEXTURE_2D_ARRAY,0,S,p.width,p.height,p.depth,0,m,v,p.data);else if(o.isData3DTexture)T?(E&&n.texStorage3D(e.TEXTURE_3D,O,S,p.width,p.height,p.depth),D&&n.texSubImage3D(e.TEXTURE_3D,0,0,0,0,p.width,p.height,p.depth,m,v,p.data)):n.texImage3D(e.TEXTURE_3D,0,S,p.width,p.height,p.depth,0,m,v,p.data);else if(o.isFramebufferTexture){if(E)if(T)n.texStorage2D(e.TEXTURE_2D,O,S,p.width,p.height);else{let t=p.width,r=p.height;for(let i=0;i>=1,r>>=1}}else if(w.length>0){if(T&&E){let t=De(w[0]);n.texStorage2D(e.TEXTURE_2D,O,S,t.width,t.height)}for(let t=0,r=w.length;t0&&D++;let t=De(m[0]);n.texStorage2D(e.TEXTURE_CUBE_MAP,D,C,t.width,t.height)}for(let t=0;t<6;t++)if(p){w?E&&n.texSubImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,0,0,m[t].width,m[t].height,b,S,m[t].data):n.texImage2D(e.TEXTURE_CUBE_MAP_POSITIVE_X+t,0,C,m[t].width,m[t].height,0,b,S,m[t].data);for(let r=0;r>u),r=Math.max(1,i.height>>u);l===e.TEXTURE_3D||l===e.TEXTURE_2D_ARRAY?n.texImage3D(l,u,p,t,r,i.depth,0,d,f,null):n.texImage2D(l,u,p,t,r,0,d,f,null)}n.bindFramebuffer(e.FRAMEBUFFER,t),we(i)?s.framebufferTexture2DMultisampleEXT(e.FRAMEBUFFER,c,l,h.__webglTexture,0,Ce(i)):(l===e.TEXTURE_2D||l>=e.TEXTURE_CUBE_MAP_POSITIVE_X&&l<=e.TEXTURE_CUBE_MAP_NEGATIVE_Z)&&e.framebufferTexture2D(e.FRAMEBUFFER,c,l,h.__webglTexture,u),n.bindFramebuffer(e.FRAMEBUFFER,null)}function le(t,n,r){if(e.bindRenderbuffer(e.RENDERBUFFER,t),n.depthBuffer){let i=n.depthTexture,a=i&&i.isDepthTexture?i.type:null,o=b(n.stencilBuffer,a),c=n.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT;we(n)?s.renderbufferStorageMultisampleEXT(e.RENDERBUFFER,Ce(n),o,n.width,n.height):r?e.renderbufferStorageMultisample(e.RENDERBUFFER,Ce(n),o,n.width,n.height):e.renderbufferStorage(e.RENDERBUFFER,o,n.width,n.height),e.framebufferRenderbuffer(e.FRAMEBUFFER,c,e.RENDERBUFFER,t)}else{let t=n.textures;for(let i=0;i{delete i.__boundDepthTexture,delete i.__depthDisposeCallback,e.removeEventListener(`dispose`,t)};e.addEventListener(`dispose`,t),i.__depthDisposeCallback=t}i.__boundDepthTexture=e}if(t.depthTexture&&!i.__autoAllocateDepthBuffer)if(a)for(let e=0;e<6;e++)ue(i.__webglFramebuffer[e],t,e);else{let e=t.texture.mipmaps;e&&e.length>0?ue(i.__webglFramebuffer[0],t,0):ue(i.__webglFramebuffer,t,0)}else if(a){i.__webglDepthbuffer=[];for(let r=0;r<6;r++)if(n.bindFramebuffer(e.FRAMEBUFFER,i.__webglFramebuffer[r]),i.__webglDepthbuffer[r]===void 0)i.__webglDepthbuffer[r]=e.createRenderbuffer(),le(i.__webglDepthbuffer[r],t,!1);else{let n=t.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT,a=i.__webglDepthbuffer[r];e.bindRenderbuffer(e.RENDERBUFFER,a),e.framebufferRenderbuffer(e.FRAMEBUFFER,n,e.RENDERBUFFER,a)}}else{let r=t.texture.mipmaps;if(r&&r.length>0?n.bindFramebuffer(e.FRAMEBUFFER,i.__webglFramebuffer[0]):n.bindFramebuffer(e.FRAMEBUFFER,i.__webglFramebuffer),i.__webglDepthbuffer===void 0)i.__webglDepthbuffer=e.createRenderbuffer(),le(i.__webglDepthbuffer,t,!1);else{let n=t.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT,r=i.__webglDepthbuffer;e.bindRenderbuffer(e.RENDERBUFFER,r),e.framebufferRenderbuffer(e.FRAMEBUFFER,n,e.RENDERBUFFER,r)}}n.bindFramebuffer(e.FRAMEBUFFER,null)}function fe(t,n,i){let a=r.get(t);n!==void 0&&ce(a.__webglFramebuffer,t,t.texture,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,0),i!==void 0&&de(t)}function _e(t){let i=t.texture,s=r.get(t),c=r.get(i);t.addEventListener(`dispose`,C);let l=t.textures,u=t.isWebGLCubeRenderTarget===!0,d=l.length>1;if(d||(c.__webglTexture===void 0&&(c.__webglTexture=e.createTexture()),c.__version=i.version,o.memory.textures++),u){s.__webglFramebuffer=[];for(let t=0;t<6;t++)if(i.mipmaps&&i.mipmaps.length>0){s.__webglFramebuffer[t]=[];for(let n=0;n0){s.__webglFramebuffer=[];for(let t=0;t0&&we(t)===!1){s.__webglMultisampledFramebuffer=e.createFramebuffer(),s.__webglColorRenderbuffer=[],n.bindFramebuffer(e.FRAMEBUFFER,s.__webglMultisampledFramebuffer);for(let n=0;n0)for(let r=0;r0)for(let n=0;n0){if(we(t)===!1){let i=t.textures,a=t.width,o=t.height,s=e.COLOR_BUFFER_BIT,l=t.stencilBuffer?e.DEPTH_STENCIL_ATTACHMENT:e.DEPTH_ATTACHMENT,u=r.get(t),d=i.length>1;if(d)for(let t=0;t0?n.bindFramebuffer(e.DRAW_FRAMEBUFFER,u.__webglFramebuffer[0]):n.bindFramebuffer(e.DRAW_FRAMEBUFFER,u.__webglFramebuffer);for(let n=0;n0&&t.has(`WEBGL_multisampled_render_to_texture`)===!0&&n.__useRenderToTexture!==!1}function Te(e){let t=o.render.frame;u.get(e)!==t&&(u.set(e,t),e.update())}function Ee(e,t){let n=e.colorSpace,r=e.format,i=e.type;return e.isCompressedTexture===!0||e.isVideoTexture===!0||n!==`srgb-linear`&&n!==``&&(gr.getTransfer(n)===`srgb`?(r!==1023||i!==1009)&&B(`WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType.`):An(`WebGLTextures: Unsupported texture color space:`,n)),t}function De(e){return typeof HTMLImageElement<`u`&&e instanceof HTMLImageElement?(l.width=e.naturalWidth||e.width,l.height=e.naturalHeight||e.height):typeof VideoFrame<`u`&&e instanceof VideoFrame?(l.width=e.displayWidth,l.height=e.displayHeight):(l.width=e.width,l.height=e.height),l}this.allocateTextureUnit=k,this.resetTextureUnits=O,this.setTexture2D=j,this.setTexture2DArray=ee,this.setTexture3D=M,this.setTextureCube=N,this.rebindTextures=fe,this.setupRenderTarget=_e,this.updateRenderTargetMipmap=ye,this.updateMultisampleRenderTarget=Se,this.setupDepthRenderbuffer=de,this.setupFrameBufferTexture=ce,this.useMultisampledRTT=we,this.isReversedDepthBuffer=function(){return n.buffers.depth.getReversed()}}function Cg(e,t){function n(n,r=``){let i,a=gr.getTransfer(r);if(n===1009)return e.UNSIGNED_BYTE;if(n===1017)return e.UNSIGNED_SHORT_4_4_4_4;if(n===1018)return e.UNSIGNED_SHORT_5_5_5_1;if(n===35902)return e.UNSIGNED_INT_5_9_9_9_REV;if(n===35899)return e.UNSIGNED_INT_10F_11F_11F_REV;if(n===1010)return e.BYTE;if(n===1011)return e.SHORT;if(n===1012)return e.UNSIGNED_SHORT;if(n===1013)return e.INT;if(n===1014)return e.UNSIGNED_INT;if(n===1015)return e.FLOAT;if(n===1016)return e.HALF_FLOAT;if(n===1021)return e.ALPHA;if(n===1022)return e.RGB;if(n===1023)return e.RGBA;if(n===1026)return e.DEPTH_COMPONENT;if(n===1027)return e.DEPTH_STENCIL;if(n===1028)return e.RED;if(n===1029)return e.RED_INTEGER;if(n===1030)return e.RG;if(n===1031)return e.RG_INTEGER;if(n===1033)return e.RGBA_INTEGER;if(n===33776||n===33777||n===33778||n===33779)if(a===`srgb`)if(i=t.get(`WEBGL_compressed_texture_s3tc_srgb`),i!==null){if(n===33776)return i.COMPRESSED_SRGB_S3TC_DXT1_EXT;if(n===33777)return i.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;if(n===33778)return i.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;if(n===33779)return i.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}else return null;else if(i=t.get(`WEBGL_compressed_texture_s3tc`),i!==null){if(n===33776)return i.COMPRESSED_RGB_S3TC_DXT1_EXT;if(n===33777)return i.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(n===33778)return i.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(n===33779)return i.COMPRESSED_RGBA_S3TC_DXT5_EXT}else return null;if(n===35840||n===35841||n===35842||n===35843)if(i=t.get(`WEBGL_compressed_texture_pvrtc`),i!==null){if(n===35840)return i.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(n===35841)return i.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(n===35842)return i.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(n===35843)return i.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}else return null;if(n===36196||n===37492||n===37496||n===37488||n===37489||n===37490||n===37491)if(i=t.get(`WEBGL_compressed_texture_etc`),i!==null){if(n===36196||n===37492)return a===`srgb`?i.COMPRESSED_SRGB8_ETC2:i.COMPRESSED_RGB8_ETC2;if(n===37496)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:i.COMPRESSED_RGBA8_ETC2_EAC;if(n===37488)return i.COMPRESSED_R11_EAC;if(n===37489)return i.COMPRESSED_SIGNED_R11_EAC;if(n===37490)return i.COMPRESSED_RG11_EAC;if(n===37491)return i.COMPRESSED_SIGNED_RG11_EAC}else return null;if(n===37808||n===37809||n===37810||n===37811||n===37812||n===37813||n===37814||n===37815||n===37816||n===37817||n===37818||n===37819||n===37820||n===37821)if(i=t.get(`WEBGL_compressed_texture_astc`),i!==null){if(n===37808)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:i.COMPRESSED_RGBA_ASTC_4x4_KHR;if(n===37809)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:i.COMPRESSED_RGBA_ASTC_5x4_KHR;if(n===37810)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:i.COMPRESSED_RGBA_ASTC_5x5_KHR;if(n===37811)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:i.COMPRESSED_RGBA_ASTC_6x5_KHR;if(n===37812)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:i.COMPRESSED_RGBA_ASTC_6x6_KHR;if(n===37813)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:i.COMPRESSED_RGBA_ASTC_8x5_KHR;if(n===37814)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:i.COMPRESSED_RGBA_ASTC_8x6_KHR;if(n===37815)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:i.COMPRESSED_RGBA_ASTC_8x8_KHR;if(n===37816)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:i.COMPRESSED_RGBA_ASTC_10x5_KHR;if(n===37817)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:i.COMPRESSED_RGBA_ASTC_10x6_KHR;if(n===37818)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:i.COMPRESSED_RGBA_ASTC_10x8_KHR;if(n===37819)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:i.COMPRESSED_RGBA_ASTC_10x10_KHR;if(n===37820)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:i.COMPRESSED_RGBA_ASTC_12x10_KHR;if(n===37821)return a===`srgb`?i.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:i.COMPRESSED_RGBA_ASTC_12x12_KHR}else return null;if(n===36492||n===36494||n===36495)if(i=t.get(`EXT_texture_compression_bptc`),i!==null){if(n===36492)return a===`srgb`?i.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT:i.COMPRESSED_RGBA_BPTC_UNORM_EXT;if(n===36494)return i.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT;if(n===36495)return i.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT}else return null;if(n===36283||n===36284||n===36285||n===36286)if(i=t.get(`EXT_texture_compression_rgtc`),i!==null){if(n===36283)return i.COMPRESSED_RED_RGTC1_EXT;if(n===36284)return i.COMPRESSED_SIGNED_RED_RGTC1_EXT;if(n===36285)return i.COMPRESSED_RED_GREEN_RGTC2_EXT;if(n===36286)return i.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT}else return null;return n===1020?e.UNSIGNED_INT_24_8:e[n]===void 0?null:e[n]}return{convert:n}}var wg=` +void main() { + + gl_Position = vec4( position, 1.0 ); + +}`,Tg=` +uniform sampler2DArray depthColor; +uniform float depthWidth; +uniform float depthHeight; + +void main() { + + vec2 coord = vec2( gl_FragCoord.x / depthWidth, gl_FragCoord.y / depthHeight ); + + if ( coord.x >= 1.0 ) { + + gl_FragDepth = texture( depthColor, vec3( coord.x - 1.0, coord.y, 1 ) ).r; + + } else { + + gl_FragDepth = texture( depthColor, vec3( coord.x, coord.y, 0 ) ).r; + + } + +}`,Eg=class{constructor(){this.texture=null,this.mesh=null,this.depthNear=0,this.depthFar=0}init(e,t){if(this.texture===null){let n=new Ks(e.texture);(e.depthNear!==t.depthNear||e.depthFar!==t.depthFar)&&(this.depthNear=e.depthNear,this.depthFar=e.depthFar),this.texture=n}}getMesh(e){if(this.texture!==null&&this.mesh===null){let t=e.cameras[0].viewport,n=new q({vertexShader:wg,fragmentShader:Tg,uniforms:{depthColor:{value:this.texture},depthWidth:{value:t.z},depthHeight:{value:t.w}}});this.mesh=new fo(new wl(20,20),n)}return this.mesh}reset(){this.texture=null,this.mesh=null}getDepthTexture(){return this.texture}},Dg=class extends Pn{constructor(e,t){super();let n=this,r=null,i=1,a=null,o=`local-floor`,s=1,c=null,l=null,u=null,d=null,f=null,p=null,m=typeof XRWebGLBinding<`u`,h=new Eg,g={},_=t.getContextAttributes(),v=null,y=null,b=[],x=[],S=new V,C=null,w=new Qu;w.viewport=new Dr;let T=new Qu;T.viewport=new Dr;let E=[w,T],D=new Ad,O=null,k=null;this.cameraAutoUpdate=!0,this.enabled=!1,this.isPresenting=!1,this.getController=function(e){let t=b[e];return t===void 0&&(t=new ui,b[e]=t),t.getTargetRaySpace()},this.getControllerGrip=function(e){let t=b[e];return t===void 0&&(t=new ui,b[e]=t),t.getGripSpace()},this.getHand=function(e){let t=b[e];return t===void 0&&(t=new ui,b[e]=t),t.getHandSpace()};function A(e){let t=x.indexOf(e.inputSource);if(t===-1)return;let n=b[t];n!==void 0&&(n.update(e.inputSource,e.frame,c||a),n.dispatchEvent({type:e.type,data:e.inputSource}))}function j(){r.removeEventListener(`select`,A),r.removeEventListener(`selectstart`,A),r.removeEventListener(`selectend`,A),r.removeEventListener(`squeeze`,A),r.removeEventListener(`squeezestart`,A),r.removeEventListener(`squeezeend`,A),r.removeEventListener(`end`,j),r.removeEventListener(`inputsourceschange`,ee);for(let e=0;e=0&&(x[r]=null,b[r].disconnect(n))}for(let t=0;t=x.length){x.push(n),r=e;break}else if(x[e]===null){x[e]=n,r=e;break}if(r===-1)break}let i=b[r];i&&i.connect(n)}}let M=new H,N=new H;function P(e,t,n){M.setFromMatrixPosition(t.matrixWorld),N.setFromMatrixPosition(n.matrixWorld);let r=M.distanceTo(N),i=t.projectionMatrix.elements,a=n.projectionMatrix.elements,o=i[14]/(i[10]-1),s=i[14]/(i[10]+1),c=(i[9]+1)/i[5],l=(i[9]-1)/i[5],u=(i[8]-1)/i[0],d=(a[8]+1)/a[0],f=o*u,p=o*d,m=r/(-u+d),h=m*-u;if(t.matrixWorld.decompose(e.position,e.quaternion,e.scale),e.translateX(h),e.translateZ(m),e.matrixWorld.compose(e.position,e.quaternion,e.scale),e.matrixWorldInverse.copy(e.matrixWorld).invert(),i[10]===-1)e.projectionMatrix.copy(t.projectionMatrix),e.projectionMatrixInverse.copy(t.projectionMatrixInverse);else{let t=o+m,n=s+m,i=f-h,a=p+(r-h),u=c*s/n*t,d=l*s/n*t;e.projectionMatrix.makePerspective(i,a,u,d,t,n),e.projectionMatrixInverse.copy(e.projectionMatrix).invert()}}function F(e,t){t===null?e.matrixWorld.copy(e.matrix):e.matrixWorld.multiplyMatrices(t.matrixWorld,e.matrix),e.matrixWorldInverse.copy(e.matrixWorld).invert()}this.updateCamera=function(e){if(r===null)return;let t=e.near,n=e.far;h.texture!==null&&(h.depthNear>0&&(t=h.depthNear),h.depthFar>0&&(n=h.depthFar)),D.near=T.near=w.near=t,D.far=T.far=w.far=n,(O!==D.near||k!==D.far)&&(r.updateRenderState({depthNear:D.near,depthFar:D.far}),O=D.near,k=D.far),D.layers.mask=e.layers.mask|6,w.layers.mask=D.layers.mask&-5,T.layers.mask=D.layers.mask&-3;let i=e.parent,a=D.cameras;F(D,i);for(let e=0;e0&&(e.alphaTest.value=r.alphaTest);let i=t.get(r),a=i.envMap,o=i.envMapRotation;a&&(e.envMap.value=a,Og.copy(o),Og.x*=-1,Og.y*=-1,Og.z*=-1,a.isCubeTexture&&a.isRenderTargetTexture===!1&&(Og.y*=-1,Og.z*=-1),e.envMapRotation.value.setFromMatrix4(kg.makeRotationFromEuler(Og)),e.flipEnvMap.value=a.isCubeTexture&&a.isRenderTargetTexture===!1?-1:1,e.reflectivity.value=r.reflectivity,e.ior.value=r.ior,e.refractionRatio.value=r.refractionRatio),r.lightMap&&(e.lightMap.value=r.lightMap,e.lightMapIntensity.value=r.lightMapIntensity,n(r.lightMap,e.lightMapTransform)),r.aoMap&&(e.aoMap.value=r.aoMap,e.aoMapIntensity.value=r.aoMapIntensity,n(r.aoMap,e.aoMapTransform))}function o(e,t){e.diffuse.value.copy(t.color),e.opacity.value=t.opacity,t.map&&(e.map.value=t.map,n(t.map,e.mapTransform))}function s(e,t){e.dashSize.value=t.dashSize,e.totalSize.value=t.dashSize+t.gapSize,e.scale.value=t.scale}function c(e,t,r,i){e.diffuse.value.copy(t.color),e.opacity.value=t.opacity,e.size.value=t.size*r,e.scale.value=i*.5,t.map&&(e.map.value=t.map,n(t.map,e.uvTransform)),t.alphaMap&&(e.alphaMap.value=t.alphaMap,n(t.alphaMap,e.alphaMapTransform)),t.alphaTest>0&&(e.alphaTest.value=t.alphaTest)}function l(e,t){e.diffuse.value.copy(t.color),e.opacity.value=t.opacity,e.rotation.value=t.rotation,t.map&&(e.map.value=t.map,n(t.map,e.mapTransform)),t.alphaMap&&(e.alphaMap.value=t.alphaMap,n(t.alphaMap,e.alphaMapTransform)),t.alphaTest>0&&(e.alphaTest.value=t.alphaTest)}function u(e,t){e.specular.value.copy(t.specular),e.shininess.value=Math.max(t.shininess,1e-4)}function d(e,t){t.gradientMap&&(e.gradientMap.value=t.gradientMap)}function f(e,t){e.metalness.value=t.metalness,t.metalnessMap&&(e.metalnessMap.value=t.metalnessMap,n(t.metalnessMap,e.metalnessMapTransform)),e.roughness.value=t.roughness,t.roughnessMap&&(e.roughnessMap.value=t.roughnessMap,n(t.roughnessMap,e.roughnessMapTransform)),t.envMap&&(e.envMapIntensity.value=t.envMapIntensity)}function p(e,t,r){e.ior.value=t.ior,t.sheen>0&&(e.sheenColor.value.copy(t.sheenColor).multiplyScalar(t.sheen),e.sheenRoughness.value=t.sheenRoughness,t.sheenColorMap&&(e.sheenColorMap.value=t.sheenColorMap,n(t.sheenColorMap,e.sheenColorMapTransform)),t.sheenRoughnessMap&&(e.sheenRoughnessMap.value=t.sheenRoughnessMap,n(t.sheenRoughnessMap,e.sheenRoughnessMapTransform))),t.clearcoat>0&&(e.clearcoat.value=t.clearcoat,e.clearcoatRoughness.value=t.clearcoatRoughness,t.clearcoatMap&&(e.clearcoatMap.value=t.clearcoatMap,n(t.clearcoatMap,e.clearcoatMapTransform)),t.clearcoatRoughnessMap&&(e.clearcoatRoughnessMap.value=t.clearcoatRoughnessMap,n(t.clearcoatRoughnessMap,e.clearcoatRoughnessMapTransform)),t.clearcoatNormalMap&&(e.clearcoatNormalMap.value=t.clearcoatNormalMap,n(t.clearcoatNormalMap,e.clearcoatNormalMapTransform),e.clearcoatNormalScale.value.copy(t.clearcoatNormalScale),t.side===1&&e.clearcoatNormalScale.value.negate())),t.dispersion>0&&(e.dispersion.value=t.dispersion),t.iridescence>0&&(e.iridescence.value=t.iridescence,e.iridescenceIOR.value=t.iridescenceIOR,e.iridescenceThicknessMinimum.value=t.iridescenceThicknessRange[0],e.iridescenceThicknessMaximum.value=t.iridescenceThicknessRange[1],t.iridescenceMap&&(e.iridescenceMap.value=t.iridescenceMap,n(t.iridescenceMap,e.iridescenceMapTransform)),t.iridescenceThicknessMap&&(e.iridescenceThicknessMap.value=t.iridescenceThicknessMap,n(t.iridescenceThicknessMap,e.iridescenceThicknessMapTransform))),t.transmission>0&&(e.transmission.value=t.transmission,e.transmissionSamplerMap.value=r.texture,e.transmissionSamplerSize.value.set(r.width,r.height),t.transmissionMap&&(e.transmissionMap.value=t.transmissionMap,n(t.transmissionMap,e.transmissionMapTransform)),e.thickness.value=t.thickness,t.thicknessMap&&(e.thicknessMap.value=t.thicknessMap,n(t.thicknessMap,e.thicknessMapTransform)),e.attenuationDistance.value=t.attenuationDistance,e.attenuationColor.value.copy(t.attenuationColor)),t.anisotropy>0&&(e.anisotropyVector.value.set(t.anisotropy*Math.cos(t.anisotropyRotation),t.anisotropy*Math.sin(t.anisotropyRotation)),t.anisotropyMap&&(e.anisotropyMap.value=t.anisotropyMap,n(t.anisotropyMap,e.anisotropyMapTransform))),e.specularIntensity.value=t.specularIntensity,e.specularColor.value.copy(t.specularColor),t.specularColorMap&&(e.specularColorMap.value=t.specularColorMap,n(t.specularColorMap,e.specularColorMapTransform)),t.specularIntensityMap&&(e.specularIntensityMap.value=t.specularIntensityMap,n(t.specularIntensityMap,e.specularIntensityMapTransform))}function m(e,t){t.matcap&&(e.matcap.value=t.matcap)}function h(e,n){let r=t.get(n).light;e.referencePosition.value.setFromMatrixPosition(r.matrixWorld),e.nearDistance.value=r.shadow.camera.near,e.farDistance.value=r.shadow.camera.far}return{refreshFogUniforms:r,refreshMaterialUniforms:i}}function jg(e,t,n,r){let i={},a={},o=[],s=e.getParameter(e.MAX_UNIFORM_BUFFER_BINDINGS);function c(e,t){let n=t.program;r.uniformBlockBinding(e,n)}function l(e,n){let o=i[e.id];o===void 0&&(m(e),o=u(e),i[e.id]=o,e.addEventListener(`dispose`,g));let s=n.program;r.updateUBOMapping(e,s);let c=t.render.frame;a[e.id]!==c&&(f(e),a[e.id]=c)}function u(t){let n=d();t.__bindingPointIndex=n;let r=e.createBuffer(),i=t.__size,a=t.usage;return e.bindBuffer(e.UNIFORM_BUFFER,r),e.bufferData(e.UNIFORM_BUFFER,i,a),e.bindBuffer(e.UNIFORM_BUFFER,null),e.bindBufferBase(e.UNIFORM_BUFFER,n,r),r}function d(){for(let e=0;e0&&(n+=16-r),e.__size=n,e.__cache={},this}function h(e){let t={boundary:0,storage:0};return typeof e==`number`||typeof e==`boolean`?(t.boundary=4,t.storage=4):e.isVector2?(t.boundary=8,t.storage=8):e.isVector3||e.isColor?(t.boundary=16,t.storage=12):e.isVector4?(t.boundary=16,t.storage=16):e.isMatrix3?(t.boundary=48,t.storage=48):e.isMatrix4?(t.boundary=64,t.storage=64):e.isTexture?B(`WebGLRenderer: Texture samplers can not be part of an uniforms group.`):B(`WebGLRenderer: Unsupported uniform value type.`,e),t}function g(t){let n=t.target;n.removeEventListener(`dispose`,g);let r=o.indexOf(n.__bindingPointIndex);o.splice(r,1),e.deleteBuffer(i[n.id]),delete i[n.id],delete a[n.id]}function _(){for(let t in i)e.deleteBuffer(i[t]);o=[],i={},a={}}return{bind:c,update:l,dispose:_}}var Mg=new Uint16Array([12469,15057,12620,14925,13266,14620,13807,14376,14323,13990,14545,13625,14713,13328,14840,12882,14931,12528,14996,12233,15039,11829,15066,11525,15080,11295,15085,10976,15082,10705,15073,10495,13880,14564,13898,14542,13977,14430,14158,14124,14393,13732,14556,13410,14702,12996,14814,12596,14891,12291,14937,11834,14957,11489,14958,11194,14943,10803,14921,10506,14893,10278,14858,9960,14484,14039,14487,14025,14499,13941,14524,13740,14574,13468,14654,13106,14743,12678,14818,12344,14867,11893,14889,11509,14893,11180,14881,10751,14852,10428,14812,10128,14765,9754,14712,9466,14764,13480,14764,13475,14766,13440,14766,13347,14769,13070,14786,12713,14816,12387,14844,11957,14860,11549,14868,11215,14855,10751,14825,10403,14782,10044,14729,9651,14666,9352,14599,9029,14967,12835,14966,12831,14963,12804,14954,12723,14936,12564,14917,12347,14900,11958,14886,11569,14878,11247,14859,10765,14828,10401,14784,10011,14727,9600,14660,9289,14586,8893,14508,8533,15111,12234,15110,12234,15104,12216,15092,12156,15067,12010,15028,11776,14981,11500,14942,11205,14902,10752,14861,10393,14812,9991,14752,9570,14682,9252,14603,8808,14519,8445,14431,8145,15209,11449,15208,11451,15202,11451,15190,11438,15163,11384,15117,11274,15055,10979,14994,10648,14932,10343,14871,9936,14803,9532,14729,9218,14645,8742,14556,8381,14461,8020,14365,7603,15273,10603,15272,10607,15267,10619,15256,10631,15231,10614,15182,10535,15118,10389,15042,10167,14963,9787,14883,9447,14800,9115,14710,8665,14615,8318,14514,7911,14411,7507,14279,7198,15314,9675,15313,9683,15309,9712,15298,9759,15277,9797,15229,9773,15166,9668,15084,9487,14995,9274,14898,8910,14800,8539,14697,8234,14590,7790,14479,7409,14367,7067,14178,6621,15337,8619,15337,8631,15333,8677,15325,8769,15305,8871,15264,8940,15202,8909,15119,8775,15022,8565,14916,8328,14804,8009,14688,7614,14569,7287,14448,6888,14321,6483,14088,6171,15350,7402,15350,7419,15347,7480,15340,7613,15322,7804,15287,7973,15229,8057,15148,8012,15046,7846,14933,7611,14810,7357,14682,7069,14552,6656,14421,6316,14251,5948,14007,5528,15356,5942,15356,5977,15353,6119,15348,6294,15332,6551,15302,6824,15249,7044,15171,7122,15070,7050,14949,6861,14818,6611,14679,6349,14538,6067,14398,5651,14189,5311,13935,4958,15359,4123,15359,4153,15356,4296,15353,4646,15338,5160,15311,5508,15263,5829,15188,6042,15088,6094,14966,6001,14826,5796,14678,5543,14527,5287,14377,4985,14133,4586,13869,4257,15360,1563,15360,1642,15358,2076,15354,2636,15341,3350,15317,4019,15273,4429,15203,4732,15105,4911,14981,4932,14836,4818,14679,4621,14517,4386,14359,4156,14083,3795,13808,3437,15360,122,15360,137,15358,285,15355,636,15344,1274,15322,2177,15281,2765,15215,3223,15120,3451,14995,3569,14846,3567,14681,3466,14511,3305,14344,3121,14037,2800,13753,2467,15360,0,15360,1,15359,21,15355,89,15346,253,15325,479,15287,796,15225,1148,15133,1492,15008,1749,14856,1882,14685,1886,14506,1783,14324,1608,13996,1398,13702,1183]),Ng=null;function Pg(){return Ng===null&&(Ng=new Eo(Mg,16,16,He,ke),Ng.name=`DFG_LUT`,Ng.minFilter=L,Ng.magFilter=L,Ng.wrapS=me,Ng.wrapT=me,Ng.generateMipmaps=!1,Ng.needsUpdate=!0),Ng}var Fg=class{constructor(e={}){let{canvas:t=Cn(),context:n=null,depth:r=!0,stencil:i=!1,alpha:a=!1,antialias:o=!1,premultipliedAlpha:s=!0,preserveDrawingBuffer:c=!1,powerPreference:l=`default`,failIfMajorPerformanceCaveat:u=!1,reversedDepthBuffer:d=!1,outputBufferType:f=Se}=e;this.isWebGLRenderer=!0;let p;if(n!==null){if(typeof WebGLRenderingContext<`u`&&n instanceof WebGLRenderingContext)throw Error(`THREE.WebGLRenderer: WebGL 1 is not supported since r163.`);p=n.getContextAttributes().alpha}else p=a;let m=f,h=new Set([Ge,Ue,Ve]),g=new Set([Se,De,Te,Me,Ae,je]),_=new Uint32Array(4),v=new Int32Array(4),y=null,b=null,x=[],S=[],C=null;this.domElement=t,this.debug={checkShaderErrors:!0,onShaderError:null},this.autoClear=!0,this.autoClearColor=!0,this.autoClearDepth=!0,this.autoClearStencil=!0,this.sortObjects=!0,this.clippingPlanes=[],this.localClippingEnabled=!1,this.toneMapping=0,this.toneMappingExposure=1,this.transmissionResolutionScale=1;let w=this,T=!1;this._outputColorSpace=Wt;let E=0,D=0,O=null,k=-1,A=null,j=new Dr,ee=new Dr,M=null,N=new U(0),P=0,F=t.width,te=t.height,ne=1,re=null,ie=null,ae=new Dr(0,0,F,te),oe=new Dr(0,0,F,te),se=!1,ce=new Ko,le=!1,ue=!1,de=new Pr,fe=new H,pe=new Dr,me={background:null,fog:null,environment:null,overrideMaterial:null,isScene:!0},he=!1;function ge(){return O===null?ne:1}let I=n;function _e(e,n){return t.getContext(e,n)}try{let e={alpha:!0,depth:r,stencil:i,antialias:o,premultipliedAlpha:s,preserveDrawingBuffer:c,powerPreference:l,failIfMajorPerformanceCaveat:u};if(`setAttribute`in t&&t.setAttribute(`data-engine`,`three.js r183`),t.addEventListener(`webglcontextlost`,Ze,!1),t.addEventListener(`webglcontextrestored`,Qe,!1),t.addEventListener(`webglcontextcreationerror`,$e,!1),I===null){let t=`webgl2`;if(I=_e(t,e),I===null)throw _e(t)?Error(`Error creating WebGL context with your selected attributes.`):Error(`Error creating WebGL context.`)}}catch(e){throw An(`WebGLRenderer: `+e.message),e}let ve,ye,L,R,z,xe,Ce,we,Ee,Oe,Ne,Pe,Fe,Ie,Le,Re,ze,Be,He,We,Ke,qe,Je;function Ye(){ve=new em(I),ve.init(),Ke=new Cg(I,ve),ye=new Ap(I,ve,e,Ke),L=new xg(I,ve),ye.reversedDepthBuffer&&d&&L.buffers.depth.setReversed(!0),R=new rm(I),z=new tg,xe=new Sg(I,ve,L,z,ye,Ke,R),Ce=new $p(w),we=new xp(I),qe=new Op(I,we),Ee=new tm(I,we,R,qe),Oe=new am(I,Ee,we,qe,R),Be=new im(I,ye,xe),Le=new jp(z),Ne=new eg(w,Ce,ve,ye,qe,Le),Pe=new Ag(w,z),Fe=new ag,Ie=new fg(ve),ze=new Dp(w,Ce,L,Oe,p,s),Re=new bg(w,Oe,ye),Je=new jg(I,R,ye,L),He=new kp(I,ve,R),We=new nm(I,ve,R),R.programs=Ne.programs,w.capabilities=ye,w.extensions=ve,w.properties=z,w.renderLists=Fe,w.shadowMap=Re,w.state=L,w.info=R}Ye(),m!==1009&&(C=new sm(m,t.width,t.height,r,i));let Xe=new Dg(w,I);this.xr=Xe,this.getContext=function(){return I},this.getContextAttributes=function(){return I.getContextAttributes()},this.forceContextLoss=function(){let e=ve.get(`WEBGL_lose_context`);e&&e.loseContext()},this.forceContextRestore=function(){let e=ve.get(`WEBGL_lose_context`);e&&e.restoreContext()},this.getPixelRatio=function(){return ne},this.setPixelRatio=function(e){e!==void 0&&(ne=e,this.setSize(F,te,!1))},this.getSize=function(e){return e.set(F,te)},this.setSize=function(e,n,r=!0){if(Xe.isPresenting){B(`WebGLRenderer: Can't change size while VR device is presenting.`);return}F=e,te=n,t.width=Math.floor(e*ne),t.height=Math.floor(n*ne),r===!0&&(t.style.width=e+`px`,t.style.height=n+`px`),C!==null&&C.setSize(t.width,t.height),this.setViewport(0,0,e,n)},this.getDrawingBufferSize=function(e){return e.set(F*ne,te*ne).floor()},this.setDrawingBufferSize=function(e,n,r){F=e,te=n,ne=r,t.width=Math.floor(e*r),t.height=Math.floor(n*r),this.setViewport(0,0,e,n)},this.setEffects=function(e){if(m===1009){console.error(`THREE.WebGLRenderer: setEffects() requires outputBufferType set to HalfFloatType or FloatType.`);return}if(e){for(let t=0;t{function n(){if(r.forEach(function(e){z.get(e).currentProgram.isReady()&&r.delete(e)}),r.size===0){t(e);return}setTimeout(n,10)}ve.get(`KHR_parallel_shader_compile`)===null?setTimeout(n,10):n()})};let it=null;function at(e){it&&it(e)}function ot(){ct.stop()}function st(){ct.start()}let ct=new bp;ct.setAnimationLoop(at),typeof self<`u`&&ct.setContext(self),this.setAnimationLoop=function(e){it=e,Xe.setAnimationLoop(e),e===null?ct.stop():ct.start()},Xe.addEventListener(`sessionstart`,ot),Xe.addEventListener(`sessionend`,st),this.render=function(e,t){if(t!==void 0&&t.isCamera!==!0){An(`WebGLRenderer.render: camera is not an instance of THREE.Camera.`);return}if(T===!0)return;let n=Xe.enabled===!0&&Xe.isPresenting===!0,r=C!==null&&(O===null||n)&&C.begin(w,O);if(e.matrixWorldAutoUpdate===!0&&e.updateMatrixWorld(),t.parent===null&&t.matrixWorldAutoUpdate===!0&&t.updateMatrixWorld(),Xe.enabled===!0&&Xe.isPresenting===!0&&(C===null||C.isCompositing()===!1)&&(Xe.cameraAutoUpdate===!0&&Xe.updateCamera(t),t=Xe.getCamera()),e.isScene===!0&&e.onBeforeRender(w,e,t,O),b=Ie.get(e,S.length),b.init(t),S.push(b),de.multiplyMatrices(t.projectionMatrix,t.matrixWorldInverse),ce.setFromProjectionMatrix(de,fn,t.reversedDepth),ue=this.localClippingEnabled,le=Le.init(this.clippingPlanes,ue),y=Fe.get(e,x.length),y.init(),x.push(y),Xe.enabled===!0&&Xe.isPresenting===!0){let e=w.xr.getDepthSensingMesh();e!==null&<(e,t,-1/0,w.sortObjects)}lt(e,t,0,w.sortObjects),y.finish(),w.sortObjects===!0&&y.sort(re,ie),he=Xe.enabled===!1||Xe.isPresenting===!1||Xe.hasDepthSensing()===!1,he&&ze.addToRenderList(y,e),this.info.render.frame++,le===!0&&Le.beginShadows();let i=b.state.shadowsArray;if(Re.render(i,e,t),le===!0&&Le.endShadows(),this.info.autoReset===!0&&this.info.reset(),(r&&C.hasRenderPass())===!1){let n=y.opaque,r=y.transmissive;if(b.setupLights(),t.isArrayCamera){let i=t.cameras;if(r.length>0)for(let t=0,a=i.length;t0&&dt(n,r,e,t),he&&ze.render(e),ut(y,e,t)}O!==null&&D===0&&(xe.updateMultisampleRenderTarget(O),xe.updateRenderTargetMipmap(O)),r&&C.end(w),e.isScene===!0&&e.onAfterRender(w,e,t),qe.resetDefaultState(),k=-1,A=null,S.pop(),S.length>0?(b=S[S.length-1],le===!0&&Le.setGlobalState(w.clippingPlanes,b.state.camera)):b=null,x.pop(),y=x.length>0?x[x.length-1]:null};function lt(e,t,n,r){if(e.visible===!1)return;if(e.layers.test(t.layers)){if(e.isGroup)n=e.renderOrder;else if(e.isLOD)e.autoUpdate===!0&&e.update(t);else if(e.isLight)b.pushLight(e),e.castShadow&&b.pushShadow(e);else if(e.isSprite){if(!e.frustumCulled||ce.intersectsSprite(e)){r&&pe.setFromMatrixPosition(e.matrixWorld).applyMatrix4(de);let t=Oe.update(e),i=e.material;i.visible&&y.push(e,t,i,n,pe.z,null)}}else if((e.isMesh||e.isLine||e.isPoints)&&(!e.frustumCulled||ce.intersectsObject(e))){let t=Oe.update(e),i=e.material;if(r&&(e.boundingSphere===void 0?(t.boundingSphere===null&&t.computeBoundingSphere(),pe.copy(t.boundingSphere.center)):(e.boundingSphere===null&&e.computeBoundingSphere(),pe.copy(e.boundingSphere.center)),pe.applyMatrix4(e.matrixWorld).applyMatrix4(de)),Array.isArray(i)){let r=t.groups;for(let a=0,o=r.length;a0&&ft(i,t,n),a.length>0&&ft(a,t,n),o.length>0&&ft(o,t,n),L.buffers.depth.setTest(!0),L.buffers.depth.setMask(!0),L.buffers.color.setMask(!0),L.setPolygonOffset(!1)}function dt(e,t,n,r){if((n.isScene===!0?n.overrideMaterial:null)!==null)return;if(b.state.transmissionRenderTarget[r.id]===void 0){let e=ve.has(`EXT_color_buffer_half_float`)||ve.has(`EXT_color_buffer_float`);b.state.transmissionRenderTarget[r.id]=new kr(1,1,{generateMipmaps:!0,type:e?ke:Se,minFilter:be,samples:Math.max(4,ye.samples),stencilBuffer:i,resolveDepthBuffer:!1,resolveStencilBuffer:!1,colorSpace:gr.workingColorSpace})}let a=b.state.transmissionRenderTarget[r.id],o=r.viewport||j;a.setSize(o.z*w.transmissionResolutionScale,o.w*w.transmissionResolutionScale);let s=w.getRenderTarget(),c=w.getActiveCubeFace(),l=w.getActiveMipmapLevel();w.setRenderTarget(a),w.getClearColor(N),P=w.getClearAlpha(),P<1&&w.setClearColor(16777215,.5),w.clear(),he&&ze.render(n);let u=w.toneMapping;w.toneMapping=0;let d=r.viewport;if(r.viewport!==void 0&&(r.viewport=void 0),b.setupLightsView(r),le===!0&&Le.setGlobalState(w.clippingPlanes,r),ft(e,n,r),xe.updateMultisampleRenderTarget(a),xe.updateRenderTargetMipmap(a),ve.has(`WEBGL_multisampled_render_to_texture`)===!1){let e=!1;for(let i=0,a=t.length;i0),f=!!n.morphAttributes.position,p=!!n.morphAttributes.normal,m=!!n.morphAttributes.color,h=0;r.toneMapped&&(O===null||O.isXRRenderTarget===!0)&&(h=w.toneMapping);let g=n.morphAttributes.position||n.morphAttributes.normal||n.morphAttributes.color,_=g===void 0?0:g.length,v=z.get(r),y=b.state.lights;if(le===!0&&(ue===!0||e!==A)){let t=e===A&&r.id===k;Le.setState(r,e,t)}let x=!1;r.version===v.__version?v.needsLights&&v.lightsStateVersion!==y.state.version?x=!0:v.outputColorSpace===s?i.isBatchedMesh&&v.batching===!1||!i.isBatchedMesh&&v.batching===!0||i.isBatchedMesh&&v.batchingColor===!0&&i.colorTexture===null||i.isBatchedMesh&&v.batchingColor===!1&&i.colorTexture!==null||i.isInstancedMesh&&v.instancing===!1||!i.isInstancedMesh&&v.instancing===!0||i.isSkinnedMesh&&v.skinning===!1||!i.isSkinnedMesh&&v.skinning===!0||i.isInstancedMesh&&v.instancingColor===!0&&i.instanceColor===null||i.isInstancedMesh&&v.instancingColor===!1&&i.instanceColor!==null||i.isInstancedMesh&&v.instancingMorph===!0&&i.morphTexture===null||i.isInstancedMesh&&v.instancingMorph===!1&&i.morphTexture!==null?x=!0:v.envMap===l?r.fog===!0&&v.fog!==a||v.numClippingPlanes!==void 0&&(v.numClippingPlanes!==Le.numPlanes||v.numIntersection!==Le.numIntersection)?x=!0:v.vertexAlphas===u&&v.vertexTangents===d&&v.morphTargets===f&&v.morphNormals===p&&v.morphColors===m&&v.toneMapping===h?v.morphTargetsCount!==_&&(x=!0):x=!0:x=!0:x=!0:(x=!0,v.__version=r.version);let S=v.currentProgram;x===!0&&(S=mt(r,t,i));let C=!1,T=!1,E=!1,D=S.getUniforms(),j=v.uniforms;if(L.useProgram(S.program)&&(C=!0,T=!0,E=!0),r.id!==k&&(k=r.id,T=!0),C||A!==e){L.buffers.depth.getReversed()&&e.reversedDepth!==!0&&(e._reversedDepth=!0,e.updateProjectionMatrix()),D.setValue(I,`projectionMatrix`,e.projectionMatrix),D.setValue(I,`viewMatrix`,e.matrixWorldInverse);let t=D.map.cameraPosition;t!==void 0&&t.setValue(I,fe.setFromMatrixPosition(e.matrixWorld)),ye.logarithmicDepthBuffer&&D.setValue(I,`logDepthBufFC`,2/(Math.log(e.far+1)/Math.LN2)),(r.isMeshPhongMaterial||r.isMeshToonMaterial||r.isMeshLambertMaterial||r.isMeshBasicMaterial||r.isMeshStandardMaterial||r.isShaderMaterial)&&D.setValue(I,`isOrthographic`,e.isOrthographicCamera===!0),A!==e&&(A=e,T=!0,E=!0)}if(v.needsLights&&(y.state.directionalShadowMap.length>0&&D.setValue(I,`directionalShadowMap`,y.state.directionalShadowMap,xe),y.state.spotShadowMap.length>0&&D.setValue(I,`spotShadowMap`,y.state.spotShadowMap,xe),y.state.pointShadowMap.length>0&&D.setValue(I,`pointShadowMap`,y.state.pointShadowMap,xe)),i.isSkinnedMesh){D.setOptional(I,i,`bindMatrix`),D.setOptional(I,i,`bindMatrixInverse`);let e=i.skeleton;e&&(e.boneTexture===null&&e.computeBoneTexture(),D.setValue(I,`boneTexture`,e.boneTexture,xe))}i.isBatchedMesh&&(D.setOptional(I,i,`batchingTexture`),D.setValue(I,`batchingTexture`,i._matricesTexture,xe),D.setOptional(I,i,`batchingIdTexture`),D.setValue(I,`batchingIdTexture`,i._indirectTexture,xe),D.setOptional(I,i,`batchingColorTexture`),i._colorsTexture!==null&&D.setValue(I,`batchingColorTexture`,i._colorsTexture,xe));let ee=n.morphAttributes;if((ee.position!==void 0||ee.normal!==void 0||ee.color!==void 0)&&Be.update(i,n,S),(T||v.receiveShadow!==i.receiveShadow)&&(v.receiveShadow=i.receiveShadow,D.setValue(I,`receiveShadow`,i.receiveShadow)),(r.isMeshStandardMaterial||r.isMeshLambertMaterial||r.isMeshPhongMaterial)&&r.envMap===null&&t.environment!==null&&(j.envMapIntensity.value=t.environmentIntensity),j.dfgLUT!==void 0&&(j.dfgLUT.value=Pg()),T&&(D.setValue(I,`toneMappingExposure`,w.toneMappingExposure),v.needsLights&&vt(j,E),a&&r.fog===!0&&Pe.refreshFogUniforms(j,a),Pe.refreshMaterialUniforms(j,r,ne,te,b.state.transmissionRenderTarget[e.id]),mh.upload(I,ht(v),j,xe)),r.isShaderMaterial&&r.uniformsNeedUpdate===!0&&(mh.upload(I,ht(v),j,xe),r.uniformsNeedUpdate=!1),r.isSpriteMaterial&&D.setValue(I,`center`,i.center),D.setValue(I,`modelViewMatrix`,i.modelViewMatrix),D.setValue(I,`normalMatrix`,i.normalMatrix),D.setValue(I,`modelMatrix`,i.matrixWorld),r.isShaderMaterial||r.isRawShaderMaterial){let e=r.uniformsGroups;for(let t=0,n=e.length;t0&&xe.useMultisampledRTT(e)===!1?z.get(e).__webglMultisampledFramebuffer:Array.isArray(c)?c[n]:c,j.copy(e.viewport),ee.copy(e.scissor),M=e.scissorTest}else j.copy(ae).multiplyScalar(ne).floor(),ee.copy(oe).multiplyScalar(ne).floor(),M=se;if(n!==0&&(r=bt),L.bindFramebuffer(I.FRAMEBUFFER,r)&&L.drawBuffers(e,r),L.viewport(j),L.scissor(ee),L.setScissorTest(M),i){let r=z.get(e.texture);I.framebufferTexture2D(I.FRAMEBUFFER,I.COLOR_ATTACHMENT0,I.TEXTURE_CUBE_MAP_POSITIVE_X+t,r.__webglTexture,n)}else if(a){let r=t;for(let t=0;t1&&I.readBuffer(I.COLOR_ATTACHMENT0+s),!ye.textureFormatReadable(c)){An(`WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format.`);return}if(!ye.textureTypeReadable(l)){An(`WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type.`);return}t>=0&&t<=e.width-r&&n>=0&&n<=e.height-i&&I.readPixels(t,n,r,i,Ke.convert(c),Ke.convert(l),a)}finally{let e=O===null?null:z.get(O).__webglFramebuffer;L.bindFramebuffer(I.FRAMEBUFFER,e)}}},this.readRenderTargetPixelsAsync=async function(e,t,n,r,i,a,o,s=0){if(!(e&&e.isWebGLRenderTarget))throw Error(`THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget.`);let c=z.get(e).__webglFramebuffer;if(e.isWebGLCubeRenderTarget&&o!==void 0&&(c=c[o]),c)if(t>=0&&t<=e.width-r&&n>=0&&n<=e.height-i){L.bindFramebuffer(I.FRAMEBUFFER,c);let o=e.textures[s],l=o.format,u=o.type;if(e.textures.length>1&&I.readBuffer(I.COLOR_ATTACHMENT0+s),!ye.textureFormatReadable(l))throw Error(`THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format.`);if(!ye.textureTypeReadable(u))throw Error(`THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type.`);let d=I.createBuffer();I.bindBuffer(I.PIXEL_PACK_BUFFER,d),I.bufferData(I.PIXEL_PACK_BUFFER,a.byteLength,I.STREAM_READ),I.readPixels(t,n,r,i,Ke.convert(l),Ke.convert(u),0);let f=O===null?null:z.get(O).__webglFramebuffer;L.bindFramebuffer(I.FRAMEBUFFER,f);let p=I.fenceSync(I.SYNC_GPU_COMMANDS_COMPLETE,0);return I.flush(),await Mn(I,p,4),I.bindBuffer(I.PIXEL_PACK_BUFFER,d),I.getBufferSubData(I.PIXEL_PACK_BUFFER,0,a),I.deleteBuffer(d),I.deleteSync(p),a}else throw Error(`THREE.WebGLRenderer.readRenderTargetPixelsAsync: requested read bounds are out of range.`)},this.copyFramebufferToTexture=function(e,t=null,n=0){let r=2**-n,i=Math.floor(e.image.width*r),a=Math.floor(e.image.height*r),o=t===null?0:t.x,s=t===null?0:t.y;xe.setTexture2D(e,0),I.copyTexSubImage2D(I.TEXTURE_2D,n,0,0,o,s,i,a),L.unbindTexture()};let xt=I.createFramebuffer(),St=I.createFramebuffer();this.copyTextureToTexture=function(e,t,n=null,r=null,i=0,a=0){let o,s,c,l,u,d,f,p,m,h=e.isCompressedTexture?e.mipmaps[a]:e.image;if(n!==null)o=n.max.x-n.min.x,s=n.max.y-n.min.y,c=n.isBox3?n.max.z-n.min.z:1,l=n.min.x,u=n.min.y,d=n.isBox3?n.min.z:0;else{let t=2**-i;o=Math.floor(h.width*t),s=Math.floor(h.height*t),c=e.isDataArrayTexture?h.depth:e.isData3DTexture?Math.floor(h.depth*t):1,l=0,u=0,d=0}r===null?(f=0,p=0,m=0):(f=r.x,p=r.y,m=r.z);let g=Ke.convert(t.format),_=Ke.convert(t.type),v;t.isData3DTexture?(xe.setTexture3D(t,0),v=I.TEXTURE_3D):t.isDataArrayTexture||t.isCompressedArrayTexture?(xe.setTexture2DArray(t,0),v=I.TEXTURE_2D_ARRAY):(xe.setTexture2D(t,0),v=I.TEXTURE_2D),I.pixelStorei(I.UNPACK_FLIP_Y_WEBGL,t.flipY),I.pixelStorei(I.UNPACK_PREMULTIPLY_ALPHA_WEBGL,t.premultiplyAlpha),I.pixelStorei(I.UNPACK_ALIGNMENT,t.unpackAlignment);let y=I.getParameter(I.UNPACK_ROW_LENGTH),b=I.getParameter(I.UNPACK_IMAGE_HEIGHT),x=I.getParameter(I.UNPACK_SKIP_PIXELS),S=I.getParameter(I.UNPACK_SKIP_ROWS),C=I.getParameter(I.UNPACK_SKIP_IMAGES);I.pixelStorei(I.UNPACK_ROW_LENGTH,h.width),I.pixelStorei(I.UNPACK_IMAGE_HEIGHT,h.height),I.pixelStorei(I.UNPACK_SKIP_PIXELS,l),I.pixelStorei(I.UNPACK_SKIP_ROWS,u),I.pixelStorei(I.UNPACK_SKIP_IMAGES,d);let w=e.isDataArrayTexture||e.isData3DTexture,T=t.isDataArrayTexture||t.isData3DTexture;if(e.isDepthTexture){let n=z.get(e),r=z.get(t),h=z.get(n.__renderTarget),g=z.get(r.__renderTarget);L.bindFramebuffer(I.READ_FRAMEBUFFER,h.__webglFramebuffer),L.bindFramebuffer(I.DRAW_FRAMEBUFFER,g.__webglFramebuffer);for(let n=0;n{var t=f();function n(e,t){return e===t&&(e!==0||1/e==1/t)||e!==e&&t!==t}var r=typeof Object.is==`function`?Object.is:n,i=t.useState,a=t.useEffect,o=t.useLayoutEffect,s=t.useDebugValue;function c(e,t){var n=t(),r=i({inst:{value:n,getSnapshot:t}}),c=r[0].inst,u=r[1];return o(function(){c.value=n,c.getSnapshot=t,l(c)&&u({inst:c})},[e,n,t]),a(function(){return l(c)&&u({inst:c}),e(function(){l(c)&&u({inst:c})})},[e]),s(n),n}function l(e){var t=e.getSnapshot;e=e.value;try{var n=t();return!r(e,n)}catch{return!0}}function u(e,t){return t()}var d=typeof window>`u`||window.document===void 0||window.document.createElement===void 0?u:c;e.useSyncExternalStore=t.useSyncExternalStore===void 0?d:t.useSyncExternalStore})),Lg=o(((e,t)=>{t.exports=Ig()})),Rg=o((e=>{var t=f(),n=Lg();function r(e,t){return e===t&&(e!==0||1/e==1/t)||e!==e&&t!==t}var i=typeof Object.is==`function`?Object.is:r,a=n.useSyncExternalStore,o=t.useRef,s=t.useEffect,c=t.useMemo,l=t.useDebugValue;e.useSyncExternalStoreWithSelector=function(e,t,n,r,u){var d=o(null);if(d.current===null){var f={hasValue:!1,value:null};d.current=f}else f=d.current;d=c(function(){function e(e){if(!a){if(a=!0,o=e,e=r(e),u!==void 0&&f.hasValue){var t=f.value;if(u(t,e))return s=t}return s=e}if(t=s,i(o,e))return t;var n=r(e);return u!==void 0&&u(t,n)?(o=e,t):(o=e,s=n)}var a=!1,o,s,c=n===void 0?null:n;return[function(){return e(t())},c===null?void 0:function(){return e(c())}]},[t,n,r,u]);var p=a(e,d[0],d[1]);return s(function(){f.hasValue=!0,f.value=p},[p]),l(p),p}})),zg=l(o(((e,t)=>{t.exports=Rg()}))(),1),Bg=e=>{let t,n=new Set,r=(e,r)=>{let i=typeof e==`function`?e(t):e;if(!Object.is(i,t)){let e=t;t=r??(typeof i!=`object`||!i)?i:Object.assign({},t,i),n.forEach(n=>n(t,e))}},i=()=>t,a={setState:r,getState:i,getInitialState:()=>o,subscribe:e=>(n.add(e),()=>n.delete(e))},o=t=e(r,i,a);return a},Vg=(e=>e?Bg(e):Bg),{useSyncExternalStoreWithSelector:Hg}=zg.default,Ug=e=>e;function Wg(e,t=Ug,n){let r=Hg(e.subscribe,e.getState,e.getInitialState,t,n);return y.useDebugValue(r),r}var Gg=(e,t)=>{let n=Vg(e),r=(e,r=t)=>Wg(n,e,r);return Object.assign(r,n),r},Kg=((e,t)=>e?Gg(e,t):Gg),qg=e=>typeof e==`object`&&typeof e.then==`function`,Jg=[];function Yg(e,t,n=(e,t)=>e===t){if(e===t)return!0;if(!e||!t)return!1;let r=e.length;if(t.length!==r)return!1;for(let i=0;i0&&(e.timeout&&clearTimeout(e.timeout),e.timeout=setTimeout(e.remove,r.lifespan)),e.response;if(!n)throw e.promise}let i={keys:t,equal:r.equal,remove:()=>{let e=Jg.indexOf(i);e!==-1&&Jg.splice(e,1)},promise:(qg(e)?e:e(...t)).then(e=>{i.response=e,r.lifespan&&r.lifespan>0&&(i.timeout=setTimeout(i.remove,r.lifespan))}).catch(e=>i.error=e)};if(Jg.push(i),!n)throw i.promise}var Zg=(e,t,n)=>Xg(e,t,!1,n),Qg=(e,t,n)=>void Xg(e,t,!0,n),$g=e=>{if(e===void 0||e.length===0)Jg.splice(0,Jg.length);else{let t=Jg.find(t=>Yg(e,t.keys,t.equal));t&&t.remove()}},e_=l(m());typeof window<`u`&&(window.document?.createElement||window.navigator?.product===`ReactNative`)?y.useLayoutEffect:y.useEffect;function t_(e,t,n){if(!e)return;if(n(e)===!0)return e;let r=t?e.return:e.child;for(;r;){let e=t_(r,t,n);if(e)return e;r=t?null:r.sibling}}function n_(e){try{return Object.defineProperties(e,{_currentRenderer:{get(){return null},set(){}},_currentRenderer2:{get(){return null},set(){}}})}catch{return e}}var r_=n_(y.createContext(null)),i_=class extends y.Component{render(){return y.createElement(r_.Provider,{value:this._reactInternals},this.props.children)}};function a_(){let e=y.useContext(r_);if(e===null)throw Error(`its-fine: useFiber must be called within a !`);let t=y.useId();return y.useMemo(()=>{for(let n of[e,e?.alternate]){if(!n)continue;let e=t_(n,!1,e=>{let n=e.memoizedState;for(;n;){if(n.memoizedState===t)return!0;n=n.next}});if(e)return e}},[e,t])}var o_=Symbol.for(`react.context`),s_=e=>typeof e==`object`&&!!e&&`$$typeof`in e&&e.$$typeof===o_;function c_(){let e=a_(),[t]=y.useState(()=>new Map);t.clear();let n=e;for(;n;){let e=n.type;s_(e)&&e!==r_&&!t.has(e)&&t.set(e,y.use(n_(e))),n=n.return}return t}function l_(){let e=c_();return y.useMemo(()=>Array.from(e.keys()).reduce((t,n)=>r=>y.createElement(t,null,y.createElement(n.Provider,{...r,value:e.get(n)})),e=>y.createElement(i_,{...e})),[e])}function u_(e){let t=e.root;for(;t.getState().previousRoot;)t=t.getState().previousRoot;return t}y.act;var d_=e=>e&&e.isOrthographicCamera,f_=e=>e&&e.hasOwnProperty(`current`),p_=e=>e!=null&&(typeof e==`string`||typeof e==`number`||e.isColor),m_=((e,t)=>typeof window<`u`&&((e=window.document)?.createElement||(t=window.navigator)?.product===`ReactNative`))()?y.useLayoutEffect:y.useEffect;function h_(e){let t=y.useRef(e);return m_(()=>void(t.current=e),[e]),t}function g_(){let e=a_(),t=l_();return y.useMemo(()=>({children:n})=>(0,N.jsx)(t_(e,!0,e=>e.type===y.StrictMode)?y.StrictMode:y.Fragment,{children:(0,N.jsx)(t,{children:n})}),[e,t])}function __({set:e}){return m_(()=>(e(new Promise(()=>null)),()=>e(!1)),[e]),null}var v_=(e=>(e=class extends y.Component{constructor(...e){super(...e),this.state={error:!1}}componentDidCatch(e){this.props.set(e)}render(){return this.state.error?null:this.props.children}},e.getDerivedStateFromError=()=>({error:!0}),e))();function y_(e){let t=typeof window<`u`?window.devicePixelRatio??2:1;return Array.isArray(e)?Math.min(Math.max(e[0],t),e[1]):e}function b_(e){return e.__r3f?.root.getState()}var x_={obj:e=>e===Object(e)&&!x_.arr(e)&&typeof e!=`function`,fun:e=>typeof e==`function`,str:e=>typeof e==`string`,num:e=>typeof e==`number`,boo:e=>typeof e==`boolean`,und:e=>e===void 0,nul:e=>e===null,arr:e=>Array.isArray(e),equ(e,t,{arrays:n=`shallow`,objects:r=`reference`,strict:i=!0}={}){if(typeof e!=typeof t||!!e!=!!t)return!1;if(x_.str(e)||x_.num(e)||x_.boo(e))return e===t;let a=x_.obj(e);if(a&&r===`reference`)return e===t;let o=x_.arr(e);if(o&&n===`reference`)return e===t;if((o||a)&&e===t)return!0;let s;for(s in e)if(!(s in t))return!1;if(a&&n===`shallow`&&r===`shallow`){for(s in i?t:e)if(!x_.equ(e[s],t[s],{strict:i,objects:`reference`}))return!1}else for(s in i?t:e)if(e[s]!==t[s])return!1;if(x_.und(s)){if(o&&e.length===0&&t.length===0||a&&Object.keys(e).length===0&&Object.keys(t).length===0)return!0;if(e!==t)return!1}return!0}};function S_(e){let t={nodes:{},materials:{},meshes:{}};return e&&e.traverse(e=>{e.name&&(t.nodes[e.name]=e),e.material&&!t.materials[e.material.name]&&(t.materials[e.material.name]=e.material),e.isMesh&&!t.meshes[e.name]&&(t.meshes[e.name]=e)}),t}function C_(e){e.type!==`Scene`&&(e.dispose==null||e.dispose());for(let t in e){let n=e[t];n?.type!==`Scene`&&(n==null||n.dispose==null||n.dispose())}}var w_=[`children`,`key`,`ref`];function T_(e){let t={};for(let n in e)w_.includes(n)||(t[n]=e[n]);return t}function E_(e,t,n,r){let i=e,a=i?.__r3f;return a||(a={root:t,type:n,parent:null,children:[],props:T_(r),object:i,eventCount:0,handlers:{},isHidden:!1},i&&(i.__r3f=a)),a}function D_(e,t){if(!t.includes(`-`)||t in e)return{root:e,key:t,target:e[t]};let n=e,r=t.split(`-`);for(let i of r){if(typeof n!=`object`||!n){if(n!==void 0){let e=r.slice(r.indexOf(i)).join(`-`);return{root:n,key:e,target:void 0}}return{root:e,key:t,target:void 0}}t=i,e=n,n=n[t]}return{root:e,key:t,target:n}}var O_=/-\d+$/;function k_(e,t){if(x_.str(t.props.attach)){if(O_.test(t.props.attach)){let n=t.props.attach.replace(O_,``),{root:r,key:i}=D_(e.object,n);Array.isArray(r[i])||(r[i]=[])}let{root:n,key:r}=D_(e.object,t.props.attach);t.previousAttach=n[r],n[r]=t.object}else x_.fun(t.props.attach)&&(t.previousAttach=t.props.attach(e.object,t.object))}function A_(e,t){if(x_.str(t.props.attach)){let{root:n,key:r}=D_(e.object,t.props.attach),i=t.previousAttach;i===void 0?delete n[r]:n[r]=i}else t.previousAttach==null||t.previousAttach(e.object,t.object);delete t.previousAttach}var j_=[...w_,`args`,`dispose`,`attach`,`object`,`onUpdate`,`dispose`],M_=new Map;function N_(e){let t=M_.get(e.constructor);try{t||(t=new e.constructor,M_.set(e.constructor,t))}catch{}return t}function P_(e,t){let n={};for(let r in t)if(!j_.includes(r)&&!x_.equ(t[r],e.props[r])){n[r]=t[r];for(let e in t)e.startsWith(`${r}-`)&&(n[e]=t[e])}for(let r in e.props){if(j_.includes(r)||t.hasOwnProperty(r))continue;let{root:i,key:a}=D_(e.object,r);if(i.constructor&&i.constructor.length===0){let e=N_(i);x_.und(e)||(n[a]=e[a])}else n[a]=0}return n}var F_=[`map`,`emissiveMap`,`sheenColorMap`,`specularColorMap`,`envMap`],I_=/^on(Pointer|Click|DoubleClick|ContextMenu|Wheel)/;function L_(e,t){var n;let r=e.__r3f,i=r&&u_(r).getState(),a=r?.eventCount;for(let n in t){let a=t[n];if(j_.includes(n))continue;if(r&&I_.test(n)){typeof a==`function`?r.handlers[n]=a:delete r.handlers[n],r.eventCount=Object.keys(r.handlers).length;continue}if(a===void 0)continue;let{root:s,key:c,target:l}=D_(e,n);if(l===void 0&&(typeof s!=`object`||!s))throw Error(`R3F: Cannot set "${n}". Ensure it is an object before setting "${c}".`);if(l instanceof Gr&&a instanceof Gr)l.mask=a.mask;else if(l instanceof U&&p_(a))l.set(a);else if(typeof l==`object`&&l&&typeof l.set==`function`&&typeof l.copy==`function`&&a!=null&&a.constructor&&l.constructor===a.constructor)l.copy(a);else if(typeof l==`object`&&l&&typeof l.set==`function`&&Array.isArray(a))typeof l.fromArray==`function`?l.fromArray(a):l.set(...a);else if(typeof l==`object`&&l&&typeof l.set==`function`&&typeof a==`number`)typeof l.setScalar==`function`?l.setScalar(a):l.set(a);else{var o;s[c]=a,i&&!i.linear&&F_.includes(c)&&(o=s[c])!=null&&o.isTexture&&s[c].format===1023&&s[c].type===1009&&(s[c].colorSpace=Wt)}}if(r!=null&&r.parent&&i!=null&&i.internal&&(n=r.object)!=null&&n.isObject3D&&a!==r.eventCount){let e=r.object,t=i.internal.interaction.indexOf(e);t>-1&&i.internal.interaction.splice(t,1),r.eventCount&&e.raycast!==null&&i.internal.interaction.push(e)}return r&&r.props.attach===void 0&&(r.object.isBufferGeometry?r.props.attach=`geometry`:r.object.isMaterial&&(r.props.attach=`material`)),r&&R_(r),e}function R_(e){var t;if(!e.parent)return;e.props.onUpdate==null||e.props.onUpdate(e.object);let n=(t=e.root)==null||t.getState==null?void 0:t.getState();n&&n.internal.frames===0&&n.invalidate()}function z_(e,t){e.manual||(d_(e)?(e.left=t.width/-2,e.right=t.width/2,e.top=t.height/2,e.bottom=t.height/-2):e.aspect=t.width/t.height,e.updateProjectionMatrix())}var B_=e=>e?.isObject3D;function V_(e){return(e.eventObject||e.object).uuid+`/`+e.index+e.instanceId}function H_(e,t,n,r){let i=n.get(t);i&&(n.delete(t),n.size===0&&(e.delete(r),i.target.releasePointerCapture(r)))}function U_(e,t){let{internal:n}=e.getState();n.interaction=n.interaction.filter(e=>e!==t),n.initialHits=n.initialHits.filter(e=>e!==t),n.hovered.forEach((e,r)=>{(e.eventObject===t||e.object===t)&&n.hovered.delete(r)}),n.capturedMap.forEach((e,r)=>{H_(n.capturedMap,t,e,r)})}function W_(e){function t(t){let{internal:n}=e.getState(),r=t.offsetX-n.initialClick[0],i=t.offsetY-n.initialClick[1];return Math.round(Math.sqrt(r*r+i*i))}function n(e){return e.filter(e=>[`Move`,`Over`,`Enter`,`Out`,`Leave`].some(t=>e.__r3f?.handlers[`onPointer`+t]))}function r(t,n){let r=e.getState(),i=new Set,a=[],o=n?n(r.internal.interaction):r.internal.interaction;for(let e=0;e{let n=b_(e.object),r=b_(t.object);return!n||!r?e.distance-t.distance:r.events.priority-n.events.priority||e.distance-t.distance}).filter(e=>{let t=V_(e);return i.has(t)?!1:(i.add(t),!0)});r.events.filter&&(c=r.events.filter(c,r));for(let e of c){let t=e.object;for(;t;){var l;(l=t.__r3f)!=null&&l.eventCount&&a.push({...e,eventObject:t}),t=t.parent}}if(`pointerId`in t&&r.internal.capturedMap.has(t.pointerId))for(let e of r.internal.capturedMap.get(t.pointerId).values())i.has(V_(e.intersection))||a.push(e.intersection);return a}function i(e,t,n,r){if(e.length){let i={stopped:!1};for(let o of e){let s=b_(o.object);if(s||o.object.traverseAncestors(e=>{let t=b_(e);if(t)return s=t,!1}),s){let{raycaster:c,pointer:l,camera:u,internal:d}=s,f=new H(l.x,l.y,0).unproject(u),p=e=>d.capturedMap.get(e)?.has(o.eventObject)??!1,m=e=>{let n={intersection:o,target:t.target};d.capturedMap.has(e)?d.capturedMap.get(e).set(o.eventObject,n):d.capturedMap.set(e,new Map([[o.eventObject,n]])),t.target.setPointerCapture(e)},h=e=>{let t=d.capturedMap.get(e);t&&H_(d.capturedMap,o.eventObject,t,e)},g={};for(let e in t){let n=t[e];typeof n!=`function`&&(g[e]=n)}let _={...o,...g,pointer:l,intersections:e,stopped:i.stopped,delta:n,unprojectedPoint:f,ray:c.ray,camera:u,stopPropagation(){let n=`pointerId`in t&&d.capturedMap.get(t.pointerId);(!n||n.has(o.eventObject))&&(_.stopped=i.stopped=!0,d.hovered.size&&Array.from(d.hovered.values()).find(e=>e.eventObject===o.eventObject)&&a([...e.slice(0,e.indexOf(o)),o]))},target:{hasPointerCapture:p,setPointerCapture:m,releasePointerCapture:h},currentTarget:{hasPointerCapture:p,setPointerCapture:m,releasePointerCapture:h},nativeEvent:t};if(r(_),i.stopped===!0)break}}}return e}function a(t){let{internal:n}=e.getState();for(let e of n.hovered.values())if(!t.length||!t.find(t=>t.object===e.object&&t.index===e.index&&t.instanceId===e.instanceId)){let r=e.eventObject.__r3f;if(n.hovered.delete(V_(e)),r!=null&&r.eventCount){let n=r.handlers,i={...e,intersections:t};n.onPointerOut==null||n.onPointerOut(i),n.onPointerLeave==null||n.onPointerLeave(i)}}}function o(e,t){for(let n=0;na([]);case`onLostPointerCapture`:return t=>{let{internal:n}=e.getState();`pointerId`in t&&n.capturedMap.has(t.pointerId)&&requestAnimationFrame(()=>{n.capturedMap.has(t.pointerId)&&(n.capturedMap.delete(t.pointerId),a([]))})}}return function(c){let{onPointerMissed:l,internal:u}=e.getState();u.lastEvent.current=c;let d=s===`onPointerMove`,f=s===`onClick`||s===`onContextMenu`||s===`onDoubleClick`,p=r(c,d?n:void 0),m=f?t(c):0;s===`onPointerDown`&&(u.initialClick=[c.offsetX,c.offsetY],u.initialHits=p.map(e=>e.eventObject)),f&&!p.length&&m<=2&&(o(c,u.interaction),l&&l(c)),d&&a(p);function h(e){let t=e.eventObject,n=t.__r3f;if(!(n!=null&&n.eventCount))return;let r=n.handlers;if(d){if(r.onPointerOver||r.onPointerEnter||r.onPointerOut||r.onPointerLeave){let t=V_(e),n=u.hovered.get(t);n?n.stopped&&e.stopPropagation():(u.hovered.set(t,e),r.onPointerOver==null||r.onPointerOver(e),r.onPointerEnter==null||r.onPointerEnter(e))}r.onPointerMove==null||r.onPointerMove(e)}else{let n=r[s];n?(!f||u.initialHits.includes(t))&&(o(c,u.interaction.filter(e=>!u.initialHits.includes(e))),n(e)):f&&u.initialHits.includes(t)&&o(c,u.interaction.filter(e=>!u.initialHits.includes(e)))}}i(p,c,m,h)}}return{handlePointer:s}}var G_=e=>!!(e!=null&&e.render),K_=y.createContext(null),q_=(e,t)=>{let n=Kg((n,r)=>{let i=new H,a=new H,o=new H;function s(e=r().camera,t=a,n=r().size){let{width:s,height:c,top:l,left:u}=n,d=s/c;t.isVector3?o.copy(t):o.set(...t);let f=e.getWorldPosition(i).distanceTo(o);if(d_(e))return{width:s/e.zoom,height:c/e.zoom,top:l,left:u,factor:1,distance:f,aspect:d};{let t=e.fov*Math.PI/180,n=2*Math.tan(t/2)*f,r=s/c*n;return{width:r,height:n,top:l,left:u,factor:s/r,distance:f,aspect:d}}}let c,l=e=>n(t=>({performance:{...t.performance,current:e}})),u=new V;return{set:n,get:r,gl:null,camera:null,raycaster:null,events:{priority:1,enabled:!0,connected:!1},scene:null,xr:null,invalidate:(t=1)=>e(r(),t),advance:(e,n)=>t(e,n,r()),legacy:!1,linear:!1,flat:!1,controls:null,clock:new bf,pointer:u,mouse:u,frameloop:`always`,onPointerMissed:void 0,performance:{current:1,min:.5,max:1,debounce:200,regress:()=>{let e=r();c&&clearTimeout(c),e.performance.current!==e.performance.min&&l(e.performance.min),c=setTimeout(()=>l(r().performance.max),e.performance.debounce)}},size:{width:0,height:0,top:0,left:0},viewport:{initialDpr:0,dpr:0,width:0,height:0,top:0,left:0,aspect:0,distance:0,factor:0,getCurrentViewport:s},setEvents:e=>n(t=>({...t,events:{...t.events,...e}})),setSize:(e,t,i=0,o=0)=>{let c=r().camera,l={width:e,height:t,top:i,left:o};n(e=>({size:l,viewport:{...e.viewport,...s(c,a,l)}}))},setDpr:e=>n(t=>{let n=y_(e);return{viewport:{...t.viewport,dpr:n,initialDpr:t.viewport.initialDpr||n}}}),setFrameloop:(e=`always`)=>{let t=r().clock;t.stop(),t.elapsedTime=0,e!==`never`&&(t.start(),t.elapsedTime=0),n(()=>({frameloop:e}))},previousRoot:void 0,internal:{interaction:[],hovered:new Map,subscribers:[],initialClick:[0,0],initialHits:[],capturedMap:new Map,lastEvent:y.createRef(),active:!1,frames:0,priority:0,subscribe:(e,t,n)=>{let i=r().internal;return i.priority+=t>0?1:0,i.subscribers.push({ref:e,priority:t,store:n}),i.subscribers=i.subscribers.sort((e,t)=>e.priority-t.priority),()=>{let n=r().internal;n!=null&&n.subscribers&&(n.priority-=t>0?1:0,n.subscribers=n.subscribers.filter(t=>t.ref!==e))}}}}}),r=n.getState(),i=r.size,a=r.viewport.dpr,o=r.camera;return n.subscribe(()=>{let{camera:e,size:t,viewport:r,gl:s,set:c}=n.getState();if(t.width!==i.width||t.height!==i.height||r.dpr!==a){i=t,a=r.dpr,z_(e,t),r.dpr>0&&s.setPixelRatio(r.dpr);let n=typeof HTMLCanvasElement<`u`&&s.domElement instanceof HTMLCanvasElement;s.setSize(t.width,t.height,n)}e!==o&&(o=e,c(t=>({viewport:{...t.viewport,...t.viewport.getCurrentViewport(e)}})))}),n.subscribe(t=>e(t)),n};function J_(){let e=y.useContext(K_);if(!e)throw Error(`R3F: Hooks can only be used within the Canvas component!`);return e}function Y_(e=e=>e,t){return J_()(e,t)}function X_(e,t=0){let n=J_(),r=n.getState().internal.subscribe,i=h_(e);return m_(()=>r(i,t,n),[t,r,n]),null}var Z_=new WeakMap,Q_=e=>typeof e==`function`&&e?.prototype?.constructor===e;function $_(e,t){return function(n,...r){let i;return Q_(n)?(i=Z_.get(n),i||(i=new n,Z_.set(n,i))):i=n,e&&e(i),Promise.all(r.map(e=>new Promise((n,r)=>i.load(e,e=>{B_(e?.scene)&&Object.assign(e,S_(e.scene)),n(e)},t,t=>r(Error(`Could not load ${e}: ${t?.message}`))))))}}function ev(e,t,n,r){let i=Array.isArray(t)?t:[t],a=Zg($_(n,r),[e,...i],{equal:x_.equ});return Array.isArray(t)?a:a[0]}ev.preload=function(e,t,n){let r=Array.isArray(t)?t:[t];return Qg($_(n),[e,...r])},ev.clear=function(e,t){return $g([e,...Array.isArray(t)?t:[t]])};var tv=1,nv=8,rv=32,iv=2,av={name:`@react-three/fiber`,version:`9.5.0`,description:`A React renderer for Threejs`,keywords:[`react`,`renderer`,`fiber`,`three`,`threejs`],author:`Paul Henschel (https://github.com/drcmda)`,license:`MIT`,maintainers:[`Josh Ellis (https://github.com/joshuaellis)`,`Cody Bennett (https://github.com/codyjasonbennett)`,`Kris Baumgarter (https://github.com/krispya)`],bugs:{url:`https://github.com/pmndrs/react-three-fiber/issues`},homepage:`https://github.com/pmndrs/react-three-fiber#readme`,repository:{type:`git`,url:`git+https://github.com/pmndrs/react-three-fiber.git`},collective:{type:`opencollective`,url:`https://opencollective.com/react-three-fiber`},main:`dist/react-three-fiber.cjs.js`,module:`dist/react-three-fiber.esm.js`,types:`dist/react-three-fiber.cjs.d.ts`,"react-native":`native/dist/react-three-fiber-native.cjs.js`,sideEffects:!1,preconstruct:{entrypoints:[`index.tsx`,`native.tsx`]},scripts:{prebuild:`cp ../../readme.md readme.md`},devDependencies:{"@types/react-reconciler":`^0.32.3`,"react-reconciler":`^0.33.0`},dependencies:{"@babel/runtime":`^7.17.8`,"@types/webxr":`*`,"base64-js":`^1.5.1`,buffer:`^6.0.3`,"its-fine":`^2.0.0`,"react-use-measure":`^2.1.7`,scheduler:`^0.27.0`,"suspend-react":`^0.1.3`,"use-sync-external-store":`^1.4.0`,zustand:`^5.0.3`},peerDependencies:{expo:`>=43.0`,"expo-asset":`>=8.4`,"expo-file-system":`>=11.0`,"expo-gl":`>=11.0`,react:`>=19 <19.3`,"react-dom":`>=19 <19.3`,"react-native":`>=0.78`,three:`>=0.156`},peerDependenciesMeta:{"react-dom":{optional:!0},"react-native":{optional:!0},expo:{optional:!0},"expo-asset":{optional:!0},"expo-file-system":{optional:!0},"expo-gl":{optional:!0}}};function ov(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,`default`)?e.default:e}var sv={exports:{}},cv={exports:{}};cv.exports;var lv;function uv(){return lv||(lv=1,function(e){e.exports=function(e){function t(e,t,n,r){return new K(e,t,n,r)}function n(){}function r(e){var t=`https://react.dev/errors/`+e;if(1fc||(e.current=dc[fc],dc[fc]=null,fc--)}function p(e,t){fc++,dc[fc]=e.current,e.current=t}function m(e){return e>>>=0,e===0?32:31-(hc(e)/gc|0)|0}function h(e){var t=e&42;if(t!==0)return t;switch(e&-e){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:return 64;case 128:return 128;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:return e&261888;case 262144:case 524288:case 1048576:case 2097152:return e&3932160;case 4194304:case 8388608:case 16777216:case 33554432:return e&62914560;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return e}}function g(e,t,n){var r=e.pendingLanes;if(r===0)return 0;var i=0,a=e.suspendedLanes,o=e.pingedLanes;e=e.warmLanes;var s=r&134217727;return s===0?(s=r&~a,s===0?o===0?n||(n=r&~e,n!==0&&(i=h(n))):i=h(o):i=h(s)):(r=s&~a,r===0?(o&=s,o===0?n||(n=s&~e,n!==0&&(i=h(n))):i=h(o)):i=h(r)),i===0?0:t!==0&&t!==i&&(t&a)===0&&(a=i&-i,n=t&-t,a>=n||a===32&&n&4194048)?t:i}function _(e,t){return(e.pendingLanes&~(e.suspendedLanes&~e.pingedLanes)&t)===0}function v(e,t){switch(e){case 1:case 2:case 4:case 8:case 64:return t+250;case 16:case 32:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return t+5e3;case 4194304:case 8388608:case 16777216:case 33554432:return-1;case 67108864:case 134217728:case 268435456:case 536870912:case 1073741824:return-1;default:return-1}}function b(){var e=yc;return yc<<=1,!(yc&62914560)&&(yc=4194304),e}function x(e){for(var t=[],n=0;31>n;n++)t.push(e);return t}function S(e,t){e.pendingLanes|=t,t!==268435456&&(e.suspendedLanes=0,e.pingedLanes=0,e.warmLanes=0)}function C(e,t,n,r,i,a){var o=e.pendingLanes;e.pendingLanes=n,e.suspendedLanes=0,e.pingedLanes=0,e.warmLanes=0,e.expiredLanes&=n,e.entangledLanes&=n,e.errorRecoveryDisabledLanes&=n,e.shellSuspendCounter=0;var s=e.entanglements,c=e.expirationTimes,l=e.hiddenUpdates;for(n=o&~n;0)`:-1i||c[r]!==l[i]){var u=` +`+c[r].replace(` at new `,` at `);return e.displayName&&u.includes(``)&&(u=u.replace(``,e.displayName)),u}while(1<=r&&0<=i);break}}}finally{Rc=!1,Error.prepareStackTrace=n}return(n=e?e.displayName||e.name:``)?j(n):``}function M(e,t){switch(e.tag){case 26:case 27:case 5:return j(e.type);case 16:return j(`Lazy`);case 13:return e.child!==t&&t!==null?j(`Suspense Fallback`):j(`Suspense`);case 19:return j(`SuspenseList`);case 0:case 15:return ee(e.type,!1);case 11:return ee(e.type.render,!1);case 1:return ee(e.type,!0);case 31:return j(`Activity`);default:return``}}function N(e){try{var t=``,n=null;do t+=M(e,n),n=e,e=e.return;while(e);return t}catch(e){return` +Error generating stack: `+e.message+` +`+e.stack}}function P(e,t){if(typeof e==`object`&&e){var n=zc.get(e);return n===void 0?(t={value:e,source:t,stack:N(t)},zc.set(e,t),t):n}return{value:e,source:t,stack:N(t)}}function F(e,t){Bc[Vc++]=Uc,Bc[Vc++]=Hc,Hc=e,Uc=t}function te(e,t,n){Wc[Gc++]=qc,Wc[Gc++]=Jc,Wc[Gc++]=Kc,Kc=e;var r=qc;e=Jc;var i=32-mc(r)-1;r&=~(1<>=o,i-=o,qc=1<<32-mc(t)+i|n<f?(p=d,d=null):p=d.sibling;var _=h(t,d,o[f],c);if(_===null){d===null&&(d=p);break}e&&d&&_.alternate===null&&n(t,d),r=s(_,r,f),u===null?l=_:u.sibling=_,u=_,d=p}if(f===o.length)return i(t,d),tl&&F(t,f),l;if(d===null){for(;fp?(_=f,f=null):_=f.sibling;var y=h(t,f,v.value,l);if(y===null){f===null&&(f=_);break}e&&f&&y.alternate===null&&n(t,f),o=s(y,o,p),d===null?u=y:d.sibling=y,d=y,f=_}if(v.done)return i(t,f),tl&&F(t,p),u;if(f===null){for(;!v.done;p++,v=c.next())v=m(t,v.value,l),v!==null&&(o=s(v,o,p),d===null?u=v:d.sibling=v,d=v);return tl&&F(t,p),u}for(f=a(f);!v.done;p++,v=c.next())v=g(f,t,p,v.value,l),v!==null&&(e&&v.alternate!==null&&f.delete(v.key===null?p:v.key),o=s(v,o,p),d===null?u=v:d.sibling=v,d=v);return e&&f.forEach(function(e){return n(t,e)}),tl&&F(t,p),u}function y(e,t,a,s){if(typeof a==`object`&&a&&a.type===ja&&a.key===null&&(a=a.props.children),typeof a==`object`&&a){switch(a.$$typeof){case ka:e:{for(var u=a.key;t!==null;){if(t.key===u){if(u=a.type,u===ja){if(t.tag===7){i(e,t.sibling),s=o(t,a.props.children),s.return=e,e=s;break e}}else if(t.elementType===u||typeof u==`object`&&u&&u.$$typeof===Ba&&Ue(u)===t.type){i(e,t.sibling),s=o(t,a.props),qe(s,a),s.return=e,e=s;break e}i(e,t);break}else n(e,t);t=t.sibling}a.type===ja?(s=pa(a.props.children,e.mode,s,a.key),s.return=e,e=s):(s=fa(a.type,a.key,a.props,null,e.mode,s),qe(s,a),s.return=e,e=s)}return c(e);case Aa:e:{for(u=a.key;t!==null;){if(t.key===u)if(t.tag===4&&t.stateNode.containerInfo===a.containerInfo&&t.stateNode.implementation===a.implementation){i(e,t.sibling),s=o(t,a.children||[]),s.return=e,e=s;break e}else{i(e,t);break}else n(e,t);t=t.sibling}s=ga(a,e.mode,s),s.return=e,e=s}return c(e);case Ba:return a=Ue(a),y(e,t,a,s)}if(Ga(a))return _(e,t,a,s);if(l(a)){if(u=l(a),typeof u!=`function`)throw Error(r(150));return a=u.call(a),v(e,t,a,s)}if(typeof a.then==`function`)return y(e,t,Ke(a),s);if(a.$$typeof===Fa)return y(e,t,be(e,a),s);Je(e,a)}return typeof a==`string`&&a!==``||typeof a==`number`||typeof a==`bigint`?(a=``+a,t!==null&&t.tag===6?(i(e,t.sibling),s=o(t,a),s.return=e,e=s):(i(e,t),s=ma(a,e.mode,s),s.return=e,e=s),c(e)):i(e,t)}return function(e,n,r,i){try{Al=0;var a=y(e,n,r,i);return kl=null,a}catch(n){if(n===wl||n===El)throw n;var o=t(29,n,null,e.mode);return o.lanes=i,o.return=e,o}}}function Xe(){for(var e=Pl,t=Fl=Pl=0;ta?a:8);var o=Ka.T,s={};Ka.T=s,Mn(e,!1,t,n);try{var c=i(),l=Ka.S;l!==null&&l(s,c),typeof c==`object`&&c&&typeof c.then==`function`?jn(e,t,Ie(c,r),Ei(e)):jn(e,t,r,Ei(e))}catch(n){jn(e,t,{then:function(){},status:`rejected`,reason:n},Ei())}finally{go(a),o!==null&&s.types!==null&&(o.types=s.types),Ka.T=o}}function Tn(e){var t=e.memoizedState;if(t!==null)return t;t={memoizedState:Oo,baseState:Oo,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:It,lastRenderedState:Oo},next:null};var n={};return t.next={memoizedState:n,baseState:n,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:It,lastRenderedState:n},next:null},e.memoizedState=t,e=e.alternate,e!==null&&(e.memoizedState=t),t}function En(){return z(ko)}function Dn(){return jt().memoizedState}function On(){return jt().memoizedState}function kn(e){for(var t=e.return;t!==null;){switch(t.tag){case 24:case 3:var n=Ei();e=it(n);var r=at(t,e,n);r!==null&&(Oi(r,t,n),ot(r,t,n)),t={cache:Se()},e.payload=t;return}t=t.return}}function B(e,t,n){var r=Ei();n={lane:r,revertLane:0,gesture:null,action:n,hasEagerState:!1,eagerState:null,next:null},Nn(e)?Pn(t,n):(n=Qe(e,t,n,r),n!==null&&(Oi(n,e,r),Fn(n,t,r)))}function An(e,t,n){jn(e,t,n,Ei())}function jn(e,t,n,r){var i={lane:r,revertLane:0,gesture:null,action:n,hasEagerState:!1,eagerState:null,next:null};if(Nn(e))Pn(t,i);else{var a=e.alternate;if(e.lanes===0&&(a===null||a.lanes===0)&&(a=t.lastRenderedReducer,a!==null))try{var o=t.lastRenderedState,s=a(o,n);if(i.hasEagerState=!0,i.eagerState=s,Nc(s,o))return Ze(e,t,i,0),Tu===null&&Xe(),!1}catch{}if(n=Qe(e,t,i,r),n!==null)return Oi(n,e,r),Fn(n,t,r),!0}return!1}function Mn(e,t,n,i){if(i={lane:2,revertLane:Ne(),gesture:null,action:i,hasEagerState:!1,eagerState:null,next:null},Nn(e)){if(t)throw Error(r(479))}else t=Qe(e,n,i,2),t!==null&&Oi(t,e,2)}function Nn(e){var t=e.alternate;return e===q||t!==null&&t===q}function Pn(e,t){ql=Kl=!0;var n=e.pending;n===null?t.next=t:(t.next=n.next,n.next=t),e.pending=t}function Fn(e,t,n){if(n&4194048){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,T(e,n)}}function In(e,t,n,r){t=e.memoizedState,n=n(r,t),n=n==null?t:Da({},t,n),e.memoizedState=n,e.lanes===0&&(e.updateQueue.baseState=n)}function Ln(e,t,n,r,i,a,o){return e=e.stateNode,typeof e.shouldComponentUpdate==`function`?e.shouldComponentUpdate(r,a,o):t.prototype&&t.prototype.isPureReactComponent?!Be(n,r)||!Be(i,a):!0}function Rn(e,t,n,r){e=t.state,typeof t.componentWillReceiveProps==`function`&&t.componentWillReceiveProps(n,r),typeof t.UNSAFE_componentWillReceiveProps==`function`&&t.UNSAFE_componentWillReceiveProps(n,r),t.state!==e&&ru.enqueueReplaceState(t,t.state,null)}function zn(e,t){var n=t;if(`ref`in t)for(var r in n={},t)r!==`ref`&&(n[r]=t[r]);if(e=e.defaultProps)for(var i in n===t&&(n=Da({},n)),e)n[i]===void 0&&(n[i]=e[i]);return n}function Bn(e,t){try{var n=e.onUncaughtError;n(t.value,{componentStack:t.stack})}catch(e){setTimeout(function(){throw e})}}function Vn(e,t,n){try{var r=e.onCaughtError;r(n.value,{componentStack:n.stack,errorBoundary:t.tag===1?t.stateNode:null})}catch(e){setTimeout(function(){throw e})}}function Hn(e,t,n){return n=it(n),n.tag=3,n.payload={element:null},n.callback=function(){Bn(e,t)},n}function Un(e){return e=it(e),e.tag=3,e}function Wn(e,t,n,r){var i=n.type.getDerivedStateFromError;if(typeof i==`function`){var a=r.value;e.payload=function(){return i(a)},e.callback=function(){Vn(t,n,r)}}var o=n.stateNode;o!==null&&typeof o.componentDidCatch==`function`&&(e.callback=function(){Vn(t,n,r),typeof i!=`function`&&(qu===null?qu=new Set([this]):qu.add(this));var e=r.stack;this.componentDidCatch(r.value,{componentStack:e===null?``:e})})}function Gn(e,t,n,i,a){if(n.flags|=32768,typeof i==`object`&&i&&typeof i.then==`function`){if(t=n.alternate,t!==null&&ye(t,n,a,!0),n=Bl.current,n!==null){switch(n.tag){case 31:case 13:return Vl===null?Bi():n.alternate===null&&Pu===0&&(Pu=3),n.flags&=-257,n.flags|=65536,n.lanes=a,i===Dl?n.flags|=16384:(t=n.updateQueue,t===null?n.updateQueue=new Set([i]):t.add(i),ra(e,i,a)),!1;case 22:return n.flags|=65536,i===Dl?n.flags|=16384:(t=n.updateQueue,t===null?(t={transitions:null,markerInstances:null,retryQueue:new Set([i])},n.updateQueue=t):(n=t.retryQueue,n===null?t.retryQueue=new Set([i]):n.add(i)),ra(e,i,a)),!1}throw Error(r(435,n.tag))}return ra(e,i,a),Bi(),!1}if(tl)return t=Bl.current,t===null?(i!==il&&(t=Error(r(423),{cause:i}),he(P(t,n))),e=e.current.alternate,e.flags|=65536,a&=-a,e.lanes|=a,i=P(i,n),a=Hn(e.stateNode,i,a),st(e,a),Pu!==4&&(Pu=2)):(!(t.flags&65536)&&(t.flags|=256),t.flags|=65536,t.lanes=a,i!==il&&(e=Error(r(422),{cause:i}),he(P(e,n)))),!1;var o=Error(r(520),{cause:i});if(o=P(o,n),Bu===null?Bu=[o]:Bu.push(o),Pu!==4&&(Pu=2),t===null)return!0;i=P(i,n),n=t;do{switch(n.tag){case 3:return n.flags|=65536,e=a&-a,n.lanes|=e,e=Hn(n.stateNode,i,e),st(n,e),!1;case 1:if(t=n.type,o=n.stateNode,!(n.flags&128)&&(typeof t.getDerivedStateFromError==`function`||o!==null&&typeof o.componentDidCatch==`function`&&(qu===null||!qu.has(o))))return n.flags|=65536,a&=-a,n.lanes|=a,a=Un(a),Wn(a,e,n,i),st(n,a),!1}n=n.return}while(n!==null);return!1}function Kn(e,t,n,r){t.child=e===null?Ml(t,null,n,r):jl(t,e.child,n,r)}function qn(e,t,n,r,i){n=n.render;var a=t.ref;if(`ref`in r){var o={};for(var s in r)s!==`ref`&&(o[s]=r[s])}else o=r;return R(t),r=Ct(e,t,n,o,a,i),s=Dt(),e!==null&&!au?(Ot(e,t,i),mr(e,t,i)):(tl&&s&&ne(t),t.flags|=1,Kn(e,t,r,i),t.child)}function Jn(e,t,n,r,i){if(e===null){var a=n.type;return typeof a==`function`&&!la(a)&&a.defaultProps===void 0&&n.compare===null?(t.tag=15,t.type=a,Yn(e,t,a,r,i)):(e=fa(n.type,null,r,t,t.mode,i),e.ref=t.ref,e.return=t,t.child=e)}if(a=e.child,!hr(e,i)){var o=a.memoizedProps;if(n=n.compare,n=n===null?Be:n,n(o,r)&&e.ref===t.ref)return mr(e,t,i)}return t.flags|=1,e=ua(a,r),e.ref=t.ref,e.return=t,t.child=e}function Yn(e,t,n,r,i){if(e!==null){var a=e.memoizedProps;if(Be(a,r)&&e.ref===t.ref)if(au=!1,t.pendingProps=r=a,hr(e,i))e.flags&131072&&(au=!0);else return t.lanes=e.lanes,mr(e,t,i)}return rr(e,t,n,r,i)}function Xn(e,t,n,r){var i=r.children,a=e===null?null:e.memoizedState;if(e===null&&t.stateNode===null&&(t.stateNode={_visibility:1,_pendingMarkers:null,_retryCache:null,_transitions:null}),r.mode===`hidden`){if(t.flags&128){if(a=a===null?n:a.baseLanes|n,e!==null){for(r=t.child=e.child,i=0;r!==null;)i=i|r.lanes|r.childLanes,r=r.sibling;r=i&~a}else r=0,t.child=null;return Qn(e,t,a,n,r)}if(n&536870912)t.memoizedState={baseLanes:0,cachePool:null},e!==null&&Re(t,a===null?null:a.cachePool),a===null?pt():ft(t,a),_t(t);else return r=t.lanes=536870912,Qn(e,t,a===null?n:a.baseLanes|n,n,r)}else a===null?(e!==null&&Re(t,null),pt(),vt()):(Re(t,a.cachePool),ft(t,a),vt(),t.memoizedState=null);return Kn(e,t,i,n),t.child}function Zn(e,t){return e!==null&&e.tag===22||t.stateNode!==null||(t.stateNode={_visibility:1,_pendingMarkers:null,_retryCache:null,_transitions:null}),t.sibling}function Qn(e,t,n,r,i){var a=Le();return a=a===null?null:{parent:lo?dl._currentValue:dl._currentValue2,pool:a},t.memoizedState={baseLanes:n,cachePool:a},e!==null&&Re(t,null),pt(),_t(t),e!==null&&ye(e,t,r,!0),t.childLanes=i,null}function $n(e,t){return t=lr({mode:t.mode,children:t.children},e.mode),t.ref=e.ref,e.child=t,t.return=e,t}function er(e,t,n){return jl(t,e.child,null,n),e=$n(t,t.pendingProps),e.flags|=2,yt(t),t.memoizedState=null,e}function tr(e,t,n){var i=t.pendingProps,a=(t.flags&128)!=0;if(t.flags&=-129,e===null){if(tl){if(i.mode===`hidden`)return e=$n(t,i),t.lanes=536870912,Zn(null,e);if(gt(t),(e=el)?(e=ws(e,rl),e!==null&&(t.memoizedState={dehydrated:e,treeContext:Kc===null?null:{id:qc,overflow:Jc},retryLane:536870912,hydrationErrors:null},n=ha(e),n.return=t,t.child=n,$c=t,el=null)):e=null,e===null)throw le(t);return t.lanes=536870912,null}return $n(t,i)}var o=e.memoizedState;if(o!==null){var s=o.dehydrated;if(gt(t),a)if(t.flags&256)t.flags&=-257,t=er(e,t,n);else if(t.memoizedState!==null)t.child=e.child,t.flags|=128,t=null;else throw Error(r(558));else if(au||ye(e,t,n,!1),a=(n&e.childLanes)!==0,au||a){if(i=Tu,i!==null&&(s=E(i,n),s!==0&&s!==o.retryLane))throw o.retryLane=s,$e(e,s),Oi(i,e,s),iu;Bi(),t=er(e,t,n)}else e=o.treeContext,po&&(el=ys(s),$c=t,tl=!0,nl=null,rl=!1,e!==null&&ie(t,e)),t=$n(t,i),t.flags|=4096;return t}return e=ua(e.child,{mode:i.mode,children:i.children}),e.ref=t.ref,t.child=e,e.return=t,e}function nr(e,t){var n=t.ref;if(n===null)e!==null&&e.ref!==null&&(t.flags|=4194816);else{if(typeof n!=`function`&&typeof n!=`object`)throw Error(r(284));(e===null||e.ref!==n)&&(t.flags|=4194816)}}function rr(e,t,n,r,i){return R(t),n=Ct(e,t,n,r,void 0,i),r=Dt(),e!==null&&!au?(Ot(e,t,i),mr(e,t,i)):(tl&&r&&ne(t),t.flags|=1,Kn(e,t,n,i),t.child)}function ir(e,t,n,r,i,a){return R(t),t.updateQueue=null,n=Tt(t,r,n,i),wt(e),r=Dt(),e!==null&&!au?(Ot(e,t,a),mr(e,t,a)):(tl&&r&&ne(t),t.flags|=1,Kn(e,t,n,a),t.child)}function ar(e,t,n,r,i){if(R(t),t.stateNode===null){var a=pc,o=n.contextType;typeof o==`object`&&o&&(a=z(o)),a=new n(r,a),t.memoizedState=a.state!==null&&a.state!==void 0?a.state:null,a.updater=ru,t.stateNode=a,a._reactInternals=t,a=t.stateNode,a.props=r,a.state=t.memoizedState,a.refs={},nt(t),o=n.contextType,a.context=typeof o==`object`&&o?z(o):pc,a.state=t.memoizedState,o=n.getDerivedStateFromProps,typeof o==`function`&&(In(t,n,o,r),a.state=t.memoizedState),typeof n.getDerivedStateFromProps==`function`||typeof a.getSnapshotBeforeUpdate==`function`||typeof a.UNSAFE_componentWillMount!=`function`&&typeof a.componentWillMount!=`function`||(o=a.state,typeof a.componentWillMount==`function`&&a.componentWillMount(),typeof a.UNSAFE_componentWillMount==`function`&&a.UNSAFE_componentWillMount(),o!==a.state&&ru.enqueueReplaceState(a,a.state,null),lt(t,r,a,i),ct(),a.state=t.memoizedState),typeof a.componentDidMount==`function`&&(t.flags|=4194308),r=!0}else if(e===null){a=t.stateNode;var s=t.memoizedProps,c=zn(n,s);a.props=c;var l=a.context,u=n.contextType;o=pc,typeof u==`object`&&u&&(o=z(u));var d=n.getDerivedStateFromProps;u=typeof d==`function`||typeof a.getSnapshotBeforeUpdate==`function`,s=t.pendingProps!==s,u||typeof a.UNSAFE_componentWillReceiveProps!=`function`&&typeof a.componentWillReceiveProps!=`function`||(s||l!==o)&&Rn(t,a,r,o),Il=!1;var f=t.memoizedState;a.state=f,lt(t,r,a,i),ct(),l=t.memoizedState,s||f!==l||Il?(typeof d==`function`&&(In(t,n,d,r),l=t.memoizedState),(c=Il||Ln(t,n,c,r,f,l,o))?(u||typeof a.UNSAFE_componentWillMount!=`function`&&typeof a.componentWillMount!=`function`||(typeof a.componentWillMount==`function`&&a.componentWillMount(),typeof a.UNSAFE_componentWillMount==`function`&&a.UNSAFE_componentWillMount()),typeof a.componentDidMount==`function`&&(t.flags|=4194308)):(typeof a.componentDidMount==`function`&&(t.flags|=4194308),t.memoizedProps=r,t.memoizedState=l),a.props=r,a.state=l,a.context=o,r=c):(typeof a.componentDidMount==`function`&&(t.flags|=4194308),r=!1)}else{a=t.stateNode,rt(e,t),o=t.memoizedProps,u=zn(n,o),a.props=u,d=t.pendingProps,f=a.context,l=n.contextType,c=pc,typeof l==`object`&&l&&(c=z(l)),s=n.getDerivedStateFromProps,(l=typeof s==`function`||typeof a.getSnapshotBeforeUpdate==`function`)||typeof a.UNSAFE_componentWillReceiveProps!=`function`&&typeof a.componentWillReceiveProps!=`function`||(o!==d||f!==c)&&Rn(t,a,r,c),Il=!1,f=t.memoizedState,a.state=f,lt(t,r,a,i),ct();var p=t.memoizedState;o!==d||f!==p||Il||e!==null&&e.dependencies!==null&&L(e.dependencies)?(typeof s==`function`&&(In(t,n,s,r),p=t.memoizedState),(u=Il||Ln(t,n,u,r,f,p,c)||e!==null&&e.dependencies!==null&&L(e.dependencies))?(l||typeof a.UNSAFE_componentWillUpdate!=`function`&&typeof a.componentWillUpdate!=`function`||(typeof a.componentWillUpdate==`function`&&a.componentWillUpdate(r,p,c),typeof a.UNSAFE_componentWillUpdate==`function`&&a.UNSAFE_componentWillUpdate(r,p,c)),typeof a.componentDidUpdate==`function`&&(t.flags|=4),typeof a.getSnapshotBeforeUpdate==`function`&&(t.flags|=1024)):(typeof a.componentDidUpdate!=`function`||o===e.memoizedProps&&f===e.memoizedState||(t.flags|=4),typeof a.getSnapshotBeforeUpdate!=`function`||o===e.memoizedProps&&f===e.memoizedState||(t.flags|=1024),t.memoizedProps=r,t.memoizedState=p),a.props=r,a.state=p,a.context=c,r=u):(typeof a.componentDidUpdate!=`function`||o===e.memoizedProps&&f===e.memoizedState||(t.flags|=4),typeof a.getSnapshotBeforeUpdate!=`function`||o===e.memoizedProps&&f===e.memoizedState||(t.flags|=1024),r=!1)}return a=r,nr(e,t),r=(t.flags&128)!=0,a||r?(a=t.stateNode,n=r&&typeof n.getDerivedStateFromError!=`function`?null:a.render(),t.flags|=1,e!==null&&r?(t.child=jl(t,e.child,null,i),t.child=jl(t,null,n,i)):Kn(e,t,n,i),t.memoizedState=a.state,e=t.child):e=mr(e,t,i),e}function or(e,t,n,r){return pe(),t.flags|=256,Kn(e,t,n,r),t.child}function sr(e){return{baseLanes:e,cachePool:ze()}}function V(e,t,n){return e=e===null?0:e.childLanes&~n,t&&(e|=Ru),e}function cr(e,t,n){var i=t.pendingProps,a=!1,o=(t.flags&128)!=0,s;if((s=o)||(s=e!==null&&e.memoizedState===null?!1:(Hl.current&2)!=0),s&&(a=!0,t.flags&=-129),s=(t.flags&32)!=0,t.flags&=-33,e===null){if(tl){if(a?ht(t):vt(),(e=el)?(e=Ts(e,rl),e!==null&&(t.memoizedState={dehydrated:e,treeContext:Kc===null?null:{id:qc,overflow:Jc},retryLane:536870912,hydrationErrors:null},n=ha(e),n.return=t,t.child=n,$c=t,el=null)):e=null,e===null)throw le(t);return us(e)?t.lanes=32:t.lanes=536870912,null}var c=i.children;return i=i.fallback,a?(vt(),a=t.mode,c=lr({mode:`hidden`,children:c},a),i=pa(i,a,n,null),c.return=t,i.return=t,c.sibling=i,t.child=c,i=t.child,i.memoizedState=sr(n),i.childLanes=V(e,s,n),t.memoizedState=ou,Zn(null,i)):(ht(t),H(t,c))}var l=e.memoizedState;if(l!==null&&(c=l.dehydrated,c!==null)){if(o)t.flags&256?(ht(t),t.flags&=-257,t=ur(e,t,n)):t.memoizedState===null?(vt(),c=i.fallback,a=t.mode,i=lr({mode:`visible`,children:i.children},a),c=pa(c,a,n,null),c.flags|=2,i.return=t,c.return=t,i.sibling=c,t.child=i,jl(t,e.child,null,n),i=t.child,i.memoizedState=sr(n),i.childLanes=V(e,s,n),t.memoizedState=ou,t=Zn(null,i)):(vt(),t.child=e.child,t.flags|=128,t=null);else if(ht(t),us(c))s=ds(c).digest,i=Error(r(419)),i.stack=``,i.digest=s,he({value:i,source:null,stack:null}),t=ur(e,t,n);else if(au||ye(e,t,n,!1),s=(n&e.childLanes)!==0,au||s){if(s=Tu,s!==null&&(i=E(s,n),i!==0&&i!==l.retryLane))throw l.retryLane=i,$e(e,i),Oi(s,e,i),iu;ls(c)||Bi(),t=ur(e,t,n)}else ls(c)?(t.flags|=192,t.child=e.child,t=null):(e=l.treeContext,po&&(el=bs(c),$c=t,tl=!0,nl=null,rl=!1,e!==null&&ie(t,e)),t=H(t,i.children),t.flags|=4096);return t}return a?(vt(),c=i.fallback,a=t.mode,l=e.child,o=l.sibling,i=ua(l,{mode:`hidden`,children:i.children}),i.subtreeFlags=l.subtreeFlags&65011712,o===null?(c=pa(c,a,n,null),c.flags|=2):c=ua(o,c),c.return=t,i.return=t,i.sibling=c,t.child=i,Zn(null,i),i=t.child,c=e.child.memoizedState,c===null?c=sr(n):(a=c.cachePool,a===null?a=ze():(l=lo?dl._currentValue:dl._currentValue2,a=a.parent===l?a:{parent:l,pool:l}),c={baseLanes:c.baseLanes|n,cachePool:a}),i.memoizedState=c,i.childLanes=V(e,s,n),t.memoizedState=ou,Zn(e.child,i)):(ht(t),n=e.child,e=n.sibling,n=ua(n,{mode:`visible`,children:i.children}),n.return=t,n.sibling=null,e!==null&&(s=t.deletions,s===null?(t.deletions=[e],t.flags|=16):s.push(e)),t.child=n,t.memoizedState=null,n)}function H(e,t){return t=lr({mode:`visible`,children:t},e.mode),t.return=e,e.child=t}function lr(e,n){return e=t(22,e,null,n),e.lanes=0,e}function ur(e,t,n){return jl(t,e.child,null,n),e=H(t,t.pendingProps.children),e.flags|=2,t.memoizedState=null,e}function dr(e,t,n){e.lanes|=t;var r=e.alternate;r!==null&&(r.lanes|=t),_e(e.return,t,n)}function fr(e,t,n,r,i,a){var o=e.memoizedState;o===null?e.memoizedState={isBackwards:t,rendering:null,renderingStartTime:0,last:r,tail:n,tailMode:i,treeForkCount:a}:(o.isBackwards=t,o.rendering=null,o.renderingStartTime=0,o.last=r,o.tail=n,o.tailMode=i,o.treeForkCount=a)}function pr(e,t,n){var r=t.pendingProps,i=r.revealOrder,a=r.tail;r=r.children;var o=Hl.current,s=(o&2)!=0;if(s?(o=o&1|2,t.flags|=128):o&=1,p(Hl,o),Kn(e,t,r,n),r=tl?Uc:0,!s&&e!==null&&e.flags&128)e:for(e=t.child;e!==null;){if(e.tag===13)e.memoizedState!==null&&dr(e,n,t);else if(e.tag===19)dr(e,n,t);else if(e.child!==null){e.child.return=e,e=e.child;continue}if(e===t)break e;for(;e.sibling===null;){if(e.return===null||e.return===t)break e;e=e.return}e.sibling.return=e.return,e=e.sibling}switch(i){case`forwards`:for(n=t.child,i=null;n!==null;)e=n.alternate,e!==null&&bt(e)===null&&(i=n),n=n.sibling;n=i,n===null?(i=t.child,t.child=null):(i=n.sibling,n.sibling=null),fr(t,!1,i,n,a,r);break;case`backwards`:case`unstable_legacy-backwards`:for(n=null,i=t.child,t.child=null;i!==null;){if(e=i.alternate,e!==null&&bt(e)===null){t.child=i;break}e=i.sibling,i.sibling=n,n=i,i=e}fr(t,!0,n,null,a,r);break;case`together`:fr(t,!1,null,null,void 0,r);break;default:t.memoizedState=null}return t.child}function mr(e,t,n){if(e!==null&&(t.dependencies=e.dependencies),Fu|=t.lanes,(n&t.childLanes)===0)if(e!==null){if(ye(e,t,n,!1),(n&t.childLanes)===0)return null}else return null;if(e!==null&&t.child!==e.child)throw Error(r(153));if(t.child!==null){for(e=t.child,n=ua(e,e.pendingProps),t.child=n,n.return=t;e.sibling!==null;)e=e.sibling,n=n.sibling=ua(e,e.pendingProps),n.return=t;n.sibling=null}return t.child}function hr(e,t){return(e.lanes&t)===0?(e=e.dependencies,!!(e!==null&&L(e))):!0}function gr(e,t,n){switch(t.tag){case 3:ae(t,t.stateNode.containerInfo),ge(t,dl,e.memoizedState.cache),pe();break;case 27:case 5:se(t);break;case 4:ae(t,t.stateNode.containerInfo);break;case 10:ge(t,t.type,t.memoizedProps.value);break;case 31:if(t.memoizedState!==null)return t.flags|=128,gt(t),null;break;case 13:var r=t.memoizedState;if(r!==null)return r.dehydrated===null?(n&t.child.childLanes)===0?(ht(t),e=mr(e,t,n),e===null?null:e.sibling):cr(e,t,n):(ht(t),t.flags|=128,null);ht(t);break;case 19:var i=(e.flags&128)!=0;if(r=(n&t.childLanes)!==0,r||=(ye(e,t,n,!1),(n&t.childLanes)!==0),i){if(r)return pr(e,t,n);t.flags|=128}if(i=t.memoizedState,i!==null&&(i.rendering=null,i.tail=null,i.lastEffect=null),p(Hl,Hl.current),r)break;return null;case 22:return t.lanes=0,Xn(e,t,n,t.pendingProps);case 24:ge(t,dl,e.memoizedState.cache)}return mr(e,t,n)}function _r(e,t,n){if(e!==null)if(e.memoizedProps!==t.pendingProps)au=!0;else{if(!hr(e,n)&&!(t.flags&128))return au=!1,gr(e,t,n);au=(e.flags&131072)!=0}else au=!1,tl&&t.flags&1048576&&te(t,Uc,t.index);switch(t.lanes=0,t.tag){case 16:e:{var i=t.pendingProps;if(e=Ue(t.elementType),t.type=e,typeof e==`function`)la(e)?(i=zn(e,i),t.tag=1,t=ar(null,t,e,i,n)):(t.tag=0,t=rr(null,t,e,i,n));else{if(e!=null){var a=e.$$typeof;if(a===Ia){t.tag=11,t=qn(null,t,e,i,n);break e}else if(a===za){t.tag=14,t=Jn(null,t,e,i,n);break e}}throw t=u(e)||e,Error(r(306,t,``))}}return t;case 0:return rr(e,t,t.type,t.pendingProps,n);case 1:return i=t.type,a=zn(i,t.pendingProps),ar(e,t,i,a,n);case 3:e:{if(ae(t,t.stateNode.containerInfo),e===null)throw Error(r(387));var o=t.pendingProps;a=t.memoizedState,i=a.element,rt(e,t),lt(t,o,null,n);var s=t.memoizedState;if(o=s.cache,ge(t,dl,o),o!==a.cache&&ve(t,[dl],n,!0),ct(),o=s.element,po&&a.isDehydrated)if(a={element:o,isDehydrated:!1,cache:s.cache},t.updateQueue.baseState=a,t.memoizedState=a,t.flags&256){t=or(e,t,o,n);break e}else if(o!==i){i=P(Error(r(424)),t),he(i),t=or(e,t,o,n);break e}else for(po&&(el=vs(t.stateNode.containerInfo),$c=t,tl=!0,nl=null,rl=!0),n=Ml(t,null,o,n),t.child=n;n;)n.flags=n.flags&-3|4096,n=n.sibling;else{if(pe(),o===i){t=mr(e,t,n);break e}Kn(e,t,o,n)}t=t.child}return t;case 26:if(Gs)return nr(e,t),e===null?(n=Js(t.type,null,t.pendingProps,null))?t.memoizedState=n:tl||(t.stateNode=ec(t.type,t.pendingProps,Zc.current,t)):t.memoizedState=Js(t.type,e.memoizedProps,t.pendingProps,e.memoizedState),null;case 27:if(ac)return se(t),e===null&&ac&&tl&&(i=t.stateNode=oc(t.type,t.pendingProps,Zc.current,Yc.current,!1),$c=t,rl=!0,el=xs(t.type,i,el)),Kn(e,t,t.pendingProps.children,n),nr(e,t),e===null&&(t.flags|=4194304),t.child;case 5:return e===null&&tl&&(Us(t.type,t.pendingProps,Yc.current),(a=i=el)&&(i=Ss(i,t.type,t.pendingProps,rl),i===null?a=!1:(t.stateNode=i,$c=t,el=_s(i),rl=!1,a=!0)),a||le(t)),se(t),a=t.type,o=t.pendingProps,s=e===null?null:e.memoizedProps,i=o.children,io(a,o)?i=null:s!==null&&io(a,s)&&(t.flags|=32),t.memoizedState!==null&&(a=Ct(e,t,Et,null,null,n),lo?ko._currentValue=a:ko._currentValue2=a),nr(e,t),Kn(e,t,i,n),t.child;case 6:return e===null&&tl&&(Ws(t.pendingProps,Yc.current),(e=n=el)&&(n=Cs(n,t.pendingProps,rl),n===null?e=!1:(t.stateNode=n,$c=t,el=null,e=!0)),e||le(t)),null;case 13:return cr(e,t,n);case 4:return ae(t,t.stateNode.containerInfo),i=t.pendingProps,e===null?t.child=jl(t,null,i,n):Kn(e,t,i,n),t.child;case 11:return qn(e,t,t.type,t.pendingProps,n);case 7:return Kn(e,t,t.pendingProps,n),t.child;case 8:return Kn(e,t,t.pendingProps.children,n),t.child;case 12:return Kn(e,t,t.pendingProps.children,n),t.child;case 10:return i=t.pendingProps,ge(t,t.type,i.value),Kn(e,t,i.children,n),t.child;case 9:return a=t.type._context,i=t.pendingProps.children,R(t),a=z(a),i=i(a),t.flags|=1,Kn(e,t,i,n),t.child;case 14:return Jn(e,t,t.type,t.pendingProps,n);case 15:return Yn(e,t,t.type,t.pendingProps,n);case 19:return pr(e,t,n);case 31:return tr(e,t,n);case 22:return Xn(e,t,n,t.pendingProps);case 24:return R(t),i=z(dl),e===null?(a=Le(),a===null&&(a=Tu,o=Se(),a.pooledCache=o,o.refCount++,o!==null&&(a.pooledCacheLanes|=n),a=o),t.memoizedState={parent:i,cache:a},nt(t),ge(t,dl,a)):((e.lanes&n)!==0&&(rt(e,t),lt(t,null,null,n),ct()),a=e.memoizedState,o=t.memoizedState,a.parent===i?(i=o.cache,ge(t,dl,i),i!==a.cache&&ve(t,[dl],n,!0)):(a={parent:i,cache:i},t.memoizedState=a,t.lanes===0&&(t.memoizedState=t.updateQueue.baseState=a),ge(t,dl,i))),Kn(e,t,t.pendingProps.children,n),t.child;case 29:throw t.pendingProps}throw Error(r(156,t.tag))}function vr(e){e.flags|=4}function yr(e){fo&&(e.flags|=8)}function br(e,t){if(e!==null&&e.child===t.child)return!1;if(t.flags&16)return!0;for(e=t.child;e!==null;){if(e.flags&8218||e.subtreeFlags&8218)return!0;e=e.sibling}return!1}function xr(e,t,n,r){if(uo)for(n=t.child;n!==null;){if(n.tag===5||n.tag===6)no(e,n.stateNode);else if(!(n.tag===4||ac&&n.tag===27)&&n.child!==null){n.child.return=n,n=n.child;continue}if(n===t)break;for(;n.sibling===null;){if(n.return===null||n.return===t)return;n=n.return}n.sibling.return=n.return,n=n.sibling}else if(fo)for(var i=t.child;i!==null;){if(i.tag===5){var a=i.stateNode;n&&r&&(a=ss(a,i.type,i.memoizedProps)),no(e,a)}else if(i.tag===6)a=i.stateNode,n&&r&&(a=cs(a,i.memoizedProps)),no(e,a);else if(i.tag!==4){if(i.tag===22&&i.memoizedState!==null)a=i.child,a!==null&&(a.return=i),xr(e,i,!0,!0);else if(i.child!==null){i.child.return=i,i=i.child;continue}}if(i===t)break;for(;i.sibling===null;){if(i.return===null||i.return===t)return;i=i.return}i.sibling.return=i.return,i=i.sibling}}function Sr(e,t,n,r){var i=!1;if(fo)for(var a=t.child;a!==null;){if(a.tag===5){var o=a.stateNode;n&&r&&(o=ss(o,a.type,a.memoizedProps)),is(e,o)}else if(a.tag===6)o=a.stateNode,n&&r&&(o=cs(o,a.memoizedProps)),is(e,o);else if(a.tag!==4){if(a.tag===22&&a.memoizedState!==null)i=a.child,i!==null&&(i.return=a),Sr(e,a,!0,!0),i=!0;else if(a.child!==null){a.child.return=a,a=a.child;continue}}if(a===t)break;for(;a.sibling===null;){if(a.return===null||a.return===t)return i;a=a.return}a.sibling.return=a.return,a=a.sibling}return i}function Cr(e,t){if(fo&&br(e,t)){e=t.stateNode;var n=e.containerInfo,r=rs();Sr(r,t,!1,!1),e.pendingChildren=r,vr(t),as(n,r)}}function wr(e,t,n,r){if(uo)e.memoizedProps!==r&&vr(t);else if(fo){var i=e.stateNode,a=e.memoizedProps;if((e=br(e,t))||a!==r){var o=Yc.current;a=ns(i,n,a,r,!e,null),a===i?t.stateNode=i:(yr(t),ro(a,n,r,o)&&vr(t),t.stateNode=a,e&&xr(a,t,!1,!1))}else t.stateNode=i}}function Tr(e,t,n,r,i){if(e.mode&32&&(n===null?xo(t,r):So(t,n,r))){if(e.flags|=16777216,(i&335544128)===i||Co(t,r))if(wo(e.stateNode,t,r))e.flags|=8192;else if(Li())e.flags|=8192;else throw Ol=Dl,Tl}else e.flags&=-16777217}function Er(e,t){if(nc(t)){if(e.flags|=16777216,!rc(t))if(Li())e.flags|=8192;else throw Ol=Dl,Tl}else e.flags&=-16777217}function Dr(e,t){t!==null&&(e.flags|=4),e.flags&16384&&(t=e.tag===22?536870912:b(),e.lanes|=t,zu|=t)}function Or(e,t){if(!tl)switch(e.tailMode){case`hidden`:t=e.tail;for(var n=null;t!==null;)t.alternate!==null&&(n=t),t=t.sibling;n===null?e.tail=null:n.sibling=null;break;case`collapsed`:n=e.tail;for(var r=null;n!==null;)n.alternate!==null&&(r=n),n=n.sibling;r===null?t||e.tail===null?e.tail=null:e.tail.sibling=null:r.sibling=null}}function kr(e){var t=e.alternate!==null&&e.alternate.child===e.child,n=0,r=0;if(t)for(var i=e.child;i!==null;)n|=i.lanes|i.childLanes,r|=i.subtreeFlags&65011712,r|=i.flags&65011712,i.return=e,i=i.sibling;else for(i=e.child;i!==null;)n|=i.lanes|i.childLanes,r|=i.subtreeFlags,r|=i.flags,i.return=e,i=i.sibling;return e.subtreeFlags|=r,e.childLanes=n,t}function Ar(e,t,n){var i=t.pendingProps;switch(re(t),t.tag){case 16:case 15:case 0:case 11:case 7:case 8:case 12:case 9:case 14:return kr(t),null;case 1:return kr(t),null;case 3:return n=t.stateNode,i=null,e!==null&&(i=e.memoizedState.cache),t.memoizedState.cache!==i&&(t.flags|=2048),I(dl),oe(),n.pendingContext&&(n.context=n.pendingContext,n.pendingContext=null),(e===null||e.child===null)&&(fe(t)?vr(t):e===null||e.memoizedState.isDehydrated&&!(t.flags&256)||(t.flags|=1024,me())),Cr(e,t),kr(t),null;case 26:if(Gs){var a=t.type,o=t.memoizedState;return e===null?(vr(t),o===null?(kr(t),Tr(t,a,null,i,n)):(kr(t),Er(t,o))):o?o===e.memoizedState?(kr(t),t.flags&=-16777217):(vr(t),kr(t),Er(t,o)):(o=e.memoizedProps,uo?o!==i&&vr(t):wr(e,t,a,i),kr(t),Tr(t,a,o,i,n)),null}case 27:if(ac){if(ce(t),n=Zc.current,a=t.type,e!==null&&t.stateNode!=null)uo?e.memoizedProps!==i&&vr(t):wr(e,t,a,i);else{if(!i){if(t.stateNode===null)throw Error(r(166));return kr(t),null}e=Yc.current,fe(t)?ue(t,e):(e=oc(a,i,n,e,!0),t.stateNode=e,vr(t))}return kr(t),null}case 5:if(ce(t),a=t.type,e!==null&&t.stateNode!=null)wr(e,t,a,i);else{if(!i){if(t.stateNode===null)throw Error(r(166));return kr(t),null}if(o=Yc.current,fe(t))ue(t,o),Is(t.stateNode,a,i,o)&&(t.flags|=64);else{var s=to(a,i,Zc.current,o,t);yr(t),xr(s,t,!1,!1),t.stateNode=s,ro(s,a,i,o)&&vr(t)}}return kr(t),Tr(t,t.type,e===null?null:e.memoizedProps,t.pendingProps,n),null;case 6:if(e&&t.stateNode!=null)n=e.memoizedProps,uo?n!==i&&vr(t):fo&&(n===i?t.stateNode=e.stateNode:(e=Zc.current,n=Yc.current,yr(t),t.stateNode=ao(i,e,n,t)));else{if(typeof i!=`string`&&t.stateNode===null)throw Error(r(166));if(e=Zc.current,n=Yc.current,fe(t)){if(!po)throw Error(r(176));if(e=t.stateNode,n=t.memoizedProps,i=null,a=$c,a!==null)switch(a.tag){case 27:case 5:i=a.memoizedProps}Ds(e,n,t,i)||le(t,!0)}else yr(t),t.stateNode=ao(i,e,n,t)}return kr(t),null;case 31:if(n=t.memoizedState,e===null||e.memoizedState!==null){if(i=fe(t),n!==null){if(e===null){if(!i)throw Error(r(318));if(!po)throw Error(r(556));if(e=t.memoizedState,e=e===null?null:e.dehydrated,!e)throw Error(r(557));Os(e,t)}else pe(),!(t.flags&128)&&(t.memoizedState=null),t.flags|=4;kr(t),e=!1}else n=me(),e!==null&&e.memoizedState!==null&&(e.memoizedState.hydrationErrors=n),e=!0;if(!e)return t.flags&256?(yt(t),t):(yt(t),null);if(t.flags&128)throw Error(r(558))}return kr(t),null;case 13:if(i=t.memoizedState,e===null||e.memoizedState!==null&&e.memoizedState.dehydrated!==null){if(a=fe(t),i!==null&&i.dehydrated!==null){if(e===null){if(!a)throw Error(r(318));if(!po)throw Error(r(344));if(a=t.memoizedState,a=a===null?null:a.dehydrated,!a)throw Error(r(317));ks(a,t)}else pe(),!(t.flags&128)&&(t.memoizedState=null),t.flags|=4;kr(t),a=!1}else a=me(),e!==null&&e.memoizedState!==null&&(e.memoizedState.hydrationErrors=a),a=!0;if(!a)return t.flags&256?(yt(t),t):(yt(t),null)}return yt(t),t.flags&128?(t.lanes=n,t):(n=i!==null,e=e!==null&&e.memoizedState!==null,n&&(i=t.child,a=null,i.alternate!==null&&i.alternate.memoizedState!==null&&i.alternate.memoizedState.cachePool!==null&&(a=i.alternate.memoizedState.cachePool.pool),o=null,i.memoizedState!==null&&i.memoizedState.cachePool!==null&&(o=i.memoizedState.cachePool.pool),o!==a&&(i.flags|=2048)),n!==e&&n&&(t.child.flags|=8192),Dr(t,t.updateQueue),kr(t),null);case 4:return oe(),Cr(e,t),e===null&&ho(t.stateNode.containerInfo),kr(t),null;case 10:return I(t.type),kr(t),null;case 19:if(f(Hl),i=t.memoizedState,i===null)return kr(t),null;if(a=(t.flags&128)!=0,o=i.rendering,o===null)if(a)Or(i,!1);else{if(Pu!==0||e!==null&&e.flags&128)for(e=t.child;e!==null;){if(o=bt(e),o!==null){for(t.flags|=128,Or(i,!1),e=o.updateQueue,t.updateQueue=e,Dr(t,e),t.subtreeFlags=0,e=n,n=t.child;n!==null;)da(n,e),n=n.sibling;return p(Hl,Hl.current&1|2),tl&&F(t,i.treeForkCount),t.child}e=e.sibling}i.tail!==null&&wc()>Gu&&(t.flags|=128,a=!0,Or(i,!1),t.lanes=4194304)}else{if(!a)if(e=bt(o),e!==null){if(t.flags|=128,a=!0,e=e.updateQueue,t.updateQueue=e,Dr(t,e),Or(i,!0),i.tail===null&&i.tailMode===`hidden`&&!o.alternate&&!tl)return kr(t),null}else 2*wc()-i.renderingStartTime>Gu&&n!==536870912&&(t.flags|=128,a=!0,Or(i,!1),t.lanes=4194304);i.isBackwards?(o.sibling=t.child,t.child=o):(e=i.last,e===null?t.child=o:e.sibling=o,i.last=o)}return i.tail===null?(kr(t),null):(e=i.tail,i.rendering=e,i.tail=e.sibling,i.renderingStartTime=wc(),e.sibling=null,n=Hl.current,p(Hl,a?n&1|2:n&1),tl&&F(t,i.treeForkCount),e);case 22:case 23:return yt(t),mt(),i=t.memoizedState!==null,e===null?i&&(t.flags|=8192):e.memoizedState!==null!==i&&(t.flags|=8192),i?n&536870912&&!(t.flags&128)&&(kr(t),t.subtreeFlags&6&&(t.flags|=8192)):kr(t),n=t.updateQueue,n!==null&&Dr(t,n.retryQueue),n=null,e!==null&&e.memoizedState!==null&&e.memoizedState.cachePool!==null&&(n=e.memoizedState.cachePool.pool),i=null,t.memoizedState!==null&&t.memoizedState.cachePool!==null&&(i=t.memoizedState.cachePool.pool),i!==n&&(t.flags|=2048),e!==null&&f(Cl),null;case 24:return n=null,e!==null&&(n=e.memoizedState.cache),t.memoizedState.cache!==n&&(t.flags|=2048),I(dl),kr(t),null;case 25:return null;case 30:return null}throw Error(r(156,t.tag))}function jr(e,t){switch(re(t),t.tag){case 1:return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return I(dl),oe(),e=t.flags,e&65536&&!(e&128)?(t.flags=e&-65537|128,t):null;case 26:case 27:case 5:return ce(t),null;case 31:if(t.memoizedState!==null){if(yt(t),t.alternate===null)throw Error(r(340));pe()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 13:if(yt(t),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(r(340));pe()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return f(Hl),null;case 4:return oe(),null;case 10:return I(t.type),null;case 22:case 23:return yt(t),mt(),e!==null&&f(Cl),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 24:return I(dl),null;case 25:return null;default:return null}}function Mr(e,t){switch(re(t),t.tag){case 3:I(dl),oe();break;case 26:case 27:case 5:ce(t);break;case 4:oe();break;case 31:t.memoizedState!==null&&yt(t);break;case 13:yt(t);break;case 19:f(Hl);break;case 10:I(t.type);break;case 22:case 23:yt(t),mt(),e!==null&&f(Cl);break;case 24:I(dl)}}function Nr(e,t){try{var n=t.updateQueue,r=n===null?null:n.lastEffect;if(r!==null){var i=r.next;n=i;do{if((n.tag&e)===e){r=void 0;var a=n.create,o=n.inst;r=a(),o.destroy=r}n=n.next}while(n!==i)}}catch(e){na(t,t.return,e)}}function Pr(e,t,n){try{var r=t.updateQueue,i=r===null?null:r.lastEffect;if(i!==null){var a=i.next;r=a;do{if((r.tag&e)===e){var o=r.inst,s=o.destroy;if(s!==void 0){o.destroy=void 0,i=t;var c=n,l=s;try{l()}catch(e){na(i,c,e)}}}r=r.next}while(r!==a)}}catch(e){na(t,t.return,e)}}function Fr(e){var t=e.updateQueue;if(t!==null){var n=e.stateNode;try{dt(t,n)}catch(t){na(e,e.return,t)}}}function Ir(e,t,n){n.props=zn(e.type,e.memoizedProps),n.state=e.memoizedState;try{n.componentWillUnmount()}catch(n){na(e,t,n)}}function Lr(e,t){try{var n=e.ref;if(n!==null){switch(e.tag){case 26:case 27:case 5:var r=Xa(e.stateNode);break;case 30:r=e.stateNode;break;default:r=e.stateNode}typeof n==`function`?e.refCleanup=n(r):n.current=r}}catch(n){na(e,t,n)}}function Rr(e,t){var n=e.ref,r=e.refCleanup;if(n!==null)if(typeof r==`function`)try{r()}catch(n){na(e,t,n)}finally{e.refCleanup=null,e=e.alternate,e!=null&&(e.refCleanup=null)}else if(typeof n==`function`)try{n(null)}catch(n){na(e,t,n)}else n.current=null}function zr(e){var t=e.type,n=e.memoizedProps,r=e.stateNode;try{Wo(r,t,n,e)}catch(t){na(e,e.return,t)}}function Br(e,t,n){try{Go(e.stateNode,e.type,n,t,e)}catch(t){na(e,e.return,t)}}function Vr(e){return e.tag===5||e.tag===3||(Gs?e.tag===26:!1)||(ac?e.tag===27&&uc(e.type):!1)||e.tag===4}function Hr(e){e:for(;;){for(;e.sibling===null;){if(e.return===null||Vr(e.return))return null;e=e.return}for(e.sibling.return=e.return,e=e.sibling;e.tag!==5&&e.tag!==6&&e.tag!==18;){if(ac&&e.tag===27&&uc(e.type)||e.flags&2||e.child===null||e.tag===4)continue e;e.child.return=e,e=e.child}if(!(e.flags&2))return e.stateNode}}function Ur(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?qo(n,e,t):Ho(n,e);else if(r!==4&&(ac&&r===27&&uc(e.type)&&(n=e.stateNode,t=null),e=e.child,e!==null))for(Ur(e,t,n),e=e.sibling;e!==null;)Ur(e,t,n),e=e.sibling}function Wr(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?Ko(n,e,t):Vo(n,e);else if(r!==4&&(ac&&r===27&&uc(e.type)&&(n=e.stateNode),e=e.child,e!==null))for(Wr(e,t,n),e=e.sibling;e!==null;)Wr(e,t,n),e=e.sibling}function Gr(e,t,n){e=e.containerInfo;try{os(e,n)}catch(e){na(t,t.return,e)}}function Kr(e){var t=e.stateNode,n=e.memoizedProps;try{sc(e.type,n,t,e)}catch(t){na(e,e.return,t)}}function qr(e,t){for($a(e.containerInfo),du=t;du!==null;)if(e=du,t=e.child,e.subtreeFlags&1028&&t!==null)t.return=e,du=t;else for(;du!==null;){e=du;var n=e.alternate;switch(t=e.flags,e.tag){case 0:if(t&4&&(t=e.updateQueue,t=t===null?null:t.events,t!==null))for(var i=0;i`;case vu:return`:has(`+(Ci(e)||``)+`)`;case yu:return`[role="`+e.value+`"]`;case xu:return`"`+e.value+`"`;case bu:return`[data-testname="`+e.value+`"]`;default:throw Error(r(365))}}function wi(e,t){var n=[];e=[e,0];for(var r=0;rn?32:n;n=Ka.T;var a=_o();try{go(i),Ka.T=null,i=$u,$u=null;var o=Yu,s=Zu;if(Ju=0,Xu=Yu=null,Zu=0,wu&6)throw Error(r(331));var c=wu;if(wu|=4,vi(o.current),fi(o,o.current,s,i),wu=c,Ee(0,!1),Mc&&typeof Mc.onPostCommitFiberRoot==`function`)try{Mc.onPostCommitFiberRoot(jc,o)}catch{}return!0}finally{go(a),Ka.T=n,Qi(e,t)}}function ta(e,t,n){t=P(n,t),t=Hn(e.stateNode,t,2),e=at(e,t,2),e!==null&&(S(e,2),Te(e))}function na(e,t,n){if(e.tag===3)ta(e,e,n);else for(;t!==null;){if(t.tag===3){ta(t,e,n);break}else if(t.tag===1){var r=t.stateNode;if(typeof t.type.getDerivedStateFromError==`function`||typeof r.componentDidCatch==`function`&&(qu===null||!qu.has(r))){e=P(n,e),n=Un(2),r=at(t,n,2),r!==null&&(Wn(n,r,t,e),S(r,2),Te(r));break}}t=t.return}}function ra(e,t,n){var r=e.pingCache;if(r===null){r=e.pingCache=new Cu;var i=new Set;r.set(t,i)}else i=r.get(t),i===void 0&&(i=new Set,r.set(t,i));i.has(n)||(Mu=!0,i.add(n),e=ia.bind(null,e,t,n),t.then(e,e))}function ia(e,t,n){var r=e.pingCache;r!==null&&r.delete(t),e.pingedLanes|=e.suspendedLanes&n,e.warmLanes&=~n,Tu===e&&(Du&n)===n&&(Pu===4||Pu===3&&(Du&62914560)===Du&&300>wc()-Uu?!(wu&2)&&Fi(e,0):Lu|=n,zu===Du&&(zu=0)),Te(e)}function aa(e,t){t===0&&(t=b()),e=$e(e,t),e!==null&&(S(e,t),Te(e))}function oa(e){var t=e.memoizedState,n=0;t!==null&&(n=t.retryLane),aa(e,n)}function sa(e,t){var n=0;switch(e.tag){case 31:case 13:var i=e.stateNode,a=e.memoizedState;a!==null&&(n=a.retryLane);break;case 19:i=e.stateNode;break;case 22:i=e.stateNode._retryCache;break;default:throw Error(r(314))}i!==null&&i.delete(t),aa(e,n)}function ca(e,t){return bc(e,t)}function K(e,t,n,r){this.tag=e,this.key=n,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.refCleanup=this.ref=null,this.pendingProps=t,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=r,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function la(e){return e=e.prototype,!(!e||!e.isReactComponent)}function ua(e,n){var r=e.alternate;return r===null?(r=t(e.tag,n,e.key,e.mode),r.elementType=e.elementType,r.type=e.type,r.stateNode=e.stateNode,r.alternate=e,e.alternate=r):(r.pendingProps=n,r.type=e.type,r.flags=0,r.subtreeFlags=0,r.deletions=null),r.flags=e.flags&65011712,r.childLanes=e.childLanes,r.lanes=e.lanes,r.child=e.child,r.memoizedProps=e.memoizedProps,r.memoizedState=e.memoizedState,r.updateQueue=e.updateQueue,n=e.dependencies,r.dependencies=n===null?null:{lanes:n.lanes,firstContext:n.firstContext},r.sibling=e.sibling,r.index=e.index,r.ref=e.ref,r.refCleanup=e.refCleanup,r}function da(e,t){e.flags&=65011714;var n=e.alternate;return n===null?(e.childLanes=0,e.lanes=t,e.child=null,e.subtreeFlags=0,e.memoizedProps=null,e.memoizedState=null,e.updateQueue=null,e.dependencies=null,e.stateNode=null):(e.childLanes=n.childLanes,e.lanes=n.lanes,e.child=n.child,e.subtreeFlags=0,e.deletions=null,e.memoizedProps=n.memoizedProps,e.memoizedState=n.memoizedState,e.updateQueue=n.updateQueue,e.type=n.type,t=n.dependencies,e.dependencies=t===null?null:{lanes:t.lanes,firstContext:t.firstContext}),e}function fa(e,n,i,a,o,s){var c=0;if(a=e,typeof e==`function`)la(e)&&(c=1);else if(typeof e==`string`)c=Gs&&ac?Ks(e,i,Yc.current)?26:lc(e)?27:5:Gs?Ks(e,i,Yc.current)?26:5:ac&&lc(e)?27:5;else e:switch(e){case Va:return e=t(31,i,n,o),e.elementType=Va,e.lanes=s,e;case ja:return pa(i.children,o,s,n);case Ma:c=8,o|=24;break;case Na:return e=t(12,i,n,o|2),e.elementType=Na,e.lanes=s,e;case La:return e=t(13,i,n,o),e.elementType=La,e.lanes=s,e;case Ra:return e=t(19,i,n,o),e.elementType=Ra,e.lanes=s,e;default:if(typeof e==`object`&&e)switch(e.$$typeof){case Fa:c=10;break e;case Pa:c=9;break e;case Ia:c=11;break e;case za:c=14;break e;case Ba:c=16,a=null;break e}c=29,i=Error(r(130,e===null?`null`:typeof e,``)),a=null}return n=t(c,i,n,o),n.elementType=e,n.type=a,n.lanes=s,n}function pa(e,n,r,i){return e=t(7,e,i,n),e.lanes=r,e}function ma(e,n,r){return e=t(6,e,null,n),e.lanes=r,e}function ha(e){var n=t(18,null,null,0);return n.stateNode=e,n}function ga(e,n,r){return n=t(4,e.children===null?[]:e.children,e.key,n),n.lanes=r,n.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},n}function _a(e,t,n,r,i,a,o,s,c){this.tag=1,this.containerInfo=e,this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=co,this.callbackNode=this.next=this.pendingContext=this.context=this.cancelPendingCommit=null,this.callbackPriority=0,this.expirationTimes=x(-1),this.entangledLanes=this.shellSuspendCounter=this.errorRecoveryDisabledLanes=this.expiredLanes=this.warmLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=x(0),this.hiddenUpdates=x(null),this.identifierPrefix=r,this.onUncaughtError=i,this.onCaughtError=a,this.onRecoverableError=o,this.pooledCache=null,this.pooledCacheLanes=0,this.formState=c,this.incompleteTransitions=new Map}function va(e,n,r,i,a,o,s,c,l,u,d,f){return e=new _a(e,n,r,s,l,u,d,f,c),n=1,o===!0&&(n|=24),o=t(3,null,null,n),e.current=o,o.stateNode=e,n=Se(),n.refCount++,e.pooledCache=n,n.refCount++,o.memoizedState={element:i,isDehydrated:r,cache:n},nt(o),e}function ya(e){return e?(e=pc,e):pc}function ba(e){var t=e._reactInternals;if(t===void 0)throw typeof e.render==`function`?Error(r(188)):(e=Object.keys(e).join(`,`),Error(r(268,e)));return e=o(t),e=e===null?null:s(e),e===null?null:Xa(e.stateNode)}function xa(e,t,n,r,i,a){i=ya(i),r.context===null?r.context=i:r.pendingContext=i,r=it(t),r.payload={element:n},a=a===void 0?null:a,a!==null&&(r.callback=a),n=at(e,r,t),n!==null&&(Oi(n,e,t),ot(n,e,t))}function Sa(e,t){if(e=e.memoizedState,e!==null&&e.dehydrated!==null){var n=e.retryLane;e.retryLane=n!==0&&n=u&&o>=f&&a<=d&&s<=p){e.splice(t,1);break}else if(i!==u||n.width!==l.width||ps){if(!(o!==f||n.height!==l.height||da)){u>i&&(l.width+=u-i,l.x=i),do&&(l.height+=f-o,l.y=o),pn&&(n=c)),c `)+` + +No matching component was found for: + `)+e.join(` > `)}return null},wa.getPublicRootInstance=function(e){if(e=e.current,!e.child)return null;switch(e.child.tag){case 27:case 5:return Xa(e.child.stateNode);default:return e.child.stateNode}},wa.injectIntoDevTools=function(){var e={bundleType:0,version:qa,rendererPackageName:Ja,currentDispatcherRef:Ka,reconcilerVersion:`19.2.0`};if(Ya!==null&&(e.rendererConfig=Ya),typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>`u`)e=!1;else{var t=__REACT_DEVTOOLS_GLOBAL_HOOK__;if(t.isDisabled||!t.supportsFiber)e=!0;else{try{jc=t.inject(e),Mc=t}catch{}e=!!t.checkDCE}}return e},wa.isAlreadyRendering=function(){return(wu&6)!=0},wa.observeVisibleRects=function(e,t,n,i){if(!No)throw Error(r(363));e=Ti(e,t);var a=Bo(e,n,i).disconnect;return{disconnect:function(){a()}}},wa.shouldError=function(){return null},wa.shouldSuspend=function(){return!1},wa.startHostTransition=function(e,t,i,a){if(e.tag!==5)throw Error(r(476));var o=Tn(e).queue;wn(e,o,t,Oo,i===null?n:function(){var t=Tn(e);return t.next===null&&(t=e.alternate.memoizedState),jn(e,t.next.queue,{},Ei()),i(a)})},wa.updateContainer=function(e,t,n,r){var i=t.current,a=Ei();return xa(i,a,e,t,n,r),a},wa.updateContainerSync=function(e,t,n,r){return xa(t.current,2,e,t,n,r),2},wa},e.exports.default=e.exports,Object.defineProperty(e.exports,`__esModule`,{value:!0})}(cv)),cv.exports}({exports:{}}).exports;var dv;function fv(){return dv||(dv=1,sv.exports=uv()),sv.exports}var pv=ov(fv());function mv(e){let t=pv(e);return t.injectIntoDevTools(),t}var hv=0,gv={},_v=/^three(?=[A-Z])/,vv=e=>`${e[0].toUpperCase()}${e.slice(1)}`,yv=0,bv=e=>typeof e==`function`;function xv(e){if(bv(e)){let t=`${yv++}`;return gv[t]=e,t}else Object.assign(gv,e)}function Sv(e,t){let n=vv(e),r=gv[n];if(e!==`primitive`&&!r)throw Error(`R3F: ${n} is not part of the THREE namespace! Did you forget to extend? See: https://docs.pmnd.rs/react-three-fiber/api/objects#using-3rd-party-objects-declaratively`);if(e===`primitive`&&!t.object)throw Error(`R3F: Primitives without 'object' are invalid!`);if(t.args!==void 0&&!Array.isArray(t.args))throw Error(`R3F: The args prop must be an array!`)}function Cv(e,t,n){var r;return e=vv(e)in gv?e:e.replace(_v,``),Sv(e,t),e===`primitive`&&(r=t.object)!=null&&r.__r3f&&delete t.object.__r3f,E_(t.object,n,e,t)}function wv(e){if(!e.isHidden){var t;e.props.attach&&(t=e.parent)!=null&&t.object?A_(e.parent,e):B_(e.object)&&(e.object.visible=!1),e.isHidden=!0,R_(e)}}function Tv(e){if(e.isHidden){var t;e.props.attach&&(t=e.parent)!=null&&t.object?k_(e.parent,e):B_(e.object)&&e.props.visible!==!1&&(e.object.visible=!0),e.isHidden=!1,R_(e)}}function Ev(e,t,n){let r=t.root.getState();if(!(!e.parent&&e.object!==r.scene)){if(!t.object){let e=gv[vv(t.type)];t.object=t.props.object??new e(...t.props.args??[]),t.object.__r3f=t}if(L_(t.object,t.props),t.props.attach)k_(e,t);else if(B_(t.object)&&B_(e.object)){let r=e.object.children.indexOf(n?.object);if(n&&r!==-1){let n=e.object.children.indexOf(t.object);if(n!==-1){e.object.children.splice(n,1);let i=n{try{e.dispose()}catch{}};typeof IS_REACT_ACT_ENVIRONMENT<`u`?t():(0,e_.unstable_scheduleCallback)(e_.unstable_IdlePriority,t)}}function Av(e,t,n){if(!t)return;t.parent=null;let r=e.children.indexOf(t);r!==-1&&e.children.splice(r,1),t.props.attach?A_(e,t):B_(t.object)&&B_(e.object)&&(e.object.remove(t.object),U_(u_(t),t.object));let i=t.props.dispose!==null&&n!==!1;for(let e=t.children.length-1;e>=0;e--){let n=t.children[e];Av(t,n,i)}t.children.length=0,delete t.object.__r3f,i&&t.type!==`primitive`&&t.object.type!==`Scene`&&kv(t.object),n===void 0&&R_(t)}function jv(e,t){for(let n of[e,e.alternate])if(n!==null)if(typeof n.ref==`function`){n.refCleanup==null||n.refCleanup();let e=n.ref(t);typeof e==`function`&&(n.refCleanup=e)}else n.ref&&(n.ref.current=t)}var Mv=[];function Nv(){for(let[e]of Mv){let t=e.parent;if(t){e.props.attach?A_(t,e):B_(e.object)&&B_(t.object)&&t.object.remove(e.object);for(let t of e.children)t.props.attach?A_(e,t):B_(t.object)&&B_(e.object)&&e.object.remove(t.object)}e.isHidden&&Tv(e),e.object.__r3f&&delete e.object.__r3f,e.type!==`primitive`&&kv(e.object)}for(let[e,t,n]of Mv){e.props=t;let r=e.parent;if(r){let t=gv[vv(e.type)];e.object=e.props.object??new t(...e.props.args??[]),e.object.__r3f=e,jv(n,e.object),L_(e.object,e.props),e.props.attach?k_(r,e):B_(e.object)&&B_(r.object)&&r.object.add(e.object);for(let t of e.children)t.props.attach?k_(e,t):B_(t.object)&&B_(e.object)&&e.object.add(t.object);R_(e)}}Mv.length=0}var Pv=()=>{},Fv={},Iv=hv,Lv=0,Rv=4,zv=mv({isPrimaryRenderer:!1,warnsIfNotActing:!1,supportsMutation:!0,supportsPersistence:!1,supportsHydration:!1,createInstance:Cv,removeChild:Av,appendChild:Dv,appendInitialChild:Dv,insertBefore:Ov,appendChildToContainer(e,t){let n=e.getState().scene.__r3f;!t||!n||Dv(n,t)},removeChildFromContainer(e,t){let n=e.getState().scene.__r3f;!t||!n||Av(n,t)},insertInContainerBefore(e,t,n){let r=e.getState().scene.__r3f;!t||!n||!r||Ov(r,t,n)},getRootHostContext:()=>Fv,getChildHostContext:()=>Fv,commitUpdate(e,t,n,r,i){var a;Sv(t,r);let o=!1;if(e.type===`primitive`&&n.object!==r.object?o=!0:r.args?.length===n.args?.length?(a=r.args)!=null&&a.some((e,t)=>e!==n.args?.[t])&&(o=!0):o=!0,o)Mv.push([e,{...r},i]);else{let t=P_(e,r);Object.keys(t).length&&(Object.assign(e.props,t),L_(e.object,t))}(i.sibling===null||(i.flags&Rv)===Lv)&&Nv()},finalizeInitialChildren:()=>!1,commitMount(){},getPublicInstance:e=>e?.object,prepareForCommit:()=>null,preparePortalMount:e=>E_(e.getState().scene,e,``,{}),resetAfterCommit:()=>{},shouldSetTextContent:()=>!1,clearContainer:()=>!1,hideInstance:wv,unhideInstance:Tv,createTextInstance:Pv,hideTextInstance:Pv,unhideTextInstance:Pv,scheduleTimeout:typeof setTimeout==`function`?setTimeout:void 0,cancelTimeout:typeof clearTimeout==`function`?clearTimeout:void 0,noTimeout:-1,getInstanceFromNode:()=>null,beforeActiveInstanceBlur(){},afterActiveInstanceBlur(){},detachDeletedInstance(){},prepareScopeUpdate(){},getInstanceFromScope:()=>null,shouldAttemptEagerTransition:()=>!1,trackSchedulerEvent:()=>{},resolveEventType:()=>null,resolveEventTimeStamp:()=>-1.1,requestPostPaintCallback(){},maySuspendCommit:()=>!1,preloadInstance:()=>!0,suspendInstance(){},waitForCommitToBeReady:()=>null,NotPendingTransition:null,HostTransitionContext:y.createContext(null),setCurrentUpdatePriority(e){Iv=e},getCurrentUpdatePriority(){return Iv},resolveUpdatePriority(){if(Iv!==hv)return Iv;switch(typeof window<`u`&&window.event?.type){case`click`:case`contextmenu`:case`dblclick`:case`pointercancel`:case`pointerdown`:case`pointerup`:return iv;case`pointermove`:case`pointerout`:case`pointerover`:case`pointerenter`:case`pointerleave`:case`wheel`:return nv;default:return rv}},resetFormInstance(){},rendererPackageName:`@react-three/fiber`,rendererVersion:av.version,applyViewTransitionName(e,t,n){},restoreViewTransitionName(e,t){},cancelViewTransitionName(e,t,n){},cancelRootViewTransitionName(e){},restoreRootViewTransitionName(e){},InstanceMeasurement:null,measureInstance:e=>null,wasInstanceInViewport:e=>!0,hasInstanceChanged:(e,t)=>!1,hasInstanceAffectedParent:(e,t)=>!1,suspendOnActiveViewTransition(e,t){},startGestureTransition:()=>null,startViewTransition:()=>null,stopViewTransition(e){},createViewTransitionInstance:e=>null,getCurrentGestureOffset(e){throw Error(`startGestureTransition is not yet supported in react-three-fiber.`)},cloneMutableInstance(e,t){return e},cloneMutableTextInstance(e){return e},cloneRootViewTransitionContainer(e){throw Error(`Not implemented.`)},removeRootViewTransitionClone(e,t){throw Error(`Not implemented.`)},createFragmentInstance:e=>null,updateFragmentInstanceFiber(e,t){},commitNewChildToFragmentInstance(e,t){},deleteChildFromFragmentInstance(e,t){},measureClonedInstance:e=>null,maySuspendCommitOnUpdate:(e,t,n)=>!1,maySuspendCommitInSyncRender:(e,t)=>!1,startSuspendingCommit:()=>null,getSuspendedCommitReason:(e,t)=>null}),Bv=new Map,Vv={objects:`shallow`,strict:!1};function Hv(e,t){if(!t&&typeof HTMLCanvasElement<`u`&&e instanceof HTMLCanvasElement&&e.parentElement){let{width:t,height:n,top:r,left:i}=e.parentElement.getBoundingClientRect();return{width:t,height:n,top:r,left:i}}else if(!t&&typeof OffscreenCanvas<`u`&&e instanceof OffscreenCanvas)return{width:e.width,height:e.height,top:0,left:0};return{width:0,height:0,top:0,left:0,...t}}function Uv(e){let t=Bv.get(e),n=t?.fiber,r=t?.store;t&&console.warn(`R3F.createRoot should only be called once!`);let i=typeof reportError==`function`?reportError:console.error,a=r||q_(cy,ly),o=n||zv.createContainer(a,tv,null,!1,null,``,i,i,i,null);t||Bv.set(e,{fiber:o,store:a});let s,c,l=!1,u=null;return{async configure(t={}){let n;u=new Promise(e=>n=e);let{gl:r,size:i,scene:o,events:d,onCreated:f,shadows:p=!1,linear:m=!1,flat:h=!1,legacy:g=!1,orthographic:_=!1,frameloop:v=`always`,dpr:y=[1,2],performance:b,raycaster:x,camera:S,onPointerMissed:C}=t,w=a.getState(),T=w.gl;if(!w.gl){let t={canvas:e,powerPreference:`high-performance`,antialias:!0,alpha:!0},n=typeof r==`function`?await r(t):r;T=G_(n)?n:new Fg({...t,...r}),w.set({gl:T})}let E=w.raycaster;E||w.set({raycaster:E=new _f});let{params:D,...O}=x||{};if(x_.equ(O,E,Vv)||L_(E,{...O}),x_.equ(D,E.params,Vv)||L_(E,{params:{...E.params,...D}}),!w.camera||w.camera===c&&!x_.equ(c,S,Vv)){c=S;let e=S?.isCamera,t=e?S:_?new rd(0,0,0,0,.1,1e3):new Qu(75,0,.1,1e3);e||(t.position.z=5,S&&(L_(t,S),t.manual||(`aspect`in S||`left`in S||`right`in S||`bottom`in S||`top`in S)&&(t.manual=!0,t.updateProjectionMatrix())),!w.camera&&!(S!=null&&S.rotation)&&t.lookAt(0,0,0)),w.set({camera:t}),E.camera=t}if(!w.scene){let e;o!=null&&o.isScene?(e=o,E_(e,a,``,{})):(e=new vi,E_(e,a,``,{}),o&&L_(e,o)),w.set({scene:e})}d&&!w.events.handlers&&w.set({events:d(a)});let k=Hv(e,i);if(x_.equ(k,w.size,Vv)||w.setSize(k.width,k.height,k.top,k.left),y&&w.viewport.dpr!==y_(y)&&w.setDpr(y),w.frameloop!==v&&w.setFrameloop(v),w.onPointerMissed||w.set({onPointerMissed:C}),b&&!x_.equ(b,w.performance,Vv)&&w.set(e=>({performance:{...e.performance,...b}})),!w.xr){let e=(e,t)=>{let n=a.getState();n.frameloop!==`never`&&ly(e,!0,n,t)},t=()=>{let t=a.getState();t.gl.xr.enabled=t.gl.xr.isPresenting,t.gl.xr.setAnimationLoop(t.gl.xr.isPresenting?e:null),t.gl.xr.isPresenting||cy(t)},n={connect(){let e=a.getState().gl;e.xr.addEventListener(`sessionstart`,t),e.xr.addEventListener(`sessionend`,t)},disconnect(){let e=a.getState().gl;e.xr.removeEventListener(`sessionstart`,t),e.xr.removeEventListener(`sessionend`,t)}};typeof T.xr?.addEventListener==`function`&&n.connect(),w.set({xr:n})}if(T.shadowMap){let e=T.shadowMap.enabled,t=T.shadowMap.type;if(T.shadowMap.enabled=!!p,x_.boo(p))T.shadowMap.type=2;else if(x_.str(p)){let e={basic:0,percentage:1,soft:2,variance:3};T.shadowMap.type=e[p]??2}else x_.obj(p)&&Object.assign(T.shadowMap,p);(e!==T.shadowMap.enabled||t!==T.shadowMap.type)&&(T.shadowMap.needsUpdate=!0)}return gr.enabled=!g,l||(T.outputColorSpace=m?Gt:Wt,T.toneMapping=h?0:4),w.legacy!==g&&w.set(()=>({legacy:g})),w.linear!==m&&w.set(()=>({linear:m})),w.flat!==h&&w.set(()=>({flat:h})),r&&!x_.fun(r)&&!G_(r)&&!x_.equ(r,T,Vv)&&L_(T,r),s=f,l=!0,n(),this},render(t){return!l&&!u&&this.configure(),u.then(()=>{zv.updateContainer((0,N.jsx)(Wv,{store:a,children:t,onCreated:s,rootElement:e}),o,null,()=>void 0)}),a},unmount(){Gv(e)}}}function Wv({store:e,children:t,onCreated:n,rootElement:r}){return m_(()=>{let t=e.getState();t.set(e=>({internal:{...e.internal,active:!0}})),n&&n(t),e.getState().events.connected||t.events.connect==null||t.events.connect(r)},[]),(0,N.jsx)(K_.Provider,{value:e,children:t})}function Gv(e,t){let n=Bv.get(e),r=n?.fiber;if(r){let i=n?.store.getState();i&&(i.internal.active=!1),zv.updateContainer(null,r,null,()=>{i&&setTimeout(()=>{try{var n,r,a,o;i.events.disconnect==null||i.events.disconnect(),(n=i.gl)==null||(r=n.renderLists)==null||r.dispose==null||r.dispose(),(a=i.gl)==null||a.forceContextLoss==null||a.forceContextLoss(),(o=i.gl)!=null&&o.xr&&i.xr.disconnect(),C_(i.scene),Bv.delete(e),t&&t(e)}catch{}},500)})}}function Kv(e,t,n){return(0,N.jsx)(qv,{children:e,container:t,state:n})}function qv({state:e={},children:t,container:n}){let{events:r,size:i,...a}=e,o=J_(),[s]=y.useState(()=>new _f),[c]=y.useState(()=>new V),l=h_((e,t)=>{let a;if(t.camera&&i){let n=t.camera;a=e.viewport.getCurrentViewport(n,new H,i),n!==e.camera&&z_(n,i)}return{...e,...t,scene:n,raycaster:s,pointer:c,mouse:c,previousRoot:o,events:{...e.events,...t.events,...r},size:{...e.size,...i},viewport:{...e.viewport,...a},setEvents:e=>t.set(t=>({...t,events:{...t.events,...e}}))}}),u=y.useMemo(()=>{let e=Kg((e,t)=>({...a,set:e,get:t})),t=t=>e.setState(e=>l.current(t,e));return t(o.getState()),o.subscribe(t),e},[o,n]);return(0,N.jsx)(N.Fragment,{children:zv.createPortal((0,N.jsx)(K_.Provider,{value:u,children:t}),u,null)})}var Jv=new Set,Yv=new Set,Xv=new Set;function Zv(e,t){if(e.size)for(let{callback:n}of e.values())n(t)}function Qv(e,t){switch(e){case`before`:return Zv(Jv,t);case`after`:return Zv(Yv,t);case`tail`:return Zv(Xv,t)}}var $v,ey;function ty(e,t,n){let r=t.clock.getDelta();t.frameloop===`never`&&typeof e==`number`&&(r=e-t.clock.elapsedTime,t.clock.oldTime=t.clock.elapsedTime,t.clock.elapsedTime=e),$v=t.internal.subscribers;for(let e=0;e<$v.length;e++)ey=$v[e],ey.ref.current(ey.store.getState(),r,n);return!t.internal.priority&&t.gl.render&&t.gl.render(t.scene,t.camera),t.internal.frames=Math.max(0,t.internal.frames-1),t.frameloop===`always`?1:t.internal.frames}var ny=!1,ry=!1,iy,ay,oy;function sy(e){ay=requestAnimationFrame(sy),ny=!0,iy=0,Qv(`before`,e),ry=!0;for(let n of Bv.values()){var t;oy=n.store.getState(),oy.internal.active&&(oy.frameloop===`always`||oy.internal.frames>0)&&!((t=oy.gl.xr)!=null&&t.isPresenting)&&(iy+=ty(e,oy))}if(ry=!1,Qv(`after`,e),iy===0)return Qv(`tail`,e),ny=!1,cancelAnimationFrame(ay)}function cy(e,t=1){var n;if(!e)return Bv.forEach(e=>cy(e.store.getState(),t));(n=e.gl.xr)!=null&&n.isPresenting||!e.internal.active||e.frameloop===`never`||(t>1?e.internal.frames=Math.min(60,e.internal.frames+t):ry?e.internal.frames=2:e.internal.frames=1,ny||(ny=!0,requestAnimationFrame(sy)))}function ly(e,t=!0,n,r){if(t&&Qv(`before`,e),n)ty(e,n,r);else for(let t of Bv.values())ty(e,t.store.getState());t&&Qv(`after`,e)}var uy={onClick:[`click`,!1],onContextMenu:[`contextmenu`,!1],onDoubleClick:[`dblclick`,!1],onWheel:[`wheel`,!0],onPointerDown:[`pointerdown`,!0],onPointerUp:[`pointerup`,!0],onPointerLeave:[`pointerleave`,!0],onPointerMove:[`pointermove`,!0],onPointerCancel:[`pointercancel`,!0],onLostPointerCapture:[`lostpointercapture`,!0]};function dy(e){let{handlePointer:t}=W_(e);return{priority:1,enabled:!0,compute(e,t,n){t.pointer.set(e.offsetX/t.size.width*2-1,-(e.offsetY/t.size.height)*2+1),t.raycaster.setFromCamera(t.pointer,t.camera)},connected:void 0,handlers:Object.keys(uy).reduce((e,n)=>({...e,[n]:t(n)}),{}),update:()=>{var t;let{events:n,internal:r}=e.getState();(t=r.lastEvent)!=null&&t.current&&n.handlers&&n.handlers.onPointerMove(r.lastEvent.current)},connect:t=>{let{set:n,events:r}=e.getState();if(r.disconnect==null||r.disconnect(),n(e=>({events:{...e.events,connected:t}})),r.handlers)for(let e in r.handlers){let n=r.handlers[e],[i,a]=uy[e];t.addEventListener(i,n,{passive:a})}},disconnect:()=>{let{set:t,events:n}=e.getState();if(n.connected){if(n.handlers)for(let e in n.handlers){let t=n.handlers[e],[r]=uy[e];n.connected.removeEventListener(r,t)}t(e=>({events:{...e.events,connected:void 0}}))}}}}function fy(e,t){let n;return(...r)=>{window.clearTimeout(n),n=window.setTimeout(()=>e(...r),t)}}function py({debounce:e,scroll:t,polyfill:n,offsetSize:r}={debounce:0,scroll:!1,offsetSize:!1}){let i=n||(typeof window>`u`?class{}:window.ResizeObserver);if(!i)throw Error(`This browser does not support ResizeObserver out of the box. See: https://github.com/react-spring/react-use-measure/#resize-observer-polyfills`);let[a,o]=(0,y.useState)({left:0,top:0,width:0,height:0,bottom:0,right:0,x:0,y:0}),s=(0,y.useRef)({element:null,scrollContainers:null,resizeObserver:null,lastBounds:a,orientationHandler:null}),c=e?typeof e==`number`?e:e.scroll:null,l=e?typeof e==`number`?e:e.resize:null,u=(0,y.useRef)(!1);(0,y.useEffect)(()=>(u.current=!0,()=>void(u.current=!1)));let[d,f,p]=(0,y.useMemo)(()=>{let e=()=>{if(!s.current.element)return;let{left:e,top:t,width:n,height:i,bottom:a,right:c,x:l,y:d}=s.current.element.getBoundingClientRect(),f={left:e,top:t,width:n,height:i,bottom:a,right:c,x:l,y:d};s.current.element instanceof HTMLElement&&r&&(f.height=s.current.element.offsetHeight,f.width=s.current.element.offsetWidth),Object.freeze(f),u.current&&!vy(s.current.lastBounds,f)&&o(s.current.lastBounds=f)};return[e,l?fy(e,l):e,c?fy(e,c):e]},[o,r,c,l]);function m(){s.current.scrollContainers&&(s.current.scrollContainers.forEach(e=>e.removeEventListener(`scroll`,p,!0)),s.current.scrollContainers=null),s.current.resizeObserver&&(s.current.resizeObserver.disconnect(),s.current.resizeObserver=null),s.current.orientationHandler&&(`orientation`in screen&&`removeEventListener`in screen.orientation?screen.orientation.removeEventListener(`change`,s.current.orientationHandler):`onorientationchange`in window&&window.removeEventListener(`orientationchange`,s.current.orientationHandler))}function h(){s.current.element&&(s.current.resizeObserver=new i(p),s.current.resizeObserver.observe(s.current.element),t&&s.current.scrollContainers&&s.current.scrollContainers.forEach(e=>e.addEventListener(`scroll`,p,{capture:!0,passive:!0})),s.current.orientationHandler=()=>{p()},`orientation`in screen&&`addEventListener`in screen.orientation?screen.orientation.addEventListener(`change`,s.current.orientationHandler):`onorientationchange`in window&&window.addEventListener(`orientationchange`,s.current.orientationHandler))}return hy(p,!!t),my(f),(0,y.useEffect)(()=>{m(),h()},[t,p,f]),(0,y.useEffect)(()=>m,[]),[e=>{!e||e===s.current.element||(m(),s.current.element=e,s.current.scrollContainers=gy(e),h())},a,d]}function my(e){(0,y.useEffect)(()=>{let t=e;return window.addEventListener(`resize`,t),()=>void window.removeEventListener(`resize`,t)},[e])}function hy(e,t){(0,y.useEffect)(()=>{if(t){let t=e;return window.addEventListener(`scroll`,t,{capture:!0,passive:!0}),()=>void window.removeEventListener(`scroll`,t,!0)}},[e,t])}function gy(e){let t=[];if(!e||e===document.body)return t;let{overflow:n,overflowX:r,overflowY:i}=window.getComputedStyle(e);return[n,r,i].some(e=>e===`auto`||e===`scroll`)&&t.push(e),[...t,...gy(e.parentElement)]}var _y=[`x`,`y`,`top`,`bottom`,`left`,`right`,`width`,`height`],vy=(e,t)=>_y.every(n=>e[n]===t[n]);function yy({ref:e,children:t,fallback:n,resize:r,style:i,gl:a,events:o=dy,eventSource:s,eventPrefix:c,shadows:l,linear:u,flat:d,legacy:f,orthographic:p,frameloop:m,dpr:h,performance:g,raycaster:_,camera:v,scene:b,onPointerMissed:x,onCreated:S,...C}){y.useMemo(()=>xv(yp),[]);let w=g_(),[T,E]=py({scroll:!0,debounce:{scroll:50,resize:0},...r}),D=y.useRef(null),O=y.useRef(null);y.useImperativeHandle(e,()=>D.current);let k=h_(x),[A,j]=y.useState(!1),[ee,M]=y.useState(!1);if(A)throw A;if(ee)throw ee;let P=y.useRef(null);return m_(()=>{let e=D.current;if(E.width>0&&E.height>0&&e){P.current||=Uv(e);async function n(){await P.current.configure({gl:a,scene:b,events:o,shadows:l,linear:u,flat:d,legacy:f,orthographic:p,frameloop:m,dpr:h,performance:g,raycaster:_,camera:v,size:E,onPointerMissed:(...e)=>k.current==null?void 0:k.current(...e),onCreated:e=>{e.events.connect==null||e.events.connect(s?f_(s)?s.current:s:O.current),c&&e.setEvents({compute:(e,t)=>{let n=e[c+`X`],r=e[c+`Y`];t.pointer.set(n/t.size.width*2-1,-(r/t.size.height)*2+1),t.raycaster.setFromCamera(t.pointer,t.camera)}}),S?.(e)}}),P.current.render((0,N.jsx)(w,{children:(0,N.jsx)(v_,{set:M,children:(0,N.jsx)(y.Suspense,{fallback:(0,N.jsx)(__,{set:j}),children:t??null})})}))}n()}}),y.useEffect(()=>{let e=D.current;if(e)return()=>Gv(e)},[]),(0,N.jsx)(`div`,{ref:O,style:{position:`relative`,width:`100%`,height:`100%`,overflow:`hidden`,pointerEvents:s?`none`:`auto`,...i},...C,children:(0,N.jsx)(`div`,{ref:T,style:{width:`100%`,height:`100%`},children:(0,N.jsx)(`canvas`,{ref:D,style:{display:`block`},children:n})})})}function by(e){return(0,N.jsx)(i_,{children:(0,N.jsx)(yy,{...e})})}var xy=parseInt(`183`.replace(/\D+/g,``)),Sy=Uint8Array,Cy=Uint16Array,wy=Uint32Array,Ty=new Sy([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),Ey=new Sy([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),Dy=new Sy([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Oy=function(e,t){for(var n=new Cy(31),r=0;r<31;++r)n[r]=t+=1<>>1|(Fy&21845)<<1;Iy=(Iy&52428)>>>2|(Iy&13107)<<2,Iy=(Iy&61680)>>>4|(Iy&3855)<<4,Py[Fy]=((Iy&65280)>>>8|(Iy&255)<<8)>>>1}for(var Ly=(function(e,t,n){for(var r=e.length,i=0,a=new Cy(t);i>>c]=l}else for(s=new Cy(r),i=0;i>>15-e[i]);return s}),Ry=new Sy(288),Fy=0;Fy<144;++Fy)Ry[Fy]=8;for(var Fy=144;Fy<256;++Fy)Ry[Fy]=9;for(var Fy=256;Fy<280;++Fy)Ry[Fy]=7;for(var Fy=280;Fy<288;++Fy)Ry[Fy]=8;for(var zy=new Sy(32),Fy=0;Fy<32;++Fy)zy[Fy]=5;Ly(Ry,9,0);var By=Ly(Ry,9,1);Ly(zy,5,0);var Vy=Ly(zy,5,1),Hy=function(e){for(var t=e[0],n=1;nt&&(t=e[n]);return t},Uy=function(e,t,n){var r=t/8|0;return(e[r]|e[r+1]<<8)>>(t&7)&n},Wy=function(e,t){var n=t/8|0;return(e[n]|e[n+1]<<8|e[n+2]<<16)>>(t&7)},Gy=function(e){return(e/8|0)+(e&7&&1)},Ky=function(e,t,n){(t==null||t<0)&&(t=0),(n==null||n>e.length)&&(n=e.length);var r=new(e instanceof Cy?Cy:e instanceof wy?wy:Sy)(n-t);return r.set(e.subarray(t,n)),r},qy=function(e,t,n){var r=e.length;if(!r||n&&!n.l&&r<5)return t||new Sy(0);var i=!t||n,a=!n||n.i;n||={},t||=new Sy(r*3);var o=function(e){var n=t.length;if(e>n){var r=new Sy(Math.max(n*2,e));r.set(t),t=r}},s=n.f||0,c=n.p||0,l=n.b||0,u=n.l,d=n.d,f=n.m,p=n.n,m=r*8;do{if(!u){n.f=s=Uy(e,c,1);var h=Uy(e,c+1,3);if(c+=3,!h){var g=Gy(c)+4,_=e[g-4]|e[g-3]<<8,v=g+_;if(v>r){if(a)throw`unexpected EOF`;break}i&&o(l+_),t.set(e.subarray(g,v),l),n.b=l+=_,n.p=c=v*8;continue}else if(h==1)u=By,d=Vy,f=9,p=5;else if(h==2){var y=Uy(e,c,31)+257,b=Uy(e,c+10,15)+4,x=y+Uy(e,c+5,31)+1;c+=14;for(var S=new Sy(x),C=new Sy(19),w=0;w>>4;if(g<16)S[w++]=g;else{var k=0,A=0;for(g==16?(A=3+Uy(e,c,3),c+=2,k=S[w-1]):g==17?(A=3+Uy(e,c,7),c+=3):g==18&&(A=11+Uy(e,c,127),c+=7);A--;)S[w++]=k}}var j=S.subarray(0,y),ee=S.subarray(y);f=Hy(j),p=Hy(ee),u=Ly(j,f,1),d=Ly(ee,p,1)}else throw`invalid block type`;if(c>m){if(a)throw`unexpected EOF`;break}}i&&o(l+131072);for(var M=(1<>>4;if(c+=k&15,c>m){if(a)throw`unexpected EOF`;break}if(!k)throw`invalid length/literal`;if(F<256)t[l++]=F;else if(F==256){P=c,u=null;break}else{var te=F-254;if(F>264){var w=F-257,ne=Ty[w];te=Uy(e,c,(1<>>4;if(!re)throw`invalid distance`;c+=re&15;var ee=Ny[ie];if(ie>3){var ne=Ey[ie];ee+=Wy(e,c)&(1<m){if(a)throw`unexpected EOF`;break}i&&o(l+131072);for(var ae=l+te;l>>4>7||(e[0]<<8|e[1])%31)throw`invalid zlib data`;if(e[1]&32)throw`invalid zlib data: preset dictionaries not supported`};function Xy(e,t){return qy((Yy(e),e.subarray(2,-4)),t)}var Zy=typeof TextDecoder<`u`&&new TextDecoder;try{Zy.decode(Jy,{stream:!0})}catch{}var Qy=e=>e&&e.isCubeTexture,$y=class extends fo{constructor(e,t){let n=Qy(e),r=((n?e.image[0]?.width:e.image.width)??1024)/4,i=Math.floor(Math.log2(r)),a=2**i,o=3*Math.max(a,112),s=4*a,c=[n?`#define ENVMAP_TYPE_CUBE`:``,`#define CUBEUV_TEXEL_WIDTH ${1/o}`,`#define CUBEUV_TEXEL_HEIGHT ${1/s}`,`#define CUBEUV_MAX_MIP ${i}.0`].join(` +`)+` + #define ENVMAP_TYPE_CUBE_UV + varying vec3 vWorldPosition; + uniform float radius; + uniform float height; + uniform float angle; + #ifdef ENVMAP_TYPE_CUBE + uniform samplerCube map; + #else + uniform sampler2D map; + #endif + // From: https://www.shadertoy.com/view/4tsBD7 + float diskIntersectWithBackFaceCulling( vec3 ro, vec3 rd, vec3 c, vec3 n, float r ) + { + float d = dot ( rd, n ); + + if( d > 0.0 ) { return 1e6; } + + vec3 o = ro - c; + float t = - dot( n, o ) / d; + vec3 q = o + rd * t; + + return ( dot( q, q ) < r * r ) ? t : 1e6; + } + // From: https://www.iquilezles.org/www/articles/intersectors/intersectors.htm + float sphereIntersect( vec3 ro, vec3 rd, vec3 ce, float ra ) + { + vec3 oc = ro - ce; + float b = dot( oc, rd ); + float c = dot( oc, oc ) - ra * ra; + float h = b * b - c; + + if( h < 0.0 ) { return -1.0; } + + h = sqrt( h ); + + return - b + h; + } + vec3 project() + { + vec3 p = normalize( vWorldPosition ); + vec3 camPos = cameraPosition; + camPos.y -= height; + float intersection = sphereIntersect( camPos, p, vec3( 0.0 ), radius ); + if( intersection > 0.0 ) { + + vec3 h = vec3( 0.0, - height, 0.0 ); + float intersection2 = diskIntersectWithBackFaceCulling( camPos, p, h, vec3( 0.0, 1.0, 0.0 ), radius ); + p = ( camPos + min( intersection, intersection2 ) * p ) / radius; + } else { + p = vec3( 0.0, 1.0, 0.0 ); + } + return p; + } + #include + #include + void main() + { + vec3 projectedWorldPosition = project(); + + #ifdef ENVMAP_TYPE_CUBE + vec3 outcolor = textureCube( map, projectedWorldPosition ).rgb; + #else + vec3 direction = normalize( projectedWorldPosition ); + vec2 uv = equirectUv( direction ); + vec3 outcolor = texture2D( map, uv ).rgb; + #endif + gl_FragColor = vec4( outcolor, 1.0 ); + #include + #include <${xy>=154?`colorspace_fragment`:`encodings_fragment`}> + } + `,l={map:{value:e},height:{value:t?.height||15},radius:{value:t?.radius||100}},u=new xl(1,16),d=new q({uniforms:l,fragmentShader:c,vertexShader:` + varying vec3 vWorldPosition; + void main() + { + vec4 worldPosition = ( modelMatrix * vec4( position, 1.0 ) ); + vWorldPosition = worldPosition.xyz; + + gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); + } + `,side:2});super(u,d)}set radius(e){this.material.uniforms.radius.value=e}get radius(){return this.material.uniforms.radius.value}set height(e){this.material.uniforms.height.value=e}get height(){return this.material.uniforms.height.value}},eb=class extends Lu{constructor(e){super(e),this.type=ke}parse(e){let t=function(e,t){switch(e){case 1:throw Error(`THREE.RGBELoader: Read Error: `+(t||``));case 2:throw Error(`THREE.RGBELoader: Write Error: `+(t||``));case 3:throw Error(`THREE.RGBELoader: Bad File Format: `+(t||``));default:case 4:throw Error(`THREE.RGBELoader: Memory Error: `+(t||``))}},n=function(e,t,n){t||=1024;let r=e.pos,i=-1,a=0,o=``,s=String.fromCharCode.apply(null,new Uint16Array(e.subarray(r,r+128)));for(;0>(i=s.indexOf(` +`))&&a=e.byteLength||!(l=n(e)))&&t(1,`no header found`),(u=l.match(r))||t(3,`bad initial token`),c.valid|=1,c.programtype=u[1],c.string+=l+` +`;l=n(e),!1!==l;){if(c.string+=l+` +`,l.charAt(0)===`#`){c.comments+=l+` +`;continue}if((u=l.match(i))&&(c.gamma=parseFloat(u[1])),(u=l.match(a))&&(c.exposure=parseFloat(u[1])),(u=l.match(o))&&(c.valid|=2,c.format=u[1]),(u=l.match(s))&&(c.valid|=4,c.height=parseInt(u[1],10),c.width=parseInt(u[2],10)),c.valid&2&&c.valid&4)break}return c.valid&2||t(3,`missing format specifier`),c.valid&4||t(3,`missing image size specifier`),c},i=function(e,n,r){let i=n;if(i<8||i>32767||e[0]!==2||e[1]!==2||e[2]&128)return new Uint8Array(e);i!==(e[2]<<8|e[3])&&t(3,`wrong scanline width`);let a=new Uint8Array(4*n*r);a.length||t(4,`unable to allocate buffer space`);let o=0,s=0,c=4*i,l=new Uint8Array(4),u=new Uint8Array(c),d=r;for(;d>0&&se.byteLength&&t(1),l[0]=e[s++],l[1]=e[s++],l[2]=e[s++],l[3]=e[s++],(l[0]!=2||l[1]!=2||(l[2]<<8|l[3])!=i)&&t(3,`bad rgbe scanline format`);let n=0,r;for(;n128;if(i&&(r-=128),(r===0||n+r>c)&&t(3,`bad scanline data`),i){let t=e[s++];for(let e=0;e=152,nb=class extends Lu{constructor(e){super(e),this.type=ke}parse(e){let t=65536,n=t>>3,r=65537,i=16384,a=i-1,o=65535,s=2.7182818**2.2;function c(e,n){for(var r=0,i=0;i>3]&1<<(i&7))&&(n[r++]=i);for(var a=r-1;r>n&(1<0;--t){var i=n+f[t]>>1;f[t]=n,n=i}for(var t=0;t0&&(e[t]=a|f[a]++<<6)}}function m(e,t,n,r,i,a,o){for(var s=n,c=0,l=0;i<=a;i++){if(s.value-n.value>r)return!1;d(6,c,l,e,s);var f=u.l;if(c=u.c,l=u.lc,o[i]=f,f==63){if(s.value-n.value>r)throw`Something wrong with hufUnpackEncTable`;d(8,c,l,e,s);var m=u.l+6;if(c=u.c,l=u.lc,i+m>a+1)throw`Something wrong with hufUnpackEncTable`;for(;m--;)o[i++]=0;i--}else if(f>=59){var m=f-59+2;if(i+m>a+1)throw`Something wrong with hufUnpackEncTable`;for(;m--;)o[i++]=0;i--}}p(o)}function h(e){return e&63}function g(e){return e>>6}function _(e,t,n,r){for(;t<=n;t++){var i=g(e[t]),a=h(e[t]);if(i>>a)throw`Invalid table entry`;if(a>14){var o=r[i>>a-14];if(o.len)throw`Invalid table entry`;if(o.lit++,o.p){var s=o.p;o.p=Array(o.lit);for(var c=0;c0;c--){var o=r[(i<<14-a)+l];if(o.len||o.p)throw`Invalid table entry`;o.len=a,o.lit=t,l++}}return!0}let v={c:0,lc:0};function y(e,t,n,r){e=e<<8|I(n,r),t+=8,v.c=e,v.lc=t}let b={c:0,lc:0};function x(e,t,n,r,i,a,o,s,c,l){if(e==t){r<8&&(y(n,r,i,o),n=v.c,r=v.lc),r-=8;var u=n>>r,u=new Uint8Array([u])[0];if(c.value+u>l)return!1;for(var d=s[c.value-1];u-- >0;)s[c.value++]=d}else if(c.value32767?t-65536:t}let w={a:0,b:0};function T(e,t){var n=C(e),r=C(t),i=n+(r&1)+(r>>1),a=i,o=i-r;w.a=a,w.b=o}function E(e,t){var n=S(e),r=S(t),i=n-(r>>1)&o;w.a=r+i-32768&o,w.b=i}function D(e,t,n,r,i,a,o){for(var s=o<16384,c=n>i?i:n,l=1,u;l<=c;)l<<=1;for(l>>=1,u=l,l>>=1;l>=1;){for(var d=0,f=d+a*(i-u),p=a*l,m=a*u,h=r*l,g=r*u,_,v,y,b;d<=f;d+=m){for(var x=d,S=d+r*(n-u);x<=S;x+=g){var C=x+h,D=x+p,O=D+h;s?(T(e[x+t],e[D+t]),_=w.a,y=w.b,T(e[C+t],e[O+t]),v=w.a,b=w.b,T(_,v),e[x+t]=w.a,e[C+t]=w.b,T(y,b),e[D+t]=w.a,e[O+t]=w.b):(E(e[x+t],e[D+t]),_=w.a,y=w.b,E(e[C+t],e[O+t]),v=w.a,b=w.b,E(_,v),e[x+t]=w.a,e[C+t]=w.b,E(y,b),e[D+t]=w.a,e[O+t]=w.b)}if(n&l){var D=x+p;s?T(e[x+t],e[D+t]):E(e[x+t],e[D+t]),_=w.a,e[D+t]=w.b,e[x+t]=_}}if(i&l)for(var x=d,S=d+r*(n-u);x<=S;x+=g){var C=x+h;s?T(e[x+t],e[C+t]):E(e[x+t],e[C+t]),_=w.a,e[C+t]=w.b,e[x+t]=_}u=l,l>>=1}return d}function O(e,t,n,r,i,o,s,c,l,u){for(var d=0,f=0,p=c,m=Math.trunc(i.value+(o+7)/8);i.value=14;){var _=t[d>>f-14&a];if(_.len)f-=_.len,x(_.lit,s,d,f,n,r,i,l,u,p),d=b.c,f=b.lc;else{if(!_.p)throw`hufDecode issues`;var S;for(S=0;S<_.lit;S++){for(var C=h(e[_.p[S]]);f=C&&g(e[_.p[S]])==(d>>f-C&(1<>=w,f-=w;f>0;){var _=t[d<<14-f&a];if(_.len)f-=_.len,x(_.lit,s,d,f,n,r,i,l,u,p),d=b.c,f=b.lc;else throw`hufDecode issues`}return!0}function k(e,t,n,a,o,s){var c={value:0},u=n.value,d=ge(t,n),f=ge(t,n);n.value+=4;var p=ge(t,n);if(n.value+=4,d<0||d>=r||f<0||f>=r)throw`Something wrong with HUF_ENCSIZE`;var h=Array(r),g=Array(i);if(l(g),m(e,t,n,a-(n.value-u),d,f,h),p>8*(a-(n.value-u)))throw`Something wrong with hufUncompress`;_(h,d,f,g),O(h,g,e,t,n,p,f,s,o,c)}function A(e,t,n){for(var r=0;ra||(t[i++]=e[n++],i>a));)t[i++]=e[r++]}function M(e){for(var t=e.byteLength,n=[],r=0,i=new DataView(e);t>0;){var a=i.getInt8(r++);if(a<0){var o=-a;t-=o+1;for(var s=0;s>8==255?i+=r&255:(n[i]=r,i++),e.value++}function F(e,t){t[0]=R(e[0]),t[1]=R(e[1]),t[2]=R(e[5]),t[3]=R(e[6]),t[4]=R(e[14]),t[5]=R(e[15]),t[6]=R(e[27]),t[7]=R(e[28]),t[8]=R(e[2]),t[9]=R(e[4]),t[10]=R(e[7]),t[11]=R(e[13]),t[12]=R(e[16]),t[13]=R(e[26]),t[14]=R(e[29]),t[15]=R(e[42]),t[16]=R(e[3]),t[17]=R(e[8]),t[18]=R(e[12]),t[19]=R(e[17]),t[20]=R(e[25]),t[21]=R(e[30]),t[22]=R(e[41]),t[23]=R(e[43]),t[24]=R(e[9]),t[25]=R(e[11]),t[26]=R(e[18]),t[27]=R(e[24]),t[28]=R(e[31]),t[29]=R(e[40]),t[30]=R(e[44]),t[31]=R(e[53]),t[32]=R(e[10]),t[33]=R(e[19]),t[34]=R(e[23]),t[35]=R(e[32]),t[36]=R(e[39]),t[37]=R(e[45]),t[38]=R(e[52]),t[39]=R(e[54]),t[40]=R(e[20]),t[41]=R(e[22]),t[42]=R(e[33]),t[43]=R(e[38]),t[44]=R(e[46]),t[45]=R(e[51]),t[46]=R(e[55]),t[47]=R(e[60]),t[48]=R(e[21]),t[49]=R(e[34]),t[50]=R(e[37]),t[51]=R(e[47]),t[52]=R(e[50]),t[53]=R(e[56]),t[54]=R(e[59]),t[55]=R(e[61]),t[56]=R(e[35]),t[57]=R(e[36]),t[58]=R(e[48]),t[59]=R(e[49]),t[60]=R(e[57]),t[61]=R(e[58]),t[62]=R(e[62]),t[63]=R(e[63])}function te(e){let t=.5*Math.cos(3.14159/4),n=.5*Math.cos(3.14159/16),r=.5*Math.cos(3.14159/8),i=.5*Math.cos(3*3.14159/16),a=.5*Math.cos(5*3.14159/16),o=.5*Math.cos(3*3.14159/8),s=.5*Math.cos(7*3.14159/16);for(var c=[,,,,],l=[,,,,],u=[,,,,],d=[,,,,],f=0;f<8;++f){var p=f*8;c[0]=r*e[p+2],c[1]=o*e[p+2],c[2]=r*e[p+6],c[3]=o*e[p+6],l[0]=n*e[p+1]+i*e[p+3]+a*e[p+5]+s*e[p+7],l[1]=i*e[p+1]-s*e[p+3]-n*e[p+5]-a*e[p+7],l[2]=a*e[p+1]-n*e[p+3]+s*e[p+5]+i*e[p+7],l[3]=s*e[p+1]-a*e[p+3]+i*e[p+5]-n*e[p+7],u[0]=t*(e[p+0]+e[p+4]),u[3]=t*(e[p+0]-e[p+4]),u[1]=c[0]+c[3],u[2]=c[1]-c[2],d[0]=u[0]+u[1],d[1]=u[3]+u[2],d[2]=u[3]-u[2],d[3]=u[0]-u[1],e[p+0]=d[0]+l[0],e[p+1]=d[1]+l[1],e[p+2]=d[2]+l[2],e[p+3]=d[3]+l[3],e[p+4]=d[3]-l[3],e[p+5]=d[2]-l[2],e[p+6]=d[1]-l[1],e[p+7]=d[0]-l[0]}for(var m=0;m<8;++m)c[0]=r*e[16+m],c[1]=o*e[16+m],c[2]=r*e[48+m],c[3]=o*e[48+m],l[0]=n*e[8+m]+i*e[24+m]+a*e[40+m]+s*e[56+m],l[1]=i*e[8+m]-s*e[24+m]-n*e[40+m]-a*e[56+m],l[2]=a*e[8+m]-n*e[24+m]+s*e[40+m]+i*e[56+m],l[3]=s*e[8+m]-a*e[24+m]+i*e[40+m]-n*e[56+m],u[0]=t*(e[m]+e[32+m]),u[3]=t*(e[m]-e[32+m]),u[1]=c[0]+c[3],u[2]=c[1]-c[2],d[0]=u[0]+u[1],d[1]=u[3]+u[2],d[2]=u[3]-u[2],d[3]=u[0]-u[1],e[0+m]=d[0]+l[0],e[8+m]=d[1]+l[1],e[16+m]=d[2]+l[2],e[24+m]=d[3]+l[3],e[32+m]=d[3]-l[3],e[40+m]=d[2]-l[2],e[48+m]=d[1]-l[1],e[56+m]=d[0]-l[0]}function ne(e){for(var t=0;t<64;++t){var n=e[0][t],r=e[1][t],i=e[2][t];e[0][t]=n+1.5747*i,e[1][t]=n-.1873*r-.4682*i,e[2][t]=n+1.8556*r}}function re(e,t,n){for(var r=0;r<64;++r)t[n+r]=Zi.toHalfFloat(ie(e[r]))}function ie(e){return e<=1?Math.sign(e)*Math.abs(e)**2.2:Math.sign(e)*s**(Math.abs(e)-1)}function ae(e){return new DataView(e.array.buffer,e.offset.value,e.size)}function oe(e){var t=e.viewer.buffer.slice(e.offset.value,e.offset.value+e.size),n=new Uint8Array(M(t)),r=new Uint8Array(n.length);return j(n),ee(n,r),new DataView(r.buffer)}function se(e){var t=Xy(e.array.slice(e.offset.value,e.offset.value+e.size)),n=new Uint8Array(t.length);return j(t),ee(t,n),new DataView(n.buffer)}function ce(e){for(var r=e.viewer,i={value:e.offset.value},a=new Uint16Array(e.width*e.scanlineBlockSize*(e.channels*e.type)),o=new Uint8Array(n),s=0,l=Array(e.channels),u=0;u=n)throw`Something is wrong with PIZ_COMPRESSION BITMAP_SIZE`;if(d<=f)for(var u=0;u0;){var s=de(t.buffer,n),c=_e(t,n),l=c>>2&3,u=(c>>4)-1,d=new Int8Array([u])[0],f=_e(t,n);a.push({name:s,index:d,type:f,compression:l}),o-=s.length+3}for(var p=Ie.channels,m=Array(e.channels),h=0;h=0&&(v.idx[b.index]=y),g.offset=y)}if(i.acCompressedSize>0)switch(i.acCompression){case 0:var x=new Uint16Array(i.totalAcUncompressedCount);k(e.array,t,n,i.acCompressedSize,x,i.totalAcUncompressedCount);break;case 1:var S=e.array.slice(n.value,n.value+i.totalAcUncompressedCount),C=Xy(S),x=new Uint16Array(C.buffer);n.value+=i.totalAcUncompressedCount;break}if(i.dcCompressedSize>0){var w={array:e.array,offset:n,size:i.dcCompressedSize},T=new Uint16Array(se(w).buffer);n.value+=i.dcCompressedSize}if(i.rleRawSize>0){var S=e.array.slice(n.value,n.value+i.rleCompressedSize),C=Xy(S),E=M(C.buffer);n.value+=i.rleCompressedSize}for(var D=0,O=Array(m.length),h=0;h>10,n=e&1023;return(e>>15?-1:1)*(t?t===31?n?NaN:1/0:2**(t-15)*(1+n/1024):n/1024*6103515625e-14)}function z(e,t){var n=e.getUint16(t.value,!0);return t.value+=2,n}function be(e,t){return R(z(e,t))}function xe(e,t,n,r){for(var i=n.value,a=[];n.valueRe.height?Re.height-t:Re.scanlineBlockSize;let n=Re.size=Re.height)break;for(let e=0;ee.size),i=Y_(e=>e.viewport),a=typeof e==`number`?e:r.width*i.dpr,o=typeof t==`number`?t:r.height*i.dpr,s=(typeof e==`number`?n:e)||{},{samples:c=0,depth:l,...u}=s,d=l??s.depthBuffer,f=y.useMemo(()=>{let e=new kr(a,o,{minFilter:L,magFilter:L,type:ke,...u});return d&&(e.depthTexture=new Ws(a,o,Oe)),e.samples=c,e},[]);return y.useLayoutEffect(()=>{f.setSize(a,o),c&&(f.samples=c)},[c,f,a,o]),y.useEffect(()=>()=>f.dispose(),[]),f}var ab=`modulepreload`,ob=function(e){return`/`+e},sb={},cb=function(e,t,n){let r=Promise.resolve();if(t&&t.length>0){let e=document.getElementsByTagName(`link`),i=document.querySelector(`meta[property=csp-nonce]`),a=i?.nonce||i?.getAttribute(`nonce`);function o(e){return Promise.all(e.map(e=>Promise.resolve(e).then(e=>({status:`fulfilled`,value:e}),e=>({status:`rejected`,reason:e}))))}r=o(t.map(t=>{if(t=ob(t,n),t in sb)return;sb[t]=!0;let r=t.endsWith(`.css`),i=r?`[rel="stylesheet"]`:``;if(n)for(let n=e.length-1;n>=0;n--){let i=e[n];if(i.href===t&&(!r||i.rel===`stylesheet`))return}else if(document.querySelector(`link[href="${t}"]${i}`))return;let o=document.createElement(`link`);if(o.rel=r?`stylesheet`:ab,r||(o.as=`script`),o.crossOrigin=``,o.href=t,a&&o.setAttribute(`nonce`,a),document.head.appendChild(o),r)return new Promise((e,n)=>{o.addEventListener(`load`,e),o.addEventListener(`error`,()=>n(Error(`Unable to preload CSS for ${t}`)))})}))}function i(e){let t=new Event(`vite:preloadError`,{cancelable:!0});if(t.payload=e,window.dispatchEvent(t),!t.defaultPrevented)throw e}return r.then(t=>{for(let e of t||[])e.status===`rejected`&&i(e.reason);return e().catch(i)})},lb=rb({},`void main() { }`,`void main() { gl_FragColor = vec4(0.0, 0.0, 0.0, 0.0); discard; }`),ub=class extends Kl{constructor(e=6,t=!1){super(),this.uniforms={chromaticAberration:{value:.05},transmission:{value:0},_transmission:{value:1},transmissionMap:{value:null},roughness:{value:0},thickness:{value:0},thicknessMap:{value:null},attenuationDistance:{value:1/0},attenuationColor:{value:new U(`white`)},anisotropicBlur:{value:.1},time:{value:0},distortion:{value:0},distortionScale:{value:.5},temporalDistortion:{value:0},buffer:{value:null}},this.onBeforeCompile=n=>{n.uniforms={...n.uniforms,...this.uniforms},this.anisotropy>0&&(n.defines.USE_ANISOTROPY=``),t?n.defines.USE_SAMPLER=``:n.defines.USE_TRANSMISSION=``,n.fragmentShader=` + uniform float chromaticAberration; + uniform float anisotropicBlur; + uniform float time; + uniform float distortion; + uniform float distortionScale; + uniform float temporalDistortion; + uniform sampler2D buffer; + + vec3 random3(vec3 c) { + float j = 4096.0*sin(dot(c,vec3(17.0, 59.4, 15.0))); + vec3 r; + r.z = fract(512.0*j); + j *= .125; + r.x = fract(512.0*j); + j *= .125; + r.y = fract(512.0*j); + return r-0.5; + } + + uint hash( uint x ) { + x += ( x << 10u ); + x ^= ( x >> 6u ); + x += ( x << 3u ); + x ^= ( x >> 11u ); + x += ( x << 15u ); + return x; + } + + // Compound versions of the hashing algorithm I whipped together. + uint hash( uvec2 v ) { return hash( v.x ^ hash(v.y) ); } + uint hash( uvec3 v ) { return hash( v.x ^ hash(v.y) ^ hash(v.z) ); } + uint hash( uvec4 v ) { return hash( v.x ^ hash(v.y) ^ hash(v.z) ^ hash(v.w) ); } + + // Construct a float with half-open range [0:1] using low 23 bits. + // All zeroes yields 0.0, all ones yields the next smallest representable value below 1.0. + float floatConstruct( uint m ) { + const uint ieeeMantissa = 0x007FFFFFu; // binary32 mantissa bitmask + const uint ieeeOne = 0x3F800000u; // 1.0 in IEEE binary32 + m &= ieeeMantissa; // Keep only mantissa bits (fractional part) + m |= ieeeOne; // Add fractional part to 1.0 + float f = uintBitsToFloat( m ); // Range [1:2] + return f - 1.0; // Range [0:1] + } + + // Pseudo-random value in half-open range [0:1]. + float randomBase( float x ) { return floatConstruct(hash(floatBitsToUint(x))); } + float randomBase( vec2 v ) { return floatConstruct(hash(floatBitsToUint(v))); } + float randomBase( vec3 v ) { return floatConstruct(hash(floatBitsToUint(v))); } + float randomBase( vec4 v ) { return floatConstruct(hash(floatBitsToUint(v))); } + float rand(float seed) { + float result = randomBase(vec3(gl_FragCoord.xy, seed)); + return result; + } + + const float F3 = 0.3333333; + const float G3 = 0.1666667; + + float snoise(vec3 p) { + vec3 s = floor(p + dot(p, vec3(F3))); + vec3 x = p - s + dot(s, vec3(G3)); + vec3 e = step(vec3(0.0), x - x.yzx); + vec3 i1 = e*(1.0 - e.zxy); + vec3 i2 = 1.0 - e.zxy*(1.0 - e); + vec3 x1 = x - i1 + G3; + vec3 x2 = x - i2 + 2.0*G3; + vec3 x3 = x - 1.0 + 3.0*G3; + vec4 w, d; + w.x = dot(x, x); + w.y = dot(x1, x1); + w.z = dot(x2, x2); + w.w = dot(x3, x3); + w = max(0.6 - w, 0.0); + d.x = dot(random3(s), x); + d.y = dot(random3(s + i1), x1); + d.z = dot(random3(s + i2), x2); + d.w = dot(random3(s + 1.0), x3); + w *= w; + w *= w; + d *= w; + return dot(d, vec4(52.0)); + } + + float snoiseFractal(vec3 m) { + return 0.5333333* snoise(m) + +0.2666667* snoise(2.0*m) + +0.1333333* snoise(4.0*m) + +0.0666667* snoise(8.0*m); + } +`+n.fragmentShader,n.fragmentShader=n.fragmentShader.replace(`#include `,` + #ifdef USE_TRANSMISSION + // Transmission code is based on glTF-Sampler-Viewer + // https://github.com/KhronosGroup/glTF-Sample-Viewer + uniform float _transmission; + uniform float thickness; + uniform float attenuationDistance; + uniform vec3 attenuationColor; + #ifdef USE_TRANSMISSIONMAP + uniform sampler2D transmissionMap; + #endif + #ifdef USE_THICKNESSMAP + uniform sampler2D thicknessMap; + #endif + uniform vec2 transmissionSamplerSize; + uniform sampler2D transmissionSamplerMap; + uniform mat4 modelMatrix; + uniform mat4 projectionMatrix; + varying vec3 vWorldPosition; + vec3 getVolumeTransmissionRay( const in vec3 n, const in vec3 v, const in float thickness, const in float ior, const in mat4 modelMatrix ) { + // Direction of refracted light. + vec3 refractionVector = refract( - v, normalize( n ), 1.0 / ior ); + // Compute rotation-independant scaling of the model matrix. + vec3 modelScale; + modelScale.x = length( vec3( modelMatrix[ 0 ].xyz ) ); + modelScale.y = length( vec3( modelMatrix[ 1 ].xyz ) ); + modelScale.z = length( vec3( modelMatrix[ 2 ].xyz ) ); + // The thickness is specified in local space. + return normalize( refractionVector ) * thickness * modelScale; + } + float applyIorToRoughness( const in float roughness, const in float ior ) { + // Scale roughness with IOR so that an IOR of 1.0 results in no microfacet refraction and + // an IOR of 1.5 results in the default amount of microfacet refraction. + return roughness * clamp( ior * 2.0 - 2.0, 0.0, 1.0 ); + } + vec4 getTransmissionSample( const in vec2 fragCoord, const in float roughness, const in float ior ) { + float framebufferLod = log2( transmissionSamplerSize.x ) * applyIorToRoughness( roughness, ior ); + #ifdef USE_SAMPLER + #ifdef texture2DLodEXT + return texture2DLodEXT(transmissionSamplerMap, fragCoord.xy, framebufferLod); + #else + return texture2D(transmissionSamplerMap, fragCoord.xy, framebufferLod); + #endif + #else + return texture2D(buffer, fragCoord.xy); + #endif + } + vec3 applyVolumeAttenuation( const in vec3 radiance, const in float transmissionDistance, const in vec3 attenuationColor, const in float attenuationDistance ) { + if ( isinf( attenuationDistance ) ) { + // Attenuation distance is +∞, i.e. the transmitted color is not attenuated at all. + return radiance; + } else { + // Compute light attenuation using Beer's law. + vec3 attenuationCoefficient = -log( attenuationColor ) / attenuationDistance; + vec3 transmittance = exp( - attenuationCoefficient * transmissionDistance ); // Beer's law + return transmittance * radiance; + } + } + vec4 getIBLVolumeRefraction( const in vec3 n, const in vec3 v, const in float roughness, const in vec3 diffuseColor, + const in vec3 specularColor, const in float specularF90, const in vec3 position, const in mat4 modelMatrix, + const in mat4 viewMatrix, const in mat4 projMatrix, const in float ior, const in float thickness, + const in vec3 attenuationColor, const in float attenuationDistance ) { + vec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix ); + vec3 refractedRayExit = position + transmissionRay; + // Project refracted vector on the framebuffer, while mapping to normalized device coordinates. + vec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 ); + vec2 refractionCoords = ndcPos.xy / ndcPos.w; + refractionCoords += 1.0; + refractionCoords /= 2.0; + // Sample framebuffer to get pixel the refracted ray hits. + vec4 transmittedLight = getTransmissionSample( refractionCoords, roughness, ior ); + vec3 attenuatedColor = applyVolumeAttenuation( transmittedLight.rgb, length( transmissionRay ), attenuationColor, attenuationDistance ); + // Get the specular component. + vec3 F = EnvironmentBRDF( n, v, specularColor, specularF90, roughness ); + return vec4( ( 1.0 - F ) * attenuatedColor * diffuseColor, transmittedLight.a ); + } + #endif +`),n.fragmentShader=n.fragmentShader.replace(`#include `,` + // Improve the refraction to use the world pos + material.transmission = _transmission; + material.transmissionAlpha = 1.0; + material.thickness = thickness; + material.attenuationDistance = attenuationDistance; + material.attenuationColor = attenuationColor; + #ifdef USE_TRANSMISSIONMAP + material.transmission *= texture2D( transmissionMap, vUv ).r; + #endif + #ifdef USE_THICKNESSMAP + material.thickness *= texture2D( thicknessMap, vUv ).g; + #endif + + vec3 pos = vWorldPosition; + float runningSeed = 0.0; + vec3 v = normalize( cameraPosition - pos ); + vec3 n = inverseTransformDirection( normal, viewMatrix ); + vec3 transmission = vec3(0.0); + float transmissionR, transmissionB, transmissionG; + float randomCoords = rand(runningSeed++); + float thickness_smear = thickness * max(pow(roughnessFactor, 0.33), anisotropicBlur); + vec3 distortionNormal = vec3(0.0); + vec3 temporalOffset = vec3(time, -time, -time) * temporalDistortion; + if (distortion > 0.0) { + distortionNormal = distortion * vec3(snoiseFractal(vec3((pos * distortionScale + temporalOffset))), snoiseFractal(vec3(pos.zxy * distortionScale - temporalOffset)), snoiseFractal(vec3(pos.yxz * distortionScale + temporalOffset))); + } + for (float i = 0.0; i < ${e}.0; i ++) { + vec3 sampleNorm = normalize(n + roughnessFactor * roughnessFactor * 2.0 * normalize(vec3(rand(runningSeed++) - 0.5, rand(runningSeed++) - 0.5, rand(runningSeed++) - 0.5)) * pow(rand(runningSeed++), 0.33) + distortionNormal); + transmissionR = getIBLVolumeRefraction( + sampleNorm, v, material.roughness, material.diffuseColor, material.specularColor, material.specularF90, + pos, modelMatrix, viewMatrix, projectionMatrix, material.ior, material.thickness + thickness_smear * (i + randomCoords) / float(${e}), + material.attenuationColor, material.attenuationDistance + ).r; + transmissionG = getIBLVolumeRefraction( + sampleNorm, v, material.roughness, material.diffuseColor, material.specularColor, material.specularF90, + pos, modelMatrix, viewMatrix, projectionMatrix, material.ior * (1.0 + chromaticAberration * (i + randomCoords) / float(${e})) , material.thickness + thickness_smear * (i + randomCoords) / float(${e}), + material.attenuationColor, material.attenuationDistance + ).g; + transmissionB = getIBLVolumeRefraction( + sampleNorm, v, material.roughness, material.diffuseColor, material.specularColor, material.specularF90, + pos, modelMatrix, viewMatrix, projectionMatrix, material.ior * (1.0 + 2.0 * chromaticAberration * (i + randomCoords) / float(${e})), material.thickness + thickness_smear * (i + randomCoords) / float(${e}), + material.attenuationColor, material.attenuationDistance + ).b; + transmission.r += transmissionR; + transmission.g += transmissionG; + transmission.b += transmissionB; + } + transmission /= ${e}.0; + totalDiffuse = mix( totalDiffuse, transmission.rgb, material.transmission );\n`)},Object.keys(this.uniforms).forEach(e=>Object.defineProperty(this,e,{get:()=>this.uniforms[e].value,set:t=>this.uniforms[e].value=t}))}},db=y.forwardRef(({buffer:e,transmissionSampler:t=!1,backside:n=!1,side:r=0,transmission:i=1,thickness:a=0,backsideThickness:o=0,backsideEnvMapIntensity:s=1,samples:c=10,resolution:l,backsideResolution:u,background:d,anisotropy:f,anisotropicBlur:p,...m},h)=>{xv({MeshTransmissionMaterial:ub});let g=y.useRef(null),[_]=y.useState(()=>new lb),v=ib(u||l),b=ib(l),x,S,C,w;return X_(e=>{g.current.time=e.clock.elapsedTime,g.current.buffer===b.texture&&!t&&(w=g.current.__r3f.parent?.object,w&&(C=e.gl.toneMapping,x=e.scene.background,S=g.current.envMapIntensity,e.gl.toneMapping=0,d&&(e.scene.background=d),w.material=_,n&&(e.gl.setRenderTarget(v),e.gl.render(e.scene,e.camera),w.material=g.current,w.material.buffer=v.texture,w.material.thickness=o,w.material.side=1,w.material.envMapIntensity=s),e.gl.setRenderTarget(b),e.gl.render(e.scene,e.camera),w.material=g.current,w.material.thickness=a,w.material.side=r,w.material.buffer=b.texture,w.material.envMapIntensity=S,e.scene.background=x,e.gl.setRenderTarget(null),e.gl.toneMapping=C))}),y.useImperativeHandle(h,()=>g.current,[]),y.createElement(`meshTransmissionMaterial`,ce({args:[c,t],ref:g},m,{buffer:e||b.texture,_transmission:i,anisotropicBlur:p??f,transmission:t?i:0,thickness:a,side:r}))}),fb=y.forwardRef(({children:e,enabled:t=!0,speed:n=1,rotationIntensity:r=1,floatIntensity:i=1,floatingRange:a=[-.1,.1],autoInvalidate:o=!1,...s},c)=>{let l=y.useRef(null);y.useImperativeHandle(c,()=>l.current,[]);let u=y.useRef(Math.random()*1e4);return X_(e=>{if(!t||n===0)return;o&&e.invalidate();let s=u.current+e.clock.elapsedTime;l.current.rotation.x=Math.cos(s/4*n)/8*r,l.current.rotation.y=Math.sin(s/4*n)/8*r,l.current.rotation.z=Math.sin(s/4*n)/20*r;let c=Math.sin(s/4*n)/10;c=sr.mapLinear(c,-.1,.1,a?.[0]??-.1,a?.[1]??.1),l.current.position.y=c*i,l.current.updateMatrix()}),y.createElement(`group`,s,y.createElement(`group`,{ref:l,matrixAutoUpdate:!1},e))}),pb=(e,t,n)=>{let r;switch(e){case Se:r=new Uint8ClampedArray(t*n*4);break;case ke:r=new Uint16Array(t*n*4);break;case De:r=new Uint32Array(t*n*4);break;case Ce:r=new Int8Array(t*n*4);break;case we:r=new Int16Array(t*n*4);break;case Ee:r=new Int32Array(t*n*4);break;case Oe:r=new Float32Array(t*n*4);break;default:throw Error(`Unsupported data type`)}return r},mb,hb=(e,t,n,r)=>{if(mb!==void 0)return mb;let i=new kr(1,1,r);t.setRenderTarget(i);let a=new fo(new wl,new $a({color:16777215}));t.render(a,n),t.setRenderTarget(null);let o=pb(e,i.width,i.height);return t.readRenderTargetPixels(i,0,0,i.width,i.height,o),i.dispose(),a.geometry.dispose(),a.material.dispose(),mb=o[0]!==0,mb},gb=class e{_renderer;_rendererIsDisposable=!1;_material;_scene;_camera;_quad;_renderTarget;_width;_height;_type;_colorSpace;_supportsReadPixels=!0;constructor(t){this._width=t.width,this._height=t.height,this._type=t.type,this._colorSpace=t.colorSpace;let n={format:Le,depthBuffer:!1,stencilBuffer:!1,type:this._type,colorSpace:this._colorSpace,anisotropy:t.renderTargetOptions?.anisotropy===void 0?1:t.renderTargetOptions?.anisotropy,generateMipmaps:t.renderTargetOptions?.generateMipmaps===void 0?!1:t.renderTargetOptions?.generateMipmaps,magFilter:t.renderTargetOptions?.magFilter===void 0?L:t.renderTargetOptions?.magFilter,minFilter:t.renderTargetOptions?.minFilter===void 0?L:t.renderTargetOptions?.minFilter,samples:t.renderTargetOptions?.samples===void 0?void 0:t.renderTargetOptions?.samples,wrapS:t.renderTargetOptions?.wrapS===void 0?me:t.renderTargetOptions?.wrapS,wrapT:t.renderTargetOptions?.wrapT===void 0?me:t.renderTargetOptions?.wrapT};if(this._material=t.material,t.renderer?this._renderer=t.renderer:(this._renderer=e.instantiateRenderer(),this._rendererIsDisposable=!0),this._scene=new vi,this._camera=new rd,this._camera.position.set(0,0,10),this._camera.left=-.5,this._camera.right=.5,this._camera.top=.5,this._camera.bottom=-.5,this._camera.updateProjectionMatrix(),!hb(this._type,this._renderer,this._camera,n)){let e;switch(this._type){case ke:e=this._renderer.extensions.has(`EXT_color_buffer_float`)?Oe:void 0;break}e===void 0?(this._supportsReadPixels=!1,console.warn(`This browser dos not support toArray or toDataTexture, calls to those methods will result in an error thrown`)):(console.warn(`This browser does not support reading pixels from ${this._type} RenderTargets, switching to ${Oe}`),this._type=e)}this._quad=new fo(new wl,this._material),this._quad.geometry.computeBoundingBox(),this._scene.add(this._quad),this._renderTarget=new kr(this.width,this.height,n),this._renderTarget.texture.mapping=t.renderTargetOptions?.mapping===void 0?300:t.renderTargetOptions?.mapping}static instantiateRenderer(){let e=new Fg;return e.setSize(128,128),e}render=()=>{this._renderer.setRenderTarget(this._renderTarget);try{this._renderer.render(this._scene,this._camera)}catch(e){throw this._renderer.setRenderTarget(null),e}this._renderer.setRenderTarget(null)};toArray(){if(!this._supportsReadPixels)throw Error(`Can't read pixels in this browser`);let e=pb(this._type,this._width,this._height);return this._renderer.readRenderTargetPixels(this._renderTarget,0,0,this._width,this._height,e),e}toDataTexture(e){let t=new Eo(this.toArray(),this.width,this.height,Le,this._type,e?.mapping||300,e?.wrapS||1001,e?.wrapT||1001,e?.magFilter||1006,e?.minFilter||1006,e?.anisotropy||1,Gt);return t.generateMipmaps=e?.generateMipmaps===void 0?!1:e?.generateMipmaps,t}disposeOnDemandRenderer(){this._renderer.setRenderTarget(null),this._rendererIsDisposable&&(this._renderer.dispose(),this._renderer.forceContextLoss())}dispose(e){this.disposeOnDemandRenderer(),e&&this.renderTarget.dispose(),this.material instanceof q&&Object.values(this.material.uniforms).forEach(e=>{e.value instanceof Er&&e.value.dispose()}),Object.values(this.material).forEach(e=>{e instanceof Er&&e.dispose()}),this.material.dispose(),this._quad.geometry.dispose()}get width(){return this._width}set width(e){this._width=e,this._renderTarget.setSize(this._width,this._height)}get height(){return this._height}set height(e){this._height=e,this._renderTarget.setSize(this._width,this._height)}get renderer(){return this._renderer}get renderTarget(){return this._renderTarget}set renderTarget(e){this._renderTarget=e,this._width=e.width,this._height=e.height}get material(){return this._material}get type(){return this._type}get colorSpace(){return this._colorSpace}},_b=class extends Error{},vb=class extends Error{},yb=(e,t,n)=>{let r=RegExp(`${t}="([^"]*)"`,`i`).exec(e);if(r)return r[1];let i=RegExp(`<${t}[^>]*>([\\s\\S]*?)`,`i`).exec(e);if(i){let e=i[1].match(/([^<]*)<\/rdf:li>/g);return e&&e.length===3?e.map(e=>e.replace(/<\/?rdf:li>/g,``)):i[1].trim()}if(n!==void 0)return n;throw Error(`Can't find ${t} in gainmap metadata`)},bb=e=>{let t;t=typeof TextDecoder<`u`?new TextDecoder().decode(e):e.toString();let n=t.indexOf(``,n),r=t.slice(n,e+10);try{let e=yb(r,`hdrgm:GainMapMin`,`0`),t=yb(r,`hdrgm:GainMapMax`),n=yb(r,`hdrgm:Gamma`,`1`),i=yb(r,`hdrgm:OffsetSDR`,`0.015625`),a=yb(r,`hdrgm:OffsetHDR`,`0.015625`),o=/hdrgm:HDRCapacityMin="([^"]*)"/.exec(r),s=o?o[1]:`0`,c=/hdrgm:HDRCapacityMax="([^"]*)"/.exec(r);if(!c)throw Error(`Incomplete gainmap metadata`);let l=c[1];return{gainMapMin:Array.isArray(e)?e.map(e=>parseFloat(e)):[parseFloat(e),parseFloat(e),parseFloat(e)],gainMapMax:Array.isArray(t)?t.map(e=>parseFloat(e)):[parseFloat(t),parseFloat(t),parseFloat(t)],gamma:Array.isArray(n)?n.map(e=>parseFloat(e)):[parseFloat(n),parseFloat(n),parseFloat(n)],offsetSdr:Array.isArray(i)?i.map(e=>parseFloat(e)):[parseFloat(i),parseFloat(i),parseFloat(i)],offsetHdr:Array.isArray(a)?a.map(e=>parseFloat(e)):[parseFloat(a),parseFloat(a),parseFloat(a)],hdrCapacityMin:parseFloat(s),hdrCapacityMax:parseFloat(l)}}catch{}n=t.indexOf(`{let r=this.options.debug,i=new DataView(e.buffer);if(i.getUint16(0)!==65496){n(Error(`Not a valid jpeg`));return}let a=i.byteLength,o=2,s=0,c;for(;o250){n(Error(`Found no marker after ${s} loops 😵`));return}if(i.getUint8(o)!==255){n(Error(`Not a valid marker at offset 0x${o.toString(16)}, found: 0x${i.getUint8(o).toString(16)}`));return}if(c=i.getUint8(o+1),r&&console.log(`Marker: ${c.toString(16)}`),c===226){r&&console.log(`Found APP2 marker (0xffe2)`);let e=o+4;if(i.getUint32(e)===1297106432){let r=e+4,a;if(i.getUint16(r)===18761)a=!1;else if(i.getUint16(r)===19789)a=!0;else{n(Error(`No valid endianness marker found in TIFF header`));return}if(i.getUint16(r+2,!a)!==42){n(Error(`Not valid TIFF data! (no 0x002A marker)`));return}let o=i.getUint32(r+4,!a);if(o<8){n(Error(`Not valid TIFF data! (First offset less than 8)`));return}let s=r+o,c=i.getUint16(s,!a),l=s+2,u=0;for(let e=l;e{let t=bb(e);if(!t)throw new vb(`Gain map XMP metadata not found`);let n=await new xb({extractFII:!0,extractNonFII:!0}).extract(e);if(n.length!==2)throw new _b(`Gain map recovery image not found`);return{sdr:new Uint8Array(await n[0].arrayBuffer()),gainMap:new Uint8Array(await n[1].arrayBuffer()),metadata:t}},Cb=e=>new Promise((t,n)=>{let r=document.createElement(`img`);r.onload=()=>{t(r)},r.onerror=e=>{n(e)},r.src=URL.createObjectURL(e)}),wb=class extends Ou{_renderer;_renderTargetOptions;_internalLoadingManager;_config;constructor(e,t){super(t),this._config=e,e.renderer&&(this._renderer=e.renderer),this._internalLoadingManager=new Eu}setRenderer(e){return this._renderer=e,this}setRenderTargetOptions(e){return this._renderTargetOptions=e,this}prepareQuadRenderer(){this._renderer||console.warn(`WARNING: A Renderer was not passed to this Loader constructor or in setRenderer, the result of this Loader will need to be converted to a Data Texture with toDataTexture() before you can use it in your renderer.`);let e=this._config.createMaterial({gainMapMax:[1,1,1],gainMapMin:[0,0,0],gamma:[1,1,1],offsetHdr:[1,1,1],offsetSdr:[1,1,1],hdrCapacityMax:1,hdrCapacityMin:0,maxDisplayBoost:1,gainMap:new Er,sdr:new Er});return this._config.createQuadRenderer({width:16,height:16,type:ke,colorSpace:Gt,material:e,renderer:this._renderer,renderTargetOptions:this._renderTargetOptions})}async processImages(e,t,n){let r=t?new Blob([t],{type:`image/jpeg`}):void 0,i=new Blob([e],{type:`image/jpeg`}),a,o,s=!1;if(typeof createImageBitmap>`u`){let e=await Promise.all([r?Cb(r):Promise.resolve(void 0),Cb(i)]);o=e[0],a=e[1],s=n===`flipY`}else{let e=await Promise.all([r?createImageBitmap(r,{imageOrientation:n||`flipY`}):Promise.resolve(void 0),createImageBitmap(i,{imageOrientation:n||`flipY`})]);o=e[0],a=e[1]}return{sdrImage:a,gainMapImage:o,needsFlip:s}}createTextures(e,t,n){let r=new Er(t||new ImageData(2,2),300,me,me,L,xe,Le,Se,1,Gt);r.flipY=n,r.needsUpdate=!0;let i=new Er(e,300,me,me,L,xe,Le,Se,1,Wt);return i.flipY=n,i.needsUpdate=!0,{gainMap:r,sdr:i}}updateQuadRenderer(e,t,n,r,i){e.width=t.width,e.height=t.height,e.material.gainMap=n,e.material.sdr=r,e.material.gainMapMin=i.gainMapMin,e.material.gainMapMax=i.gainMapMax,e.material.offsetHdr=i.offsetHdr,e.material.offsetSdr=i.offsetSdr,e.material.gamma=i.gamma,e.material.hdrCapacityMin=i.hdrCapacityMin,e.material.hdrCapacityMax=i.hdrCapacityMax,e.material.maxDisplayBoost=2**i.hdrCapacityMax,e.material.needsUpdate=!0}},Tb=` +varying vec2 vUv; + +void main() { + vUv = uv; + gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0); +} +`,Eb=` +// min half float value +#define HALF_FLOAT_MIN vec3( -65504, -65504, -65504 ) +// max half float value +#define HALF_FLOAT_MAX vec3( 65504, 65504, 65504 ) + +uniform sampler2D sdr; +uniform sampler2D gainMap; +uniform vec3 gamma; +uniform vec3 offsetHdr; +uniform vec3 offsetSdr; +uniform vec3 gainMapMin; +uniform vec3 gainMapMax; +uniform float weightFactor; + +varying vec2 vUv; + +void main() { + vec3 rgb = texture2D( sdr, vUv ).rgb; + vec3 recovery = texture2D( gainMap, vUv ).rgb; + vec3 logRecovery = pow( recovery, gamma ); + vec3 logBoost = gainMapMin * ( 1.0 - logRecovery ) + gainMapMax * logRecovery; + vec3 hdrColor = (rgb + offsetSdr) * exp2( logBoost * weightFactor ) - offsetHdr; + vec3 clampedHdrColor = max( HALF_FLOAT_MIN, min( HALF_FLOAT_MAX, hdrColor )); + gl_FragColor = vec4( clampedHdrColor , 1.0 ); +} +`,Db=class extends q{_maxDisplayBoost;_hdrCapacityMin;_hdrCapacityMax;constructor({gamma:e,offsetHdr:t,offsetSdr:n,gainMapMin:r,gainMapMax:i,maxDisplayBoost:a,hdrCapacityMin:o,hdrCapacityMax:s,sdr:c,gainMap:l}){super({name:`GainMapDecoderMaterial`,vertexShader:Tb,fragmentShader:Eb,uniforms:{sdr:{value:c},gainMap:{value:l},gamma:{value:new H(1/e[0],1/e[1],1/e[2])},offsetHdr:{value:new H().fromArray(t)},offsetSdr:{value:new H().fromArray(n)},gainMapMin:{value:new H().fromArray(r)},gainMapMax:{value:new H().fromArray(i)},weightFactor:{value:(Math.log2(a)-o)/(s-o)}},blending:0,depthTest:!1,depthWrite:!1}),this._maxDisplayBoost=a,this._hdrCapacityMin=o,this._hdrCapacityMax=s,this.needsUpdate=!0,this.uniformsNeedUpdate=!0}get sdr(){return this.uniforms.sdr.value}set sdr(e){this.uniforms.sdr.value=e}get gainMap(){return this.uniforms.gainMap.value}set gainMap(e){this.uniforms.gainMap.value=e}get offsetHdr(){return this.uniforms.offsetHdr.value.toArray()}set offsetHdr(e){this.uniforms.offsetHdr.value.fromArray(e)}get offsetSdr(){return this.uniforms.offsetSdr.value.toArray()}set offsetSdr(e){this.uniforms.offsetSdr.value.fromArray(e)}get gainMapMin(){return this.uniforms.gainMapMin.value.toArray()}set gainMapMin(e){this.uniforms.gainMapMin.value.fromArray(e)}get gainMapMax(){return this.uniforms.gainMapMax.value.toArray()}set gainMapMax(e){this.uniforms.gainMapMax.value.fromArray(e)}get gamma(){let e=this.uniforms.gamma.value;return[1/e.x,1/e.y,1/e.z]}set gamma(e){let t=this.uniforms.gamma.value;t.x=1/e[0],t.y=1/e[1],t.z=1/e[2]}get hdrCapacityMin(){return this._hdrCapacityMin}set hdrCapacityMin(e){this._hdrCapacityMin=e,this.calculateWeight()}get hdrCapacityMax(){return this._hdrCapacityMax}set hdrCapacityMax(e){this._hdrCapacityMax=e,this.calculateWeight()}get maxDisplayBoost(){return this._maxDisplayBoost}set maxDisplayBoost(e){this._maxDisplayBoost=Math.max(1,Math.min(65504,e)),this.calculateWeight()}calculateWeight(){let e=(Math.log2(this._maxDisplayBoost)-this._hdrCapacityMin)/(this._hdrCapacityMax-this._hdrCapacityMin);this.uniforms.weightFactor.value=Math.max(0,Math.min(1,e))}},Ob=class extends wb{constructor(e,t){super({renderer:e,createMaterial:e=>new Db(e),createQuadRenderer:e=>new gb(e)},t)}async render(e,t,n,r){let{sdrImage:i,gainMapImage:a,needsFlip:o}=await this.processImages(n,r,`flipY`),{gainMap:s,sdr:c}=this.createTextures(i,a,o);this.updateQuadRenderer(e,i,s,c,t),e.render()}},kb=class extends Ob{load([e,t,n],r,i,a){let o=this.prepareQuadRenderer(),s,c,l,u=async()=>{if(s&&c&&l){try{await this.render(o,l,s,c)}catch(r){this.manager.itemError(e),this.manager.itemError(t),this.manager.itemError(n),typeof a==`function`&&a(r),o.disposeOnDemandRenderer();return}typeof r==`function`&&r(o),this.manager.itemEnd(e),this.manager.itemEnd(t),this.manager.itemEnd(n),o.disposeOnDemandRenderer()}},d=!0,f=0,p=0,m=!0,h=0,g=0,_=!0,v=0,y=0,b=()=>{if(typeof i==`function`){let e=f+h+v,t=p+g+y,n=d&&m&&_;i(new ProgressEvent(`progress`,{lengthComputable:n,loaded:t,total:e}))}};this.manager.itemStart(e),this.manager.itemStart(t),this.manager.itemStart(n);let x=new ju(this._internalLoadingManager);x.setResponseType(`arraybuffer`),x.setRequestHeader(this.requestHeader),x.setPath(this.path),x.setWithCredentials(this.withCredentials),x.load(e,async e=>{if(typeof e==`string`)throw Error(`Invalid sdr buffer`);s=e,await u()},e=>{d=e.lengthComputable,p=e.loaded,f=e.total,b()},t=>{this.manager.itemError(e),typeof a==`function`&&a(t)});let S=new ju(this._internalLoadingManager);S.setResponseType(`arraybuffer`),S.setRequestHeader(this.requestHeader),S.setPath(this.path),S.setWithCredentials(this.withCredentials),S.load(t,async e=>{if(typeof e==`string`)throw Error(`Invalid gainmap buffer`);c=e,await u()},e=>{m=e.lengthComputable,g=e.loaded,h=e.total,b()},e=>{this.manager.itemError(t),typeof a==`function`&&a(e)});let C=new ju(this._internalLoadingManager);return C.setRequestHeader(this.requestHeader),C.setPath(this.path),C.setWithCredentials(this.withCredentials),C.load(n,async e=>{if(typeof e!=`string`)throw Error(`Invalid metadata string`);l=JSON.parse(e),await u()},e=>{_=e.lengthComputable,y=e.loaded,v=e.total,b()},e=>{this.manager.itemError(n),typeof a==`function`&&a(e)}),o}},Ab=class extends Ob{load(e,t,n,r){let i=this.prepareQuadRenderer(),a=new ju(this._internalLoadingManager);return a.setResponseType(`arraybuffer`),a.setRequestHeader(this.requestHeader),a.setPath(this.path),a.setWithCredentials(this.withCredentials),this.manager.itemStart(e),a.load(e,async n=>{if(typeof n==`string`)throw Error(`Invalid buffer, received [string], was expecting [ArrayBuffer]`);let a=new Uint8Array(n),o,s,c;try{let e=await Sb(a);o=e.sdr,s=e.gainMap,c=e.metadata}catch(t){if(t instanceof vb||t instanceof _b)console.warn(`Failure to reconstruct an HDR image from ${e}: Gain map metadata not found in the file, HDRJPGLoader will render the SDR jpeg`),c={gainMapMin:[0,0,0],gainMapMax:[1,1,1],gamma:[1,1,1],hdrCapacityMin:0,hdrCapacityMax:1,offsetHdr:[0,0,0],offsetSdr:[0,0,0]},o=a;else throw t}try{await this.render(i,c,o.buffer,s?.buffer)}catch(t){this.manager.itemError(e),typeof r==`function`&&r(t),i.disposeOnDemandRenderer();return}typeof t==`function`&&t(i),this.manager.itemEnd(e),i.disposeOnDemandRenderer()},n,t=>{this.manager.itemError(e),typeof r==`function`&&r(t)}),i}},jb={apartment:`lebombo_1k.hdr`,city:`potsdamer_platz_1k.hdr`,dawn:`kiara_1_dawn_1k.hdr`,forest:`forest_slope_1k.hdr`,lobby:`st_fagans_interior_1k.hdr`,night:`dikhololo_night_1k.hdr`,park:`rooitou_park_1k.hdr`,studio:`studio_small_03_1k.hdr`,sunset:`venice_sunset_1k.hdr`,warehouse:`empty_warehouse_01_1k.hdr`},Mb=`https://raw.githack.com/pmndrs/drei-assets/456060a26bbeb8fdf79326f224b6d99b8bcce736/hdri/`,Nb=e=>Array.isArray(e),Pb=[`/px.png`,`/nx.png`,`/py.png`,`/ny.png`,`/pz.png`,`/nz.png`];function Fb({files:e=Pb,path:t=``,preset:n=void 0,colorSpace:r=void 0,extensions:i}={}){n&&(Rb(n),e=jb[n],t=Mb);let a=Nb(e),{extension:o,isCubemap:s}=zb(e),c=Bb(o);if(!c)throw Error(`useEnvironment: Unrecognized file extension: `+e);let l=Y_(e=>e.gl);(0,y.useLayoutEffect)(()=>{if(o!==`webp`&&o!==`jpg`&&o!==`jpeg`)return;function t(){ev.clear(c,a?[e]:e)}l.domElement.addEventListener(`webglcontextlost`,t,{once:!0})},[e,l.domElement]);let u=ev(c,a?[e]:e,e=>{(o===`webp`||o===`jpg`||o===`jpeg`)&&e.setRenderer(l),e.setPath==null||e.setPath(t),i&&i(e)}),d=a?u[0]:u;return(o===`jpg`||o===`jpeg`||o===`webp`)&&(d=d.renderTarget?.texture),d.mapping=s?301:303,d.colorSpace=r??(s?`srgb`:`srgb-linear`),d}var Ib={files:Pb,path:``,preset:void 0,extensions:void 0};Fb.preload=e=>{let t={...Ib,...e},{files:n,path:r=``}=t,{preset:i,extensions:a}=t;i&&(Rb(i),n=jb[i],r=Mb);let{extension:o}=zb(n);if(o===`webp`||o===`jpg`||o===`jpeg`)throw Error(`useEnvironment: Preloading gainmaps is not supported`);let s=Bb(o);if(!s)throw Error(`useEnvironment: Unrecognized file extension: `+n);ev.preload(s,Nb(n)?[n]:n,e=>{e.setPath==null||e.setPath(r),a&&a(e)})};var Lb={files:Pb,preset:void 0};Fb.clear=e=>{let t={...Lb,...e},{files:n}=t,{preset:r}=t;r&&(Rb(r),n=jb[r]);let{extension:i}=zb(n),a=Bb(i);if(!a)throw Error(`useEnvironment: Unrecognized file extension: `+n);ev.clear(a,Nb(n)?[n]:n)};function Rb(e){if(!(e in jb))throw Error(`Preset must be one of: `+Object.keys(jb).join(`, `))}function zb(e){var t;let n=Nb(e)&&e.length===6,r=Nb(e)&&e.length===3&&e.some(e=>e.endsWith(`json`)),i=Nb(e)?e[0]:e;return{extension:n?`cube`:r?`webp`:i.startsWith(`data:application/exr`)?`exr`:i.startsWith(`data:application/hdr`)?`hdr`:i.startsWith(`data:image/jpeg`)?`jpg`:(t=i.split(`.`).pop())==null||(t=t.split(`?`))==null||(t=t.shift())==null?void 0:t.toLowerCase(),isCubemap:n,isGainmap:r}}function Bb(e){return e===`cube`?Iu:e===`hdr`?eb:e===`exr`?nb:e===`jpg`||e===`jpeg`?Ab:e===`webp`?kb:null}var Vb=e=>e.current&&e.current.isScene,Hb=e=>Vb(e)?e.current:e;function Ub(e,t,n,r,i={}){var a,o;i={backgroundBlurriness:0,backgroundIntensity:1,backgroundRotation:[0,0,0],environmentIntensity:1,environmentRotation:[0,0,0],...i};let s=Hb(t||n),c=s.background,l=s.environment,u={backgroundBlurriness:s.backgroundBlurriness,backgroundIntensity:s.backgroundIntensity,backgroundRotation:((a=s.backgroundRotation)==null||a.clone==null?void 0:a.clone())??[0,0,0],environmentIntensity:s.environmentIntensity,environmentRotation:((o=s.environmentRotation)==null||o.clone==null?void 0:o.clone())??[0,0,0]};return e!==`only`&&(s.environment=r),e&&(s.background=r),L_(s,i),()=>{e!==`only`&&(s.environment=l),e&&(s.background=c),L_(s,u)}}function Wb({scene:e,background:t=!1,map:n,...r}){let i=Y_(e=>e.scene);return y.useLayoutEffect(()=>{if(n)return Ub(t,e,i,n,r)}),null}function Gb({background:e=!1,scene:t,blur:n,backgroundBlurriness:r,backgroundIntensity:i,backgroundRotation:a,environmentIntensity:o,environmentRotation:s,...c}){let l=Fb(c),u=Y_(e=>e.scene);return y.useLayoutEffect(()=>Ub(e,t,u,l,{backgroundBlurriness:n??r,backgroundIntensity:i,backgroundRotation:a,environmentIntensity:o,environmentRotation:s})),y.useEffect(()=>()=>{l.dispose()},[l]),null}function Kb({children:e,near:t=.1,far:n=1e3,resolution:r=256,frames:i=1,map:a,background:o=!1,blur:s,backgroundBlurriness:c,backgroundIntensity:l,backgroundRotation:u,environmentIntensity:d,environmentRotation:f,scene:p,files:m,path:h,preset:g=void 0,extensions:_}){let v=Y_(e=>e.gl),b=Y_(e=>e.scene),x=y.useRef(null),[S]=y.useState(()=>new vi),C=y.useMemo(()=>{let e=new Qp(r);return e.texture.type=ke,e},[r]);y.useEffect(()=>()=>{C.dispose()},[C]),y.useLayoutEffect(()=>{if(i===1){let e=v.autoClear;v.autoClear=!0,x.current.update(v,S),v.autoClear=e}return Ub(o,p,b,C.texture,{backgroundBlurriness:s??c,backgroundIntensity:l,backgroundRotation:u,environmentIntensity:d,environmentRotation:f})},[e,S,C.texture,p,b,o,i,v]);let w=1;return X_(()=>{if(i===1/0||wxv({GroundProjectedEnvImpl:$y}),[]),y.useEffect(()=>()=>{t.dispose()},[t]);let r=y.useMemo(()=>[n],[n]),i=e.ground?.height,a=e.ground?.radius,o=e.ground?.scale??1e3;return y.createElement(y.Fragment,null,y.createElement(Wb,ce({},e,{map:n})),y.createElement(`groundProjectedEnvImpl`,{args:r,scale:o,height:i,radius:a}))}function Jb(e){return e.ground?y.createElement(qb,e):e.map?y.createElement(Wb,e):e.children?y.createElement(Kb,e):y.createElement(Gb,e)}var Yb=1/1e3,Xb=1e3,Zb=class{constructor(){this.startTime=performance.now(),this.previousTime=0,this.currentTime=0,this._delta=0,this._elapsed=0,this._fixedDelta=1e3/60,this.timescale=1,this.useFixedDelta=!1,this._autoReset=!1}get autoReset(){return this._autoReset}set autoReset(e){typeof document<`u`&&document.hidden!==void 0&&(e?document.addEventListener(`visibilitychange`,this):document.removeEventListener(`visibilitychange`,this),this._autoReset=e)}get delta(){return this._delta*Yb}get fixedDelta(){return this._fixedDelta*Yb}set fixedDelta(e){this._fixedDelta=e*Xb}get elapsed(){return this._elapsed*Yb}update(e){this.useFixedDelta?this._delta=this.fixedDelta:(this.previousTime=this.currentTime,this.currentTime=(e===void 0?performance.now():e)-this.startTime,this._delta=this.currentTime-this.previousTime),this._delta*=this.timescale,this._elapsed+=this._delta}reset(){this._delta=0,this._elapsed=0,this.currentTime=performance.now()-this.startTime}getDelta(){return this.delta}getElapsed(){return this.elapsed}handleEvent(e){document.hidden||(this.currentTime=performance.now()-this.startTime)}dispose(){this.autoReset=!1}},Qb=(()=>{let e=new Float32Array([-1,-1,0,3,-1,0,-1,3,0]),t=new Float32Array([0,0,2,0,0,2]),n=new ba;return n.setAttribute(`position`,new ea(e,3)),n.setAttribute(`uv`,new ea(t,2)),n})(),$b=class e{static get fullscreenGeometry(){return Qb}constructor(e=`Pass`,t=new vi,n=new rd){this.name=e,this.renderer=null,this.scene=t,this.camera=n,this.screen=null,this.rtt=!0,this.needsSwap=!0,this.needsDepthTexture=!1,this.enabled=!0}get renderToScreen(){return!this.rtt}set renderToScreen(e){if(this.rtt===e){let t=this.fullscreenMaterial;t!==null&&(t.needsUpdate=!0),this.rtt=!e}}set mainScene(e){}set mainCamera(e){}setRenderer(e){this.renderer=e}isEnabled(){return this.enabled}setEnabled(e){this.enabled=e}get fullscreenMaterial(){return this.screen===null?null:this.screen.material}set fullscreenMaterial(t){let n=this.screen;n===null?(n=new fo(e.fullscreenGeometry,t),n.frustumCulled=!1,this.scene===null&&(this.scene=new vi),this.scene.add(n),this.screen=n):n.material=t}getFullscreenMaterial(){return this.fullscreenMaterial}setFullscreenMaterial(e){this.fullscreenMaterial=e}getDepthTexture(){return null}setDepthTexture(e,t=Bt){}render(e,t,n,r,i){throw Error(`Render method not implemented!`)}setSize(e,t){}initialize(e,t,n){}dispose(){for(let t of Object.keys(this)){let n=this[t];(n instanceof kr||n instanceof Ta||n instanceof Er||n instanceof e)&&this[t].dispose()}this.fullscreenMaterial!==null&&this.fullscreenMaterial.dispose()}},ex=class extends $b{constructor(){super(`ClearMaskPass`,null,null),this.needsSwap=!1}render(e,t,n,r,i){let a=e.state.buffers.stencil;a.setLocked(!1),a.setTest(!1)}},tx=`#ifdef COLOR_WRITE +#include +#include +#ifdef FRAMEBUFFER_PRECISION_HIGH +uniform mediump sampler2D inputBuffer; +#else +uniform lowp sampler2D inputBuffer; +#endif +#endif +#ifdef DEPTH_WRITE +#include +#ifdef GL_FRAGMENT_PRECISION_HIGH +uniform highp sampler2D depthBuffer; +#else +uniform mediump sampler2D depthBuffer; +#endif +float readDepth(const in vec2 uv){ +#if DEPTH_PACKING == 3201 +return unpackRGBAToDepth(texture2D(depthBuffer,uv)); +#else +return texture2D(depthBuffer,uv).r; +#endif +} +#endif +#ifdef USE_WEIGHTS +uniform vec4 channelWeights; +#endif +uniform float opacity;varying vec2 vUv;void main(){ +#ifdef COLOR_WRITE +vec4 texel=texture2D(inputBuffer,vUv); +#ifdef USE_WEIGHTS +texel*=channelWeights; +#endif +gl_FragColor=opacity*texel; +#ifdef COLOR_SPACE_CONVERSION +#include +#endif +#include +#else +gl_FragColor=vec4(0.0); +#endif +#ifdef DEPTH_WRITE +gl_FragDepth=readDepth(vUv); +#endif +}`,nx=`varying vec2 vUv;void main(){vUv=position.xy*0.5+0.5;gl_Position=vec4(position.xy,1.0,1.0);}`,rx=class extends q{constructor(){super({name:`CopyMaterial`,defines:{COLOR_SPACE_CONVERSION:`1`,DEPTH_PACKING:`0`,COLOR_WRITE:`1`},uniforms:{inputBuffer:new df(null),depthBuffer:new df(null),channelWeights:new df(null),opacity:new df(1)},blending:0,toneMapped:!1,depthWrite:!1,depthTest:!1,fragmentShader:tx,vertexShader:nx}),this.depthFunc=1}get inputBuffer(){return this.uniforms.inputBuffer.value}set inputBuffer(e){let t=e!==null;this.colorWrite!==t&&(t?this.defines.COLOR_WRITE=!0:delete this.defines.COLOR_WRITE,this.colorWrite=t,this.needsUpdate=!0),this.uniforms.inputBuffer.value=e}get depthBuffer(){return this.uniforms.depthBuffer.value}set depthBuffer(e){let t=e!==null;this.depthWrite!==t&&(t?this.defines.DEPTH_WRITE=!0:delete this.defines.DEPTH_WRITE,this.depthTest=t,this.depthWrite=t,this.needsUpdate=!0),this.uniforms.depthBuffer.value=e}set depthPacking(e){this.defines.DEPTH_PACKING=e.toFixed(0),this.needsUpdate=!0}get colorSpaceConversion(){return this.defines.COLOR_SPACE_CONVERSION!==void 0}set colorSpaceConversion(e){this.colorSpaceConversion!==e&&(e?this.defines.COLOR_SPACE_CONVERSION=!0:delete this.defines.COLOR_SPACE_CONVERSION,this.needsUpdate=!0)}get channelWeights(){return this.uniforms.channelWeights.value}set channelWeights(e){e===null?delete this.defines.USE_WEIGHTS:(this.defines.USE_WEIGHTS=`1`,this.uniforms.channelWeights.value=e),this.needsUpdate=!0}setInputBuffer(e){this.uniforms.inputBuffer.value=e}getOpacity(e){return this.uniforms.opacity.value}setOpacity(e){this.uniforms.opacity.value=e}},ix=class extends $b{constructor(e,t=!0){super(`CopyPass`),this.fullscreenMaterial=new rx,this.needsSwap=!1,this.renderTarget=e,e===void 0&&(this.renderTarget=new kr(1,1,{minFilter:L,magFilter:L,stencilBuffer:!1,depthBuffer:!1}),this.renderTarget.texture.name=`CopyPass.Target`),this.autoResize=t}get resize(){return this.autoResize}set resize(e){this.autoResize=e}get texture(){return this.renderTarget.texture}getTexture(){return this.renderTarget.texture}setAutoResizeEnabled(e){this.autoResize=e}render(e,t,n,r,i){this.fullscreenMaterial.inputBuffer=t.texture,e.setRenderTarget(this.renderToScreen?null:this.renderTarget),e.render(this.scene,this.camera)}setSize(e,t){this.autoResize&&this.renderTarget.setSize(e,t)}initialize(e,t,n){n!==void 0&&(this.renderTarget.texture.type=n,n===1009?e!==null&&e.outputColorSpace===`srgb`&&(this.renderTarget.texture.colorSpace=Wt):this.fullscreenMaterial.defines.FRAMEBUFFER_PRECISION_HIGH=`1`)}},ax=new U,ox=class extends $b{constructor(e=!0,t=!0,n=!1){super(`ClearPass`,null,null),this.needsSwap=!1,this.color=e,this.depth=t,this.stencil=n,this.overrideClearColor=null,this.overrideClearAlpha=-1}setClearFlags(e,t,n){this.color=e,this.depth=t,this.stencil=n}getOverrideClearColor(){return this.overrideClearColor}setOverrideClearColor(e){this.overrideClearColor=e}getOverrideClearAlpha(){return this.overrideClearAlpha}setOverrideClearAlpha(e){this.overrideClearAlpha=e}render(e,t,n,r,i){let a=this.overrideClearColor,o=this.overrideClearAlpha,s=e.getClearAlpha(),c=a!==null,l=o>=0;c?(e.getClearColor(ax),e.setClearColor(a,l?o:s)):l&&e.setClearAlpha(o),e.setRenderTarget(this.renderToScreen?null:t),e.clear(this.color,this.depth,this.stencil),c?e.setClearColor(ax,s):l&&e.setClearAlpha(s)}},sx=class extends $b{constructor(e,t){super(`MaskPass`,e,t),this.needsSwap=!1,this.clearPass=new ox(!1,!1,!0),this.inverse=!1}set mainScene(e){this.scene=e}set mainCamera(e){this.camera=e}get inverted(){return this.inverse}set inverted(e){this.inverse=e}get clear(){return this.clearPass.enabled}set clear(e){this.clearPass.enabled=e}getClearPass(){return this.clearPass}isInverted(){return this.inverted}setInverted(e){this.inverted=e}render(e,t,n,r,i){let a=e.getContext(),o=e.state.buffers,s=this.scene,c=this.camera,l=this.clearPass,u=this.inverted?0:1,d=1-u;o.color.setMask(!1),o.depth.setMask(!1),o.color.setLocked(!0),o.depth.setLocked(!0),o.stencil.setTest(!0),o.stencil.setOp(a.REPLACE,a.REPLACE,a.REPLACE),o.stencil.setFunc(a.ALWAYS,u,4294967295),o.stencil.setClear(d),o.stencil.setLocked(!0),this.clearPass.enabled&&(this.renderToScreen?l.render(e,null):(l.render(e,t),l.render(e,n))),this.renderToScreen?(e.setRenderTarget(null),e.render(s,c)):(e.setRenderTarget(t),e.render(s,c),e.setRenderTarget(n),e.render(s,c)),o.color.setLocked(!1),o.depth.setLocked(!1),o.stencil.setLocked(!1),o.stencil.setFunc(a.EQUAL,1,4294967295),o.stencil.setOp(a.KEEP,a.KEEP,a.KEEP),o.stencil.setLocked(!0)}},cx=class{constructor(e=null,{depthBuffer:t=!0,stencilBuffer:n=!1,multisampling:r=0,frameBufferType:i}={}){this.renderer=null,this.inputBuffer=this.createBuffer(t,n,i,r),this.outputBuffer=this.inputBuffer.clone(),this.copyPass=new ix,this.depthTexture=null,this.passes=[],this.timer=new Zb,this.autoRenderToScreen=!0,this.setRenderer(e)}get multisampling(){return this.inputBuffer.samples||0}set multisampling(e){let t=this.inputBuffer,n=this.multisampling;n>0&&e>0?(this.inputBuffer.samples=e,this.outputBuffer.samples=e,this.inputBuffer.dispose(),this.outputBuffer.dispose()):n!==e&&(this.inputBuffer.dispose(),this.outputBuffer.dispose(),this.inputBuffer=this.createBuffer(t.depthBuffer,t.stencilBuffer,t.texture.type,e),this.inputBuffer.depthTexture=this.depthTexture,this.outputBuffer=this.inputBuffer.clone())}getTimer(){return this.timer}getRenderer(){return this.renderer}setRenderer(e){if(this.renderer=e,e!==null){let t=e.getSize(new V),n=e.getContext().getContextAttributes().alpha,r=this.inputBuffer.texture.type;r===1009&&e.outputColorSpace===`srgb`&&(this.inputBuffer.texture.colorSpace=Wt,this.outputBuffer.texture.colorSpace=Wt,this.inputBuffer.dispose(),this.outputBuffer.dispose()),e.autoClear=!1,this.setSize(t.width,t.height);for(let t of this.passes)t.initialize(e,n,r)}}replaceRenderer(e,t=!0){let n=this.renderer,r=n.domElement.parentNode;return this.setRenderer(e),t&&r!==null&&(r.removeChild(n.domElement),r.appendChild(e.domElement)),n}createDepthTexture(){let e=this.depthTexture=new Ws;return this.inputBuffer.depthTexture=e,this.inputBuffer.dispose(),this.inputBuffer.stencilBuffer?(e.format=ze,e.type=Me):e.type=De,e}deleteDepthTexture(){if(this.depthTexture!==null){this.depthTexture.dispose(),this.depthTexture=null,this.inputBuffer.depthTexture=null,this.inputBuffer.dispose();for(let e of this.passes)e.setDepthTexture(null)}}createBuffer(e,t,n,r){let i=this.renderer,a=i===null?new V:i.getDrawingBufferSize(new V),o={minFilter:L,magFilter:L,stencilBuffer:t,depthBuffer:e,type:n},s=new kr(a.width,a.height,o);return r>0&&(s.samples=r),n===1009&&i!==null&&i.outputColorSpace===`srgb`&&(s.texture.colorSpace=Wt),s.texture.name=`EffectComposer.Buffer`,s.texture.generateMipmaps=!1,s}setMainScene(e){for(let t of this.passes)t.mainScene=e}setMainCamera(e){for(let t of this.passes)t.mainCamera=e}addPass(e,t){let n=this.passes,r=this.renderer,i=r.getDrawingBufferSize(new V),a=r.getContext().getContextAttributes().alpha,o=this.inputBuffer.texture.type;if(e.setRenderer(r),e.setSize(i.width,i.height),e.initialize(r,a,o),this.autoRenderToScreen&&(n.length>0&&(n[n.length-1].renderToScreen=!1),e.renderToScreen&&(this.autoRenderToScreen=!1)),t===void 0?n.push(e):n.splice(t,0,e),this.autoRenderToScreen&&(n[n.length-1].renderToScreen=!0),e.needsDepthTexture||this.depthTexture!==null)if(this.depthTexture===null){let t=this.createDepthTexture();for(e of n)e.setDepthTexture(t)}else e.setDepthTexture(this.depthTexture)}removePass(e){let t=this.passes,n=t.indexOf(e);n!==-1&&t.splice(n,1).length>0&&(this.depthTexture!==null&&(t.reduce((e,t)=>e||t.needsDepthTexture,!1)||(e.getDepthTexture()===this.depthTexture&&e.setDepthTexture(null),this.deleteDepthTexture())),this.autoRenderToScreen&&n===t.length&&(e.renderToScreen=!1,t.length>0&&(t[t.length-1].renderToScreen=!0)))}removeAllPasses(){let e=this.passes;this.deleteDepthTexture(),e.length>0&&(this.autoRenderToScreen&&(e[e.length-1].renderToScreen=!1),this.passes=[])}render(e){let t=this.renderer,n=this.copyPass,r=this.inputBuffer,i=this.outputBuffer,a=!1,o,s,c;e===void 0&&(this.timer.update(),e=this.timer.getDelta());for(let l of this.passes)l.enabled&&(l.render(t,r,i,e,a),l.needsSwap&&(a&&(n.renderToScreen=l.renderToScreen,o=t.getContext(),s=t.state.buffers.stencil,s.setFunc(o.NOTEQUAL,1,4294967295),n.render(t,r,i,e,a),s.setFunc(o.EQUAL,1,4294967295)),c=r,r=i,i=c),l instanceof sx?a=!0:l instanceof ex&&(a=!1))}setSize(e,t,n){let r=this.renderer,i=r.getSize(new V);(e===void 0||t===void 0)&&(e=i.width,t=i.height),(i.width!==e||i.height!==t)&&r.setSize(e,t,n);let a=r.getDrawingBufferSize(new V);this.inputBuffer.setSize(a.width,a.height),this.outputBuffer.setSize(a.width,a.height);for(let e of this.passes)e.setSize(a.width,a.height)}reset(){this.dispose(),this.autoRenderToScreen=!0}dispose(){for(let e of this.passes)e.dispose();this.passes=[],this.inputBuffer!==null&&this.inputBuffer.dispose(),this.outputBuffer!==null&&this.outputBuffer.dispose(),this.deleteDepthTexture(),this.copyPass.dispose(),this.timer.dispose(),$b.fullscreenGeometry.dispose()}},lx={NONE:0,DEPTH:1,CONVOLUTION:2},ux={FRAGMENT_HEAD:`FRAGMENT_HEAD`,FRAGMENT_MAIN_UV:`FRAGMENT_MAIN_UV`,FRAGMENT_MAIN_IMAGE:`FRAGMENT_MAIN_IMAGE`,VERTEX_HEAD:`VERTEX_HEAD`,VERTEX_MAIN_SUPPORT:`VERTEX_MAIN_SUPPORT`},dx=class{constructor(){this.shaderParts=new Map([[ux.FRAGMENT_HEAD,null],[ux.FRAGMENT_MAIN_UV,null],[ux.FRAGMENT_MAIN_IMAGE,null],[ux.VERTEX_HEAD,null],[ux.VERTEX_MAIN_SUPPORT,null]]),this.defines=new Map,this.uniforms=new Map,this.blendModes=new Map,this.extensions=new Set,this.attributes=lx.NONE,this.varyings=new Set,this.uvTransformation=!1,this.readDepth=!1,this.colorSpace=Gt}},fx=!1,px=class{constructor(e=null){this.originalMaterials=new Map,this.material=null,this.materials=null,this.materialsBackSide=null,this.materialsDoubleSide=null,this.materialsFlatShaded=null,this.materialsFlatShadedBackSide=null,this.materialsFlatShadedDoubleSide=null,this.setMaterial(e),this.meshCount=0,this.replaceMaterial=e=>{if(e.isMesh){let t;if(e.material.flatShading)switch(e.material.side){case 2:t=this.materialsFlatShadedDoubleSide;break;case 1:t=this.materialsFlatShadedBackSide;break;default:t=this.materialsFlatShaded;break}else switch(e.material.side){case 2:t=this.materialsDoubleSide;break;case 1:t=this.materialsBackSide;break;default:t=this.materials;break}this.originalMaterials.set(e,e.material),e.isSkinnedMesh?e.material=t[2]:e.isInstancedMesh?e.material=t[1]:e.material=t[0],++this.meshCount}}}cloneMaterial(e){if(!(e instanceof q))return e.clone();let t=e.uniforms,n=new Map;for(let e in t){let r=t[e].value;r.isRenderTargetTexture&&(t[e].value=null,n.set(e,r))}let r=e.clone();for(let e of n)t[e[0]].value=e[1],r.uniforms[e[0]].value=e[1];return r}setMaterial(e){if(this.disposeMaterials(),this.material=e,e!==null){let t=this.materials=[this.cloneMaterial(e),this.cloneMaterial(e),this.cloneMaterial(e)];for(let n of t)n.uniforms=Object.assign({},e.uniforms),n.side=0;t[2].skinning=!0,this.materialsBackSide=t.map(t=>{let n=this.cloneMaterial(t);return n.uniforms=Object.assign({},e.uniforms),n.side=1,n}),this.materialsDoubleSide=t.map(t=>{let n=this.cloneMaterial(t);return n.uniforms=Object.assign({},e.uniforms),n.side=2,n}),this.materialsFlatShaded=t.map(t=>{let n=this.cloneMaterial(t);return n.uniforms=Object.assign({},e.uniforms),n.flatShading=!0,n}),this.materialsFlatShadedBackSide=t.map(t=>{let n=this.cloneMaterial(t);return n.uniforms=Object.assign({},e.uniforms),n.flatShading=!0,n.side=1,n}),this.materialsFlatShadedDoubleSide=t.map(t=>{let n=this.cloneMaterial(t);return n.uniforms=Object.assign({},e.uniforms),n.flatShading=!0,n.side=2,n})}}render(e,t,n){let r=e.shadowMap.enabled;if(e.shadowMap.enabled=!1,fx){let r=this.originalMaterials;this.meshCount=0,t.traverse(this.replaceMaterial),e.render(t,n);for(let e of r)e[0].material=e[1];this.meshCount!==r.size&&r.clear()}else{let r=t.overrideMaterial;t.overrideMaterial=this.material,e.render(t,n),t.overrideMaterial=r}e.shadowMap.enabled=r}disposeMaterials(){if(this.material!==null){let e=this.materials.concat(this.materialsBackSide).concat(this.materialsDoubleSide).concat(this.materialsFlatShaded).concat(this.materialsFlatShadedBackSide).concat(this.materialsFlatShadedDoubleSide);for(let t of e)t.dispose()}}dispose(){this.originalMaterials.clear(),this.disposeMaterials()}static get workaroundEnabled(){return fx}static set workaroundEnabled(e){fx=e}},mx=-1,hx=class extends Pn{constructor(e,t=mx,n=mx,r=1){super(),this.resizable=e,this.baseSize=new V(1,1),this.preferredSize=new V(t,n),this.target=this.preferredSize,this.s=r,this.effectiveSize=new V,this.addEventListener(`change`,()=>this.updateEffectiveSize()),this.updateEffectiveSize()}updateEffectiveSize(){let e=this.baseSize,t=this.preferredSize,n=this.effectiveSize,r=this.scale;t.width===mx?t.height===mx?n.width=Math.round(e.width*r):n.width=Math.round(t.height*(e.width/Math.max(e.height,1))):n.width=t.width,t.height===mx?t.width===mx?n.height=Math.round(e.height*r):n.height=Math.round(t.width/Math.max(e.width/Math.max(e.height,1),1)):n.height=t.height}get width(){return this.effectiveSize.width}set width(e){this.preferredWidth=e}get height(){return this.effectiveSize.height}set height(e){this.preferredHeight=e}getWidth(){return this.width}getHeight(){return this.height}get scale(){return this.s}set scale(e){this.s!==e&&(this.s=e,this.preferredSize.setScalar(mx),this.dispatchEvent({type:`change`}),this.resizable.setSize(this.baseSize.width,this.baseSize.height))}getScale(){return this.scale}setScale(e){this.scale=e}get baseWidth(){return this.baseSize.width}set baseWidth(e){this.baseSize.width!==e&&(this.baseSize.width=e,this.dispatchEvent({type:`change`}),this.resizable.setSize(this.baseSize.width,this.baseSize.height))}getBaseWidth(){return this.baseWidth}setBaseWidth(e){this.baseWidth=e}get baseHeight(){return this.baseSize.height}set baseHeight(e){this.baseSize.height!==e&&(this.baseSize.height=e,this.dispatchEvent({type:`change`}),this.resizable.setSize(this.baseSize.width,this.baseSize.height))}getBaseHeight(){return this.baseHeight}setBaseHeight(e){this.baseHeight=e}setBaseSize(e,t){(this.baseSize.width!==e||this.baseSize.height!==t)&&(this.baseSize.set(e,t),this.dispatchEvent({type:`change`}),this.resizable.setSize(this.baseSize.width,this.baseSize.height))}get preferredWidth(){return this.preferredSize.width}set preferredWidth(e){this.preferredSize.width!==e&&(this.preferredSize.width=e,this.dispatchEvent({type:`change`}),this.resizable.setSize(this.baseSize.width,this.baseSize.height))}getPreferredWidth(){return this.preferredWidth}setPreferredWidth(e){this.preferredWidth=e}get preferredHeight(){return this.preferredSize.height}set preferredHeight(e){this.preferredSize.height!==e&&(this.preferredSize.height=e,this.dispatchEvent({type:`change`}),this.resizable.setSize(this.baseSize.width,this.baseSize.height))}getPreferredHeight(){return this.preferredHeight}setPreferredHeight(e){this.preferredHeight=e}setPreferredSize(e,t){(this.preferredSize.width!==e||this.preferredSize.height!==t)&&(this.preferredSize.set(e,t),this.dispatchEvent({type:`change`}),this.resizable.setSize(this.baseSize.width,this.baseSize.height))}copy(e){this.s=e.scale,this.baseSize.set(e.baseWidth,e.baseHeight),this.preferredSize.set(e.preferredWidth,e.preferredHeight),this.dispatchEvent({type:`change`}),this.resizable.setSize(this.baseSize.width,this.baseSize.height)}static get AUTO_SIZE(){return mx}},gx={SKIP:9,SET:30,ADD:0,ALPHA:1,AVERAGE:2,COLOR:3,COLOR_BURN:4,COLOR_DODGE:5,DARKEN:6,DIFFERENCE:7,DIVIDE:8,DST:9,EXCLUSION:10,HARD_LIGHT:11,HARD_MIX:12,HUE:13,INVERT:14,INVERT_RGB:15,LIGHTEN:16,LINEAR_BURN:17,LINEAR_DODGE:18,LINEAR_LIGHT:19,LUMINOSITY:20,MULTIPLY:21,NEGATION:22,NORMAL:23,OVERLAY:24,PIN_LIGHT:25,REFLECT:26,SATURATION:27,SCREEN:28,SOFT_LIGHT:29,SRC:30,SUBTRACT:31,VIVID_LIGHT:32},_x=new Map([[gx.ADD,`vec4 blend(const in vec4 dst,const in vec4 src,const in float opacity){vec3 c=dst.rgb+src.rgb;return mix(dst,vec4(c,max(dst.a,src.a)),opacity);}`],[gx.ALPHA,`vec4 blend(const in vec4 dst,const in vec4 src,const in float opacity){return mix(dst,src,src.a*opacity);}`],[gx.AVERAGE,`vec4 blend(const in vec4 dst,const in vec4 src,const in float opacity){vec3 c=(dst.rgb+src.rgb)*0.5;return mix(dst,vec4(c,max(dst.a,src.a)),opacity);}`],[gx.COLOR,`vec4 blend(const in vec4 dst,const in vec4 src,const in float opacity){vec3 a=RGBToHSL(dst.rgb);vec3 b=RGBToHSL(src.rgb);vec3 c=HSLToRGB(vec3(b.xy,a.z));return mix(dst,vec4(c,max(dst.a,src.a)),opacity);}`],[gx.COLOR_BURN,`vec4 blend(const in vec4 dst,const in vec4 src,const in float opacity){vec3 a=dst.rgb,b=src.rgb;vec3 c=mix(step(0.0,b)*(1.0-min(vec3(1.0),(1.0-a)/max(b,1e-9))),vec3(1.0),step(1.0,a));return mix(dst,vec4(c,max(dst.a,src.a)),opacity);}`],[gx.COLOR_DODGE,`vec4 blend(const in vec4 dst,const in vec4 src,const in float opacity){vec3 a=dst.rgb,b=src.rgb;vec3 c=step(0.0,a)*mix(min(vec3(1.0),a/max(1.0-b,1e-9)),vec3(1.0),step(1.0,b));return mix(dst,vec4(c,max(dst.a,src.a)),opacity);}`],[gx.DARKEN,`vec4 blend(const in vec4 dst,const in vec4 src,const in float opacity){vec3 c=min(dst.rgb,src.rgb);return mix(dst,vec4(c,max(dst.a,src.a)),opacity);}`],[gx.DIFFERENCE,`vec4 blend(const in vec4 dst,const in vec4 src,const in float opacity){vec3 c=abs(dst.rgb-src.rgb);return mix(dst,vec4(c,max(dst.a,src.a)),opacity);}`],[gx.DIVIDE,`vec4 blend(const in vec4 dst,const in vec4 src,const in float opacity){vec3 c=dst.rgb/max(src.rgb,1e-9);return mix(dst,vec4(c,max(dst.a,src.a)),opacity);}`],[gx.DST,null],[gx.EXCLUSION,`vec4 blend(const in vec4 dst,const in vec4 src,const in float opacity){vec3 c=dst.rgb+src.rgb-2.0*dst.rgb*src.rgb;return mix(dst,vec4(c,max(dst.a,src.a)),opacity);}`],[gx.HARD_LIGHT,`vec4 blend(const in vec4 dst,const in vec4 src,const in float opacity){vec3 a=min(dst.rgb,1.0);vec3 b=min(src.rgb,1.0);vec3 c=mix(2.0*a*b,1.0-2.0*(1.0-a)*(1.0-b),step(0.5,b));return mix(dst,vec4(c,max(dst.a,src.a)),opacity);}`],[gx.HARD_MIX,`vec4 blend(const in vec4 dst,const in vec4 src,const in float opacity){vec3 c=step(1.0,dst.rgb+src.rgb);return mix(dst,vec4(c,max(dst.a,src.a)),opacity);}`],[gx.HUE,`vec4 blend(const in vec4 dst,const in vec4 src,const in float opacity){vec3 a=RGBToHSL(dst.rgb);vec3 b=RGBToHSL(src.rgb);vec3 c=HSLToRGB(vec3(b.x,a.yz));return mix(dst,vec4(c,max(dst.a,src.a)),opacity);}`],[gx.INVERT,`vec4 blend(const in vec4 dst,const in vec4 src,const in float opacity){vec3 c=max(1.0-src.rgb,0.0);return mix(dst,vec4(c,max(dst.a,src.a)),opacity);}`],[gx.INVERT_RGB,`vec4 blend(const in vec4 dst,const in vec4 src,const in float opacity){vec3 c=src.rgb*max(1.0-dst.rgb,0.0);return mix(dst,vec4(c,max(dst.a,src.a)),opacity);}`],[gx.LIGHTEN,`vec4 blend(const in vec4 dst,const in vec4 src,const in float opacity){vec3 c=max(dst.rgb,src.rgb);return mix(dst,vec4(c,max(dst.a,src.a)),opacity);}`],[gx.LINEAR_BURN,`vec4 blend(const in vec4 dst,const in vec4 src,const in float opacity){vec3 c=clamp(src.rgb+dst.rgb-1.0,0.0,1.0);return mix(dst,vec4(c,max(dst.a,src.a)),opacity);}`],[gx.LINEAR_DODGE,`vec4 blend(const in vec4 dst,const in vec4 src,const in float opacity){vec3 c=min(dst.rgb+src.rgb,1.0);return mix(dst,vec4(c,max(dst.a,src.a)),opacity);}`],[gx.LINEAR_LIGHT,`vec4 blend(const in vec4 dst,const in vec4 src,const in float opacity){vec3 c=clamp(2.0*src.rgb+dst.rgb-1.0,0.0,1.0);return mix(dst,vec4(c,max(dst.a,src.a)),opacity);}`],[gx.LUMINOSITY,`vec4 blend(const in vec4 dst,const in vec4 src,const in float opacity){vec3 a=RGBToHSL(dst.rgb);vec3 b=RGBToHSL(src.rgb);vec3 c=HSLToRGB(vec3(a.xy,b.z));return mix(dst,vec4(c,max(dst.a,src.a)),opacity);}`],[gx.MULTIPLY,`vec4 blend(const in vec4 dst,const in vec4 src,const in float opacity){vec3 c=dst.rgb*src.rgb;return mix(dst,vec4(c,max(dst.a,src.a)),opacity);}`],[gx.NEGATION,`vec4 blend(const in vec4 dst,const in vec4 src,const in float opacity){vec3 c=max(1.0-abs(1.0-dst.rgb-src.rgb),0.0);return mix(dst,vec4(c,max(dst.a,src.a)),opacity);}`],[gx.NORMAL,`vec4 blend(const in vec4 dst,const in vec4 src,const in float opacity){return mix(dst,src,opacity);}`],[gx.OVERLAY,`vec4 blend(const in vec4 dst,const in vec4 src,const in float opacity){vec3 a=2.0*src.rgb*dst.rgb;vec3 b=1.0-2.0*(1.0-src.rgb)*(1.0-dst.rgb);vec3 c=mix(a,b,step(0.5,dst.rgb));return mix(dst,vec4(c,max(dst.a,src.a)),opacity);}`],[gx.PIN_LIGHT,`vec4 blend(const in vec4 dst,const in vec4 src,const in float opacity){vec3 src2=2.0*src.rgb;vec3 c=mix(mix(src2,dst.rgb,step(0.5*dst.rgb,src.rgb)),max(src2-1.0,vec3(0.0)),step(dst.rgb,src2-1.0));return mix(dst,vec4(c,max(dst.a,src.a)),opacity);}`],[gx.REFLECT,`vec4 blend(const in vec4 dst,const in vec4 src,const in float opacity){vec3 a=min(dst.rgb*dst.rgb/max(1.0-src.rgb,1e-9),1.0);vec3 c=mix(a,src.rgb,step(1.0,src.rgb));return mix(dst,vec4(c,max(dst.a,src.a)),opacity);}`],[gx.SATURATION,`vec4 blend(const in vec4 dst,const in vec4 src,const in float opacity){vec3 a=RGBToHSL(dst.rgb);vec3 b=RGBToHSL(src.rgb);vec3 c=HSLToRGB(vec3(a.x,b.y,a.z));return mix(dst,vec4(c,max(dst.a,src.a)),opacity);}`],[gx.SCREEN,`vec4 blend(const in vec4 dst,const in vec4 src,const in float opacity){vec3 c=dst.rgb+src.rgb-min(dst.rgb*src.rgb,1.0);return mix(dst,vec4(c,max(dst.a,src.a)),opacity);}`],[gx.SOFT_LIGHT,`vec4 blend(const in vec4 dst,const in vec4 src,const in float opacity){vec3 src2=2.0*src.rgb;vec3 d=dst.rgb+(src2-1.0);vec3 w=step(0.5,src.rgb);vec3 a=dst.rgb-(1.0-src2)*dst.rgb*(1.0-dst.rgb);vec3 b=mix(d*(sqrt(dst.rgb)-dst.rgb),d*dst.rgb*((16.0*dst.rgb-12.0)*dst.rgb+3.0),w*(1.0-step(0.25,dst.rgb)));vec3 c=mix(a,b,w);return mix(dst,vec4(c,max(dst.a,src.a)),opacity);}`],[gx.SRC,`vec4 blend(const in vec4 dst,const in vec4 src,const in float opacity){return src;}`],[gx.SUBTRACT,`vec4 blend(const in vec4 dst,const in vec4 src,const in float opacity){vec3 c=max(dst.rgb-src.rgb,0.0);return mix(dst,vec4(c,max(dst.a,src.a)),opacity);}`],[gx.VIVID_LIGHT,`vec4 blend(const in vec4 dst,const in vec4 src,const in float opacity){vec3 c=mix(max(1.0-min((1.0-dst.rgb)/(2.0*src.rgb),1.0),0.0),min(dst.rgb/(2.0*(1.0-src.rgb)),1.0),step(0.5,src.rgb));return mix(dst,vec4(c,max(dst.a,src.a)),opacity);}`]]),vx=class extends Pn{constructor(e,t=1){super(),this._blendFunction=e,this.opacity=new df(t)}getOpacity(){return this.opacity.value}setOpacity(e){this.opacity.value=e}get blendFunction(){return this._blendFunction}set blendFunction(e){this._blendFunction=e,this.dispatchEvent({type:`change`})}getBlendFunction(){return this.blendFunction}setBlendFunction(e){this.blendFunction=e}getShaderCode(){return _x.get(this.blendFunction)}},yx=class extends Pn{constructor(e,t,{attributes:n=lx.NONE,blendFunction:r=gx.NORMAL,defines:i=new Map,uniforms:a=new Map,extensions:o=null,vertexShader:s=null}={}){super(),this.name=e,this.renderer=null,this.attributes=n,this.fragmentShader=t,this.vertexShader=s,this.defines=i,this.uniforms=a,this.extensions=o,this.blendMode=new vx(r),this.blendMode.addEventListener(`change`,e=>this.setChanged()),this._inputColorSpace=Gt,this._outputColorSpace=``}get inputColorSpace(){return this._inputColorSpace}set inputColorSpace(e){this._inputColorSpace=e,this.setChanged()}get outputColorSpace(){return this._outputColorSpace}set outputColorSpace(e){this._outputColorSpace=e,this.setChanged()}set mainScene(e){}set mainCamera(e){}getName(){return this.name}setRenderer(e){this.renderer=e}getDefines(){return this.defines}getUniforms(){return this.uniforms}getExtensions(){return this.extensions}getBlendMode(){return this.blendMode}getAttributes(){return this.attributes}setAttributes(e){this.attributes=e,this.setChanged()}getFragmentShader(){return this.fragmentShader}setFragmentShader(e){this.fragmentShader=e,this.setChanged()}getVertexShader(){return this.vertexShader}setVertexShader(e){this.vertexShader=e,this.setChanged()}setChanged(){this.dispatchEvent({type:`change`})}setDepthTexture(e,t=Bt){}update(e,t,n){}setSize(e,t){}initialize(e,t,n){}dispose(){for(let e of Object.keys(this)){let t=this[e];(t instanceof kr||t instanceof Ta||t instanceof Er||t instanceof $b)&&this[e].dispose()}}};new Float32Array([0,0]),new Float32Array([0,1,1]),new Float32Array([0,1,1,2]),new Float32Array([0,1,2,2,3]),new Float32Array([0,1,2,3,4,4,5]),new Float32Array([0,1,2,3,4,5,7,8,9,10]);var bx=class extends $b{constructor(e,t,n=null){super(`RenderPass`,e,t),this.needsSwap=!1,this.clearPass=new ox,this.overrideMaterialManager=n===null?null:new px(n),this.ignoreBackground=!1,this.skipShadowMapUpdate=!1,this.selection=null}set mainScene(e){this.scene=e}set mainCamera(e){this.camera=e}get renderToScreen(){return super.renderToScreen}set renderToScreen(e){super.renderToScreen=e,this.clearPass.renderToScreen=e}get overrideMaterial(){let e=this.overrideMaterialManager;return e===null?null:e.material}set overrideMaterial(e){let t=this.overrideMaterialManager;e===null?t!==null&&(t.dispose(),this.overrideMaterialManager=null):t===null?this.overrideMaterialManager=new px(e):t.setMaterial(e)}getOverrideMaterial(){return this.overrideMaterial}setOverrideMaterial(e){this.overrideMaterial=e}get clear(){return this.clearPass.enabled}set clear(e){this.clearPass.enabled=e}getSelection(){return this.selection}setSelection(e){this.selection=e}isBackgroundDisabled(){return this.ignoreBackground}setBackgroundDisabled(e){this.ignoreBackground=e}isShadowMapDisabled(){return this.skipShadowMapUpdate}setShadowMapDisabled(e){this.skipShadowMapUpdate=e}getClearPass(){return this.clearPass}render(e,t,n,r,i){let a=this.scene,o=this.camera,s=this.selection,c=o.layers.mask,l=a.background,u=e.shadowMap.autoUpdate,d=this.renderToScreen?null:t;s!==null&&o.layers.set(s.getLayer()),this.skipShadowMapUpdate&&(e.shadowMap.autoUpdate=!1),(this.ignoreBackground||this.clearPass.overrideClearColor!==null)&&(a.background=null),this.clearPass.enabled&&this.clearPass.render(e,t),e.setRenderTarget(d),this.overrideMaterialManager===null?e.render(a,o):this.overrideMaterialManager.render(e,a,o),o.layers.mask=c,a.background=l,e.shadowMap.autoUpdate=u}};Math.PI*.5;var xx=`#include +#ifdef GL_FRAGMENT_PRECISION_HIGH +uniform highp sampler2D depthBuffer; +#else +uniform mediump sampler2D depthBuffer; +#endif +#ifdef DOWNSAMPLE_NORMALS +uniform lowp sampler2D normalBuffer; +#endif +varying vec2 vUv0;varying vec2 vUv1;varying vec2 vUv2;varying vec2 vUv3;float readDepth(const in vec2 uv){ +#if DEPTH_PACKING == 3201 +return unpackRGBAToDepth(texture2D(depthBuffer,uv)); +#else +return texture2D(depthBuffer,uv).r; +#endif +}int findBestDepth(const in float samples[4]){float c=(samples[0]+samples[1]+samples[2]+samples[3])*0.25;float distances[4];distances[0]=abs(c-samples[0]);distances[1]=abs(c-samples[1]);distances[2]=abs(c-samples[2]);distances[3]=abs(c-samples[3]);float maxDistance=max(max(distances[0],distances[1]),max(distances[2],distances[3]));int remaining[3];int rejected[3];int i,j,k;for(i=0,j=0,k=0;i<4;++i){if(distances[i]this.setSize(s.baseWidth,s.baseHeight))}get texture(){return this.renderTarget.texture}getTexture(){return this.renderTarget.texture}getResolution(){return this.resolution}setDepthTexture(e,t=Bt){this.fullscreenMaterial.depthBuffer=e,this.fullscreenMaterial.depthPacking=t}render(e,t,n,r,i){e.setRenderTarget(this.renderToScreen?null:this.renderTarget),e.render(this.scene,this.camera)}setSize(e,t){let n=this.resolution;n.setBaseSize(e,t),this.renderTarget.setSize(n.width,n.height),this.fullscreenMaterial.setSize(e,t)}initialize(e,t,n){let r=e.getContext();if(!(r.getExtension(`EXT_color_buffer_float`)||r.getExtension(`EXT_color_buffer_half_float`)))throw Error(`Rendering to float texture is not supported.`)}},Tx=`#include +#include +#include +#define packFloatToRGBA(v) packDepthToRGBA(v) +#define unpackRGBAToFloat(v) unpackRGBAToDepth(v) +#ifdef FRAMEBUFFER_PRECISION_HIGH +uniform mediump sampler2D inputBuffer; +#else +uniform lowp sampler2D inputBuffer; +#endif +#if DEPTH_PACKING == 3201 +uniform lowp sampler2D depthBuffer; +#elif defined(GL_FRAGMENT_PRECISION_HIGH) +uniform highp sampler2D depthBuffer; +#else +uniform mediump sampler2D depthBuffer; +#endif +uniform vec2 resolution;uniform vec2 texelSize;uniform float cameraNear;uniform float cameraFar;uniform float aspect;uniform float time;varying vec2 vUv;vec4 sRGBToLinear(const in vec4 value){return vec4(mix(pow(value.rgb*0.9478672986+vec3(0.0521327014),vec3(2.4)),value.rgb*0.0773993808,vec3(lessThanEqual(value.rgb,vec3(0.04045)))),value.a);}float readDepth(const in vec2 uv){ +#if DEPTH_PACKING == 3201 +float depth=unpackRGBAToDepth(texture2D(depthBuffer,uv)); +#else +float depth=texture2D(depthBuffer,uv).r; +#endif +#if defined(USE_LOGARITHMIC_DEPTH_BUFFER) || defined(LOG_DEPTH) +float d=pow(2.0,depth*log2(cameraFar+1.0))-1.0;float a=cameraFar/(cameraFar-cameraNear);float b=cameraFar*cameraNear/(cameraNear-cameraFar);depth=a+b/d; +#elif defined(USE_REVERSED_DEPTH_BUFFER) +depth=1.0-depth; +#endif +return depth;}float getViewZ(const in float depth){ +#ifdef PERSPECTIVE_CAMERA +return perspectiveDepthToViewZ(depth,cameraNear,cameraFar); +#else +return orthographicDepthToViewZ(depth,cameraNear,cameraFar); +#endif +}vec3 RGBToHCV(const in vec3 RGB){vec4 P=mix(vec4(RGB.bg,-1.0,2.0/3.0),vec4(RGB.gb,0.0,-1.0/3.0),step(RGB.b,RGB.g));vec4 Q=mix(vec4(P.xyw,RGB.r),vec4(RGB.r,P.yzx),step(P.x,RGB.r));float C=Q.x-min(Q.w,Q.y);float H=abs((Q.w-Q.y)/(6.0*C+EPSILON)+Q.z);return vec3(H,C,Q.x);}vec3 RGBToHSL(const in vec3 RGB){vec3 HCV=RGBToHCV(RGB);float L=HCV.z-HCV.y*0.5;float S=HCV.y/(1.0-abs(L*2.0-1.0)+EPSILON);return vec3(HCV.x,S,L);}vec3 HueToRGB(const in float H){float R=abs(H*6.0-3.0)-1.0;float G=2.0-abs(H*6.0-2.0);float B=2.0-abs(H*6.0-4.0);return clamp(vec3(R,G,B),0.0,1.0);}vec3 HSLToRGB(const in vec3 HSL){vec3 RGB=HueToRGB(HSL.x);float C=(1.0-abs(2.0*HSL.z-1.0))*HSL.y;return(RGB-0.5)*C+HSL.z;}FRAGMENT_HEAD void main(){FRAGMENT_MAIN_UV vec4 color0=texture2D(inputBuffer,UV);vec4 color1=vec4(0.0);FRAGMENT_MAIN_IMAGE color0.a=clamp(color0.a,0.0,1.0);gl_FragColor=color0; +#ifdef ENCODE_OUTPUT +#include +#endif +#include +}`,Ex=`uniform vec2 resolution;uniform vec2 texelSize;uniform float cameraNear;uniform float cameraFar;uniform float aspect;uniform float time;varying vec2 vUv;VERTEX_HEAD void main(){vUv=position.xy*0.5+0.5;VERTEX_MAIN_SUPPORT gl_Position=vec4(position.xy,1.0,1.0);}`,Dx=class extends q{constructor(e,t,n,r,i=!1){super({name:`EffectMaterial`,defines:{THREE_REVISION:`183`.replace(/\D+/g,``),DEPTH_PACKING:`0`,ENCODE_OUTPUT:`1`},uniforms:{inputBuffer:new df(null),depthBuffer:new df(null),resolution:new df(new V),texelSize:new df(new V),cameraNear:new df(.3),cameraFar:new df(1e3),aspect:new df(1),time:new df(0)},blending:0,toneMapped:!1,depthWrite:!1,depthTest:!1,dithering:i}),e&&this.setShaderParts(e),t&&this.setDefines(t),n&&this.setUniforms(n),this.copyCameraSettings(r)}set inputBuffer(e){this.uniforms.inputBuffer.value=e}setInputBuffer(e){this.uniforms.inputBuffer.value=e}get depthBuffer(){return this.uniforms.depthBuffer.value}set depthBuffer(e){this.uniforms.depthBuffer.value=e}get depthPacking(){return Number(this.defines.DEPTH_PACKING)}set depthPacking(e){this.defines.DEPTH_PACKING=e.toFixed(0),this.needsUpdate=!0}setDepthBuffer(e,t=Bt){this.depthBuffer=e,this.depthPacking=t}setShaderData(e){this.setShaderParts(e.shaderParts),this.setDefines(e.defines),this.setUniforms(e.uniforms),this.setExtensions(e.extensions)}setShaderParts(e){return this.fragmentShader=Tx.replace(ux.FRAGMENT_HEAD,e.get(ux.FRAGMENT_HEAD)||``).replace(ux.FRAGMENT_MAIN_UV,e.get(ux.FRAGMENT_MAIN_UV)||``).replace(ux.FRAGMENT_MAIN_IMAGE,e.get(ux.FRAGMENT_MAIN_IMAGE)||``),this.vertexShader=Ex.replace(ux.VERTEX_HEAD,e.get(ux.VERTEX_HEAD)||``).replace(ux.VERTEX_MAIN_SUPPORT,e.get(ux.VERTEX_MAIN_SUPPORT)||``),this.needsUpdate=!0,this}setDefines(e){for(let t of e.entries())this.defines[t[0]]=t[1];return this.needsUpdate=!0,this}setUniforms(e){for(let t of e.entries())this.uniforms[t[0]]=t[1];return this}setExtensions(e){this.extensions={};for(let t of e)this.extensions[t]=!0;return this}get encodeOutput(){return this.defines.ENCODE_OUTPUT!==void 0}set encodeOutput(e){this.encodeOutput!==e&&(e?this.defines.ENCODE_OUTPUT=`1`:delete this.defines.ENCODE_OUTPUT,this.needsUpdate=!0)}isOutputEncodingEnabled(e){return this.encodeOutput}setOutputEncodingEnabled(e){this.encodeOutput=e}get time(){return this.uniforms.time.value}set time(e){this.uniforms.time.value=e}setDeltaTime(e){this.uniforms.time.value+=e}adoptCameraSettings(e){this.copyCameraSettings(e)}copyCameraSettings(e){e&&(this.uniforms.cameraNear.value=e.near,this.uniforms.cameraFar.value=e.far,e instanceof Qu?this.defines.PERSPECTIVE_CAMERA=`1`:delete this.defines.PERSPECTIVE_CAMERA,this.needsUpdate=!0)}setSize(e,t){let n=this.uniforms;n.resolution.value.set(e,t),n.texelSize.value.set(1/e,1/t),n.aspect.value=e/t}static get Section(){return ux}};Number(`183`.replace(/\D+/g,``));var Ox=255/256;new Float32Array([Ox/256**3,Ox/256**2,Ox/256,Ox]),new Float32Array([Ox,Ox/256,Ox/256**2,1/256**3]);function kx(e,t,n){for(let r of t){let t=`$1`+e+r.charAt(0).toUpperCase()+r.slice(1),i=RegExp(`([^\\.])(\\b`+r+`\\b)`,`g`);for(let e of n.entries())e[1]!==null&&n.set(e[0],e[1].replace(i,t))}}function Ax(e,t,n){let r=t.getFragmentShader(),i=t.getVertexShader(),a=r!==void 0&&/mainImage/.test(r),o=r!==void 0&&/mainUv/.test(r);if(n.attributes|=t.getAttributes(),r===void 0)throw Error(`Missing fragment shader (${t.name})`);if(o&&(n.attributes&lx.CONVOLUTION)!==0)throw Error(`Effects that transform UVs are incompatible with convolution effects (${t.name})`);if(!a&&!o)throw Error(`Could not find mainImage or mainUv function (${t.name})`);{let s=/\w+\s+(\w+)\([\w\s,]*\)\s*{/g,c=n.shaderParts,l=c.get(ux.FRAGMENT_HEAD)||``,u=c.get(ux.FRAGMENT_MAIN_UV)||``,d=c.get(ux.FRAGMENT_MAIN_IMAGE)||``,f=c.get(ux.VERTEX_HEAD)||``,p=c.get(ux.VERTEX_MAIN_SUPPORT)||``,m=new Set,h=new Set;if(o&&(u+=` ${e}MainUv(UV); +`,n.uvTransformation=!0),i!==null&&/mainSupport/.test(i)){let t=/mainSupport *\([\w\s]*?uv\s*?\)/.test(i);p+=` ${e}MainSupport(`,p+=t?`vUv); +`:`); +`;for(let e of i.matchAll(/(?:varying\s+\w+\s+([\S\s]*?);)/g))for(let t of e[1].split(/\s*,\s*/))n.varyings.add(t),m.add(t),h.add(t);for(let e of i.matchAll(s))h.add(e[1])}for(let e of r.matchAll(s))h.add(e[1]);for(let e of t.defines.keys())h.add(e.replace(/\([\w\s,]*\)/g,``));for(let e of t.uniforms.keys())h.add(e);h.delete(`while`),h.delete(`for`),h.delete(`if`),t.uniforms.forEach((t,r)=>n.uniforms.set(e+r.charAt(0).toUpperCase()+r.slice(1),t)),t.defines.forEach((t,r)=>n.defines.set(e+r.charAt(0).toUpperCase()+r.slice(1),t));let g=new Map([[`fragment`,r],[`vertex`,i]]);kx(e,h,n.defines),kx(e,h,g),r=g.get(`fragment`),i=g.get(`vertex`);let _=t.blendMode;if(n.blendModes.set(_.blendFunction,_),a){t.inputColorSpace!==null&&t.inputColorSpace!==n.colorSpace&&(d+=t.inputColorSpace===`srgb`?`color0 = sRGBTransferOETF(color0); + `:`color0 = sRGBToLinear(color0); + `),t.outputColorSpace===``?t.inputColorSpace!==null&&(n.colorSpace=t.inputColorSpace):n.colorSpace=t.outputColorSpace,d+=`${e}MainImage(color0, UV, `,(n.attributes&lx.DEPTH)!==0&&/MainImage *\([\w\s,]*?depth[\w\s,]*?\)/.test(r)&&(d+=`depth, `,n.readDepth=!0),d+=`color1); + `;let i=e+`BlendOpacity`;n.uniforms.set(i,_.opacity),d+=`color0 = blend${_.blendFunction}(color0, color1, ${i}); + + `,l+=`uniform float ${i}; + +`}if(l+=r+` +`,i!==null&&(f+=i+` +`),c.set(ux.FRAGMENT_HEAD,l),c.set(ux.FRAGMENT_MAIN_UV,u),c.set(ux.FRAGMENT_MAIN_IMAGE,d),c.set(ux.VERTEX_HEAD,f),c.set(ux.VERTEX_MAIN_SUPPORT,p),t.extensions!==null)for(let e of t.extensions)n.extensions.add(e)}}var jx=class extends $b{constructor(e,...t){super(`EffectPass`),this.fullscreenMaterial=new Dx(null,null,null,e),this.listener=e=>this.handleEvent(e),this.effects=[],this.setEffects(t),this.skipRendering=!1,this.minTime=1,this.maxTime=1/0,this.timeScale=1}set mainScene(e){for(let t of this.effects)t.mainScene=e}set mainCamera(e){this.fullscreenMaterial.copyCameraSettings(e);for(let t of this.effects)t.mainCamera=e}get encodeOutput(){return this.fullscreenMaterial.encodeOutput}set encodeOutput(e){this.fullscreenMaterial.encodeOutput=e}get dithering(){return this.fullscreenMaterial.dithering}set dithering(e){let t=this.fullscreenMaterial;t.dithering=e,t.needsUpdate=!0}setEffects(e){for(let e of this.effects)e.removeEventListener(`change`,this.listener);this.effects=e.sort((e,t)=>t.attributes-e.attributes);for(let e of this.effects)e.addEventListener(`change`,this.listener)}updateMaterial(){let e=new dx,t=0;for(let n of this.effects)if(n.blendMode.blendFunction===gx.DST)e.attributes|=n.getAttributes()&lx.DEPTH;else if((e.attributes&n.getAttributes()&lx.CONVOLUTION)!==0)throw Error(`Convolution effects cannot be merged (${n.name})`);else Ax(`e`+ t++,n,e);let n=e.shaderParts.get(ux.FRAGMENT_HEAD),r=e.shaderParts.get(ux.FRAGMENT_MAIN_IMAGE),i=e.shaderParts.get(ux.FRAGMENT_MAIN_UV),a=/\bblend\b/g;for(let t of e.blendModes.values())n+=t.getShaderCode().replace(a,`blend${t.blendFunction}`)+` +`;(e.attributes&lx.DEPTH)===0?this.needsDepthTexture=!1:(e.readDepth&&(r=`float depth = readDepth(UV); + + `+r),this.needsDepthTexture=this.getDepthTexture()===null),e.colorSpace===`srgb`&&(r+=`color0 = sRGBToLinear(color0); + `),e.uvTransformation?(i=`vec2 transformedUv = vUv; +`+i,e.defines.set(`UV`,`transformedUv`)):e.defines.set(`UV`,`vUv`),e.shaderParts.set(ux.FRAGMENT_HEAD,n),e.shaderParts.set(ux.FRAGMENT_MAIN_IMAGE,r),e.shaderParts.set(ux.FRAGMENT_MAIN_UV,i);for(let[t,n]of e.shaderParts)n!==null&&e.shaderParts.set(t,n.trim().replace(/^#/,` +#`));this.skipRendering=t===0,this.needsSwap=!this.skipRendering,this.fullscreenMaterial.setShaderData(e)}recompile(){this.updateMaterial()}getDepthTexture(){return this.fullscreenMaterial.depthBuffer}setDepthTexture(e,t=Bt){this.fullscreenMaterial.depthBuffer=e,this.fullscreenMaterial.depthPacking=t;for(let n of this.effects)n.setDepthTexture(e,t)}render(e,t,n,r,i){for(let n of this.effects)n.update(e,t,r);if(!this.skipRendering||this.renderToScreen){let i=this.fullscreenMaterial;i.inputBuffer=t.texture,i.time+=r*this.timeScale,e.setRenderTarget(this.renderToScreen?null:n),e.render(this.scene,this.camera)}}setSize(e,t){this.fullscreenMaterial.setSize(e,t);for(let n of this.effects)n.setSize(e,t)}initialize(e,t,n){this.renderer=e;for(let r of this.effects)r.initialize(e,t,n);this.updateMaterial(),n!==void 0&&n!==1009&&(this.fullscreenMaterial.defines.FRAMEBUFFER_PRECISION_HIGH=`1`)}dispose(){super.dispose();for(let e of this.effects)e.removeEventListener(`change`,this.listener),e.dispose()}handleEvent(e){switch(e.type){case`change`:this.recompile();break}}},Mx=class extends $b{constructor(e,t,{renderTarget:n,resolutionScale:r=1,width:i=hx.AUTO_SIZE,height:a=hx.AUTO_SIZE,resolutionX:o=i,resolutionY:s=a}={}){super(`NormalPass`),this.needsSwap=!1,this.renderPass=new bx(e,t,new Yl);let c=this.renderPass;c.ignoreBackground=!0,c.skipShadowMapUpdate=!0;let l=c.getClearPass();l.overrideClearColor=new U(7829503),l.overrideClearAlpha=1,this.renderTarget=n,this.renderTarget===void 0&&(this.renderTarget=new kr(1,1,{minFilter:ge,magFilter:ge}),this.renderTarget.texture.name=`NormalPass.Target`);let u=this.resolution=new hx(this,o,s,r);u.addEventListener(`change`,e=>this.setSize(u.baseWidth,u.baseHeight))}set mainScene(e){this.renderPass.mainScene=e}set mainCamera(e){this.renderPass.mainCamera=e}get texture(){return this.renderTarget.texture}getTexture(){return this.renderTarget.texture}getResolution(){return this.resolution}getResolutionScale(){return this.resolution.scale}setResolutionScale(e){this.resolution.scale=e}render(e,t,n,r,i){let a=this.renderToScreen?null:this.renderTarget;this.renderPass.render(e,a,a)}setSize(e,t){let n=this.resolution;n.setBaseSize(e,t),this.renderTarget.setSize(n.width,n.height)}};new Float32Array(3),new Float32Array(3),new Float32Array(3),new Float32Array(3),new Float32Array(3),new Float32Array(3),new Float32Array([0,0,0]),new Float32Array([1,0,0]),new Float32Array([1,1,0]),new Float32Array([1,1,1]),new Float32Array([0,0,0]),new Float32Array([1,0,0]),new Float32Array([1,0,1]),new Float32Array([1,1,1]),new Float32Array([0,0,0]),new Float32Array([0,0,1]),new Float32Array([1,0,1]),new Float32Array([1,1,1]),new Float32Array([0,0,0]),new Float32Array([0,1,0]),new Float32Array([1,1,0]),new Float32Array([1,1,1]),new Float32Array([0,0,0]),new Float32Array([0,1,0]),new Float32Array([0,1,1]),new Float32Array([1,1,1]),new Float32Array([0,0,0]),new Float32Array([0,0,1]),new Float32Array([0,1,1]),new Float32Array([1,1,1]),new Float32Array(2),new Float32Array(2),new Float32Array([0,-.25,.25,-.125,.125,-.375,.375]),new Float32Array([0,0]),new Float32Array([.25,-.25]),new Float32Array([-.25,.25]),new Float32Array([.125,-.125]),new Float32Array([-.125,.125]),new Uint8Array([0,0]),new Uint8Array([3,0]),new Uint8Array([0,3]),new Uint8Array([3,3]),new Uint8Array([1,0]),new Uint8Array([4,0]),new Uint8Array([1,3]),new Uint8Array([4,3]),new Uint8Array([0,1]),new Uint8Array([3,1]),new Uint8Array([0,4]),new Uint8Array([3,4]),new Uint8Array([1,1]),new Uint8Array([4,1]),new Uint8Array([1,4]),new Uint8Array([4,4]),new Uint8Array([0,0]),new Uint8Array([1,0]),new Uint8Array([0,2]),new Uint8Array([1,2]),new Uint8Array([2,0]),new Uint8Array([3,0]),new Uint8Array([2,2]),new Uint8Array([3,2]),new Uint8Array([0,1]),new Uint8Array([1,1]),new Uint8Array([0,3]),new Uint8Array([1,3]),new Uint8Array([2,1]),new Uint8Array([3,1]),new Uint8Array([2,3]),new Uint8Array([3,3]),new Map([[Px(0,0,0,0),new Float32Array([0,0,0,0])],[Px(0,0,0,1),new Float32Array([0,0,0,1])],[Px(0,0,1,0),new Float32Array([0,0,1,0])],[Px(0,0,1,1),new Float32Array([0,0,1,1])],[Px(0,1,0,0),new Float32Array([0,1,0,0])],[Px(0,1,0,1),new Float32Array([0,1,0,1])],[Px(0,1,1,0),new Float32Array([0,1,1,0])],[Px(0,1,1,1),new Float32Array([0,1,1,1])],[Px(1,0,0,0),new Float32Array([1,0,0,0])],[Px(1,0,0,1),new Float32Array([1,0,0,1])],[Px(1,0,1,0),new Float32Array([1,0,1,0])],[Px(1,0,1,1),new Float32Array([1,0,1,1])],[Px(1,1,0,0),new Float32Array([1,1,0,0])],[Px(1,1,0,1),new Float32Array([1,1,0,1])],[Px(1,1,1,0),new Float32Array([1,1,1,0])],[Px(1,1,1,1),new Float32Array([1,1,1,1])]]);function Nx(e,t,n){return e+(t-e)*n}function Px(e,t,n,r){return Nx(Nx(e,t,.75),Nx(n,r,.75),.875)}function Fx(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Ix(e,t){return Ix=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e},Ix(e,t)}function Lx(){if(typeof Reflect>`u`||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy==`function`)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch{return!1}}new V,new V;function Rx(e,t){if(!(e instanceof t))throw TypeError(`Cannot call a class as a function`)}var zx=function e(t,n,r){var i=this;Rx(this,e),Fx(this,`dot2`,function(e,t){return i.x*e+i.y*t}),Fx(this,`dot3`,function(e,t,n){return i.x*e+i.y*t+i.z*n}),this.x=t,this.y=n,this.z=r},Bx=[new zx(1,1,0),new zx(-1,1,0),new zx(1,-1,0),new zx(-1,-1,0),new zx(1,0,1),new zx(-1,0,1),new zx(1,0,-1),new zx(-1,0,-1),new zx(0,1,1),new zx(0,-1,1),new zx(0,1,-1),new zx(0,-1,-1)],Vx=[151,160,137,91,90,15,131,13,201,95,96,53,194,233,7,225,140,36,103,30,69,142,8,99,37,240,21,10,23,190,6,148,247,120,234,75,0,26,197,62,94,252,219,203,117,35,11,32,57,177,33,88,237,149,56,87,174,20,125,136,171,168,68,175,74,165,71,134,139,48,27,166,77,146,158,231,83,111,229,122,60,211,133,230,220,105,92,41,55,46,245,40,244,102,143,54,65,25,63,161,1,216,80,73,209,76,132,187,208,89,18,169,200,196,135,130,116,188,159,86,164,100,109,198,173,186,3,64,52,217,226,250,124,123,5,202,38,147,118,126,255,82,85,212,207,206,59,227,47,16,58,17,182,189,28,42,223,183,170,213,119,248,152,2,44,154,163,70,221,153,101,155,167,43,172,9,129,22,39,253,19,98,108,110,79,113,224,232,178,185,112,104,218,246,97,228,251,34,242,193,238,210,144,12,191,179,162,241,81,51,145,235,249,14,239,107,49,192,214,31,181,199,106,157,184,84,204,176,115,121,50,45,127,4,150,254,138,236,205,93,222,114,67,29,24,72,243,141,128,195,78,66,215,61,156,180],Hx=Array(512),Ux=Array(512);(function(e){e>0&&e<1&&(e*=65536),e=Math.floor(e),e<256&&(e|=e<<8);for(var t=0;t<256;t++){var n=t&1?Vx[t]^e&255:Vx[t]^e>>8&255;Hx[t]=Hx[t+256]=n,Ux[t]=Ux[t+256]=Bx[n%12]}})(0),.5*(Math.sqrt(3)-1),(3-Math.sqrt(3))/6,Math.PI*2;function Wx(e){if(typeof e==`number`)e=Math.abs(e);else if(typeof e==`string`){var t=e;e=0;for(var n=0;n0&&arguments[0]!==void 0?arguments[0]:2,i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:1,a=arguments.length>2&&arguments[2]!==void 0?arguments[2]:.2,o=arguments.length>3&&arguments[3]!==void 0?arguments[3]:16;Rx(this,n),e=t.call(this);for(var s=r/2-a,c=i/2-a,l=a/r,u=(r-a)/r,d=a/i,f=(i-a)/i,p=[s,c,0,-s,c,0,-s,-c,0,s,-c,0],m=[u,f,l,f,l,d,u,d],h=[3*(o+1)+3,3*(o+1)+4,o+4,o+5,2*(o+1)+4,2,1,2*(o+1)+3,3,4*(o+1)+3,4,0],g=[h[0],h[1],h[2],h[0],h[2],h[3],h[4],h[5],h[6],h[4],h[6],h[7],h[8],h[9],h[10],h[8],h[10],h[11]],_,v,y,b,x,S,C,w,T=0;T<4;T++){b=T<1||T>2?s:-s,x=T<2?c:-c,S=T<1||T>2?u:l,C=T<2?f:d;for(var E=0;E<=o;E++)_=Math.PI/2*(T+E/o),v=Math.cos(_),y=Math.sin(_),p.push(b+a*v,x+a*y,0),m.push(S+l*v,C+d*y),Ee.charCodeAt(0)),parseInt(`183`.replace(/\D+/g,``));var Zx=(0,y.createContext)(null),Qx=e=>(e.getAttributes()&2)==2,$x=(0,y.memo)((0,y.forwardRef)(({children:e,camera:t,scene:n,resolutionScale:r,enabled:i=!0,renderPriority:a=1,autoClear:o=!0,depthBuffer:s,enableNormalPass:c,stencilBuffer:l,multisampling:u=8,frameBufferType:d=ke},f)=>{let{gl:p,scene:m,camera:h,size:g}=Y_(),_=n||m,v=t||h,[b,x,S]=(0,y.useMemo)(()=>{let e=new cx(p,{depthBuffer:s,stencilBuffer:l,multisampling:u,frameBufferType:d});e.addPass(new bx(_,v));let t=null,n=null;return c&&(n=new Mx(_,v),n.enabled=!1,e.addPass(n),r!==void 0&&(t=new wx({normalBuffer:n.texture,resolutionScale:r}),t.enabled=!1,e.addPass(t))),[e,n,t]},[v,p,s,l,u,d,_,c,r]);(0,y.useEffect)(()=>b?.setSize(g.width,g.height),[b,g]),X_((e,t)=>{if(i){let e=p.autoClear;p.autoClear=o,l&&!o&&p.clearStencil(),b.render(t),p.autoClear=e}},i?a:0);let C=(0,y.useRef)(null);(0,y.useLayoutEffect)(()=>{let e=[],t=C.current.__r3f;if(t&&b){let n=t.children;for(let t=0;t{for(let t of e)b?.removePass(t);x&&(x.enabled=!1),S&&(S.enabled=!1)}},[b,e,v,x,S]),(0,y.useEffect)(()=>{let e=p.toneMapping;return p.toneMapping=0,()=>{p.toneMapping=e}},[p]);let w=(0,y.useMemo)(()=>({composer:b,normalPass:x,downSamplingPass:S,resolutionScale:r,camera:v,scene:_}),[b,x,S,r,v,_]);return(0,y.useImperativeHandle)(f,()=>b,[b]),(0,N.jsx)(Zx.Provider,{value:w,children:(0,N.jsx)(`group`,{ref:C,children:e})})})),eS={blend:5,intensity:2,force:1.1,distortion:.4,curl:1.9,radius:.3,swirl:4,pressure:.8,densityDissipation:.96,velocityDissipation:1,fluidColor:`#3300ff`,backgroundColor:`#070410`,showBackground:!0,rainbow:!1,dyeRes:512,simRes:128,blendFunction:gx.SET},tS=`uniform sampler2D tFluid; + +uniform vec3 uColor; +uniform vec3 uBackgroundColor; + +uniform float uDistort; +uniform float uIntensity; +uniform float uRainbow; +uniform float uBlend; +uniform float uShowBackground; + +void mainImage(const in vec4 inputColor, const in vec2 uv, out vec4 outputColor) { + + vec3 fluidColor = texture2D(tFluid, uv).rgb; + + vec2 distortedUv = uv - fluidColor.rg * uDistort * 0.001; + + vec4 texture = texture2D(inputBuffer, distortedUv); + + float intensity = length(fluidColor) * uIntensity * 0.0001; + + vec3 selectedColor = uColor * length(fluidColor); + + vec4 colorForFluidEffect = vec4(uRainbow == 1.0 ? fluidColor : selectedColor, 1.0); + + vec4 computedBgColor = uShowBackground != 0.0 ? vec4(uBackgroundColor, 1.0) : vec4(0.0, 0.0, 0.0, 0.0); + + outputColor = mix(texture, colorForFluidEffect, intensity); + + vec4 computedFluidColor = mix(texture, colorForFluidEffect, uBlend * 0.01); + + vec4 finalColor; + + if(texture.a < 0.1) { + finalColor = mix(computedBgColor, colorForFluidEffect, intensity); + } else { + finalColor = mix(computedFluidColor, computedBgColor, 1.0 - texture.a); + } + + outputColor = finalColor; +} +`,nS=e=>{let t=new U(e);return new H(t.r,t.g,t.b)},rS=(e,t)=>e**(t*60),iS=class extends yx{state;constructor(e){let t={tFluid:new df(e.tFluid),uDistort:new df(e.distortion),uRainbow:new df(e.rainbow),uIntensity:new df(e.intensity),uBlend:new df(e.blend),uShowBackground:new df(e.showBackground),uColor:new df(nS(e.fluidColor)),uBackgroundColor:new df(nS(e.backgroundColor))};super(`FluidEffect`,tS,{blendFunction:e.blendFunction,attributes:lx.CONVOLUTION,uniforms:new Map(Object.entries(t))}),this.state=e}updateUniform(e,t){let n=this.uniforms.get(e);n&&(n.value=t)}update(){this.updateUniform(`uIntensity`,this.state.intensity),this.updateUniform(`uDistort`,this.state.distortion),this.updateUniform(`uRainbow`,this.state.rainbow),this.updateUniform(`uBlend`,this.state.blend),this.updateUniform(`uShowBackground`,this.state.showBackground),this.updateUniform(`uColor`,nS(this.state.fluidColor)),this.updateUniform(`uBackgroundColor`,nS(this.state.backgroundColor))}},aS=(0,y.forwardRef)(function(e,t){let n=(0,y.useMemo)(()=>new iS(e),[]);return(0,y.useEffect)(()=>{n.state={...e},n.update()},[n,e]),(0,y.useEffect)(()=>()=>{n.dispose?.()},[n]),(0,N.jsx)(`primitive`,{ref:t,object:n,dispose:null})}),oS=(e,t,n)=>{let r=ib(e,t,n),i=ib(e,t,n),a=(0,y.useRef)({read:r,write:i,swap:()=>{let e=a.read;a.read=a.write,a.write=e},dispose:()=>{r.dispose(),i.dispose()},setGenerateMipmaps:e=>{r.texture.generateMipmaps=e,i.texture.generateMipmaps=e}}).current;return a},sS=()=>{let e=oS(eS.dyeRes,eS.dyeRes,{type:ke,format:Le,minFilter:L,depthBuffer:!1}),t=oS(eS.simRes,eS.simRes,{type:ke,format:He,minFilter:L,depthBuffer:!1}),n=oS(eS.simRes,eS.simRes,{type:ke,format:Be,minFilter:ge,depthBuffer:!1}),r=ib(eS.simRes,eS.simRes,{type:ke,format:Be,minFilter:ge,depthBuffer:!1}),i=ib(eS.simRes,eS.simRes,{type:ke,format:Be,minFilter:ge,depthBuffer:!1}),a=(0,y.useMemo)(()=>({density:e,velocity:t,pressure:n,divergence:r,curl:i}),[i,e,r,n,t]);return(0,y.useEffect)(()=>{for(let e of Object.values(a))`write`in e?e.setGenerateMipmaps(!1):e.texture.generateMipmaps=!1;return()=>{for(let e of Object.values(a))e.dispose()}},[a]),a},cS=`#ifdef USE_V_UV + varying vec2 vUv; +#endif + +#ifdef USE_OFFSETS + varying vec2 vL; + varying vec2 vR; + varying vec2 vT; + varying vec2 vB; + uniform vec2 texelSize; +#endif + +void main() { + #ifdef USE_V_UV + vUv = uv; + #endif + + #ifdef USE_OFFSETS + vL = uv - vec2(texelSize.x, 0.0); + vR = uv + vec2(texelSize.x, 0.0); + vT = uv + vec2(0.0, texelSize.y); + vB = uv - vec2(0.0, texelSize.y); + #endif + + gl_Position = vec4(position, 1.0); +}`,lS=`precision highp float; + +varying vec2 vUv; +uniform sampler2D uTexture; +uniform float uClearValue; + +void main() { gl_FragColor = uClearValue * texture2D(uTexture, vUv); } +`,uS=`precision highp float; + +varying vec2 vL; +varying vec2 vR; +varying vec2 vT; +varying vec2 vB; + +uniform sampler2D uVelocity; + +void main() { + float L = texture2D(uVelocity, vL).y; + + float R = texture2D(uVelocity, vR).y; + + float T = texture2D(uVelocity, vT).x; + + float B = texture2D(uVelocity, vB).x; + + float vorticity = R - L - T + B; + + gl_FragColor = vec4(vorticity, 0.0, 0.0, 1.0); +}`,dS=`precision highp float; + +varying highp vec2 vUv; +varying highp vec2 vL; +varying highp vec2 vR; +varying highp vec2 vT; +varying highp vec2 vB; + +uniform sampler2D uVelocity; + +void main() { + float L = texture2D(uVelocity, vL).x; + + float R = texture2D(uVelocity, vR).x; + + float T = texture2D(uVelocity, vT).y; + + float B = texture2D(uVelocity, vB).y; + + vec2 C = texture2D(uVelocity, vUv).xy; + + if(vL.x < 0.0) { + L = -C.x; + } + + if(vR.x > 1.0) { + R = -C.x; + } + + if(vT.y > 1.0) { + T = -C.y; + } + + if(vB.y < 0.0) { + B = -C.y; + } + + float div = 0.5 * (R - L + T - B); + + gl_FragColor = vec4(div, 0.0, 0.0, 1.0); +}`,fS=`precision highp float; + +varying highp vec2 vUv; +varying highp vec2 vL; +varying highp vec2 vR; +varying highp vec2 vT; +varying highp vec2 vB; + +uniform sampler2D uPressure; +uniform sampler2D uVelocity; + +void main() { + float L = texture2D(uPressure, vL).x; + + float R = texture2D(uPressure, vR).x; + + float T = texture2D(uPressure, vT).x; + + float B = texture2D(uPressure, vB).x; + + vec2 velocity = texture2D(uVelocity, vUv).xy; + + velocity.xy -= vec2(R - L, T - B); + + gl_FragColor = vec4(velocity, 0.0, 1.0); +}`,pS=`precision highp float; + +varying highp vec2 vUv; +varying highp vec2 vL; +varying highp vec2 vR; +varying highp vec2 vT; +varying highp vec2 vB; + +uniform sampler2D uPressure; +uniform sampler2D uDivergence; + +void main() { + float L = texture2D(uPressure, vL).x; + + float R = texture2D(uPressure, vR).x; + + float T = texture2D(uPressure, vT).x; + + float B = texture2D(uPressure, vB).x; + + float C = texture2D(uPressure, vUv).x; + + float divergence = texture2D(uDivergence, vUv).x; + + float pressure = (L + R + B + T - divergence) * 0.25; + + gl_FragColor = vec4(pressure, 0.0, 0.0, 1.0); +} +`,mS=`varying vec2 vUv; + +uniform sampler2D uTarget; +uniform float aspectRatio; +uniform vec3 uColor; +uniform vec2 uPointer; +uniform float uRadius; + +void main() { + vec2 p = vUv - uPointer.xy; + + p.x *= aspectRatio; + + vec3 splat = exp(-dot(p, p) / uRadius) * uColor; + + vec3 base = texture2D(uTarget, vUv).xyz; + + gl_FragColor = vec4(base + splat, 1.0); +} +`,hS=`precision highp float; + +varying vec2 vUv; +uniform sampler2D uVelocity; +uniform sampler2D uSource; +uniform vec2 texelSize; +uniform float dt; +uniform float uDissipation; + +void main() { + vec2 coord = vUv - dt * texture2D(uVelocity, vUv).xy * texelSize; + + gl_FragColor = uDissipation * texture2D(uSource, coord); + + gl_FragColor.a = 1.0; +}`,gS=`precision highp float; + +varying vec2 vUv; +varying vec2 vL; +varying vec2 vR; +varying vec2 vT; +varying vec2 vB; + +uniform sampler2D uVelocity; +uniform sampler2D uCurl; +uniform float uCurlValue; +uniform float dt; + +void main() { + float L = texture2D(uCurl, vL).x; + + float R = texture2D(uCurl, vR).x; + + float T = texture2D(uCurl, vT).x; + + float B = texture2D(uCurl, vB).x; + + float C = texture2D(uCurl, vUv).x; + + vec2 force = vec2(abs(T) - abs(B), abs(R) - abs(L)) * 0.5; + + force /= length(force) + 1.; + + force *= uCurlValue * C; + + force.y *= -1.; + + vec2 vel = texture2D(uVelocity, vUv).xy; + + gl_FragColor = vec4(vel + force * dt, 0.0, 1.0); +}`,_S=()=>{let e=Y_(e=>e.size),t=(0,y.useMemo)(()=>{let t=new q({name:`Fluid/Advection`,uniforms:{uVelocity:{value:new Er},uSource:{value:new Er},dt:{value:1/60},uDissipation:{value:1},texelSize:{value:new V}},fragmentShader:hS,vertexShader:cS,defines:{USE_V_UV:``},depthTest:!1,depthWrite:!1}),n=new q({name:`Fluid/Clear`,uniforms:{uTexture:{value:new Er},uClearValue:{value:eS.pressure},texelSize:{value:new V}},fragmentShader:lS,vertexShader:cS,defines:{USE_V_UV:``},depthTest:!1,depthWrite:!1}),r=new q({name:`Fluid/Curl`,uniforms:{uVelocity:{value:new Er},texelSize:{value:new V}},fragmentShader:uS,vertexShader:cS,defines:{USE_OFFSETS:``},depthTest:!1,depthWrite:!1}),i=new q({name:`Fluid/Divergence`,uniforms:{uVelocity:{value:new Er},texelSize:{value:new V}},fragmentShader:dS,vertexShader:cS,defines:{USE_V_UV:``,USE_OFFSETS:``},depthTest:!1,depthWrite:!1}),a=new q({name:`Fluid/GradientSubtract`,uniforms:{uPressure:{value:new Er},uVelocity:{value:new Er},texelSize:{value:new V}},fragmentShader:fS,vertexShader:cS,defines:{USE_V_UV:``,USE_OFFSETS:``},depthTest:!1,depthWrite:!1}),o=new q({name:`Fluid/Pressure`,uniforms:{uPressure:{value:new Er},uDivergence:{value:new Er},texelSize:{value:new V}},fragmentShader:pS,vertexShader:cS,defines:{USE_V_UV:``,USE_OFFSETS:``},depthTest:!1,depthWrite:!1});return{splat:new q({name:`Fluid/Splat`,uniforms:{uTarget:{value:new Er},aspectRatio:{value:e.width/e.height},uColor:{value:new H},uPointer:{value:new V},uRadius:{value:eS.radius/100},texelSize:{value:new V}},fragmentShader:mS,vertexShader:cS,defines:{USE_V_UV:``},depthTest:!1,depthWrite:!1}),curl:r,clear:n,divergence:i,pressure:o,gradientSubstract:a,advection:t,vorticity:new q({name:`Fluid/Vorticity`,uniforms:{uVelocity:{value:new Er},uCurl:{value:new Er},uCurlValue:{value:eS.curl},dt:{value:1/60},texelSize:{value:new V}},fragmentShader:gS,vertexShader:cS,defines:{USE_V_UV:``,USE_OFFSETS:``},depthTest:!1,depthWrite:!1})}},[e]);return(0,y.useEffect)(()=>{for(let n of Object.values(t)){let t=e.width/(e.height+400);n.uniforms.texelSize.value.set(1/(eS.simRes*t),1/eS.simRes)}return()=>{for(let e of Object.values(t))e.dispose()}},[t,e]),t},vS=({force:e})=>{let t=Y_(e=>e.size),n=(0,y.useRef)([]).current,r=(0,y.useRef)(new V),i=(0,y.useRef)(!1),a=(0,y.useCallback)(a=>{let o=a.x-r.current.x,s=a.y-r.current.y;if(!i.current){i.current=!0,r.current.set(a.x,a.y);return}r.current.set(a.x,a.y);let c={mouseX:a.x/t.width,mouseY:1-a.y/t.height,velocityX:o*e,velocityY:-s*e};n.push(c)},[e,t.height,t.width,n]);return(0,y.useEffect)(()=>(addEventListener(`pointermove`,a),()=>{removeEventListener(`pointermove`,a)}),[a]),n},yS=({blend:e=eS.blend,force:t=eS.force,radius:n=eS.radius,curl:r=eS.curl,swirl:i=eS.swirl,intensity:a=eS.intensity,distortion:o=eS.distortion,fluidColor:s=eS.fluidColor,backgroundColor:c=eS.backgroundColor,showBackground:l=eS.showBackground,rainbow:u=eS.rainbow,pressure:d=eS.pressure,densityDissipation:f=eS.densityDissipation,velocityDissipation:p=eS.velocityDissipation,blendFunction:m=eS.blendFunction})=>{let h=Y_(e=>e.size),g=Y_(e=>e.gl),[_]=(0,y.useState)(()=>new vi),v=(0,y.useMemo)(()=>new Ju,[]),b=(0,y.useRef)(null),x=(0,y.useRef)(null),S=(0,y.useRef)(new V),C=(0,y.useRef)(new H),w=sS(),T=_S(),E=vS({force:t}),D=(0,y.useCallback)(e=>{b.current&&(b.current.material=T[e],b.current.material.needsUpdate=!0)},[T]),O=(0,y.useCallback)(e=>{let t=w[e];`write`in t?(g.setRenderTarget(t.write),g.clear(),g.render(_,v),t.swap()):(g.setRenderTarget(t),g.clear(),g.render(_,v))},[v,_,w,g]),k=(0,y.useCallback)((e,t,n)=>{let r=T[e];r&&r.uniforms[t]&&(r.uniforms[t].value=n)},[T]);return X_((e,t)=>{if(!(!b.current||!x.current)){for(let e=E.length-1;e>=0;e--){let{mouseX:t,mouseY:r,velocityX:i,velocityY:a}=E[e];S.current.set(t,r),C.current.set(i,a,10),D(`splat`),k(`splat`,`uTarget`,w.velocity.read.texture),k(`splat`,`uPointer`,S.current),k(`splat`,`uColor`,C.current),k(`splat`,`uRadius`,n/100),O(`velocity`),k(`splat`,`uTarget`,w.density.read.texture),O(`density`),E.pop()}D(`curl`),k(`curl`,`uVelocity`,w.velocity.read.texture),O(`curl`),D(`vorticity`),k(`vorticity`,`uVelocity`,w.velocity.read.texture),k(`vorticity`,`uCurl`,w.curl.texture),k(`vorticity`,`uCurlValue`,r),O(`velocity`),D(`divergence`),k(`divergence`,`uVelocity`,w.velocity.read.texture),O(`divergence`),D(`clear`),k(`clear`,`uTexture`,w.pressure.read.texture),k(`clear`,`uClearValue`,rS(d,t)),O(`pressure`),D(`pressure`),k(`pressure`,`uDivergence`,w.divergence.texture);for(let e=0;e{let t=window.requestAnimationFrame(()=>{t=window.requestAnimationFrame(()=>{e()})});return()=>{window.cancelAnimationFrame(t)}},[e]),null}function SS({subdued:e=!1}){let t=e?`#060912`:eS.backgroundColor,[n,r]=(0,y.useState)(!1);return(0,N.jsxs)(`div`,{"aria-hidden":`true`,className:`fluid-backdrop`,children:[(0,N.jsx)(`div`,{className:`fluid-backdrop__scene ${n?`is-ready`:``}`,children:(0,N.jsxs)(by,{camera:{fov:42,position:[0,0,8]},dpr:[1,2],gl:{antialias:!1},children:[(0,N.jsx)(`color`,{attach:`background`,args:[t]}),(0,N.jsxs)(y.Suspense,{fallback:null,children:[(0,N.jsx)(xS,{onReady:()=>r(!0)}),(0,N.jsx)(bS,{}),(0,N.jsx)($x,{multisampling:0,children:(0,N.jsx)(yS,{...eS,backgroundColor:t,distortion:e?.32:.46,fluidColor:e?`#6fcff8`:`#96d8ff`,intensity:e?1.35:1.9,radius:.24,rainbow:!1})})]})]})}),(0,N.jsx)(`div`,{className:`fluid-backdrop__veil ${e?`is-subdued`:``}`})]})}function CS({className:e}){return(0,N.jsxs)(`svg`,{className:e,fill:`none`,viewBox:`0 8 256 256`,xmlns:`http://www.w3.org/2000/svg`,children:[(0,N.jsx)(`path`,{d:`M230.721 172.7C230.183 170.673 229.313 168.75 228.146 167.008C228.396 166.091 228.587 165.159 228.714 164.217C229.543 158.241 227.471 152.77 223.567 148.537C221.452 146.225 219.185 144.698 216.784 143.761C218.36 137.018 219.157 130.117 219.161 123.193C219.161 120.03 218.982 116.932 218.682 113.88C218.526 112.356 218.337 110.836 218.115 109.32C217.428 104.847 216.408 100.431 215.064 96.11C214.183 93.2707 213.164 90.476 212.01 87.736C210.281 83.6782 208.262 79.75 205.969 75.982C204.465 73.475 202.827 71.0508 201.062 68.72C200.197 67.543 199.296 66.3938 198.358 65.274C195.58 61.898 192.561 58.7277 189.325 55.788C188.25 54.7997 187.145 53.8453 186.01 52.926C184.893 51.9943 183.751 51.0927 182.586 50.222C180.241 48.4766 177.818 46.8392 175.324 45.315C161.543 36.945 145.382 32.145 128.109 32.145C77.817 32.145 37.057 72.907 37.057 123.196C37.055 130.208 37.867 137.196 39.477 144.02C37.317 144.958 35.247 146.42 33.327 148.535C29.424 152.766 27.351 158.217 28.18 164.193C28.306 165.142 28.495 166.082 28.747 167.006C27.5811 168.749 26.7117 170.673 26.174 172.7C24.974 177.261 25.369 181.374 26.894 184.978C25.236 189.688 25.65 194.704 27.809 199.065C29.379 202.25 31.626 204.714 34.396 206.916C37.689 209.534 41.811 211.758 46.783 213.892C52.715 216.422 59.956 218.799 63.249 219.671C71.755 221.873 79.911 223.269 88.177 223.337C99.954 223.446 110.096 220.677 117.357 213.59C120.924 214.027 124.515 214.246 128.109 214.244C131.906 214.236 135.699 213.997 139.467 213.529C146.711 220.661 156.892 223.455 168.712 223.343C176.977 223.277 185.133 221.881 193.617 219.676C196.932 218.804 204.17 216.427 210.105 213.897C215.077 211.76 219.199 209.536 222.514 206.922C225.263 204.719 227.508 202.256 229.079 199.071C231.26 194.709 231.652 189.693 230.017 184.983C231.527 181.379 231.92 177.257 230.721 172.7Z`,fill:`white`}),(0,N.jsx)(`path`,{d:`M221.784 183.816C222.786 182.312 223.458 180.613 223.756 178.831C224.053 177.048 223.97 175.223 223.512 173.475C222.848 170.952 221.476 168.854 219.615 167.347C220.512 165.873 221.1 164.233 221.344 162.525C221.881 158.811 220.648 155.103 217.874 152.079C215.716 149.726 212.662 148.431 209.282 148.431C208.889 148.431 208.489 148.452 208.081 148.492C210.643 140.304 211.942 131.774 211.933 123.195C211.933 76.5231 174.097 38.6851 127.424 38.6851C80.75 38.6851 42.9099 76.5191 42.9099 123.195C42.9015 131.752 44.1936 140.261 46.742 148.43H46.6519C43.2719 148.43 40.219 149.724 38.06 152.077C35.287 155.098 34.0529 158.81 34.5899 162.523C34.8346 164.231 35.4231 165.872 36.3199 167.346C34.4579 168.852 33.086 170.95 32.422 173.473C31.9642 175.222 31.8817 177.047 32.1799 178.83C32.4781 180.612 33.1501 182.312 34.1519 183.816C33.9739 184.094 33.8099 184.381 33.6549 184.676C31.9849 187.847 31.877 191.43 33.352 194.767C35.588 199.824 41.1419 203.808 51.9289 208.085C58.6359 210.745 64.779 212.446 64.833 212.461C73.705 214.762 81.729 215.931 88.675 215.931C100.081 215.931 108.591 212.811 114.026 206.647C123.222 208.106 132.594 208.052 141.773 206.489C147.201 212.757 155.76 215.931 167.262 215.931C174.208 215.931 182.232 214.762 191.103 212.461C191.158 212.446 197.298 210.745 204.008 208.085C214.795 203.808 220.35 199.824 222.585 194.767C224.059 191.43 223.952 187.847 222.281 184.676C222.129 184.379 221.961 184.091 221.784 183.816Z`,fill:`#FFD21E`}),(0,N.jsx)(`path`,{clipRule:`evenodd`,d:`M152.047 102.567C153.229 102.985 154.108 104.257 154.944 105.468C156.074 107.104 157.126 108.627 158.74 107.769C160.644 106.756 162.205 105.202 163.225 103.302C164.246 101.402 164.681 99.2427 164.475 97.096C164.321 95.4908 163.813 93.9398 162.987 92.5548C162.161 91.1697 161.038 89.985 159.7 89.0862C158.361 88.1874 156.839 87.5968 155.245 87.3569C153.65 87.117 152.022 87.2339 150.478 87.699C148.934 88.1639 147.513 88.9653 146.316 90.0455C145.119 91.1257 144.176 92.4578 143.556 93.946C142.936 95.4342 142.653 97.0415 142.728 98.652C142.804 100.263 143.235 101.836 143.992 103.26C144.74 104.667 146.4 104.003 148.152 103.302C149.525 102.753 150.956 102.181 152.047 102.567ZM100.672 102.567C99.49 102.985 98.611 104.258 97.775 105.468C96.645 107.105 95.592 108.627 93.979 107.769C91.5845 106.501 89.7482 104.386 88.8278 101.838C87.9075 99.2895 87.9692 96.4896 89.0008 93.9841C90.0324 91.4786 91.9601 89.4471 94.408 88.2855C96.856 87.1239 99.6488 86.9156 102.242 87.701C104.307 88.3228 106.141 89.5427 107.513 91.2065C108.885 92.8704 109.732 94.9035 109.949 97.049C110.165 99.1945 109.74 101.356 108.728 103.26C107.979 104.667 106.319 104.003 104.567 103.303C103.193 102.753 101.764 102.181 100.672 102.567ZM144.099 149.318C152.242 142.903 155.233 132.429 155.233 125.977C155.233 120.877 151.802 122.482 146.309 125.202L145.999 125.355C140.957 127.852 134.245 131.177 126.877 131.177C119.508 131.177 112.796 127.852 107.755 125.354C102.084 122.545 98.527 120.783 98.527 125.978C98.527 132.634 101.709 143.563 110.443 149.912C111.596 147.573 113.219 145.497 115.211 143.813C117.202 142.129 119.52 140.874 122.018 140.126C122.89 139.866 123.788 141.367 124.707 142.904C125.594 144.386 126.501 145.902 127.423 145.902C128.406 145.902 129.371 144.408 130.314 142.95C131.299 141.425 132.26 139.94 133.189 140.237C137.864 141.738 141.775 144.993 144.099 149.318Z`,fill:`#32343D`,fillRule:`evenodd`}),(0,N.jsx)(`path`,{d:`M144.097 149.317C139.856 152.659 134.219 154.9 126.878 154.9C119.981 154.9 114.587 152.922 110.443 149.911C111.596 147.572 113.219 145.495 115.211 143.812C117.202 142.128 119.52 140.873 122.018 140.125C123.73 139.614 125.545 145.901 127.423 145.901C129.433 145.901 131.37 139.655 133.189 140.236C137.863 141.738 141.773 144.993 144.097 149.317Z`,fill:`#FF323D`}),(0,N.jsx)(`path`,{clipRule:`evenodd`,d:`M81.2 111.64C80.2312 112.288 79.1173 112.687 77.9572 112.801C76.7971 112.916 75.6267 112.742 74.55 112.295C73.6893 111.94 72.9072 111.418 72.2488 110.759C71.5903 110.101 71.0684 109.319 70.713 108.458C70.267 107.381 70.0935 106.211 70.2082 105.051C70.3228 103.891 70.7219 102.777 71.37 101.808C72.1488 100.642 73.2558 99.7333 74.5512 99.1967C75.8466 98.6601 77.272 98.5197 78.6471 98.7935C80.0223 99.0672 81.2853 99.7427 82.2764 100.734C83.2675 101.726 83.9422 102.99 84.215 104.365C84.4883 105.74 84.3477 107.165 83.8113 108.46C83.2748 109.755 82.3654 110.861 81.2 111.64ZM182.613 111.64C181.644 112.288 180.53 112.687 179.37 112.801C178.209 112.916 177.039 112.742 175.962 112.295C175.101 111.939 174.319 111.418 173.661 110.759C173.003 110.101 172.481 109.319 172.125 108.458C171.68 107.381 171.507 106.211 171.621 105.051C171.736 103.891 172.135 102.777 172.782 101.808C173.364 100.936 174.133 100.205 175.032 99.6658C175.931 99.1269 176.938 98.7942 177.981 98.6917C179.025 98.5891 180.078 98.7193 181.064 99.0728C182.051 99.4264 182.947 99.9944 183.688 100.736C184.68 101.727 185.355 102.99 185.628 104.365C185.902 105.74 185.761 107.165 185.224 108.46C184.687 109.755 183.779 110.861 182.613 111.64Z`,fill:`#FFAD03`,fillRule:`evenodd`})]})}var wS=s({InferenceSession:()=>TC,TRACE:()=>gC,TRACE_EVENT_BEGIN:()=>bC,TRACE_EVENT_END:()=>xC,TRACE_FUNC_BEGIN:()=>vC,TRACE_FUNC_END:()=>yC,Tensor:()=>mC,default:()=>nE,env:()=>KS,registerBackend:()=>IS}),TS=Object.defineProperty,ES=Object.getOwnPropertyDescriptor,DS=Object.getOwnPropertyNames,OS=Object.prototype.hasOwnProperty,kS=(e=>typeof u<`u`?u:typeof Proxy<`u`?new Proxy(e,{get:(e,t)=>(typeof u<`u`?u:e)[t]}):e)(function(e){if(typeof u<`u`)return u.apply(this,arguments);throw Error(`Dynamic require of "`+e+`" is not supported`)}),AS=(e,t)=>()=>(e&&(t=e(e=0)),t),jS=(e,t)=>{for(var n in t)TS(e,n,{get:t[n],enumerable:!0})},MS=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(let i of DS(t))!OS.call(e,i)&&i!==n&&TS(e,i,{get:()=>t[i],enumerable:!(r=ES(t,i))||r.enumerable});return e},NS=e=>MS(TS({},`__esModule`,{value:!0}),e),PS,FS,IS,LS,RS,zS=AS(()=>{PS=new Map,FS=[],IS=(e,t,n)=>{if(t&&typeof t.init==`function`&&typeof t.createInferenceSessionHandler==`function`){let r=PS.get(e);if(r===void 0)PS.set(e,{backend:t,priority:n});else{if(r.priority>n)return;if(r.priority===n&&r.backend!==t)throw Error(`cannot register backend "${e}" using priority ${n}`)}if(n>=0){let t=FS.indexOf(e);t!==-1&&FS.splice(t,1);for(let t=0;t{let t=PS.get(e);if(!t)return`backend not found.`;if(t.initialized)return t.backend;if(t.aborted)return t.error;{let n=!!t.initPromise;try{return n||(t.initPromise=t.backend.init(e)),await t.initPromise,t.initialized=!0,t.backend}catch(e){return n||(t.error=`${e}`,t.aborted=!0),t.error}finally{delete t.initPromise}}},RS=async e=>{let t=e.executionProviders||[],n=t.map(e=>typeof e==`string`?e:e.name),r=n.length===0?FS:n,i,a=[],o=new Set;for(let e of r){let t=await LS(e);typeof t==`string`?a.push({name:e,err:t}):(i||=t,i===t&&o.add(e))}if(!i)throw Error(`no available backend found. ERR: ${a.map(e=>`[${e.name}] ${e.err}`).join(`, `)}`);for(let{name:e,err:t}of a)n.includes(e)&&console.warn(`removing requested execution provider "${e}" from session options because it is not available: ${t}`);let s=t.filter(e=>o.has(typeof e==`string`?e:e.name));return[i,new Proxy(e,{get:(e,t)=>t===`executionProviders`?s:Reflect.get(e,t)})]}}),BS=AS(()=>{zS()}),VS,HS=AS(()=>{VS=`1.24.0-dev.20251116-b39e144322`}),US,WS,GS=AS(()=>{HS(),US=`warning`,WS={wasm:{},webgl:{},webgpu:{},versions:{common:VS},set logLevel(e){if(e!==void 0){if(typeof e!=`string`||[`verbose`,`info`,`warning`,`error`,`fatal`].indexOf(e)===-1)throw Error(`Unsupported logging level: ${e}`);US=e}},get logLevel(){return US}},Object.defineProperty(WS,`logLevel`,{enumerable:!0})}),KS,qS=AS(()=>{GS(),KS=WS}),JS,YS,XS=AS(()=>{JS=(e,t)=>{let n=typeof document<`u`?document.createElement(`canvas`):new OffscreenCanvas(1,1);n.width=e.dims[3],n.height=e.dims[2];let r=n.getContext(`2d`);if(r!=null){let i,a;t?.tensorLayout!==void 0&&t.tensorLayout===`NHWC`?(i=e.dims[2],a=e.dims[3]):(i=e.dims[3],a=e.dims[2]);let o=t?.format===void 0?`RGB`:t.format,s=t?.norm,c,l;s===void 0||s.mean===void 0?c=[255,255,255,255]:typeof s.mean==`number`?c=[s.mean,s.mean,s.mean,s.mean]:(c=[s.mean[0],s.mean[1],s.mean[2],0],s.mean[3]!==void 0&&(c[3]=s.mean[3])),s===void 0||s.bias===void 0?l=[0,0,0,0]:typeof s.bias==`number`?l=[s.bias,s.bias,s.bias,s.bias]:(l=[s.bias[0],s.bias[1],s.bias[2],0],s.bias[3]!==void 0&&(l[3]=s.bias[3]));let u=a*i,d=0,f=u,p=u*2,m=-1;o===`RGBA`?(d=0,f=u,p=u*2,m=u*3):o===`RGB`?(d=0,f=u,p=u*2):o===`RBG`&&(d=0,p=u,f=u*2);for(let t=0;t{let n=typeof document<`u`?document.createElement(`canvas`).getContext(`2d`):new OffscreenCanvas(1,1).getContext(`2d`),r;if(n!=null){let i,a,o;t?.tensorLayout!==void 0&&t.tensorLayout===`NHWC`?(i=e.dims[2],a=e.dims[1],o=e.dims[3]):(i=e.dims[3],a=e.dims[2],o=e.dims[1]);let s=t!==void 0&&t.format!==void 0?t.format:`RGB`,c=t?.norm,l,u;c===void 0||c.mean===void 0?l=[255,255,255,255]:typeof c.mean==`number`?l=[c.mean,c.mean,c.mean,c.mean]:(l=[c.mean[0],c.mean[1],c.mean[2],255],c.mean[3]!==void 0&&(l[3]=c.mean[3])),c===void 0||c.bias===void 0?u=[0,0,0,0]:typeof c.bias==`number`?u=[c.bias,c.bias,c.bias,c.bias]:(u=[c.bias[0],c.bias[1],c.bias[2],0],c.bias[3]!==void 0&&(u[3]=c.bias[3]));let d=a*i;if(t!==void 0&&(t.format!==void 0&&o===4&&t.format!==`RGBA`||o===3&&t.format!==`RGB`&&t.format!==`BGR`))throw Error(`Tensor format doesn't match input tensor dims`);let f=0,p=1,m=2,h=3,g=0,_=d,v=d*2,y=-1;s===`RGBA`?(g=0,_=d,v=d*2,y=d*3):s===`RGB`?(g=0,_=d,v=d*2):s===`RBG`&&(g=0,v=d,_=d*2),r=n.createImageData(i,a);for(let t=0;t{pC(),ZS=(e,t)=>{if(e===void 0)throw Error(`Image buffer must be defined`);if(t.height===void 0||t.width===void 0)throw Error(`Image height and width must be defined`);if(t.tensorLayout===`NHWC`)throw Error(`NHWC Tensor layout is not supported yet`);let{height:n,width:r}=t,i=t.norm??{mean:255,bias:0},a,o;a=typeof i.mean==`number`?[i.mean,i.mean,i.mean,i.mean]:[i.mean[0],i.mean[1],i.mean[2],i.mean[3]??255],o=typeof i.bias==`number`?[i.bias,i.bias,i.bias,i.bias]:[i.bias[0],i.bias[1],i.bias[2],i.bias[3]??0];let s=t.format===void 0?`RGBA`:t.format,c=t.tensorFormat!==void 0&&t.tensorFormat!==void 0?t.tensorFormat:`RGB`,l=n*r,u=c===`RGBA`?new Float32Array(l*4):new Float32Array(l*3),d=4,f=0,p=1,m=2,h=3,g=0,_=l,v=l*2,y=-1;s===`RGB`&&(d=3,f=0,p=1,m=2,h=-1),c===`RGBA`?y=l*3:c===`RBG`?(g=0,v=l,_=l*2):c===`BGR`&&(v=0,_=l,g=l*2);for(let t=0;t{let n=typeof HTMLImageElement<`u`&&e instanceof HTMLImageElement,r=typeof ImageData<`u`&&e instanceof ImageData,i=typeof ImageBitmap<`u`&&e instanceof ImageBitmap,a=typeof e==`string`,o,s=t??{},c=()=>{if(typeof document<`u`)return document.createElement(`canvas`);if(typeof OffscreenCanvas<`u`)return new OffscreenCanvas(1,1);throw Error(`Canvas is not supported`)},l=e=>typeof HTMLCanvasElement<`u`&&e instanceof HTMLCanvasElement||e instanceof OffscreenCanvas?e.getContext(`2d`):null;if(n){let n=c();n.width=e.width,n.height=e.height;let r=l(n);if(r!=null){let n=e.height,i=e.width;if(t!==void 0&&t.resizedHeight!==void 0&&t.resizedWidth!==void 0&&(n=t.resizedHeight,i=t.resizedWidth),t!==void 0){if(s=t,t.tensorFormat!==void 0)throw Error(`Image input config format must be RGBA for HTMLImageElement`);s.tensorFormat=`RGBA`,s.height=n,s.width=i}else s.tensorFormat=`RGBA`,s.height=n,s.width=i;r.drawImage(e,0,0),o=r.getImageData(0,0,i,n).data}else throw Error(`Can not access image data`)}else if(r){let n,r;if(t!==void 0&&t.resizedWidth!==void 0&&t.resizedHeight!==void 0?(n=t.resizedHeight,r=t.resizedWidth):(n=e.height,r=e.width),t!==void 0&&(s=t),s.format=`RGBA`,s.height=n,s.width=r,t!==void 0){let t=c();t.width=r,t.height=n;let i=l(t);if(i!=null)i.putImageData(e,0,0),o=i.getImageData(0,0,r,n).data;else throw Error(`Can not access image data`)}else o=e.data}else if(i){if(t===void 0)throw Error(`Please provide image config with format for Imagebitmap`);let n=c();n.width=e.width,n.height=e.height;let r=l(n);if(r!=null){let t=e.height,n=e.width;return r.drawImage(e,0,0,n,t),o=r.getImageData(0,0,n,t).data,s.height=t,s.width=n,ZS(o,s)}else throw Error(`Can not access image data`)}else{if(a)return new Promise((t,n)=>{let r=c(),i=l(r);if(!e||!i)return n();let a=new Image;a.crossOrigin=`Anonymous`,a.src=e,a.onload=()=>{r.width=a.width,r.height=a.height,i.drawImage(a,0,0,r.width,r.height);let e=i.getImageData(0,0,r.width,r.height);s.height=r.height,s.width=r.width,t(ZS(e.data,s))}});throw Error(`Input data provided is not supported - aborted tensor creation`)}if(o!==void 0)return ZS(o,s);throw Error(`Input data provided is not supported - aborted tensor creation`)},$S=(e,t)=>{let{width:n,height:r,download:i,dispose:a}=t;return new fC({location:`texture`,type:`float32`,texture:e,dims:[1,r,n,4],download:i,dispose:a})},eC=(e,t)=>{let{dataType:n,dims:r,download:i,dispose:a}=t;return new fC({location:`gpu-buffer`,type:n??`float32`,gpuBuffer:e,dims:r,download:i,dispose:a})},tC=(e,t)=>{let{dataType:n,dims:r,download:i,dispose:a}=t;return new fC({location:`ml-tensor`,type:n??`float32`,mlTensor:e,dims:r,download:i,dispose:a})},nC=(e,t,n)=>new fC({location:`cpu-pinned`,type:e,data:t,dims:n??[t.length]})}),iC,aC,oC,sC,cC=AS(()=>{iC=new Map([[`float32`,Float32Array],[`uint8`,Uint8Array],[`int8`,Int8Array],[`uint16`,Uint16Array],[`int16`,Int16Array],[`int32`,Int32Array],[`bool`,Uint8Array],[`float64`,Float64Array],[`uint32`,Uint32Array],[`int4`,Uint8Array],[`uint4`,Uint8Array]]),aC=new Map([[Float32Array,`float32`],[Uint8Array,`uint8`],[Int8Array,`int8`],[Uint16Array,`uint16`],[Int16Array,`int16`],[Int32Array,`int32`],[Float64Array,`float64`],[Uint32Array,`uint32`]]),oC=!1,sC=()=>{if(!oC){oC=!0;let e=typeof BigInt64Array<`u`&&BigInt64Array.from,t=typeof BigUint64Array<`u`&&BigUint64Array.from,n=globalThis.Float16Array,r=typeof n<`u`&&n.from;e&&(iC.set(`int64`,BigInt64Array),aC.set(BigInt64Array,`int64`)),t&&(iC.set(`uint64`,BigUint64Array),aC.set(BigUint64Array,`uint64`)),r?(iC.set(`float16`,n),aC.set(n,`float16`)):iC.set(`float16`,Uint16Array)}}}),lC,uC,dC=AS(()=>{pC(),lC=e=>{let t=1;for(let n=0;n{switch(e.location){case`cpu`:return new fC(e.type,e.data,t);case`cpu-pinned`:return new fC({location:`cpu-pinned`,data:e.data,type:e.type,dims:t});case`texture`:return new fC({location:`texture`,texture:e.texture,type:e.type,dims:t});case`gpu-buffer`:return new fC({location:`gpu-buffer`,gpuBuffer:e.gpuBuffer,type:e.type,dims:t});case`ml-tensor`:return new fC({location:`ml-tensor`,mlTensor:e.mlTensor,type:e.type,dims:t});default:throw Error(`tensorReshape: tensor location ${e.location} is not supported`)}}}),fC,pC=AS(()=>{XS(),rC(),cC(),dC(),fC=class{constructor(e,t,n){sC();let r,i;if(typeof e==`object`&&`location`in e)switch(this.dataLocation=e.location,r=e.type,i=e.dims,e.location){case`cpu-pinned`:{let t=iC.get(r);if(!t)throw TypeError(`unsupported type "${r}" to create tensor from pinned buffer`);if(!(e.data instanceof t))throw TypeError(`buffer should be of type ${t.name}`);this.cpuData=e.data;break}case`texture`:if(r!==`float32`)throw TypeError(`unsupported type "${r}" to create tensor from texture`);this.gpuTextureData=e.texture,this.downloader=e.download,this.disposer=e.dispose;break;case`gpu-buffer`:if(r!==`float32`&&r!==`float16`&&r!==`int32`&&r!==`int64`&&r!==`uint32`&&r!==`uint8`&&r!==`bool`&&r!==`uint4`&&r!==`int4`)throw TypeError(`unsupported type "${r}" to create tensor from gpu buffer`);this.gpuBufferData=e.gpuBuffer,this.downloader=e.download,this.disposer=e.dispose;break;case`ml-tensor`:if(r!==`float32`&&r!==`float16`&&r!==`int32`&&r!==`int64`&&r!==`uint32`&&r!==`uint64`&&r!==`int8`&&r!==`uint8`&&r!==`bool`&&r!==`uint4`&&r!==`int4`)throw TypeError(`unsupported type "${r}" to create tensor from MLTensor`);this.mlTensorData=e.mlTensor,this.downloader=e.download,this.disposer=e.dispose;break;default:throw Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let a,o;if(typeof e==`string`)if(r=e,o=n,e===`string`){if(!Array.isArray(t))throw TypeError(`A string tensor's data must be a string array.`);a=t}else{let n=iC.get(e);if(n===void 0)throw TypeError(`Unsupported tensor type: ${e}.`);if(Array.isArray(t)){if(e===`float16`&&n===Uint16Array||e===`uint4`||e===`int4`)throw TypeError(`Creating a ${e} tensor from number array is not supported. Please use ${n.name} as data.`);a=e===`uint64`||e===`int64`?n.from(t,BigInt):n.from(t)}else if(t instanceof n)a=t;else if(t instanceof Uint8ClampedArray)if(e===`uint8`)a=Uint8Array.from(t);else throw TypeError(`A Uint8ClampedArray tensor's data must be type of uint8`);else if(e===`float16`&&t instanceof Uint16Array&&n!==Uint16Array)a=new globalThis.Float16Array(t.buffer,t.byteOffset,t.length);else throw TypeError(`A ${r} tensor's data must be type of ${n}`)}else if(o=t,Array.isArray(e)){if(e.length===0)throw TypeError(`Tensor type cannot be inferred from an empty array.`);let t=typeof e[0];if(t===`string`)r=`string`,a=e;else if(t===`boolean`)r=`bool`,a=Uint8Array.from(e);else throw TypeError(`Invalid element type of data array: ${t}.`)}else if(e instanceof Uint8ClampedArray)r=`uint8`,a=Uint8Array.from(e);else{let t=aC.get(e.constructor);if(t===void 0)throw TypeError(`Unsupported type for tensor data: ${e.constructor}.`);r=t,a=e}if(o===void 0)o=[a.length];else if(!Array.isArray(o))throw TypeError(`A tensor's dims must be a number array`);i=o,this.cpuData=a,this.dataLocation=`cpu`}let a=lC(i);if(this.cpuData&&a!==this.cpuData.length&&!((r===`uint4`||r===`int4`)&&Math.ceil(a/2)===this.cpuData.length))throw Error(`Tensor's size(${a}) does not match data length(${this.cpuData.length}).`);this.type=r,this.dims=i,this.size=a}static async fromImage(e,t){return QS(e,t)}static fromTexture(e,t){return $S(e,t)}static fromGpuBuffer(e,t){return eC(e,t)}static fromMLTensor(e,t){return tC(e,t)}static fromPinnedBuffer(e,t,n){return nC(e,t,n)}toDataURL(e){return JS(this,e)}toImageData(e){return YS(this,e)}get data(){if(this.ensureValid(),!this.cpuData)throw Error("The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.");return this.cpuData}get location(){return this.dataLocation}get texture(){if(this.ensureValid(),!this.gpuTextureData)throw Error(`The data is not stored as a WebGL texture.`);return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw Error(`The data is not stored as a WebGPU buffer.`);return this.gpuBufferData}get mlTensor(){if(this.ensureValid(),!this.mlTensorData)throw Error(`The data is not stored as a WebNN MLTensor.`);return this.mlTensorData}async getData(e){switch(this.ensureValid(),this.dataLocation){case`cpu`:case`cpu-pinned`:return this.data;case`texture`:case`gpu-buffer`:case`ml-tensor`:if(!this.downloader)throw Error(`The current tensor is not created with a specified data downloader.`);if(this.isDownloading)throw Error(`The current tensor is being downloaded.`);try{this.isDownloading=!0;let t=await this.downloader();return this.downloader=void 0,this.dataLocation=`cpu`,this.cpuData=t,e&&this.disposer&&(this.disposer(),this.disposer=void 0),t}finally{this.isDownloading=!1}default:throw Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw Error(`The current tensor is being downloaded.`);this.disposer&&=(this.disposer(),void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.mlTensorData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation=`none`}ensureValid(){if(this.dataLocation===`none`)throw Error(`The tensor is disposed.`)}reshape(e){if(this.ensureValid(),this.downloader||this.disposer)throw Error(`Cannot reshape a tensor that owns GPU resource.`);return uC(this,e)}}}),mC,hC=AS(()=>{pC(),mC=fC}),gC,_C,vC,yC,bC,xC,SC=AS(()=>{GS(),gC=(e,t)=>{(typeof WS.trace>`u`?!WS.wasm.trace:!WS.trace)||console.timeStamp(`${e}::ORT::${t}`)},_C=(e,t)=>{let n=Error().stack?.split(/\r\n|\r|\n/g)||[],r=!1;for(let i=0;i{(typeof WS.trace>`u`?!WS.wasm.trace:!WS.trace)||_C(`BEGIN`,e)},yC=e=>{(typeof WS.trace>`u`?!WS.wasm.trace:!WS.trace)||_C(`END`,e)},bC=e=>{(typeof WS.trace>`u`?!WS.wasm.trace:!WS.trace)||console.time(`ORT::${e}`)},xC=e=>{(typeof WS.trace>`u`?!WS.wasm.trace:!WS.trace)||console.timeEnd(`ORT::${e}`)}}),CC,wC=AS(()=>{zS(),hC(),SC(),CC=class e{constructor(e){this.handler=e}async run(e,t,n){vC(),bC(`InferenceSession.run`);let r={},i={};if(typeof e!=`object`||!e||e instanceof mC||Array.isArray(e))throw TypeError(`'feeds' must be an object that use input names as keys and OnnxValue as corresponding values.`);let a=!0;if(typeof t==`object`){if(t===null)throw TypeError(`Unexpected argument[1]: cannot be null.`);if(t instanceof mC)throw TypeError(`'fetches' cannot be a Tensor`);if(Array.isArray(t)){if(t.length===0)throw TypeError(`'fetches' cannot be an empty array.`);a=!1;for(let e of t){if(typeof e!=`string`)throw TypeError(`'fetches' must be a string array or an object.`);if(this.outputNames.indexOf(e)===-1)throw RangeError(`'fetches' contains invalid output name: ${e}.`);r[e]=null}if(typeof n==`object`&&n)i=n;else if(typeof n<`u`)throw TypeError(`'options' must be an object.`)}else{let e=!1,o=Object.getOwnPropertyNames(t);for(let n of this.outputNames)if(o.indexOf(n)!==-1){let i=t[n];(i===null||i instanceof mC)&&(e=!0,a=!1,r[n]=i)}if(e){if(typeof n==`object`&&n)i=n;else if(typeof n<`u`)throw TypeError(`'options' must be an object.`)}else i=t}}else if(typeof t<`u`)throw TypeError(`Unexpected argument[1]: must be 'fetches' or 'options'.`);for(let t of this.inputNames)if(typeof e[t]>`u`)throw Error(`input '${t}' is missing in 'feeds'.`);if(a)for(let e of this.outputNames)r[e]=null;let o=await this.handler.run(e,r,i),s={};for(let e in o)if(Object.hasOwnProperty.call(o,e)){let t=o[e];t instanceof mC?s[e]=t:s[e]=new mC(t.type,t.data,t.dims)}return xC(`InferenceSession.run`),yC(),s}async release(){return this.handler.dispose()}static async create(t,n,r,i){vC(),bC(`InferenceSession.create`);let a,o={};if(typeof t==`string`){if(a=t,typeof n==`object`&&n)o=n;else if(typeof n<`u`)throw TypeError(`'options' must be an object.`)}else if(t instanceof Uint8Array){if(a=t,typeof n==`object`&&n)o=n;else if(typeof n<`u`)throw TypeError(`'options' must be an object.`)}else if(t instanceof ArrayBuffer||typeof SharedArrayBuffer<`u`&&t instanceof SharedArrayBuffer){let e=t,s=0,c=t.byteLength;if(typeof n==`object`&&n)o=n;else if(typeof n==`number`){if(s=n,!Number.isSafeInteger(s))throw RangeError(`'byteOffset' must be an integer.`);if(s<0||s>=e.byteLength)throw RangeError(`'byteOffset' is out of range [0, ${e.byteLength}).`);if(c=t.byteLength-s,typeof r==`number`){if(c=r,!Number.isSafeInteger(c))throw RangeError(`'byteLength' must be an integer.`);if(c<=0||s+c>e.byteLength)throw RangeError(`'byteLength' is out of range (0, ${e.byteLength-s}].`);if(typeof i==`object`&&i)o=i;else if(typeof i<`u`)throw TypeError(`'options' must be an object.`)}else if(typeof r<`u`)throw TypeError(`'byteLength' must be a number.`)}else if(typeof n<`u`)throw TypeError(`'options' must be an object.`);a=new Uint8Array(e,s,c)}else throw TypeError(`Unexpected argument[0]: must be 'path' or 'buffer'.`);let[s,c]=await RS(o),l=await s.createInferenceSessionHandler(a,c);return xC(`InferenceSession.create`),yC(),new e(l)}startProfiling(){this.handler.startProfiling()}endProfiling(){this.handler.endProfiling()}get inputNames(){return this.handler.inputNames}get outputNames(){return this.handler.outputNames}get inputMetadata(){return this.handler.inputMetadata}get outputMetadata(){return this.handler.outputMetadata}}}),TC,EC=AS(()=>{wC(),TC=CC}),DC=AS(()=>{}),OC=AS(()=>{}),kC=AS(()=>{}),AC=AS(()=>{}),jC={};jS(jC,{InferenceSession:()=>TC,TRACE:()=>gC,TRACE_EVENT_BEGIN:()=>bC,TRACE_EVENT_END:()=>xC,TRACE_FUNC_BEGIN:()=>vC,TRACE_FUNC_END:()=>yC,Tensor:()=>mC,env:()=>KS,registerBackend:()=>IS});var MC=AS(()=>{BS(),qS(),EC(),hC(),DC(),OC(),SC(),kC(),AC()}),NC=AS(()=>{}),PC={};jS(PC,{default:()=>LC});var FC,IC,LC,RC=AS(()=>{ET(),mw(),iw(),FC=`ort-wasm-proxy-worker`,IC=globalThis.self?.name===FC,IC&&(self.onmessage=e=>{let{type:t,in:n}=e.data;try{switch(t){case`init-wasm`:fw(n.wasm).then(()=>{mT(n).then(()=>{postMessage({type:t})},e=>{postMessage({type:t,err:e})})},e=>{postMessage({type:t,err:e})});break;case`init-ep`:{let{epName:e,env:r}=n;hT(r,e).then(()=>{postMessage({type:t})},e=>{postMessage({type:t,err:e})});break}case`copy-from`:{let{buffer:e}=n,r=yT(e);postMessage({type:t,out:r});break}case`create`:{let{model:e,options:r}=n;bT(e,r).then(e=>{postMessage({type:t,out:e})},e=>{postMessage({type:t,err:e})});break}case`release`:xT(n),postMessage({type:t});break;case`run`:{let{sessionId:e,inputIndices:r,inputs:i,outputIndices:a,options:o}=n;CT(e,r,i,a,Array(a.length).fill(null),o).then(e=>{e.some(e=>e[3]!==`cpu`)?postMessage({type:t,err:`Proxy does not support non-cpu tensor location.`}):postMessage({type:t,out:e},TT([...i,...e]))},e=>{postMessage({type:t,err:e})});break}case`end-profiling`:wT(n),postMessage({type:t});break;default:}}catch(e){postMessage({type:t,err:e})}}),LC=IC?null:e=>new Worker(e??qC,{type:`module`,name:FC})}),zC={};jS(zC,{default:()=>VC});async function BC(e={}){var t=e,n=!!globalThis.window,r=!!globalThis.WorkerGlobalScope,i=r&&self.name?.startsWith(`em-pthread`);t.mountExternalData=(e,n)=>{e.startsWith(`./`)&&(e=e.substring(2)),(t.Uc||=new Map).set(e,n)},t.unmountExternalData=()=>{delete t.Uc},globalThis.SharedArrayBuffer??new WebAssembly.Memory({initial:0,maximum:0,Be:!0}).buffer.constructor;let a=()=>{let e=e=>(...t)=>{let n=$t;return t=e(...t),$t==n?t:new Promise((e,t)=>{sn={resolve:e,reject:t}})};(()=>{for(let n of[`_OrtAppendExecutionProvider`,`_OrtCreateSession`,`_OrtRun`,`_OrtRunWithBinding`,`_OrtBindInput`])t[n]=e(t[n])})(),typeof jsepRunAsync<`u`&&(t._OrtRun=jsepRunAsync(t._OrtRun),t._OrtRunWithBinding=jsepRunAsync(t._OrtRunWithBinding)),a=void 0};t.asyncInit=()=>{a?.()};var o,s,c=(e,t)=>{throw t},l=import.meta.url,u=``;if(n||r){try{u=new URL(`.`,l).href}catch{}r&&(s=e=>{var t=new XMLHttpRequest;return t.open(`GET`,e,!1),t.responseType=`arraybuffer`,t.send(null),new Uint8Array(t.response)}),o=async e=>{if(S(e))return new Promise((t,n)=>{var r=new XMLHttpRequest;r.open(`GET`,e,!0),r.responseType=`arraybuffer`,r.onload=()=>{r.status==200||r.status==0&&r.response?t(r.response):n(r.status)},r.onerror=n,r.send(null)});var t=await fetch(e,{credentials:`same-origin`});if(t.ok)return t.arrayBuffer();throw Error(t.status+` : `+t.url)}}var d,f,p,m,h,g,_=console.log.bind(console),v=console.error.bind(console),y=_,b=v,x=!1,S=e=>e.startsWith(`file://`);function C(){xe.buffer!=T.buffer&&te()}if(i){let e=function(n){try{var r=n.data,i=r.Oc;if(i===`load`){let n=[];self.onmessage=e=>n.push(e),g=()=>{postMessage({Oc:`loaded`});for(let t of n)e(t);self.onmessage=e};for(let e of r.de)t[e]&&!t[e].proxy||(t[e]=(...t)=>{postMessage({Oc:`callHandler`,ce:e,args:t})},e==`print`&&(y=t[e]),e==`printErr`&&(b=t[e]));xe=r.je,te(),f=r.ke,ae(),ko()}else if(i===`run`){(function(e){var t=(C(),A)[e+52>>>2>>>0];e=(C(),A)[e+56>>>2>>>0],Xi(t,t-e),W(t)})(r.Nc),Bi(r.Nc,0,0,1,0,0),R(),Ht(r.Nc),w||=(_i(),!0);try{Se(r.he,r.Wc)}catch(e){if(e!=`unwind`)throw e}}else r.target!==`setimmediate`&&(i===`checkMailbox`?w&&Ut():i&&(b(`worker: received unknown command ${i}`),b(r)))}catch(e){throw Vi(),e}};var w=!1;self.onunhandledrejection=e=>{throw e.reason||e},self.onmessage=e}var T,E,D,O,k,A,j,ee,M,N,P,F=!1;function te(){var e=xe.buffer;t.HEAP8=T=new Int8Array(e),D=new Int16Array(e),t.HEAPU8=E=new Uint8Array(e),O=new Uint16Array(e),t.HEAP32=k=new Int32Array(e),t.HEAPU32=A=new Uint32Array(e),j=new Float32Array(e),ee=new Float64Array(e),M=new BigInt64Array(e),N=new BigUint64Array(e)}function ne(){F=!0,i?g():Ha._b()}function re(e){throw b(e=`Aborted(`+e+`)`),x=!0,e=new WebAssembly.RuntimeError(e+`. Build with -sASSERTIONS for more info.`),h?.(e),e}function ie(){return{a:{f:Ee,J:Oe,k:Ne,p:Pe,l:Fe,ta:Ie,b:Le,ca:Re,Ka:Be,s:Ve,da:Ke,_a:qe,Ga:Je,Ia:Ye,$a:Xe,Ya:Ze,Ra:Qe,Xa:$e,pa:et,Ha:tt,Yb:nt,Za:rt,Fa:it,eb:at,Da:pt,Tb:mt,Rb:St,Ca:wt,M:Tt,I:Et,Sb:kt,ka:Lt,Ub:Rt,Ua:zt,Wb:Wt,La:Kt,Pb:qt,la:Jt,Ta:Ht,bb:Yt,U:un,n:_n,c:_t,sb:vn,w:yn,L:bn,z:xn,j:Sn,o:Cn,tb:wn,G:Tn,T:En,h:Dn,u:On,m:kn,i:B,Oa:An,Pa:Pn,Qa:Fn,Ma:In,Na:Ln,Qb:Bn,fb:Vn,db:Wn,Y:qn,rb:Jn,ma:Yn,cb:Hn,gb:Xn,ab:Zn,Xb:Qn,N:zn,hb:$n,X:er,Vb:tr,ob:xr,C:Sr,sa:Cr,ra:wr,qb:Tr,W:Er,v:Dr,nb:Or,mb:kr,lb:Ar,pb:jr,kb:Mr,jb:Nr,ib:Pr,Va:Rr,Wa:zr,Ja:ge,ea:Br,oa:Vr,Sa:Hr,na:Wr,Db:Do,xa:yo,Eb:Eo,ya:vo,F:so,e:Ja,r:Ka,x:Ga,D:io,Ib:ho,ba:po,B:Xa,za:go,$:bo,ha:mo,Fb:wo,Gb:Co,Ba:co,Aa:fo,Jb:lo,wa:To,aa:_o,d:Ya,A:Za,q:qa,Cb:Oo,t:$a,y:ao,H:Qa,E:eo,K:oo,S:xo,ja:ro,_:So,Kb:no,Lb:to,P:uo,g:Gr,a:xe,Ob:me,Hb:Kr,ia:qr,O:Jr,qa:Yr,Mb:Xr,Q:Zr,zb:Qr,Ab:$r,ua:ei,fa:ti,R:ni,Ea:ri,va:ii,Z:ai,xb:oi,Zb:si,V:ci,Bb:li,ub:ui,vb:fi,wb:pi,ga:mi,yb:U,Nb:hi}}}async function ae(){function e(e,n){var r=Ha=e.exports;e={};for(let[t,n]of Object.entries(r))typeof n==`function`?(r=Zt(n),e[t]=r):e[t]=n;return Ha=e,Ha=function(){var e=Ha,t=e=>t=>e(t)>>>0,n=e=>()=>e()>>>0;return(e=Object.assign({},e)).$b=t(e.$b),e.Cc=n(e.Cc),e.Ec=t(e.Ec),e.rd=(e=>(t,n)=>e(t,n)>>>0)(e.rd),e.wd=t(e.wd),e.xd=n(e.xd),e.Bd=t(e.Bd),e}(),ve.push(Ha.id),gi=(e=Ha).$b,_i=e.ac,t._OrtInit=e.bc,t._OrtGetLastError=e.cc,t._OrtCreateSessionOptions=e.dc,t._OrtAppendExecutionProvider=e.ec,t._OrtAddFreeDimensionOverride=e.fc,t._OrtAddSessionConfigEntry=e.gc,t._OrtReleaseSessionOptions=e.hc,t._OrtCreateSession=e.ic,t._OrtReleaseSession=e.jc,t._OrtGetInputOutputCount=e.kc,t._OrtGetInputOutputMetadata=e.lc,t._OrtFree=e.mc,t._OrtCreateTensor=e.nc,t._OrtGetTensorData=e.oc,t._OrtReleaseTensor=e.pc,t._OrtCreateRunOptions=e.qc,t._OrtAddRunConfigEntry=e.rc,t._OrtReleaseRunOptions=e.sc,t._OrtCreateBinding=e.tc,t._OrtBindInput=e.uc,t._OrtBindOutput=e.vc,t._OrtClearBoundOutputs=e.wc,t._OrtReleaseBinding=e.xc,t._OrtRunWithBinding=e.yc,t._OrtRun=e.zc,t._OrtEndProfiling=e.Ac,vi=t._OrtGetWebGpuDevice=e.Bc,yi=e.Cc,bi=t._free=e.Dc,xi=t._malloc=e.Ec,Si=t._wgpuBufferRelease=e.Fc,Ci=t._wgpuCreateInstance=e.Gc,wi=e.Hc,Ti=e.Ic,Ei=e.Jc,Di=e.Kc,Oi=e.Lc,ki=e.Pc,Ai=e.Zc,ji=e._c,Mi=e.$c,Ni=e.bd,Pi=e.cd,Fi=e.dd,Ii=e.ed,Li=e.fd,Ri=e.gd,zi=e.hd,Bi=e.kd,Vi=e.ld,Hi=e.md,Ui=e.nd,Wi=e.od,Gi=e.pd,Ki=e.qd,qi=e.rd,Ji=e.sd,Yi=e.td,Xi=e.ud,W=e.vd,Zi=e.wd,G=e.xd,Qi=e.yd,$i=e.zd,ea=e.Ad,ta=e.Bd,na=e.Cd,ra=e.Dd,ia=e.Ed,aa=e.Fd,oa=e.Gd,sa=e.Hd,ca=e.Id,K=e.Jd,la=e.Kd,ua=e.Ld,da=e.Md,fa=e.Nd,pa=e.Od,ma=e.Pd,ha=e.Qd,ga=e.Rd,_a=e.Td,va=e.Ud,ya=e.Vd,ba=e.Wd,xa=e.Yd,Sa=e.Zd,Ca=e._d,wa=e.$d,Ta=e.ae,Ea=e.be,Da=e.pe,Oa=e.qe,ka=e.re,Aa=e.se,ja=e.te,Ma=e.ue,Na=e.ve,Pa=e.we,Fa=e.xe,Ia=e.ye,La=e.ze,Ra=e.Xe,za=e.Ye,Ba=e.Ze,Va=e._e,f=n,Ha}var n,r=ie();return t.instantiateWasm?new Promise(n=>{t.instantiateWasm(r,(t,r)=>{n(e(t,r))})}):i?e(new WebAssembly.Instance(f,ie()),f):(P??=t.locateFile?t.locateFile?t.locateFile(`ort-wasm-simd-threaded.asyncify.wasm`,u):u+`ort-wasm-simd-threaded.asyncify.wasm`:new URL(`/assets/ort-wasm-simd-threaded.asyncify-DFMnNRgU.wasm`,``+import.meta.url).href,n=await async function(e){var t=P;if(!d&&!S(t))try{var n=fetch(t,{credentials:`same-origin`});return await WebAssembly.instantiateStreaming(n,e)}catch(e){b(`wasm streaming compile failed: ${e}`),b(`falling back to ArrayBuffer instantiation`)}return async function(e,t){try{var n=await async function(e){if(!d)try{var t=await o(e);return new Uint8Array(t)}catch{}if(e==P&&d)e=new Uint8Array(d);else{if(!s)throw`both async and sync fetching of the wasm failed`;e=s(e)}return e}(e);return await WebAssembly.instantiate(n,t)}catch(e){b(`failed to asynchronously prepare wasm: ${e}`),re(e)}}(t,e)}(r),e(n.instance,n.module))}class oe{name=`ExitStatus`;constructor(e){this.message=`Program terminated with exit(${e})`,this.status=e}}var se=e=>{e.terminate(),e.onmessage=()=>{}},ce=[],le=0,ue=null,de=e=>{I.length==0&&(be(),z(I[0]));var t=I.pop();if(!t)return 6;_e.push(t),ye[e.Nc]=t,t.Nc=e.Nc;var n={Oc:`run`,he:e.ge,Wc:e.Wc,Nc:e.Nc};return t.postMessage(n,e.Yc),0},fe=0,pe=(e,t,...n)=>{var r,i=16*n.length,a=G(),o=Zi(i),s=o>>>3;for(r of n)typeof r==`bigint`?((C(),M)[s++>>>0]=1n,(C(),M)[s++>>>0]=r):((C(),M)[s++>>>0]=0n,(C(),ee)[s++>>>0]=r);return e=Hi(e,0,i,o,t),W(a),e};function me(e){if(i)return pe(0,1,e);if(p=e,!(0{if(p=e,i)throw he(e),`unwind`;me(e)},I=[],_e=[],ve=[],ye={},L=e=>{var t=e.Nc;delete ye[t],I.push(e),_e.splice(_e.indexOf(e),1),e.Nc=0,Ui(t)};function R(){ve.forEach(e=>e())}var z=e=>new Promise(n=>{e.onmessage=r=>{var i=r.data;if(r=i.Oc,i.Vc&&i.Vc!=yi()){var a=ye[i.Vc];a?a.postMessage(i,i.Yc):b(`Internal error! Worker sent a message "${r}" to target pthread ${i.Vc}, but that thread no longer exists!`)}else r===`checkMailbox`?Ut():r===`spawnThread`?de(i):r===`cleanupThread`?Bt(()=>{L(ye[i.ie])}):r===`loaded`?(e.loaded=!0,n(e)):i.target===`setimmediate`?e.postMessage(i):r===`uncaughtException`?e.onerror(i.error):r===`callHandler`?t[i.ce](...i.args):r&&b(`worker sent an unknown command ${r}`)},e.onerror=e=>{throw b(`worker sent an error! ${e.filename}:${e.lineno}: ${e.message}`),e};var r,i=[];for(r of[])t.propertyIsEnumerable(r)&&i.push(r);e.postMessage({Oc:`load`,de:i,je:xe,ke:f})});function be(){var e=new Worker((()=>{let e=URL;return import.meta.url>`file:`&&import.meta.url<`file;`?new e(`ort.webgpu.bundle.min.mjs`,import.meta.url):new URL(import.meta.url)})(),{type:`module`,workerData:`em-pthread`,name:`em-pthread`});I.push(e)}var xe,Se=(e,t)=>{fe=0,e=ra(e,t),0-9007199254740992>e||9007199254740992>>=0);return(C(),T)[t.Qc+12>>>0]==0&&(ke(t,!0),we--),Ae(t,!1),Ce.push(t),ta(e)}var De=0,Oe=()=>{Ji(0,0);var e=Ce.pop();Qi(e.Xc),De=0};function ke(e,t){t=t?1:0,(C(),T)[e.Qc+12>>>0]=t}function Ae(e,t){t=t?1:0,(C(),T)[e.Qc+13>>>0]=t}class je{constructor(e){this.Xc=e,this.Qc=e-24}}var Me=e=>{var t=De;if(!t)return Yi(0),0;var n=new je(t);(C(),A)[n.Qc+16>>>2>>>0]=t;var r=(C(),A)[n.Qc+4>>>2>>>0];if(!r)return Yi(0),t;for(var i of e){if(i===0||i===r)break;if(ea(i,r,n.Qc+16))return Yi(i),t}return Yi(r),t};function Ne(){return Me([])}function Pe(e){return Me([e>>>0])}function Fe(e,t,n,r){return Me([e>>>0,t>>>0,n>>>0,r>>>0])}var Ie=()=>{var e=Ce.pop();e||re(`no exception to throw`);var t=e.Xc;throw(C(),T)[e.Qc+13>>>0]==0&&(Ce.push(e),Ae(e,!0),ke(e,!1),we++),$i(t),De=t};function Le(e,t,n){var r=new je(e>>>=0);throw t>>>=0,n>>>=0,(C(),A)[r.Qc+16>>>2>>>0]=0,(C(),A)[r.Qc+4>>>2>>>0]=t,(C(),A)[r.Qc+8>>>2>>>0]=n,$i(e),we++,De=e}var Re=()=>we;function ze(e,t,n,r){return i?pe(2,1,e,t,n,r):Be(e,t,n,r)}function Be(e,t,n,r){if(e>>>=0,t>>>=0,n>>>=0,r>>>=0,!globalThis.SharedArrayBuffer)return 6;var a=[];return i&&a.length===0?ze(e,t,n,r):(e={ge:n,Nc:e,Wc:r,Yc:a},i?(e.Oc=`spawnThread`,postMessage(e,a),0):de(e))}function Ve(e){throw De||=e>>>0,De}var He=globalThis.TextDecoder&&new TextDecoder,Ue=(e,t,n,r)=>{if(n=t+n,r)return n;for(;e[t]&&!(t>=n);)++t;return t},We=(e,t=0,n,r)=>{if(16<(n=Ue(e,t>>>=0,n,r))-t&&e.buffer&&He)return He.decode(e.buffer instanceof ArrayBuffer?e.subarray(t,n):e.slice(t,n));for(r=``;t(i=(240&i)==224?(15&i)<<12|a<<6|o:(7&i)<<18|a<<12|o<<6|63&e[t++])?r+=String.fromCharCode(i):(i-=65536,r+=String.fromCharCode(55296|i>>10,56320|1023&i))}}else r+=String.fromCharCode(i)}return r},Ge=(e,t,n)=>(e>>>=0)?We((C(),E),e,t,n):``;function Ke(e,t,n){return i?pe(3,1,e,t,n):0}function qe(e,t){if(i)return pe(4,1,e,t)}function Je(e,t){if(i)return pe(5,1,e,t)}function Ye(e,t,n){if(i)return pe(6,1,e,t,n)}function Xe(e,t,n){return i?pe(7,1,e,t,n):0}function Ze(e,t){if(i)return pe(8,1,e,t)}function Qe(e,t,n){if(i)return pe(9,1,e,t,n)}function $e(e,t,n,r){if(i)return pe(10,1,e,t,n,r)}function et(e,t,n,r){if(i)return pe(11,1,e,t,n,r)}function tt(e,t,n,r){if(i)return pe(12,1,e,t,n,r)}function nt(e){if(i)return pe(13,1,e)}function rt(e,t){if(i)return pe(14,1,e,t)}function it(e,t,n){if(i)return pe(15,1,e,t,n)}var at=()=>re(``),ot=e=>{e>>>=0;for(var t=``;;){var n=(C(),E)[e++>>>0];if(!n)return t;t+=String.fromCharCode(n)}},st={},ct={},lt={},ut=class extends Error{constructor(e){super(e),this.name=`BindingError`}};function dt(e,t,n={}){return function(e,t,n={}){var r=t.name;if(!e)throw new ut(`type "${r}" must have a positive integer typeid pointer`);if(ct.hasOwnProperty(e)){if(n.ee)return;throw new ut(`Cannot register type '${r}' twice`)}ct[e]=t,delete lt[e],st.hasOwnProperty(e)&&(t=st[e],delete st[e],t.forEach(e=>e()))}(e,t,n)}var ft=(e,t,n)=>{switch(t){case 1:return n?e=>(C(),T)[e>>>0]:e=>(C(),E)[e>>>0];case 2:return n?e=>(C(),D)[e>>>1>>>0]:e=>(C(),O)[e>>>1>>>0];case 4:return n?e=>(C(),k)[e>>>2>>>0]:e=>(C(),A)[e>>>2>>>0];case 8:return n?e=>(C(),M)[e>>>3>>>0]:e=>(C(),N)[e>>>3>>>0];default:throw TypeError(`invalid integer width (${t}): ${e}`)}};function pt(e,t,n,r,i){e>>>=0,n>>>=0,t=ot(t>>>0);let a=e=>e;if(r=r===0n){let e=8*n;a=t=>BigInt.asUintN(e,t),i=a(i)}dt(e,{name:t,Mc:a,Sc:(e,t)=>(typeof t==`number`&&(t=BigInt(t)),t),Rc:ft(t,n,!r),Tc:null})}function mt(e,t,n,r){dt(e>>>=0,{name:t=ot(t>>>0),Mc:function(e){return!!e},Sc:function(e,t){return t?n:r},Rc:function(e){return this.Mc((C(),E)[e>>>0])},Tc:null})}var ht=[],gt=[0,1,,1,null,1,!0,1,!1,1];function _t(e){9<(e>>>=0)&&--gt[e+1]==0&&(gt[e]=void 0,ht.push(e))}var vt=e=>{if(!e)throw new ut(`Cannot use deleted val. handle = ${e}`);return gt[e]},yt=e=>{switch(e){case void 0:return 2;case null:return 4;case!0:return 6;case!1:return 8;default:let t=ht.pop()||gt.length;return gt[t]=e,gt[t+1]=1,t}};function bt(e){return this.Mc((C(),A)[e>>>2>>>0])}var xt={name:`emscripten::val`,Mc:e=>{var t=vt(e);return _t(e),t},Sc:(e,t)=>yt(t),Rc:bt,Tc:null};function St(e){return dt(e>>>0,xt)}var Ct=(e,t)=>{switch(t){case 4:return function(e){return this.Mc((C(),j)[e>>>2>>>0])};case 8:return function(e){return this.Mc((C(),ee)[e>>>3>>>0])};default:throw TypeError(`invalid float width (${t}): ${e}`)}};function wt(e,t,n){n>>>=0,dt(e>>>=0,{name:t=ot(t>>>0),Mc:e=>e,Sc:(e,t)=>t,Rc:Ct(t,n),Tc:null})}function Tt(e,t,n,r,i){e>>>=0,n>>>=0,t=ot(t>>>0);let a=e=>e;if(r===0){var o=32-8*n;a=e=>e<>>o,i=a(i)}dt(e,{name:t,Mc:a,Sc:(e,t)=>t,Rc:ft(t,n,r!==0),Tc:null})}function Et(e,t,n){function r(e){var t=(C(),A)[e>>>2>>>0];return e=(C(),A)[e+4>>>2>>>0],new i((C(),T).buffer,e,t)}var i=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,BigInt64Array,BigUint64Array][t];dt(e>>>=0,{name:n=ot(n>>>0),Mc:r,Rc:r},{ee:!0})}var Dt=(e,t,n)=>{var r=(C(),E);if(t>>>=0,0=o){if(t>=n)break;r[t++>>>0]=o}else if(2047>=o){if(t+1>=n)break;r[t++>>>0]=192|o>>6,r[t++>>>0]=128|63&o}else if(65535>=o){if(t+2>=n)break;r[t++>>>0]=224|o>>12,r[t++>>>0]=128|o>>6&63,r[t++>>>0]=128|63&o}else{if(t+3>=n)break;r[t++>>>0]=240|o>>18,r[t++>>>0]=128|o>>12&63,r[t++>>>0]=128|o>>6&63,r[t++>>>0]=128|63&o,a++}}r[t>>>0]=0,e=t-i}else e=0;return e},Ot=e=>{for(var t=0,n=0;n=r?t++:2047>=r?t+=2:55296<=r&&57343>=r?(t+=4,++n):t+=3}return t};function kt(e,t){dt(e>>>=0,{name:t=ot(t>>>0),Mc(e){var t=(C(),A)[e>>>2>>>0];return t=Ge(e+4,t,!0),bi(e),t},Sc(e,t){t instanceof ArrayBuffer&&(t=new Uint8Array(t));var n=typeof t==`string`;if(!(n||ArrayBuffer.isView(t)&&t.BYTES_PER_ELEMENT==1))throw new ut(`Cannot pass non-string to std::string`);var r=n?Ot(t):t.length,i=xi(4+r+1),a=i+4;return(C(),A)[i>>>2>>>0]=r,n?Dt(t,a,r+1):(C(),E).set(t,a>>>0),e!==null&&e.push(bi,i),i},Rc:bt,Tc(e){bi(e)}})}var At=globalThis.TextDecoder?new TextDecoder(`utf-16le`):void 0,jt=(e,t,n)=>{if(e>>>=1,16<(t=Ue((C(),O),e,t/2,n))-e&&At)return At.decode((C(),O).slice(e,t));for(n=``;e>>0];n+=String.fromCharCode(r)}return n},Mt=(e,t,n)=>{if(n??=2147483647,2>n)return 0;var r=t;n=(n-=2)<2*e.length?n/2:e.length;for(var i=0;i>>1>>>0]=a,t+=2}return(C(),D)[t>>>1>>>0]=0,t-r},Nt=e=>2*e.length,Pt=(e,t,n)=>{var r=``;e>>>=2;for(var i=0;!(i>=t/4);i++){var a=(C(),A)[e+i>>>0];if(!a&&!n)break;r+=String.fromCodePoint(a)}return r},Ft=(e,t,n)=>{if(t>>>=0,n??=2147483647,4>n)return 0;var r=t;n=r+n-4;for(var i=0;i>>2>>>0]=a,(t+=4)+4>n)break}return(C(),k)[t>>>2>>>0]=0,t-r},It=e=>{for(var t=0,n=0;n>>=0,t>>>=0,n=ot(n>>>=0),t===2)var r=jt,i=Mt,a=Nt;else r=Pt,i=Ft,a=It;dt(e,{name:n,Mc:e=>{var n=(C(),A)[e>>>2>>>0];return n=r(e+4,n*t,!0),bi(e),n},Sc:(e,r)=>{if(typeof r!=`string`)throw new ut(`Cannot pass non-string to C++ string type ${n}`);var o=a(r),s=xi(4+o+t);return(C(),A)[s>>>2>>>0]=o/t,i(r,s+4,o+t),e!==null&&e.push(bi,s),s},Rc:bt,Tc(e){bi(e)}})}function Rt(e,t){dt(e>>>=0,{fe:!0,name:t=ot(t>>>0),Mc:()=>{},Sc:()=>{}})}function zt(e){Bi(e>>>0,!r,1,!n,131072,!1),R()}var Bt=e=>{if(!x)try{if(e(),!(0Number((navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)||[])[2]);function Ht(e){e>>>=0,Vt||(Atomics.waitAsync((C(),k),e>>>2,e).value.then(Ut),e+=128,Atomics.store((C(),k),e>>>2,1))}var Ut=()=>Bt(()=>{var e=yi();e&&(Ht(e),Ki())});function Wt(e,t){(e>>>=0)==t>>>0?setTimeout(Ut):i?postMessage({Vc:e,Oc:`checkMailbox`}):(e=ye[e])&&e.postMessage({Oc:`checkMailbox`})}var Gt=[];function Kt(e,t,n,r,i){for(t>>>=0,i>>>=0,Gt.length=0,n=i>>>3,r=i+r>>>3;n>>0]?(C(),M)[n++>>>0]:(C(),ee)[n++>>>0];Gt.push(a)}return(t?Wa[t]:Ua[e])(...Gt)}var qt=()=>{fe=0};function Jt(e){e>>>=0,i?postMessage({Oc:`cleanupThread`,ie:e}):L(ye[e])}function Yt(e){}var Xt=e=>{try{e()}catch(e){re(e)}};function Zt(e){var t=(...t)=>{tn.push(e);try{return e(...t)}finally{x||(tn.pop(),$t&&Qt===1&&tn.length===0&&(Qt=0,fe+=1,Xt(za),typeof Fibers<`u`&&Fibers.De()))}};return an.set(e,t),t}var Qt=0,$t=null,en=0,tn=[],nn=new Map,rn=new Map,an=new Map,on=0,sn=null,cn=[],ln=e=>function(e){if(!x){if(Qt===0){var t=!1,n=!1;e((e=0)=>{if(!x&&(en=e,t=!0,n)){Qt=2,Xt(()=>Ba($t)),typeof MainLoop<`u`&&MainLoop.Xd&&MainLoop.resume(),e=!1;try{var r=function(){var e=(C(),k)[$t+8>>>2>>>0];return e=rn.get(e),e=an.get(e),--fe,e()}()}catch(t){r=t,e=!0}var i=!1;if(!$t){var a=sn;a&&(sn=null,(e?a.reject:a.resolve)(r),i=!0)}if(e&&!i)throw r}}),n=!0,t||(Qt=1,$t=function(){var e=xi(65548),t=e+12;if((C(),A)[e>>>2>>>0]=t,(C(),A)[e+4>>>2>>>0]=t+65536,t=tn[0],!nn.has(t)){var n=on++;nn.set(t,n),rn.set(n,t)}return t=nn.get(t),(C(),k)[e+8>>>2>>>0]=t,e}(),typeof MainLoop<`u`&&MainLoop.Xd&&MainLoop.pause(),Xt(()=>Ra($t)))}else Qt===2?(Qt=0,Xt(Va),bi($t),$t=null,cn.forEach(Bt)):re(`invalid state: ${Qt}`);return en}}(t=>{e().then(t)});function un(e){return e>>>=0,ln(async()=>yt(await vt(e)))}var dn=[],fn=e=>{var t=dn.length;return dn.push(e),t},pn=(e,t)=>{for(var n=Array(e),r=0;r>>2>>>0],o=ct[a];if(o===void 0)throw e=`parameter ${r}`,a=gi(a),t=ot(a),bi(a),new ut(`${e} has unknown type ${t}`);n[i]=o}return n},mn=(e,t,n)=>{var r=[];return e=e(r,n),r.length&&((C(),A)[t>>>2>>>0]=yt(r)),e},hn={},gn=e=>{var t=hn[e];return t===void 0?ot(e):t};function _n(e,t,n){var[r,...i]=pn(e,t>>>0);t=r.Sc.bind(r);var a=i.map(e=>e.Rc.bind(e));e--;var o={toValue:vt};switch(e=a.map((e,t)=>{var n=`argFromPtr${t}`;return o[n]=e,`${n}(args${t?`+`+8*t:``})`}),n){case 0:var s=`toValue(handle)`;break;case 2:s=`new (toValue(handle))`;break;case 3:s=``;break;case 1:o.getStringOrSymbol=gn,s=`toValue(handle)[getStringOrSymbol(methodName)]`}return s+=`(${e})`,r.fe||(o.toReturnWire=t,o.emval_returnValue=mn,s=`return emval_returnValue(toReturnWire, destructorsRef, ${s})`),s=`return function (handle, methodName, destructorsRef, args) { + ${s} + }`,n=Function(Object.keys(o),s)(...Object.values(o)),s=`methodCaller<(${i.map(e=>e.name)}) => ${r.name}>`,fn(Object.defineProperty(n,`name`,{value:s}))}function vn(e,t){return t>>>=0,(e=vt(e>>>0))==vt(t)}function yn(e){return(e>>>=0)?(e=gn(e),yt(globalThis[e])):yt(globalThis)}function bn(e){return e=gn(e>>>0),yt(t[e])}function xn(e,t){return t>>>=0,e=vt(e>>>0),t=vt(t),yt(e[t])}function Sn(e){9<(e>>>=0)&&(gt[e+1]+=1)}function Cn(e,t,n,r,i){return dn[e>>>0](t>>>0,n>>>0,r>>>0,i>>>0)}function wn(e,t,n,r,i){return Cn(e>>>0,t>>>0,n>>>0,r>>>0,i>>>0)}function Tn(){return yt([])}function En(e){e=vt(e>>>0);for(var t=Array(e.length),n=0;n>>0))}function On(){return yt({})}function kn(e){for(var t=vt(e>>>=0);t.length;){var n=t.pop();t.pop()(n)}_t(e)}function B(e,t,n){t>>>=0,n>>>=0,e=vt(e>>>0),t=vt(t),n=vt(n),e[t]=n}function An(e,t){e=Te(e),t>>>=0,e=new Date(1e3*e),(C(),k)[t>>>2>>>0]=e.getUTCSeconds(),(C(),k)[t+4>>>2>>>0]=e.getUTCMinutes(),(C(),k)[t+8>>>2>>>0]=e.getUTCHours(),(C(),k)[t+12>>>2>>>0]=e.getUTCDate(),(C(),k)[t+16>>>2>>>0]=e.getUTCMonth(),(C(),k)[t+20>>>2>>>0]=e.getUTCFullYear()-1900,(C(),k)[t+24>>>2>>>0]=e.getUTCDay(),e=(e.getTime()-Date.UTC(e.getUTCFullYear(),0,1,0,0,0,0))/864e5|0,(C(),k)[t+28>>>2>>>0]=e}var jn=e=>e%4==0&&(e%100!=0||e%400==0),Mn=[0,31,60,91,121,152,182,213,244,274,305,335],Nn=[0,31,59,90,120,151,181,212,243,273,304,334];function Pn(e,t){e=Te(e),t>>>=0,e=new Date(1e3*e),(C(),k)[t>>>2>>>0]=e.getSeconds(),(C(),k)[t+4>>>2>>>0]=e.getMinutes(),(C(),k)[t+8>>>2>>>0]=e.getHours(),(C(),k)[t+12>>>2>>>0]=e.getDate(),(C(),k)[t+16>>>2>>>0]=e.getMonth(),(C(),k)[t+20>>>2>>>0]=e.getFullYear()-1900,(C(),k)[t+24>>>2>>>0]=e.getDay();var n=(jn(e.getFullYear())?Mn:Nn)[e.getMonth()]+e.getDate()-1|0;(C(),k)[t+28>>>2>>>0]=n,(C(),k)[t+36>>>2>>>0]=-60*e.getTimezoneOffset(),n=new Date(e.getFullYear(),6,1).getTimezoneOffset();var r=new Date(e.getFullYear(),0,1).getTimezoneOffset();e=0|(n!=r&&e.getTimezoneOffset()==Math.min(r,n)),(C(),k)[t+32>>>2>>>0]=e}function Fn(e){e>>>=0;var t=new Date((C(),k)[e+20>>>2>>>0]+1900,(C(),k)[e+16>>>2>>>0],(C(),k)[e+12>>>2>>>0],(C(),k)[e+8>>>2>>>0],(C(),k)[e+4>>>2>>>0],(C(),k)[e>>>2>>>0],0),n=(C(),k)[e+32>>>2>>>0],r=t.getTimezoneOffset(),i=new Date(t.getFullYear(),6,1).getTimezoneOffset(),a=new Date(t.getFullYear(),0,1).getTimezoneOffset(),o=Math.min(a,i);return 0>n?(C(),k)[e+32>>>2>>>0]=+(i!=a&&o==r):0>>2>>>0]=t.getDay(),n=(jn(t.getFullYear())?Mn:Nn)[t.getMonth()]+t.getDate()-1|0,(C(),k)[e+28>>>2>>>0]=n,(C(),k)[e>>>2>>>0]=t.getSeconds(),(C(),k)[e+4>>>2>>>0]=t.getMinutes(),(C(),k)[e+8>>>2>>>0]=t.getHours(),(C(),k)[e+12>>>2>>>0]=t.getDate(),(C(),k)[e+16>>>2>>>0]=t.getMonth(),(C(),k)[e+20>>>2>>>0]=t.getYear(),e=t.getTime(),BigInt(isNaN(e)?-1:e/1e3)}function In(e,t,n,r,a,o,s){return i?pe(16,1,e,t,n,r,a,o,s):-52}function Ln(e,t,n,r,a,o){if(i)return pe(17,1,e,t,n,r,a,o)}var Rn={},zn=()=>performance.timeOrigin+performance.now();function Bn(e,t){return i?pe(18,1,e,t):(Rn[e]&&(clearTimeout(Rn[e].id),delete Rn[e]),t&&(Rn[e]={id:setTimeout(()=>{delete Rn[e],Bt(()=>Gi(e,performance.timeOrigin+performance.now()))},t),Ce:t}),0)}function Vn(e,t,n,r){e>>>=0,t>>>=0,n>>>=0,r>>>=0;var i=new Date().getFullYear(),a=new Date(i,0,1).getTimezoneOffset();i=new Date(i,6,1).getTimezoneOffset();var o=Math.max(a,i);(C(),A)[e>>>2>>>0]=60*o,(C(),k)[t>>>2>>>0]=+(a!=i),e=(t=e=>{var t=Math.abs(e);return`UTC${0<=e?`-`:`+`}${String(Math.floor(t/60)).padStart(2,`0`)}${String(t%60).padStart(2,`0`)}`})(a),t=t(i),iDate.now(),Un=1;function Wn(e,t,n){if(n>>>=0,!(0<=e&&3>=e))return 28;if(e===0)e=Date.now();else{if(!Un)return 52;e=performance.timeOrigin+performance.now()}return e=Math.round(1e6*e),(C(),M)[n>>>3>>>0]=BigInt(e),0}var Gn=[],Kn=(e,t)=>{Gn.length=0;for(var n;n=(C(),E)[e++>>>0];){var r=n!=105;t+=(r&=n!=112)&&t%8?4:0,Gn.push(n==112?(C(),A)[t>>>2>>>0]:n==106?(C(),M)[t>>>3>>>0]:n==105?(C(),k)[t>>>2>>>0]:(C(),ee)[t>>>3>>>0]),t+=r?8:4}return Gn};function qn(e,t,n){return e>>>=0,t=Kn(t>>>0,n>>>0),Wa[e](...t)}function Jn(e,t,n){return e>>>=0,t=Kn(t>>>0,n>>>0),Wa[e](...t)}var Yn=()=>{};function Xn(e,t){return b(Ge(e>>>0,t>>>0))}var Zn=()=>{throw fe+=1,`unwind`};function Qn(){return 4294901760}var $n=()=>1,er=()=>navigator.hardwareConcurrency;function tr(e){e>>>=0;var t=(C(),E).length;if(e<=t||4294901760=n;n*=2){var r=t*(1+.2/n);r=Math.min(r,e+100663296);e:{r=(Math.min(4294901760,65536*Math.ceil(Math.max(e,r)/65536))-xe.buffer.byteLength+65535)/65536|0;try{xe.grow(r),te();var i=1;break e}catch{}i=void 0}if(i)return!0}return!1}var nr=e=>{var t=Ot(e)+1,n=Zi(t);return Dt(e,n,t),n},rr=(e,t)=>{(C(),A)[e>>>2>>>0]=t;var n=(C(),A)[e>>>2>>>0];(C(),A)[e+4>>>2>>>0]=(t-n)/4294967296},ir=e=>(C(),A)[e>>>2>>>0]+4294967296*(C(),k)[e+4>>>2>>>0],ar=[],or=(e,t)=>{ar[e>>>0]=t},sr=[],V=[],cr=(e,t)=>{V[e]=new Promise(n=>t.finally(()=>n(e)))},H=e=>{if(e)return ar[e>>>0]},lr=(e,t)=>{for(e=(C(),A)[e>>>2>>>0];e;e=(C(),A)[e>>>2>>>0])t[(C(),k)[e+4>>>2>>>0]](e)},ur=(e,t,n)=>{(C(),A)[e>>>2>>>0]=t,(C(),A)[e+4>>>2>>>0]=n},dr=e=>{var t=(C(),A)[e>>>2>>>0];return e=(C(),A)[e+4>>>2>>>0],Ge(t,e)},fr=e=>{var t=(C(),A)[e>>>2>>>0];return e=(C(),A)[e+4>>>2>>>0],t?Ge(t,e):e===0?``:void 0},pr=e=>{var t=fr(e+4),n=(n=(C(),A)[e+12>>>2>>>0])?H(n):`auto`;if(e+=16){var r=H((C(),A)[e+4>>>2>>>0]),i=(C(),A)[e+16>>>2>>>0],a=(C(),A)[e+20>>>2>>>0];if(i){for(var o={},s=0;s>>3>>>0]}i=o}else i=void 0;e={module:r,constants:i,entryPoint:fr(e+8)}}else e=void 0;return{label:t,layout:n,compute:e}},mr=(e,t)=>{function n(n,r){n=e[n],(C(),A)[t+r>>>2>>>0]=n}n(`maxTextureDimension1D`,4),n(`maxTextureDimension2D`,8),n(`maxTextureDimension3D`,12),n(`maxTextureArrayLayers`,16),n(`maxBindGroups`,20),n(`maxBindGroupsPlusVertexBuffers`,24),n(`maxBindingsPerBindGroup`,28),n(`maxDynamicUniformBuffersPerPipelineLayout`,32),n(`maxDynamicStorageBuffersPerPipelineLayout`,36),n(`maxSampledTexturesPerShaderStage`,40),n(`maxSamplersPerShaderStage`,44),n(`maxStorageBuffersPerShaderStage`,48),n(`maxStorageTexturesPerShaderStage`,52),n(`maxUniformBuffersPerShaderStage`,56),n(`minUniformBufferOffsetAlignment`,80),n(`minStorageBufferOffsetAlignment`,84),rr(t+64,e.maxUniformBufferBindingSize),rr(t+72,e.maxStorageBufferBindingSize),n(`maxVertexBuffers`,88),rr(t+96,e.maxBufferSize),n(`maxVertexAttributes`,104),n(`maxVertexBufferArrayStride`,108),n(`maxInterStageShaderVariables`,112),n(`maxColorAttachments`,116),n(`maxColorAttachmentBytesPerSample`,120),n(`maxComputeWorkgroupStorageSize`,124),n(`maxComputeInvocationsPerWorkgroup`,128),n(`maxComputeWorkgroupSizeX`,132),n(`maxComputeWorkgroupSizeY`,136),n(`maxComputeWorkgroupSizeZ`,140),n(`maxComputeWorkgroupsPerDimension`,144),e.Ae!==void 0&&n(`maxImmediateSize`,148)},hr=[,`validation`,`out-of-memory`,`internal`],gr=[,`compatibility`,`core`],_r={1:`core-features-and-limits`,2:`depth-clip-control`,3:`depth32float-stencil8`,4:`texture-compression-bc`,5:`texture-compression-bc-sliced-3d`,6:`texture-compression-etc2`,7:`texture-compression-astc`,8:`texture-compression-astc-sliced-3d`,9:`timestamp-query`,10:`indirect-first-instance`,11:`shader-f16`,12:`rg11b10ufloat-renderable`,13:`bgra8unorm-storage`,14:`float32-filterable`,15:`float32-blendable`,16:`clip-distances`,17:`dual-source-blending`,18:`subgroups`,19:`texture-formats-tier1`,20:`texture-formats-tier2`,21:`primitive-index`,22:`texture-component-swizzle`,327692:`chromium-experimental-unorm16-texture-formats`,327729:`chromium-experimental-multi-draw-indirect`},vr=[,`low-power`,`high-performance`],yr=[,`occlusion`,`timestamp`],br={undefined:1,unknown:1,destroyed:2};function xr(e,t,n,r,i,a){t=Te(t),n=Te(n),r>>>=0,i>>>=0,a>>>=0;var o=H(e>>>0);if(e={},a){var s=(C(),A)[a+12>>>2>>>0];if(s){var c=(C(),A)[a+16>>>2>>>0];e.requiredFeatures=Array.from((C(),A).subarray(c>>>2>>>0,c+4*s>>>2>>>0),e=>_r[e])}var l=(C(),A)[a+20>>>2>>>0];if(l){let t=function(e,t,n=!1){t=l+t,(t=(C(),A)[t>>>2>>>0])==4294967295||n&&t==0||(u[e]=t)},n=function(e,t){t=l+t;var n=(C(),A)[t>>>2>>>0],r=(C(),A)[t+4>>>2>>>0];n==4294967295&&r==4294967295||(u[e]=ir(t))};var u={};t(`maxTextureDimension1D`,4),t(`maxTextureDimension2D`,8),t(`maxTextureDimension3D`,12),t(`maxTextureArrayLayers`,16),t(`maxBindGroups`,20),t(`maxBindGroupsPlusVertexBuffers`,24),t(`maxDynamicUniformBuffersPerPipelineLayout`,32),t(`maxDynamicStorageBuffersPerPipelineLayout`,36),t(`maxSampledTexturesPerShaderStage`,40),t(`maxSamplersPerShaderStage`,44),t(`maxStorageBuffersPerShaderStage`,48),t(`maxStorageTexturesPerShaderStage`,52),t(`maxUniformBuffersPerShaderStage`,56),t(`minUniformBufferOffsetAlignment`,80),t(`minStorageBufferOffsetAlignment`,84),n(`maxUniformBufferBindingSize`,64),n(`maxStorageBufferBindingSize`,72),t(`maxVertexBuffers`,88),n(`maxBufferSize`,96),t(`maxVertexAttributes`,104),t(`maxVertexBufferArrayStride`,108),t(`maxInterStageShaderVariables`,112),t(`maxColorAttachments`,116),t(`maxColorAttachmentBytesPerSample`,120),t(`maxComputeWorkgroupStorageSize`,124),t(`maxComputeInvocationsPerWorkgroup`,128),t(`maxComputeWorkgroupSizeX`,132),t(`maxComputeWorkgroupSizeY`,136),t(`maxComputeWorkgroupSizeZ`,140),t(`maxComputeWorkgroupsPerDimension`,144),t(`maxImmediateSize`,148,!0),e.requiredLimits=u}(s=(C(),A)[a+24>>>2>>>0])&&(s={label:fr(s+4)},e.defaultQueue=s),e.label=fr(a+4)}fe+=1,cr(t,o.requestDevice(e).then(e=>{--fe,Bt(()=>{ar[i>>>0]=e.queue,ar[r>>>0]=e,cr(n,e.lost.then(t=>{Bt(()=>{e.onuncapturederror=()=>{};var r=G(),i=nr(t.message);Pi(n,br[t.reason],i),W(r)})})),e.onuncapturederror=e=>{var t=5;e.error instanceof GPUValidationError?t=2:e.error instanceof GPUOutOfMemoryError?t=3:e.error instanceof GPUInternalError&&(t=4);var n=G();e=nr(e.error.message),zi(r,t,e),W(n)},`adapterInfo`in e||(e.adapterInfo=o.info),Ri(t,1,r,0)})},e=>{--fe,Bt(()=>{var i=G(),a=nr(e.message);Ri(t,3,r,a),n&&Pi(n,4,a),W(i)})}))}function Sr(e){var t=H(e>>>=0),n=sr[e];if(n){for(var r=0;r>>=0;var r=H(e>>>=0);n==4294967295&&(n=void 0);try{var i=r.getMappedRange(t>>>0,n)}catch{return 0}var a=qi(16,i.byteLength);return(C(),E).set(new Uint8Array(i),a>>>0),sr[e].push(()=>bi(a)),a}function wr(e,t,n){n>>>=0;var r=H(e>>>=0);n==4294967295&&(n=void 0);try{var i=r.getMappedRange(t>>>0,n)}catch{return 0}var a=qi(16,i.byteLength);return(C(),E).fill(0,a,i.byteLength),sr[e].push(()=>{new Uint8Array(i).set((C(),E).subarray(a>>>0,a+i.byteLength>>>0)),bi(a)}),a}function Tr(e,t,n,r,i){e>>>=0,t=Te(t),n=Te(n),i>>>=0;var a=H(e);sr[e]=[],i==4294967295&&(i=void 0),fe+=1,cr(t,a.mapAsync(n,r>>>0,i).then(()=>{--fe,Bt(()=>{Fi(t,1,0)})},n=>{--fe,Bt(()=>{G();var r=nr(n.message);Fi(t,n.name===`AbortError`?4:n.name===`OperationError`?3:0,r),delete sr[e]})}))}function Er(e){var t=H(e>>>=0),n=sr[e];if(n){for(var r=0;r>>0]}function Or(e,t,n){e>>>=0,t>>>=0,n>>>=0;var r=!!(C(),A)[t+32>>>2>>>0];t={label:fr(t+4),usage:(C(),A)[t+16>>>2>>>0],size:ir(t+24),mappedAtCreation:r},e=H(e);try{var i=e.createBuffer(t)}catch{return!1}return ar[n>>>0]=i,r&&(sr[n]=[]),!0}function kr(e,t,n,r){e>>>=0,t=Te(t),r>>>=0,n=pr(n>>>0),e=H(e),fe+=1,cr(t,e.createComputePipelineAsync(n).then(e=>{--fe,Bt(()=>{ar[r>>>0]=e,Ni(t,1,r,0)})},e=>{--fe,Bt(()=>{var n=G(),i=nr(e.message);Ni(t,e.reason===`validation`?3:e.reason===`internal`?4:0,r,i),W(n)})}))}function Ar(e,t,n){e>>>=0,t>>>=0,n>>>=0;var r=(C(),A)[t>>>2>>>0],i=(C(),k)[r+4>>>2>>>0];t={label:fr(t+4),code:``},i===2&&(t.code=dr(r+8)),e=H(e).createShaderModule(t),ar[n>>>0]=e}var jr=e=>{(e=H(e)).onuncapturederror=null,e.destroy()};function Mr(e,t){t=Te(t),e=H(e>>>0),fe+=1,cr(t,e.popErrorScope().then(e=>{--fe,Bt(()=>{var n=5;e?e instanceof GPUValidationError?n=2:e instanceof GPUOutOfMemoryError?n=3:e instanceof GPUInternalError&&(n=4):n=1;var r=G(),i=e?nr(e.message):0;Ii(t,1,n,i),W(r)})},e=>{--fe,Bt(()=>{var n=G(),r=nr(e.message);Ii(t,1,5,r),W(n)})}))}function Nr(e,t,n,r){if(t=Te(t),r>>>=0,n>>>=0){var i={featureLevel:gr[(C(),k)[n+4>>>2>>>0]],powerPreference:vr[(C(),k)[n+8>>>2>>>0]],forceFallbackAdapter:!!(C(),A)[n+12>>>2>>>0]};(e=(C(),A)[n>>>2>>>0])!==0&&(C(),i.Fe=!!(C(),A)[e+8>>>2>>>0])}`gpu`in navigator?(fe+=1,cr(t,navigator.gpu.requestAdapter(i).then(e=>{--fe,Bt(()=>{if(e)ar[r>>>0]=e,Li(t,1,r,0);else{var n=G(),i=nr(`WebGPU not available on this browser (requestAdapter returned null)`);Li(t,3,r,i),W(n)}})},e=>{--fe,Bt(()=>{var n=G(),i=nr(e.message);Li(t,4,r,i),W(n)})}))):(i=G(),e=nr(`WebGPU not available on this browser (navigator.gpu is not available)`),Li(t,3,r,e),W(i))}function Pr(e,t,n){return e>>>=0,t>>>=0,n>>>=0,ln(async()=>{var r=[];if(n){var i=(C(),k)[n>>>2>>>0];r.length=t+1,r[t]=new Promise(e=>setTimeout(e,i,0))}else r.length=t;for(var a=0;a{if(!Fr){var e,t={USER:`web_user`,LOGNAME:`web_user`,PATH:`/`,PWD:`/`,HOME:`/home/web_user`,LANG:(globalThis.navigator?.language??`C`).replace(`-`,`_`)+`.UTF-8`,_:`./this.program`};for(e in Ir)Ir[e]===void 0?delete t[e]:t[e]=Ir[e];var n=[];for(e in t)n.push(`${e}=${t[e]}`);Fr=n}return Fr};function Rr(e,t){if(i)return pe(19,1,e,t);e>>>=0,t>>>=0;var n,r=0,a=0;for(n of Lr()){var o=t+r;(C(),A)[e+a>>>2>>>0]=o,r+=Dt(n,o,1/0)+1,a+=4}return 0}function zr(e,t){if(i)return pe(20,1,e,t);e>>>=0,t>>>=0;var n=Lr();for(var r of((C(),A)[e>>>2>>>0]=n.length,e=0,n))e+=Ot(r)+1;return(C(),A)[t>>>2>>>0]=e,0}function Br(e){return i?pe(21,1,e):52}function Vr(e,t,n,r){return i?pe(22,1,e,t,n,r):52}function Hr(e,t,n,r){return i?pe(23,1,e,t,n,r):70}var Ur=[null,[],[]];function Wr(e,t,n,r){if(i)return pe(24,1,e,t,n,r);t>>>=0,n>>>=0,r>>>=0;for(var a=0,o=0;o>>2>>>0],c=(C(),A)[t+4>>>2>>>0];t+=8;for(var l=0;l>>0],f=Ur[u];d===0||d===10?((u===1?y:b)(We(f)),f.length=0):f.push(d)}a+=c}return(C(),A)[r>>>2>>>0]=a,0}function Gr(e){return e>>>0}function Kr(e,t){return mr(H(e>>>0).limits,t>>>0),1}function qr(e,t){return H(e>>>0).features.has(_r[t])}function Jr(e){return BigInt(H(e>>>0).size)}function Yr(e){return BigInt(H(e>>>0).usage)}function Xr(e,t){if(e>>>=0,t>>>=0){var n=fr(t+4);n={label:n,timestampWrites:t=(t=(C(),A)[t+12>>>2>>>0])===0?void 0:{querySet:H((C(),A)[t+4>>>2>>>0]),beginningOfPassWriteIndex:(C(),A)[t+8>>>2>>>0],endOfPassWriteIndex:(C(),A)[t+12>>>2>>>0]}}}return t=H(e),e=Oi(0),n=t.beginComputePass(n),ar[e>>>0]=n,e}function Zr(e,t,n,r,i,a){n=Te(n),i=Te(i),a=Te(a),H(e>>>0).copyBufferToBuffer(H(t>>>0),n,H(r>>>0),i,a)}function Qr(e){var t=H(e>>>0);return e=Ei(0),t=t.finish(),ar[e>>>0]=t,e}function $r(e,t,n,r,i,a){a=Te(a),H(e>>>0).resolveQuerySet(H(t>>>0),n,r,H(i>>>0),a)}function ei(e,t,n,r){H(e>>>0).dispatchWorkgroups(t,n,r)}function ti(e,t,n){n=Te(n),H(e>>>0).dispatchWorkgroupsIndirect(H(t>>>0),n)}function ni(e){H(e>>>0).end()}function ri(e,t,n,r,i){r>>>=0,i>>>=0,e=H(e>>>0),n=H(n>>>0),r==0?e.setBindGroup(t,n):e.setBindGroup(t,n,(C(),A),i>>>2,r)}function ii(e,t){H(e>>>0).setPipeline(H(t>>>0))}function ai(e,t,n){H(e>>>0).Ee(H(t>>>0),n)}function oi(e,t){var n=H(e>>>0);return e=Ti(0),t=n.getBindGroupLayout(t),ar[e>>>0]=t,e}function si(e,t){function n(e){var t=(C(),A)[e+8>>>2>>>0],n=(C(),A)[e+32>>>2>>>0],r=(C(),A)[e+36>>>2>>>0],i=0;return lr(e,{327681:e=>{i=(C(),A)[e+8>>>2>>>0]}}),t?((n=ir(e+24))==-1&&(n=void 0),t={buffer:H(t),offset:ir(e+16),size:n}):t=H(n||r||i),{binding:(C(),A)[e+4>>>2>>>0],resource:t}}e>>>=0,t={label:fr(4+(t>>>=0)),layout:H((C(),A)[t+12>>>2>>>0]),entries:function(e,t){for(var r=[],i=0;i>>2>>>0],(C(),A)[t+20>>>2>>>0])},e=H(e);var r=wi(0);return or(r,e.createBindGroup(t)),r}function ci(e,t){var n;return e>>>=0,(t>>>=0)&&(n={label:fr(t+4)}),t=H(e),e=Di(0),n=t.createCommandEncoder(n),ar[e>>>0]=n,e}function li(e,t){e>>>=0,t>>>=0,t={type:yr[(C(),k)[t+12>>>2>>>0]],count:(C(),A)[t+16>>>2>>>0]};var n=H(e);return e=ki(0),t=n.createQuerySet(t),ar[e>>>0]=t,e}function ui(e,t){e=H(e>>>0).adapterInfo,t>>>=0,(C(),A)[t+52>>>2>>>0]=e.subgroupMinSize,(C(),A)[t+56>>>2>>>0]=e.subgroupMaxSize;var n=e.vendor+e.architecture+e.device+e.description,r=Ot(n)+1,i=xi(r);return i&&Dt(n,i,r),n=i,r=Ot(e.vendor),ur(t+4,n,r),n+=r,r=Ot(e.architecture),ur(t+12,n,r),n+=r,r=Ot(e.device),ur(t+20,n,r),ur(t+28,n+r,Ot(e.description)),(C(),k)[t+36>>>2>>>0]=2,e=e.isFallbackAdapter?3:4,(C(),k)[t+40>>>2>>>0]=e,(C(),A)[t+44>>>2>>>0]=0,(C(),A)[t+48>>>2>>>0]=0,1}var di={"core-features-and-limits":1,"depth-clip-control":2,"depth32float-stencil8":3,"texture-compression-bc":4,"texture-compression-bc-sliced-3d":5,"texture-compression-etc2":6,"texture-compression-astc":7,"texture-compression-astc-sliced-3d":8,"timestamp-query":9,"indirect-first-instance":10,"shader-f16":11,"rg11b10ufloat-renderable":12,"bgra8unorm-storage":13,"float32-filterable":14,"float32-blendable":15,"clip-distances":16,"dual-source-blending":17,subgroups:18,"texture-formats-tier1":19,"texture-formats-tier2":20,"primitive-index":21,"texture-component-swizzle":22,"chromium-experimental-unorm16-texture-formats":327692,"chromium-experimental-multi-draw-indirect":327729};function fi(e,t){t>>>=0;var n=H(e>>>0);e=xi(4*n.features.size);var r=0,i=0;for(let t of n.features)0<=(n=di[t])&&((C(),k)[e+r>>>2>>>0]=n,r+=4,i++);(C(),A)[t+4>>>2>>>0]=e,(C(),A)[t>>>2>>>0]=i}function pi(e,t){return mr(H(e>>>0).limits,t>>>0),1}function mi(e,t){H(e>>>0).pushErrorScope(hr[t])}function U(e,t,n){t>>>=0,n>>>=0,e=H(e>>>0),t=Array.from((C(),k).subarray(n>>>2>>>0,n+4*t>>>2>>>0),e=>H(e)),e.submit(t)}function hi(e,t,n,r,i){n=Te(n),r>>>=0,i>>>=0,e=H(e>>>0),t=H(t>>>0),r=(C(),E).subarray(r>>>0,r+i>>>0),e.writeBuffer(t,n,r,0,i)}i||function(){for(var e=t.numThreads-1;e--;)be();ce.push(async()=>{var e=async function(){if(!i)return Promise.all(I.map(z))}();le++,await e,--le==0&&ue&&(e=ue,ue=null,e())})}(),i||(xe=new WebAssembly.Memory({initial:256,maximum:65536,shared:!0}),te()),t.wasmBinary&&(d=t.wasmBinary),t.stackSave=()=>G(),t.stackRestore=e=>W(e),t.stackAlloc=e=>Zi(e),t.setValue=function(e,t,n=`i8`){switch(n.endsWith(`*`)&&(n=`*`),n){case`i1`:case`i8`:(C(),T)[e>>>0]=t;break;case`i16`:(C(),D)[e>>>1>>>0]=t;break;case`i32`:(C(),k)[e>>>2>>>0]=t;break;case`i64`:(C(),M)[e>>>3>>>0]=BigInt(t);break;case`float`:(C(),j)[e>>>2>>>0]=t;break;case`double`:(C(),ee)[e>>>3>>>0]=t;break;case`*`:(C(),A)[e>>>2>>>0]=t;break;default:re(`invalid type for setValue: ${n}`)}},t.getValue=function(e,t=`i8`){switch(t.endsWith(`*`)&&(t=`*`),t){case`i1`:case`i8`:return(C(),T)[e>>>0];case`i16`:return(C(),D)[e>>>1>>>0];case`i32`:return(C(),k)[e>>>2>>>0];case`i64`:return(C(),M)[e>>>3>>>0];case`float`:return(C(),j)[e>>>2>>>0];case`double`:return(C(),ee)[e>>>3>>>0];case`*`:return(C(),A)[e>>>2>>>0];default:re(`invalid type for getValue: ${t}`)}},t.UTF8ToString=Ge,t.stringToUTF8=Dt,t.lengthBytesUTF8=Ot;var gi,_i,vi,yi,bi,xi,Si,Ci,wi,Ti,Ei,Di,Oi,ki,Ai,ji,Mi,Ni,Pi,Fi,Ii,Li,Ri,zi,Bi,Vi,Hi,Ui,Wi,Gi,Ki,qi,Ji,Yi,Xi,W,Zi,G,Qi,$i,ea,ta,na,ra,ia,aa,oa,sa,ca,K,la,ua,da,fa,pa,ma,ha,ga,_a,va,ya,ba,xa,Sa,Ca,wa,Ta,Ea,Da,Oa,ka,Aa,ja,Ma,Na,Pa,Fa,Ia,La,Ra,za,Ba,Va,Ha,Ua=[me,he,ze,Ke,qe,Je,Ye,Xe,Ze,Qe,$e,et,tt,nt,rt,it,In,Ln,Bn,Rr,zr,Br,Vr,Hr,Wr],Wa={925676:(e,n,r,i,a)=>{if(t===void 0||!t.Uc)return 1;if((e=Ge(Number(e>>>0))).startsWith(`./`)&&(e=e.substring(2)),!(e=t.Uc.get(e)))return 2;if(n=Number(n>>>0),r=Number(r>>>0),i=Number(i>>>0),n+r>e.byteLength)return 3;try{let o=e.subarray(n,n+r);switch(a){case 0:(C(),E).set(o,i>>>0);break;case 1:t.ad?t.ad(i,o):t.oe(i,o);break;default:return 4}return 0}catch{return 4}},926500:(e,n,r)=>{t.Sd(e,(C(),E).subarray(n>>>0,n+r>>>0))},926564:()=>t.me(),926606:e=>{t.jd(e)},926643:()=>typeof wasmOffsetConverter<`u`};function Ga(e,t,n,r){var i=G();try{return ua(e,t,n,r)}catch(e){if(W(i),e!==e+0)throw e;Ji(1,0)}}function Ka(e,t,n){var r=G();try{return ca(e,t,n)}catch(e){if(W(r),e!==e+0)throw e;Ji(1,0)}}function qa(e,t,n){var r=G();try{na(e,t,n)}catch(e){if(W(r),e!==e+0)throw e;Ji(1,0)}}function Ja(e,t){var n=G();try{return ra(e,t)}catch(e){if(W(n),e!==e+0)throw e;Ji(1,0)}}function Ya(e){var t=G();try{ia(e)}catch(e){if(W(t),e!==e+0)throw e;Ji(1,0)}}function Xa(e,t,n,r,i,a,o){var s=G();try{return sa(e,t,n,r,i,a,o)}catch(e){if(W(s),e!==e+0)throw e;Ji(1,0)}}function Za(e,t){var n=G();try{da(e,t)}catch(e){if(W(n),e!==e+0)throw e;Ji(1,0)}}function Qa(e,t,n,r,i,a){var o=G();try{aa(e,t,n,r,i,a)}catch(e){if(W(o),e!==e+0)throw e;Ji(1,0)}}function $a(e,t,n,r){var i=G();try{la(e,t,n,r)}catch(e){if(W(i),e!==e+0)throw e;Ji(1,0)}}function eo(e,t,n,r,i,a,o){var s=G();try{pa(e,t,n,r,i,a,o)}catch(e){if(W(s),e!==e+0)throw e;Ji(1,0)}}function to(e,t,n,r,i,a,o){var s=G();try{ma(e,t,n,r,i,a,o)}catch(e){if(W(s),e!==e+0)throw e;Ji(1,0)}}function no(e,t,n,r,i,a,o,s){var c=G();try{Ca(e,t,n,r,i,a,o,s)}catch(e){if(W(c),e!==e+0)throw e;Ji(1,0)}}function ro(e,t,n,r,i,a,o,s,c,l,u,d){var f=G();try{ha(e,t,n,r,i,a,o,s,c,l,u,d)}catch(e){if(W(f),e!==e+0)throw e;Ji(1,0)}}function io(e,t,n,r,i){var a=G();try{return fa(e,t,n,r,i)}catch(e){if(W(a),e!==e+0)throw e;Ji(1,0)}}function ao(e,t,n,r,i){var a=G();try{oa(e,t,n,r,i)}catch(e){if(W(a),e!==e+0)throw e;Ji(1,0)}}function oo(e,t,n,r,i,a,o,s){var c=G();try{K(e,t,n,r,i,a,o,s)}catch(e){if(W(c),e!==e+0)throw e;Ji(1,0)}}function so(e){var t=G();try{return wa(e)}catch(e){if(W(t),e!==e+0)throw e;Ji(1,0)}}function co(e,t,n){var r=G();try{return Ta(e,t,n)}catch(e){if(W(r),e!==e+0)throw e;Ji(1,0)}}function lo(e,t){var n=G();try{return La(e,t)}catch(e){if(W(n),e!==e+0)throw e;return Ji(1,0),0n}}function uo(e,t,n,r,i){var a=G();try{Ea(e,t,n,r,i)}catch(e){if(W(a),e!==e+0)throw e;Ji(1,0)}}function fo(e){var t=G();try{return ga(e)}catch(e){if(W(t),e!==e+0)throw e;return Ji(1,0),0n}}function po(e,t,n,r,i,a){var o=G();try{return xa(e,t,n,r,i,a)}catch(e){if(W(o),e!==e+0)throw e;Ji(1,0)}}function mo(e,t,n,r,i,a){var o=G();try{return Da(e,t,n,r,i,a)}catch(e){if(W(o),e!==e+0)throw e;Ji(1,0)}}function ho(e,t,n,r,i,a){var o=G();try{return Oa(e,t,n,r,i,a)}catch(e){if(W(o),e!==e+0)throw e;Ji(1,0)}}function go(e,t,n,r,i,a,o,s){var c=G();try{return Sa(e,t,n,r,i,a,o,s)}catch(e){if(W(c),e!==e+0)throw e;Ji(1,0)}}function _o(e,t,n,r,i){var a=G();try{return ka(e,t,n,r,i)}catch(e){if(W(a),e!==e+0)throw e;return Ji(1,0),0n}}function vo(e,t,n,r){var i=G();try{return Aa(e,t,n,r)}catch(e){if(W(i),e!==e+0)throw e;Ji(1,0)}}function yo(e,t,n,r){var i=G();try{return ja(e,t,n,r)}catch(e){if(W(i),e!==e+0)throw e;Ji(1,0)}}function bo(e,t,n,r,i,a,o,s,c,l,u,d){var f=G();try{return Ma(e,t,n,r,i,a,o,s,c,l,u,d)}catch(e){if(W(f),e!==e+0)throw e;Ji(1,0)}}function xo(e,t,n,r,i,a,o,s,c,l,u){var d=G();try{Na(e,t,n,r,i,a,o,s,c,l,u)}catch(e){if(W(d),e!==e+0)throw e;Ji(1,0)}}function So(e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h){var g=G();try{Pa(e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h)}catch(e){if(W(g),e!==e+0)throw e;Ji(1,0)}}function Co(e,t,n,r){var i=G();try{return Fa(e,t,n,r)}catch(e){if(W(i),e!==e+0)throw e;Ji(1,0)}}function wo(e,t,n,r,i){var a=G();try{return Ia(e,t,n,r,i)}catch(e){if(W(a),e!==e+0)throw e;Ji(1,0)}}function To(e,t,n){var r=G();try{return va(e,t,n)}catch(e){if(W(r),e!==e+0)throw e;return Ji(1,0),0n}}function Eo(e,t,n){var r=G();try{return _a(e,t,n)}catch(e){if(W(r),e!==e+0)throw e;Ji(1,0)}}function Do(e,t,n){var r=G();try{return ya(e,t,n)}catch(e){if(W(r),e!==e+0)throw e;Ji(1,0)}}function Oo(e,t,n,r){var i=G();try{ba(e,t,n,r)}catch(e){if(W(i),e!==e+0)throw e;Ji(1,0)}}function ko(){if(0{let n=new WeakMap,r,i,a=1;t.webgpuRegisterDevice=e=>{if(i!==void 0)throw Error(`another WebGPU EP inference session is being created.`);if(e){var t=n.get(e);if(!t){let r=((e,t=0)=>{var n=Mi(t);return t=ji(t,n),ar[n>>>0]=e.queue,ar[t>>>0]=e,t})(e,t=Ci(0));t=[a++,t,r],n.set(e,t)}return r=e,i=t[0],t}r=void 0,i=0};let o=new Map;t.webgpuOnCreateSession=t=>{if(i!==void 0){var n=i;if(i=void 0,t){let i=vi(n);o.set(t,i),n===0&&e(r??H(i))}r=void 0}},t.webgpuOnReleaseSession=e=>{o.delete(e)};let s=Symbol(`gpuBufferMetadata`);t.webgpuRegisterBuffer=(e,t,n)=>{if(n)return e[s]=[n,NaN],n;if(n=e[s])return n[1]++,n[0];if((t=o.get(t))===void 0)throw Error(`Invalid session handle passed to webgpuRegisterBuffer`);return t=((e,t=0)=>(e.mapState===`unmapped`||re(),t=Ai(t),ar[t>>>0]=e,t))(e,t),e[s]=[t,1],t},t.webgpuUnregisterBuffer=e=>{let t=e[s];if(!t)throw Error(`Buffer is not registered`);t[1]--,t[1]===0&&(Si(t[0]),delete e[s])},t.webgpuGetBuffer=e=>H(e),t.webgpuCreateDownloader=(e,t,n)=>{if((n=o.get(n))===void 0)throw Error(`Invalid session handle passed to webgpuRegisterBuffer`);let r=H(n),i=16*Math.ceil(Number(t)/16);return async()=>{let n=r.createBuffer({size:i,usage:9});try{let a=r.createCommandEncoder();return a.copyBufferToBuffer(e,0,n,0,i),r.queue.submit([a.finish()]),await n.mapAsync(GPUMapMode.READ),n.getMappedRange().slice(0,t)}finally{n.destroy()}}},t.ad=(e,t)=>{var n=t.buffer;let a=t.byteOffset,o=t.byteLength;if(t=16*Math.ceil(Number(o)/16),e=H(e),!r){var s=vi(i);r=H(s)}let c=(s=r.createBuffer({mappedAtCreation:!0,size:t,usage:6})).getMappedRange();new Uint8Array(c).set(new Uint8Array(n,a,o)),s.unmap(),(n=r.createCommandEncoder()).copyBufferToBuffer(s,0,e,0,t),r.queue.submit([n.finish()]),s.destroy()}},t.webnnInit=e=>{let n=e[0];[t.me,t.jd,t.webnnEnsureTensor,t.Sd,t.webnnDownloadTensor,t.le,t.webnnEnableTraceEvent]=e.slice(1),t.webnnReleaseTensorId=t.jd,t.webnnUploadTensor=t.Sd,t.webnnRegisterMLContext=t.le,t.webnnOnRunStart=e=>n.onRunStart(e),t.webnnOnRunEnd=n.onRunEnd.bind(n),t.webnnOnReleaseSession=e=>{n.onReleaseSession(e)},t.webnnCreateMLTensorDownloader=(e,t)=>n.createMLTensorDownloader(e,t),t.webnnRegisterMLTensor=(e,t,r,i)=>n.registerMLTensor(e,t,r,i),t.webnnCreateMLContext=e=>n.createMLContext(e),t.webnnRegisterMLConstant=(e,r,i,a,o,s)=>n.registerMLConstant(e,r,i,a,o,t.Uc,s),t.webnnRegisterGraphInput=n.registerGraphInput.bind(n),t.webnnIsGraphInput=n.isGraphInput.bind(n),t.webnnRegisterGraphOutput=n.registerGraphOutput.bind(n),t.webnnIsGraphOutput=n.isGraphOutput.bind(n),t.webnnCreateTemporaryTensor=n.createTemporaryTensor.bind(n),t.webnnIsGraphInputOutputTypeSupported=n.isGraphInputOutputTypeSupported.bind(n)},F?t:new Promise((e,t)=>{m=e,h=t})}var VC,HC,UC=AS(()=>{VC=BC,HC=globalThis.self?.name?.startsWith(`em-pthread`),HC&&BC()}),WC,GC,KC,qC,JC,YC,XC,ZC,QC,$C,ew,tw,nw,rw,iw=AS(()=>{NC(),WC=typeof location>`u`?void 0:location.origin,GC=import.meta.url>`file:`&&import.meta.url<`file;`,KC=()=>{if(GC){let e=URL;return new URL(new e(`ort.webgpu.bundle.min.mjs`,import.meta.url).href,WC).href}return import.meta.url},qC=KC(),JC=()=>{if(qC&&!qC.startsWith(`blob:`))return qC.substring(0,qC.lastIndexOf(`/`)+1)},YC=(e,t)=>{try{let n=t??qC;return(n?new URL(e,n):new URL(e)).origin===WC}catch{return!1}},XC=(e,t)=>{let n=t??qC;try{return(n?new URL(e,n):new URL(e)).href}catch{return}},ZC=(e,t)=>`${t??`./`}${e}`,QC=async e=>{let t=await(await fetch(e,{credentials:`same-origin`})).blob();return URL.createObjectURL(t)},$C=async e=>(await cb(async()=>{let{default:t}=await import(e);return{default:t}},[])).default,ew=(RC(),NS(PC)).default,tw=async()=>{if(!qC)throw Error(`Failed to load proxy worker: cannot determine the script source URL.`);if(YC(qC))return[void 0,ew()];let e=await QC(qC);return[e,ew(e)]},nw=(UC(),NS(zC)).default,rw=async(e,t,n,r)=>{let i=nw&&!(e||t);if(i)if(qC)i=YC(qC)||r&&!n;else if(r&&!n)i=!0;else throw Error(`cannot determine the script source URL.`);if(i)return[void 0,nw];{let r=`ort-wasm-simd-threaded.asyncify.mjs`,i=e??XC(r,t),a=n&&i&&!YC(i,t),o=a?await QC(i):i??ZC(r,t);return[a?o:void 0,await $C(o)]}}}),aw,ow,sw,cw,lw,uw,dw,fw,pw,mw=AS(()=>{iw(),ow=!1,sw=!1,cw=!1,lw=()=>{if(typeof SharedArrayBuffer>`u`)return!1;try{return typeof MessageChannel<`u`&&new MessageChannel().port1.postMessage(new SharedArrayBuffer(1)),WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,5,4,1,3,1,1,10,11,1,9,0,65,0,254,16,2,0,26,11]))}catch{return!1}},uw=()=>{try{return WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,10,30,1,28,0,65,0,253,15,253,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,253,186,1,26,11]))}catch{return!1}},dw=()=>{try{return WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,19,1,17,0,65,1,253,15,65,2,253,15,65,3,253,15,253,147,2,11]))}catch{return!1}},fw=async e=>{if(ow)return Promise.resolve();if(sw)throw Error(`multiple calls to 'initializeWebAssembly()' detected.`);if(cw)throw Error(`previous call to 'initializeWebAssembly()' failed.`);sw=!0;let t=e.initTimeout,n=e.numThreads;if(e.simd!==!1){if(e.simd===`relaxed`){if(!dw())throw Error(`Relaxed WebAssembly SIMD is not supported in the current environment.`)}else if(!uw())throw Error(`WebAssembly SIMD is not supported in the current environment.`)}let r=lw();n>1&&!r&&(typeof self<`u`&&!self.crossOriginIsolated&&console.warn(`env.wasm.numThreads is set to `+n+`, but this will not work unless you enable crossOriginIsolated mode. See https://web.dev/cross-origin-isolation-guide/ for more info.`),console.warn(`WebAssembly multi-threading is not supported in the current environment. Falling back to single-threading.`),e.numThreads=n=1);let i=e.wasmPaths,a=typeof i==`string`?i:void 0,o=i?.mjs,s=o?.href??o,c=i?.wasm,l=c?.href??c,u=e.wasmBinary,[d,f]=await rw(s,a,n>1,!!u||!!l),p=!1,m=[];if(t>0&&m.push(new Promise(e=>{setTimeout(()=>{p=!0,e()},t)})),m.push(new Promise((e,t)=>{let r={numThreads:n};if(u)r.wasmBinary=u,r.locateFile=e=>e;else if(l||a)r.locateFile=e=>l??a+e;else if(s&&s.indexOf(`blob:`)!==0)r.locateFile=e=>new URL(e,s).href;else if(d){let e=JC();e&&(r.locateFile=t=>e+t)}f(r).then(t=>{sw=!1,ow=!0,aw=t,e(),d&&URL.revokeObjectURL(d)},e=>{sw=!1,cw=!0,t(e)})})),await Promise.race(m),p)throw Error(`WebAssembly backend initializing failed due to timeout: ${t}ms`)},pw=()=>{if(ow&&aw)return aw;throw Error(`WebAssembly is not initialized yet.`)}}),hw,gw,_w,vw=AS(()=>{mw(),hw=(e,t)=>{let n=pw(),r=n.lengthBytesUTF8(e)+1,i=n._malloc(r);return n.stringToUTF8(e,i,r),t.push(i),i},gw=(e,t,n,r)=>{if(typeof e==`object`&&e){if(n.has(e))throw Error(`Circular reference in options`);n.add(e)}Object.entries(e).forEach(([e,i])=>{let a=t?t+e:e;if(typeof i==`object`)gw(i,a+`.`,n,r);else if(typeof i==`string`||typeof i==`number`)r(a,i.toString());else if(typeof i==`boolean`)r(a,i?`1`:`0`);else throw Error(`Can't handle extra config type: ${typeof i}`)})},_w=e=>{let t=pw(),n=t.stackSave();try{let n=t.PTR_SIZE,r=t.stackAlloc(2*n);t._OrtGetLastError(r,r+n);let i=Number(t.getValue(r,n===4?`i32`:`i64`)),a=t.getValue(r+n,`*`),o=a?t.UTF8ToString(a):``;throw Error(`${e} ERROR_CODE: ${i}, ERROR_MESSAGE: ${o}`)}finally{t.stackRestore(n)}}}),yw,bw=AS(()=>{mw(),vw(),yw=e=>{let t=pw(),n=0,r=[],i=e||{};try{if(e?.logSeverityLevel===void 0)i.logSeverityLevel=2;else if(typeof e.logSeverityLevel!=`number`||!Number.isInteger(e.logSeverityLevel)||e.logSeverityLevel<0||e.logSeverityLevel>4)throw Error(`log severity level is not valid: ${e.logSeverityLevel}`);if(e?.logVerbosityLevel===void 0)i.logVerbosityLevel=0;else if(typeof e.logVerbosityLevel!=`number`||!Number.isInteger(e.logVerbosityLevel))throw Error(`log verbosity level is not valid: ${e.logVerbosityLevel}`);e?.terminate===void 0&&(i.terminate=!1);let a=0;return e?.tag!==void 0&&(a=hw(e.tag,r)),n=t._OrtCreateRunOptions(i.logSeverityLevel,i.logVerbosityLevel,!!i.terminate,a),n===0&&_w(`Can't create run options.`),e?.extra!==void 0&&gw(e.extra,``,new WeakSet,(e,i)=>{let a=hw(e,r),o=hw(i,r);t._OrtAddRunConfigEntry(n,a,o)!==0&&_w(`Can't set a run config entry: ${e} - ${i}.`)}),[n,r]}catch(e){throw n!==0&&t._OrtReleaseRunOptions(n),r.forEach(e=>t._free(e)),e}}}),xw,Sw,Cw,ww,Tw,Ew,Dw,Ow=AS(()=>{mw(),vw(),xw=e=>{switch(e){case`disabled`:return 0;case`basic`:return 1;case`extended`:return 2;case`layout`:return 3;case`all`:return 99;default:throw Error(`unsupported graph optimization level: ${e}`)}},Sw=e=>{switch(e){case`sequential`:return 0;case`parallel`:return 1;default:throw Error(`unsupported execution mode: ${e}`)}},Cw=e=>{e.extra||={},e.extra.session||(e.extra.session={});let t=e.extra.session;t.use_ort_model_bytes_directly||=`1`,e.executionProviders&&e.executionProviders.some(e=>(typeof e==`string`?e:e.name)===`webgpu`)&&(e.enableMemPattern=!1)},ww=(e,t,n,r)=>{let i=hw(t,r),a=hw(n,r);pw()._OrtAddSessionConfigEntry(e,i,a)!==0&&_w(`Can't set a session config entry: ${t} - ${n}.`)},Tw=(e,t,n,r)=>{let i=hw(t,r),a=hw(n,r);e.push([i,a])},Ew=async(e,t,n)=>{let r=t.executionProviders;for(let i of r){let r=typeof i==`string`?i:i.name,a=[];switch(r){case`webnn`:if(r=`WEBNN`,typeof i!=`string`){let t=i?.deviceType;t&&ww(e,`deviceType`,t,n)}break;case`webgpu`:{r=`WebGPU`;let e;if(typeof i!=`string`){let r=i;if(r.device)if(typeof GPUDevice<`u`&&r.device instanceof GPUDevice)e=r.device;else throw Error(`Invalid GPU device set in WebGPU EP options.`);let{enableGraphCapture:o}=t;if(typeof o==`boolean`&&o&&Tw(a,`enableGraphCapture`,`1`,n),typeof r.preferredLayout==`string`&&Tw(a,`preferredLayout`,r.preferredLayout,n),r.forceCpuNodeNames){let e=Array.isArray(r.forceCpuNodeNames)?r.forceCpuNodeNames:[r.forceCpuNodeNames];Tw(a,`forceCpuNodeNames`,e.join(` +`),n)}r.validationMode&&Tw(a,`validationMode`,r.validationMode,n)}let o=pw().webgpuRegisterDevice(e);if(o){let[e,t,r]=o;Tw(a,`deviceId`,e.toString(),n),Tw(a,`webgpuInstance`,t.toString(),n),Tw(a,`webgpuDevice`,r.toString(),n)}}break;case`wasm`:case`cpu`:continue;default:throw Error(`not supported execution provider: ${r}`)}let o=hw(r,n),s=a.length,c=0,l=0;if(s>0){c=pw()._malloc(s*pw().PTR_SIZE),n.push(c),l=pw()._malloc(s*pw().PTR_SIZE),n.push(l);for(let e=0;e{let t=pw(),n=0,r=[],i=e||{};Cw(i);try{let e=xw(i.graphOptimizationLevel??`all`),a=Sw(i.executionMode??`sequential`),o=typeof i.logId==`string`?hw(i.logId,r):0,s=i.logSeverityLevel??2;if(!Number.isInteger(s)||s<0||s>4)throw Error(`log severity level is not valid: ${s}`);let c=i.logVerbosityLevel??0;if(!Number.isInteger(c)||c<0||c>4)throw Error(`log verbosity level is not valid: ${c}`);let l=typeof i.optimizedModelFilePath==`string`?hw(i.optimizedModelFilePath,r):0;if(n=t._OrtCreateSessionOptions(e,!!i.enableCpuMemArena,!!i.enableMemPattern,a,!!i.enableProfiling,0,o,s,c,l),n===0&&_w(`Can't create session options.`),i.executionProviders&&await Ew(n,i,r),i.enableGraphCapture!==void 0){if(typeof i.enableGraphCapture!=`boolean`)throw Error(`enableGraphCapture must be a boolean value: ${i.enableGraphCapture}`);ww(n,`enableGraphCapture`,i.enableGraphCapture.toString(),r)}if(i.freeDimensionOverrides)for(let[e,a]of Object.entries(i.freeDimensionOverrides)){if(typeof e!=`string`)throw Error(`free dimension override name must be a string: ${e}`);if(typeof a!=`number`||!Number.isInteger(a)||a<0)throw Error(`free dimension override value must be a non-negative integer: ${a}`);let i=hw(e,r);t._OrtAddFreeDimensionOverride(n,i,a)!==0&&_w(`Can't set a free dimension override: ${e} - ${a}.`)}return i.extra!==void 0&&gw(i.extra,``,new WeakSet,(e,t)=>{ww(n,e,t,r)}),[n,r]}catch(e){throw n!==0&&t._OrtReleaseSessionOptions(n)!==0&&_w(`Can't release session options.`),r.forEach(e=>t._free(e)),e}}}),kw,Aw,jw,Mw,Nw,Pw,Fw,Iw,Lw=AS(()=>{kw=e=>{switch(e){case`int8`:return 3;case`uint8`:return 2;case`bool`:return 9;case`int16`:return 5;case`uint16`:return 4;case`int32`:return 6;case`uint32`:return 12;case`float16`:return 10;case`float32`:return 1;case`float64`:return 11;case`string`:return 8;case`int64`:return 7;case`uint64`:return 13;case`int4`:return 22;case`uint4`:return 21;default:throw Error(`unsupported data type: ${e}`)}},Aw=e=>{switch(e){case 3:return`int8`;case 2:return`uint8`;case 9:return`bool`;case 5:return`int16`;case 4:return`uint16`;case 6:return`int32`;case 12:return`uint32`;case 10:return`float16`;case 1:return`float32`;case 11:return`float64`;case 8:return`string`;case 7:return`int64`;case 13:return`uint64`;case 22:return`int4`;case 21:return`uint4`;default:throw Error(`unsupported data type: ${e}`)}},jw=(e,t)=>{let n=[-1,4,1,1,2,2,4,8,-1,1,2,8,4,8,-1,-1,-1,-1,-1,-1,-1,.5,.5][e],r=typeof t==`number`?t:t.reduce((e,t)=>e*t,1);return n>0?Math.ceil(r*n):void 0},Mw=e=>{switch(e){case`float16`:return typeof Float16Array<`u`&&Float16Array.from?Float16Array:Uint16Array;case`float32`:return Float32Array;case`uint8`:return Uint8Array;case`int8`:return Int8Array;case`uint16`:return Uint16Array;case`int16`:return Int16Array;case`int32`:return Int32Array;case`bool`:return Uint8Array;case`float64`:return Float64Array;case`uint32`:return Uint32Array;case`int64`:return BigInt64Array;case`uint64`:return BigUint64Array;default:throw Error(`unsupported type: ${e}`)}},Nw=e=>{switch(e){case`verbose`:return 0;case`info`:return 1;case`warning`:return 2;case`error`:return 3;case`fatal`:return 4;default:throw Error(`unsupported logging level: ${e}`)}},Pw=e=>e===`float32`||e===`float16`||e===`int32`||e===`int64`||e===`uint32`||e===`uint8`||e===`bool`||e===`uint4`||e===`int4`,Fw=e=>e===`float32`||e===`float16`||e===`int32`||e===`int64`||e===`uint32`||e===`uint64`||e===`int8`||e===`uint8`||e===`bool`||e===`uint4`||e===`int4`,Iw=e=>{switch(e){case`none`:return 0;case`cpu`:return 1;case`cpu-pinned`:return 2;case`texture`:return 3;case`gpu-buffer`:return 4;case`ml-tensor`:return 5;default:throw Error(`unsupported data location: ${e}`)}}}),Rw,zw=AS(()=>{NC(),Rw=async e=>{if(typeof e==`string`){let t=await fetch(e);if(!t.ok)throw Error(`failed to load external data file: ${e}`);let n=t.headers.get(`Content-Length`),r=n?parseInt(n,10):0;if(r<1073741824)return new Uint8Array(await t.arrayBuffer());{if(!t.body)throw Error(`failed to load external data file: ${e}, no response body.`);let n=t.body.getReader(),i;try{i=new ArrayBuffer(r)}catch(e){if(e instanceof RangeError){let e=Math.ceil(r/65536);i=new WebAssembly.Memory({initial:e,maximum:e}).buffer}else throw e}let a=0;for(;;){let{done:e,value:t}=await n.read();if(e)break;let r=t.byteLength;new Uint8Array(i,a,r).set(t),a+=r}return new Uint8Array(i,0,r)}}else return e instanceof Blob?new Uint8Array(await e.arrayBuffer()):e instanceof Uint8Array?e:new Uint8Array(e)}}),Bw,Vw=AS(()=>{Lw(),Bw=(e,t)=>new(Mw(t))(e)}),Hw,Uw,Ww,Gw,Kw,qw,Jw,Yw=AS(()=>{Lw(),Hw=[`V`,`I`,`W`,`E`,`F`],Uw=(e,t)=>{console.log(`[${Hw[e]},${new Date().toISOString()}]${t}`)},Kw=(e,t)=>{Ww=e,Gw=t},qw=(e,t)=>{let n=Nw(e);n>=Nw(Ww)&&Uw(n,typeof t==`function`?t():t)},Jw=(...e)=>{Gw&&qw(...e)}}),Xw,Zw,Qw,$w,eT,tT,nT,rT,iT,aT,oT,sT=AS(()=>{Lw(),Yw(),Xw=new Map([[`float32`,32],[`float16`,16],[`int32`,32],[`uint32`,32],[`int64`,64],[`uint64`,64],[`int8`,8],[`uint8`,8],[`int4`,4],[`uint4`,4]]),Zw=(e,t)=>{if(t===`int32`)return e;let n=Xw.get(t);if(!n)throw Error(`WebNN backend does not support data type: ${t}`);let r=n/8;if(e.byteLength%r!==0)throw Error(`Invalid Uint8Array length - must be a multiple of ${r}.`);let i=e.byteLength/r,a=new(Mw(t))(e.buffer,e.byteOffset,i);switch(t){case`int64`:case`uint64`:{let e=new Int32Array(i);for(let t=0;t2147483647n||n<-2147483648n)throw Error(`Can not convert int64 data to int32 - value out of range.`);e[t]=Number(n)}return new Uint8Array(e.buffer)}case`int8`:case`uint8`:case`uint32`:{if(t===`uint32`&&a.some(e=>e>2147483647))throw Error(`Can not convert uint32 data to int32 - value out of range.`);let e=Int32Array.from(a,Number);return new Uint8Array(e.buffer)}default:throw Error(`Unsupported data conversion from ${t} to 'int32'`)}},Qw=(e,t)=>{if(t===`int32`)return e;if(e.byteLength%4!=0)throw Error(`Invalid Uint8Array length - must be a multiple of 4 (int32).`);let n=e.byteLength/4,r=new Int32Array(e.buffer,e.byteOffset,n);switch(t){case`int64`:{let e=BigInt64Array.from(r,BigInt);return new Uint8Array(e.buffer)}case`uint64`:{if(r.some(e=>e<0))throw Error(`Can not convert int32 data to uin64 - negative value found.`);let e=BigUint64Array.from(r,BigInt);return new Uint8Array(e.buffer)}case`int8`:{if(r.some(e=>e<-128||e>127))throw Error(`Can not convert int32 data to int8 - value out of range.`);let e=Int8Array.from(r,Number);return new Uint8Array(e.buffer)}case`uint8`:if(r.some(e=>e<0||e>255))throw Error(`Can not convert int32 data to uint8 - value out of range.`);return Uint8Array.from(r,Number);case`uint32`:{if(r.some(e=>e<0))throw Error(`Can not convert int32 data to uint32 - negative value found.`);let e=Uint32Array.from(r,Number);return new Uint8Array(e.buffer)}default:throw Error(`Unsupported data conversion from 'int32' to ${t}`)}},$w=1,eT=()=>$w++,tT=new Map([[`int8`,`int32`],[`uint8`,`int32`],[`uint32`,`int32`],[`int64`,`int32`]]),nT=(e,t)=>{let n=Xw.get(e);if(!n)throw Error(`WebNN backend does not support data type: ${e}`);return t.length>0?Math.ceil(t.reduce((e,t)=>e*t)*n/8):0},rT=class{constructor(e){this.isDataConverted=!1;let{sessionId:t,context:n,tensor:r,dataType:i,shape:a,fallbackDataType:o}=e;this.sessionId=t,this.mlContext=n,this.mlTensor=r,this.dataType=i,this.tensorShape=a,this.fallbackDataType=o}get tensor(){return this.mlTensor}get type(){return this.dataType}get fallbackType(){return this.fallbackDataType}get shape(){return this.tensorShape}get byteLength(){return nT(this.dataType,this.tensorShape)}destroy(){Jw(`verbose`,()=>`[WebNN] TensorWrapper.destroy`),this.mlTensor.destroy()}write(e){this.mlContext.writeTensor(this.mlTensor,e)}async read(e){if(this.fallbackDataType){let t=await this.mlContext.readTensor(this.mlTensor),n=Qw(new Uint8Array(t),this.dataType);if(e){(e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)).set(n);return}else return n.buffer}else return e?this.mlContext.readTensor(this.mlTensor,e):this.mlContext.readTensor(this.mlTensor)}canReuseTensor(e,t,n){return this.mlContext===e&&this.dataType===t&&this.tensorShape.length===n.length&&this.tensorShape.every((e,t)=>e===n[t])}setIsDataConverted(e){this.isDataConverted=e}},iT=class{constructor(e,t){this.tensorManager=e,this.wrapper=t}get tensorWrapper(){return this.wrapper}releaseTensor(){this.tensorWrapper&&(this.tensorManager.releaseTensor(this.tensorWrapper),this.wrapper=void 0)}async ensureTensor(e,t,n,r){let i=this.tensorManager.getMLContext(e),a=this.tensorManager.getMLOpSupportLimits(e),o;if(!a?.input.dataTypes.includes(t)){if(o=tT.get(t),!o||a?.input.dataTypes.includes(o))throw Error(`WebNN backend does not support data type: ${t}`);Jw(`verbose`,()=>`[WebNN] TensorIdTracker.ensureTensor: fallback dataType from ${t} to ${o}`)}if(this.wrapper){if(this.wrapper.canReuseTensor(i,t,n))return this.wrapper.tensor;if(r){if(this.wrapper.byteLength!==nT(t,n))throw Error(`Unable to copy data to tensor with different size.`);this.activeUpload=new Uint8Array(await this.wrapper.read())}this.tensorManager.releaseTensor(this.wrapper)}let s=typeof MLTensorUsage>`u`?void 0:MLTensorUsage.READ|MLTensorUsage.WRITE;return this.wrapper=await this.tensorManager.getCachedTensor(e,t,n,s,!0,!0,o),r&&this.activeUpload&&(this.wrapper.write(this.activeUpload),this.activeUpload=void 0),this.wrapper.tensor}upload(e){let t=e;if(this.wrapper){if(this.wrapper.fallbackType)if(this.wrapper.fallbackType===`int32`)t=Zw(e,this.wrapper.type),this.wrapper.setIsDataConverted(!0);else throw Error(`Unsupported fallback data type: ${this.wrapper.fallbackType}`);if(e.byteLength===this.wrapper.byteLength){this.wrapper.write(t);return}else Jw(`verbose`,()=>`Data size does not match tensor size. Releasing tensor.`),this.releaseTensor()}this.activeUpload?this.activeUpload.set(t):this.activeUpload=new Uint8Array(t)}async download(e){if(this.activeUpload){let t=this.wrapper?.isDataConverted?Qw(this.activeUpload,this.wrapper?.type):this.activeUpload;if(e){e instanceof ArrayBuffer?new Uint8Array(e).set(t):new Uint8Array(e.buffer,e.byteOffset,e.byteLength).set(t);return}else return t.buffer}if(!this.wrapper)throw Error(`Tensor has not been created.`);return e?this.wrapper.read(e):this.wrapper.read()}},aT=class{constructor(e){this.backend=e,this.tensorTrackersById=new Map,this.freeTensors=[],this.externalTensors=new Set}getMLContext(e){let t=this.backend.getMLContext(e);if(!t)throw Error(`MLContext not found for session.`);return t}getMLOpSupportLimits(e){return this.backend.getMLOpSupportLimits(e)}reserveTensorId(){let e=eT();return this.tensorTrackersById.set(e,new iT(this)),e}releaseTensorId(e){let t=this.tensorTrackersById.get(e);t&&(this.tensorTrackersById.delete(e),t.tensorWrapper&&this.releaseTensor(t.tensorWrapper))}async ensureTensor(e,t,n,r,i){Jw(`verbose`,()=>`[WebNN] TensorManager.ensureTensor {tensorId: ${t}, dataType: ${n}, shape: ${r}, copyOld: ${i}}`);let a=this.tensorTrackersById.get(t);if(!a)throw Error(`Tensor not found.`);return a.ensureTensor(e,n,r,i)}upload(e,t){let n=this.tensorTrackersById.get(e);if(!n)throw Error(`Tensor not found.`);n.upload(t)}async download(e,t){Jw(`verbose`,()=>`[WebNN] TensorManager.download {tensorId: ${e}, dstBuffer: ${t?.byteLength}}`);let n=this.tensorTrackersById.get(e);if(!n)throw Error(`Tensor not found.`);return n.download(t)}releaseTensorsForSession(e){for(let t of this.freeTensors)t.sessionId===e&&t.destroy();this.freeTensors=this.freeTensors.filter(t=>t.sessionId!==e)}registerTensor(e,t,n,r){let i=this.getMLContext(e),a=eT(),o=new rT({sessionId:e,context:i,tensor:t,dataType:n,shape:r});return this.tensorTrackersById.set(a,new iT(this,o)),this.externalTensors.add(o),a}async getCachedTensor(e,t,n,r,i,a,o){let s=this.getMLContext(e);for(let[r,i]of this.freeTensors.entries())if(i.canReuseTensor(s,t,n)){Jw(`verbose`,()=>`[WebNN] Reusing tensor {dataType: ${t}, ${o?`fallbackDataType: ${o},`:``} shape: ${n}`);let i=this.freeTensors.splice(r,1)[0];return i.sessionId=e,i}Jw(`verbose`,()=>`[WebNN] MLContext.createTensor {dataType: ${t}, ${o?`fallbackDataType: ${o},`:``} shape: ${n}}`);let c=await s.createTensor({dataType:o??t,shape:n,dimensions:n,usage:r,writable:i,readable:a});return new rT({sessionId:e,context:s,tensor:c,dataType:t,shape:n,fallbackDataType:o})}releaseTensor(e){this.externalTensors.has(e)&&this.externalTensors.delete(e),this.freeTensors.push(e)}},oT=(...e)=>new aT(...e)}),cT={};jS(cT,{WebNNBackend:()=>dT});var lT,uT,dT,fT=AS(()=>{Lw(),mw(),Vw(),sT(),Yw(),lT=new Map([[1,`float32`],[10,`float16`],[6,`int32`],[12,`uint32`],[7,`int64`],[13,`uint64`],[22,`int4`],[21,`uint4`],[3,`int8`],[2,`uint8`],[9,`uint8`]]),uT=(e,t)=>{if(e===t)return!0;if(e===void 0||t===void 0)return!1;let n=Object.keys(e).sort(),r=Object.keys(t).sort();return n.length===r.length&&n.every((n,i)=>n===r[i]&&e[n]===t[n])},dT=class{constructor(e){this.tensorManager=oT(this),this.mlContextBySessionId=new Map,this.sessionIdsByMLContext=new Map,this.mlContextCache=[],this.sessionGraphInputs=new Map,this.sessionGraphOutputs=new Map,this.temporaryGraphInputs=[],this.temporaryGraphOutputs=[],this.temporarySessionTensorIds=new Map,this.mlOpSupportLimitsBySessionId=new Map,Kw(e.logLevel,!!e.debug)}get currentSessionId(){if(this.activeSessionId===void 0)throw Error(`No active session`);return this.activeSessionId}onRunStart(e){Jw(`verbose`,()=>`[WebNN] onRunStart {sessionId: ${e}}`),this.activeSessionId=e}onRunEnd(e){Jw(`verbose`,()=>`[WebNN] onRunEnd {sessionId: ${e}}`);let t=this.temporarySessionTensorIds.get(e);if(t){for(let e of t)Jw(`verbose`,()=>`[WebNN] releasing temporary tensor {tensorId: ${e}}`),this.tensorManager.releaseTensorId(e);this.temporarySessionTensorIds.delete(e),this.activeSessionId=void 0}}async createMLContext(e){if(e instanceof GPUDevice){let t=this.mlContextCache.findIndex(t=>t.gpuDevice===e);if(t!==-1)return this.mlContextCache[t].mlContext;{let t=await navigator.ml.createContext(e);return this.mlContextCache.push({gpuDevice:e,mlContext:t}),t}}else if(e===void 0){let e=this.mlContextCache.findIndex(e=>e.options===void 0&&e.gpuDevice===void 0);if(e!==-1)return this.mlContextCache[e].mlContext;{let e=await navigator.ml.createContext();return this.mlContextCache.push({mlContext:e}),e}}let t=this.mlContextCache.findIndex(t=>uT(t.options,e));if(t!==-1)return this.mlContextCache[t].mlContext;{let t=await navigator.ml.createContext(e);return this.mlContextCache.push({options:e,mlContext:t}),t}}registerMLContext(e,t){this.mlContextBySessionId.set(e,t);let n=this.sessionIdsByMLContext.get(t);n||(n=new Set,this.sessionIdsByMLContext.set(t,n)),n.add(e),this.mlOpSupportLimitsBySessionId.has(e)||this.mlOpSupportLimitsBySessionId.set(e,t.opSupportLimits()),this.temporaryGraphInputs.length>0&&(this.sessionGraphInputs.set(e,this.temporaryGraphInputs),this.temporaryGraphInputs=[]),this.temporaryGraphOutputs.length>0&&(this.sessionGraphOutputs.set(e,this.temporaryGraphOutputs),this.temporaryGraphOutputs=[])}onReleaseSession(e){this.sessionGraphInputs.delete(e),this.sessionGraphOutputs.delete(e);let t=this.mlContextBySessionId.get(e);if(!t)return;this.tensorManager.releaseTensorsForSession(e),this.mlContextBySessionId.delete(e),this.mlOpSupportLimitsBySessionId.delete(e);let n=this.sessionIdsByMLContext.get(t);if(n.delete(e),n.size===0){this.sessionIdsByMLContext.delete(t);let e=this.mlContextCache.findIndex(e=>e.mlContext===t);e!==-1&&this.mlContextCache.splice(e,1)}}getMLContext(e){return this.mlContextBySessionId.get(e)}getMLOpSupportLimits(e){return this.mlOpSupportLimitsBySessionId.get(e)}reserveTensorId(){return this.tensorManager.reserveTensorId()}releaseTensorId(e){Jw(`verbose`,()=>`[WebNN] releaseTensorId {tensorId: ${e}}`),this.tensorManager.releaseTensorId(e)}async ensureTensor(e,t,n,r,i){let a=lT.get(n);if(!a)throw Error(`Unsupported ONNX data type: ${n}`);return this.tensorManager.ensureTensor(e??this.currentSessionId,t,a,r,i)}async createTemporaryTensor(e,t,n){Jw(`verbose`,()=>`[WebNN] createTemporaryTensor {onnxDataType: ${t}, shape: ${n}}`);let r=lT.get(t);if(!r)throw Error(`Unsupported ONNX data type: ${t}`);let i=this.tensorManager.reserveTensorId();await this.tensorManager.ensureTensor(e,i,r,n,!1);let a=this.temporarySessionTensorIds.get(e);return a?a.push(i):this.temporarySessionTensorIds.set(e,[i]),i}uploadTensor(e,t){if(!pw().shouldTransferToMLTensor)throw Error(`Trying to upload to a MLTensor while shouldTransferToMLTensor is false`);Jw(`verbose`,()=>`[WebNN] uploadTensor {tensorId: ${e}, data: ${t.byteLength}}`),this.tensorManager.upload(e,t)}async downloadTensor(e,t){return this.tensorManager.download(e,t)}createMLTensorDownloader(e,t){return async()=>{let n=await this.tensorManager.download(e);return Bw(n,t)}}registerMLTensor(e,t,n,r){let i=lT.get(n);if(!i)throw Error(`Unsupported ONNX data type: ${n}`);let a=this.tensorManager.registerTensor(e,t,i,r);return Jw(`verbose`,()=>`[WebNN] registerMLTensor {tensor: ${t}, dataType: ${i}, dimensions: ${r}} -> {tensorId: ${a}}`),a}registerMLConstant(e,t,n,r,i,a,o=!1){if(!a)throw Error(`External mounted files are not available.`);let s=e;e.startsWith(`./`)&&(s=e.substring(2));let c=a.get(s);if(!c)throw Error(`File with name ${s} not found in preloaded files.`);if(t+n>c.byteLength)throw Error(`Out of bounds: data offset and length exceed the external file data size.`);let l=c.slice(t,t+n).buffer,u;switch(i.dataType){case`float32`:u=new Float32Array(l);break;case`float16`:u=typeof Float16Array<`u`&&Float16Array.from?new Float16Array(l):new Uint16Array(l);break;case`int32`:u=new Int32Array(l);break;case`uint32`:u=new Uint32Array(l);break;case`int64`:if(o){let e=Zw(new Uint8Array(l),`int64`);u=new Int32Array(e.buffer),i.dataType=`int32`}else u=new BigInt64Array(l);break;case`uint64`:u=new BigUint64Array(l);break;case`int8`:u=new Int8Array(l);break;case`int4`:case`uint4`:case`uint8`:u=new Uint8Array(l);break;default:throw Error(`Unsupported data type: ${i.dataType} in creating WebNN Constant from external data.`)}return Jw(`verbose`,()=>`[WebNN] registerMLConstant {dataType: ${i.dataType}, shape: ${i.shape}}} ${o?`(Note: it was int64 data type and registered to int32 as workaround)`:``}`),r.constant(i,u)}registerGraphInput(e){this.temporaryGraphInputs.push(e)}registerGraphOutput(e){this.temporaryGraphOutputs.push(e)}isGraphInput(e,t){let n=this.sessionGraphInputs.get(e);return n?n.includes(t):!1}isGraphOutput(e,t){let n=this.sessionGraphOutputs.get(e);return n?n.includes(t):!1}isGraphInputOutputTypeSupported(e,t,n=!0){let r=lT.get(kw(t)),i=this.mlOpSupportLimitsBySessionId.get(e);return typeof r>`u`?!1:n?!!i?.input.dataTypes.includes(r):!!i?.output.dataTypes.includes(r)}flush(){}}}),pT,mT,hT,gT,_T,vT,yT,bT,xT,ST,CT,wT,TT,ET=AS(()=>{MC(),bw(),Ow(),Lw(),mw(),vw(),zw(),pT=(e,t)=>{pw()._OrtInit(e,t)!==0&&_w(`Can't initialize onnxruntime.`)},mT=async e=>{pT(e.wasm.numThreads,Nw(e.logLevel))},hT=async(e,t)=>{pw().asyncInit?.();let n=e.webgpu.adapter;if(t===`webgpu`){if(typeof navigator>`u`||!navigator.gpu)throw Error(`WebGPU is not supported in current environment`);if(n){if(typeof n.limits!=`object`||typeof n.features!=`object`||typeof n.requestDevice!=`function`)throw Error("Invalid GPU adapter set in `env.webgpu.adapter`. It must be a GPUAdapter object.")}else{let t=e.webgpu.powerPreference;if(t!==void 0&&t!==`low-power`&&t!==`high-performance`)throw Error(`Invalid powerPreference setting: "${t}"`);let r=e.webgpu.forceFallbackAdapter;if(r!==void 0&&typeof r!=`boolean`)throw Error(`Invalid forceFallbackAdapter setting: "${r}"`);if(n=await navigator.gpu.requestAdapter({powerPreference:t,forceFallbackAdapter:r}),!n)throw Error(`Failed to get GPU adapter. You may need to enable flag "--enable-unsafe-webgpu" if you are using Chrome.`)}}if(t===`webnn`&&(typeof navigator>`u`||!navigator.ml))throw Error(`WebNN is not supported in current environment`);if(t===`webgpu`&&pw().webgpuInit(t=>{e.webgpu.device=t}),t===`webnn`){let t=new(fT(),NS(cT)).WebNNBackend(e);pw().webnnInit([t,()=>t.reserveTensorId(),e=>t.releaseTensorId(e),async(e,n,r,i,a)=>t.ensureTensor(e,n,r,i,a),(e,n)=>{t.uploadTensor(e,n)},async(e,n)=>t.downloadTensor(e,n),(e,n)=>t.registerMLContext(e,n),!!e.trace])}},gT=new Map,_T=e=>{let t=pw(),n=t.stackSave();try{let n=t.PTR_SIZE,r=t.stackAlloc(2*n);t._OrtGetInputOutputCount(e,r,r+n)!==0&&_w(`Can't get session input/output count.`);let i=n===4?`i32`:`i64`;return[Number(t.getValue(r,i)),Number(t.getValue(r+n,i))]}finally{t.stackRestore(n)}},vT=(e,t)=>{let n=pw(),r=n.stackSave(),i=0;try{let r=n.PTR_SIZE,a=n.stackAlloc(2*r);n._OrtGetInputOutputMetadata(e,t,a,a+r)!==0&&_w(`Can't get session input/output metadata.`);let o=Number(n.getValue(a,`*`));i=Number(n.getValue(a+r,`*`));let s=n.HEAP32[i/4];if(s===0)return[o,0];let c=n.HEAPU32[i/4+1],l=[];for(let e=0;e{let t=pw(),n=t._malloc(e.byteLength);if(n===0)throw Error(`Can't create a session. failed to allocate a buffer of size ${e.byteLength}.`);return t.HEAPU8.set(e,n),[n,e.byteLength]},bT=async(e,t)=>{let n,r,i=pw();Array.isArray(e)?[n,r]=e:e.buffer===i.HEAPU8.buffer?[n,r]=[e.byteOffset,e.byteLength]:[n,r]=yT(e);let a=0,o=0,s=0,c=[],l=[],u=[];try{if([o,c]=await Dw(t),t?.externalData&&i.mountExternalData){let e=[];for(let n of t.externalData){let t=typeof n==`string`?n:n.path;e.push(Rw(typeof n==`string`?n:n.data).then(e=>{i.mountExternalData(t,e)}))}await Promise.all(e)}for(let e of t?.executionProviders??[])if((typeof e==`string`?e:e.name)===`webnn`){if(i.shouldTransferToMLTensor=!1,typeof e!=`string`){let t=e,n=t?.context,r=t?.gpuDevice,a=t?.deviceType,o=t?.powerPreference;n?i.currentContext=n:r?i.currentContext=await i.webnnCreateMLContext(r):i.currentContext=await i.webnnCreateMLContext({deviceType:a,powerPreference:o})}else i.currentContext=await i.webnnCreateMLContext();break}a=await i._OrtCreateSession(n,r,o),i.webgpuOnCreateSession?.(a),a===0&&_w(`Can't create a session.`),i.jsepOnCreateSession?.(),i.currentContext&&(i.webnnRegisterMLContext(a,i.currentContext),i.currentContext=void 0,i.shouldTransferToMLTensor=!0);let[e,d]=_T(a),f=!!t?.enableGraphCapture,p=[],m=[],h=[],g=[],_=[];for(let t=0;te===`gpu-buffer`||e===`ml-tensor`||e===`ml-tensor-cpu-output`)&&(s=i._OrtCreateBinding(a),s===0&&_w(`Can't create IO binding.`),v={handle:s,outputPreferredLocations:_,outputPreferredLocationsEncoded:_.map(e=>e===`ml-tensor-cpu-output`?`ml-tensor`:e).map(e=>Iw(e))}),gT.set(a,[a,l,u,v,f,!1]),[a,p,m,h,g]}catch(e){throw l.forEach(e=>i._OrtFree(e)),u.forEach(e=>i._OrtFree(e)),s!==0&&i._OrtReleaseBinding(s)!==0&&_w(`Can't release IO binding.`),a!==0&&i._OrtReleaseSession(a)!==0&&_w(`Can't release session.`),e}finally{i._free(n),o!==0&&i._OrtReleaseSessionOptions(o)!==0&&_w(`Can't release session options.`),c.forEach(e=>i._free(e)),i.unmountExternalData?.()}},xT=e=>{let t=pw(),n=gT.get(e);if(!n)throw Error(`cannot release session. invalid session id: ${e}`);let[r,i,a,o,s]=n;o&&(s&&t._OrtClearBoundOutputs(o.handle)!==0&&_w(`Can't clear bound outputs.`),t._OrtReleaseBinding(o.handle)!==0&&_w(`Can't release IO binding.`)),t.jsepOnReleaseSession?.(e),t.webnnOnReleaseSession?.(e),t.webgpuOnReleaseSession?.(e),i.forEach(e=>t._OrtFree(e)),a.forEach(e=>t._OrtFree(e)),t._OrtReleaseSession(r)!==0&&_w(`Can't release session.`),gT.delete(e)},ST=async(e,t,n,r,i,a,o=!1)=>{if(!e){t.push(0);return}let s=pw(),c=s.PTR_SIZE,l=e[0],u=e[1],d=e[3],f=d,p,m;if(l===`string`&&(d===`gpu-buffer`||d===`ml-tensor`))throw Error(`String tensor is not supported on GPU.`);if(o&&d!==`gpu-buffer`)throw Error(`External buffer must be provided for input/output index ${a} when enableGraphCapture is true.`);if(d===`gpu-buffer`){let t=e[2].gpuBuffer;m=jw(kw(l),u);{let e=s.webgpuRegisterBuffer;if(!e)throw Error(`Tensor location "gpu-buffer" is not supported without using WebGPU.`);p=e(t,r)}}else if(d===`ml-tensor`){let t=e[2].mlTensor;m=jw(kw(l),u);let n=s.webnnRegisterMLTensor;if(!n)throw Error(`Tensor location "ml-tensor" is not supported without using WebNN.`);p=n(r,t,kw(l),u)}else{let t=e[2];if(Array.isArray(t)){m=c*t.length,p=s._malloc(m),n.push(p);for(let e=0;es.setValue(g+t*c,e,c===4?`i32`:`i64`));let e=s._OrtCreateTensor(kw(l),p,m,g,u.length,Iw(f));e===0&&_w(`Can't create tensor for input/output. session=${r}, index=${a}.`),t.push(e)}finally{s.stackRestore(h)}},CT=async(e,t,n,r,i,a)=>{let o=pw(),s=o.PTR_SIZE,c=gT.get(e);if(!c)throw Error(`cannot run inference. invalid session id: ${e}`);let l=c[0],u=c[1],d=c[2],f=c[3],p=c[4],m=c[5],h=t.length,g=r.length,_=0,v=[],y=[],b=[],x=[],S=[],C=o.stackSave(),w=o.stackAlloc(h*s),T=o.stackAlloc(h*s),E=o.stackAlloc(g*s),D=o.stackAlloc(g*s);try{[_,v]=yw(a),bC(`wasm prepareInputOutputTensor`);for(let r=0;re*t,1);u=Aw(a);let _=f?.outputPreferredLocations[r[t]];if(u===`string`){if(_===`gpu-buffer`||_===`ml-tensor`)throw Error(`String tensor is not supported on GPU.`);let e=[];for(let t=0;t0){let t=o.webgpuGetBuffer;if(!t)throw Error(`preferredLocation "gpu-buffer" is not supported without using WebGPU.`);let r=t(d),i=jw(a,g);if(i===void 0||!Pw(u))throw Error(`Unsupported data type: ${u}`);l=!0;{o.webgpuRegisterBuffer(r,e,d);let t=o.webgpuCreateDownloader(r,i,e);C.push([u,h,{gpuBuffer:r,download:async()=>{let e=await t();return new(Mw(u))(e)},dispose:()=>{o._OrtReleaseTensor(n)!==0&&_w(`Can't release tensor.`)}},`gpu-buffer`])}}else if(_===`ml-tensor`&&g>0){let t=o.webnnEnsureTensor,r=o.webnnIsGraphInputOutputTypeSupported;if(!t||!r)throw Error(`preferredLocation "ml-tensor" is not supported without using WebNN.`);if(jw(a,g)===void 0||!Fw(u))throw Error(`Unsupported data type: ${u}`);if(!r(e,u,!1))throw Error(`preferredLocation "ml-tensor" for ${u} output is not supported by current WebNN Context.`);let i=await t(e,d,a,h,!1);l=!0,C.push([u,h,{mlTensor:i,download:o.webnnCreateMLTensorDownloader(d,u),dispose:()=>{o.webnnReleaseTensorId(d),o._OrtReleaseTensor(n)}},`ml-tensor`])}else if(_===`ml-tensor-cpu-output`&&g>0){let e=o.webnnCreateMLTensorDownloader(d,u)(),t=C.length;l=!0,O.push((async()=>{let r=[t,await e];return o.webnnReleaseTensorId(d),o._OrtReleaseTensor(n),r})()),C.push([u,h,[],`cpu`])}else{let e=new(Mw(u))(g);new Uint8Array(e.buffer,e.byteOffset,e.byteLength).set(o.HEAPU8.subarray(d,d+e.byteLength)),C.push([u,h,e,`cpu`])}}finally{o.stackRestore(a),u===`string`&&d&&o._free(d),l||o._OrtReleaseTensor(n)}}f&&!p&&(o._OrtClearBoundOutputs(f.handle)!==0&&_w(`Can't clear bound outputs.`),gT.set(e,[l,u,d,f,p,!1]));for(let[e,t]of await Promise.all(O))C[e][2]=t;return xC(`wasm ProcessOutputTensor`),C}finally{o.webnnOnRunEnd?.(l),o.stackRestore(C),n.forEach(e=>{e&&e[3]===`gpu-buffer`&&o.webgpuUnregisterBuffer(e[2].gpuBuffer)}),i.forEach(e=>{e&&e[3]===`gpu-buffer`&&o.webgpuUnregisterBuffer(e[2].gpuBuffer)}),y.forEach(e=>o._OrtReleaseTensor(e)),b.forEach(e=>o._OrtReleaseTensor(e)),x.forEach(e=>o._free(e)),_!==0&&o._OrtReleaseRunOptions(_),v.forEach(e=>o._free(e))}},wT=e=>{let t=pw(),n=gT.get(e);if(!n)throw Error(`invalid session id`);let r=n[0],i=t._OrtEndProfiling(r);i===0&&_w(`Can't get an profile file name.`),t._OrtFree(i)},TT=e=>{let t=[];for(let n of e){let e=n[2];!Array.isArray(e)&&`buffer`in e&&t.push(e.buffer)}return t}}),DT,OT,kT,AT,jT,MT,NT,PT,FT,IT,LT,RT,zT,BT,VT,HT,UT,WT,GT=AS(()=>{MC(),ET(),mw(),iw(),DT=()=>!!KS.wasm.proxy&&typeof document<`u`,kT=!1,AT=!1,jT=!1,PT=new Map,FT=(e,t)=>{let n=PT.get(e);n?n.push(t):PT.set(e,[t])},IT=()=>{if(kT||!AT||jT||!OT)throw Error(`worker not ready`)},LT=e=>{switch(e.data.type){case`init-wasm`:kT=!1,e.data.err?(jT=!0,NT[1](e.data.err)):(AT=!0,NT[0]()),MT&&=(URL.revokeObjectURL(MT),void 0);break;case`init-ep`:case`copy-from`:case`create`:case`release`:case`run`:case`end-profiling`:{let t=PT.get(e.data.type);e.data.err?t.shift()[1](e.data.err):t.shift()[0](e.data.out);break}default:}},RT=async()=>{if(!AT){if(kT)throw Error(`multiple calls to 'initWasm()' detected.`);if(jT)throw Error(`previous call to 'initWasm()' failed.`);if(kT=!0,DT())return new Promise((e,t)=>{OT?.terminate(),tw().then(([n,r])=>{try{OT=r,OT.onerror=e=>t(e),OT.onmessage=LT,NT=[e,t];let i={type:`init-wasm`,in:KS};!i.in.wasm.wasmPaths&&(n||GC)&&(i.in.wasm.wasmPaths={wasm:new URL(`/assets/ort-wasm-simd-threaded.asyncify-DFMnNRgU.wasm`,``+import.meta.url).href}),OT.postMessage(i),MT=n}catch(e){t(e)}},t)});try{await fw(KS.wasm),await mT(KS),AT=!0}catch(e){throw jT=!0,e}finally{kT=!1}}},zT=async e=>{if(DT())return IT(),new Promise((t,n)=>{FT(`init-ep`,[t,n]);let r={type:`init-ep`,in:{epName:e,env:KS}};OT.postMessage(r)});await hT(KS,e)},BT=async e=>DT()?(IT(),new Promise((t,n)=>{FT(`copy-from`,[t,n]);let r={type:`copy-from`,in:{buffer:e}};OT.postMessage(r,[e.buffer])})):yT(e),VT=async(e,t)=>{if(DT()){if(t?.preferredOutputLocation)throw Error(`session option "preferredOutputLocation" is not supported for proxy.`);return IT(),new Promise((n,r)=>{FT(`create`,[n,r]);let i={type:`create`,in:{model:e,options:{...t}}},a=[];e instanceof Uint8Array&&a.push(e.buffer),OT.postMessage(i,a)})}else return bT(e,t)},HT=async e=>{if(DT())return IT(),new Promise((t,n)=>{FT(`release`,[t,n]);let r={type:`release`,in:e};OT.postMessage(r)});xT(e)},UT=async(e,t,n,r,i,a)=>{if(DT()){if(n.some(e=>e[3]!==`cpu`))throw Error(`input tensor on GPU is not supported for proxy.`);if(i.some(e=>e))throw Error(`pre-allocated output tensor is not supported for proxy.`);return IT(),new Promise((i,o)=>{FT(`run`,[i,o]);let s=n,c={type:`run`,in:{sessionId:e,inputIndices:t,inputs:s,outputIndices:r,options:a}};OT.postMessage(c,TT(s))})}else return CT(e,t,n,r,i,a)},WT=async e=>{if(DT())return IT(),new Promise((t,n)=>{FT(`end-profiling`,[t,n]);let r={type:`end-profiling`,in:e};OT.postMessage(r)});wT(e)}}),KT,qT,JT,YT=AS(()=>{MC(),GT(),Lw(),NC(),zw(),KT=(e,t)=>{switch(e.location){case`cpu`:return[e.type,e.dims,e.data,`cpu`];case`gpu-buffer`:return[e.type,e.dims,{gpuBuffer:e.gpuBuffer},`gpu-buffer`];case`ml-tensor`:return[e.type,e.dims,{mlTensor:e.mlTensor},`ml-tensor`];default:throw Error(`invalid data location: ${e.location} for ${t()}`)}},qT=e=>{switch(e[3]){case`cpu`:return new mC(e[0],e[2],e[1]);case`gpu-buffer`:{let t=e[0];if(!Pw(t))throw Error(`not supported data type: ${t} for deserializing GPU tensor`);let{gpuBuffer:n,download:r,dispose:i}=e[2];return mC.fromGpuBuffer(n,{dataType:t,dims:e[1],download:r,dispose:i})}case`ml-tensor`:{let t=e[0];if(!Fw(t))throw Error(`not supported data type: ${t} for deserializing MLTensor tensor`);let{mlTensor:n,download:r,dispose:i}=e[2];return mC.fromMLTensor(n,{dataType:t,dims:e[1],download:r,dispose:i})}default:throw Error(`invalid data location: ${e[3]}`)}},JT=class{async fetchModelAndCopyToWasmMemory(e){return BT(await Rw(e))}async loadModel(e,t){vC();let n;n=typeof e==`string`?await this.fetchModelAndCopyToWasmMemory(e):e,[this.sessionId,this.inputNames,this.outputNames,this.inputMetadata,this.outputMetadata]=await VT(n,t),yC()}async dispose(){return HT(this.sessionId)}async run(e,t,n){vC();let r=[],i=[];Object.entries(e).forEach(e=>{let t=e[0],n=e[1],a=this.inputNames.indexOf(t);if(a===-1)throw Error(`invalid input '${t}'`);r.push(n),i.push(a)});let a=[],o=[];Object.entries(t).forEach(e=>{let t=e[0],n=e[1],r=this.outputNames.indexOf(t);if(r===-1)throw Error(`invalid output '${t}'`);a.push(n),o.push(r)});let s=r.map((e,t)=>KT(e,()=>`input "${this.inputNames[i[t]]}"`)),c=a.map((e,t)=>e?KT(e,()=>`output "${this.outputNames[o[t]]}"`):null),l=await UT(this.sessionId,i,s,o,c,n),u={};for(let e=0;eQT,initializeFlags:()=>ZT,wasmBackend:()=>$T});var ZT,QT,$T,eE=AS(()=>{MC(),GT(),YT(),ZT=()=>{(typeof KS.wasm.initTimeout!=`number`||KS.wasm.initTimeout<0)&&(KS.wasm.initTimeout=0);let e=KS.wasm.simd;if(typeof e!=`boolean`&&e!==void 0&&e!==`fixed`&&e!==`relaxed`&&(console.warn(`Property "env.wasm.simd" is set to unknown value "${e}". Reset it to \`false\` and ignore SIMD feature checking.`),KS.wasm.simd=!1),typeof KS.wasm.proxy!=`boolean`&&(KS.wasm.proxy=!1),typeof KS.wasm.trace!=`boolean`&&(KS.wasm.trace=!1),typeof KS.wasm.numThreads!=`number`||!Number.isInteger(KS.wasm.numThreads)||KS.wasm.numThreads<=0)if(typeof self<`u`&&!self.crossOriginIsolated)KS.wasm.numThreads=1;else{let e=typeof navigator>`u`?kS(`node:os`).cpus().length:navigator.hardwareConcurrency;KS.wasm.numThreads=Math.min(4,Math.ceil((e||1)/2))}},QT=class{async init(e){ZT(),await RT(),await zT(e)}async createInferenceSessionHandler(e,t){let n=new JT;return await n.loadModel(e,t),n}},$T=new QT});MC(),MC(),MC();var tE=`1.25.0-dev.20260307-d626b568e0`,nE=jC;{let e=(eE(),NS(XT)).wasmBackend;IS(`webgpu`,e,5),IS(`webnn`,e,5),IS(`cpu`,e,10),IS(`wasm`,e,10)}Object.defineProperty(KS.versions,`web`,{value:tE,enumerable:!0});var rE=`1.24.3`,iE=`warning`,aE={wasm:{},webgl:{},webgpu:{},versions:{common:rE},set logLevel(e){if(e!==void 0){if(typeof e!=`string`||[`verbose`,`info`,`warning`,`error`,`fatal`].indexOf(e)===-1)throw Error(`Unsupported logging level: ${e}`);iE=e}},get logLevel(){return iE}};Object.defineProperty(aE,`logLevel`,{enumerable:!0});var oE=(e,t)=>{let n=typeof document<`u`?document.createElement(`canvas`):new OffscreenCanvas(1,1);n.width=e.dims[3],n.height=e.dims[2];let r=n.getContext(`2d`);if(r!=null){let i,a;t?.tensorLayout!==void 0&&t.tensorLayout===`NHWC`?(i=e.dims[2],a=e.dims[3]):(i=e.dims[3],a=e.dims[2]);let o=t?.format===void 0?`RGB`:t.format,s=t?.norm,c,l;s===void 0||s.mean===void 0?c=[255,255,255,255]:typeof s.mean==`number`?c=[s.mean,s.mean,s.mean,s.mean]:(c=[s.mean[0],s.mean[1],s.mean[2],0],s.mean[3]!==void 0&&(c[3]=s.mean[3])),s===void 0||s.bias===void 0?l=[0,0,0,0]:typeof s.bias==`number`?l=[s.bias,s.bias,s.bias,s.bias]:(l=[s.bias[0],s.bias[1],s.bias[2],0],s.bias[3]!==void 0&&(l[3]=s.bias[3]));let u=a*i,d=0,f=u,p=u*2,m=-1;o===`RGBA`?(d=0,f=u,p=u*2,m=u*3):o===`RGB`?(d=0,f=u,p=u*2):o===`RBG`&&(d=0,p=u,f=u*2);for(let t=0;t{let n=typeof document<`u`?document.createElement(`canvas`).getContext(`2d`):new OffscreenCanvas(1,1).getContext(`2d`),r;if(n!=null){let i,a,o;t?.tensorLayout!==void 0&&t.tensorLayout===`NHWC`?(i=e.dims[2],a=e.dims[1],o=e.dims[3]):(i=e.dims[3],a=e.dims[2],o=e.dims[1]);let s=t===void 0||t.format===void 0?`RGB`:t.format,c=t?.norm,l,u;c===void 0||c.mean===void 0?l=[255,255,255,255]:typeof c.mean==`number`?l=[c.mean,c.mean,c.mean,c.mean]:(l=[c.mean[0],c.mean[1],c.mean[2],255],c.mean[3]!==void 0&&(l[3]=c.mean[3])),c===void 0||c.bias===void 0?u=[0,0,0,0]:typeof c.bias==`number`?u=[c.bias,c.bias,c.bias,c.bias]:(u=[c.bias[0],c.bias[1],c.bias[2],0],c.bias[3]!==void 0&&(u[3]=c.bias[3]));let d=a*i;if(t!==void 0&&(t.format!==void 0&&o===4&&t.format!==`RGBA`||o===3&&t.format!==`RGB`&&t.format!==`BGR`))throw Error(`Tensor format doesn't match input tensor dims`);let f=0,p=1,m=2,h=3,g=0,_=d,v=d*2,y=-1;s===`RGBA`?(g=0,_=d,v=d*2,y=d*3):s===`RGB`?(g=0,_=d,v=d*2):s===`RBG`&&(g=0,v=d,_=d*2),r=n.createImageData(i,a);for(let t=0;t{if(e===void 0)throw Error(`Image buffer must be defined`);if(t.height===void 0||t.width===void 0)throw Error(`Image height and width must be defined`);if(t.tensorLayout===`NHWC`)throw Error(`NHWC Tensor layout is not supported yet`);let{height:n,width:r}=t,i=t.norm??{mean:255,bias:0},a,o;a=typeof i.mean==`number`?[i.mean,i.mean,i.mean,i.mean]:[i.mean[0],i.mean[1],i.mean[2],i.mean[3]??255],o=typeof i.bias==`number`?[i.bias,i.bias,i.bias,i.bias]:[i.bias[0],i.bias[1],i.bias[2],i.bias[3]??0];let s=t.format===void 0?`RGBA`:t.format,c=t.tensorFormat===void 0||t.tensorFormat===void 0?`RGB`:t.tensorFormat,l=n*r,u=c===`RGBA`?new Float32Array(l*4):new Float32Array(l*3),d=4,f=0,p=1,m=2,h=3,g=0,_=l,v=l*2,y=-1;s===`RGB`&&(d=3,f=0,p=1,m=2,h=-1),c===`RGBA`?y=l*3:c===`RBG`?(g=0,v=l,_=l*2):c===`BGR`&&(v=0,_=l,g=l*2);for(let t=0;t{let n=typeof HTMLImageElement<`u`&&e instanceof HTMLImageElement,r=typeof ImageData<`u`&&e instanceof ImageData,i=typeof ImageBitmap<`u`&&e instanceof ImageBitmap,a=typeof e==`string`,o,s=t??{},c=()=>{if(typeof document<`u`)return document.createElement(`canvas`);if(typeof OffscreenCanvas<`u`)return new OffscreenCanvas(1,1);throw Error(`Canvas is not supported`)},l=e=>typeof HTMLCanvasElement<`u`&&e instanceof HTMLCanvasElement||e instanceof OffscreenCanvas?e.getContext(`2d`):null;if(n){let n=c();n.width=e.width,n.height=e.height;let r=l(n);if(r!=null){let n=e.height,i=e.width;if(t!==void 0&&t.resizedHeight!==void 0&&t.resizedWidth!==void 0&&(n=t.resizedHeight,i=t.resizedWidth),t!==void 0){if(s=t,t.tensorFormat!==void 0)throw Error(`Image input config format must be RGBA for HTMLImageElement`);s.tensorFormat=`RGBA`,s.height=n,s.width=i}else s.tensorFormat=`RGBA`,s.height=n,s.width=i;r.drawImage(e,0,0),o=r.getImageData(0,0,i,n).data}else throw Error(`Can not access image data`)}else if(r){let n,r;if(t!==void 0&&t.resizedWidth!==void 0&&t.resizedHeight!==void 0?(n=t.resizedHeight,r=t.resizedWidth):(n=e.height,r=e.width),t!==void 0&&(s=t),s.format=`RGBA`,s.height=n,s.width=r,t!==void 0){let t=c();t.width=r,t.height=n;let i=l(t);if(i!=null)i.putImageData(e,0,0),o=i.getImageData(0,0,r,n).data;else throw Error(`Can not access image data`)}else o=e.data}else if(i){if(t===void 0)throw Error(`Please provide image config with format for Imagebitmap`);let n=c();n.width=e.width,n.height=e.height;let r=l(n);if(r!=null){let t=e.height,n=e.width;return r.drawImage(e,0,0,n,t),o=r.getImageData(0,0,n,t).data,s.height=t,s.width=n,cE(o,s)}else throw Error(`Can not access image data`)}else if(a)return new Promise((t,n)=>{let r=c(),i=l(r);if(!e||!i)return n();let a=new Image;a.crossOrigin=`Anonymous`,a.src=e,a.onload=()=>{r.width=a.width,r.height=a.height,i.drawImage(a,0,0,r.width,r.height);let e=i.getImageData(0,0,r.width,r.height);s.height=r.height,s.width=r.width,t(cE(e.data,s))}});else throw Error(`Input data provided is not supported - aborted tensor creation`);if(o!==void 0)return cE(o,s);throw Error(`Input data provided is not supported - aborted tensor creation`)},uE=(e,t)=>{let{width:n,height:r,download:i,dispose:a}=t;return new bE({location:`texture`,type:`float32`,texture:e,dims:[1,r,n,4],download:i,dispose:a})},dE=(e,t)=>{let{dataType:n,dims:r,download:i,dispose:a}=t;return new bE({location:`gpu-buffer`,type:n??`float32`,gpuBuffer:e,dims:r,download:i,dispose:a})},fE=(e,t)=>{let{dataType:n,dims:r,download:i,dispose:a}=t;return new bE({location:`ml-tensor`,type:n??`float32`,mlTensor:e,dims:r,download:i,dispose:a})},pE=(e,t,n)=>new bE({location:`cpu-pinned`,type:e,data:t,dims:n??[t.length]}),mE=new Map([[`float32`,Float32Array],[`uint8`,Uint8Array],[`int8`,Int8Array],[`uint16`,Uint16Array],[`int16`,Int16Array],[`int32`,Int32Array],[`bool`,Uint8Array],[`float64`,Float64Array],[`uint32`,Uint32Array],[`int4`,Uint8Array],[`uint4`,Uint8Array]]),hE=new Map([[Float32Array,`float32`],[Uint8Array,`uint8`],[Int8Array,`int8`],[Uint16Array,`uint16`],[Int16Array,`int16`],[Int32Array,`int32`],[Float64Array,`float64`],[Uint32Array,`uint32`]]),gE=!1,_E=()=>{if(!gE){gE=!0;let e=typeof BigInt64Array<`u`&&BigInt64Array.from,t=typeof BigUint64Array<`u`&&BigUint64Array.from,n=globalThis.Float16Array,r=n!==void 0&&n.from;e&&(mE.set(`int64`,BigInt64Array),hE.set(BigInt64Array,`int64`)),t&&(mE.set(`uint64`,BigUint64Array),hE.set(BigUint64Array,`uint64`)),r?(mE.set(`float16`,n),hE.set(n,`float16`)):mE.set(`float16`,Uint16Array)}},vE=e=>{let t=1;for(let n=0;n{switch(e.location){case`cpu`:return new bE(e.type,e.data,t);case`cpu-pinned`:return new bE({location:`cpu-pinned`,data:e.data,type:e.type,dims:t});case`texture`:return new bE({location:`texture`,texture:e.texture,type:e.type,dims:t});case`gpu-buffer`:return new bE({location:`gpu-buffer`,gpuBuffer:e.gpuBuffer,type:e.type,dims:t});case`ml-tensor`:return new bE({location:`ml-tensor`,mlTensor:e.mlTensor,type:e.type,dims:t});default:throw Error(`tensorReshape: tensor location ${e.location} is not supported`)}},bE=class{constructor(e,t,n){_E();let r,i;if(typeof e==`object`&&`location`in e)switch(this.dataLocation=e.location,r=e.type,i=e.dims,e.location){case`cpu-pinned`:{let t=mE.get(r);if(!t)throw TypeError(`unsupported type "${r}" to create tensor from pinned buffer`);if(!(e.data instanceof t))throw TypeError(`buffer should be of type ${t.name}`);this.cpuData=e.data;break}case`texture`:if(r!==`float32`)throw TypeError(`unsupported type "${r}" to create tensor from texture`);this.gpuTextureData=e.texture,this.downloader=e.download,this.disposer=e.dispose;break;case`gpu-buffer`:if(r!==`float32`&&r!==`float16`&&r!==`int32`&&r!==`int64`&&r!==`uint32`&&r!==`uint8`&&r!==`bool`&&r!==`uint4`&&r!==`int4`)throw TypeError(`unsupported type "${r}" to create tensor from gpu buffer`);this.gpuBufferData=e.gpuBuffer,this.downloader=e.download,this.disposer=e.dispose;break;case`ml-tensor`:if(r!==`float32`&&r!==`float16`&&r!==`int32`&&r!==`int64`&&r!==`uint32`&&r!==`uint64`&&r!==`int8`&&r!==`uint8`&&r!==`bool`&&r!==`uint4`&&r!==`int4`)throw TypeError(`unsupported type "${r}" to create tensor from MLTensor`);this.mlTensorData=e.mlTensor,this.downloader=e.download,this.disposer=e.dispose;break;default:throw Error(`Tensor constructor: unsupported location '${this.dataLocation}'`)}else{let a,o;if(typeof e==`string`)if(r=e,o=n,e===`string`){if(!Array.isArray(t))throw TypeError(`A string tensor's data must be a string array.`);a=t}else{let n=mE.get(e);if(n===void 0)throw TypeError(`Unsupported tensor type: ${e}.`);if(Array.isArray(t)){if(e===`float16`&&n===Uint16Array||e===`uint4`||e===`int4`)throw TypeError(`Creating a ${e} tensor from number array is not supported. Please use ${n.name} as data.`);a=e===`uint64`||e===`int64`?n.from(t,BigInt):n.from(t)}else if(t instanceof n)a=t;else if(t instanceof Uint8ClampedArray)if(e===`uint8`)a=Uint8Array.from(t);else throw TypeError(`A Uint8ClampedArray tensor's data must be type of uint8`);else if(e===`float16`&&t instanceof Uint16Array&&n!==Uint16Array)a=new globalThis.Float16Array(t.buffer,t.byteOffset,t.length);else throw TypeError(`A ${r} tensor's data must be type of ${n}`)}else if(o=t,Array.isArray(e)){if(e.length===0)throw TypeError(`Tensor type cannot be inferred from an empty array.`);let t=typeof e[0];if(t===`string`)r=`string`,a=e;else if(t===`boolean`)r=`bool`,a=Uint8Array.from(e);else throw TypeError(`Invalid element type of data array: ${t}.`)}else if(e instanceof Uint8ClampedArray)r=`uint8`,a=Uint8Array.from(e);else{let t=hE.get(e.constructor);if(t===void 0)throw TypeError(`Unsupported type for tensor data: ${e.constructor}.`);r=t,a=e}if(o===void 0)o=[a.length];else if(!Array.isArray(o))throw TypeError(`A tensor's dims must be a number array`);i=o,this.cpuData=a,this.dataLocation=`cpu`}let a=vE(i);if(this.cpuData&&a!==this.cpuData.length&&!((r===`uint4`||r===`int4`)&&Math.ceil(a/2)===this.cpuData.length))throw Error(`Tensor's size(${a}) does not match data length(${this.cpuData.length}).`);this.type=r,this.dims=i,this.size=a}static async fromImage(e,t){return lE(e,t)}static fromTexture(e,t){return uE(e,t)}static fromGpuBuffer(e,t){return dE(e,t)}static fromMLTensor(e,t){return fE(e,t)}static fromPinnedBuffer(e,t,n){return pE(e,t,n)}toDataURL(e){return oE(this,e)}toImageData(e){return sE(this,e)}get data(){if(this.ensureValid(),!this.cpuData)throw Error("The data is not on CPU. Use `getData()` to download GPU data to CPU, or use `texture` or `gpuBuffer` property to access the GPU data directly.");return this.cpuData}get location(){return this.dataLocation}get texture(){if(this.ensureValid(),!this.gpuTextureData)throw Error(`The data is not stored as a WebGL texture.`);return this.gpuTextureData}get gpuBuffer(){if(this.ensureValid(),!this.gpuBufferData)throw Error(`The data is not stored as a WebGPU buffer.`);return this.gpuBufferData}get mlTensor(){if(this.ensureValid(),!this.mlTensorData)throw Error(`The data is not stored as a WebNN MLTensor.`);return this.mlTensorData}async getData(e){switch(this.ensureValid(),this.dataLocation){case`cpu`:case`cpu-pinned`:return this.data;case`texture`:case`gpu-buffer`:case`ml-tensor`:if(!this.downloader)throw Error(`The current tensor is not created with a specified data downloader.`);if(this.isDownloading)throw Error(`The current tensor is being downloaded.`);try{this.isDownloading=!0;let t=await this.downloader();return this.downloader=void 0,this.dataLocation=`cpu`,this.cpuData=t,e&&this.disposer&&(this.disposer(),this.disposer=void 0),t}finally{this.isDownloading=!1}default:throw Error(`cannot get data from location: ${this.dataLocation}`)}}dispose(){if(this.isDownloading)throw Error(`The current tensor is being downloaded.`);this.disposer&&=(this.disposer(),void 0),this.cpuData=void 0,this.gpuTextureData=void 0,this.gpuBufferData=void 0,this.mlTensorData=void 0,this.downloader=void 0,this.isDownloading=void 0,this.dataLocation=`none`}ensureValid(){if(this.dataLocation===`none`)throw Error(`The tensor is disposed.`)}reshape(e){if(this.ensureValid(),this.downloader||this.disposer)throw Error(`Cannot reshape a tensor that owns GPU resource.`);return yE(this,e)}},xE=bE,SE=Object.defineProperty,CE=(e,t)=>{for(var n in t)SE(e,n,{get:t[n],enumerable:!0})},wE={},TE={},EE={},DE=`4.0.0-next.7`,OE=typeof self<`u`,kE=!tD(wE),AE=!tD(TE),jE=OE&&`caches`in self,ME=globalThis.Deno!==void 0;globalThis.Bun;var NE=ME&&jE&&!kE,PE=typeof process<`u`,FE=PE&&process?.release?.name===`node`&&!NE,IE=typeof window<`u`&&window.document!==void 0,LE=OE&&[`DedicatedWorkerGlobalScope`,`ServiceWorkerGlobalScope`,`SharedWorkerGlobalScope`].includes(self.constructor?.name),RE=IE||LE||NE,zE=FE||typeof navigator<`u`&&`gpu`in navigator,BE=typeof navigator<`u`&&`ml`in navigator,VE=typeof crypto<`u`&&typeof crypto.getRandomValues==`function`,HE=typeof chrome<`u`&&chrome.runtime!==void 0&&typeof chrome.runtime.id==`string`,UE=typeof ServiceWorkerGlobalScope<`u`&&OE&&self instanceof ServiceWorkerGlobalScope,WE=(()=>{if(typeof navigator>`u`)return!1;let e=navigator.userAgent,t=(navigator.vendor||``).indexOf(`Apple`)>-1,n=!e.match(/CriOS|FxiOS|EdgiOS|OPiOS|mercury|brave/i)&&!e.includes(`Chrome`)&&!e.includes(`Android`);return t&&n})(),GE=Object.freeze({IS_BROWSER_ENV:IE,IS_WEBWORKER_ENV:LE,IS_WEB_ENV:RE,IS_SERVICE_WORKER_ENV:UE,IS_DENO_WEB_RUNTIME:NE,IS_WEB_CACHE_AVAILABLE:jE,IS_WEBGPU_AVAILABLE:zE,IS_WEBNN_AVAILABLE:BE,IS_SAFARI:WE,IS_PROCESS_AVAILABLE:PE,IS_NODE_ENV:FE,IS_FS_AVAILABLE:kE,IS_PATH_AVAILABLE:AE,IS_CRYPTO_AVAILABLE:VE,IS_CHROME_AVAILABLE:HE}),KE=kE&&AE,qE=`./`;if(KE){let e=Object(import.meta).url;e?qE=TE.dirname(TE.dirname(EE.fileURLToPath(e))):typeof __dirname<`u`&&(qE=TE.dirname(__dirname))}var JE=KE?TE.join(qE,`/.cache/`):null,YE=`/models/`,XE=KE?TE.join(qE,YE):YE,ZE=typeof globalThis.fetch==`function`?globalThis.fetch.bind(globalThis):void 0,QE=Object.freeze({DEBUG:10,INFO:20,WARNING:30,ERROR:40,NONE:50}),$E=QE.WARNING,eD={version:DE,backends:{onnx:{}},get logLevel(){return $E},set logLevel(e){$E=e,eD.backends.onnx?.setLogLevel?.(e)},allowRemoteModels:!0,remoteHost:`https://huggingface.co/`,remotePathTemplate:`{model}/resolve/{revision}/`,allowLocalModels:!(IE||LE||NE),localModelPath:XE,useFS:kE,useBrowserCache:jE,useFSCache:kE,cacheDir:JE,useCustomCache:!1,customCache:null,useWasmCache:jE||kE,cacheKey:`transformers-cache`,experimental_useCrossOriginStorage:!1,fetch:ZE};function tD(e){return Object.keys(e).length===0}function nD(e,t){e&&e(t)}function rD(e){return Number.isInteger(e)||typeof e==`bigint`}function iD(e){return e==null||e===-1}function aD(e){let t=[],n=e;for(;Array.isArray(n);)t.push(n.length),n=n[0];return t}function oD(...e){return Array.prototype.concat.apply([],e)}function sD(...e){return e.reduce((e,t)=>e.flatMap(e=>t.map(t=>[e,t])))}function cD(e,t){return Math.abs((e+t)%(2*t)-t)}function lD(e,t){return Object.assign({},...t.map(t=>{if(e[t]!==void 0)return{[t]:e[t]}}))}function uD(e,t){let n=0;for(let r of e)r===t&&++n;return n}var dD={error(...e){eD.logLevel<=QE.ERROR&&console.error(...e)},warn(...e){eD.logLevel<=QE.WARNING&&console.warn(...e)},info(...e){eD.logLevel<=QE.INFO&&console.log(...e)},debug(...e){eD.logLevel<=QE.DEBUG&&console.log(...e)},log(...e){this.info(...e)}},fD=class{constructor(e){this.trie=this._build_trie(e)}_build_trie(e){let t=Object.create(null);for(let n of e){let e=t;for(let t=0;tr&&t.push(e.slice(r,i)),t.push(o),i+=o.length,r=i):++i}return r{let e=[...Array.from({length:94},(e,t)=>t+33),...Array.from({length:12},(e,t)=>t+161),...Array.from({length:82},(e,t)=>t+174)],t=e.slice(),n=0;for(let r=0;r<256;++r)e.includes(r)||(e.push(r),t.push(256+n),n+=1);let r=t.map(e=>String.fromCharCode(e));return Object.fromEntries(e.map((e,t)=>[e,r[t]]))})(),hD=(e=>Object.fromEntries(Object.entries(e).map(([e,t])=>[t,e])))(mD),gD=`.,!?…。,、।۔،`,_D=new Map([[`(?i:'s|'t|'re|'ve|'m|'ll|'d)`,`(?:'([sS]|[tT]|[rR][eE]|[vV][eE]|[mM]|[lL][lL]|[dD]))`],[`(?i:[sdmt]|ll|ve|re)`,`(?:[sS]|[dD]|[mM]|[tT]|[lL][lL]|[vV][eE]|[rR][eE])`],[`[^\\r\\n\\p{L}\\p{N}]?+`,`[^\\r\\n\\p{L}\\p{N}]?`],[`[^\\s\\p{L}\\p{N}]++`,`[^\\s\\p{L}\\p{N}]+`],[`(?>\\p{Nd}{510})`,`(?:\\p{Nd}{510})`],[`\\p{Nd}{3}+`,`(?:\\p{Nd}{3})+`],[`\\G`,``],[` ?[^(\\s|[${gD}])]+`,` ?[^\\s${gD}]+`]]),vD=`\\p{P}\\u0021-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E`,yD=e=>e.replace(/ \./g,`.`).replace(/ \?/g,`?`).replace(/ \!/g,`!`).replace(/ ,/g,`,`).replace(/ \' /g,`'`).replace(/ n't/g,`n't`).replace(/ 'm/g,`'m`).replace(/ 's/g,`'s`).replace(/ 've/g,`'ve`).replace(/ 're/g,`'re`),bD=(e,t=!0)=>{if(e.Regex!==void 0){let t=e.Regex.replace(/\\([#&~])/g,`$1`);t=t.replace(/\\A/g,`^`).replace(/\\z/g,`$`).replace(/\\Z/g,`(?=\\r?\\n?$)`);for(let[e,n]of _D)t=t.replaceAll(e,n);try{return new RegExp(t,`gu`)}catch(e){if(!(e instanceof SyntaxError)||!e.message.toLowerCase().includes(`invalid property name`))throw e;let n=!1,r=t.replace(/(\\[pP])\{([^}=]+)\}/g,(e,t,r)=>{try{return RegExp(`\\p{${r}}`,`u`),`${t}{${r}}`}catch{return n=!0,`${t}{Script=${r}}`}});if(!n)throw e;try{return new RegExp(r,`gu`)}catch{throw e}}}else if(e.String!==void 0){let n=xD(e.String);return new RegExp(t?n:`(${n})`,`gu`)}else return console.warn(`Unknown pattern type:`,e),null},xD=e=>e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`),SD=(e,t,n)=>{let r=[],i=0;for(;ie>=19968&&e<=40959||e>=13312&&e<=19903||e>=131072&&e<=173791||e>=173824&&e<=177983||e>=177984&&e<=178207||e>=178208&&e<=183983||e>=63744&&e<=64255||e>=194560&&e<=195103,wD=e=>Number.isInteger(e)||typeof e==`bigint`,TD=e=>{let t=0;for(let n of e)++t;return t},ED=e=>AD(e.toLowerCase()),DD=(...e)=>Array.prototype.concat.apply([],e),OD=e=>new Map(Object.entries(e)),kD=(e,t)=>{let n=[],r=0;for(let i of e.matchAll(t)){let t=i[0];r0&&n.push(t),r=i.index+t.length}return re.replace(/\p{M}/gu,``),jD=(e,t,n=[])=>{if(!e||Array.isArray(e)||typeof e!=`object`)return`${t} must be a valid object`;for(let r of n)if(!(r in e))return`${t} must contain a "${r}" property`;return null},MD=e=>e.match(/\S+/g)||[],ND=class{constructor(){let e=function(...t){return e._call(...t)};return Object.setPrototypeOf(e,new.target.prototype)}},PD=class extends ND{constructor(e){super(),this.config=e}_call(e){return this.normalize(e)}},FD=class extends PD{tokenize_chinese_chars(e){let t=[];for(let n=0;ne.normalize(`NFKC`)).join(`~`):e.normalize(`NFKC`),e}},LD=class extends PD{constructor(e){super(e),this.normalizers=(e.normalizers??[]).map(e=>YD(e))}normalize(e){return this.normalizers.reduce((e,t)=>t?t.normalize(e):e,e)}},RD=class extends PD{normalize(e){let t=bD(this.config.pattern??{});return t===null?e:e.replaceAll(t,this.config.content??``)}},zD=class extends PD{constructor(){super(...arguments),this.form=`NFC`}normalize(e){return e=e.normalize(this.form),e}},BD=class extends zD{constructor(){super(...arguments),this.form=`NFC`}},VD=class extends zD{constructor(){super(...arguments),this.form=`NFD`}},HD=class extends zD{constructor(){super(...arguments),this.form=`NFKC`}},UD=class extends zD{constructor(){super(...arguments),this.form=`NFKD`}},WD=class extends PD{normalize(e){return this.config.strip_left&&this.config.strip_right?e=e.trim():(this.config.strip_left&&(e=e.trimStart()),this.config.strip_right&&(e=e.trimEnd())),e}},GD=class extends PD{normalize(e){return AD(e)}},KD=class extends PD{normalize(e){return e.toLowerCase()}},qD=class extends PD{normalize(e){return e=this.config.prepend+e,e}};function JD(e){if(e===null)return null;switch(e.type){case`BertNormalizer`:return new FD(e);case`Precompiled`:return new ID(e);case`Sequence`:return new LD(e);case`Replace`:return new RD(e);case`NFC`:return new BD(e);case`NFD`:return new VD(e);case`NFKC`:return new HD(e);case`NFKD`:return new UD(e);case`Strip`:return new WD(e);case`StripAccents`:return new GD(e);case`Lowercase`:return new KD(e);case`Prepend`:return new qD(e);default:throw Error(`Unknown Normalizer type: ${e.type}`)}}var YD=JD,XD=class extends ND{pre_tokenize(e,t){return(Array.isArray(e)?e.map(e=>this.pre_tokenize_text(e,t)):this.pre_tokenize_text(e,t)).flat()}_call(e,t){return this.pre_tokenize(e,t)}},ZD=class extends XD{constructor(e){super(),this.config=e,this.add_prefix_space=this.config.add_prefix_space??!1,this.trim_offsets=this.config.trim_offsets??!1,this.use_regex=this.config.use_regex??!0,this.pattern=/'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+/gu,this.byte_encoder=mD,this.text_encoder=new TextEncoder}pre_tokenize_text(e,t){return this.add_prefix_space&&!e.startsWith(` `)&&(e=` `+e),(this.use_regex?e.match(this.pattern)||[]:[e]).map(e=>Array.from(this.text_encoder.encode(e),e=>this.byte_encoder[e]).join(``))}},QD=class extends XD{pre_tokenize_text(e,t){return e.match(/\w+|[^\w\s]+/g)||[]}},$D=class extends XD{constructor(e){super(),this.replacement=e.replacement??`▁`,this.str_rep=e.str_rep||this.replacement,this.prepend_scheme=e.prepend_scheme??`always`}pre_tokenize_text(e,t){let{section_index:n=void 0}=t??{},r=e.replaceAll(` `,this.str_rep);return!r.startsWith(this.replacement)&&(this.prepend_scheme===`always`||this.prepend_scheme===`first`&&n===0)&&(r=this.str_rep+r),[r]}},eO=class extends XD{constructor(e){super(),this.config=e,this.pattern=bD(this.config.pattern??{},this.config.invert??!0)}pre_tokenize_text(e){return this.pattern===null?[]:this.config.invert?e.match(this.pattern)||[]:this.config.behavior?.toLowerCase()===`removed`?e.split(this.pattern).filter(e=>e):kD(e,this.pattern)}},tO=class extends XD{constructor(e){super(),this.config=e,this.pattern=RegExp(`[^${vD}]+|[${vD}]+`,`gu`)}pre_tokenize_text(e){return e.match(this.pattern)||[]}},nO=class extends XD{constructor(e){super(),this.config=e;let t=`[^\\d]+|\\d${this.config.individual_digits?``:`+`}`;this.pattern=new RegExp(t,`gu`)}pre_tokenize_text(e){return e.match(this.pattern)||[]}},rO=class extends XD{constructor(){super(),this.pattern=RegExp(`[^\\s${vD}]+|[${vD}]`,`gu`)}pre_tokenize_text(e,t){return e.trim().match(this.pattern)||[]}},iO=class extends XD{constructor(e){super(),this.config=e,this.pattern=bD(this.config.pattern??{}),this.content=this.config.content??``}pre_tokenize_text(e){return this.pattern===null?[e]:[e.replaceAll(this.pattern,this.config.content??``)]}},aO=class extends XD{constructor(e){super(),this.tokenizers=(e.pretokenizers??[]).map(e=>lO(e))}pre_tokenize_text(e,t){return this.tokenizers.reduce((e,n)=>n?n.pre_tokenize(e,t):e,[e])}},oO=class extends XD{pre_tokenize_text(e){return MD(e)}},sO=class extends XD{constructor(e){super(),this.config=e,this._length=e.length}pre_tokenize_text(e){let t=[];for(let n=0;nthis.max_input_chars_per_word){t.push(this.unk_token);continue}let r=!1,i=0,a=[];for(;i0&&(r=this.config.continuing_subword_prefix+r),this.tokens_to_ids.has(r)){n=r;break}--t}if(n===null){r=!0;break}a.push(n),i=t}r?t.push(this.unk_token):t.push(...a)}return t}},fO=class e{constructor(e,t){this.is_leaf=e,this.children=t}static default(){return new e(!1,new Map)}},pO=class{constructor(){this.root=fO.default()}extend(e){for(let t of e)this.push(t)}push(e){let t=this.root;for(let n of e){let e=t.children.get(n);e===void 0&&(e=fO.default(),t.children.set(n,e)),t=e}t.is_leaf=!0}*common_prefix_search(e){let t=this.root;if(t===void 0)return;let n=``;for(let r of e){if(n+=r,t=t.children.get(r),t===void 0)return;t.is_leaf&&(yield n)}}},mO=class e{constructor(e,t,n,r,i){this.token_id=e,this.node_id=t,this.pos=n,this.length=r,this.score=i,this.prev=null,this.backtrace_score=0}clone(){let t=new e(this.token_id,this.node_id,this.pos,this.length,this.score);return t.prev=this.prev,t.backtrace_score=this.backtrace_score,t}},hO=class{constructor(e,t,n){this.chars=Array.from(e),this.len=this.chars.length,this.bos_token_id=t,this.eos_token_id=n,this.nodes=[],this.begin_nodes=Array.from({length:this.len+1},()=>[]),this.end_nodes=Array.from({length:this.len+1},()=>[]);let r=new mO(this.bos_token_id??0,0,0,0,0),i=new mO(this.eos_token_id??0,1,this.len,0,0);this.nodes.push(r.clone()),this.nodes.push(i.clone()),this.begin_nodes[this.len].push(i),this.end_nodes[0].push(r)}insert(e,t,n,r){let i=this.nodes.length,a=new mO(r,i,e,t,n);this.begin_nodes[e].push(a),this.end_nodes[e+t].push(a),this.nodes.push(a)}viterbi(){let e=this.len,t=0;for(;t<=e;){if(this.begin_nodes[t].length==0)return[];for(let e of this.begin_nodes[t]){e.prev=null;let n=0,r=null;for(let i of this.end_nodes[t]){let t=i.backtrace_score+e.score;(r===null||t>n)&&(r=i.clone(),n=t)}if(r!==null)e.prev=r,e.backtrace_score=n;else return[]}++t}let n=[],r=this.begin_nodes[e][0].prev;if(r===null)return[];let i=r.clone();for(;i.prev!==null;)n.push(i.clone()),i=i.clone().prev.clone();return n.reverse(),n}piece(e){return this.chars.slice(e.pos,e.pos+e.length).join(``)}tokens(){return this.viterbi().map(e=>this.piece(e))}token_ids(){return this.viterbi().map(e=>e.token_id)}};function gO(e){if(e.length===0)throw Error(`Array must not be empty`);let t=e[0],n=0;for(let r=1;r[e,t])),this.bos_token=` `,this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=t,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.unk_token=this.vocab[this.unk_token_id],this.min_score=gO(this.scores)[0],this.unk_score=this.min_score-10,this.scores[this.unk_token_id]=this.unk_score,this.trie=new pO,this.trie.extend(this.vocab),this.fuse_unk=!0}populate_nodes(e){let t=e.chars,n=0;for(;ne>t,t=1/0){this._heap=[],this._comparator=e,this._max_size=t}get size(){return this._heap.length}is_empty(){return this.size===0}peek(){return this._heap[0]}push(...e){return this.extend(e)}extend(e){for(let t of e)if(this.size0&&this._swap(0,t),this._heap.pop(),this._sift_down(),e}replace(e){let t=this.peek();return this._heap[0]=e,this._sift_down(),t}_parent(e){return(e+1>>>1)-1}_left(e){return(e<<1)+1}_right(e){return e+1<<1}_greater(e,t){return this._comparator(this._heap[e],this._heap[t])}_swap(e,t){let n=this._heap[e];this._heap[e]=this._heap[t],this._heap[t]=n}_sift_up(){this._sift_up_from(this.size-1)}_sift_up_from(e){for(;e>0&&this._greater(e,this._parent(e));)this._swap(e,this._parent(e)),e=this._parent(e)}_sift_down(){let e=0;for(;this._left(e)this.capacity&&this.cache.delete(this.cache.keys().next().value)}clear(){this.cache.clear()}},bO=class extends uO{constructor(e){super(e),this.tokens_to_ids=OD(e.vocab),this.unk_token_id=this.tokens_to_ids.get(e.unk_token),this.unk_token=e.unk_token,this.vocab=Array(this.tokens_to_ids.size);for(let[e,t]of this.tokens_to_ids)this.vocab[t]=e;this.merges=Array.isArray(e.merges[0])?e.merges:e.merges.map(e=>e.split(` `,2)),this.bpe_ranks=new Map(this.merges.map((e,t)=>[JSON.stringify(e),t])),this.end_of_word_suffix=e.end_of_word_suffix,this.continuing_subword_suffix=e.continuing_subword_suffix??null,this.byte_fallback=this.config.byte_fallback??!1,this.byte_fallback&&(this.text_encoder=new TextEncoder),this.ignore_merges=this.config.ignore_merges??!1,this.max_length_to_cache=256,this.cache_capacity=1e4,this.cache=new yO(this.cache_capacity)}clear_cache(){this.cache.clear()}bpe(e){if(e.length===0)return[];let t=this.cache.get(e);if(t!==void 0)return t;let n=Array.from(e);this.end_of_word_suffix&&(n[n.length-1]+=this.end_of_word_suffix);let r=[];if(n.length>1){let e=new vO((e,t)=>e.score`<0x${e.toString(16).toUpperCase().padStart(2,`0`)}>`);e.every(e=>this.tokens_to_ids.has(e))?t.push(...e):t.push(this.unk_token)}else t.push(this.unk_token)}return t}},xO=class extends uO{constructor(e,t){super(e);let n=e.vocab;this.tokens_to_ids=OD(t.target_lang?n[t.target_lang]:n),this.bos_token=t.bos_token,this.bos_token_id=this.tokens_to_ids.get(this.bos_token),this.eos_token=t.eos_token,this.eos_token_id=this.tokens_to_ids.get(this.eos_token),this.pad_token=t.pad_token,this.pad_token_id=this.tokens_to_ids.get(this.pad_token),this.unk_token=t.unk_token,this.unk_token_id=this.tokens_to_ids.get(this.unk_token),this.vocab=Array(this.tokens_to_ids.size);for(let[e,t]of this.tokens_to_ids)this.vocab[t]=e}encode(e){return e}};function SO(e,t){switch(e.type){case`WordPiece`:return new dO(e);case`Unigram`:return new _O(e,t.eos_token);case`BPE`:return new bO(e);default:if(e.vocab)return Array.isArray(e.vocab)?new _O(e,t.eos_token):Object.hasOwn(e,`continuing_subword_prefix`)&&Object.hasOwn(e,`unk_token`)?Object.hasOwn(e,`merges`)?new bO(e):new dO(e):new xO(e,{target_lang:t.target_lang,bos_token:t.bos_token,eos_token:t.eos_token,pad_token:t.pad_token,unk_token:t.unk_token});throw Error(`Unknown TokenizerModel type: ${e?.type}`)}}var CO=SO,wO=class extends ND{constructor(e){super(),this.config=e}_call(e,...t){return this.post_process(e,...t)}},TO=class extends wO{post_process(e,t=null,n=!0){let r=t===null?this.config.single:this.config.pair,i=[],a=[];for(let o of r)`SpecialToken`in o?n&&(i.push(o.SpecialToken.id),a.push(o.SpecialToken.type_id)):`Sequence`in o&&(o.Sequence.id===`A`?(i=DD(i,e),a=DD(a,Array(e.length).fill(o.Sequence.type_id))):o.Sequence.id===`B`&&(i=DD(i,t),a=DD(a,Array(t.length).fill(o.Sequence.type_id))));return{tokens:i,token_type_ids:a}}},EO=class extends wO{post_process(e,t=null){return{tokens:e,tokens_pair:t}}},DO=class extends wO{constructor(e){super(e),this.sep=e.sep,this.cls=e.cls}post_process(e,t=null,n=!0){n&&(e=DD([this.cls[0]],e,[this.sep[0]]));let r=Array(e.length).fill(0);if(t){let i=[],a=n?[this.sep[0]]:[];e=DD(e,i,t,a),r=DD(r,Array(t.length+i.length+a.length).fill(1))}return{tokens:e,token_type_ids:r}}},OO=class extends wO{constructor(e){super(e),this.sep=e.sep,this.cls=e.cls}post_process(e,t,n=!0){n&&(e=DD([this.cls[0]],e,[this.sep[0]]));let r=Array(e.length).fill(0);if(t){let i=n?[this.sep[0]]:[],a=n?[this.sep[0]]:[];e=DD(e,i,t,a),r=DD(r,Array(t.length+i.length+a.length).fill(1))}return{tokens:e,token_type_ids:r}}},kO=class extends wO{constructor(e){super(e),this.processors=(e.processors??[]).map(e=>jO(e))}post_process(e,t=null,n=!0){let r={tokens:e,tokens_pair:t};for(let e of this.processors)r=e.post_process(r.tokens,r.tokens_pair,n);return r}};function AO(e){if(e===null)return null;switch(e.type){case`TemplateProcessing`:return new TO(e);case`ByteLevel`:return new EO(e);case`BertProcessing`:return new DO(e);case`RobertaProcessing`:return new OO(e);case`Sequence`:return new kO(e);default:throw Error(`Unknown PostProcessor type: ${e.type}`)}}var jO=AO,MO=class extends ND{constructor(e){super(),this.config=e,this.added_tokens=[],this.end_of_word_suffix=null,this.trim_offsets=`trim_offsets`in e?e.trim_offsets:!1}_call(e){return this.decode(e)}decode(e){return this.decode_chain(e).join(``)}},NO=class extends MO{constructor(e){super(e),this.byte_decoder=hD,this.text_decoder=new TextDecoder(`utf-8`,{fatal:!1,ignoreBOM:!0}),this.end_of_word_suffix=null}convert_tokens_to_string(e){let t=e.join(``),n=new Uint8Array([...t].map(e=>this.byte_decoder[e]));return this.text_decoder.decode(n)}decode_chain(e){let t=[],n=[];for(let r of e)this.added_tokens.find(e=>e.content===r)===void 0?n.push(r):(n.length>0&&(t.push(this.convert_tokens_to_string(n)),n=[]),t.push(r));return n.length>0&&t.push(this.convert_tokens_to_string(n)),t}},PO=class extends MO{constructor(e){super(e),this.cleanup=e.cleanup}decode_chain(e){return e.map((e,t)=>{if(t!==0){let t=this.config.prefix;e=t&&e.startsWith(t)?e.replace(t,``):` `+e}return this.cleanup&&(e=yD(e)),e})}},FO=class extends MO{constructor(e){super(e),this.replacement=e.replacement??`▁`}decode_chain(e){let t=[];for(let n=0;nt.replaceAll(this.suffix,n===e.length-1?``:` `))}},LO=class extends MO{constructor(e){super(e),this.pad_token=e.pad_token??``,this.word_delimiter_token=e.word_delimiter_token??``,this.cleanup=e.cleanup}convert_tokens_to_string(e){if(e.length===0)return``;let t=[e[0]];for(let n=1;ne!==this.pad_token).join(``);return this.cleanup&&(n=yD(n).replaceAll(this.word_delimiter_token,` `).trim()),n}decode_chain(e){return[this.convert_tokens_to_string(e)]}},RO=class extends MO{constructor(e){super(e),this.decoders=(e.decoders??[]).map(e=>WO(e))}decode_chain(e){return this.decoders.reduce((e,t)=>t.decode_chain(e),e)}},zO=class extends MO{decode_chain(e){let t=bD(this.config.pattern),n=this.config.content??``;return t===null?e:e.map(e=>e.replaceAll(t,n))}},BO=class extends MO{decode_chain(e){return[e.join(``)]}},VO=class extends MO{constructor(e){super(e),this.content=e.content??``,this.start=e.start??0,this.stop=e.stop??0}decode_chain(e){return e.map(e=>{let t=0;for(let n=0;n`)){let t=parseInt(r.slice(3,5),16);isNaN(t)||(e=t)}if(e!==null)n.push(e);else{if(n.length>0){let e=this.text_decoder.decode(Uint8Array.from(n));t.push(e),n=[]}t.push(r)}}if(n.length>0){let e=this.text_decoder.decode(Uint8Array.from(n));t.push(e),n=[]}return t}};function UO(e){if(e===null)return null;switch(e.type){case`ByteLevel`:return new NO(e);case`WordPiece`:return new PO(e);case`Metaspace`:return new FO(e);case`BPEDecoder`:return new IO(e);case`CTC`:return new LO(e);case`Sequence`:return new RO(e);case`Replace`:return new zO(e);case`Fuse`:return new BO(e);case`Strip`:return new VO(e);case`ByteFallback`:return new HO(e);default:throw Error(`Unknown Decoder type: ${e.type}`)}}var WO=UO,GO=class{constructor(e,t){let n=jD(e,`Tokenizer`,[`model`,`decoder`,`post_processor`,`pre_tokenizer`,`normalizer`]);if(n)throw Error(n);let r=jD(t,`Config`);if(r)throw Error(r);this.tokenizer=e,this.config=t,this.normalizer=YD(this.tokenizer.normalizer),this.pre_tokenizer=lO(this.tokenizer.pre_tokenizer),this.model=CO(this.tokenizer.model,this.config),this.post_processor=jO(this.tokenizer.post_processor),this.decoder=WO(this.tokenizer.decoder),this.special_tokens=[],this.all_special_ids=[],this.added_tokens=[];let i=[],a=[];this.added_tokens_map=new Map;for(let e of this.tokenizer.added_tokens){let t=new pD(e);if(this.added_tokens.push(t),this.model.tokens_to_ids.set(t.content,t.id),this.model.vocab[t.id]=t.content,t.special&&(this.special_tokens.push(t.content),this.all_special_ids.push(t.id)),this.added_tokens_map.set(t.content,t),t.normalized&&this.normalizer!==null){let e=this.normalizer(t.content);a.push(e),this.added_tokens_map.set(e,t)}else i.push(t.content)}(this.config.additional_special_tokens??[]).forEach(e=>{this.special_tokens.includes(e)||this.special_tokens.push(e)}),this.decoder&&(this.decoder.added_tokens=this.added_tokens,this.decoder.end_of_word_suffix=this.model.end_of_word_suffix),this.splitter_unnormalized=new fD(i),this.splitter_normalized=new fD(a),this.remove_space=this.config.remove_space,this.clean_up_tokenization_spaces=this.config.clean_up_tokenization_spaces??!0,this.do_lowercase_and_remove_accent=this.config.do_lowercase_and_remove_accent??!1}encode(e,{text_pair:t=null,add_special_tokens:n=!0,return_token_type_ids:r=null}={}){let{tokens:i,token_type_ids:a}=this.tokenize_helper(e,{text_pair:t,add_special_tokens:n}),o=i.map(e=>this.added_tokens_map.get(e)?.id??this.model.tokens_to_ids.get(e)??this.model.unk_token_id),s={ids:o,tokens:i,attention_mask:Array(o.length).fill(1)};return r&&a&&(s.token_type_ids=a),s}decode(e,t={}){if(!Array.isArray(e)||e.length===0||!wD(e[0]))throw Error(`token_ids must be a non-empty array of integers.`);let n=e.map(e=>this.model.vocab[Number(e)]??this.model.unk_token);t.skip_special_tokens&&(n=n.filter(e=>!this.special_tokens.includes(e)));let r=this.decoder?this.decoder(n):n.join(` `);return this.decoder&&this.decoder.end_of_word_suffix&&(r=r.replaceAll(this.decoder.end_of_word_suffix,` `),t.skip_special_tokens&&(r=r.trim())),(t.clean_up_tokenization_spaces??this.clean_up_tokenization_spaces)&&(r=yD(r)),r}tokenize(e,{text_pair:t=null,add_special_tokens:n=!1}={}){return this.tokenize_helper(e,{text_pair:t,add_special_tokens:n}).tokens}encode_text(e){if(e===null)return null;let t=this.splitter_unnormalized.split(e);return t.forEach((e,n)=>{let r=this.added_tokens_map.get(e);r&&(r.lstrip&&n>0&&(t[n-1]=t[n-1].trimEnd()),r.rstrip&&n{if(e.length===0)return[];if(this.added_tokens_map.has(e))return[e];if(this.remove_space===!0&&(e=e.trim().split(/\s+/).join(` `)),this.do_lowercase_and_remove_accent&&(e=ED(e)),this.normalizer!==null&&(e=this.normalizer(e)),e.length===0)return[];let n=this.splitter_normalized.split(e);return n.forEach((e,t)=>{let r=this.added_tokens_map.get(e);r&&(r.lstrip&&t>0&&(n[t-1]=n[t-1].trimEnd()),r.rstrip&&t{if(e.length===0)return[];if(this.added_tokens_map.has(e))return[e];let n=this.pre_tokenizer===null?[e]:this.pre_tokenizer(e,{section_index:t});return this.model(n)})})}tokenize_helper(e,{text_pair:t=null,add_special_tokens:n=!0}){let r=this.encode_text(e),i=this.encode_text(t||null);return this.post_processor?this.post_processor(r,i,n):{tokens:DD(r??[],i??[])}}token_to_id(e){return this.model.tokens_to_ids.get(e)}id_to_token(e){return this.model.vocab[e]}get_added_tokens_decoder(){let e=new Map;for(let t of this.added_tokens)e.set(t.id,t);return e}get_vocab(e=!0){let t=new Map;for(let n=0;n=`,Y.ComparisonBinaryOperator],[`==`,Y.ComparisonBinaryOperator],[`!=`,Y.ComparisonBinaryOperator],[`<`,Y.ComparisonBinaryOperator],[`>`,Y.ComparisonBinaryOperator],[`+`,Y.AdditiveBinaryOperator],[`-`,Y.AdditiveBinaryOperator],[`~`,Y.AdditiveBinaryOperator],[`*`,Y.MultiplicativeBinaryOperator],[`/`,Y.MultiplicativeBinaryOperator],[`%`,Y.MultiplicativeBinaryOperator],[`=`,Y.Equals]],ZO=new Map([[`n`,` +`],[`t`,` `],[`r`,`\r`],[`b`,`\b`],[`f`,`\f`],[`v`,`\v`],[`'`,`'`],[`"`,`"`],[`\\`,`\\`]]);function QO(e,t={}){return e.endsWith(` +`)&&(e=e.slice(0,-1)),t.lstrip_blocks&&(e=e.replace(/^[ \t]*({[#%-])/gm,`$1`)),t.trim_blocks&&(e=e.replace(/([#%-]})\n/g,`$1`)),e.replace(/{%\s*(end)?generation\s*%}/gs,``)}function $O(e,t={}){let n=[],r=QO(e,t),i=0,a=0,o=e=>{let t=``;for(;e(r[i]);){if(r[i]===`\\`){if(++i,i>=r.length)throw SyntaxError(`Unexpected end of input`);let e=r[i++],n=ZO.get(e);if(n===void 0)throw SyntaxError(`Unexpected escaped character: ${e}`);t+=n;continue}if(t+=r[i++],i>=r.length)throw SyntaxError(`Unexpected end of input`)}return t},s=()=>{let e=n.at(-1);e&&e.type===Y.Text&&(e.value=e.value.trimEnd(),e.value===``&&n.pop())},c=()=>{for(;i0){n.push(new KO(e,Y.Text));continue}}if(r[i]===`{`&&r[i+1]===`#`){i+=2;let e=r[i]===`-`;e&&++i;let t=``;for(;r[i]!==`#`||r[i+1]!==`}`;){if(i+2>=r.length)throw SyntaxError(`Missing end of comment tag`);t+=r[i++]}let a=t.endsWith(`-`);a&&(t=t.slice(0,-1)),e&&s(),n.push(new KO(t,Y.Comment)),i+=2,a&&c();continue}if(r.slice(i,i+3)===`{%-`){s(),n.push(new KO(`{%`,Y.OpenStatement)),i+=3;continue}if(r.slice(i,i+3)===`{{-`){s(),n.push(new KO(`{{`,Y.OpenExpression)),a=0,i+=3;continue}if(o(YO),r.slice(i,i+3)===`-%}`){n.push(new KO(`%}`,Y.CloseStatement)),i+=3,c();continue}if(r.slice(i,i+3)===`-}}`){n.push(new KO(`}}`,Y.CloseExpression)),i+=3,c();continue}let t=r[i];if(t===`-`||t===`+`){let e=n.at(-1)?.type;if(e===Y.Text||e===void 0)throw SyntaxError(`Unexpected character: ${t}`);switch(e){case Y.Identifier:case Y.NumericLiteral:case Y.StringLiteral:case Y.CloseParen:case Y.CloseSquareBracket:break;default:{++i;let e=o(JO);n.push(new KO(`${t}${e}`,e.length>0?Y.NumericLiteral:Y.UnaryOperator));continue}}}for(let[e,t]of XO)if(!(e===`}}`&&a>0)&&r.slice(i,i+e.length)===e){n.push(new KO(e,t)),t===Y.OpenExpression?a=0:t===Y.OpenCurlyBracket?++a:t===Y.CloseCurlyBracket&&--a,i+=e.length;continue main}if(t===`'`||t===`"`){++i;let e=o(e=>e!==t);n.push(new KO(e,Y.StringLiteral)),++i;continue}if(JO(t)){let e=o(JO);if(r[i]===`.`&&JO(r[i+1])){++i;let t=o(JO);e=`${e}.${t}`}n.push(new KO(e,Y.NumericLiteral));continue}if(qO(t)){let e=o(qO);n.push(new KO(e,Y.Identifier));continue}throw SyntaxError(`Unexpected character: ${t}`)}return n}var ek=class{type=`Statement`},tk=class extends ek{constructor(e){super(),this.body=e}type=`Program`},nk=class extends ek{constructor(e,t,n){super(),this.test=e,this.body=t,this.alternate=n}type=`If`},rk=class extends ek{constructor(e,t,n,r){super(),this.loopvar=e,this.iterable=t,this.body=n,this.defaultBlock=r}type=`For`},ik=class extends ek{type=`Break`},ak=class extends ek{type=`Continue`},ok=class extends ek{constructor(e,t,n){super(),this.assignee=e,this.value=t,this.body=n}type=`Set`},sk=class extends ek{constructor(e,t,n){super(),this.name=e,this.args=t,this.body=n}type=`Macro`},ck=class extends ek{constructor(e){super(),this.value=e}type=`Comment`},lk=class extends ek{type=`Expression`},uk=class extends lk{constructor(e,t,n){super(),this.object=e,this.property=t,this.computed=n}type=`MemberExpression`},dk=class extends lk{constructor(e,t){super(),this.callee=e,this.args=t}type=`CallExpression`},fk=class extends lk{constructor(e){super(),this.value=e}type=`Identifier`},pk=class extends lk{constructor(e){super(),this.value=e}type=`Literal`},mk=class extends pk{type=`IntegerLiteral`},hk=class extends pk{type=`FloatLiteral`},gk=class extends pk{type=`StringLiteral`},_k=class extends pk{type=`ArrayLiteral`},vk=class extends pk{type=`TupleLiteral`},yk=class extends pk{type=`ObjectLiteral`},bk=class extends lk{constructor(e,t,n){super(),this.operator=e,this.left=t,this.right=n}type=`BinaryExpression`},xk=class extends lk{constructor(e,t){super(),this.operand=e,this.filter=t}type=`FilterExpression`},Sk=class extends ek{constructor(e,t){super(),this.filter=e,this.body=t}type=`FilterStatement`},Ck=class extends lk{constructor(e,t){super(),this.lhs=e,this.test=t}type=`SelectExpression`},wk=class extends lk{constructor(e,t,n){super(),this.operand=e,this.negate=t,this.test=n}type=`TestExpression`},Tk=class extends lk{constructor(e,t){super(),this.operator=e,this.argument=t}type=`UnaryExpression`},Ek=class extends lk{constructor(e=void 0,t=void 0,n=void 0){super(),this.start=e,this.stop=t,this.step=n}type=`SliceExpression`},Dk=class extends lk{constructor(e,t){super(),this.key=e,this.value=t}type=`KeywordArgumentExpression`},Ok=class extends lk{constructor(e){super(),this.argument=e}type=`SpreadExpression`},kk=class extends ek{constructor(e,t,n){super(),this.call=e,this.callerArgs=t,this.body=n}type=`CallStatement`},Ak=class extends lk{constructor(e,t,n){super(),this.condition=e,this.trueExpr=t,this.falseExpr=n}type=`Ternary`};function jk(e){let t=new tk([]),n=0;function r(t,r){let i=e[n++];if(!i||i.type!==t)throw Error(`Parser Error: ${r}. ${i.type} !== ${t}.`);return i}function i(e){if(!c(e))throw SyntaxError(`Expected ${e}`);++n}function a(){switch(e[n].type){case Y.Comment:return new ck(e[n++].value);case Y.Text:return l();case Y.OpenStatement:return u();case Y.OpenExpression:return d();default:throw SyntaxError(`Unexpected token type: ${e[n].type}`)}}function o(...t){return n+t.length<=e.length&&t.every((t,r)=>t===e[n+r].type)}function s(...t){return e[n]?.type===Y.OpenStatement&&e[n+1]?.type===Y.Identifier&&t.includes(e[n+1]?.value)}function c(...t){return n+t.length<=e.length&&t.every((t,r)=>e[n+r].type===`Identifier`&&t===e[n+r].value)}function l(){return new gk(r(Y.Text,`Expected text token`).value)}function u(){if(r(Y.OpenStatement,`Expected opening statement token`),e[n].type!==Y.Identifier)throw SyntaxError(`Unknown statement, got ${e[n].type}`);let t=e[n].value,c;switch(t){case`set`:++n,c=f();break;case`if`:++n,c=p(),r(Y.OpenStatement,`Expected {% token`),i(`endif`),r(Y.CloseStatement,`Expected %} token`);break;case`macro`:++n,c=m(),r(Y.OpenStatement,`Expected {% token`),i(`endmacro`),r(Y.CloseStatement,`Expected %} token`);break;case`for`:++n,c=g(),r(Y.OpenStatement,`Expected {% token`),i(`endfor`),r(Y.CloseStatement,`Expected %} token`);break;case`call`:{++n;let e=null;o(Y.OpenParen)&&(e=E());let t=M();if(t.type!==`Identifier`)throw SyntaxError(`Expected identifier following call statement`);let l=E();r(Y.CloseStatement,`Expected closing statement token`);let u=[];for(;!s(`endcall`);)u.push(a());r(Y.OpenStatement,`Expected '{%'`),i(`endcall`),r(Y.CloseStatement,`Expected closing statement token`),c=new kk(new dk(t,l),e,u);break}case`break`:++n,r(Y.CloseStatement,`Expected closing statement token`),c=new ik;break;case`continue`:++n,r(Y.CloseStatement,`Expected closing statement token`),c=new ak;break;case`filter`:{++n;let e=M();e instanceof fk&&o(Y.OpenParen)&&(e=T(e)),r(Y.CloseStatement,`Expected closing statement token`);let t=[];for(;!s(`endfilter`);)t.push(a());r(Y.OpenStatement,`Expected '{%'`),i(`endfilter`),r(Y.CloseStatement,`Expected '%}'`),c=new Sk(e,t);break}default:throw SyntaxError(`Unknown statement type: ${t}`)}return c}function d(){r(Y.OpenExpression,`Expected opening expression token`);let e=_();return r(Y.CloseExpression,`Expected closing expression token`),e}function f(){let e=h(),t=null,c=[];if(o(Y.Equals))++n,t=h();else{for(r(Y.CloseStatement,`Expected %} token`);!s(`endset`);)c.push(a());r(Y.OpenStatement,`Expected {% token`),i(`endset`)}return r(Y.CloseStatement,`Expected closing statement token`),new ok(e,t,c)}function p(){let e=_();r(Y.CloseStatement,`Expected closing statement token`);let t=[],i=[];for(;!s(`elif`,`else`,`endif`);)t.push(a());if(s(`elif`)){++n,++n;let e=p();i.push(e)}else if(s(`else`))for(++n,++n,r(Y.CloseStatement,`Expected closing statement token`);!s(`endif`);)i.push(a());return new nk(e,t,i)}function m(){let e=M();if(e.type!==`Identifier`)throw SyntaxError(`Expected identifier following macro statement`);let t=E();r(Y.CloseStatement,`Expected closing statement token`);let n=[];for(;!s(`endmacro`);)n.push(a());return new sk(e,t,n)}function h(e=!1){let t=e?M:_,r=[t()],i=o(Y.Comma);for(;i&&(++n,r.push(t()),o(Y.Comma)););return i?new vk(r):r[0]}function g(){let e=h(!0);if(!(e instanceof fk||e instanceof vk))throw SyntaxError(`Expected identifier/tuple for the loop variable, got ${e.type} instead`);if(!c(`in`))throw SyntaxError("Expected `in` keyword following loop variable");++n;let t=_();r(Y.CloseStatement,`Expected closing statement token`);let i=[];for(;!s(`endfor`,`else`);)i.push(a());let o=[];if(s(`else`))for(++n,++n,r(Y.CloseStatement,`Expected closing statement token`);!s(`endfor`);)o.push(a());return new rk(e,t,i,o)}function _(){return v()}function v(){let e=y();if(c(`if`)){++n;let t=y();return c(`else`)?(++n,new Ak(t,e,v())):new Ck(e,t)}return e}function y(){let t=b();for(;c(`or`);){let r=e[n];++n;let i=b();t=new bk(r,t,i)}return t}function b(){let t=x();for(;c(`and`);){let r=e[n];++n;let i=x();t=new bk(r,t,i)}return t}function x(){let t;for(;c(`not`);){let r=e[n];++n,t=new Tk(r,x())}return t??S()}function S(){let t=C();for(;;){let r;if(c(`not`,`in`))r=new KO(`not in`,Y.Identifier),n+=2;else if(c(`in`))r=e[n++];else if(o(Y.ComparisonBinaryOperator))r=e[n++];else break;let i=C();t=new bk(r,t,i)}return t}function C(){let t=A();for(;o(Y.AdditiveBinaryOperator);){let r=e[n];++n;let i=A();t=new bk(r,t,i)}return t}function w(){let e=k(M());return o(Y.OpenParen)?T(e):e}function T(e){let t=new dk(e,E());return t=k(t),o(Y.OpenParen)&&(t=T(t)),t}function E(){r(Y.OpenParen,`Expected opening parenthesis for arguments list`);let e=D();return r(Y.CloseParen,`Expected closing parenthesis for arguments list`),e}function D(){let t=[];for(;!o(Y.CloseParen);){let r;if(e[n].type===Y.MultiplicativeBinaryOperator&&e[n].value===`*`)++n,r=new Ok(_());else if(r=_(),o(Y.Equals)){if(++n,!(r instanceof fk))throw SyntaxError(`Expected identifier for keyword argument`);let e=_();r=new Dk(r,e)}t.push(r),o(Y.Comma)&&++n}return t}function O(){let e=[],t=!1;for(;!o(Y.CloseSquareBracket);)o(Y.Colon)?(e.push(void 0),++n,t=!0):(e.push(_()),o(Y.Colon)&&(++n,t=!0));if(e.length===0)throw SyntaxError(`Expected at least one argument for member/slice expression`);if(t){if(e.length>3)throw SyntaxError(`Expected 0-3 arguments for slice expression`);return new Ek(...e)}return e[0]}function k(t){for(;o(Y.Dot)||o(Y.OpenSquareBracket);){let i=e[n];++n;let a,o=i.type===Y.OpenSquareBracket;if(o)a=O(),r(Y.CloseSquareBracket,`Expected closing square bracket`);else if(a=M(),a.type!==`Identifier`)throw SyntaxError(`Expected identifier following dot operator`);t=new uk(t,a,o)}return t}function A(){let t=j();for(;o(Y.MultiplicativeBinaryOperator);){let r=e[n++],i=j();t=new bk(r,t,i)}return t}function j(){let e=ee();for(;c(`is`);){++n;let t=c(`not`);t&&++n;let r=M();if(!(r instanceof fk))throw SyntaxError(`Expected identifier for the test`);e=new wk(e,t,r)}return e}function ee(){let e=w();for(;o(Y.Pipe);){++n;let t=M();if(!(t instanceof fk))throw SyntaxError(`Expected identifier for the filter`);o(Y.OpenParen)&&(t=T(t)),e=new xk(e,t)}return e}function M(){let t=e[n++];switch(t.type){case Y.NumericLiteral:{let e=t.value;return e.includes(`.`)?new hk(Number(e)):new mk(Number(e))}case Y.StringLiteral:{let r=t.value;for(;o(Y.StringLiteral);)r+=e[n++].value;return new gk(r)}case Y.Identifier:return new fk(t.value);case Y.OpenParen:{let e=h();return r(Y.CloseParen,"Expected closing parenthesis, got ${tokens[current].type} instead."),e}case Y.OpenSquareBracket:{let e=[];for(;!o(Y.CloseSquareBracket);)e.push(_()),o(Y.Comma)&&++n;return++n,new _k(e)}case Y.OpenCurlyBracket:{let e=new Map;for(;!o(Y.CloseCurlyBracket);){let t=_();r(Y.Colon,`Expected colon between key and value in object literal`);let i=_();e.set(t,i),o(Y.Comma)&&++n}return++n,new yk(e)}default:throw SyntaxError(`Unexpected token: ${t.type}`)}}for(;n0)for(let i=e;it;i+=n)r.push(i);return r}function Nk(e,t,n,r=1){let i=Math.sign(r);i>=0?(t=(t??=0)<0?Math.max(e.length+t,0):Math.min(t,e.length),n=(n??=e.length)<0?Math.max(e.length+n,0):Math.min(n,e.length)):(t=(t??=e.length-1)<0?Math.max(e.length+t,-1):Math.min(t,e.length-1),n=(n??=-1)<-1?Math.max(e.length+n,-1):Math.min(n,e.length-1));let a=[];for(let o=t;i*oe.toUpperCase())}function Fk(e){return Ik(new Date,e)}function Ik(e,t){let n=new Intl.DateTimeFormat(void 0,{month:`long`}),r=new Intl.DateTimeFormat(void 0,{month:`short`}),i=e=>e<10?`0`+e:e.toString();return t.replace(/%[YmdbBHM%]/g,t=>{switch(t){case`%Y`:return e.getFullYear().toString();case`%m`:return i(e.getMonth()+1);case`%d`:return i(e.getDate());case`%b`:return r.format(e);case`%B`:return n.format(e);case`%H`:return i(e.getHours());case`%M`:return i(e.getMinutes());case`%%`:return`%`;default:return t}})}function Lk(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function Rk(e,t,n,r){if(r===0)return e;let i=r==null||r<0?1/0:r,a=t.length===0?RegExp(`(?=)`,`gu`):new RegExp(Lk(t),`gu`);return e.replaceAll(a,e=>i>0?(--i,n):e)}var zk=class extends Error{},Bk=class extends Error{},Vk=class{type=`RuntimeValue`;value;builtins=new Map;constructor(e=void 0){this.value=e}__bool__(){return new Wk(!!this.value)}toString(){return String(this.value)}},Hk=class extends Vk{type=`IntegerValue`},Uk=class extends Vk{type=`FloatValue`;toString(){return this.value%1==0?this.value.toFixed(1):this.value.toString()}},X=class extends Vk{type=`StringValue`;builtins=new Map([[`upper`,new Qk(()=>new X(this.value.toUpperCase()))],[`lower`,new Qk(()=>new X(this.value.toLowerCase()))],[`strip`,new Qk(()=>new X(this.value.trim()))],[`title`,new Qk(()=>new X(Pk(this.value)))],[`capitalize`,new Qk(()=>new X(this.value.charAt(0).toUpperCase()+this.value.slice(1)))],[`length`,new Hk(this.value.length)],[`rstrip`,new Qk(()=>new X(this.value.trimEnd()))],[`lstrip`,new Qk(()=>new X(this.value.trimStart()))],[`startswith`,new Qk(e=>{if(e.length===0)throw Error(`startswith() requires at least one argument`);let t=e[0];if(t instanceof X)return new Wk(this.value.startsWith(t.value));if(t instanceof Xk){for(let e of t.value){if(!(e instanceof X))throw Error(`startswith() tuple elements must be strings`);if(this.value.startsWith(e.value))return new Wk(!0)}return new Wk(!1)}throw Error(`startswith() argument must be a string or tuple of strings`)})],[`endswith`,new Qk(e=>{if(e.length===0)throw Error(`endswith() requires at least one argument`);let t=e[0];if(t instanceof X)return new Wk(this.value.endsWith(t.value));if(t instanceof Xk){for(let e of t.value){if(!(e instanceof X))throw Error(`endswith() tuple elements must be strings`);if(this.value.endsWith(e.value))return new Wk(!0)}return new Wk(!1)}throw Error(`endswith() argument must be a string or tuple of strings`)})],[`split`,new Qk(e=>{let t=e[0]??new $k;if(!(t instanceof X||t instanceof $k))throw Error(`sep argument must be a string or null`);let n=e[1]??new Hk(-1);if(!(n instanceof Hk))throw Error(`maxsplit argument must be a number`);let r=[];if(t instanceof $k){let e=this.value.trimStart();for(let{0:t,index:i}of e.matchAll(/\S+/g)){if(n.value!==-1&&r.length>=n.value&&i!==void 0){r.push(t+e.slice(i+t.length));break}r.push(t)}}else{if(t.value===``)throw Error(`empty separator`);r=this.value.split(t.value),n.value!==-1&&r.length>n.value&&r.push(r.splice(n.value).join(t.value))}return new Xk(r.map(e=>new X(e)))})],[`replace`,new Qk(e=>{if(e.length<2)throw Error(`replace() requires at least two arguments`);let t=e[0],n=e[1];if(!(t instanceof X&&n instanceof X))throw Error(`replace() arguments must be strings`);let r;if(r=e.length>2?e[2].type===`KeywordArgumentsValue`?e[2].value.get(`count`)??new $k:e[2]:new $k,!(r instanceof Hk||r instanceof $k))throw Error(`replace() count argument must be a number or null`);return new X(Rk(this.value,t.value,n.value,r.value))})]])},Wk=class extends Vk{type=`BooleanValue`},Gk=/[\x7f-\uffff]/g;function Kk(e){return e.replace(Gk,e=>`\\u`+e.charCodeAt(0).toString(16).padStart(4,`0`))}function qk(e,t={},n=0,r=!0){let{indent:i=null,ensureAscii:a=!1,separators:o=null,sortKeys:s=!1}=t,c,l;switch(o?[c,l]=o:i?(c=`,`,l=`: `):(c=`, `,l=`: `),e.type){case`NullValue`:return`null`;case`UndefinedValue`:return r?`null`:`undefined`;case`IntegerValue`:case`FloatValue`:case`BooleanValue`:return JSON.stringify(e.value);case`StringValue`:{let t=JSON.stringify(e.value);return a&&(t=Kk(t)),t}case`ArrayValue`:case`ObjectValue`:{let o=i?` `.repeat(i):``,u=` +`+o.repeat(n),d=u+o;if(e.type===`ArrayValue`){let a=e.value.map(e=>qk(e,t,n+1,r));return i?`[${d}${a.join(`${c}${d}`)}${u}]`:`[${a.join(c)}]`}else{let o=Array.from(e.value.entries());s&&(o=o.sort(([e],[t])=>e.localeCompare(t)));let f=o.map(([e,o])=>{let s=JSON.stringify(e);a&&(s=Kk(s));let c=`${s}${l}${qk(o,t,n+1,r)}`;return i?`${d}${c}`:c});return i?`{${f.join(c)}${u}}`:`{${f.join(c)}}`}}default:throw Error(`Cannot convert to JSON: ${e.type}`)}}var Jk=class extends Vk{type=`ObjectValue`;__bool__(){return new Wk(this.value.size>0)}builtins=new Map([[`get`,new Qk(([e,t])=>{if(!(e instanceof X))throw Error(`Object key must be a string: got ${e.type}`);return this.value.get(e.value)??t??new $k})],[`items`,new Qk(()=>this.items())],[`keys`,new Qk(()=>this.keys())],[`values`,new Qk(()=>this.values())],[`dictsort`,new Qk(e=>{let t=new Map,n=e.filter(e=>e instanceof Yk?(t=e.value,!1):!0),r=n.at(0)??t.get(`case_sensitive`)??new Wk(!1);if(!(r instanceof Wk))throw Error(`case_sensitive must be a boolean`);let i=n.at(1)??t.get(`by`)??new X(`key`);if(!(i instanceof X))throw Error(`by must be a string`);if(![`key`,`value`].includes(i.value))throw Error(`by must be either 'key' or 'value'`);let a=n.at(2)??t.get(`reverse`)??new Wk(!1);if(!(a instanceof Wk))throw Error(`reverse must be a boolean`);return new Xk(Array.from(this.value.entries()).map(([e,t])=>new Xk([new X(e),t])).sort((e,t)=>{let n=i.value===`key`?0:1,o=e.value[n],s=t.value[n],c=iA(o,s,r.value);return a.value?-c:c}))})]]);items(){return new Xk(Array.from(this.value.entries()).map(([e,t])=>new Xk([new X(e),t])))}keys(){return new Xk(Array.from(this.value.keys()).map(e=>new X(e)))}values(){return new Xk(Array.from(this.value.values()))}toString(){return qk(this,{},0,!1)}},Yk=class extends Jk{type=`KeywordArgumentsValue`},Xk=class extends Vk{type=`ArrayValue`;builtins=new Map([[`length`,new Hk(this.value.length)]]);__bool__(){return new Wk(this.value.length>0)}toString(){return qk(this,{},0,!1)}},Zk=class extends Xk{type=`TupleValue`},Qk=class extends Vk{type=`FunctionValue`},$k=class extends Vk{type=`NullValue`},eA=class extends Vk{type=`UndefinedValue`},tA=class{constructor(e){this.parent=e}variables=new Map([[`namespace`,new Qk(e=>{if(e.length===0)return new Jk(new Map);if(e.length!==1||!(e[0]instanceof Jk))throw Error("`namespace` expects either zero arguments or a single object argument");return e[0]})]]);tests=new Map([[`boolean`,e=>e.type===`BooleanValue`],[`callable`,e=>e instanceof Qk],[`odd`,e=>{if(!(e instanceof Hk))throw Error(`cannot odd on ${e.type}`);return e.value%2!=0}],[`even`,e=>{if(!(e instanceof Hk))throw Error(`cannot even on ${e.type}`);return e.value%2==0}],[`false`,e=>e.type===`BooleanValue`&&!e.value],[`true`,e=>e.type===`BooleanValue`&&e.value],[`none`,e=>e.type===`NullValue`],[`string`,e=>e.type===`StringValue`],[`number`,e=>e instanceof Hk||e instanceof Uk],[`integer`,e=>e instanceof Hk],[`iterable`,e=>e.type===`ArrayValue`||e.type===`StringValue`],[`mapping`,e=>e instanceof Jk],[`sequence`,e=>e instanceof Xk||e instanceof Jk||e instanceof X],[`lower`,e=>{let t=e.value;return e.type===`StringValue`&&t===t.toLowerCase()}],[`upper`,e=>{let t=e.value;return e.type===`StringValue`&&t===t.toUpperCase()}],[`none`,e=>e.type===`NullValue`],[`defined`,e=>e.type!==`UndefinedValue`],[`undefined`,e=>e.type===`UndefinedValue`],[`equalto`,(e,t)=>e.value===t.value],[`eq`,(e,t)=>e.value===t.value]]);set(e,t){return this.declareVariable(e,oA(t))}declareVariable(e,t){if(this.variables.has(e))throw SyntaxError(`Variable already declared: ${e}`);return this.variables.set(e,t),t}setVariable(e,t){return this.variables.set(e,t),t}resolve(e){if(this.variables.has(e))return this;if(this.parent)return this.parent.resolve(e);throw Error(`Unknown variable: ${e}`)}lookupVariable(e){try{return this.resolve(e).variables.get(e)??new eA}catch{return new eA}}};function nA(e){e.set(`false`,!1),e.set(`true`,!0),e.set(`none`,null),e.set(`raise_exception`,e=>{throw Error(e)}),e.set(`range`,Mk),e.set(`strftime_now`,Fk),e.set(`True`,!0),e.set(`False`,!1),e.set(`None`,null)}function rA(e,t){let n=t.split(`.`),r=e;for(let e of n)if(r instanceof Jk)r=r.value.get(e)??new eA;else if(r instanceof Xk){let t=parseInt(e,10);if(!isNaN(t)&&t>=0&&te instanceof Hk||e instanceof Uk||e instanceof Wk,i=e=>e instanceof Wk?e.value?1:0:e.value;if(r(e)&&r(t)){let n=i(e),r=i(t);return nr?1:0}if(e.type!==t.type)throw Error(`Cannot compare different types: ${e.type} and ${t.type}`);switch(e.type){case`StringValue`:{let r=e.value,i=t.value;return n||(r=r.toLowerCase(),i=i.toLowerCase()),ri?1:0}default:throw Error(`Cannot compare type: ${e.type}`)}}var aA=class{global;constructor(e){this.global=e??new tA}run(e){return this.evaluate(e,this.global)}evaluateBinaryExpression(e,t){let n=this.evaluate(e.left,t);switch(e.operator.value){case`and`:return n.__bool__().value?this.evaluate(e.right,t):n;case`or`:return n.__bool__().value?n:this.evaluate(e.right,t)}let r=this.evaluate(e.right,t);switch(e.operator.value){case`==`:return new Wk(n.value==r.value);case`!=`:return new Wk(n.value!=r.value)}if(n instanceof eA||r instanceof eA){if(r instanceof eA&&[`in`,`not in`].includes(e.operator.value))return new Wk(e.operator.value===`not in`);throw Error(`Cannot perform operation ${e.operator.value} on undefined values`)}else if(n instanceof $k||r instanceof $k)throw Error(`Cannot perform operation on null values`);else if(e.operator.value===`~`)return new X(n.value.toString()+r.value.toString());else if((n instanceof Hk||n instanceof Uk)&&(r instanceof Hk||r instanceof Uk)){let t=n.value,i=r.value;switch(e.operator.value){case`+`:case`-`:case`*`:{let a=e.operator.value===`+`?t+i:e.operator.value===`-`?t-i:t*i;return n instanceof Uk||r instanceof Uk?new Uk(a):new Hk(a)}case`/`:return new Uk(t/i);case`%`:{let e=t%i;return n instanceof Uk||r instanceof Uk?new Uk(e):new Hk(e)}case`<`:return new Wk(t`:return new Wk(t>i);case`>=`:return new Wk(t>=i);case`<=`:return new Wk(t<=i)}}else if(n instanceof Xk&&r instanceof Xk)switch(e.operator.value){case`+`:return new Xk(n.value.concat(r.value))}else if(r instanceof Xk){let t=r.value.find(e=>e.value===n.value)!==void 0;switch(e.operator.value){case`in`:return new Wk(t);case`not in`:return new Wk(!t)}}if(n instanceof X||r instanceof X)switch(e.operator.value){case`+`:return new X(n.value.toString()+r.value.toString())}if(n instanceof X&&r instanceof X)switch(e.operator.value){case`in`:return new Wk(r.value.includes(n.value));case`not in`:return new Wk(!r.value.includes(n.value))}if(n instanceof X&&r instanceof Jk)switch(e.operator.value){case`in`:return new Wk(r.value.has(n.value));case`not in`:return new Wk(!r.value.has(n.value))}throw SyntaxError(`Unknown operator "${e.operator.value}" between ${n.type} and ${r.type}`)}evaluateArguments(e,t){let n=[],r=new Map;for(let i of e)if(i.type===`SpreadExpression`){let e=i,r=this.evaluate(e.argument,t);if(!(r instanceof Xk))throw Error(`Cannot unpack non-iterable type: ${r.type}`);for(let e of r.value)n.push(e)}else if(i.type===`KeywordArgumentExpression`){let e=i;r.set(e.key.value,this.evaluate(e.value,t))}else{if(r.size>0)throw Error(`Positional arguments must come before keyword arguments`);n.push(this.evaluate(i,t))}return[n,r]}applyFilter(e,t,n){if(t.type===`Identifier`){let r=t;if(r.value===`safe`)return e;if(r.value===`tojson`)return new X(qk(e,{}));if(e instanceof Xk)switch(r.value){case`list`:return e;case`first`:return e.value[0];case`last`:return e.value[e.value.length-1];case`length`:return new Hk(e.value.length);case`reverse`:return new Xk(e.value.slice().reverse());case`sort`:return new Xk(e.value.slice().sort((e,t)=>iA(e,t,!1)));case`join`:return new X(e.value.map(e=>e.value).join(``));case`string`:return new X(qk(e,{},0,!1));case`unique`:{let t=new Set,n=[];for(let r of e.value)t.has(r.value)||(t.add(r.value),n.push(r));return new Xk(n)}default:throw Error(`Unknown ArrayValue filter: ${r.value}`)}else if(e instanceof X)switch(r.value){case`length`:case`upper`:case`lower`:case`title`:case`capitalize`:{let t=e.builtins.get(r.value);if(t instanceof Qk)return t.value([],n);if(t instanceof Hk)return t;throw Error(`Unknown StringValue filter: ${r.value}`)}case`trim`:return new X(e.value.trim());case`indent`:return new X(e.value.split(` +`).map((e,t)=>t===0||e.length===0?e:` `+e).join(` +`));case`join`:case`string`:return e;case`int`:{let t=parseInt(e.value,10);return new Hk(isNaN(t)?0:t)}case`float`:{let t=parseFloat(e.value);return new Uk(isNaN(t)?0:t)}default:throw Error(`Unknown StringValue filter: ${r.value}`)}else if(e instanceof Hk||e instanceof Uk)switch(r.value){case`abs`:return e instanceof Hk?new Hk(Math.abs(e.value)):new Uk(Math.abs(e.value));case`int`:return new Hk(Math.floor(e.value));case`float`:return new Uk(e.value);case`string`:return new X(e.toString());default:throw Error(`Unknown NumericValue filter: ${r.value}`)}else if(e instanceof Jk)switch(r.value){case`items`:return new Xk(Array.from(e.value.entries()).map(([e,t])=>new Xk([new X(e),t])));case`length`:return new Hk(e.value.size);default:{let t=e.builtins.get(r.value);if(t)return t instanceof Qk?t.value([],n):t;throw Error(`Unknown ObjectValue filter: ${r.value}`)}}else if(e instanceof Wk)switch(r.value){case`bool`:return new Wk(e.value);case`int`:return new Hk(e.value?1:0);case`float`:return new Uk(e.value?1:0);case`string`:return new X(e.value?`true`:`false`);default:throw Error(`Unknown BooleanValue filter: ${r.value}`)}throw Error(`Cannot apply filter "${r.value}" to type: ${e.type}`)}else if(t.type===`CallExpression`){let r=t;if(r.callee.type!==`Identifier`)throw Error(`Unknown filter: ${r.callee.type}`);let i=r.callee.value;if(i===`tojson`){let[,t]=this.evaluateArguments(r.args,n),i=t.get(`indent`)??new $k;if(!(i instanceof Hk||i instanceof $k))throw Error(`If set, indent must be a number`);let a=t.get(`ensure_ascii`)??new Wk(!1);if(!(a instanceof Wk))throw Error(`If set, ensure_ascii must be a boolean`);let o=t.get(`sort_keys`)??new Wk(!1);if(!(o instanceof Wk))throw Error(`If set, sort_keys must be a boolean`);let s=t.get(`separators`)??new $k,c=null;if(s instanceof Xk||s instanceof Zk){if(s.value.length!==2)throw Error(`separators must be a tuple of two strings`);let[e,t]=s.value;if(!(e instanceof X)||!(t instanceof X))throw Error(`separators must be a tuple of two strings`);c=[e.value,t.value]}else if(!(s instanceof $k))throw Error(`If set, separators must be a tuple of two strings`);return new X(qk(e,{indent:i.value,ensureAscii:a.value,sortKeys:o.value,separators:c}))}else if(i===`join`){let t;if(e instanceof X)t=Array.from(e.value);else if(e instanceof Xk)t=e.value.map(e=>e.value);else throw Error(`Cannot apply filter "${i}" to type: ${e.type}`);let[a,o]=this.evaluateArguments(r.args,n),s=a.at(0)??o.get(`separator`)??new X(``);if(!(s instanceof X))throw Error(`separator must be a string`);return new X(t.join(s.value))}else if(i===`int`||i===`float`){let[t,a]=this.evaluateArguments(r.args,n),o=t.at(0)??a.get(`default`)??(i===`int`?new Hk(0):new Uk(0));if(e instanceof X){let t=i===`int`?parseInt(e.value,10):parseFloat(e.value);return isNaN(t)?o:i===`int`?new Hk(t):new Uk(t)}else if(e instanceof Hk||e instanceof Uk)return e;else if(e instanceof Wk)return i===`int`?new Hk(e.value?1:0):new Uk(e.value?1:0);else throw Error(`Cannot apply filter "${i}" to type: ${e.type}`)}else if(i===`default`){let[t,i]=this.evaluateArguments(r.args,n),a=t[0]??new X(``),o=t[1]??i.get(`boolean`)??new Wk(!1);if(!(o instanceof Wk))throw Error("`default` filter flag must be a boolean");return e instanceof eA||o.value&&!e.__bool__().value?a:e}if(e instanceof Xk){switch(i){case`sort`:{let[t,i]=this.evaluateArguments(r.args,n),a=t.at(0)??i.get(`reverse`)??new Wk(!1);if(!(a instanceof Wk))throw Error(`reverse must be a boolean`);let o=t.at(1)??i.get(`case_sensitive`)??new Wk(!1);if(!(o instanceof Wk))throw Error(`case_sensitive must be a boolean`);let s=t.at(2)??i.get(`attribute`)??new $k;if(!(s instanceof X||s instanceof Hk||s instanceof $k))throw Error(`attribute must be a string, integer, or null`);let c=e=>s instanceof $k?e:rA(e,s instanceof Hk?String(s.value):s.value);return new Xk(e.value.slice().sort((e,t)=>{let n=iA(c(e),c(t),o.value);return a.value?-n:n}))}case`selectattr`:case`rejectattr`:{let t=i===`selectattr`;if(e.value.some(e=>!(e instanceof Jk)))throw Error(`\`${i}\` can only be applied to array of objects`);if(r.args.some(e=>e.type!==`StringLiteral`))throw Error(`arguments of \`${i}\` must be strings`);let[a,o,s]=r.args.map(e=>this.evaluate(e,n)),c;if(o){let e=n.tests.get(o.value);if(!e)throw Error(`Unknown test: ${o.value}`);c=e}else c=(...e)=>e[0].__bool__().value;return new Xk(e.value.filter(e=>{let n=e.value.get(a.value),r=n?c(n,s):!1;return t?r:!r}))}case`map`:{let[,t]=this.evaluateArguments(r.args,n);if(t.has(`attribute`)){let n=t.get(`attribute`);if(!(n instanceof X))throw Error(`attribute must be a string`);let r=t.get(`default`);return new Xk(e.value.map(e=>{if(!(e instanceof Jk))throw Error(`items in map must be an object`);let t=rA(e,n.value);return t instanceof eA?r??new eA:t}))}else throw Error("`map` expressions without `attribute` set are not currently supported.")}}throw Error(`Unknown ArrayValue filter: ${i}`)}else if(e instanceof X){switch(i){case`indent`:{let[t,i]=this.evaluateArguments(r.args,n),a=t.at(0)??i.get(`width`)??new Hk(4);if(!(a instanceof Hk))throw Error(`width must be a number`);let o=t.at(1)??i.get(`first`)??new Wk(!1),s=t.at(2)??i.get(`blank`)??new Wk(!1),c=e.value.split(` +`),l=` `.repeat(a.value);return new X(c.map((e,t)=>!o.value&&t===0||!s.value&&e.length===0?e:l+e).join(` +`))}case`replace`:{let t=e.builtins.get(`replace`);if(!(t instanceof Qk))throw Error(`replace filter not available`);let[i,a]=this.evaluateArguments(r.args,n);return t.value([...i,new Yk(a)],n)}}throw Error(`Unknown StringValue filter: ${i}`)}else if(e instanceof Jk){let t=e.builtins.get(i);if(t&&t instanceof Qk){let[e,i]=this.evaluateArguments(r.args,n);return i.size>0&&e.push(new Yk(i)),t.value(e,n)}throw Error(`Unknown ObjectValue filter: ${i}`)}else throw Error(`Cannot apply filter "${i}" to type: ${e.type}`)}throw Error(`Unknown filter: ${t.type}`)}evaluateFilterExpression(e,t){let n=this.evaluate(e.operand,t);return this.applyFilter(n,e.filter,t)}evaluateTestExpression(e,t){let n=this.evaluate(e.operand,t),r=t.tests.get(e.test.value);if(!r)throw Error(`Unknown test: ${e.test.value}`);let i=r(n);return new Wk(e.negate?!i:i)}evaluateSelectExpression(e,t){return this.evaluate(e.test,t).__bool__().value?this.evaluate(e.lhs,t):new eA}evaluateUnaryExpression(e,t){let n=this.evaluate(e.argument,t);switch(e.operator.value){case`not`:return new Wk(!n.value);default:throw SyntaxError(`Unknown operator: ${e.operator.value}`)}}evaluateTernaryExpression(e,t){return this.evaluate(e.condition,t).__bool__().value?this.evaluate(e.trueExpr,t):this.evaluate(e.falseExpr,t)}evalProgram(e,t){return this.evaluateBlock(e.body,t)}evaluateBlock(e,t){let n=``;for(let r of e){let e=this.evaluate(r,t);e.type!==`NullValue`&&e.type!==`UndefinedValue`&&(n+=e.toString())}return new X(n)}evaluateIdentifier(e,t){return t.lookupVariable(e.value)}evaluateCallExpression(e,t){let[n,r]=this.evaluateArguments(e.args,t);r.size>0&&n.push(new Yk(r));let i=this.evaluate(e.callee,t);if(i.type!==`FunctionValue`)throw Error(`Cannot call something that is not a function: got ${i.type}`);return i.value(n,t)}evaluateSliceExpression(e,t,n){if(!(e instanceof Xk||e instanceof X))throw Error(`Slice object must be an array or string`);let r=this.evaluate(t.start,n),i=this.evaluate(t.stop,n),a=this.evaluate(t.step,n);if(!(r instanceof Hk||r instanceof eA))throw Error(`Slice start must be numeric or undefined`);if(!(i instanceof Hk||i instanceof eA))throw Error(`Slice stop must be numeric or undefined`);if(!(a instanceof Hk||a instanceof eA))throw Error(`Slice step must be numeric or undefined`);return e instanceof Xk?new Xk(Nk(e.value,r.value,i.value,a.value)):new X(Nk(Array.from(e.value),r.value,i.value,a.value).join(``))}evaluateMemberExpression(e,t){let n=this.evaluate(e.object,t),r;if(e.computed){if(e.property.type===`SliceExpression`)return this.evaluateSliceExpression(n,e.property,t);r=this.evaluate(e.property,t)}else r=new X(e.property.value);let i;if(n instanceof Jk){if(!(r instanceof X))throw Error(`Cannot access property with non-string: got ${r.type}`);i=n.value.get(r.value)??n.builtins.get(r.value)}else if(n instanceof Xk||n instanceof X)if(r instanceof Hk)i=n.value.at(r.value),n instanceof X&&(i=new X(n.value.at(r.value)));else if(r instanceof X)i=n.builtins.get(r.value);else throw Error(`Cannot access property with non-string/non-number: got ${r.type}`);else{if(!(r instanceof X))throw Error(`Cannot access property with non-string: got ${r.type}`);i=n.builtins.get(r.value)}return i instanceof Vk?i:new eA}evaluateSet(e,t){let n=e.value?this.evaluate(e.value,t):this.evaluateBlock(e.body,t);if(e.assignee.type===`Identifier`){let r=e.assignee.value;t.setVariable(r,n)}else if(e.assignee.type===`TupleLiteral`){let r=e.assignee;if(!(n instanceof Xk))throw Error(`Cannot unpack non-iterable type in set: ${n.type}`);let i=n.value;if(i.length!==r.value.length)throw Error(`Too ${r.value.length>i.length?`few`:`many`} items to unpack in set`);for(let e=0;et.setVariable(e.loopvar.value,c);else if(e.loopvar.type===`TupleLiteral`){let t=e.loopvar;if(c.type!==`ArrayValue`)throw Error(`Cannot unpack non-iterable type: ${c.type}`);let n=c;if(t.value.length!==n.value.length)throw Error(`Too ${t.value.length>n.value.length?`few`:`many`} items to unpack`);l=e=>{for(let r=0;r0?a[t-1]:new eA],[`nextitem`,t{let r=new tA(n);t=t.slice();let i;t.at(-1)?.type===`KeywordArgumentsValue`&&(i=t.pop());for(let n=0;n{let r=new tA(n);if(e.callerArgs)for(let n=0;nthis.evaluate(e,t)));case`TupleLiteral`:return new Zk(e.value.map(e=>this.evaluate(e,t)));case`ObjectLiteral`:{let n=new Map;for(let[r,i]of e.value){let e=this.evaluate(r,t);if(!(e instanceof X))throw Error(`Object keys must be strings: got ${e.type}`);n.set(e.value,this.evaluate(i,t))}return new Jk(n)}case`Identifier`:return this.evaluateIdentifier(e,t);case`CallExpression`:return this.evaluateCallExpression(e,t);case`MemberExpression`:return this.evaluateMemberExpression(e,t);case`UnaryExpression`:return this.evaluateUnaryExpression(e,t);case`BinaryExpression`:return this.evaluateBinaryExpression(e,t);case`FilterExpression`:return this.evaluateFilterExpression(e,t);case`FilterStatement`:return this.evaluateFilterStatement(e,t);case`TestExpression`:return this.evaluateTestExpression(e,t);case`SelectExpression`:return this.evaluateSelectExpression(e,t);case`Ternary`:return this.evaluateTernaryExpression(e,t);case`Comment`:return new $k;default:throw SyntaxError(`Unknown node type: ${e.type}`)}}};function oA(e){switch(typeof e){case`number`:return Number.isInteger(e)?new Hk(e):new Uk(e);case`string`:return new X(e);case`boolean`:return new Wk(e);case`undefined`:return new eA;case`object`:return e===null?new $k:Array.isArray(e)?new Xk(e.map(oA)):new Jk(new Map(Object.entries(e).map(([e,t])=>[e,oA(t)])));case`function`:return new Qk((t,n)=>oA(e(...t.map(e=>e.value))??null));default:throw Error(`Cannot convert to runtime value: ${e}`)}}var sA=` +`,cA=`{%- `,lA=` -%}`;function uA(e){switch(e.operator.type){case`MultiplicativeBinaryOperator`:return 4;case`AdditiveBinaryOperator`:return 3;case`ComparisonBinaryOperator`:return 2;case`Identifier`:return e.operator.value===`and`?1:e.operator.value===`in`||e.operator.value===`not in`?2:0}return 0}function dA(e,t=` `){let n=typeof t==`number`?` `.repeat(t):t;return pA(e.body,0,n).replace(/\n$/,``)}function fA(...e){return cA+e.join(` `)+lA}function pA(e,t,n){return e.map(e=>mA(e,t,n)).join(sA)}function mA(e,t,n){let r=n.repeat(t);switch(e.type){case`Program`:return pA(e.body,t,n);case`If`:return hA(e,t,n);case`For`:return gA(e,t,n);case`Set`:return _A(e,t,n);case`Macro`:return vA(e,t,n);case`Break`:return r+fA(`break`);case`Continue`:return r+fA(`continue`);case`CallStatement`:return yA(e,t,n);case`FilterStatement`:return bA(e,t,n);case`Comment`:return r+`{# `+e.value+` #}`;default:return r+`{{- `+xA(e)+` -}}`}}function hA(e,t,n){let r=n.repeat(t),i=[],a=e;for(;a&&(i.push({test:a.test,body:a.body}),a.alternate.length===1&&a.alternate[0].type===`If`);)a=a.alternate[0];let o=r+fA(`if`,xA(i[0].test))+sA+pA(i[0].body,t+1,n);for(let e=1;e0&&(o+=sA+r+fA(`else`)+sA+pA(a.alternate,t+1,n)),o+=sA+r+fA(`endif`),o}function gA(e,t,n){let r=n.repeat(t),i=``;if(e.iterable.type===`SelectExpression`){let t=e.iterable;i=`${xA(t.lhs)} if ${xA(t.test)}`}else i=xA(e.iterable);let a=r+fA(`for`,xA(e.loopvar),`in`,i)+sA+pA(e.body,t+1,n);return e.defaultBlock.length>0&&(a+=sA+r+fA(`else`)+sA+pA(e.defaultBlock,t+1,n)),a+=sA+r+fA(`endfor`),a}function _A(e,t,n){let r=n.repeat(t),i=xA(e.assignee),a=e.value?xA(e.value):``,o=r+fA(`set`,`${i}${e.value?` = `+a:``}`);return e.body.length===0?o:o+sA+pA(e.body,t+1,n)+sA+r+fA(`endset`)}function vA(e,t,n){let r=n.repeat(t),i=e.args.map(xA).join(`, `);return r+fA(`macro`,`${e.name.value}(${i})`)+sA+pA(e.body,t+1,n)+sA+r+fA(`endmacro`)}function yA(e,t,n){let r=n.repeat(t),i=e.callerArgs&&e.callerArgs.length>0?`(${e.callerArgs.map(xA).join(`, `)})`:``,a=xA(e.call),o=r+fA(`call${i}`,a)+sA;return o+=pA(e.body,t+1,n)+sA,o+=r+fA(`endcall`),o}function bA(e,t,n){let r=n.repeat(t),i=r+fA(`filter`,e.filter.type===`Identifier`?e.filter.value:xA(e.filter))+sA;return i+=pA(e.body,t+1,n)+sA,i+=r+fA(`endfilter`),i}function xA(e,t=-1){switch(e.type){case`SpreadExpression`:return`*${xA(e.argument)}`;case`Identifier`:return e.value;case`IntegerLiteral`:return`${e.value}`;case`FloatLiteral`:return`${e.value}`;case`StringLiteral`:return JSON.stringify(e.value);case`BinaryExpression`:{let n=e,r=uA(n),i=xA(n.left,r),a=xA(n.right,r+1),o=`${i} ${n.operator.value} ${a}`;return r`${xA(e)}: ${xA(t)}`).join(`, `)}}`;case`SliceExpression`:{let t=e;return`${t.start?xA(t.start):``}:${t.stop?xA(t.stop):``}${t.step?`:${xA(t.step)}`:``}`}case`KeywordArgumentExpression`:{let t=e;return`${t.key.value}=${xA(t.value)}`}case`Ternary`:{let n=e,r=`${xA(n.trueExpr)} if ${xA(n.condition,0)} else ${xA(n.falseExpr)}`;return t>-1?`(${r})`:r}default:throw Error(`Unknown expression type: ${e.type}`)}}var SA=class{parsed;constructor(e){this.parsed=jk($O(e,{lstrip_blocks:!0,trim_blocks:!0}))}render(e){let t=new tA;if(nA(t),e)for(let[n,r]of Object.entries(e))t.set(n,r);return new aA(t).run(this.parsed).value}format(e){return dA(this.parsed,e?.indent||` `)}},CA=class{constructor(){let e=function(...t){return e._call(...t)};return Object.setPrototypeOf(e,new.target.prototype)}_call(...e){throw Error(`Must implement _call method in subclass`)}},wA={txt:`text/plain`,html:`text/html`,css:`text/css`,js:`text/javascript`,json:`application/json`,png:`image/png`,jpg:`image/jpeg`,jpeg:`image/jpeg`,gif:`image/gif`},TA=class e{constructor(e){if(this.filePath=e,this.headers=new Headers,this.exists=wE.existsSync(e),this.exists){this.status=200,this.statusText=`OK`;let t=wE.statSync(e);this.headers.set(`content-length`,t.size.toString()),this.updateContentType();let n=wE.createReadStream(e);this.body=new ReadableStream({start(e){n.on(`data`,t=>e.enqueue(t)),n.on(`end`,()=>e.close()),n.on(`error`,t=>e.error(t))},cancel(){n.destroy()}})}else this.status=404,this.statusText=`Not Found`,this.body=null}updateContentType(){let e=this.filePath.toString().split(`.`).pop().toLowerCase();this.headers.set(`content-type`,wA[e]??`application/octet-stream`)}clone(){let t=new e(this.filePath);return t.exists=this.exists,t.status=this.status,t.statusText=this.statusText,t.headers=new Headers(this.headers),t}async arrayBuffer(){return(await wE.promises.readFile(this.filePath)).buffer}async blob(){let e=await wE.promises.readFile(this.filePath);return new Blob([e],{type:this.headers.get(`content-type`)})}async text(){return await wE.promises.readFile(this.filePath,`utf8`)}async json(){return JSON.parse(await this.text())}},EA=class{constructor(e){this._mt=new Uint32Array(624),this._idx=625,this._gauss_next=null,this._random_fn=this.random.bind(this),this.seed(e)}seed(e){if(e==null)if(GE.IS_CRYPTO_AVAILABLE){let t=new Uint32Array(1);crypto.getRandomValues(t),e=t[0]}else e=Date.now()>>>0;let t=this._mt,n=(e,t)=>Math.imul(e,t)>>>0,r=[];for(let t=e||0;t>0;t=Math.floor(t/4294967296))r.push(t&4294967295);r.length||r.push(0),t[0]=19650218;for(let e=1;e<624;++e)t[e]=n(1812433253,t[e-1]^t[e-1]>>>30)+e>>>0;let i=1,a=0;for(let e=Math.max(624,r.length);e>0;--e,++i,++a)i>=624&&(t[0]=t[623],i=1),a>=r.length&&(a=0),t[i]=(t[i]^n(t[i-1]^t[i-1]>>>30,1664525))+r[a]+a>>>0;for(let e=623;e>0;--e,++i)i>=624&&(t[0]=t[623],i=1),t[i]=(t[i]^n(t[i-1]^t[i-1]>>>30,1566083941))-i>>>0;t[0]=2147483648,this._idx=624,this._gauss_next=null}_int32(){let e=this._mt;if(this._idx>=624){for(let t=0;t<624;++t){let n=e[t]&2147483648|e[(t+1)%624]&2147483647;e[t]=(e[(t+397)%624]^n>>>1^(n&1?2567483615:0))>>>0}this._idx=0}let t=e[this._idx++];return t^=t>>>11,t^=t<<7&2636928640,t^=t<<15&4022730752,t^=t>>>18,t>>>0}random(){return((this._int32()>>>5)*67108864+(this._int32()>>>6))/9007199254740992}gauss(e=0,t=1){let n=this._gauss_next;if(this._gauss_next=null,n===null){let e=this.random()*2*Math.PI,t=Math.sqrt(-2*Math.log(1-this.random()));n=Math.cos(e)*t,this._gauss_next=Math.sin(e)*t}return e+n*t}shuffle(e){for(let t=e.length-1;t>0;--t){let n=32-Math.clz32(t+1),r=this._int32()>>>32-n;for(;r>t;)r=this._int32()>>>32-n;let i=e[t];e[t]=e[r],e[r]=i}}choices(e,t){return e[DA(this._random_fn,t)]}};function DA(e,t){let n=0;for(let e=0;eDA(kA.random,e),jA=new EA,MA=class{constructor(e){this.path=e}async match(e){let t=new TA(TE.join(this.path,e));if(t.exists)return t}async put(e,t,n=void 0){let r=TE.join(this.path,e),i=r+`.tmp.${GE.IS_PROCESS_AVAILABLE?process.pid:Date.now()}.${jA._int32().toString(36)}`;try{let e=t.headers.get(`Content-Length`),a=parseInt(e??`0`),o=0;await wE.promises.mkdir(TE.dirname(r),{recursive:!0});let s=wE.createWriteStream(i),c=t.body.getReader();for(;;){let{done:e,value:t}=await c.read();if(e)break;await new Promise((e,n)=>{s.write(t,t=>{if(t){n(t);return}e()})}),o+=t.length;let r=a?o/a*100:0;n?.({progress:r,loaded:o,total:a})}await new Promise((e,t)=>{s.close(n=>n?t(n):e())}),await wE.promises.rename(i,r)}catch(e){try{await wE.promises.unlink(i)}catch{}throw e}}async delete(e){let t=TE.join(this.path,e);try{return await wE.promises.unlink(t),!0}catch{return!1}}},NA={400:`Bad request error occurred while trying to load file`,401:`Unauthorized access to file`,403:`Forbidden access to file`,404:`Could not locate file`,408:`Request timeout error occurred while trying to load file`,500:`Internal server error error occurred while trying to load file`,502:`Bad gateway error occurred while trying to load file`,503:`Service unavailable error occurred while trying to load file`,504:`Gateway timeout error occurred while trying to load file`},PA=100,FA=/^(\b[\w\-.]+\b\/)?\b[\w\-.]{1,96}\b$/;function IA(...e){return e=e.map((t,n)=>(n&&(t=t.replace(RegExp(`^/`),``)),n!==e.length-1&&(t=t.replace(RegExp(`/$`),``)),t)),e.join(`/`)}function LA(e,t=null,n=null){let r;try{r=new URL(e)}catch{return!1}return!(t&&!t.includes(r.protocol)||n&&!n.includes(r.hostname))}function RA(e){return!(!FA.test(e)||e.includes(`..`)||e.includes(`--`)||e.endsWith(`.git`)||e.endsWith(`.ipynb`))}function zA(e,t,n){if(!n)return null;let r=NA[e]??`Error (${e}) occurred while trying to load file`;throw Error(`${r}: "${t}".`)}async function BA(e,t,n){let r=e.headers.get(`Content-Length`),i=r?parseInt(r,10):n??0;r===null&&!n&&dD.warn(`Unable to determine content-length from response headers. Will expand buffer when needed.`);let a=new Uint8Array(i),o=0,s=e.body.getReader();async function c(){let{done:e,value:n}=await s.read();if(e)return;let r=o+n.length;if(r>i){i=r;let e=new Uint8Array(i);e.set(a),a=e}return a.set(n,o),o=r,t({progress:o/i*100,loaded:o,total:i}),c()}return await c(),a}function VA(e){return LA(e,[`blob:`])}function HA(e){let t;if(typeof location<`u`&&location.href)t=location.href;else if(import.meta.url)t=import.meta.url;else return e;return new URL(e,t).href}var UA=`SHA-256`,WA=`experimental_transformers-hash-cache`,GA=e=>({algorithm:UA,value:e}),KA=class{#e=null;_getHashCache=()=>(this.#e??=caches.open(WA),this.#e);static isAvailable=()=>typeof navigator<`u`&&`crossOriginStorage`in navigator;match=async e=>{let t=await this._getFileHash(e);if(t)try{let[e]=await navigator.crossOriginStorage.requestFileHandles([GA(t)]),n=await e.getFile();return new Response(n,{headers:{"Content-Length":String(n.size)}})}catch{return}};put=async(e,t)=>{let n=await this._getFileHash(e);if(n){let e=await t.blob();await this._storeBlobInCOS(e,n)}else this._processAndStore(e,t.body)};_storeBlobInCOS=async(e,t)=>{let[n]=await navigator.crossOriginStorage.requestFileHandles([GA(t)],{create:!0}),r=await n.createWritable();await r.write(e),await r.close()};_processAndStore=async(e,t)=>{try{let n=[];for await(let e of t)n.push(e);let r=new Blob(n),i=await this._getBlobHash(r);await this._storeBlobInCOS(r,i);try{await(await this._getHashCache()).put(e,new Response(i))}catch{}}catch{}};delete=async e=>{try{return await(await this._getHashCache()).delete(e)}catch{return!1}};_getFileHash=async e=>{try{let t=await this._getHashCache(),n=await t.match(e);if(n)return n.text();let r=await this._getLfsFileHash(e);return r?(await t.put(e,new Response(r)),r):null}catch{return null}};_getLfsFileHash=async e=>{if(!e.includes(`/resolve/`))return null;let t=e.replace(`/resolve/`,`/raw/`);try{let e=(await fetch(t).then(e=>e.text())).match(/^oid sha256:([0-9a-f]+)$/m);return e?e[1]:null}catch{return null}};_getBlobHash=async e=>{let t=await e.arrayBuffer(),n=await crypto.subtle.digest(UA,t);return Array.from(new Uint8Array(n)).map(e=>e.toString(16).padStart(2,`0`)).join(``)}};async function qA(e=null){let t=null;if(eD.useCustomCache){if(!eD.customCache)throw Error("`env.useCustomCache=true`, but `env.customCache` is not defined.");if(!eD.customCache.match||!eD.customCache.put)throw Error("`env.customCache` must be an object which implements the `match` and `put` functions of the Web Cache API. For more information, see https://developer.mozilla.org/en-US/docs/Web/API/Cache");t=eD.customCache}if(!t&&eD.experimental_useCrossOriginStorage&&KA.isAvailable()&&(t=new KA),!t&&eD.useBrowserCache){if(typeof caches>`u`)throw Error(`Browser cache is not available in this environment.`);try{t=await caches.open(eD.cacheKey)}catch(e){dD.warn(`An error occurred while opening the browser cache:`,e)}}if(!t&&eD.useFSCache){if(!GE.IS_FS_AVAILABLE)throw Error(`File System Cache is not available in this environment.`);t=new MA(e??eD.cacheDir)}return t}async function JA(e,...t){for(let n of t)try{let t=await e.match(n);if(t)return t}catch{continue}}var YA=new class{#e;#t;constructor(e){this.#e=e,this.#t=new Map}get(e){if(!this.#t.has(e))return;let t=this.#t.get(e);return this.#t.delete(e),this.#t.set(e,t),t}put(e,t){this.#t.has(e)&&this.#t.delete(e),this.#t.set(e,t),this.#t.size>this.#e&&this.#t.delete(this.#t.keys().next().value)}delete(e){return this.#t.delete(e)}clear(){this.#t.clear()}}(100);function XA(e,t){let n=YA.get(e);if(n!==void 0)return n;let r=t().then(e=>e,t=>(YA.delete(e),Promise.reject(t)));return YA.put(e,r),r}async function ZA(e){if(!LA(e,[`http:`,`https:`]))return null;let t=tj(e);return t.set(`Range`,`bytes=0-0`),eD.fetch(e,{method:`GET`,headers:t,cache:`no-store`})}function QA(e,t,n={}){return XA(JSON.stringify([e,t,n?.revision,n?.cache_dir,n?.local_files_only]),()=>$A(e,t,n))}async function $A(e,t,n){let r=await qA(n?.cache_dir),{localPath:i,remoteURL:a,proposedCacheKey:o,validModelId:s}=nj(e,t,n,r),c=await rj(r,i,o);if(c!==void 0&&typeof c!=`string`){let e=c.headers.get(`content-length`),t=c.headers.get(`content-type`);return{exists:!0,size:e?parseInt(e,10):void 0,contentType:t||void 0,fromCache:!0}}if(eD.allowLocalModels&&!LA(i,[`http:`,`https:`]))try{let e=await ej(i);if(typeof e!=`string`&&e.status!==404){let t=e.headers.get(`content-length`),n=e.headers.get(`content-type`);return{exists:!0,size:t?parseInt(t,10):void 0,contentType:n||void 0,fromCache:!1}}}catch{}if(eD.allowRemoteModels&&!n.local_files_only&&s)try{let e=await ZA(a);if(e&&e.status>=200&&e.status<300){let t,n=e.headers.get(`content-type`);if(e.status===206){let n=e.headers.get(`content-range`);if(n){let e=n.match(/bytes \d+-\d+\/(\d+)/);e&&(t=parseInt(e[1],10))}}else if(e.status===200)try{await e.body?.cancel()}catch{}if(t===void 0){let n=e.headers.get(`content-length`);t=n?parseInt(n,10):void 0}return{exists:!0,size:t,contentType:n||void 0,fromCache:!1}}}catch(e){dD.warn(`Unable to fetch file metadata for "${a}": ${e}`)}return{exists:!1,fromCache:!1}}async function ej(e){return eD.useFS&&!LA(e,[`http:`,`https:`,`blob:`])?new TA(e instanceof URL?e.protocol===`file:`?e.pathname:e.toString():e):eD.fetch(e,{headers:tj(e)})}function tj(e){let t=typeof process<`u`&&process?.release?.name===`node`,n=new Headers;if(t){let t=!!{}?.TESTING_REMOTELY,r=eD.version;if(n.set(`User-Agent`,`transformers.js/${r}; is_ci/${t};`),LA(e,[`http:`,`https:`],[`huggingface.co`,`hf.co`])){let e={}?.HF_TOKEN??{}?.HF_ACCESS_TOKEN;e&&n.set(`Authorization`,`Bearer ${e}`)}}return n}function nj(e,t,n={},r=null){let i=n.revision??`main`,a=IA(e,t),o=RA(e),s=o?IA(eD.localModelPath,a):a,c=IA(eD.remoteHost,eD.remotePathTemplate.replaceAll(`{model}`,e).replaceAll(`{revision}`,encodeURIComponent(i)),t);return{requestURL:a,localPath:s,remoteURL:c,proposedCacheKey:r instanceof MA?i===`main`?a:IA(e,i,t):c,validModelId:o}}async function rj(e,t,n){if(e)return await JA(e,t,n)}async function ij(e,t,n,r,i,a,o={}){if(await n.match(r)===void 0)if(a)typeof i!=`string`&&await n.put(r,new Response(a,{headers:i.headers})).catch(e=>{dD.warn(`Unable to add response to browser cache: ${e}.`)});else{let a=o.progress_callback?n=>nD(o.progress_callback,{status:`progress`,name:e,file:t,...n}):void 0;await n.put(r,i,a)}}async function aj(e,t,n=!0,r={},i=!1,a=null){let{requestURL:o,localPath:s,remoteURL:c,proposedCacheKey:l,validModelId:u}=nj(e,t,r,a),d,f=!1,p;p=await rj(a,s,l);let m=p!==void 0;if(!m){if(eD.allowLocalModels){if(!LA(o,[`http:`,`https:`]))try{p=await ej(s),d=s}catch(e){dD.warn(`Unable to load from local path "${s}": "${e}"`)}else if(r.local_files_only)throw Error(`\`local_files_only=true\`, but attempted to load a remote file from: ${o}.`);else if(!eD.allowRemoteModels)throw Error(`\`env.allowRemoteModels=false\`, but attempted to load a remote file from: ${o}.`)}if(p===void 0||typeof p!=`string`&&p.status===404){if(r.local_files_only||!eD.allowRemoteModels){if(n)throw Error(`\`local_files_only=true\` or \`env.allowRemoteModels=false\` and file was not found locally at "${s}".`);return null}if(!u)throw Error(`Local file missing at "${s}" and download aborted due to invalid model ID "${e}".`);if(p=await ej(c),p.status!==200)return zA(p.status,c,n);d=l}f=a&&typeof Response<`u`&&p instanceof Response&&p.status===200}nD(r.progress_callback,{status:`download`,name:e,file:t});let h;if(!(GE.IS_NODE_ENV&&i)){let n;if(typeof p!=`string`)if(!r.progress_callback)n=new Uint8Array(await p.arrayBuffer());else if(m&&typeof navigator<`u`&&/firefox/i.test(navigator.userAgent))n=new Uint8Array(await p.arrayBuffer()),nD(r.progress_callback,{status:`progress`,name:e,file:t,progress:100,loaded:n.length,total:n.length});else{let i,a=p.headers.get(`content-length`);if(a)i=parseInt(a,10);else try{let n=await QA(e,t,r);n.size&&(i=n.size)}catch{}n=await BA(p,n=>{nD(r.progress_callback,{status:`progress`,name:e,file:t,...n})},i)}h=n}if(f&&d&&typeof p!=`string`&&await ij(e,t,a,d,p,h,r),nD(r.progress_callback,{status:`done`,name:e,file:t}),h){if(!GE.IS_NODE_ENV&&i)throw Error(`Cannot return path in a browser environment.`);return h}if(p instanceof TA)return p.filePath;let g=await a?.match(d);if(g instanceof TA)return g.filePath;if(g instanceof Response)return new Uint8Array(await g.arrayBuffer());if(typeof g==`string`)return g;throw Error(`Unable to get model file path or buffer.`)}async function oj(e,t,n=!0,r={},i=!1){if(!eD.allowLocalModels){if(r.local_files_only)throw Error("Invalid configuration detected: local models are disabled (`env.allowLocalModels=false`) but you have requested to only use local models (`local_files_only=true`).");if(!eD.allowRemoteModels)throw Error("Invalid configuration detected: both local and remote models are disabled. Fix by setting `env.allowLocalModels` or `env.allowRemoteModels` to `true`.")}return nD(r.progress_callback,{status:`initiate`,name:e,file:t}),await aj(e,t,n,r,i,await qA(r?.cache_dir))}async function sj(e,t,n=!0,r={}){let i=await oj(e,t,n,r,!1);return i===null?null:new TextDecoder(`utf-8`).decode(i)}async function cj(e,t,n=!0,r={}){let i=await sj(e,t,n,r);return i===null?{}:JSON.parse(i)}function lj(e,[t,n,r],[i,a],o=`bilinear`,s=!1){let c=a/r,l=i/n,u=new e.constructor(i*a*t),d=n*r,f=i*a;for(let o=0;o=0;--e)i[e]=a,r[e]=t[n[e]],a*=r[e];let a=n.map((e,t)=>i[n.indexOf(t)]),o=new e.constructor(e.length);for(let n=0;n=0;--e)r+=i%t[e]*a[e],i=Math.floor(i/t[e]);o[r]=e[n]}return[o,r]}function dj(e){let t=mj(e)[0],n=e.map(e=>Math.exp(e-t)),r=n.reduce((e,t)=>e+t,0);return n.map(e=>e/r)}function fj(e){let t=mj(e)[0],n=0;for(let r=0;re-t-r)}function pj(e){if(e.length===0)throw Error(`Array must not be empty`);let t=e[0],n=0;for(let r=1;rt&&(t=e[r],n=r);return[t,n]}function hj(e){return e>0&&(e&e-1)==0}var gj=class{constructor(e){if(this.size=e|0,this.size<=1||!hj(this.size))throw Error(`FFT size must be a power of two larger than 1`);this._csize=e<<1,this.table=new Float64Array(this.size*2);for(let e=0;ee;e<<=1)++t;this._width=t%2==0?t-1:t,this._bitrev=new Int32Array(1<>>t&3)<>>1);for(let t=0;t>>1]=e[t];return n}toComplexArray(e,t){let n=t||this.createComplexArray();for(let t=0;t>>1],n[t+1]=0;return n}transform(e,t){if(e===t)throw Error(`Input and output buffers must be different`);this._transform4(e,t,1)}realTransform(e,t){if(e===t)throw Error(`Input and output buffers must be different`);this._realTransform4(e,t,1)}inverseTransform(e,t){if(e===t)throw Error(`Input and output buffers must be different`);this._transform4(e,t,-1);for(let t=0;t>=2;i>=2;i>>=2){a=r/i<<1;let t=a>>>2;for(o=0;o>>1,i>>>1)}else for(o=0,s=0;o>>1,i>>>1,n)}let l=this.table;for(i>>=2;i>=2;i>>=2){a=r/i<<1;let t=a>>>1,s=t>>>1,c=s>>>1;for(o=0;o>>1;for(let t=2;t>1;++t){let n=(t+1-e)**2/2,r=Math.sqrt(s**2+c**2)**n,o=n*Math.atan2(c,s),l=2*t;i[l]=r*Math.cos(o),i[l+1]=r*Math.sin(o),a[l]=i[l],a[l+1]=-i[l+1]}this._slicedChirpBuffer=i.subarray(t,n),this._f=new gj(r>>1),this._f.transform(this._chirpBuffer,a)}_transform(e,t,n){let r=this._buffer1,i=this._buffer2,a=this._outBuffer1,o=this._outBuffer2,s=this._chirpBuffer,c=this._slicedChirpBuffer,l=this._a;if(n)for(let e=0;e>1];r[e]=i*c[e],r[n]=i*c[n]}else for(let e=0;e=e.length&&(i=2*(e.length-1)-i),r[a++]=e[i]}r.sort(),n[t]=r[i]}return n}function bj(e,t){let n=10**t;return Math.round(e*n)/n}function xj(e){let t=Math.round(e);return Math.abs(e)%1==.5?t%2==0?t:t-1:t}function Sj(e){let t=e.length,n=e[0].length,r=[t+1,n+1],i=Array.from({length:r[0]},()=>Array(r[1]).fill(1/0));i[0][0]=0;let a=Array.from({length:r[0]},()=>Array(r[1]).fill(-1));for(let t=1;t0||s>0;)switch(c.push(o-1),l.push(s-1),a[o][s]){case 0:--o,--s;break;case 1:--o;break;case 2:--s;break;default:throw Error(`Internal error in dynamic time warping. Unexpected trace[${o}, ${s}]. Please file a bug report.`)}return c.reverse(),l.reverse(),[c,l]}var Cj=(function(){let e=null;return function(t){if(!e){e=new Float32Array(65536);let t=new ArrayBuffer(4),n=new Uint32Array(t),r=new Float32Array(t);for(let t=0;t>10,s=t&1023;if(o===31)i=a|2139095040|s<<13;else if(o===0)if(s===0)i=a;else{let e=113;for(;!(s&1024);)s<<=1,--e;s&=-1025,i=a|e<<23|s<<13}else i=a|o+112<<23|s<<13;n[0]=i,e[t]=r[0]}}let n=t.length,r=e,i=new Float32Array(n);for(let e=0;eTj});var Tj={};async function Ej(e){let t=e.split(`/`).pop(),n;try{if(n=await qA(),n){let t=await n.match(e);if(t)return t}}catch(e){dD.warn(`Failed to load ${t} from cache:`,e)}let r=await eD.fetch(e);if(!r.ok)throw Error(`Failed to fetch ${t}: ${r.status} ${r.statusText}`);if(n)try{await n.put(e,r.clone())}catch(e){dD.warn(`Failed to cache ${t}:`,e)}return r}async function Dj(e){let t=await Ej(e);if(!t||typeof t==`string`)return null;try{return await t.arrayBuffer()}catch(e){return dD.warn(`Failed to read WASM binary:`,e),null}}async function Oj(e){if(GE.IS_SERVICE_WORKER_ENV||GE.IS_CHROME_AVAILABLE)return e;let t=await Ej(e);if(!t||typeof t==`string`)return null;try{let e=await t.text();e=e.replaceAll(`globalThis.process?.versions?.node`,`false`);let n=new Blob([e],{type:`text/javascript`});return URL.createObjectURL(n)}catch(e){return dD.warn(`Failed to read WASM factory:`,e),null}}var kj=Object.freeze({auto:null,gpu:null,cpu:`cpu`,wasm:`wasm`,webgpu:`webgpu`,cuda:`cuda`,dml:`dml`,coreml:`coreml`,webnn:{name:`webnn`,deviceType:`cpu`},"webnn-npu":{name:`webnn`,deviceType:`npu`},"webnn-gpu":{name:`webnn`,deviceType:`gpu`},"webnn-cpu":{name:`webnn`,deviceType:`cpu`}});function Aj(e){return e<=QE.DEBUG?0:e<=QE.INFO?2:e<=QE.WARNING||e<=QE.ERROR?3:4}var jj={0:`verbose`,1:`info`,2:`warning`,3:`error`,4:`fatal`},Mj=[],Nj,Pj,Fj=Symbol.for(`onnxruntime`);if(Fj in globalThis)Pj=globalThis[Fj];else if(GE.IS_NODE_ENV){switch(Pj=wj,process.platform){case`win32`:Mj.push(`dml`);break;case`linux`:process.arch===`x64`&&Mj.push(`cuda`);break;case`darwin`:Mj.push(`coreml`);break}Mj.push(`webgpu`),Mj.push(`cpu`),Nj=[`cpu`]}else Pj=wS,GE.IS_WEBNN_AVAILABLE&&Mj.push(`webnn-npu`,`webnn-gpu`,`webnn-cpu`,`webnn`),GE.IS_WEBGPU_AVAILABLE&&Mj.push(`webgpu`),Mj.push(`wasm`),Nj=[`wasm`];var Ij=Pj.InferenceSession;function Lj(e=null){if(!e)return Nj;switch(e){case`auto`:return Mj;case`gpu`:return Mj.filter(e=>[`webgpu`,`cuda`,`dml`,`webnn-gpu`].includes(e))}if(Mj.includes(e))return[kj[e]??e];throw Error(`Unsupported device: "${e}". Should be one of: ${Mj.join(`, `)}.`)}var Rj=Promise.resolve(),zj=null;async function Bj(){if(zj)return zj;if(!(eD.useWasmCache&&typeof Gj?.wasm?.wasmPaths==`object`&&Gj?.wasm?.wasmPaths?.wasm&&Gj?.wasm?.wasmPaths?.mjs)){if(GE.IS_DENO_WEB_RUNTIME)throw Error(`env.useWasmCache=false is not supported in Deno's web runtime. Remove the useWasmCache override.`);return zj=Promise.resolve(),zj}return zj=(async()=>{let e=Gj.wasm.wasmPaths,t=!1;await Promise.all([e.wasm&&!VA(e.wasm)?(async()=>{try{let n=await Dj(HA(e.wasm));n&&(Gj.wasm.wasmBinary=n,t=!0)}catch(e){dD.warn(`Failed to pre-load WASM binary:`,e)}})():Promise.resolve(),e.mjs&&!VA(e.mjs)?(async()=>{try{let t=await Oj(HA(e.mjs));t&&(Gj.wasm.wasmPaths.mjs=t)}catch(e){dD.warn(`Failed to pre-load WASM factory:`,e)}})():Promise.resolve()]),t||(Gj.wasm.wasmPaths.mjs=e.mjs)})(),zj}async function Vj(e,t,n){await Bj();let r=Aj(eD.logLevel??QE.WARNING),i=()=>Ij.create(e,{logSeverityLevel:r,...t}),a=await(GE.IS_WEB_ENV?Rj=Rj.then(i):i());return a.config=n,a}var Hj=Promise.resolve();async function Uj(e,t){let n=()=>e.run(t);return GE.IS_WEB_ENV?Hj=Hj.then(n):n()}function Wj(e){return e instanceof Pj.Tensor}var Gj=Pj?.env;function Kj(){return Gj?.wasm?.proxy}if(Gj){let e=function(e){Gj.logLevel=jj[Aj(e)]};if(Gj.wasm){if(!(typeof ServiceWorkerGlobalScope<`u`&&self instanceof ServiceWorkerGlobalScope)&&Gj.versions?.web&&!Gj.wasm.wasmPaths){let e=`https://cdn.jsdelivr.net/npm/onnxruntime-web@${Gj.versions.web}/dist/`;Gj.wasm.wasmPaths=GE.IS_SAFARI?{mjs:`${e}ort-wasm-simd-threaded.mjs`,wasm:`${e}ort-wasm-simd-threaded.wasm`}:{mjs:`${e}ort-wasm-simd-threaded.asyncify.mjs`,wasm:`${e}ort-wasm-simd-threaded.asyncify.wasm`}}Gj.wasm.proxy=!1}Gj.webgpu&&(Gj.webgpu.powerPreference=`high-performance`),e(eD.logLevel??QE.WARNING),eD.backends.onnx={...Gj,setLogLevel:e}}var qj=async(e,t,n)=>{let r=await Vj(new Uint8Array(e),t);return(async e=>{let t=Kj(),i=await Uj(r,Object.fromEntries(Object.entries(e).map(([e,n])=>[e,(t?n.clone():n).ort_tensor])));return Array.isArray(n)?n.map(e=>new Z(i[e])):new Z(i[n])})},Jj=class{static session_options={};static get nearest_interpolate_4d(){return this._nearest_interpolate_4d||=qj([8,10,18,0,58,129,1,10,41,10,1,120,10,0,10,0,10,1,115,18,1,121,34,6,82,101,115,105,122,101,42,18,10,4,109,111,100,101,34,7,110,101,97,114,101,115,116,160,1,3,18,1,114,90,31,10,1,120,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,90,15,10,1,115,18,10,10,8,8,7,18,4,10,2,8,4,98,31,10,1,121,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,66,2,16,21],this.session_options,`y`),this._nearest_interpolate_4d}static get bilinear_interpolate_4d(){return this._bilinear_interpolate_4d||=qj([8,9,18,0,58,128,1,10,40,10,1,120,10,0,10,0,10,1,115,18,1,121,34,6,82,101,115,105,122,101,42,17,10,4,109,111,100,101,34,6,108,105,110,101,97,114,160,1,3,18,1,114,90,31,10,1,120,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,90,15,10,1,115,18,10,10,8,8,7,18,4,10,2,8,4,98,31,10,1,121,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,66,2,16,20],this.session_options,`y`),this._bilinear_interpolate_4d}static get bicubic_interpolate_4d(){return this._bicubic_interpolate_4d||=qj([8,9,18,0,58,127,10,39,10,1,120,10,0,10,0,10,1,115,18,1,121,34,6,82,101,115,105,122,101,42,16,10,4,109,111,100,101,34,5,99,117,98,105,99,160,1,3,18,1,114,90,31,10,1,120,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,90,15,10,1,115,18,10,10,8,8,7,18,4,10,2,8,4,98,31,10,1,121,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,99,10,3,18,1,104,10,3,18,1,119,66,2,16,20],this.session_options,`y`),this._bicubic_interpolate_4d}static get matmul(){return this._matmul||=qj([8,9,18,0,58,55,10,17,10,1,97,10,1,98,18,1,99,34,6,77,97,116,77,117,108,18,1,114,90,9,10,1,97,18,4,10,2,8,1,90,9,10,1,98,18,4,10,2,8,1,98,9,10,1,99,18,4,10,2,8,1,66,2,16,20],this.session_options,`c`),this._matmul}static get stft(){return this._stft||=qj([8,7,18,0,58,148,1,10,38,10,1,115,10,1,106,10,1,119,10,1,108,18,1,111,34,4,83,84,70,84,42,15,10,8,111,110,101,115,105,100,101,100,24,1,160,1,2,18,1,115,90,26,10,1,115,18,21,10,19,8,1,18,15,10,3,18,1,98,10,3,18,1,115,10,3,18,1,99,90,11,10,1,106,18,6,10,4,8,7,18,0,90,16,10,1,119,18,11,10,9,8,1,18,5,10,3,18,1,119,90,11,10,1,108,18,6,10,4,8,7,18,0,98,31,10,1,111,18,26,10,24,8,1,18,20,10,3,18,1,98,10,3,18,1,102,10,3,18,1,100,10,3,18,1,99,66,2,16,17],this.session_options,`o`),this._stft}static get rfft(){return this._rfft||=qj([8,9,18,0,58,97,10,33,10,1,120,10,0,10,1,97,18,1,121,34,3,68,70,84,42,15,10,8,111,110,101,115,105,100,101,100,24,1,160,1,2,18,1,100,90,21,10,1,120,18,16,10,14,8,1,18,10,10,3,18,1,115,10,3,18,1,99,90,11,10,1,97,18,6,10,4,8,7,18,0,98,21,10,1,121,18,16,10,14,8,1,18,10,10,3,18,1,115,10,3,18,1,99,66,2,16,20],this.session_options,`y`),this._rfft}static get top_k(){return this._top_k||=qj([8,10,18,0,58,73,10,18,10,1,120,10,1,107,18,1,118,18,1,105,34,4,84,111,112,75,18,1,116,90,9,10,1,120,18,4,10,2,8,1,90,15,10,1,107,18,10,10,8,8,7,18,4,10,2,8,1,98,9,10,1,118,18,4,10,2,8,1,98,9,10,1,105,18,4,10,2,8,7,66,2,16,21],this.session_options,[`v`,`i`]),this._top_k}static get slice(){return this._slice||=qj([8,7,18,0,58,96,10,25,10,1,120,10,1,115,10,1,101,10,1,97,10,1,116,18,1,121,34,5,83,108,105,99,101,18,1,114,90,9,10,1,120,18,4,10,2,8,1,90,9,10,1,115,18,4,10,2,8,7,90,9,10,1,101,18,4,10,2,8,7,90,9,10,1,97,18,4,10,2,8,7,90,9,10,1,116,18,4,10,2,8,7,98,9,10,1,121,18,4,10,2,8,1,66,2,16,13],this.session_options,`y`),this._slice}},Yj=Object.freeze({auto:`auto`,gpu:`gpu`,cpu:`cpu`,wasm:`wasm`,webgpu:`webgpu`,cuda:`cuda`,dml:`dml`,coreml:`coreml`,webnn:`webnn`,"webnn-npu":`webnn-npu`,"webnn-gpu":`webnn-gpu`,"webnn-cpu":`webnn-cpu`}),Xj=GE.IS_NODE_ENV?`cpu`:`wasm`;function Zj(e,t,{warn:n}={}){return e?typeof e==`string`?e:e.hasOwnProperty(t)?e[t]:(n&&n(`device not specified for "${t}". Using the default device (${Xj}).`),Xj):Xj}var Qj=(function(){let e;return async function(){if(e===void 0)if(!GE.IS_WEBGPU_AVAILABLE)e=!1;else try{e=(await navigator.gpu.requestAdapter()).features.has(`shader-f16`)}catch{e=!1}return e}})(),$j=Object.freeze({auto:`auto`,fp32:`fp32`,fp16:`fp16`,q8:`q8`,int8:`int8`,uint8:`uint8`,q4:`q4`,bnb4:`bnb4`,q4f16:`q4f16`}),eM=$j.fp32,tM=Object.freeze({[Yj.wasm]:$j.q8}),nM=Object.freeze({[$j.fp32]:``,[$j.fp16]:`_fp16`,[$j.int8]:`_int8`,[$j.uint8]:`_uint8`,[$j.q8]:`_quantized`,[$j.q4]:`_q4`,[$j.q4f16]:`_q4f16`,[$j.bnb4]:`_bnb4`});function rM(e,t,n,{configDtype:r=null,warn:i}={}){let a,o=!1;e&&typeof e!=`string`?e.hasOwnProperty(t)?a=e[t]:(a=null,o=!0):a=e;let s;if(a===$j.auto){if(r){let e=typeof r==`string`?r:r?.[t];if(e&&e!==$j.auto&&$j.hasOwnProperty(e))return e}s=tM[n]??eM}else s=a&&$j.hasOwnProperty(a)?a:tM[n]??eM;return o&&i&&i(`dtype not specified for "${t}". Using the default dtype (${s}) for this device (${n}).`),s}var iM=Object.freeze({float32:Float32Array,float16:typeof Float16Array<`u`?Float16Array:Uint16Array,float64:Float64Array,string:Array,int8:Int8Array,uint8:Uint8Array,int16:Int16Array,uint16:Uint16Array,int32:Int32Array,uint32:Uint32Array,int64:BigInt64Array,uint64:BigUint64Array,bool:Uint8Array,uint4:Uint8Array,int4:Int8Array}),Z=class e{get dims(){return this.ort_tensor.dims}set dims(e){this.ort_tensor.dims=e}get type(){return this.ort_tensor.type}get data(){return this.ort_tensor.data}get size(){return this.ort_tensor.size}get location(){return this.ort_tensor.location}ort_tensor;constructor(...e){return Wj(e[0])?this.ort_tensor=e[0]:this.ort_tensor=new xE(e[0],e[1],e[2]),new Proxy(this,{get:(e,t)=>{if(typeof t==`string`){let n=Number(t);if(Number.isInteger(n))return e._getitem(n)}return e[t]},set:(e,t,n)=>e[t]=n})}dispose(){this.ort_tensor.dispose()}*[Symbol.iterator](){let[e,...t]=this.dims;if(t.length>0){let n=t.reduce((e,t)=>e*t);for(let r=0;r0){let e=r.reduce((e,t)=>e*t);return this._subarray(t,e,r)}else return new e(this.type,[this.data[t]],r)}indexOf(e){let t=this.data;for(let n=0;na)throw Error(`Invalid slice: ${i}`);let o=[Math.max(t,0),Math.min(a,this.dims[e])];r.push(o),n.push(o[1]-o[0])}else throw Error(`Invalid slice: ${i}`)}let i=r.map(([e,t])=>t-e),a=i.reduce((e,t)=>e*t),o=this.data,s=new o.constructor(a),c=this.stride(),l=!0;for(let e=1;e=0;--n){let e=i[n];t+=(a%e+r[n][0])*c[n],a=Math.floor(a/e)}s[e]=o[t]}return new e(this.type,s,n)}permute(...e){return oM(this,e)}transpose(...e){return this.permute(...e)}sum(e=null,t=!1){return this.norm(1,e,t)}norm(t=`fro`,n=null,r=!1){if(t===`fro`)t=2;else if(typeof t==`string`)throw Error(`Unsupported norm: ${t}`);let i=this.data,a=i instanceof BigInt64Array||i instanceof BigUint64Array;if(a&&t!==1)throw Error(`Expected a floating point tensor as input. Got ${this.type}`);let o,s;if(a?(o=(e,t)=>e+t,s=0n):(o=(e,n)=>e+n**t,s=0),n===null){let n=i.reduce(o,s);return t!==1&&(n**=1/t),new e(this.type,[n],[])}let[c,l,u]=yM(o,this,n,r);if(t!==1)for(let e=0;e=0;--r){let e=this.dims[r];if(r!==t){let t=i%e;n+=t*a,a*=this.dims[r]}i=Math.floor(i/e)}r[e]/=i[n]}return this}normalize(e=2,t=1){return this.clone().normalize_(e,t)}stride(){return SM(this.dims)}squeeze(t=null){return new e(this.type,this.data,mM(this.dims,t))}squeeze_(e=null){return this.dims=mM(this.dims,e),this}unsqueeze(t){return new e(this.type,this.data,hM(this.dims,t))}unsqueeze_(e){return this.dims=hM(this.dims,e),this}flatten_(e=0,t=-1){t=(t+this.dims.length)%this.dims.length;let n=this.dims.slice(0,e),r=this.dims.slice(e,t+1),i=this.dims.slice(t+1);return this.dims=[...n,r.reduce((e,t)=>e*t,1),...i],this}flatten(e=0,t=-1){return this.clone().flatten_(e,t)}view(...t){let n=-1;for(let e=0;er===n?e:e*t,1);t[n]=r.length/e}return new e(this.type,r,t)}neg_(){let e=this.data;for(let t=0;tt?1:0;return new e(`bool`,n,this.dims)}lt(t){let n=new Uint8Array(this.data.length),r=this.data;for(let e=0;eMath.min(e,t),this,t,n,1/0);return new e(r,i,a)}max(t=null,n=!1){if(t===null){let t=mj(this.data)[0];return new e(this.type,[t],[])}let[r,i,a]=yM((e,t)=>Math.max(e,t),this,t,n,-1/0);return new e(r,i,a)}argmin(t=null,n=!1){if(t!==null)throw Error("`dim !== null` not yet implemented.");let r=pj(this.data)[1];return new e(`int64`,[BigInt(r)],[])}argmax(t=null,n=!1){if(t!==null)throw Error("`dim !== null` not yet implemented.");let r=mj(this.data)[1];return new e(`int64`,[BigInt(r)],[])}repeat(...t){if(t.lengthe===1)){if(t.length===this.dims.length)return this.clone();let n=t.length-this.dims.length,r=Array(n).fill(1).concat(this.dims);return new e(this.type,this.data.slice(),r)}let n=t.length-this.dims.length,r=Array(n).fill(1).concat(this.dims),i=r.map((e,n)=>e*t[n]),a=i.reduce((e,t)=>e*t,1),o=this.data,s=new o.constructor(a),c=SM(r),l=SM(i);for(let e=0;eBigInt(Math.floor(e)):BigInt;else if(this.type===`float16`&&t==`float32`&&this.data instanceof Uint16Array)return new e(t,Cj(this.data),this.dims);return new e(t,iM[t].from(this.data,n),this.dims)}};function aM(e,t){let n=e.length;if(n!==t.reduce((e,t)=>e*t))throw Error(`cannot reshape array of size ${n} into shape (${t})`);let r=e;for(let e=t.length-1;e>=0;e--)r=r.reduce((n,r)=>{let i=n[n.length-1];return i.lengthnew Z(`int64`,e,[e.length]);async function fM(e,t,n,r,i){return await(await Jj.slice)({x:e,s:dM(t),e:dM(n),a:dM(r),t:dM(i??Array(r.length).fill(1))})}function pM(e,t){let n=e.data,r=t.data,i=[e.dims[0],e.dims[2]],a=new n.constructor(i[0]*i[1]),[o,s,c]=e.dims,l=0;for(let e=0;ee!==1):typeof t==`number`?e[t]===1&&e.splice(t,1):Array.isArray(t)&&(e=e.filter((e,n)=>e!==1||!t.includes(n))),e}function hM(e,t){return t=gM(t,e.length+1),e=e.slice(),e.splice(t,0,1),e}function gM(e,t,n=null,r=!0){if(e<-t||e>=t){if(r)throw Error(`IndexError: index ${e} is out of bounds for dimension${n===null?``:` `+n} with size ${t}`);return e<-t?0:t}return e<0&&(e=(e%t+t)%t),e}function _M(e,t=0){t=gM(t,e[0].dims.length);let n=e[0].dims.slice();n[t]=e.reduce((e,n)=>e+n.dims[t],0);let r=n.reduce((e,t)=>e*t,1),i=new e[0].data.constructor(r),a=e[0].type;if(t===0){let t=0;for(let n of e){let e=n.data;i.set(e,t),t+=e.length}}else{let r=0;for(let a=0;a=0;--i){let e=s[i],l=o%e;i===t&&(l+=r),a+=l*c,c*=n[i],o=Math.floor(o/e)}i[a]=o[e]}r+=s[t]}}return new Z(a,i,n)}function vM(e,t=0){return _M(e.map(e=>e.unsqueeze(t)),t)}function yM(e,t,n,r=!1,i=null){let a=t.data,o=t.dims;n=gM(n,o.length);let s=o.slice();s[n]=1;let c=new a.constructor(a.length/o[n]);i!==null&&c.fill(i);for(let t=0;t=0;--e){let t=o[e];if(e!==n){let n=i%t;r+=n*a,a*=s[e]}i=Math.floor(i/t)}c[r]=e(c[r],a[t],t,r)}return r||s.splice(n,1),[t.type,c,s]}function bM(e,t=null,n=1,r=!1){let i=e.data,a=e.dims;if(t===null){let t=i.reduce((e,t)=>e+t,0)/i.length,r=Math.sqrt(i.reduce((e,n)=>e+(n-t)**2,0)/(i.length-n)),a=new Z(e.type,[t],[]);return[new Z(e.type,[r],[]),a]}t=gM(t,a.length);let o=xM(e,t,r),s=o.data,[c,l,u]=yM((e,t,n,r)=>e+(t-s[r])**2,e,t,r);for(let e=0;ee+t,0);return new Z(e.type,[t/i.length],[])}t=gM(t,r.length);let[a,o,s]=yM((e,t)=>e+t,e,t,n);if(r[t]!==1)for(let e=0;e=0;--n)t[n]=r,r*=e[n];return t}function CM(e,t,n,r){return new Z(n,new r(e.reduce((e,t)=>e*t,1)).fill(t),e)}function wM(e,t){let n,r;if(typeof t==`number`)n=`float32`,r=Float32Array;else if(typeof t==`bigint`)n=`int64`,r=BigInt64Array;else if(typeof t==`boolean`)n=`bool`,r=Uint8Array;else throw Error(`Unsupported data type: ${typeof t}`);return CM(e,t,n,r)}function TM(e,t){return wM(e.dims,t)}function EM(e){return CM(e,1n,`int64`,BigInt64Array)}function DM(e){return EM(e.dims)}function OM(e){return CM(e,0n,`int64`,BigInt64Array)}function kM(e){return OM(e.dims)}function AM(e){let t=e.reduce((e,t)=>e*t,1);return new Z(`float32`,Float32Array.from({length:t},()=>kA.gauss()),e)}function jM(e,t){if(e.dims.length!==2)throw Error(`The tensor must have 2 dimensions`);if(e.dims.at(-1)%8!=0)throw Error(`The last dimension of the tensor must be a multiple of 8`);if(![`binary`,`ubinary`].includes(t))throw Error(`The precision must be either 'binary' or 'ubinary'`);let n=t===`binary`,r=n?`int8`:`uint8`,i=n?Int8Array:Uint8Array,a=e.data,o=new i(a.length/8);for(let e=0;e0?1:0,r=Math.floor(e/8),i=e%8;o[r]|=t<<7-i,n&&i===0&&(o[r]-=128)}return new Z(r,o,[e.dims[0],e.dims[1]/8])}async function MM(e){if(!e)throw Error(`modelId is required for get_tokenizer_files`);return(await QA(e,`tokenizer_config.json`,{})).exists?[`tokenizer.json`,`tokenizer_config.json`]:[]}async function NM(e,t){let n=await MM(e);return await Promise.all(n.map(n=>cj(e,n,!0,t)))}function PM(e){let t=e.dims;switch(t.length){case 1:return e.tolist();case 2:if(t[0]!==1)throw Error("Unable to decode tensor with `batch size !== 1`. Use `tokenizer.batch_decode(...)` for batched inputs.");return e.tolist()[0];default:throw Error(`Expected tensor to have 1-2 dimensions, got ${t.length}.`)}}var FM=[`bos_token`,`eos_token`,`unk_token`,`sep_token`,`pad_token`,`cls_token`,`mask_token`];function IM(e,t,n,r){for(let i of Object.keys(e)){let a=t-e[i].length,o=n(i),s=Array(a).fill(o);e[i]=r===`right`?oD(e[i],s):oD(s,e[i])}}function LM(e,t){for(let n of Object.keys(e))e[n].length=t}function RM(e,...t){for(let n of t){if(!Object.hasOwn(e,n))continue;let t=e[n];if(t)if(typeof t==`object`){if(t.__type===`AddedToken`)return t.content;throw Error(`Unknown token: ${t}`)}else return t}return null}function zM(e){let t=[];for(let n of e.get_added_tokens_decoder().values())n.special&&t.push(n);return t}var BM=class extends CA{return_token_type_ids=!1;padding_side=`right`;constructor(e,t){if(super(),this._tokenizerJSON=e,this._tokenizerConfig=t,this._tokenizer=new GO(e,t),this.config=t,this.padding_side=t.padding_side??this.padding_side,this.mask_token=RM(t,`mask_token`),this.mask_token_id=this._tokenizer.token_to_id(this.mask_token),this.pad_token=RM(t,`pad_token`,`eos_token`),this.pad_token_id=this._tokenizer.token_to_id(this.pad_token),this.sep_token=RM(t,`sep_token`),this.sep_token_id=this._tokenizer.token_to_id(this.sep_token),this.unk_token=RM(t,`unk_token`),this.unk_token_id=this._tokenizer.token_to_id(this.unk_token),this.bos_token=RM(t,`bos_token`),this.bos_token_id=this._tokenizer.token_to_id(this.bos_token),this.eos_token=RM(t,`eos_token`),this.eos_token_id=this._tokenizer.token_to_id(this.eos_token),this.chat_template=t.chat_template??null,Array.isArray(this.chat_template)){let e=Object.create(null);for(let{name:t,template:n}of this.chat_template){if(typeof t!=`string`||typeof n!=`string`)throw Error(`Chat template must be a list of objects with "name" and "template" properties`);e[t]=n}this.chat_template=e}this._compiled_template_cache=new Map;let n=zM(this._tokenizer);this.all_special_ids=n.map(e=>e.id),this.all_special_tokens=n.map(e=>e.content)}static async from_pretrained(e,{progress_callback:t=null,config:n=null,cache_dir:r=null,local_files_only:i=!1,revision:a=`main`}={}){let o=await NM(e,{progress_callback:t,config:n,cache_dir:r,local_files_only:i,revision:a});return new this(...o)}get_vocab(){return this._tokenizer.get_vocab()}get model_max_length(){return this._tokenizerConfig.model_max_length??1/0}get add_eos_token(){return this._tokenizerConfig.add_eos_token}get add_bos_token(){return this._tokenizerConfig.add_bos_token}convert_tokens_to_ids(e){return typeof e==`string`?this._tokenizer.token_to_id(e):e.map(e=>this._tokenizer.token_to_id(e))}_call(e,{text_pair:t=null,add_special_tokens:n=!0,padding:r=!1,truncation:i=null,max_length:a=null,return_tensor:o=!0,return_token_type_ids:s=null}={}){let c=Array.isArray(e),l;if(c){if(e.length===0)throw Error(`text array must be non-empty`);if(t!==null){if(!Array.isArray(t))throw Error(`text_pair must also be an array`);if(e.length!==t.length)throw Error(`text and text_pair must have the same length`);l=e.map((e,r)=>this._encode_plus(e,{text_pair:t[r],add_special_tokens:n,return_token_type_ids:s}))}else l=e.map(e=>this._encode_plus(e,{add_special_tokens:n,return_token_type_ids:s}))}else{if(e==null)throw Error(`text may not be null or undefined`);if(Array.isArray(t))throw Error("When specifying `text_pair`, since `text` is a string, `text_pair` must also be a string (i.e., not an array).");l=[this._encode_plus(e,{text_pair:t,add_special_tokens:n,return_token_type_ids:s})]}if(a===null?a=this.model_max_length:i===null&&(r===!0?(dD.warn("`max_length` is ignored when `padding: true` and there is no truncation strategy. To pad to max length, use `padding: 'max_length'`."),a=this.model_max_length):r===!1&&(dD.warn("Truncation was not explicitly activated but `max_length` is provided a specific value, please use `truncation: true` to explicitly truncate examples to max length."),i=!0)),r===!0&&(a=Math.min(mj(l.map(e=>e.input_ids.length))[0],a??1/0)),a=Math.min(a,this.model_max_length??1/0),r||i)for(let e=0;ea?i&&LM(l[e],a):r&&IM(l[e],a,e=>e===`input_ids`?this.pad_token_id:0,this.padding_side);let u={};if(o){if(!(r&&i)&&l.some(e=>{for(let t of Object.keys(e))if(e[t].length!==l[0][t]?.length)return!0;return!1}))throw Error(`Unable to create tensor, you should probably activate truncation and/or padding with 'padding=true' and 'truncation=true' to have batched tensors with the same length.`);let e=[l.length,l[0].input_ids.length];for(let t of Object.keys(l[0]))u[t]=new Z(`int64`,BigInt64Array.from(l.flatMap(e=>e[t]).map(BigInt)),e)}else{for(let e of Object.keys(l[0]))u[e]=l.map(t=>t[e]);if(!c)for(let e of Object.keys(u))u[e]=u[e][0]}return u}_encode_text(e){return e===null?null:this._tokenizer.encode(e).tokens}_encode_plus(e,{text_pair:t=null,add_special_tokens:n=!0,return_token_type_ids:r=null}={}){let{ids:i,attention_mask:a,token_type_ids:o}=this._tokenizer.encode(e,{text_pair:t,add_special_tokens:n,return_token_type_ids:r??this.return_token_type_ids});return{input_ids:i,attention_mask:a,...o?{token_type_ids:o}:{}}}tokenize(e,{pair:t=null,add_special_tokens:n=!1}={}){return this._tokenizer.tokenize(e,{text_pair:t,add_special_tokens:n})}encode(e,{text_pair:t=null,add_special_tokens:n=!0,return_token_type_ids:r=null}={}){return this._tokenizer.encode(e,{text_pair:t,add_special_tokens:n,return_token_type_ids:r}).ids}batch_decode(e,t={}){return e instanceof Z&&(e=e.tolist()),e.map(e=>this.decode(e,t))}decode(e,t={}){if(e instanceof Z&&(e=PM(e)),!Array.isArray(e)||e.length===0||!rD(e[0]))throw Error(`token_ids must be a non-empty array of integers.`);return this.decode_single(e,t)}decode_single(e,{skip_special_tokens:t=!1,clean_up_tokenization_spaces:n=null}){return this._tokenizer.decode(e,{skip_special_tokens:t,clean_up_tokenization_spaces:n})}get_chat_template({chat_template:e=null,tools:t=null}={}){if(this.chat_template&&typeof this.chat_template==`object`){let n=this.chat_template;if(e!==null&&Object.hasOwn(n,e))e=n[e];else if(e===null)if(t!==null&&`tool_use`in n)e=n.tool_use;else if(`default`in n)e=n.default;else throw Error(`This model has multiple chat templates with no default specified! Please either pass a chat template or the name of the template you wish to use to the 'chat_template' argument. Available template names are ${Object.keys(n).sort()}.`)}else if(e===null)if(this.chat_template)e=this.chat_template;else throw Error(`Cannot use apply_chat_template() because tokenizer.chat_template is not set and no template argument was passed! For information about writing templates and setting the tokenizer.chat_template attribute, please see the documentation at https://huggingface.co/docs/transformers/main/en/chat_templating`);return e}apply_chat_template(e,{tools:t=null,documents:n=null,chat_template:r=null,add_generation_prompt:i=!1,tokenize:a=!0,padding:o=!1,truncation:s=!1,max_length:c=null,return_tensor:l=!0,return_dict:u=!0,tokenizer_kwargs:d={},...f}={}){if(r=this.get_chat_template({chat_template:r,tools:t}),typeof r!=`string`)throw Error(`chat_template must be a string, but got ${typeof r}`);let p=this._compiled_template_cache.get(r);p===void 0&&(p=new SA(r),this._compiled_template_cache.set(r,p));let m=Object.create(null);for(let e of FM){let t=RM(this.config,e);t&&(m[e]=t)}let h=p.render({messages:e,add_generation_prompt:i,tools:t,documents:n,...m,...f});if(a){let e=this._call(h,{add_special_tokens:!1,padding:o,truncation:s,max_length:c,return_tensor:l,...d});return u?e:e.input_ids}return h}};function VM(e,t,n,r){if(!(`language_codes`in e)||!Array.isArray(e.language_codes))throw Error("Tokenizer must have `language_codes` attribute set and it should be an array of language ids.");if(!(`languageRegex`in e)||!(e.languageRegex instanceof RegExp))throw Error("Tokenizer must have `languageRegex` attribute set and it should be a regular expression.");if(!(`lang_to_token`in e)||typeof e.lang_to_token!=`function`)throw Error("Tokenizer must have `lang_to_token` attribute set and it should be a function.");let i=r.src_lang,a=r.tgt_lang;if(!e.language_codes.includes(a))throw Error(`Target language code "${a}" is not valid. Must be one of: {${e.language_codes.join(`, `)}}`);if(i!==void 0){if(!e.language_codes.includes(i))throw Error(`Source language code "${i}" is not valid. Must be one of: {${e.language_codes.join(`, `)}}`);for(let t of e._tokenizer.post_processor.config.single)if(`SpecialToken`in t&&e.languageRegex.test(t.SpecialToken.id)){t.SpecialToken.id=e.lang_to_token(i);break}}return r.forced_bos_token_id=e._tokenizer.token_to_id(e.lang_to_token(a)),e._call(t,n)}var HM={};CE(HM,{AlbertTokenizer:()=>UM,AutoTokenizer:()=>zN,BartTokenizer:()=>WM,BertTokenizer:()=>GM,BlenderbotSmallTokenizer:()=>KM,BlenderbotTokenizer:()=>qM,BloomTokenizer:()=>JM,CLIPTokenizer:()=>XM,CamembertTokenizer:()=>YM,CodeGenTokenizer:()=>QM,CodeLlamaTokenizer:()=>ZM,CohereTokenizer:()=>$M,ConvBertTokenizer:()=>eN,DebertaTokenizer:()=>nN,DebertaV2Tokenizer:()=>tN,DistilBertTokenizer:()=>rN,ElectraTokenizer:()=>iN,EsmTokenizer:()=>aN,FalconTokenizer:()=>oN,GPT2Tokenizer:()=>lN,GPTNeoXTokenizer:()=>cN,GemmaTokenizer:()=>sN,HerbertTokenizer:()=>uN,LlamaTokenizer:()=>dN,M2M100Tokenizer:()=>fN,MBart50Tokenizer:()=>hN,MBartTokenizer:()=>mN,MPNetTokenizer:()=>vN,MarianTokenizer:()=>pN,MgpstrTokenizer:()=>gN,MobileBertTokenizer:()=>_N,NllbTokenizer:()=>yN,NougatTokenizer:()=>bN,PreTrainedTokenizer:()=>BM,Qwen2Tokenizer:()=>xN,RoFormerTokenizer:()=>CN,RobertaTokenizer:()=>SN,SiglipTokenizer:()=>wN,SpeechT5Tokenizer:()=>TN,SqueezeBertTokenizer:()=>EN,T5Tokenizer:()=>DN,TokenizersBackend:()=>BM,VitsTokenizer:()=>kN,Wav2Vec2CTCTokenizer:()=>AN,WhisperTokenizer:()=>IN,XLMRobertaTokenizer:()=>LN,XLMTokenizer:()=>RN});var UM=class extends BM{return_token_type_ids=!0},WM=class extends BM{},GM=class extends BM{return_token_type_ids=!0},KM=class extends BM{},qM=class extends BM{},JM=class extends BM{},YM=class extends BM{},XM=class extends BM{},ZM=class extends BM{},QM=class extends BM{},$M=class extends BM{},eN=class extends BM{return_token_type_ids=!0},tN=class extends BM{return_token_type_ids=!0},nN=class extends BM{return_token_type_ids=!0},rN=class extends BM{},iN=class extends BM{return_token_type_ids=!0},aN=class extends BM{},oN=class extends BM{},sN=class extends BM{},cN=class extends BM{},lN=class extends BM{},uN=class extends BM{return_token_type_ids=!0},dN=class extends BM{padding_side=`left`},fN=class extends BM{constructor(e,t){super(e,t),this.languageRegex=/^__[a-z]{2,3}__$/,this.language_codes=this.all_special_tokens.filter(e=>this.languageRegex.test(e)).map(e=>e.slice(2,-2)),this.lang_to_token=e=>`__${e}__`}_build_translation_inputs(e,t,n){return VM(this,e,t,n)}},pN=class extends BM{constructor(e,t){super(e,t),this.languageRegex=/^(>>\w+<<)\s*/g,this.supported_language_codes=Array.from(this.get_vocab().keys()).filter(e=>this.languageRegex.test(e)),dD.warn('WARNING: `MarianTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}_encode_text(e){if(e===null)return null;let[t,...n]=e.trim().split(this.languageRegex);if(n.length===0)return super._encode_text(t);if(n.length===2){let[e,t]=n;return this.supported_language_codes.includes(e)||dD.warn(`Unsupported language code "${e}" detected, which may lead to unexpected behavior. Should be one of: ${JSON.stringify(this.supported_language_codes)}`),oD([e],super._encode_text(t))}}},mN=class extends BM{constructor(e,t){super(e,t),this.languageRegex=/^[a-z]{2}_[A-Z]{2}$/,this.language_codes=this.all_special_tokens.filter(e=>this.languageRegex.test(e)).map(e=>e),this.lang_to_token=e=>e}_build_translation_inputs(e,t,n){return VM(this,e,t,n)}},hN=class extends mN{},gN=class extends BM{},_N=class extends BM{return_token_type_ids=!0},vN=class extends BM{},yN=class extends BM{constructor(e,t){super(e,t),this.languageRegex=/^[a-z]{3}_[A-Z][a-z]{3}$/,this.language_codes=this.all_special_tokens.filter(e=>this.languageRegex.test(e)),this.lang_to_token=e=>e}_build_translation_inputs(e,t,n){return VM(this,e,t,n)}},bN=class extends BM{},xN=class extends BM{},SN=class extends BM{},CN=class extends BM{return_token_type_ids=!0},wN=class extends BM{},TN=class extends BM{},EN=class extends BM{return_token_type_ids=!0},DN=class extends BM{},ON=class extends MO{decode_chain(e){let t=``;for(let n=1;n[t,e]),...[[`burmese`,`my`],[`valencian`,`ca`],[`flemish`,`nl`],[`haitian`,`ht`],[`letzeburgesch`,`lb`],[`pushto`,`ps`],[`panjabi`,`pa`],[`moldavian`,`ro`],[`moldovan`,`ro`],[`sinhalese`,`si`],[`castilian`,`es`]]]);function PN(e){e=e.toLowerCase();let t=NN.get(e);if(t===void 0){let n=e.match(/^<\|([a-z]{2})\|>$/);if(n&&(e=n[1]),MN.has(e))t=e;else{let t=e.length===2?MN.keys():MN.values();throw Error(`Language "${e}" is not supported. Must be one of: ${JSON.stringify(Array.from(t))}`)}}return t}var FN=RegExp(`^[\\p{P}\\u0021-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E]+$`,`gu`),IN=class extends BM{get timestamp_begin(){return this._tokenizer.token_to_id(`<|notimestamps|>`)+1}_decode_asr(e,{return_timestamps:t=!1,return_language:n=!1,time_precision:r=null,force_full_sequences:i=!0}={}){if(r===null)throw Error(`Must specify time_precision`);let a=null,o=t===`word`;function s(){return{language:a,timestamp:[null,null],text:``}}let c=[],l=s(),u=0,d=this.timestamp_begin,f=d+1500,p=[],m=[],h=!1,g=null,_=new Set(this.all_special_ids);for(let n of e){let e=n.tokens,i=o?n.token_timestamps:null,v=null,y=d;if(`stride`in n){let[t,i,a]=n.stride;if(u-=i,g=t-a,i&&(y=i/r+d),a)for(let t=e.length-1;t>=0;--t){let n=Number(e[t]);if(n>=d){if(v!==null&&(n-d)*r=d&&g<=f){let e=bj((g-d)*r+u,2);if(v!==null&&g>=v)h=!0;else if(h||p.length>0&&g0?(p.push(b),o&&m.push(x)):p.every(e=>e.length===0)&&(l=s(),p=[],b=[],m=[],x=[])}if(p.length>0){if(i&&t)throw Error(`Whisper did not predict an ending timestamp, which can happen if audio is cut off in the middle of a word. Also make sure WhisperTimeStampLogitsProcessor was used during generation.`);let[e,n]=this.findLongestCommonSequence(p,m),r=this.decode(e);l.text=r,o&&(l.words=this.collateWordTimestamps(e,n,a)),c.push(l)}let v=Object.create(null),y=c.map(e=>e.text).join(``);if(t||n){for(let e=0;e0,o=a?[]:null,s=a?t[0]:null;for(let c=1;ce===g[n]&&s[i+n]<=t[c][m+n]).length:p.filter((e,t)=>e===g[t]).length;let v=e/1e4,y=_/e+v;_>1&&y>u&&(u=y,d=[i,o,m,h])}let[p,m,h,g]=d,_=Math.floor((m+p)/2),v=Math.floor((g+h)/2);i.push(...n.slice(0,_)),n=l.slice(v),r=n.length,a&&(o.push(...s.slice(0,_)),s=t[c].slice(v))}return i.push(...n),a?(o.push(...s),[i,o]):[i,[]]}collateWordTimestamps(e,t,n){let[r,i,a]=this.combineTokensIntoWords(e,n),o=[];for(let e=0;e=r){let e=((t-r)*n).toFixed(2);i.push(`<|${e}|>`),i.push([])}else i[i.length-1].push(t);return i=i.map(e=>typeof e==`string`?e:super.decode(e,t)),i.join(``)}splitTokensOnUnicode(e){let t=this.decode(e,{decode_with_timestamps:!0}),n=[],r=[],i=[],a=[],o=[],s=0;for(let c=0;c=this._tokenizer.token_to_id(`<|endoftext|>`),d=s.startsWith(` `),f=s.trim(),p=FN.test(f);if(u||d||p||i.length===0)i.push(s),a.push(c),o.push(l);else{let e=i.length-1;i[e]+=s,a[e].push(...c),o[e].push(...l)}}return[i,a,o]}mergePunctuations(e,t,n,r,i){let a=structuredClone(e),o=structuredClone(t),s=structuredClone(n),c=a.length-2,l=a.length-1;for(;c>=0;)a[c].startsWith(` `)&&r.includes(a[c].trim())?(a[l]=a[c]+a[l],o[l]=oD(o[c],o[l]),s[l]=oD(s[c],s[l]),a[c]=``,o[c]=[],s[c]=[]):l=c,--c;for(c=0,l=1;le),o.filter(e=>e.length>0),s.filter(e=>e.length>0)]}},LN=class extends BM{},RN=class extends BM{return_token_type_ids=!0;constructor(e,t){super(e,t),dD.warn('WARNING: `XLMTokenizer` is not yet supported by Hugging Face\'s "fast" tokenizers library. Therefore, you may experience slightly inaccurate results.')}},zN=class{static async from_pretrained(e,{progress_callback:t=null,config:n=null,cache_dir:r=null,local_files_only:i=!1,revision:a=`main`}={}){let[o,s]=await NM(e,{progress_callback:t,config:n,cache_dir:r,local_files_only:i,revision:a}),c=s.tokenizer_class?.replace(/Fast$/,``)??`PreTrainedTokenizer`,l=HM[c];return l||=(dD.warn(`Unknown tokenizer class "${c}", attempting to construct from base class.`),BM),new l(o,s)}},BN=`https://github.com/huggingface/transformers.js/issues/new/choose`,VN=`preprocessor_config.json`,HN=VN,UN=`processor_config.json`,WN=`chat_template.jinja`,GN=class extends CA{static classes=[`image_processor_class`,`tokenizer_class`,`feature_extractor_class`];static uses_processor_config=!1;static uses_chat_template_file=!1;constructor(e,t,n){super(),this.config=e,this.components=t,this.chat_template=n}get image_processor(){return this.components.image_processor}get tokenizer(){return this.components.tokenizer}get feature_extractor(){return this.components.feature_extractor}apply_chat_template(e,t={}){if(!this.tokenizer)throw Error(`Unable to apply chat template without a tokenizer.`);return this.tokenizer.apply_chat_template(e,{tokenize:!1,chat_template:this.chat_template??void 0,...t})}batch_decode(...e){if(!this.tokenizer)throw Error(`Unable to decode without a tokenizer.`);return this.tokenizer.batch_decode(...e)}decode(...e){if(!this.tokenizer)throw Error(`Unable to decode without a tokenizer.`);return this.tokenizer.decode(...e)}async _call(e,...t){for(let n of[this.image_processor,this.feature_extractor,this.tokenizer])if(n)return n(e,...t);throw Error(`No image processor, feature extractor, or tokenizer found.`)}static async from_pretrained(e,t={}){let[n,r,i]=await Promise.all([this.uses_processor_config?cj(e,UN,!0,t):{},Promise.all(this.classes.filter(e=>e in this).map(async n=>{let r=await this[n].from_pretrained(e,t);return[n.replace(/_class$/,``),r]})).then(Object.fromEntries),this.uses_chat_template_file?sj(e,WN,!0,t):null]);return new this(n,r,i)}},KN={};CE(KN,{ChatterboxProcessor:()=>LP,Florence2Processor:()=>bI,Gemma3nProcessor:()=>xI,GraniteSpeechProcessor:()=>SI,GroundingDinoProcessor:()=>wI,Idefics3Processor:()=>OI,JinaCLIPProcessor:()=>AI,Lfm2VlProcessor:()=>jI,LlavaProcessor:()=>MI,MgpstrProcessor:()=>PI,MoonshineProcessor:()=>FI,OwlViTProcessor:()=>II,PaliGemmaProcessor:()=>zI,Phi3VProcessor:()=>HI,PixtralProcessor:()=>UI,Processor:()=>GN,PyAnnoteProcessor:()=>WI,Qwen2VLProcessor:()=>GI,Qwen2_5_VLProcessor:()=>KI,Qwen3VLProcessor:()=>qI,Sam2Processor:()=>YI,Sam2VideoProcessor:()=>XI,SamProcessor:()=>JI,SmolVLMProcessor:()=>OI,SpeechT5Processor:()=>ZI,UltravoxProcessor:()=>QI,VLChatProcessor:()=>kI,VoxtralProcessor:()=>rL,VoxtralRealtimeProcessor:()=>lL,Wav2Vec2Processor:()=>uL,Wav2Vec2ProcessorWithLM:()=>dL,WhisperProcessor:()=>fL});var qN=class extends CA{constructor(e){super(),this.config=e}static async from_pretrained(e,t={}){let n=await cj(e,VN,!0,t);return new this(n)}};function JN(e,t){if(!(e instanceof Float32Array||e instanceof Float64Array))throw Error(`${t} expects input to be a Float32Array or a Float64Array, but got ${e?.constructor?.name??typeof e} instead. If using the feature extractor directly, remember to use \`read_audio(url, sampling_rate)\` to obtain the raw audio data of the file/url.`)}var YN={};CE(YN,{ASTFeatureExtractor:()=>vP,ChatterboxFeatureExtractor:()=>bP,ClapFeatureExtractor:()=>xP,DacFeatureExtractor:()=>SP,EncodecFeatureExtractor:()=>yP,FeatureExtractor:()=>qN,Gemma3nAudioFeatureExtractor:()=>CP,GraniteSpeechFeatureExtractor:()=>wP,MoonshineFeatureExtractor:()=>TP,ParakeetFeatureExtractor:()=>DP,PyAnnoteFeatureExtractor:()=>OP,SeamlessM4TFeatureExtractor:()=>kP,SnacFeatureExtractor:()=>AP,SpeechT5FeatureExtractor:()=>jP,VoxtralRealtimeFeatureExtractor:()=>PP,Wav2Vec2FeatureExtractor:()=>MP,WeSpeakerFeatureExtractor:()=>NP,WhisperFeatureExtractor:()=>FP});var XN={fromWeb:()=>{}};async function ZN(e,t){if(GE.IS_BROWSER_ENV){if(GE.IS_WEBWORKER_ENV)throw Error(`Unable to save a file from a Web Worker.`);let n=URL.createObjectURL(t),r=document.createElement(`a`);r.href=n,r.download=e,r.click(),r.remove(),URL.revokeObjectURL(n)}else if(GE.IS_FS_AVAILABLE){let n=t.stream();await(XN.fromWeb(n),wE.createWriteStream(e),void 0)}else throw Error(`Unable to save because filesystem is disabled in this environment.`)}async function QN(e,t){if(typeof AudioContext>`u`)throw Error("Unable to load audio from path/URL since `AudioContext` is not available in your environment. Instead, audio data should be passed directly to the pipeline/processor. For more information and some example code, see https://huggingface.co/docs/transformers.js/guides/node-audio-processing.");let n=await(await ej(e)).arrayBuffer(),r=new AudioContext({sampleRate:t});t===void 0&&dD.warn(`No sampling rate provided, using default of ${r.sampleRate}Hz.`);let i=await r.decodeAudioData(n),a;if(i.numberOfChannels===2){let e=Math.sqrt(2),t=i.getChannelData(0),n=i.getChannelData(1);a=new Float32Array(t.length);for(let r=0;r2595*Math.log10(1+e/700),kaldi:e=>1127*Math.log(1+e/700),slaney:(e,t=1e3,n=15,r=27/Math.log(6.4))=>e>=t?n+Math.log(e/t)*r:3*e/200};function rP(e,t=`htk`){let n=nP[t];if(!n)throw Error(`mel_scale should be one of "htk", "slaney" or "kaldi".`);return typeof e==`number`?n(e):e.map(e=>n(e))}var iP={htk:e=>700*(10**(e/2595)-1),kaldi:e=>700*(Math.exp(e/1127)-1),slaney:(e,t=1e3,n=15,r=Math.log(6.4)/27)=>e>=n?t*Math.exp(r*(e-n)):200*e/3};function aP(e,t=`htk`){let n=iP[t];if(!n)throw Error(`mel_scale should be one of "htk", "slaney" or "kaldi".`);return typeof e==`number`?n(e):e.map(e=>n(e))}function oP(e,t){let n=Float64Array.from({length:t.length-1},(e,n)=>t[n+1]-t[n]),r=Array.from({length:e.length},()=>Array(t.length));for(let n=0;nArray(e.length));for(let t=0;te+r*n)}function cP(e,t,n,r,i,a=null,o=`htk`,s=!1){if(a!==null&&a!==`slaney`)throw Error(`norm must be one of null or "slaney"`);if(e<2)throw Error(`Require num_frequency_bins: ${e} >= 2`);if(n>r)throw Error(`Require min_frequency: ${n} <= max_frequency: ${r}`);let c=sP(rP(n,o),rP(r,o),t+2),l=aP(c,o),u;if(s){let t=i/((e-1)*2);u=rP(Float64Array.from({length:e},(e,n)=>n*t),o),l=c}else u=sP(0,Math.floor(i/2),e);let d=oP(u,l);if(a!==null&&a===`slaney`)for(let n=0;ni)throw Error(`frame_length (${n}) may not be larger than fft_length (${i})`);if(w!==n)throw Error(`Length of the window (${w}) must equal frame_length (${n})`);if(r<=0)throw Error(`hop_length must be greater than zero`);if(a===null&&d!==null)throw Error("You have provided `mel_filters` but `power` is `None`. Mel spectrogram computation is not yet supported for complex-valued spectrogram. Specify `power` to fix this issue.");if(!u)throw Error("`preemphasis_htk_flavor=false` is not currently supported.");if(o)switch(s){case`reflect`:{let t=Math.floor((i-1)/2)+1;e=lP(e,t,t);break}case`constant`:{let t=Math.floor(i/2),n=new e.constructor(e.length+2*t);n.set(e,t),e=n;break}default:throw Error(`pad_mode="${s}" not implemented yet.`)}let T=Math.floor(1+Math.floor((e.length-n)/r));y!==null&&TT?x&&(O=b):O=D=b);let k=new vj(i),A=new Float64Array(i),j=new Float64Array(k.outputBufferSize),ee=new Float32Array(E*O);for(let i=0;i=1;--e)A[e]-=l*A[e-1];A[0]*=1-l}for(let e=0;ee**.85);break;default:throw Error(`Unknown window type ${t}.`)}if(n&&(o=o.subarray(0,e)),r===null)return o;if(e>r)throw Error(`Length of the window (${e}) may not be larger than frame_length (${r})`);return o}function hP(e,t){let n=e.reduce((e,t)=>e+t.length,0),r=new ArrayBuffer(44),i=new DataView(r);return gP(i,0,`RIFF`),i.setUint32(4,36+n*4,!0),gP(i,8,`WAVE`),gP(i,12,`fmt `),i.setUint32(16,16,!0),i.setUint16(20,3,!0),i.setUint16(22,1,!0),i.setUint32(24,t,!0),i.setUint32(28,t*4,!0),i.setUint16(32,4,!0),i.setUint16(34,32,!0),gP(i,36,`data`),i.setUint32(40,n*4,!0),new Blob([r,...e.map(e=>e.buffer)],{type:`audio/wav`})}function gP(e,t,n){for(let r=0;re+t.length,0),t=new Float32Array(e),n=0;for(let e of this.audio)t.set(e,n),n+=e.length;return t}else return this.audio}toBlob(){let e=this.audio;return e instanceof Float32Array&&(e=[e]),hP(e,this.sampling_rate)}async save(e){return ZN(e,this.toBlob())}},vP=class extends qN{constructor(e){super(e);let t=this.config.sampling_rate;this.mel_filters=cP(257,this.config.num_mel_bins,20,Math.floor(t/2),t,null,`kaldi`,!0),this.window=mP(400,`hann`,{periodic:!1}),this.mean=this.config.mean,this.std=this.config.std}async _extract_fbank_features(e,t){return pP(e,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:`log`,mel_floor:1.192092955078125e-7,remove_dc_offset:!0,max_num_frames:t,transpose:!0})}async _call(e){JN(e,`ASTFeatureExtractor`);let t=await this._extract_fbank_features(e,this.config.max_length);if(this.config.do_normalize){let e=this.std*2,n=t.data;for(let t=0;t0)if(n===`rand_trunc`){let n=Math.floor(kA.random()*(a+1));e=e.subarray(n,n+t),i=await this._extract_fbank_features(e,this.mel_filters_slaney,this.config.nb_max_samples)}else throw Error(`Truncation strategy "${n}" not implemented`);else{if(a<0){let n=new Float64Array(t);if(n.set(e),r===`repeat`)for(let r=e.length;rt&&(e=e.slice(0,t)),r&&e.length%i!==0){let t=i-e.length%i,n=new Float64Array(e.length+t);n.set(e),this.config.padding_value!==0&&n.fill(this.config.padding_value,e.length),e=n}let a=await this._extract_fbank_features(e,this.config.max_length),o=wM([1,a.dims[0]],!0);return{input_features:a.unsqueeze_(0),input_features_mask:o}}},wP=class extends qN{constructor(e){super(e);let{n_fft:t,win_length:n,n_mels:r,sample_rate:i}=e.melspec_kwargs;this.mel_filters=cP(Math.floor(1+t/2),r,0,i/2,i,null,`htk`);let a=mP(n,`hann`);this.window=new Float64Array(t);let o=Math.floor((t-n)/2);this.window.set(a,o)}async _call(e){JN(e,`GraniteSpeechFeatureExtractor`);let{n_fft:t,hop_length:n,n_mels:r}=this.config.melspec_kwargs,i=1+Math.floor((e.length-1)/n),a=i-i%2;return{input_features:(await pP(e,this.window,t,n,{power:2,mel_filters:this.mel_filters,log_mel:`log10_max_norm`,transpose:!0,max_num_frames:a,do_pad:!1})).view(-1,2*r).unsqueeze_(0)}}},TP=class extends qN{async _call(e){JN(e,`MoonshineFeatureExtractor`),e instanceof Float64Array&&(e=new Float32Array(e));let t=[1,e.length];return{input_values:new Z(`float32`,e,t)}}},EP=1e-5,DP=class extends qN{constructor(e){super(e),this.config.mel_filters??=cP(Math.floor(1+this.config.n_fft/2),this.config.feature_size,0,this.config.sampling_rate/2,this.config.sampling_rate,`slaney`,`slaney`);let t=mP(this.config.win_length,`hann`,{periodic:!1});this.window=new Float64Array(this.config.n_fft);let n=Math.floor((this.config.n_fft-this.config.win_length)/2);this.window.set(t,n)}async _extract_fbank_features(e){let t=this.config.preemphasis;e=new Float64Array(e);for(let n=e.length-1;n>=1;--n)e[n]-=t*e[n-1];return await pP(e,this.window,this.window.length,this.config.hop_length,{fft_length:this.config.n_fft,power:2,mel_filters:this.config.mel_filters,log_mel:`log`,mel_floor:-1/0,pad_mode:`constant`,center:!0,transpose:!0,mel_offset:2**-24})}async _call(e){JN(e,`ParakeetFeatureExtractor`);let t=await this._extract_fbank_features(e),n=Math.floor((e.length+Math.floor(this.config.n_fft/2)*2-this.config.n_fft)/this.config.hop_length),r=t.data;r.fill(0,n*t.dims[1]);let[i,a]=t.dims,o=new Float64Array(a),s=new Float64Array(a);for(let e=0;e1?n-1:1;for(let e=0;e({id:e,start:t*n,end:r*n,confidence:i/(r-t)})))}return r}},kP=class extends qN{constructor(e){super(e);let t=this.config.sampling_rate;this.mel_filters=cP(257,this.config.num_mel_bins,20,Math.floor(t/2),t,null,`kaldi`,!0),this.window=mP(400,`povey`,{periodic:!1})}async _extract_fbank_features(e,t){return e=e.map(e=>e*32768),pP(e,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:`log`,mel_floor:1.192092955078125e-7,remove_dc_offset:!0,max_num_frames:t,transpose:!0})}async _call(e,{padding:t=!0,pad_to_multiple_of:n=2,do_normalize_per_mel_bins:r=!0,return_attention_mask:i=!0}={}){JN(e,`SeamlessM4TFeatureExtractor`);let a=await this._extract_fbank_features(e,this.config.max_length);if(r){let[e,t]=a.dims,n=a.data;for(let r=0;r0){let n=new Float32Array(t*(e+s));n.set(r),n.fill(this.config.padding_value,r.length);let c=e+s;a=new Z(a.type,n,[c,t]),i&&(o=new Z(`int64`,new BigInt64Array(c),[1,c]),o.data.fill(1n,0,e))}}let[s,c]=a.dims,l=this.config.stride;if(s%l!==0)throw Error(`The number of frames (${s}) must be a multiple of the stride (${l}).`);let u=a.view(1,Math.floor(s/l),c*l),d={input_features:u};if(i){let e=u.dims[1],t=new BigInt64Array(e);if(o){let e=o.data;for(let n=1,r=0;ne+t,0)/e.length,n=e.reduce((e,n)=>e+(n-t)**2,0)/e.length;return e.map(e=>(e-t)/Math.sqrt(n+1e-7))}async _call(e){JN(e,`Wav2Vec2FeatureExtractor`),e instanceof Float64Array&&(e=new Float32Array(e));let t=e;this.config.do_normalize&&(t=this._zero_mean_unit_var_norm(t));let n=[1,t.length];return{input_values:new Z(`float32`,t,n),attention_mask:new Z(`int64`,new BigInt64Array(t.length).fill(1n),n)}}},NP=class extends qN{constructor(e){super(e);let t=this.config.sampling_rate;this.mel_filters=cP(257,this.config.num_mel_bins,20,Math.floor(t/2),t,null,`kaldi`,!0),this.window=mP(400,`hamming`,{periodic:!1}),this.min_num_frames=this.config.min_num_frames}async _extract_fbank_features(e){return e=e.map(e=>e*32768),pP(e,this.window,400,160,{fft_length:512,power:2,center:!1,preemphasis:.97,mel_filters:this.mel_filters,log_mel:`log`,mel_floor:1.192092955078125e-7,remove_dc_offset:!0,transpose:!0,min_num_frames:this.min_num_frames})}async _call(e){JN(e,`WeSpeakerFeatureExtractor`);let t=(await this._extract_fbank_features(e)).unsqueeze_(0);if(this.config.fbank_centering_span===null){let e=t.mean(1).data,n=t.data,[r,i,a]=t.dims;for(let t=0;tr?(e.length>this.config.n_samples&&dD.warn("Attempting to extract features for audio longer than 30 seconds. If using a pipeline to extract transcript from a long audio clip, remember to specify `chunk_length_s` and/or `stride_length_s`."),n=e.slice(0,r)):(n=new Float32Array(r),n.set(e)),{input_features:(await this._extract_fbank_features(n)).unsqueeze_(0)}}},IP=class{static async from_pretrained(e,t={}){let n=await cj(e,VN,!0,t),r=n.feature_extractor_type,i=YN[r];if(!i)throw Error(`Unknown feature_extractor_type: '${r}'. Please report this at ${BN}.`);return new i(n)}},LP=class extends GN{static tokenizer_class=zN;static feature_extractor_class=IP;async _call(e,t=null){let n=this.tokenizer(e),r=t?await this.feature_extractor(t):{};return{...n,...r}}},RP={},zP,BP,VP;if(GE.IS_WEB_ENV)zP=(e,t)=>{if(!self.OffscreenCanvas)throw Error(`OffscreenCanvas not supported by this environment.`);return new self.OffscreenCanvas(e,t)},VP=self.createImageBitmap,BP=self.ImageData;else if(RP)VP=async e=>{let t=(await e.metadata()).channels,{data:n,info:r}=await e.rotate().raw().toBuffer({resolveWithObject:!0}),i=new WP(new Uint8ClampedArray(n),r.width,r.height,r.channels);return t!==void 0&&t!==r.channels&&i.convert(t),i};else throw Error(`Unable to load image processing library.`);var HP={0:`nearest`,1:`lanczos`,2:`bilinear`,3:`bicubic`,4:`box`,5:`hamming`},UP=new Map([[`png`,`image/png`],[`jpg`,`image/jpeg`],[`jpeg`,`image/jpeg`],[`gif`,`image/gif`]]),WP=class e{constructor(e,t,n,r){this.data=e,this.width=t,this.height=n,this.channels=r}get size(){return[this.width,this.height]}static async read(t){if(t instanceof e)return t;if(typeof t==`string`||t instanceof URL)return await this.fromURL(t);if(t instanceof Blob)return await this.fromBlob(t);if(typeof HTMLCanvasElement<`u`&&t instanceof HTMLCanvasElement||typeof OffscreenCanvas<`u`&&t instanceof OffscreenCanvas)return this.fromCanvas(t);throw Error(`Unsupported input type: ${typeof t}`)}static fromCanvas(t){if(!GE.IS_WEB_ENV)throw Error(`fromCanvas() is only supported in browser environments.`);let n=t.getContext(`2d`).getImageData(0,0,t.width,t.height).data;return new e(n,t.width,t.height,4)}static async fromURL(e){let t=await ej(e);if(t.status!==200)throw Error(`Unable to read image from "${e}" (${t.status} ${t.statusText})`);let n=await t.blob();return this.fromBlob(n)}static async fromBlob(e){if(GE.IS_WEB_ENV){let t=await VP(e),n=zP(t.width,t.height).getContext(`2d`);return n.drawImage(t,0,0),new this(n.getImageData(0,0,t.width,t.height).data,t.width,t.height,4)}else{let t=RP(await e.arrayBuffer());return await VP(t)}}static fromTensor(t,n=`CHW`){if(t.dims.length!==3)throw Error(`Tensor should have 3 dimensions, but has ${t.dims.length} dimensions.`);if(n===`CHW`)t=t.transpose(1,2,0);else if(n!==`HWC`)throw Error(`Unsupported channel format: ${n}`);if(!(t.data instanceof Uint8ClampedArray||t.data instanceof Uint8Array))throw Error(`Unsupported tensor type: ${t.type}`);switch(t.dims[2]){case 1:case 2:case 3:case 4:return new e(t.data,t.dims[1],t.dims[0],t.dims[2]);default:throw Error(`Unsupported number of channels: ${t.dims[2]}`)}}grayscale(){if(this.channels===1)return this;let e=new Uint8ClampedArray(this.width*this.height*1);switch(this.channels){case 3:case 4:for(let t=0,n=0;t=0?c=r:u=-r,i>=0?l=i:d=-i,s.drawImage(o,c,l,t,n,u,d,t,n),new e(s.getImageData(0,0,t,n).data,t,n,4).convert(a)}else{let e=this.toSharp();if(r>=0&&i>=0)e=e.extract({left:Math.floor(r),top:Math.floor(i),width:t,height:n});else if(r<=0&&i<=0){let a=Math.floor(-i),o=Math.floor(-r);e=e.extend({top:a,left:o,right:t-this.width-o,bottom:n-this.height-a})}else{let a=[0,0],o=0;i<0?(a[0]=Math.floor(-i),a[1]=n-this.height-a[0]):o=Math.floor(i);let s=[0,0],c=0;r<0?(s[0]=Math.floor(-r),s[1]=t-this.width-s[0]):c=Math.floor(r),e=e.extend({top:a[0],bottom:a[1],left:s[0],right:s[1]}).extract({left:c,top:o,width:t,height:n})}return await VP(e)}}async toBlob(e=`image/png`,t=1){if(!GE.IS_WEB_ENV)throw Error(`toBlob() is only supported in browser environments.`);return await this.toCanvas().convertToBlob({type:e,quality:t})}toTensor(e=`CHW`){let t=new Z(`uint8`,new Uint8Array(this.data),[this.height,this.width,this.channels]);if(e!==`HWC`)if(e===`CHW`)t=t.permute(2,0,1);else throw Error(`Unsupported channel format: ${e}`);return t}toCanvas(){if(!GE.IS_WEB_ENV)throw Error(`toCanvas() is only supported in browser environments.`);let e=this.clone().rgba(),t=zP(e.width,e.height),n=new BP(e.data,e.width,e.height);return t.getContext(`2d`).putImageData(n,0,0),t}split(){let{data:t,width:n,height:r,channels:i}=this,a=t.constructor,o=t.length/i,s=Array.from({length:i},()=>new a(o));for(let e=0;enew e(t,n,r,1))}_update(e,t,n,r=null){return this.data=e,this.width=t,this.height=n,r!==null&&(this.channels=r),this}clone(){return new e(this.data.slice(),this.width,this.height,this.channels)}convert(e){if(this.channels===e)return this;switch(e){case 1:this.grayscale();break;case 3:this.rgb();break;case 4:this.rgba();break;default:throw Error(`Conversion failed due to unsupported number of channels: ${this.channels}`)}return this}async save(e){if(GE.IS_WEB_ENV){if(GE.IS_WEBWORKER_ENV)throw Error(`Unable to save an image from a Web Worker.`);let t=e.split(`.`).pop().toLowerCase(),n=UP.get(t)??`image/png`;return ZN(e,await this.toBlob(n))}else if(GE.IS_FS_AVAILABLE)await this.toSharp().toFile(e);else throw Error(`Unable to save the image because filesystem is disabled in this environment.`)}toSharp(){if(GE.IS_WEB_ENV)throw Error(`toSharp() is only supported in server-side environments.`);return RP(this.data,{raw:{width:this.width,height:this.height,channels:this.channels}})}};WP.read.bind(WP);function GP(e,t,n=0,r=null){let i=e/t,a=xj(i)*t;return r!==null&&a>r&&(a=Math.floor(i)*t),at&&i.push(e)}else{let e=mj(n.data)[1];if(e===c-1||(a=dj(n.data),a[e]e*o[(t+1)%2])),u.boxes.push(n),u.classes.push(t),u.scores.push(a[t])}}l.push(u)}return l}function YP(e,t=null){let n=e.logits,r=n.dims[0];if(t!==null&&t.length!==r)throw Error(`Make sure that you pass in as many target sizes as the batch dimension of the logits`);let i=[];for(let e=0;el[n]&&(l[n]=t[n],u[n]=e)}let d=Array(a.dims[0]);for(let e=0;ee!==void 0);i.push({segmentation:c,labels:f})}return i}function XP(e,t,n,r){let i=[],a=[],o=[];for(let s=0;sn&&(i.push(l),a.push(d),o.push(u))}return[i,a,o]}function ZP(e,t,n,r=.5,i=.8){let a=[],o=0,s=0,c=t[n].data;for(let t=0;t=r&&++s;let l=o>0&&s>0;return l&&=o/s>i,[l,a]}function QP(e,t,n,r,i,a=null,o=null){let[s,c]=o??e[0].dims,l=new Z(`int32`,new Int32Array(s*c),[s,c]),u=[];if(o!==null)for(let t=0;tf[e]&&(d[e]=n,f[e]=i[e])}let p=0,m=l.data;for(let a=0;a200)throw Error(`absolute aspect ratio must be smaller than 200, got ${Math.max(e,t)/Math.min(e,t)}`);let a=Math.round(e/n)*n,o=Math.round(t/n)*n;if(a*o>i){let r=Math.sqrt(e*t/i);a=Math.floor(e/r/n)*n,o=Math.floor(t/r/n)*n}else if(a*oi?c=Math.floor(i*s/r):i>r&&(s=Math.floor(r*c/i)),await e.resize(c,s,{resample:n}))}async crop_margin(e,t=200){let n=e.clone().grayscale(),r=pj(n.data)[0],i=mj(n.data)[0]-r;if(i===0)return e;let a=t/255,o=n.width,s=n.height,c=0,l=0,u=n.data;for(let e=0;ethis.preprocess(e)));return{pixel_values:vM(n.map(e=>e.pixel_values),0),original_sizes:n.map(e=>e.original_size),reshaped_input_sizes:n.map(e=>e.reshaped_input_size)}}static async from_pretrained(e,t={}){let n=await cj(e,HN,!0,t);return new this(n)}},rF={};CE(rF,{BeitFeatureExtractor:()=>iF,BitImageProcessor:()=>aF,CLIPFeatureExtractor:()=>cF,CLIPImageProcessor:()=>sF,ChineseCLIPFeatureExtractor:()=>oF,ConvNextFeatureExtractor:()=>uF,ConvNextImageProcessor:()=>lF,DINOv3ViTImageProcessor:()=>hF,DPTFeatureExtractor:()=>yF,DPTImageProcessor:()=>vF,DeiTFeatureExtractor:()=>fF,DeiTImageProcessor:()=>dF,DetrFeatureExtractor:()=>mF,DetrImageProcessor:()=>pF,DonutFeatureExtractor:()=>_F,DonutImageProcessor:()=>gF,EfficientNetImageProcessor:()=>bF,GLPNFeatureExtractor:()=>xF,GroundingDinoImageProcessor:()=>SF,Idefics3ImageProcessor:()=>CF,ImageFeatureExtractor:()=>nF,ImageProcessor:()=>nF,JinaCLIPImageProcessor:()=>TF,Lfm2VlImageProcessor:()=>jF,LlavaOnevisionImageProcessor:()=>MF,Mask2FormerImageProcessor:()=>FF,MaskFormerFeatureExtractor:()=>PF,MaskFormerImageProcessor:()=>NF,MobileNetV1FeatureExtractor:()=>LF,MobileNetV1ImageProcessor:()=>IF,MobileNetV2FeatureExtractor:()=>zF,MobileNetV2ImageProcessor:()=>RF,MobileNetV3FeatureExtractor:()=>VF,MobileNetV3ImageProcessor:()=>BF,MobileNetV4FeatureExtractor:()=>UF,MobileNetV4ImageProcessor:()=>HF,MobileViTFeatureExtractor:()=>GF,MobileViTImageProcessor:()=>WF,NougatImageProcessor:()=>KF,OwlViTFeatureExtractor:()=>JF,OwlViTImageProcessor:()=>qF,Owlv2ImageProcessor:()=>YF,Phi3VImageProcessor:()=>tI,PixtralImageProcessor:()=>nI,PvtImageProcessor:()=>rI,Qwen2VLImageProcessor:()=>iI,RTDetrImageProcessor:()=>aI,Sam2ImageProcessor:()=>oI,Sam3ImageProcessor:()=>oI,SamImageProcessor:()=>oI,SapiensFeatureExtractor:()=>cI,SapiensImageProcessor:()=>sI,SegformerFeatureExtractor:()=>uI,SegformerImageProcessor:()=>lI,SiglipImageProcessor:()=>dI,SmolVLMImageProcessor:()=>CF,Swin2SRImageProcessor:()=>fI,VLMImageProcessor:()=>wF,ViTFeatureExtractor:()=>mI,ViTImageProcessor:()=>pI,VitMatteImageProcessor:()=>hI,VitPoseImageProcessor:()=>gI,YolosFeatureExtractor:()=>vI,YolosImageProcessor:()=>_I});var iF=class extends nF{},aF=class extends nF{},oF=class extends nF{},sF=class extends nF{},cF=class extends sF{},lF=class extends nF{constructor(e){super(e),this.crop_pct=this.config.crop_pct??224/256}async resize(e){let t=this.size?.shortest_edge;if(t===void 0)throw Error(`Size dictionary must contain 'shortest_edge' key.`);if(t<384){let n=Math.floor(t/this.crop_pct),[r,i]=this.get_resize_output_image_size(e,{shortest_edge:n});e=await e.resize(r,i,{resample:this.resample}),e=await e.center_crop(t,t)}else e=await e.resize(t,t,{resample:this.resample});return e}},uF=class extends lF{},dF=class extends nF{},fF=class extends dF{},pF=class extends nF{async _call(e){let t=await super._call(e),n=wM([t.pixel_values.dims[0],64,64],1n);return{...t,pixel_mask:n}}post_process_object_detection(...e){return JP(...e)}post_process_panoptic_segmentation(...e){return eF(...e)}post_process_instance_segmentation(...e){return tF(...e)}},mF=class extends pF{},hF=class extends nF{},gF=class extends nF{pad_image(e,t,n,r={}){let[i,a,o]=t,s=this.image_mean;Array.isArray(this.image_mean)||(s=Array(o).fill(s));let c=this.image_std;Array.isArray(c)||(c=Array(o).fill(s));let l=s.map((e,t)=>-e/c[t]);return super.pad_image(e,t,n,{center:!0,constant_values:l,...r})}},_F=class extends gF{},vF=class extends nF{},yF=class extends vF{},bF=class extends nF{constructor(e){super(e),this.include_top=this.config.include_top??!0,this.include_top&&(this.image_std=this.image_std.map(e=>e*e))}},xF=class extends nF{},SF=class extends nF{async _call(e){let t=await super._call(e),n=t.pixel_values.dims,r=EM([n[0],n[2],n[3]]);return{...t,pixel_mask:r}}},CF=class extends nF{constructor(e){super(e),this.do_image_splitting=e.do_image_splitting??!0,this.max_image_size=e.max_image_size}get_resize_for_vision_encoder(e,t){let[n,r]=e.dims.slice(-2),i=r/n;return r>=n?(r=Math.ceil(r/t)*t,n=Math.floor(r/i),n=Math.ceil(n/t)*t):(n=Math.ceil(n/t)*t,r=Math.floor(n*i),r=Math.ceil(r/t)*t),{height:n,width:r}}async _call(e,{do_image_splitting:t=null,return_row_col_info:n=!1}={}){let r;if(!Array.isArray(e))r=[[e]];else{if(e.length===0||!e[0])throw Error(`No images provided.`);r=Array.isArray(e[0])?e:[e]}let i=[],a=[],o=[],s=[],c=[];for(let e of r){let n=await Promise.all(e.map(e=>this.preprocess(e)));s.push(...n.map(e=>e.original_size)),c.push(...n.map(e=>e.reshaped_input_size)),n.forEach(e=>e.pixel_values.unsqueeze_(0));let{longest_edge:r}=this.max_image_size,l;if(t??this.do_image_splitting){let e=Array(n.length),t=Array(n.length);l=await Promise.all(n.map(async(n,i)=>{let a=this.get_resize_for_vision_encoder(n.pixel_values,r),o=await cM(n.pixel_values,{size:[a.height,a.width]}),{frames:s,num_splits_h:c,num_splits_w:l}=await this.split_image(o,this.max_image_size);return e[i]=c,t[i]=l,_M(s,0)})),a.push(e),o.push(t)}else{let e=[r,r];l=await Promise.all(n.map(t=>cM(t.pixel_values,{size:e}))),a.push(Array(n.length).fill(0)),o.push(Array(n.length).fill(0))}i.push(_M(l,0))}let l=i.length,[u,d,f,p]=i[0].dims,m,h;if(l===1)m=i[0].unsqueeze_(0),h=wM([l,u,f,p],!0);else{let e=Math.max(...i.map(e=>e.dims.at(0)));h=wM([l,e,f,p],!0);let t=h.data,n=e*f*p;for(let r=0;rn||o>r){s=Math.ceil(a/n),c=Math.ceil(o/r);let t=Math.ceil(a/s),l=Math.ceil(o/c);for(let n=0;ne*this.rescale_factor)}pad_image(e,t,n,r){return super.pad_image(e,t,n,{constant_values:this.constant_values,center:!0,...r})}},TF=class extends nF{constructor(e){let{resize_mode:t,fill_color:n,interpolation:r,size:i,...a}=e,o=t===`squash`?{width:i,height:i}:t===`shortest`?{shortest_edge:i}:{longest_edge:i},s=r===`bicubic`?3:2;super({...a,size:o,resample:s,do_center_crop:!0,crop_size:i,do_normalize:!0})}};function EF(e,t){return Math.round(e/t)*t}function DF(e,t,n,r,i){let a=1/0,o=[1,1],s=n*r;for(let n of t){let t=Math.abs(e-n[0]/n[1]);t.5*i*i*n[0]*n[1]&&(o=n)}return o}function OF(e,t){let n=[],r=new Set;for(let i=e;i<=t;++i)for(let a=1;a<=i;++a)for(let o=1;o<=i;++o){let i=a*o;if(i>=e&&i<=t){let e=a<<16|o;r.has(e)||(r.add(e),n.push([a,o]))}}return n.sort((e,t)=>e[0]*e[1]-t[0]*t[1])}function kF(e,t){let[n,r,i,a]=e.dims,o=Math.floor(i/t),s=Math.floor(a/t),c=t*t*r,l=e.data,u=new Float32Array(n*o*s*c),d=i*a;for(let e=0;ethis.max_image_tokens*(this.encoder_patch_size*this.downsample_factor)**2*this.max_pixels_tolerance}_get_grid_layout(e,t){let n=OF(this.min_tiles,this.max_tiles),[r,i]=DF(t/e,n,t,e,this.tile_size);return{grid_width:r,grid_height:i,target_width:this.tile_size*r,target_height:this.tile_size*i}}async _call(e,{return_row_col_info:t=null}={}){let n;n=Array.isArray(e)?Array.isArray(e[0])?e:[e]:[[e]];let r=[],i=[],a=[],o=[],s=[],c=[];for(let e of n){let t=await Promise.all(e.map(e=>this.preprocess(e,{do_pad:!1})));for(let{pixel_values:e}of t){let[,t,n]=e.dims,l=e.unsqueeze_(0),u=this.encoder_patch_size*this.downsample_factor,d=u**2,[f,p]=$P(Math.max(u,t),Math.max(u,n),u,this.min_image_tokens*d,this.max_image_tokens*d).map(e=>Math.max(u,e)),m,h=1,g=1,_=this._is_image_too_large(t,n),v=this.do_image_splitting&&!(this.min_tiles===1&&this.max_tiles===1);if(_&&v){let{grid_width:e,grid_height:r,target_width:i,target_height:a}=this._get_grid_layout(t,n);h=r,g=e;let o=await cM(l,{size:[a,i]});m=[];for(let t=0;t(e-this.image_mean[t])/this.image_std[t]);return super.pad_image(e,t,{width:s,height:o},{center:!0,constant_values:c,...r})}async _call(e,{num_crops:t=null}={}){if(this._num_crops=t??=this.config.num_crops,t<4||eI(t)%1!=0)throw Error(`num_crops must be a square number >= 4`);Array.isArray(e)||(e=[e]);let n=e.length,r=await Promise.all(e.map(e=>this.preprocess(e))),i=r.map(e=>e.original_size),a=r.map(e=>e.reshaped_input_size),o=[];for(let{pixel_values:e}of r){e.unsqueeze_(0);let[n,r]=e.dims.slice(-2),i=await cM(e,{size:[XF,XF],mode:`bicubic`});if(t>0){let a=[],s=eI(t),c=$F(r/s),l=$F(n/s);for(let t=0;te.map(e=>XF*QF(e/XF)));return{pixel_values:s,original_sizes:i,reshaped_input_sizes:a,image_sizes:new Z(`int64`,c.flat(),[n,2]),num_img_tokens:c.map(([e,t])=>this.calc_num_image_tokens_from_image_size(t,e))}}},nI=class extends nF{get_resize_output_image_size(e,t){let{longest_edge:n}=t;if(n===void 0)throw Error(`size must contain 'longest_edge'`);let[r,i]=e.size,a=Math.max(r,i)/n,o=r,s=i;a>1&&(o=Math.floor(r/a),s=Math.floor(i/a));let{patch_size:c,spatial_merge_size:l}=this.config;if(!l)throw Error(`config must contain 'spatial_merge_size'`);let u=c*l,d=Math.floor((o-1)/u)+1,f=Math.floor((s-1)/u)+1;return[d*u,f*u]}},rI=class extends nF{},iI=class extends nF{constructor(e){super(e),this.min_pixels=e.min_pixels??e.size?.shortest_edge,this.max_pixels=e.max_pixels??e.size?.longest_edge,this.patch_size=e.patch_size,this.merge_size=e.merge_size}get_resize_output_image_size(e,t){let n=this.patch_size*this.merge_size;return $P(e.height,e.width,n,this.min_pixels,this.max_pixels)}async _call(e,...t){let{pixel_values:n,original_sizes:r,reshaped_input_sizes:i}=await super._call(e,...t),a=n,{temporal_patch_size:o,merge_size:s,patch_size:c}=this.config;a.dims[0]===1&&(a=_M(Array.from({length:o},()=>a),0));let l=a.dims[0]/o,u=a.dims[1],d=Math.floor(a.dims[2]/c),f=Math.floor(a.dims[3]/c);return{pixel_values:a.view(l,o,u,Math.floor(d/s),s,c,Math.floor(f/s),s,c).permute(0,3,6,4,7,2,1,5,8).view(l*d*f,u*o*c*c),image_grid_thw:new Z(`int64`,[l,d,f],[1,3]),original_sizes:r,reshaped_input_sizes:i}}},aI=class extends nF{post_process_object_detection(...e){return JP(...e)}},oI=class extends nF{reshape_input_points(e,t,n,r=!1){e=structuredClone(e);let i=aD(e);if(i.length===3)r||(i=[1,...i]),e=[e];else if(i.length!==4)throw Error("The input_points must be a 4D tensor of shape `batch_size`, `point_batch_size`, `nb_points_per_image`, `2`.");for(let r=0;re!==t.dims[n]))throw Error(`The first ${n.length} dimensions of 'input_points' and 'input_labels' must be the same.`);return new Z(`int64`,e.flat(1/0).map(BigInt),n)}async _call(e,{input_points:t=null,input_labels:n=null,input_boxes:r=null}={}){let i=await super._call(e);if(t&&(i.input_points=this.reshape_input_points(t,i.original_sizes,i.reshaped_input_sizes)),n){if(!i.input_points)throw Error("`input_points` must be provided if `input_labels` are provided.");i.input_labels=this.add_input_labels(n,i.input_points)}return r&&(i.input_boxes=this.reshape_input_points(r,i.original_sizes,i.reshaped_input_sizes,!0)),i}async post_process_masks(e,t,n,{mask_threshold:r=0,binarize:i=!0,pad_size:a=null}={}){let o=[];a=a??this.pad_size??this.size;let s=[a.height,a.width];for(let a=0;ar&&(t[n]=1);u=new Z(`bool`,t,u.dims)}o.push(u)}return o}generate_crop_boxes(e,t,{crop_n_layers:n=0,overlap_ratio:r=512/1500,points_per_crop:i=32,crop_n_points_downscale_factor:a=1}={}){}},sI=class extends nF{post_process_semantic_segmentation(...e){return YP(...e)}},cI=class extends sI{},lI=class extends nF{post_process_semantic_segmentation(...e){return YP(...e)}},uI=class extends lI{},dI=class extends nF{},fI=class extends nF{pad_image(e,t,n,r={}){let[i,a,o]=t;return super.pad_image(e,t,{width:a+(n-a%n)%n,height:i+(n-i%n)%n},{mode:`symmetric`,center:!1,constant_values:-1,...r})}},pI=class extends nF{},mI=class extends pI{},hI=class extends nF{async _call(e,t){Array.isArray(e)||(e=[e]),Array.isArray(t)||(t=[t]);let n=await Promise.all(e.map(e=>this.preprocess(e))),r=await Promise.all(t.map(e=>this.preprocess(e,{do_normalize:!1,do_convert_rgb:!1,do_convert_grayscale:!0})));return{pixel_values:vM(n.map((e,t)=>_M([e.pixel_values,r[t].pixel_values],0)),0),original_sizes:n.map(e=>e.original_size),reshaped_input_sizes:n.map(e=>e.reshaped_input_size)}}},gI=class extends nF{post_process_pose_estimation(e,t,{threshold:n=null}={}){let r=e.tolist(),[i,a,o,s]=e.dims,c=[];for(let e=0;e/gm,bboxes:/([^<]+)?/gm},this.size_per_bin=1e3}construct_prompts(e){typeof e==`string`&&(e=[e]);let t=[];for(let n of e)if(this.task_prompts_without_inputs.has(n))t.push(this.task_prompts_without_inputs.get(n));else{for(let[e,r]of this.task_prompts_with_input)if(n.includes(e)){t.push(r.replaceAll(`{input}`,n).replaceAll(e,``));break}t.length!==e.length&&t.push(n)}return t}post_process_generation(e,t,n){let r=this.tasks_answer_post_processing_type.get(t)??`pure_text`;e=e.replaceAll(``,``).replaceAll(``,``);let i;switch(r){case`pure_text`:i=e;break;case`description_with_bboxes`:case`bboxes`:case`phrase_grounding`:case`ocr`:let a=r===`ocr`?`quad_boxes`:`bboxes`,o=e.matchAll(this.regexes[a]),s=[],c=[];for(let[e,t,...r]of o)s.push(t?t.trim():s.at(-1)??``),c.push(r.map((e,t)=>(Number(e)+.5)/this.size_per_bin*n[t%2]));i={labels:s,[a]:c};break;default:throw Error(`Task "${t}" (of type "${r}") not yet implemented.`)}return{[t]:i}}async _call(e,t=null,n={}){if(!e&&!t)throw Error(`Either text or images must be provided`);let r=await this.image_processor(e,n),i=t?this.tokenizer(this.construct_prompts(t),n):{};return{...r,...i}}},xI=class extends GN{static image_processor_class=yI;static feature_extractor_class=IP;static tokenizer_class=zN;static uses_processor_config=!0;static uses_chat_template_file=!0;constructor(e,t,n){super(e,t,n),this.audio_seq_length=this.config.audio_seq_length,this.image_seq_length=this.config.image_seq_length;let{audio_token_id:r,boa_token:i,audio_token:a,eoa_token:o,image_token_id:s,boi_token:c,image_token:l,eoi_token:u}=this.tokenizer.config;this.audio_token_id=r,this.boa_token=i,this.audio_token=a,this.full_audio_sequence=` + +${i}${a.repeat(this.audio_seq_length)}${o} + +`,this.image_token_id=s,this.boi_token=c,this.image_token=l,this.full_image_sequence=` + +${c}${l.repeat(this.image_seq_length)}${u} + +`}async _call(e,t=null,n=null,r={}){typeof e==`string`&&(e=[e]);let i;n&&(i=await this.feature_extractor(n,r),e=e.map(e=>e.replaceAll(this.audio_token,this.full_audio_sequence)));let a;return t&&(a=await this.image_processor(t,r),e=e.map(e=>e.replaceAll(this.image_token,this.full_image_sequence))),{...this.tokenizer(e,r),...a,...i}}},SI=class extends GN{static tokenizer_class=zN;static feature_extractor_class=IP;static uses_processor_config=!0;_get_num_audio_features(e){let{hop_length:t}=this.feature_extractor.config.melspec_kwargs,{projector_window_size:n,projector_downsample_rate:r}=this.feature_extractor.config,i=Math.floor(n/r),a=Math.floor(e/t)+1,o=Math.floor(a/2);return Math.ceil(o/n)*i}async _call(e,t=null,n={}){if(Array.isArray(e))throw Error(`Batched inputs are not supported yet.`);let r={};if(t){let{input_features:n}=await this.feature_extractor(t);r.input_features=n;let i=this._get_num_audio_features(t.length);r.input_features_mask=new Z(`bool`,new Uint8Array(i).fill(1),[1,i]);let a=this.config.audio_token??`<|audio|>`;if(!e.includes(a))throw Error(`The input text does not contain the audio token ${a}.`);e=e.replaceAll(a,a.repeat(i))}return{...this.tokenizer(e,{add_special_tokens:!1,...n}),...r}}};function CI(e,t){let n=e.dims.at(-1)-1,r=e.tolist();r.fill(!1,0,1),r.fill(!1,n);let i=t.tolist();return r.map((e,t)=>e?t:null).filter(e=>e!==null).map(e=>i[e])}var wI=class extends GN{static tokenizer_class=zN;static image_processor_class=yI;async _call(e,t,n={}){let r=e?await this.image_processor(e,n):{};return{...t?this.tokenizer(t,n):{},...r}}post_process_grounded_object_detection(e,t,{box_threshold:n=.25,text_threshold:r=.25,target_sizes:i=null}={}){let{logits:a,pred_boxes:o}=e,s=a.dims[0];if(i!==null&&i.length!==s)throw Error(`Make sure that you pass in as many target sizes as the batch dimension of the logits`);let c=a.dims.at(1),l=a.sigmoid(),u=l.max(-1).tolist(),d=o.tolist().map(e=>e.map(e=>qP(e))),f=[];for(let e=0;ee.map((e,t)=>e*a[(t+1)%2])));let o=u[e],s=[],p=[],m=[];for(let i=0;i`+i.repeat(e);o+=` +`}return o+=` +${r}${a}`+i.repeat(e)+`${r}`,o}function EI(e,t,n,r){return`${t}${r}`+n.repeat(e)+`${t}`}function DI(e,t,n,r,i,a){return e===0&&t===0?EI(n,r,i,a):TI(n,e,t,r,i,a)}var OI=class extends GN{static image_processor_class=yI;static tokenizer_class=zN;static uses_processor_config=!0;fake_image_token=``;image_token=``;global_img_token=``;async _call(e,t=null,n={}){n.return_row_col_info??=!0;let r;t&&(r=await this.image_processor(t,n)),Array.isArray(e)||(e=[e]);let i=r.rows??[Array(e.length).fill(0)],a=r.cols??[Array(e.length).fill(0)],o=this.config.image_seq_len,s=[],c=[];for(let t=0;tDI(e,l[t],o,this.fake_image_token,this.image_token,this.global_img_token)),d=n.split(this.image_token);if(d.length===0)throw Error(`The image token should be present in the text.`);let f=d[0];for(let e=0;ee.images).flatMap(e=>e.images).map(e=>WP.read(e)));let r=this.tokenizer,i=r.apply_chat_template(e,{tokenize:!1,add_generation_prompt:!0,chat_template:n}),a=e=>r.encode(e,{add_special_tokens:!1}),o=i.split(this.image_tag),s=o.length-1;if(t.length!==s)throw Error(`Number of images provided (${t.length}) does not match number of "${this.image_tag}" image tags (${s})`);let[c,l,u]=r.convert_tokens_to_ids([this.image_tag,this.image_start_tag,this.image_end_tag]),d=a(o[0]),f=Array(d.length).fill(!1);for(let e=1;e0){let e=await this.image_processor(t);return e.pixel_values.unsqueeze_(0),{...m,...e}}return m}},AI=class extends GN{static tokenizer_class=zN;static image_processor_class=yI;async _call(e=null,t=null,n={}){if(!e&&!t)throw Error(`Either text or images must be provided`);let r=e?this.tokenizer(e,n):{},i=t?await this.image_processor(t,n):{};return{...r,...i}}},jI=class extends GN{static tokenizer_class=zN;static image_processor_class=yI;async _call(e,t=null,n={}){let{image_rows:r,image_cols:i,image_sizes:a,...o}=await this.image_processor(e,{...n,return_row_col_info:!0});if(t){let e=this.config.image_token??``,{tile_size:n=512,downsample_factor:o=2,encoder_patch_size:s=16,use_thumbnail:c=!0}=this.image_processor.config,l=e=>Math.ceil(Math.floor(e/s)/o),u=l(n)**2,d=this.config.image_start_token??`<|image_start|>`,f=this.config.image_end_token??`<|image_end|>`,p=this.config.image_thumbnail??`<|img_thumbnail|>`;Array.isArray(t)||(t=[t]);let m=0;t=t.map(t=>{let n=t.split(e);return n[0]+n.slice(1).map(t=>{let n=m++,[o,s]=a[n],h=r[n],g=i[n],_=l(o)*l(s),v=d;if(h>1||g>1){let t=e.repeat(u);for(let e=0;e`+t;c&&(v+=p+e.repeat(_))}else v+=e.repeat(_);return v+f+t}).join(``)})}return{...o,...t?this.tokenizer(t,n):{}}}},MI=class extends GN{static tokenizer_class=zN;static image_processor_class=yI;static uses_processor_config=!0;async _call(e,t=null,n={}){let r=await this.image_processor(e,n);if(t){let[e,n]=r.pixel_values.dims.slice(-2),{image_token:i,patch_size:a,num_additional_image_tokens:o}=this.config,s=Math.floor(e/a)*Math.floor(n/a)+o;t=structuredClone(t),Array.isArray(t)||(t=[t]);for(let e=0;e0?i.reduce((e,t)=>e*t,1):0;c.push(n),s.push(a)}return[i(c),s]}char_decode(e){return this.char_tokenizer.batch_decode(e).map(e=>e.replaceAll(` `,``))}bpe_decode(e){return this.bpe_tokenizer.batch_decode(e)}wp_decode(e){return this.wp_tokenizer.batch_decode(e).map(e=>e.replaceAll(` `,``))}batch_decode([e,t,n]){let[r,i]=this._decode_helper(e,`char`),[a,o]=this._decode_helper(t,`bpe`),[s,c]=this._decode_helper(n,`wp`),l=[],u=[];for(let e=0;e`;function RI(e,t,n,r,i){return`${r.repeat(n*i)}${t}${e} +`}var zI=class extends GN{static tokenizer_class=zN;static image_processor_class=yI;static uses_processor_config=!1;async _call(e,t=null,n={}){t||=(dD.warn(`You are using PaliGemma without a text prefix. It will perform as a picture-captioning model.`),``),Array.isArray(e)||(e=[e]),Array.isArray(t)||(t=[t]);let r=this.tokenizer.bos_token,i=this.image_processor.config.image_seq_length,a;t.some(e=>e.includes(LI))?a=t.map(e=>{let t=e.replaceAll(LI,LI.repeat(i)),n=t.lastIndexOf(LI),a=n===-1?0:n+LI.length;return t.slice(0,a)+r+t.slice(a)+` +`}):(dD.warn("You are passing both `text` and `images` to `PaliGemmaProcessor`. The processor expects special image tokens in the text, as many tokens as there are images per each text. It is recommended to add `` tokens in the very beginning of your text. For this call, we will infer how many images each text has and add special tokens."),a=t.map(t=>RI(t,r,i,LI,e.length)));let o=this.tokenizer(a,n);return{...await this.image_processor(e,n),...o}}},BI=`<|image|>`,VI=/<\|image_\d+\|>/g,HI=class extends GN{static image_processor_class=yI;static tokenizer_class=zN;async _call(e,t=null,{padding:n=!0,truncation:r=!0,num_crops:i=null}={}){Array.isArray(e)||(e=[e]);let a,o;if(t){o=await this.image_processor(t,{num_crops:i});let{num_img_tokens:s}=o,c=e.map((e,t)=>e.split(VI).join(BI.repeat(s[t])));a=this.tokenizer(c,{padding:n,truncation:r});let l=this.tokenizer._tokenizer.token_to_id(BI);a.input_ids.map_(e=>e==l?-e:e)}else a=this.tokenizer(e);return{...a,...o}}},UI=class extends GN{static tokenizer_class=zN;static image_processor_class=yI;static uses_processor_config=!0;async _call(e,t=null,n={}){let r=await this.image_processor(e,n);if(t){let[e,n]=r.pixel_values.dims.slice(-2),{image_token:i,image_break_token:a,image_end_token:o,patch_size:s,spatial_merge_size:c}=this.config,l=s*c,u=Math.floor(e/l),d=Math.floor(n/l);t=structuredClone(t),Array.isArray(t)||(t=[t]);for(let e=0;e{for(;e.includes(`<|image_pad|>`);){let i=Number(r[n++].reduce((e,t)=>e*t,1n));e=e.replace(`<|image_pad|>`,`<|placeholder|>`.repeat(Math.floor(i/t)))}return e.replaceAll(`<|placeholder|>`,`<|image_pad|>`)})}return{...this.tokenizer(e),...r}}},KI=class extends GI{},qI=class extends KI{},JI=class extends GN{static image_processor_class=yI;async _call(...e){return await this.image_processor(...e)}post_process_masks(...e){return this.image_processor.post_process_masks(...e)}reshape_input_points(...e){return this.image_processor.reshape_input_points(...e)}},YI=class extends JI{},XI=class extends YI{},ZI=class extends GN{static tokenizer_class=zN;static feature_extractor_class=IP;async _call(e){return await this.feature_extractor(e)}},QI=class extends GN{static tokenizer_class=zN;static feature_extractor_class=IP;static uses_processor_config=!0;async _call(e,t=null,n={}){if(Array.isArray(e))throw Error(`Batched inputs are not supported yet.`);let r={};if(t){let i=t.length,{input_features:a}=await this.feature_extractor(t,{...n,max_length:i}),o=Math.round(i/this.config.encoder_ds_factor+1e-4),s=1+Math.ceil(o/this.config.stack_factor);r.audio_token_len=[s],r.audio_values=a;let c=this.config.audio_placeholder;if(!e.includes(c))throw Error(`The input text does not contain the image token ${c}.`);e=e.replaceAll(c,c.repeat(s))}return{...this.tokenizer(e,{add_special_tokens:!1,...n}),...r}}},$I=`[AUDIO]`,eL=`[BEGIN_AUDIO]`,tL=375;function nL(e,t){let n=[];for(let r=0;rnL(e,o)),c=s.map(e=>e.length),l=s.flat(),u=(await Promise.all(l.map(e=>this.feature_extractor(e,n)))).map(e=>e.input_features);r.audio_values=u.length>1?_M(u,0):u[0];let d=i[0];for(let e=0;e0){if(l>PA)throw Error(`The number of external data chunks (${l}) exceeds the maximum allowed value (${PA}).`);let t=xL(o,l);for(let n of t){let t=`${r.subfolder??``}/${n}`;c.push(new Promise(async(i,a)=>{let o=await oj(e,t,!0,r,s);i(o instanceof Uint8Array?{path:n,data:o}:n)}))}}else a.externalData!==void 0&&(c=a.externalData.map(async t=>{if(typeof t.data==`string`){let n=await oj(e,t.data,!0,r);return{...t,data:n}}return t}));return Promise.all(c)}async function wL(e,t,n,r=!1,i=void 0){let a=n.config?.[`transformers.js_config`]??{},o=Zj(n.device??a.device,t,{warn:e=>dD.info(e)}),s=Lj(o),c=a.device_config??{};c.hasOwnProperty(o)&&(a={...a,...c[o]});let l=rM(n.dtype??a.dtype,t,o,{configDtype:a.dtype,warn:e=>dD.info(e)});if(!nM.hasOwnProperty(l))throw Error(`Invalid dtype: ${l}. Should be one of: ${Object.keys($j).join(`, `)}`);if(o===`webgpu`&&!GE.IS_NODE_ENV&&l===$j.fp16&&!await Qj())throw Error(`The device (${o}) does not support fp16.`);let u=a.kv_cache_dtype,d=u?typeof u==`string`?u:u[l]??`float32`:void 0;if(d&&![`float32`,`float16`].includes(d))throw Error(`Invalid kv_cache_dtype: ${d}. Should be one of: float32, float16`);let f=nM[l],p={...n.session_options};p.executionProviders??=s;let m=a.free_dimension_overrides;m?p.freeDimensionOverrides??=m:o.startsWith(`webnn`)&&!p.freeDimensionOverrides&&dD.warn(`WebNN does not currently support dynamic shapes and requires 'free_dimension_overrides' to be set in config.json, preferably as a field within config["transformers.js_config"]["device_config"]["${o}"]. When 'free_dimension_overrides' is not set, you may experience significant performance degradation.`);let h=SL(e,t,n,f),g=await CL(e,t,f,n,n.use_external_data_format??a.use_external_data_format,p);if(g.length>0&&!GE.IS_NODE_ENV&&(p.externalData=g),r&&o===`webgpu`&&u!==!1){let e=gL(n.config,{prefix:`present`,session_name:i});if(Object.keys(e).length>0&&!Kj()){let t={};for(let n in e)t[n]=`gpu-buffer`;p.preferredOutputLocation=t}}return{buffer_or_path:await h,session_options:p,session_config:{dtype:l,kv_cache_dtype:d,device:o}}}async function TL(e,t,n,r=void 0){return Object.fromEntries(await Promise.all(Object.keys(t).map(async i=>{let a=r?.[i]??!1,{buffer_or_path:o,session_options:s,session_config:c}=await wL(e,t[i],n,a,i);return[i,await Vj(o,s,c)]})))}function EL(e){for(let t in e)Wj(e[t])?e[t]=new Z(e[t]):typeof e[t]==`object`&&EL(e[t]);return e}async function DL(e,t){let n=OL(e,t);try{return EL(await Uj(e,Object.fromEntries(Object.entries(n).map(([e,t])=>{let n=t.ort_tensor;return GE.IS_NODE_ENV&&typeof Float16Array<`u`&&n.cpuData instanceof Float16Array&&(n.cpuData=new Uint16Array(n.cpuData.buffer)),[e,n]}))))}catch(e){let t=Object.fromEntries(Object.entries(n).map(([e,t])=>{let n={type:t.type,dims:t.dims,location:t.location};return n.location!==`gpu-buffer`&&(n.data=t.data),[e,n]}));throw dD.error(`An error occurred during model execution: "${e}".`),dD.error(`Inputs given to model:`,t),e}}function OL(e,t){let n=Object.create(null),r=[];for(let i of e.inputNames){let e=t[i];if(!(e instanceof Z)){r.push(i);continue}n[i]=Kj()?e.clone():e}if(r.length>0)throw Error(`An error occurred during model execution: "Missing the following inputs: ${r.join(`, `)}.`);let i=Object.keys(t).length,a=e.inputNames.length;if(i>a){let n=Object.keys(t).filter(t=>!e.inputNames.includes(t));dD.warn(`WARNING: Too many inputs were provided (${i} > ${a}). The following inputs will be ignored: "${n.join(`, `)}".`)}return n}var kL=class{},AL=class extends kL{constructor({logits:e,...t}){super(),this.logits=e;let n=Object.values(t);n.length>0&&(this.attentions=n)}},jL=class extends kL{constructor({logits:e}){super(),this.logits=e}},ML=class extends kL{constructor({logits:e}){super(),this.logits=e}},NL=class extends kL{constructor({start_logits:e,end_logits:t}){super(),this.start_logits=e,this.end_logits=t}},PL=class extends kL{constructor({logits:e}){super(),this.logits=e}},FL=class extends kL{constructor({alphas:e}){super(),this.alphas=e}},IL=class extends CA{_call(e,t){throw Error("`_call` should be implemented in a subclass")}},LL=class extends CA{_call(e,t){throw Error("`_call` should be implemented in a subclass")}},RL=class extends CA{constructor(){super(),this.processors=[]}push(e){this.processors.push(e)}extend(e){this.processors.push(...e)}_call(e,t){let n=t;for(let t of this.processors)n=t(e,n);return n}[Symbol.iterator](){return this.processors.values()}},zL=class extends IL{constructor(e){super(),this.bos_token_id=e}_call(e,t){for(let n=0;n=1&&i[i.length-1]>=this.timestamp_begin,o=i.length<2||i[i.length-2]>=this.timestamp_begin;if(a&&(o?r.subarray(this.timestamp_begin).fill(-1/0):r.subarray(0,this.eos_token_id).fill(-1/0)),e[n].length===this.begin_index&&this.max_initial_timestamp_index!==null){let e=this.timestamp_begin+this.max_initial_timestamp_index;r.subarray(e+1).fill(-1/0)}let s=fj(r);Math.log(s.subarray(this.timestamp_begin).map(Math.exp).reduce((e,t)=>e+t))>mj(s.subarray(0,this.timestamp_begin))[0]&&r.subarray(0,this.timestamp_begin).fill(-1/0)}return t}},UL=class extends IL{constructor(e){super(),this.no_repeat_ngram_size=e}getNgrams(e){let t=e.length,n=[];for(let r=0;r1 to use the classifier free guidance processor, got guidance scale ${e}.`);this.guidance_scale=e}_call(e,t){if(t.dims[0]!==2*e.length)throw Error(`Logits should have twice the batch size of the input ids, the first half of batches corresponding to the conditional inputs, and the second half of batches corresponding to the unconditional inputs. Got batch size ${t.dims[0]} for the logits and ${e.length} for the input ids.`);let n=e.length,r=t.slice([0,n],null),i=t.slice([n,t.dims[0]],null);for(let e=0;ee.length>=this.max_length)}},eR=class extends ZL{constructor(e){super(),Array.isArray(e)||(e=[e]),this.eos_token_id=e}_call(e,t){return e.map(e=>{let t=e.at(-1);return this.eos_token_id.some(e=>t==e)})}},tR=class extends CA{constructor(e){super(),this.generation_config=e}async _call(e){return this.sample(e)}async sample(e){throw Error(`sample should be implemented in subclasses.`)}getLogits(e,t){let n=e.dims.at(-1),r=e.data;if(t===-1)r=r.slice(-n);else{let e=t*n;r=r.slice(e,e+n)}return r}randomSelect(e){return AA(e)}static getSampler(e){if(e.do_sample)return new rR(e);if(e.num_beams>1)return new iR(e);if(e.num_return_sequences>1)throw Error(`num_return_sequences has to be 1 when doing greedy search, but is ${e.num_return_sequences}.`);return new nR(e)}},nR=class extends tR{async sample(e){let t=mj(e.data)[1];return[[BigInt(t),0]]}},rR=class extends tR{async sample(e){let t=e.dims.at(-1);this.generation_config.top_k>0&&(t=Math.min(this.generation_config.top_k,t));let[n,r]=await uM(e,t),i=dj(n.data);return Array.from({length:this.generation_config.num_beams},()=>{let e=this.randomSelect(i);return[r.data[e],Math.log(i[e])]})}},iR=class extends tR{async sample(e){let t=e.dims.at(-1);this.generation_config.top_k>0&&(t=Math.min(this.generation_config.top_k,t));let[n,r]=await uM(e,t),i=dj(n.data);return Array.from({length:this.generation_config.num_beams},(e,t)=>[r.data[t],Math.log(i[t])])}},aR=class{constructor(e){if(e)for(let t in e){if(t in this)throw TypeError(`Key "${t}" conflicts with an existing property on DynamicCache`);let n=e[t];if(!(n instanceof Z))throw TypeError(`Expected a Tensor for key "${t}", got ${typeof n}`);this[t]=n}}get_seq_length(){let e=this;for(let t in e)if(t.startsWith(`past_key_values.`))return e[t].dims.at(-2);throw Error(`Unable to determine sequence length from the cache.`)}async dispose(){let e=[];for(let t of Object.values(this))t.location===`gpu-buffer`&&e.push(t.dispose());await Promise.all(e)}},oR=null;function sR(e){oR=e}function cR(e){if(e instanceof Z)return e;if(e.length===0)throw Error(`items must be non-empty`);if(Array.isArray(e[0])){if(e.some(t=>t.length!==e[0].length))throw Error(`Unable to create tensor, you should probably activate truncation and/or padding with 'padding=True' and/or 'truncation=True' to have batched tensors with the same length.`);return new Z(`int64`,BigInt64Array.from(e.flat().map(e=>BigInt(e))),[e.length,e[0].length])}else return new Z(`int64`,BigInt64Array.from(e.map(e=>BigInt(e))),[1,e.length])}function lR(e){return new Z(`bool`,[e],[1])}var Q={EncoderOnly:0,EncoderDecoder:1,Seq2Seq:2,Vision2Seq:3,DecoderOnly:4,DecoderOnlyWithoutHead:5,MaskGeneration:6,ImageTextToText:7,Musicgen:8,MultiModality:9,Phi3V:10,AudioTextToText:11,AutoEncoder:12,ImageAudioTextToText:13,Supertonic:14,Chatterbox:15,MultimodalLanguageModelOnly:16,VoxtralRealtime:17},uR={[Q.DecoderOnly]:{can_generate:!0,forward:_R,prepare_inputs:CR,sessions:(e,t)=>({model:t.model_file_name??`model`}),cache_sessions:{model:!0},optional_configs:{generation_config:`generation_config.json`}},[Q.DecoderOnlyWithoutHead]:{can_generate:!1,forward:_R,prepare_inputs:CR,sessions:(e,t)=>({model:t.model_file_name??`model`})},[Q.Seq2Seq]:{can_generate:!0,forward:mR,prepare_inputs:wR,sessions:()=>({model:`encoder_model`,decoder_model_merged:`decoder_model_merged`}),cache_sessions:{decoder_model_merged:!0},optional_configs:{generation_config:`generation_config.json`}},[Q.Vision2Seq]:{can_generate:!0,forward:mR,prepare_inputs:wR,sessions:()=>({model:`encoder_model`,decoder_model_merged:`decoder_model_merged`}),cache_sessions:{decoder_model_merged:!0},optional_configs:{generation_config:`generation_config.json`}},[Q.Musicgen]:{can_generate:!0,forward:mR,sessions:()=>({model:`text_encoder`,decoder_model_merged:`decoder_model_merged`,encodec_decode:`encodec_decode`}),cache_sessions:{decoder_model_merged:!0},optional_configs:{generation_config:`generation_config.json`}},[Q.EncoderDecoder]:{can_generate:!1,forward:mR,sessions:()=>({model:`encoder_model`,decoder_model_merged:`decoder_model_merged`}),cache_sessions:{decoder_model_merged:!0}},[Q.MaskGeneration]:{sessions:()=>({model:`vision_encoder`,prompt_encoder_mask_decoder:`prompt_encoder_mask_decoder`})},[Q.ImageTextToText]:{can_generate:!0,forward:bR,prepare_inputs:TR,sessions:e=>{let t={embed_tokens:`embed_tokens`,vision_encoder:`vision_encoder`,decoder_model_merged:`decoder_model_merged`};return e.is_encoder_decoder&&(t.model=`encoder_model`),t},cache_sessions:{decoder_model_merged:!0},optional_configs:{generation_config:`generation_config.json`}},[Q.AudioTextToText]:{can_generate:!0,forward:yR,prepare_inputs:TR,sessions:()=>({embed_tokens:`embed_tokens`,audio_encoder:`audio_encoder`,decoder_model_merged:`decoder_model_merged`}),cache_sessions:{decoder_model_merged:!0},optional_configs:{generation_config:`generation_config.json`}},[Q.ImageAudioTextToText]:{can_generate:!0,prepare_inputs:TR,sessions:()=>({embed_tokens:`embed_tokens`,audio_encoder:`audio_encoder`,vision_encoder:`vision_encoder`,decoder_model_merged:`decoder_model_merged`}),optional_configs:{generation_config:`generation_config.json`}},[Q.Phi3V]:{can_generate:!0,prepare_inputs:TR,sessions:()=>({prepare_inputs_embeds:`prepare_inputs_embeds`,model:`model`,vision_encoder:`vision_encoder`}),cache_sessions:{model:!0},optional_configs:{generation_config:`generation_config.json`}},[Q.MultiModality]:{can_generate:!0,sessions:()=>({prepare_inputs_embeds:`prepare_inputs_embeds`,model:`language_model`,lm_head:`lm_head`,gen_head:`gen_head`,gen_img_embeds:`gen_img_embeds`,image_decode:`image_decode`}),cache_sessions:{model:!0},optional_configs:{generation_config:`generation_config.json`}},[Q.AutoEncoder]:{can_generate:!1,forward:gR,sessions:()=>({encoder_model:`encoder_model`,decoder_model:`decoder_model`})},[Q.Supertonic]:{sessions:()=>({text_encoder:`text_encoder`,latent_denoiser:`latent_denoiser`,voice_decoder:`voice_decoder`})},[Q.Chatterbox]:{can_generate:!0,forward:hR,sessions:()=>({embed_tokens:`embed_tokens`,speech_encoder:`speech_encoder`,model:`language_model`,conditional_decoder:`conditional_decoder`}),cache_sessions:{model:!0},optional_configs:{generation_config:`generation_config.json`}},[Q.MultimodalLanguageModelOnly]:{can_generate:!0,forward:bR,prepare_inputs:TR,sessions:()=>({embed_tokens:`embed_tokens`,decoder_model_merged:`decoder_model_merged`}),cache_sessions:{decoder_model_merged:!0},optional_configs:{generation_config:`generation_config.json`}},[Q.VoxtralRealtime]:{can_generate:!0,prepare_inputs:CR,sessions:()=>({embed_tokens:`embed_tokens`,audio_encoder:`audio_encoder`,decoder_model_merged:`decoder_model_merged`}),cache_sessions:{decoder_model_merged:!0,audio_encoder:!0},optional_configs:{generation_config:`generation_config.json`}},default:{can_generate:!1,forward:hR,sessions:(e,t)=>({model:t.model_file_name??`model`})}},dR=new Map,fR=new Map,pR=new Map,$=class extends CA{main_input_name=`input_ids`;forward_params=[`input_ids`,`attention_mask`];_return_dict_in_generate_keys=null;constructor(e,t,n){super(),this.config=e,this.sessions=t,this.configs=n;let r=pR.get(this.constructor),i=uR[dR.get(r)]??uR.default;this.can_generate=i.can_generate,this._forward=i.forward,this._prepare_inputs_for_generation=i.prepare_inputs,this.can_generate&&this.forward_params.push(`past_key_values`),this.custom_config=this.config[`transformers.js_config`]??{}}async dispose(){let e=[];for(let t of Object.values(this.sessions))e.push(t.release?.());return await Promise.all(e)}static async from_pretrained(e,{progress_callback:t=null,config:n=null,cache_dir:r=null,local_files_only:i=!1,revision:a=`main`,model_file_name:o=null,subfolder:s=`onnx`,device:c=null,dtype:l=null,use_external_data_format:u=null,session_options:d={}}={}){let f={progress_callback:t,config:n,cache_dir:r,local_files_only:i,revision:a,model_file_name:o,subfolder:s,device:c,dtype:l,use_external_data_format:u,session_options:d},p=pR.get(this),m=dR.get(p);n=f.config=await yL.from_pretrained(e,f);let h=uR[m]??uR.default;if(m===void 0){let e=p??n?.model_type;e!==`custom`&&dD.warn(`Model type for '${e}' not found, assuming encoder-only architecture. Please report this at ${BN}.`)}let g=[TL(e,h.sessions(n,f),f,h.cache_sessions)];h.optional_configs&&g.push(kR(e,h.optional_configs,f));let _=await Promise.all(g);return new this(n,..._)}async _call(e){return await this.forward(e)}async forward(e){return await this._forward(this,e)}get generation_config(){return this.configs?.generation_config??null}_get_logits_processor(e,t,n=null){let r=new RL;if(e.repetition_penalty!==null&&e.repetition_penalty!==1&&r.push(new WL(e.repetition_penalty)),e.no_repeat_ngram_size!==null&&e.no_repeat_ngram_size>0&&r.push(new UL(e.no_repeat_ngram_size)),e.bad_words_ids!==null&&r.push(new qL(e.bad_words_ids,e.eos_token_id)),e.min_length!==null&&e.eos_token_id!==null&&e.min_length>0&&r.push(new GL(e.min_length,e.eos_token_id)),e.min_new_tokens!==null&&e.eos_token_id!==null&&e.min_new_tokens>0&&r.push(new KL(t,e.min_new_tokens,e.eos_token_id)),e.forced_bos_token_id!==null&&r.push(new zL(e.forced_bos_token_id)),e.forced_eos_token_id!==null&&r.push(new BL(e.max_length,e.forced_eos_token_id)),e.begin_suppress_tokens!==null){let n=t>1||e.forced_bos_token_id===null?t:t+1;r.push(new VL(e.begin_suppress_tokens,n))}return e.guidance_scale!==null&&e.guidance_scale>1&&r.push(new JL(e.guidance_scale)),e.temperature===0&&e.do_sample&&(dD.warn("`do_sample` changed to false because `temperature: 0` implies greedy sampling (always selecting the most likely token), which is incompatible with `do_sample: true`."),e.do_sample=!1),e.do_sample&&e.temperature!==null&&e.temperature!==1&&r.push(new YL(e.temperature)),n!==null&&r.extend(n),r}_prepare_generation_config(e,t,n=XL){let r={...this.config};for(let e of[`decoder`,`generator`,`text_config`])e in r&&Object.assign(r,r[e]);let i=new n(r);return Object.assign(i,this.generation_config??{}),e&&Object.assign(i,e),t&&Object.assign(i,lD(t,Object.getOwnPropertyNames(i))),i}_get_stopping_criteria(e,t=null){let n=new QL;return e.max_length!==null&&n.push(new $L(e.max_length,this.config.max_position_embeddings??null)),e.eos_token_id!==null&&n.push(new eR(e.eos_token_id)),t&&n.extend(t),n}_validate_model_class(){if(!this.can_generate){let e=[oR.MODEL_FOR_CAUSAL_LM_MAPPING_NAMES,oR.MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES,oR.MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES,oR.MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES].filter(Boolean),t=pR.get(this.constructor),n=new Set,r=this.config.model_type;for(let t of e){let e=t?.get(r);e&&n.add(e)}let i=`The current model class (${t}) is not compatible with \`.generate()\`, as it doesn't have a language model head.`;throw n.size>0&&(i+=` Please use the following class instead: ${[...n].join(`, `)}`),Error(i)}}prepare_inputs_for_generation(...e){if(!this._prepare_inputs_for_generation)throw Error(`prepare_inputs_for_generation is not implemented for this model.`);return this._prepare_inputs_for_generation(this,...e)}_update_model_kwargs_for_generation({generated_input_ids:e,outputs:t,model_inputs:n,is_encoder_decoder:r}){return n.past_key_values=this.getPastKeyValues(t,n.past_key_values),n.input_ids=new Z(`int64`,e.flat(),[e.length,1]),r?`decoder_attention_mask`in n:n.attention_mask=_M([n.attention_mask,EM([n.attention_mask.dims[0],1])],1),n.position_ids=null,n}_prepare_model_inputs({inputs:e,bos_token_id:t,model_kwargs:n}){let r=lD(n,this.forward_params),i=this.main_input_name;if(i in r){if(e)throw Error("`inputs`: {inputs}` were passed alongside {input_name} which is not allowed. Make sure to either pass {inputs} or {input_name}=...")}else r[i]=e;return{inputs_tensor:r[i],model_inputs:r,model_input_name:i}}async _prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:e,model_inputs:t,model_input_name:n,generation_config:r}){if(this.sessions.model.inputNames.includes(`inputs_embeds`)&&!t.inputs_embeds&&`_prepare_inputs_embeds`in this){let{input_ids:e,pixel_values:n,attention_mask:r,...i}=t,a=await this._prepare_inputs_embeds(t);t={...i,...lD(a,[`inputs_embeds`,`attention_mask`])}}let{last_hidden_state:i}=await hR(this,t);if(r.guidance_scale!==null&&r.guidance_scale>1)i=_M([i,TM(i,0)],0),`attention_mask`in t&&(t.attention_mask=_M([t.attention_mask,kM(t.attention_mask)],0));else if(t.decoder_input_ids){let e=cR(t.decoder_input_ids).dims[0];if(e!==i.dims[0]){if(i.dims[0]!==1)throw Error(`The encoder outputs have a different batch size (${i.dims[0]}) than the decoder inputs (${e}).`);i=_M(Array.from({length:e},()=>i),0)}}return t.encoder_outputs=i,t}_prepare_decoder_input_ids_for_generation({batch_size:e,model_input_name:t,model_kwargs:n,decoder_start_token_id:r,bos_token_id:i,generation_config:a}){let{decoder_input_ids:o,...s}=n;if(!(o instanceof Z)){if(o)Array.isArray(o[0])||(o=Array.from({length:e},()=>o));else if(r??=i,this.config.model_type===`musicgen`)o=Array.from({length:e*this.config.decoder.num_codebooks},()=>[r]);else if(Array.isArray(r)){if(r.length!==e)throw Error(`\`decoder_start_token_id\` expcted to have length ${e} but got ${r.length}`);o=r}else o=Array.from({length:e},()=>[r]);o=cR(o)}return n.decoder_attention_mask=DM(o),{input_ids:o,model_inputs:s}}async generate({inputs:e=null,generation_config:t=null,logits_processor:n=null,stopping_criteria:r=null,streamer:i=null,...a}){this._validate_model_class(),t=this._prepare_generation_config(t,a);let{inputs_tensor:o,model_inputs:s,model_input_name:c}=this._prepare_model_inputs({inputs:e,model_kwargs:a}),l=this.config.is_encoder_decoder;l&&(`encoder_outputs`in s||(s=await this._prepare_encoder_decoder_kwargs_for_generation({inputs_tensor:o,model_inputs:s,model_input_name:c,generation_config:t})));let u;l?{input_ids:u,model_inputs:s}=this._prepare_decoder_input_ids_for_generation({batch_size:s[c].dims.at(0),model_input_name:c,model_kwargs:s,decoder_start_token_id:t.decoder_start_token_id,bos_token_id:t.bos_token_id,generation_config:t}):u=s[c];let d=u.dims.at(-1);t.max_new_tokens!==null&&(t.max_length=d+t.max_new_tokens);let f=this._get_logits_processor(t,d,n),p=this._get_stopping_criteria(t,r),m=s[c].dims.at(0),h=tR.getSampler(t),g=Array(m).fill(0),_=u.tolist();i&&i.put(_);let v,y={},b={};for(;;){if(s=this.prepare_inputs_for_generation(_,s,t),v=await this.forward(s),t.return_dict_in_generate)if(t.output_attentions){let e=this.getAttentions(v);for(let t in e)t in y||(y[t]=[]),y[t].push(e[t])}else this._return_dict_in_generate_keys&&Object.assign(b,lD(v,this._return_dict_in_generate_keys));let e=f(_,v.logits.slice(null,-1,null).to(`float32`)),n=[];for(let t=0;te))break;s=this._update_model_kwargs_for_generation({generated_input_ids:n,outputs:v,model_inputs:s,is_encoder_decoder:l})}i&&i.end();let x=this.getPastKeyValues(v,s.past_key_values,!0),S=new Z(`int64`,_.flat(),[_.length,_[0].length]);if(t.return_dict_in_generate)return{sequences:S,past_key_values:x,...y,...b};for(let e of Object.values(v))e.location===`gpu-buffer`&&e.dispose();return S}getPastKeyValues(e,t,n=!1){let r=Object.create(null);for(let i in e)if(i.startsWith(`present`)){let a=i.replace(`present_ssm`,`past_ssm`).replace(`present_conv`,`past_conv`).replace(`present_recurrent`,`past_recurrent`).replace(`present`,`past_key_values`),o=i.includes(`encoder`);if(o&&t?r[a]=t[a]:r[a]=e[i],t&&(!o||n)){let e=t[a];e.location===`gpu-buffer`&&e.dispose()}}return new aR(r)}getAttentions(e){let t={};for(let n of[`cross_attentions`,`encoder_attentions`,`decoder_attentions`])for(let r in e)r.startsWith(n)&&(n in t||(t[n]=[]),t[n].push(e[r]));return t}addPastKeyValues(e,t){if(t)Object.assign(e,t);else{let t=this.sessions.decoder_model_merged??this.sessions.model,n=(e[this.main_input_name]??e.attention_mask)?.dims?.[0]??1,r=t?.config?.kv_cache_dtype??`float32`,i=r===`float16`?iM.float16:iM.float32,a=gL(this.config,{batch_size:n});for(let t in a)e[t]=new Z(r,new i(a[t].reduce((e,t)=>e*t,1)),a[t])}}async _encode_input(e,t,n){if(!Object.hasOwn(this.sessions,e))throw Error(`Model does not have a ${e} session.`);let r=this.sessions[e];return(await DL(r,lD(t,r.inputNames)))[n]}async encode_image(e){return this._encode_input(`vision_encoder`,e,`image_features`)}async encode_text(e){return this._encode_input(`embed_tokens`,e,`inputs_embeds`)}async encode_audio(e){return this._encode_input(`audio_encoder`,e,`audio_features`)}};async function mR(e,t){let{encoder_outputs:n,input_ids:r,decoder_input_ids:i,...a}=t;return n||=(await hR(e,lD(t,e.sessions.model.inputNames))).last_hidden_state,a.input_ids=i,a.encoder_hidden_states=n,e.sessions.decoder_model_merged.inputNames.includes(`encoder_attention_mask`)&&(a.encoder_attention_mask=t.attention_mask),await _R(e,a,!0)}async function hR(e,t){let n=e.sessions.model,r=lD(t,n.inputNames);if(n.inputNames.includes(`inputs_embeds`)&&!r.inputs_embeds){if(!t.input_ids)throw Error("Both `input_ids` and `inputs_embeds` are missing in the model inputs.");r.inputs_embeds=await e.encode_text({input_ids:t.input_ids})}if(n.inputNames.includes(`token_type_ids`)&&!r.token_type_ids){if(!r.input_ids)throw Error("Both `input_ids` and `token_type_ids` are missing in the model inputs.");r.token_type_ids=kM(r.input_ids)}if(n.inputNames.includes(`pixel_mask`)&&!r.pixel_mask){if(!r.pixel_values)throw Error("Both `pixel_values` and `pixel_mask` are missing in the model inputs.");let e=r.pixel_values.dims;r.pixel_mask=EM([e[0],e[2],e[3]])}return await DL(n,r)}async function gR(e,t){let n=await e.encode(t);return await e.decode(n)}async function _R(e,t,n=!1){let r=e.sessions[n?`decoder_model_merged`:`model`],{past_key_values:i,...a}=t;return r.inputNames.includes(`use_cache_branch`)&&(a.use_cache_branch=lR(!!i)),r.inputNames.includes(`position_ids`)&&a.attention_mask&&!a.position_ids&&(a.position_ids=SR(a,i,[`paligemma`,`gemma3_text`,`gemma3`].includes(e.config.model_type)?1:0)),r.inputNames.includes(`num_logits_to_keep`)&&!a.num_logits_to_keep&&(a.num_logits_to_keep=new Z(`int64`,[0n],[])),e.addPastKeyValues(a,i),await DL(r,lD(a,r.inputNames))}async function vR(e,{encode_function:t,merge_function:n,modality_input_names:r,modality_output_name:i,input_ids:a=null,attention_mask:o=null,position_ids:s=null,inputs_embeds:c=null,past_key_values:l=null,generation_config:u=null,logits_processor:d=null,...f}){if(!c){c=await e.encode_text({input_ids:a,...f});let s=lD(f,r);if(Object.keys(s).length>0){if(a.dims[1]!==1){let e=await t({...s,...f});({inputs_embeds:c,attention_mask:o}=n({[i]:e,inputs_embeds:c,input_ids:a,attention_mask:o}))}else if(l&&a.dims[1]===1){let e=a.dims[1],t=l.get_seq_length();o=_M([EM([a.dims[0],t]),o.slice(null,[o.dims[1]-e,o.dims[1]])],1)}}}if(!s&&[`qwen2_vl`,`qwen2_vl_text`,`qwen2_5_vl`,`qwen2_5_vl_text`,`qwen3_vl`,`qwen3_vl_text`,`qwen3_vl_moe`,`qwen3_vl_moe_text`,`qwen3_5`,`qwen3_5_text`,`qwen3_5_moe`,`qwen3_5_moe_text`].includes(e.config.model_type)){let{image_grid_thw:t,video_grid_thw:n}=f;[s]=e.get_rope_index(a,t,n,o)}return await _R(e,{inputs_embeds:c,past_key_values:l,attention_mask:o,position_ids:s,generation_config:u,logits_processor:d},!0)}async function yR(e,t){return await vR(e,{...t,modality_input_names:[`audio_values`,`input_features`],modality_output_name:`audio_features`,encode_function:e.encode_audio.bind(e),merge_function:e._merge_input_ids_with_audio_features.bind(e)})}async function bR(e,t){return await vR(e,{...t,modality_input_names:[`pixel_values`],modality_output_name:`image_features`,encode_function:e.encode_image.bind(e),merge_function:e._merge_input_ids_with_image_features.bind(e)})}function xR(e,t=0){let[n,r]=e.dims,i=e.data,a=new BigInt64Array(i.length);for(let e=0;ee.dims[1]||i[e.at(-1)])),{...n,decoder_input_ids:cR(t)}}function TR(e,...t){return e.config.is_encoder_decoder?wR(e,...t):CR(e,...t)}function ER({modality_token_id:e,inputs_embeds:t,modality_features:n,input_ids:r,attention_mask:i}){let a=r.tolist().map(t=>t.reduce((t,n,r)=>(n==e&&t.push(r),t),[])),o=a.reduce((e,t)=>e+t.length,0),s=n.dims[0];if(o!==s)throw Error(`Number of tokens and features do not match: tokens: ${o}, features ${s}`);let c=0;for(let e=0;e[r,await cj(e,t[r],!1,n)])))}var AR={};CE(AR,{ASTForAudioClassification:()=>qR,ASTModel:()=>KR,ASTPreTrainedModel:()=>GR,AfmoeForCausalLM:()=>VR,AfmoeModel:()=>BR,AfmoePreTrainedModel:()=>zR,AlbertForMaskedLM:()=>FR,AlbertForQuestionAnswering:()=>PR,AlbertForSequenceClassification:()=>NR,AlbertModel:()=>MR,AlbertPreTrainedModel:()=>jR,ApertusForCausalLM:()=>RR,ApertusModel:()=>LR,ApertusPreTrainedModel:()=>IR,ArceeForCausalLM:()=>WR,ArceeModel:()=>UR,ArceePreTrainedModel:()=>HR,BartForConditionalGeneration:()=>XR,BartForSequenceClassification:()=>ZR,BartModel:()=>YR,BartPretrainedModel:()=>JR,BeitForImageClassification:()=>ez,BeitModel:()=>$R,BeitPreTrainedModel:()=>QR,BertForMaskedLM:()=>rz,BertForQuestionAnswering:()=>oz,BertForSequenceClassification:()=>iz,BertForTokenClassification:()=>az,BertModel:()=>nz,BertPreTrainedModel:()=>tz,BlenderbotForConditionalGeneration:()=>lz,BlenderbotModel:()=>cz,BlenderbotPreTrainedModel:()=>sz,BlenderbotSmallForConditionalGeneration:()=>fz,BlenderbotSmallModel:()=>dz,BlenderbotSmallPreTrainedModel:()=>uz,BloomForCausalLM:()=>hz,BloomModel:()=>mz,BloomPreTrainedModel:()=>pz,CLIPModel:()=>Nz,CLIPPreTrainedModel:()=>Mz,CLIPSegForImageSegmentation:()=>Bz,CLIPSegModel:()=>zz,CLIPSegPreTrainedModel:()=>Rz,CLIPTextModel:()=>Pz,CLIPTextModelWithProjection:()=>Fz,CLIPVisionModel:()=>Iz,CLIPVisionModelWithProjection:()=>Lz,CamembertForMaskedLM:()=>vz,CamembertForQuestionAnswering:()=>xz,CamembertForSequenceClassification:()=>yz,CamembertForTokenClassification:()=>bz,CamembertModel:()=>_z,CamembertPreTrainedModel:()=>gz,ChatterboxModel:()=>Tz,ChatterboxPreTrainedModel:()=>wz,ChineseCLIPModel:()=>Dz,ChineseCLIPPreTrainedModel:()=>Ez,ClapAudioModelWithProjection:()=>jz,ClapModel:()=>kz,ClapPreTrainedModel:()=>Oz,ClapTextModelWithProjection:()=>Az,CodeGenForCausalLM:()=>Uz,CodeGenModel:()=>Hz,CodeGenPreTrainedModel:()=>Vz,Cohere2ForCausalLM:()=>Yz,Cohere2Model:()=>Jz,Cohere2PreTrainedModel:()=>qz,CohereForCausalLM:()=>Kz,CohereModel:()=>Gz,CoherePreTrainedModel:()=>Wz,ConvBertForMaskedLM:()=>Qz,ConvBertForQuestionAnswering:()=>tB,ConvBertForSequenceClassification:()=>$z,ConvBertForTokenClassification:()=>eB,ConvBertModel:()=>Zz,ConvBertPreTrainedModel:()=>Xz,ConvNextForImageClassification:()=>iB,ConvNextModel:()=>rB,ConvNextPreTrainedModel:()=>nB,ConvNextV2ForImageClassification:()=>sB,ConvNextV2Model:()=>oB,ConvNextV2PreTrainedModel:()=>aB,DFineForObjectDetection:()=>mB,DFineModel:()=>pB,DFinePreTrainedModel:()=>fB,DINOv3ConvNextModel:()=>tV,DINOv3ConvNextPreTrainedModel:()=>eV,DINOv3ViTModel:()=>rV,DINOv3ViTPreTrainedModel:()=>nV,DPTForDepthEstimation:()=>mV,DPTModel:()=>pV,DPTPreTrainedModel:()=>fV,DacDecoderModel:()=>bB,DacDecoderOutput:()=>gB,DacEncoderModel:()=>yB,DacEncoderOutput:()=>hB,DacModel:()=>vB,DacPreTrainedModel:()=>_B,DebertaForMaskedLM:()=>CB,DebertaForQuestionAnswering:()=>EB,DebertaForSequenceClassification:()=>wB,DebertaForTokenClassification:()=>TB,DebertaModel:()=>SB,DebertaPreTrainedModel:()=>xB,DebertaV2ForMaskedLM:()=>kB,DebertaV2ForQuestionAnswering:()=>MB,DebertaV2ForSequenceClassification:()=>AB,DebertaV2ForTokenClassification:()=>jB,DebertaV2Model:()=>OB,DebertaV2PreTrainedModel:()=>DB,DecisionTransformerModel:()=>PB,DecisionTransformerPreTrainedModel:()=>NB,DeiTForImageClassification:()=>LB,DeiTModel:()=>IB,DeiTPreTrainedModel:()=>FB,DepthAnythingForDepthEstimation:()=>zB,DepthAnythingPreTrainedModel:()=>RB,DepthProForDepthEstimation:()=>VB,DepthProPreTrainedModel:()=>BB,DetrForObjectDetection:()=>WB,DetrForSegmentation:()=>GB,DetrModel:()=>UB,DetrObjectDetectionOutput:()=>KB,DetrPreTrainedModel:()=>HB,DetrSegmentationOutput:()=>qB,Dinov2ForImageClassification:()=>XB,Dinov2Model:()=>YB,Dinov2PreTrainedModel:()=>JB,Dinov2WithRegistersForImageClassification:()=>$B,Dinov2WithRegistersModel:()=>QB,Dinov2WithRegistersPreTrainedModel:()=>ZB,DistilBertForMaskedLM:()=>lV,DistilBertForQuestionAnswering:()=>cV,DistilBertForSequenceClassification:()=>oV,DistilBertForTokenClassification:()=>sV,DistilBertModel:()=>aV,DistilBertPreTrainedModel:()=>iV,DonutSwinModel:()=>dV,DonutSwinPreTrainedModel:()=>uV,EdgeTamModel:()=>Cq,EfficientNetForImageClassification:()=>_V,EfficientNetModel:()=>gV,EfficientNetPreTrainedModel:()=>hV,ElectraForMaskedLM:()=>bV,ElectraForQuestionAnswering:()=>CV,ElectraForSequenceClassification:()=>xV,ElectraForTokenClassification:()=>SV,ElectraModel:()=>yV,ElectraPreTrainedModel:()=>vV,Ernie4_5ForCausalLM:()=>EV,Ernie4_5Model:()=>TV,Ernie4_5PretrainedModel:()=>wV,EsmForMaskedLM:()=>kV,EsmForSequenceClassification:()=>AV,EsmForTokenClassification:()=>jV,EsmModel:()=>OV,EsmPreTrainedModel:()=>DV,ExaoneForCausalLM:()=>PV,ExaoneModel:()=>NV,ExaonePreTrainedModel:()=>MV,FalconForCausalLM:()=>LV,FalconH1ForCausalLM:()=>BV,FalconH1Model:()=>zV,FalconH1PreTrainedModel:()=>RV,FalconModel:()=>IV,FalconPreTrainedModel:()=>FV,FastViTForImageClassification:()=>UV,FastViTModel:()=>HV,FastViTPreTrainedModel:()=>VV,Florence2ForConditionalGeneration:()=>GV,Florence2PreTrainedModel:()=>WV,GLPNForDepthEstimation:()=>lH,GLPNModel:()=>cH,GLPNPreTrainedModel:()=>sH,GPT2LMHeadModel:()=>wH,GPT2Model:()=>CH,GPT2PreTrainedModel:()=>SH,GPTBigCodeForCausalLM:()=>fH,GPTBigCodeModel:()=>dH,GPTBigCodePreTrainedModel:()=>uH,GPTJForCausalLM:()=>DH,GPTJModel:()=>EH,GPTJPreTrainedModel:()=>TH,GPTNeoForCausalLM:()=>hH,GPTNeoModel:()=>mH,GPTNeoPreTrainedModel:()=>pH,GPTNeoXForCausalLM:()=>vH,GPTNeoXModel:()=>_H,GPTNeoXPreTrainedModel:()=>gH,Gemma2ForCausalLM:()=>ZV,Gemma2Model:()=>XV,Gemma2PreTrainedModel:()=>YV,Gemma3ForCausalLM:()=>eH,Gemma3Model:()=>$V,Gemma3PreTrainedModel:()=>QV,Gemma3nForCausalLM:()=>rH,Gemma3nForConditionalGeneration:()=>nH,Gemma3nPreTrainedModel:()=>tH,GemmaForCausalLM:()=>JV,GemmaModel:()=>qV,GemmaPreTrainedModel:()=>KV,GlmForCausalLM:()=>oH,GlmModel:()=>aH,GlmPreTrainedModel:()=>iH,GptOssForCausalLM:()=>xH,GptOssModel:()=>bH,GptOssPreTrainedModel:()=>yH,GraniteForCausalLM:()=>AH,GraniteModel:()=>kH,GraniteMoeHybridForCausalLM:()=>NH,GraniteMoeHybridModel:()=>MH,GraniteMoeHybridPreTrainedModel:()=>jH,GranitePreTrainedModel:()=>OH,GraniteSpeechForConditionalGeneration:()=>IH,GroundingDinoForObjectDetection:()=>RH,GroundingDinoPreTrainedModel:()=>LH,GroupViTModel:()=>BH,GroupViTPreTrainedModel:()=>zH,HeliumForCausalLM:()=>UH,HeliumModel:()=>HH,HeliumPreTrainedModel:()=>VH,HieraForImageClassification:()=>KH,HieraModel:()=>GH,HieraPreTrainedModel:()=>WH,HubertForCTC:()=>eU,HubertForSequenceClassification:()=>tU,HubertModel:()=>$H,HubertPreTrainedModel:()=>QH,HunYuanDenseV1ForCausalLM:()=>iU,HunYuanDenseV1Model:()=>rU,HunYuanDenseV1PreTrainedModel:()=>nU,IJepaForImageClassification:()=>fU,IJepaModel:()=>dU,IJepaPreTrainedModel:()=>uU,Idefics3ForConditionalGeneration:()=>lU,JAISLMHeadModel:()=>hU,JAISModel:()=>mU,JAISPreTrainedModel:()=>pU,JinaCLIPModel:()=>_U,JinaCLIPPreTrainedModel:()=>gU,JinaCLIPTextModel:()=>vU,JinaCLIPVisionModel:()=>yU,Lfm2ForCausalLM:()=>SU,Lfm2Model:()=>xU,Lfm2MoeForCausalLM:()=>TU,Lfm2MoeModel:()=>wU,Lfm2MoePreTrainedModel:()=>CU,Lfm2PreTrainedModel:()=>bU,Lfm2VlForConditionalGeneration:()=>EU,LiteWhisperForConditionalGeneration:()=>OY,Llama4ForCausalLM:()=>jU,Llama4PreTrainedModel:()=>AU,LlamaForCausalLM:()=>kU,LlamaModel:()=>OU,LlamaPreTrainedModel:()=>DU,LlavaForConditionalGeneration:()=>oU,LlavaOnevisionForConditionalGeneration:()=>oU,LlavaPreTrainedModel:()=>aU,LlavaQwen2ForCausalLM:()=>cU,LongT5ForConditionalGeneration:()=>PU,LongT5Model:()=>NU,LongT5PreTrainedModel:()=>MU,M2M100ForConditionalGeneration:()=>LU,M2M100Model:()=>IU,M2M100PreTrainedModel:()=>FU,MBartForCausalLM:()=>JU,MBartForConditionalGeneration:()=>KU,MBartForSequenceClassification:()=>qU,MBartModel:()=>GU,MBartPreTrainedModel:()=>WU,MPNetForMaskedLM:()=>eG,MPNetForQuestionAnswering:()=>rG,MPNetForSequenceClassification:()=>tG,MPNetForTokenClassification:()=>nG,MPNetModel:()=>$W,MPNetPreTrainedModel:()=>QW,MT5ForConditionalGeneration:()=>lG,MT5Model:()=>cG,MT5PreTrainedModel:()=>sG,MarianMTModel:()=>BU,MarianModel:()=>zU,MarianPreTrainedModel:()=>RU,MaskFormerForInstanceSegmentation:()=>UU,MaskFormerModel:()=>HU,MaskFormerPreTrainedModel:()=>VU,Metric3DForDepthEstimation:()=>XU,Metric3DPreTrainedModel:()=>YU,Metric3Dv2ForDepthEstimation:()=>QU,Metric3Dv2PreTrainedModel:()=>ZU,MgpstrForSceneTextRecognition:()=>tW,MgpstrModelOutput:()=>$U,MgpstrPreTrainedModel:()=>eW,MimiDecoderModel:()=>sW,MimiDecoderOutput:()=>rW,MimiEncoderModel:()=>oW,MimiEncoderOutput:()=>nW,MimiModel:()=>aW,MimiPreTrainedModel:()=>iW,MistralForCausalLM:()=>uW,MistralModel:()=>lW,MistralPreTrainedModel:()=>cW,MobileBertForMaskedLM:()=>pW,MobileBertForQuestionAnswering:()=>hW,MobileBertForSequenceClassification:()=>mW,MobileBertModel:()=>fW,MobileBertPreTrainedModel:()=>dW,MobileLLMForCausalLM:()=>vW,MobileLLMModel:()=>_W,MobileLLMPreTrainedModel:()=>gW,MobileNetV1ForImageClassification:()=>xW,MobileNetV1ForSemanticSegmentation:()=>SW,MobileNetV1Model:()=>bW,MobileNetV1PreTrainedModel:()=>yW,MobileNetV2ForImageClassification:()=>TW,MobileNetV2ForSemanticSegmentation:()=>EW,MobileNetV2Model:()=>wW,MobileNetV2PreTrainedModel:()=>CW,MobileNetV3ForImageClassification:()=>kW,MobileNetV3ForSemanticSegmentation:()=>AW,MobileNetV3Model:()=>OW,MobileNetV3PreTrainedModel:()=>DW,MobileNetV4ForImageClassification:()=>NW,MobileNetV4ForSemanticSegmentation:()=>PW,MobileNetV4Model:()=>MW,MobileNetV4PreTrainedModel:()=>jW,MobileViTForImageClassification:()=>LW,MobileViTModel:()=>IW,MobileViTPreTrainedModel:()=>FW,MobileViTV2ForImageClassification:()=>BW,MobileViTV2Model:()=>zW,MobileViTV2PreTrainedModel:()=>RW,ModernBertDecoderForCausalLM:()=>JW,ModernBertDecoderModel:()=>qW,ModernBertDecoderPreTrainedModel:()=>KW,ModernBertForMaskedLM:()=>UW,ModernBertForSequenceClassification:()=>WW,ModernBertForTokenClassification:()=>GW,ModernBertModel:()=>HW,ModernBertPreTrainedModel:()=>VW,Moondream1ForConditionalGeneration:()=>sU,MoonshineForConditionalGeneration:()=>ZW,MoonshineModel:()=>XW,MoonshinePreTrainedModel:()=>YW,MptForCausalLM:()=>oG,MptModel:()=>aG,MptPreTrainedModel:()=>iG,MultiModalityCausalLM:()=>dG,MultiModalityPreTrainedModel:()=>uG,MusicgenForCausalLM:()=>mG,MusicgenForConditionalGeneration:()=>hG,MusicgenModel:()=>pG,MusicgenPreTrainedModel:()=>fG,NanoChatForCausalLM:()=>vG,NanoChatModel:()=>_G,NanoChatPreTrainedModel:()=>gG,NeoBertForMaskedLM:()=>xG,NeoBertForQuestionAnswering:()=>wG,NeoBertForSequenceClassification:()=>SG,NeoBertForTokenClassification:()=>CG,NeoBertModel:()=>bG,NeoBertPreTrainedModel:()=>yG,NomicBertModel:()=>EG,NomicBertPreTrainedModel:()=>TG,OPTForCausalLM:()=>WG,OPTModel:()=>UG,OPTPreTrainedModel:()=>HG,Olmo2ForCausalLM:()=>MG,Olmo2Model:()=>jG,Olmo2PreTrainedModel:()=>AG,Olmo3ForCausalLM:()=>FG,Olmo3Model:()=>PG,Olmo3PreTrainedModel:()=>NG,OlmoForCausalLM:()=>kG,OlmoHybridForCausalLM:()=>RG,OlmoHybridModel:()=>LG,OlmoHybridPreTrainedModel:()=>IG,OlmoModel:()=>OG,OlmoPreTrainedModel:()=>DG,OpenELMForCausalLM:()=>VG,OpenELMModel:()=>BG,OpenELMPreTrainedModel:()=>zG,OwlViTForObjectDetection:()=>XG,OwlViTModel:()=>YG,OwlViTPreTrainedModel:()=>JG,Owlv2ForObjectDetection:()=>qG,Owlv2Model:()=>KG,Owlv2PreTrainedModel:()=>GG,PaliGemmaForConditionalGeneration:()=>ZG,ParakeetForCTC:()=>$G,ParakeetPreTrainedModel:()=>QG,PatchTSMixerForPrediction:()=>nK,PatchTSMixerModel:()=>tK,PatchTSMixerPreTrainedModel:()=>eK,PatchTSTForPrediction:()=>aK,PatchTSTModel:()=>iK,PatchTSTPreTrainedModel:()=>rK,Phi3ForCausalLM:()=>dK,Phi3Model:()=>uK,Phi3PreTrainedModel:()=>lK,Phi3VForCausalLM:()=>pK,Phi3VPreTrainedModel:()=>fK,PhiForCausalLM:()=>cK,PhiModel:()=>sK,PhiPreTrainedModel:()=>oK,PreTrainedModel:()=>$,PvtForImageClassification:()=>gK,PvtModel:()=>hK,PvtPreTrainedModel:()=>mK,PyAnnoteForAudioFrameClassification:()=>yK,PyAnnoteModel:()=>vK,PyAnnotePreTrainedModel:()=>_K,Qwen2ForCausalLM:()=>SK,Qwen2Model:()=>xK,Qwen2MoeForCausalLM:()=>TK,Qwen2MoeModel:()=>wK,Qwen2MoePreTrainedModel:()=>CK,Qwen2PreTrainedModel:()=>bK,Qwen2VLForCausalLM:()=>OK,Qwen2VLForConditionalGeneration:()=>DK,Qwen2VLPreTrainedModel:()=>EK,Qwen2_5_VLForCausalLM:()=>AK,Qwen2_5_VLForConditionalGeneration:()=>kK,Qwen3ForCausalLM:()=>NK,Qwen3Model:()=>MK,Qwen3MoeForCausalLM:()=>IK,Qwen3MoeModel:()=>FK,Qwen3MoePreTrainedModel:()=>PK,Qwen3NextForCausalLM:()=>zK,Qwen3NextModel:()=>RK,Qwen3NextPreTrainedModel:()=>LK,Qwen3PreTrainedModel:()=>jK,Qwen3VLForCausalLM:()=>VK,Qwen3VLForConditionalGeneration:()=>BK,Qwen3VLMoeForCausalLM:()=>UK,Qwen3VLMoeForConditionalGeneration:()=>HK,Qwen3_5ForCausalLM:()=>GK,Qwen3_5ForConditionalGeneration:()=>WK,Qwen3_5MoeForCausalLM:()=>qK,Qwen3_5MoeForConditionalGeneration:()=>KK,RFDetrForObjectDetection:()=>$K,RFDetrModel:()=>QK,RFDetrObjectDetectionOutput:()=>eq,RFDetrPreTrainedModel:()=>ZK,RTDetrForObjectDetection:()=>uB,RTDetrModel:()=>lB,RTDetrObjectDetectionOutput:()=>dB,RTDetrPreTrainedModel:()=>cB,RTDetrV2ForObjectDetection:()=>hq,RTDetrV2Model:()=>mq,RTDetrV2ObjectDetectionOutput:()=>gq,RTDetrV2PreTrainedModel:()=>pq,ResNetForImageClassification:()=>XK,ResNetModel:()=>YK,ResNetPreTrainedModel:()=>JK,RoFormerForMaskedLM:()=>lq,RoFormerForQuestionAnswering:()=>fq,RoFormerForSequenceClassification:()=>uq,RoFormerForTokenClassification:()=>dq,RoFormerModel:()=>cq,RoFormerPreTrainedModel:()=>sq,RobertaForMaskedLM:()=>rq,RobertaForQuestionAnswering:()=>oq,RobertaForSequenceClassification:()=>iq,RobertaForTokenClassification:()=>aq,RobertaModel:()=>nq,RobertaPreTrainedModel:()=>tq,Sam2ImageSegmentationOutput:()=>bq,Sam2Model:()=>Sq,Sam2PreTrainedModel:()=>xq,Sam3TrackerModel:()=>wq,SamImageSegmentationOutput:()=>_q,SamModel:()=>yq,SamPreTrainedModel:()=>vq,SapiensForDepthEstimation:()=>Dq,SapiensForNormalEstimation:()=>Oq,SapiensForSemanticSegmentation:()=>Eq,SapiensPreTrainedModel:()=>Tq,SegformerForImageClassification:()=>jq,SegformerForSemanticSegmentation:()=>Mq,SegformerModel:()=>Aq,SegformerPreTrainedModel:()=>kq,SiglipModel:()=>Pq,SiglipPreTrainedModel:()=>Nq,SiglipTextModel:()=>Fq,SiglipVisionModel:()=>Iq,SmolLM3ForCausalLM:()=>zq,SmolLM3Model:()=>Rq,SmolLM3PreTrainedModel:()=>Lq,SnacDecoderModel:()=>Uq,SnacEncoderModel:()=>Hq,SnacModel:()=>Vq,SnacPreTrainedModel:()=>Bq,SpeechT5ForSpeechToText:()=>Kq,SpeechT5ForTextToSpeech:()=>qq,SpeechT5HifiGan:()=>Jq,SpeechT5Model:()=>Gq,SpeechT5PreTrainedModel:()=>Wq,SqueezeBertForMaskedLM:()=>Zq,SqueezeBertForQuestionAnswering:()=>$q,SqueezeBertForSequenceClassification:()=>Qq,SqueezeBertModel:()=>Xq,SqueezeBertPreTrainedModel:()=>Yq,StableLmForCausalLM:()=>nJ,StableLmModel:()=>tJ,StableLmPreTrainedModel:()=>eJ,Starcoder2ForCausalLM:()=>aJ,Starcoder2Model:()=>iJ,Starcoder2PreTrainedModel:()=>rJ,StyleTextToSpeech2Model:()=>sJ,StyleTextToSpeech2PreTrainedModel:()=>oJ,SupertonicForConditionalGeneration:()=>lJ,SupertonicPreTrainedModel:()=>cJ,Swin2SRForImageSuperResolution:()=>gJ,Swin2SRModel:()=>hJ,Swin2SRPreTrainedModel:()=>mJ,SwinForImageClassification:()=>fJ,SwinForSemanticSegmentation:()=>pJ,SwinModel:()=>dJ,SwinPreTrainedModel:()=>uJ,T5ForConditionalGeneration:()=>yJ,T5Model:()=>vJ,T5PreTrainedModel:()=>_J,TableTransformerForObjectDetection:()=>SJ,TableTransformerModel:()=>xJ,TableTransformerObjectDetectionOutput:()=>CJ,TableTransformerPreTrainedModel:()=>bJ,TrOCRForCausalLM:()=>TJ,TrOCRPreTrainedModel:()=>wJ,UltravoxModel:()=>FH,UltravoxPreTrainedModel:()=>PH,UniSpeechForCTC:()=>OJ,UniSpeechForSequenceClassification:()=>kJ,UniSpeechModel:()=>DJ,UniSpeechPreTrainedModel:()=>EJ,UniSpeechSatForAudioFrameClassification:()=>PJ,UniSpeechSatForCTC:()=>MJ,UniSpeechSatForSequenceClassification:()=>NJ,UniSpeechSatModel:()=>jJ,UniSpeechSatPreTrainedModel:()=>AJ,VaultGemmaForCausalLM:()=>LJ,VaultGemmaModel:()=>IJ,VaultGemmaPreTrainedModel:()=>FJ,ViTForImageClassification:()=>VJ,ViTMAEModel:()=>UJ,ViTMAEPreTrainedModel:()=>HJ,ViTMSNForImageClassification:()=>KJ,ViTMSNModel:()=>GJ,ViTMSNPreTrainedModel:()=>WJ,ViTModel:()=>BJ,ViTPreTrainedModel:()=>zJ,VisionEncoderDecoderModel:()=>RJ,VitMatteForImageMatting:()=>JJ,VitMattePreTrainedModel:()=>qJ,VitPoseForPoseEstimation:()=>XJ,VitPosePreTrainedModel:()=>YJ,VitsModel:()=>$J,VitsModelOutput:()=>ZJ,VitsPreTrainedModel:()=>QJ,VoxtralForConditionalGeneration:()=>eY,VoxtralRealtimeForConditionalGeneration:()=>uY,VoxtralRealtimePreTrainedModel:()=>lY,Wav2Vec2BertForCTC:()=>pY,Wav2Vec2BertForSequenceClassification:()=>mY,Wav2Vec2BertModel:()=>fY,Wav2Vec2BertPreTrainedModel:()=>dY,Wav2Vec2ForAudioFrameClassification:()=>ZH,Wav2Vec2ForCTC:()=>YH,Wav2Vec2ForSequenceClassification:()=>XH,Wav2Vec2Model:()=>JH,Wav2Vec2PreTrainedModel:()=>qH,WavLMForAudioFrameClassification:()=>xY,WavLMForCTC:()=>vY,WavLMForSequenceClassification:()=>yY,WavLMForXVector:()=>bY,WavLMModel:()=>_Y,WavLMPreTrainedModel:()=>gY,WeSpeakerResNetModel:()=>CY,WeSpeakerResNetPreTrainedModel:()=>SY,WhisperForConditionalGeneration:()=>DY,WhisperModel:()=>EY,WhisperPreTrainedModel:()=>TY,XLMForQuestionAnswering:()=>PY,XLMForSequenceClassification:()=>MY,XLMForTokenClassification:()=>NY,XLMModel:()=>AY,XLMPreTrainedModel:()=>kY,XLMRobertaForMaskedLM:()=>LY,XLMRobertaForQuestionAnswering:()=>BY,XLMRobertaForSequenceClassification:()=>RY,XLMRobertaForTokenClassification:()=>zY,XLMRobertaModel:()=>IY,XLMRobertaPreTrainedModel:()=>FY,XLMWithLMHeadModel:()=>jY,XVectorOutput:()=>hY,YolosForObjectDetection:()=>UY,YolosModel:()=>HY,YolosObjectDetectionOutput:()=>WY,YolosPreTrainedModel:()=>VY,YoutuForCausalLM:()=>qY,YoutuModel:()=>KY,YoutuPreTrainedModel:()=>GY});var jR=class extends ${},MR=class extends jR{},NR=class extends jR{async _call(e){return new AL(await super._call(e))}},PR=class extends jR{async _call(e){return new NL(await super._call(e))}},FR=class extends jR{async _call(e){return new ML(await super._call(e))}},IR=class extends ${},LR=class extends IR{},RR=class extends IR{},zR=class extends ${},BR=class extends zR{},VR=class extends zR{},HR=class extends ${},UR=class extends HR{},WR=class extends HR{},GR=class extends ${},KR=class extends GR{},qR=class extends GR{},JR=class extends ${},YR=class extends JR{},XR=class extends JR{},ZR=class extends JR{async _call(e){return new AL(await super._call(e))}},QR=class extends ${},$R=class extends QR{},ez=class extends QR{async _call(e){return new AL(await super._call(e))}},tz=class extends ${},nz=class extends tz{},rz=class extends tz{async _call(e){return new ML(await super._call(e))}},iz=class extends tz{async _call(e){return new AL(await super._call(e))}},az=class extends tz{async _call(e){return new jL(await super._call(e))}},oz=class extends tz{async _call(e){return new NL(await super._call(e))}},sz=class extends ${},cz=class extends sz{},lz=class extends sz{},uz=class extends ${},dz=class extends uz{},fz=class extends uz{},pz=class extends ${},mz=class extends pz{},hz=class extends pz{},gz=class extends ${},_z=class extends gz{},vz=class extends gz{async _call(e){return new ML(await super._call(e))}},yz=class extends gz{async _call(e){return new AL(await super._call(e))}},bz=class extends gz{async _call(e){return new jL(await super._call(e))}},xz=class extends gz{async _call(e){return new NL(await super._call(e))}},Sz=4299n,Cz=6561n,wz=class extends ${forward_params=[`input_ids`,`inputs_embeds`,`attention_mask`,`position_ids`,`audio_values`,`exaggeration`,`audio_features`,`audio_tokens`,`speaker_embeddings`,`speaker_features`,`past_key_values`];main_input_name=`input_ids`;_return_dict_in_generate_keys=[`audio_tokens`,`speaker_embeddings`,`speaker_features`]},Tz=class extends wz{async encode_speech(e){return DL(this.sessions.speech_encoder,{audio_values:e})}async forward({input_ids:e=null,attention_mask:t=null,audio_values:n=null,exaggeration:r=null,position_ids:i=null,inputs_embeds:a=null,past_key_values:o=null,generation_config:s=null,logits_processor:c=null,audio_features:l=null,audio_tokens:u=null,speaker_embeddings:d=null,speaker_features:f=null,...p}){let m;if(!a){let s=this.sessions.embed_tokens.inputNames,c={input_ids:e};if(s.includes(`exaggeration`)){if(!(r instanceof Z)){let t=e.dims[0];if(r==null)r=wM([t],.5);else if(typeof r==`number`)r=wM([t],r);else if(Array.isArray(r))r=new Z(`float32`,r,[t]);else throw Error("Unsupported type for `exaggeration` input")}c.exaggeration=r}if(s.includes(`position_ids`)&&(c.position_ids=i),{inputs_embeds:a}=await DL(this.sessions.embed_tokens,c),l&&u&&d&&f&&(m={audio_features:l,audio_tokens:u,speaker_embeddings:d,speaker_features:f}),m||n)m??=await this.encode_speech(n),a=_M([m.audio_features,a],1),t=EM([a.dims[0],a.dims[1]]);else{let e=a.dims[1];if(!o||e!==1)throw Error(`Incorrect state encountered during generation.`);let n=o.get_seq_length();t=EM([a.dims[0],n+e])}}return{...await _R(this,{inputs_embeds:a,past_key_values:o,attention_mask:t,generation_config:s,logits_processor:c},!1),...m}}prepare_inputs_for_generation(e,t,n){return!t.position_ids&&this.sessions.embed_tokens.inputNames.includes(`position_ids`)&&(t.input_ids.dims[1]===1?t.position_ids=new Z(`int64`,Array.from({length:e.length},(t,n)=>e[n].length-e[n].findLastIndex(e=>e==Cz)-1),[e.length,1]):t.position_ids=new Z(`int64`,t.input_ids.tolist().map(e=>{let t=0;return e.map(e=>e>=Cz?0:t++)}).flat(),t.input_ids.dims)),t.input_ids.dims[1]===1&&(delete t.audio_values,delete t.audio_features,delete t.audio_tokens,delete t.speaker_embeddings,delete t.speaker_features),CR(this,e,t,n)}async generate(e){let{sequences:t,audio_tokens:n,speaker_embeddings:r,speaker_features:i}=await super.generate({...e,return_dict_in_generate:!0}),a=t.slice(null,[e.input_ids.dims[1],-1]),o=_M([n,a,wM([a.dims[0],3],Sz)],1),{waveform:s}=await DL(this.sessions.conditional_decoder,{speech_tokens:o,speaker_features:i,speaker_embeddings:r});return s}},Ez=class extends ${},Dz=class extends Ez{},Oz=class extends ${},kz=class extends Oz{},Az=class extends Oz{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??`text_model`})}},jz=class extends Oz{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??`audio_model`})}},Mz=class extends ${},Nz=class extends Mz{},Pz=class extends Mz{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??`text_model`})}},Fz=class extends Mz{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??`text_model`})}},Iz=class extends Mz{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??`vision_model`})}},Lz=class extends Mz{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??`vision_model`})}},Rz=class extends ${},zz=class extends Rz{},Bz=class extends Rz{},Vz=class extends ${},Hz=class extends Vz{},Uz=class extends Vz{},Wz=class extends ${},Gz=class extends Wz{},Kz=class extends Wz{},qz=class extends ${},Jz=class extends qz{},Yz=class extends qz{},Xz=class extends ${},Zz=class extends Xz{},Qz=class extends Xz{async _call(e){return new ML(await super._call(e))}},$z=class extends Xz{async _call(e){return new AL(await super._call(e))}},eB=class extends Xz{async _call(e){return new jL(await super._call(e))}},tB=class extends Xz{async _call(e){return new NL(await super._call(e))}},nB=class extends ${},rB=class extends nB{},iB=class extends nB{async _call(e){return new AL(await super._call(e))}},aB=class extends ${},oB=class extends aB{},sB=class extends aB{async _call(e){return new AL(await super._call(e))}},cB=class extends ${},lB=class extends cB{},uB=class extends cB{async _call(e){return new dB(await super._call(e))}},dB=class extends kL{constructor({logits:e,pred_boxes:t}){super(),this.logits=e,this.pred_boxes=t}},fB=class extends ${},pB=class extends fB{},mB=class extends fB{async _call(e){return new dB(await super._call(e))}},hB=class extends kL{constructor({audio_codes:e}){super(),this.audio_codes=e}},gB=class extends kL{constructor({audio_values:e}){super(),this.audio_values=e}},_B=class extends ${main_input_name=`input_values`;forward_params=[`input_values`]},vB=class extends _B{async encode(e){return new hB(await DL(this.sessions.encoder_model,e))}async decode(e){return new gB(await DL(this.sessions.decoder_model,e))}},yB=class extends _B{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??`encoder_model`})}},bB=class extends _B{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??`decoder_model`})}},xB=class extends ${},SB=class extends xB{},CB=class extends xB{async _call(e){return new ML(await super._call(e))}},wB=class extends xB{async _call(e){return new AL(await super._call(e))}},TB=class extends xB{async _call(e){return new jL(await super._call(e))}},EB=class extends xB{async _call(e){return new NL(await super._call(e))}},DB=class extends ${},OB=class extends DB{},kB=class extends DB{async _call(e){return new ML(await super._call(e))}},AB=class extends DB{async _call(e){return new AL(await super._call(e))}},jB=class extends DB{async _call(e){return new jL(await super._call(e))}},MB=class extends DB{async _call(e){return new NL(await super._call(e))}},NB=class extends ${},PB=class extends NB{},FB=class extends ${},IB=class extends FB{},LB=class extends FB{async _call(e){return new AL(await super._call(e))}},RB=class extends ${},zB=class extends RB{},BB=class extends ${},VB=class extends BB{},HB=class extends ${},UB=class extends HB{},WB=class extends HB{async _call(e){return new KB(await super._call(e))}},GB=class extends HB{async _call(e){return new qB(await super._call(e))}},KB=class extends kL{constructor({logits:e,pred_boxes:t}){super(),this.logits=e,this.pred_boxes=t}},qB=class extends kL{constructor({logits:e,pred_boxes:t,pred_masks:n}){super(),this.logits=e,this.pred_boxes=t,this.pred_masks=n}},JB=class extends ${},YB=class extends JB{},XB=class extends JB{async _call(e){return new AL(await super._call(e))}},ZB=class extends ${},QB=class extends ZB{},$B=class extends ZB{async _call(e){return new AL(await super._call(e))}},eV=class extends ${},tV=class extends eV{},nV=class extends ${},rV=class extends nV{},iV=class extends ${},aV=class extends iV{},oV=class extends iV{async _call(e){return new AL(await super._call(e))}},sV=class extends iV{async _call(e){return new jL(await super._call(e))}},cV=class extends iV{async _call(e){return new NL(await super._call(e))}},lV=class extends iV{async _call(e){return new ML(await super._call(e))}},uV=class extends ${},dV=class extends uV{},fV=class extends ${},pV=class extends fV{},mV=class extends fV{},hV=class extends ${},gV=class extends hV{},_V=class extends hV{async _call(e){return new AL(await super._call(e))}},vV=class extends ${},yV=class extends vV{},bV=class extends vV{async _call(e){return new ML(await super._call(e))}},xV=class extends vV{async _call(e){return new AL(await super._call(e))}},SV=class extends vV{async _call(e){return new jL(await super._call(e))}},CV=class extends vV{async _call(e){return new NL(await super._call(e))}},wV=class extends ${},TV=class extends wV{},EV=class extends wV{},DV=class extends ${},OV=class extends DV{},kV=class extends DV{async _call(e){return new ML(await super._call(e))}},AV=class extends DV{async _call(e){return new AL(await super._call(e))}},jV=class extends DV{async _call(e){return new jL(await super._call(e))}},MV=class extends ${},NV=class extends MV{},PV=class extends MV{},FV=class extends ${},IV=class extends FV{},LV=class extends FV{},RV=class extends ${},zV=class extends RV{},BV=class extends RV{},VV=class extends ${},HV=class extends VV{},UV=class extends VV{async _call(e){return new AL(await super._call(e))}},WV=class extends ${forward_params=[`input_ids`,`inputs_embeds`,`attention_mask`,`pixel_values`,`encoder_outputs`,`decoder_input_ids`,`decoder_inputs_embeds`,`decoder_attention_mask`,`past_key_values`];main_input_name=`inputs_embeds`},GV=class extends WV{_merge_input_ids_with_image_features({inputs_embeds:e,image_features:t,input_ids:n,attention_mask:r}){return{inputs_embeds:_M([t,e],1),attention_mask:_M([EM(t.dims.slice(0,2)),r],1)}}async _prepare_inputs_embeds({input_ids:e,pixel_values:t,inputs_embeds:n,attention_mask:r}){if(!e&&!t)throw Error("Either `input_ids` or `pixel_values` should be provided.");let i,a;return e&&(i=await this.encode_text({input_ids:e})),t&&(a=await this.encode_image({pixel_values:t})),i&&a?{inputs_embeds:n,attention_mask:r}=this._merge_input_ids_with_image_features({inputs_embeds:i,image_features:a,input_ids:e,attention_mask:r}):n=i||a,{inputs_embeds:n,attention_mask:r}}async forward({input_ids:e,pixel_values:t,attention_mask:n,decoder_input_ids:r,decoder_attention_mask:i,encoder_outputs:a,past_key_values:o,inputs_embeds:s,decoder_inputs_embeds:c}){if(s||({inputs_embeds:s,attention_mask:n}=await this._prepare_inputs_embeds({input_ids:e,pixel_values:t,inputs_embeds:s,attention_mask:n})),!a){let{last_hidden_state:e}=await hR(this,{inputs_embeds:s,attention_mask:n});a=e}if(!c){if(!r)throw Error("Either `decoder_input_ids` or `decoder_inputs_embeds` should be provided.");c=await this.encode_text({input_ids:r})}return await _R(this,{inputs_embeds:c,attention_mask:i,encoder_attention_mask:n,encoder_hidden_states:a,past_key_values:o},!0)}},KV=class extends ${},qV=class extends KV{},JV=class extends KV{},YV=class extends ${},XV=class extends YV{},ZV=class extends YV{},QV=class extends ${},$V=class extends QV{},eH=class extends QV{},tH=class extends ${forward_params=[`input_ids`,`attention_mask`,`inputs_embeds`,`per_layer_inputs`,`position_ids`,`pixel_values`,`input_features`,`input_features_mask`,`past_key_values`]},nH=class extends tH{async forward({input_ids:e=null,attention_mask:t=null,pixel_values:n=null,input_features:r=null,input_features_mask:i=null,position_ids:a=null,inputs_embeds:o=null,per_layer_inputs:s=null,past_key_values:c=null,generation_config:l=null,logits_processor:u=null,...d}){if((!o||!s)&&({inputs_embeds:o,per_layer_inputs:s}=await DL(this.sessions.embed_tokens,{input_ids:e}),e.dims[1]!==1)){if(n){let{image_features:r}=await DL(this.sessions.vision_encoder,{pixel_values:n});({inputs_embeds:o,attention_mask:t}=this._merge_input_ids_with_image_features({image_features:r,inputs_embeds:o,input_ids:e,attention_mask:t}))}if(r){let{audio_features:n}=await DL(this.sessions.audio_encoder,{input_features:r,input_features_mask:i});({inputs_embeds:o,attention_mask:t}=this._merge_input_ids_with_audio_features({audio_features:n,inputs_embeds:o,input_ids:e,attention_mask:t}))}}return await _R(this,{inputs_embeds:o,per_layer_inputs:s,past_key_values:c,attention_mask:t,position_ids:a,generation_config:l,logits_processor:u},!0)}_merge_input_ids_with_image_features(e){let t=e.image_features.dims.at(-1),n=e.image_features.view(-1,t);return DR({image_token_id:this.config.image_token_id,...e,image_features:n})}_merge_input_ids_with_audio_features(e){let t=e.audio_features.dims.at(-1),n=e.audio_features.view(-1,t);return OR({audio_token_id:this.config.audio_token_id,...e,audio_features:n})}},rH=class extends nH{},iH=class extends ${},aH=class extends iH{},oH=class extends iH{},sH=class extends ${},cH=class extends sH{},lH=class extends sH{},uH=class extends ${},dH=class extends uH{},fH=class extends uH{},pH=class extends ${},mH=class extends pH{},hH=class extends pH{},gH=class extends ${},_H=class extends gH{},vH=class extends gH{},yH=class extends ${},bH=class extends yH{},xH=class extends yH{},SH=class extends ${},CH=class extends SH{},wH=class extends SH{},TH=class extends ${},EH=class extends TH{},DH=class extends TH{},OH=class extends ${},kH=class extends OH{},AH=class extends OH{},jH=class extends ${},MH=class extends jH{},NH=class extends jH{},PH=class extends ${forward_params=[`input_ids`,`attention_mask`,`position_ids`,`audio_values`,`past_key_values`]},FH=class extends PH{_merge_input_ids_with_audio_features(e){let t=e.audio_features.dims.at(-1),n=e.audio_features.view(-1,t);return OR({audio_token_id:this.config.ignore_index??this.config.audio_token_id??this.config.audio_token_index,...e,audio_features:n})}},IH=class extends FH{forward_params=[`input_ids`,`attention_mask`,`input_features`,`past_key_values`]},LH=class extends ${},RH=class extends LH{},zH=class extends ${},BH=class extends zH{},VH=class extends ${},HH=class extends VH{},UH=class extends VH{},WH=class extends ${},GH=class extends WH{},KH=class extends WH{async _call(e){return new AL(await super._call(e))}},qH=class extends ${},JH=class extends qH{},YH=class extends qH{async _call(e){return new PL(await super._call(e))}},XH=class extends qH{async _call(e){return new AL(await super._call(e))}},ZH=class extends qH{async _call(e){return new jL(await super._call(e))}},QH=class extends ${},$H=class extends qH{},eU=class extends qH{async _call(e){return new PL(await super._call(e))}},tU=class extends qH{async _call(e){return new AL(await super._call(e))}},nU=class extends ${},rU=class extends nU{},iU=class extends nU{},aU=class extends ${forward_params=[`input_ids`,`attention_mask`,`pixel_values`,`position_ids`,`past_key_values`]},oU=class extends aU{_merge_input_ids_with_image_features(e){let t=e.image_features.dims.at(-1),n=e.image_features.view(-1,t);return DR({image_token_id:this.config.image_token_index??this.config.image_token_id,...e,image_features:n})}},sU=class extends oU{},cU=class extends oU{},lU=class extends oU{forward_params=[`input_ids`,`attention_mask`,`pixel_values`,`pixel_attention_mask`,`position_ids`,`past_key_values`]},uU=class extends ${},dU=class extends uU{},fU=class extends uU{async _call(e){return new AL(await super._call(e))}},pU=class extends ${},mU=class extends pU{},hU=class extends pU{},gU=class extends ${},_U=class extends gU{async forward(e){let t=!e.input_ids,n=!e.pixel_values;if(t&&n)throw Error("Either `input_ids` or `pixel_values` should be provided.");if(t&&(e.input_ids=EM([e.pixel_values.dims[0],1])),n){let{image_size:t}=this.config.vision_config;e.pixel_values=wM([0,3,t,t],0)}let{text_embeddings:r,image_embeddings:i,l2norm_text_embeddings:a,l2norm_image_embeddings:o}=await super.forward(e),s={};return t||(s.text_embeddings=r,s.l2norm_text_embeddings=a),n||(s.image_embeddings=i,s.l2norm_image_embeddings=o),s}},vU=class extends gU{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??`text_model`})}},yU=class extends gU{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??`vision_model`})}},bU=class extends ${},xU=class extends bU{},SU=class extends bU{},CU=class extends ${},wU=class extends CU{},TU=class extends CU{},EU=class extends oU{forward_params=[`input_ids`,`attention_mask`,`pixel_values`,`pixel_attention_mask`,`spatial_shapes`,`position_ids`,`past_key_values`]},DU=class extends ${},OU=class extends DU{},kU=class extends DU{},AU=class extends ${},jU=class extends AU{},MU=class extends ${},NU=class extends MU{},PU=class extends MU{},FU=class extends ${},IU=class extends FU{},LU=class extends FU{},RU=class extends ${},zU=class extends RU{},BU=class extends RU{},VU=class extends ${},HU=class extends VU{},UU=class extends VU{},WU=class extends ${},GU=class extends WU{},KU=class extends WU{},qU=class extends WU{async _call(e){return new AL(await super._call(e))}},JU=class extends WU{},YU=class extends ${},XU=class extends YU{},ZU=class extends ${},QU=class extends ZU{},$U=class extends kL{constructor({char_logits:e,bpe_logits:t,wp_logits:n}){super(),this.char_logits=e,this.bpe_logits=t,this.wp_logits=n}get logits(){return[this.char_logits,this.bpe_logits,this.wp_logits]}},eW=class extends ${},tW=class extends eW{async _call(e){return new $U(await super._call(e))}},nW=class extends kL{constructor({audio_codes:e}){super(),this.audio_codes=e}},rW=class extends kL{constructor({audio_values:e}){super(),this.audio_values=e}},iW=class extends ${main_input_name=`input_values`;forward_params=[`input_values`]},aW=class extends iW{async encode(e){return new nW(await DL(this.sessions.encoder_model,e))}async decode(e){return new rW(await DL(this.sessions.decoder_model,e))}},oW=class extends iW{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??`encoder_model`})}},sW=class extends iW{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??`decoder_model`})}},cW=class extends ${},lW=class extends cW{},uW=class extends cW{},dW=class extends ${},fW=class extends dW{},pW=class extends dW{async _call(e){return new ML(await super._call(e))}},mW=class extends dW{async _call(e){return new AL(await super._call(e))}},hW=class extends dW{async _call(e){return new NL(await super._call(e))}},gW=class extends ${},_W=class extends gW{},vW=class extends gW{},yW=class extends ${},bW=class extends yW{},xW=class extends yW{async _call(e){return new AL(await super._call(e))}},SW=class extends yW{},CW=class extends ${},wW=class extends CW{},TW=class extends CW{async _call(e){return new AL(await super._call(e))}},EW=class extends CW{},DW=class extends ${},OW=class extends DW{},kW=class extends DW{async _call(e){return new AL(await super._call(e))}},AW=class extends DW{},jW=class extends ${},MW=class extends jW{},NW=class extends jW{async _call(e){return new AL(await super._call(e))}},PW=class extends jW{},FW=class extends ${},IW=class extends FW{},LW=class extends FW{async _call(e){return new AL(await super._call(e))}},RW=class extends ${},zW=class extends RW{},BW=class extends RW{async _call(e){return new AL(await super._call(e))}},VW=class extends ${},HW=class extends VW{},UW=class extends VW{async _call(e){return new ML(await super._call(e))}},WW=class extends VW{async _call(e){return new AL(await super._call(e))}},GW=class extends VW{async _call(e){return new jL(await super._call(e))}},KW=class extends ${},qW=class extends KW{},JW=class extends KW{},YW=class extends ${requires_attention_mask=!1;main_input_name=`input_values`;forward_params=[`input_values`,`decoder_input_ids`,`past_key_values`]},XW=class extends YW{},ZW=class extends YW{},QW=class extends ${},$W=class extends QW{},eG=class extends QW{async _call(e){return new ML(await super._call(e))}},tG=class extends QW{async _call(e){return new AL(await super._call(e))}},nG=class extends QW{async _call(e){return new jL(await super._call(e))}},rG=class extends QW{async _call(e){return new NL(await super._call(e))}},iG=class extends ${},aG=class extends iG{},oG=class extends iG{},sG=class extends ${},cG=class extends sG{},lG=class extends sG{},uG=class extends ${},dG=class extends uG{forward_params=[`input_ids`,`pixel_values`,`images_seq_mask`,`images_emb_mask`,`attention_mask`,`position_ids`,`past_key_values`];constructor(...e){super(...e),this._generation_mode=`text`}async forward(e){let t=this._generation_mode??`text`,n;if(t===`text`||!e.past_key_values){let t=this.sessions.prepare_inputs_embeds;n=await DL(t,lD(e,t.inputNames))}else{let t=this.sessions.gen_img_embeds;n=await DL(t,lD({image_ids:e.input_ids},t.inputNames))}let r={...e,...n},i=await _R(this,r),a=this.sessions[t===`text`?`lm_head`:`gen_head`];if(!a)throw Error(`Unable to find "${a}" generation head`);let o=await DL(a,lD(i,a.inputNames));return{...n,...i,...o}}prepare_inputs_for_generation(e,t,n){let r=!!t.past_key_values;return n.guidance_scale!==null&&n.guidance_scale>1&&(r?t.input_ids=_M([t.input_ids,t.input_ids],0):(t.input_ids=_M([t.input_ids,TM(t.input_ids,BigInt(n.pad_token_id))],0),t.attention_mask=_M([t.attention_mask,TM(t.attention_mask,0n)],0))),(r||!t.pixel_values)&&(t.pixel_values=wM([0,0,3,384,384],1)),r&&(t.images_seq_mask=new Z(`bool`,[,].fill(!0).fill(!1,0,1),[1,1]),t.images_emb_mask=new Z(`bool`,[].fill(!1),[1,1,0])),t}async generate(e){return this._generation_mode=`text`,super.generate(e)}async generate_images(e){this._generation_mode=`image`;let t=(e.inputs??e[this.main_input_name]).dims[1],n=(await super.generate(e)).slice(null,[t,null]),r=this.sessions.image_decode,{decoded_image:i}=await DL(r,{generated_tokens:n}),a=i.add_(1).mul_(255/2).clamp_(0,255).to(`uint8`),o=[];for(let e of a){let t=WP.fromTensor(e);o.push(t)}return o}},fG=class extends ${},pG=class extends fG{},mG=class extends fG{},hG=class extends ${forward_params=[`input_ids`,`attention_mask`,`encoder_outputs`,`decoder_input_ids`,`decoder_attention_mask`,`past_key_values`];_apply_and_filter_by_delay_pattern_mask(e){let[t,n]=e.dims,r=this.config.decoder.num_codebooks,i=n-r,a=0;for(let t=0;t0&&o<=i&&(e.data[a++]=e.data[t])}let o=Math.floor(t/r),s=a/(o*r);return new Z(e.type,e.data.slice(0,a),[o,r,s])}prepare_inputs_for_generation(e,t,n){let r=BigInt(this.config.decoder.pad_token_id),i=structuredClone(e);for(let e=0;e=t&&(i[e][t]=r);return n.guidance_scale!==null&&n.guidance_scale>1&&(i=i.concat(i)),wR(this,i,t,n)}async generate(e){let t=await super.generate(e),n=this._apply_and_filter_by_delay_pattern_mask(t).unsqueeze_(0),{audio_values:r}=await DL(this.sessions.encodec_decode,{audio_codes:n});return r}},gG=class extends ${},_G=class extends gG{},vG=class extends gG{},yG=class extends ${},bG=class extends yG{},xG=class extends yG{async _call(e){return new ML(await super._call(e))}},SG=class extends yG{async _call(e){return new AL(await super._call(e))}},CG=class extends yG{async _call(e){return new jL(await super._call(e))}},wG=class extends yG{async _call(e){return new NL(await super._call(e))}},TG=class extends ${},EG=class extends TG{},DG=class extends ${},OG=class extends DG{},kG=class extends DG{},AG=class extends ${},jG=class extends AG{},MG=class extends AG{},NG=class extends ${},PG=class extends NG{},FG=class extends NG{},IG=class extends ${},LG=class extends IG{},RG=class extends IG{},zG=class extends ${},BG=class extends zG{},VG=class extends zG{},HG=class extends ${},UG=class extends HG{},WG=class extends HG{},GG=class extends ${},KG=class extends GG{},qG=class extends GG{},JG=class extends ${},YG=class extends JG{},XG=class extends JG{},ZG=class extends oU{},QG=class extends ${},$G=class extends QG{async _call(e){return new PL(await super._call(e))}},eK=class extends ${},tK=class extends eK{},nK=class extends eK{},rK=class extends ${},iK=class extends rK{},aK=class extends rK{},oK=class extends ${},sK=class extends oK{},cK=class extends oK{},lK=class extends ${},uK=class extends lK{},dK=class extends lK{},fK=class extends ${forward_params=[`input_ids`,`inputs_embeds`,`attention_mask`,`position_ids`,`pixel_values`,`image_sizes`,`past_key_values`]},pK=class extends fK{async forward({input_ids:e=null,attention_mask:t=null,pixel_values:n=null,image_sizes:r=null,position_ids:i=null,inputs_embeds:a=null,past_key_values:o=null,generation_config:s=null,logits_processor:c=null,...l}){if(!a){let t;if(n&&e.dims[1]!==1){if(!r)throw Error("`image_sizes` must be provided when `pixel_values` is provided.");({image_features:t}=await DL(this.sessions.vision_encoder,{pixel_values:n,image_sizes:r}))}else{let e=this.config.normalized_config.hidden_size;t=new Z(`float32`,[],[0,e])}({inputs_embeds:a}=await DL(this.sessions.prepare_inputs_embeds,{input_ids:e,image_features:t}))}return await _R(this,{inputs_embeds:a,past_key_values:o,attention_mask:t,position_ids:i,generation_config:s,logits_processor:c},!1)}},mK=class extends ${},hK=class extends mK{},gK=class extends mK{async _call(e){return new AL(await super._call(e))}},_K=class extends ${},vK=class extends _K{},yK=class extends _K{async _call(e){return new jL(await super._call(e))}},bK=class extends ${},xK=class extends bK{},SK=class extends bK{},CK=class extends ${},wK=class extends CK{},TK=class extends CK{},EK=class extends ${forward_params=[`input_ids`,`attention_mask`,`position_ids`,`past_key_values`,`pixel_values`,`image_grid_thw`]},DK=class extends EK{image_grid_thw_name=`grid_thw`;get_rope_index(e,t,n,r){let{vision_config:i,image_token_id:a,video_token_id:o,vision_start_token_id:s}=this.config,c=i.spatial_merge_size??2,l=[];if(t||n){let i=e.tolist();r||=DM(e);let u=r.tolist(),d=Array.from({length:3},t=>Array.from({length:e.dims[0]},t=>Array.from({length:e.dims[1]},e=>1))),f=t?t.tolist():[],p=n?n.tolist():[],m=0,h=0;for(let e=0;eu[e][n]==1),n=t.reduce((e,t,n)=>(t==s&&e.push(n),e),[]).map(e=>t[e+1]),r=n.filter(e=>e==a).length,g=n.filter(e=>e==o).length,_=[],v=0,y=r,b=g;for(let e=0;et>v&&e==a),n=t.findIndex((e,t)=>t>v&&e==o),r=y>0&&e!==-1?e:t.length+1,i=b>0&&n!==-1?n:t.length+1,s,l,u,d;r0?mj(_.at(-1))[0]+1:0;_.push(Array.from({length:3*C},(e,t)=>w+t%C));let T=C+w,E=g*x*S,D=Array.from({length:E},(e,t)=>T+Math.floor(t/(x*S))),O=Array.from({length:E},(e,t)=>T+Math.floor(t/S)%x),k=Array.from({length:E},(e,t)=>T+t%S);_.push([D,O,k].flat()),v=s+E}if(v0?mj(_.at(-1))[0]+1:0,n=t.length-v;_.push(Array.from({length:3*n},(t,r)=>e+r%n))}let x=_.reduce((e,t)=>e+t.length,0),S=Array(x),C=0;for(let e=0;e<3;++e)for(let t=0;t<_.length;++t){let n=_[t],r=n.length/3;for(let t=e*r;t<(e+1)*r;++t)S[C++]=n[t]}let w=0,T=u[e];for(let t=0;te[n%e.length]),i=Array.from({length:t[0]},(n,r)=>mj(e.subarray(t[1]*r,t[1]*(r+1)))[0]+1n+BigInt(t[1]));return[new Z(`int64`,n,[3,...t]),new Z(`int64`,i,[i.length,1])]}else{let[t,n]=e.dims;return[new Z(`int64`,BigInt64Array.from({length:3*t*n},(e,r)=>BigInt(Math.floor(r%n/t))),[3,...e.dims]),OM([t,1])]}}async encode_image({pixel_values:e,image_grid_thw:t}){return(await DL(this.sessions.vision_encoder,{pixel_values:e,[this.image_grid_thw_name]:t})).image_features}_merge_input_ids_with_image_features(e){return DR({image_token_id:this.config.image_token_id,...e})}prepare_inputs_for_generation(e,t,n){if(t.attention_mask&&!t.position_ids)if(!t.past_key_values)[t.position_ids,t.rope_deltas]=this.get_rope_index(t.input_ids,t.image_grid_thw,t.video_grid_thw,t.attention_mask);else{t.pixel_values=null;let e=t.past_key_values.get_seq_length();if(en+e);t.position_ids=vM([r,r,r],0)}}return t}},OK=class extends DK{},kK=class extends DK{image_grid_thw_name=`image_grid_thw`},AK=class extends OK{image_grid_thw_name=`image_grid_thw`},jK=class extends ${},MK=class extends jK{},NK=class extends jK{},PK=class extends ${},FK=class extends PK{},IK=class extends PK{},LK=class extends ${},RK=class extends LK{},zK=class extends LK{},BK=class extends kK{},VK=class extends AK{},HK=class extends BK{},UK=class extends VK{},WK=class extends BK{},GK=class extends WK{},KK=class extends WK{},qK=class extends GK{},JK=class extends ${},YK=class extends JK{},XK=class extends JK{async _call(e){return new AL(await super._call(e))}},ZK=class extends ${},QK=class extends ZK{},$K=class extends ZK{async _call(e){return new eq(await super._call(e))}},eq=class extends dB{},tq=class extends ${},nq=class extends tq{},rq=class extends tq{async _call(e){return new ML(await super._call(e))}},iq=class extends tq{async _call(e){return new AL(await super._call(e))}},aq=class extends tq{async _call(e){return new jL(await super._call(e))}},oq=class extends tq{async _call(e){return new NL(await super._call(e))}},sq=class extends ${},cq=class extends sq{},lq=class extends sq{async _call(e){return new ML(await super._call(e))}},uq=class extends sq{async _call(e){return new AL(await super._call(e))}},dq=class extends sq{async _call(e){return new jL(await super._call(e))}},fq=class extends sq{async _call(e){return new NL(await super._call(e))}},pq=class extends ${},mq=class extends pq{},hq=class extends pq{async _call(e){return new gq(await super._call(e))}},gq=class extends dB{},_q=class extends kL{constructor({iou_scores:e,pred_masks:t}){super(),this.iou_scores=e,this.pred_masks=t}},vq=class extends ${},yq=class extends vq{async get_image_embeddings({pixel_values:e}){return await hR(this,{pixel_values:e})}async forward(e){e=!e.image_embeddings||!e.image_positional_embeddings?{...e,...await this.get_image_embeddings(e)}:{...e},e.input_labels??=EM(e.input_points.dims.slice(0,-1));let t={image_embeddings:e.image_embeddings,image_positional_embeddings:e.image_positional_embeddings};return e.input_points&&(t.input_points=e.input_points),e.input_labels&&(t.input_labels=e.input_labels),e.input_boxes&&(t.input_boxes=e.input_boxes),await DL(this.sessions.prompt_encoder_mask_decoder,t)}async _call(e){return new _q(await super._call(e))}},bq=class extends kL{constructor({iou_scores:e,pred_masks:t,object_score_logits:n}){super(),this.iou_scores=e,this.pred_masks=t,this.object_score_logits=n}},xq=class extends ${},Sq=class extends xq{async get_image_embeddings({pixel_values:e}){return await hR(this,{pixel_values:e})}async forward(e){let{num_feature_levels:t}=this.config.vision_config;if(e=Array.from({length:t},(e,t)=>`image_embeddings.${t}`).some(t=>!e[t])?{...e,...await this.get_image_embeddings(e)}:{...e},e.input_points){if(e.input_boxes&&e.input_boxes.dims[1]!==1)throw Error("When both `input_points` and `input_boxes` are provided, the number of boxes per image must be 1.");let t=e.input_points.dims;e.input_labels??=EM(t.slice(0,-1)),e.input_boxes??=wM([t[0],0,4],0)}else if(e.input_boxes){let t=e.input_boxes.dims;e.input_labels=wM([t[0],t[1],0],-1n),e.input_points=wM([t[0],1,0,2],0)}else throw Error("At least one of `input_points` or `input_boxes` must be provided.");let n=this.sessions.prompt_encoder_mask_decoder;return await DL(n,lD(e,n.inputNames))}async _call(e){return new bq(await super._call(e))}},Cq=class extends Sq{},wq=class extends Sq{},Tq=class extends ${},Eq=class extends Tq{},Dq=class extends Tq{},Oq=class extends Tq{},kq=class extends ${},Aq=class extends kq{},jq=class extends kq{},Mq=class extends kq{},Nq=class extends ${},Pq=class extends Nq{},Fq=class extends Nq{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??`text_model`})}},Iq=class extends Mz{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??`vision_model`})}},Lq=class extends ${},Rq=class extends Lq{},zq=class extends Lq{},Bq=class extends ${main_input_name=`input_values`;forward_params=[`input_values`]},Vq=class extends Bq{async encode(e){return await DL(this.sessions.encoder_model,e)}async decode(e){return await DL(this.sessions.decoder_model,e)}},Hq=class extends Bq{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??`encoder_model`})}},Uq=class extends Bq{static async from_pretrained(e,t={}){return super.from_pretrained(e,{...t,model_file_name:t.model_file_name??`decoder_model`})}},Wq=class extends ${},Gq=class extends Wq{},Kq=class extends Wq{},qq=class extends Wq{async generate_speech(e,t,{threshold:n=.5,minlenratio:r=0,maxlenratio:i=20,vocoder:a=null}={}){let{encoder_outputs:o,encoder_attention_mask:s}=await hR(this,{input_ids:e}),c=o.dims[1]/this.config.reduction_factor,l=Math.floor(c*i),u=Math.floor(c*r),d=this.config.num_mel_bins,f=[],p=null,m=null,h=0;for(;;){++h;let e=lR(!!m),r;r=m?m.output_sequence_out:new Z(`float32`,new Float32Array(d),[1,1,d]);let i={use_cache_branch:e,output_sequence:r,encoder_attention_mask:s,speaker_embeddings:t,encoder_hidden_states:o};this.addPastKeyValues(i,p),m=await DL(this.sessions.decoder_model_merged,i),p=this.getPastKeyValues(m,p);let{prob:a,spectrum:c}=m;if(f.push(c),h>=u&&(Array.from(a.data).filter(e=>e>=n).length>0||h>=l))break}let g=_M(f),{waveform:_}=await DL(a.sessions.model,{spectrogram:g});return{spectrogram:g,waveform:_}}},Jq=class extends ${main_input_name=`spectrogram`},Yq=class extends ${},Xq=class extends Yq{},Zq=class extends Yq{async _call(e){return new ML(await super._call(e))}},Qq=class extends Yq{async _call(e){return new AL(await super._call(e))}},$q=class extends Yq{async _call(e){return new NL(await super._call(e))}},eJ=class extends ${},tJ=class extends eJ{},nJ=class extends eJ{},rJ=class extends ${},iJ=class extends rJ{},aJ=class extends rJ{},oJ=class extends ${},sJ=class extends oJ{},cJ=class extends ${},lJ=class extends cJ{async generate_speech({input_ids:e,attention_mask:t,style:n,num_inference_steps:r=5,speed:i=1.05}){let{sampling_rate:a,chunk_compress_factor:o,base_chunk_size:s,latent_dim:c}=this.config,{last_hidden_state:l,durations:u}=await DL(this.sessions.text_encoder,{input_ids:e,attention_mask:t,style:n}),d=u.div(i).mul_(a),f=s*o,p=d.data,m=Int32Array.from(p,e=>Math.ceil(e/f)),h=Math.max(...m),g=e.dims[0],_=new BigInt64Array(g*h);for(let e=0;ee*t,1)),d[e]);let f=new Z(l,new u(s*tY),[1,s,tY]),p=t[Symbol.asyncIterator]?.()??t[Symbol.iterator]?.();if(!p)throw Error(`input_features must be iterable or async iterable`);return{encoder_session:i,enc_kv_cache:c,enc_padding_cache:f,enc_past_seq_len:0,audio_embed_queue:[],audio_embed_total_tokens:0,audio_queue_offset:0,audio_consumed:0,stream_exhausted:!1,chunks_iter:p,text_hidden_size:n.hidden_size}}async function aY(e,t){let n=t.dims[2],r=Math.floor((nY+n-3)/2)+1,i=new Z(`int64`,BigInt64Array.from({length:r},(t,n)=>BigInt(e.enc_past_seq_len+n)),[1,r]),a=e.enc_past_seq_len+r,o=EM([1,a]),{audio_embeds:s,present_padding_cache:c,...l}=await DL(e.encoder_session,{input_features:t,attention_mask:o,position_ids:i,past_padding_cache:e.enc_padding_cache,...e.enc_kv_cache});e.enc_padding_cache.location===`gpu-buffer`&&e.enc_padding_cache.dispose(),e.enc_padding_cache=c;for(let t in l)if(t.startsWith(`present.`)){let n=t.replace(`present`,`past_key_values`),r=e.enc_kv_cache[n];r?.location===`gpu-buffer`&&r.dispose(),e.enc_kv_cache[n]=l[t]}return e.enc_past_seq_len=a,s}async function oY(e,t){for(;e.audio_embed_total_tokens0&&e.audio_embed_queue.length>0;){let t=e.audio_embed_queue[0],n=t.tokens-e.audio_queue_offset,o=Math.min(a,n),s=e.audio_queue_offset*e.text_hidden_size;for(let n=0;n=t.tokens&&(e.audio_embed_queue.shift(),e.audio_queue_offset=0)}e.audio_consumed+=n-a}var cY=class extends ZL{constructor(e){super(),this._s=e}_call(e){let t=this._s.stream_exhausted&&this._s.audio_embed_queue.length===0;return e.map(()=>t)}},lY=class extends ${forward_params=[`input_ids`,`attention_mask`,`position_ids`,`past_key_values`]},uY=class extends lY{async forward({input_ids:e,past_key_values:t,...n}){let r=e.dims[1],i=rY.get(this);i&&await oY(i,i.audio_consumed+r);let{inputs_embeds:a}=await DL(this.sessions.embed_tokens,{input_ids:e});i&&sY(i,a,r);let o={inputs_embeds:a,...n};this.addPastKeyValues(o,t);let s=this.sessions.decoder_model_merged;return await DL(s,lD(o,s.inputNames))}async generate({input_features:e,stopping_criteria:t,...n}){if(!e)throw Error(`input_features (generator/iterable) must be provided`);let r=iY(this,e);rY.set(this,r);let i=new QL;i.push(new cY(r)),t&&i.extend(t);try{return await super.generate({...n,stopping_criteria:i})}finally{r.enc_kv_cache.dispose(),rY.delete(this)}}},dY=class extends ${},fY=class extends dY{},pY=class extends dY{async _call(e){return new PL(await super._call(e))}},mY=class extends dY{async _call(e){return new AL(await super._call(e))}},hY=class extends kL{constructor({logits:e,embeddings:t}){super(),this.logits=e,this.embeddings=t}},gY=class extends ${},_Y=class extends gY{},vY=class extends gY{async _call(e){return new PL(await super._call(e))}},yY=class extends gY{async _call(e){return new AL(await super._call(e))}},bY=class extends gY{async _call(e){return new hY(await super._call(e))}},xY=class extends gY{async _call(e){return new jL(await super._call(e))}},SY=class extends ${},CY=class extends SY{},wY=class extends XL{return_timestamps=null;return_token_timestamps=null;num_frames=null;alignment_heads=null;task=null;language=null;no_timestamps_token_id=null;prompt_ids=null;is_multilingual=null;lang_to_id=null;task_to_id=null;max_initial_timestamp_index=1},TY=class extends ${requires_attention_mask=!1;main_input_name=`input_features`;forward_params=[`input_features`,`attention_mask`,`decoder_input_ids`,`decoder_attention_mask`,`past_key_values`]},EY=class extends TY{},DY=class extends TY{_prepare_generation_config(e,t){return super._prepare_generation_config(e,t,wY)}_retrieve_init_tokens(e){let t=[e.decoder_start_token_id],n=e.language,r=e.task;if(e.is_multilingual){n||=(dD.warn(`No language specified - defaulting to English (en).`),`en`);let i=`<|${PN(n)}|>`;t.push(e.lang_to_id[i]),t.push(e.task_to_id[r??`transcribe`])}else if(n||r)throw Error("Cannot specify `task` or `language` for an English-only model. If the model is intended to be multilingual, pass `is_multilingual=true` to generate, or update the generation config.");return!e.return_timestamps&&e.no_timestamps_token_id&&t.at(-1)!==e.no_timestamps_token_id?t.push(e.no_timestamps_token_id):e.return_timestamps&&t.at(-1)===e.no_timestamps_token_id&&(dD.warn("<|notimestamps|> prompt token is removed from generation_config since `return_timestamps` is set to `true`."),t.pop()),t.filter(e=>e!=null)}async generate({inputs:e=null,generation_config:t=null,logits_processor:n=null,stopping_criteria:r=null,...i}){t=this._prepare_generation_config(t,i);let a=i.decoder_input_ids??this._retrieve_init_tokens(t);if(t.return_timestamps&&(n??=new RL,n.push(new HL(t,a))),t.begin_suppress_tokens&&(n??=new RL,n.push(new VL(t.begin_suppress_tokens,a.length))),t.return_token_timestamps){if(!t.alignment_heads)throw Error("Model generation config has no `alignment_heads`, token-level timestamps not available. See https://gist.github.com/hollance/42e32852f24243b748ae6bc1f985b13a on how to add this property to the generation config.");t.task===`translate`&&dD.warn(`Token-level timestamps may not be reliable for task 'translate'.`),t.output_attentions=!0,t.return_dict_in_generate=!0}let o=await super.generate({inputs:e,generation_config:t,logits_processor:n,decoder_input_ids:a,...i});return t.return_token_timestamps&&(o.token_timestamps=this._extract_token_timestamps(o,t.alignment_heads,t.num_frames)),o}_extract_token_timestamps(e,t,n=null,r=.02){if(!e.cross_attentions)throw Error("Model outputs must contain cross attentions to extract timestamps. This is most likely because the model was not exported with `output_attentions=True`.");n??dD.warn("`num_frames` has not been set, meaning the entire audio will be analyzed. This may lead to inaccurate token-level timestamps for short audios (< 30 seconds).");let i=this.config.median_filter_width;i===void 0&&(dD.warn("Model config has no `median_filter_width`, using default value of 7."),i=7);let a=e.cross_attentions,o=Array.from({length:this.config.decoder_layers},(e,t)=>_M(a.map(e=>e[t]),2)),s=vM(t.map(([e,t])=>{if(e>=o.length)throw Error(`Layer index ${e} is out of bounds for cross attentions (length ${o.length}).`);return n?o[e].slice(null,t,null,[0,n]):o[e].slice(null,t)})).transpose(1,0,2,3),[c,l]=bM(s,-2,0,!0),u=s.clone();for(let e=0;et[n+1]-t[n])).map(e=>!!e),a=[];for(let e=0;ee[0]);static BASE_IF_FAIL=!0},LX=class extends FX{static MODEL_CLASS_MAPPINGS=[PX.MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES]},RX=class extends FX{static MODEL_CLASS_MAPPINGS=[PX.MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES]},zX=class extends FX{static MODEL_CLASS_MAPPINGS=[PX.MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES]},BX=class extends FX{static MODEL_CLASS_MAPPINGS=[PX.MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES]},VX=class extends FX{static MODEL_CLASS_MAPPINGS=[PX.MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING_NAMES]},HX=class extends FX{static MODEL_CLASS_MAPPINGS=[PX.MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING_NAMES]},UX=class extends FX{static MODEL_CLASS_MAPPINGS=[PX.MODEL_FOR_CAUSAL_LM_MAPPING_NAMES]},WX=class extends FX{static MODEL_CLASS_MAPPINGS=[PX.MODEL_FOR_MASKED_LM_MAPPING_NAMES]},GX=class extends FX{static MODEL_CLASS_MAPPINGS=[PX.MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES]},KX=class extends FX{static MODEL_CLASS_MAPPINGS=[PX.MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES]},qX=class extends FX{static MODEL_CLASS_MAPPINGS=[PX.MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES]},JX=class extends FX{static MODEL_CLASS_MAPPINGS=[PX.MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES]},YX=class extends FX{static MODEL_CLASS_MAPPINGS=[PX.MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES]},XX=class extends FX{static MODEL_CLASS_MAPPINGS=[PX.MODEL_FOR_UNIVERSAL_SEGMENTATION_MAPPING_NAMES]},ZX=class extends FX{static MODEL_CLASS_MAPPINGS=[PX.MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES]},QX=class extends FX{static MODEL_CLASS_MAPPINGS=[PX.MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES]};(class extends FX{static MODEL_CLASS_MAPPINGS=[PX.MODEL_FOR_MASK_GENERATION_MAPPING_NAMES]});var $X=class extends FX{static MODEL_CLASS_MAPPINGS=[PX.MODEL_FOR_CTC_MAPPING_NAMES]},eZ=class extends FX{static MODEL_CLASS_MAPPINGS=[PX.MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES]};(class extends FX{static MODEL_CLASS_MAPPINGS=[PX.MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES]}),class extends FX{static MODEL_CLASS_MAPPINGS=[PX.MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING_NAMES]};var tZ=class extends FX{static MODEL_CLASS_MAPPINGS=[PX.MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES]};(class extends FX{static MODEL_CLASS_MAPPINGS=[PX.MODEL_FOR_IMAGE_MATTING_MAPPING_NAMES]});var nZ=class extends FX{static MODEL_CLASS_MAPPINGS=[PX.MODEL_FOR_IMAGE_TO_IMAGE_MAPPING_NAMES]},rZ=class extends FX{static MODEL_CLASS_MAPPINGS=[PX.MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES]};(class extends FX{static MODEL_CLASS_MAPPINGS=[PX.MODEL_FOR_NORMAL_ESTIMATION_MAPPING_NAMES]}),class extends FX{static MODEL_CLASS_MAPPINGS=[PX.MODEL_FOR_POSE_ESTIMATION_MAPPING_NAMES]};var iZ=class extends FX{static MODEL_CLASS_MAPPINGS=[PX.MODEL_FOR_IMAGE_FEATURE_EXTRACTION_MAPPING_NAMES]},aZ=class extends FX{static MODEL_CLASS_MAPPINGS=[PX.MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING_NAMES]};(class extends FX{static MODEL_CLASS_MAPPINGS=[PX.MODEL_FOR_AUDIO_TEXT_TO_TEXT_MAPPING_NAMES]});async function oZ(e){return Array.isArray(e)||(e=[e]),await Promise.all(e.map(e=>WP.read(e)))}async function sZ(e,t){return Array.isArray(e)||(e=[e]),await Promise.all(e.map(e=>typeof e==`string`||e instanceof URL?QN(e,t):e instanceof Float64Array?new Float32Array(e):e))}function cZ(e,t){t&&(e=e.map(e=>e|0));let[n,r,i,a]=e;return{xmin:n,ymin:r,xmax:i,ymax:a}}var lZ=class extends CA{constructor({task:e,model:t,tokenizer:n=null,processor:r=null}){super(),this.task=e,this.model=t,this.tokenizer=n,this.processor=r}async dispose(){await this.model.dispose()}},uZ=class extends lZ{async _call(e,{top_k:t=1}={}){let n=this.tokenizer(e,{padding:!0,truncation:!0}),r=await this.model(n),{problem_type:i,id2label:a}=this.model.config,o=i===`multi_label_classification`?e=>e.sigmoid():e=>new Z(`float32`,dj(e.data),e.dims),s=[];for(let e of r.logits){let n=await uM(o(e),t),r=n[0].tolist(),i=n[1].tolist().map((e,t)=>({label:a?a[e]:`LABEL_${e}`,score:r[t]}));t===1?s.push(...i):s.push(i)}return Array.isArray(e)||t===1?s:s[0]}},dZ=class extends lZ{async _call(e,{ignore_labels:t=[`O`]}={}){let n=Array.isArray(e),r=this.tokenizer(n?e:[e],{padding:!0,truncation:!0}),i=(await this.model(r)).logits,a=this.model.config.id2label,o=[];for(let e=0;ee==u),i=a[e].tolist(),f=o[e].tolist();for(let n=1;ne==t[n])!==-1)&&(i[n]=-1/0,f[n]=-1/0);let p=dj(i).map((e,t)=>[e,t]),m=dj(f).map((e,t)=>[e,t]);p[0][0]=0,m[0][0]=0;let h=sD(p,m).filter(e=>e[0][1]<=e[1][1]).map(e=>[e[0][1],e[1][1],e[0][0]*e[1][0]]).sort((e,t)=>t[2]-e[2]),g=[];for(let e=0;ee==n);if(c===-1)throw Error(`Mask token (${r}) not found in text.`);let l=a[e][c],u=await uM(new Z(`float32`,dj(l.data),l.dims),t),d=u[0].tolist(),f=u[1].tolist();o.push(f.map((e,t)=>{let n=i.slice();return n[c]=e,{score:d[t],token:Number(e),token_str:this.tokenizer.decode([e]),sequence:this.tokenizer.decode(n,{skip_special_tokens:!0})}}))}return Array.isArray(e)?o:o[0]}},mZ=class extends lZ{_key=`generated_text`;async _call(e,t={}){Array.isArray(e)||(e=[e]),this.model.config.prefix&&(e=e.map(e=>this.model.config.prefix+e));let n=this.model.config.task_specific_params;n&&n[this.task]&&n[this.task].prefix&&(e=e.map(e=>n[this.task].prefix+e));let r=this.tokenizer,i={padding:!0,truncation:!0},a;a=this.task===`translation`&&`_build_translation_inputs`in r?r._build_translation_inputs(e,i,t):r(e,i);let o=await this.model.generate({...a,...t});return r.batch_decode(o,{skip_special_tokens:!0}).map(e=>({[this._key]:e}))}},hZ=class extends mZ{_key=`summary_text`},gZ=class extends mZ{_key=`translation_text`};function _Z(e){return Array.isArray(e)&&e.every(e=>`role`in e&&`content`in e)}var vZ=class extends lZ{async _call(e,t={}){let n=!1,r=!1,i=t.add_special_tokens??(this.tokenizer.add_bos_token||this.tokenizer.add_eos_token)??!1,a=t.tokenizer_encode_kwargs,o;if(typeof e==`string`)o=e=[e];else if(Array.isArray(e)&&e.every(e=>typeof e==`string`))n=!0,o=e;else{if(_Z(e))e=[e];else if(Array.isArray(e)&&e.every(_Z))n=!0;else throw Error(`Input must be a string, an array of strings, a Chat, or an array of Chats`);r=!0,o=e.map(e=>this.tokenizer.apply_chat_template(e,{tokenize:!1,add_generation_prompt:!0,...a})),i=!1,a=void 0}let s=r?!1:t.return_full_text??!0;this.tokenizer.padding_side=`left`;let c=this.tokenizer(o,{add_special_tokens:i,padding:!0,truncation:!0,...a}),l=await this.model.generate({...c,...t}),u=this.tokenizer.batch_decode(l,{skip_special_tokens:!0}),d;!s&&c.input_ids.dims.at(-1)>0&&(d=this.tokenizer.batch_decode(c.input_ids,{skip_special_tokens:!0}).map(e=>e.length));let f=Array.from({length:e.length},e=>[]);for(let t=0;t[e.toLowerCase(),t])),this.entailment_id=this.label2id.entailment,this.entailment_id===void 0&&(dD.warn(`Could not find 'entailment' in label2id mapping. Using 2 as entailment_id.`),this.entailment_id=2),this.contradiction_id=this.label2id.contradiction??this.label2id.not_entailment,this.contradiction_id===void 0&&(dD.warn(`Could not find 'contradiction' in label2id mapping. Using 0 as contradiction_id.`),this.contradiction_id=0)}async _call(e,t,{hypothesis_template:n=`This example is {}.`,multi_label:r=!1}={}){let i=Array.isArray(e);i||(e=[e]),Array.isArray(t)||(t=[t]);let a=t.map(e=>n.replace(`{}`,e)),o=r||t.length===1,s=[];for(let n of e){let e=[];for(let t of a){let r=this.tokenizer(n,{text_pair:t,padding:!0,truncation:!0}),i=await this.model(r);o?e.push([i.logits.data[this.contradiction_id],i.logits.data[this.entailment_id]]):e.push(i.logits.data[this.entailment_id])}let r=(o?e.map(e=>dj(e)[1]):dj(e)).map((e,t)=>[e,t]).sort((e,t)=>t[0]-e[0]);s.push({sequence:n,labels:r.map(e=>t[e[1]]),scores:r.map(e=>e[0])})}return i?s:s[0]}},bZ=class extends lZ{async _call(e,{top_k:t=5}={}){let n=this.processor.feature_extractor.config.sampling_rate,r=await sZ(e,n),i=this.model.config.id2label,a=[];for(let e of r){let n=await this.processor(e),r=(await this.model(n)).logits[0],o=await uM(new Z(`float32`,dj(r.data),r.dims),t),s=o[0].tolist(),c=o[1].tolist().map((e,t)=>({label:i?i[e]:`LABEL_${e}`,score:s[t]}));a.push(c)}return Array.isArray(e)?a:a[0]}},xZ=class extends lZ{async _call(e,t,{hypothesis_template:n=`This is a sound of {}.`}={}){let r=!Array.isArray(e);r&&(e=[e]);let i=t.map(e=>n.replace(`{}`,e)),a=this.tokenizer(i,{padding:!0,truncation:!0}),o=this.processor.feature_extractor.config.sampling_rate,s=await sZ(e,o),c=[];for(let e of s){let n=await this.processor(e),r=dj((await this.model({...a,...n})).logits_per_audio.data);c.push([...r].map((e,n)=>({score:e,label:t[n]})))}return r?c[0]:c}},SZ=class extends lZ{async _call(e,t={}){switch(this.model.config.model_type){case`whisper`:case`lite-whisper`:return this._call_whisper(e,t);case`wav2vec2`:case`wav2vec2-bert`:case`unispeech`:case`unispeech-sat`:case`hubert`:case`parakeet_ctc`:return this._call_wav2vec2(e,t);case`moonshine`:return this._call_moonshine(e,t);default:throw Error(`AutomaticSpeechRecognitionPipeline does not support model type '${this.model.config.model_type}'.`)}}async _call_wav2vec2(e,t){t.language&&dD.warn('`language` parameter is not yet supported for `wav2vec2` models, defaulting to "English".'),t.task&&dD.warn('`task` parameter is not yet supported for `wav2vec2` models, defaulting to "transcribe".');let n=!Array.isArray(e),r=n?[e]:e,i=this.processor.feature_extractor.config.sampling_rate,a=await sZ(r,i),o=[];for(let e of a){let t=await this.processor(e),n=(await this.model(t)).logits[0],r=[];for(let e of n)r.push(mj(e.data)[1]);let i=this.tokenizer.decode(r,{skip_special_tokens:!0}).trim();o.push({text:i})}return n?o[0]:o}async _call_whisper(e,t){let n=t.return_timestamps??!1,r=t.chunk_length_s??0,i=t.force_full_sequences??!1,a=t.stride_length_s??null,o={...t};n===`word`&&(o.return_token_timestamps=!0,o.return_timestamps=!1);let s=!Array.isArray(e),c=s?[e]:e,l=this.processor.feature_extractor.config,u=l.chunk_length/this.model.config.max_source_positions,d=l.hop_length,f=l.sampling_rate,p=await sZ(c,f),m=[];for(let e of p){let t=[];if(r>0){if(a===null)a=r/6;else if(r<=a)throw Error("`chunk_length_s` must be larger than `stride_length_s`.");let n=f*r,i=f*a,o=n-2*i,s=0;for(;;){let r=s+n,a=e.subarray(s,r),c=await this.processor(a),l=s===0,u=r>=e.length;if(t.push({stride:[a.length,l?0:i,u?0:i],input_features:c.input_features,is_last:u}),u)break;s+=o}}else t=[{stride:[e.length,0,0],input_features:(await this.processor(e)).input_features,is_last:!0}];for(let e of t){o.num_frames=Math.floor(e.stride[0]/d);let t=await this.model.generate({inputs:e.input_features,...o});n===`word`?(e.tokens=t.sequences.tolist()[0],e.token_timestamps=t.token_timestamps.tolist()[0].map(e=>bj(e,2))):e.tokens=t[0].tolist(),e.stride=e.stride.map(e=>e/f)}let[s,c]=this.tokenizer._decode_asr(t,{time_precision:u,return_timestamps:n,force_full_sequences:i});m.push({text:s,...c})}return s?m[0]:m}async _call_moonshine(e,t){let n=!Array.isArray(e),r=n?[e]:e,i=this.processor.feature_extractor.config.sampling_rate,a=await sZ(r,i),o=[];for(let e of a){let n=await this.processor(e),r=Math.floor(e.length/i)*6,a=await this.model.generate({max_new_tokens:r,...t,...n}),s=this.processor.batch_decode(a,{skip_special_tokens:!0})[0];o.push({text:s})}return n?o[0]:o}},CZ=class extends lZ{DEFAULT_VOCODER_ID=`Xenova/speecht5_hifigan`;constructor(e){super(e),this.vocoder=e.vocoder??null}async _prepare_speaker_embeddings(e,t){if((typeof e==`string`||e instanceof URL)&&(e=new Float32Array(await(await eD.fetch(e)).arrayBuffer())),e instanceof Float32Array)e=new Z(`float32`,e,[e.length]);else if(!(e instanceof Z))throw Error("Speaker embeddings must be a `Tensor`, `Float32Array`, `string`, or `URL`.");if(t>1){if(e.dims[0]===1)e=e.repeat(t,1);else if(e.dims[0]!==t)throw Error(`Expected speaker embeddings batch size to be 1 or ${t}, but got ${e.dims[0]}.`)}return e}_postprocess_waveform(e,t,n,r=null){let i=t.data,[a,o]=t.dims,s=r?r.data:null,c=[];for(let e=0;e({generated_text:e.trim()}));a.push(r)}return n?a:a[0]}},TZ=class extends lZ{async _call(e,{top_k:t=5}={}){let n=await oZ(e),{pixel_values:r}=await this.processor(n),i=await this.model({pixel_values:r}),{id2label:a}=this.model.config,o=[];for(let e of i.logits){let n=await uM(new Z(`float32`,dj(e.data),e.dims),t),r=n[0].tolist(),i=n[1].tolist().map((e,t)=>({label:a?a[e]:`LABEL_${e}`,score:r[t]}));o.push(i)}return Array.isArray(e)?o:o[0]}},EZ={panoptic:`post_process_panoptic_segmentation`,instance:`post_process_instance_segmentation`,semantic:`post_process_semantic_segmentation`},DZ=class extends lZ{async _call(e,{threshold:t=.5,mask_threshold:n=.5,overlap_mask_area_threshold:r=.8,label_ids_to_fuse:i=null,target_sizes:a=null,subtask:o=null}={}){if(Array.isArray(e)&&e.length!==1)throw Error(`Image segmentation pipeline currently only supports a batch size of 1.`);let s=await oZ(e),c=s.map(e=>[e.height,e.width]),l=await this.processor(s),{inputNames:u,outputNames:d}=this.model.sessions.model;if(!u.includes(`pixel_values`)){if(u.length!==1)throw Error(`Expected a single input name, but got ${u.length} inputs: ${u}.`);let e=u[0];if(e in l)throw Error(`Input name ${e} already exists in the inputs.`);l[e]=l.pixel_values}let f=await this.model(l),p=null;if(o!==null)p=EZ[o];else if(this.processor.image_processor){for(let[e,t]of Object.entries(EZ))if(t in this.processor.image_processor){p=this.processor.image_processor[t].bind(this.processor.image_processor),o=e;break}}let m=this.model.config.id2label,h=[];if(!o){let e=1e-5,t=f[d[0]];for(let n=0;nt<-e||t>1+e)&&i.sigmoid_();let a=await WP.fromTensor(i.mul_(255).to(`uint8`)).resize(r[1],r[0]);h.push({label:null,score:null,mask:a})}}else if(o===`panoptic`||o===`instance`){let e=p(f,t,n,r,i,a??c)[0],o=e.segmentation;for(let t of e.segments_info){let e=new Uint8ClampedArray(o.data.length);for(let n=0;n{let n=e.clone();return n.putAlpha(r[t].mask),n});return Array.isArray(e)?i:i[0]}},kZ=class extends lZ{async _call(e,t,{hypothesis_template:n=`This is a photo of {}`}={}){let r=Array.isArray(e),i=await oZ(e),a=t.map(e=>n.replace(`{}`,e)),o=this.tokenizer(a,{padding:this.model.config.model_type===`siglip`?`max_length`:!0,truncation:!0}),{pixel_values:s}=await this.processor(i),c=await this.model({...o,pixel_values:s}),l=this.model.config.model_type===`siglip`?e=>e.sigmoid().data:e=>dj(e.data),u=[];for(let e of c.logits_per_image){let n=[...l(e)].map((e,n)=>({score:e,label:t[n]}));n.sort((e,t)=>t.score-e.score),u.push(n)}return r?u:u[0]}},AZ=class extends lZ{async _call(e,{threshold:t=.9,percentage:n=!1}={}){let r=Array.isArray(e);if(r&&e.length!==1)throw Error(`Object detection pipeline currently only supports a batch size of 1.`);let i=await oZ(e),a=n?null:i.map(e=>[e.height,e.width]),{pixel_values:o,pixel_mask:s}=await this.processor(i),c=await this.model({pixel_values:o,pixel_mask:s}),l=this.processor.image_processor.post_process_object_detection(c,t,a),{id2label:u}=this.model.config,d=l.map(e=>e.boxes.map((t,r)=>({score:e.scores[r],label:u[e.classes[r]],box:cZ(t,!n)})));return r?d:d[0]}},jZ=class extends lZ{async _call(e,t,{threshold:n=.1,top_k:r=null,percentage:i=!1}={}){let a=Array.isArray(e),o=await oZ(e),s=this.tokenizer(t,{padding:!0,truncation:!0}),c=await this.processor(o),l=[];for(let e=0;e({score:e.scores[n],label:e.labels[n],box:cZ(t,!i)}))}else{let e=this.processor.image_processor.post_process_object_detection(f,n,u,!0)[0];p=e.boxes.map((n,r)=>({score:e.scores[r],label:t[e.classes[r]],box:cZ(n,!i)}))}p.sort((e,t)=>t.score-e.score),r!==null&&(p=p.slice(0,r)),l.push(p)}return a?l:l[0]}},MZ=class extends lZ{async _call(e,t,n={}){if(Array.isArray(e)){if(e.length!==1)throw Error(`Document Question Answering pipeline currently only supports a batch size of 1.`);e=e[0]}let r=(await oZ(e))[0],{pixel_values:i}=await this.processor(r),a=`${t}`,o=this.tokenizer(a,{add_special_tokens:!1,padding:!0,truncation:!0}).input_ids,s=await this.model.generate({inputs:i,max_length:this.model.config.decoder.max_position_embeddings,decoder_input_ids:o,...n}),c=this.tokenizer.batch_decode(s)[0].match(/(.*?)<\/s_answer>/),l=null;return c&&c.length>=2&&(l=c[1].trim()),[{answer:l}]}},NZ=class extends lZ{async _call(e){let t=await oZ(e),n=await this.processor(t),r=await this.model(n),i=[];for(let e of r.reconstruction){let t=e.squeeze().clamp_(0,1).mul_(255).round_().to(`uint8`);i.push(WP.fromTensor(t))}return Array.isArray(e)?i:i[0]}},PZ=class extends lZ{async _call(e){let t=await oZ(e),n=await this.processor(t),{predicted_depth:r}=await this.model(n),i=[];for(let e=0;ee>=19968&&e<=40959||e>=13312&&e<=19903||e>=131072&&e<=173791||e>=173824&&e<=177983||e>=177984&&e<=178207||e>=178208&&e<=183983||e>=63744&&e<=64255||e>=194560&&e<=195103,RZ=class{put(e){throw Error(`Not implemented`)}end(){throw Error(`Not implemented`)}},zZ=GE.IS_PROCESS_AVAILABLE?e=>process.stdout.write(e):e=>console.log(e),BZ=class extends RZ{constructor(e,{skip_prompt:t=!1,callback_function:n=null,token_callback_function:r=null,skip_special_tokens:i=!0,decode_kwargs:a={},...o}={}){super(),this.tokenizer=e,this.skip_prompt=t,this.callback_function=n??zZ,this.token_callback_function=r,this.decode_kwargs={skip_special_tokens:i,...a,...o},this.token_cache=[],this.print_len=0,this.next_tokens_are_prompt=!0,this.special_ids=new Set(this.tokenizer.all_special_ids.map(BigInt))}put(e){if(e.length>1)throw Error(`TextStreamer only supports batch size of 1`);let t=this.next_tokens_are_prompt;if(t&&(this.next_tokens_are_prompt=!1,this.skip_prompt))return;let n=e[0];if(this.token_callback_function?.(n),n.length===1&&this.special_ids.has(n[0])){if(this.decode_kwargs.skip_special_tokens)return;if(this.token_cache.length>0){let e=this.tokenizer.decode(this.token_cache,this.decode_kwargs).slice(this.print_len);this.on_finalized_text(e,!1),this.token_cache=[],this.print_len=0}let e=this.tokenizer.decode(n,this.decode_kwargs);this.on_finalized_text(e,!1);return}this.token_cache=oD(this.token_cache,n);let r=this.tokenizer.decode(this.token_cache,this.decode_kwargs),i;t||r.endsWith(` +`)?(i=r.slice(this.print_len),this.token_cache=[],this.print_len=0):r.length>0&&LZ(r.charCodeAt(r.length-1))?(i=r.slice(this.print_len),this.print_len+=i.length):(i=r.slice(this.print_len,r.lastIndexOf(` `)+1),this.print_len+=i.length),this.on_finalized_text(i,!1)}end(){let e;this.token_cache.length>0?(e=this.tokenizer.decode(this.token_cache,this.decode_kwargs).slice(this.print_len),this.token_cache=[],this.print_len=0):e=``,this.next_tokens_are_prompt=!0,this.on_finalized_text(e,!0)}on_finalized_text(e,t){e.length>0&&this.callback_function?.(e),t&&this.callback_function===zZ&&GE.IS_PROCESS_AVAILABLE&&this.callback_function?.(` +`)}},VZ=`onnx-community/LFM2-VL-450M-ONNX`,HZ=3,UZ=128,WZ={error:null,message:`Downloading...`,progress:0,status:`idle`};function GZ(e){return e.replace(/\s+/g,` `).trim()}function KZ(e){return e instanceof Error?e.message:`The model could not be loaded.`}function qZ({children:e}){let[t,n]=(0,y.useState)(WZ),r=(0,y.useRef)(null),i=(0,y.useRef)(null),a=(0,y.useRef)(null),o=(0,y.useRef)(!1),s=(0,y.useCallback)(e=>{n(t=>({...t,...e}))},[]),c=(0,y.useCallback)(async()=>{if(r.current&&i.current){s({error:null,message:`Model ready`,progress:100,status:`ready`});return}if(a.current)return a.current;if(!(`gpu`in navigator)){let e=`WebGPU is not available in this browser.`;throw s({error:e,message:`WebGPU unavailable`,progress:0,status:`error`}),Error(e)}return a.current=(async()=>{try{r.current=await pL.from_pretrained(VZ),s({message:`Downloading...`,progress:0,status:`loading`});let e=new Map;i.current=await aZ.from_pretrained(VZ,{device:`webgpu`,dtype:{vision_encoder:`fp16`,embed_tokens:`fp16`,decoder_model_merged:`q4f16`},progress_callback:t=>{t.status!==`progress`||!t.file.endsWith(`.onnx_data`)||t.total===0||(e.set(t.file,t.loaded/t.total),s({message:`Downloading...`,progress:Array.from(e.values()).reduce((e,t)=>e+t,0)/HZ*100,status:`loading`}))}}),s({error:null,message:`Model ready`,progress:100,status:`ready`})}catch(e){throw s({error:KZ(e),message:`Unable to load model`,progress:0,status:`error`}),e}finally{a.current=null}})(),a.current},[s]),l=(0,y.useCallback)(async({frame:e,onStream:t,prompt:n})=>{let a=r.current,s=i.current;if(!a||!s||!a.tokenizer)throw Error(`The model is not ready yet.`);if(o.current)return``;o.current=!0;try{let r=[{content:[{type:`image`},{text:GZ(n),type:`text`}],role:`user`}],i=a.apply_chat_template(r,{add_generation_prompt:!0}),o=await a(new WP(e.data,e.width,e.height,4),i,{add_special_tokens:!1}),c=``,l=new BZ(a.tokenizer,{callback_function:e=>{c+=e;let n=GZ(c);n.length>0&&t?.(n)},skip_prompt:!0,skip_special_tokens:!0}),u=await s.generate({...o,do_sample:!1,max_new_tokens:UZ,repetition_penalty:1.08,streamer:l}),d=o.input_ids.dims.at(-1)??0,f=u.slice(null,[d,null]),[p]=a.batch_decode(f,{skip_special_tokens:!0}),m=GZ(p??c);return m.length>0&&t?.(m),m}finally{o.current=!1}},[]);return(0,N.jsx)(F.Provider,{value:{...t,generateCaption:l,loadModel:c},children:e})}var JZ=[{display:`Describe the scene`,prompt:`Describe the scene in one sentence.`},{display:`What color shirt am I wearing?`,prompt:`What color shirt am I wearing?`},{display:`What am I holding?`,prompt:`What am I holding?`},{display:`How old do I look?`,prompt:`How old do I look?`}];function YZ(e){if(e){if(e.kind===`webcam`){e.stream.getTracks().forEach(e=>e.stop());return}URL.revokeObjectURL(e.url)}}function XZ(e){return e instanceof Error?e.message:`Something went wrong.`}function ZZ(){let[e,t]=(0,y.useState)(`landing`),[n,r]=(0,y.useState)(null),[i,a]=(0,y.useState)(JZ[0].prompt),[o,s]=(0,y.useState)(null),c=(0,y.useRef)(null),l=(0,y.useRef)(null),{error:u,loadModel:d,message:f,progress:p,status:m}=te();(0,y.useEffect)(()=>{l.current=n},[n]),(0,y.useEffect)(()=>()=>{YZ(l.current)},[]),(0,y.useEffect)(()=>{if(e!==`loading`||m===`ready`)return;let n=!1;return d().then(()=>{n||(0,y.startTransition)(()=>{t(`source`)})}).catch(()=>void 0),()=>{n=!0}},[d,e,m]);let h=()=>{(0,y.startTransition)(()=>{t(`loading`)})},g=e=>{YZ(n),s(null),r(e),(0,y.startTransition)(()=>{t(`capture`)})},_=async()=>{try{if(!navigator.mediaDevices?.getUserMedia)throw Error(`Camera access is not available in this browser.`);g({kind:`webcam`,label:`Live camera`,stream:await navigator.mediaDevices.getUserMedia({audio:!1,video:{facingMode:`user`,width:{ideal:1280},height:{ideal:720}}})})}catch(e){s(XZ(e))}},v=()=>{c.current?.click()},b=e=>{let t=e.target.files?.[0];e.target.value=``,t&&g({kind:`file`,label:t.name,url:URL.createObjectURL(t)})},x=()=>{YZ(n),r(null),s(null),(0,y.startTransition)(()=>{t(`source`)})};return(0,N.jsxs)(N.Fragment,{children:[e===`capture`?null:(0,N.jsx)(SS,{subdued:e===`loading`}),(0,N.jsx)(`input`,{ref:c,accept:`video/*`,className:`hidden-file-input`,onChange:b,type:`file`}),e===`landing`?(0,N.jsx)(`button`,{className:`landing-scene`,onClick:h,type:`button`,children:(0,N.jsxs)(`div`,{className:`landing-inner`,children:[(0,N.jsx)(P,{}),(0,N.jsxs)(`div`,{className:`hero-copy`,children:[(0,N.jsx)(`h1`,{children:`LFM2-VL WebGPU`}),(0,N.jsxs)(`p`,{children:[`Real-time video captioning in your browser,`,(0,N.jsx)(`br`,{}),`powered by`,(0,N.jsx)(CS,{className:`hero-inline-icon`}),(0,N.jsx)(`span`,{className:`hero-inline-wordmark`,children:`Transformers.js`})]})]}),(0,N.jsx)(`div`,{className:`begin-prompt`,children:`Click anywhere to begin`})]})}):null,e===`loading`?(0,N.jsxs)(`main`,{className:`scene-shell scene-shell--centered`,children:[(0,N.jsx)(P,{}),(0,N.jsxs)(`section`,{className:`loading-card`,children:[(0,N.jsx)(`span`,{className:`eyebrow`,children:`Loading Model`}),(0,N.jsx)(`h2`,{children:f}),(0,N.jsx)(`div`,{"aria-hidden":`true`,className:`progress-track`,children:(0,N.jsx)(`div`,{className:`progress-fill`,style:{width:`${Math.max(p,m===`ready`?100:6)}%`}})}),(0,N.jsxs)(`p`,{children:[Math.round(p),`%`]}),u?(0,N.jsxs)(N.Fragment,{children:[(0,N.jsx)(`div`,{className:`error-banner`,role:`alert`,children:u}),(0,N.jsx)(`button`,{className:`primary-button`,onClick:()=>void d(),type:`button`,children:`Retry loading`})]}):null]})]}):null,e===`source`?(0,N.jsxs)(`main`,{className:`scene-shell`,children:[(0,N.jsx)(`div`,{className:`scene-header`,children:(0,N.jsx)(P,{})}),(0,N.jsxs)(`section`,{className:`source-card`,children:[(0,N.jsx)(`span`,{className:`eyebrow`,children:`Choose Input`}),(0,N.jsx)(`h2`,{children:`Caption a live camera or a local video file.`}),(0,N.jsx)(`p`,{children:`The model is ready. Pick a source and we'll start captioning each frame as quickly as the browser can process it.`}),(0,N.jsxs)(`div`,{className:`source-grid`,children:[(0,N.jsxs)(`button`,{className:`source-option`,onClick:()=>void _(),type:`button`,children:[(0,N.jsxs)(`div`,{className:`source-option__header`,children:[(0,N.jsx)(k,{className:`source-option__icon`,size:28,strokeWidth:1.9}),(0,N.jsx)(`strong`,{children:`Webcam`})]}),(0,N.jsx)(`span`,{children:`Start a live camera stream and caption it in real time.`})]}),(0,N.jsxs)(`button`,{className:`source-option`,onClick:v,type:`button`,children:[(0,N.jsxs)(`div`,{className:`source-option__header`,children:[(0,N.jsx)(A,{className:`source-option__icon`,size:28,strokeWidth:1.9}),(0,N.jsx)(`strong`,{children:`File`})]}),(0,N.jsx)(`span`,{children:`Upload a local clip and run the same caption loop against it.`})]})]}),o?(0,N.jsx)(`div`,{className:`error-banner`,role:`alert`,children:o}):null]})]}):null,e===`capture`&&n?(0,N.jsx)(se,{mediaError:o,onChooseVideo:v,onChooseWebcam:_,onDismissMediaError:()=>s(null),onExit:x,onPromptChange:a,prompt:i,promptPresets:JZ,source:n}):null]})}function QZ(){return(0,N.jsx)(qZ,{children:(0,N.jsx)(ZZ,{})})}(0,v.createRoot)(document.getElementById(`root`)).render((0,N.jsx)(y.StrictMode,{children:(0,N.jsx)(QZ,{})})); \ No newline at end of file diff --git a/dist/assets/index-BOaEXwaP.css b/dist/assets/index-BOaEXwaP.css new file mode 100644 index 0000000000000000000000000000000000000000..d503ebd567bf207e76450a008288bff7e44fe395 --- /dev/null +++ b/dist/assets/index-BOaEXwaP.css @@ -0,0 +1 @@ +@font-face{font-family:Sohne;font-style:normal;font-weight:400;src:url(/fonts/S%C3%B6hne/S%C3%B6hne-Buch.otf)format("opentype")}@font-face{font-family:Sohne;font-style:normal;font-weight:300;src:url(/fonts/S%C3%B6hne/S%C3%B6hne-Leicht.otf)format("opentype")}@font-face{font-family:Sohne;font-style:normal;font-weight:700;src:url(/fonts/S%C3%B6hne/S%C3%B6hne-Kr%C3%A4ftig.otf)format("opentype")}@font-face{font-family:JetBrains Mono;font-style:normal;font-weight:100 800;src:url(/fonts/JetBrains/JetBrainsMono-VariableFont_wght.ttf)format("truetype")}:root{--bg:#050814;--bg-soft:#080d19b8;--panel:#0a0f1cad;--panel-strong:#ffffff1f;--line:#ffffff1f;--line-strong:#ffffff38;--text:#f3f7ff;--text-soft:#f3f7ffb8;--text-muted:#f3f7ff8a;--accent:#9de0ff;--accent-strong:#d7f4ff;--shadow:0 28px 80px #02061159;--font-body:"Sohne", sans-serif;--font-mono:"JetBrains Mono", monospace}*{box-sizing:border-box}html,body,#root{min-height:100%}html{background:var(--bg)}body{background:var(--bg);color:var(--text);font-family:var(--font-body);font-synthesis:none;text-rendering:optimizelegibility;-moz-osx-font-smoothing:grayscale;-webkit-font-smoothing:antialiased;margin:0;overflow:hidden}button,input,textarea{color:inherit;font:inherit}button{cursor:pointer;border:0}img{max-width:100%;display:block}.hidden-file-input,.capture-canvas{display:none}.fluid-backdrop{background:#000;position:fixed;inset:0}.fluid-backdrop canvas{display:block}.fluid-backdrop__scene{opacity:0;width:100%;height:100%;transition:opacity .9s cubic-bezier(.16,1,.3,1),transform .9s cubic-bezier(.16,1,.3,1);transform:scale(1.02)}.fluid-backdrop__scene.is-ready{opacity:1;transform:scale(1)}.fluid-backdrop__veil{pointer-events:none;background:0 0;transition:background-color .32s;position:absolute;inset:0}.fluid-backdrop__veil.is-subdued{background:#03071042}.landing-scene,.scene-shell,.capture-scene{z-index:1;position:relative}.landing-scene{text-align:left;background:0 0;width:100%;min-height:100vh;padding:28px}.landing-inner{flex-direction:column;justify-content:space-between;gap:32px;width:min(1120px,100%);min-height:calc(100vh - 56px);margin:0 auto;display:flex}.brand-mark{border:1px solid var(--line);width:fit-content;box-shadow:var(--shadow);-webkit-backdrop-filter:blur(18px);background:#070b168a;border-radius:999px;align-items:center;gap:14px;padding:11px 17px 11px 11px;display:inline-flex}.brand-logo{object-fit:contain;width:36px;height:36px}.brand-copy{flex-direction:column;gap:3px;display:flex}.brand-copy span{color:var(--text-muted);font-family:var(--font-mono);letter-spacing:.18em;text-transform:uppercase;font-size:.7rem}.brand-copy strong{letter-spacing:.01em;font-size:.95rem;font-weight:700}.hero-copy{max-width:760px}.eyebrow,.dock-label{color:var(--accent);font-family:var(--font-mono);letter-spacing:.22em;text-transform:uppercase;font-size:.73rem;display:inline-block}.hero-copy h1,.loading-card h2,.source-card h2{letter-spacing:-.06em;margin:18px 0 0;font-size:clamp(3.4rem,9vw,7.8rem);font-weight:700;line-height:.95}.hero-copy p,.source-card p{max-width:620px;color:var(--text-soft);margin:20px 0 0;font-size:clamp(1.05rem,2.6vw,1.42rem);line-height:1.5}.hero-inline-icon{vertical-align:text-bottom;width:1.6rem;height:1.6rem;margin:0 .25rem 1px .35rem;display:inline-block}.hero-inline-wordmark{display:inline-block}.begin-prompt{border:1px solid var(--line-strong);width:fit-content;color:var(--accent-strong);letter-spacing:.02em;-webkit-backdrop-filter:blur(16px);background:#ffffff14;border-radius:999px;align-items:center;gap:12px;margin:0 auto;padding:14px 20px;font-size:.96rem;display:inline-flex}.scene-shell{flex-direction:column;justify-content:center;width:100%;min-height:100vh;padding:28px;display:flex}.scene-shell--centered{align-items:center;gap:28px}.scene-header{position:absolute;top:28px;left:28px}.loading-card,.source-card,.prompt-dock,.floating-alert{border:1px solid var(--line);background:var(--panel);box-shadow:var(--shadow);-webkit-backdrop-filter:blur(24px)}.loading-card{border-radius:32px;width:min(520px,100%);padding:30px}.loading-card h2{margin-top:16px;font-size:clamp(2.3rem,6vw,4.3rem)}.loading-card p{color:var(--text-soft);font-family:var(--font-mono);margin:16px 0 0;font-size:.9rem}.progress-track{background:#ffffff14;border-radius:999px;width:100%;height:12px;margin-top:24px;overflow:hidden}.progress-fill{border-radius:inherit;background:linear-gradient(90deg,#80deffcc,#f5fbfffa);height:100%;box-shadow:0 0 40px #9ce4ff66}.source-card{border-radius:36px;width:min(860px,100%);margin:0 auto;padding:32px}.source-card h2{margin-top:16px;font-size:clamp(2.2rem,5vw,4.8rem)}.source-grid{grid-template-columns:repeat(2,minmax(0,1fr));gap:16px;margin-top:30px;display:grid}.source-option,.ghost-button,.primary-button,.prompt-chip{transition:transform .18s,border-color .18s,background-color .18s,opacity .18s}.source-option{border:1px solid var(--line);text-align:left;background:#ffffff0d;border-radius:28px;flex-direction:column;justify-content:space-between;gap:8px;padding:26px;display:flex}.source-option strong{letter-spacing:-.02em;font-size:1.45rem;font-weight:700}.source-option__header{align-items:center;gap:14px;display:inline-flex}.source-option__icon,.button-icon{color:var(--accent)}.source-option span{color:var(--text-soft);font-size:1.06rem;line-height:1.5}.source-option:hover,.ghost-button:hover,.primary-button:hover,.prompt-chip:hover{transform:translateY(-2px)}.capture-scene{background:#03050a;min-height:100vh;overflow:hidden}.capture-video,.capture-scrim{position:absolute;inset:0}.capture-video{object-fit:cover;width:100%;height:100%}.capture-scrim{background:linear-gradient(#03050a26,#03050a47 36%,#03050aad),radial-gradient(circle at 0 0,#92dcff33,#0000 34%),radial-gradient(circle at 100% 100%,#ffffff17,#0000 24%)}.capture-toolbar{z-index:2;justify-content:space-between;gap:16px;padding:24px;display:flex;position:relative}.capture-toolbar__left{flex-wrap:wrap;align-items:center;gap:14px;display:flex}.status-pill,.ghost-button,.primary-button{border:1px solid var(--line);-webkit-backdrop-filter:blur(16px);background:#080d1870;border-radius:999px;align-items:center;gap:10px;padding:12px 16px;display:inline-flex}.button-icon{flex-shrink:0}.status-pill{color:var(--text-soft);font-family:var(--font-mono);letter-spacing:.08em;text-transform:uppercase;font-size:.78rem}.status-dot{background:#ffffff4d;border-radius:999px;width:8px;height:8px}.status-dot.is-live{background:#9ce5ff;box-shadow:0 0 16px #9ce5ffb3}.toolbar-actions{flex-wrap:wrap;justify-content:flex-end;gap:10px;display:flex}.ghost-button{color:var(--text)}.ghost-button--small{padding:8px 12px}.primary-button{background:#ffffff1f;width:fit-content;margin-top:18px}.floating-alert{z-index:3;border-radius:20px;align-items:center;gap:14px;max-width:min(620px,100vw - 48px);padding:14px 16px;display:inline-flex;position:absolute;top:96px;left:24px}.floating-alert--secondary{top:156px}.error-banner{color:#ffd9d9;background:#ff787814;border:1px solid #ffa0a04d;border-radius:18px;margin-top:18px;padding:14px 16px;line-height:1.5}.prompt-dock,.capture-side-rail{z-index:2;position:absolute;bottom:24px}.prompt-dock{border-radius:30px;width:min(520px,100vw - 48px);padding:18px;left:24px}.prompt-chip-row{flex-wrap:wrap;gap:10px;margin:14px 0 16px;display:flex}.prompt-chip{border:1px solid var(--line);color:var(--text-soft);background:#ffffff0d;border-radius:999px;padding:10px 14px}.prompt-chip.is-active{color:var(--accent-strong);background:#9de0ff24;border-color:#9de0ff6b}.prompt-input{border:1px solid var(--line);width:100%;min-height:78px;color:var(--text);resize:none;background:#ffffff0a;border-radius:20px;padding:14px 16px;line-height:1.5}.prompt-input::placeholder{color:var(--text-muted)}.prompt-input:focus{border-color:#9de0ff70;outline:1px solid #9de0ff70}.capture-side-rail{flex-direction:column;gap:14px;width:min(400px,100vw - 48px);display:flex;right:24px}.capture-actions{z-index:4;pointer-events:auto;flex-wrap:wrap;justify-content:flex-end;gap:10px;display:flex;position:fixed;top:24px;right:24px}.caption-dock{flex-direction:column;align-items:stretch;gap:12px;width:100%;display:flex}.caption-bubble{color:#07101b;border-radius:30px 30px 12px;width:100%;padding:16px 18px;line-height:1.48;box-shadow:0 20px 48px #0307113d}.caption-bubble--history{background:#ffffffc7}.caption-bubble--active{background:#fffffffa;min-height:74px}.caption-meta{color:#07101b8a;font-family:var(--font-mono);letter-spacing:.18em;text-transform:uppercase;margin-bottom:8px;font-size:.72rem}.caption-placeholder{color:#07101b80}@media (width<=900px){body{overflow:auto}.landing-scene,.scene-shell{padding:22px}.landing-inner{min-height:calc(100vh - 44px)}.source-grid{grid-template-columns:1fr}.capture-toolbar{flex-direction:column;align-items:flex-start}.prompt-dock,.capture-side-rail{width:auto;margin:0 22px 22px;position:relative;bottom:auto;left:auto;right:auto}.capture-actions{justify-content:flex-start;top:22px;left:22px;right:22px}.capture-scene{flex-direction:column;justify-content:flex-end;min-height:100dvh;display:flex}.capture-scrim{background:linear-gradient(#03050a33,#03050a6b 42%,#03050ad6),radial-gradient(circle at 0 0,#92dcff2e,#0000 30%)}}@media (width<=640px){.hero-copy h1,.loading-card h2,.source-card h2{letter-spacing:-.05em}.floating-alert{flex-direction:column;align-items:flex-start;inset:auto 22px 22px}.floating-alert--secondary{bottom:96px}} diff --git a/dist/fonts/JetBrains/JetBrainsMono-Italic-VariableFont_wght.ttf b/dist/fonts/JetBrains/JetBrainsMono-Italic-VariableFont_wght.ttf new file mode 100644 index 0000000000000000000000000000000000000000..d8a9eaa68dc66c1e108571a2bebf6ae11879542a --- /dev/null +++ b/dist/fonts/JetBrains/JetBrainsMono-Italic-VariableFont_wght.ttf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d2a1563e89aa3c3816abfbca03e295abcdca11d9cbd689a7754cc1c5f454d18f +size 191988 diff --git a/dist/fonts/JetBrains/JetBrainsMono-VariableFont_wght.ttf b/dist/fonts/JetBrains/JetBrainsMono-VariableFont_wght.ttf new file mode 100644 index 0000000000000000000000000000000000000000..8d80506ef6e61067e429bb8e8d731b04a7a94ad9 --- /dev/null +++ b/dist/fonts/JetBrains/JetBrainsMono-VariableFont_wght.ttf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b6490e1a902e56fc84050bee9aad91509e6f45aa00f96f882dab53c9abaf83eb +size 187860 diff --git "a/dist/fonts/S\303\266hne/S\303\266hne-Buch.otf" "b/dist/fonts/S\303\266hne/S\303\266hne-Buch.otf" new file mode 100644 index 0000000000000000000000000000000000000000..0a2f37c614c67c1c021359717c184674c4498640 --- /dev/null +++ "b/dist/fonts/S\303\266hne/S\303\266hne-Buch.otf" @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d3e050e7df5a5695e1ba1691633f2a8767ea9c6ac747fccf7b23a38e4ca02cc2 +size 191552 diff --git "a/dist/fonts/S\303\266hne/S\303\266hne-Kr\303\244ftig.otf" "b/dist/fonts/S\303\266hne/S\303\266hne-Kr\303\244ftig.otf" new file mode 100644 index 0000000000000000000000000000000000000000..68b449d7c171130db287eda022cb19fa26c2770d --- /dev/null +++ "b/dist/fonts/S\303\266hne/S\303\266hne-Kr\303\244ftig.otf" @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7f17003124700a22684c3f83ac8252793f1e6e902842e385d4bd4220f94a79cb +size 245976 diff --git "a/dist/fonts/S\303\266hne/S\303\266hne-Leicht.otf" "b/dist/fonts/S\303\266hne/S\303\266hne-Leicht.otf" new file mode 100644 index 0000000000000000000000000000000000000000..c0444229a7a34c237d17114bbd7f5ccff10223e8 --- /dev/null +++ "b/dist/fonts/S\303\266hne/S\303\266hne-Leicht.otf" @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:366970f59ef3332afd6d0a2a5bc84e71c002c2a351a93a8a66f315e5892be028 +size 191884 diff --git a/dist/index.html b/dist/index.html new file mode 100644 index 0000000000000000000000000000000000000000..ba214ce2d2101c56e56a8f86d990849039639530 --- /dev/null +++ b/dist/index.html @@ -0,0 +1,17 @@ + + + + + + + lfm2-vl-webgpu + + + + +
+ + diff --git a/dist/liquid.svg b/dist/liquid.svg new file mode 100644 index 0000000000000000000000000000000000000000..91f23296297b42ee1be8e54ef12b8cb16ee12534 --- /dev/null +++ b/dist/liquid.svg @@ -0,0 +1,11 @@ + + + + + + + + + + + diff --git a/dist/logo-dark.webp b/dist/logo-dark.webp new file mode 100644 index 0000000000000000000000000000000000000000..fc243dac9199acdda0ac05f9ded0b2ce231212fb Binary files /dev/null and b/dist/logo-dark.webp differ diff --git a/dist/logo-light.webp b/dist/logo-light.webp new file mode 100644 index 0000000000000000000000000000000000000000..09ac9c221eddeeeb2924bb1c4db52fddc8be3ebe Binary files /dev/null and b/dist/logo-light.webp differ diff --git a/eslint.config.js b/eslint.config.js new file mode 100644 index 0000000000000000000000000000000000000000..2acdced6dd1710b2540a3fa68ac9adb8bfba15a5 --- /dev/null +++ b/eslint.config.js @@ -0,0 +1,23 @@ +import js from "@eslint/js"; +import globals from "globals"; +import reactHooks from "eslint-plugin-react-hooks"; +import reactRefresh from "eslint-plugin-react-refresh"; +import tseslint from "typescript-eslint"; +import { defineConfig, globalIgnores } from "eslint/config"; + +export default defineConfig([ + globalIgnores(["dist", "src/react-fluid-distortion/**"]), + { + files: ["**/*.{ts,tsx}"], + extends: [ + js.configs.recommended, + tseslint.configs.recommended, + reactHooks.configs.flat.recommended, + reactRefresh.configs.vite, + ], + languageOptions: { + ecmaVersion: 2020, + globals: globals.browser, + }, + }, +]); diff --git a/index.html b/index.html index b0c4b3666032a737f3903db53e6a8a9272483e28..642b4d43c02921d44ceb0ba5c53a4a4c9a4798d7 100644 --- a/index.html +++ b/index.html @@ -1,19 +1,16 @@ - - - - - My static Space - - - -
-

Welcome to your static Space!

-

You can modify this app directly by editing index.html in the Files and versions tab.

-

- Also don't forget to check the - Spaces documentation. -

-
- + + + + + + lfm2-vl-webgpu + + +
+ + diff --git a/package.json b/package.json new file mode 100644 index 0000000000000000000000000000000000000000..4b72002e3a315c27b925acfc2123085c39bcf489 --- /dev/null +++ b/package.json @@ -0,0 +1,38 @@ +{ + "name": "lfm2-vl-webgpu", + "private": true, + "version": "0.0.0", + "type": "module", + "scripts": { + "dev": "vite", + "build": "tsc -b && vite build", + "lint": "eslint .", + "preview": "vite preview" + }, + "dependencies": { + "@huggingface/transformers": "^4.0.0-next.7", + "@react-three/drei": "^10.7.7", + "@react-three/postprocessing": "^3.0.4", + "lucide-react": "^0.577.0", + "postprocessing": "^6.38.3", + "react": "^19.2.0", + "react-dom": "^19.2.0" + }, + "devDependencies": { + "@eslint/js": "^9.39.1", + "@types/node": "^24.10.1", + "@types/react": "^19.2.7", + "@types/react-dom": "^19.2.3", + "@vitejs/plugin-react": "^5.1.1", + "eslint": "^9.39.1", + "eslint-plugin-react-hooks": "^7.0.1", + "eslint-plugin-react-refresh": "^0.4.24", + "globals": "^16.5.0", + "typescript": "~5.9.3", + "typescript-eslint": "^8.48.0", + "vite": "^8.0.0-beta.13" + }, + "overrides": { + "vite": "^8.0.0-beta.13" + } +} diff --git a/public/fonts/JetBrains/JetBrainsMono-Italic-VariableFont_wght.ttf b/public/fonts/JetBrains/JetBrainsMono-Italic-VariableFont_wght.ttf new file mode 100644 index 0000000000000000000000000000000000000000..d8a9eaa68dc66c1e108571a2bebf6ae11879542a --- /dev/null +++ b/public/fonts/JetBrains/JetBrainsMono-Italic-VariableFont_wght.ttf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d2a1563e89aa3c3816abfbca03e295abcdca11d9cbd689a7754cc1c5f454d18f +size 191988 diff --git a/public/fonts/JetBrains/JetBrainsMono-VariableFont_wght.ttf b/public/fonts/JetBrains/JetBrainsMono-VariableFont_wght.ttf new file mode 100644 index 0000000000000000000000000000000000000000..8d80506ef6e61067e429bb8e8d731b04a7a94ad9 --- /dev/null +++ b/public/fonts/JetBrains/JetBrainsMono-VariableFont_wght.ttf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b6490e1a902e56fc84050bee9aad91509e6f45aa00f96f882dab53c9abaf83eb +size 187860 diff --git "a/public/fonts/S\303\266hne/S\303\266hne-Buch.otf" "b/public/fonts/S\303\266hne/S\303\266hne-Buch.otf" new file mode 100644 index 0000000000000000000000000000000000000000..0a2f37c614c67c1c021359717c184674c4498640 --- /dev/null +++ "b/public/fonts/S\303\266hne/S\303\266hne-Buch.otf" @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d3e050e7df5a5695e1ba1691633f2a8767ea9c6ac747fccf7b23a38e4ca02cc2 +size 191552 diff --git "a/public/fonts/S\303\266hne/S\303\266hne-Kr\303\244ftig.otf" "b/public/fonts/S\303\266hne/S\303\266hne-Kr\303\244ftig.otf" new file mode 100644 index 0000000000000000000000000000000000000000..68b449d7c171130db287eda022cb19fa26c2770d --- /dev/null +++ "b/public/fonts/S\303\266hne/S\303\266hne-Kr\303\244ftig.otf" @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7f17003124700a22684c3f83ac8252793f1e6e902842e385d4bd4220f94a79cb +size 245976 diff --git "a/public/fonts/S\303\266hne/S\303\266hne-Leicht.otf" "b/public/fonts/S\303\266hne/S\303\266hne-Leicht.otf" new file mode 100644 index 0000000000000000000000000000000000000000..c0444229a7a34c237d17114bbd7f5ccff10223e8 --- /dev/null +++ "b/public/fonts/S\303\266hne/S\303\266hne-Leicht.otf" @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:366970f59ef3332afd6d0a2a5bc84e71c002c2a351a93a8a66f315e5892be028 +size 191884 diff --git a/public/liquid.svg b/public/liquid.svg new file mode 100644 index 0000000000000000000000000000000000000000..91f23296297b42ee1be8e54ef12b8cb16ee12534 --- /dev/null +++ b/public/liquid.svg @@ -0,0 +1,11 @@ + + + + + + + + + + + diff --git a/public/logo-dark.webp b/public/logo-dark.webp new file mode 100644 index 0000000000000000000000000000000000000000..fc243dac9199acdda0ac05f9ded0b2ce231212fb Binary files /dev/null and b/public/logo-dark.webp differ diff --git a/public/logo-light.webp b/public/logo-light.webp new file mode 100644 index 0000000000000000000000000000000000000000..09ac9c221eddeeeb2924bb1c4db52fddc8be3ebe Binary files /dev/null and b/public/logo-light.webp differ diff --git a/src/App.tsx b/src/App.tsx new file mode 100644 index 0000000000000000000000000000000000000000..9f8e6f1be226f5ff08ce2c829ad5fb6e1c8edd32 --- /dev/null +++ b/src/App.tsx @@ -0,0 +1,326 @@ +import { startTransition, useEffect, useRef, useState } from "react"; +import { Camera, Film } from "lucide-react"; +import { BrandMark } from "./components/BrandMark"; +import { CaptureScene, type CaptureSource } from "./components/CaptureScene"; +import { FluidBackdrop } from "./components/FluidBackdrop"; +import { HfIcon } from "./components/HfIcon"; +import { VLMProvider } from "./context/VLMProvider"; +import { useVLM } from "./context/VLMContext"; + +const PROMPT_PRESETS = [ + { + display: "Describe the scene", + prompt: "Describe the scene in one sentence.", + }, + { + display: "What color shirt am I wearing?", + prompt: "What color shirt am I wearing?", + }, + { + display: "What am I holding?", + prompt: "What am I holding?", + }, + { + display: "How old do I look?", + prompt: "How old do I look?", + }, +] as const; + +type Scene = "landing" | "loading" | "source" | "capture"; + +function disposeSource(source: CaptureSource | null) { + if (!source) { + return; + } + + if (source.kind === "webcam") { + source.stream.getTracks().forEach((track) => track.stop()); + return; + } + + URL.revokeObjectURL(source.url); +} + +function getErrorMessage(error: unknown) { + if (error instanceof Error) { + return error.message; + } + + return "Something went wrong."; +} + +function AppContent() { + const [scene, setScene] = useState("landing"); + const [source, setSource] = useState(null); + const [prompt, setPrompt] = useState(PROMPT_PRESETS[0].prompt); + const [mediaError, setMediaError] = useState(null); + const fileInputRef = useRef(null); + const sourceRef = useRef(null); + + const { error, loadModel, message, progress, status } = useVLM(); + + useEffect(() => { + sourceRef.current = source; + }, [source]); + + useEffect(() => { + return () => { + disposeSource(sourceRef.current); + }; + }, []); + + useEffect(() => { + if (scene !== "loading" || status === "ready") { + return; + } + + let cancelled = false; + + void loadModel() + .then(() => { + if (cancelled) { + return; + } + + startTransition(() => { + setScene("source"); + }); + }) + .catch(() => undefined); + + return () => { + cancelled = true; + }; + }, [loadModel, scene, status]); + + const beginExperience = () => { + startTransition(() => { + setScene("loading"); + }); + }; + + const replaceSource = (nextSource: CaptureSource) => { + disposeSource(source); + setMediaError(null); + setSource(nextSource); + + startTransition(() => { + setScene("capture"); + }); + }; + + const handleUseWebcam = async () => { + try { + if (!navigator.mediaDevices?.getUserMedia) { + throw new Error("Camera access is not available in this browser."); + } + + const stream = await navigator.mediaDevices.getUserMedia({ + audio: false, + video: { + facingMode: "user", + width: { ideal: 1280 }, + height: { ideal: 720 }, + }, + }); + + replaceSource({ + kind: "webcam", + label: "Live camera", + stream, + }); + } catch (cameraError) { + setMediaError(getErrorMessage(cameraError)); + } + }; + + const openVideoPicker = () => { + fileInputRef.current?.click(); + }; + + const handleVideoSelection = (event: React.ChangeEvent) => { + const file = event.target.files?.[0]; + event.target.value = ""; + + if (!file) { + return; + } + + replaceSource({ + kind: "file", + label: file.name, + url: URL.createObjectURL(file), + }); + }; + + const exitCapture = () => { + disposeSource(source); + setSource(null); + setMediaError(null); + + startTransition(() => { + setScene("source"); + }); + }; + + const showBackdrop = scene !== "capture"; + + return ( + <> + {showBackdrop ? : null} + + + + {scene === "landing" ? ( + + ) : null} + + {scene === "loading" ? ( +
+ + +
+ Loading Model +

{message}

+
+
+ ) : null} + + {scene === "source" ? ( +
+
+ +
+ +
+ Choose Input +

Caption a live camera or a local video file.

+

+ The model is ready. Pick a source and we'll start captioning + each frame as quickly as the browser can process it. +

+ +
+ + + +
+ + {mediaError ? ( +
+ {mediaError} +
+ ) : null} +
+
+ ) : null} + + {scene === "capture" && source ? ( + setMediaError(null)} + onExit={exitCapture} + onPromptChange={setPrompt} + prompt={prompt} + promptPresets={PROMPT_PRESETS} + source={source} + /> + ) : null} + + ); +} + +function App() { + return ( + + + + ); +} + +export default App; diff --git a/src/components/BrandMark.tsx b/src/components/BrandMark.tsx new file mode 100644 index 0000000000000000000000000000000000000000..920b7838314d3882afbeb2610690ba7c77ce05dd --- /dev/null +++ b/src/components/BrandMark.tsx @@ -0,0 +1,11 @@ +export function BrandMark() { + return ( +
+ Liquid AI icon +
+ Liquid AI + LFM2-VL WebGPU +
+
+ ); +} diff --git a/src/components/CaptureScene.tsx b/src/components/CaptureScene.tsx new file mode 100644 index 0000000000000000000000000000000000000000..95ddbb4c06667cfdaacf0fd359a2fa8c44bd24c9 --- /dev/null +++ b/src/components/CaptureScene.tsx @@ -0,0 +1,419 @@ +import { + startTransition, + useDeferredValue, + useEffect, + useEffectEvent, + useRef, + useState, +} from "react"; +import { ArrowLeft, Camera, Film, Pause, Play } from "lucide-react"; +import { BrandMark } from "./BrandMark"; +import { useVLM } from "../context/VLMContext"; + +export type CaptureSource = + | { + kind: "webcam"; + label: string; + stream: MediaStream; + } + | { + kind: "file"; + label: string; + url: string; + }; + +type CaptionEntry = { + id: string; + text: string; +}; + +type CaptureSceneProps = { + mediaError: string | null; + onChooseVideo: () => void; + onChooseWebcam: () => Promise; + onDismissMediaError: () => void; + onExit: () => void; + onPromptChange: (prompt: string) => void; + prompt: string; + promptPresets: readonly { + display: string; + prompt: string; + }[]; + source: CaptureSource; +}; + +const CAPTION_LIMIT = 4; + +function wait(milliseconds: number) { + return new Promise((resolve) => { + window.setTimeout(resolve, milliseconds); + }); +} + +function createCaptionId() { + return ( + globalThis.crypto?.randomUUID?.() ?? + `caption-${Date.now()}-${Math.random()}` + ); +} + +function normalizePrompt(text: string) { + return text.replace(/\s+/g, " ").trim(); +} + +function getErrorMessage(error: unknown) { + if (error instanceof Error) { + return error.message; + } + + return "Something went wrong while captioning the current frame."; +} + +export function CaptureScene({ + mediaError, + onChooseVideo, + onChooseWebcam, + onDismissMediaError, + onExit, + onPromptChange, + prompt, + promptPresets, + source, +}: CaptureSceneProps) { + const { generateCaption } = useVLM(); + const videoRef = useRef(null); + const canvasRef = useRef(null); + const loopIdRef = useRef(0); + + const [activeCaption, setActiveCaption] = useState(""); + const [captionHistory, setCaptionHistory] = useState([]); + const [isGenerating, setIsGenerating] = useState(false); + const [isPaused, setIsPaused] = useState(false); + const [runtimeError, setRuntimeError] = useState(null); + const [videoReady, setVideoReady] = useState(false); + + const deferredPrompt = useDeferredValue( + normalizePrompt(prompt) || promptPresets[0].prompt, + ); + + useEffect(() => { + const video = videoRef.current; + if (!video) { + return; + } + + setVideoReady(false); + setRuntimeError(null); + + if (source.kind === "webcam") { + video.srcObject = source.stream; + video.removeAttribute("src"); + void video.play().catch(() => undefined); + + return () => { + video.pause(); + video.srcObject = null; + }; + } + + video.srcObject = null; + video.src = source.url; + video.load(); + void video.play().catch(() => undefined); + + return () => { + video.pause(); + video.removeAttribute("src"); + video.load(); + }; + }, [source]); + + useEffect(() => { + setCaptionHistory([]); + setActiveCaption(""); + setIsGenerating(false); + setIsPaused(false); + }, [source]); + + useEffect(() => { + if (!isPaused) { + return; + } + + setActiveCaption(""); + setIsGenerating(false); + }, [isPaused]); + + const handleCanPlay = () => { + setVideoReady(true); + void videoRef.current?.play().catch(() => undefined); + }; + + const captureFrame = useEffectEvent(() => { + const video = videoRef.current; + const canvas = canvasRef.current; + + if ( + !video || + !canvas || + !videoReady || + video.paused || + video.ended || + video.readyState < HTMLMediaElement.HAVE_CURRENT_DATA || + video.videoWidth === 0 || + video.videoHeight === 0 + ) { + return null; + } + + const maxDimension = 960; + const scale = Math.min( + 1, + maxDimension / Math.max(video.videoWidth, video.videoHeight), + ); + const width = Math.max(1, Math.round(video.videoWidth * scale)); + const height = Math.max(1, Math.round(video.videoHeight * scale)); + + if (canvas.width !== width) { + canvas.width = width; + } + + if (canvas.height !== height) { + canvas.height = height; + } + + const context = canvas.getContext("2d", { willReadFrequently: true }); + if (!context) { + return null; + } + + context.drawImage(video, 0, 0, width, height); + return context.getImageData(0, 0, width, height); + }); + + const runCaptionPass = useEffectEvent(async (loopId: number) => { + if (isPaused) { + await wait(120); + return; + } + + const frame = captureFrame(); + if (!frame) { + await wait(120); + return; + } + + setRuntimeError(null); + setIsGenerating(true); + setActiveCaption(""); + + try { + const finalCaption = await generateCaption({ + frame, + onStream: (text) => { + if (loopIdRef.current !== loopId) { + return; + } + + setActiveCaption(text); + }, + prompt: deferredPrompt, + }); + + if (loopIdRef.current !== loopId) { + return; + } + + const normalizedCaption = normalizePrompt(finalCaption); + if (normalizedCaption.length === 0) { + return; + } + + startTransition(() => { + setCaptionHistory((current) => { + if (current[0]?.text === normalizedCaption) { + return current; + } + + return [ + { id: createCaptionId(), text: normalizedCaption }, + ...current, + ].slice(0, CAPTION_LIMIT); + }); + }); + } catch (error) { + if (loopIdRef.current !== loopId) { + return; + } + + setRuntimeError(getErrorMessage(error)); + await wait(240); + } finally { + if (loopIdRef.current === loopId) { + setActiveCaption(""); + setIsGenerating(false); + } + } + }); + + useEffect(() => { + loopIdRef.current += 1; + const currentLoopId = loopIdRef.current; + let mounted = true; + + const loop = async () => { + while (mounted && loopIdRef.current === currentLoopId) { + await runCaptionPass(currentLoopId); + await wait(72); + } + }; + + void loop(); + + return () => { + mounted = false; + loopIdRef.current += 1; + }; + }, [source]); + + const displayedHistory = [...captionHistory].reverse(); + + return ( +
+