From ff6977c5748dd347d487395080b5546a29b9e834 Mon Sep 17 00:00:00 2001 From: lhy6305 Date: Fri, 18 Apr 2025 09:42:30 +0800 Subject: [PATCH] git auto update --- .gitignore | 2 + assets/sprite-note-iceball.png | Bin 0 -> 2457 bytes assets/sprite-note-meteor.png | Bin 0 -> 3144 bytes assets/sprite-player.png | Bin 0 -> 1859 bytes css/main.css | 14 + index.html | 9 + js/0-fconsole.js | 36 + js/0-jsloadentry.js | 19 + js/0-jsloader.js | 52 ++ js/js2min.bat | 20 + js/libcubicbezier.js | 1 + js/libpixi_v891uni.min.js | 911 ++++++++++++++++++++++++ js/libpolyfill.requestAnimationFrame.js | 30 + js/libtransition.js | 120 ++++ js/libutil.js | 24 + 15 files changed, 1238 insertions(+) create mode 100644 .gitignore create mode 100644 assets/sprite-note-iceball.png create mode 100644 assets/sprite-note-meteor.png create mode 100644 assets/sprite-player.png create mode 100644 css/main.css create mode 100644 index.html create mode 100644 js/0-fconsole.js create mode 100644 js/0-jsloadentry.js create mode 100644 js/0-jsloader.js create mode 100644 js/js2min.bat create mode 100644 js/libcubicbezier.js create mode 100644 js/libpixi_v891uni.min.js create mode 100644 js/libpolyfill.requestAnimationFrame.js create mode 100644 js/libtransition.js create mode 100644 js/libutil.js diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..11c12b8 --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +/*.bat +/*.sh diff --git a/assets/sprite-note-iceball.png b/assets/sprite-note-iceball.png new file mode 100644 index 0000000000000000000000000000000000000000..3345f053787f13565063987929b6ee9677e2f30f GIT binary patch literal 2457 zcmV;K31;?*P)Px;Q%OWYRCt{2UAs;tM-c6?*_0RwQhvY)f{h$IV!wa@SvcTxHt-5LxPQPWI9|jT zkb<-^>0*t8b$iR@epFRgcURBtBO&f%reCM(RCQ0!T<0bxCMG5(CMG5(CMG5(CMG5( zCMG5(CMG5}i=}r1M!>_<+v=Qi=cfn7 z<8BX+96ZjyhxJP2y=6!+YXB)vpm;aO#uQwWy;NQ8S58i7P2=65L+mrBzX@{Z)+?W(*Q^ELnz5zY8gRy z1ArZi8GwJCi}fF0zlh1nfs#LjkZMoNAS|sDR0SLW{2Km+j=_);)B~`soDfoD<+7VK zr851HBBZPzPs2*uR9Z#~I8WJ~oh)3h-h>L^fySPWKMQ^Dq2c+d@@vAky|)T91*HSE z$&ZDY9@r}*ppx(Z!`JvYF8Njn58>+Znbj_feaNCU`I>`teYaL0aIO&y1+I0cGXK`( zw*og54An=eyzLA59uyU@8pfh1iEZ$Gh`^NJT! zv7(pc% z$^cSRx10gABHxtl@iTstk4%sHWOs;0LXOF!097)FuYJdDFvpma_o@67k2c%h($y{sHX&Fq=WB z-X9AaCCQ%Tyb@^F8OoJvsX!G4fZLrY$HN;pB-^C+1(NOZIaCV)9w{wGMsCrkbVJ1T-5Q;OeR{cE{hze_6u2RPyU>NlP;*9bP+EWny!77+I`o~?56(H~ z-e*YGG=iJs`$e)Nd3ScgIxnRHrHWZS1UMIN;F8vRsN0B97cP@oa3@r52(=Ez}%3N0sUG7WSt?fqP2i@ zU2}l&d4R?>fvQWvxdye2`!TZp=kE?bHzU?U_V1yV1H@DTdVdMwrGxhF@bi))`RnV& zDp7>dp<)1`O`W+=(JSlEdHTpkAekbnPXi(GI63s-lHWoyy+X7M1s1?E0BQmVFIiee zFQP5Qf9DhwK(ZgMr}uw-y;w2%Tkv}CnA{m!m6bpri_T9E7XJeb7Owwe@^i$GbX8Fb z6$3~;x4$F|XnTK%@RSi~8>?o2w5|y>yBg?Rd_d>D0Oc^XBgpUgEkVj#_CcCkp@{<2 znDbj$lI5UQ_P;wjSw6mg5nmLlW&kCd9dq7q^}-Qh#8Y!pS=;+1<>&SYXv_a_JA!JWXD$$`do&d&+7_-Ik13vFWpHnf@0XD`qr^bLe0r+~p0KCYPI)+o`!_(XP`=37+ zJ<+RXJTCEYsA?f^w~)^iD?sUD#QEvLBDv9HcXqPCr-9Ux{FGr)>Ws;}W&(YCc;sBG z1u}da7kn&i>>T(UApG6+-70?UnFS9@A!gVb&k*+S@gsS;P`w-+0)<%VI=1CGxApAb zqsc-Ld=v^K3=fjk$DwH&nN<37xtCP_iwyuKh9QZfdiVM1!6H$D7Al|_TeZs4+Cx!f z0I7!?;RafkYwMtp-E3@Q&jrdITLD5+Pn`-D%2mBFBm^He-hO%selJ~D*jk8bwNFy@-aswy9qs|i02wS|a8sR;-Pb{=y|-Gn+yo zs1_`FIO0}-`|ioijU60|?h8RF>|0VOP5vP9oK;hP3zfl*ddXcz%UvMqGHC;3|P zuL`S1U}cR!NuD;#j@>oFKDydM&e=lo_3z`6ED;LEc-C=&AFxj6gRY+Dsj z2#IZQEUmZX{2Jg+T~oiDUZa0i7Zh?=t3uyvT;Yn{bcK*j%Sl2^uG{+bZE0d(lY`sc}q9OiWBnOiWBnOiWBnYy^J; Xm7{3^c{#5J00000NkvXXu0mjf2v3R% literal 0 HcmV?d00001 diff --git a/assets/sprite-note-meteor.png b/assets/sprite-note-meteor.png new file mode 100644 index 0000000000000000000000000000000000000000..6ced2cdcefe6e37008a592aaef7e126b4547730a GIT binary patch literal 3144 zcmV-O47c-%P)Px>0!c(cRCt{2T|06dyAH*;o>G_hq1=i0;T1S^Ag#dV71)78uR!}y;#~VsIaQz+ z=t9C^01zO-Pv6T^mszp@gXW)rX?P+&LLkFM)~K74rne0z5<^7O~&PtV$KGqD^& zv+(@=`oc<2-yUB1gGwO@QM#8Z1>U!!5-df`NN_9X0^^7Xjw{6J+rx>6fmIaYf3pb~ z1ug&-JX(3CbyCj(fC}+=)>lS98CXIKdqA@|v`(*!wp@P{)H84;nS~{Y$bcsBsH@L_ zq%4%a+q?S{D#L6=IJ5$ArtMh3>IzDl|{5r(@*a zpm*(HX$7!i{LS?v{CxNz3LYTe(j&70=~_Db(2_*zrMyL`RxGOkmc^r$Ak(x;Tn58h zm>*RHDO72SkmVVcQ-G4y1HhT(1Atgyi86;XG}G!Lia^5wDmV9FnY2w;04=7{xDW8= z^6@u%zmy}i($d4-YKmYffi^?PQi3505J{XQfl5r`?Pds`(@@)9v_Bl5L_=1Wcf78pcw?>UkEqwvKKNMqZ?kAjM~UfF_||pEuxuJ?uFFJ3 z2@a_M9MtMPR*k>c4!-8T6_h|4bB2OWiyso<+MJ%=gUMh`mJd*$EA*U;OQ6|5uYE`f z;|Q8UC|NQ7Pc_`SzQyu0EqJ6i;5@6{@5FTK4;27CwUVfhxgr9>8PK5#dMs zUy2!tptB>(3rrn97bqu;5-cgo7JeC$5=hg-8MLVca7EC(1Y!&S5>g%j&{+X$;)_H~ zB#GI=*P-#TyBCO*PWj)|W$}bAL-?&U9|^SlO+U9Nz&p=Hw|Dm^T$$1u<`pR(&rjbT zPNfyS3{V=EtdKQ;R!FTSVt~u#^i-4@rj)0aNCTE8^QsG)szNM1l2yJxH}55VEk zu2Nke@#C|;-t7Sn-m{i({dN=}pQN2a0E4`q$HIDBzckIPrFjNgia3@BkovLOIy)TN zY9V;P_t+D+eod>jemr!qln?M2O}}4(K9`kvv`yNqAz7EWgmE{Ghj)zw=jFYwpZCX^b}n35s3@!!rfUM{G%n%R3wTw4 zT7s!X1C$R&@)JEZ{eAuY1ORX$;H&q4!~+vlG2T9xt-cl`gpZbwhGWgltb-)s5TFgr zBhVKDAE74k!~0)~Qg7c`E*OD|VbNa$DV+2czBG=X4VEF>EdUN_>qTb-TU0KiyQ$1gbm$9dIOuN36ewsk5?f zZ@*TO7Hu<2*}Fa_4hKvHpDBD#0@w>re?LC|`f>$0BhkRX9MH(?cs3BK=_Ly@t=K0%!z8+&?F1#Ix{v3P@_(6OvX& z(F0goRdWBcpMsf*)sj;z|4P5n<#zrX&r94Ppv8?JT@k48qkLFB5iBY|>jRj23|?BB zuSIF22e*>)KCuBg|v0SZ$~D2ytbdamPhc~093mLC-|&By5Tl)Z2(0QC^1GH|ct?^4iDue9Os7W1?{jT&kd zqQ?f*UZLqs0cLKi(qJWKd|P*ke(OL>sc-9kfTu1Aq=&{Y{Myt|k zCy!6Bg8BOUOt%uO1{(JM{q7pcJ9^X3P z7W!-N?X@p4qL8&v7lURif(JbqkK>*_cCR5&FDxbAB{^0v2U`a~Tb}ko2TfP%v=zHv zN^k@N;P5C6=dpV&z{8MeMXFSRlZ0DZ{>@Z~k+UMc=OD9BYaHQOfOi{rFXol@0=#^e zdGhzXt={JlYIxS|`2d}I+1 zNYP5VHnM_B@5PdP%NcJoE;jzEw%w^F7 zSlK^%gH}e<0eTj6YWfeK*_?%aSwT70R^v?ceu+Ull9@LpP@?q5UIegKIW=`kfW0-&W>?=mgk z=j~$#_;|d#l(e?c*oN)8LZM)1`~gMyUFn?wHU06vYuc*0F9V!z>F;QJoZl_4m96ps zH2I6%=k1H$OaDGvZJw8R0optjUH_*uu9h}K$HQq6h<}&)wvTMgTG-*qZL9Eat{*S> z+`6Bl`uPB~vr+=mO8~2T1WzvGt$RpE>_#5Cxd4Cp6MvJ1bWcsZYq`I*|CW9{eU+}k zcBGh}#pC8};WQ^`J*04CMCR|_>L0JPA~Ze^o$^YLhNZKBEDg=NH?s}iUQL_UJ$$Bx zpSjnKw5cKGU`V78G<&|DRUB%`>b3r{&712-xcO(jQvTaVSBhZ zUa0B4cA%}NAg}nej;`=YOY9lNrIZ|i?+2iSmo#{_1)E;b)&jIg=uq#8^?vTTmgO0r zua-i=?3m1H=rL2EpE1^Je34$j(Xtj|q08}bX@i3031)hMQDtIk@c?>gq~UagwRdB< zv{ekC{bA8Pkr7j^_9P?ViUDw*3oPsAEl@YdiyEcyutGR!Z9{U|(l{w^_!MyUb&d;2 zgXV*>K1cJ0UTE2KAmtHSJjcIh8$$ZD3gB`FF?D-VXpr0@*1^w+9rWD6NGRfCrh>x^ zUy9{cSR5G&yUlk2^w=l;4RFo~i3y_=LfXioK}sSuWuT~edTI~F=&EHj!O@Bwnj&}x zn-M0ke@)PyT}hX_rCvaV?s-vWX^o(VR~Y6}0qlbfw9+-w^?Q`a%F4MyNJ6LmWV|Ce z6GNvMlJ)Rc$!U26K+g0inp{Z=X@SRlYu>NT^G66CF@4SrAjd~3xhkE0@mQ+oph^jm zvv}6F?HU@hu|$!9=L%BJP^#EPEj0^V>9icdYGa1r5lbilh2-u_urhH(DZA$P@?_2H z9ir36$UQxPx*{YgYYRCt{2ox70~F%X7(C~!%DO8}dy4FUTyz$6H4f;f{5unB=GY!cuSSa*%V zV0CDE^lCl3rT(h6?rv{)Uj6sql14KFpeTx>D2k#eilQirq9}@@D2k#eiZU&~zx>!o zZ^J0I(Hk%tJNWOvel))>b6j4H-hh#q;G@7V6MTTh1pol>{_96O;LDbRRoUSj^c?`; zcD*bihGiY#9$=T{Z?KRPEGdAL?0)n1=eB|iEGYnhe*q5s`^5!j7r}A@2n7`VZ;Oaz z3RV+9G@FeGY%$F20Ph3jqALe^+2l?O!4L0oD<~DbRNCL%}wJm{k-jlz<%o zHk18^H*bG#=H>gM&-!O72`dPI%t~co_8m0Yf5_O>z}h0fC1VzWr~@p{%mOINe)CyR zV{xBlq;OUNm~s9SB|)>s2+TUfGot`rf?p#;LzzB<3(P2hAhjB9xLYZe*#uBE`)y`u z@w=F5rw(=BH_V&6@IV=W+w~$=AhS6D0JIsY3j|nX;0?0~z}xC~5fO;@e^RqN#0&z6 zT0g+?44~bgcYKsICCpl%$lkyV0!Rjl!{-{oK)PJu-W@F5x-m!>04e+N?*VcrhKh3m z$pR>;`=sw;u!tlN21yk_aschoI$|R(>H?1CiJMX`RRAXlSr`*fQV?Ckz!IH6q5yhi zzab~1MY(`90XTzC81*Zv{V^n-9Fisg5{20xCD0fY;{uWdkevNCXwauu84!aM0g!^{ zu;OL`#4cd1TZC{V2q1fQ4+;)7`wy3iL1HlR309OHIWxxH?S`JW` z<$<&eDK5ZO0A51b->4R6l>rAVT|k@wTm*)F0sbHOl5SwhcG$2J0Y?FlTmGFd)XbeS z#uAPKAkp}w54rp3X^Y@xvJnM00o2TXd$MNtemeKeH*gaG8Bd?zyjLsmc00m5&M)zf zBAf)!G_bovL zIBSDt0K0%=KUlZ`dja@J==OQV@bvt+o4}jDBg;yjD2m_X?gFd@ka_Te-?0O4<9g3S zR17{B;E2c@MMnDmNun{f9|*k9@?Gy8t~?@iS#w7ztHHqmvgZ0F5Iv}gS)Wy_@x6w* zx&Q|Okcb?}Xf_e7-bM2D2(I4&__YaG3LxboPs9itjRsP}9miP;ppf2TaFz&{3wQ)P zv^zLj0Hi`TJ zelC*F5@Hwdh`zgsh6|uD`#Fd}G$RBM4I0N<8G&@oAgBEs>Hrhfe*5>_v5e?4TF_en zwX(nFHGf^bjLX$>E zxx(;npn;hEl0$RrF3b!iCp5Wo&_eughVwdvBPywtQ% zygb`QVnQI#93Baa5|D`r#D?CZd^hEiFdTF&4sw?I9!l*f1I=Ba%auU|Q@vb-Mgb|q zt$2AUpLeaBMJDIc+5t}8wLkDlGZZUV@dB0X*3F_DK)HEjsC6u^$3rb$%w^nnK$-xlcN01_^c7)7Xu)T0bE z6Tt0yIRu;2IdBe`QPGs-X!%^?rsDvqJ2)$pN7~?H<@j!sUQiPUNZ6SvFn&1h&C<1(QzCYkFwF79CAAi#MxxVDZY_rss|GFF z0Nx + + + + + + +
+ \ No newline at end of file diff --git a/js/0-fconsole.js b/js/0-fconsole.js new file mode 100644 index 0000000..27029d8 --- /dev/null +++ b/js/0-fconsole.js @@ -0,0 +1,36 @@ +//fconsole.js + +(function() { + var do_loadfail=function(msg) { + var a=document.createElement("div"); + a.style.textAlign="center"; + a.style.display="inline-block"; + a.style.position="absolute"; + a.style.zIndex="999999"; + a.style.margin="auto"; + a.style.color="rgba("+0xff+","+0xff+","+0x00+",1)"; + a.style.width="100%"; + a.style.verticalAlign="middle"; + a.style.outline="none"; + a.style.top="20vh"; + a.style.fontSize="20px"; + a.style.lineHeight="25px"; + a.style.whiteSpace="pre"; + a.innerHTML="Fatal error: "+msg; + + document.body.innerHTML=""; + document.body.style.backgroundColor="rgba("+0x75+","+0x60+","+0x60+",1)"; + document.body.appendChild(a); + }; + + window.loadfail=function(msg) { + if(document.readyState=="complete") { + do_loadfail(msg); + } else { + window.addEventListener("load", function() { + do_loadfail(msg); + }); + } + }; + +})(); diff --git a/js/0-jsloadentry.js b/js/0-jsloadentry.js new file mode 100644 index 0000000..f6714e1 --- /dev/null +++ b/js/0-jsloadentry.js @@ -0,0 +1,19 @@ +//jsloadentry.js + +(async function() { + if(!(typeof scriptManager=="object"&&"loadjs" in scriptManager)) { + if(typeof loadfail=="function") { + loadfail("jsloadentry.js:scriptManager.loadjs is not defined"); + } else { + window.alert("jsloadentry.js:scriptManager.loadjs is not defined"); + } + return; + } + + scriptManager.loadjs("./js/libpolyfill.requestAnimationFrame.js"); + scriptManager.loadjs("./js/libutil.js"); + scriptManager.loadjs("./js/libcubicbezier.js"); + scriptManager.loadjs("./js/libpixi_v891uni.min.js"); + scriptManager.loadjs("./js/libtransition.js"); + await scriptManager.waitAll(); +})(); \ No newline at end of file diff --git a/js/0-jsloader.js b/js/0-jsloader.js new file mode 100644 index 0000000..150a185 --- /dev/null +++ b/js/0-jsloader.js @@ -0,0 +1,52 @@ +//jsloader.js + +(function() { + + var scriptManager= {}; + scriptManager.loadingcount=0; + + scriptManager.loadjs=async function(pth) { + var resolve; + var reject; + var ret=new Promise(function(s, r) { + resolve=s; + reject=r; + }); + var sc=document.createElement("script"); + sc.src=pth; + //sc.type="text/javascript"; + if(document.readyState=="complete") { + document.body.appendChild(sc); + } else { + window.addEventListener("load", function() { + document.body.appendChild(sc); + }); + } + + sc.addEventListener(("readyState" in sc?"readystatechange":"load"), function() { + console.info("script "+pth+" loaded successfully."); + scriptManager.loadingcount--; + resolve(); + }); + + sc.addEventListener("error", function() { + window.loadfail("script "+pth+" load failed"); + reject(); + }); + + scriptManager.loadingcount++; + + }; + + scriptManager.isDone=function() { + return scriptManager.loadingcount==0; + }; + + scriptManager.waitAll=async function() { + return new Promise(function(resolve, reject) { + + }); + }; + + window.scriptManager=scriptManager; +})(); diff --git a/js/js2min.bat b/js/js2min.bat new file mode 100644 index 0000000..b932c5a --- /dev/null +++ b/js/js2min.bat @@ -0,0 +1,20 @@ +@echo off +if %1 == "" ( +exit +) +cmd /c uglifyjs %1 -c -e -o temp.js + +cmd /c uglifyjs temp.js -c -e -o %~n1.min%~x1 +del /f /s /q temp.js +cmd /c uglifyjs %~n1.min%~x1 -c -e -o temp.js +del /f /s /q %~n1.min%~x1 +cmd /c uglifyjs temp.js -c -e -o %~n1.min%~x1 +del /f /s /q temp.js +cmd /c uglifyjs %~n1.min%~x1 -c -e -o temp.js +del /f /s /q %~n1.min%~x1 +cmd /c uglifyjs temp.js -c -e -o %~n1.min%~x1 +del /f /s /q temp.js +cmd /c uglifyjs %~n1.min%~x1 -c -e -o temp.js +del /f /s /q %~n1.min%~x1 +cmd /c uglifyjs temp.js -c -e -o %~n1.min%~x1 +del /f /s /q temp.js \ No newline at end of file diff --git a/js/libcubicbezier.js b/js/libcubicbezier.js new file mode 100644 index 0000000..f58bb73 --- /dev/null +++ b/js/libcubicbezier.js @@ -0,0 +1 @@ +!function(){function r(r,n){return 1-3*n+3*r}function n(r,n){return 3*n-6*r}function t(t,u,e){return((r(u,e)*t+n(u,e))*t+3*u)*t}function u(t,u,e){return 3*r(u,e)*t*t+2*n(u,e)*t+3*u}function e(r){return r}function Bezier(r,n,f,i){if(!(0<=r&&r<=1&&0<=f&&f<=1))throw new Error("Bezier x value must be in [0, 1] range");if(r===n&&f===i)return e;for(var a=new(o?Float32Array:Array)(11),c=0;c<11;++c)a[c]=t(.1*c,r,f);return function(e){return 0===e||1===e?e:t(function(n){for(var i,c,e=0,o=1;10!==o&&a[o]<=n;++o)e+=.1;return.001<=(c=u(i=e+(n-a[--o])/(a[o+1]-a[o])*.1,r,f))?function(r,n,e,o){for(var i,f=0;f<4;++f){if(0===(i=u(n,e,o)))return n;n-=(t(n,e,o)-r)/i}return n}(n,i,r,f):0===c?i:function(r,n,u,e,o){for(var f,i,a=0;0<(f=t(i=n+(u-n)/2,e,o)-r)?u=i:n=i,1e-7key in obj?__defProp$1d(obj,key,{enumerable:!0,configurable:!0,writable:!0,value:value}):obj[key]=value,__spreadValues$1d=(a,b)=>{for(var prop in b=b||{})__hasOwnProp$1d.call(b,prop)&&__defNormalProp$1d(a,prop,b[prop]);if(__getOwnPropSymbols$1d)for(var prop of __getOwnPropSymbols$1d(b))__propIsEnum$1d.call(b,prop)&&__defNormalProp$1d(a,prop,b[prop]);return a},ExtensionType2_ShapeBuilder="shape-builder";const normalizeExtension=ext=>{if("function"==typeof ext||"object"==typeof ext&&ext.extension){if(!ext.extension)throw new Error("Extension class must have an extension object");var metadata="object"!=typeof ext.extension?{type:ext.extension}:ext.extension,metadata=__spreadValues$1d({},metadata);ext=__defProps$r(metadata,__getOwnPropDescs$r({ref:ext}))}if("object"!=typeof ext)throw new Error("Invalid extension type");return"string"==typeof(ext=__spreadValues$1d({},ext)).type&&(ext.type=[ext.type]),ext},normalizeExtensionPriority=(ext,defaultPriority)=>null!=(ext=normalizeExtension(ext).priority)?ext:defaultPriority,extensions={_addHandlers:{},_removeHandlers:{},_queue:{},remove(...extensions2){return extensions2.map(normalizeExtension).forEach(ext=>{ext.type.forEach(type=>{var _a;return null==(type=(_a=this._removeHandlers)[type])?void 0:type.call(_a,ext)})}),this},add(...extensions2){return extensions2.map(normalizeExtension).forEach(ext=>{ext.type.forEach(type=>{var _b,handlers=this._addHandlers,queue=this._queue;handlers[type]?null!=(_b=handlers[type])&&_b.call(handlers,ext):(queue[type]=queue[type]||[],null!=(_b=queue[type])&&_b.push(ext))})}),this},handle(type,onAdd,onRemove){var addHandlers=this._addHandlers,removeHandlers=this._removeHandlers;if(addHandlers[type]||removeHandlers[type])throw new Error(`Extension type ${type} already has a handler`);return addHandlers[type]=onAdd,removeHandlers[type]=onRemove,(addHandlers=this._queue)[type]&&(null!=(removeHandlers=addHandlers[type])&&removeHandlers.forEach(ext=>onAdd(ext)),delete addHandlers[type]),this},handleByMap(type,map){return this.handle(type,extension=>{extension.name&&(map[extension.name]=extension.ref)},extension=>{extension.name&&delete map[extension.name]})},handleByNamedList(type,map,defaultPriority=-1){return this.handle(type,extension=>{0<=map.findIndex(item=>item.name===extension.name)||(map.push({name:extension.name,value:extension.ref}),map.sort((a,b)=>normalizeExtensionPriority(b.value,defaultPriority)-normalizeExtensionPriority(a.value,defaultPriority)))},extension=>{var index=map.findIndex(item=>item.name===extension.name);-1!==index&&map.splice(index,1)})},handleByList(type,list,defaultPriority=-1){return this.handle(type,extension=>{list.includes(extension.ref)||(list.push(extension.ref),list.sort((a,b)=>normalizeExtensionPriority(b,defaultPriority)-normalizeExtensionPriority(a,defaultPriority)))},extension=>{-1!==(extension=list.indexOf(extension.ref))&&list.splice(extension,1)})},mixin(Target,...sources){for(const source of sources)Object.defineProperties(Target.prototype,Object.getOwnPropertyDescriptors(source))}};function getDefaultExportFromCjs(x){return x&&x.__esModule&&Object.prototype.hasOwnProperty.call(x,"default")?x.default:x}function t(r){return"string"==typeof r?0key in obj?__defProp$1c(obj,key,{enumerable:!0,configurable:!0,writable:!0,value:value}):obj[key]=value;!function(r){r.forEach(function(r){S.indexOf(r)<0&&(r(j,y),S.push(r))})}([function(e,f){var d,a={white:"#ffffff",bisque:"#ffe4c4",blue:"#0000ff",cadetblue:"#5f9ea0",chartreuse:"#7fff00",chocolate:"#d2691e",coral:"#ff7f50",antiquewhite:"#faebd7",aqua:"#00ffff",azure:"#f0ffff",whitesmoke:"#f5f5f5",papayawhip:"#ffefd5",plum:"#dda0dd",blanchedalmond:"#ffebcd",black:"#000000",gold:"#ffd700",goldenrod:"#daa520",gainsboro:"#dcdcdc",cornsilk:"#fff8dc",cornflowerblue:"#6495ed",burlywood:"#deb887",aquamarine:"#7fffd4",beige:"#f5f5dc",crimson:"#dc143c",cyan:"#00ffff",darkblue:"#00008b",darkcyan:"#008b8b",darkgoldenrod:"#b8860b",darkkhaki:"#bdb76b",darkgray:"#a9a9a9",darkgreen:"#006400",darkgrey:"#a9a9a9",peachpuff:"#ffdab9",darkmagenta:"#8b008b",darkred:"#8b0000",darkorchid:"#9932cc",darkorange:"#ff8c00",darkslateblue:"#483d8b",gray:"#808080",darkslategray:"#2f4f4f",darkslategrey:"#2f4f4f",deeppink:"#ff1493",deepskyblue:"#00bfff",wheat:"#f5deb3",firebrick:"#b22222",floralwhite:"#fffaf0",ghostwhite:"#f8f8ff",darkviolet:"#9400d3",magenta:"#ff00ff",green:"#008000",dodgerblue:"#1e90ff",grey:"#808080",honeydew:"#f0fff0",hotpink:"#ff69b4",blueviolet:"#8a2be2",forestgreen:"#228b22",lawngreen:"#7cfc00",indianred:"#cd5c5c",indigo:"#4b0082",fuchsia:"#ff00ff",brown:"#a52a2a",maroon:"#800000",mediumblue:"#0000cd",lightcoral:"#f08080",darkturquoise:"#00ced1",lightcyan:"#e0ffff",ivory:"#fffff0",lightyellow:"#ffffe0",lightsalmon:"#ffa07a",lightseagreen:"#20b2aa",linen:"#faf0e6",mediumaquamarine:"#66cdaa",lemonchiffon:"#fffacd",lime:"#00ff00",khaki:"#f0e68c",mediumseagreen:"#3cb371",limegreen:"#32cd32",mediumspringgreen:"#00fa9a",lightskyblue:"#87cefa",lightblue:"#add8e6",midnightblue:"#191970",lightpink:"#ffb6c1",mistyrose:"#ffe4e1",moccasin:"#ffe4b5",mintcream:"#f5fffa",lightslategray:"#778899",lightslategrey:"#778899",navajowhite:"#ffdead",navy:"#000080",mediumvioletred:"#c71585",powderblue:"#b0e0e6",palegoldenrod:"#eee8aa",oldlace:"#fdf5e6",paleturquoise:"#afeeee",mediumturquoise:"#48d1cc",mediumorchid:"#ba55d3",rebeccapurple:"#663399",lightsteelblue:"#b0c4de",mediumslateblue:"#7b68ee",thistle:"#d8bfd8",tan:"#d2b48c",orchid:"#da70d6",mediumpurple:"#9370db",purple:"#800080",pink:"#ffc0cb",skyblue:"#87ceeb",springgreen:"#00ff7f",palegreen:"#98fb98",red:"#ff0000",yellow:"#ffff00",slateblue:"#6a5acd",lavenderblush:"#fff0f5",peru:"#cd853f",palevioletred:"#db7093",violet:"#ee82ee",teal:"#008080",slategray:"#708090",slategrey:"#708090",aliceblue:"#f0f8ff",darkseagreen:"#8fbc8f",darkolivegreen:"#556b2f",greenyellow:"#adff2f",seagreen:"#2e8b57",seashell:"#fff5ee",tomato:"#ff6347",silver:"#c0c0c0",sienna:"#a0522d",lavender:"#e6e6fa",lightgreen:"#90ee90",orange:"#ffa500",orangered:"#ff4500",steelblue:"#4682b4",royalblue:"#4169e1",turquoise:"#40e0d0",yellowgreen:"#9acd32",salmon:"#fa8072",saddlebrown:"#8b4513",sandybrown:"#f4a460",rosybrown:"#bc8f8f",darksalmon:"#e9967a",lightgoldenrodyellow:"#fafad2",snow:"#fffafa",lightgrey:"#d3d3d3",lightgray:"#d3d3d3",dimgray:"#696969",dimgrey:"#696969",olivedrab:"#6b8e23",olive:"#808000"},r={};for(d in a)r[a[d]]=d;var l={};e.prototype.toName=function(f){if(!(this.rgba.a||this.rgba.r||this.rgba.g||this.rgba.b))return"transparent";var n=r[this.toHex()];if(n)return n;if(null!=f&&f.closest){var g,o=this.toRgb(),t=1/0,b="black";if(!l.length)for(var c in a)l[c]=new e(a[c]).toRgb();for(g in a){var d=o,i=l[g];(d=Math.pow(d.r-i.r,2)+Math.pow(d.g-i.g,2)+Math.pow(d.b-i.b,2))v===value2[i]):null!==value1&&null!==value2?(type1=Object.keys(value1),keys2=Object.keys(value2),type1.length===keys2.length&&type1.every(key=>value1[key]===value2[key])):value1===value2)}toRgba(){var[r,g,b,a]=this._components;return{r:r,g:g,b:b,a:a}}toRgb(){var[r,g,b]=this._components;return{r:r,g:g,b:b}}toRgbaString(){var[r,g,b]=this.toUint8RgbArray();return`rgba(${r},${g},${b},${this.alpha})`}toUint8RgbArray(out){var[r,g,b]=this._components;return this._arrayRgb||(this._arrayRgb=[]),(out=out||this._arrayRgb)[0]=Math.round(255*r),out[1]=Math.round(255*g),out[2]=Math.round(255*b),out}toArray(out){this._arrayRgba||(this._arrayRgba=[]),out=out||this._arrayRgba;var[r,g,b,a]=this._components;return out[0]=r,out[1]=g,out[2]=b,out[3]=a,out}toRgbArray(out){this._arrayRgb||(this._arrayRgb=[]),out=out||this._arrayRgb;var[r,g,b]=this._components;return out[0]=r,out[1]=g,out[2]=b,out}toNumber(){return this._int}toBgrNumber(){var[r,g,b]=this.toUint8RgbArray();return(b<<16)+(g<<8)+r}toLittleEndianNumber(){var value=this._int;return(value>>16)+(65280&value)+((255&value)<<16)}multiply(value){var[value,g,b,a]=_Color._temp.setValue(value)._components;return this._components[0]*=value,this._components[1]*=g,this._components[2]*=b,this._components[3]*=a,this._refreshInt(),this._value=null,this}premultiply(alpha,applyToRGB=!0){return applyToRGB&&(this._components[0]*=alpha,this._components[1]*=alpha,this._components[2]*=alpha),this._components[3]=alpha,this._refreshInt(),this._value=null,this}toPremultiplied(alpha,applyToRGB=!0){if(1===alpha)return(255<<24)+this._int;if(0===alpha)return applyToRGB?0:this._int;let r=this._int>>16&255,g=this._int>>8&255,b=255&this._int;return applyToRGB&&(r=r*alpha+.5|0,g=g*alpha+.5|0,b=b*alpha+.5|0),(255*alpha<<24)+(r<<16)+(g<<8)+b}toHex(){var hexString=this._int.toString(16);return"#"+("000000".substring(0,6-hexString.length)+hexString)}toHexa(){var alphaString=Math.round(255*this._components[3]).toString(16);return this.toHex()+"00".substring(0,2-alphaString.length)+alphaString}setAlpha(alpha){return this._components[3]=this._clamp(alpha),this}_normalize(value){let r,g,b,a;var match;if(("number"==typeof value||value instanceof Number)&&0<=value&&value<=16777215?(r=(value>>16&255)/255,g=(value>>8&255)/255,b=(255&value)/255,a=1):(Array.isArray(value)||value instanceof Float32Array)&&3<=value.length&&value.length<=4?(value=this._clamp(value),[r,g,b,a=1]=value):(value instanceof Uint8Array||value instanceof Uint8ClampedArray)&&3<=value.length&&value.length<=4?(value=this._clamp(value,0,255),[r,g,b,a=255]=value,r/=255,g/=255,b/=255,a/=255):"string"!=typeof value&&"object"!=typeof value||("string"==typeof value&&(match=_Color.HEX_PATTERN.exec(value))&&(value="#"+match[2]),(match=w(value)).isValid()&&({r,g,b,a}=match.rgba,r/=255,g/=255,b/=255)),void 0===r)throw new Error("Unable to convert color "+value);this._components[0]=r,this._components[1]=g,this._components[2]=b,this._components[3]=a,this._refreshInt()}_refreshInt(){this._clamp(this._components);var[r,g,b]=this._components;this._int=(255*r<<16)+(255*g<<8)+(255*b|0)}_clamp(value,min=0,max=1){return"number"==typeof value?Math.min(Math.max(value,min),max):(value.forEach((v,i)=>{value[i]=Math.min(Math.max(v,min),max)}),value)}static isColorLike(value){return"number"==typeof value||"string"==typeof value||value instanceof Number||value instanceof _Color||Array.isArray(value)||value instanceof Uint8Array||value instanceof Uint8ClampedArray||value instanceof Float32Array||void 0!==value.r&&void 0!==value.g&&void 0!==value.b||void 0!==value.r&&void 0!==value.g&&void 0!==value.b&&void 0!==value.a||void 0!==value.h&&void 0!==value.s&&void 0!==value.l||void 0!==value.h&&void 0!==value.s&&void 0!==value.l&&void 0!==value.a||void 0!==value.h&&void 0!==value.s&&void 0!==value.v||void 0!==value.h&&void 0!==value.s&&void 0!==value.v&&void 0!==value.a}};_Color.shared=new _Color,_Color._temp=new _Color,_Color.HEX_PATTERN=/^(#|0x)?(([a-f0-9]{3}){1,2}([a-f0-9]{2})?)$/i;let Color=_Color;eventemitter3$1={cullArea:null,cullable:!1,cullableChildren:!0};const PI_2=2*Math.PI,RAD_TO_DEG=180/Math.PI,DEG_TO_RAD=Math.PI/180;class Point{constructor(x=0,y=0){this.x=0,this.y=0,this.x=x,this.y=y}clone(){return new Point(this.x,this.y)}copyFrom(p){return this.set(p.x,p.y),this}copyTo(p){return p.set(this.x,this.y),p}equals(p){return p.x===this.x&&p.y===this.y}set(x=0,y=x){return this.x=x,this.y=y,this}toString(){return`[pixi.js/math:Point x=${this.x} y=${this.y}]`}static get shared(){return tempPoint.x=0,tempPoint.y=0,tempPoint}}const tempPoint=new Point;class Matrix{constructor(a=1,b=0,c=0,d=1,tx=0,ty=0){this.array=null,this.a=a,this.b=b,this.c=c,this.d=d,this.tx=tx,this.ty=ty}fromArray(array){this.a=array[0],this.b=array[1],this.c=array[3],this.d=array[4],this.tx=array[2],this.ty=array[5]}set(a,b,c,d,tx,ty){return this.a=a,this.b=b,this.c=c,this.d=d,this.tx=tx,this.ty=ty,this}toArray(transpose,out){return this.array||(this.array=new Float32Array(9)),out=out||this.array,transpose?(out[0]=this.a,out[1]=this.b,out[2]=0,out[3]=this.c,out[4]=this.d,out[5]=0,out[6]=this.tx,out[7]=this.ty):(out[0]=this.a,out[1]=this.c,out[2]=this.tx,out[3]=this.b,out[4]=this.d,out[5]=this.ty,out[6]=0,out[7]=0),out[8]=1,out}apply(pos,newPos){newPos=newPos||new Point;var x=pos.x,pos=pos.y;return newPos.x=this.a*x+this.c*pos+this.tx,newPos.y=this.b*x+this.d*pos+this.ty,newPos}applyInverse(pos,newPos){newPos=newPos||new Point;var a=this.a,b=this.b,c=this.c,d=this.d,tx=this.tx,ty=this.ty,id=1/(a*d+c*-b),x=pos.x,pos=pos.y;return newPos.x=d*id*x+-c*id*pos+(ty*c-tx*d)*id,newPos.y=a*id*pos+-b*id*x+(-ty*a+tx*b)*id,newPos}translate(x,y){return this.tx+=x,this.ty+=y,this}scale(x,y){return this.a*=x,this.d*=y,this.c*=x,this.b*=y,this.tx*=x,this.ty*=y,this}rotate(angle){var cos=Math.cos(angle),angle=Math.sin(angle),a1=this.a,c1=this.c,tx1=this.tx;return this.a=a1*cos-this.b*angle,this.b=a1*angle+this.b*cos,this.c=c1*cos-this.d*angle,this.d=c1*angle+this.d*cos,this.tx=tx1*cos-this.ty*angle,this.ty=tx1*angle+this.ty*cos,this}append(matrix){var a1=this.a,b1=this.b,c1=this.c,d1=this.d;return this.a=matrix.a*a1+matrix.b*c1,this.b=matrix.a*b1+matrix.b*d1,this.c=matrix.c*a1+matrix.d*c1,this.d=matrix.c*b1+matrix.d*d1,this.tx=matrix.tx*a1+matrix.ty*c1+this.tx,this.ty=matrix.tx*b1+matrix.ty*d1+this.ty,this}appendFrom(a,b){var a1=a.a,b1=a.b,c1=a.c,d1=a.d,tx=a.tx,a=a.ty,a2=b.a,b2=b.b,c2=b.c,d2=b.d;return this.a=a1*a2+b1*c2,this.b=a1*b2+b1*d2,this.c=c1*a2+d1*c2,this.d=c1*b2+d1*d2,this.tx=tx*a2+a*c2+b.tx,this.ty=tx*b2+a*d2+b.ty,this}setTransform(x,y,pivotX,pivotY,scaleX,scaleY,rotation,skewX,skewY){return this.a=Math.cos(rotation+skewY)*scaleX,this.b=Math.sin(rotation+skewY)*scaleX,this.c=-Math.sin(rotation-skewX)*scaleY,this.d=Math.cos(rotation-skewX)*scaleY,this.tx=x-(pivotX*this.a+pivotY*this.c),this.ty=y-(pivotX*this.b+pivotY*this.d),this}prepend(matrix){var a1,c1,tx1=this.tx;return 1===matrix.a&&0===matrix.b&&0===matrix.c&&1===matrix.d||(a1=this.a,c1=this.c,this.a=a1*matrix.a+this.b*matrix.c,this.b=a1*matrix.b+this.b*matrix.d,this.c=c1*matrix.a+this.d*matrix.c,this.d=c1*matrix.b+this.d*matrix.d),this.tx=tx1*matrix.a+this.ty*matrix.c+matrix.tx,this.ty=tx1*matrix.b+this.ty*matrix.d+matrix.ty,this}decompose(transform){var a=this.a,b=this.b,c=this.c,d=this.d,pivot=transform.pivot,skewX=-Math.atan2(-c,d),skewY=Math.atan2(b,a),delta=Math.abs(skewX+skewY);return delta<1e-5||Math.abs(PI_2-delta)<1e-5?(transform.rotation=skewY,transform.skew.x=transform.skew.y=0):(transform.rotation=0,transform.skew.x=skewX,transform.skew.y=skewY),transform.scale.x=Math.sqrt(a*a+b*b),transform.scale.y=Math.sqrt(c*c+d*d),transform.position.x=this.tx+(pivot.x*a+pivot.y*c),transform.position.y=this.ty+(pivot.x*b+pivot.y*d),transform}invert(){var a1=this.a,b1=this.b,c1=this.c,d1=this.d,tx1=this.tx,n=a1*d1-b1*c1;return this.a=d1/n,this.b=-b1/n,this.c=-c1/n,this.d=a1/n,this.tx=(c1*this.ty-d1*tx1)/n,this.ty=-(a1*this.ty-b1*tx1)/n,this}isIdentity(){return 1===this.a&&0===this.b&&0===this.c&&1===this.d&&0===this.tx&&0===this.ty}identity(){return this.a=1,this.b=0,this.c=0,this.d=1,this.tx=0,this.ty=0,this}clone(){var matrix=new Matrix;return matrix.a=this.a,matrix.b=this.b,matrix.c=this.c,matrix.d=this.d,matrix.tx=this.tx,matrix.ty=this.ty,matrix}copyTo(matrix){return matrix.a=this.a,matrix.b=this.b,matrix.c=this.c,matrix.d=this.d,matrix.tx=this.tx,matrix.ty=this.ty,matrix}copyFrom(matrix){return this.a=matrix.a,this.b=matrix.b,this.c=matrix.c,this.d=matrix.d,this.tx=matrix.tx,this.ty=matrix.ty,this}equals(matrix){return matrix.a===this.a&&matrix.b===this.b&&matrix.c===this.c&&matrix.d===this.d&&matrix.tx===this.tx&&matrix.ty===this.ty}toString(){return`[pixi.js:Matrix a=${this.a} b=${this.b} c=${this.c} d=${this.d} tx=${this.tx} ty=${this.ty}]`}static get IDENTITY(){return identityMatrix$1.identity()}static get shared(){return tempMatrix$6.identity()}}const tempMatrix$6=new Matrix,identityMatrix$1=new Matrix;class ObservablePoint{constructor(observer,x,y){this._x=x||0,this._y=y||0,this._observer=observer}clone(observer){return new ObservablePoint(null!=observer?observer:this._observer,this._x,this._y)}set(x=0,y=x){return this._x===x&&this._y===y||(this._x=x,this._y=y,this._observer._onUpdate(this)),this}copyFrom(p){return this._x===p.x&&this._y===p.y||(this._x=p.x,this._y=p.y,this._observer._onUpdate(this)),this}copyTo(p){return p.set(this._x,this._y),p}equals(p){return p.x===this._x&&p.y===this._y}toString(){return`[pixi.js/math:ObservablePoint x=0 y=0 scope=${this._observer}]`}get x(){return this._x}set x(value){this._x!==value&&(this._x=value,this._observer._onUpdate(this))}get y(){return this._y}set y(value){this._y!==value&&(this._y=value,this._observer._onUpdate(this))}}const uidCache={default:-1};function uid$1(name="default"){return void 0===uidCache[name]&&(uidCache[name]=-1),++uidCache[name]}const warnings={},v8_0_0="8.0.0";function deprecation(version,message,ignoreDepth=3){if(!warnings[message]){let stack=(new Error).stack;void 0===stack?console.warn("PixiJS Deprecation Warning: ",message+` +Deprecated since v`+version):(stack=stack.split("\n").splice(ignoreDepth).join("\n"),console.groupCollapsed?(console.groupCollapsed("%cPixiJS Deprecation Warning: %c%s","color:#614108;background:#fffbe6","font-weight:normal;color:#614108;background:#fffbe6",message+` +Deprecated since v`+version),console.warn(stack),console.groupEnd()):(console.warn("PixiJS Deprecation Warning: ",message+` +Deprecated since v`+version),console.warn(stack))),warnings[message]=!0}}class Pool{constructor(ClassType,initialSize){this._pool=[],this._count=0,this._index=0,this._classType=ClassType,initialSize&&this.prepopulate(initialSize)}prepopulate(total){for(let i=0;i{var name=stats[pool._classType.name]?pool._classType.name+pool._classType.ID:pool._classType.name;stats[name]={free:pool.totalFree,used:pool.totalUsed,size:pool.totalSize}}),stats}};var cacheAsTextureMixin={get isCachedAsTexture(){var _a;return!(null==(_a=this.renderGroup)||!_a.isCachedAsTexture)},cacheAsTexture(val){"boolean"==typeof val&&!1===val?this.disableRenderGroup():(this.enableRenderGroup(),this.renderGroup.enableCacheAsTexture(!0===val?{}:val))},updateCacheTexture(){var _a;null!=(_a=this.renderGroup)&&_a.updateCacheTexture()},get cacheAsBitmap(){return this.isCachedAsTexture},set cacheAsBitmap(val){deprecation("v8.6.0","cacheAsBitmap is deprecated, use cacheAsTexture instead."),this.cacheAsTexture(val)}};function removeItems(arr,startIdx,removeCount){var length=arr.length;let i;if(!(length<=startIdx||0===removeCount)){var len=length-(removeCount=length=beginIndex;i--){var child=this.children[i];child&&(removed.push(child),child.parent=null)}removeItems(this.children,beginIndex,endIndex),(endIndex=this.renderGroup||this.parentRenderGroup)&&endIndex.removeChildren(removed);for(let i=0;i=this.children.length)throw new Error(`getChildAt: Index (${index}) does not exist.`);return this.children[index]},setChildIndex(child,index){if(index<0||index>=this.children.length)throw new Error(`The index ${index} supplied is out of bounds `+this.children.length);this.getChildIndex(child),this.addChildAt(child,index)},getChildIndex(child){if(-1===(child=this.children.indexOf(child)))throw new Error("The supplied Container must be a child of the caller");return child},addChildAt(child,index){this.allowChildren||deprecation(v8_0_0,"addChildAt: Only Containers will be allowed to add children in v8.0.0");var children=this.children;if(index<0||index>children.length)throw new Error(child+`addChildAt: The index ${index} supplied is out of bounds `+children.length);if(child.parent){var currentIndex=child.parent.children.indexOf(child);if(child.parent===this&¤tIndex===index)return child;-1!==currentIndex&&child.parent.children.splice(currentIndex,1)}return index===children.length?children.push(child):children.splice(index,0,child),child.parent=this,child.didChange=!0,child._updateFlags=15,(currentIndex=this.renderGroup||this.parentRenderGroup)&¤tIndex.addChild(child),this.sortableChildren&&(this.sortDirty=!0),this.emit("childAdded",child,this,index),child.emit("added",this),child},swapChildren(child,child2){var index2,index1;child!==child2&&(index1=this.getChildIndex(child),index2=this.getChildIndex(child2),this.children[index1]=child2,this.children[index2]=child,(index1=this.renderGroup||this.parentRenderGroup)&&(index1.structureDidChange=!0),this._didContainerChangeTick++)},removeFromParent(){var _a;null!=(_a=this.parent)&&_a.removeChild(this)},reparentChild(...child){return 1===child.length?this.reparentChildAt(child[0],this.children.length):(child.forEach(c=>this.reparentChildAt(c,this.children.length)),child[0])},reparentChildAt(child,index){var childMat;return child.parent===this?this.setChildIndex(child,index):(childMat=child.worldTransform.clone(),child.removeFromParent(),this.addChildAt(child,index),(index=this.worldTransform.clone()).invert(),childMat.prepend(index),child.setFromMatrix(childMat)),child}},collectRenderablesMixin={collectRenderables(instructionSet,renderer,currentLayer){this.parentRenderLayer&&this.parentRenderLayer!==currentLayer||this.globalDisplayStatus<7||!this.includeInBuild||(this.sortableChildren&&this.sortChildren(),this.isSimple?this.collectRenderablesSimple(instructionSet,renderer,currentLayer):this.renderGroup?renderer.renderPipes.renderGroup.addRenderGroup(this.renderGroup,instructionSet):this.collectRenderablesWithEffects(instructionSet,renderer,currentLayer))},collectRenderablesSimple(instructionSet,renderer,currentLayer){var children=this.children,length=children.length;for(let i=0;i{this.add({test:test.test,maskClass:test})}))}add(test){this._tests.push(test)}getMaskEffect(item){this._initialized||this.init();for(let i=0;ikey in obj?__defProp$1b(obj,key,{enumerable:!0,configurable:!0,writable:!0,value:value}):obj[key]=value,__spreadValues$1b=(a,b)=>{for(var prop in b=b||{})__hasOwnProp$1b.call(b,prop)&&__defNormalProp$1b(a,prop,b[prop]);if(__getOwnPropSymbols$1b)for(var prop of __getOwnPropSymbols$1b(b))__propIsEnum$1b.call(b,prop)&&__defNormalProp$1b(a,prop,b[prop]);return a},effectsMixin={_maskEffect:null,_maskOptions:{inverse:!1},_filterEffect:null,effects:[],_markStructureAsChanged(){var renderGroup=this.renderGroup||this.parentRenderGroup;renderGroup&&(renderGroup.structureDidChange=!0)},addEffect(effect){-1===this.effects.indexOf(effect)&&(this.effects.push(effect),this.effects.sort((a,b)=>a.priority-b.priority),this._markStructureAsChanged(),this._updateIsSimple())},removeEffect(effect){-1!==(effect=this.effects.indexOf(effect))&&(this.effects.splice(effect,1),this._markStructureAsChanged(),this._updateIsSimple())},set mask(value){var effect=this._maskEffect;(null==effect?void 0:effect.mask)!==value&&(effect&&(this.removeEffect(effect),MaskEffectManager.returnMaskEffect(effect),this._maskEffect=null),null!=value)&&(this._maskEffect=MaskEffectManager.getMaskEffect(value),this.addEffect(this._maskEffect))},setMask(options){this._maskOptions=__spreadValues$1b(__spreadValues$1b({},this._maskOptions),options),options.mask&&(this.mask=options.mask),this._markStructureAsChanged()},get mask(){var _a;return null==(_a=this._maskEffect)?void 0:_a.mask},set filters(value){Array.isArray(value)||(value=value&&[value]);var effect=this._filterEffect||(this._filterEffect=new FilterEffect),hasFilters=0<(null==value?void 0:value.length),_a=hasFilters!=0<(null==(_a=effect.filters)?void 0:_a.length);value=Array.isArray(value)?value.slice(0):value,effect.filters=Object.freeze(value),_a&&(hasFilters?this.addEffect(effect):(this.removeEffect(effect),effect.filters=null!=value?value:null))},get filters(){var _a;return null==(_a=this._filterEffect)?void 0:_a.filters},set filterArea(value){this._filterEffect||(this._filterEffect=new FilterEffect),this._filterEffect.filterArea=value},get filterArea(){var _a;return null==(_a=this._filterEffect)?void 0:_a.filterArea}},findMixin={label:null,get name(){return deprecation(v8_0_0,"Container.name property has been removed, use Container.label instead"),this.label},set name(value){deprecation(v8_0_0,"Container.name property has been removed, use Container.label instead"),this.label=value},getChildByName(name,deep=!1){return this.getChildByLabel(name,deep)},getChildByLabel(label,deep=!1){var children=this.children;for(let i=0;i=this.x&&x=this.y&&y=x1||Math.max(lt.y,lb.y,rt.y,rb.y)<=y0||Math.min(lt.y,lb.y,rt.y,rb.y)>=y1||(n00=(transform=s*(lb.y-lt.y))*x0+(lb=s*(lt.x-lb.x))*y0,n10=transform*x1+lb*y0,n01=transform*x0+lb*y1,n11=transform*x1+lb*y1,Math.max(n00,n10,n01,n11)<=transform*lt.x+lb*lt.y)||Math.min(n00,n10,n01,n11)>=transform*rb.x+lb*rb.y||(n01=(n00=s*(lt.y-rt.y))*x0+(n10=s*(rt.x-lt.x))*y0,n11=n00*x1+n10*y0,transform=n00*x0+n10*y1,lb=n00*x1+n10*y1,Math.max(n01,n11,transform,lb)<=n00*lt.x+n10*lt.y)||Math.min(n01,n11,transform,lb)>=n00*rb.x+n10*rb.y)):(s=(this.xother.right?other:this).right<=s)&&(this.yother.bottom?other:this).bottom)}pad(paddingX=0,paddingY=paddingX){return this.x-=paddingX,this.y-=paddingY,this.width+=2*paddingX,this.height+=2*paddingY,this}fit(rectangle){var x1=Math.max(this.x,rectangle.x),x2=Math.min(this.x+this.width,rectangle.x+rectangle.width),y1=Math.max(this.y,rectangle.y),rectangle=Math.min(this.y+this.height,rectangle.y+rectangle.height);return this.x=x1,this.width=Math.max(x2-x1,0),this.y=y1,this.height=Math.max(rectangle-y1,0),this}ceil(resolution=1,eps=.001){var x2=Math.ceil((this.x+this.width-eps)*resolution)/resolution,y2=Math.ceil((this.y+this.height-eps)*resolution)/resolution;return this.x=Math.floor((this.x+eps)*resolution)/resolution,this.y=Math.floor((this.y+eps)*resolution)/resolution,this.width=x2-this.x,this.height=y2-this.y,this}enlarge(rectangle){var x1=Math.min(this.x,rectangle.x),x2=Math.max(this.x+this.width,rectangle.x+rectangle.width),y1=Math.min(this.y,rectangle.y),rectangle=Math.max(this.y+this.height,rectangle.y+rectangle.height);return this.x=x1,this.width=x2-x1,this.y=y1,this.height=rectangle-y1,this}getBounds(out){return(out=out||new Rectangle).copyFrom(this),out}containsRect(other){var x1,y1,x2;return!(this.width<=0||this.height<=0)&&(x1=other.x,y1=other.y,x2=other.x+other.width,other=other.y+other.height,x1>=this.x)&&x1=this.y&&y1=this.x&&x2=this.y&&otherthis.maxX||this.minY>this.maxY}get rectangle(){this._rectangle||(this._rectangle=new Rectangle);var rectangle=this._rectangle;return this.minX>this.maxX||this.minY>this.maxY?(rectangle.x=0,rectangle.y=0,rectangle.width=0,rectangle.height=0):rectangle.copyFromBounds(this),rectangle}clear(){return this.minX=1/0,this.minY=1/0,this.maxX=-1/0,this.maxY=-1/0,this.matrix=defaultMatrix,this}set(x0,y0,x1,y1){this.minX=x0,this.minY=y0,this.maxX=x1,this.maxY=y1}addFrame(x0,y0,x1,y1,matrix){var a=(matrix=matrix||this.matrix).a,b=matrix.b,c=matrix.c,d=matrix.d,tx=matrix.tx,matrix=matrix.ty;let minX=this.minX,minY=this.minY,maxX=this.maxX,maxY=this.maxY;var x=a*x0+c*y0+tx,y=b*x0+d*y0+matrix;xmaxX&&(maxX=x),y>maxY&&(maxY=y),y=b*x1+d*y0+matrix,(x=a*x1+c*y0+tx)maxX&&(maxX=x),y>maxY&&(maxY=y),y=b*x0+d*y1+matrix,(x=a*x0+c*y1+tx)maxX&&(maxX=x),y>maxY&&(maxY=y),y=b*x1+d*y1+matrix,(x=a*x1+c*y1+tx)maxX&&(maxX=x),y>maxY&&(maxY=y),this.minX=minX,this.minY=minY,this.maxX=maxX,this.maxY=maxY}addRect(rect,matrix){this.addFrame(rect.x,rect.y,rect.x+rect.width,rect.y+rect.height,matrix)}addBounds(bounds,matrix){this.addFrame(bounds.minX,bounds.minY,bounds.maxX,bounds.maxY,matrix)}addBoundsMask(mask){this.minX=(this.minX>mask.minX?this:mask).minX,this.minY=(this.minY>mask.minY?this:mask).minY,this.maxX=(this.maxXthis.maxX?x:this.maxX,this.maxY=y>this.maxY?y:this.maxY,y=b*minX+d*maxY+ty,this.minX=(x=matrix*minX+c*maxY+tx)this.maxX?x:this.maxX,this.maxY=y>this.maxY?y:this.maxY,y=b*maxX+d*maxY+ty,this.minX=(x=matrix*maxX+c*maxY+tx)this.maxX?x:this.maxX,this.maxY=y>this.maxY?y:this.maxY}fit(rect){return this.minXrect.right&&(this.maxX=rect.right),this.minYrect.bottom&&(this.maxY=rect.bottom),this}fitBounds(left,right,top,bottom){return this.minXright&&(this.maxX=right),this.minYbottom&&(this.maxY=bottom),this}pad(paddingX,paddingY=paddingX){return this.minX-=paddingX,this.maxX+=paddingX,this.minY-=paddingY,this.maxY+=paddingY,this}ceil(){return this.minX=Math.floor(this.minX),this.minY=Math.floor(this.minY),this.maxX=Math.ceil(this.maxX),this.maxY=Math.ceil(this.maxY),this}clone(){return new Bounds(this.minX,this.minY,this.maxX,this.maxY)}scale(x,y=x){return this.minX*=x,this.minY*=y,this.maxX*=x,this.maxY*=y,this}get x(){return this.minX}set x(value){var width=this.maxX-this.minX;this.minX=value,this.maxX=value+width}get y(){return this.minY}set y(value){var height=this.maxY-this.minY;this.minY=value,this.maxY=value+height}get width(){return this.maxX-this.minX}set width(value){this.maxX=this.minX+value}get height(){return this.maxY-this.minY}set height(value){this.maxY=this.minY+value}get left(){return this.minX}get right(){return this.maxX}get top(){return this.minY}get bottom(){return this.maxY}get isPositive(){return 0maxX?x:maxX,maxY=localX>maxY?localX:maxY}this.minX=minX,this.minY=minY,this.maxX=maxX,this.maxY=maxY}containsPoint(x,y){return this.minX<=x&&this.minY<=y&&this.maxX>=x&&this.maxY>=y}toString(){return`[pixi.js:Bounds minX=${this.minX} minY=${this.minY} maxX=${this.maxX} maxY=${this.maxY} width=${this.width} height=${this.height}]`}copyFrom(bounds){return this.minX=bounds.minX,this.minY=bounds.minY,this.maxX=bounds.maxX,this.maxY=bounds.maxY,this}}const matrixPool=new Pool(Matrix),boundsPool=new Pool(Bounds),tempMatrix$5=new Matrix;var getFastGlobalBoundsMixin={getFastGlobalBounds(factorRenderLayers,bounds){return(bounds=bounds||new Bounds).clear(),this._getGlobalBoundsRecursive(!!factorRenderLayers,bounds,this.parentRenderLayer),bounds.isValid||bounds.set(0,0,0,0),factorRenderLayers=this.renderGroup||this.parentRenderGroup,bounds.applyMatrix(factorRenderLayers.worldTransform),bounds},_getGlobalBoundsRecursive(factorRenderLayers,bounds,currentLayer){let localBounds=bounds;if((!factorRenderLayers||!this.parentRenderLayer||this.parentRenderLayer===currentLayer)&&7===this.localDisplayStatus&&this.measurable){var manageEffects=!!this.effects.length;if((this.renderGroup||manageEffects)&&(localBounds=boundsPool.get().clear()),this.boundsArea)bounds.addRect(this.boundsArea,this.worldTransform);else{this.renderPipeId&&(viewBounds=this.bounds,localBounds.addFrame(viewBounds.minX,viewBounds.minY,viewBounds.maxX,viewBounds.maxY,this.groupTransform));var viewBounds,children=this.children;for(let i=0;i>16&255)*(color2>>16&255)/255|0)<<16)+(((color1>>8&255)*(color2>>8&255)/255|0)<<8)+((255&color1)*(255&color2)/255|0):color1:color2}function multiplyColors(localBGRColor,parentBGRColor){return 16777215===localBGRColor?parentBGRColor:16777215===parentBGRColor?localBGRColor:multiplyHexColors(localBGRColor,parentBGRColor)}function bgr2rgb(color){return((255&color)<<16)+(65280&color)+(color>>16&255)}var getGlobalMixin={getGlobalAlpha(skipUpdate){if(skipUpdate)return this.renderGroup?this.renderGroup.worldAlpha:this.parentRenderGroup?this.parentRenderGroup.worldAlpha*this.alpha:this.alpha;let alpha=this.alpha,current=this.parent;for(;current;)alpha*=current.alpha,current=current.parent;return alpha},getGlobalTransform(matrix,skipUpdate){return skipUpdate?matrix.copyFrom(this.worldTransform):(this.updateLocalTransform(),skipUpdate=updateTransformBackwards(this,matrixPool.get().identity()),matrix.appendFrom(this.localTransform,skipUpdate),matrixPool.return(skipUpdate),matrix)},getGlobalTint(skipUpdate){if(skipUpdate)return this.renderGroup?bgr2rgb(this.renderGroup.worldColor):this.parentRenderGroup?bgr2rgb(multiplyColors(this.localColor,this.parentRenderGroup.worldColor)):this.tint;let color=this.localColor,parent=this.parent;for(;parent;)color=multiplyColors(color,parent.localColor),parent=parent.parent;return bgr2rgb(color)}};let warnCount=0;function warn(...args){500!==warnCount&&(500==++warnCount?console.warn("PixiJS Warning: too many warnings, no more warnings will be reported to the console by PixiJS."):console.warn("PixiJS Warning: ",...args))}function getLocalBounds(target,bounds,relativeMatrix){return bounds.clear(),function _getLocalBounds(target,bounds,parentTransform,rootContainer,isRoot){var _a,_b;let relativeTransform;if(isRoot)relativeTransform=matrixPool.get(),relativeTransform=parentTransform.copyTo(relativeTransform);else{if(!target.visible||!target.measurable)return;target.updateLocalTransform(),isRoot=target.localTransform,(relativeTransform=matrixPool.get()).appendFrom(isRoot,parentTransform)}if(isRoot=bounds,(parentTransform=!!target.effects.length)&&(bounds=boundsPool.get().clear()),target.boundsArea)bounds.addRect(target.boundsArea,relativeTransform);else{target.renderPipeId&&(bounds.matrix=relativeTransform,bounds.addBounds(target.bounds));var children=target.children;for(let i=0;i>>1)|v>>>2)|v>>>4)|v>>>8)|v>>>16)}function isPow2(v){return!(v&v-1||!v)}function definedProps(obj){var result={};for(const key in obj)void 0!==obj[key]&&(result[key]=obj[key]);return result}var __defProp$1a=Object.defineProperty,__getOwnPropSymbols$1a=Object.getOwnPropertySymbols,__hasOwnProp$1a=Object.prototype.hasOwnProperty,__propIsEnum$1a=Object.prototype.propertyIsEnumerable,__defNormalProp$1a=(obj,key,value)=>key in obj?__defProp$1a(obj,key,{enumerable:!0,configurable:!0,writable:!0,value:value}):obj[key]=value,__spreadValues$1a=(a,b)=>{for(var prop in b=b||{})__hasOwnProp$1a.call(b,prop)&&__defNormalProp$1a(a,prop,b[prop]);if(__getOwnPropSymbols$1a)for(var prop of __getOwnPropSymbols$1a(b))__propIsEnum$1a.call(b,prop)&&__defNormalProp$1a(a,prop,b[prop]);return a};const idHash$1=Object.create(null),_TextureStyle=class _TextureStyle extends EventEmitter{constructor(options={}){var _a;super(),this._resourceType="textureSampler",this._touched=0,this._maxAnisotropy=1,this.destroyed=!1,options=__spreadValues$1a(__spreadValues$1a({},_TextureStyle.defaultOptions),options),this.addressMode=options.addressMode,this.addressModeU=null!=(_a=options.addressModeU)?_a:this.addressModeU,this.addressModeV=null!=(_a=options.addressModeV)?_a:this.addressModeV,this.addressModeW=null!=(_a=options.addressModeW)?_a:this.addressModeW,this.scaleMode=options.scaleMode,this.magFilter=null!=(_a=options.magFilter)?_a:this.magFilter,this.minFilter=null!=(_a=options.minFilter)?_a:this.minFilter,this.mipmapFilter=null!=(_a=options.mipmapFilter)?_a:this.mipmapFilter,this.lodMinClamp=options.lodMinClamp,this.lodMaxClamp=options.lodMaxClamp,this.compare=options.compare,this.maxAnisotropy=null!=(_a=options.maxAnisotropy)?_a:1}set addressMode(value){this.addressModeU=value,this.addressModeV=value,this.addressModeW=value}get addressMode(){return this.addressModeU}set wrapMode(value){deprecation(v8_0_0,"TextureStyle.wrapMode is now TextureStyle.addressMode"),this.addressMode=value}get wrapMode(){return this.addressMode}set scaleMode(value){this.magFilter=value,this.minFilter=value,this.mipmapFilter=value}get scaleMode(){return this.magFilter}set maxAnisotropy(value){this._maxAnisotropy=Math.min(value,16),1key in obj?__defProp$19(obj,key,{enumerable:!0,configurable:!0,writable:!0,value:value}):obj[key]=value,__spreadValues$19=(a,b)=>{for(var prop in b=b||{})__hasOwnProp$19.call(b,prop)&&__defNormalProp$19(a,prop,b[prop]);if(__getOwnPropSymbols$19)for(var prop of __getOwnPropSymbols$19(b))__propIsEnum$19.call(b,prop)&&__defNormalProp$19(a,prop,b[prop]);return a};const _TextureSource=class _TextureSource extends EventEmitter{constructor(options={}){var _a;super(),this.options=options,this.uid=uid$1("textureSource"),this._resourceType="textureSource",this._resourceId=uid$1("resource"),this.uploadMethodId="unknown",this._resolution=1,this.pixelWidth=1,this.pixelHeight=1,this.width=1,this.height=1,this.sampleCount=1,this.mipLevelCount=1,this.autoGenerateMipmaps=!1,this.format="rgba8unorm",this.dimension="2d",this.antialias=!1,this._touched=0,this._batchTick=-1,this._textureBindLocation=-1,options=__spreadValues$19(__spreadValues$19({},_TextureSource.defaultOptions),options),this.label=null!=(_a=options.label)?_a:"",this.resource=options.resource,this.autoGarbageCollect=options.autoGarbageCollect,this._resolution=options.resolution,options.width?this.pixelWidth=options.width*this._resolution:this.pixelWidth=this.resource&&null!=(_a=this.resourceWidth)?_a:1,options.height?this.pixelHeight=options.height*this._resolution:this.pixelHeight=this.resource&&null!=(_a=this.resourceHeight)?_a:1,this.width=this.pixelWidth/this._resolution,this.height=this.pixelHeight/this._resolution,this.format=options.format,this.dimension=options.dimensions,this.mipLevelCount=options.mipLevelCount,this.autoGenerateMipmaps=options.autoGenerateMipmaps,this.sampleCount=options.sampleCount,this.antialias=options.antialias,this.alphaMode=options.alphaMode,this.style=new TextureStyle(definedProps(options)),this.destroyed=!1,this._refreshPOT()}get source(){return this}get style(){return this._style}set style(value){var _a;this.style!==value&&(null!=(_a=this._style)&&_a.off("change",this._onStyleChange,this),this._style=value,null!=(_a=this._style)&&_a.on("change",this._onStyleChange,this),this._onStyleChange())}get addressMode(){return this._style.addressMode}set addressMode(value){this._style.addressMode=value}get repeatMode(){return this._style.addressMode}set repeatMode(value){this._style.addressMode=value}get magFilter(){return this._style.magFilter}set magFilter(value){this._style.magFilter=value}get minFilter(){return this._style.minFilter}set minFilter(value){this._style.minFilter=value}get mipmapFilter(){return this._style.mipmapFilter}set mipmapFilter(value){this._style.mipmapFilter=value}get lodMinClamp(){return this._style.lodMinClamp}set lodMinClamp(value){this._style.lodMinClamp=value}get lodMaxClamp(){return this._style.lodMaxClamp}set lodMaxClamp(value){this._style.lodMaxClamp=value}_onStyleChange(){this.emit("styleChange",this)}update(){if(this.resource){var resolution=this._resolution;if(this.resize(this.resourceWidth/resolution,this.resourceHeight/resolution))return}this.emit("update",this)}destroy(){this.destroyed=!0,this.emit("destroy",this),this.emit("change",this),this._style&&(this._style.destroy(),this._style=null),this.uploadMethodId=null,this.resource=null,this.removeAllListeners()}unload(){this._resourceId=uid$1("resource"),this.emit("change",this),this.emit("unload",this)}get resourceWidth(){var resource=this.resource;return resource.naturalWidth||resource.videoWidth||resource.displayWidth||resource.width}get resourceHeight(){var resource=this.resource;return resource.naturalHeight||resource.videoHeight||resource.displayHeight||resource.height}get resolution(){return this._resolution}set resolution(resolution){this._resolution!==resolution&&(this._resolution=resolution,this.width=this.pixelWidth/resolution,this.height=this.pixelHeight/resolution)}resize(width,height,resolution){return resolution=resolution||this._resolution,width=width||this.width,height=height||this.height,width=Math.round(width*resolution),height=Math.round(height*resolution),this.width=width/resolution,this.height=height/resolution,this._resolution=resolution,(this.pixelWidth!==width||this.pixelHeight!==height)&&(this._refreshPOT(),this.pixelWidth=width,this.pixelHeight=height,this.emit("resize",this),this._resourceId=uid$1("resource"),this.emit("change",this),!0)}updateMipmaps(){this.autoGenerateMipmaps&&1ux[ind],uY:ind=>uy[ind],vX:ind=>vx[ind],vY:ind=>vy[ind],inv:rotation=>8&rotation?15&rotation:7&-rotation,add:(rotationSecond,rotationFirst)=>rotationCayley[rotationSecond][rotationFirst],sub:(rotationSecond,rotationFirst)=>rotationCayley[rotationSecond][groupD8.inv(rotationFirst)],rotate180:rotation=>4^rotation,isVertical:rotation=>2==(3&rotation),byDirection:(dx,dy)=>2*Math.abs(dx)<=Math.abs(dy)?0<=dy?groupD8.S:groupD8.N:2*Math.abs(dy)<=Math.abs(dx)?0{(rotation=rotationMatrices[groupD8.inv(rotation)]).tx=tx,rotation.ty=ty,matrix.append(rotation)}};var NOOP=()=>{},__defProp$18=Object.defineProperty,__defProps$q=Object.defineProperties,__getOwnPropDescs$q=Object.getOwnPropertyDescriptors,__getOwnPropSymbols$18=Object.getOwnPropertySymbols,__hasOwnProp$18=Object.prototype.hasOwnProperty,__propIsEnum$18=Object.prototype.propertyIsEnumerable,__defNormalProp$18=(obj,key,value)=>key in obj?__defProp$18(obj,key,{enumerable:!0,configurable:!0,writable:!0,value:value}):obj[key]=value;class BufferImageSource extends TextureSource{constructor(options){var buffer=options.resource||new Float32Array(options.width*options.height*4),format=options.format||(buffer instanceof Float32Array?"rgba32float":buffer instanceof Int32Array||buffer instanceof Uint32Array?"rgba32uint":buffer instanceof Int16Array||buffer instanceof Uint16Array?"rgba16uint":(0 instanceof Int8Array,"bgra8unorm"));super((options=((a,b)=>{for(var prop in b=options||{})__hasOwnProp$18.call(b,prop)&&__defNormalProp$18(a,prop,b[prop]);if(__getOwnPropSymbols$18)for(var prop of __getOwnPropSymbols$18(b))__propIsEnum$18.call(b,prop)&&__defNormalProp$18(a,prop,b[prop]);return a})({}),__defProps$q(options,__getOwnPropDescs$q({resource:buffer,format:format})))),this.uploadMethodId="buffer"}static test(resource){return resource instanceof Int8Array||resource instanceof Uint8Array||resource instanceof Uint8ClampedArray||resource instanceof Int16Array||resource instanceof Uint16Array||resource instanceof Int32Array||resource instanceof Uint32Array||resource instanceof Float32Array}}BufferImageSource.extension="texture-source";const tempMat=new Matrix;class TextureMatrix{constructor(texture,clampMargin){this.mapCoord=new Matrix,this.uClampFrame=new Float32Array(4),this.uClampOffset=new Float32Array(2),this._textureID=-1,this._updateID=0,this.clampOffset=0,this.clampMargin=void 0===clampMargin?texture.width<10?0:.5:clampMargin,this.isSimple=!1,this.texture=texture}get texture(){return this._texture}set texture(value){var _a;this.texture!==value&&(null!=(_a=this._texture)&&_a.removeListener("update",this.update,this),this._texture=value,this._texture.addListener("update",this.update,this),this.update())}multiplyUvs(uvs,out){void 0===out&&(out=uvs);var mat=this.mapCoord;for(let i=0;ikey in obj?__defProp$17(obj,key,{enumerable:!0,configurable:!0,writable:!0,value:value}):obj[key]=value;let count=0;const TexturePool=new class{constructor(textureOptions){this._poolKeyHash=Object.create(null),this._texturePool={},this.textureOptions=textureOptions||{},this.enableFullScreen=!1}createTexture(pixelWidth,pixelHeight,antialias){var a=new TextureSource((a=((a,b)=>{for(var prop in b=b||{})__hasOwnProp$17.call(b,prop)&&__defNormalProp$17(a,prop,b[prop]);if(__getOwnPropSymbols$17)for(var prop of __getOwnPropSymbols$17(b))__propIsEnum$17.call(b,prop)&&__defNormalProp$17(a,prop,b[prop]);return a})({},this.textureOptions),__defProps$p(a,__getOwnPropDescs$p({width:pixelWidth,height:pixelHeight,resolution:1,antialias:antialias,autoGarbageCollect:!1}))));return new Texture({source:a,label:"texturePool_"+count++})}getOptimalTexture(frameWidth,frameHeight,resolution=1,antialias){var po2Width=Math.ceil(frameWidth*resolution-1e-6),po2Height=Math.ceil(frameHeight*resolution-1e-6),key=((po2Width=nextPow2(po2Width))<<17)+((po2Height=nextPow2(po2Height))<<1)+(antialias?1:0);this._texturePool[key]||(this._texturePool[key]=[]);let texture=this._texturePool[key].pop();return(texture=texture||this.createTexture(po2Width,po2Height,antialias)).source._resolution=resolution,texture.source.width=po2Width/resolution,texture.source.height=po2Height/resolution,texture.source.pixelWidth=po2Width,texture.source.pixelHeight=po2Height,texture.frame.x=0,texture.frame.y=0,texture.frame.width=frameWidth,texture.frame.height=frameHeight,texture.updateUvs(),this._poolKeyHash[texture.uid]=key,texture}getSameSizeTexture(texture,antialias=!1){var source=texture.source;return this.getOptimalTexture(texture.width,texture.height,source._resolution,antialias)}returnTexture(renderTexture){var key=this._poolKeyHash[renderTexture.uid];this._texturePool[key].push(renderTexture)}clear(destroyTextures){if(destroyTextures=!1!==destroyTextures)for(const i in this._texturePool){var textures=this._texturePool[i];if(textures)for(let j=0;jthis.addChild(child)),null!=(_a=options.parent)&&_a.addChild(this)}static mixin(source){deprecation("8.8.0","Container.mixin is deprecated, please use extensions.mixin instead."),extensions.mixin(Container,source)}set _didChangeId(value){this._didViewChangeTick=value>>12&4095,this._didContainerChangeTick=4095&value}get _didChangeId(){return 4095&this._didContainerChangeTick|(4095&this._didViewChangeTick)<<12}addChild(...children){if(this.allowChildren||deprecation(v8_0_0,"addChild: Only Containers will be allowed to add children in v8.0.0"),1key in obj?__defProp$16(obj,key,{enumerable:!0,configurable:!0,writable:!0,value:value}):obj[key]=value,__spreadValues$16=(a,b)=>{for(var prop in b=b||{})__hasOwnProp$16.call(b,prop)&&__defNormalProp$16(a,prop,b[prop]);if(__getOwnPropSymbols$16)for(var prop of __getOwnPropSymbols$16(b))__propIsEnum$16.call(b,prop)&&__defNormalProp$16(a,prop,b[prop]);return a};const _AccessibilitySystem=class _AccessibilitySystem{constructor(renderer,_mobileInfo=isMobile){this._mobileInfo=_mobileInfo,this.debug=!1,this._activateOnTab=!0,this._deactivateOnMouseMove=!0,this._isActive=!1,this._isMobileAccessibility=!1,this._div=null,this._pool=[],this._renderId=0,this._children=[],this._androidUpdateCount=0,this._androidUpdateFrequency=500,this._hookDiv=null,(_mobileInfo.tablet||_mobileInfo.phone)&&this._createTouchHook(),this._renderer=renderer}get isActive(){return this._isActive}get isMobileAccessibility(){return this._isMobileAccessibility}get hookDiv(){return this._hookDiv}_createTouchHook(){var hookDiv=document.createElement("button");hookDiv.style.width="1px",hookDiv.style.height="1px",hookDiv.style.position="absolute",hookDiv.style.top="-1000px",hookDiv.style.left="-1000px",hookDiv.style.zIndex=2..toString(),hookDiv.style.backgroundColor="#FF0000",hookDiv.title="select to enable accessibility for this content",hookDiv.addEventListener("focus",()=>{this._isMobileAccessibility=!0,this._activate(),this._destroyTouchHook()}),document.body.appendChild(hookDiv),this._hookDiv=hookDiv}_destroyTouchHook(){this._hookDiv&&(document.body.removeChild(this._hookDiv),this._hookDiv=null)}_activate(){if(!this._isActive){this._isActive=!0,this._div||(this._div=document.createElement("div"),this._div.style.width="100px",this._div.style.height="100px",this._div.style.position="absolute",this._div.style.top="0px",this._div.style.left="0px",this._div.style.zIndex=2..toString(),this._div.style.pointerEvents="none"),this._activateOnTab&&(this._onKeyDown=this._onKeyDown.bind(this),globalThis.addEventListener("keydown",this._onKeyDown,!1)),this._deactivateOnMouseMove&&(this._onMouseMove=this._onMouseMove.bind(this),globalThis.document.addEventListener("mousemove",this._onMouseMove,!0));const canvas=this._renderer.view.canvas;if(canvas.parentNode)canvas.parentNode.appendChild(this._div),this._initAccessibilitySetup();else{const observer=new MutationObserver(()=>{canvas.parentNode&&(canvas.parentNode.appendChild(this._div),observer.disconnect(),this._initAccessibilitySetup())});observer.observe(document.body,{childList:!0,subtree:!0})}}}_initAccessibilitySetup(){this._renderer.runners.postrender.add(this),this._renderer.lastObjectRendered&&this._updateAccessibleObjects(this._renderer.lastObjectRendered)}_deactivate(){if(this._isActive&&!this._isMobileAccessibility){this._isActive=!1,globalThis.document.removeEventListener("mousemove",this._onMouseMove,!0),this._activateOnTab&&globalThis.addEventListener("keydown",this._onKeyDown,!1),this._renderer.runners.postrender.remove(this);for(const child of this._children)child._accessibleDiv&&child._accessibleDiv.parentNode&&(child._accessibleDiv.parentNode.removeChild(child._accessibleDiv),child._accessibleDiv=null),child._accessibleActive=!1;this._pool.forEach(div=>{div.parentNode&&div.parentNode.removeChild(div)}),this._div&&this._div.parentNode&&this._div.parentNode.removeChild(this._div),this._pool=[],this._children=[]}}_updateAccessibleObjects(container){if(container.visible&&container.accessibleChildren){container.accessible&&(container._accessibleActive||this._addChild(container),container._renderId=this._renderId);var children=container.children;if(children)for(let i=0;i title : ${div.title}
tabIndex: `+div.tabIndex}_capHitArea(hitArea){hitArea.x<0&&(hitArea.width+=hitArea.x,hitArea.x=0),hitArea.y<0&&(hitArea.height+=hitArea.y,hitArea.y=0);var{width:viewWidth,height:viewHeight}=this._renderer;hitArea.x+hitArea.width>viewWidth&&(hitArea.width=viewWidth-hitArea.x),hitArea.y+hitArea.height>viewHeight&&(hitArea.height=viewHeight-hitArea.y)}_addChild(container){let div=this._pool.pop();div||("button"===container.accessibleType?div=document.createElement("button"):((div=document.createElement(container.accessibleType)).style.cssText=` + color: transparent; + pointer-events: none; + padding: 0; + margin: 0; + border: 0; + outline: 0; + background: transparent; + box-sizing: border-box; + user-select: none; + -webkit-user-select: none; + -moz-user-select: none; + -ms-user-select: none; + `,container.accessibleText&&(div.innerText=container.accessibleText)),div.style.width="100px",div.style.height="100px",div.style.backgroundColor=this.debug?"rgba(255,255,255,0.5)":"transparent",div.style.position="absolute",div.style.zIndex=2..toString(),div.style.borderStyle="none",navigator.userAgent.toLowerCase().includes("chrome")?div.setAttribute("aria-live","off"):div.setAttribute("aria-live","polite"),navigator.userAgent.match(/rv:.*Gecko\//)?div.setAttribute("aria-relevant","additions"):div.setAttribute("aria-relevant","text"),div.addEventListener("click",this._onClick.bind(this)),div.addEventListener("focus",this._onFocus.bind(this)),div.addEventListener("focusout",this._onFocusOut.bind(this))),div.style.pointerEvents=container.accessiblePointerEvents,div.type=container.accessibleType,container.accessibleTitle&&null!==container.accessibleTitle?div.title=container.accessibleTitle:container.accessibleHint&&null!==container.accessibleHint||(div.title="container "+container.tabIndex),container.accessibleHint&&null!==container.accessibleHint&&div.setAttribute("aria-label",container.accessibleHint),this.debug&&this._updateDebugHTML(div),container._accessibleActive=!0,(container._accessibleDiv=div).container=container,this._children.push(container),this._div.appendChild(container._accessibleDiv),container.interactive&&(container._accessibleDiv.tabIndex=container.tabIndex)}_dispatchEvent(e,type){e=e.target.container;const boundary=this._renderer.events.rootBoundary,event=Object.assign(new FederatedEvent(boundary),{target:e});boundary.rootTarget=this._renderer.lastObjectRendered,type.forEach(type2=>boundary.dispatchEvent(event,type2))}_onClick(e){this._dispatchEvent(e,["click","pointertap","tap"])}_onFocus(e){e.target.getAttribute("aria-live")||e.target.setAttribute("aria-live","assertive"),this._dispatchEvent(e,["mouseover"])}_onFocusOut(e){e.target.getAttribute("aria-live")||e.target.setAttribute("aria-live","polite"),this._dispatchEvent(e,["mouseout"])}_onKeyDown(e){9===e.keyCode&&this._activateOnTab&&this._activate()}_onMouseMove(e){0===e.movementX&&0===e.movementY||this._deactivate()}destroy(){this._deactivate(),this._destroyTouchHook(),this._div=null,this._pool=null,this._children=null,this._renderer=null,this._activateOnTab&&globalThis.removeEventListener("keydown",this._onKeyDown)}setAccessibilityEnabled(enabled){enabled?this._activate():this._deactivate()}};_AccessibilitySystem.extension={type:["webgl-system","webgpu-system"],name:"accessibility"},_AccessibilitySystem.defaultOptions={enabledByDefault:!1,debug:!1,activateOnTab:!0,deactivateOnMouseMove:!0},NOOP=_AccessibilitySystem,childrenHelperMixin={accessible:!1,accessibleTitle:null,accessibleHint:null,tabIndex:0,_accessibleActive:!1,_accessibleDiv:null,accessibleType:"button",accessibleText:null,accessiblePointerEvents:"auto",accessibleChildren:!0,_renderId:-1},extensions.add(NOOP),extensions.mixin(Container,childrenHelperMixin);class ResizePlugin{static init(options){Object.defineProperty(this,"resizeTo",{set(dom){globalThis.removeEventListener("resize",this.queueResize),(this._resizeTo=dom)&&(globalThis.addEventListener("resize",this.queueResize),this.resize())},get(){return this._resizeTo}}),this.queueResize=()=>{this._resizeTo&&(this._cancelResize(),this._resizeId=requestAnimationFrame(()=>this.resize()))},this._cancelResize=()=>{this._resizeId&&(cancelAnimationFrame(this._resizeId),this._resizeId=null)},this.resize=()=>{if(this._resizeTo){this._cancelResize();let width,height;var clientWidth,clientHeight;height=this._resizeTo===globalThis.window?(width=globalThis.innerWidth,globalThis.innerHeight):({clientWidth,clientHeight}=this._resizeTo,width=clientWidth,clientHeight),this.renderer.resize(width,height),this.render()}},this._resizeId=null,this._resizeTo=null,this.resizeTo=options.resizeTo||null}static destroy(){globalThis.removeEventListener("resize",this.queueResize),this._cancelResize(),this._cancelResize=null,this.queueResize=null,this.resizeTo=null,this.resize=null}}ResizePlugin.extension="application";class TickerListener{constructor(fn,context=null,priority=0,once=!1){this.next=null,this.previous=null,this._destroyed=!1,this._fn=fn,this._context=context,this.priority=priority,this._once=once}match(fn,context=null){return this._fn===fn&&this._context===context}emit(ticker){return this._fn&&(this._context?this._fn.call(this._context,ticker):this._fn(ticker)),ticker=this.next,this._once&&this.destroy(!0),this._destroyed&&(this.next=null),ticker}connect(previous){(this.previous=previous).next&&(previous.next.previous=this),this.next=previous.next,previous.next=this}destroy(hard=!1){this._destroyed=!0,this._fn=null,this._context=null,this.previous&&(this.previous.next=this.next),this.next&&(this.next.previous=this.previous);var redirect=this.next;return this.next=hard?null:redirect,this.previous=null,redirect}}const _Ticker=class _Ticker{constructor(){this.autoStart=!1,this.deltaTime=1,this.lastTime=-1,this.speed=1,this.started=!1,this._requestId=null,this._maxElapsedMS=100,this._minElapsedMS=0,this._protected=!1,this._lastFrame=-1,this._head=new TickerListener(null,null,1/0),this.deltaMS=1/_Ticker.targetFPMS,this.elapsedMS=1/_Ticker.targetFPMS,this._tick=time=>{this._requestId=null,this.started&&(this.update(time),this.started)&&null===this._requestId&&this._head.next&&(this._requestId=requestAnimationFrame(this._tick))}}_requestIfNeeded(){null===this._requestId&&this._head.next&&(this.lastTime=performance.now(),this._lastFrame=this.lastTime,this._requestId=requestAnimationFrame(this._tick))}_cancelIfNeeded(){null!==this._requestId&&(cancelAnimationFrame(this._requestId),this._requestId=null)}_startIfPossible(){this.started?this._requestIfNeeded():this.autoStart&&this.start()}add(fn,context,priority=0){return this._addListener(new TickerListener(fn,context,priority))}addOnce(fn,context,priority=0){return this._addListener(new TickerListener(fn,context,priority,!0))}_addListener(listener){let current=this._head.next,previous=this._head;if(current){for(;current;){if(listener.priority>current.priority){listener.connect(previous);break}current=(previous=current).next}listener.previous||listener.connect(previous)}else listener.connect(previous);return this._startIfPossible(),this}remove(fn,context){let listener=this._head.next;for(;listener;)listener=listener.match(fn,context)?listener.destroy():listener.next;return this._head.next||this._cancelIfNeeded(),this}get count(){if(!this._head)return 0;let count=0,current=this._head;for(;current=current.next;)count++;return count}start(){this.started||(this.started=!0,this._requestIfNeeded())}stop(){this.started&&(this.started=!1,this._cancelIfNeeded())}destroy(){if(!this._protected){this.stop();let listener=this._head.next;for(;listener;)listener=listener.destroy(!0);this._head.destroy(),this._head=null}}update(currentTime=performance.now()){let elapsedMS;if(currentTime>this.lastTime){if((elapsedMS=this.elapsedMS=currentTime-this.lastTime)>this._maxElapsedMS&&(elapsedMS=this._maxElapsedMS),elapsedMS*=this.speed,this._minElapsedMS){var delta=currentTime-this._lastFrame|0;if(delta{this._ticker.stop()},this.start=()=>{this._ticker.start()},this._ticker=null,this.ticker=options.sharedTicker?Ticker.shared:new Ticker,options.autoStart&&this.start()}static destroy(){var oldTicker;this._ticker&&(oldTicker=this._ticker,this.ticker=null,oldTicker.destroy())}}TickerPlugin.extension="application",extensions.add(ResizePlugin),extensions.add(TickerPlugin);const EventsTicker=new class{constructor(){this.interactionFrequency=10,this._deltaTime=0,this._didMove=!1,this._tickerAdded=!1,this._pauseUpdate=!0}init(events){this.removeTickerListener(),this.events=events,this.interactionFrequency=10,this._deltaTime=0,this._didMove=!1,this._tickerAdded=!1,this._pauseUpdate=!0}get pauseUpdate(){return this._pauseUpdate}set pauseUpdate(paused){this._pauseUpdate=paused}addTickerListener(){!this._tickerAdded&&this.domElement&&(Ticker.system.add(this._tickerUpdate,this,50),this._tickerAdded=!0)}removeTickerListener(){this._tickerAdded&&(Ticker.system.remove(this._tickerUpdate,this),this._tickerAdded=!1)}pointerMoved(){this._didMove=!0}_update(){var rootPointerEvent;this.domElement&&!this._pauseUpdate&&(this._didMove?this._didMove=!1:(rootPointerEvent=this.events._rootPointerEvent,this.events.supportsTouchEvents&&"touch"===rootPointerEvent.pointerType||globalThis.document.dispatchEvent(new PointerEvent("pointermove",{clientX:rootPointerEvent.clientX,clientY:rootPointerEvent.clientY,pointerType:rootPointerEvent.pointerType,pointerId:rootPointerEvent.pointerId}))))}_tickerUpdate(ticker){this._deltaTime+=ticker.deltaTime,this._deltaTimea.priority-b.priority)}dispatchEvent(e,type){e.propagationStopped=!1,e.propagationImmediatelyStopped=!1,this.propagate(e,type),this.dispatch.emit(type||e.type,e)}mapEvent(e){if(this.rootTarget){var mappers=this.mappingTable[e.type];if(mappers)for(let i=0,j=mappers.length;i{e.currentTarget=targets[i],this.notifyTarget(e,event)})}}propagationPath(target){var propagationPath=[target];for(let i=0;i<2048&&target!==this.rootTarget&&target.parent;i++){if(!target.parent)throw new Error("Cannot find propagation path to disconnected target");propagationPath.push(target.parent),target=target.parent}return propagationPath.reverse(),propagationPath}hitTestMoveRecursive(currentTarget,eventMode,location,testFn,pruneFn,ignore=!1){let shouldReturn=!1;if(this._interactivePrune(currentTarget))return null;if("dynamic"!==currentTarget.eventMode&&"dynamic"!==eventMode||(EventsTicker.pauseUpdate=!1),currentTarget.interactiveChildren&¤tTarget.children){var children=currentTarget.children;for(let i=children.length-1;0<=i;i--){var isInteractive,child=children[i];!(child=this.hitTestMoveRecursive(child,this._isInteractive(eventMode)?eventMode:child.eventMode,location,testFn,pruneFn,ignore||pruneFn(currentTarget,location)))||0key in obj?__defProp$15(obj,key,{enumerable:!0,configurable:!0,writable:!0,value:value}):obj[key]=value;const TOUCH_TO_POINTER={touchstart:"pointerdown",touchend:"pointerup",touchendoutside:"pointerupoutside",touchmove:"pointermove",touchcancel:"pointercancel"},_EventSystem=class _EventSystem{constructor(renderer){this.supportsTouchEvents="ontouchstart"in globalThis,this.supportsPointerEvents=!!globalThis.PointerEvent,this.domElement=null,this.resolution=1,this.renderer=renderer,this.rootBoundary=new EventBoundary(null),EventsTicker.init(this),this.autoPreventDefault=!0,this._eventsAdded=!1,this._rootPointerEvent=new FederatedPointerEvent(null),this._rootWheelEvent=new FederatedWheelEvent(null),this.cursorStyles={default:"inherit",pointer:"pointer"},this.features=new Proxy(((a,b)=>{for(var prop in b=_EventSystem.defaultEventFeatures||{})__hasOwnProp$15.call(b,prop)&&__defNormalProp$15(a,prop,b[prop]);if(__getOwnPropSymbols$15)for(var prop of __getOwnPropSymbols$15(b))__propIsEnum$15.call(b,prop)&&__defNormalProp$15(a,prop,b[prop]);return a})({}),{set:(target,key,value)=>("globalMove"===key&&(this.rootBoundary.enableGlobalMoveEvents=value),target[key]=value,!0)}),this._onPointerDown=this._onPointerDown.bind(this),this._onPointerMove=this._onPointerMove.bind(this),this._onPointerUp=this._onPointerUp.bind(this),this._onPointerOverOut=this._onPointerOverOut.bind(this),this.onWheel=this.onWheel.bind(this)}static get defaultEventMode(){return this._defaultEventMode}init(options){var{canvas,resolution}=this.renderer;this.setTargetElement(canvas),this.resolution=resolution,_EventSystem._defaultEventMode=null!=(canvas=options.eventMode)?canvas:"passive",Object.assign(this.features,null!=(resolution=options.eventFeatures)?resolution:{}),this.rootBoundary.enableGlobalMoveEvents=this.features.globalMove}resolutionChange(resolution){this.resolution=resolution}destroy(){this.setTargetElement(null),this.renderer=null,this._currentCursor=null}setCursor(mode){mode=mode||"default";let applyStyles=!0;if(globalThis.OffscreenCanvas&&this.domElement instanceof OffscreenCanvas&&(applyStyles=!1),this._currentCursor!==mode){this._currentCursor=mode;var style=this.cursorStyles[mode];if(style)switch(typeof style){case"string":applyStyles&&(this.domElement.style.cursor=style);break;case"function":style(mode);break;case"object":applyStyles&&Object.assign(this.domElement.style,style)}else applyStyles&&"string"==typeof mode&&!Object.prototype.hasOwnProperty.call(this.cursorStyles,mode)&&(this.domElement.style.cursor=mode)}}get pointer(){return this._rootPointerEvent}_onPointerDown(nativeEvent){if(this.features.click){this.rootBoundary.rootTarget=this.renderer.lastObjectRendered;var events=this._normalizeToPointerData(nativeEvent);!this.autoPreventDefault||!events[0].isNormalized||!nativeEvent.cancelable&&"cancelable"in nativeEvent||nativeEvent.preventDefault();for(let i=0,j=events.length;i{emitter.off(type,listenerFn,context)}),options?emitter.once(type,listenerFn,context):emitter.on(type,listenerFn,context)},removeEventListener(type,listener,options){var options="boolean"==typeof options&&options||"object"==typeof options&&options.capture,context="function"==typeof listener?void 0:listener;listener="function"==typeof listener?listener:listener.handleEvent,this.off(type=options?type+"capture":type,listener,context)},dispatchEvent(e){if(e instanceof FederatedEvent)return e.defaultPrevented=!1,e.path=null,e.target=this,e.manager.dispatchEvent(e),!e.defaultPrevented;throw new Error("Container cannot propagate events outside of the Federated Events API")}},extensions.add(EventSystem),extensions.mixin(Container,toLocalGlobalMixin);class DOMPipe{constructor(renderer){this._destroyRenderableBound=this.destroyRenderable.bind(this),this._attachedDomElements=[],this._renderer=renderer,this._renderer.runners.postrender.add(this),this._domElement=document.createElement("div"),this._domElement.style.position="absolute",this._domElement.style.top="0",this._domElement.style.left="0",this._domElement.style.pointerEvents="none",this._domElement.style.zIndex="1000"}addRenderable(domContainer,_instructionSet){this._attachedDomElements.includes(domContainer)||(this._attachedDomElements.push(domContainer),domContainer.on("destroyed",this._destroyRenderableBound))}updateRenderable(_domContainer){}validateRenderable(_domContainer){return!0}destroyRenderable(domContainer){var index=this._attachedDomElements.indexOf(domContainer);-1!==index&&this._attachedDomElements.splice(index,1),domContainer.off("destroyed",this._destroyRenderableBound)}postrender(){var _a,attachedDomElements=this._attachedDomElements;if(0===attachedDomElements.length)this._domElement.remove();else{var canvas=this._renderer.view.canvas;this._domElement.parentNode!==canvas.parentNode&&null!=(_a=canvas.parentNode)&&_a.appendChild(this._domElement),this._domElement.style.transform=`translate(${canvas.offsetLeft}px, ${canvas.offsetTop}px)`;for(let i=0;i=bounds.minX&&point<=bounds.maxX&&y>=bounds.minY&&y<=bounds.maxY}onViewUpdate(){var renderGroup;this._didViewChangeTick++,this._boundsDirty=!0,!this.didViewUpdate&&(this.didViewUpdate=!0,renderGroup=this.renderGroup||this.parentRenderGroup)&&renderGroup.onChildViewUpdate(this)}destroy(options){super.destroy(options),this._bounds=null}collectRenderablesSimple(instructionSet,renderer,currentLayer){var{renderPipes,renderableGC}=renderer,children=(renderPipes.blendMode.setBlendMode(this,this.groupBlendMode,instructionSet),renderPipes[this.renderPipeId].addRenderable(this,instructionSet),renderableGC.addRenderable(this),this.didViewUpdate=!1,this.children),length=children.length;for(let i=0;i{var canvas=document.createElement("canvas");return canvas.width=width,canvas.height=height,canvas},getCanvasRenderingContext2D:()=>CanvasRenderingContext2D,getWebGLRenderingContext:()=>WebGLRenderingContext,getNavigator:()=>navigator,getBaseUrl:()=>{var _a;return null!=(_a=document.baseURI)?_a:window.location.href},getFontFaceSet:()=>document.fonts,fetch:(url,options)=>fetch(url,options),parseXML:xml=>(new DOMParser).parseFromString(xml,"text/xml")};const DOMAdapter={get(){return currentAdapter},set(adapter){currentAdapter=adapter}};function assertPath(path2){if("string"!=typeof path2)throw new TypeError("Path must be a string. Received "+JSON.stringify(path2))}function removeUrlParams(url){return url.split("?")[0].split("#")[0]}const path={toPosix(path2){return path2.replace(new RegExp("\\".replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),"/")},isUrl(path2){return/^https?:/.test(this.toPosix(path2))},isDataUrl(path2){return/^data:([a-z]+\/[a-z0-9-+.]+(;[a-z0-9-.!#$%*+.{}|~`]+=[a-z0-9-.!#$%*+.{}()_|~`]+)*)?(;base64)?,([a-z0-9!$&',()*+;=\-._~:@\/?%\s<>]*?)$/i.test(path2)},isBlobUrl(path2){return path2.startsWith("blob:")},hasProtocol(path2){return/^[^/:]+:/.test(this.toPosix(path2))},getProtocol(path2){return assertPath(path2),path2=this.toPosix(path2),(path2=/^file:\/\/\//.exec(path2)||/^[^/:]+:\/{0,2}/.exec(path2))?path2[0]:""},toAbsolute(url,customBaseUrl,customRootUrl){return assertPath(url),this.isDataUrl(url)||this.isBlobUrl(url)?url:(customBaseUrl=removeUrlParams(this.toPosix(null!=customBaseUrl?customBaseUrl:DOMAdapter.get().getBaseUrl())),customRootUrl=removeUrlParams(this.toPosix(null!=customRootUrl?customRootUrl:this.rootname(customBaseUrl))),(url=this.toPosix(url)).startsWith("/")?path.join(customRootUrl,url.slice(1)):this.isAbsolute(url)?url:this.join(customBaseUrl,url))},normalize(path2){if(assertPath(path2),0===path2.length)return".";if(this.isDataUrl(path2)||this.isBlobUrl(path2))return path2;let protocol="";var isAbsolute=(path2=this.toPosix(path2)).startsWith("/"),trailingSeparator=(this.hasProtocol(path2)&&(protocol=this.rootname(path2),path2=path2.slice(protocol.length)),path2.endsWith("/"));return 0<(path2=function(path2){let res="",lastSegmentLength=0,lastSlash=-1,dots=0,code=-1;for(let i=0;i<=path2.length;++i){if(i=start;--i){if(47===(code=path2.charCodeAt(i))){if(matchedSlash)continue;startPart=i+1;break}-1===end&&(matchedSlash=!1,end=i+1),46===code?-1===startDot?startDot=i:1!==preDotState&&(preDotState=1):-1!==startDot&&(preDotState=-1)}-1===startDot||-1===end||0===preDotState||1===preDotState&&startDot===end-1&&startDot===startPart+1?-1!==end&&(0===startPart&&isAbsolute?ret.base=ret.name=path2.slice(1,end):ret.base=ret.name=path2.slice(startPart,end)):(0===startPart&&isAbsolute?(ret.name=path2.slice(1,startDot),ret.base=path2.slice(1,end)):(ret.name=path2.slice(startPart,startDot),ret.base=path2.slice(startPart,end)),ret.ext=path2.slice(startDot,end)),ret.dir=this.dirname(path2)}return ret},sep:"/",delimiter:":",joinExtensions:[".html"]},convertToList=(input,transform,forceTransform=!1)=>(Array.isArray(input)||(input=[input]),transform?input.map(item=>"string"==typeof item||forceTransform?transform(item):item):input),isSingleItem=item=>!Array.isArray(item);var __defProp$13=Object.defineProperty,__getOwnPropSymbols$13=Object.getOwnPropertySymbols,__hasOwnProp$13=Object.prototype.hasOwnProperty,__propIsEnum$13=Object.prototype.propertyIsEnumerable,__defNormalProp$13=(obj,key,value)=>key in obj?__defProp$13(obj,key,{enumerable:!0,configurable:!0,writable:!0,value:value}):obj[key]=value,__spreadValues$13=(a,b)=>{for(var prop in b=b||{})__hasOwnProp$13.call(b,prop)&&__defNormalProp$13(a,prop,b[prop]);if(__getOwnPropSymbols$13)for(var prop of __getOwnPropSymbols$13(b))__propIsEnum$13.call(b,prop)&&__defNormalProp$13(a,prop,b[prop]);return a};class Resolver{constructor(){this._defaultBundleIdentifierOptions={connector:"-",createBundleAssetId:(bundleId,assetId)=>""+bundleId+this._bundleIdConnector+assetId,extractAssetIdFromBundle:(bundleId,assetBundleId)=>assetBundleId.replace(""+bundleId+this._bundleIdConnector,"")},this._bundleIdConnector=this._defaultBundleIdentifierOptions.connector,this._createBundleAssetId=this._defaultBundleIdentifierOptions.createBundleAssetId,this._extractAssetIdFromBundle=this._defaultBundleIdentifierOptions.extractAssetIdFromBundle,this._assetMap={},this._preferredOrder=[],this._parsers=[],this._resolverHash={},this._bundles={}}setBundleIdentifier(bundleIdentifier){var _a;if(this._bundleIdConnector=null!=(_a=bundleIdentifier.connector)?_a:this._bundleIdConnector,this._createBundleAssetId=null!=(_a=bundleIdentifier.createBundleAssetId)?_a:this._createBundleAssetId,this._extractAssetIdFromBundle=null!=(_a=bundleIdentifier.extractAssetIdFromBundle)?_a:this._extractAssetIdFromBundle,"bar"!==this._extractAssetIdFromBundle("foo",this._createBundleAssetId("foo","bar")))throw new Error("[Resolver] GenerateBundleAssetId are not working correctly")}prefer(...preferOrders){preferOrders.forEach(prefer=>{this._preferredOrder.push(prefer),prefer.priority||(prefer.priority=Object.keys(prefer.params))}),this._resolverHash={}}set basePath(basePath){this._basePath=basePath}get basePath(){return this._basePath}set rootPath(rootPath){this._rootPath=rootPath}get rootPath(){return this._rootPath}get parsers(){return this._parsers}reset(){this.setBundleIdentifier(this._defaultBundleIdentifierOptions),this._assetMap={},this._preferredOrder=[],this._resolverHash={},this._rootPath=null,this._basePath=null,this._manifest=null,this._bundles={},this._defaultSearchParams=null}setDefaultSearchParams(searchParams){if("string"==typeof searchParams)this._defaultSearchParams=searchParams;else{const queryValues=searchParams;this._defaultSearchParams=Object.keys(queryValues).map(key=>encodeURIComponent(key)+"="+encodeURIComponent(queryValues[key])).join("&")}}getAlias(asset){var{alias:asset,src}=asset;return convertToList(asset||src,value=>"string"==typeof value?value:Array.isArray(value)?value.map(v=>{var _a;return null!=(_a=null==v?void 0:v.src)?_a:v}):null!=value&&value.src?value.src:value,!0)}addManifest(manifest){this._manifest&&warn("[Resolver] Manifest already exists, this will be overwritten"),(this._manifest=manifest).bundles.forEach(bundle=>{this.addBundle(bundle.name,bundle.assets)})}addBundle(bundleId,assets){const assetNames=[];let convertedAssets=assets;(convertedAssets=Array.isArray(assets)?convertedAssets:Object.entries(assets).map(([alias,src])=>"string"==typeof src||Array.isArray(src)?{alias:alias,src:src}:__spreadValues$13({alias:alias},src))).forEach(asset=>{var bundleAssetId,srcs=asset.src,aliases="string"==typeof(aliases=asset.alias)?(bundleAssetId=this._createBundleAssetId(bundleId,aliases),assetNames.push(bundleAssetId),[aliases,bundleAssetId]):(bundleAssetId=aliases.map(name=>this._createBundleAssetId(bundleId,name)),assetNames.push(...bundleAssetId),[...aliases,...bundleAssetId]);this.add(__spreadValues$13(__spreadValues$13({},asset),{alias:aliases,src:srcs}))}),this._bundles[bundleId]=assetNames}add(aliases){var assets=[];Array.isArray(aliases)?assets.push(...aliases):assets.push(aliases);let keyCheck;keyCheck=key=>{this.hasKey(key)&&warn(`[Resolver] already has key: ${key} overwriting`)},convertToList(assets).forEach(asset=>{var src=asset.src;let{data,format,loadParser}=asset;src=convertToList(src).map(src2=>{if("string"!=typeof src2)return Array.isArray(src2)?src2:[src2];var result=src2.match(/\{(.*?)\}/g),tags=[];if(result){const ids=[];result.forEach(vars=>{vars=vars.substring(1,vars.length-1).split(","),ids.push(vars)}),function processX(base,ids,depth,result,tags){var id=ids[depth];for(let i=0;i{srcs.forEach(src2=>{var _a;let formattedAsset={};if("object"!=typeof src2){formattedAsset.src=src2;for(let i=0;i{this._assetMap[alias]=resolvedAssets})})}resolveBundle(bundleIds){var singleAsset=isSingleItem(bundleIds);bundleIds=convertToList(bundleIds);const out={};return bundleIds.forEach(bundleId=>{var assetNames=this._bundles[bundleId];if(assetNames){var results=this.resolve(assetNames),assets={};for(const key in results){var asset=results[key];assets[this._extractAssetIdFromBundle(bundleId,key)]=asset}out[bundleId]=assets}}),singleAsset?out[bundleIds[0]]:out}resolveUrl(key){var result=this.resolve(key);if("string"==typeof key)return result.src;var out={};for(const i in result)out[i]=result[i].src;return out}resolve(keys){var singleAsset=isSingleItem(keys);keys=convertToList(keys);const result={};return keys.forEach(key=>{if(!this._resolverHash[key])if(this._assetMap[key]){let assets=this._assetMap[key];const preferredOrder=this._getPreferredOrder(assets);null!=preferredOrder&&preferredOrder.priority.forEach(priorityKey=>{preferredOrder.params[priorityKey].forEach(value=>{var filteredAssets=assets.filter(asset=>!!asset[priorityKey]&&asset[priorityKey]===value);filteredAssets.length&&(assets=filteredAssets)})}),this._resolverHash[key]=assets[0]}else this._resolverHash[key]=this._buildResolvedAsset({alias:[key],src:key},{});result[key]=this._resolverHash[key]}),singleAsset?result[keys[0]]:result}hasKey(key){return!!this._assetMap[key]}hasBundle(key){return!!this._bundles[key]}_getPreferredOrder(assets){for(let i=0;ipreference.params.format.includes(asset.format));if(preferred)return preferred}return this._preferredOrder[0]}_appendDefaultSearchParams(url){return this._defaultSearchParams?url+(/\?/.test(url)?"&":"?")+this._defaultSearchParams:url}_buildResolvedAsset(formattedAsset,data){var{aliases:data,data:assetData,loadParser,format}=data;return(this._basePath||this._rootPath)&&(formattedAsset.src=path.toAbsolute(formattedAsset.src,this._basePath,this._rootPath)),formattedAsset.alias=null!=(data=null!=data?data:formattedAsset.alias)?data:[formattedAsset.src],formattedAsset.src=this._appendDefaultSearchParams(formattedAsset.src),formattedAsset.data=__spreadValues$13(__spreadValues$13({},assetData||{}),formattedAsset.data),formattedAsset.loadParser=null!=loadParser?loadParser:formattedAsset.loadParser,formattedAsset.format=null!=(data=null!=format?format:formattedAsset.format)?data:formattedAsset.src.split(".").pop().split("?").shift().split("#").shift(),formattedAsset}}Resolver.RETINA_PREFIX=/@([0-9\.]+)x/;const copySearchParams=(targetUrl,sourceUrl)=>((sourceUrl=sourceUrl.split("?")[1])&&(targetUrl+="?"+sourceUrl),targetUrl),_Spritesheet=class _Spritesheet{constructor(texture,data){this.linkedSheets=[],this._texture=texture instanceof Texture?texture:null,this.textureSource=texture.source,this.textures={},this.animations={},this.data=data,(data=parseFloat(data.meta.scale))?(this.resolution=data,texture.source.resolution=this.resolution):this.resolution=texture.source._resolution,this._frames=this.data.frames,this._frameKeys=Object.keys(this._frames),this._batchIndex=0,this._callback=null}parse(){return new Promise(resolve=>{this._callback=resolve,this._batchIndex=0,this._frameKeys.length<=_Spritesheet.BATCH_SIZE?(this._processFrames(0),this._processAnimations(),this._parseComplete()):this._nextBatch()})}_processFrames(initialFrameIndex){let frameIndex=initialFrameIndex;for(var maxFrames=_Spritesheet.BATCH_SIZE;frameIndex-initialFrameIndex{this._batchIndex*_Spritesheet.BATCH_SIZEasset instanceof Spritesheet,getCacheableAssets:(keys,asset)=>function getCacheableAssets(keys,asset,ignoreMultiPack){const out={};if(keys.forEach(key=>{out[key]=asset}),Object.keys(asset.textures).forEach(key=>{out[key]=asset.textures[key]}),!ignoreMultiPack){const basePath=path.dirname(keys[0]);asset.linkedSheets.forEach((item,i)=>{i=getCacheableAssets([basePath+"/"+asset.data.meta.related_multi_packs[i]],item,!0),Object.assign(out,i)})}return out}(keys,asset,!1)},resolver:{extension:{type:"resolve-parser",name:"resolveSpritesheet"},test:value=>{var extension=(value=value.split("?")[0].split(".")).pop(),value=value.pop();return"json"===extension&&validImages.includes(value)},parse:value=>{var _a,split=value.split(".");return{resolution:parseFloat(null!=(_a=null==(_a=Resolver.RETINA_PREFIX.exec(value))?void 0:_a[1])?_a:"1"),format:split[split.length-2],src:value}}},loader:{name:"spritesheetLoader",extension:{type:"load-parser",priority:measureMixin.Normal,name:"spritesheetLoader"},async testParse(asset,options){return".json"===path.extname(options.src).toLowerCase()&&!!asset.frames},async parse(asset,options,loader){var _c,texture,{texture:_a,imageFilename,textureOptions}=null!=(_a=null==options?void 0:options.data)?_a:{};let basePath=path.dirname(options.src);basePath&&basePath.lastIndexOf("/")!==basePath.length-1&&(basePath+="/"),texture=_a instanceof Texture?_a:(_a=copySearchParams(basePath+(null!=imageFilename?imageFilename:asset.meta.image),options.src),(await loader.load([{src:_a,data:textureOptions}]))[_a]);const spritesheet=new Spritesheet(texture.source,asset);if(await spritesheet.parse(),_a=null==(imageFilename=null==asset?void 0:asset.meta)?void 0:imageFilename.related_multi_packs,Array.isArray(_a)){var itemUrl,promises=[];for(const item of _a)"string"!=typeof item||(itemUrl=basePath+item,null!=(_c=options.data)&&_c.ignoreMultiPack)||(itemUrl=copySearchParams(itemUrl,options.src),promises.push(loader.load({src:itemUrl,data:{textureOptions:textureOptions,ignoreMultiPack:!0}})));asset=await Promise.all(promises),(spritesheet.linkedSheets=asset).forEach(item=>{item.linkedSheets=[spritesheet].concat(spritesheet.linkedSheets.filter(sp=>sp!==item))})}return spritesheet},async unload(spritesheet,_resolvedAsset,loader){await loader.unload(spritesheet.textureSource._sourceOrigin),spritesheet.destroy(!1)}}});var __defProp$12=Object.defineProperty,__getOwnPropSymbols$12=Object.getOwnPropertySymbols,__hasOwnProp$12=Object.prototype.hasOwnProperty,__propIsEnum$12=Object.prototype.propertyIsEnumerable,__defNormalProp$12=(obj,key,value)=>key in obj?__defProp$12(obj,key,{enumerable:!0,configurable:!0,writable:!0,value:value}):obj[key]=value;class Sprite extends ViewContainer{constructor(options=Texture.EMPTY){var options=options instanceof Texture?{texture:options}:options,{texture=Texture.EMPTY,anchor,roundPixels,width,height}=options;super(((a,b)=>{for(var prop in b=b||{})__hasOwnProp$12.call(b,prop)&&__defNormalProp$12(a,prop,b[prop]);if(__getOwnPropSymbols$12)for(var prop of __getOwnPropSymbols$12(b))__propIsEnum$12.call(b,prop)&&__defNormalProp$12(a,prop,b[prop]);return a})({label:"Sprite"},((source,exclude)=>{var target={};for(prop in source)__hasOwnProp$12.call(source,prop)&&exclude.indexOf(prop)<0&&(target[prop]=source[prop]);if(null!=source&&__getOwnPropSymbols$12)for(var prop of __getOwnPropSymbols$12(source))exclude.indexOf(prop)<0&&__propIsEnum$12.call(source,prop)&&(target[prop]=source[prop]);return target})(options,["texture","anchor","roundPixels","width","height"]))),this.renderPipeId="sprite",this.batched=!0,this._visualBounds={minX:0,maxX:1,minY:0,maxY:0},this._anchor=new ObservablePoint({_onUpdate:()=>{this.onViewUpdate()}}),anchor?this.anchor=anchor:texture.defaultAnchor&&(this.anchor=texture.defaultAnchor),this.texture=texture,this.allowChildren=!1,this.roundPixels=null!=roundPixels&&roundPixels,void 0!==width&&(this.width=width),void 0!==height&&(this.height=height)}static from(source,skipCache=!1){return source instanceof Texture?new Sprite(source):new Sprite(Texture.from(source,skipCache))}set texture(value){value=value||Texture.EMPTY;var currentTexture=this._texture;currentTexture!==value&&(currentTexture&¤tTexture.dynamic&¤tTexture.off("update",this.onViewUpdate,this),value.dynamic&&value.on("update",this.onViewUpdate,this),this._texture=value,this._width&&this._setWidth(this._width,this._texture.orig.width),this._height&&this._setHeight(this._height,this._texture.orig.height),this.onViewUpdate())}get texture(){return this._texture}get visualBounds(){return updateQuadBounds(this._visualBounds,this._anchor,this._texture),this._visualBounds}get sourceBounds(){return deprecation("8.6.1","Sprite.sourceBounds is deprecated, use visualBounds instead."),this.visualBounds}updateBounds(){var anchor=this._anchor,texture=this._texture,bounds=this._bounds,{width:texture,height}=texture.orig;bounds.minX=-anchor._x*texture,bounds.maxX=bounds.minX+texture,bounds.minY=-anchor._y*height,bounds.maxY=bounds.minY+height}destroy(options=!1){super.destroy(options),("boolean"==typeof options?options:null!=options&&options.texture)&&(options="boolean"==typeof options?options:null==options?void 0:options.textureSource,this._texture.destroy(options)),this._texture=null,this._visualBounds=null,this._bounds=null,this._anchor=null}get anchor(){return this._anchor}set anchor(value){"number"==typeof value?this._anchor.set(value):this._anchor.copyFrom(value)}get width(){return Math.abs(this.scale.x)*this._texture.orig.width}set width(value){this._setWidth(value,this._texture.orig.width),this._width=value}get height(){return Math.abs(this.scale.y)*this._texture.orig.height}set height(value){this._setHeight(value,this._texture.orig.height),this._height=value}getSize(out){return(out=out||{}).width=Math.abs(this.scale.x)*this._texture.orig.width,out.height=Math.abs(this.scale.y)*this._texture.orig.height,out}setSize(value,height){var _a;"object"==typeof value?(height=null!=(_a=value.height)?_a:value.width,value=value.width):null==height&&(height=value),void 0!==value&&this._setWidth(value,this._texture.orig.width),void 0!==height&&this._setHeight(height,this._texture.orig.height)}}const tempBounds$4=new Bounds;function addMaskBounds(mask,bounds,skipUpdateTransform){var boundsToMask=tempBounds$4;mask.measurable=!0,getGlobalBounds(mask,skipUpdateTransform,boundsToMask),bounds.addBoundsMask(boundsToMask),mask.measurable=!1}function addMaskLocalBounds(mask,bounds,localRoot){var boundsToMask=boundsPool.get(),tempMatrix=(mask.measurable=!0,matrixPool.get().identity());getLocalBounds(mask,boundsToMask,function getMatrixRelativeToParent(target,root,matrix){return target?target!==root&&(getMatrixRelativeToParent(target.parent,root,matrix),target.updateLocalTransform(),matrix.append(target.localTransform)):warn("Mask bounds, renderable is not inside the root container"),matrix}(mask,localRoot,tempMatrix)),mask.measurable=!1,bounds.addBoundsMask(boundsToMask),matrixPool.return(tempMatrix),boundsPool.return(boundsToMask)}class AlphaMask{constructor(options){this.priority=0,this.inverse=!1,this.pipe="alphaMask",null!=options&&options.mask&&this.init(options.mask)}init(mask){this.mask=mask,this.renderMaskToTexture=!(mask instanceof Sprite),this.mask.renderable=this.renderMaskToTexture,this.mask.includeInBuild=!this.renderMaskToTexture,this.mask.measurable=!1}reset(){this.mask.measurable=!0,this.mask=null}addBounds(bounds,skipUpdateTransform){this.inverse||addMaskBounds(this.mask,bounds,skipUpdateTransform)}addLocalBounds(bounds,localRoot){addMaskLocalBounds(this.mask,bounds,localRoot)}containsPoint(point,hitTestFn){return hitTestFn(this.mask,point)}destroy(){this.reset()}static test(mask){return mask instanceof Sprite}}class ColorMask{constructor(options){this.priority=0,this.pipe="colorMask",null!=options&&options.mask&&this.init(options.mask)}init(mask){this.mask=mask}destroy(){}static test(mask){return"number"==typeof mask}}class StencilMask{constructor(options){this.priority=0,this.pipe="stencilMask",null!=options&&options.mask&&this.init(options.mask)}init(mask){this.mask=mask,this.mask.includeInBuild=!1,this.mask.measurable=!1}reset(){this.mask.measurable=!0,this.mask.includeInBuild=!0,this.mask=null}addBounds(bounds,skipUpdateTransform){addMaskBounds(this.mask,bounds,skipUpdateTransform)}addLocalBounds(bounds,localRoot){addMaskLocalBounds(this.mask,bounds,localRoot)}containsPoint(point,hitTestFn){return hitTestFn(this.mask,point)}destroy(){this.reset()}static test(mask){return mask instanceof Container}}StencilMask.extension=ColorMask.extension=AlphaMask.extension="mask-effect";class CanvasSource extends TextureSource{constructor(options){options.resource||(options.resource=DOMAdapter.get().createCanvas()),options.width||(options.width=options.resource.width,options.autoDensity)||(options.width/=options.resolution),options.height||(options.height=options.resource.height,options.autoDensity)||(options.height/=options.resolution),super(options),this.uploadMethodId="image",this.autoDensity=options.autoDensity,this.resizeCanvas(),this.transparent=!!options.transparent}resizeCanvas(){this.autoDensity&&"style"in this.resource&&(this.resource.style.width=this.width+"px",this.resource.style.height=this.height+"px"),this.resource.width===this.pixelWidth&&this.resource.height===this.pixelHeight||(this.resource.width=this.pixelWidth,this.resource.height=this.pixelHeight)}resize(width=this.width,height=this.height,resolution=this._resolution){return(width=super.resize(width,height,resolution))&&this.resizeCanvas(),width}static test(resource){return globalThis.HTMLCanvasElement&&resource instanceof HTMLCanvasElement||globalThis.OffscreenCanvas&&resource instanceof OffscreenCanvas}get context2D(){return this._context2D||(this._context2D=this.resource.getContext("2d"))}}CanvasSource.extension="texture-source";class ImageSource extends TextureSource{constructor(options){var canvas;options.resource&&globalThis.HTMLImageElement&&options.resource instanceof HTMLImageElement&&((canvas=DOMAdapter.get().createCanvas(options.resource.width,options.resource.height)).getContext("2d").drawImage(options.resource,0,0,options.resource.width,options.resource.height),options.resource=canvas,warn("ImageSource: Image element passed, converting to canvas. Use CanvasSource instead.")),super(options),this.uploadMethodId="image",this.autoGarbageCollect=!0}static test(resource){return globalThis.HTMLImageElement&&resource instanceof HTMLImageElement||"undefined"!=typeof ImageBitmap&&resource instanceof ImageBitmap||globalThis.VideoFrame&&resource instanceof VideoFrame}}ImageSource.extension="texture-source";let promise;async function detectVideoAlphaMode(){return null!=promise?promise:promise=(async()=>{var texture,framebuffer,video,gl=document.createElement("canvas").getContext("webgl");return gl&&(video=await new Promise(resolve=>{const video2=document.createElement("video");video2.onloadeddata=()=>resolve(video2),video2.onerror=()=>resolve(null),video2.autoplay=!1,video2.crossOrigin="anonymous",video2.preload="auto",video2.src="data:video/webm;base64,GkXfo59ChoEBQveBAULygQRC84EIQoKEd2VibUKHgQJChYECGFOAZwEAAAAAAAHTEU2bdLpNu4tTq4QVSalmU6yBoU27i1OrhBZUrmtTrIHGTbuMU6uEElTDZ1OsggEXTbuMU6uEHFO7a1OsggG97AEAAAAAAABZAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAVSalmoCrXsYMPQkBNgIRMYXZmV0GETGF2ZkSJiEBEAAAAAAAAFlSua8yuAQAAAAAAAEPXgQFzxYgAAAAAAAAAAZyBACK1nIN1bmSIgQCGhVZfVlA5g4EBI+ODhAJiWgDglLCBArqBApqBAlPAgQFVsIRVuYEBElTDZ9Vzc9JjwItjxYgAAAAAAAAAAWfInEWjh0VOQ09ERVJEh49MYXZjIGxpYnZweC12cDlnyKJFo4hEVVJBVElPTkSHlDAwOjAwOjAwLjA0MDAwMDAwMAAAH0O2dcfngQCgwqGggQAAAIJJg0IAABAAFgA4JBwYSgAAICAAEb///4r+AAB1oZ2mm+6BAaWWgkmDQgAAEAAWADgkHBhKAAAgIABIQBxTu2uRu4+zgQC3iveBAfGCAXHwgQM=",video2.load()}))&&(texture=gl.createTexture(),gl.bindTexture(gl.TEXTURE_2D,texture),framebuffer=gl.createFramebuffer(),gl.bindFramebuffer(gl.FRAMEBUFFER,framebuffer),gl.framebufferTexture2D(gl.FRAMEBUFFER,gl.COLOR_ATTACHMENT0,gl.TEXTURE_2D,texture,0),gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL,!1),gl.pixelStorei(gl.UNPACK_COLORSPACE_CONVERSION_WEBGL,gl.NONE),gl.texImage2D(gl.TEXTURE_2D,0,gl.RGBA,gl.RGBA,gl.UNSIGNED_BYTE,video),video=new Uint8Array(4),gl.readPixels(0,0,1,1,gl.RGBA,gl.UNSIGNED_BYTE,video),gl.deleteFramebuffer(framebuffer),gl.deleteTexture(texture),null!=(framebuffer=gl.getExtension("WEBGL_lose_context"))&&framebuffer.loseContext(),video[0]<=video[3])?"premultiplied-alpha":"premultiply-alpha-on-upload"})(),promise}var __defProp$11=Object.defineProperty,__defProps$o=Object.defineProperties,__getOwnPropDescs$o=Object.getOwnPropertyDescriptors,__getOwnPropSymbols$11=Object.getOwnPropertySymbols,__hasOwnProp$11=Object.prototype.hasOwnProperty,__propIsEnum$11=Object.prototype.propertyIsEnumerable,__defNormalProp$11=(obj,key,value)=>key in obj?__defProp$11(obj,key,{enumerable:!0,configurable:!0,writable:!0,value:value}):obj[key]=value,__spreadValues$11=(a,b)=>{for(var prop in b=b||{})__hasOwnProp$11.call(b,prop)&&__defNormalProp$11(a,prop,b[prop]);if(__getOwnPropSymbols$11)for(var prop of __getOwnPropSymbols$11(b))__propIsEnum$11.call(b,prop)&&__defNormalProp$11(a,prop,b[prop]);return a};const _VideoSource=class _VideoSource extends TextureSource{constructor(options){var _a;super(options),this.isReady=!1,this.uploadMethodId="video",options=__spreadValues$11(__spreadValues$11({},_VideoSource.defaultOptions),options),this._autoUpdate=!0,this._isConnectedToTicker=!1,this._updateFPS=options.updateFPS||0,this._msToNextUpdate=0,this.autoPlay=!1!==options.autoPlay,this.alphaMode=null!=(_a=options.alphaMode)?_a:"premultiply-alpha-on-upload",this._videoFrameRequestCallback=this._videoFrameRequestCallback.bind(this),this._videoFrameRequestCallbackHandle=null,this._load=null,this._resolve=null,this._reject=null,this._onCanPlay=this._onCanPlay.bind(this),this._onCanPlayThrough=this._onCanPlayThrough.bind(this),this._onError=this._onError.bind(this),this._onPlayStart=this._onPlayStart.bind(this),this._onPlayStop=this._onPlayStop.bind(this),this._onSeeked=this._onSeeked.bind(this),!1!==options.autoLoad&&this.load()}updateFrame(){var elapsedMS;this.destroyed||(this._updateFPS&&(elapsedMS=Ticker.shared.elapsedMS*this.resource.playbackRate,this._msToNextUpdate=Math.floor(this._msToNextUpdate-elapsedMS)),(!this._updateFPS||this._msToNextUpdate<=0)&&(this._msToNextUpdate=this._updateFPS?Math.floor(1e3/this._updateFPS):0),this.isValid&&this.update())}_videoFrameRequestCallback(){this.updateFrame(),this.destroyed?this._videoFrameRequestCallbackHandle=null:this._videoFrameRequestCallbackHandle=this.resource.requestVideoFrameCallback(this._videoFrameRequestCallback)}get isValid(){return!!this.resource.videoWidth&&!!this.resource.videoHeight}async load(){if(!this._load){const source=this.resource,options=this.options;(source.readyState===source.HAVE_ENOUGH_DATA||source.readyState===source.HAVE_FUTURE_DATA)&&source.width&&source.height&&(source.complete=!0),source.addEventListener("play",this._onPlayStart),source.addEventListener("pause",this._onPlayStop),source.addEventListener("seeked",this._onSeeked),this._isSourceReady()?this._mediaReady():(options.preload||source.addEventListener("canplay",this._onCanPlay),source.addEventListener("canplaythrough",this._onCanPlayThrough),source.addEventListener("error",this._onError,!0)),this.alphaMode=await detectVideoAlphaMode(),this._load=new Promise((resolve,reject)=>{this.isValid?resolve(this):(this._resolve=resolve,this._reject=reject,void 0!==options.preloadTimeoutMs&&(this._preloadTimeout=setTimeout(()=>{this._onError(new ErrorEvent(`Preload exceeded timeout of ${options.preloadTimeoutMs}ms`))})),source.load())})}return this._load}_onError(event){this.resource.removeEventListener("error",this._onError,!0),this.emit("error",event),this._reject&&(this._reject(event),this._reject=null,this._resolve=null)}_isSourcePlaying(){var source=this.resource;return!source.paused&&!source.ended}_isSourceReady(){return 2__defProps$o(a,__getOwnPropDescs$o({autoLoad:!0,autoPlay:!0,updateFPS:0,crossorigin:!0,loop:!1,muted:!0,playsinline:!0,preload:!1})))(__spreadValues$11({},TextureSource.defaultOptions)),_VideoSource.MIME_TYPES={ogv:"video/ogg",mov:"video/quicktime",m4v:"video/mp4"};let VideoSource=_VideoSource;const Cache=new class{constructor(){this._parsers=[],this._cache=new Map,this._cacheMap=new Map}reset(){this._cacheMap.clear(),this._cache.clear()}has(key){return this._cache.has(key)}get(key){var result=this._cache.get(key);return result||warn(`[Assets] Asset id ${key} was not found in the Cache`),result}set(key,value){var keys=convertToList(key);let cacheableAssets;for(let i=0;i{cacheableMap.set(key2,value)}),{cacheKeys:key=[...cacheableMap.keys()],keys:keys});keys.forEach(key2=>{this._cacheMap.set(key2,cachedAssets)}),key.forEach(key2=>{var val=cacheableAssets?cacheableAssets[key2]:value;this._cache.has(key2)&&this._cache.get(key2)!==val&&warn("[Cache] already has key:",key2),this._cache.set(key2,cacheableMap.get(key2))})}remove(key){var cacheMap;this._cacheMap.has(key)?((cacheMap=this._cacheMap.get(key)).cacheKeys.forEach(key2=>{this._cache.delete(key2)}),cacheMap.keys.forEach(key2=>{this._cacheMap.delete(key2)})):warn(`[Assets] Asset id ${key} was not found in the Cache`)}get parsers(){return this._parsers}},sources=[];function textureSourceFrom(options={}){var hasResource=options&&options.resource,res=hasResource?options.resource:options,opts=hasResource?options:{resource:options};for(let i=0;i{Cache.has(resource)&&Cache.remove(resource)}),skipCache||Cache.set(resource,options),options)}(id,skipCache)},TextureSource.from=textureSourceFrom,extensions.add(AlphaMask,ColorMask,StencilMask,VideoSource,ImageSource,CanvasSource,BufferImageSource);class BindGroup{constructor(resources){this.resources=Object.create(null),this._dirty=!0;let index=0;for(const i in resources){var resource=resources[i];this.setResource(resource,index++)}this._updateKey()}_updateKey(){if(this._dirty){this._dirty=!1;var keyParts=[];let index=0;for(const i in this.resources)keyParts[index++]=this.resources[i]._resourceId;this._key=keyParts.join("|")}}setResource(resource,index){var currentResource=this.resources[index];resource!==currentResource&&(currentResource&&null!=(currentResource=resource.off)&¤tResource.call(resource,"change",this.onResourceChange,this),null!=(currentResource=resource.on)&¤tResource.call(resource,"change",this.onResourceChange,this),this.resources[index]=resource,this._dirty=!0)}getResource(index){return this.resources[index]}_touch(tick){var resources=this.resources;for(const i in resources)resources[i]._touched=tick}destroy(){var _a,resources=this.resources;for(const i in resources){var resource=resources[i];null!=(_a=resource.off)&&_a.call(resource,"change",this.onResourceChange,this)}this.resources=null}onResourceChange(resource){if(this._dirty=!0,resource.destroyed){var resources=this.resources;for(const i in resources)resources[i]===resource&&(resources[i]=null)}else this._updateKey()}}let context;function getTestContext(){var canvas;return(!context||null!=context&&context.isContextLost())&&(canvas=DOMAdapter.get().createCanvas(),context=canvas.getContext("webgl",{})),context}const fragTemplate$1=["precision mediump float;","void main(void){","float test = 0.1;","%forloop%","gl_FragColor = vec4(0.0);","}"].join("\n");let maxTexturesPerBatchCache=null;function getMaxTexturesPerBatch(){var gl;return maxTexturesPerBatchCache||(gl=getTestContext(),maxTexturesPerBatchCache=function(maxIfs,gl){if(0===maxIfs)throw new Error("Invalid value of `0` passed to `checkMaxIfStatementsInShader`");var shader=gl.createShader(gl.FRAGMENT_SHADER);try{for(;;){var fragmentSrc=fragTemplate$1.replace(/%forloop%/gi,function(maxIfs){let src="";for(let i=0;i>>=0;return cachedGroups[uid]||function(textures,size,key){var bindGroupResources={};let bindIndex=0;maxTextures=maxTextures||getMaxTexturesPerBatch();for(let i=0;ikey in obj?__defProp$10(obj,key,{enumerable:!0,configurable:!0,writable:!0,value:value}):obj[key]=value,__spreadValues$10=(a,b)=>{for(var prop in b=b||{})__hasOwnProp$10.call(b,prop)&&__defNormalProp$10(a,prop,b[prop]);if(__getOwnPropSymbols$10)for(var prop of __getOwnPropSymbols$10(b))__propIsEnum$10.call(b,prop)&&__defNormalProp$10(a,prop,b[prop]);return a};class Batch{constructor(){this.renderPipeId="batch",this.action="startBatch",this.start=0,this.size=0,this.textures=new BatchTextureArray,this.blendMode="normal",this.topology="triangle-strip",this.canBundle=!0}destroy(){this.textures=null,this.gpuBindGroup=null,this.bindGroup=null,this.batcher=null}}const batchPool=[];let batchPoolIndex=0;function getBatchFromPool(){return 0this.attributeBuffer.size&&this._resizeAttributeBuffer(4*this.attributeSize),this.indexSize>this.indexBuffer.length&&this._resizeIndexBuffer(this.indexSize);var f32=this.attributeBuffer.float32View,u32=this.attributeBuffer.uint32View,indexBuffer=this.indexBuffer;let size=this._batchIndexSize,start=this._batchIndexStart,action="startBatch";var maxTextures=this.maxTextures;for(let i=this.elementStart;i=maxTextures||breakRequired)&&(this._finishBatch(batch,start,size-start,textureBatch,blendMode,topology,instructionSet,action),action="renderBatch",start=size,blendMode=adjustedBlendMode,topology=element.topology,batch=getBatchFromPool(),(textureBatch=batch.textures).clear(),++BATCH_TICK),element._textureId=texture._textureBindLocation=textureBatch.count,textureBatch.ids[texture.uid]=textureBatch.count,textureBatch.textures[textureBatch.count++]=texture,element._batch=batch,size+=element.indexSize,element.packAsQuad?(this.packQuadAttributes(element,f32,u32,element._attributeStart,element._textureId),this.packQuadIndex(indexBuffer,element._indexStart,element._attributeStart/this.vertexSize)):(this.packAttributes(element,f32,u32,element._attributeStart,element._textureId),this.packIndex(element,indexBuffer,element._indexStart,element._attributeStart/this.vertexSize))):(element._textureId=texture._textureBindLocation,size+=element.indexSize,element.packAsQuad?(this.packQuadAttributes(element,f32,u32,element._attributeStart,element._textureId),this.packQuadIndex(indexBuffer,element._indexStart,element._attributeStart/this.vertexSize)):(this.packAttributes(element,f32,u32,element._attributeStart,element._textureId),this.packIndex(element,indexBuffer,element._indexStart,element._attributeStart/this.vertexSize)),element._batch=batch)}0maxX&&(maxX=x),y>maxY&&(maxY=y),xbuffer.destroy()),this.attributes=null,this.buffers=null,this.indexBuffer=null,this._bounds=null}}const placeHolderBufferData=new Float32Array(1),placeHolderIndexData=new Uint32Array(1);class BatchGeometry extends Geometry{constructor(){var attributeBuffer=new Buffer({data:placeHolderBufferData,label:"attribute-batch-buffer",usage:BufferUsage.VERTEX|BufferUsage.COPY_DST,shrinkToFit:!1});super({attributes:{aPosition:{buffer:attributeBuffer,format:"float32x2",stride:24,offset:0},aUV:{buffer:attributeBuffer,format:"float32x2",stride:24,offset:8},aColor:{buffer:attributeBuffer,format:"unorm8x4",stride:24,offset:16},aTextureIdAndRound:{buffer:attributeBuffer,format:"uint16x2",stride:24,offset:20}},indexBuffer:new Buffer({data:placeHolderIndexData,label:"index-batch-buffer",usage:BufferUsage.INDEX|BufferUsage.COPY_DST,shrinkToFit:!1})})}}const idCounts=Object.create(null),idHash=Object.create(null);function createIdFromString(value,groupId){let id=idHash[value];return void 0===id&&(void 0===idCounts[groupId]&&(idCounts[groupId]=1),idHash[value]=id=idCounts[groupId]++),id}let maxFragmentPrecision;const fragmentNameCache={},VertexNameCache={};var __defProp$$=Object.defineProperty,__getOwnPropSymbols$$=Object.getOwnPropertySymbols,__hasOwnProp$$=Object.prototype.hasOwnProperty,__propIsEnum$$=Object.prototype.propertyIsEnumerable,__defNormalProp$$=(obj,key,value)=>key in obj?__defProp$$(obj,key,{enumerable:!0,configurable:!0,writable:!0,value:value}):obj[key]=value,__spreadValues$$=(a,b)=>{for(var prop in b=b||{})__hasOwnProp$$.call(b,prop)&&__defNormalProp$$(a,prop,b[prop]);if(__getOwnPropSymbols$$)for(var prop of __getOwnPropSymbols$$(b))__propIsEnum$$.call(b,prop)&&__defNormalProp$$(a,prop,b[prop]);return a};const processes={stripVersion:function(src,isES300){return isES300?src.replace("#version 300 es",""):src},ensurePrecision:function(src,options,isFragment){var maxSupportedPrecision=isFragment?options.maxSupportedFragmentPrecision:options.maxSupportedVertexPrecision;return"precision"===src.substring(0,9)?"highp"!==maxSupportedPrecision&&"precision highp"===src.substring(0,15)?src.replace("precision highp","precision mediump"):src:`precision ${isFragment="highp"===(isFragment=isFragment?options.requestedFragmentPrecision:options.requestedVertexPrecision)&&"highp"!==maxSupportedPrecision?"mediump":isFragment} float; +`+src},addProgramDefines:function(src,isES300,isFragment){return isES300?src:isFragment?` + + #ifdef GL_ES // This checks if it is WebGL1 + #define in varying + #define finalColor gl_FragColor + #define texture texture2D + #endif + ${src=src.replace("out vec4 finalColor;","")} + `:` + + #ifdef GL_ES // This checks if it is WebGL1 + #define in attribute + #define out varying + #endif + ${src} + `},setProgramName:function(src,{name="pixi-program"},isFragment=!0){return name=name.replace(/\s+/g,"-"),name+=isFragment?"-fragment":"-vertex",(isFragment=isFragment?fragmentNameCache:VertexNameCache)[name]?(isFragment[name]++,name+="-"+isFragment[name]):isFragment[name]=1,-1!==src.indexOf("#define SHADER_NAME")?src:"#define SHADER_NAME "+name+` +`+src},insertVersion:function(src,isES300){return isES300?`#version 300 es +`+src:src}},programCache$1=Object.create(null),_GlProgram=class _GlProgram{constructor(options){var gl,isES300=-1!==(options=__spreadValues$$(__spreadValues$$({},_GlProgram.defaultOptions),options)).fragment.indexOf("#version 300 es");const preprocessorOptions={stripVersion:isES300,ensurePrecision:{requestedFragmentPrecision:options.preferredFragmentPrecision,requestedVertexPrecision:options.preferredVertexPrecision,maxSupportedVertexPrecision:"highp",maxSupportedFragmentPrecision:(maxFragmentPrecision||(maxFragmentPrecision="mediump",(gl=getTestContext())&&gl.getShaderPrecisionFormat&&(gl=gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER,gl.HIGH_FLOAT),maxFragmentPrecision=gl.precision?"highp":"mediump")),maxFragmentPrecision)},setProgramName:{name:options.name},addProgramDefines:isES300,insertVersion:isES300};let fragment=options.fragment,vertex=options.vertex;Object.keys(processes).forEach(processKey=>{var processOptions=preprocessorOptions[processKey];fragment=processes[processKey](fragment,processOptions,!0),vertex=processes[processKey](vertex,processOptions,!1)}),this.fragment=fragment,this.vertex=vertex,this.transformFeedbackVaryings=options.transformFeedbackVaryings,this._key=createIdFromString(this.vertex+":"+this.fragment,"gl-program")}destroy(){this.fragment=null,this.vertex=null,this._attributeData=null,this._uniformData=null,this._uniformBlockData=null,this.transformFeedbackVaryings=null}static from(options){var key=options.vertex+":"+options.fragment;return programCache$1[key]||(programCache$1[key]=new _GlProgram(options)),programCache$1[key]}};_GlProgram.defaultOptions={preferredVertexPrecision:"highp",preferredFragmentPrecision:"mediump"};let GlProgram=_GlProgram;const attributeFormatData={uint8x2:{size:2,stride:2,normalised:!1},uint8x4:{size:4,stride:4,normalised:!1},sint8x2:{size:2,stride:2,normalised:!1},sint8x4:{size:4,stride:4,normalised:!1},unorm8x2:{size:2,stride:2,normalised:!0},unorm8x4:{size:4,stride:4,normalised:!0},snorm8x2:{size:2,stride:2,normalised:!0},snorm8x4:{size:4,stride:4,normalised:!0},uint16x2:{size:2,stride:4,normalised:!1},uint16x4:{size:4,stride:8,normalised:!1},sint16x2:{size:2,stride:4,normalised:!1},sint16x4:{size:4,stride:8,normalised:!1},unorm16x2:{size:2,stride:4,normalised:!0},unorm16x4:{size:4,stride:8,normalised:!0},snorm16x2:{size:2,stride:4,normalised:!0},snorm16x4:{size:4,stride:8,normalised:!0},float16x2:{size:2,stride:4,normalised:!1},float16x4:{size:4,stride:8,normalised:!1},float32:{size:1,stride:4,normalised:!1},float32x2:{size:2,stride:8,normalised:!1},float32x3:{size:3,stride:12,normalised:!1},float32x4:{size:4,stride:16,normalised:!1},uint32:{size:1,stride:4,normalised:!1},uint32x2:{size:2,stride:8,normalised:!1},uint32x3:{size:3,stride:12,normalised:!1},uint32x4:{size:4,stride:16,normalised:!1},sint32:{size:1,stride:4,normalised:!1},sint32x2:{size:2,stride:8,normalised:!1},sint32x3:{size:3,stride:12,normalised:!1},sint32x4:{size:4,stride:16,normalised:!1}};function getAttributeInfoFromFormat(format){return null!=(format=attributeFormatData[format])?format:attributeFormatData.float32}const WGSL_TO_VERTEX_TYPES={f32:"float32","vec2":"float32x2","vec3":"float32x3","vec4":"float32x4",vec2f:"float32x2",vec3f:"float32x3",vec4f:"float32x4",i32:"sint32","vec2":"sint32x2","vec3":"sint32x3","vec4":"sint32x4",u32:"uint32","vec2":"uint32x2","vec3":"uint32x3","vec4":"uint32x4",bool:"uint32","vec2":"uint32x2","vec3":"uint32x3","vec4":"uint32x4"};function extractStructAndGroups(wgsl){const groupPattern=/@group\((\d+)\)/,bindingPattern=/@binding\((\d+)\)/,namePattern=/var(<[^>]+>)? (\w+)/,typePattern=/:\s*(\w+)/;var _a;const structMemberPattern=/(\w+)\s*:\s*([\w\<\>]+)/g,structName=/struct\s+(\w+)/,groups=null==(_a=wgsl.match(/(^|[^/])@(group|binding)\(\d+\)[^;]+;/g))?void 0:_a.map(item=>({group:parseInt(item.match(groupPattern)[1],10),binding:parseInt(item.match(bindingPattern)[1],10),name:item.match(namePattern)[2],isUniform:""===item.match(namePattern)[1],type:item.match(typePattern)[1]}));return groups?(_a=null!=(wgsl=null==(_a=wgsl.match(/struct\s+(\w+)\s*{([^}]+)}/g))?void 0:_a.map(struct=>{var name=struct.match(structName)[1];return(struct=struct.match(structMemberPattern).reduce((acc,member)=>{var[member,type]=member.split(":");return acc[member.trim()]=type.trim(),acc},{}))?{name:name,members:struct}:null}).filter(({name})=>groups.some(group=>group.type===name)))?wgsl:[],{groups:groups,structs:_a}):{groups:[],structs:[]}}var ShaderStage=getGlobalMixin={VERTEX:1,1:"VERTEX",FRAGMENT:2,2:"FRAGMENT",COMPUTE:4,4:"COMPUTE"};const programCache=Object.create(null);class GpuProgram{constructor(options){this._layoutKey=0,this._attributeLocationsKey=0;var{fragment:options,vertex,layout,gpuLayout,name}=options;this.name=name,this.fragment=options,this.vertex=vertex,options.source===vertex.source?(name=extractStructAndGroups(options.source),this.structsAndGroups=name):(name=extractStructAndGroups(vertex.source),vertex=extractStructAndGroups(options.source),this.structsAndGroups=function(vertexStructsAndGroups,fragmentStructsAndGroups){const structNameSet=new Set,dupeGroupKeySet=new Set;return{structs:[...vertexStructsAndGroups.structs,...fragmentStructsAndGroups.structs].filter(struct=>!structNameSet.has(struct.name)&&(structNameSet.add(struct.name),!0)),groups:[...vertexStructsAndGroups.groups,...fragmentStructsAndGroups.groups].filter(group=>(group=group.name+"-"+group.binding,!dupeGroupKeySet.has(group)&&(dupeGroupKeySet.add(group),!0)))}}(name,vertex)),this.layout=null!=layout?layout:function({groups}){var layout=[];for(let i=0;i",entryPoint);if(-1!==arrowFunctionStart)for(var match,functionArgsSubstring=source.substring(entryPoint,arrowFunctionStart),inputsRegex=/@location\((\d+)\)\s+([a-zA-Z0-9_]+)\s*:\s*([a-zA-Z0-9_<>]+)(?:,|\s|$)/g;null!==(match=inputsRegex.exec(functionArgsSubstring));){var _a=null!=(_a=WGSL_TO_VERTEX_TYPES[match[3]])?_a:"float32";results[match[2]]={location:parseInt(match[1],10),format:_a,stride:getAttributeInfoFromFormat(_a).stride,offset:0,instance:!1,start:0}}}return results}(this.vertex)),this._attributeData}destroy(){this.gpuLayout=null,this.layout=null,this.structsAndGroups=null,this.fragment=null,this.vertex=null}static from(options){var key=`${options.vertex.source}:${options.fragment.source}:${options.fragment.entryPoint}:`+options.vertex.entryPoint;return programCache[key]||(programCache[key]=new GpuProgram(options)),programCache[key]}}function addBits(srcParts,parts,name){if(srcParts)for(const i in srcParts){var part=parts[i.toLocaleLowerCase()];if(part){let sanitisedPart=srcParts[i];"header"===i&&(sanitisedPart=sanitisedPart.replace(/@in\s+[^;]+;\s*/g,"").replace(/@out\s+[^;]+;\s*/g,"")),name&&part.push(`//----${name}----//`),part.push(sanitisedPart)}else warn(i+" placement hook does not exist in shader")}}const findHooksRx=/\{\{(.*?)\}\}/g;function compileHooks(programSrc){const parts={};return(null!=(programSrc=null==(programSrc=programSrc.match(findHooksRx))?void 0:programSrc.map(hook=>hook.replace(/[{()}]/g,"")))?programSrc:[]).forEach(hook=>{parts[hook]=[]}),parts}function extractInputs(fragmentSource,out){for(var match,regex=/@in\s+([^;]+);/g;null!==(match=regex.exec(fragmentSource));)out.push(match[1])}function compileInputs(fragments,template,sort=!1){const results=[];extractInputs(template,results),fragments.forEach(fragment=>{fragment.header&&extractInputs(fragment.header,results)}),fragments=results,sort&&fragments.sort(),sort=fragments.map((inValue,i)=>` @location(${i}) ${inValue},`).join("\n");let cleanedString=template.replace(/@in\s+[^;]+;\s*/g,"");return cleanedString=cleanedString.replace("{{in}}",` +${sort} +`)}function extractOutputs(fragmentSource,out){for(var match,regex=/@out\s+([^;]+);/g;null!==(match=regex.exec(fragmentSource));)out.push(match[1])}function injectBits(templateSrc,fragmentParts){let out=templateSrc;for(const i in fragmentParts){var parts=fragmentParts[i],toInject=parts.join("\n");out=toInject.length?out.replace(`{{${i}}}`,`//-----${i} START-----// +${parts.join("\n")} +//----${i} FINISH----//`):out.replace(`{{${i}}}`,"")}return out}const cacheMap=Object.create(null),bitCacheMap=new Map;let CACHE_UID=0;function generateCacheId(template,bits){return bits.map(highFragment=>(bitCacheMap.has(highFragment)||bitCacheMap.set(highFragment,CACHE_UID++),bitCacheMap.get(highFragment))).sort((a,b)=>a-b).join("-")+template.vertex+template.fragment}function compileBits(vertex,fragment,bits){const vertexParts=compileHooks(vertex),fragmentParts=compileHooks(fragment);return bits.forEach(shaderBit=>{addBits(shaderBit.vertex,vertexParts,shaderBit.name),addBits(shaderBit.fragment,fragmentParts,shaderBit.name)}),{vertex:injectBits(vertex,vertexParts),fragment:injectBits(fragment,fragmentParts)}}const vertexGPUTemplate=` + @in aPosition: vec2; + @in aUV: vec2; + + @out @builtin(position) vPosition: vec4; + @out vUV : vec2; + @out vColor : vec4; + + {{header}} + + struct VSOutput { + {{struct}} + }; + + @vertex + fn main( {{in}} ) -> VSOutput { + + var worldTransformMatrix = globalUniforms.uWorldTransformMatrix; + var modelMatrix = mat3x3( + 1.0, 0.0, 0.0, + 0.0, 1.0, 0.0, + 0.0, 0.0, 1.0 + ); + var position = aPosition; + var uv = aUV; + + {{start}} + + vColor = vec4(1., 1., 1., 1.); + + {{main}} + + vUV = uv; + + var modelViewProjectionMatrix = globalUniforms.uProjectionMatrix * worldTransformMatrix * modelMatrix; + + vPosition = vec4((modelViewProjectionMatrix * vec3(position, 1.0)).xy, 0.0, 1.0); + + vColor *= globalUniforms.uWorldColorAlpha; + + {{end}} + + {{return}} + }; +`,fragmentGPUTemplate=` + @in vUV : vec2; + @in vColor : vec4; + + {{header}} + + @fragment + fn main( + {{in}} + ) -> @location(0) vec4 { + + {{start}} + + var outColor:vec4; + + {{main}} + + var finalColor:vec4 = outColor * vColor; + + {{end}} + + return finalColor; + }; +`,vertexGlTemplate=` + in vec2 aPosition; + in vec2 aUV; + + out vec4 vColor; + out vec2 vUV; + + {{header}} + + void main(void){ + + mat3 worldTransformMatrix = uWorldTransformMatrix; + mat3 modelMatrix = mat3( + 1.0, 0.0, 0.0, + 0.0, 1.0, 0.0, + 0.0, 0.0, 1.0 + ); + vec2 position = aPosition; + vec2 uv = aUV; + + {{start}} + + vColor = vec4(1.); + + {{main}} + + vUV = uv; + + mat3 modelViewProjectionMatrix = uProjectionMatrix * worldTransformMatrix * modelMatrix; + + gl_Position = vec4((modelViewProjectionMatrix * vec3(position, 1.0)).xy, 0.0, 1.0); + + vColor *= uWorldColorAlpha; + + {{end}} + } +`,fragmentGlTemplate=` + + in vec4 vColor; + in vec2 vUV; + + out vec4 finalColor; + + {{header}} + + void main(void) { + + {{start}} + + vec4 outColor; + + {{main}} + + finalColor = outColor * vColor; + + {{end}} + } +`,globalUniformsBit={name:"global-uniforms-bit",vertex:{header:` + struct GlobalUniforms { + uProjectionMatrix:mat3x3, + uWorldTransformMatrix:mat3x3, + uWorldColorAlpha: vec4, + uResolution: vec2, + } + + @group(0) @binding(0) var globalUniforms : GlobalUniforms; + `}},globalUniformsBitGl={name:"global-uniforms-bit",vertex:{header:` + uniform mat3 uProjectionMatrix; + uniform mat3 uWorldTransformMatrix; + uniform vec4 uWorldColorAlpha; + uniform vec2 uResolution; + `}};var __defProp$_=Object.defineProperty,__getOwnPropSymbols$_=Object.getOwnPropertySymbols,__hasOwnProp$_=Object.prototype.hasOwnProperty,__propIsEnum$_=Object.prototype.propertyIsEnumerable,__defNormalProp$_=(obj,key,value)=>key in obj?__defProp$_(obj,key,{enumerable:!0,configurable:!0,writable:!0,value:value}):obj[key]=value;function compileHighShaderGpuProgram({bits,name}){return bits=function({template,bits}){var fragment,cacheId=generateCacheId(template,bits);return cacheMap[cacheId]||({vertex:template,fragment}=function(template,bits){var vertexFragments=bits.map(shaderBit=>shaderBit.vertex).filter(v=>!!v),bits=bits.map(shaderBit=>shaderBit.fragment).filter(v=>!!v);return{vertex:function(fragments,template){const results=[];extractOutputs(template,results),fragments.forEach(fragment=>{fragment.header&&extractOutputs(fragment.header,results)});let index=0;var fragments=results.sort().map(inValue=>-1` var ${inValue.replace(/@.*?\s+/g,"")};`).join("\n"),mainEnd=`return VSOutput( + ${results.sort().map(inValue=>" "+((inValue=/\b(\w+)\s*:/g.exec(inValue))?inValue[1]:"")).join(",\n")});`;let compiledCode=template.replace(/@out\s+[^;]+;\s*/g,"");return compiledCode=(compiledCode=(compiledCode=compiledCode.replace("{{struct}}",` +${fragments} +`)).replace("{{start}}",` +${mainStart} +`)).replace("{{return}}",` +${mainEnd} +`)}(vertexFragments,compileInputs(vertexFragments,template.vertex,!0)),fragment:compileInputs(bits,template.fragment,!0)}}(template,bits),cacheMap[cacheId]=compileBits(template,fragment,bits)),cacheMap[cacheId]}({template:{fragment:fragmentGPUTemplate,vertex:vertexGPUTemplate},bits:[globalUniformsBit,...bits]}),GpuProgram.from({name:name,vertex:{source:bits.vertex,entryPoint:"main"},fragment:{source:bits.fragment,entryPoint:"main"}})}function compileHighShaderGlProgram({bits,name}){return new GlProgram(((a,b)=>{for(var prop in b=function({template,bits}){var cacheId=generateCacheId(template,bits);return cacheMap[cacheId]||(cacheMap[cacheId]=compileBits(template.vertex,template.fragment,bits)),cacheMap[cacheId]}({template:{vertex:vertexGlTemplate,fragment:fragmentGlTemplate},bits:[globalUniformsBitGl,...bits]})||{})__hasOwnProp$_.call(b,prop)&&__defNormalProp$_(a,prop,b[prop]);if(__getOwnPropSymbols$_)for(var prop of __getOwnPropSymbols$_(b))__propIsEnum$_.call(b,prop)&&__defNormalProp$_(a,prop,b[prop]);return a})({name:name}))}const colorBit={name:"color-bit",vertex:{header:` + @in aColor: vec4; + `,main:` + vColor *= vec4(aColor.rgb * aColor.a, aColor.a); + `}},colorBitGl={name:"color-bit",vertex:{header:` + in vec4 aColor; + `,main:` + vColor *= vec4(aColor.rgb * aColor.a, aColor.a); + `}},textureBatchBitGpuCache={};function generateTextureBatchBit(maxTextures){return textureBatchBitGpuCache[maxTextures]||(textureBatchBitGpuCache[maxTextures]={name:"texture-batch-bit",vertex:{header:` + @in aTextureIdAndRound: vec2; + @out @interpolate(flat) vTextureId : u32; + `,main:` + vTextureId = aTextureIdAndRound.y; + `,end:` + if(aTextureIdAndRound.x == 1) + { + vPosition = vec4(roundPixels(vPosition.xy, globalUniforms.uResolution), vPosition.zw); + } + `},fragment:{header:` + @in @interpolate(flat) vTextureId: u32; + + ${function(maxTextures){var src=[];if(1===maxTextures)src.push("@group(1) @binding(0) var textureSource1: texture_2d;"),src.push("@group(1) @binding(1) var textureSampler1: sampler;");else{let bindingIndex=0;for(let i=0;i;`),src.push(`@group(1) @binding(${bindingIndex++}) var textureSampler${i+1}: sampler;`)}return src.join("\n")}(maxTextures)} + `,main:` + var uvDx = dpdx(vUV); + var uvDy = dpdy(vUV); + + ${function(maxTextures){var src=[];if(1===maxTextures)src.push("outColor = textureSampleGrad(textureSource1, textureSampler1, vUV, uvDx, uvDy);");else{src.push("switch vTextureId {");for(let i=0;i, targetSize: vec2) -> vec2 + { + return (floor(((position * 0.5 + 0.5) * targetSize) + 0.5) / targetSize) * 2.0 - 1.0; + } + `}},roundPixelsBitGl={name:"round-pixels-bit",vertex:{header:` + vec2 roundPixels(vec2 position, vec2 targetSize) + { + return (floor(((position * 0.5 + 0.5) * targetSize) + 0.5) / targetSize) * 2.0 - 1.0; + } + `}},UNIFORM_TYPES_VALUES=["f32","i32","vec2","vec3","vec4","mat2x2","mat3x3","mat4x4","mat3x2","mat4x2","mat2x3","mat4x3","mat2x4","mat3x4","vec2","vec3","vec4"],UNIFORM_TYPES_MAP=UNIFORM_TYPES_VALUES.reduce((acc,type)=>(acc[type]=!0,acc),{});var __defProp$Z=Object.defineProperty,__getOwnPropSymbols$Z=Object.getOwnPropertySymbols,__hasOwnProp$Z=Object.prototype.hasOwnProperty,__propIsEnum$Z=Object.prototype.propertyIsEnumerable,__defNormalProp$Z=(obj,key,value)=>key in obj?__defProp$Z(obj,key,{enumerable:!0,configurable:!0,writable:!0,value:value}):obj[key]=value,__spreadValues$Z=(a,b)=>{for(var prop in b=b||{})__hasOwnProp$Z.call(b,prop)&&__defNormalProp$Z(a,prop,b[prop]);if(__getOwnPropSymbols$Z)for(var prop of __getOwnPropSymbols$Z(b))__propIsEnum$Z.call(b,prop)&&__defNormalProp$Z(a,prop,b[prop]);return a};const _UniformGroup=class _UniformGroup{constructor(uniformStructures,options){this._touched=0,this.uid=uid$1("uniform"),this._resourceType="uniformGroup",this._resourceId=uid$1("resource"),this.isUniformGroup=!0,this._dirtyId=0,this.destroyed=!1,options=__spreadValues$Z(__spreadValues$Z({},_UniformGroup.defaultOptions),options);var _a,uniforms={};for(const i in this.uniformStructures=uniformStructures){var uniformData=uniformStructures[i];if(uniformData.name=i,uniformData.size=null!=(_a=uniformData.size)?_a:1,!UNIFORM_TYPES_MAP[uniformData.type])throw new Error(`Uniform type ${uniformData.type} is not supported. Supported uniform types are: `+UNIFORM_TYPES_VALUES.join(", "));null==uniformData.value&&(uniformData.value=function(type,size){switch(type){case"f32":return 0;case"vec2":return new Float32Array(2*size);case"vec3":return new Float32Array(3*size);case"vec4":return new Float32Array(4*size);case"mat2x2":return new Float32Array([1,0,0,1]);case"mat3x3":return new Float32Array([1,0,0,0,1,0,0,0,1]);case"mat4x4":return new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1])}return null}(uniformData.type,uniformData.size)),uniforms[i]=uniformData.value}this.uniforms=uniforms,this._dirtyId=1,this.ubo=options.ubo,this.isStatic=options.isStatic,this._signature=createIdFromString(Object.keys(uniforms).map(i=>i+"-"+uniformStructures[i].type).join("-"),"uniform-group")}update(){this._dirtyId++}};_UniformGroup.defaultOptions={ubo:!1,isStatic:!1};let UniformGroup=_UniformGroup;const batchSamplersUniformGroupHash={};function getBatchSamplersUniformGroup(maxTextures){var batchSamplersUniformGroup=batchSamplersUniformGroupHash[maxTextures];if(!batchSamplersUniformGroup){var sampleValues=new Int32Array(maxTextures);for(let i=0;ikey in obj?__defProp$Y(obj,key,{enumerable:!0,configurable:!0,writable:!0,value:value}):obj[key]=value;class Shader extends EventEmitter{constructor(options){super(),this.uid=uid$1("shader"),this._uniformBindMap=Object.create(null),this._ownedBindGroups=[];let{gpuProgram,glProgram,groups,resources,compatibleRenderers,groupMap}=options;this.gpuProgram=gpuProgram,this.glProgram=glProgram,void 0===compatibleRenderers&&(compatibleRenderers=0,gpuProgram&&(compatibleRenderers|=2),glProgram)&&(compatibleRenderers|=1),this.compatibleRenderers=compatibleRenderers;const nameHash={};if((resources=resources||groups?resources:{})&&groups)throw new Error("[Shader] Cannot have both resources and groups");if(!gpuProgram&&groups&&!groupMap)throw new Error("[Shader] No group map or WebGPU shader provided - consider using resources instead.");if(!gpuProgram&&groups&&groupMap)for(const i in groupMap)for(const j in groupMap[i]){var uniformName=groupMap[i][j];nameHash[uniformName]={group:i,binding:j,name:uniformName}}else if(gpuProgram&&groups&&!groupMap)options=gpuProgram.structsAndGroups.groups,groupMap={},options.forEach(data=>{groupMap[data.group]=groupMap[data.group]||{},groupMap[data.group][data.binding]=data.name,nameHash[data.name]=data});else if(resources){groups={},groupMap={},gpuProgram&&gpuProgram.structsAndGroups.groups.forEach(data=>{groupMap[data.group]=groupMap[data.group]||{},groupMap[data.group][data.binding]=data.name,nameHash[data.name]=data});let bindTick=0;for(const i in resources)nameHash[i]||(groups[99]||(groups[99]=new BindGroup,this._ownedBindGroups.push(groups[99])),nameHash[i]={group:99,binding:bindTick,name:i},groupMap[99]=groupMap[99]||{},groupMap[99][bindTick]=i,bindTick++);for(const i in resources){var name=i;let value=resources[i];value.source||value._resourceType||(value=new UniformGroup(value)),(name=nameHash[name])&&(groups[name.group]||(groups[name.group]=new BindGroup,this._ownedBindGroups.push(groups[name.group])),groups[name.group].setResource(value,name.binding))}}this.groups=groups,this._uniformBindMap=groupMap,this.resources=this._buildResourceAccessor(groups,nameHash)}addResource(name,groupIndex,bindIndex){var _a;(_a=this._uniformBindMap)[groupIndex]||(_a[groupIndex]={}),(_a=this._uniformBindMap[groupIndex])[bindIndex]||(_a[bindIndex]=name),this.groups[groupIndex]||(this.groups[groupIndex]=new BindGroup,this._ownedBindGroups.push(this.groups[groupIndex]))}_buildResourceAccessor(groups,nameHash){var uniformsOut={};for(const i in nameHash){const data=nameHash[i];Object.defineProperty(uniformsOut,data.name,{get(){return groups[data.group].getResource(data.binding)},set(value){groups[data.group].setResource(value,data.binding)}})}return uniformsOut}destroy(destroyPrograms=!1){this.emit("destroy",this),destroyPrograms&&(null!=(destroyPrograms=this.gpuProgram)&&destroyPrograms.destroy(),null!=(destroyPrograms=this.glProgram))&&destroyPrograms.destroy(),this.gpuProgram=null,this.glProgram=null,this.removeAllListeners(),this._uniformBindMap=null,this._ownedBindGroups.forEach(bindGroup=>{bindGroup.destroy()}),this._ownedBindGroups=null,this.resources=null,this.groups=null}static from(options){var{gpu,gl}=options,options=((source,exclude)=>{var target={};for(prop in source)__hasOwnProp$Y.call(source,prop)&&exclude.indexOf(prop)<0&&(target[prop]=source[prop]);if(null!=source&&__getOwnPropSymbols$Y)for(var prop of __getOwnPropSymbols$Y(source))exclude.indexOf(prop)<0&&__propIsEnum$Y.call(source,prop)&&(target[prop]=source[prop]);return target})(options,["gpu","gl"]);let gpuProgram,glProgram;return gpu&&(gpuProgram=GpuProgram.from(gpu)),gl&&(glProgram=GlProgram.from(gl)),new Shader(((a,b)=>{for(var prop in b=options||{})__hasOwnProp$Y.call(b,prop)&&__defNormalProp$Y(a,prop,b[prop]);if(__getOwnPropSymbols$Y)for(var prop of __getOwnPropSymbols$Y(b))__propIsEnum$Y.call(b,prop)&&__defNormalProp$Y(a,prop,b[prop]);return a})({gpuProgram:gpuProgram,glProgram:glProgram}))}}class DefaultShader extends Shader{constructor(maxTextures){super({glProgram:compileHighShaderGlProgram({name:"batch",bits:[colorBitGl,generateTextureBatchBitGl(maxTextures),roundPixelsBitGl]}),gpuProgram:compileHighShaderGpuProgram({name:"batch",bits:[colorBit,generateTextureBatchBit(maxTextures),roundPixelsBit]}),resources:{batchSamplers:getBatchSamplersUniformGroup(maxTextures)}})}}let defaultShader=null;const _DefaultBatcher=class _DefaultBatcher extends eventemitter3$1{constructor(){super(...arguments),this.geometry=new BatchGeometry,this.shader=defaultShader=defaultShader||new DefaultShader(this.maxTextures),this.name=_DefaultBatcher.extension.name,this.vertexSize=6}packAttributes(element,float32View,uint32View,index,textureId){var textureIdAndRound=textureId<<16|65535&element.roundPixels,a=(textureId=element.transform).a,b=textureId.b,c=textureId.c,d=textureId.d,tx=textureId.tx,ty=textureId.ty,{positions,uvs}=element,argb=element.color,end=(textureId=element.attributeOffset)+element.attributeSize;for(let i=textureId;i>16|65280&rgb|(255&rgb)<<16,renderable=this.renderable;return renderable?multiplyHexColors(rgb,renderable.groupColor)+(this.alpha*renderable.groupAlpha*255<<24):rgb+(255*this.alpha<<24)}get transform(){var _a;return(null==(_a=this.renderable)?void 0:_a.groupTransform)||identityMatrix}copyTo(gpuBuffer){gpuBuffer.indexOffset=this.indexOffset,gpuBuffer.indexSize=this.indexSize,gpuBuffer.attributeOffset=this.attributeOffset,gpuBuffer.attributeSize=this.attributeSize,gpuBuffer.baseColor=this.baseColor,gpuBuffer.alpha=this.alpha,gpuBuffer.texture=this.texture,gpuBuffer.geometryData=this.geometryData,gpuBuffer.topology=this.topology}reset(){this.applyTransform=!0,this.renderable=null,this.topology="triangle-list"}}var __defProp$X=Object.defineProperty,__defProps$n=Object.defineProperties,__getOwnPropDescs$n=Object.getOwnPropertyDescriptors,__getOwnPropSymbols$X=Object.getOwnPropertySymbols,__hasOwnProp$X=Object.prototype.hasOwnProperty,__propIsEnum$X=Object.prototype.propertyIsEnumerable,__defNormalProp$X=(obj,key,value)=>key in obj?__defProp$X(obj,key,{enumerable:!0,configurable:!0,writable:!0,value:value}):obj[key]=value,toLocalGlobalMixin=(getFastGlobalBoundsMixin=(a,b)=>__defProps$n(a,__getOwnPropDescs$n(b)))((NOOP=(a,b)=>{for(var prop in b=b||{})__hasOwnProp$X.call(b,prop)&&__defNormalProp$X(a,prop,b[prop]);if(__getOwnPropSymbols$X)for(var prop of __getOwnPropSymbols$X(b))__propIsEnum$X.call(b,prop)&&__defNormalProp$X(a,prop,b[prop]);return a})({},childrenHelperMixin={extension:{type:ExtensionType2_ShapeBuilder,name:"circle"},build(shape,points){let x,y,dx,dy,rx,ry;if("circle"===shape.type?(x=shape.x,y=shape.y,rx=ry=shape.radius,dx=dy=0):"ellipse"===shape.type?(x=shape.x,y=shape.y,rx=shape.halfWidth,ry=shape.halfHeight,dx=dy=0):(halfWidth=shape.width/2,halfHeight=shape.height/2,x=shape.x+halfWidth,y=shape.y+halfHeight,rx=ry=Math.max(0,Math.min(shape.radius,Math.min(halfWidth,halfHeight))),dx=halfWidth-rx,dy=halfHeight-ry),0<=rx&&0<=ry&&0<=dx&&0<=dy){var n=Math.ceil(2.3*Math.sqrt(rx+ry));if(0!=(shape=8*n+(dx?4:0)+(dy?4:0)))if(0===n)points[0]=points[6]=x+dx,points[1]=points[3]=y+dy,points[2]=points[4]=x-dx,points[5]=points[7]=y-dy;else{let j1=0,j2=4*n+(dx?2:0)+2,j3=j2,j4=shape;var halfWidth=dx+rx,halfHeight=dy,shape=x+halfWidth,x2=x-halfWidth,y1=y+halfHeight;points[j1++]=shape,points[j1++]=y1,points[--j2]=y1,points[--j2]=x2,dy&&(y22=y-halfHeight,points[j3++]=x2,points[j3++]=y22,points[--j4]=y22,points[--j4]=shape);for(let i=1;iangle1&&(angle1+=2*Math.PI);var startAngle=angle0,angleDiff=angle1-angle0,absAngleDiff=Math.abs(angleDiff),radius=Math.sqrt(cx2p0x*cx2p0x+cy2p0y*cy2p0y),segCount=1+(15*absAngleDiff*Math.sqrt(radius)/Math.PI>>0),angleInc=angleDiff/segCount;if(startAngle+=angleInc,clockwise){verts.push(cx,cy),verts.push(sx,sy);for(let i=1,angle=startAngle;i=p.next.y&&p.next.y!==p.y){var x=p.x+(hy-p.y)*(p.next.x-p.x)/(p.next.y-p.y);if(x<=hx&&qx=p.x&&p.x>=mx&&hx!==p.x&&pointInTriangle$1(hym.x||p.x===m.x&&function(m,p){return area(m.prev,m,p.prev)<0&&area(p.next,m,m.next)<0}(m,p)))&&(m=p,tanMin=tan),(p=p.next)!==stop;);return m}(hole,outerNode);return bridge?(filterPoints(hole=splitPolygon(bridge,hole),hole.next),filterPoints(bridge,bridge.next)):outerNode}(queue[i],outerNode);return outerNode}(data,holeIndices,outerNode,dim)),data.length>80*dim){for(var minX=maxX=data[0],minY=maxY=data[1],i=dim;i=minZ&&n&&n.z<=maxZ;){if(p.x>=x0&&p.x<=x1&&p.y>=y0&&p.y<=y1&&p!==a&&p!==c&&pointInTriangle$1(ax,ay,bx,by,cx,cy,p.x,p.y)&&0<=area(p.prev,p,p.next))return;if(p=p.prevZ,n.x>=x0&&n.x<=x1&&n.y>=y0&&n.y<=y1&&n!==a&&n!==c&&pointInTriangle$1(ax,ay,bx,by,cx,cy,n.x,n.y)&&0<=area(n.prev,n,n.next))return;n=n.nextZ}for(;p&&p.z>=minZ;){if(p.x>=x0&&p.x<=x1&&p.y>=y0&&p.y<=y1&&p!==a&&p!==c&&pointInTriangle$1(ax,ay,bx,by,cx,cy,p.x,p.y)&&0<=area(p.prev,p,p.next))return;p=p.prevZ}for(;n&&n.z<=maxZ;){if(n.x>=x0&&n.x<=x1&&n.y>=y0&&n.y<=y1&&n!==a&&n!==c&&pointInTriangle$1(ax,ay,bx,by,cx,cy,n.x,n.y)&&0<=area(n.prev,n,n.next))return;n=n.nextZ}return 1}}(ear,minX,minY,invSize):function(ear){var a=ear.prev,b=ear;if(!(0<=area(a,b,ear=ear.next))){for(var ax=a.x,bx=b.x,cx=ear.x,ay=a.y,by=b.y,cy=ear.y,x0=ax=x0&&p.x<=x1&&p.y>=y0&&p.y<=y1&&pointInTriangle$1(ax,ay,bx,by,cx,cy,p.x,p.y)&&0<=area(p.prev,p,p.next))return;p=p.next}return 1}}(ear))triangles.push(prev.i/dim|0),triangles.push(ear.i/dim|0),triangles.push(next.i/dim|0),removeNode(ear),ear=next.next,stop=next.next;else if((ear=next)===stop){pass?1===pass?earcutLinked(ear=function(start,triangles,dim){var p=start;do{var a=p.prev,b=p.next.next}while(!equals(a,b)&&intersects(a,p,p.next,b)&&locallyInside(a,b)&&locallyInside(b,a)&&(triangles.push(a.i/dim|0),triangles.push(p.i/dim|0),triangles.push(b.i/dim|0),removeNode(p),removeNode(p.next),p=start=b),(p=p.next)!==start);return filterPoints(p)}(filterPoints(ear),triangles,dim),triangles,dim,minX,minY,invSize,2):2===pass&&function(start,triangles,dim,minX,minY,invSize){var a=start;do{for(var c,b=a.next.next;b!==a.prev;){if(a.i!==b.i&&function(a,b){return a.next.i!==b.i&&a.prev.i!==b.i&&!function(a,b){var p=a;do{if(p.i!==a.i&&p.next.i!==a.i&&p.i!==b.i&&p.next.i!==b.i&&intersects(p,p.next,a,b))return 1}while((p=p.next)!==a)}(a,b)&&(locallyInside(a,b)&&locallyInside(b,a)&&function(a,b){for(var p=a,inside=!1,px=(a.x+b.x)/2,py=(a.y+b.y)/2;p.y>py!=p.next.y>py&&p.next.y!==p.y&&px<(p.next.x-p.x)*(py-p.y)/(p.next.y-p.y)+p.x&&(inside=!inside),(p=p.next)!==a;);return inside}(a,b)&&(area(a.prev,a,b.prev)||area(a,b.prev,b))||equals(a,b)&&0=Math.min(p.x,r.x)&&q.y<=Math.max(p.y,r.y)&&q.y>=Math.min(p.y,r.y)}function sign(num){return 0{var indexOffset=indices.length,vertOffset=vertices.length/2,points=[],build=shapeBuilders[shape.type];let topology="triangle-list";if(build.build(shape,points),matrix&&transformVertices(points,matrix),isStroke){var _a=null==(_a=shape.closePath)||_a,lineStyle=style;lineStyle.pixelLine?(function(points,closed,vertices,indices){if(0!==points.length){var fx=points[0],fy=points[1],lx=points[points.length-2],ly=points[points.length-1],closed=closed||Math.abs(fx-lx)<1e-4&&Math.abs(fy-ly)<1e-4,verts=vertices,length=points.length/2,indexStart=verts.length/2;for(let i=0;i{holeIndices.push(otherPoints.length/2),otherPoints.push(...holePoints)}),triangulateWithHoles(otherPoints,holeIndices,vertices,2,vertOffset,indices,indexOffset)}else build.triangulate(points,vertices,2,vertOffset,indices,indexOffset);lineStyle=uvs.length/2,(_a=style.texture)!==Texture.WHITE?(holes=function(out,style,shape,matrix){return out=style.matrix?out.copyFrom(style.matrix).invert():out.identity(),"local"===style.textureSpace?(shape=shape.getBounds(tempRect$3),out.translate(-shape.x,-shape.y),out.scale(1/shape.width,1/shape.height)):(out.translate(style.texture.frame.x,style.texture.frame.y),out.scale(1/style.texture.source.width,1/style.texture.source.height),"clamp-to-edge"===(shape=style.texture.source.style).addressMode&&(shape.addressMode="repeat",shape.update())),matrix&&out.append(tempTextureMatrix$1.copyFrom(matrix).invert()),out}(tempTextureMatrix,style,shape,matrix),function(vertices,verticesOffset,uvs,uvsOffset,size,matrix=null){let index=0;verticesOffset*=2,uvsOffset*=2;for(var a=matrix.a,b=matrix.b,c=matrix.c,d=matrix.d,tx=matrix.tx,ty=matrix.ty;index{BigPool.return(batch)})}destroy(){for(const i in this._gpuContextHash)this._gpuContextHash[i]&&this.onGraphicsContextDestroy(this._gpuContextHash[i].context)}};_GraphicsContextSystem.extension={type:["webgl-system","webgpu-system","canvas-system"],name:"graphicsContext"},_GraphicsContextSystem.defaultOptions={bezierSmoothness:.5};let GraphicsContextSystem=_GraphicsContextSystem;const blendModeIds={normal:0,add:1,multiply:2,screen:3,overlay:4,erase:5,"normal-npm":6,"add-npm":7,"screen-npm":8,min:9,max:10},_State=class _State{constructor(){this.data=0,this.blendMode="normal",this.polygonOffset=0,this.blend=!0,this.depthMask=!0}get blend(){return!!(1&this.data)}set blend(value){!!(1&this.data)!==value&&(this.data^=1)}get offsets(){return!!(2&this.data)}set offsets(value){!!(2&this.data)!==value&&(this.data^=2)}set cullMode(value){"none"===value?this.culling=!1:(this.culling=!0,this.clockwiseFrontFace="front"===value)}get cullMode(){return this.culling?this.clockwiseFrontFace?"front":"back":"none"}get culling(){return!!(4&this.data)}set culling(value){!!(4&this.data)!==value&&(this.data^=4)}get depthTest(){return!!(8&this.data)}set depthTest(value){!!(8&this.data)!==value&&(this.data^=8)}get depthMask(){return!!(32&this.data)}set depthMask(value){!!(32&this.data)!==value&&(this.data^=32)}get clockwiseFrontFace(){return!!(16&this.data)}set clockwiseFrontFace(value){!!(16&this.data)!==value&&(this.data^=16)}get blendMode(){return this._blendMode}set blendMode(value){this.blend="none"!==value,this._blendMode=value,this._blendModeId=blendModeIds[value]||0}get polygonOffset(){return this._polygonOffset}set polygonOffset(value){this.offsets=!!value,this._polygonOffset=value}toString(){return`[pixi.js/core:State blendMode=${this.blendMode} clockwiseFrontFace=${this.clockwiseFrontFace} culling=${this.culling} depthMask=${this.depthMask} polygonOffset=${this.polygonOffset}]`}static for2d(){var state=new _State;return state.depthTest=!1,state.blend=!0,state}};_State.default2d=_State.for2d();let State=_State;function color32BitToUniform(abgr,out,offset){var alpha=(abgr>>24&255)/255;out[offset++]=(255&abgr)/255*alpha,out[offset++]=(abgr>>8&255)/255*alpha,out[offset++]=(abgr>>16&255)/255*alpha,out[offset++]=alpha}class GraphicsPipe{constructor(renderer,adaptor){this.state=State.for2d(),this._graphicsBatchesHash=Object.create(null),this._destroyRenderableBound=this.destroyRenderable.bind(this),this.renderer=renderer,this._adaptor=adaptor,this._adaptor.init(),this.renderer.renderableGC.addManagedHash(this,"_graphicsBatchesHash")}validateRenderable(graphics){var context=graphics.context,graphics=!!this._graphicsBatchesHash[graphics.uid];return!(!(context=this.renderer.graphicsContext.updateGpuContext(context)).isBatchable&&graphics===context.isBatchable)}addRenderable(graphics,instructionSet){var gpuContext=this.renderer.graphicsContext.updateGpuContext(graphics.context);graphics.didViewUpdate&&this._rebuild(graphics),gpuContext.isBatchable?this._addToBatcher(graphics,instructionSet):(this.renderer.renderPipes.batch.break(instructionSet),instructionSet.add(graphics))}updateRenderable(graphics){var batches=this._graphicsBatchesHash[graphics.uid];if(batches)for(let i=0;i{var batchClone=BigPool.get(BatchableGraphics);return batch.copyTo(batchClone),batchClone.renderable=graphics,batchClone.roundPixels=roundPixels,batchClone}),void 0===this._graphicsBatchesHash[graphics.uid]&&graphics.on("destroyed",this._destroyRenderableBound),this._graphicsBatchesHash[graphics.uid]=context}_removeBatchForRenderable(graphicsUid){this._graphicsBatchesHash[graphicsUid].forEach(batch=>{BigPool.return(batch)}),this._graphicsBatchesHash[graphicsUid]=null}destroy(){this.renderer=null,this._adaptor.destroy(),this._adaptor=null,this.state=null;for(const i in this._graphicsBatchesHash)this._removeBatchForRenderable(i);this._graphicsBatchesHash=null}}GraphicsPipe.extension={type:["webgl-pipes","webgpu-pipes","canvas-pipes"],name:"graphics"},extensions.add(GraphicsPipe),extensions.add(GraphicsContextSystem);class BatchableMesh{constructor(){this.batcherName="default",this.packAsQuad=!1,this.indexOffset=0,this.attributeOffset=0,this.roundPixels=0,this._batcher=null,this._batch=null,this._textureMatrixUpdateId=-1,this._uvUpdateId=-1}get blendMode(){return this.renderable.groupBlendMode}get topology(){return this._topology||this.geometry.topology}set topology(value){this._topology=value}reset(){this.renderable=null,this.texture=null,this._batcher=null,this._batch=null,this.geometry=null,this._uvUpdateId=-1,this._textureMatrixUpdateId=-1}setTexture(value){this.texture!==value&&(this.texture=value,this._textureMatrixUpdateId=-1)}get uvs(){var uvBuffer=this.geometry.getBuffer("aUV"),uvs=uvBuffer.data;let transformedUvs=uvs;var textureMatrix=this.texture.textureMatrix;return textureMatrix.isSimple||(transformedUvs=this._transformedUvs,this._textureMatrixUpdateId===textureMatrix._updateID&&this._uvUpdateId===uvBuffer._updateID)||((!transformedUvs||transformedUvs.length"},uColor:{value:new Float32Array([1,1,1,1]),type:"vec4"},uRound:{value:0,type:"f32"}}),this.localUniformsBindGroup=new BindGroup({0:this.localUniforms}),this._meshDataHash=Object.create(null),this._gpuBatchableMeshHash=Object.create(null),this._destroyRenderableBound=this.destroyRenderable.bind(this),this.renderer=renderer,this._adaptor=adaptor,this._adaptor.init(),renderer.renderableGC.addManagedHash(this,"_gpuBatchableMeshHash"),renderer.renderableGC.addManagedHash(this,"_meshDataHash")}validateRenderable(mesh){var meshData=this._getMeshData(mesh),wasBatched=meshData.batched,isBatched=mesh.batched;return wasBatched!==(meshData.batched=isBatched)||!!isBatched&&((wasBatched=mesh._geometry).indices.length!==meshData.indexSize||wasBatched.positions.length!==meshData.vertexSize?(meshData.indexSize=wasBatched.indices.length,meshData.vertexSize=wasBatched.positions.length,!0):((isBatched=this._getBatchableMesh(mesh)).texture.uid!==mesh._texture.uid&&(isBatched._textureMatrixUpdateId=-1),!isBatched._batcher.checkAndUpdateTexture(isBatched,mesh._texture)))}addRenderable(mesh,instructionSet){var batcher=this.renderer.renderPipes.batch,batched=this._getMeshData(mesh).batched;batched?((batched=this._getBatchableMesh(mesh)).setTexture(mesh._texture),batched.geometry=mesh._geometry,batcher.addToBatch(batched,instructionSet)):(batcher.break(instructionSet),instructionSet.add(mesh))}updateRenderable(mesh){var gpuBatchableMesh;mesh.batched&&((gpuBatchableMesh=this._gpuBatchableMeshHash[mesh.uid]).setTexture(mesh._texture),gpuBatchableMesh.geometry=mesh._geometry,gpuBatchableMesh._batcher.updateElement(gpuBatchableMesh))}destroyRenderable(mesh){this._meshDataHash[mesh.uid]=null;var gpuMesh=this._gpuBatchableMeshHash[mesh.uid];gpuMesh&&(BigPool.return(gpuMesh),this._gpuBatchableMeshHash[mesh.uid]=null),mesh.off("destroyed",this._destroyRenderableBound)}execute(mesh){var localUniforms;mesh.isRenderable&&(mesh.state.blendMode=getAdjustedBlendModeBlend(mesh.groupBlendMode,mesh.texture._source),(localUniforms=this.localUniforms).uniforms.uTransformMatrix=mesh.groupTransform,localUniforms.uniforms.uRound=this.renderer._roundPixels|mesh._roundPixels,localUniforms.update(),color32BitToUniform(mesh.groupColorAlpha,localUniforms.uniforms.uColor,0),this._adaptor.execute(this,mesh))}_getMeshData(mesh){return this._meshDataHash[mesh.uid]||this._initMeshData(mesh)}_initMeshData(mesh){var _a;return this._meshDataHash[mesh.uid]={batched:mesh.batched,indexSize:null==(_a=mesh._geometry.indices)?void 0:_a.length,vertexSize:null==(_a=mesh._geometry.positions)?void 0:_a.length},mesh.on("destroyed",this._destroyRenderableBound),this._meshDataHash[mesh.uid]}_getBatchableMesh(mesh){return this._gpuBatchableMeshHash[mesh.uid]||this._initBatchableMesh(mesh)}_initBatchableMesh(mesh){var gpuMesh=BigPool.get(BatchableMesh);return gpuMesh.renderable=mesh,gpuMesh.setTexture(mesh._texture),gpuMesh.transform=mesh.groupTransform,gpuMesh.roundPixels=this.renderer._roundPixels|mesh._roundPixels,this._gpuBatchableMeshHash[mesh.uid]=gpuMesh}destroy(){for(const i in this._gpuBatchableMeshHash)this._gpuBatchableMeshHash[i]&&BigPool.return(this._gpuBatchableMeshHash[i]);this._gpuBatchableMeshHash=null,this._meshDataHash=null,this.localUniforms=null,this.localUniformsBindGroup=null,this._adaptor.destroy(),this._adaptor=null,this.renderer=null}}MeshPipe.extension={type:["webgl-pipes","webgpu-pipes","canvas-pipes"],name:"mesh"},extensions.add(MeshPipe);class GlParticleContainerAdaptor{execute(particleContainerPipe,container){var state=particleContainerPipe.state,renderer=particleContainerPipe.renderer,shader=container.shader||particleContainerPipe.defaultShader,gl=(shader.resources.uTexture=container.texture._source,shader.resources.uniforms=particleContainerPipe.localUniforms,renderer.gl),particleContainerPipe=particleContainerPipe.getBuffers(container);renderer.shader.bind(shader),renderer.state.set(state),renderer.geometry.bind(particleContainerPipe.geometry,shader.glProgram),renderer=2===particleContainerPipe.geometry.indexBuffer.data.BYTES_PER_ELEMENT?gl.UNSIGNED_SHORT:gl.UNSIGNED_INT,gl.drawElements(gl.TRIANGLES,6*container.particleChildren.length,renderer,0)}}function createIndicesForQuads(size,outBuffer=null){var totalIndices=6*size;if((outBuffer=65535this._size&&(uploadStatic=!0,this._size=Math.max(particles.length,1.5*this._size|0),this.staticAttributeBuffer=new ViewableBuffer(this._size*this._staticStride*4*4),this.dynamicAttributeBuffer=new ViewableBuffer(this._size*this._dynamicStride*4*4),this.indexBuffer=createIndicesForQuads(this._size),this.geometry.indexBuffer.setDataWithSize(this.indexBuffer,this.indexBuffer.byteLength,!0));var dynamicAttributeBuffer=this.dynamicAttributeBuffer;this._dynamicUpload(particles,dynamicAttributeBuffer.float32View,dynamicAttributeBuffer.uint32View),this._dynamicBuffer.setDataWithSize(this.dynamicAttributeBuffer.float32View,particles.length*this._dynamicStride*4,!0),uploadStatic&&(dynamicAttributeBuffer=this.staticAttributeBuffer,this._staticUpload(particles,dynamicAttributeBuffer.float32View,dynamicAttributeBuffer.uint32View),this._staticBuffer.setDataWithSize(dynamicAttributeBuffer.float32View,particles.length*this._staticStride*4,!0))}destroy(){this._staticBuffer.destroy(),this._dynamicBuffer.destroy(),this.geometry.destroy()}}var wgsl="\nstruct ParticleUniforms {\n uProjectionMatrix:mat3x3,\n uColor:vec4,\n uResolution:vec2,\n uRoundPixels:f32,\n};\n\n@group(0) @binding(0) var uniforms: ParticleUniforms;\n\n@group(1) @binding(0) var uTexture: texture_2d;\n@group(1) @binding(1) var uSampler : sampler;\n\nstruct VSOutput {\n @builtin(position) position: vec4,\n @location(0) uv : vec2,\n @location(1) color : vec4,\n };\n@vertex\nfn mainVertex(\n @location(0) aVertex: vec2,\n @location(1) aPosition: vec2,\n @location(2) aUV: vec2,\n @location(3) aColor: vec4,\n @location(4) aRotation: f32,\n) -> VSOutput {\n \n let v = vec2(\n aVertex.x * cos(aRotation) - aVertex.y * sin(aRotation),\n aVertex.x * sin(aRotation) + aVertex.y * cos(aRotation)\n ) + aPosition;\n\n let position = vec4((uniforms.uProjectionMatrix * vec3(v, 1.0)).xy, 0.0, 1.0);\n\n let vColor = vec4(aColor.rgb * aColor.a, aColor.a) * uniforms.uColor;\n\n return VSOutput(\n position,\n aUV,\n vColor,\n );\n}\n\n@fragment\nfn mainFragment(\n @location(0) uv: vec2,\n @location(1) color: vec4,\n @builtin(position) position: vec4,\n) -> @location(0) vec4 {\n\n var sample = textureSample(uTexture, uSampler, uv) * color;\n \n return sample;\n}";class ParticleShader extends Shader{constructor(){super({glProgram:GlProgram.from({vertex:"attribute vec2 aVertex;\nattribute vec2 aUV;\nattribute vec4 aColor;\n\nattribute vec2 aPosition;\nattribute float aRotation;\n\nuniform mat3 uTranslationMatrix;\nuniform float uRound;\nuniform vec2 uResolution;\nuniform vec4 uColor;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n\nvec2 roundPixels(vec2 position, vec2 targetSize)\n{ \n return (floor(((position * 0.5 + 0.5) * targetSize) + 0.5) / targetSize) * 2.0 - 1.0;\n}\n\nvoid main(void){\n float cosRotation = cos(aRotation);\n float sinRotation = sin(aRotation);\n float x = aVertex.x * cosRotation - aVertex.y * sinRotation;\n float y = aVertex.x * sinRotation + aVertex.y * cosRotation;\n\n vec2 v = vec2(x, y);\n v = v + aPosition;\n\n gl_Position = vec4((uTranslationMatrix * vec3(v, 1.0)).xy, 0.0, 1.0);\n\n if(uRound == 1.0)\n {\n gl_Position.xy = roundPixels(gl_Position.xy, uResolution);\n }\n\n vUV = aUV;\n vColor = vec4(aColor.rgb * aColor.a, aColor.a) * uColor;\n}\n",fragment:"varying vec2 vUV;\nvarying vec4 vColor;\n\nuniform sampler2D uTexture;\n\nvoid main(void){\n vec4 color = texture2D(uTexture, vUV) * vColor;\n gl_FragColor = color;\n}"}),gpuProgram:GpuProgram.from({fragment:{source:wgsl,entryPoint:"mainFragment"},vertex:{source:wgsl,entryPoint:"mainVertex"}}),resources:{uTexture:Texture.WHITE.source,uSampler:new TextureStyle({}),uniforms:{uTranslationMatrix:{value:new Matrix,type:"mat3x3"},uColor:{value:new Color(16777215),type:"vec4"},uRound:{value:1,type:"f32"},uResolution:{value:[0,0],type:"vec2"}}}})}}class ParticleContainerPipe{constructor(renderer,adaptor){this.state=State.for2d(),this._gpuBufferHash=Object.create(null),this._destroyRenderableBound=this.destroyRenderable.bind(this),this.localUniforms=new UniformGroup({uTranslationMatrix:{value:new Matrix,type:"mat3x3"},uColor:{value:new Float32Array(4),type:"vec4"},uRound:{value:1,type:"f32"},uResolution:{value:[0,0],type:"vec2"}}),this.renderer=renderer,this.adaptor=adaptor,this.defaultShader=new ParticleShader,this.state=State.for2d()}validateRenderable(_renderable){return!1}addRenderable(renderable,instructionSet){this.renderer.renderPipes.batch.break(instructionSet),instructionSet.add(renderable)}getBuffers(renderable){return this._gpuBufferHash[renderable.uid]||this._initBuffer(renderable)}_initBuffer(renderable){return this._gpuBufferHash[renderable.uid]=new ParticleBuffer({size:renderable.particleChildren.length,properties:renderable._properties}),renderable.on("destroyed",this._destroyRenderableBound),this._gpuBufferHash[renderable.uid]}updateRenderable(_renderable){}destroyRenderable(renderable){this._gpuBufferHash[renderable.uid].destroy(),this._gpuBufferHash[renderable.uid]=null,renderable.off("destroyed",this._destroyRenderableBound)}execute(container){var renderer,state,buffer,children=container.particleChildren;0!==children.length&&(renderer=this.renderer,buffer=this.getBuffers(container),container.texture||(container.texture=children[0].texture),state=this.state,buffer.update(children,container._childrenDirty),container._childrenDirty=!1,state.blendMode=getAdjustedBlendModeBlend(container.blendMode,container.texture._source),children=(buffer=this.localUniforms.uniforms).uTranslationMatrix,container.worldTransform.copyTo(children),children.prepend(renderer.globalUniforms.globalUniformData.projectionMatrix),buffer.uResolution=renderer.globalUniforms.globalUniformData.resolution,buffer.uRound=renderer._roundPixels|container._roundPixels,color32BitToUniform(container.groupColorAlpha,buffer.uColor,0),this.adaptor.execute(this,container))}destroy(){this.defaultShader&&(this.defaultShader.destroy(),this.defaultShader=null)}}class GlParticleContainerPipe extends ParticleContainerPipe{constructor(renderer){super(renderer,new GlParticleContainerAdaptor)}}GlParticleContainerPipe.extension={type:["webgl-pipes"],name:"particle"};class GpuParticleContainerAdaptor{execute(particleContainerPipe,container){var renderer=particleContainerPipe.renderer,shader=((shader=container.shader||particleContainerPipe.defaultShader).groups[0]=renderer.renderPipes.uniformBatch.getUniformBindGroup(particleContainerPipe.localUniforms,!0),shader.groups[1]=renderer.texture.getTextureBindGroup(container.texture),particleContainerPipe.state),buffer=particleContainerPipe.getBuffers(container);renderer.encoder.draw({geometry:buffer.geometry,shader:container.shader||particleContainerPipe.defaultShader,state:shader,size:6*container.particleChildren.length})}}class GpuParticleContainerPipe extends ParticleContainerPipe{constructor(renderer){super(renderer,new GpuParticleContainerAdaptor)}}GpuParticleContainerPipe.extension={type:["webgpu-pipes"],name:"particle"},extensions.add(GlParticleContainerPipe),extensions.add(GpuParticleContainerPipe);class BatchableSprite{constructor(){this.batcherName="default",this.topology="triangle-list",this.attributeSize=4,this.indexSize=6,this.packAsQuad=!0,this.roundPixels=0,this._attributeStart=0,this._batcher=null,this._batch=null}get blendMode(){return this.renderable.groupBlendMode}get color(){return this.renderable.groupColorAlpha}reset(){this.renderable=null,this.texture=null,this._batcher=null,this._batch=null,this.bounds=null}}function updateTextBounds(batchableSprite,text){var{texture:batchableSprite,bounds}=batchableSprite,batchableSprite=(updateQuadBounds(bounds,text._anchor,batchableSprite),text._style.padding);bounds.minX-=batchableSprite,bounds.minY-=batchableSprite,bounds.maxX-=batchableSprite,bounds.maxY-=batchableSprite}class CanvasTextPipe{constructor(renderer){this._gpuText=Object.create(null),this._destroyRenderableBound=this.destroyRenderable.bind(this),this._renderer=renderer,this._renderer.runners.resolutionChange.add(this),this._renderer.renderableGC.addManagedHash(this,"_gpuText")}resolutionChange(){for(const i in this._gpuText){var gpuText=this._gpuText[i];gpuText&&(gpuText=gpuText.batchableSprite.renderable)._autoResolution&&(gpuText._resolution=this._renderer.resolution,gpuText.onViewUpdate())}}validateRenderable(text){var gpuText=this._getGpuText(text),text=text._getKey();return gpuText.currentKey!==text}addRenderable(text,instructionSet){var batchableSprite=this._getGpuText(text).batchableSprite;text._didTextUpdate&&this._updateText(text),this._renderer.renderPipes.batch.addToBatch(batchableSprite,instructionSet)}updateRenderable(text){var batchableSprite=this._getGpuText(text).batchableSprite;text._didTextUpdate&&this._updateText(text),batchableSprite._batcher.updateElement(batchableSprite)}destroyRenderable(text){text.off("destroyed",this._destroyRenderableBound),this._destroyRenderableById(text.uid)}_destroyRenderableById(textUid){var gpuText=this._gpuText[textUid];this._renderer.canvasText.decreaseReferenceCount(gpuText.currentKey),BigPool.return(gpuText.batchableSprite),this._gpuText[textUid]=null}_updateText(text){var newKey=text._getKey(),gpuText=this._getGpuText(text),batchableSprite=gpuText.batchableSprite;gpuText.currentKey!==newKey&&this._updateGpuText(text),text._didTextUpdate=!1,updateTextBounds(batchableSprite,text)}_updateGpuText(text){var gpuText=this._getGpuText(text),batchableSprite=gpuText.batchableSprite;gpuText.texture&&this._renderer.canvasText.decreaseReferenceCount(gpuText.currentKey),gpuText.texture=batchableSprite.texture=this._renderer.canvasText.getManagedTexture(text),gpuText.currentKey=text._getKey(),batchableSprite.texture=gpuText.texture}_getGpuText(text){return this._gpuText[text.uid]||this.initGpuText(text)}initGpuText(text){var gpuTextData={texture:null,currentKey:"--",batchableSprite:BigPool.get(BatchableSprite)};return gpuTextData.batchableSprite.renderable=text,gpuTextData.batchableSprite.transform=text.groupTransform,gpuTextData.batchableSprite.bounds={minX:0,maxX:1,minY:0,maxY:0},gpuTextData.batchableSprite.roundPixels=this._renderer._roundPixels|text._roundPixels,this._gpuText[text.uid]=gpuTextData,text._resolution=(text._autoResolution?this._renderer:text).resolution,this._updateText(text),text.on("destroyed",this._destroyRenderableBound),gpuTextData}destroy(){for(const i in this._gpuText)this._destroyRenderableById(i);this._gpuText=null,this._renderer=null}}CanvasTextPipe.extension={type:["webgl-pipes","webgpu-pipes","canvas-pipes"],name:"text"};const CanvasPool=new class{constructor(canvasOptions){this._canvasPool=Object.create(null),this.canvasOptions=canvasOptions||{},this.enableFullScreen=!1}_createCanvasAndContext(pixelWidth,pixelHeight){var canvas=DOMAdapter.get().createCanvas(),pixelWidth=(canvas.width=pixelWidth,canvas.height=pixelHeight,canvas.getContext("2d"));return{canvas:canvas,context:pixelWidth}}getOptimalCanvasAndContext(minWidth,minHeight,resolution=1){return minWidth=Math.ceil(minWidth*resolution-1e-6),minHeight=Math.ceil(minHeight*resolution-1e-6),resolution=((minWidth=nextPow2(minWidth))<<17)+((minHeight=nextPow2(minHeight))<<1),this._canvasPool[resolution]||(this._canvasPool[resolution]=[]),(resolution=this._canvasPool[resolution].pop())||this._createCanvasAndContext(minWidth,minHeight)}returnCanvasAndContext(canvasAndContext){var{width,height}=canvasAndContext.canvas,key=(width<<17)+(height<<1);canvasAndContext.context.clearRect(0,0,width,height),this._canvasPool[key].push(canvasAndContext)}clear(){this._canvasPool={}}};function checkRow(data,width,y){for(let x=0,index=4*y*width;xkey in obj?__defProp$W(obj,key,{enumerable:!0,configurable:!0,writable:!0,value:value}):obj[key]=value,__spreadValues$W=(a,b)=>{for(var prop in b=b||{})__hasOwnProp$W.call(b,prop)&&__defNormalProp$W(a,prop,b[prop]);if(__getOwnPropSymbols$W)for(var prop of __getOwnPropSymbols$W(b))__propIsEnum$W.call(b,prop)&&__defNormalProp$W(a,prop,b[prop]);return a};const emptyColorStops=[{offset:0,color:"white"},{offset:1,color:"black"}],_FillGradient=class _FillGradient{constructor(...args){this.uid=uid$1("fillGradient"),this.type="linear",this.colorStops=[];var defaults="radial"===(args=function(args){var _a;let options=null!=(_a=args[0])?_a:{};return"number"!=typeof options&&!args[1]||(deprecation("8.5.2","use options object instead"),options={type:"linear",start:{x:args[0],y:args[1]},end:{x:args[2],y:args[3]},textureSpace:args[4],textureSize:null!=(_a=args[5])?_a:FillGradient.defaultLinearOptions.textureSize}),options}(args)).type?_FillGradient.defaultRadialOptions:_FillGradient.defaultLinearOptions,args=__spreadValues$W(__spreadValues$W({},defaults),definedProps(args));this._textureSize=args.textureSize,"radial"===args.type?(this.center=args.center,this.outerCenter=null!=(defaults=args.outerCenter)?defaults:this.center,this.innerRadius=args.innerRadius,this.outerRadius=args.outerRadius,this.scale=args.scale,this.rotation=args.rotation):(this.start=args.start,this.end=args.end),this.textureSpace=args.textureSpace,this.type=args.type,args.colorStops.forEach(stop=>{this.addColorStop(stop.offset,stop.color)})}addColorStop(offset,color){return this.colorStops.push({offset:offset,color:Color.shared.setValue(color).toHexa()}),this}buildLinearGradient(){var defaultSize,colorStops,gradient,m,context,dist,canvas;this.texture||(colorStops=this.colorStops.length?this.colorStops:emptyColorStops,{canvas,context}=getCanvas(defaultSize=this._textureSize,1),{x:colorStops,y:gradient}=(addColorStops(gradient=context.createLinearGradient(0,0,this._textureSize,0),colorStops),context.fillStyle=gradient,context.fillRect(0,0,defaultSize,1),this.texture=new Texture({source:new ImageSource({resource:canvas})}),this.start),{x:context,y:canvas}=this.end,m=new Matrix,context-=colorStops,canvas-=gradient,dist=Math.sqrt(context*context+canvas*canvas),canvas=Math.atan2(canvas,context),m.scale(dist/defaultSize,1),m.rotate(canvas),m.translate(colorStops,gradient),"local"===this.textureSpace&&m.scale(defaultSize,defaultSize),this.transform=m)}buildGradient(){"linear"===this.type?this.buildLinearGradient():this.buildRadialGradient()}buildRadialGradient(){var colorStops,defaultSize,canvas,context,y1,r1,x0,y0,scale,cx,cy,r0,x1;this.texture||(colorStops=this.colorStops.length?this.colorStops:emptyColorStops,{canvas,context}=getCanvas(defaultSize=this._textureSize,defaultSize),{x:x0,y:y0}=this.center,{x:x1,y:y1}=this.outerCenter,r0=this.innerRadius,r1=this.outerRadius,addColorStops(r0=context.createRadialGradient(cx=(x0-(x0=x1-r1))*(scale=defaultSize/(2*r1)),cy=(y0-(y0=y1-r1))*scale,r0*scale,(x1-x0)*scale,(y1-y0)*scale,r1*scale),colorStops),context.fillStyle=colorStops[colorStops.length-1].color,context.fillRect(0,0,defaultSize,defaultSize),context.fillStyle=r0,context.translate(cx,cy),context.rotate(this.rotation),context.scale(1,this.scale),context.translate(-cx,-cy),context.fillRect(0,0,defaultSize,defaultSize),this.texture=new Texture({source:new ImageSource({resource:canvas,addressModeU:"clamp-to-edge",addressModeV:"clamp-to-edge"})}),(x1=new Matrix).scale(1/scale,1/scale),x1.translate(x0,y0),"local"===this.textureSpace&&x1.scale(defaultSize,defaultSize),this.transform=x1)}get styleKey(){return this.uid}destroy(){var _a;null!=(_a=this.texture)&&_a.destroy(!0),this.texture=null}};_FillGradient.defaultLinearOptions={start:{x:0,y:0},end:{x:0,y:1},colorStops:[],textureSpace:"local",type:"linear",textureSize:256},_FillGradient.defaultRadialOptions={center:{x:.5,y:.5},innerRadius:0,outerRadius:.5,colorStops:[],scale:1,textureSpace:"local",type:"radial",textureSize:256};let FillGradient=_FillGradient;function addColorStops(gradient,colorStops){for(let i=0;imaxX?x:maxX,minY=ymaxY?y:maxY}return out.x=minX,out.width=maxX-minX,out.y=minY,out.height=maxY-minY,out}copyFrom(polygon){return this.points=polygon.points.slice(),this.closePath=polygon.closePath,this}copyTo(polygon){return polygon.copyFrom(this),polygon}toString(){return`[pixi.js/math:PolygoncloseStroke=${this.closePath}points=${this.points.reduce((pointsDesc,currentPoint)=>pointsDesc+", "+currentPoint,"")}]`}get lastX(){return this.points[this.points.length-2]}get lastY(){return this.points[this.points.length-1]}get x(){return this.points[this.points.length-2]}get y(){return this.points[this.points.length-1]}}const isCornerWithinStroke=(pX,pY,cornerX,cornerY,radius,strokeWidthInner,strokeWidthOuter)=>(pX-=cornerX,cornerX=pY-cornerY,radius-strokeWidthInner<=(pY=Math.sqrt(pX*pX+cornerX*cornerX))&&pY<=radius+strokeWidthOuter);class RoundedRectangle{constructor(x=0,y=0,width=0,height=0,radius=20){this.type="roundedRectangle",this.x=x,this.y=y,this.width=width,this.height=height,this.radius=radius}getBounds(out){return(out=out||new Rectangle).x=this.x,out.y=this.y,out.width=this.width,out.height=this.height,out}clone(){return new RoundedRectangle(this.x,this.y,this.width,this.height,this.radius)}copyFrom(rectangle){return this.x=rectangle.x,this.y=rectangle.y,this.width=rectangle.width,this.height=rectangle.height,this}copyTo(rectangle){return rectangle.copyFrom(this),rectangle}contains(x,y){if(!(this.width<=0||this.height<=0)&&x>=this.x&&x<=this.x+this.width&&y>=this.y&&y<=this.y+this.height){var radius=Math.max(0,Math.min(this.radius,Math.min(this.width,this.height)/2));if(y>=this.y+radius&&y<=this.y+this.height-radius||x>=this.x+radius&&x<=this.x+this.width-radius)return!0;var dx=x-(this.x+radius),dy=y-(this.y+radius),radius2=radius*radius;if(dx*dx+dy*dy<=radius2)return!0;if((dx=x-(this.x+this.width-radius))*dx+dy*dy<=radius2)return!0;if(dx*dx+(dy=y-(this.y+this.height-radius))*dy<=radius2)return!0;if((dx=x-(this.x+radius))*dx+dy*dy<=radius2)return!0}return!1}strokeContains(pX,pY,strokeWidth,alignment=.5){var{x,y,width,height,radius}=this,strokeWidth=strokeWidth-(alignment=strokeWidth*(1-alignment)),innerX=x+radius,innerY=y+radius,rightBound=x+width,bottomBound=y+height;return(x-alignment<=pX&&pX<=x+strokeWidth||rightBound-strokeWidth<=pX&&pX<=rightBound+alignment)&&innerY<=pY&&pY<=innerY+(height-2*radius)||(y-alignment<=pY&&pY<=y+strokeWidth||bottomBound-strokeWidth<=pY&&pY<=bottomBound+alignment)&&innerX<=pX&&pX<=innerX+(width-2*radius)||pX(rx=sinPhi*(x*=rx)+cosPhi*(y*=ry),out2.x=cosPhi*x-sinPhi*y+centerX,out2.y=rx+centerY,out2),vectorAngle=(ux,uy,vx,vy)=>{let dot=ux*vx+uy*vy;return(dot=1{var rxSq=Math.pow(rx,2),rySq=Math.pow(ry,2),pxpSq=Math.pow(pxp,2),pypSq=Math.pow(pyp,2);let radicant=rxSq*rySq-rxSq*pypSq-rySq*pxpSq,ang2=(radicant<0&&(radicant=0),radicant/=rxSq*pypSq+rySq*pxpSq,rySq=cosPhi*(rxSq=(radicant=Math.sqrt(radicant)*(largeArcFlag===sweepFlag?-1:1))*rx/ry*pyp)-sinPhi*(pypSq=radicant*-ry/rx*pxp)+(px+cx)/2,pxpSq=sinPhi*rxSq+cosPhi*pypSq+(py+cy)/2,largeArcFlag=(pxp-rxSq)/rx,px=(pyp-pypSq)/ry,cx=(-pxp-rxSq)/rx,sinPhi=(-pyp-pypSq)/ry,cosPhi=vectorAngle(1,0,largeArcFlag,px),vectorAngle(largeArcFlag,px,cx,sinPhi));0===sweepFlag&&0Math.sqrt((p1.x-p2.x)**2+(p1.y-p2.y)**2),pointLerp=(p1,p2,t)=>({x:p1.x+(p2.x-p1.x)*t,y:p1.y+(p2.y-p1.y)*t}),numPoints=points.length;for(let i=0;i{var x=pp.x-p.x,pp=pp.y-p.y;return{len:p=Math.sqrt(x*x+pp*pp),nx:x/p,ny:pp/p}},sharpCorner=(i,p)=>{0===i?g.moveTo(p.x,p.y):g.lineTo(p.x,p.y)};let p1=points[points.length-1];for(let i=0;iMath.min(v1.len/2,p3.len/2)?(lenOut=Math.min(v1.len/2,p3.len/2),Math.abs(lenOut*Math.sin(halfAngle)/Math.cos(halfAngle))):_a,halfAngle=p2.x+p3.nx*lenOut+-p3.ny*cRadius*radDirection,_a=p2.y+p3.ny*lenOut+p3.nx*cRadius*radDirection,v1=Math.atan2(v1.ny,v1.nx)+Math.PI/2*radDirection,p3=Math.atan2(p3.ny,p3.nx)-Math.PI/2*radDirection,0===i&&g.moveTo(halfAngle+Math.cos(v1)*cRadius,_a+Math.sin(v1)*cRadius),g.arc(halfAngle,_a,cRadius,v1,p3,drawDirection)}}p1=p2}}(this,points,radius),this.closePath())}filletRect(x,y,width,height,fillet){var right,maxFillet;return 0===fillet?this.rect(x,y,width,height):(maxFillet=Math.min(width,height)/2,right=x+width,height=y+height,fillet=(maxFillet=Math.min(maxFillet,Math.max(-maxFillet,fillet)))<0?-maxFillet:0,maxFillet=Math.abs(maxFillet),this.moveTo(x,y+maxFillet).arcTo(x+fillet,y+fillet,x+maxFillet,y,maxFillet).lineTo(right-maxFillet,y).arcTo(right-fillet,y+fillet,right,y+maxFillet,maxFillet).lineTo(right,height-maxFillet).arcTo(right-fillet,height-fillet,x+width-maxFillet,height,maxFillet).lineTo(x+maxFillet,height).arcTo(x+fillet,height-fillet,x,height-maxFillet,maxFillet).closePath())}chamferRect(x,y,width,height,chamfer,transform){if(chamfer<=0)return this.rect(x,y,width,height);var points=[x+(chamfer=Math.min(chamfer,Math.min(width,height)/2)),y,(width=x+width)-chamfer,y,width,y+chamfer,width,(height=y+height)-chamfer,width-chamfer,height,x+chamfer,height,x,height-chamfer,x,y+chamfer];for(let i=points.length-1;2<=i;i-=2)points[i]===points[i-2]&&points[i-1]===points[i-3]&&points.splice(i-1,2);return this.poly(points,!0,transform)}ellipse(x,y,radiusX,radiusY,transform){return this.drawShape(new Ellipse(x,y,radiusX,radiusY),transform),this}roundRect(x,y,w,h,radius,transform){return this.drawShape(new RoundedRectangle(x,y,w,h,radius),transform),this}drawShape(shape,matrix){return this.endPoly(),this.shapePrimitives.push({shape:shape,transform:matrix}),this}startPoly(x,y){var currentPoly=this._currentPoly;return currentPoly&&this.endPoly(),(currentPoly=new Polygon).points.push(x,y),this._currentPoly=currentPoly,this}endPoly(closePath=!1){var shape=this._currentPoly;return shape&&2key in obj?__defProp$V(obj,key,{enumerable:!0,configurable:!0,writable:!0,value:value}):obj[key]=value,__spreadValues$V=(a,b)=>{for(var prop in b=b||{})__hasOwnProp$V.call(b,prop)&&__defNormalProp$V(a,prop,b[prop]);if(__getOwnPropSymbols$V)for(var prop of __getOwnPropSymbols$V(b))__propIsEnum$V.call(b,prop)&&__defNormalProp$V(a,prop,b[prop]);return a},__defProp$U=Object.defineProperty,__getOwnPropSymbols$U=Object.getOwnPropertySymbols,__hasOwnProp$U=Object.prototype.hasOwnProperty,__propIsEnum$U=Object.prototype.propertyIsEnumerable,__defNormalProp$U=(obj,key,value)=>key in obj?__defProp$U(obj,key,{enumerable:!0,configurable:!0,writable:!0,value:value}):obj[key]=value,__spreadValues$U=(a,b)=>{for(var prop in b=b||{})__hasOwnProp$U.call(b,prop)&&__defNormalProp$U(a,prop,b[prop]);if(__getOwnPropSymbols$U)for(var prop of __getOwnPropSymbols$U(b))__propIsEnum$U.call(b,prop)&&__defNormalProp$U(a,prop,b[prop]);return a};function isFillPattern(value){return value instanceof FillPattern}function isFillGradient(value){return value instanceof FillGradient}function handleFillPattern(fill,value,defaultStyle){return fill.fill=value,fill.color=16777215,fill.texture=value.texture,fill.matrix=value.transform,__spreadValues$U(__spreadValues$U({},defaultStyle),fill)}function handleFillGradient(fill,value,defaultStyle){return value.buildGradient(),fill.fill=value,fill.color=16777215,fill.texture=value.texture,fill.matrix=value.transform,fill.textureSpace=value.textureSpace,__spreadValues$U(__spreadValues$U({},defaultStyle),fill)}function toFillStyle(value,defaultStyle){var fill,objectStyle;return null==value?null:(fill={},function(value){return Color.isColorLike(value)}(objectStyle=value)?function(fill,value,defaultStyle){return value=Color.shared.setValue(null!=value?value:0),fill.color=value.toNumber(),fill.alpha=(1===value.alpha?defaultStyle:value).alpha,fill.texture=Texture.WHITE,__spreadValues$U(__spreadValues$U({},defaultStyle),fill)}(fill,value,defaultStyle):function(value){return value instanceof Texture}(value)?function(fill,value,defaultStyle){return fill.texture=value,__spreadValues$U(__spreadValues$U({},defaultStyle),fill)}(fill,value,defaultStyle):isFillPattern(value)?handleFillPattern(fill,value,defaultStyle):isFillGradient(value)?handleFillGradient(fill,value,defaultStyle):objectStyle.fill&&isFillPattern(objectStyle.fill)?handleFillPattern(objectStyle,objectStyle.fill,defaultStyle):objectStyle.fill&&isFillGradient(objectStyle.fill)?handleFillGradient(objectStyle,objectStyle.fill,defaultStyle):function(value,defaultStyle){return defaultStyle=__spreadValues$U(__spreadValues$U({},defaultStyle),value),value=Color.shared.setValue(defaultStyle.color),defaultStyle.alpha*=value.alpha,defaultStyle.color=value.toNumber(),defaultStyle}(objectStyle,defaultStyle))}function toStrokeStyle(value,defaultStyle){var{width,alignment,miterLimit,cap,join,pixelLine}=defaultStyle;return(value=toFillStyle(value,((source,exclude)=>{var target={};for(prop in source)__hasOwnProp$U.call(source,prop)&&exclude.indexOf(prop)<0&&(target[prop]=source[prop]);if(null!=source&&__getOwnPropSymbols$U)for(var prop of __getOwnPropSymbols$U(source))exclude.indexOf(prop)<0&&__propIsEnum$U.call(source,prop)&&(target[prop]=source[prop]);return target})(defaultStyle,["width","alignment","miterLimit","cap","join","pixelLine"])))?__spreadValues$U({width:width,alignment:alignment,miterLimit:miterLimit,cap:cap,join:join,pixelLine:pixelLine},value):null}var __defProp$T=Object.defineProperty,__getOwnPropSymbols$T=Object.getOwnPropertySymbols,__hasOwnProp$T=Object.prototype.hasOwnProperty,__propIsEnum$T=Object.prototype.propertyIsEnumerable,__defNormalProp$T=(obj,key,value)=>key in obj?__defProp$T(obj,key,{enumerable:!0,configurable:!0,writable:!0,value:value}):obj[key]=value,__spreadValues$T=(a,b)=>{for(var prop in b=b||{})__hasOwnProp$T.call(b,prop)&&__defNormalProp$T(a,prop,b[prop]);if(__getOwnPropSymbols$T)for(var prop of __getOwnPropSymbols$T(b))__propIsEnum$T.call(b,prop)&&__defNormalProp$T(a,prop,b[prop]);return a};const tmpPoint=new Point,tempMatrix$3=new Matrix,_GraphicsContext=class _GraphicsContext extends EventEmitter{constructor(){super(...arguments),this.uid=uid$1("graphicsContext"),this.dirty=!0,this.batchMode="auto",this.instructions=[],this._activePath=new GraphicsPath,this._transform=new Matrix,this._fillStyle=__spreadValues$T({},_GraphicsContext.defaultFillStyle),this._strokeStyle=__spreadValues$T({},_GraphicsContext.defaultStrokeStyle),this._stateStack=[],this._tick=0,this._bounds=new Bounds,this._boundsDirty=!0}clone(){var clone=new _GraphicsContext;return clone.batchMode=this.batchMode,clone.instructions=this.instructions.slice(),clone._activePath=this._activePath.clone(),clone._transform=this._transform.clone(),clone._fillStyle=__spreadValues$T({},this._fillStyle),clone._strokeStyle=__spreadValues$T({},this._strokeStyle),clone._stateStack=this._stateStack.slice(),clone._bounds=this._bounds.clone(),clone._boundsDirty=!0,clone}get fillStyle(){return this._fillStyle}set fillStyle(value){this._fillStyle=toFillStyle(value,_GraphicsContext.defaultFillStyle)}get strokeStyle(){return this._strokeStyle}set strokeStyle(value){this._strokeStyle=toStrokeStyle(value,_GraphicsContext.defaultStrokeStyle)}setFillStyle(style){return this._fillStyle=toFillStyle(style,_GraphicsContext.defaultFillStyle),this}setStrokeStyle(style){return this._strokeStyle=toFillStyle(style,_GraphicsContext.defaultStrokeStyle),this}texture(texture,tint,dx,dy,dw,dh){return this.instructions.push({action:"texture",data:{image:texture,dx:dx||0,dy:dy||0,dw:dw||texture.frame.width,dh:dh||texture.frame.height,transform:this._transform.clone(),alpha:this._fillStyle.alpha,style:tint?Color.shared.setValue(tint).toNumber():16777215}}),this.onUpdate(),this}beginPath(){return this._activePath=new GraphicsPath,this}fill(style,alpha){var lastInstruction=this.instructions[this.instructions.length-1];return(lastInstruction=0===this._tick&&lastInstruction&&"stroke"===lastInstruction.action?lastInstruction.data.path:this._activePath.clone())&&(null!=style&&(void 0!==alpha&&"number"==typeof style&&(deprecation(v8_0_0,"GraphicsContext.fill(color, alpha) is deprecated, use GraphicsContext.fill({ color, alpha }) instead"),style={color:style,alpha:alpha}),this._fillStyle=toFillStyle(style,_GraphicsContext.defaultFillStyle)),this.instructions.push({action:"fill",data:{style:this.fillStyle,path:lastInstruction}}),this.onUpdate(),this._initNextPathLocation(),this._tick=0),this}_initNextPathLocation(){var{x,y}=this._activePath.getLastPoint(Point.shared);this._activePath.clear(),this._activePath.moveTo(x,y)}stroke(style){var lastInstruction=this.instructions[this.instructions.length-1];return(lastInstruction=0===this._tick&&lastInstruction&&"fill"===lastInstruction.action?lastInstruction.data.path:this._activePath.clone())&&(null!=style&&(this._strokeStyle=toStrokeStyle(style,_GraphicsContext.defaultStrokeStyle)),this.instructions.push({action:"stroke",data:{style:this.strokeStyle,path:lastInstruction}}),this.onUpdate(),this._initNextPathLocation(),this._tick=0),this}cut(){for(let i=0;i<2;i++){var lastInstruction=this.instructions[this.instructions.length-1-i],holePath=this._activePath.clone();if(lastInstruction&&("stroke"===lastInstruction.action||"fill"===lastInstruction.action)){if(!lastInstruction.data.hole){lastInstruction.data.hole=holePath;break}lastInstruction.data.hole.addPath(holePath)}}return this._initNextPathLocation(),this}arc(x,y,radius,startAngle,endAngle,counterclockwise){this._tick++;var t=this._transform;return this._activePath.arc(t.a*x+t.c*y+t.tx,t.b*x+t.d*y+t.ty,radius,startAngle,endAngle,counterclockwise),this}arcTo(x1,y1,x2,y2,radius){this._tick++;var t=this._transform;return this._activePath.arcTo(t.a*x1+t.c*y1+t.tx,t.b*x1+t.d*y1+t.ty,t.a*x2+t.c*y2+t.tx,t.b*x2+t.d*y2+t.ty,radius),this}arcToSvg(rx,ry,xAxisRotation,largeArcFlag,sweepFlag,x,y){this._tick++;var t=this._transform;return this._activePath.arcToSvg(rx,ry,xAxisRotation,largeArcFlag,sweepFlag,t.a*x+t.c*y+t.tx,t.b*x+t.d*y+t.ty),this}bezierCurveTo(cp1x,cp1y,cp2x,cp2y,x,y,smoothness){this._tick++;var t=this._transform;return this._activePath.bezierCurveTo(t.a*cp1x+t.c*cp1y+t.tx,t.b*cp1x+t.d*cp1y+t.ty,t.a*cp2x+t.c*cp2y+t.tx,t.b*cp2x+t.d*cp2y+t.ty,t.a*x+t.c*y+t.tx,t.b*x+t.d*y+t.ty,smoothness),this}closePath(){var _a;return this._tick++,null!=(_a=this._activePath)&&_a.closePath(),this}ellipse(x,y,radiusX,radiusY){return this._tick++,this._activePath.ellipse(x,y,radiusX,radiusY,this._transform.clone()),this}circle(x,y,radius){return this._tick++,this._activePath.circle(x,y,radius,this._transform.clone()),this}path(path){return this._tick++,this._activePath.addPath(path,this._transform.clone()),this}lineTo(x,y){this._tick++;var t=this._transform;return this._activePath.lineTo(t.a*x+t.c*y+t.tx,t.b*x+t.d*y+t.ty),this}moveTo(x,y){this._tick++;var t=this._transform,instructions=this._activePath.instructions,transformedX=t.a*x+t.c*y+t.tx,x=t.b*x+t.d*y+t.ty;return 1===instructions.length&&"moveTo"===instructions[0].action?(instructions[0].data[0]=transformedX,instructions[0].data[1]=x):this._activePath.moveTo(transformedX,x),this}quadraticCurveTo(cpx,cpy,x,y,smoothness){this._tick++;var t=this._transform;return this._activePath.quadraticCurveTo(t.a*cpx+t.c*cpy+t.tx,t.b*cpx+t.d*cpy+t.ty,t.a*x+t.c*y+t.tx,t.b*x+t.d*y+t.ty,smoothness),this}rect(x,y,w,h){return this._tick++,this._activePath.rect(x,y,w,h,this._transform.clone()),this}roundRect(x,y,w,h,radius){return this._tick++,this._activePath.roundRect(x,y,w,h,radius,this._transform.clone()),this}poly(points,close){return this._tick++,this._activePath.poly(points,close,this._transform.clone()),this}regularPoly(x,y,radius,sides,rotation=0,transform){return this._tick++,this._activePath.regularPoly(x,y,radius,sides,rotation,transform),this}roundPoly(x,y,radius,sides,corner,rotation){return this._tick++,this._activePath.roundPoly(x,y,radius,sides,corner,rotation),this}roundShape(points,radius,useQuadratic,smoothness){return this._tick++,this._activePath.roundShape(points,radius,useQuadratic,smoothness),this}filletRect(x,y,width,height,fillet){return this._tick++,this._activePath.filletRect(x,y,width,height,fillet),this}chamferRect(x,y,width,height,chamfer,transform){return this._tick++,this._activePath.chamferRect(x,y,width,height,chamfer,transform),this}star(x,y,points,radius,innerRadius=0,rotation=0){return this._tick++,this._activePath.star(x,y,points,radius,innerRadius,rotation,this._transform.clone()),this}svg(svg){return this._tick++,function(svg,graphicsContext){"string"==typeof svg&&((div=document.createElement("div")).innerHTML=svg.trim(),svg=div.querySelector("svg"));var div,session={context:graphicsContext,defs:{},path:new GraphicsPath},children=(function(svg,session){var definitions=svg.querySelectorAll("defs");for(let i=0;iparseInt(n,10)),session.context.poly(points,!0),fillStyle&&session.context.fill(fillStyle),strokeStyle&&session.context.stroke(strokeStyle);break;case"polyline":pointsString=svg.getAttribute("points"),points=pointsString.match(/\d+/g).map(n=>parseInt(n,10)),session.context.poly(points,!1),strokeStyle&&session.context.stroke(strokeStyle);break;case"g":case"svg":break;default:warn(`[SVG parser] <${svg.nodeName}> elements unsupported`)}f1&&(fillStyle=null);for(let i=0;ikey in obj?__defProp$S(obj,key,{enumerable:!0,configurable:!0,writable:!0,value:value}):obj[key]=value,__spreadValues$S=(a,b)=>{for(var prop in b=b||{})__hasOwnProp$S.call(b,prop)&&__defNormalProp$S(a,prop,b[prop]);if(__getOwnPropSymbols$S)for(var prop of __getOwnPropSymbols$S(b))__propIsEnum$S.call(b,prop)&&__defNormalProp$S(a,prop,b[prop]);return a};const _TextStyle=class _TextStyle extends EventEmitter{constructor(style={}){super(),function(style){var defaults,oldStyle=style;if("boolean"==typeof oldStyle.dropShadow&&oldStyle.dropShadow&&(defaults=TextStyle.defaultDropShadow,style.dropShadow={alpha:null!=(_a=oldStyle.dropShadowAlpha)?_a:defaults.alpha,angle:null!=(_a=oldStyle.dropShadowAngle)?_a:defaults.angle,blur:null!=(_a=oldStyle.dropShadowBlur)?_a:defaults.blur,color:null!=(_a=oldStyle.dropShadowColor)?_a:defaults.color,distance:null!=(_a=oldStyle.dropShadowDistance)?_a:defaults.distance}),void 0!==oldStyle.strokeThickness){deprecation(v8_0_0,"strokeThickness is now a part of stroke");var _a=oldStyle.stroke;let obj={};if(Color.isColorLike(_a))obj.color=_a;else if(_a instanceof FillGradient||_a instanceof FillPattern)obj.fill=_a;else{if(!Object.hasOwnProperty.call(_a,"color")&&!Object.hasOwnProperty.call(_a,"fill"))throw new Error("Invalid stroke value.");obj=_a}style.stroke=(defaults=__spreadValues$S({},obj),_a={width:oldStyle.strokeThickness},__defProps$m(defaults,__getOwnPropDescs$m(_a)))}if(Array.isArray(oldStyle.fillGradientStops)){deprecation(v8_0_0,"gradient fill is now a fill pattern: `new FillGradient(...)`");let fontSize;null==style.fontSize?style.fontSize=TextStyle.defaultTextStyle.fontSize:fontSize="string"==typeof style.fontSize?parseInt(style.fontSize,10):style.fontSize;const gradientFill=new FillGradient({start:{x:0,y:0},end:{x:0,y:1.7*(fontSize||0)}}),fills=oldStyle.fillGradientStops.map(color=>Color.shared.setValue(color).toNumber());fills.forEach((number,index)=>{index/=fills.length-1,gradientFill.addColorStop(index,number)}),style.fill={fill:gradientFill}}}(style);var fullStyle=__spreadValues$S(__spreadValues$S({},_TextStyle.defaultTextStyle),style);for(const key in fullStyle)this[key]=fullStyle[key];this.update()}get align(){return this._align}set align(value){this._align=value,this.update()}get breakWords(){return this._breakWords}set breakWords(value){this._breakWords=value,this.update()}get dropShadow(){return this._dropShadow}set dropShadow(value){this._dropShadow=null!==value&&"object"==typeof value?this._createProxy(__spreadValues$S(__spreadValues$S({},_TextStyle.defaultDropShadow),value)):value?this._createProxy(__spreadValues$S({},_TextStyle.defaultDropShadow)):null,this.update()}get fontFamily(){return this._fontFamily}set fontFamily(value){this._fontFamily=value,this.update()}get fontSize(){return this._fontSize}set fontSize(value){this._fontSize="string"==typeof value?parseInt(value,10):value,this.update()}get fontStyle(){return this._fontStyle}set fontStyle(value){this._fontStyle=value.toLowerCase(),this.update()}get fontVariant(){return this._fontVariant}set fontVariant(value){this._fontVariant=value,this.update()}get fontWeight(){return this._fontWeight}set fontWeight(value){this._fontWeight=value,this.update()}get leading(){return this._leading}set leading(value){this._leading=value,this.update()}get letterSpacing(){return this._letterSpacing}set letterSpacing(value){this._letterSpacing=value,this.update()}get lineHeight(){return this._lineHeight}set lineHeight(value){this._lineHeight=value,this.update()}get padding(){return this._padding}set padding(value){this._padding=value,this.update()}get trim(){return this._trim}set trim(value){this._trim=value,this.update()}get textBaseline(){return this._textBaseline}set textBaseline(value){this._textBaseline=value,this.update()}get whiteSpace(){return this._whiteSpace}set whiteSpace(value){this._whiteSpace=value,this.update()}get wordWrap(){return this._wordWrap}set wordWrap(value){this._wordWrap=value,this.update()}get wordWrapWidth(){return this._wordWrapWidth}set wordWrapWidth(value){this._wordWrapWidth=value,this.update()}get fill(){return this._originalFill}set fill(value){value!==this._originalFill&&(this._originalFill=value,this._isFillStyle(value)&&(this._originalFill=this._createProxy(__spreadValues$S(__spreadValues$S({},GraphicsContext.defaultFillStyle),value),()=>{this._fill=toFillStyle(__spreadValues$S({},this._originalFill),GraphicsContext.defaultFillStyle)})),this._fill=toFillStyle(0===value?"black":value,GraphicsContext.defaultFillStyle),this.update())}get stroke(){return this._originalStroke}set stroke(value){value!==this._originalStroke&&(this._originalStroke=value,this._isFillStyle(value)&&(this._originalStroke=this._createProxy(__spreadValues$S(__spreadValues$S({},GraphicsContext.defaultStrokeStyle),value),()=>{this._stroke=toStrokeStyle(__spreadValues$S({},this._originalStroke),GraphicsContext.defaultStrokeStyle)})),this._stroke=toStrokeStyle(value,GraphicsContext.defaultStrokeStyle),this.update())}_generateKey(){return this._styleKey=generateTextStyleKey(this),this._styleKey}update(){this._styleKey=null,this.emit("update",this)}reset(){var defaultStyle=_TextStyle.defaultTextStyle;for(const key in defaultStyle)this[key]=defaultStyle[key]}get styleKey(){return this._styleKey||this._generateKey()}clone(){return new _TextStyle({align:this.align,breakWords:this.breakWords,dropShadow:this._dropShadow?__spreadValues$S({},this._dropShadow):null,fill:this._fill,fontFamily:this.fontFamily,fontSize:this.fontSize,fontStyle:this.fontStyle,fontVariant:this.fontVariant,fontWeight:this.fontWeight,leading:this.leading,letterSpacing:this.letterSpacing,lineHeight:this.lineHeight,padding:this.padding,stroke:this._stroke,textBaseline:this.textBaseline,whiteSpace:this.whiteSpace,wordWrap:this.wordWrap,wordWrapWidth:this.wordWrapWidth})}destroy(options=!1){this.removeAllListeners();var destroyTexture="boolean"==typeof options?options:null==options?void 0:options.texture;destroyTexture&&(destroyTexture="boolean"==typeof options?options:null==options?void 0:options.textureSource,null!=(options=this._fill)&&options.texture&&this._fill.texture.destroy(destroyTexture),null!=(options=this._originalFill)&&options.texture&&this._originalFill.texture.destroy(destroyTexture),null!=(options=this._stroke)&&options.texture&&this._stroke.texture.destroy(destroyTexture),null!=(options=this._originalStroke))&&options.texture&&this._originalStroke.texture.destroy(destroyTexture),this._fill=null,this._stroke=null,this.dropShadow=null,this._originalStroke=null,this._originalFill=null}_createProxy(value,cb){return new Proxy(value,{set:(target,property,newValue)=>(target[property]=newValue,null!=cb&&cb(property,newValue),this.update(),!0)})}_isFillStyle(value){return null!==(null!=value?value:null)&&!(Color.isColorLike(value)||value instanceof FillGradient||value instanceof FillPattern)}};_TextStyle.defaultDropShadow={alpha:1,angle:Math.PI/6,blur:0,color:"black",distance:5},_TextStyle.defaultTextStyle={align:"left",breakWords:!1,dropShadow:null,fill:"black",fontFamily:"Arial",fontSize:26,fontStyle:"normal",fontVariant:"normal",fontWeight:"normal",leading:0,letterSpacing:0,lineHeight:0,padding:0,stroke:null,textBaseline:"alphabetic",trim:!1,whiteSpace:"pre",wordWrap:!1,wordWrapWidth:100};let TextStyle=_TextStyle;const tempBounds$3=new Bounds;function getPo2TextureFromSource(image,width,height,resolution){var bounds=tempBounds$3;return bounds.minX=0,bounds.minY=0,bounds.maxX=image.width/resolution|0,bounds.maxY=image.height/resolution|0,(bounds=TexturePool.getOptimalTexture(bounds.width,bounds.height,resolution,!1)).source.uploadMethodId="image",bounds.source.resource=image,bounds.source.alphaMode="premultiply-alpha-on-upload",bounds.frame.width=width/resolution,bounds.frame.height=height/resolution,bounds.source.emit("update",bounds.source),bounds.updateUvs(),bounds}const genericFontFamilies=["serif","sans-serif","monospace","cursive","fantasy","system-ui"];function fontStringFromTextStyle(style){var fontSizeString="number"==typeof style.fontSize?style.fontSize+"px":style.fontSize,fontFamilies=style.fontFamily;for(let i=(fontFamilies=Array.isArray(style.fontFamily)?fontFamilies:style.fontFamily.split(",")).length-1;0<=i;i--){let fontFamily=fontFamilies[i].trim();/([\"\'])[^\'\"]+\1/.test(fontFamily)||genericFontFamilies.includes(fontFamily)||(fontFamily=`"${fontFamily}"`),fontFamilies[i]=fontFamily}return`${style.fontStyle} ${style.fontVariant} ${style.fontWeight} ${fontSizeString} `+fontFamilies.join(",")}const contextSettings={willReadFrequently:!0},_CanvasTextMetrics=class _CanvasTextMetrics{static get experimentalLetterSpacingSupported(){let result=_CanvasTextMetrics._experimentalLetterSpacingSupported;var proto;return void 0!==result&&(proto=DOMAdapter.get().getCanvasRenderingContext2D().prototype,result=_CanvasTextMetrics._experimentalLetterSpacingSupported="letterSpacing"in proto||"textLetterSpacing"in proto),result}constructor(text,style,width,height,lines,lineWidths,lineHeight,maxLineWidth,fontProperties){this.text=text,this.style=style,this.width=width,this.height=height,this.lines=lines,this.lineWidths=lineWidths,this.lineHeight=lineHeight,this.maxLineWidth=maxLineWidth,this.fontProperties=fontProperties}static measureText(text=" ",style,canvas=_CanvasTextMetrics._canvas,wordWrap=style.wordWrap){var textKey=text+":"+style.styleKey;if(_CanvasTextMetrics._measurementCache[textKey])return _CanvasTextMetrics._measurementCache[textKey];var textKey=fontStringFromTextStyle(style),fontProperties=_CanvasTextMetrics.measureFont(textKey),context=(0===fontProperties.fontSize&&(fontProperties.fontSize=style.fontSize,fontProperties.ascent=style.fontSize),_CanvasTextMetrics.__context),lines=(context.font=textKey,(wordWrap?_CanvasTextMetrics._wordWrap(text,style,canvas):text).split(/(?:\r\n|\r|\n)/)),lineWidths=new Array(lines.length);let maxLineWidth=0;for(let i=0;iwordWrapWidth&&(lines+=_CanvasTextMetrics._addLine(line),canPrependSpaces=!1,line="",width=0),line+=char,width+=characterWidth}}else 0wordWrapWidth&&(canPrependSpaces=!1,lines+=_CanvasTextMetrics._addLine(line),line="",width=0),(0{if("function"!=typeof(null==Intl?void 0:Intl.Segmenter))return s=>[...s];{const segmenter=new Intl.Segmenter;return s=>[...segmenter.segment(s)].map(x=>x.segment)}})(),_CanvasTextMetrics.experimentalLetterSpacing=!1,_CanvasTextMetrics._fonts={},_CanvasTextMetrics._newlines=[10,13],_CanvasTextMetrics._breakingSpaces=[9,32,8192,8193,8194,8195,8196,8197,8198,8200,8201,8202,8287,12288],_CanvasTextMetrics._measurementCache={};let CanvasTextMetrics=_CanvasTextMetrics;function getCanvasFillStyle(fillStyle,context,textMetrics,padding=0){if(fillStyle.texture===Texture.WHITE&&!fillStyle.fill)return Color.shared.setValue(fillStyle.color).setAlpha(null!=(_a=fillStyle.alpha)?_a:1).toHexa();if(!fillStyle.fill)return _a=context.createPattern(fillStyle.texture.source.resource,"repeat"),(tempMatrix=fillStyle.matrix.copyTo(Matrix.shared)).scale(fillStyle.texture.frame.width,fillStyle.texture.frame.height),_a.setTransform(tempMatrix),_a;if(fillStyle.fill instanceof FillPattern){var _a=fillStyle.fill;const pattern=context.createPattern(_a.texture.source.resource,"repeat"),tempMatrix=_a.transform.copyTo(Matrix.shared);return tempMatrix.scale(_a.texture.frame.width,_a.texture.frame.height),pattern.setTransform(tempMatrix),pattern}if(fillStyle.fill instanceof FillGradient){var end,outerCenter,outerRadius,fillGradient=fillStyle.fill,tempMatrix="linear"===fillGradient.type;let width=1,height=1;(_a="local"===fillGradient.textureSpace)&&textMetrics&&(width=textMetrics.width+padding,height=textMetrics.height+padding);let gradient,isNearlyVertical=!1;if(tempMatrix?({start:tempMatrix,end}=fillGradient,gradient=context.createLinearGradient(tempMatrix.x*width,tempMatrix.y*height,end.x*width,end.y*height),isNearlyVertical=Math.abs(end.x-tempMatrix.x){var globalStop=start+stop.offset*ratio;gradient.addColorStop(Math.floor(1e5*globalStop)/1e5,Color.shared.setValue(stop.color).toHex())})}}else fillGradient.colorStops.forEach(stop=>{gradient.addColorStop(stop.offset,Color.shared.setValue(stop.color).toHex())});return gradient}return warn("FillStyle not recognised",fillStyle),"red"}class CanvasTextSystem{constructor(_renderer){this._activeTextures={},this._renderer=_renderer}getTextureSize(text,resolution,style){var text=CanvasTextMetrics.measureText(text||" ",style),width=Math.ceil(Math.ceil(Math.max(1,text.width)+2*style.padding)*resolution),text=Math.ceil(Math.ceil(Math.max(1,text.height)+2*style.padding)*resolution),width=Math.ceil(width-1e-6),text=Math.ceil(text-1e-6);return{width:nextPow2(width),height:nextPow2(text)}}getTexture(options,resolution,style,_textKey){"string"==typeof options&&(deprecation("8.0.0","CanvasTextSystem.getTexture: Use object TextOptions instead of separate arguments"),options={text:options,style:style,resolution:resolution}),options.style instanceof TextStyle||(options.style=new TextStyle(options.style));var{texture:style,canvasAndContext:resolution}=this.createTextureAndCanvas(options);return this._renderer.texture.initSource(style._source),CanvasPool.returnCanvasAndContext(resolution),style}createTextureAndCanvas(options){var{text,style}=options,options=null!=(options=options.resolution)?options:this._renderer.resolution,measured=CanvasTextMetrics.measureText(text||" ",style),width=Math.ceil(Math.ceil(Math.max(1,measured.width)+2*style.padding)*options),measured=Math.ceil(Math.ceil(Math.max(1,measured.height)+2*style.padding)*options),canvasAndContext=CanvasPool.getOptimalCanvasAndContext(width,measured),canvas=canvasAndContext.canvas,text=(this.renderTextToCanvas(text,style,options,canvasAndContext),getPo2TextureFromSource(canvas,width,measured,options));return style.trim&&(width=function(canvas,resolution=1){var{width,height}=canvas;if(null===(canvas=canvas.getContext("2d",{willReadFrequently:!0})))throw new TypeError("Failed to get canvas 2D context");var data=canvas.getImageData(0,0,width,height).data;let left=0,top=0,right=width-1,bottom=height-1;for(;topkey in obj?__defProp$R(obj,key,{enumerable:!0,configurable:!0,writable:!0,value:value}):obj[key]=value;class Graphics extends ViewContainer{constructor(options){var{context,roundPixels}=options=(options instanceof GraphicsContext?{context:options}:options)||{};super(((a,b)=>{for(var prop in b=b||{})__hasOwnProp$R.call(b,prop)&&__defNormalProp$R(a,prop,b[prop]);if(__getOwnPropSymbols$R)for(var prop of __getOwnPropSymbols$R(b))__propIsEnum$R.call(b,prop)&&__defNormalProp$R(a,prop,b[prop]);return a})({label:"Graphics"},((source,exclude)=>{var target={};for(prop in source)__hasOwnProp$R.call(source,prop)&&exclude.indexOf(prop)<0&&(target[prop]=source[prop]);if(null!=source&&__getOwnPropSymbols$R)for(var prop of __getOwnPropSymbols$R(source))exclude.indexOf(prop)<0&&__propIsEnum$R.call(source,prop)&&(target[prop]=source[prop]);return target})(options,["context","roundPixels"]))),this.renderPipeId="graphics",this._context=context||(this._ownedContext=new GraphicsContext),this._context.on("update",this.onViewUpdate,this),this.allowChildren=!1,this.roundPixels=null!=roundPixels&&roundPixels}set context(context){context!==this._context&&(this._context.off("update",this.onViewUpdate,this),this._context=context,this._context.on("update",this.onViewUpdate,this),this.onViewUpdate())}get context(){return this._context}get bounds(){return this._context.bounds}updateBounds(){}containsPoint(point){return this._context.containsPoint(point)}destroy(options){this._ownedContext&&!options?this._ownedContext.destroy(options):!0!==options&&!0!==(null==options?void 0:options.context)||this._context.destroy(options),this._ownedContext=null,this._context=null,super.destroy(options)}_callContextMethod(method,args){return this.context[method](...args),this}setFillStyle(...args){return this._callContextMethod("setFillStyle",args)}setStrokeStyle(...args){return this._callContextMethod("setStrokeStyle",args)}fill(...args){return this._callContextMethod("fill",args)}stroke(...args){return this._callContextMethod("stroke",args)}texture(...args){return this._callContextMethod("texture",args)}beginPath(){return this._callContextMethod("beginPath",[])}cut(){return this._callContextMethod("cut",[])}arc(...args){return this._callContextMethod("arc",args)}arcTo(...args){return this._callContextMethod("arcTo",args)}arcToSvg(...args){return this._callContextMethod("arcToSvg",args)}bezierCurveTo(...args){return this._callContextMethod("bezierCurveTo",args)}closePath(){return this._callContextMethod("closePath",[])}ellipse(...args){return this._callContextMethod("ellipse",args)}circle(...args){return this._callContextMethod("circle",args)}path(...args){return this._callContextMethod("path",args)}lineTo(...args){return this._callContextMethod("lineTo",args)}moveTo(...args){return this._callContextMethod("moveTo",args)}quadraticCurveTo(...args){return this._callContextMethod("quadraticCurveTo",args)}rect(...args){return this._callContextMethod("rect",args)}roundRect(...args){return this._callContextMethod("roundRect",args)}poly(...args){return this._callContextMethod("poly",args)}regularPoly(...args){return this._callContextMethod("regularPoly",args)}roundPoly(...args){return this._callContextMethod("roundPoly",args)}roundShape(...args){return this._callContextMethod("roundShape",args)}filletRect(...args){return this._callContextMethod("filletRect",args)}chamferRect(...args){return this._callContextMethod("chamferRect",args)}star(...args){return this._callContextMethod("star",args)}svg(...args){return this._callContextMethod("svg",args)}restore(...args){return this._callContextMethod("restore",args)}save(){return this._callContextMethod("save",[])}getTransform(){return this.context.getTransform()}resetTransform(){return this._callContextMethod("resetTransform",[])}rotateTransform(...args){return this._callContextMethod("rotate",args)}scaleTransform(...args){return this._callContextMethod("scale",args)}setTransform(...args){return this._callContextMethod("setTransform",args)}transform(...args){return this._callContextMethod("transform",args)}translateTransform(...args){return this._callContextMethod("translate",args)}clear(){return this._callContextMethod("clear",[])}get fillStyle(){return this._context.fillStyle}set fillStyle(value){this._context.fillStyle=value}get strokeStyle(){return this._context.strokeStyle}set strokeStyle(value){this._context.strokeStyle=value}clone(deep=!1){return deep?new Graphics(this._context.clone()):(this._ownedContext=null,new Graphics(this._context))}lineStyle(width,color,alpha){deprecation(v8_0_0,"Graphics#lineStyle is no longer needed. Use Graphics#setStrokeStyle to set the stroke style.");var strokeStyle={};return width&&(strokeStyle.width=width),color&&(strokeStyle.color=color),alpha&&(strokeStyle.alpha=alpha),this.context.strokeStyle=strokeStyle,this}beginFill(color,alpha){deprecation(v8_0_0,"Graphics#beginFill is no longer needed. Use Graphics#fill to fill the shape with the desired style.");var fillStyle={};return void 0!==color&&(fillStyle.color=color),void 0!==alpha&&(fillStyle.alpha=alpha),this.context.fillStyle=fillStyle,this}endFill(){deprecation(v8_0_0,"Graphics#endFill is no longer needed. Use Graphics#fill to fill the shape with the desired style."),this.context.fill();var strokeStyle=this.context.strokeStyle;return strokeStyle.width===GraphicsContext.defaultStrokeStyle.width&&strokeStyle.color===GraphicsContext.defaultStrokeStyle.color&&strokeStyle.alpha===GraphicsContext.defaultStrokeStyle.alpha||this.context.stroke(),this}drawCircle(...args){return deprecation(v8_0_0,"Graphics#drawCircle has been renamed to Graphics#circle"),this._callContextMethod("circle",args)}drawEllipse(...args){return deprecation(v8_0_0,"Graphics#drawEllipse has been renamed to Graphics#ellipse"),this._callContextMethod("ellipse",args)}drawPolygon(...args){return deprecation(v8_0_0,"Graphics#drawPolygon has been renamed to Graphics#poly"),this._callContextMethod("poly",args)}drawRect(...args){return deprecation(v8_0_0,"Graphics#drawRect has been renamed to Graphics#rect"),this._callContextMethod("rect",args)}drawRoundedRect(...args){return deprecation(v8_0_0,"Graphics#drawRoundedRect has been renamed to Graphics#roundRect"),this._callContextMethod("roundRect",args)}drawStar(...args){return deprecation(v8_0_0,"Graphics#drawStar has been renamed to Graphics#star"),this._callContextMethod("star",args)}}const localUniformMSDFBit={name:"local-uniform-msdf-bit",vertex:{header:` + struct LocalUniforms { + uColor:vec4, + uTransformMatrix:mat3x3, + uDistance: f32, + uRound:f32, + } + + @group(2) @binding(0) var localUniforms : LocalUniforms; + `,main:` + vColor *= localUniforms.uColor; + modelMatrix *= localUniforms.uTransformMatrix; + `,end:` + if(localUniforms.uRound == 1) + { + vPosition = vec4(roundPixels(vPosition.xy, globalUniforms.uResolution), vPosition.zw); + } + `},fragment:{header:` + struct LocalUniforms { + uColor:vec4, + uTransformMatrix:mat3x3, + uDistance: f32 + } + + @group(2) @binding(0) var localUniforms : LocalUniforms; + `,main:` + outColor = vec4(calculateMSDFAlpha(outColor, localUniforms.uColor, localUniforms.uDistance)); + `}},localUniformMSDFBitGl={name:"local-uniform-msdf-bit",vertex:{header:` + uniform mat3 uTransformMatrix; + uniform vec4 uColor; + uniform float uRound; + `,main:` + vColor *= uColor; + modelMatrix *= uTransformMatrix; + `,end:` + if(uRound == 1.) + { + gl_Position.xy = roundPixels(gl_Position.xy, uResolution); + } + `},fragment:{header:` + uniform float uDistance; + `,main:` + outColor = vec4(calculateMSDFAlpha(outColor, vColor, uDistance)); + `}},mSDFBit={name:"msdf-bit",fragment:{header:` + fn calculateMSDFAlpha(msdfColor:vec4, shapeColor:vec4, distance:f32) -> f32 { + + // MSDF + var median = msdfColor.r + msdfColor.g + msdfColor.b - + min(msdfColor.r, min(msdfColor.g, msdfColor.b)) - + max(msdfColor.r, max(msdfColor.g, msdfColor.b)); + + // SDF + median = min(median, msdfColor.a); + + var screenPxDistance = distance * (median - 0.5); + var alpha = clamp(screenPxDistance + 0.5, 0.0, 1.0); + if (median < 0.01) { + alpha = 0.0; + } else if (median > 0.99) { + alpha = 1.0; + } + + // Gamma correction for coverage-like alpha + var luma: f32 = dot(shapeColor.rgb, vec3(0.299, 0.587, 0.114)); + var gamma: f32 = mix(1.0, 1.0 / 2.2, luma); + var coverage: f32 = pow(shapeColor.a * alpha, gamma); + + return coverage; + + } + `}},mSDFBitGl={name:"msdf-bit",fragment:{header:` + float calculateMSDFAlpha(vec4 msdfColor, vec4 shapeColor, float distance) { + + // MSDF + float median = msdfColor.r + msdfColor.g + msdfColor.b - + min(msdfColor.r, min(msdfColor.g, msdfColor.b)) - + max(msdfColor.r, max(msdfColor.g, msdfColor.b)); + + // SDF + median = min(median, msdfColor.a); + + float screenPxDistance = distance * (median - 0.5); + float alpha = clamp(screenPxDistance + 0.5, 0.0, 1.0); + + if (median < 0.01) { + alpha = 0.0; + } else if (median > 0.99) { + alpha = 1.0; + } + + // Gamma correction for coverage-like alpha + float luma = dot(shapeColor.rgb, vec3(0.299, 0.587, 0.114)); + float gamma = mix(1.0, 1.0 / 2.2, luma); + float coverage = pow(shapeColor.a * alpha, gamma); + + return coverage; + } + `}};let gpuProgram$1,glProgram$1;class SdfShader extends Shader{constructor(){var uniforms=new UniformGroup({uColor:{value:new Float32Array([1,1,1,1]),type:"vec4"},uTransformMatrix:{value:new Matrix,type:"mat3x3"},uDistance:{value:4,type:"f32"},uRound:{value:0,type:"f32"}}),maxTextures=getMaxTexturesPerBatch();null!=gpuProgram$1?gpuProgram$1:gpuProgram$1=compileHighShaderGpuProgram({name:"sdf-shader",bits:[colorBit,generateTextureBatchBit(maxTextures),localUniformMSDFBit,mSDFBit,roundPixelsBit]}),null!=glProgram$1?glProgram$1:glProgram$1=compileHighShaderGlProgram({name:"sdf-shader",bits:[colorBitGl,generateTextureBatchBitGl(maxTextures),localUniformMSDFBitGl,mSDFBitGl,roundPixelsBitGl]}),super({glProgram:glProgram$1,gpuProgram:gpuProgram$1,resources:{localUniforms:uniforms,batchSamplers:getBatchSamplersUniformGroup(maxTextures)}})}}class AbstractBitmapFont extends EventEmitter{constructor(){super(...arguments),this.chars=Object.create(null),this.lineHeight=0,this.fontFamily="",this.fontMetrics={fontSize:0,ascent:0,descent:0},this.baseLineOffset=0,this.distanceField={type:"none",range:0},this.pages=[],this.applyFillAsTint=!0,this.baseMeasurementFontSize=100,this.baseRenderedFontSize=100}get font(){return deprecation(v8_0_0,"BitmapFont.font is deprecated, please use BitmapFont.fontFamily instead."),this.fontFamily}get pageTextures(){return deprecation(v8_0_0,"BitmapFont.pageTextures is deprecated, please use BitmapFont.pages instead."),this.pages}get size(){return deprecation(v8_0_0,"BitmapFont.size is deprecated, please use BitmapFont.fontMetrics.fontSize instead."),this.fontMetrics.fontSize}get distanceFieldRange(){return deprecation(v8_0_0,"BitmapFont.distanceFieldRange is deprecated, please use BitmapFont.distanceField.range instead."),this.distanceField.range}get distanceFieldType(){return deprecation(v8_0_0,"BitmapFont.distanceFieldType is deprecated, please use BitmapFont.distanceField.type instead."),this.distanceField.type}destroy(destroyTextures=!1){var _a;this.emit("destroy",this),this.removeAllListeners();for(const i in this.chars)null!=(_a=this.chars[i].texture)&&_a.destroy();this.chars=null,destroyTextures&&(this.pages.forEach(page=>page.texture.destroy(!0)),this.pages=null)}}function resolveCharacters(chars){if(""===chars)return[];var result=[];for(let i=0,j=(chars="string"==typeof chars?[chars]:chars).length;ikey in obj?__defProp$Q(obj,key,{enumerable:!0,configurable:!0,writable:!0,value:value}):obj[key]=value,__spreadValues$Q=(a,b)=>{for(var prop in b=b||{})__hasOwnProp$Q.call(b,prop)&&__defNormalProp$Q(a,prop,b[prop]);if(__getOwnPropSymbols$Q)for(var prop of __getOwnPropSymbols$Q(b))__propIsEnum$Q.call(b,prop)&&__defNormalProp$Q(a,prop,b[prop]);return a};const _DynamicBitmapFont=class _DynamicBitmapFont extends AbstractBitmapFont{constructor(options){super(),this.resolution=1,this.pages=[],this._padding=0,this._measureCache=Object.create(null),this._currentChars=[],this._currentX=0,this._currentY=0,this._currentPageIndex=-1,this._skipKerning=!1;var options=__spreadValues$Q(__spreadValues$Q({},_DynamicBitmapFont.defaultOptions),options),style=(this._textureSize=options.textureSize,this._mipmap=options.mipmap,options.style.clone()),requestedFontSize=(options.overrideFill&&(style._fill.color=16777215,style._fill.alpha=1,style._fill.texture=Texture.WHITE,style._fill.fill=null),this.applyFillAsTint=options.overrideFill,style.fontSize),font=(style.fontSize=this.baseMeasurementFontSize,fontStringFromTextStyle(style));options.overrideSize?style._stroke&&(style._stroke.width*=this.baseRenderedFontSize/requestedFontSize):style.fontSize=this.baseRenderedFontSize=requestedFontSize,this._style=style,this._skipKerning=null!=(requestedFontSize=options.skipKerning)&&requestedFontSize,this.resolution=null!=(requestedFontSize=options.resolution)?requestedFontSize:1,this._padding=null!=(requestedFontSize=options.padding)?requestedFontSize:4,this.fontMetrics=CanvasTextMetrics.measureFont(font),this.lineHeight=style.lineHeight||this.fontMetrics.fontSize||style.fontSize}ensureCharacters(chars){var charList=resolveCharacters(chars).filter(char=>!this._currentChars.includes(char)).filter((char,index,self)=>self.indexOf(char)===index);if(charList.length){this._currentChars=[...this._currentChars,...charList];let pageData,{canvas,context}=(pageData=-1===this._currentPageIndex?this._nextPage():this.pages[this._currentPageIndex]).canvasAndContext,textureSource=pageData.texture.source;var style=this._style;let currentX=this._currentX,currentY=this._currentY;var fontScale=this.baseRenderedFontSize/this.baseMeasurementFontSize,padding=this._padding*fontScale;let maxCharHeight=0,skipTexture=!1;var maxTextureWidth=canvas.width/this.resolution,maxTextureHeight=canvas.height/this.resolution;for(let i=0;imaxTextureWidth&&(currentY+=maxCharHeight,maxCharHeight=paddedHeight,currentX=0,currentY+maxCharHeight>maxTextureHeight)&&(textureSource.update(),pageData2=this._nextPage(),canvas=pageData2.canvasAndContext.canvas,context=pageData2.canvasAndContext.context,textureSource=pageData2.texture.source,currentY=0),width/fontScale-(null!=(width=null==(pageData2=style.dropShadow)?void 0:pageData2.distance)?width:0)-(null!=(width=null==(width=style._stroke)?void 0:width.width)?width:0));this.chars[char]={id:char.codePointAt(0),xOffset:-this._padding,yOffset:-this._padding,xAdvance:width,kerning:{}},skipTexture&&(this._drawGlyph(context,metrics,currentX+padding,currentY+padding,fontScale,style),width=textureSource.width*fontScale,metrics=textureSource.height*fontScale,width=new Rectangle(currentX/width*textureSource.width,currentY/metrics*textureSource.height,paddedWidth/width*textureSource.width,paddedHeight/metrics*textureSource.height),this.chars[char].texture=new Texture({source:textureSource,frame:width}),currentX+=Math.ceil(paddedWidth))}textureSource.update(),this._currentX=currentX,this._currentY=currentY,this._skipKerning&&this._applyKerning(charList,context)}}get pageTextures(){return deprecation(v8_0_0,"BitmapFont.pageTextures is deprecated, please use BitmapFont.pages instead."),this.pages}_applyKerning(newChars,context){var measureCache=this._measureCache;for(let i=0;i{let index=currentLine.chars.length-1;if(trimEnd){let lastChar=currentLine.chars[index];for(;" "===lastChar;)currentLine.width-=font.chars[lastChar].xAdvance,lastChar=currentLine.chars[--index]}layoutData.width=Math.max(layoutData.width,currentLine.width),currentLine={width:0,charPositions:[],chars:[],spaceWidth:0,spacesIndex:[]},firstWord=!0,layoutData.lines.push(currentLine),layoutData.height+=font.lineHeight},scale=font.baseMeasurementFontSize/style.fontSize,adjustedLetterSpacing=style.letterSpacing*scale,adjustedWordWrapWidth=style.wordWrapWidth*scale;for(let i=0;iadjustedWordWrapWidth?nextLine():currentWord.start=currentLine.width;var word=currentWord,start=currentLine.width;for(let j=0;jkey in obj?__defProp$P(obj,key,{enumerable:!0,configurable:!0,writable:!0,value:value}):obj[key]=value,__spreadValues$P=(a,b)=>{for(var prop in b=b||{})__hasOwnProp$P.call(b,prop)&&__defNormalProp$P(a,prop,b[prop]);if(__getOwnPropSymbols$P)for(var prop of __getOwnPropSymbols$P(b))__propIsEnum$P.call(b,prop)&&__defNormalProp$P(a,prop,b[prop]);return a};let fontCount=0;const BitmapFontManager=new class{constructor(){this.ALPHA=[["a","z"],["A","Z"]," "],this.NUMERIC=[["0","9"]],this.ALPHANUMERIC=[["a","z"],["A","Z"],["0","9"]," "],this.ASCII=[[" ","~"]],this.defaultOptions={chars:this.ALPHANUMERIC,resolution:1,padding:4,skipKerning:!1}}getFont(text,style){var _a;let fontFamilyKey=style.fontFamily+"-bitmap",overrideFill=!0;if(style._fill.fill&&!style._stroke)fontFamilyKey+=style._fill.fill.styleKey,overrideFill=!1;else if(style._stroke||style.dropShadow){let key=style.styleKey;key=key.substring(0,key.lastIndexOf("-")),fontFamilyKey=key+"-bitmap",overrideFill=!1}return Cache.has(fontFamilyKey)||(style=new DynamicBitmapFont(__spreadValues$P({style:style,overrideFill:overrideFill,overrideSize:!0},this.defaultOptions)),50<++fontCount&&warn("BitmapText",`You have dynamically created ${fontCount} bitmap fonts, this can be inefficient. Try pre installing your font styles using \`BitmapFont.install({name:"style1", style})\``),style.once("destroy",()=>{fontCount--,Cache.remove(fontFamilyKey)}),Cache.set(fontFamilyKey,style)),null!=(_a=(style=Cache.get(fontFamilyKey)).ensureCharacters)&&_a.call(style,text),style}getLayout(text,style,trimEnd=!0){var bitmapFont=this.getFont(text,style);return getBitmapTextLayout([...text],style,bitmapFont,trimEnd)}measureText(text,style,trimEnd=!0){return this.getLayout(text,style,trimEnd)}install(...args){var _a;let options=args[0];"string"==typeof options&&(options={name:options,style:args[1],chars:null==(_a=args[2])?void 0:_a.chars,resolution:null==(_a=args[2])?void 0:_a.resolution,padding:null==(_a=args[2])?void 0:_a.padding,skipKerning:null==(_a=args[2])?void 0:_a.skipKerning},deprecation(v8_0_0,"BitmapFontManager.install(name, style, options) is deprecated, use BitmapFontManager.install({name, style, ...options})"));const name=null==options?void 0:options.name;if(name)return args=null!==(_a=(args=(options=__spreadValues$P(__spreadValues$P({},this.defaultOptions),options)).style)instanceof TextStyle?args:new TextStyle(args))._fill.fill&&void 0!==_a._fill.fill,_a=new DynamicBitmapFont({style:_a,overrideFill:args,skipKerning:options.skipKerning,padding:options.padding,resolution:options.resolution,overrideSize:!1}),args=resolveCharacters(options.chars),_a.ensureCharacters(args.join("")),Cache.set(name+"-bitmap",_a),_a.once("destroy",()=>Cache.remove(name+"-bitmap")),_a;throw new Error("[BitmapFontManager] Property `name` is required.")}uninstall(name){name+="-bitmap",(name=Cache.get(name))&&name.destroy()}};class BitmapTextPipe{constructor(renderer){this._gpuBitmapText={},this._destroyRenderableBound=this.destroyRenderable.bind(this),this._renderer=renderer,this._renderer.renderableGC.addManagedHash(this,"_gpuBitmapText")}validateRenderable(bitmapText){var graphicsRenderable=this._getGpuBitmapText(bitmapText);return bitmapText._didTextUpdate&&(bitmapText._didTextUpdate=!1,this._updateContext(bitmapText,graphicsRenderable)),this._renderer.renderPipes.graphics.validateRenderable(graphicsRenderable)}addRenderable(bitmapText,instructionSet){var graphicsRenderable=this._getGpuBitmapText(bitmapText);syncWithProxy(bitmapText,graphicsRenderable),bitmapText._didTextUpdate&&(bitmapText._didTextUpdate=!1,this._updateContext(bitmapText,graphicsRenderable)),this._renderer.renderPipes.graphics.addRenderable(graphicsRenderable,instructionSet),graphicsRenderable.context.customShader&&this._updateDistanceField(bitmapText)}destroyRenderable(bitmapText){bitmapText.off("destroyed",this._destroyRenderableBound),this._destroyRenderableByUid(bitmapText.uid)}_destroyRenderableByUid(renderableUid){var context=this._gpuBitmapText[renderableUid].context;context.customShader&&(BigPool.return(context.customShader),context.customShader=null),BigPool.return(this._gpuBitmapText[renderableUid]),this._gpuBitmapText[renderableUid]=null}updateRenderable(bitmapText){var graphicsRenderable=this._getGpuBitmapText(bitmapText);syncWithProxy(bitmapText,graphicsRenderable),this._renderer.renderPipes.graphics.updateRenderable(graphicsRenderable),graphicsRenderable.context.customShader&&this._updateDistanceField(bitmapText)}_updateContext(bitmapText,proxyGraphics){var context=proxyGraphics.context,bitmapFont=BitmapFontManager.getFont(bitmapText.text,bitmapText._style),chars=(context.clear(),"none"===bitmapFont.distanceField.type||context.customShader||(context.customShader=BigPool.get(SdfShader)),Array.from(bitmapText.text)),proxyGraphics=bitmapText._style;let currentY=bitmapFont.baseLineOffset;var bitmapTextLayout=getBitmapTextLayout(chars,proxyGraphics,bitmapFont,!0);let index=0;var padding=proxyGraphics.padding,scale=bitmapTextLayout.scale;let tx=bitmapTextLayout.width,ty=bitmapTextLayout.height+bitmapTextLayout.offsetY;proxyGraphics._stroke&&(tx+=proxyGraphics._stroke.width/scale,ty+=proxyGraphics._stroke.width/scale),context.translate(-bitmapText._anchor._x*tx-padding,-bitmapText._anchor._y*ty-padding).scale(scale,scale);var tint=bitmapFont.applyFillAsTint?proxyGraphics._fill.color:16777215;for(let i=0;i{console.error(e)}),htmlText._didTextUpdate=!1,updateTextBounds(batchableSprite,htmlText)}async _updateGpuText(htmlText){htmlText._didTextUpdate=!1;var newKey,batchableSprite,gpuText=this._getGpuText(htmlText);gpuText.generatingTexture||(newKey=htmlText._getKey(),this._renderer.htmlText.decreaseReferenceCount(gpuText.currentKey),gpuText.generatingTexture=!0,gpuText.currentKey=newKey,newKey=null!=(newKey=htmlText.resolution)?newKey:this._renderer.resolution,newKey=await this._renderer.htmlText.getManagedTexture(htmlText.text,newKey,htmlText._style,htmlText._getKey()),(batchableSprite=gpuText.batchableSprite).texture=gpuText.texture=newKey,gpuText.generatingTexture=!1,gpuText.textureNeedsUploading=!0,htmlText.onViewUpdate(),updateTextBounds(batchableSprite,htmlText))}_getGpuText(htmlText){return this._gpuText[htmlText.uid]||this.initGpuText(htmlText)}initGpuText(htmlText){var gpuTextData={texture:Texture.EMPTY,currentKey:"--",batchableSprite:BigPool.get(BatchableSprite),textureNeedsUploading:!1,generatingTexture:!1},batchableSprite=gpuTextData.batchableSprite;return batchableSprite.renderable=htmlText,batchableSprite.transform=htmlText.groupTransform,batchableSprite.texture=Texture.EMPTY,batchableSprite.bounds={minX:0,maxX:1,minY:0,maxY:0},batchableSprite.roundPixels=this._renderer._roundPixels|htmlText._roundPixels,htmlText._resolution=(htmlText._autoResolution?this._renderer:htmlText).resolution,this._gpuText[htmlText.uid]=gpuTextData,htmlText.on("destroyed",this._destroyRenderableBound),gpuTextData}destroy(){for(const i in this._gpuText)this._destroyRenderableById(i);this._gpuText=null,this._renderer=null}}HTMLTextPipe.extension={type:["webgl-pipes","webgpu-pipes","canvas-pipes"],name:"htmlText"};const nssvg="http://www.w3.org/2000/svg",nsxhtml="http://www.w3.org/1999/xhtml";class HTMLTextRenderData{constructor(){this.svgRoot=document.createElementNS(nssvg,"svg"),this.foreignObject=document.createElementNS(nssvg,"foreignObject"),this.domElement=document.createElementNS(nsxhtml,"div"),this.styleElement=document.createElementNS(nsxhtml,"style"),this.image=new Image;var{foreignObject,svgRoot,styleElement,domElement}=this;foreignObject.setAttribute("width","10000"),foreignObject.setAttribute("height","10000"),foreignObject.style.overflow="hidden",svgRoot.appendChild(foreignObject),foreignObject.appendChild(styleElement),foreignObject.appendChild(domElement)}}function dropShadowToCSS(dropShadowStyle){var color=Color.shared.setValue(dropShadowStyle.color).setAlpha(dropShadowStyle.alpha).toHexa(),position=Math.round(Math.cos(dropShadowStyle.angle)*dropShadowStyle.distance)+`px ${Math.round(Math.sin(dropShadowStyle.angle)*dropShadowStyle.distance)}px`;return 0"color: "+Color.shared.setValue(value).toHex(),breakWords:value=>"word-wrap: "+(value?"break-all":"break-word"),stroke:strokeToCSS,dropShadow:dropShadowToCSS};var __defProp$O=Object.defineProperty,__getOwnPropSymbols$O=Object.getOwnPropertySymbols,__hasOwnProp$O=Object.prototype.hasOwnProperty,__propIsEnum$O=Object.prototype.propertyIsEnumerable,__defNormalProp$O=(obj,key,value)=>key in obj?__defProp$O(obj,key,{enumerable:!0,configurable:!0,writable:!0,value:value}):obj[key]=value;class HTMLTextStyle extends TextStyle{constructor(options={}){super(options),this._cssOverrides=[],null==this.cssOverrides&&(this.cssOverrides=options.cssOverrides),this.tagStyles=null!=(options=options.tagStyles)?options:{}}set cssOverrides(value){this._cssOverrides=value instanceof Array?value:[value],this.update()}get cssOverrides(){return this._cssOverrides}_generateKey(){return this._styleKey=generateTextStyleKey(this)+this._cssOverrides.join("-"),this._styleKey}update(){this._cssStyle=null,super.update()}clone(){return new HTMLTextStyle({align:this.align,breakWords:this.breakWords,dropShadow:this.dropShadow?((a,b)=>{for(var prop in b=b||{})__hasOwnProp$O.call(b,prop)&&__defNormalProp$O(a,prop,b[prop]);if(__getOwnPropSymbols$O)for(var prop of __getOwnPropSymbols$O(b))__propIsEnum$O.call(b,prop)&&__defNormalProp$O(a,prop,b[prop]);return a})({},this.dropShadow):null,fill:this._fill,fontFamily:this.fontFamily,fontSize:this.fontSize,fontStyle:this.fontStyle,fontVariant:this.fontVariant,fontWeight:this.fontWeight,letterSpacing:this.letterSpacing,lineHeight:this.lineHeight,padding:this.padding,stroke:this._stroke,whiteSpace:this.whiteSpace,wordWrap:this.wordWrap,wordWrapWidth:this.wordWrapWidth,cssOverrides:this.cssOverrides})}get cssStyle(){return this._cssStyle||(this._cssStyle=function(style){var stroke=style._stroke,fill=style._fill,fill=[`div { ${["color: "+Color.shared.setValue(fill.color).toHex(),`font-size: ${style.fontSize}px`,"font-family: "+style.fontFamily,"font-weight: "+style.fontWeight,"font-style: "+style.fontStyle,"font-variant: "+style.fontVariant,`letter-spacing: ${style.letterSpacing}px`,"text-align: "+style.align,`padding: ${style.padding}px`,"white-space: "+("pre"===style.whiteSpace&&style.wordWrap?"pre-wrap":style.whiteSpace),...style.lineHeight?[`line-height: ${style.lineHeight}px`]:[],...style.wordWrap?["word-wrap: "+(style.breakWords?"break-all":"break-word"),`max-width: ${style.wordWrapWidth}px`]:[],...stroke?[strokeToCSS(stroke)]:[],...style.dropShadow?[dropShadowToCSS(style.dropShadow)]:[],...style.cssOverrides].join(";")} }`],tagStyles=style.tagStyles,out=fill;for(const i in tagStyles){var tagStyle=tagStyles[i],cssTagStyle=[];for(const j in tagStyle)transform[j]?cssTagStyle.push(transform[j](tagStyle[j])):templates[j]&&cssTagStyle.push(templates[j].replace("{{VALUE}}",tagStyle[j]));out.push(`${i} { ${cssTagStyle.join(";")} }`)}return fill.join(" ")}(this)),this._cssStyle}addOverride(...value){0<(value=value.filter(v=>!this.cssOverrides.includes(v))).length&&(this.cssOverrides.push(...value),this.update())}removeOverride(...value){const toRemove=value.filter(v=>this.cssOverrides.includes(v));0!toRemove.includes(v)),this.update())}set fill(value){"string"!=typeof value&&"number"!=typeof value&&warn("[HTMLTextStyle] only color fill is not supported by HTMLText"),super.fill=value}set stroke(value){value&&"string"!=typeof value&&"number"!=typeof value&&warn("[HTMLTextStyle] only color stroke is not supported by HTMLText"),super.stroke=value}}async function loadFontCSS(style,url){return url=await async function(url){const blob=await(await DOMAdapter.get().fetch(url)).blob(),reader=new FileReader;return new Promise((resolve,reject)=>{reader.onloadend=()=>resolve(reader.result),reader.onerror=reject,reader.readAsDataURL(blob)})}(url),`@font-face { + font-family: "${style.fontFamily}"; + src: url('${url}'); + font-weight: ${style.fontWeight}; + font-style: ${style.fontStyle}; + }`}const FontStylePromiseCache=new Map;let tempHTMLTextRenderData;class HTMLTextSystem{constructor(renderer){this._activeTextures={},this._renderer=renderer,this._createCanvas=2===renderer.type}getTexture(options){return this._buildTexturePromise(options.text,options.resolution,options.style)}getManagedTexture(text,resolution,style,textKey){return this._activeTextures[textKey]?(this._increaseReferenceCount(textKey),this._activeTextures[textKey].promise):(text=this._buildTexturePromise(text,resolution,style).then(texture=>this._activeTextures[textKey].texture=texture),this._activeTextures[textKey]={texture:null,promise:text,usageCount:1},text)}async _buildTexturePromise(text,resolution,style){var htmlTextData=BigPool.get(HTMLTextRenderData),fontFamilies=function(text,style){var fontFamily=style.fontFamily;const fontFamilies=[],dedupe={};function addFontFamily(fontFamily2){dedupe[fontFamily2]||(fontFamilies.push(fontFamily2),dedupe[fontFamily2]=!0)}if(text=text.match(/font-family:([^;"\s]+)/g),Array.isArray(fontFamily))for(let i=0;i{addFontFamily(match.split(":")[1].trim())});for(const i in style.tagStyles)addFontFamily(style.tagStyles[i].fontFamily);return fontFamilies}(text,style),fontCSS=await async function(fontFamilies,style,defaultOptions){return fontFamilies=fontFamilies.filter(fontFamily=>Cache.has(fontFamily+"-and-url")).map((fontFamily,i)=>{var url;return FontStylePromiseCache.has(fontFamily)||(url=Cache.get(fontFamily+"-and-url").url,0===i?FontStylePromiseCache.set(fontFamily,loadFontCSS({fontWeight:style.fontWeight,fontStyle:style.fontStyle,fontFamily:fontFamily},url)):FontStylePromiseCache.set(fontFamily,loadFontCSS({fontWeight:defaultOptions.fontWeight,fontStyle:defaultOptions.fontStyle,fontFamily:fontFamily},url))),FontStylePromiseCache.get(fontFamily)}),(await Promise.all(fontFamilies)).join("\n")}(fontFamilies,style,HTMLTextStyle.defaultTextStyle),measured=function(text,style,fontStyleCSS,htmlTextRenderData){var{domElement:htmlTextRenderData,styleElement,svgRoot}=htmlTextRenderData=htmlTextRenderData||(tempHTMLTextRenderData=tempHTMLTextRenderData||new HTMLTextRenderData),text=(htmlTextRenderData.innerHTML=`
${text}
`,htmlTextRenderData.setAttribute("style","transform-origin: top left; display: inline-block"),fontStyleCSS&&(styleElement.textContent=fontStyleCSS),document.body.appendChild(svgRoot),htmlTextRenderData.getBoundingClientRect()),styleElement=(svgRoot.remove(),2*style.padding);return{width:text.width-styleElement,height:text.height-styleElement}}(text,style,fontCSS,htmlTextData),width=Math.ceil(Math.ceil(Math.max(1,measured.width)+2*style.padding)*resolution),measured=Math.ceil(Math.ceil(Math.max(1,measured.height)+2*style.padding)*resolution),image=htmlTextData.image,width=(image.width=2+(0|width),image.height=2+(0|measured),function(text,style,resolution,fontCSS,htmlTextData){var{domElement,styleElement,svgRoot}=htmlTextData,{width:style,height:text}=(domElement.innerHTML=`
${text}
`,domElement.setAttribute("style",`transform: scale(${resolution});transform-origin: top left; display: inline-block`),styleElement.textContent=fontCSS,htmlTextData.image);return svgRoot.setAttribute("width",style.toString()),svgRoot.setAttribute("height",text.toString()),(new XMLSerializer).serializeToString(svgRoot)}(text,style,resolution,fontCSS,htmlTextData)),measured=(await function(image,url,delay){return new Promise(async resolve=>{delay&&await new Promise(resolve2=>setTimeout(resolve2,100)),image.onload=()=>{resolve()},image.src="data:image/svg+xml;charset=utf8,"+encodeURIComponent(url),image.crossOrigin="anonymous"})}(image,width,(fontCSS=DOMAdapter.get().getNavigator().userAgent,/^((?!chrome|android).)*safari/i.test(fontCSS)&&0{activeTexture.texture=texture,this._cleanUp(activeTexture)}).catch(()=>{warn("HTMLTextSystem: Failed to clean texture")}),this._activeTextures[textKey]=null)}_cleanUp(activeTexture){TexturePool.returnTexture(activeTexture.texture),activeTexture.texture.source.resource=null,activeTexture.texture.source.uploadMethodId="unknown"}getReferenceCount(textKey){return this._activeTextures[textKey].usageCount}destroy(){this._activeTextures=null}}HTMLTextSystem.extension={type:["webgl-system","webgpu-system","canvas-system"],name:"htmlText"},HTMLTextSystem.defaultFontOptions={fontFamily:"Arial",fontStyle:"normal",fontWeight:"normal"},extensions.add(HTMLTextSystem),extensions.add(HTMLTextPipe);var __defProp$N=Object.defineProperty,__getOwnPropSymbols$N=Object.getOwnPropertySymbols,__hasOwnProp$N=Object.prototype.hasOwnProperty,__propIsEnum$N=Object.prototype.propertyIsEnumerable,__defNormalProp$N=(obj,key,value)=>key in obj?__defProp$N(obj,key,{enumerable:!0,configurable:!0,writable:!0,value:value}):obj[key]=value,__spreadValues$N=(a,b)=>{for(var prop in b=b||{})__hasOwnProp$N.call(b,prop)&&__defNormalProp$N(a,prop,b[prop]);if(__getOwnPropSymbols$N)for(var prop of __getOwnPropSymbols$N(b))__propIsEnum$N.call(b,prop)&&__defNormalProp$N(a,prop,b[prop]);return a};const _MeshGeometry=class _MeshGeometry extends Geometry{constructor(...args){let options=null!=(_a=args[0])?_a:{};options instanceof Float32Array&&(deprecation(v8_0_0,"use new MeshGeometry({ positions, uvs, indices }) instead"),options={positions:options,uvs:args[1],indices:args[2]});var _a=(options=__spreadValues$N(__spreadValues$N({},_MeshGeometry.defaultOptions),options)).positions||new Float32Array([0,0,1,0,1,1,0,1]),uvs=options.uvs||(options.positions?new Float32Array(_a.length):new Float32Array([0,0,1,0,1,1,0,1])),args=options.indices||new Uint32Array([0,1,2,0,2,3]),shrinkToFit=options.shrinkBuffersToFit;super({attributes:{aPosition:{buffer:new Buffer({data:_a,label:"attribute-mesh-positions",shrinkToFit:shrinkToFit,usage:BufferUsage.VERTEX|BufferUsage.COPY_DST}),format:"float32x2",stride:8,offset:0},aUV:{buffer:new Buffer({data:uvs,label:"attribute-mesh-uvs",shrinkToFit:shrinkToFit,usage:BufferUsage.VERTEX|BufferUsage.COPY_DST}),format:"float32x2",stride:8,offset:0}},indexBuffer:new Buffer({data:args,label:"index-mesh-buffer",shrinkToFit:shrinkToFit,usage:BufferUsage.INDEX|BufferUsage.COPY_DST}),topology:options.topology}),this.batchMode="auto"}get positions(){return this.attributes.aPosition.buffer.data}set positions(value){this.attributes.aPosition.buffer.data=value}get uvs(){return this.attributes.aUV.buffer.data}set uvs(value){this.attributes.aUV.buffer.data=value}get indices(){return this.indexBuffer.data}set indices(value){this.indexBuffer.data=value}};_MeshGeometry.defaultOptions={topology:"triangle-list",shrinkBuffersToFit:!1};let MeshGeometry=_MeshGeometry;var __defProp$M=Object.defineProperty,__defProps$l=Object.defineProperties,__getOwnPropDescs$l=Object.getOwnPropertyDescriptors,__getOwnPropSymbols$M=Object.getOwnPropertySymbols,__hasOwnProp$M=Object.prototype.hasOwnProperty,__propIsEnum$M=Object.prototype.propertyIsEnumerable,__defNormalProp$M=(obj,key,value)=>key in obj?__defProp$M(obj,key,{enumerable:!0,configurable:!0,writable:!0,value:value}):obj[key]=value;const localUniformBit={name:"local-uniform-bit",vertex:{header:` + + struct LocalUniforms { + uTransformMatrix:mat3x3, + uColor:vec4, + uRound:f32, + } + + @group(1) @binding(0) var localUniforms : LocalUniforms; + `,main:` + vColor *= localUniforms.uColor; + modelMatrix *= localUniforms.uTransformMatrix; + `,end:` + if(localUniforms.uRound == 1) + { + vPosition = vec4(roundPixels(vPosition.xy, globalUniforms.uResolution), vPosition.zw); + } + `}},localUniformBitGroup2=(findMixin=(a,b)=>__defProps$l(a,__getOwnPropDescs$l(b)))((sortMixin=(a,b)=>{for(var prop in b=b||{})__hasOwnProp$M.call(b,prop)&&__defNormalProp$M(a,prop,b[prop]);if(__getOwnPropSymbols$M)for(var prop of __getOwnPropSymbols$M(b))__propIsEnum$M.call(b,prop)&&__defNormalProp$M(a,prop,b[prop]);return a})({},localUniformBit),{vertex:findMixin(sortMixin({},localUniformBit.vertex),{header:localUniformBit.vertex.header.replace("group(1)","group(2)")})}),localUniformBitGl={name:"local-uniform-bit",vertex:{header:` + + uniform mat3 uTransformMatrix; + uniform vec4 uColor; + uniform float uRound; + `,main:` + vColor *= uColor; + modelMatrix = uTransformMatrix; + `,end:` + if(uRound == 1.) + { + gl_Position.xy = roundPixels(gl_Position.xy, uResolution); + } + `}},tilingBit={name:"tiling-bit",vertex:{header:` + struct TilingUniforms { + uMapCoord:mat3x3, + uClampFrame:vec4, + uClampOffset:vec2, + uTextureTransform:mat3x3, + uSizeAnchor:vec4 + }; + + @group(2) @binding(0) var tilingUniforms: TilingUniforms; + @group(2) @binding(1) var uTexture: texture_2d; + @group(2) @binding(2) var uSampler: sampler; + `,main:` + uv = (tilingUniforms.uTextureTransform * vec3(uv, 1.0)).xy; + + position = (position - tilingUniforms.uSizeAnchor.zw) * tilingUniforms.uSizeAnchor.xy; + `},fragment:{header:` + struct TilingUniforms { + uMapCoord:mat3x3, + uClampFrame:vec4, + uClampOffset:vec2, + uTextureTransform:mat3x3, + uSizeAnchor:vec4 + }; + + @group(2) @binding(0) var tilingUniforms: TilingUniforms; + @group(2) @binding(1) var uTexture: texture_2d; + @group(2) @binding(2) var uSampler: sampler; + `,main:` + + var coord = vUV + ceil(tilingUniforms.uClampOffset - vUV); + coord = (tilingUniforms.uMapCoord * vec3(coord, 1.0)).xy; + var unclamped = coord; + coord = clamp(coord, tilingUniforms.uClampFrame.xy, tilingUniforms.uClampFrame.zw); + + var bias = 0.; + + if(unclamped.x == coord.x && unclamped.y == coord.y) + { + bias = -32.; + } + + outColor = textureSampleBias(uTexture, uSampler, coord, bias); + `}},tilingBitGl={name:"tiling-bit",vertex:{header:` + uniform mat3 uTextureTransform; + uniform vec4 uSizeAnchor; + + `,main:` + uv = (uTextureTransform * vec3(aUV, 1.0)).xy; + + position = (position - uSizeAnchor.zw) * uSizeAnchor.xy; + `},fragment:{header:` + uniform sampler2D uTexture; + uniform mat3 uMapCoord; + uniform vec4 uClampFrame; + uniform vec2 uClampOffset; + `,main:` + + vec2 coord = vUV + ceil(uClampOffset - vUV); + coord = (uMapCoord * vec3(coord, 1.0)).xy; + vec2 unclamped = coord; + coord = clamp(coord, uClampFrame.xy, uClampFrame.zw); + + outColor = texture(uTexture, coord, unclamped == coord ? 0.0 : -32.0);// lod-bias very negative to force lod 0 + + `}};let gpuProgram,glProgram;class TilingSpriteShader extends Shader{constructor(){null!=gpuProgram?gpuProgram:gpuProgram=compileHighShaderGpuProgram({name:"tiling-sprite-shader",bits:[localUniformBit,tilingBit,roundPixelsBit]}),null!=glProgram?glProgram:glProgram=compileHighShaderGlProgram({name:"tiling-sprite-shader",bits:[localUniformBitGl,tilingBitGl,roundPixelsBitGl]});var tilingUniforms=new UniformGroup({uMapCoord:{value:new Matrix,type:"mat3x3"},uClampFrame:{value:new Float32Array([0,0,1,1]),type:"vec4"},uClampOffset:{value:new Float32Array([0,0]),type:"vec2"},uTextureTransform:{value:new Matrix,type:"mat3x3"},uSizeAnchor:{value:new Float32Array([100,100,.5,.5]),type:"vec4"}});super({glProgram:glProgram,gpuProgram:gpuProgram,resources:{localUniforms:new UniformGroup({uTransformMatrix:{value:new Matrix,type:"mat3x3"},uColor:{value:new Float32Array([1,1,1,1]),type:"vec4"},uRound:{value:0,type:"f32"}}),tilingUniforms:tilingUniforms,uTexture:Texture.EMPTY.source,uSampler:Texture.EMPTY.source.style}})}updateUniforms(width,height,matrix,anchorX,anchorY,texture){var tilingUniforms=this.resources.tilingUniforms,textureWidth=texture.width,textureHeight=texture.height,textureMatrix=texture.textureMatrix,uTextureTransform=tilingUniforms.uniforms.uTextureTransform;uTextureTransform.set(matrix.a*textureWidth/width,matrix.b*textureWidth/height,matrix.c*textureHeight/width,matrix.d*textureHeight/height,matrix.tx/width,matrix.ty/height),uTextureTransform.invert(),tilingUniforms.uniforms.uMapCoord=textureMatrix.mapCoord,tilingUniforms.uniforms.uClampFrame=textureMatrix.uClampFrame,tilingUniforms.uniforms.uClampOffset=textureMatrix.uClampOffset,tilingUniforms.uniforms.uTextureTransform=uTextureTransform,tilingUniforms.uniforms.uSizeAnchor[0]=width,tilingUniforms.uniforms.uSizeAnchor[1]=height,tilingUniforms.uniforms.uSizeAnchor[2]=anchorX,tilingUniforms.uniforms.uSizeAnchor[3]=anchorY,texture&&(this.resources.uTexture=texture.source,this.resources.uSampler=texture.source.style)}}class QuadGeometry extends MeshGeometry{constructor(){super({positions:new Float32Array([0,0,1,0,1,1,0,1]),uvs:new Float32Array([0,0,1,0,1,1,0,1]),indices:new Uint32Array([0,1,2,0,2,3])})}}const sharedQuad=new QuadGeometry;class TilingSpritePipe{constructor(renderer){this._state=State.default2d,this._tilingSpriteDataHash=Object.create(null),this._destroyRenderableBound=this.destroyRenderable.bind(this),this._renderer=renderer,this._renderer.renderableGC.addManagedHash(this,"_tilingSpriteDataHash")}validateRenderable(renderable){var tilingSpriteData=this._getTilingSpriteData(renderable),couldBatch=tilingSpriteData.canBatch,canBatch=(this._updateCanBatch(renderable),tilingSpriteData.canBatch);return canBatch&&canBatch===couldBatch?!(tilingSpriteData=tilingSpriteData.batchableMesh)._batcher.checkAndUpdateTexture(tilingSpriteData,renderable.texture):couldBatch!==canBatch}addRenderable(tilingSprite,instructionSet){var batcher=this._renderer.renderPipes.batch,tilingSpriteData=(this._updateCanBatch(tilingSprite),this._getTilingSpriteData(tilingSprite)),{geometry,canBatch}=tilingSpriteData;canBatch?(tilingSpriteData.batchableMesh||(tilingSpriteData.batchableMesh=new BatchableMesh),canBatch=tilingSpriteData.batchableMesh,tilingSprite.didViewUpdate&&(this._updateBatchableMesh(tilingSprite),canBatch.geometry=geometry,canBatch.renderable=tilingSprite,canBatch.transform=tilingSprite.groupTransform,canBatch.setTexture(tilingSprite._texture)),canBatch.roundPixels=this._renderer._roundPixels|tilingSprite._roundPixels,batcher.addToBatch(canBatch,instructionSet)):(batcher.break(instructionSet),tilingSpriteData.shader||(tilingSpriteData.shader=new TilingSpriteShader),this.updateRenderable(tilingSprite),instructionSet.add(tilingSprite))}execute(tilingSprite){var shader=this._tilingSpriteDataHash[tilingSprite.uid].shader,localUniforms=(shader.groups[0]=this._renderer.globalUniforms.bindGroup,shader.resources.localUniforms.uniforms);localUniforms.uTransformMatrix=tilingSprite.groupTransform,localUniforms.uRound=this._renderer._roundPixels|tilingSprite._roundPixels,color32BitToUniform(tilingSprite.groupColorAlpha,localUniforms.uColor,0),this._state.blendMode=getAdjustedBlendModeBlend(tilingSprite.groupBlendMode,tilingSprite.texture._source),this._renderer.encoder.draw({geometry:sharedQuad,shader:shader,state:this._state})}updateRenderable(tilingSprite){var tilingSpriteData=this._getTilingSpriteData(tilingSprite),canBatch=tilingSpriteData.canBatch;canBatch?(canBatch=tilingSpriteData.batchableMesh,tilingSprite.didViewUpdate&&this._updateBatchableMesh(tilingSprite),canBatch._batcher.updateElement(canBatch)):tilingSprite.didViewUpdate&&(canBatch=tilingSpriteData.shader).updateUniforms(tilingSprite.width,tilingSprite.height,tilingSprite._tileTransform.matrix,tilingSprite.anchor.x,tilingSprite.anchor.y,tilingSprite.texture)}destroyRenderable(tilingSprite){var tilingSpriteData=this._getTilingSpriteData(tilingSprite);(tilingSpriteData.batchableMesh=null)!=(tilingSpriteData=tilingSpriteData.shader)&&tilingSpriteData.destroy(),this._tilingSpriteDataHash[tilingSprite.uid]=null,tilingSprite.off("destroyed",this._destroyRenderableBound)}_getTilingSpriteData(renderable){return this._tilingSpriteDataHash[renderable.uid]||this._initTilingSpriteData(renderable)}_initTilingSpriteData(tilingSprite){var geometry=new MeshGeometry({indices:sharedQuad.indices,positions:sharedQuad.positions.slice(),uvs:sharedQuad.uvs.slice()});return this._tilingSpriteDataHash[tilingSprite.uid]={canBatch:!0,renderable:tilingSprite,geometry:geometry},tilingSprite.on("destroyed",this._destroyRenderableBound),this._tilingSpriteDataHash[tilingSprite.uid]}_updateBatchableMesh(tilingSprite){var geometry=this._getTilingSpriteData(tilingSprite).geometry,style=tilingSprite.texture.source.style;"repeat"!==style.addressMode&&(style.addressMode="repeat",style.update()),function(tilingSprite,uvs){var width=(texture=tilingSprite.texture).frame.width,texture=texture.frame.height;let anchorX=0,anchorY=0;tilingSprite.applyAnchorToTexture&&(anchorX=tilingSprite.anchor.x,anchorY=tilingSprite.anchor.y),uvs[0]=uvs[6]=-anchorX,uvs[2]=uvs[4]=1-anchorX,uvs[1]=uvs[3]=-anchorY,uvs[5]=uvs[7]=1-anchorY;var textureMatrix=Matrix.shared;textureMatrix.copyFrom(tilingSprite._tileTransform.matrix),textureMatrix.tx/=tilingSprite.width,textureMatrix.ty/=tilingSprite.height,textureMatrix.invert(),textureMatrix.scale(tilingSprite.width/width,tilingSprite.height/texture);{var array=uvs,offset=0;let index=0;var size=array.length/2,a=textureMatrix.a,b=textureMatrix.b,c=textureMatrix.c,d=textureMatrix.d,tx=textureMatrix.tx,ty=textureMatrix.ty;for(offset*=2;indexkey in obj?__defProp$L(obj,key,{enumerable:!0,configurable:!0,writable:!0,value:value}):obj[key]=value,__spreadValues$L=(a,b)=>{for(var prop in b=b||{})__hasOwnProp$L.call(b,prop)&&__defNormalProp$L(a,prop,b[prop]);if(__getOwnPropSymbols$L)for(var prop of __getOwnPropSymbols$L(b))__propIsEnum$L.call(b,prop)&&__defNormalProp$L(a,prop,b[prop]);return a};const _PlaneGeometry=class _PlaneGeometry extends MeshGeometry{constructor(...args){var _a;super({});let options=null!=(_a=args[0])?_a:{};"number"==typeof options&&(deprecation(v8_0_0,"PlaneGeometry constructor changed please use { width, height, verticesX, verticesY } instead"),options={width:options,height:args[1],verticesX:args[2],verticesY:args[3]}),this.build(options)}build(options){options=__spreadValues$L(__spreadValues$L({},_PlaneGeometry.defaultOptions),options),this.verticesX=null!=(_a=this.verticesX)?_a:options.verticesX,this.verticesY=null!=(_a=this.verticesY)?_a:options.verticesY,this.width=null!=(_a=this.width)?_a:options.width,this.height=null!=(_a=this.height)?_a:options.height;var _a,total=this.verticesX*this.verticesY,verts=[],uvs=[],indices=[],verticesX=this.verticesX-1,verticesY=this.verticesY-1,sizeX=this.width/verticesX,sizeY=this.height/verticesY;for(let i=0;ikey in obj?__defProp$K(obj,key,{enumerable:!0,configurable:!0,writable:!0,value:value}):obj[key]=value,__spreadValues$K=(a,b)=>{for(var prop in b=b||{})__hasOwnProp$K.call(b,prop)&&__defNormalProp$K(a,prop,b[prop]);if(__getOwnPropSymbols$K)for(var prop of __getOwnPropSymbols$K(b))__propIsEnum$K.call(b,prop)&&__defNormalProp$K(a,prop,b[prop]);return a};const _NineSliceGeometry=class _NineSliceGeometry extends ExtensionType2_MaskEffect{constructor(options={}){super({width:(options=__spreadValues$K(__spreadValues$K({},_NineSliceGeometry.defaultOptions),options)).width,height:options.height,verticesX:4,verticesY:4}),this.update(options)}update(options){var _a;this.width=null!=(_a=options.width)?_a:this.width,this.height=null!=(_a=options.height)?_a:this.height,this._originalWidth=null!=(_a=options.originalWidth)?_a:this._originalWidth,this._originalHeight=null!=(_a=options.originalHeight)?_a:this._originalHeight,this._leftWidth=null!=(_a=options.leftWidth)?_a:this._leftWidth,this._rightWidth=null!=(_a=options.rightWidth)?_a:this._rightWidth,this._topHeight=null!=(_a=options.topHeight)?_a:this._topHeight,this._bottomHeight=null!=(_a=options.bottomHeight)?_a:this._bottomHeight,this._anchorX=null==(_a=options.anchor)?void 0:_a.x,this._anchorY=null==(_a=options.anchor)?void 0:_a.y,this.updateUvs(),this.updatePositions()}updatePositions(){var p=this.positions,{width,height,_leftWidth,_rightWidth,_topHeight,_bottomHeight,_anchorX,_anchorY}=this,w=_leftWidth+_rightWidth,h=_topHeight+_bottomHeight,w=Math.min(w"},uInputPixel:{value:new Float32Array(4),type:"vec4"},uInputClamp:{value:new Float32Array(4),type:"vec4"},uOutputFrame:{value:new Float32Array(4),type:"vec4"},uGlobalFrame:{value:new Float32Array(4),type:"vec4"},uOutputTexture:{value:new Float32Array(4),type:"vec4"}}),this._globalFilterBindGroup=new BindGroup({}),this.renderer=renderer}get activeBackTexture(){var _a;return null==(_a=this._activeFilterData)?void 0:_a.backTexture}push(instruction){var renderer=this.renderer,filters=instruction.filterEffect.filters,filterData=(this._filterStack[this._filterStackIndex]||(this._filterStack[this._filterStackIndex]=this._getFilterData()),this._filterStack[this._filterStackIndex]);if(this._filterStackIndex++,0===filters.length)filterData.skip=!0;else{var filterFrameTransform,rootResolution,bounds=filterData.bounds,colorTextureSource=(instruction.renderables?function(renderables,bounds){bounds.clear();var tempMatrix=bounds.matrix;for(let i=0;ikey in obj?__defProp$J(obj,key,{enumerable:!0,configurable:!0,writable:!0,value:value}):obj[key]=value,__spreadValues$J=(a,b)=>{for(var prop in b=b||{})__hasOwnProp$J.call(b,prop)&&__defNormalProp$J(a,prop,b[prop]);if(__getOwnPropSymbols$J)for(var prop of __getOwnPropSymbols$J(b))__propIsEnum$J.call(b,prop)&&__defNormalProp$J(a,prop,b[prop]);return a};const defaultRunners=["init","destroy","contextChange","resolutionChange","resetState","renderEnd","renderStart","render","update","postrender","prerender"],_AbstractRenderer=class _AbstractRenderer extends EventEmitter{constructor(config){super(),this.runners=Object.create(null),this.renderPipes=Object.create(null),this._initOptions={},this._systemsHash=Object.create(null),this.type=config.type,this.name=config.name,this.config=config,config=[...defaultRunners,...null!=(config=this.config.runners)?config:[]],this._addRunners(...config),this._unsafeEvalCheck()}async init(options={}){await async function(skip){if(!skip)for(let i=0;i{this.runners[runnerId]=new SystemRunner(runnerId)})}_addSystems(systems){let i;for(i in systems){var val=systems[i];this._addSystem(val.value,val.name)}}_addSystem(ClassRef,name){var system=new ClassRef(this);if(this[name])throw new Error(`Whoops! The name "${name}" is already in use`);this[name]=system,this._systemsHash[name]=system;for(const i in this.runners)this.runners[i].add(system);return this}_addPipes(pipes,pipeAdaptors){const adaptors=pipeAdaptors.reduce((acc,adaptor)=>(acc[adaptor.name]=adaptor.value,acc),{});pipes.forEach(pipe=>{var PipeClass=pipe.value,pipe=pipe.name,Adaptor=adaptors[pipe];this.renderPipes[pipe]=new PipeClass(this,Adaptor?new Adaptor:null)})}destroy(options=!1){this.runners.destroy.items.reverse(),this.runners.destroy.emit(options),Object.values(this.runners).forEach(runner=>{runner.destroy()}),this._systemsHash=null,this.renderPipes=null}generateTexture(options){return this.textureGenerator.generateTexture(options)}get roundPixels(){return!!this._roundPixels}_unsafeEvalCheck(){if(!unsafeEvalSupported())throw new Error("Current environment does not allow unsafe-eval, please use pixi.js/unsafe-eval module to enable support.")}resetState(){this.runners.resetState.emit()}};_AbstractRenderer.defaultOptions={resolution:1,failIfMajorPerformanceCaveat:!1,roundPixels:!1};let AbstractRenderer=_AbstractRenderer,_isWebGLSupported,_isWebGPUSupported;var __defProp$I=Object.defineProperty,__getOwnPropSymbols$I=Object.getOwnPropertySymbols,__hasOwnProp$I=Object.prototype.hasOwnProperty,__propIsEnum$I=Object.prototype.propertyIsEnumerable,__defNormalProp$I=(obj,key,value)=>key in obj?__defProp$I(obj,key,{enumerable:!0,configurable:!0,writable:!0,value:value}):obj[key]=value,__spreadValues$I=(a,b)=>{for(var prop in b=b||{})__hasOwnProp$I.call(b,prop)&&__defNormalProp$I(a,prop,b[prop]);if(__getOwnPropSymbols$I)for(var prop of __getOwnPropSymbols$I(b))__propIsEnum$I.call(b,prop)&&__defNormalProp$I(a,prop,b[prop]);return a};const renderPriority=["webgl","webgpu","canvas"];class ApplicationInitHook{static init(){var _a;null!=(_a=globalThis.__PIXI_APP_INIT__)&&_a.call(globalThis,this,"8.9.1")}static destroy(){}}ApplicationInitHook.extension="application";class RendererInitHook{constructor(renderer){this._renderer=renderer}init(){var _a;null!=(_a=globalThis.__PIXI_RENDERER_INIT__)&&_a.call(globalThis,this._renderer,"8.9.1")}destroy(){this._renderer=null}}RendererInitHook.extension={type:["webgl-system","webgpu-system"],name:"initHook",priority:-10};var __defProp$H=Object.defineProperty,__getOwnPropSymbols$H=Object.getOwnPropertySymbols,__hasOwnProp$H=Object.prototype.hasOwnProperty,__propIsEnum$H=Object.prototype.propertyIsEnumerable,__defNormalProp$H=(obj,key,value)=>key in obj?__defProp$H(obj,key,{enumerable:!0,configurable:!0,writable:!0,value:value}):obj[key]=value;const _Application=class _Application{constructor(...args){this.stage=new Container,void 0!==args[0]&&deprecation(v8_0_0,"Application constructor options are deprecated, please use Application.init() instead.")}async init(options){options=((a,b)=>{for(var prop in b=options||{})__hasOwnProp$H.call(b,prop)&&__defNormalProp$H(a,prop,b[prop]);if(__getOwnPropSymbols$H)for(var prop of __getOwnPropSymbols$H(b))__propIsEnum$H.call(b,prop)&&__defNormalProp$H(a,prop,b[prop]);return a})({}),this.renderer=await async function(options){var renderer,failIfMajorPerformanceCaveat;let preferredOrder=[];options.preference?(preferredOrder.push(options.preference),renderPriority.forEach(item=>{item!==options.preference&&preferredOrder.push(item)})):preferredOrder=renderPriority.slice();let RendererClass,finalOptions={};for(let i=0;i{var gpu=DOMAdapter.get().getNavigator().gpu;if(!gpu)return!1;try{return await(await gpu.requestAdapter(options)).requestDevice(),!0}catch(_e){return!1}})():_isWebGPUSupported}()){var WebGPURenderer=(await Promise.resolve().then(function(){return WebGPURenderer$1})).WebGPURenderer;RendererClass=WebGPURenderer,finalOptions=__spreadValues$I(__spreadValues$I({},options),options.webgpu);break}if("webgl"===rendererType&&(failIfMajorPerformanceCaveat=null!=(WebGPURenderer=options.failIfMajorPerformanceCaveat)?WebGPURenderer:AbstractRenderer.defaultOptions.failIfMajorPerformanceCaveat,_isWebGLSupported=void 0===_isWebGLSupported?(()=>{var _a,contextOptions={stencil:!0,failIfMajorPerformanceCaveat:null!=failIfMajorPerformanceCaveat?failIfMajorPerformanceCaveat:AbstractRenderer.defaultOptions.failIfMajorPerformanceCaveat};try{if(!DOMAdapter.get().getWebGLRenderingContext())return!1;let gl=DOMAdapter.get().createCanvas().getContext("webgl",contextOptions);var loseContext,success=!(null==(_a=null==gl?void 0:gl.getContextAttributes())||!_a.stencil);return gl&&(loseContext=gl.getExtension("WEBGL_lose_context"))&&loseContext.loseContext(),gl=null,success}catch(_e){return!1}})():_isWebGLSupported)){var WebGLRenderer=(await Promise.resolve().then(function(){return WebGLRenderer$1})).WebGLRenderer;RendererClass=WebGLRenderer,finalOptions=__spreadValues$I(__spreadValues$I({},options),options.webgl);break}if("canvas"===rendererType)throw finalOptions=__spreadValues$I({},options),new Error("CanvasRenderer is not yet implemented")}if(delete finalOptions.webgpu,delete finalOptions.webgl,RendererClass)return await(renderer=new RendererClass).init(finalOptions),renderer;throw new Error("No available renderer for the current environment")}(options),_Application._plugins.forEach(plugin=>{plugin.init.call(this,options)})}render(){this.renderer.render({container:this.stage})}get canvas(){return this.renderer.canvas}get view(){return deprecation(v8_0_0,"Application.view is deprecated, please use Application.canvas instead."),this.renderer.canvas}get screen(){return this.renderer.screen}destroy(rendererDestroyOptions=!1,options=!1){var plugins=_Application._plugins.slice(0);plugins.reverse(),plugins.forEach(plugin=>{plugin.destroy.call(this)}),this.stage.destroy(options),this.stage=null,this.renderer.destroy(rendererDestroyOptions),this.renderer=null}};_Application._plugins=[],findMixin=_Application,extensions.handleByList("application",findMixin._plugins),extensions.add(ApplicationInitHook);class BitmapFont extends AbstractBitmapFont{constructor(options,url){super();const{textures,data}=options;Object.keys(data.pages).forEach(key=>{key=data.pages[parseInt(key,10)],key=textures[key.id],this.pages.push({texture:key})}),Object.keys(data.chars).forEach(key=>{var charData=data.chars[key],{frame:textureFrame,source:textureSource}=textures[charData.page],textureFrame=new Rectangle(charData.x+textureFrame.x,charData.y+textureFrame.y,charData.width,charData.height),textureSource=new Texture({source:textureSource,frame:textureFrame});this.chars[key]={id:key.codePointAt(0),xOffset:charData.xOffset,yOffset:charData.yOffset,xAdvance:charData.xAdvance,kerning:null!=(textureFrame=charData.kerning)?textureFrame:{},texture:textureSource}}),this.baseRenderedFontSize=data.fontSize,this.baseMeasurementFontSize=data.fontSize,this.fontMetrics={ascent:0,descent:0,fontSize:data.fontSize},this.baseLineOffset=data.baseLineOffset,this.lineHeight=data.lineHeight,this.fontFamily=data.fontFamily,this.distanceField=null!=(options=data.distanceField)?options:{type:"none",range:0},this.url=url}destroy(){super.destroy();for(let i=0;i"))&&bitmapFontXMLParser.test(DOMAdapter.get().parseXML(data))},parse(data){return bitmapFontXMLParser.parse(DOMAdapter.get().parseXML(data))}},validExtensions=[".xml",".fnt"];sortMixin={extension:{type:"cache-parser",name:"cacheBitmapFont"},test:asset=>asset instanceof BitmapFont,getCacheableAssets(keys,asset){const out={};return keys.forEach(key=>{out[key]=asset,out[key+"-bitmap"]=asset}),out[asset.fontFamily+"-bitmap"]=asset,out}},getGlobalMixin={extension:{type:"load-parser",priority:measureMixin.Normal},name:"loadBitmapFont",test(url){return validExtensions.includes(path.extname(url).toLowerCase())},async testParse(data){return bitmapFontTextParser.test(data)||bitmapFontXMLStringParser.test(data)},async parse(asset,data,loader){var asset=(bitmapFontTextParser.test(asset)?bitmapFontTextParser:bitmapFontXMLStringParser).parse(asset),src=data.src,pages=asset.pages,textureUrls=[],textureOptions=asset.distanceField?{scaleMode:"linear",alphaMode:"premultiply-alpha-on-upload",autoGenerateMipmaps:!1,resolution:1}:{};for(let i=0;iloadedTextures[url.src]),new BitmapFont({data:asset,textures:data},src)},async load(url,_options){return(await DOMAdapter.get().fetch(url)).text()},async unload(bitmapFont,_resolvedAsset,loader){await Promise.all(bitmapFont.pages.map(page=>loader.unload(page.texture.source._sourceOrigin))),bitmapFont.destroy()}};class BackgroundLoader{constructor(loader,verbose=!1){this._loader=loader,this._assetList=[],this._isLoading=!1,this._maxConcurrent=1,this.verbose=verbose}add(assetUrls){assetUrls.forEach(a=>{this._assetList.push(a)}),this.verbose&&console.log("[BackgroundLoader] assets: ",this._assetList),this._isActive&&!this._isLoading&&this._next()}async _next(){if(this._assetList.length&&this._isActive){this._isLoading=!0;var toLoad=[],toLoadAmount=Math.min(this._assetList.length,this._maxConcurrent);for(let i=0;i{var image=new Image;image.onload=()=>{resolve(!0)},image.onerror=()=>{resolve(!1)},image.src=imageData});if("createImageBitmap"in globalThis&&"fetch"in globalThis){try{var blob=await(await fetch(imageData)).blob();await createImageBitmap(blob)}catch(_e){return!1}return!0}return!1}collectRenderablesMixin={extension:{type:"cache-parser",name:"cacheTextureArray"},test:asset=>Array.isArray(asset)&&asset.every(t=>t instanceof Texture),getCacheableAssets:(keys,asset)=>{const out={};return keys.forEach(key=>{asset.forEach((item,i)=>{out[key+(0===i?"":i+1)]=item})}),out}},eventemitter3$1={extension:{type:"detection-parser",priority:1},test:async()=>testImageFormat("data:image/avif;base64,AAAAIGZ0eXBhdmlmAAAAAGF2aWZtaWYxbWlhZk1BMUIAAADybWV0YQAAAAAAAAAoaGRscgAAAAAAAAAAcGljdAAAAAAAAAAAAAAAAGxpYmF2aWYAAAAADnBpdG0AAAAAAAEAAAAeaWxvYwAAAABEAAABAAEAAAABAAABGgAAAB0AAAAoaWluZgAAAAAAAQAAABppbmZlAgAAAAABAABhdjAxQ29sb3IAAAAAamlwcnAAAABLaXBjbwAAABRpc3BlAAAAAAAAAAIAAAACAAAAEHBpeGkAAAAAAwgICAAAAAxhdjFDgQ0MAAAAABNjb2xybmNseAACAAIAAYAAAAAXaXBtYQAAAAAAAAABAAEEAQKDBAAAACVtZGF0EgAKCBgANogQEAwgMg8f8D///8WfhwB8+ErK42A="),add:async formats=>[...formats,"avif"],remove:async formats=>formats.filter(f=>"avif"!==f)};const imageFormats=["png","jpg","jpeg"],inWorker=(onRenderMixin={extension:{type:"detection-parser",priority:-1},test:()=>Promise.resolve(!0),add:async formats=>[...formats,...imageFormats],remove:async formats=>formats.filter(f=>!imageFormats.includes(f))},"WorkerGlobalScope"in globalThis&&globalThis instanceof globalThis.WorkerGlobalScope);function testVideoFormat(mimeType){return!inWorker&&""!==document.createElement("video").canPlayType(mimeType)}var NOOP={extension:{type:"detection-parser",priority:0},test:async()=>testVideoFormat("video/mp4"),add:async formats=>[...formats,"mp4","m4v"],remove:async formats=>formats.filter(f=>"mp4"!==f&&"m4v"!==f)},effectsMixin={extension:{type:"detection-parser",priority:0},test:async()=>testVideoFormat("video/ogg"),add:async formats=>[...formats,"ogv"],remove:async formats=>formats.filter(f=>"ogv"!==f)},childrenHelperMixin={extension:{type:"detection-parser",priority:0},test:async()=>testVideoFormat("video/webm"),add:async formats=>[...formats,"webm"],remove:async formats=>formats.filter(f=>"webm"!==f)},toLocalGlobalMixin={extension:{type:"detection-parser",priority:0},test:async()=>testImageFormat("data:image/webp;base64,UklGRh4AAABXRUJQVlA4TBEAAAAvAAAAAAfQ//73v/+BiOh/AAA="),add:async formats=>[...formats,"webp"],remove:async formats=>formats.filter(f=>"webp"!==f)},__defProp$G=Object.defineProperty,__defProps$k=Object.defineProperties,__getOwnPropDescs$k=Object.getOwnPropertyDescriptors,__getOwnPropSymbols$G=Object.getOwnPropertySymbols,__hasOwnProp$G=Object.prototype.hasOwnProperty,__propIsEnum$G=Object.prototype.propertyIsEnumerable,__defNormalProp$G=(obj,key,value)=>key in obj?__defProp$G(obj,key,{enumerable:!0,configurable:!0,writable:!0,value:value}):obj[key]=value;class Loader{constructor(){this._parsers=[],this._parsersValidated=!1,this.parsers=new Proxy(this._parsers,{set:(target,key,value)=>(this._parsersValidated=!1,target[key]=value,!0)}),this.promiseCache={}}reset(){this._parsersValidated=!1,this.promiseCache={}}_getLoadPromiseAndParser(url,data){const result={promise:null,parser:null};return result.promise=(async()=>{var _a,_b;let asset=null,parser=null;if(data.loadParser&&!(parser=this._parserHash[data.loadParser])&&warn(`[Assets] specified load parser "${data.loadParser}" not found while loading `+url),!parser){for(let i=0;i({alias:[item],src:item,data:{}}))).length;var promises=assetsToLoadIn.map(async asset=>{var url=path.toAbsolute(asset.src);if(!assets[asset.src])try{this.promiseCache[url]||(this.promiseCache[url]=this._getLoadPromiseAndParser(url,asset)),assets[asset.src]=await this.promiseCache[url].promise,onProgress&&onProgress(++count/total)}catch(e){throw delete this.promiseCache[url],delete assets[asset.src],new Error(`[Loader.load] Failed to load ${url}. +`+e)}});return await Promise.all(promises),singleAsset?assets[assetsToLoadIn[0].src]:assets}async unload(assetsToUnloadIn){assetsToUnloadIn=convertToList(assetsToUnloadIn,item=>({alias:[item],src:item})).map(async asset=>{var loadedAsset,url=path.toAbsolute(asset.src),loadPromise=this.promiseCache[url];loadPromise&&(loadedAsset=await loadPromise.promise,delete this.promiseCache[url],await(null==(loadPromise=null==(url=loadPromise.parser)?void 0:url.unload)?void 0:loadPromise.call(url,loadedAsset,asset,this)))}),await Promise.all(assetsToUnloadIn)}_validateParsers(){this._parsersValidated=!0,this._parserHash=this._parsers.filter(parser=>parser.name).reduce((hash,parser)=>(parser.name?hash[parser.name]&&warn(`[Assets] loadParser name conflict "${parser.name}"`):warn("[Assets] loadParser should have a name"),hash=((a,b)=>{for(var prop in b=hash||{})__hasOwnProp$G.call(b,prop)&&__defNormalProp$G(a,prop,b[prop]);if(__getOwnPropSymbols$G)for(var prop of __getOwnPropSymbols$G(b))__propIsEnum$G.call(b,prop)&&__defNormalProp$G(a,prop,b[prop]);return a})({}),parser={[parser.name]:parser},__defProps$k(hash,__getOwnPropDescs$k(parser))),{})}}function checkDataUrl(url,mimes){if(Array.isArray(mimes)){for(const mime of mimes)if(url.startsWith("data:"+mime))return!0;return!1}return url.startsWith("data:"+mimes)}function checkExtension(url,extension){return url=url.split("?")[0],url=path.extname(url).toLowerCase(),Array.isArray(extension)?extension.includes(url):url===extension}var getFastGlobalBoundsMixin={extension:{type:"load-parser",priority:measureMixin.Low},name:"loadJson",test(url){return checkDataUrl(url,"application/json")||checkExtension(url,".json")},async load(url){return(await DOMAdapter.get().fetch(url)).json()}},cacheAsTextureMixin={name:"loadTxt",extension:{type:"load-parser",priority:measureMixin.Low,name:"loadTxt"},test(url){return checkDataUrl(url,"text/plain")||checkExtension(url,".txt")},async load(url){return(await DOMAdapter.get().fetch(url)).text()}},__defProp$F=Object.defineProperty,__defProps$j=Object.defineProperties,__getOwnPropDescs$j=Object.getOwnPropertyDescriptors,__getOwnPropSymbols$F=Object.getOwnPropertySymbols,__hasOwnProp$F=Object.prototype.hasOwnProperty,__propIsEnum$F=Object.prototype.propertyIsEnumerable,__defNormalProp$F=(obj,key,value)=>key in obj?__defProp$F(obj,key,{enumerable:!0,configurable:!0,writable:!0,value:value}):obj[key]=value;const validWeights=["normal","bold","100","200","300","400","500","600","700","800","900"],validFontExtensions=[".ttf",".otf",".woff",".woff2"],validFontMIMEs=["font/ttf","font/otf","font/woff","font/woff2"],CSS_IDENT_TOKEN_REGEX=/^(--|-?[A-Z_])[0-9A-Z_-]*$/i,validURICharactersRegex=/^[0-9A-Za-z%:/?#\[\]@!\$&'()\*\+,;=\-._~]*$/;function getResolutionOfUrl(url,defaultValue=1){var _a=null==(_a=Resolver.RETINA_PREFIX)?void 0:_a.exec(url);return _a?parseFloat(_a[1]):defaultValue}function createTexture(source,loader,url){source.label=url,source._sourceOrigin=url;var texture=new Texture({source:source,label:url});const unload=()=>{delete loader.promiseCache[url],Cache.has(url)&&Cache.remove(url)};return texture.source.once("destroy",()=>{loader.promiseCache[url]&&(warn("[Assets] A TextureSource managed by Assets was destroyed instead of unloaded! Use Assets.unload() instead of destroying the TextureSource."),unload())}),texture.once("destroy",()=>{source.destroyed||(warn("[Assets] A Texture managed by Assets was destroyed instead of unloaded! Use Assets.unload() instead of destroying the Texture."),unload())}),texture}var findMixin={extension:{type:"load-parser",priority:measureMixin.Low},name:"loadWebFont",test(url){return checkDataUrl(url,validFontMIMEs)||checkExtension(url,validFontExtensions)},async load(url,options){var _a,fonts=DOMAdapter.get().getFontFaceSet();if(fonts){var fontFaces=[],name=null!=(_a=null==(_a=options.data)?void 0:_a.family)?_a:function(url){var ext=path.extname(url);let valid=0<(url=path.basename(url,ext).replace(/(-|_)/g," ").toLowerCase().split(" ").map(word=>word.charAt(0).toUpperCase()+word.slice(1))).length;for(const token of url)if(!token.match(CSS_IDENT_TOKEN_REGEX)){valid=!1;break}let fontFamilyName=url.join(" ");return fontFamilyName=valid?fontFamilyName:`"${fontFamilyName.replace(/[\\"]/g,"\\$&")}"`}(url),weights=null!=(_a=null==(_a=null==(_a=options.data)?void 0:_a.weights)?void 0:_a.filter(weight=>validWeights.includes(weight)))?_a:["normal"],data=null!=(_a=options.data)?_a:{};for(let i=0;i{for(var prop in b=data||{})__hasOwnProp$F.call(b,prop)&&__defNormalProp$F(a,prop,b[prop]);if(__getOwnPropSymbols$F)for(var prop of __getOwnPropSymbols$F(b))__propIsEnum$F.call(b,prop)&&__defNormalProp$F(a,prop,b[prop]);return a})({}),__defProps$j(uri,__getOwnPropDescs$j({weight:weight}))));await uri.load(),fonts.add(uri),fontFaces.push(uri)}return Cache.set(name+"-and-url",{url:url,fontFaces:fontFaces}),1===fontFaces.length?fontFaces[0]:fontFaces}return warn("[loadWebFont] FontFace API is not supported. Skipping loading font"),null},unload(font){(Array.isArray(font)?font:[font]).forEach(t=>{Cache.remove(t.family+"-and-url"),DOMAdapter.get().getFontFaceSet().delete(t)})}},__defProp$E=Object.defineProperty,__getOwnPropSymbols$E=Object.getOwnPropertySymbols,__hasOwnProp$E=Object.prototype.hasOwnProperty,__propIsEnum$E=Object.prototype.propertyIsEnumerable,__defNormalProp$E=(obj,key,value)=>key in obj?__defProp$E(obj,key,{enumerable:!0,configurable:!0,writable:!0,value:value}):obj[key]=value,ExtensionType2_TextureSource={extension:{type:"load-parser",priority:measureMixin.Low,name:"loadSVG"},name:"loadSVG",config:{crossOrigin:"anonymous",parseAsGraphicsContext:!1},test(url){return checkDataUrl(url,"image/svg+xml")||checkExtension(url,".svg")},async load(url,asset,loader){var _a;return(null!=(_a=null==(_a=asset.data)?void 0:_a.parseAsGraphicsContext)?_a:this.config.parseAsGraphicsContext)?async function(url){var url=await(url=await DOMAdapter.get().fetch(url)).text(),context=new GraphicsContext;return context.svg(url),context}(url):async function(url,asset,loader,crossOrigin){var response=await(response=await DOMAdapter.get().fetch(url)).blob(),response=URL.createObjectURL(response),image=new Image,response=(image.src=response,image.crossOrigin=crossOrigin,await image.decode(),URL.revokeObjectURL(response),(crossOrigin=document.createElement("canvas")).getContext("2d")),_a=(null==(_a=asset.data)?void 0:_a.resolution)||getResolutionOfUrl(url),_b=null!=(_b=null==(_b=asset.data)?void 0:_b.width)?_b:image.width,_d=null!=(_d=null==(_d=asset.data)?void 0:_d.height)?_d:image.height,{}=(crossOrigin.width=_b*_a,crossOrigin.height=_d*_a,response.drawImage(image,0,0,_b*_a,_d*_a),image=null!=(response=asset.data)?response:{}),_b=((source,exclude)=>{var target={};for(prop in source)__hasOwnProp$E.call(source,prop)&&exclude.indexOf(prop)<0&&(target[prop]=source[prop]);if(null!=source&&__getOwnPropSymbols$E)for(var prop of __getOwnPropSymbols$E(source))exclude.indexOf(prop)<0&&__propIsEnum$E.call(source,prop)&&(target[prop]=source[prop]);return target})(image,["parseAsGraphicsContext"]);return createTexture(new ImageSource(((a,b)=>{for(var prop in b=_b||{})__hasOwnProp$E.call(b,prop)&&__defNormalProp$E(a,prop,b[prop]);if(__getOwnPropSymbols$E)for(var prop of __getOwnPropSymbols$E(b))__propIsEnum$E.call(b,prop)&&__defNormalProp$E(a,prop,b[prop]);return a})({resource:crossOrigin,alphaMode:"premultiply-alpha-on-upload",resolution:_a})),loader,url)}(url,asset,loader,this.config.crossOrigin)},unload(asset){asset.destroy(!0)}};let WORKER_URL$3=null,WorkerInstance$3=class{constructor(){WORKER_URL$3=WORKER_URL$3||URL.createObjectURL(new Blob(['(function () {\n \'use strict\';\n\n const WHITE_PNG = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+ip1sAAAAASUVORK5CYII=";\n async function checkImageBitmap() {\n try {\n if (typeof createImageBitmap !== "function")\n return false;\n const response = await fetch(WHITE_PNG);\n const imageBlob = await response.blob();\n const imageBitmap = await createImageBitmap(imageBlob);\n return imageBitmap.width === 1 && imageBitmap.height === 1;\n } catch (_e) {\n return false;\n }\n }\n void checkImageBitmap().then((result) => {\n self.postMessage(result);\n });\n\n})();\n'],{type:"application/javascript"})),this.worker=new Worker(WORKER_URL$3)}},WORKER_URL$2=(WorkerInstance$3.revokeObjectURL=function(){WORKER_URL$3&&(URL.revokeObjectURL(WORKER_URL$3),WORKER_URL$3=null)},null),WorkerInstance$2=class{constructor(){WORKER_URL$2=WORKER_URL$2||URL.createObjectURL(new Blob(['(function () {\n \'use strict\';\n\n async function loadImageBitmap(url, alphaMode) {\n const response = await fetch(url);\n if (!response.ok) {\n throw new Error(`[WorkerManager.loadImageBitmap] Failed to fetch ${url}: ${response.status} ${response.statusText}`);\n }\n const imageBlob = await response.blob();\n return alphaMode === "premultiplied-alpha" ? createImageBitmap(imageBlob, { premultiplyAlpha: "none" }) : createImageBitmap(imageBlob);\n }\n self.onmessage = async (event) => {\n try {\n const imageBitmap = await loadImageBitmap(event.data.data[0], event.data.data[1]);\n self.postMessage({\n data: imageBitmap,\n uuid: event.data.uuid,\n id: event.data.id\n }, [imageBitmap]);\n } catch (e) {\n self.postMessage({\n error: e,\n uuid: event.data.uuid,\n id: event.data.id\n });\n }\n };\n\n})();\n'],{type:"application/javascript"})),this.worker=new Worker(WORKER_URL$2)}},UUID=(WorkerInstance$2.revokeObjectURL=function(){WORKER_URL$2&&(URL.revokeObjectURL(WORKER_URL$2),WORKER_URL$2=null)},0),MAX_WORKERS;const WorkerManager=new class{constructor(){this._initialized=!1,this._createdWorkers=0,this._workerPool=[],this._queue=[],this._resolveHash={}}isImageBitmapSupported(){return void 0===this._isImageBitmapSupported&&(this._isImageBitmapSupported=new Promise(resolve=>{const worker=(new WorkerInstance$3).worker;worker.addEventListener("message",event=>{worker.terminate(),WorkerInstance$3.revokeObjectURL(),resolve(event.data)})})),this._isImageBitmapSupported}loadImageBitmap(src,asset){return this._run("loadImageBitmap",[src,null==(src=null==asset?void 0:asset.data)?void 0:src.alphaMode])}async _initWorkers(){this._initialized||(this._initialized=!0)}_getWorker(){void 0===MAX_WORKERS&&(MAX_WORKERS=navigator.hardwareConcurrency||4);let worker=this._workerPool.pop();return!worker&&this._createdWorkers{this._complete(event.data),this._returnWorker(event.target),this._next()})),worker}_returnWorker(worker){this._workerPool.push(worker)}_complete(data){void 0!==data.error?this._resolveHash[data.uuid].reject(data.error):this._resolveHash[data.uuid].resolve(data.data),this._resolveHash[data.uuid]=null}async _run(id,args){await this._initWorkers();var promise=new Promise((resolve,reject)=>{this._queue.push({id:id,arguments:args,resolve:resolve,reject:reject})});return this._next(),promise}_next(){var worker,toDo,id;this._queue.length&&(worker=this._getWorker())&&(id=(toDo=this._queue.pop()).id,this._resolveHash[UUID]={resolve:toDo.resolve,reject:toDo.reject},worker.postMessage({data:toDo.arguments,uuid:UUID++,id:id}))}};var __defProp$D=Object.defineProperty,__getOwnPropSymbols$D=Object.getOwnPropertySymbols,__hasOwnProp$D=Object.prototype.hasOwnProperty,__propIsEnum$D=Object.prototype.propertyIsEnumerable,__defNormalProp$D=(obj,key,value)=>key in obj?__defProp$D(obj,key,{enumerable:!0,configurable:!0,writable:!0,value:value}):obj[key]=value;const validImageExtensions=[".jpeg",".jpg",".png",".webp",".avif"],validImageMIMEs=["image/jpeg","image/png","image/webp","image/avif"];var measureMixin={name:"loadTextures",extension:{type:"load-parser",priority:measureMixin.High,name:"loadTextures"},config:{preferWorkers:!0,preferCreateImageBitmap:!0,crossOrigin:"anonymous"},test(url){return checkDataUrl(url,validImageMIMEs)||checkExtension(url,validImageExtensions)},async load(url,asset,loader){var _a;let src=null;return src=globalThis.createImageBitmap&&this.config.preferCreateImageBitmap?this.config.preferWorkers&&await WorkerManager.isImageBitmapSupported()?await WorkerManager.loadImageBitmap(url,asset):await async function(url,asset){var imageBlob,response=await DOMAdapter.get().fetch(url);if(response.ok)return imageBlob=await response.blob(),"premultiplied-alpha"===(null==(asset=null==asset?void 0:asset.data)?void 0:asset.alphaMode)?createImageBitmap(imageBlob,{premultiplyAlpha:"none"}):createImageBitmap(imageBlob);throw new Error(`[loadImageBitmap] Failed to fetch ${url}: ${response.status} `+response.statusText)}(url,asset):await new Promise((resolve,reject)=>{(src=new Image).crossOrigin=this.config.crossOrigin,src.src=url,src.complete?resolve(src):(src.onload=()=>{resolve(src)},src.onerror=reject)}),createTexture(new ImageSource(((a,b)=>{for(var prop in b=asset.data||{})__hasOwnProp$D.call(b,prop)&&__defNormalProp$D(a,prop,b[prop]);if(__getOwnPropSymbols$D)for(var prop of __getOwnPropSymbols$D(b))__propIsEnum$D.call(b,prop)&&__defNormalProp$D(a,prop,b[prop]);return a})({resource:src,alphaMode:"premultiply-alpha-on-upload",resolution:(null==(_a=asset.data)?void 0:_a.resolution)||getResolutionOfUrl(url)})),loader,url)},unload(texture){texture.destroy(!0)}},__defProp$C=Object.defineProperty,__defProps$i=Object.defineProperties,__getOwnPropDescs$i=Object.getOwnPropertyDescriptors,__getOwnPropSymbols$C=Object.getOwnPropertySymbols,__hasOwnProp$C=Object.prototype.hasOwnProperty,__propIsEnum$C=Object.prototype.propertyIsEnumerable,__defNormalProp$C=(obj,key,value)=>key in obj?__defProp$C(obj,key,{enumerable:!0,configurable:!0,writable:!0,value:value}):obj[key]=value,__spreadValues$C=(a,b)=>{for(var prop in b=b||{})__hasOwnProp$C.call(b,prop)&&__defNormalProp$C(a,prop,b[prop]);if(__getOwnPropSymbols$C)for(var prop of __getOwnPropSymbols$C(b))__propIsEnum$C.call(b,prop)&&__defNormalProp$C(a,prop,b[prop]);return a},__spreadProps$i=(a,b)=>__defProps$i(a,__getOwnPropDescs$i(b));const validVideoExtensions=[".mp4",".m4v",".webm",".ogg",".ogv",".h264",".avi",".mov"],validVideoMIMEs=validVideoExtensions.map(ext=>"video/"+ext.substring(1));var ExtensionType2_Environment,ExtensionType2_ShapeBuilder={name:"loadVideo",extension:{type:"load-parser",name:"loadVideo"},test(url){var isValidDataUrl=checkDataUrl(url,validVideoMIMEs),url=checkExtension(url,validVideoExtensions);return isValidDataUrl||url},async load(url,asset,loader){var _a;const options=__spreadValues$C(__spreadProps$i(__spreadValues$C({},VideoSource.defaultOptions),{resolution:(null==(_a=asset.data)?void 0:_a.resolution)||getResolutionOfUrl(url),alphaMode:(null==(_a=asset.data)?void 0:_a.alphaMode)||await detectVideoAlphaMode()}),asset.data),videoElement=document.createElement("video"),attributeMap={preload:!1!==options.autoLoad?"auto":void 0,"webkit-playsinline":!1!==options.playsinline?"":void 0,playsinline:!1!==options.playsinline?"":void 0,muted:!0===options.muted?"":void 0,loop:!0===options.loop?"":void 0,autoplay:!1!==options.autoPlay?"":void 0},sourceElement=(Object.keys(attributeMap).forEach(key=>{var value=attributeMap[key];void 0!==value&&videoElement.setAttribute(key,value)}),!0===options.muted&&(videoElement.muted=!0),function(element,url,crossorigin){void 0!==crossorigin||url.startsWith("data:")?!1!==crossorigin&&(element.crossOrigin="string"==typeof crossorigin?crossorigin:"anonymous"):element.crossOrigin=function(url,loc=globalThis.location){return url.startsWith("data:")||(loc=loc||globalThis.location,(url=new URL(url,document.baseURI)).hostname===loc.hostname&&url.port===loc.port&&url.protocol===loc.protocol)?"":"anonymous"}(url)}(videoElement,url,options.crossorigin),document.createElement("source"));let mime;return url.startsWith("data:")?mime=url.slice(5,url.indexOf(";")):url.startsWith("blob:")||(_a=url.split("?")[0].slice(url.lastIndexOf(".")+1).toLowerCase(),mime=VideoSource.MIME_TYPES[_a]||"video/"+_a),sourceElement.src=url,mime&&(sourceElement.type=mime),new Promise(resolve=>{const onCanPlay=async()=>{var element,base=new VideoSource(__spreadProps$i(__spreadValues$C({},options),{resource:videoElement}));videoElement.removeEventListener("canplay",onCanPlay),asset.data.preload&&(element=videoElement,await new Promise((resolve,reject)=>{function loaded(){cleanup(),resolve()}function error(err){cleanup(),reject(err)}function cleanup(){element.removeEventListener("canplaythrough",loaded),element.removeEventListener("error",error)}element.addEventListener("canplaythrough",loaded),element.addEventListener("error",error),element.load()})),resolve(createTexture(base,loader,url))};videoElement.addEventListener("canplay",onCanPlay),videoElement.appendChild(sourceElement)})},unload(texture){texture.destroy(!0)}},ExtensionType2_Application={extension:{type:"resolve-parser",priority:-2,name:"resolveJson"},test:value=>Resolver.RETINA_PREFIX.test(value)&&value.endsWith(".json"),parse:(ExtensionType2_Environment={extension:{type:"resolve-parser",name:"resolveTexture"},test:measureMixin.test,parse:value=>{var _a;return{resolution:parseFloat(null!=(_a=null==(_a=Resolver.RETINA_PREFIX.exec(value))?void 0:_a[1])?_a:"1"),format:value.split(".").pop(),src:value}}}).parse},Assets=new class{constructor(){this._detections=[],this._initialized=!1,this.resolver=new Resolver,this.loader=new Loader,this.cache=Cache,this._backgroundLoader=new BackgroundLoader(this.loader),this._backgroundLoader.active=!0,this.reset()}async init(options={}){if(this._initialized)warn("[Assets]AssetManager already initialized, did you load before calling this Assets.init()?");else{if(this._initialized=!0,options.defaultSearchParams&&this.resolver.setDefaultSearchParams(options.defaultSearchParams),options.basePath&&(this.resolver.basePath=options.basePath),options.bundleIdentifier&&this.resolver.setBundleIdentifier(options.bundleIdentifier),options.manifest){let manifest=options.manifest;"string"==typeof manifest&&(manifest=await this.load(manifest)),this.resolver.addManifest(manifest)}var _a="number"==typeof(_a=null!=(_a=null==(_a=options.texturePreference)?void 0:_a.resolution)?_a:1)?[_a]:_a,_c=await this._detectFormats({preferredFormats:null==(_c=options.texturePreference)?void 0:_c.format,skipDetections:options.skipDetections,detections:this._detections});this.resolver.prefer({params:{format:_c,resolution:_a}}),options.preferences&&this.setPreferences(options.preferences)}}add(assets){this.resolver.add(assets)}async load(urls,onProgress){this._initialized||await this.init();var singleAsset=isSingleItem(urls),urls=convertToList(urls).map(url=>{var aliases;return"string"!=typeof url?((aliases=this.resolver.getAlias(url)).some(alias=>!this.resolver.hasKey(alias))&&this.add(url),Array.isArray(aliases)?aliases[0]:aliases):(this.resolver.hasKey(url)||this.add({alias:url,src:url}),url)}),resolveResults=this.resolver.resolve(urls),resolveResults=await this._mapLoadToResolve(resolveResults,onProgress);return singleAsset?resolveResults[urls[0]]:resolveResults}addBundle(bundleId,assets){this.resolver.addBundle(bundleId,assets)}async loadBundle(bundleIds,onProgress){this._initialized||await this.init();let singleAsset=!1;"string"==typeof bundleIds&&(singleAsset=!0,bundleIds=[bundleIds]);const resolveResults=this.resolver.resolveBundle(bundleIds),out={};var keys=Object.keys(resolveResults);let count=0,total=0;const _onProgress=()=>{null!=onProgress&&onProgress(++count/total)};return keys=keys.map(bundleId=>{var resolveResult=resolveResults[bundleId];return total+=Object.keys(resolveResult).length,this._mapLoadToResolve(resolveResult,_onProgress).then(resolveResult2=>{out[bundleId]=resolveResult2})}),await Promise.all(keys),singleAsset?out[bundleIds[0]]:out}async backgroundLoad(urls){this._initialized||await this.init(),urls=this.resolver.resolve(urls="string"==typeof urls?[urls]:urls),this._backgroundLoader.add(Object.values(urls))}async backgroundLoadBundle(bundleIds){this._initialized||await this.init(),bundleIds=this.resolver.resolveBundle(bundleIds="string"==typeof bundleIds?[bundleIds]:bundleIds),Object.values(bundleIds).forEach(resolveResult=>{this._backgroundLoader.add(Object.values(resolveResult))})}reset(){this.resolver.reset(),this.loader.reset(),this.cache.reset(),this._initialized=!1}get(keys){if("string"==typeof keys)return Cache.get(keys);var assets={};for(let i=0;i{const asset=loadedAssets[resolveResult.src];var keys=[resolveResult.src];resolveResult.alias&&keys.push(...resolveResult.alias),keys.forEach(key=>{out[key]=asset}),Cache.set(keys,asset)}),out}async unload(urls){this._initialized||await this.init(),urls=convertToList(urls).map(url=>"string"!=typeof url?url.src:url),urls=this.resolver.resolve(urls),await this._unloadFromResolved(urls)}async unloadBundle(bundleIds){this._initialized||await this.init(),bundleIds=convertToList(bundleIds);const resolveResults=this.resolver.resolveBundle(bundleIds);bundleIds=Object.keys(resolveResults).map(bundleId=>this._unloadFromResolved(resolveResults[bundleId])),await Promise.all(bundleIds)}async _unloadFromResolved(resolveResult){(resolveResult=Object.values(resolveResult)).forEach(resolveResult2=>{Cache.remove(resolveResult2.src)}),await this.loader.unload(resolveResult)}async _detectFormats(options){let formats=[];options.preferredFormats&&(formats=Array.isArray(options.preferredFormats)?options.preferredFormats:[options.preferredFormats]);for(const detection of options.detections)options.skipDetections||await detection.test()?formats=await detection.add(formats):options.skipDetections||(formats=await detection.remove(formats));return formats=formats.filter((format,index)=>formats.indexOf(format)===index)}get detections(){return this._detections}setPreferences(preferences){this.loader.parsers.forEach(parser=>{parser.config&&Object.keys(parser.config).filter(key=>key in preferences).forEach(key=>{parser.config[key]=preferences[key]})})}};extensions.handleByList("load-parser",Assets.loader.parsers).handleByList("resolve-parser",Assets.resolver.parsers).handleByList("cache-parser",Assets.cache.parsers).handleByList("detection-parser",Assets.detections),extensions.add(collectRenderablesMixin,onRenderMixin,eventemitter3$1,toLocalGlobalMixin,NOOP,effectsMixin,childrenHelperMixin,getFastGlobalBoundsMixin,cacheAsTextureMixin,findMixin,ExtensionType2_TextureSource,measureMixin,ExtensionType2_ShapeBuilder,getGlobalMixin,sortMixin,ExtensionType2_Environment,ExtensionType2_Application);const assetKeyMap={loader:"load-parser",resolver:"resolve-parser",cache:"cache-parser",detection:"detection-parser"};function fourCCToInt32(value){return value.charCodeAt(0)+(value.charCodeAt(1)<<8)+(value.charCodeAt(2)<<16)+(value.charCodeAt(3)<<24)}extensions.handle("asset",extension=>{const ref=extension.ref;Object.entries(assetKeyMap).filter(([key])=>!!ref[key]).forEach(([key,type])=>extensions.add(Object.assign(ref[key],{extension:null!=(key=ref[key].extension)?key:type})))},extension=>{const ref=extension.ref;Object.keys(assetKeyMap).filter(key=>!!ref[key]).forEach(key=>extensions.remove(ref[key]))}),class extends TextureSource{},(toLocalGlobalMixin={UNKNOWN:0,0:"UNKNOWN",R8G8B8:20,20:"R8G8B8",A8R8G8B8:21,21:"A8R8G8B8",X8R8G8B8:22,22:"X8R8G8B8",R5G6B5:23,23:"R5G6B5",X1R5G5B5:24,24:"X1R5G5B5",A1R5G5B5:25,25:"A1R5G5B5",A4R4G4B4:26,26:"A4R4G4B4",R3G3B2:27,27:"R3G3B2",A8:28,28:"A8",A8R3G3B2:29,29:"A8R3G3B2",X4R4G4B4:30,30:"X4R4G4B4",A2B10G10R10:31,31:"A2B10G10R10",A8B8G8R8:32,32:"A8B8G8R8",X8B8G8R8:33,33:"X8B8G8R8",G16R16:34,34:"G16R16",A2R10G10B10:35,35:"A2R10G10B10",A16B16G16R16:36,36:"A16B16G16R16",A8P8:40,40:"A8P8",P8:41,41:"P8",L8:50,50:"L8",A8L8:51,51:"A8L8",A4L4:52,52:"A4L4",V8U8:60,60:"V8U8",L6V5U5:61,61:"L6V5U5",X8L8V8U8:62,62:"X8L8V8U8",Q8W8V8U8:63,63:"Q8W8V8U8",V16U16:64,64:"V16U16",A2W10V10U10:67,67:"A2W10V10U10",Q16W16V16U16:110,110:"Q16W16V16U16",R16F:111,111:"R16F",G16R16F:112,112:"G16R16F",A16B16G16R16F:113,113:"A16B16G16R16F",R32F:114,114:"R32F",G32R32F:115,115:"G32R32F",A32B32G32R32F:116,116:"A32B32G32R32F"})[toLocalGlobalMixin.UYVY=fourCCToInt32("UYVY")]="UYVY",toLocalGlobalMixin[toLocalGlobalMixin.R8G8_B8G8=fourCCToInt32("RGBG")]="R8G8_B8G8",toLocalGlobalMixin[toLocalGlobalMixin.YUY2=fourCCToInt32("YUY2")]="YUY2",toLocalGlobalMixin[toLocalGlobalMixin.D3DFMT_G8R8_G8B8=fourCCToInt32("GRGB")]="D3DFMT_G8R8_G8B8",toLocalGlobalMixin[toLocalGlobalMixin.DXT1=fourCCToInt32("DXT1")]="DXT1",toLocalGlobalMixin[toLocalGlobalMixin.DXT2=fourCCToInt32("DXT2")]="DXT2",toLocalGlobalMixin[toLocalGlobalMixin.DXT3=fourCCToInt32("DXT3")]="DXT3",toLocalGlobalMixin[toLocalGlobalMixin.DXT4=fourCCToInt32("DXT4")]="DXT4",toLocalGlobalMixin[toLocalGlobalMixin.DXT5=fourCCToInt32("DXT5")]="DXT5",toLocalGlobalMixin[toLocalGlobalMixin.ATI1=fourCCToInt32("ATI1")]="ATI1",toLocalGlobalMixin[toLocalGlobalMixin.AT1N=fourCCToInt32("AT1N")]="AT1N",toLocalGlobalMixin[toLocalGlobalMixin.ATI2=fourCCToInt32("ATI2")]="ATI2",toLocalGlobalMixin[toLocalGlobalMixin.AT2N=fourCCToInt32("AT2N")]="AT2N",toLocalGlobalMixin[toLocalGlobalMixin.BC4U=fourCCToInt32("BC4U")]="BC4U",toLocalGlobalMixin[toLocalGlobalMixin.BC4S=fourCCToInt32("BC4S")]="BC4S",toLocalGlobalMixin[toLocalGlobalMixin.BC5U=fourCCToInt32("BC5U")]="BC5U",toLocalGlobalMixin[toLocalGlobalMixin.BC5S=fourCCToInt32("BC5S")]="BC5S",toLocalGlobalMixin[toLocalGlobalMixin.DX10=fourCCToInt32("DX10")]="DX10",toLocalGlobalMixin.DXT1,toLocalGlobalMixin.DXT2,toLocalGlobalMixin.DXT3,toLocalGlobalMixin.DXT4,toLocalGlobalMixin.DXT5,toLocalGlobalMixin.ATI1,toLocalGlobalMixin.BC4U,toLocalGlobalMixin.BC4S,toLocalGlobalMixin.ATI2,toLocalGlobalMixin.BC5U,toLocalGlobalMixin.BC5S,NOOP={RGBA8_SNORM:36759,36759:"RGBA8_SNORM",RGBA:6408,6408:"RGBA",RGBA8UI:36220,36220:"RGBA8UI",SRGB8_ALPHA8:35907,35907:"SRGB8_ALPHA8",RGBA8I:36238,36238:"RGBA8I",RGBA8:32856,32856:"RGBA8",COMPRESSED_RGB_S3TC_DXT1_EXT:33776,33776:"COMPRESSED_RGB_S3TC_DXT1_EXT",COMPRESSED_RGBA_S3TC_DXT1_EXT:33777,33777:"COMPRESSED_RGBA_S3TC_DXT1_EXT",COMPRESSED_RGBA_S3TC_DXT3_EXT:33778,33778:"COMPRESSED_RGBA_S3TC_DXT3_EXT",COMPRESSED_RGBA_S3TC_DXT5_EXT:33779,33779:"COMPRESSED_RGBA_S3TC_DXT5_EXT",COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT:35917,35917:"COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT",COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT:35918,35918:"COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT",COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT:35919,35919:"COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT",COMPRESSED_SRGB_S3TC_DXT1_EXT:35916,35916:"COMPRESSED_SRGB_S3TC_DXT1_EXT",COMPRESSED_RED_RGTC1_EXT:36283,36283:"COMPRESSED_RED_RGTC1_EXT",COMPRESSED_SIGNED_RED_RGTC1_EXT:36284,36284:"COMPRESSED_SIGNED_RED_RGTC1_EXT",COMPRESSED_RED_GREEN_RGTC2_EXT:36285,36285:"COMPRESSED_RED_GREEN_RGTC2_EXT",COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT:36286,36286:"COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT",COMPRESSED_R11_EAC:37488,37488:"COMPRESSED_R11_EAC",COMPRESSED_SIGNED_R11_EAC:37489,37489:"COMPRESSED_SIGNED_R11_EAC",COMPRESSED_RG11_EAC:37490,37490:"COMPRESSED_RG11_EAC",COMPRESSED_SIGNED_RG11_EAC:37491,37491:"COMPRESSED_SIGNED_RG11_EAC",COMPRESSED_RGB8_ETC2:37492,37492:"COMPRESSED_RGB8_ETC2",COMPRESSED_RGBA8_ETC2_EAC:37496,37496:"COMPRESSED_RGBA8_ETC2_EAC",COMPRESSED_SRGB8_ETC2:37493,37493:"COMPRESSED_SRGB8_ETC2",COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:37497,37497:"COMPRESSED_SRGB8_ALPHA8_ETC2_EAC",COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2:37494,37494:"COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2",COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2:37495,37495:"COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2",COMPRESSED_RGBA_ASTC_4x4_KHR:37808,37808:"COMPRESSED_RGBA_ASTC_4x4_KHR",COMPRESSED_RGBA_ASTC_5x4_KHR:37809,37809:"COMPRESSED_RGBA_ASTC_5x4_KHR",COMPRESSED_RGBA_ASTC_5x5_KHR:37810,37810:"COMPRESSED_RGBA_ASTC_5x5_KHR",COMPRESSED_RGBA_ASTC_6x5_KHR:37811,37811:"COMPRESSED_RGBA_ASTC_6x5_KHR",COMPRESSED_RGBA_ASTC_6x6_KHR:37812,37812:"COMPRESSED_RGBA_ASTC_6x6_KHR",COMPRESSED_RGBA_ASTC_8x5_KHR:37813,37813:"COMPRESSED_RGBA_ASTC_8x5_KHR",COMPRESSED_RGBA_ASTC_8x6_KHR:37814,37814:"COMPRESSED_RGBA_ASTC_8x6_KHR",COMPRESSED_RGBA_ASTC_8x8_KHR:37815,37815:"COMPRESSED_RGBA_ASTC_8x8_KHR",COMPRESSED_RGBA_ASTC_10x5_KHR:37816,37816:"COMPRESSED_RGBA_ASTC_10x5_KHR",COMPRESSED_RGBA_ASTC_10x6_KHR:37817,37817:"COMPRESSED_RGBA_ASTC_10x6_KHR",COMPRESSED_RGBA_ASTC_10x8_KHR:37818,37818:"COMPRESSED_RGBA_ASTC_10x8_KHR",COMPRESSED_RGBA_ASTC_10x10_KHR:37819,37819:"COMPRESSED_RGBA_ASTC_10x10_KHR",COMPRESSED_RGBA_ASTC_12x10_KHR:37820,37820:"COMPRESSED_RGBA_ASTC_12x10_KHR",COMPRESSED_RGBA_ASTC_12x12_KHR:37821,37821:"COMPRESSED_RGBA_ASTC_12x12_KHR",COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:37840,37840:"COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR",COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:37841,37841:"COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR",COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:37842,37842:"COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR",COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:37843,37843:"COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR",COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:37844,37844:"COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR",COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:37845,37845:"COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR",COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:37846,37846:"COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR",COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:37847,37847:"COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR",COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:37848,37848:"COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR",COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:37849,37849:"COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR",COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:37850,37850:"COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR",COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:37851,37851:"COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR",COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:37852,37852:"COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR",COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:37853,37853:"COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR",COMPRESSED_RGBA_BPTC_UNORM_EXT:36492,36492:"COMPRESSED_RGBA_BPTC_UNORM_EXT",COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT:36493,36493:"COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT",COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT:36494,36494:"COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT",COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT:36495,36495:"COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT"};const tempBounds$2=new Bounds,_Culler=class{cull(container,view,skipUpdateTransform=!0){this._cullRecursive(container,view,skipUpdateTransform)}_cullRecursive(container,view,skipUpdateTransform=!0){var _a;if(container.cullable&&container.measurable&&container.includeInBuild?(_a=null!=(_a=container.cullArea)?_a:getGlobalBounds(container,skipUpdateTransform,tempBounds$2),container.culled=_a.x>=view.x+view.width||_a.y>=view.y+view.height||_a.x+_a.width<=view.x||_a.y+_a.height<=view.y):container.culled=!1,container.cullableChildren&&!container.culled&&container.renderable&&container.measurable&&container.includeInBuild)for(let i=0;ikey in obj?__defProp$B(obj,key,{enumerable:!0,configurable:!0,writable:!0,value:value}):obj[key]=value,__spreadValues$B=(a,b)=>{for(var prop in b=b||{})__hasOwnProp$B.call(b,prop)&&__defNormalProp$B(a,prop,b[prop]);if(__getOwnPropSymbols$B)for(var prop of __getOwnPropSymbols$B(b))__propIsEnum$B.call(b,prop)&&__defNormalProp$B(a,prop,b[prop]);return a};const _Filter=class _Filter extends Shader{constructor(options){super(options=__spreadValues$B(__spreadValues$B({},_Filter.defaultOptions),options)),this.enabled=!0,this._state=State.for2d(),this.blendMode=options.blendMode,this.padding=options.padding,"boolean"==typeof options.antialias?this.antialias=options.antialias?"on":"off":this.antialias=options.antialias,this.resolution=options.resolution,this.blendRequired=options.blendRequired,this.clipToViewport=options.clipToViewport,this.addResource("uTexture",0,1)}apply(filterManager,input,output,clearMode){filterManager.applyFilter(this,input,output,clearMode)}get blendMode(){return this._state.blendMode}set blendMode(value){this._state.blendMode=value}static from(options){var{gpu,gl}=options,options=((source,exclude)=>{var target={};for(prop in source)__hasOwnProp$B.call(source,prop)&&exclude.indexOf(prop)<0&&(target[prop]=source[prop]);if(null!=source&&__getOwnPropSymbols$B)for(var prop of __getOwnPropSymbols$B(source))exclude.indexOf(prop)<0&&__propIsEnum$B.call(source,prop)&&(target[prop]=source[prop]);return target})(options,["gpu","gl"]);let gpuProgram,glProgram;return gpu&&(gpuProgram=GpuProgram.from(gpu)),gl&&(glProgram=GlProgram.from(gl)),new _Filter(__spreadValues$B({gpuProgram:gpuProgram,glProgram:glProgram},options))}};_Filter.defaultOptions={blendMode:"normal",resolution:1,padding:0,antialias:"off",blendRequired:!1,clipToViewport:!0},effectsMixin=_Filter,Object.defineProperty,Object.getOwnPropertySymbols,Object.prototype.hasOwnProperty,Object.prototype.propertyIsEnumerable,class extends effectsMixin{};var vertex$2="in vec2 aPosition;\nout vec2 vTextureCoord;\n\nuniform vec4 uInputSize;\nuniform vec4 uOutputFrame;\nuniform vec4 uOutputTexture;\n\nvec4 filterVertexPosition( void )\n{\n vec2 position = aPosition * uOutputFrame.zw + uOutputFrame.xy;\n \n position.x = position.x * (2.0 / uOutputTexture.x) - 1.0;\n position.y = position.y * (2.0*uOutputTexture.z / uOutputTexture.y) - uOutputTexture.z;\n\n return vec4(position, 0.0, 1.0);\n}\n\nvec2 filterTextureCoord( void )\n{\n return aPosition * (uOutputFrame.zw * uInputSize.zw);\n}\n\nvoid main(void)\n{\n gl_Position = filterVertexPosition();\n vTextureCoord = filterTextureCoord();\n}\n",source$5="struct GlobalFilterUniforms {\n uInputSize:vec4,\n uInputPixel:vec4,\n uInputClamp:vec4,\n uOutputFrame:vec4,\n uGlobalFrame:vec4,\n uOutputTexture:vec4,\n};\n\nstruct AlphaUniforms {\n uAlpha:f32,\n};\n\n@group(0) @binding(0) var gfu: GlobalFilterUniforms;\n@group(0) @binding(1) var uTexture: texture_2d;\n@group(0) @binding(2) var uSampler : sampler;\n\n@group(1) @binding(0) var alphaUniforms : AlphaUniforms;\n\nstruct VSOutput {\n @builtin(position) position: vec4,\n @location(0) uv : vec2\n };\n\nfn filterVertexPosition(aPosition:vec2) -> vec4\n{\n var position = aPosition * gfu.uOutputFrame.zw + gfu.uOutputFrame.xy;\n\n position.x = position.x * (2.0 / gfu.uOutputTexture.x) - 1.0;\n position.y = position.y * (2.0*gfu.uOutputTexture.z / gfu.uOutputTexture.y) - gfu.uOutputTexture.z;\n\n return vec4(position, 0.0, 1.0);\n}\n\nfn filterTextureCoord( aPosition:vec2 ) -> vec2\n{\n return aPosition * (gfu.uOutputFrame.zw * gfu.uInputSize.zw);\n}\n\nfn globalTextureCoord( aPosition:vec2 ) -> vec2\n{\n return (aPosition.xy / gfu.uGlobalFrame.zw) + (gfu.uGlobalFrame.xy / gfu.uGlobalFrame.zw); \n}\n\nfn getSize() -> vec2\n{\n return gfu.uGlobalFrame.zw;\n}\n \n@vertex\nfn mainVertex(\n @location(0) aPosition : vec2, \n) -> VSOutput {\n return VSOutput(\n filterVertexPosition(aPosition),\n filterTextureCoord(aPosition)\n );\n}\n\n@fragment\nfn mainFragment(\n @location(0) uv: vec2,\n @builtin(position) position: vec4\n) -> @location(0) vec4 {\n \n var sample = textureSample(uTexture, uSampler, uv);\n \n return sample * alphaUniforms.uAlpha;\n}",__defProp$z=Object.defineProperty,__defProps$h=Object.defineProperties,__getOwnPropDescs$h=Object.getOwnPropertyDescriptors,__getOwnPropSymbols$z=Object.getOwnPropertySymbols,__hasOwnProp$z=Object.prototype.hasOwnProperty,__propIsEnum$z=Object.prototype.propertyIsEnumerable,__defNormalProp$z=(obj,key,value)=>key in obj?__defProp$z(obj,key,{enumerable:!0,configurable:!0,writable:!0,value:value}):obj[key]=value,__spreadValues$z=(a,b)=>{for(var prop in b=b||{})__hasOwnProp$z.call(b,prop)&&__defNormalProp$z(a,prop,b[prop]);if(__getOwnPropSymbols$z)for(var prop of __getOwnPropSymbols$z(b))__propIsEnum$z.call(b,prop)&&__defNormalProp$z(a,prop,b[prop]);return a};const _AlphaFilter=class _AlphaFilter extends effectsMixin{constructor(options){options=__spreadValues$z(__spreadValues$z({},_AlphaFilter.defaultOptions),options);var gpuProgram=GpuProgram.from({vertex:{source:source$5,entryPoint:"mainVertex"},fragment:{source:source$5,entryPoint:"mainFragment"}}),glProgram=GlProgram.from({vertex:vertex$2,fragment:"\nin vec2 vTextureCoord;\n\nout vec4 finalColor;\n\nuniform float uAlpha;\nuniform sampler2D uTexture;\n\nvoid main()\n{\n finalColor = texture(uTexture, vTextureCoord) * uAlpha;\n}\n",name:"alpha-filter"}),alpha=options.alpha,options=((source2,exclude)=>{var target={};for(prop in source2)__hasOwnProp$z.call(source2,prop)&&exclude.indexOf(prop)<0&&(target[prop]=source2[prop]);if(null!=source2&&__getOwnPropSymbols$z)for(var prop of __getOwnPropSymbols$z(source2))exclude.indexOf(prop)<0&&__propIsEnum$z.call(source2,prop)&&(target[prop]=source2[prop]);return target})(options,["alpha"]),alpha=new UniformGroup({uAlpha:{value:alpha,type:"f32"}});super((options=__spreadValues$z({},options),__defProps$h(options,__getOwnPropDescs$h({gpuProgram:gpuProgram,glProgram:glProgram,resources:{alphaUniforms:alpha}}))))}get alpha(){return this.resources.alphaUniforms.uniforms.uAlpha}set alpha(value){this.resources.alphaUniforms.uniforms.uAlpha=value}},GAUSSIAN_VALUES=(_AlphaFilter.defaultOptions={alpha:1},_AlphaFilter,{5:[.153388,.221461,.250301],7:[.071303,.131514,.189879,.214607],9:[.028532,.067234,.124009,.179044,.20236],11:[.0093,.028002,.065984,.121703,.175713,.198596],13:[.002406,.009255,.027867,.065666,.121117,.174868,.197641],15:[489e-6,.002403,.009246,.02784,.065602,.120999,.174697,.197448]}),fragTemplate=["in vec2 vBlurTexCoords[%size%];","uniform sampler2D uTexture;","out vec4 finalColor;","void main(void)","{"," finalColor = vec4(0.0);"," %blur%","}"].join("\n");var __defProp$y=Object.defineProperty,__getOwnPropSymbols$y=Object.getOwnPropertySymbols,__hasOwnProp$y=Object.prototype.hasOwnProperty,__propIsEnum$y=Object.prototype.propertyIsEnumerable,__defNormalProp$y=(obj,key,value)=>key in obj?__defProp$y(obj,key,{enumerable:!0,configurable:!0,writable:!0,value:value}):obj[key]=value,__spreadValues$y=(a,b)=>{for(var prop in b=b||{})__hasOwnProp$y.call(b,prop)&&__defNormalProp$y(a,prop,b[prop]);if(__getOwnPropSymbols$y)for(var prop of __getOwnPropSymbols$y(b))__propIsEnum$y.call(b,prop)&&__defNormalProp$y(a,prop,b[prop]);return a};const _BlurFilterPass=class _BlurFilterPass extends effectsMixin{constructor(options){var horizontal=(options=__spreadValues$y(__spreadValues$y({},_BlurFilterPass.defaultOptions),options)).horizontal,vertex=function(kernelSize,x){var halfLength=Math.ceil(kernelSize/2);let vertSource=` + in vec2 aPosition; + + uniform float uStrength; + + out vec2 vBlurTexCoords[%size%]; + + uniform vec4 uInputSize; + uniform vec4 uOutputFrame; + uniform vec4 uOutputTexture; + + vec4 filterVertexPosition( void ) +{ + vec2 position = aPosition * uOutputFrame.zw + uOutputFrame.xy; + + position.x = position.x * (2.0 / uOutputTexture.x) - 1.0; + position.y = position.y * (2.0*uOutputTexture.z / uOutputTexture.y) - uOutputTexture.z; + + return vec4(position, 0.0, 1.0); +} + + vec2 filterTextureCoord( void ) + { + return aPosition * (uOutputFrame.zw * uInputSize.zw); + } + + void main(void) + { + gl_Position = filterVertexPosition(); + + float pixelStrength = uInputSize.%dimension% * uStrength; + + vec2 textureCoord = filterTextureCoord(); + %blur% + }`,blurLoop="",template;template=x?"vBlurTexCoords[%index%] = textureCoord + vec2(%sampleIndex% * pixelStrength, 0.0);":"vBlurTexCoords[%index%] = textureCoord + vec2(0.0, %sampleIndex% * pixelStrength);";for(let i=0;i=halfLength&&(value=kernelSize-i-1),blur=blur.replace("%value%",kernel[value].toString()),blurLoop=blurLoop+blur+"\n"}return fragSource=(fragSource=fragSource.replace("%blur%",blurLoop)).replace("%size%",kernelSize.toString())}(kernelSize),vertex=GlProgram.from({vertex:vertex,fragment:kernelSize,name:`blur-${horizontal?"horizontal":"vertical"}-pass-filter`}),kernelSize=function(horizontal,kernelSize){var kernel=GAUSSIAN_VALUES[kernelSize],halfLength=kernel.length,blurStructSource=[],blurOutSource=[],blurSamplingSource=[];for(let i=0;i,`,blurOutSource[i]=horizontal?`filteredCord + vec2(${i-halfLength+1} * pixelStrength, 0.0),`:`filteredCord + vec2(0.0, ${i-halfLength+1} * pixelStrength),`;var kernelValue=kernel[i,\n uInputPixel:vec4,\n uInputClamp:vec4,\n uOutputFrame:vec4,\n uGlobalFrame:vec4,\n uOutputTexture:vec4,\n};\n\nstruct BlurUniforms {\n uStrength:f32,\n};\n\n@group(0) @binding(0) var gfu: GlobalFilterUniforms;\n@group(0) @binding(1) var uTexture: texture_2d;\n@group(0) @binding(2) var uSampler : sampler;\n\n@group(1) @binding(0) var blurUniforms : BlurUniforms;\n\n\nstruct VSOutput {\n @builtin(position) position: vec4,\n %blur-struct%\n };\n\nfn filterVertexPosition(aPosition:vec2) -> vec4\n{\n var position = aPosition * gfu.uOutputFrame.zw + gfu.uOutputFrame.xy;\n\n position.x = position.x * (2.0 / gfu.uOutputTexture.x) - 1.0;\n position.y = position.y * (2.0*gfu.uOutputTexture.z / gfu.uOutputTexture.y) - gfu.uOutputTexture.z;\n\n return vec4(position, 0.0, 1.0);\n}\n\nfn filterTextureCoord( aPosition:vec2 ) -> vec2\n{\n return aPosition * (gfu.uOutputFrame.zw * gfu.uInputSize.zw);\n}\n\nfn globalTextureCoord( aPosition:vec2 ) -> vec2\n{\n return (aPosition.xy / gfu.uGlobalFrame.zw) + (gfu.uGlobalFrame.xy / gfu.uGlobalFrame.zw); \n}\n\nfn getSize() -> vec2\n{\n return gfu.uGlobalFrame.zw;\n}\n\n\n@vertex\nfn mainVertex(\n @location(0) aPosition : vec2, \n) -> VSOutput {\n\n let filteredCord = filterTextureCoord(aPosition);\n\n let pixelStrength = gfu.uInputSize.%dimension% * blurUniforms.uStrength;\n\n return VSOutput(\n filterVertexPosition(aPosition),\n %blur-vertex-out%\n );\n}\n\n@fragment\nfn mainFragment(\n @builtin(position) position: vec4,\n %blur-fragment-in%\n) -> @location(0) vec4 {\n\n var finalColor = vec4(0.0);\n\n %blur-sampling%\n\n return finalColor;\n}".replace("%blur-struct%",blurStruct).replace("%blur-vertex-out%",blurOut).replace("%blur-fragment-in%",blurStruct).replace("%blur-sampling%",blurSampling).replace("%dimension%",horizontal?"z":"w");return GpuProgram.from({vertex:{source:blurOut,entryPoint:"mainVertex"},fragment:{source:blurOut,entryPoint:"mainFragment"}})}(options.horizontal,options.kernelSize);super(__spreadValues$y({glProgram:vertex,gpuProgram:kernelSize,resources:{blurUniforms:{uStrength:{value:0,type:"f32"}}}},options)),this.horizontal=options.horizontal,this._quality=0,this.quality=options.quality,this.blur=options.strength,this._uniforms=this.resources.blurUniforms.uniforms}apply(filterManager,input,output,clearMode){if(this._uniforms.uStrength=this.strength/this.passes,1===this.passes)filterManager.applyFilter(this,input,output,clearMode);else{var tempTexture=TexturePool.getSameSizeTexture(input);let flip=input,flop=tempTexture;this._state.blend=!1;var shouldClear=2===filterManager.renderer.type;for(let i=0;ikey in obj?__defProp$u(obj,key,{enumerable:!0,configurable:!0,writable:!0,value:value}):obj[key]=value,__spreadValues$u=(a,b)=>{for(var prop in b=b||{})__hasOwnProp$u.call(b,prop)&&__defNormalProp$u(a,prop,b[prop]);if(__getOwnPropSymbols$u)for(var prop of __getOwnPropSymbols$u(b))__propIsEnum$u.call(b,prop)&&__defNormalProp$u(a,prop,b[prop]);return a};const _NoiseFilter=class _NoiseFilter extends effectsMixin{constructor(options={}){options=__spreadValues$u(__spreadValues$u({},_NoiseFilter.defaultOptions),options);var gpuProgram=GpuProgram.from({vertex:{source:source$1,entryPoint:"mainVertex"},fragment:{source:source$1,entryPoint:"mainFragment"}}),glProgram=GlProgram.from({vertex:vertex$2,fragment:"\nin vec2 vTextureCoord;\nin vec4 vColor;\n\nout vec4 finalColor;\n\nuniform float uNoise;\nuniform float uSeed;\nuniform sampler2D uTexture;\n\nfloat rand(vec2 co)\n{\n return fract(sin(dot(co.xy, vec2(12.9898, 78.233))) * 43758.5453);\n}\n\nvoid main()\n{\n vec4 color = texture(uTexture, vTextureCoord);\n float randomValue = rand(gl_FragCoord.xy * uSeed);\n float diff = (randomValue - 0.5) * uNoise;\n\n // Un-premultiply alpha before applying the color matrix. See issue #3539.\n if (color.a > 0.0) {\n color.rgb /= color.a;\n }\n\n color.r += diff;\n color.g += diff;\n color.b += diff;\n\n // Premultiply alpha again.\n color.rgb *= color.a;\n\n finalColor = color;\n}\n",name:"noise-filter"}),{noise,seed}=options,options=((source2,exclude)=>{var target={};for(prop in source2)__hasOwnProp$u.call(source2,prop)&&exclude.indexOf(prop)<0&&(target[prop]=source2[prop]);if(null!=source2&&__getOwnPropSymbols$u)for(var prop of __getOwnPropSymbols$u(source2))exclude.indexOf(prop)<0&&__propIsEnum$u.call(source2,prop)&&(target[prop]=source2[prop]);return target})(options,["noise","seed"]);super((options=__spreadValues$u({},options),gpuProgram={gpuProgram:gpuProgram,glProgram:glProgram,resources:{noiseUniforms:new UniformGroup({uNoise:{value:1,type:"f32"},uSeed:{value:1,type:"f32"}})}},__defProps$d(options,__getOwnPropDescs$d(gpuProgram)))),this.noise=noise,this.seed=null!=seed?seed:Math.random()}get noise(){return this.resources.noiseUniforms.uniforms.uNoise}set noise(value){this.resources.noiseUniforms.uniforms.uNoise=value}get seed(){return this.resources.noiseUniforms.uniforms.uSeed}set seed(value){this.resources.noiseUniforms.uniforms.uSeed=value}};_NoiseFilter.defaultOptions={noise:.5},_NoiseFilter;var source="struct GlobalFilterUniforms {\n uInputSize:vec4,\n uInputPixel:vec4,\n uInputClamp:vec4,\n uOutputFrame:vec4,\n uGlobalFrame:vec4,\n uOutputTexture:vec4,\n};\n\nstruct MaskUniforms {\n uFilterMatrix:mat3x3,\n uMaskClamp:vec4,\n uAlpha:f32,\n uInverse:f32,\n};\n\n@group(0) @binding(0) var gfu: GlobalFilterUniforms;\n@group(0) @binding(1) var uTexture: texture_2d;\n@group(0) @binding(2) var uSampler : sampler;\n\n@group(1) @binding(0) var filterUniforms : MaskUniforms;\n@group(1) @binding(1) var uMaskTexture: texture_2d;\n\nstruct VSOutput {\n @builtin(position) position: vec4,\n @location(0) uv : vec2,\n @location(1) filterUv : vec2,\n};\n\nfn filterVertexPosition(aPosition:vec2) -> vec4\n{\n var position = aPosition * gfu.uOutputFrame.zw + gfu.uOutputFrame.xy;\n\n position.x = position.x * (2.0 / gfu.uOutputTexture.x) - 1.0;\n position.y = position.y * (2.0*gfu.uOutputTexture.z / gfu.uOutputTexture.y) - gfu.uOutputTexture.z;\n\n return vec4(position, 0.0, 1.0);\n}\n\nfn filterTextureCoord( aPosition:vec2 ) -> vec2\n{\n return aPosition * (gfu.uOutputFrame.zw * gfu.uInputSize.zw);\n}\n\nfn globalTextureCoord( aPosition:vec2 ) -> vec2\n{\n return (aPosition.xy / gfu.uGlobalFrame.zw) + (gfu.uGlobalFrame.xy / gfu.uGlobalFrame.zw);\n}\n\nfn getFilterCoord(aPosition:vec2 ) -> vec2\n{\n return ( filterUniforms.uFilterMatrix * vec3( filterTextureCoord(aPosition), 1.0) ).xy;\n}\n\nfn getSize() -> vec2\n{\n return gfu.uGlobalFrame.zw;\n}\n\n@vertex\nfn mainVertex(\n @location(0) aPosition : vec2,\n) -> VSOutput {\n return VSOutput(\n filterVertexPosition(aPosition),\n filterTextureCoord(aPosition),\n getFilterCoord(aPosition)\n );\n}\n\n@fragment\nfn mainFragment(\n @location(0) uv: vec2,\n @location(1) filterUv: vec2,\n @builtin(position) position: vec4\n) -> @location(0) vec4 {\n\n var maskClamp = filterUniforms.uMaskClamp;\n var uAlpha = filterUniforms.uAlpha;\n\n var clip = step(3.5,\n step(maskClamp.x, filterUv.x) +\n step(maskClamp.y, filterUv.y) +\n step(filterUv.x, maskClamp.z) +\n step(filterUv.y, maskClamp.w));\n\n var mask = textureSample(uMaskTexture, uSampler, filterUv);\n var source = textureSample(uTexture, uSampler, uv);\n var alphaMul = 1.0 - uAlpha * (1.0 - mask.a);\n\n var a: f32 = alphaMul * mask.r * uAlpha * clip;\n\n if (filterUniforms.uInverse == 1.0) {\n a = 1.0 - a;\n }\n\n return source * a;\n}\n",__defProp$t=Object.defineProperty,__defProps$c=Object.defineProperties,__getOwnPropDescs$c=Object.getOwnPropertyDescriptors,__getOwnPropSymbols$t=Object.getOwnPropertySymbols,__hasOwnProp$t=Object.prototype.hasOwnProperty,__propIsEnum$t=Object.prototype.propertyIsEnumerable,__defNormalProp$t=(obj,key,value)=>key in obj?__defProp$t(obj,key,{enumerable:!0,configurable:!0,writable:!0,value:value}):obj[key]=value;class MaskFilter extends effectsMixin{constructor(options){var sprite=options.sprite,rest=((source2,exclude)=>{var target={};for(prop in source2)__hasOwnProp$t.call(source2,prop)&&exclude.indexOf(prop)<0&&(target[prop]=source2[prop]);if(null!=source2&&__getOwnPropSymbols$t)for(var prop of __getOwnPropSymbols$t(source2))exclude.indexOf(prop)<0&&__propIsEnum$t.call(source2,prop)&&(target[prop]=source2[prop]);return target})(options,["sprite"]),textureMatrix=new TextureMatrix(sprite.texture),options=new UniformGroup({uFilterMatrix:{value:new Matrix,type:"mat3x3"},uMaskClamp:{value:textureMatrix.uClampFrame,type:"vec4"},uAlpha:{value:1,type:"f32"},uInverse:{value:options.inverse?1:0,type:"f32"}}),gpuProgram=GpuProgram.from({vertex:{source:source,entryPoint:"mainVertex"},fragment:{source:source,entryPoint:"mainFragment"}}),glProgram=GlProgram.from({vertex:"in vec2 aPosition;\n\nout vec2 vTextureCoord;\nout vec2 vMaskCoord;\n\n\nuniform vec4 uInputSize;\nuniform vec4 uOutputFrame;\nuniform vec4 uOutputTexture;\nuniform mat3 uFilterMatrix;\n\nvec4 filterVertexPosition( vec2 aPosition )\n{\n vec2 position = aPosition * uOutputFrame.zw + uOutputFrame.xy;\n \n position.x = position.x * (2.0 / uOutputTexture.x) - 1.0;\n position.y = position.y * (2.0*uOutputTexture.z / uOutputTexture.y) - uOutputTexture.z;\n\n return vec4(position, 0.0, 1.0);\n}\n\nvec2 filterTextureCoord( vec2 aPosition )\n{\n return aPosition * (uOutputFrame.zw * uInputSize.zw);\n}\n\nvec2 getFilterCoord( vec2 aPosition )\n{\n return ( uFilterMatrix * vec3( filterTextureCoord(aPosition), 1.0) ).xy;\n} \n\nvoid main(void)\n{\n gl_Position = filterVertexPosition(aPosition);\n vTextureCoord = filterTextureCoord(aPosition);\n vMaskCoord = getFilterCoord(aPosition);\n}\n",fragment:"in vec2 vMaskCoord;\nin vec2 vTextureCoord;\n\nuniform sampler2D uTexture;\nuniform sampler2D uMaskTexture;\n\nuniform float uAlpha;\nuniform vec4 uMaskClamp;\nuniform float uInverse;\n\nout vec4 finalColor;\n\nvoid main(void)\n{\n float clip = step(3.5,\n step(uMaskClamp.x, vMaskCoord.x) +\n step(uMaskClamp.y, vMaskCoord.y) +\n step(vMaskCoord.x, uMaskClamp.z) +\n step(vMaskCoord.y, uMaskClamp.w));\n\n // TODO look into why this is needed\n float npmAlpha = uAlpha;\n vec4 original = texture(uTexture, vTextureCoord);\n vec4 masky = texture(uMaskTexture, vMaskCoord);\n float alphaMul = 1.0 - npmAlpha * (1.0 - masky.a);\n\n float a = alphaMul * masky.r * npmAlpha * clip;\n\n if (uInverse == 1.0) {\n a = 1.0 - a;\n }\n\n finalColor = original * a;\n}\n",name:"mask-filter"});super((rest=((a,b)=>{for(var prop in b=rest||{})__hasOwnProp$t.call(b,prop)&&__defNormalProp$t(a,prop,b[prop]);if(__getOwnPropSymbols$t)for(var prop of __getOwnPropSymbols$t(b))__propIsEnum$t.call(b,prop)&&__defNormalProp$t(a,prop,b[prop]);return a})({}),gpuProgram={gpuProgram:gpuProgram,glProgram:glProgram,resources:{filterUniforms:options,uMaskTexture:sprite.texture.source}},__defProps$c(rest,__getOwnPropDescs$c(gpuProgram)))),this.sprite=sprite,this._textureMatrix=textureMatrix}set inverse(value){this.resources.filterUniforms.uniforms.uInverse=value?1:0}get inverse(){return 1===this.resources.filterUniforms.uniforms.uInverse}apply(filterManager,input,output,clearMode){this._textureMatrix.texture=this.sprite.texture,filterManager.calculateSpriteMatrix(this.resources.filterUniforms.uniforms.uFilterMatrix,this.sprite).prepend(this._textureMatrix.mapCoord),this.resources.uMaskTexture=this.sprite.texture.source,filterManager.applyFilter(this,input,output,clearMode)}}function pointInTriangle(px,py,x1,y1,x2,y2,x3,y3){return x3-=x1,x2-=x1,px-=x1,x1=py-y1,py=x3*x3+(y3-=y1)*y3,y1=x3*x2+y3*(y2-=y1),x3=x3*px+y3*x1,y3=x2*x2+y2*y2,x1=(py*(x2=x2*px+y2*x1)-y1*x3)*(px=1/(py*y3-y1*y1)),0<=(y2=(y3*x3-y1*x2)*px)&&0<=x1&&y2+x1<1}const _PrepareBase=class _PrepareBase{constructor(renderer){this._tick=()=>{this.timeout=setTimeout(this._processQueue,0)},this._processQueue=()=>{var queue=this.queue;let itemsProcessed=0;for(;queue.length&&itemsProcessed<_PrepareBase.uploadsPerFrame;){var queueItem=queue.shift();this.uploadQueueItem(queueItem),itemsProcessed++}queue.length?Ticker.system.addOnce(this._tick,this,-50):this._resolve()},this.renderer=renderer,this.queue=[],this.resolves=[]}getQueue(){return[...this.queue]}add(resource){for(const resourceItem of Array.isArray(resource)?resource:[resource])resourceItem instanceof Container?this._addContainer(resourceItem):this.resolveQueueItem(resourceItem,this.queue);return this}_addContainer(container){this.resolveQueueItem(container,this.queue);for(const child of container.children)this._addContainer(child)}upload(resource){return resource&&this.add(resource),new Promise(resolve=>{this.queue.length?(this.resolves.push(resolve),this.dedupeQueue(),Ticker.system.addOnce(this._tick,this,-50)):resolve()})}dedupeQueue(){var hash=Object.create(null);let nextUnique=0;for(let i=0;ikey in obj?__defProp$s(obj,key,{enumerable:!0,configurable:!0,writable:!0,value:value}):obj[key]=value;class Mesh extends ViewContainer{constructor(...args){let options=args[0];options instanceof Geometry&&(deprecation(v8_0_0,"Mesh: use new Mesh({ geometry, shader }) instead"),options={geometry:options,shader:args[1]},args[3])&&(deprecation(v8_0_0,"Mesh: drawMode argument has been removed, use geometry.topology instead"),options.geometry.topology=args[3]);var{geometry:args,shader,texture,roundPixels,state}=options;super(((a,b)=>{for(var prop in b=b||{})__hasOwnProp$s.call(b,prop)&&__defNormalProp$s(a,prop,b[prop]);if(__getOwnPropSymbols$s)for(var prop of __getOwnPropSymbols$s(b))__propIsEnum$s.call(b,prop)&&__defNormalProp$s(a,prop,b[prop]);return a})({label:"Mesh"},((source,exclude)=>{var target={};for(prop in source)__hasOwnProp$s.call(source,prop)&&exclude.indexOf(prop)<0&&(target[prop]=source[prop]);if(null!=source&&__getOwnPropSymbols$s)for(var prop of __getOwnPropSymbols$s(source))exclude.indexOf(prop)<0&&__propIsEnum$s.call(source,prop)&&(target[prop]=source[prop]);return target})(options,["geometry","shader","texture","roundPixels","state"]))),this.renderPipeId="mesh",this._shader=null,this.allowChildren=!1,this.shader=null!=shader?shader:null,this.texture=null!=(texture=null!=texture?texture:null==shader?void 0:shader.texture)?texture:Texture.WHITE,this.state=null!=state?state:State.for2d(),this._geometry=args,this._geometry.on("update",this.onViewUpdate,this),this.roundPixels=null!=roundPixels&&roundPixels}get material(){return deprecation(v8_0_0,"mesh.material property has been removed, use mesh.shader instead"),this._shader}set shader(value){this._shader!==value&&(this._shader=value,this.onViewUpdate())}get shader(){return this._shader}set geometry(value){var _a;this._geometry!==value&&(null!=(_a=this._geometry)&&_a.off("update",this.onViewUpdate,this),value.on("update",this.onViewUpdate,this),this._geometry=value,this.onViewUpdate())}get geometry(){return this._geometry}set texture(value){value=value||Texture.EMPTY;var currentTexture=this._texture;currentTexture!==value&&(currentTexture&¤tTexture.dynamic&¤tTexture.off("update",this.onViewUpdate,this),value.dynamic&&value.on("update",this.onViewUpdate,this),this.shader&&(this.shader.texture=value),this._texture=value,this.onViewUpdate())}get texture(){return this._texture}get batched(){return!this._shader&&0==(12&this.state.data)&&this._geometry instanceof MeshGeometry&&("auto"===this._geometry.batchMode?this._geometry.positions.length/2<=100:"batch"===this._geometry.batchMode)}get bounds(){return this._geometry.bounds}updateBounds(){this._bounds=this._geometry.bounds}containsPoint(point){var{x,y}=point;if(this.bounds.containsPoint(x,y)){var vertices=this.geometry.getBuffer("aPosition").data,step="triangle-strip"===this.geometry.topology?3:1;if(this.geometry.getIndex()){var indices=this.geometry.getIndex().data,len=indices.length;for(let i=0;i+2key in obj?__defProp$r(obj,key,{enumerable:!0,configurable:!0,writable:!0,value:value}):obj[key]=value;class AnimatedSprite extends Sprite{constructor(...args){var options=args[0],{animationSpeed:args=1,autoPlay=!1,autoUpdate=!0,loop=!0,onComplete=null,onFrameChange=null,onLoop=null,textures,updateAnchor=!1}=options=Array.isArray(args[0])?{textures:args[0],autoUpdate:args[1]}:options,rest=((source,exclude)=>{var target={};for(prop in source)__hasOwnProp$r.call(source,prop)&&exclude.indexOf(prop)<0&&(target[prop]=source[prop]);if(null!=source&&__getOwnPropSymbols$r)for(var prop of __getOwnPropSymbols$r(source))exclude.indexOf(prop)<0&&__propIsEnum$r.call(source,prop)&&(target[prop]=source[prop]);return target})(options,["animationSpeed","autoPlay","autoUpdate","loop","onComplete","onFrameChange","onLoop","textures","updateAnchor"]),[options]=textures;super((rest=((a,b)=>{for(var prop in b=rest||{})__hasOwnProp$r.call(b,prop)&&__defNormalProp$r(a,prop,b[prop]);if(__getOwnPropSymbols$r)for(var prop of __getOwnPropSymbols$r(b))__propIsEnum$r.call(b,prop)&&__defNormalProp$r(a,prop,b[prop]);return a})({}),options={texture:options instanceof Texture?options:options.texture},__defProps$b(rest,__getOwnPropDescs$b(options)))),this._textures=null,this._durations=null,this._autoUpdate=autoUpdate,this._isConnectedToTicker=!1,this.animationSpeed=args,this.loop=loop,this.updateAnchor=updateAnchor,this.onComplete=onComplete,this.onFrameChange=onFrameChange,this.onLoop=onLoop,this._currentTime=0,this._playing=!1,this._previousFrame=null,this.textures=textures,autoPlay&&this.play()}stop(){this._playing&&(this._playing=!1,this._autoUpdate)&&this._isConnectedToTicker&&(Ticker.shared.remove(this.update,this),this._isConnectedToTicker=!1)}play(){this._playing||(this._playing=!0,this._autoUpdate&&!this._isConnectedToTicker&&(Ticker.shared.add(this.update,this,25),this._isConnectedToTicker=!0))}gotoAndStop(frameNumber){this.stop(),this.currentFrame=frameNumber}gotoAndPlay(frameNumber){this.currentFrame=frameNumber,this.play()}update(ticker){if(this._playing){var ticker=ticker.deltaTime,elapsed=this.animationSpeed*ticker,previousFrame=this.currentFrame;if(null!==this._durations){let lag=this._currentTime%1*this._durations[this.currentFrame];for(lag+=elapsed/60*1e3;lag<0;)this._currentTime--,lag+=this._durations[this.currentFrame];var sign=Math.sign(this.animationSpeed*ticker);for(this._currentTime=Math.floor(this._currentTime);lag>=this._durations[this.currentFrame];)lag-=this._durations[this.currentFrame]*sign,this._currentTime+=sign;this._currentTime+=lag/this._durations[this.currentFrame]}else this._currentTime+=elapsed;this._currentTime<0&&!this.loop?(this.gotoAndStop(0),this.onComplete&&this.onComplete()):this._currentTime>=this._textures.length&&!this.loop?(this.gotoAndStop(this._textures.length-1),this.onComplete&&this.onComplete()):previousFrame!==this.currentFrame&&(this.loop&&this.onLoop&&(0previousFrame)&&this.onLoop(),this._updateTexture())}}_updateTexture(){var currentFrame=this.currentFrame;this._previousFrame!==currentFrame&&(this._previousFrame=currentFrame,this.texture=this._textures[currentFrame],this.updateAnchor&&this.texture.defaultAnchor&&this.anchor.copyFrom(this.texture.defaultAnchor),this.onFrameChange)&&this.onFrameChange(this.currentFrame)}destroy(){this.stop(),super.destroy(),this.onComplete=null,this.onFrameChange=null,this.onLoop=null}static fromFrames(frames){var textures=[];for(let i=0;ithis.totalFrames-1)throw new Error(`[AnimatedSprite]: Invalid frame index value ${value}, expected to be between 0 and totalFrames ${this.totalFrames}.`);var previousFrame=this.currentFrame;this._currentTime=value,previousFrame!==this.currentFrame&&this._updateTexture()}get playing(){return this._playing}get autoUpdate(){return this._autoUpdate}set autoUpdate(value){value!==this._autoUpdate&&(this._autoUpdate=value,!this._autoUpdate&&this._isConnectedToTicker?(Ticker.shared.remove(this.update,this),this._isConnectedToTicker=!1):this._autoUpdate&&!this._isConnectedToTicker&&this._playing&&(Ticker.shared.add(this.update,this),this._isConnectedToTicker=!0))}}class Transform{constructor({matrix,observer}={}){this.dirty=!0,this._matrix=null!=matrix?matrix:new Matrix,this.observer=observer,this.position=new ObservablePoint(this,0,0),this.scale=new ObservablePoint(this,1,1),this.pivot=new ObservablePoint(this,0,0),this.skew=new ObservablePoint(this,0,0),this._rotation=0,this._cx=1,this._sx=0,this._cy=0,this._sy=1}get matrix(){var lt=this._matrix;return this.dirty&&(lt.a=this._cx*this.scale.x,lt.b=this._sx*this.scale.x,lt.c=this._cy*this.scale.y,lt.d=this._sy*this.scale.y,lt.tx=this.position.x-(this.pivot.x*lt.a+this.pivot.y*lt.c),lt.ty=this.position.y-(this.pivot.x*lt.b+this.pivot.y*lt.d),this.dirty=!1),lt}_onUpdate(point){this.dirty=!0,point===this.skew&&this.updateSkew(),null!=(point=this.observer)&&point._onUpdate(this)}updateSkew(){this._cx=Math.cos(this._rotation+this.skew.y),this._sx=Math.sin(this._rotation+this.skew.y),this._cy=-Math.sin(this._rotation-this.skew.x),this._sy=Math.cos(this._rotation-this.skew.x),this.dirty=!0}toString(){return`[pixi.js/math:Transform position=(${this.position.x}, ${this.position.y}) rotation=${this.rotation} scale=(${this.scale.x}, ${this.scale.y}) skew=(${this.skew.x}, ${this.skew.y}) ]`}setFromMatrix(matrix){matrix.decompose(this),this.dirty=!0}get rotation(){return this._rotation}set rotation(value){this._rotation!==value&&(this._rotation=value,this._onUpdate(this.skew))}}var __defProp$q=Object.defineProperty,__getOwnPropSymbols$q=Object.getOwnPropertySymbols,__hasOwnProp$q=Object.prototype.hasOwnProperty,__propIsEnum$q=Object.prototype.propertyIsEnumerable,__defNormalProp$q=(obj,key,value)=>key in obj?__defProp$q(obj,key,{enumerable:!0,configurable:!0,writable:!0,value:value}):obj[key]=value,__spreadValues$q=(a,b)=>{for(var prop in b=b||{})__hasOwnProp$q.call(b,prop)&&__defNormalProp$q(a,prop,b[prop]);if(__getOwnPropSymbols$q)for(var prop of __getOwnPropSymbols$q(b))__propIsEnum$q.call(b,prop)&&__defNormalProp$q(a,prop,b[prop]);return a};const _TilingSprite=class _TilingSprite extends ViewContainer{constructor(...args){let options=args[0]||{};options instanceof Texture&&(options={texture:options}),1{var target={};for(prop in source)__hasOwnProp$q.call(source,prop)&&exclude.indexOf(prop)<0&&(target[prop]=source[prop]);if(null!=source&&__getOwnPropSymbols$q)for(var prop of __getOwnPropSymbols$q(source))exclude.indexOf(prop)<0&&__propIsEnum$q.call(source,prop)&&(target[prop]=source[prop]);return target})(args,["texture","anchor","tilePosition","tileScale","tileRotation","width","height","applyAnchorToTexture","roundPixels"]);super(__spreadValues$q({label:"TilingSprite"},args)),this.renderPipeId="tilingSprite",this.batched=!0,this.allowChildren=!1,this._anchor=new ObservablePoint({_onUpdate:()=>{this.onViewUpdate()}}),this.applyAnchorToTexture=applyAnchorToTexture,this.texture=texture,this._width=null!=width?width:texture.width,this._height=null!=height?height:texture.height,this._tileTransform=new Transform({observer:{_onUpdate:()=>this.onViewUpdate()}}),anchor&&(this.anchor=anchor),this.tilePosition=tilePosition,this.tileScale=tileScale,this.tileRotation=tileRotation,this.roundPixels=null!=roundPixels&&roundPixels}static from(source,options={}){return"string"==typeof source?new _TilingSprite(__spreadValues$q({texture:Cache.get(source)},options)):new _TilingSprite(__spreadValues$q({texture:source},options))}get uvRespectAnchor(){return warn("uvRespectAnchor is deprecated, please use applyAnchorToTexture instead"),this.applyAnchorToTexture}set uvRespectAnchor(value){warn("uvRespectAnchor is deprecated, please use applyAnchorToTexture instead"),this.applyAnchorToTexture=value}get clampMargin(){return this._texture.textureMatrix.clampMargin}set clampMargin(value){this._texture.textureMatrix.clampMargin=value}get anchor(){return this._anchor}set anchor(value){"number"==typeof value?this._anchor.set(value):this._anchor.copyFrom(value)}get tilePosition(){return this._tileTransform.position}set tilePosition(value){this._tileTransform.position.copyFrom(value)}get tileScale(){return this._tileTransform.scale}set tileScale(value){"number"==typeof value?this._tileTransform.scale.set(value):this._tileTransform.scale.copyFrom(value)}set tileRotation(value){this._tileTransform.rotation=value}get tileRotation(){return this._tileTransform.rotation}get tileTransform(){return this._tileTransform}set texture(value){value=value||Texture.EMPTY;var currentTexture=this._texture;currentTexture!==value&&(currentTexture&¤tTexture.dynamic&¤tTexture.off("update",this.onViewUpdate,this),value.dynamic&&value.on("update",this.onViewUpdate,this),this._texture=value,this.onViewUpdate())}get texture(){return this._texture}set width(value){this._width=value,this.onViewUpdate()}get width(){return this._width}set height(value){this._height=value,this.onViewUpdate()}get height(){return this._height}setSize(value,height){var _a;"object"==typeof value&&(height=null!=(_a=value.height)?_a:value.width,value=value.width),this._width=value,this._height=null!=height?height:value,this.onViewUpdate()}getSize(out){return(out=out||{}).width=this._width,out.height=this._height,out}updateBounds(){var bounds=this._bounds,anchor=this._anchor,width=this._width,height=this._height;bounds.minX=-anchor._x*width,bounds.maxX=bounds.minX+width,bounds.minY=-anchor._y*height,bounds.maxY=bounds.minY+height}containsPoint(point){var width=this._width,height=this._height,x1=-width*this._anchor._x;return point.x>=x1&&point.x<=x1+width&&(x1=-height*this._anchor._y,point.y>=x1)&&point.y<=x1+height}destroy(options=!1){super.destroy(options),this._anchor=null,this._tileTransform=null,this._bounds=null,("boolean"==typeof options?options:null!=options&&options.texture)&&(options="boolean"==typeof options?options:null==options?void 0:options.textureSource,this._texture.destroy(options)),this._texture=null}};_TilingSprite.defaultOptions={texture:Texture.EMPTY,anchor:{x:0,y:0},tilePosition:{x:0,y:0},tileScale:{x:1,y:1},tileRotation:0,applyAnchorToTexture:!1},_TilingSprite,Object.defineProperty,Object.getOwnPropertySymbols,Object.prototype.hasOwnProperty,Object.prototype.propertyIsEnumerable,class extends ViewContainer{},class extends childrenHelperMixin{};class GlBatchAdaptor{constructor(){this._tempState=State.for2d(),this._didUploadHash={}}init(batcherPipe){batcherPipe.renderer.runners.contextChange.add(this)}contextChange(){this._didUploadHash={}}start(batchPipe,geometry,shader){var batchPipe=batchPipe.renderer,didUpload=this._didUploadHash[shader.uid];batchPipe.shader.bind(shader,didUpload),didUpload||(this._didUploadHash[shader.uid]=!0),batchPipe.shader.updateUniformGroup(batchPipe.globalUniforms.uniformGroup),batchPipe.geometry.bind(geometry,shader.glProgram)}execute(batchPipe,batch){var renderer=batchPipe.renderer,textures=(this._tempState.blendMode=batch.blendMode,renderer.state.set(this._tempState),batch.textures.textures);for(let i=0;i, + } + + @group(2) @binding(2) var textureUniforms : TextureUniforms; + `,main:` + uv = (textureUniforms.uTextureMatrix * vec3(uv, 1.0)).xy; + `},fragment:{header:` + @group(2) @binding(0) var uTexture: texture_2d; + @group(2) @binding(1) var uSampler: sampler; + + + `,main:` + outColor = textureSample(uTexture, uSampler, vUV); + `}}),textureBitGl={name:"texture-bit",vertex:{header:` + uniform mat3 uTextureMatrix; + `,main:` + uv = (uTextureMatrix * vec3(uv, 1.0)).xy; + `},fragment:{header:` + uniform sampler2D uTexture; + + + `,main:` + outColor = texture(uTexture, vUV); + `}},tempBounds$1=new Bounds;class AlphaMaskEffect extends FilterEffect{constructor(){super(),this.filters=[new MaskFilter({sprite:new Sprite(Texture.EMPTY),inverse:!1,resolution:"inherit",antialias:"inherit"})]}get sprite(){return this.filters[0].sprite}set sprite(value){this.filters[0].sprite=value}get inverse(){return this.filters[0].inverse}set inverse(value){this.filters[0].inverse=value}}class AlphaMaskPipe{constructor(renderer){this._activeMaskStage=[],this._renderer=renderer}push(mask,maskedContainer,instructionSet){var maskContainer,renderer=this._renderer;renderer.renderPipes.batch.break(instructionSet),instructionSet.add({renderPipeId:"alphaMask",action:"pushMaskBegin",mask:mask,inverse:maskedContainer._maskOptions.inverse,canBundle:!1,maskedContainer:maskedContainer}),mask.inverse=maskedContainer._maskOptions.inverse,mask.renderMaskToTexture&&((maskContainer=mask.mask).includeInBuild=!0,maskContainer.collectRenderables(instructionSet,renderer,null),maskContainer.includeInBuild=!1),renderer.renderPipes.batch.break(instructionSet),instructionSet.add({renderPipeId:"alphaMask",action:"pushMaskEnd",mask:mask,maskedContainer:maskedContainer,inverse:maskedContainer._maskOptions.inverse,canBundle:!1})}pop(mask,_maskedContainer,instructionSet){this._renderer.renderPipes.batch.break(instructionSet),instructionSet.add({renderPipeId:"alphaMask",action:"popMaskEnd",mask:mask,inverse:_maskedContainer._maskOptions.inverse,canBundle:!1})}execute(instruction){var colorTextureSource,filterEffect,sprite,bounds,renderer=this._renderer,renderMask=instruction.mask.renderMaskToTexture;"pushMaskBegin"===instruction.action?((filterEffect=BigPool.get(AlphaMaskEffect)).inverse=instruction.inverse,renderMask?(instruction.mask.mask.measurable=!0,bounds=getGlobalBounds(instruction.mask.mask,!0,tempBounds$1),instruction.mask.mask.measurable=!1,bounds.ceil(),colorTextureSource=renderer.renderTarget.renderTarget.colorTexture.source,colorTextureSource=TexturePool.getOptimalTexture(bounds.width,bounds.height,colorTextureSource._resolution,colorTextureSource.antialias),renderer.renderTarget.push(colorTextureSource,!0),renderer.globalUniforms.push({offset:bounds,worldColor:4294967295}),(sprite=filterEffect.sprite).texture=colorTextureSource,sprite.worldTransform.tx=bounds.minX,sprite.worldTransform.ty=bounds.minY,this._activeMaskStage.push({filterEffect:filterEffect,maskedContainer:instruction.maskedContainer,filterTexture:colorTextureSource})):(filterEffect.sprite=instruction.mask.mask,this._activeMaskStage.push({filterEffect:filterEffect,maskedContainer:instruction.maskedContainer}))):"pushMaskEnd"===instruction.action?(sprite=this._activeMaskStage[this._activeMaskStage.length-1],renderMask&&(1===renderer.type&&renderer.renderTarget.finishRenderPass(),renderer.renderTarget.pop(),renderer.globalUniforms.pop()),renderer.filter.push({renderPipeId:"filter",action:"pushFilter",container:sprite.maskedContainer,filterEffect:sprite.filterEffect,canBundle:!1})):"popMaskEnd"===instruction.action&&(renderer.filter.pop(),bounds=this._activeMaskStage.pop(),renderMask&&TexturePool.returnTexture(bounds.filterTexture),BigPool.return(bounds.filterEffect))}destroy(){this._renderer=null,this._activeMaskStage=null}}AlphaMaskPipe.extension={type:["webgl-pipes","webgpu-pipes","canvas-pipes"],name:"alphaMask"};class ColorMaskPipe{constructor(renderer){this._colorStack=[],this._colorStackIndex=0,this._currentColor=0,this._renderer=renderer}buildStart(){this._colorStack[0]=15,this._colorStackIndex=1,this._currentColor=15}push(mask,_container,instructionSet){this._renderer.renderPipes.batch.break(instructionSet);var colorStack=this._colorStack;colorStack[this._colorStackIndex]=colorStack[this._colorStackIndex-1]&mask.mask,(colorStack=this._colorStack[this._colorStackIndex])!==this._currentColor&&(this._currentColor=colorStack,instructionSet.add({renderPipeId:"colorMask",colorMask:colorStack,canBundle:!1})),this._colorStackIndex++}pop(_mask,_container,instructionSet){this._renderer.renderPipes.batch.break(instructionSet);var colorStack=this._colorStack;this._colorStackIndex--,(colorStack=colorStack[this._colorStackIndex-1])!==this._currentColor&&(this._currentColor=colorStack,instructionSet.add({renderPipeId:"colorMask",colorMask:colorStack,canBundle:!1}))}execute(instruction){this._renderer.colorMask.setMask(instruction.colorMask)}destroy(){this._colorStack=null}}ColorMaskPipe.extension={type:["webgl-pipes","webgpu-pipes","canvas-pipes"],name:"colorMask"};class StencilMaskPipe{constructor(renderer){this._maskStackHash={},this._maskHash=new WeakMap,this._renderer=renderer}push(mask,_container,instructionSet){var effect=mask,renderer=this._renderer,maskContainer=(renderer.renderPipes.batch.break(instructionSet),renderer.renderPipes.blendMode.setBlendMode(effect.mask,"none",instructionSet),instructionSet.add({renderPipeId:"stencilMask",action:"pushMaskBegin",mask:mask,inverse:_container._maskOptions.inverse,canBundle:!1}),(maskContainer=effect.mask).includeInBuild=!0,this._maskHash.has(effect)||this._maskHash.set(effect,{instructionsStart:0,instructionsLength:0}),(effect=this._maskHash.get(effect)).instructionsStart=instructionSet.instructionSize,maskContainer.collectRenderables(instructionSet,renderer,null),maskContainer.includeInBuild=!1,renderer.renderPipes.batch.break(instructionSet),instructionSet.add({renderPipeId:"stencilMask",action:"pushMaskEnd",mask:mask,inverse:_container._maskOptions.inverse,canBundle:!1}),instructionSet.instructionSize-effect.instructionsStart-1),mask=(effect.instructionsLength=maskContainer,renderer.renderTarget.renderTarget.uid);null==(_container=this._maskStackHash)[mask]&&(_container[mask]=0)}pop(mask,_container,instructionSet){var effect=mask,renderer=this._renderer,maskData=(renderer.renderPipes.batch.break(instructionSet),renderer.renderPipes.blendMode.setBlendMode(effect.mask,"none",instructionSet),instructionSet.add({renderPipeId:"stencilMask",action:"popMaskBegin",inverse:_container._maskOptions.inverse,canBundle:!1}),this._maskHash.get(mask));for(let i=0;i=this._minBaseLocation)glBuffer._lastBindCallId=this._bindCallId;else{let loop=0,nextIndex=this._nextBindBaseIndex;for(;loop<2;){nextIndex>=this._maxBindings&&(nextIndex=this._minBaseLocation,loop++);var curBuf=this._boundBufferBases[nextIndex];if(!curBuf||curBuf._lastBindCallId!==this._bindCallId)break;nextIndex++}if(freeIndex=nextIndex,this._nextBindBaseIndex=nextIndex+1,2<=loop)return-1;glBuffer._lastBindCallId=this._bindCallId,this._boundBufferBases[freeIndex]=null}return freeIndex}getLastBindBaseLocation(glBuffer){var index=glBuffer._lastBindBaseLocation;return this._boundBufferBases[index]===glBuffer?index:-1}bindBufferRange(glBuffer,index,offset,size){var gl=this._gl;offset=offset||0,this._boundBufferBases[index=index||0]=null,gl.bindBufferRange(gl.UNIFORM_BUFFER,index||0,glBuffer.buffer,256*offset,size||256)}updateBuffer(buffer){var data,drawType,gl=this._gl,glBuffer=this.getGlBuffer(buffer);return buffer._updateID!==glBuffer.updateID&&(glBuffer.updateID=buffer._updateID,gl.bindBuffer(glBuffer.type,glBuffer.buffer),data=buffer.data,drawType=buffer.descriptor.usage&BufferUsage.STATIC?gl.STATIC_DRAW:gl.DYNAMIC_DRAW,data?glBuffer.byteLength>=data.byteLength?gl.bufferSubData(glBuffer.type,0,data,0,buffer._updateSize/data.BYTES_PER_ELEMENT):(glBuffer.byteLength=data.byteLength,gl.bufferData(glBuffer.type,data,drawType)):(glBuffer.byteLength=buffer.descriptor.size,gl.bufferData(glBuffer.type,glBuffer.byteLength,drawType))),glBuffer}destroyAll(){var gl=this._gl;for(const id in this._gpuBuffers)gl.deleteBuffer(this._gpuBuffers[id].buffer);this._gpuBuffers=Object.create(null)}onBufferDestroy(buffer,contextLost){var glBuffer=this._gpuBuffers[buffer.uid],gl=this._gl;contextLost||gl.deleteBuffer(glBuffer.buffer),this._gpuBuffers[buffer.uid]=null}createGLBuffer(buffer){var gl=this._gl;let type=BUFFER_TYPE.ARRAY_BUFFER;return buffer.descriptor.usage&BufferUsage.INDEX?type=BUFFER_TYPE.ELEMENT_ARRAY_BUFFER:buffer.descriptor.usage&BufferUsage.UNIFORM&&(type=BUFFER_TYPE.UNIFORM_BUFFER),gl=new GlBuffer(gl.createBuffer(),type),this._gpuBuffers[buffer.uid]=gl,buffer.on("destroy",this.onBufferDestroy,this),gl}resetState(){this._boundBufferBases=Object.create(null)}}GlBufferSystem.extension={type:["webgl-system"],name:"buffer"};var __defProp$o=Object.defineProperty,__defProps$a=Object.defineProperties,__getOwnPropDescs$a=Object.getOwnPropertyDescriptors,__getOwnPropSymbols$o=Object.getOwnPropertySymbols,__hasOwnProp$o=Object.prototype.hasOwnProperty,__propIsEnum$o=Object.prototype.propertyIsEnumerable,__defNormalProp$o=(obj,key,value)=>key in obj?__defProp$o(obj,key,{enumerable:!0,configurable:!0,writable:!0,value:value}):obj[key]=value,__spreadValues$o=(a,b)=>{for(var prop in b=b||{})__hasOwnProp$o.call(b,prop)&&__defNormalProp$o(a,prop,b[prop]);if(__getOwnPropSymbols$o)for(var prop of __getOwnPropSymbols$o(b))__propIsEnum$o.call(b,prop)&&__defNormalProp$o(a,prop,b[prop]);return a},__spreadProps$a=(a,b)=>__defProps$a(a,__getOwnPropDescs$a(b));const _GlContextSystem=class _GlContextSystem{constructor(renderer){this.supports={uint32Indices:!0,uniformBufferObject:!0,vertexArrayObject:!0,srgbTextures:!0,nonPowOf2wrapping:!0,msaa:!0,nonPowOf2mipmaps:!0},this._renderer=renderer,this.extensions=Object.create(null),this.handleContextLost=this.handleContextLost.bind(this),this.handleContextRestored=this.handleContextRestored.bind(this)}get isLost(){return!this.gl||this.gl.isContextLost()}contextChange(gl){this.gl=gl,this._renderer.gl=gl}init(options){var alpha,_a,antialias;options=__spreadValues$o(__spreadValues$o({},_GlContextSystem.defaultOptions),options);let multiView=this.multiView=options.multiView;options.context&&multiView&&(warn("Renderer created with both a context and multiview enabled. Disabling multiView as both cannot work together."),multiView=!1),multiView?this.canvas=DOMAdapter.get().createCanvas(this._renderer.canvas.width,this._renderer.canvas.height):this.canvas=this._renderer.view.canvas,options.context?this.initFromContext(options.context):(alpha=this._renderer.background.alpha<1,_a=null==(_a=options.premultipliedAlpha)||_a,antialias=options.antialias&&!this._renderer.backBuffer.useBackBuffer,this.createContext(options.preferWebGLVersion,{alpha:alpha,premultipliedAlpha:_a,antialias:antialias,stencil:!0,preserveDrawingBuffer:options.preserveDrawingBuffer,powerPreference:null!=(alpha=options.powerPreference)?alpha:"default"}))}ensureCanvasSize(targetCanvas){var canvas;this.multiView?((canvas=this.canvas).width{var _a;this.gl.isContextLost()&&null!=(_a=this.extensions.loseContext)&&_a.restoreContext()},0))}handleContextRestored(){this.getExtensions(),this._renderer.runners.contextChange.emit(this.gl)}destroy(){var element=this._renderer.view.canvas;this._renderer=null,element.removeEventListener("webglcontextlost",this.handleContextLost),element.removeEventListener("webglcontextrestored",this.handleContextRestored),this.gl.useProgram(null),null!=(element=this.extensions.loseContext)&&element.loseContext()}forceContextLoss(){var _a;null!=(_a=this.extensions.loseContext)&&_a.loseContext(),this._contextLossForced=!0}validateContext(gl){(gl=gl.getContextAttributes())&&!gl.stencil&&warn("Provided WebGL context does not have a stencil buffer, masks may not render correctly");var gl=this.supports,isWebGl2=2===this.webGLVersion,extensions=this.extensions;gl.uint32Indices=isWebGl2||!!extensions.uint32ElementIndex,gl.uniformBufferObject=isWebGl2,gl.vertexArrayObject=isWebGl2||!!extensions.vertexArrayObject,gl.srgbTextures=isWebGl2||!!extensions.srgb,gl.nonPowOf2wrapping=isWebGl2,gl.nonPowOf2mipmaps=isWebGl2,gl.msaa=isWebGl2,gl.uint32Indices||warn("Provided WebGL context does not support 32 index buffer, large scenes may not render correctly")}};function ensureAttributes(geometry,extractedData){for(const i in geometry.attributes){var attribute=geometry.attributes[i],attributeData=extractedData[i];attributeData?(null==attribute.format&&(attribute.format=attributeData.format),null==attribute.offset&&(attribute.offset=attributeData.offset),null==attribute.instance&&(attribute.instance=attributeData.instance)):warn(`Attribute ${i} is not present in the shader, but is present in the geometry. Unable to infer attribute details.`)}!function(geometry){var attribute,{buffers,attributes}=geometry,tempStride={},tempStart={};for(const j in buffers){var buffer=buffers[j];tempStride[buffer.uid]=0,tempStart[buffer.uid]=0}for(const j in attributes)tempStride[(attribute=attributes[j]).buffer.uid]+=getAttributeInfoFromFormat(attribute.format).stride;for(const j in attributes)null==(attribute=attributes[j]).stride&&(attribute.stride=tempStride[attribute.buffer.uid]),null==attribute.start&&(attribute.start=tempStart[attribute.buffer.uid]),tempStart[attribute.buffer.uid]+=getAttributeInfoFromFormat(attribute.format).stride}(geometry)}_GlContextSystem.extension={type:["webgl-system"],name:"context"},_GlContextSystem.defaultOptions={context:null,premultipliedAlpha:!0,preserveDrawingBuffer:!1,powerPreference:void 0,preferWebGLVersion:2,multiView:!1},findMixin=_GlContextSystem;var GL_TARGETS={TEXTURE_2D:3553,3553:"TEXTURE_2D",TEXTURE_CUBE_MAP:34067,34067:"TEXTURE_CUBE_MAP",TEXTURE_2D_ARRAY:35866,35866:"TEXTURE_2D_ARRAY",TEXTURE_CUBE_MAP_POSITIVE_X:34069,34069:"TEXTURE_CUBE_MAP_POSITIVE_X",TEXTURE_CUBE_MAP_NEGATIVE_X:34070,34070:"TEXTURE_CUBE_MAP_NEGATIVE_X",TEXTURE_CUBE_MAP_POSITIVE_Y:34071,34071:"TEXTURE_CUBE_MAP_POSITIVE_Y",TEXTURE_CUBE_MAP_NEGATIVE_Y:34072,34072:"TEXTURE_CUBE_MAP_NEGATIVE_Y",TEXTURE_CUBE_MAP_POSITIVE_Z:34073,34073:"TEXTURE_CUBE_MAP_POSITIVE_Z",TEXTURE_CUBE_MAP_NEGATIVE_Z:34074,34074:"TEXTURE_CUBE_MAP_NEGATIVE_Z"},GL_TYPES=((ExtensionType2_ShapeBuilder={})[ExtensionType2_ShapeBuilder.CLAMP=33071]="CLAMP",ExtensionType2_ShapeBuilder[ExtensionType2_ShapeBuilder.REPEAT=10497]="REPEAT",ExtensionType2_ShapeBuilder[ExtensionType2_ShapeBuilder.MIRRORED_REPEAT=33648]="MIRRORED_REPEAT",(getGlobalMixin={})[getGlobalMixin.UNSIGNED_BYTE=5121]="UNSIGNED_BYTE",getGlobalMixin[getGlobalMixin.UNSIGNED_SHORT=5123]="UNSIGNED_SHORT",getGlobalMixin[getGlobalMixin.UNSIGNED_SHORT_5_6_5=33635]="UNSIGNED_SHORT_5_6_5",getGlobalMixin[getGlobalMixin.UNSIGNED_SHORT_4_4_4_4=32819]="UNSIGNED_SHORT_4_4_4_4",getGlobalMixin[getGlobalMixin.UNSIGNED_SHORT_5_5_5_1=32820]="UNSIGNED_SHORT_5_5_5_1",getGlobalMixin[getGlobalMixin.UNSIGNED_INT=5125]="UNSIGNED_INT",getGlobalMixin[getGlobalMixin.UNSIGNED_INT_10F_11F_11F_REV=35899]="UNSIGNED_INT_10F_11F_11F_REV",getGlobalMixin[getGlobalMixin.UNSIGNED_INT_2_10_10_10_REV=33640]="UNSIGNED_INT_2_10_10_10_REV",getGlobalMixin[getGlobalMixin.UNSIGNED_INT_24_8=34042]="UNSIGNED_INT_24_8",getGlobalMixin[getGlobalMixin.UNSIGNED_INT_5_9_9_9_REV=35902]="UNSIGNED_INT_5_9_9_9_REV",getGlobalMixin[getGlobalMixin.BYTE=5120]="BYTE",getGlobalMixin[getGlobalMixin.SHORT=5122]="SHORT",getGlobalMixin[getGlobalMixin.INT=5124]="INT",getGlobalMixin[getGlobalMixin.FLOAT=5126]="FLOAT",getGlobalMixin[getGlobalMixin.FLOAT_32_UNSIGNED_INT_24_8_REV=36269]="FLOAT_32_UNSIGNED_INT_24_8_REV",getGlobalMixin[getGlobalMixin.HALF_FLOAT=36193]="HALF_FLOAT",getGlobalMixin);const infoMap={uint8x2:GL_TYPES.UNSIGNED_BYTE,uint8x4:GL_TYPES.UNSIGNED_BYTE,sint8x2:GL_TYPES.BYTE,sint8x4:GL_TYPES.BYTE,unorm8x2:GL_TYPES.UNSIGNED_BYTE,unorm8x4:GL_TYPES.UNSIGNED_BYTE,snorm8x2:GL_TYPES.BYTE,snorm8x4:GL_TYPES.BYTE,uint16x2:GL_TYPES.UNSIGNED_SHORT,uint16x4:GL_TYPES.UNSIGNED_SHORT,sint16x2:GL_TYPES.SHORT,sint16x4:GL_TYPES.SHORT,unorm16x2:GL_TYPES.UNSIGNED_SHORT,unorm16x4:GL_TYPES.UNSIGNED_SHORT,snorm16x2:GL_TYPES.SHORT,snorm16x4:GL_TYPES.SHORT,float16x2:GL_TYPES.HALF_FLOAT,float16x4:GL_TYPES.HALF_FLOAT,float32:GL_TYPES.FLOAT,float32x2:GL_TYPES.FLOAT,float32x3:GL_TYPES.FLOAT,float32x4:GL_TYPES.FLOAT,uint32:GL_TYPES.UNSIGNED_INT,uint32x2:GL_TYPES.UNSIGNED_INT,uint32x3:GL_TYPES.UNSIGNED_INT,uint32x4:GL_TYPES.UNSIGNED_INT,sint32:GL_TYPES.INT,sint32x2:GL_TYPES.INT,sint32x3:GL_TYPES.INT,sint32x4:GL_TYPES.INT},topologyToGlMap={"point-list":0,"line-list":1,"line-strip":3,"triangle-list":4,"triangle-strip":5};class GlGeometrySystem{constructor(renderer){this._geometryVaoHash=Object.create(null),this._renderer=renderer,this._activeGeometry=null,this._activeVao=null,this.hasVao=!0,this.hasInstance=!0,this._renderer.renderableGC.addManagedHash(this,"_geometryVaoHash")}contextChange(){var gl=this.gl=this._renderer.gl;if(!this._renderer.context.supports.vertexArrayObject)throw new Error("[PixiJS] Vertex Array Objects are not supported on this device");const nativeVaoExtension=this._renderer.context.extensions.vertexArrayObject,nativeInstancedExtension=(nativeVaoExtension&&(gl.createVertexArray=()=>nativeVaoExtension.createVertexArrayOES(),gl.bindVertexArray=vao=>nativeVaoExtension.bindVertexArrayOES(vao),gl.deleteVertexArray=vao=>nativeVaoExtension.deleteVertexArrayOES(vao)),this._renderer.context.extensions.vertexAttribDivisorANGLE);nativeInstancedExtension&&(gl.drawArraysInstanced=(a,b,c,d)=>{nativeInstancedExtension.drawArraysInstancedANGLE(a,b,c,d)},gl.drawElementsInstanced=(a,b,c,d,e)=>{nativeInstancedExtension.drawElementsInstancedANGLE(a,b,c,d,e)},gl.vertexAttribDivisor=(a,b)=>nativeInstancedExtension.vertexAttribDivisorANGLE(a,b)),this._activeGeometry=null,this._activeVao=null,this._geometryVaoHash=Object.create(null)}bind(geometry,program){var gl=this.gl,geometry=(this._activeGeometry=geometry,this.getVao(geometry,program));this._activeVao!==geometry&&(this._activeVao=geometry,gl.bindVertexArray(geometry)),this.updateBuffers()}resetState(){this.unbind()}updateBuffers(){var geometry=this._activeGeometry,bufferSystem=this._renderer.buffer;for(let i=0;ikey in obj?__defProp$n(obj,key,{enumerable:!0,configurable:!0,writable:!0,value:value}):obj[key]=value,__spreadValues$n=(a,b)=>{for(var prop in b=b||{})__hasOwnProp$n.call(b,prop)&&__defNormalProp$n(a,prop,b[prop]);if(__getOwnPropSymbols$n)for(var prop of __getOwnPropSymbols$n(b))__propIsEnum$n.call(b,prop)&&__defNormalProp$n(a,prop,b[prop]);return a};const bigTriangleGeometry=new Geometry({attributes:{aPosition:[-1,-1,3,-1,-1,3]}}),_GlBackBufferSystem=class _GlBackBufferSystem{constructor(renderer){this.useBackBuffer=!1,this._useBackBufferThisRender=!1,this._renderer=renderer}init(options={}){var{useBackBuffer:options,antialias}=__spreadValues$n(__spreadValues$n({},_GlBackBufferSystem.defaultOptions),options),options=(this.useBackBuffer=options,this._antialias=antialias,this._renderer.context.supports.msaa||(warn("antialiasing, is not supported on when using the back buffer"),this._antialias=!1),this._state=State.for2d(),new GlProgram({vertex:` + attribute vec2 aPosition; + out vec2 vUv; + + void main() { + gl_Position = vec4(aPosition, 0.0, 1.0); + + vUv = (aPosition + 1.0) / 2.0; + + // flip dem UVs + vUv.y = 1.0 - vUv.y; + }`,fragment:` + in vec2 vUv; + out vec4 finalColor; + + uniform sampler2D uTexture; + + void main() { + finalColor = texture(uTexture, vUv); + }`,name:"big-triangle"}));this._bigTriangleShader=new Shader({glProgram:options,resources:{uTexture:Texture.WHITE.source}})}renderStart(options){var renderTarget=this._renderer.renderTarget.getRenderTarget(options.target);this._useBackBufferThisRender=this.useBackBuffer&&!!renderTarget.isRoot,this._useBackBufferThisRender&&(renderTarget=this._renderer.renderTarget.getRenderTarget(options.target),this._targetTexture=renderTarget.colorTexture,options.target=this._getBackBufferTexture(renderTarget.colorTexture))}renderEnd(){this._presentBackBuffer()}_presentBackBuffer(){var renderer=this._renderer;renderer.renderTarget.finishRenderPass(),this._useBackBufferThisRender&&(renderer.renderTarget.bind(this._targetTexture,!1),this._bigTriangleShader.resources.uTexture=this._backBufferTexture.source,renderer.encoder.draw({geometry:bigTriangleGeometry,shader:this._bigTriangleShader,state:this._state}))}_getBackBufferTexture(targetSourceTexture){return this._backBufferTexture=this._backBufferTexture||new Texture({source:new TextureSource({width:targetSourceTexture.width,height:targetSourceTexture.height,resolution:targetSourceTexture._resolution,antialias:this._antialias})}),this._backBufferTexture.source.resize(targetSourceTexture.width,targetSourceTexture.height,targetSourceTexture._resolution),this._backBufferTexture}destroy(){this._backBufferTexture&&(this._backBufferTexture.destroy(),this._backBufferTexture=null)}};_GlBackBufferSystem.extension={type:["webgl-system"],name:"backBuffer",priority:1},_GlBackBufferSystem.defaultOptions={useBackBuffer:!1},sortMixin=_GlBackBufferSystem;class GlColorMaskSystem{constructor(renderer){this._colorMaskCache=15,this._renderer=renderer}setMask(colorMask){this._colorMaskCache!==colorMask&&(this._colorMaskCache=colorMask,this._renderer.gl.colorMask(!!(8&colorMask),!!(4&colorMask),!!(2&colorMask),!!(1&colorMask)))}}GlColorMaskSystem.extension={type:["webgl-system"],name:"colorMask"};class GlEncoderSystem{constructor(renderer){this.commandFinished=Promise.resolve(),this._renderer=renderer}setGeometry(geometry,shader){this._renderer.geometry.bind(geometry,shader.glProgram)}finishRenderPass(){}draw(options){var renderer=this._renderer,{geometry:options,shader,state,skipSync,topology:type,size,start,instanceCount}=options;renderer.shader.bind(shader,skipSync),renderer.geometry.bind(options,renderer.shader._activeProgram),state&&renderer.state.set(state),renderer.geometry.draw(type,size,start,null!=instanceCount?instanceCount:options.instanceCount)}destroy(){this._renderer=null}}GlEncoderSystem.extension={type:["webgl-system"],name:"encoder"};class GlRenderTarget{constructor(){this.width=-1,this.height=-1,this.msaa=!1,this.msaaRenderBuffer=[]}}const GpuStencilModesToPixi=[];GpuStencilModesToPixi[5]=void 0,GpuStencilModesToPixi[0]={stencilWriteMask:0,stencilReadMask:0},GpuStencilModesToPixi[1]={stencilFront:{compare:"equal",passOp:"increment-clamp"},stencilBack:{compare:"equal",passOp:"increment-clamp"}},GpuStencilModesToPixi[4]={stencilFront:{compare:"equal",passOp:"decrement-clamp"},stencilBack:{compare:"equal",passOp:"decrement-clamp"}},GpuStencilModesToPixi[2]={stencilWriteMask:0,stencilFront:{compare:"equal",passOp:"keep"},stencilBack:{compare:"equal",passOp:"keep"}},GpuStencilModesToPixi[3]={stencilWriteMask:0,stencilFront:{compare:"not-equal",passOp:"replace"},stencilBack:{compare:"not-equal",passOp:"replace"}};class GlStencilSystem{constructor(renderer){this._stencilCache={enabled:!1,stencilReference:0,stencilMode:5},this._renderTargetStencilState=Object.create(null),renderer.renderTarget.onRenderTargetChange.add(this)}contextChange(gl){this._gl=gl,this._comparisonFuncMapping={always:gl.ALWAYS,never:gl.NEVER,equal:gl.EQUAL,"not-equal":gl.NOTEQUAL,less:gl.LESS,"less-equal":gl.LEQUAL,greater:gl.GREATER,"greater-equal":gl.GEQUAL},this._stencilOpsMapping={keep:gl.KEEP,zero:gl.ZERO,replace:gl.REPLACE,invert:gl.INVERT,"increment-clamp":gl.INCR,"decrement-clamp":gl.DECR,"increment-wrap":gl.INCR_WRAP,"decrement-wrap":gl.DECR_WRAP},this.resetState()}onRenderTargetChange(renderTarget){this._activeRenderTarget!==renderTarget&&(this._activeRenderTarget=renderTarget,renderTarget=this._renderTargetStencilState[renderTarget.uid]||(this._renderTargetStencilState[renderTarget.uid]={stencilMode:0,stencilReference:0}),this.setStencilMode(renderTarget.stencilMode,renderTarget.stencilReference))}resetState(){this._stencilCache.enabled=!1,this._stencilCache.stencilMode=5,this._stencilCache.stencilReference=0}setStencilMode(stencilMode,stencilReference){var stencilState=this._renderTargetStencilState[this._activeRenderTarget.uid],gl=this._gl,mode=GpuStencilModesToPixi[stencilMode],_stencilCache=this._stencilCache;stencilState.stencilMode=stencilMode,stencilState.stencilReference=stencilReference,0===stencilMode?this._stencilCache.enabled&&(this._stencilCache.enabled=!1,gl.disable(gl.STENCIL_TEST)):(this._stencilCache.enabled||(this._stencilCache.enabled=!0,gl.enable(gl.STENCIL_TEST)),stencilMode===_stencilCache.stencilMode&&_stencilCache.stencilReference===stencilReference||(_stencilCache.stencilMode=stencilMode,_stencilCache.stencilReference=stencilReference,gl.stencilFunc(this._comparisonFuncMapping[mode.stencilBack.compare],stencilReference,255),gl.stencilOp(gl.KEEP,gl.KEEP,this._stencilOpsMapping[mode.stencilBack.passOp])))}}GlStencilSystem.extension={type:["webgl-system"],name:"stencil"};class UboSystem{constructor(adaptor){this._syncFunctionHash=Object.create(null),this._adaptor=adaptor,this._systemCheck()}_systemCheck(){if(!unsafeEvalSupported())throw new Error("Current environment does not allow unsafe-eval, please use pixi.js/unsafe-eval module to enable support.")}ensureUniformGroup(uniformGroup){var uniformData=this.getUniformGroupData(uniformGroup);uniformGroup.buffer||(uniformGroup.buffer=new Buffer({data:new Float32Array(uniformData.layout.size/4),usage:BufferUsage.UNIFORM|BufferUsage.COPY_DST}))}getUniformGroupData(uniformGroup){return this._syncFunctionHash[uniformGroup._signature]||this._initUniformGroup(uniformGroup)}_initUniformGroup(uniformGroup){var elements,syncFunction,uniformGroupSignature=uniformGroup._signature;return this._syncFunctionHash[uniformGroupSignature]||(elements=Object.keys(uniformGroup.uniformStructures).map(i=>uniformGroup.uniformStructures[i]),elements=this._adaptor.createUboElements(elements),syncFunction=this._generateUboSync(elements.uboElements),this._syncFunctionHash[uniformGroupSignature]={layout:elements,syncFunction:syncFunction}),this._syncFunctionHash[uniformGroupSignature]}_generateUboSync(uboElements){return this._adaptor.generateUboSync(uboElements)}syncUniformGroup(uniformGroup,data,offset){var uniformGroupData=this.getUniformGroupData(uniformGroup);uniformGroup.buffer||(uniformGroup.buffer=new Buffer({data:new Float32Array(uniformGroupData.layout.size/4),usage:BufferUsage.UNIFORM|BufferUsage.COPY_DST}));let dataInt32=null;return data||(data=uniformGroup.buffer.data,dataInt32=uniformGroup.buffer.dataInt32),offset=offset||0,uniformGroupData.syncFunction(uniformGroup.uniforms,data,dataInt32,offset),!0}updateUniformGroup(uniformGroup){if(uniformGroup.isStatic&&!uniformGroup._dirtyId)return!1;uniformGroup._dirtyId=0;var synced=this.syncUniformGroup(uniformGroup);return uniformGroup.buffer.update(),synced}destroy(){this._syncFunctionHash=null}}const WGSL_TO_STD40_SIZE={f32:4,i32:4,"vec2":8,"vec3":12,"vec4":16,"vec2":8,"vec3":12,"vec4":16,"mat2x2":32,"mat3x3":48,"mat4x4":64};function createUboElementsSTD40(uniformData){var uboElements=uniformData.map(data=>({data:data,offset:0,size:0}));let size,offset=0;for(let i=0;i",test:data=>void 0!==data.value.a,ubo:` + var matrix = uv[name].toArray(true); + data[offset] = matrix[0]; + data[offset + 1] = matrix[1]; + data[offset + 2] = matrix[2]; + data[offset + 4] = matrix[3]; + data[offset + 5] = matrix[4]; + data[offset + 6] = matrix[5]; + data[offset + 8] = matrix[6]; + data[offset + 9] = matrix[7]; + data[offset + 10] = matrix[8]; + `,uniform:` + gl.uniformMatrix3fv(ud[name].location, false, uv[name].toArray(true)); + `},{type:"vec4",test:data=>"vec4"===data.type&&1===data.size&&void 0!==data.value.width,ubo:` + v = uv[name]; + data[offset] = v.x; + data[offset + 1] = v.y; + data[offset + 2] = v.width; + data[offset + 3] = v.height; + `,uniform:` + cv = ud[name].value; + v = uv[name]; + if (cv[0] !== v.x || cv[1] !== v.y || cv[2] !== v.width || cv[3] !== v.height) { + cv[0] = v.x; + cv[1] = v.y; + cv[2] = v.width; + cv[3] = v.height; + gl.uniform4f(ud[name].location, v.x, v.y, v.width, v.height); + } + `},{type:"vec2",test:data=>"vec2"===data.type&&1===data.size&&void 0!==data.value.x,ubo:` + v = uv[name]; + data[offset] = v.x; + data[offset + 1] = v.y; + `,uniform:` + cv = ud[name].value; + v = uv[name]; + if (cv[0] !== v.x || cv[1] !== v.y) { + cv[0] = v.x; + cv[1] = v.y; + gl.uniform2f(ud[name].location, v.x, v.y); + } + `},{type:"vec4",test:data=>"vec4"===data.type&&1===data.size&&void 0!==data.value.red,ubo:` + v = uv[name]; + data[offset] = v.red; + data[offset + 1] = v.green; + data[offset + 2] = v.blue; + data[offset + 3] = v.alpha; + `,uniform:` + cv = ud[name].value; + v = uv[name]; + if (cv[0] !== v.red || cv[1] !== v.green || cv[2] !== v.blue || cv[3] !== v.alpha) { + cv[0] = v.red; + cv[1] = v.green; + cv[2] = v.blue; + cv[3] = v.alpha; + gl.uniform4f(ud[name].location, v.red, v.green, v.blue, v.alpha); + } + `},{type:"vec3",test:data=>"vec3"===data.type&&1===data.size&&void 0!==data.value.red,ubo:` + v = uv[name]; + data[offset] = v.red; + data[offset + 1] = v.green; + data[offset + 2] = v.blue; + `,uniform:` + cv = ud[name].value; + v = uv[name]; + if (cv[0] !== v.red || cv[1] !== v.green || cv[2] !== v.blue) { + cv[0] = v.red; + cv[1] = v.green; + cv[2] = v.blue; + gl.uniform3f(ud[name].location, v.red, v.green, v.blue); + } + `}];function createUboSyncFunction(uboElements,parserCode,arrayGenerationFunction,singleSettersMap){var funcFragments=[` + var v = null; + var v2 = null; + var t = 0; + var index = 0; + var name = null; + var arrayOffset = null; + `];let prev=0;for(let i=0;ikey in obj?__defProp$m(obj,key,{enumerable:!0,configurable:!0,writable:!0,value:value}):obj[key]=value;function loopMatrix(col,row){return` + for (let i = 0; i < ${col*row}; i++) { + data[offset + (((i / ${col})|0) * 4) + (i % ${col})] = v[i]; + } + `}const uboSyncFunctionsSTD40={f32:` + data[offset] = v;`,i32:` + dataInt32[offset] = v;`,"vec2":` + data[offset] = v[0]; + data[offset + 1] = v[1];`,"vec3":` + data[offset] = v[0]; + data[offset + 1] = v[1]; + data[offset + 2] = v[2];`,"vec4":` + data[offset] = v[0]; + data[offset + 1] = v[1]; + data[offset + 2] = v[2]; + data[offset + 3] = v[3];`,"vec2":` + dataInt32[offset] = v[0]; + dataInt32[offset + 1] = v[1];`,"vec3":` + dataInt32[offset] = v[0]; + dataInt32[offset + 1] = v[1]; + dataInt32[offset + 2] = v[2];`,"vec4":` + dataInt32[offset] = v[0]; + dataInt32[offset + 1] = v[1]; + dataInt32[offset + 2] = v[2]; + dataInt32[offset + 3] = v[3];`,"mat2x2":` + data[offset] = v[0]; + data[offset + 1] = v[1]; + data[offset + 4] = v[2]; + data[offset + 5] = v[3];`,"mat3x3":` + data[offset] = v[0]; + data[offset + 1] = v[1]; + data[offset + 2] = v[2]; + data[offset + 4] = v[3]; + data[offset + 5] = v[4]; + data[offset + 6] = v[5]; + data[offset + 8] = v[6]; + data[offset + 9] = v[7]; + data[offset + 10] = v[8];`,"mat4x4":` + for (let i = 0; i < 16; i++) { + data[offset + i] = v[i]; + }`,"mat3x2":loopMatrix(3,2),"mat4x2":loopMatrix(4,2),"mat2x3":loopMatrix(2,3),"mat4x3":loopMatrix(4,3),"mat2x4":loopMatrix(2,4),"mat3x4":loopMatrix(3,4)},uboSyncFunctionsWGSL=(a=>__defProps$9(a,__getOwnPropDescs$9({"mat2x2":` + data[offset] = v[0]; + data[offset + 1] = v[1]; + data[offset + 2] = v[2]; + data[offset + 3] = v[3]; + `})))(((a,b)=>{for(var prop in uboSyncFunctionsSTD40)__hasOwnProp$m.call(b,prop)&&__defNormalProp$m(a,prop,b[prop]);if(__getOwnPropSymbols$m)for(var prop of __getOwnPropSymbols$m(b))__propIsEnum$m.call(b,prop)&&__defNormalProp$m(a,prop,b[prop]);return a})({},uboSyncFunctionsSTD40));function generateArraySyncSTD40(uboElement,offsetToAdd){var rowSize=Math.max(WGSL_TO_STD40_SIZE[uboElement.data.type]/16,1),elementSize=uboElement.data.value.length/uboElement.data.size,remainder=(4-elementSize%4)%4,data=0<=uboElement.data.type.indexOf("i32")?"dataInt32":"data";return` + v = uv.${uboElement.data.name}; + offset += ${offsetToAdd}; + + arrayOffset = offset; + + t = 0; + + for(var i=0; i < ${uboElement.data.size*rowSize}; i++) + { + for(var j = 0; j < ${elementSize}; j++) + { + ${data}[arrayOffset++] = v[t++]; + } + ${0!=remainder?`arrayOffset += ${remainder};`:""} + } + `}function createUboSyncFunctionSTD40(uboElements){return createUboSyncFunction(uboElements,"uboStd40",generateArraySyncSTD40,uboSyncFunctionsSTD40)}class GlUboSystem extends UboSystem{constructor(){super({createUboElements:createUboElementsSTD40,generateUboSync:createUboSyncFunctionSTD40})}}GlUboSystem.extension={type:["webgl-system"],name:"ubo"};class GlRenderTargetAdaptor{constructor(){this._clearColorCache=[0,0,0,0],this._viewPortCache=new Rectangle}init(renderer,renderTargetSystem){this._renderer=renderer,this._renderTargetSystem=renderTargetSystem,renderer.runners.contextChange.add(this)}contextChange(){this._clearColorCache=[0,0,0,0],this._viewPortCache=new Rectangle}copyToTexture(sourceRenderSurfaceTexture,destinationTexture,originSrc,size,originDest){var renderTargetSystem=this._renderTargetSystem,renderer=this._renderer,renderTargetSystem=renderTargetSystem.getGpuRenderTarget(sourceRenderSurfaceTexture),gl=renderer.gl;return this.finishRenderPass(sourceRenderSurfaceTexture),gl.bindFramebuffer(gl.FRAMEBUFFER,renderTargetSystem.resolveTargetFramebuffer),renderer.texture.bind(destinationTexture,0),gl.copyTexSubImage2D(gl.TEXTURE_2D,0,originDest.x,originDest.y,originSrc.x,originSrc.y,size.width,size.height),destinationTexture}startRenderPass(renderTarget,clear=!0,clearColor,viewport){var renderTargetSystem=this._renderTargetSystem,source=renderTarget.colorTexture,renderTargetSystem=renderTargetSystem.getGpuRenderTarget(renderTarget);let viewPortY=viewport.y;renderTarget.isRoot&&(viewPortY=source.pixelHeight-viewport.height),renderTarget.colorTextures.forEach(texture=>{this._renderer.texture.unbind(texture)}),(source=this._renderer.gl).bindFramebuffer(source.FRAMEBUFFER,renderTargetSystem.framebuffer);var viewPortCache=this._viewPortCache;viewPortCache.x===viewport.x&&viewPortCache.y===viewPortY&&viewPortCache.width===viewport.width&&viewPortCache.height===viewport.height||(viewPortCache.x=viewport.x,viewPortCache.y=viewPortY,viewPortCache.width=viewport.width,viewPortCache.height=viewport.height,source.viewport(viewport.x,viewPortY,viewport.width,viewport.height)),renderTargetSystem.depthStencilRenderBuffer||!renderTarget.stencil&&!renderTarget.depth||this._initStencil(renderTargetSystem),this.clear(renderTarget,clear,clearColor)}finishRenderPass(renderTarget){var gl;(renderTarget=this._renderTargetSystem.getGpuRenderTarget(renderTarget)).msaa&&((gl=this._renderer.gl).bindFramebuffer(gl.FRAMEBUFFER,renderTarget.resolveTargetFramebuffer),gl.bindFramebuffer(gl.READ_FRAMEBUFFER,renderTarget.framebuffer),gl.blitFramebuffer(0,0,renderTarget.width,renderTarget.height,0,0,renderTarget.width,renderTarget.height,gl.COLOR_BUFFER_BIT,gl.NEAREST),gl.bindFramebuffer(gl.FRAMEBUFFER,renderTarget.framebuffer))}initGpuRenderTarget(renderTarget){var gl=this._renderer.gl,glRenderTarget=new GlRenderTarget,colorTexture=renderTarget.colorTexture;return CanvasSource.test(colorTexture.resource)?(this._renderer.context.ensureCanvasSize(renderTarget.colorTexture.resource),glRenderTarget.framebuffer=null):(this._initColor(renderTarget,glRenderTarget),gl.bindFramebuffer(gl.FRAMEBUFFER,null)),glRenderTarget}destroyGpuRenderTarget(gpuRenderTarget){const gl=this._renderer.gl;gpuRenderTarget.framebuffer&&(gl.deleteFramebuffer(gpuRenderTarget.framebuffer),gpuRenderTarget.framebuffer=null),gpuRenderTarget.resolveTargetFramebuffer&&(gl.deleteFramebuffer(gpuRenderTarget.resolveTargetFramebuffer),gpuRenderTarget.resolveTargetFramebuffer=null),gpuRenderTarget.depthStencilRenderBuffer&&(gl.deleteRenderbuffer(gpuRenderTarget.depthStencilRenderBuffer),gpuRenderTarget.depthStencilRenderBuffer=null),gpuRenderTarget.msaaRenderBuffer.forEach(renderBuffer=>{gl.deleteRenderbuffer(renderBuffer)}),gpuRenderTarget.msaaRenderBuffer=null}clear(_renderTarget,clear,clearColor){var gl,renderTargetSystem;clear&&(renderTargetSystem=this._renderTargetSystem,gl=this._renderer.gl,(clear="boolean"==typeof clear?clear?CLEAR.ALL:CLEAR.NONE:clear)&CLEAR.COLOR&&(renderTargetSystem=clearColor=null==clearColor?renderTargetSystem.defaultClearColor:clearColor,(clearColor=this._clearColorCache)[0]===renderTargetSystem[0]&&clearColor[1]===renderTargetSystem[1]&&clearColor[2]===renderTargetSystem[2]&&clearColor[3]===renderTargetSystem[3]||(clearColor[0]=renderTargetSystem[0],clearColor[1]=renderTargetSystem[1],clearColor[2]=renderTargetSystem[2],clearColor[3]=renderTargetSystem[3],gl.clearColor(renderTargetSystem[0],renderTargetSystem[1],renderTargetSystem[2],renderTargetSystem[3]))),gl.clear(clear))}resizeGpuRenderTarget(renderTarget){var glRenderTarget;!renderTarget.isRoot&&(glRenderTarget=this._renderTargetSystem.getGpuRenderTarget(renderTarget),this._resizeColor(renderTarget,glRenderTarget),renderTarget.stencil||renderTarget.depth)&&this._resizeStencil(glRenderTarget)}_initColor(renderTarget,glRenderTarget){const renderer=this._renderer,gl=renderer.gl;var viewFramebuffer,resolveTargetFramebuffer=gl.createFramebuffer();glRenderTarget.resolveTargetFramebuffer=resolveTargetFramebuffer,gl.bindFramebuffer(gl.FRAMEBUFFER,resolveTargetFramebuffer),glRenderTarget.width=renderTarget.colorTexture.source.pixelWidth,glRenderTarget.height=renderTarget.colorTexture.source.pixelHeight,renderTarget.colorTextures.forEach((colorTexture,i)=>{(colorTexture=colorTexture.source).antialias&&(renderer.context.supports.msaa?glRenderTarget.msaa=!0:warn("[RenderTexture] Antialiasing on textures is not supported in WebGL1")),renderer.texture.bindSource(colorTexture,0),colorTexture=(colorTexture=renderer.texture.getGlSource(colorTexture)).texture,gl.framebufferTexture2D(gl.FRAMEBUFFER,gl.COLOR_ATTACHMENT0+i,3553,colorTexture,0)}),glRenderTarget.msaa?(viewFramebuffer=gl.createFramebuffer(),glRenderTarget.framebuffer=viewFramebuffer,gl.bindFramebuffer(gl.FRAMEBUFFER,viewFramebuffer),renderTarget.colorTextures.forEach((_,i)=>{var msaaRenderBuffer=gl.createRenderbuffer();glRenderTarget.msaaRenderBuffer[i]=msaaRenderBuffer})):glRenderTarget.framebuffer=resolveTargetFramebuffer,this._resizeColor(renderTarget,glRenderTarget)}_resizeColor(renderTarget,glRenderTarget){const source=renderTarget.colorTexture.source;if(glRenderTarget.width=source.pixelWidth,glRenderTarget.height=source.pixelHeight,renderTarget.colorTextures.forEach((colorTexture,i)=>{0!==i&&colorTexture.source.resize(source.width,source.height,source._resolution)}),glRenderTarget.msaa){const renderer=this._renderer,gl=renderer.gl;var viewFramebuffer=glRenderTarget.framebuffer;gl.bindFramebuffer(gl.FRAMEBUFFER,viewFramebuffer),renderTarget.colorTextures.forEach((colorTexture,i)=>{colorTexture=colorTexture.source,renderer.texture.bindSource(colorTexture,0);var glSource=renderer.texture.getGlSource(colorTexture).internalFormat,msaaRenderBuffer=glRenderTarget.msaaRenderBuffer[i];gl.bindRenderbuffer(gl.RENDERBUFFER,msaaRenderBuffer),gl.renderbufferStorageMultisample(gl.RENDERBUFFER,4,glSource,colorTexture.pixelWidth,colorTexture.pixelHeight),gl.framebufferRenderbuffer(gl.FRAMEBUFFER,gl.COLOR_ATTACHMENT0+i,gl.RENDERBUFFER,msaaRenderBuffer)})}}_initStencil(glRenderTarget){var gl,depthStencilRenderBuffer;null!==glRenderTarget.framebuffer&&(depthStencilRenderBuffer=(gl=this._renderer.gl).createRenderbuffer(),glRenderTarget.depthStencilRenderBuffer=depthStencilRenderBuffer,gl.bindRenderbuffer(gl.RENDERBUFFER,depthStencilRenderBuffer),gl.framebufferRenderbuffer(gl.FRAMEBUFFER,gl.DEPTH_STENCIL_ATTACHMENT,gl.RENDERBUFFER,depthStencilRenderBuffer),this._resizeStencil(glRenderTarget))}_resizeStencil(glRenderTarget){var gl=this._renderer.gl;gl.bindRenderbuffer(gl.RENDERBUFFER,glRenderTarget.depthStencilRenderBuffer),glRenderTarget.msaa?gl.renderbufferStorageMultisample(gl.RENDERBUFFER,4,gl.DEPTH24_STENCIL8,glRenderTarget.width,glRenderTarget.height):gl.renderbufferStorage(gl.RENDERBUFFER,2===this._renderer.context.webGLVersion?gl.DEPTH24_STENCIL8:gl.DEPTH_STENCIL,glRenderTarget.width,glRenderTarget.height)}prerender(renderTarget){renderTarget=renderTarget.colorTexture.resource,this._renderer.context.multiView&&CanvasSource.test(renderTarget)&&this._renderer.context.ensureCanvasSize(renderTarget)}postrender(renderTarget){var contextCanvas;this._renderer.context.multiView&&CanvasSource.test(renderTarget.colorTexture.resource)&&(contextCanvas=this._renderer.context.canvas,(renderTarget=renderTarget.colorTexture).context2D.drawImage(contextCanvas,0,renderTarget.pixelHeight-contextCanvas.height))}}var __defProp$l=Object.defineProperty,__getOwnPropSymbols$l=Object.getOwnPropertySymbols,__hasOwnProp$l=Object.prototype.hasOwnProperty,__propIsEnum$l=Object.prototype.propertyIsEnumerable,__defNormalProp$l=(obj,key,value)=>key in obj?__defProp$l(obj,key,{enumerable:!0,configurable:!0,writable:!0,value:value}):obj[key]=value;const canvasCache=new Map;function getCanvasTexture(canvas,options){if(!canvasCache.has(canvas)){const texture=new Texture({source:new CanvasSource(((a,b)=>{for(var prop in b=options||{})__hasOwnProp$l.call(b,prop)&&__defNormalProp$l(a,prop,b[prop]);if(__getOwnPropSymbols$l)for(var prop of __getOwnPropSymbols$l(b))__propIsEnum$l.call(b,prop)&&__defNormalProp$l(a,prop,b[prop]);return a})({resource:canvas}))});options=()=>{canvasCache.get(canvas)===texture&&canvasCache.delete(canvas)},texture.once("destroy",options),texture.source.once("destroy",options),canvasCache.set(canvas,texture)}return canvasCache.get(canvas)}var __defProp$k=Object.defineProperty,__getOwnPropSymbols$k=Object.getOwnPropertySymbols,__hasOwnProp$k=Object.prototype.hasOwnProperty,__propIsEnum$k=Object.prototype.propertyIsEnumerable,__defNormalProp$k=(obj,key,value)=>key in obj?__defProp$k(obj,key,{enumerable:!0,configurable:!0,writable:!0,value:value}):obj[key]=value,__spreadValues$k=(a,b)=>{for(var prop in b=b||{})__hasOwnProp$k.call(b,prop)&&__defNormalProp$k(a,prop,b[prop]);if(__getOwnPropSymbols$k)for(var prop of __getOwnPropSymbols$k(b))__propIsEnum$k.call(b,prop)&&__defNormalProp$k(a,prop,b[prop]);return a};const _RenderTarget=class _RenderTarget{constructor(descriptor={}){if(this.uid=uid$1("renderTarget"),this.colorTextures=[],this.dirtyId=0,this.isRoot=!1,this._size=new Float32Array(2),this._managedColorTextures=!1,descriptor=__spreadValues$k(__spreadValues$k({},_RenderTarget.defaultOptions),descriptor),this.stencil=descriptor.stencil,this.depth=descriptor.depth,this.isRoot=descriptor.isRoot,"number"==typeof descriptor.colorTextures){this._managedColorTextures=!0;for(let i=0;itexture.source)];var colorSource=this.colorTexture.source;this.resize(colorSource.width,colorSource.height,colorSource._resolution)}this.colorTexture.source.on("resize",this.onSourceResize,this),(descriptor.depthStencilTexture||this.stencil)&&(descriptor.depthStencilTexture instanceof Texture||descriptor.depthStencilTexture instanceof TextureSource?this.depthStencilTexture=descriptor.depthStencilTexture.source:this.ensureDepthStencilTexture())}get size(){var _size=this._size;return _size[0]=this.pixelWidth,_size[1]=this.pixelHeight,_size}get width(){return this.colorTexture.source.width}get height(){return this.colorTexture.source.height}get pixelWidth(){return this.colorTexture.source.pixelWidth}get pixelHeight(){return this.colorTexture.source.pixelHeight}get resolution(){return this.colorTexture.source._resolution}get colorTexture(){return this.colorTextures[0]}onSourceResize(source){this.resize(source.width,source.height,source._resolution,!0)}ensureDepthStencilTexture(){this.depthStencilTexture||(this.depthStencilTexture=new TextureSource({width:this.width,height:this.height,resolution:this.resolution,format:"depth24plus-stencil8",autoGenerateMipmaps:!1,antialias:!1,mipLevelCount:1}))}resize(width,height,resolution=this.resolution,skipColorTexture=!1){this.dirtyId++,this.colorTextures.forEach((colorTexture,i)=>{skipColorTexture&&0===i||colorTexture.source.resize(width,height,resolution)}),this.depthStencilTexture&&this.depthStencilTexture.source.resize(width,height,resolution)}destroy(){this.colorTexture.source.off("resize",this.onSourceResize,this),this._managedColorTextures&&this.colorTextures.forEach(texture=>{texture.destroy()}),this.depthStencilTexture&&(this.depthStencilTexture.destroy(),delete this.depthStencilTexture)}};_RenderTarget.defaultOptions={width:0,height:0,resolution:1,colorTextures:1,stencil:!1,depth:!1,antialias:!1,isRoot:!1};let RenderTarget=_RenderTarget;class RenderTargetSystem{constructor(renderer){this.rootViewPort=new Rectangle,this.viewport=new Rectangle,this.onRenderTargetChange=new SystemRunner("onRenderTargetChange"),this.projectionMatrix=new Matrix,this.defaultClearColor=[0,0,0,0],this._renderSurfaceToRenderTargetHash=new Map,this._gpuRenderTargetHash=Object.create(null),this._renderTargetStack=[],(this._renderer=renderer).renderableGC.addManagedHash(this,"_gpuRenderTargetHash")}finishRenderPass(){this.adaptor.finishRenderPass(this.renderTarget)}renderStart({target,clear,clearColor,frame}){this._renderTargetStack.length=0,this.push(target,clear,clearColor,frame),this.rootViewPort.copyFrom(this.viewport),this.rootRenderTarget=this.renderTarget,this.renderingToScreen=(clearColor=(clearColor=this.rootRenderTarget).colorTexture.source.resource,globalThis.HTMLCanvasElement&&clearColor instanceof HTMLCanvasElement&&document.body.contains(clearColor)),null!=(clear=(target=this.adaptor).prerender)&&clear.call(target,this.rootRenderTarget)}postrender(){var _a,_b;null!=(_b=(_a=this.adaptor).postrender)&&_b.call(_a,this.rootRenderTarget)}bind(renderSurface,clear=!0,clearColor,frame){var renderTarget=this.getRenderTarget(renderSurface),didChange=this.renderTarget!==renderTarget,gpuRenderTarget=(this.renderTarget=renderTarget,this.renderSurface=renderSurface,this.getGpuRenderTarget(renderTarget)),gpuRenderTarget=(renderTarget.pixelWidth===gpuRenderTarget.width&&renderTarget.pixelHeight===gpuRenderTarget.height||(this.adaptor.resizeGpuRenderTarget(renderTarget),gpuRenderTarget.width=renderTarget.pixelWidth,gpuRenderTarget.height=renderTarget.pixelHeight),renderTarget.colorTexture),viewport=this.viewport,pixelWidth=gpuRenderTarget.pixelWidth,pixelHeight=gpuRenderTarget.pixelHeight;return(frame=!frame&&renderSurface instanceof Texture?renderSurface.frame:frame)?(renderSurface=gpuRenderTarget._resolution,viewport.x=frame.x*renderSurface+.5|0,viewport.y=frame.y*renderSurface+.5|0,viewport.width=frame.width*renderSurface+.5|0,viewport.height=frame.height*renderSurface+.5|0):(viewport.x=0,viewport.y=0,viewport.width=pixelWidth,viewport.height=pixelHeight),frame=this.projectionMatrix,renderSurface=0,pixelHeight=viewport.width/gpuRenderTarget.resolution,gpuRenderTarget=viewport.height/gpuRenderTarget.resolution,pixelWidth=renderTarget.isRoot?-1:1,frame.identity(),frame.a=1/pixelHeight*2,frame.d=1/gpuRenderTarget*2*pixelWidth,frame.tx=-1-renderSurface*frame.a,frame.ty=-pixelWidth-0*frame.d,this.adaptor.startRenderPass(renderTarget,clear,clearColor,viewport),didChange&&this.onRenderTargetChange.emit(renderTarget),renderTarget}clear(target,clear=CLEAR.ALL,clearColor){clear&&(target=target&&this.getRenderTarget(target),this.adaptor.clear(target||this.renderTarget,clear,clearColor,this.viewport))}contextChange(){this._gpuRenderTargetHash=Object.create(null)}push(renderSurface,clear=CLEAR.ALL,clearColor,frame){return renderSurface=this.bind(renderSurface,clear,clearColor,frame),this._renderTargetStack.push({renderTarget:renderSurface,frame:frame}),renderSurface}pop(){this._renderTargetStack.pop();var currentRenderTargetData=this._renderTargetStack[this._renderTargetStack.length-1];this.bind(currentRenderTargetData.renderTarget,!1,null,currentRenderTargetData.frame)}getRenderTarget(renderSurface){var _a;return renderSurface.isTexture&&(renderSurface=renderSurface.source),null!=(_a=this._renderSurfaceToRenderTargetHash.get(renderSurface))?_a:this._initRenderTarget(renderSurface)}copyToTexture(sourceRenderSurfaceTexture,destinationTexture,originSrc,size,originDest){originSrc.x<0&&(size.width+=originSrc.x,originDest.x-=originSrc.x,originSrc.x=0),originSrc.y<0&&(size.height+=originSrc.y,originDest.y-=originSrc.y,originSrc.y=0);var{pixelWidth,pixelHeight}=sourceRenderSurfaceTexture;return size.width=Math.min(size.width,pixelWidth-originSrc.x),size.height=Math.min(size.height,pixelHeight-originSrc.y),this.adaptor.copyToTexture(sourceRenderSurfaceTexture,destinationTexture,originSrc,size,originDest)}ensureDepthStencil(){this.renderTarget.stencil||(this.renderTarget.stencil=!0,this.adaptor.startRenderPass(this.renderTarget,!1,null,this.viewport))}destroy(){this._renderer=null,this._renderSurfaceToRenderTargetHash.forEach((renderTarget,key)=>{renderTarget!==key&&renderTarget.destroy()}),this._renderSurfaceToRenderTargetHash.clear(),this._gpuRenderTargetHash=Object.create(null)}_initRenderTarget(renderSurface){let renderTarget=null;return(renderSurface=CanvasSource.test(renderSurface)?getCanvasTexture(renderSurface).source:renderSurface)instanceof RenderTarget?renderTarget=renderSurface:renderSurface instanceof TextureSource&&(renderTarget=new RenderTarget({colorTextures:[renderSurface]}),CanvasSource.test(renderSurface.source.resource)&&(renderTarget.isRoot=!0),renderSurface.once("destroy",()=>{renderTarget.destroy(),this._renderSurfaceToRenderTargetHash.delete(renderSurface);var gpuRenderTarget=this._gpuRenderTargetHash[renderTarget.uid];gpuRenderTarget&&(this._gpuRenderTargetHash[renderTarget.uid]=null,this.adaptor.destroyGpuRenderTarget(gpuRenderTarget))})),this._renderSurfaceToRenderTargetHash.set(renderSurface,renderTarget),renderTarget}getGpuRenderTarget(renderTarget){return this._gpuRenderTargetHash[renderTarget.uid]||(this._gpuRenderTargetHash[renderTarget.uid]=this.adaptor.initGpuRenderTarget(renderTarget))}resetState(){this.renderTarget=null,this.renderSurface=null}}class GlRenderTargetSystem extends RenderTargetSystem{constructor(renderer){super(renderer),this.adaptor=new GlRenderTargetAdaptor,this.adaptor.init(renderer,this)}}GlRenderTargetSystem.extension={type:["webgl-system"],name:"renderTarget"};class BufferResource extends EventEmitter{constructor({buffer,offset,size}){super(),this.uid=uid$1("buffer"),this._resourceType="bufferResource",this._touched=0,this._resourceId=uid$1("resource"),this._bufferResource=!0,this.destroyed=!1,this.buffer=buffer,this.offset=0|offset,this.size=size,this.buffer.on("change",this.onBufferChange,this)}onBufferChange(){this._resourceId=uid$1("resource"),this.emit("change",this)}destroy(destroyBuffer=!1){this.destroyed=!0,destroyBuffer&&this.buffer.destroy(),this.emit("change",this),this.buffer=null}}class GlProgramData{constructor(program,uniformData){this.program=program,this.uniformData=uniformData,this.uniformGroups={},this.uniformDirtyGroups={},this.uniformBlockBindings={}}destroy(){this.uniformData=null,this.uniformGroups=null,this.uniformDirtyGroups=null,this.uniformBlockBindings=null,this.program=null}}function compileShader(gl,type,src){return type=gl.createShader(type),gl.shaderSource(type,src),gl.compileShader(type),type}function booleanArray(size){var array=new Array(size);for(let i=0;iindex+": "+line),dedupe=(shader=(gl=gl.getShaderInfoLog(shader)).split("\n"),{}),logArgs=(shader=shader.map(line=>parseFloat(line.replace(/^ERROR\: 0\:([\d]+)\:.*$/,"$1"))).filter(n=>!(!n||dedupe[n])&&(dedupe[n]=!0)),[""]);shader.forEach(number=>{shaderSrc[number-1]=`%c${shaderSrc[number-1]}%c`,logArgs.push("background: #FF0000; color:#FFFFFF; font-size: 10px","font-size: 10px")}),shader=shaderSrc.join("\n"),logArgs[0]=shader,console.error(gl),console.groupCollapsed("click to view full shader code"),console.warn(...logArgs),console.groupEnd()}const defaultSyncData={textureCount:0,blockIndex:0};class GlShaderSystem{constructor(renderer){this._activeProgram=null,this._programDataHash=Object.create(null),this._shaderSyncFunctions=Object.create(null),this._renderer=renderer,this._renderer.renderableGC.addManagedHash(this,"_programDataHash")}contextChange(gl){this._gl=gl,this._programDataHash=Object.create(null),this._shaderSyncFunctions=Object.create(null),this._activeProgram=null,this.maxTextures=getMaxTexturesPerBatch()}bind(shader,skipSync){this._setProgram(shader.glProgram),skipSync||(defaultSyncData.textureCount=0,defaultSyncData.blockIndex=0,skipSync=(skipSync=this._shaderSyncFunctions[shader.glProgram._key])||(this._shaderSyncFunctions[shader.glProgram._key]=this._generateShaderSync(shader,this)),this._renderer.buffer.nextBindBase(!!shader.glProgram.transformFeedbackVaryings),skipSync(this._renderer,shader,defaultSyncData))}updateUniformGroup(uniformGroup){this._renderer.uniformGroup.updateUniformGroup(uniformGroup,this._activeProgram,defaultSyncData)}bindUniformBlock(uniformGroup,name,index=0){var bufferSystem=this._renderer.buffer,programData=this._getProgramData(this._activeProgram),isBufferResource=uniformGroup._bufferResource,buffer=(isBufferResource||this._renderer.ubo.updateUniformGroup(uniformGroup),uniformGroup.buffer),glBuffer=bufferSystem.updateBuffer(buffer),boundLocation=bufferSystem.freeLocationForBufferBase(glBuffer),uniformGroup=(isBufferResource?({offset:isBufferResource,size:uniformGroup}=uniformGroup,0===isBufferResource&&uniformGroup===buffer.data.byteLength?bufferSystem.bindBufferBase(glBuffer,boundLocation):bufferSystem.bindBufferRange(glBuffer,boundLocation,isBufferResource)):bufferSystem.getLastBindBaseLocation(glBuffer)!==boundLocation&&bufferSystem.bindBufferBase(glBuffer,boundLocation),this._activeProgram._uniformBlockData[name].index);programData.uniformBlockBindings[index]!==boundLocation&&(programData.uniformBlockBindings[index]=boundLocation,this._renderer.gl.uniformBlockBinding(programData.program,uniformGroup,boundLocation))}_setProgram(program){this._activeProgram!==program&&(this._activeProgram=program,program=this._getProgramData(program),this._gl.useProgram(program.program))}_getProgramData(program){return this._programDataHash[program._key]||this._createProgramData(program)}_createProgramData(program){var key=program._key;return this._programDataHash[key]=function(gl,program){var glVertShader=compileShader(gl,gl.VERTEX_SHADER,program.vertex),glFragShader=compileShader(gl,gl.FRAGMENT_SHADER,program.fragment),webGLProgram=gl.createProgram(),transformFeedbackVaryings=(gl.attachShader(webGLProgram,glVertShader),gl.attachShader(webGLProgram,glFragShader),program.transformFeedbackVaryings),uniformData=(transformFeedbackVaryings&&("function"!=typeof gl.transformFeedbackVaryings?warn("TransformFeedback is not supported but TransformFeedbackVaryings are given."):gl.transformFeedbackVaryings(webGLProgram,transformFeedbackVaryings.names,"separate"===transformFeedbackVaryings.bufferMode?gl.SEPARATE_ATTRIBS:gl.INTERLEAVED_ATTRIBS)),gl.linkProgram(webGLProgram),gl.getProgramParameter(webGLProgram,gl.LINK_STATUS)||function(gl,program,vertexShader,fragmentShader){gl.getProgramParameter(program,gl.LINK_STATUS)||(gl.getShaderParameter(vertexShader,gl.COMPILE_STATUS)||logPrettyShaderError(gl,vertexShader),gl.getShaderParameter(fragmentShader,gl.COMPILE_STATUS)||logPrettyShaderError(gl,fragmentShader),console.error("PixiJS Error: Could not initialize shader."),""!==gl.getProgramInfoLog(program)&&console.warn("PixiJS Warning: gl.getProgramInfoLog()",gl.getProgramInfoLog(program)))}(gl,webGLProgram,glVertShader,glFragShader),program._attributeData=function(program,gl,sortAttributes){var attributes={},totalAttributes=gl.getProgramParameter(program,gl.ACTIVE_ATTRIBUTES);for(let i=0;ib":`if (cv[0] !== v[0] || cv[1] !== v[1]) { + cv[0] = v[0]; + cv[1] = v[1]; + gl.uniform2f(location, v[0], v[1]); + }`,"vec3":`if (cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2]) { + cv[0] = v[0]; + cv[1] = v[1]; + cv[2] = v[2]; + gl.uniform3f(location, v[0], v[1], v[2]); + }`,"vec4":`if (cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2] || cv[3] !== v[3]) { + cv[0] = v[0]; + cv[1] = v[1]; + cv[2] = v[2]; + cv[3] = v[3]; + gl.uniform4f(location, v[0], v[1], v[2], v[3]); + }`,i32:`if (cv !== v) { + cu.value = v; + gl.uniform1i(location, v); + }`,"vec2":`if (cv[0] !== v[0] || cv[1] !== v[1]) { + cv[0] = v[0]; + cv[1] = v[1]; + gl.uniform2i(location, v[0], v[1]); + }`,"vec3":`if (cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2]) { + cv[0] = v[0]; + cv[1] = v[1]; + cv[2] = v[2]; + gl.uniform3i(location, v[0], v[1], v[2]); + }`,"vec4":`if (cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2] || cv[3] !== v[3]) { + cv[0] = v[0]; + cv[1] = v[1]; + cv[2] = v[2]; + cv[3] = v[3]; + gl.uniform4i(location, v[0], v[1], v[2], v[3]); + }`,u32:`if (cv !== v) { + cu.value = v; + gl.uniform1ui(location, v); + }`,"vec2":`if (cv[0] !== v[0] || cv[1] !== v[1]) { + cv[0] = v[0]; + cv[1] = v[1]; + gl.uniform2ui(location, v[0], v[1]); + }`,"vec3":`if (cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2]) { + cv[0] = v[0]; + cv[1] = v[1]; + cv[2] = v[2]; + gl.uniform3ui(location, v[0], v[1], v[2]); + }`,"vec4":`if (cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2] || cv[3] !== v[3]) { + cv[0] = v[0]; + cv[1] = v[1]; + cv[2] = v[2]; + cv[3] = v[3]; + gl.uniform4ui(location, v[0], v[1], v[2], v[3]); + }`,bool:`if (cv !== v) { + cu.value = v; + gl.uniform1i(location, v); + }`,"vec2":`if (cv[0] !== v[0] || cv[1] !== v[1]) { + cv[0] = v[0]; + cv[1] = v[1]; + gl.uniform2i(location, v[0], v[1]); + }`,"vec3":`if (cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2]) { + cv[0] = v[0]; + cv[1] = v[1]; + cv[2] = v[2]; + gl.uniform3i(location, v[0], v[1], v[2]); + }`,"vec4":`if (cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2] || cv[3] !== v[3]) { + cv[0] = v[0]; + cv[1] = v[1]; + cv[2] = v[2]; + cv[3] = v[3]; + gl.uniform4i(location, v[0], v[1], v[2], v[3]); + }`,"mat2x2":"gl.uniformMatrix2fv(location, false, v);","mat3x3":"gl.uniformMatrix3fv(location, false, v);","mat4x4":"gl.uniformMatrix4fv(location, false, v);"},UNIFORM_TO_ARRAY_SETTERS={f32:"gl.uniform1fv(location, v);","vec2":"gl.uniform2fv(location, v);","vec3":"gl.uniform3fv(location, v);","vec4":"gl.uniform4fv(location, v);","mat2x2":"gl.uniformMatrix2fv(location, false, v);","mat3x3":"gl.uniformMatrix3fv(location, false, v);","mat4x4":"gl.uniformMatrix4fv(location, false, v);",i32:"gl.uniform1iv(location, v);","vec2":"gl.uniform2iv(location, v);","vec3":"gl.uniform3iv(location, v);","vec4":"gl.uniform4iv(location, v);",u32:"gl.uniform1iv(location, v);","vec2":"gl.uniform2iv(location, v);","vec3":"gl.uniform3iv(location, v);","vec4":"gl.uniform4iv(location, v);",bool:"gl.uniform1iv(location, v);","vec2":"gl.uniform2iv(location, v);","vec3":"gl.uniform3iv(location, v);","vec4":"gl.uniform4iv(location, v);"};class GlUniformGroupSystem{constructor(renderer){this._cache={},this._uniformGroupSyncHash={},this._renderer=renderer,this.gl=null,this._cache={}}contextChange(gl){this.gl=gl}updateUniformGroup(group,program,syncData){var programData=this._renderer.shader._getProgramData(program);group.isStatic&&group._dirtyId===programData.uniformDirtyGroups[group.uid]||(programData.uniformDirtyGroups[group.uid]=group._dirtyId,this._getUniformSyncFunction(group,program)(programData.uniformData,group.uniforms,this._renderer,syncData))}_getUniformSyncFunction(group,program){var _a;return(null==(_a=this._uniformGroupSyncHash[group._signature])?void 0:_a[program._key])||this._createUniformSyncFunction(group,program)}_createUniformSyncFunction(group,program){var uniformGroupSyncHash=this._uniformGroupSyncHash[group._signature]||(this._uniformGroupSyncHash[group._signature]={}),id=this._getSignature(group,program._uniformData,"u");return this._cache[id]||(this._cache[id]=this._generateUniformsSync(group,program._uniformData)),uniformGroupSyncHash[program._key]=this._cache[id],uniformGroupSyncHash[program._key]}_generateUniformsSync(group,uniformData){var funcFragments=[` + var v = null; + var cv = null; + var cu = null; + var t = 0; + var gl = renderer.gl; + var name = null; + `];for(const i in group.uniforms)if(uniformData[i]){var template,uniform=group.uniformStructures[i];let parsed=!1;for(let j=0;j>=1,i++;this.stateId=state.data}for(let i=0;i>1,1),mipHeight=Math.max(mipHeight>>1,1)}}},glUploadImageResource={id:"image",upload(source,glTexture,gl,webGLVersion){var glWidth=glTexture.width,glHeight=glTexture.height,textureWidth=source.pixelWidth,textureHeight=source.pixelHeight,resourceWidth=source.resourceWidth,resourceHeight=source.resourceHeight;resourceWidthkey in obj?__defProp$j(obj,key,{enumerable:!0,configurable:!0,writable:!0,value:value}):obj[key]=value,__spreadValues$j=(a,b)=>{for(var prop in b=b||{})__hasOwnProp$j.call(b,prop)&&__defNormalProp$j(a,prop,b[prop]);if(__getOwnPropSymbols$j)for(var prop of __getOwnPropSymbols$j(b))__propIsEnum$j.call(b,prop)&&__defNormalProp$j(a,prop,b[prop]);return a};class GlTextureSystem{constructor(renderer){this.managedTextures=[],this._glTextures=Object.create(null),this._glSamplers=Object.create(null),this._boundTextures=[],this._activeTextureLocation=-1,this._boundSamplers=Object.create(null),this._uploads={image:glUploadImageResource,buffer:glUploadBufferImageResource,video:glUploadVideoResource,compressed:glUploadCompressedTextureResource},this._premultiplyAlpha=!1,this._useSeparateSamplers=!1,this._renderer=renderer,this._renderer.renderableGC.addManagedHash(this,"_glTextures"),this._renderer.renderableGC.addManagedHash(this,"_glSamplers")}contextChange(gl){this._gl=gl,this._mapFormatToInternalFormat||(this._mapFormatToInternalFormat=function(gl,extensions){let srgb={},bgra8unorm=gl.RGBA;return gl instanceof DOMAdapter.get().getWebGLRenderingContext()?extensions.srgb&&(srgb={"rgba8unorm-srgb":extensions.srgb.SRGB8_ALPHA8_EXT,"bgra8unorm-srgb":extensions.srgb.SRGB8_ALPHA8_EXT}):(srgb={"rgba8unorm-srgb":gl.SRGB8_ALPHA8,"bgra8unorm-srgb":gl.SRGB8_ALPHA8},bgra8unorm=gl.RGBA8),__spreadValues$j(__spreadValues$j(__spreadValues$j(__spreadValues$j(__spreadValues$j(__spreadValues$j((a=__spreadValues$j({r8unorm:gl.R8,r8snorm:gl.R8_SNORM,r8uint:gl.R8UI,r8sint:gl.R8I,r16uint:gl.R16UI,r16sint:gl.R16I,r16float:gl.R16F,rg8unorm:gl.RG8,rg8snorm:gl.RG8_SNORM,rg8uint:gl.RG8UI,rg8sint:gl.RG8I,r32uint:gl.R32UI,r32sint:gl.R32I,r32float:gl.R32F,rg16uint:gl.RG16UI,rg16sint:gl.RG16I,rg16float:gl.RG16F,rgba8unorm:gl.RGBA},srgb),gl={rgba8snorm:gl.RGBA8_SNORM,rgba8uint:gl.RGBA8UI,rgba8sint:gl.RGBA8I,bgra8unorm:bgra8unorm,rgb9e5ufloat:gl.RGB9_E5,rgb10a2unorm:gl.RGB10_A2,rg11b10ufloat:gl.R11F_G11F_B10F,rg32uint:gl.RG32UI,rg32sint:gl.RG32I,rg32float:gl.RG32F,rgba16uint:gl.RGBA16UI,rgba16sint:gl.RGBA16I,rgba16float:gl.RGBA16F,rgba32uint:gl.RGBA32UI,rgba32sint:gl.RGBA32I,rgba32float:gl.RGBA32F,stencil8:gl.STENCIL_INDEX8,depth16unorm:gl.DEPTH_COMPONENT16,depth24plus:gl.DEPTH_COMPONENT24,"depth24plus-stencil8":gl.DEPTH24_STENCIL8,depth32float:gl.DEPTH_COMPONENT32F,"depth32float-stencil8":gl.DEPTH32F_STENCIL8},__defProps$8(a,__getOwnPropDescs$8(gl))),extensions.s3tc?{"bc1-rgba-unorm":extensions.s3tc.COMPRESSED_RGBA_S3TC_DXT1_EXT,"bc2-rgba-unorm":extensions.s3tc.COMPRESSED_RGBA_S3TC_DXT3_EXT,"bc3-rgba-unorm":extensions.s3tc.COMPRESSED_RGBA_S3TC_DXT5_EXT}:{}),extensions.s3tc_sRGB?{"bc1-rgba-unorm-srgb":extensions.s3tc_sRGB.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT,"bc2-rgba-unorm-srgb":extensions.s3tc_sRGB.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT,"bc3-rgba-unorm-srgb":extensions.s3tc_sRGB.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}:{}),extensions.rgtc?{"bc4-r-unorm":extensions.rgtc.COMPRESSED_RED_RGTC1_EXT,"bc4-r-snorm":extensions.rgtc.COMPRESSED_SIGNED_RED_RGTC1_EXT,"bc5-rg-unorm":extensions.rgtc.COMPRESSED_RED_GREEN_RGTC2_EXT,"bc5-rg-snorm":extensions.rgtc.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT}:{}),extensions.bptc?{"bc6h-rgb-float":extensions.bptc.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT,"bc6h-rgb-ufloat":extensions.bptc.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT,"bc7-rgba-unorm":extensions.bptc.COMPRESSED_RGBA_BPTC_UNORM_EXT,"bc7-rgba-unorm-srgb":extensions.bptc.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT}:{}),extensions.etc?{"etc2-rgb8unorm":extensions.etc.COMPRESSED_RGB8_ETC2,"etc2-rgb8unorm-srgb":extensions.etc.COMPRESSED_SRGB8_ETC2,"etc2-rgb8a1unorm":extensions.etc.COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2,"etc2-rgb8a1unorm-srgb":extensions.etc.COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2,"etc2-rgba8unorm":extensions.etc.COMPRESSED_RGBA8_ETC2_EAC,"etc2-rgba8unorm-srgb":extensions.etc.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC,"eac-r11unorm":extensions.etc.COMPRESSED_R11_EAC,"eac-rg11unorm":extensions.etc.COMPRESSED_SIGNED_RG11_EAC}:{}),extensions.astc?{"astc-4x4-unorm":extensions.astc.COMPRESSED_RGBA_ASTC_4x4_KHR,"astc-4x4-unorm-srgb":extensions.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR,"astc-5x4-unorm":extensions.astc.COMPRESSED_RGBA_ASTC_5x4_KHR,"astc-5x4-unorm-srgb":extensions.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR,"astc-5x5-unorm":extensions.astc.COMPRESSED_RGBA_ASTC_5x5_KHR,"astc-5x5-unorm-srgb":extensions.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR,"astc-6x5-unorm":extensions.astc.COMPRESSED_RGBA_ASTC_6x5_KHR,"astc-6x5-unorm-srgb":extensions.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR,"astc-6x6-unorm":extensions.astc.COMPRESSED_RGBA_ASTC_6x6_KHR,"astc-6x6-unorm-srgb":extensions.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR,"astc-8x5-unorm":extensions.astc.COMPRESSED_RGBA_ASTC_8x5_KHR,"astc-8x5-unorm-srgb":extensions.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR,"astc-8x6-unorm":extensions.astc.COMPRESSED_RGBA_ASTC_8x6_KHR,"astc-8x6-unorm-srgb":extensions.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR,"astc-8x8-unorm":extensions.astc.COMPRESSED_RGBA_ASTC_8x8_KHR,"astc-8x8-unorm-srgb":extensions.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR,"astc-10x5-unorm":extensions.astc.COMPRESSED_RGBA_ASTC_10x5_KHR,"astc-10x5-unorm-srgb":extensions.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR,"astc-10x6-unorm":extensions.astc.COMPRESSED_RGBA_ASTC_10x6_KHR,"astc-10x6-unorm-srgb":extensions.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR,"astc-10x8-unorm":extensions.astc.COMPRESSED_RGBA_ASTC_10x8_KHR,"astc-10x8-unorm-srgb":extensions.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR,"astc-10x10-unorm":extensions.astc.COMPRESSED_RGBA_ASTC_10x10_KHR,"astc-10x10-unorm-srgb":extensions.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR,"astc-12x10-unorm":extensions.astc.COMPRESSED_RGBA_ASTC_12x10_KHR,"astc-12x10-unorm-srgb":extensions.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR,"astc-12x12-unorm":extensions.astc.COMPRESSED_RGBA_ASTC_12x12_KHR,"astc-12x12-unorm-srgb":extensions.astc.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR}:{});var a}(gl,this._renderer.context.extensions),this._mapFormatToType=function(gl){return{r8unorm:gl.UNSIGNED_BYTE,r8snorm:gl.BYTE,r8uint:gl.UNSIGNED_BYTE,r8sint:gl.BYTE,r16uint:gl.UNSIGNED_SHORT,r16sint:gl.SHORT,r16float:gl.HALF_FLOAT,rg8unorm:gl.UNSIGNED_BYTE,rg8snorm:gl.BYTE,rg8uint:gl.UNSIGNED_BYTE,rg8sint:gl.BYTE,r32uint:gl.UNSIGNED_INT,r32sint:gl.INT,r32float:gl.FLOAT,rg16uint:gl.UNSIGNED_SHORT,rg16sint:gl.SHORT,rg16float:gl.HALF_FLOAT,rgba8unorm:gl.UNSIGNED_BYTE,"rgba8unorm-srgb":gl.UNSIGNED_BYTE,rgba8snorm:gl.BYTE,rgba8uint:gl.UNSIGNED_BYTE,rgba8sint:gl.BYTE,bgra8unorm:gl.UNSIGNED_BYTE,"bgra8unorm-srgb":gl.UNSIGNED_BYTE,rgb9e5ufloat:gl.UNSIGNED_INT_5_9_9_9_REV,rgb10a2unorm:gl.UNSIGNED_INT_2_10_10_10_REV,rg11b10ufloat:gl.UNSIGNED_INT_10F_11F_11F_REV,rg32uint:gl.UNSIGNED_INT,rg32sint:gl.INT,rg32float:gl.FLOAT,rgba16uint:gl.UNSIGNED_SHORT,rgba16sint:gl.SHORT,rgba16float:gl.HALF_FLOAT,rgba32uint:gl.UNSIGNED_INT,rgba32sint:gl.INT,rgba32float:gl.FLOAT,stencil8:gl.UNSIGNED_BYTE,depth16unorm:gl.UNSIGNED_SHORT,depth24plus:gl.UNSIGNED_INT,"depth24plus-stencil8":gl.UNSIGNED_INT_24_8,depth32float:gl.FLOAT,"depth32float-stencil8":gl.FLOAT_32_UNSIGNED_INT_24_8_REV}}(gl),this._mapFormatToFormat=function(gl){return{r8unorm:gl.RED,r8snorm:gl.RED,r8uint:gl.RED,r8sint:gl.RED,r16uint:gl.RED,r16sint:gl.RED,r16float:gl.RED,rg8unorm:gl.RG,rg8snorm:gl.RG,rg8uint:gl.RG,rg8sint:gl.RG,r32uint:gl.RED,r32sint:gl.RED,r32float:gl.RED,rg16uint:gl.RG,rg16sint:gl.RG,rg16float:gl.RG,rgba8unorm:gl.RGBA,"rgba8unorm-srgb":gl.RGBA,rgba8snorm:gl.RGBA,rgba8uint:gl.RGBA,rgba8sint:gl.RGBA,bgra8unorm:gl.RGBA,"bgra8unorm-srgb":gl.RGBA,rgb9e5ufloat:gl.RGB,rgb10a2unorm:gl.RGBA,rg11b10ufloat:gl.RGB,rg32uint:gl.RG,rg32sint:gl.RG,rg32float:gl.RG,rgba16uint:gl.RGBA,rgba16sint:gl.RGBA,rgba16float:gl.RGBA,rgba32uint:gl.RGBA,rgba32sint:gl.RGBA,rgba32float:gl.RGBA,stencil8:gl.STENCIL_INDEX8,depth16unorm:gl.DEPTH_COMPONENT,depth24plus:gl.DEPTH_COMPONENT,"depth24plus-stencil8":gl.DEPTH_STENCIL,depth32float:gl.DEPTH_COMPONENT,"depth32float-stencil8":gl.DEPTH_STENCIL}}(gl)),this._glTextures=Object.create(null),this._glSamplers=Object.create(null),this._boundSamplers=Object.create(null),this._premultiplyAlpha=!1;for(let i=0;i<16;i++)this.bind(Texture.EMPTY,i)}initSource(source){this.bind(source)}bind(texture,location=0){var source=texture.source;texture?(this.bindSource(source,location),this._useSeparateSamplers&&this._bindSampler(source.style,location)):(this.bindSource(null,location),this._useSeparateSamplers&&this._bindSampler(null,location))}bindSource(source,location=0){var gl=this._gl;source._touched=this._renderer.textureGC.count,this._boundTextures[location]!==source&&(this._boundTextures[location]=source,this._activateLocation(location),source=source||Texture.EMPTY.source,location=this.getGlSource(source),gl.bindTexture(location.target,location.texture))}_bindSampler(style,location=0){var gl=this._gl;style?(style=this._getGlSampler(style),this._boundSamplers[location]!==style&&(this._boundSamplers[location]=style,gl.bindSampler(location,style))):(this._boundSamplers[location]=null,gl.bindSampler(location,null))}unbind(texture){var glTexture,source=texture.source,boundTextures=this._boundTextures,gl=this._gl;for(let i=0;ithis.onSourceDestroy(source)),this.managedTextures=null,this._renderer=null}resetState(){this._activeTextureLocation=-1,this._boundTextures.fill(Texture.EMPTY.source),this._boundSamplers=Object.create(null);var gl=this._gl;this._premultiplyAlpha=!1,gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL,this._premultiplyAlpha)}}GlTextureSystem.extension={type:["webgl-system"],name:"texture"};class GlGraphicsAdaptor{init(){var uniforms=new UniformGroup({uColor:{value:new Float32Array([1,1,1,1]),type:"vec4"},uTransformMatrix:{value:new Matrix,type:"mat3x3"},uRound:{value:0,type:"f32"}}),maxTextures=getMaxTexturesPerBatch(),glProgram=compileHighShaderGlProgram({name:"graphics",bits:[colorBitGl,generateTextureBatchBitGl(maxTextures),localUniformBitGl,roundPixelsBitGl]});this.shader=new Shader({glProgram:glProgram,resources:{localUniforms:uniforms,batchSamplers:getBatchSamplersUniformGroup(maxTextures)}})}execute(graphicsPipe,renderable){var shader=(renderable=renderable.context).customShader||this.shader,renderer=graphicsPipe.renderer,{batcher:renderable,instructions}=renderer.graphicsContext.getContextRenderData(renderable),batches=(shader.groups[0]=renderer.globalUniforms.bindGroup,renderer.state.set(graphicsPipe.state),renderer.shader.bind(shader),renderer.geometry.bind(renderable.geometry,shader.glProgram),instructions.instructions);for(let i=0;i",value:new Matrix}}}})}execute(meshPipe,mesh){var renderer=meshPipe.renderer;let shader=mesh._shader;if(shader){if(!shader.glProgram)return void warn("Mesh shader has no glProgram",mesh.shader)}else{shader=this._shader;var texture=mesh.texture,source=texture.source;shader.resources.uTexture=source,shader.resources.uSampler=source.style,shader.resources.textureUniforms.uniforms.uTextureMatrix=texture.textureMatrix.mapCoord}shader.groups[100]=renderer.globalUniforms.bindGroup,shader.groups[101]=meshPipe.localUniformsBindGroup,renderer.encoder.draw({geometry:mesh._geometry,shader:shader,state:mesh.state})}destroy(){this._shader.destroy(!0),this._shader=null}}GlMeshAdaptor.extension={type:["webgl-pipes-adaptor"],name:"mesh"};class CustomRenderPipe{constructor(renderer){this._renderer=renderer}updateRenderable(){}destroyRenderable(){}validateRenderable(){return!1}addRenderable(container,instructionSet){this._renderer.renderPipes.batch.break(instructionSet),instructionSet.add(container)}execute(container){container.isRenderable&&container.render(this._renderer)}destroy(){this._renderer=null}}function executeInstructions(renderGroup,renderer){var instructionSet=renderGroup.instructionSet,instructions=instructionSet.instructions;for(let i=0;ikey in obj?__defProp$i(obj,key,{enumerable:!0,configurable:!0,writable:!0,value:value}):obj[key]=value,__spreadValues$i=(a,b)=>{for(var prop in b=b||{})__hasOwnProp$i.call(b,prop)&&__defNormalProp$i(a,prop,b[prop]);if(__getOwnPropSymbols$i)for(var prop of __getOwnPropSymbols$i(b))__propIsEnum$i.call(b,prop)&&__defNormalProp$i(a,prop,b[prop]);return a};const _BackgroundSystem=class _BackgroundSystem{constructor(){this.clearBeforeRender=!0,this._backgroundColor=new Color(0),this.color=this._backgroundColor,this.alpha=1}init(options){options=__spreadValues$i(__spreadValues$i({},_BackgroundSystem.defaultOptions),options),this.clearBeforeRender=options.clearBeforeRender,this.color=options.background||options.backgroundColor||this._backgroundColor,this.alpha=options.backgroundAlpha,this._backgroundColor.setAlpha(options.backgroundAlpha)}get color(){return this._backgroundColor}set color(value){this._backgroundColor.setValue(value)}get alpha(){return this._backgroundColor.alpha}set alpha(value){this._backgroundColor.setAlpha(value)}get colorRgba(){return this._backgroundColor.toArray()}destroy(){}},BLEND_MODE_FILTERS=(_BackgroundSystem.extension={type:["webgl-system","webgpu-system","canvas-system"],name:"background",priority:0},_BackgroundSystem.defaultOptions={backgroundAlpha:1,backgroundColor:0,clearBeforeRender:!0},ExtensionType2_Application=_BackgroundSystem,{});extensions.handle("blend-mode",value=>{if(!value.name)throw new Error("BlendMode extension must have a name property");BLEND_MODE_FILTERS[value.name]=value.ref},value=>{delete BLEND_MODE_FILTERS[value.name]});class BlendModePipe{constructor(renderer){this._isAdvanced=!1,this._filterHash=Object.create(null),this._renderer=renderer,this._renderer.runners.prerender.add(this)}prerender(){this._activeBlendMode="normal",this._isAdvanced=!1}setBlendMode(renderable,blendMode,instructionSet){this._activeBlendMode===blendMode?this._isAdvanced&&this._renderableList.push(renderable):(this._activeBlendMode=blendMode,this._isAdvanced&&this._endAdvancedBlendMode(instructionSet),this._isAdvanced=!!BLEND_MODE_FILTERS[blendMode],this._isAdvanced&&(this._beginAdvancedBlendMode(instructionSet),this._renderableList.push(renderable)))}_beginAdvancedBlendMode(instructionSet){this._renderer.renderPipes.batch.break(instructionSet);var blendMode=this._activeBlendMode;if(BLEND_MODE_FILTERS[blendMode]){let filterEffect=this._filterHash[blendMode];filterEffect||((filterEffect=this._filterHash[blendMode]=new FilterEffect).filters=[new BLEND_MODE_FILTERS[blendMode]]);var instruction={renderPipeId:"filter",action:"pushFilter",renderables:[],filterEffect:filterEffect,canBundle:!1};this._renderableList=instruction.renderables,instructionSet.add(instruction)}else warn(`Unable to assign BlendMode: '${blendMode}'. You may want to include: import 'pixi.js/advanced-blend-modes'`)}_endAdvancedBlendMode(instructionSet){this._renderableList=null,this._renderer.renderPipes.batch.break(instructionSet),instructionSet.add({renderPipeId:"filter",action:"popFilter",canBundle:!1})}buildStart(){this._isAdvanced=!1}buildEnd(instructionSet){this._isAdvanced&&this._endAdvancedBlendMode(instructionSet)}destroy(){this._renderer=null,this._renderableList=null;for(const i in this._filterHash)this._filterHash[i].destroy();this._filterHash=null}}BlendModePipe.extension={type:["webgl-pipes","webgpu-pipes","canvas-pipes"],name:"blendMode"};var __defProp$h=Object.defineProperty,__getOwnPropSymbols$h=Object.getOwnPropertySymbols,__hasOwnProp$h=Object.prototype.hasOwnProperty,__propIsEnum$h=Object.prototype.propertyIsEnumerable,__defNormalProp$h=(obj,key,value)=>key in obj?__defProp$h(obj,key,{enumerable:!0,configurable:!0,writable:!0,value:value}):obj[key]=value,__spreadValues$h=(a,b)=>{for(var prop in b=b||{})__hasOwnProp$h.call(b,prop)&&__defNormalProp$h(a,prop,b[prop]);if(__getOwnPropSymbols$h)for(var prop of __getOwnPropSymbols$h(b))__propIsEnum$h.call(b,prop)&&__defNormalProp$h(a,prop,b[prop]);return a};const imageTypes={png:"image/png",jpg:"image/jpeg",webp:"image/webp"},_ExtractSystem=class _ExtractSystem{constructor(renderer){this._renderer=renderer}_normalizeOptions(options,defaults={}){return options instanceof Container||options instanceof Texture?__spreadValues$h({target:options},defaults):__spreadValues$h(__spreadValues$h({},defaults),options)}async image(options){var image=new Image;return image.src=await this.base64(options),image}async base64(options){const{format,quality}=options=this._normalizeOptions(options,_ExtractSystem.defaultImageOptions),canvas=this.canvas(options);if(void 0!==canvas.toBlob)return new Promise((resolve,reject)=>{canvas.toBlob(blob=>{if(blob){const reader=new FileReader;reader.onload=()=>resolve(reader.result),reader.onerror=reject,reader.readAsDataURL(blob)}else reject(new Error("ICanvas.toBlob failed!"))},imageTypes[format],quality)});if(void 0!==canvas.toDataURL)return canvas.toDataURL(imageTypes[format],quality);if(void 0===canvas.convertToBlob)throw new Error("Extract.base64() requires ICanvas.toDataURL, ICanvas.toBlob, or ICanvas.convertToBlob to be implemented");{const blob=await canvas.convertToBlob({type:imageTypes[format],quality:quality});return new Promise((resolve,reject)=>{const reader=new FileReader;reader.onload=()=>resolve(reader.result),reader.onerror=reject,reader.readAsDataURL(blob)})}}canvas(options){var target=(options=this._normalizeOptions(options)).target,renderer=this._renderer;return target instanceof Texture?renderer.texture.generateCanvas(target):(target=renderer.textureGenerator.generateTexture(options),options=renderer.texture.generateCanvas(target),target.destroy(!0),options)}pixels(options){var target=(options=this._normalizeOptions(options)).target,renderer=this._renderer,options=target instanceof Texture?target:renderer.textureGenerator.generateTexture(options),renderer=renderer.texture.getPixels(options);return target instanceof Container&&options.destroy(!0),renderer}texture(options){return(options=this._normalizeOptions(options)).target instanceof Texture?options.target:this._renderer.textureGenerator.generateTexture(options)}download(options){options=this._normalizeOptions(options);var canvas=this.canvas(options),link=document.createElement("a");link.download=null!=(options=options.filename)?options:"image.png",link.href=canvas.toDataURL("image/png"),document.body.appendChild(link),link.click(),document.body.removeChild(link)}log(options){var _a=null!=(_a=options.width)?_a:200,base64=(options=this._normalizeOptions(options),(options=this.canvas(options)).toDataURL()),options=(console.log(`[Pixi Texture] ${options.width}px ${options.height}px`),["font-size: 1px;",`padding: ${_a}px 300px;`,`background: url(${base64}) no-repeat;`,"background-size: contain;"].join(" "));console.log("%c ",options)}destroy(){this._renderer=null}};_ExtractSystem.extension={type:["webgl-system","webgpu-system"],name:"extract"},_ExtractSystem.defaultImageOptions={format:"png",quality:1},Assets=_ExtractSystem;class RenderTexture extends Texture{static create(options){return new RenderTexture({source:new TextureSource(options)})}resize(width,height,resolution){return this.source.resize(width,height,resolution),this}}var __defProp$g=Object.defineProperty,__defProps$7=Object.defineProperties,__getOwnPropDescs$7=Object.getOwnPropertyDescriptors,__getOwnPropSymbols$g=Object.getOwnPropertySymbols,__hasOwnProp$g=Object.prototype.hasOwnProperty,__propIsEnum$g=Object.prototype.propertyIsEnumerable,__defNormalProp$g=(obj,key,value)=>key in obj?__defProp$g(obj,key,{enumerable:!0,configurable:!0,writable:!0,value:value}):obj[key]=value;const tempRect=new Rectangle,tempBounds=new Bounds,noColor=[0,0,0,0];class GenerateTextureSystem{constructor(renderer){this._renderer=renderer}generateTexture(options){var resolution=(options=options instanceof Container?{target:options,frame:void 0,textureSourceOptions:{},resolution:void 0}:options).resolution||this._renderer.resolution,antialias=options.antialias||this._renderer.view.antialias,container=options.target,clearColor=(clearColor=options.clearColor)?Array.isArray(clearColor)&&4===clearColor.length?clearColor:Color.shared.setValue(clearColor).toArray():noColor,_a=(null==(_a=options.frame)?void 0:_a.copyTo(tempRect))||getLocalBounds(container,tempBounds).rectangle,antialias=(_a.width=0|Math.max(_a.width,1/resolution),_a.height=0|Math.max(_a.height,1/resolution),RenderTexture.create((options=((a,b)=>{for(var prop in b=options.textureSourceOptions||{})__hasOwnProp$g.call(b,prop)&&__defNormalProp$g(a,prop,b[prop]);if(__getOwnPropSymbols$g)for(var prop of __getOwnPropSymbols$g(b))__propIsEnum$g.call(b,prop)&&__defNormalProp$g(a,prop,b[prop]);return a})({}),resolution={width:_a.width,height:_a.height,resolution:resolution,antialias:antialias},__defProps$7(options,__getOwnPropDescs$7(resolution))))),options=Matrix.shared.translate(-_a.x,-_a.y);return this._renderer.render({container:container,transform:options,target:antialias,clearColor:clearColor}),antialias.source.updateMipmaps(),antialias}destroy(){this._renderer=null}}GenerateTextureSystem.extension={type:["webgl-system","webgpu-system"],name:"textureGenerator"};class GlobalUniformSystem{constructor(renderer){this._stackIndex=0,this._globalUniformDataStack=[],this._uniformsPool=[],this._activeUniforms=[],this._bindGroupPool=[],this._activeBindGroups=[],this._renderer=renderer}reset(){for(let i=this._stackIndex=0;i"},uWorldTransformMatrix:{value:new Matrix,type:"mat3x3"},uWorldColorAlpha:{value:new Float32Array(4),type:"vec4"},uResolution:{value:[0,0],type:"vec2"}},{isStatic:!0})}destroy(){this._renderer=null}}GlobalUniformSystem.extension={type:["webgl-system","webgpu-system","canvas-system"],name:"globalUniforms"};let uid=1;class SchedulerSystem{constructor(){this._tasks=[],this._offset=0}init(){Ticker.system.add(this._update,this)}repeat(func,duration,useOffset=!0){var id=uid++;let offset=0;return useOffset&&(this._offset+=1e3,offset=this._offset),this._tasks.push({func:func,duration:duration,start:performance.now(),offset:offset,last:performance.now(),repeat:!0,id:id}),id}cancel(id){for(let i=0;i=task.duration&&(elapsed=now-task.start,task.func(elapsed),task.last=now)}}destroy(){Ticker.system.remove(this._update,this),this._tasks.length=0}}let saidHello=!(SchedulerSystem.extension={type:["webgl-system","webgpu-system","canvas-system"],name:"scheduler",priority:0});class HelloSystem{constructor(renderer){this._renderer=renderer}init(options){if(options.hello){let name=this._renderer.name;1===this._renderer.type&&(name+=" "+this._renderer.context.webGLVersion),options=name,saidHello||(-1key in obj?__defProp$f(obj,key,{enumerable:!0,configurable:!0,writable:!0,value:value}):obj[key]=value,__spreadValues$f=(a,b)=>{for(var prop in b=b||{})__hasOwnProp$f.call(b,prop)&&__defNormalProp$f(a,prop,b[prop]);if(__getOwnPropSymbols$f)for(var prop of __getOwnPropSymbols$f(b))__propIsEnum$f.call(b,prop)&&__defNormalProp$f(a,prop,b[prop]);return a};let renderableGCTick=0;const _RenderableGCSystem=class _RenderableGCSystem{constructor(renderer){this._managedRenderables=[],this._managedHashes=[],this._managedArrays=[],this._renderer=renderer}init(options){options=__spreadValues$f(__spreadValues$f({},_RenderableGCSystem.defaultOptions),options),this.maxUnusedTime=options.renderableGCMaxUnusedTime,this._frequency=options.renderableGCFrequency,this.enabled=options.renderableGCActive}get enabled(){return!!this._handler}set enabled(value){this.enabled!==value&&(value?(this._handler=this._renderer.scheduler.repeat(()=>this.run(),this._frequency,!1),this._hashHandler=this._renderer.scheduler.repeat(()=>{for(const hash of this._managedHashes)hash.context[hash.hash]=function(hash){let clean=!1;for(const i in hash)if(null==hash[i]){clean=!0;break}if(!clean)return hash;var cleanHash2=Object.create(null);for(const i in hash){var value=hash[i];value&&(cleanHash2[i]=value)}return cleanHash2}(hash.context[hash.hash])},this._frequency),this._arrayHandler=this._renderer.scheduler.repeat(()=>{for(const array of this._managedArrays){var arr=void 0,arr=array.context[array.hash];let offset=0;for(let i=0;ithis.maxUnusedTime?(renderable.destroyed||(_d=renderPipes,_a&&(_a.structureDidChange=!0),_d[renderable.renderPipeId].destroyRenderable(renderable)),renderable._lastUsed=-1,offset++,renderable.off("destroyed",this._removeRenderable,this)):managedRenderables[i-offset]=renderable)}managedRenderables.length-=offset}destroy(){this.enabled=!1,this._renderer=null,this._managedRenderables.length=0,this._managedHashes.length=0,this._managedArrays.length=0}_removeRenderable(renderable){var index=this._managedRenderables.indexOf(renderable);0<=index&&(renderable.off("destroyed",this._removeRenderable,this),this._managedRenderables[index]=null)}_updateInstructionGCTick(renderGroup,gcTick){renderGroup.instructionSet.gcTick=gcTick;for(const child of renderGroup.renderGroupChildren)this._updateInstructionGCTick(child,gcTick)}};_RenderableGCSystem.extension={type:["webgl-system","webgpu-system"],name:"renderableGC",priority:0},_RenderableGCSystem.defaultOptions={renderableGCActive:!0,renderableGCMaxUnusedTime:6e4,renderableGCFrequency:3e4};var onRenderMixin=_RenderableGCSystem,__defProp$e=Object.defineProperty,__getOwnPropSymbols$e=Object.getOwnPropertySymbols,__hasOwnProp$e=Object.prototype.hasOwnProperty,__propIsEnum$e=Object.prototype.propertyIsEnumerable,__defNormalProp$e=(obj,key,value)=>key in obj?__defProp$e(obj,key,{enumerable:!0,configurable:!0,writable:!0,value:value}):obj[key]=value,__spreadValues$e=(a,b)=>{for(var prop in b=b||{})__hasOwnProp$e.call(b,prop)&&__defNormalProp$e(a,prop,b[prop]);if(__getOwnPropSymbols$e)for(var prop of __getOwnPropSymbols$e(b))__propIsEnum$e.call(b,prop)&&__defNormalProp$e(a,prop,b[prop]);return a};const _TextureGCSystem=class _TextureGCSystem{constructor(renderer){this._renderer=renderer,this.count=0,this.checkCount=0}init(options){var _a;options=__spreadValues$e(__spreadValues$e({},_TextureGCSystem.defaultOptions),options),this.checkCountMax=options.textureGCCheckCountMax,this.maxIdle=null!=(_a=options.textureGCAMaxIdle)?_a:options.textureGCMaxIdle,this.active=options.textureGCActive}postrender(){this._renderer.renderingToScreen&&(this.count++,this.active)&&(this.checkCount++,this.checkCount>this.checkCountMax)&&(this.checkCount=0,this.run())}run(){var managedTextures=this._renderer.texture.managedTextures;for(let i=0;ithis.maxIdle&&(texture._touched=-1,texture.unload())}}destroy(){this._renderer=null}};_TextureGCSystem.extension={type:["webgl-system","webgpu-system"],name:"textureGC"},_TextureGCSystem.defaultOptions={textureGCActive:!0,textureGCAMaxIdle:null,textureGCMaxIdle:3600,textureGCCheckCountMax:600};var collectRenderablesMixin=_TextureGCSystem,__defProp$d=Object.defineProperty,__getOwnPropSymbols$d=Object.getOwnPropertySymbols,__hasOwnProp$d=Object.prototype.hasOwnProperty,__propIsEnum$d=Object.prototype.propertyIsEnumerable,__defNormalProp$d=(obj,key,value)=>key in obj?__defProp$d(obj,key,{enumerable:!0,configurable:!0,writable:!0,value:value}):obj[key]=value,__spreadValues$d=(a,b)=>{for(var prop in b=b||{})__hasOwnProp$d.call(b,prop)&&__defNormalProp$d(a,prop,b[prop]);if(__getOwnPropSymbols$d)for(var prop of __getOwnPropSymbols$d(b))__propIsEnum$d.call(b,prop)&&__defNormalProp$d(a,prop,b[prop]);return a};const _ViewSystem=class _ViewSystem{get autoDensity(){return this.texture.source.autoDensity}set autoDensity(value){this.texture.source.autoDensity=value}get resolution(){return this.texture.source._resolution}set resolution(value){this.texture.source.resize(this.texture.source.width,this.texture.source.height,value)}init(options){(options=__spreadValues$d(__spreadValues$d({},_ViewSystem.defaultOptions),options)).view&&(deprecation(v8_0_0,"ViewSystem.view has been renamed to ViewSystem.canvas"),options.canvas=options.view),this.screen=new Rectangle(0,0,options.width,options.height),this.canvas=options.canvas||DOMAdapter.get().createCanvas(),this.antialias=!!options.antialias,this.texture=getCanvasTexture(this.canvas,options),this.renderTarget=new RenderTarget({colorTextures:[this.texture],depth:!!options.depth,isRoot:!0}),this.texture.source.transparent=options.backgroundAlpha<1,this.resolution=options.resolution}resize(desiredScreenWidth,desiredScreenHeight,resolution){this.texture.source.resize(desiredScreenWidth,desiredScreenHeight,resolution),this.screen.width=this.texture.frame.width,this.screen.height=this.texture.frame.height}destroy(options=!1){("boolean"==typeof options?options:null!=options&&options.removeView)&&this.canvas.parentNode&&this.canvas.parentNode.removeChild(this.canvas)}},systems$1=(_ViewSystem.extension={type:["webgl-system","webgpu-system","canvas-system"],name:"view",priority:0},_ViewSystem.defaultOptions={width:800,height:600,autoDensity:!1,antialias:!1},eventemitter3$1=_ViewSystem,NOOP=[BlendModePipe,getFastGlobalBoundsMixin,SpritePipe,RenderGroupPipe,AlphaMaskPipe,StencilMaskPipe,ColorMaskPipe,CustomRenderPipe],effectsMixin=[...toLocalGlobalMixin=[ExtensionType2_Application,GlobalUniformSystem,HelloSystem,eventemitter3$1,RenderGroupSystem,collectRenderablesMixin,GenerateTextureSystem,Assets,RendererInitHook,onRenderMixin,SchedulerSystem],GlUboSystem,sortMixin,findMixin,GlBufferSystem,GlTextureSystem,GlRenderTargetSystem,GlGeometrySystem,GlUniformGroupSystem,GlShaderSystem,GlEncoderSystem,ExtensionType2_Environment,GlStencilSystem,GlColorMaskSystem],childrenHelperMixin=[...NOOP],cacheAsTextureMixin=[GlBatchAdaptor,GlMeshAdaptor,GlGraphicsAdaptor],[]),renderPipes$1=[],renderPipeAdaptors$1=[];extensions.handleByNamedList("webgl-system",systems$1),extensions.handleByNamedList("webgl-pipes",renderPipes$1),extensions.handleByNamedList("webgl-pipes-adaptor",renderPipeAdaptors$1),extensions.add(...effectsMixin,...childrenHelperMixin,...cacheAsTextureMixin);class WebGLRenderer extends AbstractRenderer{constructor(){super({name:"webgl",type:1,systems:systems$1,renderPipes:renderPipes$1,renderPipeAdaptors:renderPipeAdaptors$1})}}var WebGLRenderer$1={__proto__:null,WebGLRenderer:WebGLRenderer};class BindGroupSystem{constructor(renderer){this._hash=Object.create(null),this._renderer=renderer,this._renderer.renderableGC.addManagedHash(this,"_hash")}contextChange(gpu){this._gpu=gpu}getBindGroup(bindGroup,program,groupIndex){return bindGroup._updateKey(),this._hash[bindGroup._key]||this._createBindGroup(bindGroup,program,groupIndex)}_createBindGroup(group,program,groupIndex){var device=this._gpu.device,groupLayout=program.layout[groupIndex],entries=[],renderer=this._renderer;for(const j in groupLayout){var uniformGroup,buffer,_a=null!=(_a=group.resources[j])?_a:group.resources[groupLayout[j]];let gpuResource;"uniformGroup"===_a._resourceType?(renderer.ubo.updateUniformGroup(uniformGroup=_a),uniformGroup=uniformGroup.buffer,gpuResource={buffer:renderer.buffer.getGPUBuffer(uniformGroup),offset:0,size:uniformGroup.descriptor.size}):"buffer"===_a._resourceType?(buffer=_a,gpuResource={buffer:renderer.buffer.getGPUBuffer(buffer),offset:0,size:buffer.descriptor.size}):"bufferResource"===_a._resourceType?(uniformGroup=_a,gpuResource={buffer:renderer.buffer.getGPUBuffer(uniformGroup.buffer),offset:uniformGroup.offset,size:uniformGroup.size}):"textureSampler"===_a._resourceType?gpuResource=renderer.texture.getGpuSampler(_a):"textureSource"===_a._resourceType&&(gpuResource=renderer.texture.getGpuSource(_a).createView({})),entries.push({binding:groupLayout[j],resource:gpuResource})}return program=renderer.shader.getProgramData(program).bindGroups[groupIndex],groupIndex=device.createBindGroup({layout:program,entries:entries}),this._hash[group._key]=groupIndex}destroy(){for(const key of Object.keys(this._hash))this._hash[key]=null;this._hash=null,this._renderer=null}}BindGroupSystem.extension={type:["webgpu-system"],name:"bindGroup"};class GpuBufferSystem{constructor(renderer){this._gpuBuffers=Object.create(null),this._managedBuffers=[],renderer.renderableGC.addManagedHash(this,"_gpuBuffers")}contextChange(gpu){this._gpu=gpu}getGPUBuffer(buffer){return this._gpuBuffers[buffer.uid]||this.createGPUBuffer(buffer)}updateBuffer(buffer){var gpuBuffer=this._gpuBuffers[buffer.uid]||this.createGPUBuffer(buffer),data=buffer.data;return buffer._updateID&&data&&(buffer._updateID=0,this._gpu.device.queue.writeBuffer(gpuBuffer,0,data.buffer,0,(buffer._updateSize||data.byteLength)+3&-4)),gpuBuffer}destroyAll(){for(const id in this._gpuBuffers)this._gpuBuffers[id].destroy();this._gpuBuffers={}}createGPUBuffer(buffer){this._gpuBuffers[buffer.uid]||(buffer.on("update",this.updateBuffer,this),buffer.on("change",this.onBufferChange,this),buffer.on("destroy",this.onBufferDestroy,this),this._managedBuffers.push(buffer));var gpuBuffer=this._gpu.device.createBuffer(buffer.descriptor);return buffer._updateID=0,buffer.data&&(fastCopy(buffer.data.buffer,gpuBuffer.getMappedRange()),gpuBuffer.unmap()),this._gpuBuffers[buffer.uid]=gpuBuffer}onBufferChange(buffer){this._gpuBuffers[buffer.uid].destroy(),buffer._updateID=0,this._gpuBuffers[buffer.uid]=this.createGPUBuffer(buffer)}onBufferDestroy(buffer){this._managedBuffers.splice(this._managedBuffers.indexOf(buffer),1),this._destroyBuffer(buffer)}destroy(){this._managedBuffers.forEach(buffer=>this._destroyBuffer(buffer)),this._managedBuffers=null,this._gpuBuffers=null}_destroyBuffer(buffer){this._gpuBuffers[buffer.uid].destroy(),buffer.off("update",this.updateBuffer,this),buffer.off("change",this.onBufferChange,this),buffer.off("destroy",this.onBufferDestroy,this),this._gpuBuffers[buffer.uid]=null}}GpuBufferSystem.extension={type:["webgpu-system"],name:"buffer"};class UboBatch{constructor({minUniformOffsetAlignment}){this._minUniformOffsetAlignment=256,this.byteIndex=0,this._minUniformOffsetAlignment=minUniformOffsetAlignment,this.data=new Float32Array(65535)}clear(){this.byteIndex=0}addEmptyGroup(size){if(size>this._minUniformOffsetAlignment/4)throw new Error("UniformBufferBatch: array is too large: "+4*size);var start=this.byteIndex,size=start+4*size;if((size=Math.ceil(size/this._minUniformOffsetAlignment)*this._minUniformOffsetAlignment)>4*this.data.length)throw new Error("UniformBufferBatch: ubo batch got too big");return this.byteIndex=size,start}addGroup(array){var offset=this.addEmptyGroup(array.length);for(let i=0;i{this.gpu=gpu,this._renderer.runners.contextChange.emit(this.gpu)})),this._initPromise}contextChange(gpu){this._renderer.gpu=gpu}async _createDeviceAndAdaptor(options){const adapter=await DOMAdapter.get().getNavigator().gpu.requestAdapter({powerPreference:options.powerPreference,forceFallbackAdapter:options.forceFallbackAdapter});return options=["texture-compression-bc","texture-compression-astc","texture-compression-etc2"].filter(feature=>adapter.features.has(feature)),options=await adapter.requestDevice({requiredFeatures:options}),{adapter:adapter,device:options}}destroy(){this.gpu=null,this._renderer=null}}GpuDeviceSystem.extension={type:["webgpu-system"],name:"device"},GpuDeviceSystem.defaultOptions={powerPreference:void 0,forceFallbackAdapter:!1};var __defProp$c=Object.defineProperty,__getOwnPropSymbols$c=Object.getOwnPropertySymbols,__hasOwnProp$c=Object.prototype.hasOwnProperty,__propIsEnum$c=Object.prototype.propertyIsEnumerable,__defNormalProp$c=(obj,key,value)=>key in obj?__defProp$c(obj,key,{enumerable:!0,configurable:!0,writable:!0,value:value}):obj[key]=value,__spreadValues$c=(a,b)=>{for(var prop in b=b||{})__hasOwnProp$c.call(b,prop)&&__defNormalProp$c(a,prop,b[prop]);if(__getOwnPropSymbols$c)for(var prop of __getOwnPropSymbols$c(b))__propIsEnum$c.call(b,prop)&&__defNormalProp$c(a,prop,b[prop]);return a};class GpuEncoderSystem{constructor(renderer){this._boundBindGroup=Object.create(null),this._boundVertexBuffer=Object.create(null),this._renderer=renderer}renderStart(){this.commandFinished=new Promise(resolve=>{this._resolveCommandFinished=resolve}),this.commandEncoder=this._renderer.gpu.device.createCommandEncoder()}beginRenderPass(gpuRenderTarget){this.endRenderPass(),this._clearCache(),this.renderPassEncoder=this.commandEncoder.beginRenderPass(gpuRenderTarget.descriptor)}endRenderPass(){this.renderPassEncoder&&this.renderPassEncoder.end(),this.renderPassEncoder=null}setViewport(viewport){this.renderPassEncoder.setViewport(viewport.x,viewport.y,viewport.width,viewport.height,0,1)}setPipelineFromGeometryProgramAndState(geometry,program,state,topology){geometry=this._renderer.pipeline.getPipeline(geometry,program,state,topology),this.setPipeline(geometry)}setPipeline(pipeline){this._boundPipeline!==pipeline&&(this._boundPipeline=pipeline,this.renderPassEncoder.setPipeline(pipeline))}_setVertexBuffer(index,buffer){this._boundVertexBuffer[index]!==buffer&&(this._boundVertexBuffer[index]=buffer,this.renderPassEncoder.setVertexBuffer(index,this._renderer.buffer.updateBuffer(buffer)))}_setIndexBuffer(buffer){var indexFormat;this._boundIndexBuffer!==buffer&&(indexFormat=2===(this._boundIndexBuffer=buffer).data.BYTES_PER_ELEMENT?"uint16":"uint32",this.renderPassEncoder.setIndexBuffer(this._renderer.buffer.updateBuffer(buffer),indexFormat))}resetBindGroup(index){this._boundBindGroup[index]=null}setBindGroup(index,bindGroup,program){this._boundBindGroup[index]!==bindGroup&&((this._boundBindGroup[index]=bindGroup)._touch(this._renderer.textureGC.count),bindGroup=this._renderer.bindGroup.getBindGroup(bindGroup,program,index),this.renderPassEncoder.setBindGroup(index,bindGroup))}setGeometry(geometry,program){var buffersToBind=this._renderer.pipeline.getBufferNamesToBind(geometry,program);for(const i in buffersToBind)this._setVertexBuffer(i,geometry.attributes[buffersToBind[i]].buffer);geometry.indexBuffer&&this._setIndexBuffer(geometry.indexBuffer)}_setShaderBindGroups(shader,skipSync){for(const i in shader.groups){var bindGroup=shader.groups[i];skipSync||this._syncBindGroup(bindGroup),this.setBindGroup(i,bindGroup,shader.gpuProgram)}}_syncBindGroup(bindGroup){for(const j in bindGroup.resources){var resource=bindGroup.resources[j];resource.isUniformGroup&&this._renderer.ubo.updateUniformGroup(resource)}}draw(options){var{geometry:options,shader,state,topology,size,start,instanceCount,skipSync}=options;this.setPipelineFromGeometryProgramAndState(options,shader.gpuProgram,state,topology),this.setGeometry(options,shader.gpuProgram),this._setShaderBindGroups(shader,skipSync),options.indexBuffer?this.renderPassEncoder.drawIndexed(size||options.indexBuffer.data.length,null!=instanceCount?instanceCount:options.instanceCount,start||0):this.renderPassEncoder.draw(size||options.getSize(),null!=instanceCount?instanceCount:options.instanceCount,start||0)}finishRenderPass(){this.renderPassEncoder&&(this.renderPassEncoder.end(),this.renderPassEncoder=null)}postrender(){this.finishRenderPass(),this._gpu.device.queue.submit([this.commandEncoder.finish()]),this._resolveCommandFinished(),this.commandEncoder=null}restoreRenderPass(){var descriptor=this._renderer.renderTarget.adaptor.getDescriptor(this._renderer.renderTarget.renderTarget,!1,[0,0,0,1]),descriptor=(this.renderPassEncoder=this.commandEncoder.beginRenderPass(descriptor),this._boundPipeline),boundVertexBuffer=__spreadValues$c({},this._boundVertexBuffer),boundIndexBuffer=this._boundIndexBuffer,boundBindGroup=__spreadValues$c({},this._boundBindGroup),viewport=(this._clearCache(),this._renderer.renderTarget.viewport);this.renderPassEncoder.setViewport(viewport.x,viewport.y,viewport.width,viewport.height,0,1),this.setPipeline(descriptor);for(const i in boundVertexBuffer)this._setVertexBuffer(i,boundVertexBuffer[i]);for(const i in boundBindGroup)this.setBindGroup(i,boundBindGroup[i],null);this._setIndexBuffer(boundIndexBuffer)}_clearCache(){for(let i=0;i<16;i++)this._boundBindGroup[i]=null,this._boundVertexBuffer[i]=null;this._boundIndexBuffer=null,this._boundPipeline=null}destroy(){this._renderer=null,this._gpu=null,this._boundBindGroup=null,this._boundVertexBuffer=null,this._boundIndexBuffer=null,this._boundPipeline=null}contextChange(gpu){this._gpu=gpu}}GpuEncoderSystem.extension={type:["webgpu-system"],name:"encoder",priority:1};class GpuStencilSystem{constructor(renderer){this._renderTargetStencilState=Object.create(null),(this._renderer=renderer).renderTarget.onRenderTargetChange.add(this)}onRenderTargetChange(renderTarget){var stencilState=this._renderTargetStencilState[renderTarget.uid]||(this._renderTargetStencilState[renderTarget.uid]={stencilMode:0,stencilReference:0});this._activeRenderTarget=renderTarget,this.setStencilMode(stencilState.stencilMode,stencilState.stencilReference)}setStencilMode(stencilMode,stencilReference){var stencilState=this._renderTargetStencilState[this._activeRenderTarget.uid];stencilState.stencilMode=stencilMode,stencilState.stencilReference=stencilReference,(stencilState=this._renderer).pipeline.setStencilMode(stencilMode),stencilState.encoder.renderPassEncoder.setStencilReference(stencilReference)}destroy(){this._renderer.renderTarget.onRenderTargetChange.remove(this),this._renderer=null,this._activeRenderTarget=null,this._renderTargetStencilState=null}}GpuStencilSystem.extension={type:["webgpu-system"],name:"stencil"};const WGSL_ALIGN_SIZE_DATA={i32:{align:4,size:4},u32:{align:4,size:4},f32:{align:4,size:4},f16:{align:2,size:2},"vec2":{align:8,size:8},"vec2":{align:8,size:8},"vec2":{align:8,size:8},"vec2":{align:4,size:4},"vec3":{align:16,size:12},"vec3":{align:16,size:12},"vec3":{align:16,size:12},"vec3":{align:8,size:6},"vec4":{align:16,size:16},"vec4":{align:16,size:16},"vec4":{align:16,size:16},"vec4":{align:8,size:8},"mat2x2":{align:8,size:16},"mat2x2":{align:4,size:8},"mat3x2":{align:8,size:24},"mat3x2":{align:4,size:12},"mat4x2":{align:8,size:32},"mat4x2":{align:4,size:16},"mat2x3":{align:16,size:32},"mat2x3":{align:8,size:16},"mat3x3":{align:16,size:48},"mat3x3":{align:8,size:24},"mat4x3":{align:16,size:64},"mat4x3":{align:8,size:32},"mat2x4":{align:16,size:32},"mat2x4":{align:8,size:16},"mat3x4":{align:16,size:48},"mat3x4":{align:8,size:24},"mat4x4":{align:16,size:64},"mat4x4":{align:8,size:32}};function createUboElementsWGSL(uniformData){var uboElements=uniformData.map(data=>({data:data,offset:0,size:0}));let offset=0;for(let i=0;ikey in obj?__defProp$b(obj,key,{enumerable:!0,configurable:!0,writable:!0,value:value}):obj[key]=value;const topologyStringToId={"point-list":0,"line-list":1,"line-strip":2,"triangle-list":3,"triangle-strip":4};class PipelineSystem{constructor(renderer){this._moduleCache=Object.create(null),this._bufferLayoutsCache=Object.create(null),this._bindingNamesCache=Object.create(null),this._pipeCache=Object.create(null),this._pipeStateCaches=Object.create(null),this._colorMask=15,this._multisampleCount=1,this._renderer=renderer}contextChange(gpu){this._gpu=gpu,this.setStencilMode(0),this._updatePipeHash()}setMultisampleCount(multisampleCount){this._multisampleCount!==multisampleCount&&(this._multisampleCount=multisampleCount,this._updatePipeHash())}setRenderTarget(renderTarget){this._multisampleCount=renderTarget.msaaSamples,this._depthStencilAttachment=renderTarget.descriptor.depthStencilAttachment?1:0,this._updatePipeHash()}setColorMask(colorMask){this._colorMask!==colorMask&&(this._colorMask=colorMask,this._updatePipeHash())}setStencilMode(stencilMode){this._stencilMode!==stencilMode&&(this._stencilMode=stencilMode,this._stencilState=GpuStencilModesToPixi[stencilMode],this._updatePipeHash())}setPipeline(geometry,program,state,passEncoder){geometry=this.getPipeline(geometry,program,state),passEncoder.setPipeline(geometry)}getPipeline(geometry,program,state,topology){geometry._layoutKey||(ensureAttributes(geometry,program.attributeData),this._generateBufferKey(geometry)),topology=topology||geometry.topology;var key=geometry._layoutKey<<24|program._layoutKey<<16|state.data<<10|state._blendModeId<<5|topologyStringToId[topology];return this._pipeCache[key]||(this._pipeCache[key]=this._createPipeline(geometry,program,state,topology)),this._pipeCache[key]}_createPipeline(geometry,program,state,topology){var device=this._gpu.device,geometry=this._createVertexBufferLayouts(geometry,program),blendModes=this._renderer.state.getColorTargets(state),layout=(blendModes[0].writeMask=1===this._stencilMode?0:this._colorMask,this._renderer.shader.getProgramData(program).pipeline),geometry={vertex:{module:this._getModule(program.vertex.source),entryPoint:program.vertex.entryPoint,buffers:geometry},fragment:{module:this._getModule(program.fragment.source),entryPoint:program.fragment.entryPoint,targets:blendModes},primitive:{topology:topology,cullMode:state.cullMode},layout:layout,multisample:{count:this._multisampleCount},label:"PIXI Pipeline"};return this._depthStencilAttachment&&(geometry.depthStencil=(program=((a,b)=>{for(var prop in b=b||{})__hasOwnProp$b.call(b,prop)&&__defNormalProp$b(a,prop,b[prop]);if(__getOwnPropSymbols$b)for(var prop of __getOwnPropSymbols$b(b))__propIsEnum$b.call(b,prop)&&__defNormalProp$b(a,prop,b[prop]);return a})({},this._stencilState),blendModes={format:"depth24plus-stencil8",depthWriteEnabled:state.depthTest,depthCompare:state.depthTest?"less":"always"},__defProps$6(program,__getOwnPropDescs$6(blendModes)))),device.createRenderPipeline(geometry)}_getModule(code){return this._moduleCache[code]||this._createModule(code)}_createModule(code){var device=this._gpu.device;return this._moduleCache[code]=device.createShaderModule({code:code}),this._moduleCache[code]}_generateBufferKey(geometry){var keyGen=[];let index=0;var attributeKeys=Object.keys(geometry.attributes).sort();for(let i=0;i{var _a,bufferEntry={arrayStride:0,stepMode:"vertex",attributes:[]},bufferEntryAttributes=bufferEntry.attributes;for(const i in program.attributeData){var attribute=geometry.attributes[i];1!==(null!=(_a=attribute.divisor)?_a:1)&&warn(`Attribute ${i} has an invalid divisor value of '${attribute.divisor}'. WebGPU only supports a divisor value of 1`),attribute.buffer===buffer&&(bufferEntry.arrayStride=attribute.stride,bufferEntry.stepMode=attribute.instance?"instance":"vertex",bufferEntryAttributes.push({shaderLocation:program.attributeData[i].location,offset:attribute.offset,format:attribute.format}))}bufferEntryAttributes.length&&vertexBuffersLayout.push(bufferEntry)}),this._bufferLayoutsCache[key]=vertexBuffersLayout}_updatePipeHash(){var stencilStateId=this._stencilMode,multiSampleCount=this._multisampleCount,colorMask=this._colorMask,renderTarget=this._depthStencilAttachment;this._pipeStateCaches[colorMask=colorMask<<6|stencilStateId<<3|renderTarget<<1|multiSampleCount]||(this._pipeStateCaches[colorMask]=Object.create(null)),this._pipeCache=this._pipeStateCaches[colorMask]}destroy(){this._renderer=null,this._bufferLayoutsCache=null}}PipelineSystem.extension={type:["webgpu-system"],name:"pipeline"};class GpuRenderTarget{constructor(){this.contexts=[],this.msaaTextures=[],this.msaaSamples=1}}class GpuRenderTargetAdaptor{init(renderer,renderTargetSystem){this._renderer=renderer,this._renderTargetSystem=renderTargetSystem}copyToTexture(sourceRenderSurfaceTexture,destinationTexture,originSrc,size,originDest){var renderer=this._renderer,sourceRenderSurfaceTexture=this._getGpuColorTexture(sourceRenderSurfaceTexture),backGpuTexture=renderer.texture.getGpuSource(destinationTexture.source);return renderer.encoder.commandEncoder.copyTextureToTexture({texture:sourceRenderSurfaceTexture,origin:originSrc},{texture:backGpuTexture,origin:originDest},size),destinationTexture}startRenderPass(renderTarget,clear=!0,clearColor,viewport){var gpuRenderTarget=this._renderTargetSystem.getGpuRenderTarget(renderTarget),renderTarget=this.getDescriptor(renderTarget,clear,clearColor);gpuRenderTarget.descriptor=renderTarget,this._renderer.pipeline.setRenderTarget(gpuRenderTarget),this._renderer.encoder.beginRenderPass(gpuRenderTarget),this._renderer.encoder.setViewport(viewport)}finishRenderPass(){this._renderer.encoder.endRenderPass()}_getGpuColorTexture(renderTarget){var gpuRenderTarget=this._renderTargetSystem.getGpuRenderTarget(renderTarget);return gpuRenderTarget.contexts[0]?gpuRenderTarget.contexts[0].getCurrentTexture():this._renderer.texture.getGpuSource(renderTarget.colorTextures[0].source)}getDescriptor(renderTarget,clear,clearValue){"boolean"==typeof clear&&(clear=clear?CLEAR.ALL:CLEAR.NONE);const renderTargetSystem=this._renderTargetSystem,gpuRenderTarget=renderTargetSystem.getGpuRenderTarget(renderTarget);var stencilLoadOp,depthLoadOp,colorAttachments=renderTarget.colorTextures.map((texture,i)=>{var context=gpuRenderTarget.contexts[i];let view,resolveTarget;return view=context?context.getCurrentTexture().createView():this._renderer.texture.getGpuSource(texture).createView({mipLevelCount:1}),gpuRenderTarget.msaaTextures[i]&&(resolveTarget=view,view=this._renderer.texture.getTextureView(gpuRenderTarget.msaaTextures[i])),context=clear&CLEAR.COLOR?"clear":"load",null==clearValue&&(clearValue=renderTargetSystem.defaultClearColor),{view:view,resolveTarget:resolveTarget,clearValue:clearValue,storeOp:"store",loadOp:context}});let depthStencilAttachment;return!renderTarget.stencil&&!renderTarget.depth||renderTarget.depthStencilTexture||(renderTarget.ensureDepthStencilTexture(),renderTarget.depthStencilTexture.source.sampleCount=gpuRenderTarget.msaa?4:1),renderTarget.depthStencilTexture&&(stencilLoadOp=clear&CLEAR.STENCIL?"clear":"load",depthLoadOp=clear&CLEAR.DEPTH?"clear":"load",depthStencilAttachment={view:this._renderer.texture.getGpuSource(renderTarget.depthStencilTexture.source).createView(),stencilStoreOp:"store",stencilLoadOp:stencilLoadOp,depthClearValue:1,depthLoadOp:depthLoadOp,depthStoreOp:"store"}),{colorAttachments:colorAttachments,depthStencilAttachment:depthStencilAttachment}}clear(renderTarget,clear=!0,clearColor,viewport){var gpu,encoder,renderPassDescriptor;clear&&({gpu,encoder}=this._renderer,gpu=gpu.device,null===encoder.commandEncoder?(encoder=gpu.createCommandEncoder(),renderPassDescriptor=this.getDescriptor(renderTarget,clear,clearColor),(renderPassDescriptor=encoder.beginRenderPass(renderPassDescriptor)).setViewport(viewport.x,viewport.y,viewport.width,viewport.height,0,1),renderPassDescriptor.end(),renderPassDescriptor=encoder.finish(),gpu.queue.submit([renderPassDescriptor])):this.startRenderPass(renderTarget,clear,clearColor,viewport))}initGpuRenderTarget(renderTarget){renderTarget.isRoot=!0;const gpuRenderTarget=new GpuRenderTarget;return renderTarget.colorTextures.forEach((colorTexture,i)=>{if(CanvasSource.test(colorTexture.resource)){var context=colorTexture.resource.getContext("webgpu"),alphaMode=colorTexture.transparent?"premultiplied":"opaque";try{context.configure({device:this._renderer.gpu.device,usage:GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_DST|GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.COPY_SRC,format:"bgra8unorm",alphaMode:alphaMode})}catch(e){console.error(e)}gpuRenderTarget.contexts[i]=context}gpuRenderTarget.msaa=colorTexture.source.antialias,colorTexture.source.antialias&&(alphaMode=new TextureSource({width:0,height:0,sampleCount:4}),gpuRenderTarget.msaaTextures[i]=alphaMode)}),gpuRenderTarget.msaa&&(gpuRenderTarget.msaaSamples=4,renderTarget.depthStencilTexture)&&(renderTarget.depthStencilTexture.source.sampleCount=4),gpuRenderTarget}destroyGpuRenderTarget(gpuRenderTarget){gpuRenderTarget.contexts.forEach(context=>{context.unconfigure()}),gpuRenderTarget.msaaTextures.forEach(texture=>{texture.destroy()}),gpuRenderTarget.msaaTextures.length=0,gpuRenderTarget.contexts.length=0}ensureDepthStencilTexture(renderTarget){var gpuRenderTarget=this._renderTargetSystem.getGpuRenderTarget(renderTarget);renderTarget.depthStencilTexture&&gpuRenderTarget.msaa&&(renderTarget.depthStencilTexture.source.sampleCount=4)}resizeGpuRenderTarget(renderTarget){const gpuRenderTarget=this._renderTargetSystem.getGpuRenderTarget(renderTarget);gpuRenderTarget.width=renderTarget.width,gpuRenderTarget.height=renderTarget.height,gpuRenderTarget.msaa&&renderTarget.colorTextures.forEach((colorTexture,i)=>{null!=(i=gpuRenderTarget.msaaTextures[i])&&i.resize(colorTexture.source.width,colorTexture.source.height,colorTexture.source._resolution)})}}class GpuRenderTargetSystem extends RenderTargetSystem{constructor(renderer){super(renderer),this.adaptor=new GpuRenderTargetAdaptor,this.adaptor.init(renderer,this)}}GpuRenderTargetSystem.extension={type:["webgpu-system"],name:"renderTarget"};class GpuShaderSystem{constructor(){this._gpuProgramData=Object.create(null)}contextChange(gpu){this._gpu=gpu,this.maxTextures=gpu.device.limits.maxSampledTexturesPerShaderStage}getProgramData(program){return this._gpuProgramData[program._layoutKey]||this._createGPUProgramData(program)}_createGPUProgramData(program){const device=this._gpu.device;var bindGroups=program.gpuLayout.map(group=>device.createBindGroupLayout({entries:group}));return this._gpuProgramData[program._layoutKey]={bindGroups:bindGroups,pipeline:device.createPipelineLayout({bindGroupLayouts:bindGroups})},this._gpuProgramData[program._layoutKey]}destroy(){this._gpu=null,this._gpuProgramData=null}}GpuShaderSystem.extension={type:["webgpu-system"],name:"shader"};const GpuBlendModesToPixi={normal:{alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"},color:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"}},add:{alpha:{srcFactor:"src-alpha",dstFactor:"one-minus-src-alpha",operation:"add"},color:{srcFactor:"one",dstFactor:"one",operation:"add"}},multiply:{alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"},color:{srcFactor:"dst",dstFactor:"one-minus-src-alpha",operation:"add"}},screen:{alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"},color:{srcFactor:"one",dstFactor:"one-minus-src",operation:"add"}},overlay:{alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"},color:{srcFactor:"one",dstFactor:"one-minus-src",operation:"add"}},none:{alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"},color:{srcFactor:"zero",dstFactor:"zero",operation:"add"}},"normal-npm":{alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"},color:{srcFactor:"src-alpha",dstFactor:"one-minus-src-alpha",operation:"add"}},"add-npm":{alpha:{srcFactor:"one",dstFactor:"one",operation:"add"},color:{srcFactor:"src-alpha",dstFactor:"one",operation:"add"}},"screen-npm":{alpha:{srcFactor:"one",dstFactor:"one-minus-src-alpha",operation:"add"},color:{srcFactor:"src-alpha",dstFactor:"one-minus-src",operation:"add"}},erase:{alpha:{srcFactor:"zero",dstFactor:"one-minus-src-alpha",operation:"add"},color:{srcFactor:"zero",dstFactor:"one-minus-src",operation:"add"}},min:{alpha:{srcFactor:"one",dstFactor:"one",operation:"min"},color:{srcFactor:"one",dstFactor:"one",operation:"min"}},max:{alpha:{srcFactor:"one",dstFactor:"one",operation:"max"},color:{srcFactor:"one",dstFactor:"one",operation:"max"}}};class GpuStateSystem{constructor(){this.defaultState=new State,this.defaultState.blend=!0}contextChange(gpu){this.gpu=gpu}getColorTargets(state){return[{format:"bgra8unorm",writeMask:0,blend:GpuBlendModesToPixi[state.blendMode]||GpuBlendModesToPixi.normal}]}destroy(){this.gpu=null}}GpuStateSystem.extension={type:["webgpu-system"],name:"state"};const gpuUploadBufferImageResource={type:"image",upload(source,gpuTexture,gpu){var resource=source.resource,total=(0|source.pixelWidth)*(0|source.pixelHeight),total=resource.byteLength/total;gpu.device.queue.writeTexture({texture:gpuTexture},resource,{offset:0,rowsPerImage:source.pixelHeight,bytesPerRow:source.pixelHeight*total},{width:source.pixelWidth,height:source.pixelHeight,depthOrArrayLayers:1})}},blockDataMap={"bc1-rgba-unorm":{blockBytes:8,blockWidth:4,blockHeight:4},"bc2-rgba-unorm":{blockBytes:16,blockWidth:4,blockHeight:4},"bc3-rgba-unorm":{blockBytes:16,blockWidth:4,blockHeight:4},"bc7-rgba-unorm":{blockBytes:16,blockWidth:4,blockHeight:4},"etc1-rgb-unorm":{blockBytes:8,blockWidth:4,blockHeight:4},"etc2-rgba8unorm":{blockBytes:16,blockWidth:4,blockHeight:4},"astc-4x4-unorm":{blockBytes:16,blockWidth:4,blockHeight:4}},defaultBlockData={blockBytes:4,blockWidth:1,blockHeight:1},gpuUploadCompressedTextureResource={type:"compressed",upload(source,gpuTexture,gpu){let mipWidth=source.pixelWidth,mipHeight=source.pixelHeight;var blockData=blockDataMap[source.format]||defaultBlockData;for(let i=0;i>1,1),mipHeight=Math.max(mipHeight>>1,1)}}},gpuUploadImageResource={type:"image",upload(source,gpuTexture,gpu){var width,height,resource=source.resource;resource&&(width=Math.min(gpuTexture.width,source.resourceWidth||source.pixelWidth),height=Math.min(gpuTexture.height,source.resourceHeight||source.pixelHeight),source="premultiply-alpha-on-upload"===source.alphaMode,gpu.device.queue.copyExternalImageToTexture({source:resource},{texture:gpuTexture,premultipliedAlpha:source},{width:width,height:height}))}},gpuUploadVideoResource={type:"video",upload(source,gpuTexture,gpu){gpuUploadImageResource.upload(source,gpuTexture,gpu)}};class GpuMipmapGenerator{constructor(device){this.device=device,this.sampler=device.createSampler({minFilter:"linear"}),this.pipelines={}}_getMipmapPipeline(format){let pipeline=this.pipelines[format];return pipeline||(this.mipmapShaderModule||(this.mipmapShaderModule=this.device.createShaderModule({code:` + var pos : array, 3> = array, 3>( + vec2(-1.0, -1.0), vec2(-1.0, 3.0), vec2(3.0, -1.0)); + + struct VertexOutput { + @builtin(position) position : vec4, + @location(0) texCoord : vec2, + }; + + @vertex + fn vertexMain(@builtin(vertex_index) vertexIndex : u32) -> VertexOutput { + var output : VertexOutput; + output.texCoord = pos[vertexIndex] * vec2(0.5, -0.5) + vec2(0.5); + output.position = vec4(pos[vertexIndex], 0.0, 1.0); + return output; + } + + @group(0) @binding(0) var imgSampler : sampler; + @group(0) @binding(1) var img : texture_2d; + + @fragment + fn fragmentMain(@location(0) texCoord : vec2) -> @location(0) vec4 { + return textureSample(img, imgSampler, texCoord); + } + `})),pipeline=this.device.createRenderPipeline({layout:"auto",vertex:{module:this.mipmapShaderModule,entryPoint:"vertexMain"},fragment:{module:this.mipmapShaderModule,entryPoint:"fragmentMain",targets:[{format:format}]}}),this.pipelines[format]=pipeline),pipeline}generateMipmap(texture){var pipeline=this._getMipmapPipeline(texture.format);if("3d"===texture.dimension||"1d"===texture.dimension)throw new Error("Generating mipmaps for non-2d textures is currently unsupported!");let mipTexture=texture;var mipTextureDescriptor,arrayLayerCount=texture.depthOrArrayLayers||1,renderToSource=texture.usage&GPUTextureUsage.RENDER_ATTACHMENT,commandEncoder=(renderToSource||(mipTextureDescriptor={size:{width:Math.ceil(texture.width/2),height:Math.ceil(texture.height/2),depthOrArrayLayers:arrayLayerCount},format:texture.format,usage:GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_SRC|GPUTextureUsage.RENDER_ATTACHMENT,mipLevelCount:texture.mipLevelCount-1},mipTexture=this.device.createTexture(mipTextureDescriptor)),this.device.createCommandEncoder({})),bindGroupLayout=pipeline.getBindGroupLayout(0);for(let arrayLayer=0;arrayLayer",value:texture.textureMatrix.mapCoord}})}),this._bindGroupHash[texture.uid]}getTextureView(texture){var _a,texture=texture.source;return null!=(_a=this._textureViewHash[texture.uid])?_a:this._createTextureView(texture)}_createTextureView(texture){return this._textureViewHash[texture.uid]=this.getGpuSource(texture).createView(),this._textureViewHash[texture.uid]}generateCanvas(texture){var renderer=this._renderer,commandEncoder=renderer.gpu.device.createCommandEncoder(),canvas=DOMAdapter.get().createCanvas(),context=(canvas.width=texture.source.pixelWidth,canvas.height=texture.source.pixelHeight,canvas.getContext("webgpu"));return context.configure({device:renderer.gpu.device,usage:GPUTextureUsage.COPY_DST|GPUTextureUsage.COPY_SRC,format:DOMAdapter.get().getNavigator().gpu.getPreferredCanvasFormat(),alphaMode:"premultiplied"}),commandEncoder.copyTextureToTexture({texture:renderer.texture.getGpuSource(texture.source),origin:{x:0,y:0}},{texture:context.getCurrentTexture()},{width:canvas.width,height:canvas.height}),renderer.gpu.device.queue.submit([commandEncoder.finish()]),canvas}getPixels(texture){var texture=this.generateCanvas(texture),canvasAndContext=CanvasPool.getOptimalCanvasAndContext(texture.width,texture.height),{width:texture,height}=((context=canvasAndContext.context).drawImage(texture,0,0),texture),context=context.getImageData(0,0,texture,height),context=new Uint8ClampedArray(context.data.buffer);return CanvasPool.returnCanvasAndContext(canvasAndContext),{pixels:context,width:texture,height:height}}destroy(){this.managedTextures.slice().forEach(source=>this.onSourceDestroy(source)),this.managedTextures=null;for(const k of Object.keys(this._bindGroupHash)){var key=Number(k),bindGroup=this._bindGroupHash[key];null!=bindGroup&&bindGroup.destroy(),this._bindGroupHash[key]=null}this._gpu=null,this._mipmapGenerator=null,this._gpuSources=null,this._bindGroupHash=null,this._textureViewHash=null,this._gpuSamplers=null}}GpuTextureSystem.extension={type:["webgpu-system"],name:"texture"};class GpuGraphicsAdaptor{init(){var localUniforms=new UniformGroup({uTransformMatrix:{value:new Matrix,type:"mat3x3"},uColor:{value:new Float32Array([1,1,1,1]),type:"vec4"},uRound:{value:0,type:"f32"}}),gpuProgram=compileHighShaderGpuProgram({name:"graphics",bits:[colorBit,generateTextureBatchBit(getMaxTexturesPerBatch()),localUniformBitGroup2,roundPixelsBit]});this.shader=new Shader({gpuProgram:gpuProgram,resources:{localUniforms:localUniforms}})}execute(graphicsPipe,renderable){var shader=(renderable=renderable.context).customShader||this.shader,renderer=graphicsPipe.renderer,{batcher,instructions}=renderer.graphicsContext.getContextRenderData(renderable),encoder=renderer.encoder,renderable=(encoder.setGeometry(batcher.geometry,shader.gpuProgram),renderer.globalUniforms.bindGroup),renderable=(encoder.setBindGroup(0,renderable,shader.gpuProgram),renderer.renderPipes.uniformBatch.getUniformBindGroup(shader.resources.localUniforms,!0)),batches=(encoder.setBindGroup(2,renderable,shader.gpuProgram),instructions.instructions);let topology=null;for(let i=0;i",value:new Matrix}}}})}execute(meshPipe,mesh){var renderer=meshPipe.renderer;let shader=mesh._shader;if(shader){if(!shader.gpuProgram)return void warn("Mesh shader has no gpuProgram",mesh.shader)}else(shader=this._shader).groups[2]=renderer.texture.getTextureBindGroup(mesh.texture);var gpuProgram=shader.gpuProgram;gpuProgram.autoAssignGlobalUniforms&&(shader.groups[0]=renderer.globalUniforms.bindGroup),gpuProgram.autoAssignLocalUniforms&&(gpuProgram=meshPipe.localUniforms,shader.groups[1]=renderer.renderPipes.uniformBatch.getUniformBindGroup(gpuProgram,!0)),renderer.encoder.draw({geometry:mesh._geometry,shader:shader,state:mesh.state})}destroy(){this._shader.destroy(!0),this._shader=null}}GpuMeshAdapter.extension={type:["webgpu-pipes-adaptor"],name:"mesh"},effectsMixin=[...toLocalGlobalMixin,GpuUboSystem,GpuEncoderSystem,GpuDeviceSystem,GpuBufferSystem,GpuTextureSystem,GpuRenderTargetSystem,GpuShaderSystem,GpuStateSystem,PipelineSystem,GpuColorMaskSystem,GpuStencilSystem,BindGroupSystem],childrenHelperMixin=[...NOOP,GpuUniformBatchPipe],cacheAsTextureMixin=[GpuBatchAdaptor,GpuMeshAdapter,GpuGraphicsAdaptor];const systems=[],renderPipes=[],renderPipeAdaptors=[];extensions.handleByNamedList("webgpu-system",systems),extensions.handleByNamedList("webgpu-pipes",renderPipes),extensions.handleByNamedList("webgpu-pipes-adaptor",renderPipeAdaptors),extensions.add(...effectsMixin,...childrenHelperMixin,...cacheAsTextureMixin);class WebGPURenderer extends AbstractRenderer{constructor(){super({name:"webgpu",type:2,systems:systems,renderPipes:renderPipes,renderPipeAdaptors:renderPipeAdaptors})}}var WebGPURenderer$1={__proto__:null,WebGPURenderer:WebGPURenderer};const DEPRECATED_DRAW_MODES={POINTS:"point-list",LINES:"line-list",LINE_STRIP:"line-strip",TRIANGLES:"triangle-list",TRIANGLE_STRIP:"triangle-strip"};new Proxy(DEPRECATED_DRAW_MODES,{get(target,prop){return deprecation(v8_0_0,`DRAW_MODES.${prop} is deprecated, use '${DEPRECATED_DRAW_MODES[prop]}' instead`),target[prop]}}),new Rectangle(0,0,1,1);var DEPRECATED_WRAP_MODES={CLAMP:"clamp-to-edge",REPEAT:"repeat",MIRRORED_REPEAT:"mirror-repeat"},DEPRECATED_SCALE_MODES=(new Proxy(DEPRECATED_WRAP_MODES,{get(target,prop){return deprecation(v8_0_0,`DRAW_MODES.${prop} is deprecated, use '${DEPRECATED_WRAP_MODES[prop]}' instead`),target[prop]}}),(ExtensionType2_ShapeBuilder={}).NEAREST="nearest",ExtensionType2_ShapeBuilder.LINEAR="linear",ExtensionType2_ShapeBuilder),__defProp$9=(new Proxy(DEPRECATED_SCALE_MODES,{get(target,prop){return deprecation(v8_0_0,`DRAW_MODES.${prop} is deprecated, use '${DEPRECATED_SCALE_MODES[prop]}' instead`),target[prop]}}),Object.defineProperty,Object.getOwnPropertySymbols,Object.prototype.hasOwnProperty,Object.prototype.propertyIsEnumerable,class extends ViewContainer{},Object.defineProperty),__getOwnPropSymbols$9=Object.getOwnPropertySymbols,__hasOwnProp$9=Object.prototype.hasOwnProperty,__propIsEnum$9=Object.prototype.propertyIsEnumerable,__defNormalProp$9=(obj,key,value)=>key in obj?__defProp$9(obj,key,{enumerable:!0,configurable:!0,writable:!0,value:value}):obj[key]=value,__spreadValues$9=(a,b)=>{for(var prop in b=b||{})__hasOwnProp$9.call(b,prop)&&__defNormalProp$9(a,prop,b[prop]);if(__getOwnPropSymbols$9)for(var prop of __getOwnPropSymbols$9(b))__propIsEnum$9.call(b,prop)&&__defNormalProp$9(a,prop,b[prop]);return a};const _RenderLayerClass=class _RenderLayerClass extends Container{constructor(options={}){options=__spreadValues$9(__spreadValues$9({},_RenderLayerClass.defaultOptions),options),super(),this.renderLayerChildren=[],this.sortableChildren=options.sortableChildren,this.sortFunction=options.sortFunction}attach(...children){for(let i=0;ia.zIndex-b.zIndex},_RenderLayerClass;const tempMatrix=[0,0,0,0,0,0,0,0,0],tempVec=[0,0,0],tempVec2=[0,0,0];function generateBasisToPointsMatrix(out,x1,y1,x2,y2,x3,y3,x4,y4){var m=tempMatrix,x1=(m[0]=x1,m[1]=x2,m[2]=x3,m[3]=y1,m[4]=y2,m[5]=y3,m[6]=1,m[7]=1,m[8]=1,computeAdjugate(out,m)),x2=(tempVec2[0]=x4,tempVec2[1]=y4,tempVec2[2]=1,function(out,m,v){var x=v[0],y=v[1];return out[0]=m[0]*x+m[1]*y+m[2]*(v=v[2]),out[1]=m[3]*x+m[4]*y+m[5]*v,out[2]=m[6]*x+m[7]*y+m[8]*v,out}(tempVec,x1,tempVec2)),x3=out;return out[0]=x2[0],out[1]=0,out[2]=0,out[3]=0,out[4]=x2[1],out[5]=0,out[6]=0,out[7]=0,out[8]=x2[2],multiplyMatrix3x3(out,x3,m)}const tempSourceMatrix=[0,0,0,0,0,0,0,0,0],tempDestinationMatrix=[0,0,0,0,0,0,0,0,0];class PerspectivePlaneGeometry extends ExtensionType2_MaskEffect{constructor(options){super(options),this._projectionMatrix=[0,0,0,0,0,0,0,0,0];var{width:options,height}=options;this.corners=[0,0,options,0,options,height,0,height]}setCorners(x0,y0,x1,y1,x2,y2,x3,y3){var corners=this.corners;corners[0]=x0,corners[1]=y0,corners[2]=x1,corners[3]=y1,corners[4]=x2,corners[5]=y2,corners[6]=x3,corners[7]=y3,this.updateProjection()}updateProjection(){var out,x1d,y1d,x2s,x2d,y2d,y3s,x3d,y3d,x4d,{width,height}=this,corners=this.corners;!function(width,height,geometry,transformationMatrix){var buffer=geometry.buffers[0],vertices=buffer.data,{verticesX,verticesY:geometry}=geometry,sizeX=width/(verticesX-1),sizeY=height/(geometry-1);let index=0;var a00=transformationMatrix[0],a01=transformationMatrix[1],a02=transformationMatrix[2],a10=transformationMatrix[3],a11=transformationMatrix[4],a12=transformationMatrix[5],a20=transformationMatrix[6],a21=transformationMatrix[7],a22=transformationMatrix[8];for(let i=0;ikey in obj?__defProp$8(obj,key,{enumerable:!0,configurable:!0,writable:!0,value:value}):obj[key]=value,__spreadValues$8=(a,b)=>{for(var prop in b=b||{})__hasOwnProp$8.call(b,prop)&&__defNormalProp$8(a,prop,b[prop]);if(__getOwnPropSymbols$8)for(var prop of __getOwnPropSymbols$8(b))__propIsEnum$8.call(b,prop)&&__defNormalProp$8(a,prop,b[prop]);return a};const _PerspectiveMesh=class _PerspectiveMesh extends Mesh{constructor(options){var{texture,verticesX,verticesY}=options=__spreadValues$8(__spreadValues$8({},_PerspectiveMesh.defaultOptions),options),rest=((source,exclude)=>{var target={};for(prop in source)__hasOwnProp$8.call(source,prop)&&exclude.indexOf(prop)<0&&(target[prop]=source[prop]);if(null!=source&&__getOwnPropSymbols$8)for(var prop of __getOwnPropSymbols$8(source))exclude.indexOf(prop)<0&&__propIsEnum$8.call(source,prop)&&(target[prop]=source[prop]);return target})(options,["texture","verticesX","verticesY"]),verticesX=new PerspectivePlaneGeometry(definedProps({width:texture.width,height:texture.height,verticesX:verticesX,verticesY:verticesY}));super(definedProps((verticesY=__spreadValues$8({},rest),__defProps$5(verticesY,__getOwnPropDescs$5({geometry:verticesX}))))),this._texture=texture,this.geometry.setCorners(options.x0,options.y0,options.x1,options.y1,options.x2,options.y2,options.x3,options.y3)}textureUpdated(){var width,height,geometry=this.geometry;geometry&&({width,height}=this.texture,geometry.width===width&&geometry.height===height||(geometry.width=width,geometry.height=height,geometry.updateProjection()))}set texture(value){this._texture!==value&&(super.texture=value,this.textureUpdated())}get texture(){return this._texture}setCorners(x0,y0,x1,y1,x2,y2,x3,y3){this.geometry.setCorners(x0,y0,x1,y1,x2,y2,x3,y3)}};_PerspectiveMesh.defaultOptions={texture:Texture.WHITE,verticesX:10,verticesY:10,x0:0,y0:0,x1:100,y1:0,x2:100,y2:100,x3:0,y3:100},_PerspectiveMesh,Object.defineProperty,Object.defineProperties,Object.getOwnPropertyDescriptors,Object.getOwnPropertySymbols,Object.prototype.hasOwnProperty,Object.prototype.propertyIsEnumerable,class extends Mesh{};var __defProp$6=Object.defineProperty,__getOwnPropSymbols$6=Object.getOwnPropertySymbols,__hasOwnProp$6=Object.prototype.hasOwnProperty,__propIsEnum$6=Object.prototype.propertyIsEnumerable,__defNormalProp$6=(obj,key,value)=>key in obj?__defProp$6(obj,key,{enumerable:!0,configurable:!0,writable:!0,value:value}):obj[key]=value,__spreadValues$6=(a,b)=>{for(var prop in b=b||{})__hasOwnProp$6.call(b,prop)&&__defNormalProp$6(a,prop,b[prop]);if(__getOwnPropSymbols$6)for(var prop of __getOwnPropSymbols$6(b))__propIsEnum$6.call(b,prop)&&__defNormalProp$6(a,prop,b[prop]);return a};const _RopeGeometry=class _RopeGeometry extends MeshGeometry{constructor(options){var{width:options,points,textureScale}=__spreadValues$6(__spreadValues$6({},_RopeGeometry.defaultOptions),options);super({positions:new Float32Array(4*points.length),uvs:new Float32Array(4*points.length),indices:new Uint32Array(6*(points.length-1))}),this.points=points,this._width=options,this.textureScale=textureScale,this._build()}get width(){return this._width}_build(){var points=this.points;if(points){var vertexBuffer=this.getBuffer("aPosition"),uvBuffer=this.getBuffer("aUV"),indexBuffer=this.getIndex();if(!(points.length<1)){vertexBuffer.data.length/4!==points.length&&(vertexBuffer.data=new Float32Array(4*points.length),uvBuffer.data=new Float32Array(4*points.length),indexBuffer.data=new Uint16Array(6*(points.length-1)));var uvs=uvBuffer.data,indices=indexBuffer.data;uvs[0]=0,uvs[1]=0,uvs[2]=0,uvs[3]=1;let amount=0,prev=points[0];var textureWidth=this._width*this.textureScale,total=points.length;for(let i=0;ikey in obj?__defProp$5(obj,key,{enumerable:!0,configurable:!0,writable:!0,value:value}):obj[key]=value,__spreadValues$5=(a,b)=>{for(var prop in b=b||{})__hasOwnProp$5.call(b,prop)&&__defNormalProp$5(a,prop,b[prop]);if(__getOwnPropSymbols$5)for(var prop of __getOwnPropSymbols$5(b))__propIsEnum$5.call(b,prop)&&__defNormalProp$5(a,prop,b[prop]);return a};const _MeshRope=class _MeshRope extends Mesh{constructor(options){var{texture,points,textureScale}=options=__spreadValues$5(__spreadValues$5({},_MeshRope.defaultOptions),options),options=((source,exclude)=>{var target={};for(prop in source)__hasOwnProp$5.call(source,prop)&&exclude.indexOf(prop)<0&&(target[prop]=source[prop]);if(null!=source&&__getOwnPropSymbols$5)for(var prop of __getOwnPropSymbols$5(source))exclude.indexOf(prop)<0&&__propIsEnum$5.call(source,prop)&&(target[prop]=source[prop]);return target})(options,["texture","points","textureScale"]),points=new RopeGeometry(definedProps({width:texture.height,points:points,textureScale:textureScale}));0key in obj?__defProp$3(obj,key,{enumerable:!0,configurable:!0,writable:!0,value:value}):obj[key]=value,__spreadValues$3=(a,b)=>{for(var prop in b=b||{})__hasOwnProp$3.call(b,prop)&&__defNormalProp$3(a,prop,b[prop]);if(__getOwnPropSymbols$3)for(var prop of __getOwnPropSymbols$3(b))__propIsEnum$3.call(b,prop)&&__defNormalProp$3(a,prop,b[prop]);return a};const _Particle=class _Particle{constructor(options){options instanceof Texture?(this.texture=options,assignWithIgnore(this,_Particle.defaultOptions,{})):assignWithIgnore(this,__spreadValues$3(__spreadValues$3({},_Particle.defaultOptions),options),{})}get alpha(){return this._alpha}set alpha(value){this._alpha=Math.min(Math.max(value,0),1),this._updateColor()}get tint(){return bgr2rgb(this._tint)}set tint(value){this._tint="number"==typeof value?value:Color.shared.setValue(null!=value?value:16777215).toBgrNumber(),this._updateColor()}_updateColor(){this.color=this._tint+((255*this._alpha|0)<<24)}},particleData=(_Particle.defaultOptions={anchorX:0,anchorY:0,x:0,y:0,scaleX:1,scaleY:1,rotation:0,tint:16777215,alpha:1},_Particle,{vertex:{attributeName:"aVertex",format:"float32x2",code:` + const texture = p.texture; + const sx = p.scaleX; + const sy = p.scaleY; + const ax = p.anchorX; + const ay = p.anchorY; + const trim = texture.trim; + const orig = texture.orig; + + if (trim) + { + w1 = trim.x - (ax * orig.width); + w0 = w1 + trim.width; + + h1 = trim.y - (ay * orig.height); + h0 = h1 + trim.height; + } + else + { + w1 = -ax * (orig.width); + w0 = w1 + orig.width; + + h1 = -ay * (orig.height); + h0 = h1 + orig.height; + } + + f32v[offset] = w1 * sx; + f32v[offset + 1] = h1 * sy; + + f32v[offset + stride] = w0 * sx; + f32v[offset + stride + 1] = h1 * sy; + + f32v[offset + (stride * 2)] = w0 * sx; + f32v[offset + (stride * 2) + 1] = h0 * sy; + + f32v[offset + (stride * 3)] = w1 * sx; + f32v[offset + (stride * 3) + 1] = h0 * sy; + `,dynamic:!1},position:{attributeName:"aPosition",format:"float32x2",code:` + var x = p.x; + var y = p.y; + + f32v[offset] = x; + f32v[offset + 1] = y; + + f32v[offset + stride] = x; + f32v[offset + stride + 1] = y; + + f32v[offset + (stride * 2)] = x; + f32v[offset + (stride * 2) + 1] = y; + + f32v[offset + (stride * 3)] = x; + f32v[offset + (stride * 3) + 1] = y; + `,dynamic:!0},rotation:{attributeName:"aRotation",format:"float32",code:` + var rotation = p.rotation; + + f32v[offset] = rotation; + f32v[offset + stride] = rotation; + f32v[offset + (stride * 2)] = rotation; + f32v[offset + (stride * 3)] = rotation; + `,dynamic:!1},uvs:{attributeName:"aUV",format:"float32x2",code:` + var uvs = p.texture.uvs; + + f32v[offset] = uvs.x0; + f32v[offset + 1] = uvs.y0; + + f32v[offset + stride] = uvs.x1; + f32v[offset + stride + 1] = uvs.y1; + + f32v[offset + (stride * 2)] = uvs.x2; + f32v[offset + (stride * 2) + 1] = uvs.y2; + + f32v[offset + (stride * 3)] = uvs.x3; + f32v[offset + (stride * 3) + 1] = uvs.y3; + `,dynamic:!1},color:{attributeName:"aColor",format:"unorm8x4",code:` + const c = p.color; + + u32v[offset] = c; + u32v[offset + stride] = c; + u32v[offset + (stride * 2)] = c; + u32v[offset + (stride * 3)] = c; + `,dynamic:!1}});var __defProp$2=Object.defineProperty,__defProps$1=Object.defineProperties,__getOwnPropDescs$1=Object.getOwnPropertyDescriptors,__getOwnPropSymbols$2=Object.getOwnPropertySymbols,__hasOwnProp$2=Object.prototype.hasOwnProperty,__propIsEnum$2=Object.prototype.propertyIsEnumerable,__defNormalProp$2=(obj,key,value)=>key in obj?__defProp$2(obj,key,{enumerable:!0,configurable:!0,writable:!0,value:value}):obj[key]=value,__spreadValues$2=(a,b)=>{for(var prop in b=b||{})__hasOwnProp$2.call(b,prop)&&__defNormalProp$2(a,prop,b[prop]);if(__getOwnPropSymbols$2)for(var prop of __getOwnPropSymbols$2(b))__propIsEnum$2.call(b,prop)&&__defNormalProp$2(a,prop,b[prop]);return a},__spreadProps$1=(a,b)=>__defProps$1(a,__getOwnPropDescs$1(b));const emptyBounds=new Bounds(0,0,0,0),_ParticleContainer=class _ParticleContainer extends ViewContainer{constructor(options={}){var{dynamicProperties,shader,roundPixels,texture,particles}=options=__spreadProps$1(__spreadValues$2(__spreadValues$2({},_ParticleContainer.defaultOptions),options),{dynamicProperties:__spreadValues$2(__spreadValues$2({},_ParticleContainer.defaultOptions.dynamicProperties),null==options?void 0:options.dynamicProperties)}),options=((source,exclude)=>{var target={};for(prop in source)__hasOwnProp$2.call(source,prop)&&exclude.indexOf(prop)<0&&(target[prop]=source[prop]);if(null!=source&&__getOwnPropSymbols$2)for(var prop of __getOwnPropSymbols$2(source))exclude.indexOf(prop)<0&&__propIsEnum$2.call(source,prop)&&(target[prop]=source[prop]);return target})(options,["dynamicProperties","shader","roundPixels","texture","particles"]);super(__spreadValues$2({label:"ParticleContainer"},options)),this.renderPipeId="particle",this.batched=!1,this._childrenDirty=!1,this.texture=texture||null,this.shader=shader,this._properties={};for(const key in particleData){var property=particleData[key],dynamic=dynamicProperties[key];this._properties[key]=__spreadProps$1(__spreadValues$2({},property),{dynamic:dynamic})}this.allowChildren=!0,this.roundPixels=null!=roundPixels&&roundPixels,this.particleChildren=null!=particles?particles:[]}addParticle(...children){for(let i=0;ikey in obj?__defProp$1(obj,key,{enumerable:!0,configurable:!0,writable:!0,value:value}):obj[key]=value;const _NineSliceSprite=class _NineSliceSprite extends ViewContainer{constructor(options){var{width,height,anchor,leftWidth,rightWidth,topHeight,bottomHeight,texture,roundPixels}=options=options instanceof Texture?{texture:options}:options;super(((a,b)=>{for(var prop in b=b||{})__hasOwnProp$1.call(b,prop)&&__defNormalProp$1(a,prop,b[prop]);if(__getOwnPropSymbols$1)for(var prop of __getOwnPropSymbols$1(b))__propIsEnum$1.call(b,prop)&&__defNormalProp$1(a,prop,b[prop]);return a})({label:"NineSliceSprite"},((source,exclude)=>{var target={};for(prop in source)__hasOwnProp$1.call(source,prop)&&exclude.indexOf(prop)<0&&(target[prop]=source[prop]);if(null!=source&&__getOwnPropSymbols$1)for(var prop of __getOwnPropSymbols$1(source))exclude.indexOf(prop)<0&&__propIsEnum$1.call(source,prop)&&(target[prop]=source[prop]);return target})(options,["width","height","anchor","leftWidth","rightWidth","topHeight","bottomHeight","texture","roundPixels"]))),this.renderPipeId="nineSliceSprite",this.batched=!0,this._leftWidth=null!=(leftWidth=null!=leftWidth?leftWidth:null==(options=null==texture?void 0:texture.defaultBorders)?void 0:options.left)?leftWidth:NineSliceGeometry.defaultOptions.leftWidth,this._topHeight=null!=(leftWidth=null!=topHeight?topHeight:null==(options=null==texture?void 0:texture.defaultBorders)?void 0:options.top)?leftWidth:NineSliceGeometry.defaultOptions.topHeight,this._rightWidth=null!=(options=null!=rightWidth?rightWidth:null==(topHeight=null==texture?void 0:texture.defaultBorders)?void 0:topHeight.right)?options:NineSliceGeometry.defaultOptions.rightWidth,this._bottomHeight=null!=(rightWidth=null!=bottomHeight?bottomHeight:null==(leftWidth=null==texture?void 0:texture.defaultBorders)?void 0:leftWidth.bottom)?rightWidth:NineSliceGeometry.defaultOptions.bottomHeight,this._width=null!=(topHeight=null!=width?width:texture.width)?topHeight:NineSliceGeometry.defaultOptions.width,this._height=null!=(options=null!=height?height:texture.height)?options:NineSliceGeometry.defaultOptions.height,this.allowChildren=!1,this.texture=null!=texture?texture:_NineSliceSprite.defaultOptions.texture,this.roundPixels=null!=roundPixels&&roundPixels,this._anchor=new ObservablePoint({_onUpdate:()=>{this.onViewUpdate()}}),anchor?this.anchor=anchor:this.texture.defaultAnchor&&(this.anchor=this.texture.defaultAnchor)}get anchor(){return this._anchor}set anchor(value){"number"==typeof value?this._anchor.set(value):this._anchor.copyFrom(value)}get width(){return this._width}set width(value){this._width=value,this.onViewUpdate()}get height(){return this._height}set height(value){this._height=value,this.onViewUpdate()}setSize(value,height){var _a;"object"==typeof value&&(height=null!=(_a=value.height)?_a:value.width,value=value.width),this._width=value,this._height=null!=height?height:value,this.onViewUpdate()}getSize(out){return(out=out||{}).width=this._width,out.height=this._height,out}get leftWidth(){return this._leftWidth}set leftWidth(value){this._leftWidth=value,this.onViewUpdate()}get topHeight(){return this._topHeight}set topHeight(value){this._topHeight=value,this.onViewUpdate()}get rightWidth(){return this._rightWidth}set rightWidth(value){this._rightWidth=value,this.onViewUpdate()}get bottomHeight(){return this._bottomHeight}set bottomHeight(value){this._bottomHeight=value,this.onViewUpdate()}get texture(){return this._texture}set texture(value){value=value||Texture.EMPTY;var currentTexture=this._texture;currentTexture!==value&&(currentTexture&¤tTexture.dynamic&¤tTexture.off("update",this.onViewUpdate,this),value.dynamic&&value.on("update",this.onViewUpdate,this),this._texture=value,this.onViewUpdate())}get originalWidth(){return this._texture.width}get originalHeight(){return this._texture.height}destroy(options){super.destroy(options),("boolean"==typeof options?options:null!=options&&options.texture)&&(options="boolean"==typeof options?options:null==options?void 0:options.textureSource,this._texture.destroy(options)),this._texture=null}updateBounds(){var bounds=this._bounds,anchor=this._anchor,width=this._width,height=this._height;bounds.minX=-anchor._x*width,bounds.maxX=bounds.minX+width,bounds.minY=-anchor._y*height,bounds.maxY=bounds.minY+height}};_NineSliceSprite.defaultOptions={texture:Texture.EMPTY},class extends(getGlobalMixin=_NineSliceSprite){},Object.defineProperty,Object.defineProperties,Object.getOwnPropertyDescriptors,Object.getOwnPropertySymbols,Object.prototype.hasOwnProperty,Object.prototype.propertyIsEnumerable,AbstractBitmapFont,AbstractRenderer,AnimatedSprite,BLEND_TO_NPM,BackgroundLoader,Batch,BatchGeometry,BatchTextureArray,BatchableGraphics,BatchableMesh,BatchableSprite,BigPool,BindGroup,BitmapFont,BitmapFontManager,Bounds,Buffer,BufferResource,Cache,CanvasPool,CanvasSource,CanvasTextMetrics,Circle,Color,Container,DEG_TO_RAD,DOMAdapter,DefaultBatcher,DefaultShader,DynamicBitmapFont,Ellipse,EventBoundary,EventSystem,EventsTicker,FederatedEvent,FederatedMouseEvent,FederatedPointerEvent,FederatedWheelEvent,FillGradient,FillPattern,FilterEffect,FontStylePromiseCache,GAUSSIAN_VALUES,Geometry,GlBuffer,GlParticleContainerAdaptor,GlProgram,GlProgramData,GlRenderTarget,GlRenderTargetAdaptor,GlTexture,GpuBlendModesToPixi,GpuGraphicsContext,GpuMipmapGenerator,GpuParticleContainerAdaptor,GpuProgram,GpuRenderTarget,GpuRenderTargetAdaptor,GpuStencilModesToPixi,Graphics,GraphicsContext,GraphicsContextRenderData,GraphicsContextSystem,GraphicsPath,HTMLTextRenderData,HTMLTextStyle,ImageSource,InstructionSet,Loader,MaskEffectManager,MaskFilter,Matrix,Mesh,MeshGeometry,NineSliceGeometry,ObservablePoint,PI_2,ParticleBuffer,ParticleShader,PerspectivePlaneGeometry,Point,Polygon,Pool,RAD_TO_DEG,Rectangle,RenderGroup,RenderTarget,RenderTexture,Resolver,RopeGeometry,RoundedRectangle,SdfShader,Shader,ShapePath,Sprite,Spritesheet,State,SystemRunner,TextStyle,Texture,TextureMatrix,TexturePool,TextureSource,TextureStyle,Ticker,TickerListener,TilingSpriteShader,Transform,UNIFORM_TO_ARRAY_SETTERS,UNIFORM_TO_SINGLE_SETTERS,UNIFORM_TYPES_MAP,UNIFORM_TYPES_VALUES,UboBatch,UniformGroup,VideoSource,ViewContainer,ViewableBuffer,WGSL_ALIGN_SIZE_DATA,WGSL_TO_STD40_SIZE,WorkerManager,bitmapFontTextParser,bitmapFontXMLParser,bitmapFontXMLStringParser,blockDataMap,boundsPool,colorBit,colorBitGl,compareModeToGlCompare,convertToList,copySearchParams,extensions,findHooksRx,fragmentGPUTemplate,fragmentGlTemplate,glUploadBufferImageResource,glUploadCompressedTextureResource,glUploadImageResource,glUploadVideoResource,globalUniformsBit,globalUniformsBitGl,gpuUploadBufferImageResource,gpuUploadCompressedTextureResource,gpuUploadImageResource,gpuUploadVideoResource,groupD8,isMobile,isSingleItem,localUniformBit,localUniformBitGl,localUniformBitGroup2,localUniformMSDFBit,localUniformMSDFBitGl,mSDFBit,mSDFBitGl,matrixPool,mipmapScaleModeToGlFilter,normalizeExtensionPriority,nssvg,nsxhtml,particleData,path,roundPixelsBit,roundPixelsBitGl,scaleModeToGlFilter,shapeBuilders,styleAttributes,textureBit,textureBitGl,tilingBit,tilingBitGl,uboSyncFunctionsSTD40,uboSyncFunctionsWGSL,uniformParsers,v8_0_0,vertexGPUTemplate,vertexGlTemplate,wrapModeToGlAddress}(); \ No newline at end of file diff --git a/js/libpolyfill.requestAnimationFrame.js b/js/libpolyfill.requestAnimationFrame.js new file mode 100644 index 0000000..bca2fb5 --- /dev/null +++ b/js/libpolyfill.requestAnimationFrame.js @@ -0,0 +1,30 @@ +'use strict'; + +// requestAnimationFrame polyfill by Erik Möller. +// Fixes from Paul Irish, Tino Zijdel, Andrew Mao, Klemen Slavic, Darius Bacon and Joan Alba Maldonado. +// Adapted from https://gist.github.com/paulirish/1579671 which derived from +// http://paulirish.com/2011/requestanimationframe-for-smart-animating/ +// http://my.opera.com/emoller/blog/2011/12/20/requestanimationframe-for-smart-er-animating +// Added high resolution timing. This window.performance.now() polyfill can be used: https://gist.github.com/jalbam/cc805ac3cfe14004ecdf323159ecf40e +// MIT license +// Gist: https://gist.github.com/jalbam/5fe05443270fa6d8136238ec72accbc0 +(function() { + var vendors = ['webkit', 'moz', 'ms', 'o'], vp = null; + for (var x = 0; x < vendors.length && !window.requestAnimationFrame && !window.cancelAnimationFrame; x++) + { + vp = vendors[x]; + window.requestAnimationFrame = window.requestAnimationFrame || window[vp + 'RequestAnimationFrame']; + window.cancelAnimationFrame = window.cancelAnimationFrame || window[vp + 'CancelAnimationFrame'] || window[vp + 'CancelRequestAnimationFrame']; + } + if (/iP(ad|hone|od).*OS 6/.test(window.navigator.userAgent) || !window.requestAnimationFrame || !window.cancelAnimationFrame) //iOS6 is buggy. + { + var lastTime = 0; + window.requestAnimationFrame = function(callback, element) + { + var now = window.performance.now(); + var nextTime = Math.max(lastTime + 16, now); //First time will execute it immediately but barely noticeable and performance is gained. + return setTimeout(function() { callback(lastTime = nextTime); }, nextTime - now); + }; + window.cancelAnimationFrame = clearTimeout; + } +}()); \ No newline at end of file diff --git a/js/libtransition.js b/js/libtransition.js new file mode 100644 index 0000000..6b7cad7 --- /dev/null +++ b/js/libtransition.js @@ -0,0 +1,120 @@ +(function() { + + if(typeof libutil!="object") { + if(typeof loadfail=="function") { + loadfail("libtransition.js:object libutil(type of "+(typeof libutil)+") is not defined"); + } else { + window.alert("libtransition.js:object libutil is not defined"); + } + return; + } + + if(typeof Bezier!="function") { + if(typeof loadfail=="function") { + loadfail("libtransition.js:class Bezier(type of "+(typeof Bezier)+") is not defined"); + } else { + window.alert("libtransition.js:class Bezier is not defined"); + } + return; + } + + if(typeof requestAnimationFrame!="function") { + if(typeof loadfail=="function") { + loadfail("libtransition.js:function requestAnimationFrame(type of "+(typeof requestAnimationFrame)+") is not defined"); + } else { + window.alert("libtransition.js:function requestAnimationFrame is not defined"); + } + return; + } + + class Transition { + + static linear=new Bezier(0, 0, 1, 1); + + constructor() { + // static fields (set by user) + this.obj = null; + this.key = null; + this.startval = 0.0; + this.endval = 0.0; + this.duration = 0; + this.animfunc = Transition.linear; + this.stoponend=true; + this.onend = null; + // dynamic fields (set by this program) + this.elapsed = 0; + this.carryover = 0; + } + + start() { + this.stop(); + transition_update_list.push(this); + } + + stop() { + var index=-1; + do { + index = transition_update_list.indexOf(this); + if(index > -1) { + transition_update_list.splice(index, 1); + } + } while(index!=-1); + } + + update(et) { + if(window.EnableDebugMode) { + if(!(this.key in this.obj)) { + this.stop(); + console.error("the key", this.key, "is not in the obj", this.obj); + return; + } + if(typeof this.animfunc!="function") { + this.stop(); + console.error("(a instance of transition).animfunc is not a function"); + return; + } + if(!libutil.isNumber(et)) { + et=0; + } + } + // this.carryover is for this.onend() only, not for the animation itself + this.carryover=0; + this.elapsed+=et; + if(this.elapsed>=this.duration) { + this.carryover=this.elapsed-this.duration; + this.elapsed=this.duration; + this.obj[this.key]=this.endval; + if(this.onend!==null&&typeof this.onend=="function") { + try { + this.onend(); + } catch(e) { + console.error(e); + } + } + if(this.stoponend) { + this.stop(); + } + return; + } + this.obj[this.key]=(this.endval-this.startval)*libutil.clamp(this.animfunc(this.elapsed/this.duration), 0, 1); + } + + } + + var transition_update_list=[]; + + var ticker_lasttime=Date.now(); + + var run_ticker=function(ts) { + requestAnimationFrame(run_ticker); + var et = ts - ticker_lasttime; + ticker_lasttime = ts; + transition_update_list.forEach(function(elem) { + elem.update(et); + }); + }; + + run_ticker(ticker_lasttime); + + window.Transition=Transition; +})(); \ No newline at end of file diff --git a/js/libutil.js b/js/libutil.js new file mode 100644 index 0000000..f6fdc2f --- /dev/null +++ b/js/libutil.js @@ -0,0 +1,24 @@ +(function() { + + var libutil= {}; + + libutil.isNumber=function(v) { + return typeof v === "number"; + }; + + libutil.clamp=function(val, min, max) { + if(window.EnableDebugMode) { + if(max