pixi.mjs 1.5 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656
  1. /*!
  2. * pixi.js - v6.5.10
  3. * Compiled Thu, 06 Jul 2023 15:25:11 UTC
  4. *
  5. * pixi.js is licensed under the MIT License.
  6. * http://www.opensource.org/licenses/mit-license
  7. */
  8. /**
  9. * @this {Promise}
  10. */
  11. function finallyConstructor(callback) {
  12. var constructor = this.constructor;
  13. return this.then(
  14. function(value) {
  15. // @ts-ignore
  16. return constructor.resolve(callback()).then(function() {
  17. return value;
  18. });
  19. },
  20. function(reason) {
  21. // @ts-ignore
  22. return constructor.resolve(callback()).then(function() {
  23. // @ts-ignore
  24. return constructor.reject(reason);
  25. });
  26. }
  27. );
  28. }
  29. function allSettled(arr) {
  30. var P = this;
  31. return new P(function(resolve, reject) {
  32. if (!(arr && typeof arr.length !== 'undefined')) {
  33. return reject(
  34. new TypeError(
  35. typeof arr +
  36. ' ' +
  37. arr +
  38. ' is not iterable(cannot read property Symbol(Symbol.iterator))'
  39. )
  40. );
  41. }
  42. var args = Array.prototype.slice.call(arr);
  43. if (args.length === 0) { return resolve([]); }
  44. var remaining = args.length;
  45. function res(i, val) {
  46. if (val && (typeof val === 'object' || typeof val === 'function')) {
  47. var then = val.then;
  48. if (typeof then === 'function') {
  49. then.call(
  50. val,
  51. function(val) {
  52. res(i, val);
  53. },
  54. function(e) {
  55. args[i] = { status: 'rejected', reason: e };
  56. if (--remaining === 0) {
  57. resolve(args);
  58. }
  59. }
  60. );
  61. return;
  62. }
  63. }
  64. args[i] = { status: 'fulfilled', value: val };
  65. if (--remaining === 0) {
  66. resolve(args);
  67. }
  68. }
  69. for (var i = 0; i < args.length; i++) {
  70. res(i, args[i]);
  71. }
  72. });
  73. }
  74. // Store setTimeout reference so promise-polyfill will be unaffected by
  75. // other code modifying setTimeout (like sinon.useFakeTimers())
  76. var setTimeoutFunc = setTimeout;
  77. function isArray(x) {
  78. return Boolean(x && typeof x.length !== 'undefined');
  79. }
  80. function noop() {}
  81. // Polyfill for Function.prototype.bind
  82. function bind(fn, thisArg) {
  83. return function() {
  84. fn.apply(thisArg, arguments);
  85. };
  86. }
  87. /**
  88. * @constructor
  89. * @param {Function} fn
  90. */
  91. function Promise$1(fn) {
  92. if (!(this instanceof Promise$1))
  93. { throw new TypeError('Promises must be constructed via new'); }
  94. if (typeof fn !== 'function') { throw new TypeError('not a function'); }
  95. /** @type {!number} */
  96. this._state = 0;
  97. /** @type {!boolean} */
  98. this._handled = false;
  99. /** @type {Promise|undefined} */
  100. this._value = undefined;
  101. /** @type {!Array<!Function>} */
  102. this._deferreds = [];
  103. doResolve(fn, this);
  104. }
  105. function handle(self, deferred) {
  106. while (self._state === 3) {
  107. self = self._value;
  108. }
  109. if (self._state === 0) {
  110. self._deferreds.push(deferred);
  111. return;
  112. }
  113. self._handled = true;
  114. Promise$1._immediateFn(function() {
  115. var cb = self._state === 1 ? deferred.onFulfilled : deferred.onRejected;
  116. if (cb === null) {
  117. (self._state === 1 ? resolve$1 : reject)(deferred.promise, self._value);
  118. return;
  119. }
  120. var ret;
  121. try {
  122. ret = cb(self._value);
  123. } catch (e) {
  124. reject(deferred.promise, e);
  125. return;
  126. }
  127. resolve$1(deferred.promise, ret);
  128. });
  129. }
  130. function resolve$1(self, newValue) {
  131. try {
  132. // Promise Resolution Procedure: https://github.com/promises-aplus/promises-spec#the-promise-resolution-procedure
  133. if (newValue === self)
  134. { throw new TypeError('A promise cannot be resolved with itself.'); }
  135. if (
  136. newValue &&
  137. (typeof newValue === 'object' || typeof newValue === 'function')
  138. ) {
  139. var then = newValue.then;
  140. if (newValue instanceof Promise$1) {
  141. self._state = 3;
  142. self._value = newValue;
  143. finale(self);
  144. return;
  145. } else if (typeof then === 'function') {
  146. doResolve(bind(then, newValue), self);
  147. return;
  148. }
  149. }
  150. self._state = 1;
  151. self._value = newValue;
  152. finale(self);
  153. } catch (e) {
  154. reject(self, e);
  155. }
  156. }
  157. function reject(self, newValue) {
  158. self._state = 2;
  159. self._value = newValue;
  160. finale(self);
  161. }
  162. function finale(self) {
  163. if (self._state === 2 && self._deferreds.length === 0) {
  164. Promise$1._immediateFn(function() {
  165. if (!self._handled) {
  166. Promise$1._unhandledRejectionFn(self._value);
  167. }
  168. });
  169. }
  170. for (var i = 0, len = self._deferreds.length; i < len; i++) {
  171. handle(self, self._deferreds[i]);
  172. }
  173. self._deferreds = null;
  174. }
  175. /**
  176. * @constructor
  177. */
  178. function Handler(onFulfilled, onRejected, promise) {
  179. this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null;
  180. this.onRejected = typeof onRejected === 'function' ? onRejected : null;
  181. this.promise = promise;
  182. }
  183. /**
  184. * Take a potentially misbehaving resolver function and make sure
  185. * onFulfilled and onRejected are only called once.
  186. *
  187. * Makes no guarantees about asynchrony.
  188. */
  189. function doResolve(fn, self) {
  190. var done = false;
  191. try {
  192. fn(
  193. function(value) {
  194. if (done) { return; }
  195. done = true;
  196. resolve$1(self, value);
  197. },
  198. function(reason) {
  199. if (done) { return; }
  200. done = true;
  201. reject(self, reason);
  202. }
  203. );
  204. } catch (ex) {
  205. if (done) { return; }
  206. done = true;
  207. reject(self, ex);
  208. }
  209. }
  210. Promise$1.prototype['catch'] = function(onRejected) {
  211. return this.then(null, onRejected);
  212. };
  213. Promise$1.prototype.then = function(onFulfilled, onRejected) {
  214. // @ts-ignore
  215. var prom = new this.constructor(noop);
  216. handle(this, new Handler(onFulfilled, onRejected, prom));
  217. return prom;
  218. };
  219. Promise$1.prototype['finally'] = finallyConstructor;
  220. Promise$1.all = function(arr) {
  221. return new Promise$1(function(resolve, reject) {
  222. if (!isArray(arr)) {
  223. return reject(new TypeError('Promise.all accepts an array'));
  224. }
  225. var args = Array.prototype.slice.call(arr);
  226. if (args.length === 0) { return resolve([]); }
  227. var remaining = args.length;
  228. function res(i, val) {
  229. try {
  230. if (val && (typeof val === 'object' || typeof val === 'function')) {
  231. var then = val.then;
  232. if (typeof then === 'function') {
  233. then.call(
  234. val,
  235. function(val) {
  236. res(i, val);
  237. },
  238. reject
  239. );
  240. return;
  241. }
  242. }
  243. args[i] = val;
  244. if (--remaining === 0) {
  245. resolve(args);
  246. }
  247. } catch (ex) {
  248. reject(ex);
  249. }
  250. }
  251. for (var i = 0; i < args.length; i++) {
  252. res(i, args[i]);
  253. }
  254. });
  255. };
  256. Promise$1.allSettled = allSettled;
  257. Promise$1.resolve = function(value) {
  258. if (value && typeof value === 'object' && value.constructor === Promise$1) {
  259. return value;
  260. }
  261. return new Promise$1(function(resolve) {
  262. resolve(value);
  263. });
  264. };
  265. Promise$1.reject = function(value) {
  266. return new Promise$1(function(resolve, reject) {
  267. reject(value);
  268. });
  269. };
  270. Promise$1.race = function(arr) {
  271. return new Promise$1(function(resolve, reject) {
  272. if (!isArray(arr)) {
  273. return reject(new TypeError('Promise.race accepts an array'));
  274. }
  275. for (var i = 0, len = arr.length; i < len; i++) {
  276. Promise$1.resolve(arr[i]).then(resolve, reject);
  277. }
  278. });
  279. };
  280. // Use polyfill for setImmediate for performance gains
  281. Promise$1._immediateFn =
  282. // @ts-ignore
  283. (typeof setImmediate === 'function' &&
  284. function(fn) {
  285. // @ts-ignore
  286. setImmediate(fn);
  287. }) ||
  288. function(fn) {
  289. setTimeoutFunc(fn, 0);
  290. };
  291. Promise$1._unhandledRejectionFn = function _unhandledRejectionFn(err) {
  292. if (typeof console !== 'undefined' && console) {
  293. console.warn('Possible Unhandled Promise Rejection:', err); // eslint-disable-line no-console
  294. }
  295. };
  296. /*
  297. object-assign
  298. (c) Sindre Sorhus
  299. @license MIT
  300. */
  301. 'use strict';
  302. /* eslint-disable no-unused-vars */
  303. var getOwnPropertySymbols = Object.getOwnPropertySymbols;
  304. var hasOwnProperty$1 = Object.prototype.hasOwnProperty;
  305. var propIsEnumerable = Object.prototype.propertyIsEnumerable;
  306. function toObject(val) {
  307. if (val === null || val === undefined) {
  308. throw new TypeError('Object.assign cannot be called with null or undefined');
  309. }
  310. return Object(val);
  311. }
  312. function shouldUseNative() {
  313. try {
  314. if (!Object.assign) {
  315. return false;
  316. }
  317. // Detect buggy property enumeration order in older V8 versions.
  318. // https://bugs.chromium.org/p/v8/issues/detail?id=4118
  319. var test1 = new String('abc'); // eslint-disable-line no-new-wrappers
  320. test1[5] = 'de';
  321. if (Object.getOwnPropertyNames(test1)[0] === '5') {
  322. return false;
  323. }
  324. // https://bugs.chromium.org/p/v8/issues/detail?id=3056
  325. var test2 = {};
  326. for (var i = 0; i < 10; i++) {
  327. test2['_' + String.fromCharCode(i)] = i;
  328. }
  329. var order2 = Object.getOwnPropertyNames(test2).map(function (n) {
  330. return test2[n];
  331. });
  332. if (order2.join('') !== '0123456789') {
  333. return false;
  334. }
  335. // https://bugs.chromium.org/p/v8/issues/detail?id=3056
  336. var test3 = {};
  337. 'abcdefghijklmnopqrst'.split('').forEach(function (letter) {
  338. test3[letter] = letter;
  339. });
  340. if (Object.keys(Object.assign({}, test3)).join('') !==
  341. 'abcdefghijklmnopqrst') {
  342. return false;
  343. }
  344. return true;
  345. } catch (err) {
  346. // We don't expect any of the above to throw, but better to be safe.
  347. return false;
  348. }
  349. }
  350. var objectAssign = shouldUseNative() ? Object.assign : function (target, source) {
  351. var arguments$1 = arguments;
  352. var from;
  353. var to = toObject(target);
  354. var symbols;
  355. for (var s = 1; s < arguments.length; s++) {
  356. from = Object(arguments$1[s]);
  357. for (var key in from) {
  358. if (hasOwnProperty$1.call(from, key)) {
  359. to[key] = from[key];
  360. }
  361. }
  362. if (getOwnPropertySymbols) {
  363. symbols = getOwnPropertySymbols(from);
  364. for (var i = 0; i < symbols.length; i++) {
  365. if (propIsEnumerable.call(from, symbols[i])) {
  366. to[symbols[i]] = from[symbols[i]];
  367. }
  368. }
  369. }
  370. }
  371. return to;
  372. };
  373. /*!
  374. * @pixi/polyfill - v6.5.10
  375. * Compiled Thu, 06 Jul 2023 15:25:11 UTC
  376. *
  377. * @pixi/polyfill is licensed under the MIT License.
  378. * http://www.opensource.org/licenses/mit-license
  379. */
  380. if (typeof globalThis === 'undefined') {
  381. if (typeof self !== 'undefined') {
  382. // covers browsers
  383. // @ts-expect-error not-writable ts(2540) error only on node
  384. self.globalThis = self;
  385. }
  386. else if (typeof global !== 'undefined') {
  387. // covers versions of Node < 12
  388. // @ts-expect-error not-writable ts(2540) error only on node
  389. global.globalThis = global;
  390. }
  391. }
  392. // Support for IE 9 - 11 which does not include Promises
  393. if (!globalThis.Promise) {
  394. globalThis.Promise = Promise$1;
  395. }
  396. // References:
  397. if (!Object.assign) {
  398. Object.assign = objectAssign;
  399. }
  400. // References:
  401. // http://paulirish.com/2011/requestanimationframe-for-smart-animating/
  402. // https://gist.github.com/1579671
  403. // http://updates.html5rocks.com/2012/05/requestAnimationFrame-API-now-with-sub-millisecond-precision
  404. // https://gist.github.com/timhall/4078614
  405. // https://github.com/Financial-Times/polyfill-service/tree/master/polyfills/requestAnimationFrame
  406. // Expected to be used with Browserfiy
  407. // Browserify automatically detects the use of `global` and passes the
  408. // correct reference of `global`, `globalThis`, and finally `window`
  409. var ONE_FRAME_TIME = 16;
  410. // Date.now
  411. if (!(Date.now && Date.prototype.getTime)) {
  412. Date.now = function now() {
  413. return new Date().getTime();
  414. };
  415. }
  416. // performance.now
  417. if (!(globalThis.performance && globalThis.performance.now)) {
  418. var startTime_1 = Date.now();
  419. if (!globalThis.performance) {
  420. globalThis.performance = {};
  421. }
  422. globalThis.performance.now = function () { return Date.now() - startTime_1; };
  423. }
  424. // requestAnimationFrame
  425. var lastTime = Date.now();
  426. var vendors = ['ms', 'moz', 'webkit', 'o'];
  427. for (var x = 0; x < vendors.length && !globalThis.requestAnimationFrame; ++x) {
  428. var p = vendors[x];
  429. globalThis.requestAnimationFrame = globalThis[p + "RequestAnimationFrame"];
  430. globalThis.cancelAnimationFrame = globalThis[p + "CancelAnimationFrame"]
  431. || globalThis[p + "CancelRequestAnimationFrame"];
  432. }
  433. if (!globalThis.requestAnimationFrame) {
  434. globalThis.requestAnimationFrame = function (callback) {
  435. if (typeof callback !== 'function') {
  436. throw new TypeError(callback + "is not a function");
  437. }
  438. var currentTime = Date.now();
  439. var delay = ONE_FRAME_TIME + lastTime - currentTime;
  440. if (delay < 0) {
  441. delay = 0;
  442. }
  443. lastTime = currentTime;
  444. return globalThis.self.setTimeout(function () {
  445. lastTime = Date.now();
  446. callback(performance.now());
  447. }, delay);
  448. };
  449. }
  450. if (!globalThis.cancelAnimationFrame) {
  451. globalThis.cancelAnimationFrame = function (id) { return clearTimeout(id); };
  452. }
  453. // References:
  454. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sign
  455. if (!Math.sign) {
  456. Math.sign = function mathSign(x) {
  457. x = Number(x);
  458. if (x === 0 || isNaN(x)) {
  459. return x;
  460. }
  461. return x > 0 ? 1 : -1;
  462. };
  463. }
  464. // References:
  465. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isInteger
  466. if (!Number.isInteger) {
  467. Number.isInteger = function numberIsInteger(value) {
  468. return typeof value === 'number' && isFinite(value) && Math.floor(value) === value;
  469. };
  470. }
  471. if (!globalThis.ArrayBuffer) {
  472. globalThis.ArrayBuffer = Array;
  473. }
  474. if (!globalThis.Float32Array) {
  475. globalThis.Float32Array = Array;
  476. }
  477. if (!globalThis.Uint32Array) {
  478. globalThis.Uint32Array = Array;
  479. }
  480. if (!globalThis.Uint16Array) {
  481. globalThis.Uint16Array = Array;
  482. }
  483. if (!globalThis.Uint8Array) {
  484. globalThis.Uint8Array = Array;
  485. }
  486. if (!globalThis.Int32Array) {
  487. globalThis.Int32Array = Array;
  488. }
  489. /*!
  490. * @pixi/constants - v6.5.10
  491. * Compiled Thu, 06 Jul 2023 15:25:11 UTC
  492. *
  493. * @pixi/constants is licensed under the MIT License.
  494. * http://www.opensource.org/licenses/mit-license
  495. */
  496. /**
  497. * Different types of environments for WebGL.
  498. * @static
  499. * @memberof PIXI
  500. * @name ENV
  501. * @enum {number}
  502. * @property {number} WEBGL_LEGACY - Used for older v1 WebGL devices. PixiJS will aim to ensure compatibility
  503. * with older / less advanced devices. If you experience unexplained flickering prefer this environment.
  504. * @property {number} WEBGL - Version 1 of WebGL
  505. * @property {number} WEBGL2 - Version 2 of WebGL
  506. */
  507. var ENV;
  508. (function (ENV) {
  509. ENV[ENV["WEBGL_LEGACY"] = 0] = "WEBGL_LEGACY";
  510. ENV[ENV["WEBGL"] = 1] = "WEBGL";
  511. ENV[ENV["WEBGL2"] = 2] = "WEBGL2";
  512. })(ENV || (ENV = {}));
  513. /**
  514. * Constant to identify the Renderer Type.
  515. * @static
  516. * @memberof PIXI
  517. * @name RENDERER_TYPE
  518. * @enum {number}
  519. * @property {number} UNKNOWN - Unknown render type.
  520. * @property {number} WEBGL - WebGL render type.
  521. * @property {number} CANVAS - Canvas render type.
  522. */
  523. var RENDERER_TYPE;
  524. (function (RENDERER_TYPE) {
  525. RENDERER_TYPE[RENDERER_TYPE["UNKNOWN"] = 0] = "UNKNOWN";
  526. RENDERER_TYPE[RENDERER_TYPE["WEBGL"] = 1] = "WEBGL";
  527. RENDERER_TYPE[RENDERER_TYPE["CANVAS"] = 2] = "CANVAS";
  528. })(RENDERER_TYPE || (RENDERER_TYPE = {}));
  529. /**
  530. * Bitwise OR of masks that indicate the buffers to be cleared.
  531. * @static
  532. * @memberof PIXI
  533. * @name BUFFER_BITS
  534. * @enum {number}
  535. * @property {number} COLOR - Indicates the buffers currently enabled for color writing.
  536. * @property {number} DEPTH - Indicates the depth buffer.
  537. * @property {number} STENCIL - Indicates the stencil buffer.
  538. */
  539. var BUFFER_BITS;
  540. (function (BUFFER_BITS) {
  541. BUFFER_BITS[BUFFER_BITS["COLOR"] = 16384] = "COLOR";
  542. BUFFER_BITS[BUFFER_BITS["DEPTH"] = 256] = "DEPTH";
  543. BUFFER_BITS[BUFFER_BITS["STENCIL"] = 1024] = "STENCIL";
  544. })(BUFFER_BITS || (BUFFER_BITS = {}));
  545. /**
  546. * Various blend modes supported by PIXI.
  547. *
  548. * IMPORTANT - The WebGL renderer only supports the NORMAL, ADD, MULTIPLY and SCREEN blend modes.
  549. * Anything else will silently act like NORMAL.
  550. * @memberof PIXI
  551. * @name BLEND_MODES
  552. * @enum {number}
  553. * @property {number} NORMAL -
  554. * @property {number} ADD -
  555. * @property {number} MULTIPLY -
  556. * @property {number} SCREEN -
  557. * @property {number} OVERLAY -
  558. * @property {number} DARKEN -
  559. * @property {number} LIGHTEN -
  560. * @property {number} COLOR_DODGE -
  561. * @property {number} COLOR_BURN -
  562. * @property {number} HARD_LIGHT -
  563. * @property {number} SOFT_LIGHT -
  564. * @property {number} DIFFERENCE -
  565. * @property {number} EXCLUSION -
  566. * @property {number} HUE -
  567. * @property {number} SATURATION -
  568. * @property {number} COLOR -
  569. * @property {number} LUMINOSITY -
  570. * @property {number} NORMAL_NPM -
  571. * @property {number} ADD_NPM -
  572. * @property {number} SCREEN_NPM -
  573. * @property {number} NONE -
  574. * @property {number} SRC_IN -
  575. * @property {number} SRC_OUT -
  576. * @property {number} SRC_ATOP -
  577. * @property {number} DST_OVER -
  578. * @property {number} DST_IN -
  579. * @property {number} DST_OUT -
  580. * @property {number} DST_ATOP -
  581. * @property {number} SUBTRACT -
  582. * @property {number} SRC_OVER -
  583. * @property {number} ERASE -
  584. * @property {number} XOR -
  585. */
  586. var BLEND_MODES;
  587. (function (BLEND_MODES) {
  588. BLEND_MODES[BLEND_MODES["NORMAL"] = 0] = "NORMAL";
  589. BLEND_MODES[BLEND_MODES["ADD"] = 1] = "ADD";
  590. BLEND_MODES[BLEND_MODES["MULTIPLY"] = 2] = "MULTIPLY";
  591. BLEND_MODES[BLEND_MODES["SCREEN"] = 3] = "SCREEN";
  592. BLEND_MODES[BLEND_MODES["OVERLAY"] = 4] = "OVERLAY";
  593. BLEND_MODES[BLEND_MODES["DARKEN"] = 5] = "DARKEN";
  594. BLEND_MODES[BLEND_MODES["LIGHTEN"] = 6] = "LIGHTEN";
  595. BLEND_MODES[BLEND_MODES["COLOR_DODGE"] = 7] = "COLOR_DODGE";
  596. BLEND_MODES[BLEND_MODES["COLOR_BURN"] = 8] = "COLOR_BURN";
  597. BLEND_MODES[BLEND_MODES["HARD_LIGHT"] = 9] = "HARD_LIGHT";
  598. BLEND_MODES[BLEND_MODES["SOFT_LIGHT"] = 10] = "SOFT_LIGHT";
  599. BLEND_MODES[BLEND_MODES["DIFFERENCE"] = 11] = "DIFFERENCE";
  600. BLEND_MODES[BLEND_MODES["EXCLUSION"] = 12] = "EXCLUSION";
  601. BLEND_MODES[BLEND_MODES["HUE"] = 13] = "HUE";
  602. BLEND_MODES[BLEND_MODES["SATURATION"] = 14] = "SATURATION";
  603. BLEND_MODES[BLEND_MODES["COLOR"] = 15] = "COLOR";
  604. BLEND_MODES[BLEND_MODES["LUMINOSITY"] = 16] = "LUMINOSITY";
  605. BLEND_MODES[BLEND_MODES["NORMAL_NPM"] = 17] = "NORMAL_NPM";
  606. BLEND_MODES[BLEND_MODES["ADD_NPM"] = 18] = "ADD_NPM";
  607. BLEND_MODES[BLEND_MODES["SCREEN_NPM"] = 19] = "SCREEN_NPM";
  608. BLEND_MODES[BLEND_MODES["NONE"] = 20] = "NONE";
  609. BLEND_MODES[BLEND_MODES["SRC_OVER"] = 0] = "SRC_OVER";
  610. BLEND_MODES[BLEND_MODES["SRC_IN"] = 21] = "SRC_IN";
  611. BLEND_MODES[BLEND_MODES["SRC_OUT"] = 22] = "SRC_OUT";
  612. BLEND_MODES[BLEND_MODES["SRC_ATOP"] = 23] = "SRC_ATOP";
  613. BLEND_MODES[BLEND_MODES["DST_OVER"] = 24] = "DST_OVER";
  614. BLEND_MODES[BLEND_MODES["DST_IN"] = 25] = "DST_IN";
  615. BLEND_MODES[BLEND_MODES["DST_OUT"] = 26] = "DST_OUT";
  616. BLEND_MODES[BLEND_MODES["DST_ATOP"] = 27] = "DST_ATOP";
  617. BLEND_MODES[BLEND_MODES["ERASE"] = 26] = "ERASE";
  618. BLEND_MODES[BLEND_MODES["SUBTRACT"] = 28] = "SUBTRACT";
  619. BLEND_MODES[BLEND_MODES["XOR"] = 29] = "XOR";
  620. })(BLEND_MODES || (BLEND_MODES = {}));
  621. /**
  622. * Various webgl draw modes. These can be used to specify which GL drawMode to use
  623. * under certain situations and renderers.
  624. * @memberof PIXI
  625. * @static
  626. * @name DRAW_MODES
  627. * @enum {number}
  628. * @property {number} POINTS -
  629. * @property {number} LINES -
  630. * @property {number} LINE_LOOP -
  631. * @property {number} LINE_STRIP -
  632. * @property {number} TRIANGLES -
  633. * @property {number} TRIANGLE_STRIP -
  634. * @property {number} TRIANGLE_FAN -
  635. */
  636. var DRAW_MODES;
  637. (function (DRAW_MODES) {
  638. DRAW_MODES[DRAW_MODES["POINTS"] = 0] = "POINTS";
  639. DRAW_MODES[DRAW_MODES["LINES"] = 1] = "LINES";
  640. DRAW_MODES[DRAW_MODES["LINE_LOOP"] = 2] = "LINE_LOOP";
  641. DRAW_MODES[DRAW_MODES["LINE_STRIP"] = 3] = "LINE_STRIP";
  642. DRAW_MODES[DRAW_MODES["TRIANGLES"] = 4] = "TRIANGLES";
  643. DRAW_MODES[DRAW_MODES["TRIANGLE_STRIP"] = 5] = "TRIANGLE_STRIP";
  644. DRAW_MODES[DRAW_MODES["TRIANGLE_FAN"] = 6] = "TRIANGLE_FAN";
  645. })(DRAW_MODES || (DRAW_MODES = {}));
  646. /**
  647. * Various GL texture/resources formats.
  648. * @memberof PIXI
  649. * @static
  650. * @name FORMATS
  651. * @enum {number}
  652. * @property {number} [RGBA=6408] -
  653. * @property {number} [RGB=6407] -
  654. * @property {number} [RG=33319] -
  655. * @property {number} [RED=6403] -
  656. * @property {number} [RGBA_INTEGER=36249] -
  657. * @property {number} [RGB_INTEGER=36248] -
  658. * @property {number} [RG_INTEGER=33320] -
  659. * @property {number} [RED_INTEGER=36244] -
  660. * @property {number} [ALPHA=6406] -
  661. * @property {number} [LUMINANCE=6409] -
  662. * @property {number} [LUMINANCE_ALPHA=6410] -
  663. * @property {number} [DEPTH_COMPONENT=6402] -
  664. * @property {number} [DEPTH_STENCIL=34041] -
  665. */
  666. var FORMATS;
  667. (function (FORMATS) {
  668. FORMATS[FORMATS["RGBA"] = 6408] = "RGBA";
  669. FORMATS[FORMATS["RGB"] = 6407] = "RGB";
  670. FORMATS[FORMATS["RG"] = 33319] = "RG";
  671. FORMATS[FORMATS["RED"] = 6403] = "RED";
  672. FORMATS[FORMATS["RGBA_INTEGER"] = 36249] = "RGBA_INTEGER";
  673. FORMATS[FORMATS["RGB_INTEGER"] = 36248] = "RGB_INTEGER";
  674. FORMATS[FORMATS["RG_INTEGER"] = 33320] = "RG_INTEGER";
  675. FORMATS[FORMATS["RED_INTEGER"] = 36244] = "RED_INTEGER";
  676. FORMATS[FORMATS["ALPHA"] = 6406] = "ALPHA";
  677. FORMATS[FORMATS["LUMINANCE"] = 6409] = "LUMINANCE";
  678. FORMATS[FORMATS["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
  679. FORMATS[FORMATS["DEPTH_COMPONENT"] = 6402] = "DEPTH_COMPONENT";
  680. FORMATS[FORMATS["DEPTH_STENCIL"] = 34041] = "DEPTH_STENCIL";
  681. })(FORMATS || (FORMATS = {}));
  682. /**
  683. * Various GL target types.
  684. * @memberof PIXI
  685. * @static
  686. * @name TARGETS
  687. * @enum {number}
  688. * @property {number} [TEXTURE_2D=3553] -
  689. * @property {number} [TEXTURE_CUBE_MAP=34067] -
  690. * @property {number} [TEXTURE_2D_ARRAY=35866] -
  691. * @property {number} [TEXTURE_CUBE_MAP_POSITIVE_X=34069] -
  692. * @property {number} [TEXTURE_CUBE_MAP_NEGATIVE_X=34070] -
  693. * @property {number} [TEXTURE_CUBE_MAP_POSITIVE_Y=34071] -
  694. * @property {number} [TEXTURE_CUBE_MAP_NEGATIVE_Y=34072] -
  695. * @property {number} [TEXTURE_CUBE_MAP_POSITIVE_Z=34073] -
  696. * @property {number} [TEXTURE_CUBE_MAP_NEGATIVE_Z=34074] -
  697. */
  698. var TARGETS;
  699. (function (TARGETS) {
  700. TARGETS[TARGETS["TEXTURE_2D"] = 3553] = "TEXTURE_2D";
  701. TARGETS[TARGETS["TEXTURE_CUBE_MAP"] = 34067] = "TEXTURE_CUBE_MAP";
  702. TARGETS[TARGETS["TEXTURE_2D_ARRAY"] = 35866] = "TEXTURE_2D_ARRAY";
  703. TARGETS[TARGETS["TEXTURE_CUBE_MAP_POSITIVE_X"] = 34069] = "TEXTURE_CUBE_MAP_POSITIVE_X";
  704. TARGETS[TARGETS["TEXTURE_CUBE_MAP_NEGATIVE_X"] = 34070] = "TEXTURE_CUBE_MAP_NEGATIVE_X";
  705. TARGETS[TARGETS["TEXTURE_CUBE_MAP_POSITIVE_Y"] = 34071] = "TEXTURE_CUBE_MAP_POSITIVE_Y";
  706. TARGETS[TARGETS["TEXTURE_CUBE_MAP_NEGATIVE_Y"] = 34072] = "TEXTURE_CUBE_MAP_NEGATIVE_Y";
  707. TARGETS[TARGETS["TEXTURE_CUBE_MAP_POSITIVE_Z"] = 34073] = "TEXTURE_CUBE_MAP_POSITIVE_Z";
  708. TARGETS[TARGETS["TEXTURE_CUBE_MAP_NEGATIVE_Z"] = 34074] = "TEXTURE_CUBE_MAP_NEGATIVE_Z";
  709. })(TARGETS || (TARGETS = {}));
  710. /**
  711. * Various GL data format types.
  712. * @memberof PIXI
  713. * @static
  714. * @name TYPES
  715. * @enum {number}
  716. * @property {number} [UNSIGNED_BYTE=5121] -
  717. * @property {number} [UNSIGNED_SHORT=5123] -
  718. * @property {number} [UNSIGNED_SHORT_5_6_5=33635] -
  719. * @property {number} [UNSIGNED_SHORT_4_4_4_4=32819] -
  720. * @property {number} [UNSIGNED_SHORT_5_5_5_1=32820] -
  721. * @property {number} [UNSIGNED_INT=5125] -
  722. * @property {number} [UNSIGNED_INT_10F_11F_11F_REV=35899] -
  723. * @property {number} [UNSIGNED_INT_2_10_10_10_REV=33640] -
  724. * @property {number} [UNSIGNED_INT_24_8=34042] -
  725. * @property {number} [UNSIGNED_INT_5_9_9_9_REV=35902] -
  726. * @property {number} [BYTE=5120] -
  727. * @property {number} [SHORT=5122] -
  728. * @property {number} [INT=5124] -
  729. * @property {number} [FLOAT=5126] -
  730. * @property {number} [FLOAT_32_UNSIGNED_INT_24_8_REV=36269] -
  731. * @property {number} [HALF_FLOAT=36193] -
  732. */
  733. var TYPES;
  734. (function (TYPES) {
  735. TYPES[TYPES["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  736. TYPES[TYPES["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  737. TYPES[TYPES["UNSIGNED_SHORT_5_6_5"] = 33635] = "UNSIGNED_SHORT_5_6_5";
  738. TYPES[TYPES["UNSIGNED_SHORT_4_4_4_4"] = 32819] = "UNSIGNED_SHORT_4_4_4_4";
  739. TYPES[TYPES["UNSIGNED_SHORT_5_5_5_1"] = 32820] = "UNSIGNED_SHORT_5_5_5_1";
  740. TYPES[TYPES["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  741. TYPES[TYPES["UNSIGNED_INT_10F_11F_11F_REV"] = 35899] = "UNSIGNED_INT_10F_11F_11F_REV";
  742. TYPES[TYPES["UNSIGNED_INT_2_10_10_10_REV"] = 33640] = "UNSIGNED_INT_2_10_10_10_REV";
  743. TYPES[TYPES["UNSIGNED_INT_24_8"] = 34042] = "UNSIGNED_INT_24_8";
  744. TYPES[TYPES["UNSIGNED_INT_5_9_9_9_REV"] = 35902] = "UNSIGNED_INT_5_9_9_9_REV";
  745. TYPES[TYPES["BYTE"] = 5120] = "BYTE";
  746. TYPES[TYPES["SHORT"] = 5122] = "SHORT";
  747. TYPES[TYPES["INT"] = 5124] = "INT";
  748. TYPES[TYPES["FLOAT"] = 5126] = "FLOAT";
  749. TYPES[TYPES["FLOAT_32_UNSIGNED_INT_24_8_REV"] = 36269] = "FLOAT_32_UNSIGNED_INT_24_8_REV";
  750. TYPES[TYPES["HALF_FLOAT"] = 36193] = "HALF_FLOAT";
  751. })(TYPES || (TYPES = {}));
  752. /**
  753. * Various sampler types. Correspond to `sampler`, `isampler`, `usampler` GLSL types respectively.
  754. * WebGL1 works only with FLOAT.
  755. * @memberof PIXI
  756. * @static
  757. * @name SAMPLER_TYPES
  758. * @enum {number}
  759. * @property {number} [FLOAT=0] -
  760. * @property {number} [INT=1] -
  761. * @property {number} [UINT=2] -
  762. */
  763. var SAMPLER_TYPES;
  764. (function (SAMPLER_TYPES) {
  765. SAMPLER_TYPES[SAMPLER_TYPES["FLOAT"] = 0] = "FLOAT";
  766. SAMPLER_TYPES[SAMPLER_TYPES["INT"] = 1] = "INT";
  767. SAMPLER_TYPES[SAMPLER_TYPES["UINT"] = 2] = "UINT";
  768. })(SAMPLER_TYPES || (SAMPLER_TYPES = {}));
  769. /**
  770. * The scale modes that are supported by pixi.
  771. *
  772. * The {@link PIXI.settings.SCALE_MODE} scale mode affects the default scaling mode of future operations.
  773. * It can be re-assigned to either LINEAR or NEAREST, depending upon suitability.
  774. * @memberof PIXI
  775. * @static
  776. * @name SCALE_MODES
  777. * @enum {number}
  778. * @property {number} LINEAR Smooth scaling
  779. * @property {number} NEAREST Pixelating scaling
  780. */
  781. var SCALE_MODES;
  782. (function (SCALE_MODES) {
  783. SCALE_MODES[SCALE_MODES["NEAREST"] = 0] = "NEAREST";
  784. SCALE_MODES[SCALE_MODES["LINEAR"] = 1] = "LINEAR";
  785. })(SCALE_MODES || (SCALE_MODES = {}));
  786. /**
  787. * The wrap modes that are supported by pixi.
  788. *
  789. * The {@link PIXI.settings.WRAP_MODE} wrap mode affects the default wrapping mode of future operations.
  790. * It can be re-assigned to either CLAMP or REPEAT, depending upon suitability.
  791. * If the texture is non power of two then clamp will be used regardless as WebGL can
  792. * only use REPEAT if the texture is po2.
  793. *
  794. * This property only affects WebGL.
  795. * @name WRAP_MODES
  796. * @memberof PIXI
  797. * @static
  798. * @enum {number}
  799. * @property {number} CLAMP - The textures uvs are clamped
  800. * @property {number} REPEAT - The texture uvs tile and repeat
  801. * @property {number} MIRRORED_REPEAT - The texture uvs tile and repeat with mirroring
  802. */
  803. var WRAP_MODES;
  804. (function (WRAP_MODES) {
  805. WRAP_MODES[WRAP_MODES["CLAMP"] = 33071] = "CLAMP";
  806. WRAP_MODES[WRAP_MODES["REPEAT"] = 10497] = "REPEAT";
  807. WRAP_MODES[WRAP_MODES["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  808. })(WRAP_MODES || (WRAP_MODES = {}));
  809. /**
  810. * Mipmap filtering modes that are supported by pixi.
  811. *
  812. * The {@link PIXI.settings.MIPMAP_TEXTURES} affects default texture filtering.
  813. * Mipmaps are generated for a baseTexture if its `mipmap` field is `ON`,
  814. * or its `POW2` and texture dimensions are powers of 2.
  815. * Due to platform restriction, `ON` option will work like `POW2` for webgl-1.
  816. *
  817. * This property only affects WebGL.
  818. * @name MIPMAP_MODES
  819. * @memberof PIXI
  820. * @static
  821. * @enum {number}
  822. * @property {number} OFF - No mipmaps
  823. * @property {number} POW2 - Generate mipmaps if texture dimensions are pow2
  824. * @property {number} ON - Always generate mipmaps
  825. * @property {number} ON_MANUAL - Use mipmaps, but do not auto-generate them; this is used with a resource
  826. * that supports buffering each level-of-detail.
  827. */
  828. var MIPMAP_MODES;
  829. (function (MIPMAP_MODES) {
  830. MIPMAP_MODES[MIPMAP_MODES["OFF"] = 0] = "OFF";
  831. MIPMAP_MODES[MIPMAP_MODES["POW2"] = 1] = "POW2";
  832. MIPMAP_MODES[MIPMAP_MODES["ON"] = 2] = "ON";
  833. MIPMAP_MODES[MIPMAP_MODES["ON_MANUAL"] = 3] = "ON_MANUAL";
  834. })(MIPMAP_MODES || (MIPMAP_MODES = {}));
  835. /**
  836. * How to treat textures with premultiplied alpha
  837. * @name ALPHA_MODES
  838. * @memberof PIXI
  839. * @static
  840. * @enum {number}
  841. * @property {number} NO_PREMULTIPLIED_ALPHA - Source is not premultiplied, leave it like that.
  842. * Option for compressed and data textures that are created from typed arrays.
  843. * @property {number} PREMULTIPLY_ON_UPLOAD - Source is not premultiplied, premultiply on upload.
  844. * Default option, used for all loaded images.
  845. * @property {number} PREMULTIPLIED_ALPHA - Source is already premultiplied
  846. * Example: spine atlases with `_pma` suffix.
  847. * @property {number} NPM - Alias for NO_PREMULTIPLIED_ALPHA.
  848. * @property {number} UNPACK - Default option, alias for PREMULTIPLY_ON_UPLOAD.
  849. * @property {number} PMA - Alias for PREMULTIPLIED_ALPHA.
  850. */
  851. var ALPHA_MODES;
  852. (function (ALPHA_MODES) {
  853. ALPHA_MODES[ALPHA_MODES["NPM"] = 0] = "NPM";
  854. ALPHA_MODES[ALPHA_MODES["UNPACK"] = 1] = "UNPACK";
  855. ALPHA_MODES[ALPHA_MODES["PMA"] = 2] = "PMA";
  856. ALPHA_MODES[ALPHA_MODES["NO_PREMULTIPLIED_ALPHA"] = 0] = "NO_PREMULTIPLIED_ALPHA";
  857. ALPHA_MODES[ALPHA_MODES["PREMULTIPLY_ON_UPLOAD"] = 1] = "PREMULTIPLY_ON_UPLOAD";
  858. ALPHA_MODES[ALPHA_MODES["PREMULTIPLY_ALPHA"] = 2] = "PREMULTIPLY_ALPHA";
  859. ALPHA_MODES[ALPHA_MODES["PREMULTIPLIED_ALPHA"] = 2] = "PREMULTIPLIED_ALPHA";
  860. })(ALPHA_MODES || (ALPHA_MODES = {}));
  861. /**
  862. * Configure whether filter textures are cleared after binding.
  863. *
  864. * Filter textures need not be cleared if the filter does not use pixel blending. {@link CLEAR_MODES.BLIT} will detect
  865. * this and skip clearing as an optimization.
  866. * @name CLEAR_MODES
  867. * @memberof PIXI
  868. * @static
  869. * @enum {number}
  870. * @property {number} BLEND - Do not clear the filter texture. The filter's output will blend on top of the output texture.
  871. * @property {number} CLEAR - Always clear the filter texture.
  872. * @property {number} BLIT - Clear only if {@link FilterSystem.forceClear} is set or if the filter uses pixel blending.
  873. * @property {number} NO - Alias for BLEND, same as `false` in earlier versions
  874. * @property {number} YES - Alias for CLEAR, same as `true` in earlier versions
  875. * @property {number} AUTO - Alias for BLIT
  876. */
  877. var CLEAR_MODES;
  878. (function (CLEAR_MODES) {
  879. CLEAR_MODES[CLEAR_MODES["NO"] = 0] = "NO";
  880. CLEAR_MODES[CLEAR_MODES["YES"] = 1] = "YES";
  881. CLEAR_MODES[CLEAR_MODES["AUTO"] = 2] = "AUTO";
  882. CLEAR_MODES[CLEAR_MODES["BLEND"] = 0] = "BLEND";
  883. CLEAR_MODES[CLEAR_MODES["CLEAR"] = 1] = "CLEAR";
  884. CLEAR_MODES[CLEAR_MODES["BLIT"] = 2] = "BLIT";
  885. })(CLEAR_MODES || (CLEAR_MODES = {}));
  886. /**
  887. * The gc modes that are supported by pixi.
  888. *
  889. * The {@link PIXI.settings.GC_MODE} Garbage Collection mode for PixiJS textures is AUTO
  890. * If set to GC_MODE, the renderer will occasionally check textures usage. If they are not
  891. * used for a specified period of time they will be removed from the GPU. They will of course
  892. * be uploaded again when they are required. This is a silent behind the scenes process that
  893. * should ensure that the GPU does not get filled up.
  894. *
  895. * Handy for mobile devices!
  896. * This property only affects WebGL.
  897. * @name GC_MODES
  898. * @enum {number}
  899. * @static
  900. * @memberof PIXI
  901. * @property {number} AUTO - Garbage collection will happen periodically automatically
  902. * @property {number} MANUAL - Garbage collection will need to be called manually
  903. */
  904. var GC_MODES;
  905. (function (GC_MODES) {
  906. GC_MODES[GC_MODES["AUTO"] = 0] = "AUTO";
  907. GC_MODES[GC_MODES["MANUAL"] = 1] = "MANUAL";
  908. })(GC_MODES || (GC_MODES = {}));
  909. /**
  910. * Constants that specify float precision in shaders.
  911. * @name PRECISION
  912. * @memberof PIXI
  913. * @constant
  914. * @static
  915. * @enum {string}
  916. * @property {string} [LOW='lowp'] -
  917. * @property {string} [MEDIUM='mediump'] -
  918. * @property {string} [HIGH='highp'] -
  919. */
  920. var PRECISION;
  921. (function (PRECISION) {
  922. PRECISION["LOW"] = "lowp";
  923. PRECISION["MEDIUM"] = "mediump";
  924. PRECISION["HIGH"] = "highp";
  925. })(PRECISION || (PRECISION = {}));
  926. /**
  927. * Constants for mask implementations.
  928. * We use `type` suffix because it leads to very different behaviours
  929. * @name MASK_TYPES
  930. * @memberof PIXI
  931. * @static
  932. * @enum {number}
  933. * @property {number} NONE - Mask is ignored
  934. * @property {number} SCISSOR - Scissor mask, rectangle on screen, cheap
  935. * @property {number} STENCIL - Stencil mask, 1-bit, medium, works only if renderer supports stencil
  936. * @property {number} SPRITE - Mask that uses SpriteMaskFilter, uses temporary RenderTexture
  937. * @property {number} COLOR - Color mask (RGBA)
  938. */
  939. var MASK_TYPES;
  940. (function (MASK_TYPES) {
  941. MASK_TYPES[MASK_TYPES["NONE"] = 0] = "NONE";
  942. MASK_TYPES[MASK_TYPES["SCISSOR"] = 1] = "SCISSOR";
  943. MASK_TYPES[MASK_TYPES["STENCIL"] = 2] = "STENCIL";
  944. MASK_TYPES[MASK_TYPES["SPRITE"] = 3] = "SPRITE";
  945. MASK_TYPES[MASK_TYPES["COLOR"] = 4] = "COLOR";
  946. })(MASK_TYPES || (MASK_TYPES = {}));
  947. /**
  948. * Bitwise OR of masks that indicate the color channels that are rendered to.
  949. * @static
  950. * @memberof PIXI
  951. * @name COLOR_MASK_BITS
  952. * @enum {number}
  953. * @property {number} RED - Red channel.
  954. * @property {number} GREEN - Green channel
  955. * @property {number} BLUE - Blue channel.
  956. * @property {number} ALPHA - Alpha channel.
  957. */
  958. var COLOR_MASK_BITS;
  959. (function (COLOR_MASK_BITS) {
  960. COLOR_MASK_BITS[COLOR_MASK_BITS["RED"] = 1] = "RED";
  961. COLOR_MASK_BITS[COLOR_MASK_BITS["GREEN"] = 2] = "GREEN";
  962. COLOR_MASK_BITS[COLOR_MASK_BITS["BLUE"] = 4] = "BLUE";
  963. COLOR_MASK_BITS[COLOR_MASK_BITS["ALPHA"] = 8] = "ALPHA";
  964. })(COLOR_MASK_BITS || (COLOR_MASK_BITS = {}));
  965. /**
  966. * Constants for multi-sampling antialiasing.
  967. * @see PIXI.Framebuffer#multisample
  968. * @name MSAA_QUALITY
  969. * @memberof PIXI
  970. * @static
  971. * @enum {number}
  972. * @property {number} NONE - No multisampling for this renderTexture
  973. * @property {number} LOW - Try 2 samples
  974. * @property {number} MEDIUM - Try 4 samples
  975. * @property {number} HIGH - Try 8 samples
  976. */
  977. var MSAA_QUALITY;
  978. (function (MSAA_QUALITY) {
  979. MSAA_QUALITY[MSAA_QUALITY["NONE"] = 0] = "NONE";
  980. MSAA_QUALITY[MSAA_QUALITY["LOW"] = 2] = "LOW";
  981. MSAA_QUALITY[MSAA_QUALITY["MEDIUM"] = 4] = "MEDIUM";
  982. MSAA_QUALITY[MSAA_QUALITY["HIGH"] = 8] = "HIGH";
  983. })(MSAA_QUALITY || (MSAA_QUALITY = {}));
  984. /**
  985. * Constants for various buffer types in Pixi
  986. * @see PIXI.BUFFER_TYPE
  987. * @name BUFFER_TYPE
  988. * @memberof PIXI
  989. * @static
  990. * @enum {number}
  991. * @property {number} ELEMENT_ARRAY_BUFFER - buffer type for using as an index buffer
  992. * @property {number} ARRAY_BUFFER - buffer type for using attribute data
  993. * @property {number} UNIFORM_BUFFER - the buffer type is for uniform buffer objects
  994. */
  995. var BUFFER_TYPE;
  996. (function (BUFFER_TYPE) {
  997. BUFFER_TYPE[BUFFER_TYPE["ELEMENT_ARRAY_BUFFER"] = 34963] = "ELEMENT_ARRAY_BUFFER";
  998. BUFFER_TYPE[BUFFER_TYPE["ARRAY_BUFFER"] = 34962] = "ARRAY_BUFFER";
  999. // NOT YET SUPPORTED
  1000. BUFFER_TYPE[BUFFER_TYPE["UNIFORM_BUFFER"] = 35345] = "UNIFORM_BUFFER";
  1001. })(BUFFER_TYPE || (BUFFER_TYPE = {}));
  1002. /*!
  1003. * @pixi/settings - v6.5.10
  1004. * Compiled Thu, 06 Jul 2023 15:25:11 UTC
  1005. *
  1006. * @pixi/settings is licensed under the MIT License.
  1007. * http://www.opensource.org/licenses/mit-license
  1008. */
  1009. var BrowserAdapter = {
  1010. /**
  1011. * Creates a canvas element of the given size.
  1012. * This canvas is created using the browser's native canvas element.
  1013. * @param width - width of the canvas
  1014. * @param height - height of the canvas
  1015. */
  1016. createCanvas: function (width, height) {
  1017. var canvas = document.createElement('canvas');
  1018. canvas.width = width;
  1019. canvas.height = height;
  1020. return canvas;
  1021. },
  1022. getWebGLRenderingContext: function () { return WebGLRenderingContext; },
  1023. getNavigator: function () { return navigator; },
  1024. getBaseUrl: function () { var _a; return ((_a = document.baseURI) !== null && _a !== void 0 ? _a : window.location.href); },
  1025. fetch: function (url, options) { return fetch(url, options); },
  1026. };
  1027. var appleIphone = /iPhone/i;
  1028. var appleIpod = /iPod/i;
  1029. var appleTablet = /iPad/i;
  1030. var appleUniversal = /\biOS-universal(?:.+)Mac\b/i;
  1031. var androidPhone = /\bAndroid(?:.+)Mobile\b/i;
  1032. var androidTablet = /Android/i;
  1033. var amazonPhone = /(?:SD4930UR|\bSilk(?:.+)Mobile\b)/i;
  1034. var amazonTablet = /Silk/i;
  1035. var windowsPhone = /Windows Phone/i;
  1036. var windowsTablet = /\bWindows(?:.+)ARM\b/i;
  1037. var otherBlackBerry = /BlackBerry/i;
  1038. var otherBlackBerry10 = /BB10/i;
  1039. var otherOpera = /Opera Mini/i;
  1040. var otherChrome = /\b(CriOS|Chrome)(?:.+)Mobile/i;
  1041. var otherFirefox = /Mobile(?:.+)Firefox\b/i;
  1042. var isAppleTabletOnIos13 = function (navigator) {
  1043. return (typeof navigator !== 'undefined' &&
  1044. navigator.platform === 'MacIntel' &&
  1045. typeof navigator.maxTouchPoints === 'number' &&
  1046. navigator.maxTouchPoints > 1 &&
  1047. typeof MSStream === 'undefined');
  1048. };
  1049. function createMatch(userAgent) {
  1050. return function (regex) { return regex.test(userAgent); };
  1051. }
  1052. function isMobile$1(param) {
  1053. var nav = {
  1054. userAgent: '',
  1055. platform: '',
  1056. maxTouchPoints: 0
  1057. };
  1058. if (!param && typeof navigator !== 'undefined') {
  1059. nav = {
  1060. userAgent: navigator.userAgent,
  1061. platform: navigator.platform,
  1062. maxTouchPoints: navigator.maxTouchPoints || 0
  1063. };
  1064. }
  1065. else if (typeof param === 'string') {
  1066. nav.userAgent = param;
  1067. }
  1068. else if (param && param.userAgent) {
  1069. nav = {
  1070. userAgent: param.userAgent,
  1071. platform: param.platform,
  1072. maxTouchPoints: param.maxTouchPoints || 0
  1073. };
  1074. }
  1075. var userAgent = nav.userAgent;
  1076. var tmp = userAgent.split('[FBAN');
  1077. if (typeof tmp[1] !== 'undefined') {
  1078. userAgent = tmp[0];
  1079. }
  1080. tmp = userAgent.split('Twitter');
  1081. if (typeof tmp[1] !== 'undefined') {
  1082. userAgent = tmp[0];
  1083. }
  1084. var match = createMatch(userAgent);
  1085. var result = {
  1086. apple: {
  1087. phone: match(appleIphone) && !match(windowsPhone),
  1088. ipod: match(appleIpod),
  1089. tablet: !match(appleIphone) &&
  1090. (match(appleTablet) || isAppleTabletOnIos13(nav)) &&
  1091. !match(windowsPhone),
  1092. universal: match(appleUniversal),
  1093. device: (match(appleIphone) ||
  1094. match(appleIpod) ||
  1095. match(appleTablet) ||
  1096. match(appleUniversal) ||
  1097. isAppleTabletOnIos13(nav)) &&
  1098. !match(windowsPhone)
  1099. },
  1100. amazon: {
  1101. phone: match(amazonPhone),
  1102. tablet: !match(amazonPhone) && match(amazonTablet),
  1103. device: match(amazonPhone) || match(amazonTablet)
  1104. },
  1105. android: {
  1106. phone: (!match(windowsPhone) && match(amazonPhone)) ||
  1107. (!match(windowsPhone) && match(androidPhone)),
  1108. tablet: !match(windowsPhone) &&
  1109. !match(amazonPhone) &&
  1110. !match(androidPhone) &&
  1111. (match(amazonTablet) || match(androidTablet)),
  1112. device: (!match(windowsPhone) &&
  1113. (match(amazonPhone) ||
  1114. match(amazonTablet) ||
  1115. match(androidPhone) ||
  1116. match(androidTablet))) ||
  1117. match(/\bokhttp\b/i)
  1118. },
  1119. windows: {
  1120. phone: match(windowsPhone),
  1121. tablet: match(windowsTablet),
  1122. device: match(windowsPhone) || match(windowsTablet)
  1123. },
  1124. other: {
  1125. blackberry: match(otherBlackBerry),
  1126. blackberry10: match(otherBlackBerry10),
  1127. opera: match(otherOpera),
  1128. firefox: match(otherFirefox),
  1129. chrome: match(otherChrome),
  1130. device: match(otherBlackBerry) ||
  1131. match(otherBlackBerry10) ||
  1132. match(otherOpera) ||
  1133. match(otherFirefox) ||
  1134. match(otherChrome)
  1135. },
  1136. any: false,
  1137. phone: false,
  1138. tablet: false
  1139. };
  1140. result.any =
  1141. result.apple.device ||
  1142. result.android.device ||
  1143. result.windows.device ||
  1144. result.other.device;
  1145. result.phone =
  1146. result.apple.phone || result.android.phone || result.windows.phone;
  1147. result.tablet =
  1148. result.apple.tablet || result.android.tablet || result.windows.tablet;
  1149. return result;
  1150. }
  1151. var isMobile = isMobile$1(globalThis.navigator);
  1152. /**
  1153. * Uploading the same buffer multiple times in a single frame can cause performance issues.
  1154. * Apparent on iOS so only check for that at the moment
  1155. * This check may become more complex if this issue pops up elsewhere.
  1156. * @private
  1157. * @returns {boolean} `true` if the same buffer may be uploaded more than once.
  1158. */
  1159. function canUploadSameBuffer() {
  1160. return !isMobile.apple.device;
  1161. }
  1162. /**
  1163. * The maximum recommended texture units to use.
  1164. * In theory the bigger the better, and for desktop we'll use as many as we can.
  1165. * But some mobile devices slow down if there is to many branches in the shader.
  1166. * So in practice there seems to be a sweet spot size that varies depending on the device.
  1167. *
  1168. * In v4, all mobile devices were limited to 4 texture units because for this.
  1169. * In v5, we allow all texture units to be used on modern Apple or Android devices.
  1170. * @private
  1171. * @param {number} max
  1172. * @returns {number} The maximum recommended texture units to use.
  1173. */
  1174. function maxRecommendedTextures(max) {
  1175. var allowMax = true;
  1176. if (isMobile.tablet || isMobile.phone) {
  1177. if (isMobile.apple.device) {
  1178. var match = (navigator.userAgent).match(/OS (\d+)_(\d+)?/);
  1179. if (match) {
  1180. var majorVersion = parseInt(match[1], 10);
  1181. // Limit texture units on devices below iOS 11, which will be older hardware
  1182. if (majorVersion < 11) {
  1183. allowMax = false;
  1184. }
  1185. }
  1186. }
  1187. if (isMobile.android.device) {
  1188. var match = (navigator.userAgent).match(/Android\s([0-9.]*)/);
  1189. if (match) {
  1190. var majorVersion = parseInt(match[1], 10);
  1191. // Limit texture units on devices below Android 7 (Nougat), which will be older hardware
  1192. if (majorVersion < 7) {
  1193. allowMax = false;
  1194. }
  1195. }
  1196. }
  1197. }
  1198. return allowMax ? max : 4;
  1199. }
  1200. /**
  1201. * User's customizable globals for overriding the default PIXI settings, such
  1202. * as a renderer's default resolution, framerate, float precision, etc.
  1203. * @example
  1204. * // Use the native window resolution as the default resolution
  1205. * // will support high-density displays when rendering
  1206. * PIXI.settings.RESOLUTION = window.devicePixelRatio;
  1207. *
  1208. * // Disable interpolation when scaling, will make texture be pixelated
  1209. * PIXI.settings.SCALE_MODE = PIXI.SCALE_MODES.NEAREST;
  1210. * @namespace PIXI.settings
  1211. */
  1212. var settings = {
  1213. /**
  1214. * This adapter is used to call methods that are platform dependent.
  1215. * For example `document.createElement` only runs on the web but fails in node environments.
  1216. * This allows us to support more platforms by abstracting away specific implementations per platform.
  1217. *
  1218. * By default the adapter is set to work in the browser. However you can create your own
  1219. * by implementing the `IAdapter` interface. See `IAdapter` for more information.
  1220. * @name ADAPTER
  1221. * @memberof PIXI.settings
  1222. * @type {PIXI.IAdapter}
  1223. * @default PIXI.BrowserAdapter
  1224. */
  1225. ADAPTER: BrowserAdapter,
  1226. /**
  1227. * If set to true WebGL will attempt make textures mimpaped by default.
  1228. * Mipmapping will only succeed if the base texture uploaded has power of two dimensions.
  1229. * @static
  1230. * @name MIPMAP_TEXTURES
  1231. * @memberof PIXI.settings
  1232. * @type {PIXI.MIPMAP_MODES}
  1233. * @default PIXI.MIPMAP_MODES.POW2
  1234. */
  1235. MIPMAP_TEXTURES: MIPMAP_MODES.POW2,
  1236. /**
  1237. * Default anisotropic filtering level of textures.
  1238. * Usually from 0 to 16
  1239. * @static
  1240. * @name ANISOTROPIC_LEVEL
  1241. * @memberof PIXI.settings
  1242. * @type {number}
  1243. * @default 0
  1244. */
  1245. ANISOTROPIC_LEVEL: 0,
  1246. /**
  1247. * Default resolution / device pixel ratio of the renderer.
  1248. * @static
  1249. * @name RESOLUTION
  1250. * @memberof PIXI.settings
  1251. * @type {number}
  1252. * @default 1
  1253. */
  1254. RESOLUTION: 1,
  1255. /**
  1256. * Default filter resolution.
  1257. * @static
  1258. * @name FILTER_RESOLUTION
  1259. * @memberof PIXI.settings
  1260. * @type {number}
  1261. * @default 1
  1262. */
  1263. FILTER_RESOLUTION: 1,
  1264. /**
  1265. * Default filter samples.
  1266. * @static
  1267. * @name FILTER_MULTISAMPLE
  1268. * @memberof PIXI.settings
  1269. * @type {PIXI.MSAA_QUALITY}
  1270. * @default PIXI.MSAA_QUALITY.NONE
  1271. */
  1272. FILTER_MULTISAMPLE: MSAA_QUALITY.NONE,
  1273. /**
  1274. * The maximum textures that this device supports.
  1275. * @static
  1276. * @name SPRITE_MAX_TEXTURES
  1277. * @memberof PIXI.settings
  1278. * @type {number}
  1279. * @default 32
  1280. */
  1281. SPRITE_MAX_TEXTURES: maxRecommendedTextures(32),
  1282. // TODO: maybe change to SPRITE.BATCH_SIZE: 2000
  1283. // TODO: maybe add PARTICLE.BATCH_SIZE: 15000
  1284. /**
  1285. * The default sprite batch size.
  1286. *
  1287. * The default aims to balance desktop and mobile devices.
  1288. * @static
  1289. * @name SPRITE_BATCH_SIZE
  1290. * @memberof PIXI.settings
  1291. * @type {number}
  1292. * @default 4096
  1293. */
  1294. SPRITE_BATCH_SIZE: 4096,
  1295. /**
  1296. * The default render options if none are supplied to {@link PIXI.Renderer}
  1297. * or {@link PIXI.CanvasRenderer}.
  1298. * @static
  1299. * @name RENDER_OPTIONS
  1300. * @memberof PIXI.settings
  1301. * @type {object}
  1302. * @property {boolean} [antialias=false] - {@link PIXI.IRendererOptions.antialias}
  1303. * @property {boolean} [autoDensity=false] - {@link PIXI.IRendererOptions.autoDensity}
  1304. * @property {number} [backgroundAlpha=1] - {@link PIXI.IRendererOptions.backgroundAlpha}
  1305. * @property {number} [backgroundColor=0x000000] - {@link PIXI.IRendererOptions.backgroundColor}
  1306. * @property {boolean} [clearBeforeRender=true] - {@link PIXI.IRendererOptions.clearBeforeRender}
  1307. * @property {number} [height=600] - {@link PIXI.IRendererOptions.height}
  1308. * @property {boolean} [preserveDrawingBuffer=false] - {@link PIXI.IRendererOptions.preserveDrawingBuffer}
  1309. * @property {boolean|'notMultiplied'} [useContextAlpha=true] - {@link PIXI.IRendererOptions.useContextAlpha}
  1310. * @property {HTMLCanvasElement} [view=null] - {@link PIXI.IRendererOptions.view}
  1311. * @property {number} [width=800] - {@link PIXI.IRendererOptions.width}
  1312. */
  1313. RENDER_OPTIONS: {
  1314. view: null,
  1315. width: 800,
  1316. height: 600,
  1317. autoDensity: false,
  1318. backgroundColor: 0x000000,
  1319. backgroundAlpha: 1,
  1320. useContextAlpha: true,
  1321. clearBeforeRender: true,
  1322. antialias: false,
  1323. preserveDrawingBuffer: false,
  1324. },
  1325. /**
  1326. * Default Garbage Collection mode.
  1327. * @static
  1328. * @name GC_MODE
  1329. * @memberof PIXI.settings
  1330. * @type {PIXI.GC_MODES}
  1331. * @default PIXI.GC_MODES.AUTO
  1332. */
  1333. GC_MODE: GC_MODES.AUTO,
  1334. /**
  1335. * Default Garbage Collection max idle.
  1336. * @static
  1337. * @name GC_MAX_IDLE
  1338. * @memberof PIXI.settings
  1339. * @type {number}
  1340. * @default 3600
  1341. */
  1342. GC_MAX_IDLE: 60 * 60,
  1343. /**
  1344. * Default Garbage Collection maximum check count.
  1345. * @static
  1346. * @name GC_MAX_CHECK_COUNT
  1347. * @memberof PIXI.settings
  1348. * @type {number}
  1349. * @default 600
  1350. */
  1351. GC_MAX_CHECK_COUNT: 60 * 10,
  1352. /**
  1353. * Default wrap modes that are supported by pixi.
  1354. * @static
  1355. * @name WRAP_MODE
  1356. * @memberof PIXI.settings
  1357. * @type {PIXI.WRAP_MODES}
  1358. * @default PIXI.WRAP_MODES.CLAMP
  1359. */
  1360. WRAP_MODE: WRAP_MODES.CLAMP,
  1361. /**
  1362. * Default scale mode for textures.
  1363. * @static
  1364. * @name SCALE_MODE
  1365. * @memberof PIXI.settings
  1366. * @type {PIXI.SCALE_MODES}
  1367. * @default PIXI.SCALE_MODES.LINEAR
  1368. */
  1369. SCALE_MODE: SCALE_MODES.LINEAR,
  1370. /**
  1371. * Default specify float precision in vertex shader.
  1372. * @static
  1373. * @name PRECISION_VERTEX
  1374. * @memberof PIXI.settings
  1375. * @type {PIXI.PRECISION}
  1376. * @default PIXI.PRECISION.HIGH
  1377. */
  1378. PRECISION_VERTEX: PRECISION.HIGH,
  1379. /**
  1380. * Default specify float precision in fragment shader.
  1381. * iOS is best set at highp due to https://github.com/pixijs/pixi.js/issues/3742
  1382. * @static
  1383. * @name PRECISION_FRAGMENT
  1384. * @memberof PIXI.settings
  1385. * @type {PIXI.PRECISION}
  1386. * @default PIXI.PRECISION.MEDIUM
  1387. */
  1388. PRECISION_FRAGMENT: isMobile.apple.device ? PRECISION.HIGH : PRECISION.MEDIUM,
  1389. /**
  1390. * Can we upload the same buffer in a single frame?
  1391. * @static
  1392. * @name CAN_UPLOAD_SAME_BUFFER
  1393. * @memberof PIXI.settings
  1394. * @type {boolean}
  1395. */
  1396. CAN_UPLOAD_SAME_BUFFER: canUploadSameBuffer(),
  1397. /**
  1398. * Enables bitmap creation before image load. This feature is experimental.
  1399. * @static
  1400. * @name CREATE_IMAGE_BITMAP
  1401. * @memberof PIXI.settings
  1402. * @type {boolean}
  1403. * @default false
  1404. */
  1405. CREATE_IMAGE_BITMAP: false,
  1406. /**
  1407. * If true PixiJS will Math.floor() x/y values when rendering, stopping pixel interpolation.
  1408. * Advantages can include sharper image quality (like text) and faster rendering on canvas.
  1409. * The main disadvantage is movement of objects may appear less smooth.
  1410. * @static
  1411. * @constant
  1412. * @memberof PIXI.settings
  1413. * @type {boolean}
  1414. * @default false
  1415. */
  1416. ROUND_PIXELS: false,
  1417. };
  1418. var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
  1419. function getDefaultExportFromCjs (x) {
  1420. return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
  1421. }
  1422. function createCommonjsModule(fn, basedir, module) {
  1423. return module = {
  1424. path: basedir,
  1425. exports: {},
  1426. require: function (path, base) {
  1427. return commonjsRequire(path, (base === undefined || base === null) ? module.path : base);
  1428. }
  1429. }, fn(module, module.exports), module.exports;
  1430. }
  1431. function getDefaultExportFromNamespaceIfPresent (n) {
  1432. return n && Object.prototype.hasOwnProperty.call(n, 'default') ? n['default'] : n;
  1433. }
  1434. function getDefaultExportFromNamespaceIfNotNamed (n) {
  1435. return n && Object.prototype.hasOwnProperty.call(n, 'default') && Object.keys(n).length === 1 ? n['default'] : n;
  1436. }
  1437. function getAugmentedNamespace(n) {
  1438. if (n.__esModule) return n;
  1439. var a = Object.defineProperty({}, '__esModule', {value: true});
  1440. Object.keys(n).forEach(function (k) {
  1441. var d = Object.getOwnPropertyDescriptor(n, k);
  1442. Object.defineProperty(a, k, d.get ? d : {
  1443. enumerable: true,
  1444. get: function () {
  1445. return n[k];
  1446. }
  1447. });
  1448. });
  1449. return a;
  1450. }
  1451. function commonjsRequire () {
  1452. throw new Error('Dynamic requires are not currently supported by @rollup/plugin-commonjs');
  1453. }
  1454. var eventemitter3 = createCommonjsModule(function (module) {
  1455. 'use strict';
  1456. var has = Object.prototype.hasOwnProperty
  1457. , prefix = '~';
  1458. /**
  1459. * Constructor to create a storage for our `EE` objects.
  1460. * An `Events` instance is a plain object whose properties are event names.
  1461. *
  1462. * @constructor
  1463. * @private
  1464. */
  1465. function Events() {}
  1466. //
  1467. // We try to not inherit from `Object.prototype`. In some engines creating an
  1468. // instance in this way is faster than calling `Object.create(null)` directly.
  1469. // If `Object.create(null)` is not supported we prefix the event names with a
  1470. // character to make sure that the built-in object properties are not
  1471. // overridden or used as an attack vector.
  1472. //
  1473. if (Object.create) {
  1474. Events.prototype = Object.create(null);
  1475. //
  1476. // This hack is needed because the `__proto__` property is still inherited in
  1477. // some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5.
  1478. //
  1479. if (!new Events().__proto__) { prefix = false; }
  1480. }
  1481. /**
  1482. * Representation of a single event listener.
  1483. *
  1484. * @param {Function} fn The listener function.
  1485. * @param {*} context The context to invoke the listener with.
  1486. * @param {Boolean} [once=false] Specify if the listener is a one-time listener.
  1487. * @constructor
  1488. * @private
  1489. */
  1490. function EE(fn, context, once) {
  1491. this.fn = fn;
  1492. this.context = context;
  1493. this.once = once || false;
  1494. }
  1495. /**
  1496. * Add a listener for a given event.
  1497. *
  1498. * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.
  1499. * @param {(String|Symbol)} event The event name.
  1500. * @param {Function} fn The listener function.
  1501. * @param {*} context The context to invoke the listener with.
  1502. * @param {Boolean} once Specify if the listener is a one-time listener.
  1503. * @returns {EventEmitter}
  1504. * @private
  1505. */
  1506. function addListener(emitter, event, fn, context, once) {
  1507. if (typeof fn !== 'function') {
  1508. throw new TypeError('The listener must be a function');
  1509. }
  1510. var listener = new EE(fn, context || emitter, once)
  1511. , evt = prefix ? prefix + event : event;
  1512. if (!emitter._events[evt]) { emitter._events[evt] = listener, emitter._eventsCount++; }
  1513. else if (!emitter._events[evt].fn) { emitter._events[evt].push(listener); }
  1514. else { emitter._events[evt] = [emitter._events[evt], listener]; }
  1515. return emitter;
  1516. }
  1517. /**
  1518. * Clear event by name.
  1519. *
  1520. * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.
  1521. * @param {(String|Symbol)} evt The Event name.
  1522. * @private
  1523. */
  1524. function clearEvent(emitter, evt) {
  1525. if (--emitter._eventsCount === 0) { emitter._events = new Events(); }
  1526. else { delete emitter._events[evt]; }
  1527. }
  1528. /**
  1529. * Minimal `EventEmitter` interface that is molded against the Node.js
  1530. * `EventEmitter` interface.
  1531. *
  1532. * @constructor
  1533. * @public
  1534. */
  1535. function EventEmitter() {
  1536. this._events = new Events();
  1537. this._eventsCount = 0;
  1538. }
  1539. /**
  1540. * Return an array listing the events for which the emitter has registered
  1541. * listeners.
  1542. *
  1543. * @returns {Array}
  1544. * @public
  1545. */
  1546. EventEmitter.prototype.eventNames = function eventNames() {
  1547. var names = []
  1548. , events
  1549. , name;
  1550. if (this._eventsCount === 0) { return names; }
  1551. for (name in (events = this._events)) {
  1552. if (has.call(events, name)) { names.push(prefix ? name.slice(1) : name); }
  1553. }
  1554. if (Object.getOwnPropertySymbols) {
  1555. return names.concat(Object.getOwnPropertySymbols(events));
  1556. }
  1557. return names;
  1558. };
  1559. /**
  1560. * Return the listeners registered for a given event.
  1561. *
  1562. * @param {(String|Symbol)} event The event name.
  1563. * @returns {Array} The registered listeners.
  1564. * @public
  1565. */
  1566. EventEmitter.prototype.listeners = function listeners(event) {
  1567. var evt = prefix ? prefix + event : event
  1568. , handlers = this._events[evt];
  1569. if (!handlers) { return []; }
  1570. if (handlers.fn) { return [handlers.fn]; }
  1571. for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) {
  1572. ee[i] = handlers[i].fn;
  1573. }
  1574. return ee;
  1575. };
  1576. /**
  1577. * Return the number of listeners listening to a given event.
  1578. *
  1579. * @param {(String|Symbol)} event The event name.
  1580. * @returns {Number} The number of listeners.
  1581. * @public
  1582. */
  1583. EventEmitter.prototype.listenerCount = function listenerCount(event) {
  1584. var evt = prefix ? prefix + event : event
  1585. , listeners = this._events[evt];
  1586. if (!listeners) { return 0; }
  1587. if (listeners.fn) { return 1; }
  1588. return listeners.length;
  1589. };
  1590. /**
  1591. * Calls each of the listeners registered for a given event.
  1592. *
  1593. * @param {(String|Symbol)} event The event name.
  1594. * @returns {Boolean} `true` if the event had listeners, else `false`.
  1595. * @public
  1596. */
  1597. EventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) {
  1598. var arguments$1 = arguments;
  1599. var evt = prefix ? prefix + event : event;
  1600. if (!this._events[evt]) { return false; }
  1601. var listeners = this._events[evt]
  1602. , len = arguments.length
  1603. , args
  1604. , i;
  1605. if (listeners.fn) {
  1606. if (listeners.once) { this.removeListener(event, listeners.fn, undefined, true); }
  1607. switch (len) {
  1608. case 1: return listeners.fn.call(listeners.context), true;
  1609. case 2: return listeners.fn.call(listeners.context, a1), true;
  1610. case 3: return listeners.fn.call(listeners.context, a1, a2), true;
  1611. case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true;
  1612. case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true;
  1613. case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true;
  1614. }
  1615. for (i = 1, args = new Array(len -1); i < len; i++) {
  1616. args[i - 1] = arguments$1[i];
  1617. }
  1618. listeners.fn.apply(listeners.context, args);
  1619. } else {
  1620. var length = listeners.length
  1621. , j;
  1622. for (i = 0; i < length; i++) {
  1623. if (listeners[i].once) { this.removeListener(event, listeners[i].fn, undefined, true); }
  1624. switch (len) {
  1625. case 1: listeners[i].fn.call(listeners[i].context); break;
  1626. case 2: listeners[i].fn.call(listeners[i].context, a1); break;
  1627. case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break;
  1628. case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break;
  1629. default:
  1630. if (!args) { for (j = 1, args = new Array(len -1); j < len; j++) {
  1631. args[j - 1] = arguments$1[j];
  1632. } }
  1633. listeners[i].fn.apply(listeners[i].context, args);
  1634. }
  1635. }
  1636. }
  1637. return true;
  1638. };
  1639. /**
  1640. * Add a listener for a given event.
  1641. *
  1642. * @param {(String|Symbol)} event The event name.
  1643. * @param {Function} fn The listener function.
  1644. * @param {*} [context=this] The context to invoke the listener with.
  1645. * @returns {EventEmitter} `this`.
  1646. * @public
  1647. */
  1648. EventEmitter.prototype.on = function on(event, fn, context) {
  1649. return addListener(this, event, fn, context, false);
  1650. };
  1651. /**
  1652. * Add a one-time listener for a given event.
  1653. *
  1654. * @param {(String|Symbol)} event The event name.
  1655. * @param {Function} fn The listener function.
  1656. * @param {*} [context=this] The context to invoke the listener with.
  1657. * @returns {EventEmitter} `this`.
  1658. * @public
  1659. */
  1660. EventEmitter.prototype.once = function once(event, fn, context) {
  1661. return addListener(this, event, fn, context, true);
  1662. };
  1663. /**
  1664. * Remove the listeners of a given event.
  1665. *
  1666. * @param {(String|Symbol)} event The event name.
  1667. * @param {Function} fn Only remove the listeners that match this function.
  1668. * @param {*} context Only remove the listeners that have this context.
  1669. * @param {Boolean} once Only remove one-time listeners.
  1670. * @returns {EventEmitter} `this`.
  1671. * @public
  1672. */
  1673. EventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) {
  1674. var evt = prefix ? prefix + event : event;
  1675. if (!this._events[evt]) { return this; }
  1676. if (!fn) {
  1677. clearEvent(this, evt);
  1678. return this;
  1679. }
  1680. var listeners = this._events[evt];
  1681. if (listeners.fn) {
  1682. if (
  1683. listeners.fn === fn &&
  1684. (!once || listeners.once) &&
  1685. (!context || listeners.context === context)
  1686. ) {
  1687. clearEvent(this, evt);
  1688. }
  1689. } else {
  1690. for (var i = 0, events = [], length = listeners.length; i < length; i++) {
  1691. if (
  1692. listeners[i].fn !== fn ||
  1693. (once && !listeners[i].once) ||
  1694. (context && listeners[i].context !== context)
  1695. ) {
  1696. events.push(listeners[i]);
  1697. }
  1698. }
  1699. //
  1700. // Reset the array, or remove it completely if we have no more listeners.
  1701. //
  1702. if (events.length) { this._events[evt] = events.length === 1 ? events[0] : events; }
  1703. else { clearEvent(this, evt); }
  1704. }
  1705. return this;
  1706. };
  1707. /**
  1708. * Remove all listeners, or those of the specified event.
  1709. *
  1710. * @param {(String|Symbol)} [event] The event name.
  1711. * @returns {EventEmitter} `this`.
  1712. * @public
  1713. */
  1714. EventEmitter.prototype.removeAllListeners = function removeAllListeners(event) {
  1715. var evt;
  1716. if (event) {
  1717. evt = prefix ? prefix + event : event;
  1718. if (this._events[evt]) { clearEvent(this, evt); }
  1719. } else {
  1720. this._events = new Events();
  1721. this._eventsCount = 0;
  1722. }
  1723. return this;
  1724. };
  1725. //
  1726. // Alias methods names because people roll like that.
  1727. //
  1728. EventEmitter.prototype.off = EventEmitter.prototype.removeListener;
  1729. EventEmitter.prototype.addListener = EventEmitter.prototype.on;
  1730. //
  1731. // Expose the prefix.
  1732. //
  1733. EventEmitter.prefixed = prefix;
  1734. //
  1735. // Allow `EventEmitter` to be imported as module namespace.
  1736. //
  1737. EventEmitter.EventEmitter = EventEmitter;
  1738. //
  1739. // Expose the module.
  1740. //
  1741. if ('undefined' !== 'object') {
  1742. module.exports = EventEmitter;
  1743. }
  1744. });
  1745. 'use strict';
  1746. var earcut_1 = earcut;
  1747. var _default = earcut;
  1748. function earcut(data, holeIndices, dim) {
  1749. dim = dim || 2;
  1750. var hasHoles = holeIndices && holeIndices.length,
  1751. outerLen = hasHoles ? holeIndices[0] * dim : data.length,
  1752. outerNode = linkedList(data, 0, outerLen, dim, true),
  1753. triangles = [];
  1754. if (!outerNode || outerNode.next === outerNode.prev) { return triangles; }
  1755. var minX, minY, maxX, maxY, x, y, invSize;
  1756. if (hasHoles) { outerNode = eliminateHoles(data, holeIndices, outerNode, dim); }
  1757. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  1758. if (data.length > 80 * dim) {
  1759. minX = maxX = data[0];
  1760. minY = maxY = data[1];
  1761. for (var i = dim; i < outerLen; i += dim) {
  1762. x = data[i];
  1763. y = data[i + 1];
  1764. if (x < minX) { minX = x; }
  1765. if (y < minY) { minY = y; }
  1766. if (x > maxX) { maxX = x; }
  1767. if (y > maxY) { maxY = y; }
  1768. }
  1769. // minX, minY and invSize are later used to transform coords into integers for z-order calculation
  1770. invSize = Math.max(maxX - minX, maxY - minY);
  1771. invSize = invSize !== 0 ? 32767 / invSize : 0;
  1772. }
  1773. earcutLinked(outerNode, triangles, dim, minX, minY, invSize, 0);
  1774. return triangles;
  1775. }
  1776. // create a circular doubly linked list from polygon points in the specified winding order
  1777. function linkedList(data, start, end, dim, clockwise) {
  1778. var i, last;
  1779. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  1780. for (i = start; i < end; i += dim) { last = insertNode(i, data[i], data[i + 1], last); }
  1781. } else {
  1782. for (i = end - dim; i >= start; i -= dim) { last = insertNode(i, data[i], data[i + 1], last); }
  1783. }
  1784. if (last && equals(last, last.next)) {
  1785. removeNode(last);
  1786. last = last.next;
  1787. }
  1788. return last;
  1789. }
  1790. // eliminate colinear or duplicate points
  1791. function filterPoints(start, end) {
  1792. if (!start) { return start; }
  1793. if (!end) { end = start; }
  1794. var p = start,
  1795. again;
  1796. do {
  1797. again = false;
  1798. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  1799. removeNode(p);
  1800. p = end = p.prev;
  1801. if (p === p.next) { break; }
  1802. again = true;
  1803. } else {
  1804. p = p.next;
  1805. }
  1806. } while (again || p !== end);
  1807. return end;
  1808. }
  1809. // main ear slicing loop which triangulates a polygon (given as a linked list)
  1810. function earcutLinked(ear, triangles, dim, minX, minY, invSize, pass) {
  1811. if (!ear) { return; }
  1812. // interlink polygon nodes in z-order
  1813. if (!pass && invSize) { indexCurve(ear, minX, minY, invSize); }
  1814. var stop = ear,
  1815. prev, next;
  1816. // iterate through ears, slicing them one by one
  1817. while (ear.prev !== ear.next) {
  1818. prev = ear.prev;
  1819. next = ear.next;
  1820. if (invSize ? isEarHashed(ear, minX, minY, invSize) : isEar(ear)) {
  1821. // cut off the triangle
  1822. triangles.push(prev.i / dim | 0);
  1823. triangles.push(ear.i / dim | 0);
  1824. triangles.push(next.i / dim | 0);
  1825. removeNode(ear);
  1826. // skipping the next vertex leads to less sliver triangles
  1827. ear = next.next;
  1828. stop = next.next;
  1829. continue;
  1830. }
  1831. ear = next;
  1832. // if we looped through the whole remaining polygon and can't find any more ears
  1833. if (ear === stop) {
  1834. // try filtering points and slicing again
  1835. if (!pass) {
  1836. earcutLinked(filterPoints(ear), triangles, dim, minX, minY, invSize, 1);
  1837. // if this didn't work, try curing all small self-intersections locally
  1838. } else if (pass === 1) {
  1839. ear = cureLocalIntersections(filterPoints(ear), triangles, dim);
  1840. earcutLinked(ear, triangles, dim, minX, minY, invSize, 2);
  1841. // as a last resort, try splitting the remaining polygon into two
  1842. } else if (pass === 2) {
  1843. splitEarcut(ear, triangles, dim, minX, minY, invSize);
  1844. }
  1845. break;
  1846. }
  1847. }
  1848. }
  1849. // check whether a polygon node forms a valid ear with adjacent nodes
  1850. function isEar(ear) {
  1851. var a = ear.prev,
  1852. b = ear,
  1853. c = ear.next;
  1854. if (area(a, b, c) >= 0) { return false; } // reflex, can't be an ear
  1855. // now make sure we don't have other points inside the potential ear
  1856. var ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;
  1857. // triangle bbox; min & max are calculated like this for speed
  1858. var x0 = ax < bx ? (ax < cx ? ax : cx) : (bx < cx ? bx : cx),
  1859. y0 = ay < by ? (ay < cy ? ay : cy) : (by < cy ? by : cy),
  1860. x1 = ax > bx ? (ax > cx ? ax : cx) : (bx > cx ? bx : cx),
  1861. y1 = ay > by ? (ay > cy ? ay : cy) : (by > cy ? by : cy);
  1862. var p = c.next;
  1863. while (p !== a) {
  1864. if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 &&
  1865. pointInTriangle(ax, ay, bx, by, cx, cy, p.x, p.y) &&
  1866. area(p.prev, p, p.next) >= 0) { return false; }
  1867. p = p.next;
  1868. }
  1869. return true;
  1870. }
  1871. function isEarHashed(ear, minX, minY, invSize) {
  1872. var a = ear.prev,
  1873. b = ear,
  1874. c = ear.next;
  1875. if (area(a, b, c) >= 0) { return false; } // reflex, can't be an ear
  1876. var ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y;
  1877. // triangle bbox; min & max are calculated like this for speed
  1878. var x0 = ax < bx ? (ax < cx ? ax : cx) : (bx < cx ? bx : cx),
  1879. y0 = ay < by ? (ay < cy ? ay : cy) : (by < cy ? by : cy),
  1880. x1 = ax > bx ? (ax > cx ? ax : cx) : (bx > cx ? bx : cx),
  1881. y1 = ay > by ? (ay > cy ? ay : cy) : (by > cy ? by : cy);
  1882. // z-order range for the current triangle bbox;
  1883. var minZ = zOrder(x0, y0, minX, minY, invSize),
  1884. maxZ = zOrder(x1, y1, minX, minY, invSize);
  1885. var p = ear.prevZ,
  1886. n = ear.nextZ;
  1887. // look for points inside the triangle in both directions
  1888. while (p && p.z >= minZ && n && n.z <= maxZ) {
  1889. if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&
  1890. pointInTriangle(ax, ay, bx, by, cx, cy, p.x, p.y) && area(p.prev, p, p.next) >= 0) { return false; }
  1891. p = p.prevZ;
  1892. if (n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&
  1893. pointInTriangle(ax, ay, bx, by, cx, cy, n.x, n.y) && area(n.prev, n, n.next) >= 0) { return false; }
  1894. n = n.nextZ;
  1895. }
  1896. // look for remaining points in decreasing z-order
  1897. while (p && p.z >= minZ) {
  1898. if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c &&
  1899. pointInTriangle(ax, ay, bx, by, cx, cy, p.x, p.y) && area(p.prev, p, p.next) >= 0) { return false; }
  1900. p = p.prevZ;
  1901. }
  1902. // look for remaining points in increasing z-order
  1903. while (n && n.z <= maxZ) {
  1904. if (n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c &&
  1905. pointInTriangle(ax, ay, bx, by, cx, cy, n.x, n.y) && area(n.prev, n, n.next) >= 0) { return false; }
  1906. n = n.nextZ;
  1907. }
  1908. return true;
  1909. }
  1910. // go through all polygon nodes and cure small local self-intersections
  1911. function cureLocalIntersections(start, triangles, dim) {
  1912. var p = start;
  1913. do {
  1914. var a = p.prev,
  1915. b = p.next.next;
  1916. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  1917. triangles.push(a.i / dim | 0);
  1918. triangles.push(p.i / dim | 0);
  1919. triangles.push(b.i / dim | 0);
  1920. // remove two nodes involved
  1921. removeNode(p);
  1922. removeNode(p.next);
  1923. p = start = b;
  1924. }
  1925. p = p.next;
  1926. } while (p !== start);
  1927. return filterPoints(p);
  1928. }
  1929. // try splitting polygon into two and triangulate them independently
  1930. function splitEarcut(start, triangles, dim, minX, minY, invSize) {
  1931. // look for a valid diagonal that divides the polygon into two
  1932. var a = start;
  1933. do {
  1934. var b = a.next.next;
  1935. while (b !== a.prev) {
  1936. if (a.i !== b.i && isValidDiagonal(a, b)) {
  1937. // split the polygon in two by the diagonal
  1938. var c = splitPolygon(a, b);
  1939. // filter colinear points around the cuts
  1940. a = filterPoints(a, a.next);
  1941. c = filterPoints(c, c.next);
  1942. // run earcut on each half
  1943. earcutLinked(a, triangles, dim, minX, minY, invSize, 0);
  1944. earcutLinked(c, triangles, dim, minX, minY, invSize, 0);
  1945. return;
  1946. }
  1947. b = b.next;
  1948. }
  1949. a = a.next;
  1950. } while (a !== start);
  1951. }
  1952. // link every hole into the outer loop, producing a single-ring polygon without holes
  1953. function eliminateHoles(data, holeIndices, outerNode, dim) {
  1954. var queue = [],
  1955. i, len, start, end, list;
  1956. for (i = 0, len = holeIndices.length; i < len; i++) {
  1957. start = holeIndices[i] * dim;
  1958. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  1959. list = linkedList(data, start, end, dim, false);
  1960. if (list === list.next) { list.steiner = true; }
  1961. queue.push(getLeftmost(list));
  1962. }
  1963. queue.sort(compareX);
  1964. // process holes from left to right
  1965. for (i = 0; i < queue.length; i++) {
  1966. outerNode = eliminateHole(queue[i], outerNode);
  1967. }
  1968. return outerNode;
  1969. }
  1970. function compareX(a, b) {
  1971. return a.x - b.x;
  1972. }
  1973. // find a bridge between vertices that connects hole with an outer ring and and link it
  1974. function eliminateHole(hole, outerNode) {
  1975. var bridge = findHoleBridge(hole, outerNode);
  1976. if (!bridge) {
  1977. return outerNode;
  1978. }
  1979. var bridgeReverse = splitPolygon(bridge, hole);
  1980. // filter collinear points around the cuts
  1981. filterPoints(bridgeReverse, bridgeReverse.next);
  1982. return filterPoints(bridge, bridge.next);
  1983. }
  1984. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  1985. function findHoleBridge(hole, outerNode) {
  1986. var p = outerNode,
  1987. hx = hole.x,
  1988. hy = hole.y,
  1989. qx = -Infinity,
  1990. m;
  1991. // find a segment intersected by a ray from the hole's leftmost point to the left;
  1992. // segment's endpoint with lesser x will be potential connection point
  1993. do {
  1994. if (hy <= p.y && hy >= p.next.y && p.next.y !== p.y) {
  1995. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  1996. if (x <= hx && x > qx) {
  1997. qx = x;
  1998. m = p.x < p.next.x ? p : p.next;
  1999. if (x === hx) { return m; } // hole touches outer segment; pick leftmost endpoint
  2000. }
  2001. }
  2002. p = p.next;
  2003. } while (p !== outerNode);
  2004. if (!m) { return null; }
  2005. // look for points inside the triangle of hole point, segment intersection and endpoint;
  2006. // if there are no points found, we have a valid connection;
  2007. // otherwise choose the point of the minimum angle with the ray as connection point
  2008. var stop = m,
  2009. mx = m.x,
  2010. my = m.y,
  2011. tanMin = Infinity,
  2012. tan;
  2013. p = m;
  2014. do {
  2015. if (hx >= p.x && p.x >= mx && hx !== p.x &&
  2016. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  2017. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  2018. if (locallyInside(p, hole) &&
  2019. (tan < tanMin || (tan === tanMin && (p.x > m.x || (p.x === m.x && sectorContainsSector(m, p)))))) {
  2020. m = p;
  2021. tanMin = tan;
  2022. }
  2023. }
  2024. p = p.next;
  2025. } while (p !== stop);
  2026. return m;
  2027. }
  2028. // whether sector in vertex m contains sector in vertex p in the same coordinates
  2029. function sectorContainsSector(m, p) {
  2030. return area(m.prev, m, p.prev) < 0 && area(p.next, m, m.next) < 0;
  2031. }
  2032. // interlink polygon nodes in z-order
  2033. function indexCurve(start, minX, minY, invSize) {
  2034. var p = start;
  2035. do {
  2036. if (p.z === 0) { p.z = zOrder(p.x, p.y, minX, minY, invSize); }
  2037. p.prevZ = p.prev;
  2038. p.nextZ = p.next;
  2039. p = p.next;
  2040. } while (p !== start);
  2041. p.prevZ.nextZ = null;
  2042. p.prevZ = null;
  2043. sortLinked(p);
  2044. }
  2045. // Simon Tatham's linked list merge sort algorithm
  2046. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  2047. function sortLinked(list) {
  2048. var i, p, q, e, tail, numMerges, pSize, qSize,
  2049. inSize = 1;
  2050. do {
  2051. p = list;
  2052. list = null;
  2053. tail = null;
  2054. numMerges = 0;
  2055. while (p) {
  2056. numMerges++;
  2057. q = p;
  2058. pSize = 0;
  2059. for (i = 0; i < inSize; i++) {
  2060. pSize++;
  2061. q = q.nextZ;
  2062. if (!q) { break; }
  2063. }
  2064. qSize = inSize;
  2065. while (pSize > 0 || (qSize > 0 && q)) {
  2066. if (pSize !== 0 && (qSize === 0 || !q || p.z <= q.z)) {
  2067. e = p;
  2068. p = p.nextZ;
  2069. pSize--;
  2070. } else {
  2071. e = q;
  2072. q = q.nextZ;
  2073. qSize--;
  2074. }
  2075. if (tail) { tail.nextZ = e; }
  2076. else { list = e; }
  2077. e.prevZ = tail;
  2078. tail = e;
  2079. }
  2080. p = q;
  2081. }
  2082. tail.nextZ = null;
  2083. inSize *= 2;
  2084. } while (numMerges > 1);
  2085. return list;
  2086. }
  2087. // z-order of a point given coords and inverse of the longer side of data bbox
  2088. function zOrder(x, y, minX, minY, invSize) {
  2089. // coords are transformed into non-negative 15-bit integer range
  2090. x = (x - minX) * invSize | 0;
  2091. y = (y - minY) * invSize | 0;
  2092. x = (x | (x << 8)) & 0x00FF00FF;
  2093. x = (x | (x << 4)) & 0x0F0F0F0F;
  2094. x = (x | (x << 2)) & 0x33333333;
  2095. x = (x | (x << 1)) & 0x55555555;
  2096. y = (y | (y << 8)) & 0x00FF00FF;
  2097. y = (y | (y << 4)) & 0x0F0F0F0F;
  2098. y = (y | (y << 2)) & 0x33333333;
  2099. y = (y | (y << 1)) & 0x55555555;
  2100. return x | (y << 1);
  2101. }
  2102. // find the leftmost node of a polygon ring
  2103. function getLeftmost(start) {
  2104. var p = start,
  2105. leftmost = start;
  2106. do {
  2107. if (p.x < leftmost.x || (p.x === leftmost.x && p.y < leftmost.y)) { leftmost = p; }
  2108. p = p.next;
  2109. } while (p !== start);
  2110. return leftmost;
  2111. }
  2112. // check if a point lies within a convex triangle
  2113. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  2114. return (cx - px) * (ay - py) >= (ax - px) * (cy - py) &&
  2115. (ax - px) * (by - py) >= (bx - px) * (ay - py) &&
  2116. (bx - px) * (cy - py) >= (cx - px) * (by - py);
  2117. }
  2118. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  2119. function isValidDiagonal(a, b) {
  2120. return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) && // dones't intersect other edges
  2121. (locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b) && // locally visible
  2122. (area(a.prev, a, b.prev) || area(a, b.prev, b)) || // does not create opposite-facing sectors
  2123. equals(a, b) && area(a.prev, a, a.next) > 0 && area(b.prev, b, b.next) > 0); // special zero-length case
  2124. }
  2125. // signed area of a triangle
  2126. function area(p, q, r) {
  2127. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  2128. }
  2129. // check if two points are equal
  2130. function equals(p1, p2) {
  2131. return p1.x === p2.x && p1.y === p2.y;
  2132. }
  2133. // check if two segments intersect
  2134. function intersects(p1, q1, p2, q2) {
  2135. var o1 = sign$1(area(p1, q1, p2));
  2136. var o2 = sign$1(area(p1, q1, q2));
  2137. var o3 = sign$1(area(p2, q2, p1));
  2138. var o4 = sign$1(area(p2, q2, q1));
  2139. if (o1 !== o2 && o3 !== o4) { return true; } // general case
  2140. if (o1 === 0 && onSegment(p1, p2, q1)) { return true; } // p1, q1 and p2 are collinear and p2 lies on p1q1
  2141. if (o2 === 0 && onSegment(p1, q2, q1)) { return true; } // p1, q1 and q2 are collinear and q2 lies on p1q1
  2142. if (o3 === 0 && onSegment(p2, p1, q2)) { return true; } // p2, q2 and p1 are collinear and p1 lies on p2q2
  2143. if (o4 === 0 && onSegment(p2, q1, q2)) { return true; } // p2, q2 and q1 are collinear and q1 lies on p2q2
  2144. return false;
  2145. }
  2146. // for collinear points p, q, r, check if point q lies on segment pr
  2147. function onSegment(p, q, r) {
  2148. return q.x <= Math.max(p.x, r.x) && q.x >= Math.min(p.x, r.x) && q.y <= Math.max(p.y, r.y) && q.y >= Math.min(p.y, r.y);
  2149. }
  2150. function sign$1(num) {
  2151. return num > 0 ? 1 : num < 0 ? -1 : 0;
  2152. }
  2153. // check if a polygon diagonal intersects any polygon segments
  2154. function intersectsPolygon(a, b) {
  2155. var p = a;
  2156. do {
  2157. if (p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i &&
  2158. intersects(p, p.next, a, b)) { return true; }
  2159. p = p.next;
  2160. } while (p !== a);
  2161. return false;
  2162. }
  2163. // check if a polygon diagonal is locally inside the polygon
  2164. function locallyInside(a, b) {
  2165. return area(a.prev, a, a.next) < 0 ?
  2166. area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0 :
  2167. area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  2168. }
  2169. // check if the middle point of a polygon diagonal is inside the polygon
  2170. function middleInside(a, b) {
  2171. var p = a,
  2172. inside = false,
  2173. px = (a.x + b.x) / 2,
  2174. py = (a.y + b.y) / 2;
  2175. do {
  2176. if (((p.y > py) !== (p.next.y > py)) && p.next.y !== p.y &&
  2177. (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  2178. { inside = !inside; }
  2179. p = p.next;
  2180. } while (p !== a);
  2181. return inside;
  2182. }
  2183. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  2184. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  2185. function splitPolygon(a, b) {
  2186. var a2 = new Node(a.i, a.x, a.y),
  2187. b2 = new Node(b.i, b.x, b.y),
  2188. an = a.next,
  2189. bp = b.prev;
  2190. a.next = b;
  2191. b.prev = a;
  2192. a2.next = an;
  2193. an.prev = a2;
  2194. b2.next = a2;
  2195. a2.prev = b2;
  2196. bp.next = b2;
  2197. b2.prev = bp;
  2198. return b2;
  2199. }
  2200. // create a node and optionally link it with previous one (in a circular doubly linked list)
  2201. function insertNode(i, x, y, last) {
  2202. var p = new Node(i, x, y);
  2203. if (!last) {
  2204. p.prev = p;
  2205. p.next = p;
  2206. } else {
  2207. p.next = last.next;
  2208. p.prev = last;
  2209. last.next.prev = p;
  2210. last.next = p;
  2211. }
  2212. return p;
  2213. }
  2214. function removeNode(p) {
  2215. p.next.prev = p.prev;
  2216. p.prev.next = p.next;
  2217. if (p.prevZ) { p.prevZ.nextZ = p.nextZ; }
  2218. if (p.nextZ) { p.nextZ.prevZ = p.prevZ; }
  2219. }
  2220. function Node(i, x, y) {
  2221. // vertex index in coordinates array
  2222. this.i = i;
  2223. // vertex coordinates
  2224. this.x = x;
  2225. this.y = y;
  2226. // previous and next vertex nodes in a polygon ring
  2227. this.prev = null;
  2228. this.next = null;
  2229. // z-order curve value
  2230. this.z = 0;
  2231. // previous and next nodes in z-order
  2232. this.prevZ = null;
  2233. this.nextZ = null;
  2234. // indicates whether this is a steiner point
  2235. this.steiner = false;
  2236. }
  2237. // return a percentage difference between the polygon area and its triangulation area;
  2238. // used to verify correctness of triangulation
  2239. earcut.deviation = function (data, holeIndices, dim, triangles) {
  2240. var hasHoles = holeIndices && holeIndices.length;
  2241. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  2242. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  2243. if (hasHoles) {
  2244. for (var i = 0, len = holeIndices.length; i < len; i++) {
  2245. var start = holeIndices[i] * dim;
  2246. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  2247. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  2248. }
  2249. }
  2250. var trianglesArea = 0;
  2251. for (i = 0; i < triangles.length; i += 3) {
  2252. var a = triangles[i] * dim;
  2253. var b = triangles[i + 1] * dim;
  2254. var c = triangles[i + 2] * dim;
  2255. trianglesArea += Math.abs(
  2256. (data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  2257. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  2258. }
  2259. return polygonArea === 0 && trianglesArea === 0 ? 0 :
  2260. Math.abs((trianglesArea - polygonArea) / polygonArea);
  2261. };
  2262. function signedArea(data, start, end, dim) {
  2263. var sum = 0;
  2264. for (var i = start, j = end - dim; i < end; i += dim) {
  2265. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  2266. j = i;
  2267. }
  2268. return sum;
  2269. }
  2270. // turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  2271. earcut.flatten = function (data) {
  2272. var dim = data[0][0].length,
  2273. result = {vertices: [], holes: [], dimensions: dim},
  2274. holeIndex = 0;
  2275. for (var i = 0; i < data.length; i++) {
  2276. for (var j = 0; j < data[i].length; j++) {
  2277. for (var d = 0; d < dim; d++) { result.vertices.push(data[i][j][d]); }
  2278. }
  2279. if (i > 0) {
  2280. holeIndex += data[i - 1].length;
  2281. result.holes.push(holeIndex);
  2282. }
  2283. }
  2284. return result;
  2285. };
  2286. earcut_1.default = _default;
  2287. var punycode = createCommonjsModule(function (module, exports) {
  2288. /*! https://mths.be/punycode v1.3.2 by @mathias */
  2289. ;(function(root) {
  2290. /** Detect free variables */
  2291. var freeExports = 'object' == 'object' && exports &&
  2292. !exports.nodeType && exports;
  2293. var freeModule = 'object' == 'object' && module &&
  2294. !module.nodeType && module;
  2295. var freeGlobal = typeof commonjsGlobal == 'object' && commonjsGlobal;
  2296. if (
  2297. freeGlobal.global === freeGlobal ||
  2298. freeGlobal.window === freeGlobal ||
  2299. freeGlobal.self === freeGlobal
  2300. ) {
  2301. root = freeGlobal;
  2302. }
  2303. /**
  2304. * The `punycode` object.
  2305. * @name punycode
  2306. * @type Object
  2307. */
  2308. var punycode,
  2309. /** Highest positive signed 32-bit float value */
  2310. maxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1
  2311. /** Bootstring parameters */
  2312. base = 36,
  2313. tMin = 1,
  2314. tMax = 26,
  2315. skew = 38,
  2316. damp = 700,
  2317. initialBias = 72,
  2318. initialN = 128, // 0x80
  2319. delimiter = '-', // '\x2D'
  2320. /** Regular expressions */
  2321. regexPunycode = /^xn--/,
  2322. regexNonASCII = /[^\x20-\x7E]/, // unprintable ASCII chars + non-ASCII chars
  2323. regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g, // RFC 3490 separators
  2324. /** Error messages */
  2325. errors = {
  2326. 'overflow': 'Overflow: input needs wider integers to process',
  2327. 'not-basic': 'Illegal input >= 0x80 (not a basic code point)',
  2328. 'invalid-input': 'Invalid input'
  2329. },
  2330. /** Convenience shortcuts */
  2331. baseMinusTMin = base - tMin,
  2332. floor = Math.floor,
  2333. stringFromCharCode = String.fromCharCode,
  2334. /** Temporary variable */
  2335. key;
  2336. /*--------------------------------------------------------------------------*/
  2337. /**
  2338. * A generic error utility function.
  2339. * @private
  2340. * @param {String} type The error type.
  2341. * @returns {Error} Throws a `RangeError` with the applicable error message.
  2342. */
  2343. function error(type) {
  2344. throw RangeError(errors[type]);
  2345. }
  2346. /**
  2347. * A generic `Array#map` utility function.
  2348. * @private
  2349. * @param {Array} array The array to iterate over.
  2350. * @param {Function} callback The function that gets called for every array
  2351. * item.
  2352. * @returns {Array} A new array of values returned by the callback function.
  2353. */
  2354. function map(array, fn) {
  2355. var length = array.length;
  2356. var result = [];
  2357. while (length--) {
  2358. result[length] = fn(array[length]);
  2359. }
  2360. return result;
  2361. }
  2362. /**
  2363. * A simple `Array#map`-like wrapper to work with domain name strings or email
  2364. * addresses.
  2365. * @private
  2366. * @param {String} domain The domain name or email address.
  2367. * @param {Function} callback The function that gets called for every
  2368. * character.
  2369. * @returns {Array} A new string of characters returned by the callback
  2370. * function.
  2371. */
  2372. function mapDomain(string, fn) {
  2373. var parts = string.split('@');
  2374. var result = '';
  2375. if (parts.length > 1) {
  2376. // In email addresses, only the domain name should be punycoded. Leave
  2377. // the local part (i.e. everything up to `@`) intact.
  2378. result = parts[0] + '@';
  2379. string = parts[1];
  2380. }
  2381. // Avoid `split(regex)` for IE8 compatibility. See #17.
  2382. string = string.replace(regexSeparators, '\x2E');
  2383. var labels = string.split('.');
  2384. var encoded = map(labels, fn).join('.');
  2385. return result + encoded;
  2386. }
  2387. /**
  2388. * Creates an array containing the numeric code points of each Unicode
  2389. * character in the string. While JavaScript uses UCS-2 internally,
  2390. * this function will convert a pair of surrogate halves (each of which
  2391. * UCS-2 exposes as separate characters) into a single code point,
  2392. * matching UTF-16.
  2393. * @see `punycode.ucs2.encode`
  2394. * @see <https://mathiasbynens.be/notes/javascript-encoding>
  2395. * @memberOf punycode.ucs2
  2396. * @name decode
  2397. * @param {String} string The Unicode input string (UCS-2).
  2398. * @returns {Array} The new array of code points.
  2399. */
  2400. function ucs2decode(string) {
  2401. var output = [],
  2402. counter = 0,
  2403. length = string.length,
  2404. value,
  2405. extra;
  2406. while (counter < length) {
  2407. value = string.charCodeAt(counter++);
  2408. if (value >= 0xD800 && value <= 0xDBFF && counter < length) {
  2409. // high surrogate, and there is a next character
  2410. extra = string.charCodeAt(counter++);
  2411. if ((extra & 0xFC00) == 0xDC00) { // low surrogate
  2412. output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);
  2413. } else {
  2414. // unmatched surrogate; only append this code unit, in case the next
  2415. // code unit is the high surrogate of a surrogate pair
  2416. output.push(value);
  2417. counter--;
  2418. }
  2419. } else {
  2420. output.push(value);
  2421. }
  2422. }
  2423. return output;
  2424. }
  2425. /**
  2426. * Creates a string based on an array of numeric code points.
  2427. * @see `punycode.ucs2.decode`
  2428. * @memberOf punycode.ucs2
  2429. * @name encode
  2430. * @param {Array} codePoints The array of numeric code points.
  2431. * @returns {String} The new Unicode string (UCS-2).
  2432. */
  2433. function ucs2encode(array) {
  2434. return map(array, function(value) {
  2435. var output = '';
  2436. if (value > 0xFFFF) {
  2437. value -= 0x10000;
  2438. output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800);
  2439. value = 0xDC00 | value & 0x3FF;
  2440. }
  2441. output += stringFromCharCode(value);
  2442. return output;
  2443. }).join('');
  2444. }
  2445. /**
  2446. * Converts a basic code point into a digit/integer.
  2447. * @see `digitToBasic()`
  2448. * @private
  2449. * @param {Number} codePoint The basic numeric code point value.
  2450. * @returns {Number} The numeric value of a basic code point (for use in
  2451. * representing integers) in the range `0` to `base - 1`, or `base` if
  2452. * the code point does not represent a value.
  2453. */
  2454. function basicToDigit(codePoint) {
  2455. if (codePoint - 48 < 10) {
  2456. return codePoint - 22;
  2457. }
  2458. if (codePoint - 65 < 26) {
  2459. return codePoint - 65;
  2460. }
  2461. if (codePoint - 97 < 26) {
  2462. return codePoint - 97;
  2463. }
  2464. return base;
  2465. }
  2466. /**
  2467. * Converts a digit/integer into a basic code point.
  2468. * @see `basicToDigit()`
  2469. * @private
  2470. * @param {Number} digit The numeric value of a basic code point.
  2471. * @returns {Number} The basic code point whose value (when used for
  2472. * representing integers) is `digit`, which needs to be in the range
  2473. * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is
  2474. * used; else, the lowercase form is used. The behavior is undefined
  2475. * if `flag` is non-zero and `digit` has no uppercase form.
  2476. */
  2477. function digitToBasic(digit, flag) {
  2478. // 0..25 map to ASCII a..z or A..Z
  2479. // 26..35 map to ASCII 0..9
  2480. return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5);
  2481. }
  2482. /**
  2483. * Bias adaptation function as per section 3.4 of RFC 3492.
  2484. * http://tools.ietf.org/html/rfc3492#section-3.4
  2485. * @private
  2486. */
  2487. function adapt(delta, numPoints, firstTime) {
  2488. var k = 0;
  2489. delta = firstTime ? floor(delta / damp) : delta >> 1;
  2490. delta += floor(delta / numPoints);
  2491. for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) {
  2492. delta = floor(delta / baseMinusTMin);
  2493. }
  2494. return floor(k + (baseMinusTMin + 1) * delta / (delta + skew));
  2495. }
  2496. /**
  2497. * Converts a Punycode string of ASCII-only symbols to a string of Unicode
  2498. * symbols.
  2499. * @memberOf punycode
  2500. * @param {String} input The Punycode string of ASCII-only symbols.
  2501. * @returns {String} The resulting string of Unicode symbols.
  2502. */
  2503. function decode(input) {
  2504. // Don't use UCS-2
  2505. var output = [],
  2506. inputLength = input.length,
  2507. out,
  2508. i = 0,
  2509. n = initialN,
  2510. bias = initialBias,
  2511. basic,
  2512. j,
  2513. index,
  2514. oldi,
  2515. w,
  2516. k,
  2517. digit,
  2518. t,
  2519. /** Cached calculation results */
  2520. baseMinusT;
  2521. // Handle the basic code points: let `basic` be the number of input code
  2522. // points before the last delimiter, or `0` if there is none, then copy
  2523. // the first basic code points to the output.
  2524. basic = input.lastIndexOf(delimiter);
  2525. if (basic < 0) {
  2526. basic = 0;
  2527. }
  2528. for (j = 0; j < basic; ++j) {
  2529. // if it's not a basic code point
  2530. if (input.charCodeAt(j) >= 0x80) {
  2531. error('not-basic');
  2532. }
  2533. output.push(input.charCodeAt(j));
  2534. }
  2535. // Main decoding loop: start just after the last delimiter if any basic code
  2536. // points were copied; start at the beginning otherwise.
  2537. for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) {
  2538. // `index` is the index of the next character to be consumed.
  2539. // Decode a generalized variable-length integer into `delta`,
  2540. // which gets added to `i`. The overflow checking is easier
  2541. // if we increase `i` as we go, then subtract off its starting
  2542. // value at the end to obtain `delta`.
  2543. for (oldi = i, w = 1, k = base; /* no condition */; k += base) {
  2544. if (index >= inputLength) {
  2545. error('invalid-input');
  2546. }
  2547. digit = basicToDigit(input.charCodeAt(index++));
  2548. if (digit >= base || digit > floor((maxInt - i) / w)) {
  2549. error('overflow');
  2550. }
  2551. i += digit * w;
  2552. t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
  2553. if (digit < t) {
  2554. break;
  2555. }
  2556. baseMinusT = base - t;
  2557. if (w > floor(maxInt / baseMinusT)) {
  2558. error('overflow');
  2559. }
  2560. w *= baseMinusT;
  2561. }
  2562. out = output.length + 1;
  2563. bias = adapt(i - oldi, out, oldi == 0);
  2564. // `i` was supposed to wrap around from `out` to `0`,
  2565. // incrementing `n` each time, so we'll fix that now:
  2566. if (floor(i / out) > maxInt - n) {
  2567. error('overflow');
  2568. }
  2569. n += floor(i / out);
  2570. i %= out;
  2571. // Insert `n` at position `i` of the output
  2572. output.splice(i++, 0, n);
  2573. }
  2574. return ucs2encode(output);
  2575. }
  2576. /**
  2577. * Converts a string of Unicode symbols (e.g. a domain name label) to a
  2578. * Punycode string of ASCII-only symbols.
  2579. * @memberOf punycode
  2580. * @param {String} input The string of Unicode symbols.
  2581. * @returns {String} The resulting Punycode string of ASCII-only symbols.
  2582. */
  2583. function encode(input) {
  2584. var n,
  2585. delta,
  2586. handledCPCount,
  2587. basicLength,
  2588. bias,
  2589. j,
  2590. m,
  2591. q,
  2592. k,
  2593. t,
  2594. currentValue,
  2595. output = [],
  2596. /** `inputLength` will hold the number of code points in `input`. */
  2597. inputLength,
  2598. /** Cached calculation results */
  2599. handledCPCountPlusOne,
  2600. baseMinusT,
  2601. qMinusT;
  2602. // Convert the input in UCS-2 to Unicode
  2603. input = ucs2decode(input);
  2604. // Cache the length
  2605. inputLength = input.length;
  2606. // Initialize the state
  2607. n = initialN;
  2608. delta = 0;
  2609. bias = initialBias;
  2610. // Handle the basic code points
  2611. for (j = 0; j < inputLength; ++j) {
  2612. currentValue = input[j];
  2613. if (currentValue < 0x80) {
  2614. output.push(stringFromCharCode(currentValue));
  2615. }
  2616. }
  2617. handledCPCount = basicLength = output.length;
  2618. // `handledCPCount` is the number of code points that have been handled;
  2619. // `basicLength` is the number of basic code points.
  2620. // Finish the basic string - if it is not empty - with a delimiter
  2621. if (basicLength) {
  2622. output.push(delimiter);
  2623. }
  2624. // Main encoding loop:
  2625. while (handledCPCount < inputLength) {
  2626. // All non-basic code points < n have been handled already. Find the next
  2627. // larger one:
  2628. for (m = maxInt, j = 0; j < inputLength; ++j) {
  2629. currentValue = input[j];
  2630. if (currentValue >= n && currentValue < m) {
  2631. m = currentValue;
  2632. }
  2633. }
  2634. // Increase `delta` enough to advance the decoder's <n,i> state to <m,0>,
  2635. // but guard against overflow
  2636. handledCPCountPlusOne = handledCPCount + 1;
  2637. if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) {
  2638. error('overflow');
  2639. }
  2640. delta += (m - n) * handledCPCountPlusOne;
  2641. n = m;
  2642. for (j = 0; j < inputLength; ++j) {
  2643. currentValue = input[j];
  2644. if (currentValue < n && ++delta > maxInt) {
  2645. error('overflow');
  2646. }
  2647. if (currentValue == n) {
  2648. // Represent delta as a generalized variable-length integer
  2649. for (q = delta, k = base; /* no condition */; k += base) {
  2650. t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
  2651. if (q < t) {
  2652. break;
  2653. }
  2654. qMinusT = q - t;
  2655. baseMinusT = base - t;
  2656. output.push(
  2657. stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0))
  2658. );
  2659. q = floor(qMinusT / baseMinusT);
  2660. }
  2661. output.push(stringFromCharCode(digitToBasic(q, 0)));
  2662. bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength);
  2663. delta = 0;
  2664. ++handledCPCount;
  2665. }
  2666. }
  2667. ++delta;
  2668. ++n;
  2669. }
  2670. return output.join('');
  2671. }
  2672. /**
  2673. * Converts a Punycode string representing a domain name or an email address
  2674. * to Unicode. Only the Punycoded parts of the input will be converted, i.e.
  2675. * it doesn't matter if you call it on a string that has already been
  2676. * converted to Unicode.
  2677. * @memberOf punycode
  2678. * @param {String} input The Punycoded domain name or email address to
  2679. * convert to Unicode.
  2680. * @returns {String} The Unicode representation of the given Punycode
  2681. * string.
  2682. */
  2683. function toUnicode(input) {
  2684. return mapDomain(input, function(string) {
  2685. return regexPunycode.test(string)
  2686. ? decode(string.slice(4).toLowerCase())
  2687. : string;
  2688. });
  2689. }
  2690. /**
  2691. * Converts a Unicode string representing a domain name or an email address to
  2692. * Punycode. Only the non-ASCII parts of the domain name will be converted,
  2693. * i.e. it doesn't matter if you call it with a domain that's already in
  2694. * ASCII.
  2695. * @memberOf punycode
  2696. * @param {String} input The domain name or email address to convert, as a
  2697. * Unicode string.
  2698. * @returns {String} The Punycode representation of the given domain name or
  2699. * email address.
  2700. */
  2701. function toASCII(input) {
  2702. return mapDomain(input, function(string) {
  2703. return regexNonASCII.test(string)
  2704. ? 'xn--' + encode(string)
  2705. : string;
  2706. });
  2707. }
  2708. /*--------------------------------------------------------------------------*/
  2709. /** Define the public API */
  2710. punycode = {
  2711. /**
  2712. * A string representing the current Punycode.js version number.
  2713. * @memberOf punycode
  2714. * @type String
  2715. */
  2716. 'version': '1.3.2',
  2717. /**
  2718. * An object of methods to convert from JavaScript's internal character
  2719. * representation (UCS-2) to Unicode code points, and back.
  2720. * @see <https://mathiasbynens.be/notes/javascript-encoding>
  2721. * @memberOf punycode
  2722. * @type Object
  2723. */
  2724. 'ucs2': {
  2725. 'decode': ucs2decode,
  2726. 'encode': ucs2encode
  2727. },
  2728. 'decode': decode,
  2729. 'encode': encode,
  2730. 'toASCII': toASCII,
  2731. 'toUnicode': toUnicode
  2732. };
  2733. /** Expose `punycode` */
  2734. // Some AMD build optimizers, like r.js, check for specific condition patterns
  2735. // like the following:
  2736. if (
  2737. typeof undefined == 'function' &&
  2738. typeof undefined.amd == 'object' &&
  2739. undefined.amd
  2740. ) {
  2741. undefined('punycode', function() {
  2742. return punycode;
  2743. });
  2744. } else if (freeExports && freeModule) {
  2745. if (module.exports == freeExports) { // in Node.js or RingoJS v0.8.0+
  2746. freeModule.exports = punycode;
  2747. } else { // in Narwhal or RingoJS v0.7.0-
  2748. for (key in punycode) {
  2749. punycode.hasOwnProperty(key) && (freeExports[key] = punycode[key]);
  2750. }
  2751. }
  2752. } else { // in Rhino or a web browser
  2753. root.punycode = punycode;
  2754. }
  2755. }(commonjsGlobal));
  2756. });
  2757. 'use strict';
  2758. var util = {
  2759. isString: function(arg) {
  2760. return typeof(arg) === 'string';
  2761. },
  2762. isObject: function(arg) {
  2763. return typeof(arg) === 'object' && arg !== null;
  2764. },
  2765. isNull: function(arg) {
  2766. return arg === null;
  2767. },
  2768. isNullOrUndefined: function(arg) {
  2769. return arg == null;
  2770. }
  2771. };
  2772. // Copyright Joyent, Inc. and other Node contributors.
  2773. //
  2774. // Permission is hereby granted, free of charge, to any person obtaining a
  2775. // copy of this software and associated documentation files (the
  2776. // "Software"), to deal in the Software without restriction, including
  2777. // without limitation the rights to use, copy, modify, merge, publish,
  2778. // distribute, sublicense, and/or sell copies of the Software, and to permit
  2779. // persons to whom the Software is furnished to do so, subject to the
  2780. // following conditions:
  2781. //
  2782. // The above copyright notice and this permission notice shall be included
  2783. // in all copies or substantial portions of the Software.
  2784. //
  2785. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  2786. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  2787. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  2788. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  2789. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  2790. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  2791. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  2792. 'use strict';
  2793. // If obj.hasOwnProperty has been overridden, then calling
  2794. // obj.hasOwnProperty(prop) will break.
  2795. // See: https://github.com/joyent/node/issues/1707
  2796. function hasOwnProperty(obj, prop) {
  2797. return Object.prototype.hasOwnProperty.call(obj, prop);
  2798. }
  2799. var decode = function(qs, sep, eq, options) {
  2800. sep = sep || '&';
  2801. eq = eq || '=';
  2802. var obj = {};
  2803. if (typeof qs !== 'string' || qs.length === 0) {
  2804. return obj;
  2805. }
  2806. var regexp = /\+/g;
  2807. qs = qs.split(sep);
  2808. var maxKeys = 1000;
  2809. if (options && typeof options.maxKeys === 'number') {
  2810. maxKeys = options.maxKeys;
  2811. }
  2812. var len = qs.length;
  2813. // maxKeys <= 0 means that we should not limit keys count
  2814. if (maxKeys > 0 && len > maxKeys) {
  2815. len = maxKeys;
  2816. }
  2817. for (var i = 0; i < len; ++i) {
  2818. var x = qs[i].replace(regexp, '%20'),
  2819. idx = x.indexOf(eq),
  2820. kstr, vstr, k, v;
  2821. if (idx >= 0) {
  2822. kstr = x.substr(0, idx);
  2823. vstr = x.substr(idx + 1);
  2824. } else {
  2825. kstr = x;
  2826. vstr = '';
  2827. }
  2828. k = decodeURIComponent(kstr);
  2829. v = decodeURIComponent(vstr);
  2830. if (!hasOwnProperty(obj, k)) {
  2831. obj[k] = v;
  2832. } else if (Array.isArray(obj[k])) {
  2833. obj[k].push(v);
  2834. } else {
  2835. obj[k] = [obj[k], v];
  2836. }
  2837. }
  2838. return obj;
  2839. };
  2840. // Copyright Joyent, Inc. and other Node contributors.
  2841. //
  2842. // Permission is hereby granted, free of charge, to any person obtaining a
  2843. // copy of this software and associated documentation files (the
  2844. // "Software"), to deal in the Software without restriction, including
  2845. // without limitation the rights to use, copy, modify, merge, publish,
  2846. // distribute, sublicense, and/or sell copies of the Software, and to permit
  2847. // persons to whom the Software is furnished to do so, subject to the
  2848. // following conditions:
  2849. //
  2850. // The above copyright notice and this permission notice shall be included
  2851. // in all copies or substantial portions of the Software.
  2852. //
  2853. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  2854. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  2855. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  2856. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  2857. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  2858. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  2859. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  2860. 'use strict';
  2861. var stringifyPrimitive = function(v) {
  2862. switch (typeof v) {
  2863. case 'string':
  2864. return v;
  2865. case 'boolean':
  2866. return v ? 'true' : 'false';
  2867. case 'number':
  2868. return isFinite(v) ? v : '';
  2869. default:
  2870. return '';
  2871. }
  2872. };
  2873. var encode = function(obj, sep, eq, name) {
  2874. sep = sep || '&';
  2875. eq = eq || '=';
  2876. if (obj === null) {
  2877. obj = undefined;
  2878. }
  2879. if (typeof obj === 'object') {
  2880. return Object.keys(obj).map(function(k) {
  2881. var ks = encodeURIComponent(stringifyPrimitive(k)) + eq;
  2882. if (Array.isArray(obj[k])) {
  2883. return obj[k].map(function(v) {
  2884. return ks + encodeURIComponent(stringifyPrimitive(v));
  2885. }).join(sep);
  2886. } else {
  2887. return ks + encodeURIComponent(stringifyPrimitive(obj[k]));
  2888. }
  2889. }).join(sep);
  2890. }
  2891. if (!name) { return ''; }
  2892. return encodeURIComponent(stringifyPrimitive(name)) + eq +
  2893. encodeURIComponent(stringifyPrimitive(obj));
  2894. };
  2895. var querystring = createCommonjsModule(function (module, exports) {
  2896. 'use strict';
  2897. exports.decode = exports.parse = decode;
  2898. exports.encode = exports.stringify = encode;
  2899. });
  2900. // Copyright Joyent, Inc. and other Node contributors.
  2901. //
  2902. // Permission is hereby granted, free of charge, to any person obtaining a
  2903. // copy of this software and associated documentation files (the
  2904. // "Software"), to deal in the Software without restriction, including
  2905. // without limitation the rights to use, copy, modify, merge, publish,
  2906. // distribute, sublicense, and/or sell copies of the Software, and to permit
  2907. // persons to whom the Software is furnished to do so, subject to the
  2908. // following conditions:
  2909. //
  2910. // The above copyright notice and this permission notice shall be included
  2911. // in all copies or substantial portions of the Software.
  2912. //
  2913. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  2914. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  2915. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  2916. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  2917. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  2918. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  2919. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  2920. 'use strict';
  2921. var parse = urlParse;
  2922. var resolve = urlResolve;
  2923. var resolveObject = urlResolveObject;
  2924. var format = urlFormat;
  2925. var Url_1 = Url;
  2926. function Url() {
  2927. this.protocol = null;
  2928. this.slashes = null;
  2929. this.auth = null;
  2930. this.host = null;
  2931. this.port = null;
  2932. this.hostname = null;
  2933. this.hash = null;
  2934. this.search = null;
  2935. this.query = null;
  2936. this.pathname = null;
  2937. this.path = null;
  2938. this.href = null;
  2939. }
  2940. // Reference: RFC 3986, RFC 1808, RFC 2396
  2941. // define these here so at least they only have to be
  2942. // compiled once on the first module load.
  2943. var protocolPattern = /^([a-z0-9.+-]+:)/i,
  2944. portPattern = /:[0-9]*$/,
  2945. // Special case for a simple path URL
  2946. simplePathPattern = /^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/,
  2947. // RFC 2396: characters reserved for delimiting URLs.
  2948. // We actually just auto-escape these.
  2949. delims = ['<', '>', '"', '`', ' ', '\r', '\n', '\t'],
  2950. // RFC 2396: characters not allowed for various reasons.
  2951. unwise = ['{', '}', '|', '\\', '^', '`'].concat(delims),
  2952. // Allowed by RFCs, but cause of XSS attacks. Always escape these.
  2953. autoEscape = ['\''].concat(unwise),
  2954. // Characters that are never ever allowed in a hostname.
  2955. // Note that any invalid chars are also handled, but these
  2956. // are the ones that are *expected* to be seen, so we fast-path
  2957. // them.
  2958. nonHostChars = ['%', '/', '?', ';', '#'].concat(autoEscape),
  2959. hostEndingChars = ['/', '?', '#'],
  2960. hostnameMaxLen = 255,
  2961. hostnamePartPattern = /^[+a-z0-9A-Z_-]{0,63}$/,
  2962. hostnamePartStart = /^([+a-z0-9A-Z_-]{0,63})(.*)$/,
  2963. // protocols that can allow "unsafe" and "unwise" chars.
  2964. unsafeProtocol = {
  2965. 'javascript': true,
  2966. 'javascript:': true
  2967. },
  2968. // protocols that never have a hostname.
  2969. hostlessProtocol = {
  2970. 'javascript': true,
  2971. 'javascript:': true
  2972. },
  2973. // protocols that always contain a // bit.
  2974. slashedProtocol = {
  2975. 'http': true,
  2976. 'https': true,
  2977. 'ftp': true,
  2978. 'gopher': true,
  2979. 'file': true,
  2980. 'http:': true,
  2981. 'https:': true,
  2982. 'ftp:': true,
  2983. 'gopher:': true,
  2984. 'file:': true
  2985. };
  2986. function urlParse(url, parseQueryString, slashesDenoteHost) {
  2987. if (url && util.isObject(url) && url instanceof Url) { return url; }
  2988. var u = new Url;
  2989. u.parse(url, parseQueryString, slashesDenoteHost);
  2990. return u;
  2991. }
  2992. Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) {
  2993. if (!util.isString(url)) {
  2994. throw new TypeError("Parameter 'url' must be a string, not " + typeof url);
  2995. }
  2996. // Copy chrome, IE, opera backslash-handling behavior.
  2997. // Back slashes before the query string get converted to forward slashes
  2998. // See: https://code.google.com/p/chromium/issues/detail?id=25916
  2999. var queryIndex = url.indexOf('?'),
  3000. splitter =
  3001. (queryIndex !== -1 && queryIndex < url.indexOf('#')) ? '?' : '#',
  3002. uSplit = url.split(splitter),
  3003. slashRegex = /\\/g;
  3004. uSplit[0] = uSplit[0].replace(slashRegex, '/');
  3005. url = uSplit.join(splitter);
  3006. var rest = url;
  3007. // trim before proceeding.
  3008. // This is to support parse stuff like " http://foo.com \n"
  3009. rest = rest.trim();
  3010. if (!slashesDenoteHost && url.split('#').length === 1) {
  3011. // Try fast path regexp
  3012. var simplePath = simplePathPattern.exec(rest);
  3013. if (simplePath) {
  3014. this.path = rest;
  3015. this.href = rest;
  3016. this.pathname = simplePath[1];
  3017. if (simplePath[2]) {
  3018. this.search = simplePath[2];
  3019. if (parseQueryString) {
  3020. this.query = querystring.parse(this.search.substr(1));
  3021. } else {
  3022. this.query = this.search.substr(1);
  3023. }
  3024. } else if (parseQueryString) {
  3025. this.search = '';
  3026. this.query = {};
  3027. }
  3028. return this;
  3029. }
  3030. }
  3031. var proto = protocolPattern.exec(rest);
  3032. if (proto) {
  3033. proto = proto[0];
  3034. var lowerProto = proto.toLowerCase();
  3035. this.protocol = lowerProto;
  3036. rest = rest.substr(proto.length);
  3037. }
  3038. // figure out if it's got a host
  3039. // user@server is *always* interpreted as a hostname, and url
  3040. // resolution will treat //foo/bar as host=foo,path=bar because that's
  3041. // how the browser resolves relative URLs.
  3042. if (slashesDenoteHost || proto || rest.match(/^\/\/[^@\/]+@[^@\/]+/)) {
  3043. var slashes = rest.substr(0, 2) === '//';
  3044. if (slashes && !(proto && hostlessProtocol[proto])) {
  3045. rest = rest.substr(2);
  3046. this.slashes = true;
  3047. }
  3048. }
  3049. if (!hostlessProtocol[proto] &&
  3050. (slashes || (proto && !slashedProtocol[proto]))) {
  3051. // there's a hostname.
  3052. // the first instance of /, ?, ;, or # ends the host.
  3053. //
  3054. // If there is an @ in the hostname, then non-host chars *are* allowed
  3055. // to the left of the last @ sign, unless some host-ending character
  3056. // comes *before* the @-sign.
  3057. // URLs are obnoxious.
  3058. //
  3059. // ex:
  3060. // http://a@b@c/ => user:a@b host:c
  3061. // http://a@b?@c => user:a host:c path:/?@c
  3062. // v0.12 TODO(isaacs): This is not quite how Chrome does things.
  3063. // Review our test case against browsers more comprehensively.
  3064. // find the first instance of any hostEndingChars
  3065. var hostEnd = -1;
  3066. for (var i = 0; i < hostEndingChars.length; i++) {
  3067. var hec = rest.indexOf(hostEndingChars[i]);
  3068. if (hec !== -1 && (hostEnd === -1 || hec < hostEnd))
  3069. { hostEnd = hec; }
  3070. }
  3071. // at this point, either we have an explicit point where the
  3072. // auth portion cannot go past, or the last @ char is the decider.
  3073. var auth, atSign;
  3074. if (hostEnd === -1) {
  3075. // atSign can be anywhere.
  3076. atSign = rest.lastIndexOf('@');
  3077. } else {
  3078. // atSign must be in auth portion.
  3079. // http://a@b/c@d => host:b auth:a path:/c@d
  3080. atSign = rest.lastIndexOf('@', hostEnd);
  3081. }
  3082. // Now we have a portion which is definitely the auth.
  3083. // Pull that off.
  3084. if (atSign !== -1) {
  3085. auth = rest.slice(0, atSign);
  3086. rest = rest.slice(atSign + 1);
  3087. this.auth = decodeURIComponent(auth);
  3088. }
  3089. // the host is the remaining to the left of the first non-host char
  3090. hostEnd = -1;
  3091. for (var i = 0; i < nonHostChars.length; i++) {
  3092. var hec = rest.indexOf(nonHostChars[i]);
  3093. if (hec !== -1 && (hostEnd === -1 || hec < hostEnd))
  3094. { hostEnd = hec; }
  3095. }
  3096. // if we still have not hit it, then the entire thing is a host.
  3097. if (hostEnd === -1)
  3098. { hostEnd = rest.length; }
  3099. this.host = rest.slice(0, hostEnd);
  3100. rest = rest.slice(hostEnd);
  3101. // pull out port.
  3102. this.parseHost();
  3103. // we've indicated that there is a hostname,
  3104. // so even if it's empty, it has to be present.
  3105. this.hostname = this.hostname || '';
  3106. // if hostname begins with [ and ends with ]
  3107. // assume that it's an IPv6 address.
  3108. var ipv6Hostname = this.hostname[0] === '[' &&
  3109. this.hostname[this.hostname.length - 1] === ']';
  3110. // validate a little.
  3111. if (!ipv6Hostname) {
  3112. var hostparts = this.hostname.split(/\./);
  3113. for (var i = 0, l = hostparts.length; i < l; i++) {
  3114. var part = hostparts[i];
  3115. if (!part) { continue; }
  3116. if (!part.match(hostnamePartPattern)) {
  3117. var newpart = '';
  3118. for (var j = 0, k = part.length; j < k; j++) {
  3119. if (part.charCodeAt(j) > 127) {
  3120. // we replace non-ASCII char with a temporary placeholder
  3121. // we need this to make sure size of hostname is not
  3122. // broken by replacing non-ASCII by nothing
  3123. newpart += 'x';
  3124. } else {
  3125. newpart += part[j];
  3126. }
  3127. }
  3128. // we test again with ASCII char only
  3129. if (!newpart.match(hostnamePartPattern)) {
  3130. var validParts = hostparts.slice(0, i);
  3131. var notHost = hostparts.slice(i + 1);
  3132. var bit = part.match(hostnamePartStart);
  3133. if (bit) {
  3134. validParts.push(bit[1]);
  3135. notHost.unshift(bit[2]);
  3136. }
  3137. if (notHost.length) {
  3138. rest = '/' + notHost.join('.') + rest;
  3139. }
  3140. this.hostname = validParts.join('.');
  3141. break;
  3142. }
  3143. }
  3144. }
  3145. }
  3146. if (this.hostname.length > hostnameMaxLen) {
  3147. this.hostname = '';
  3148. } else {
  3149. // hostnames are always lower case.
  3150. this.hostname = this.hostname.toLowerCase();
  3151. }
  3152. if (!ipv6Hostname) {
  3153. // IDNA Support: Returns a punycoded representation of "domain".
  3154. // It only converts parts of the domain name that
  3155. // have non-ASCII characters, i.e. it doesn't matter if
  3156. // you call it with a domain that already is ASCII-only.
  3157. this.hostname = punycode.toASCII(this.hostname);
  3158. }
  3159. var p = this.port ? ':' + this.port : '';
  3160. var h = this.hostname || '';
  3161. this.host = h + p;
  3162. this.href += this.host;
  3163. // strip [ and ] from the hostname
  3164. // the host field still retains them, though
  3165. if (ipv6Hostname) {
  3166. this.hostname = this.hostname.substr(1, this.hostname.length - 2);
  3167. if (rest[0] !== '/') {
  3168. rest = '/' + rest;
  3169. }
  3170. }
  3171. }
  3172. // now rest is set to the post-host stuff.
  3173. // chop off any delim chars.
  3174. if (!unsafeProtocol[lowerProto]) {
  3175. // First, make 100% sure that any "autoEscape" chars get
  3176. // escaped, even if encodeURIComponent doesn't think they
  3177. // need to be.
  3178. for (var i = 0, l = autoEscape.length; i < l; i++) {
  3179. var ae = autoEscape[i];
  3180. if (rest.indexOf(ae) === -1)
  3181. { continue; }
  3182. var esc = encodeURIComponent(ae);
  3183. if (esc === ae) {
  3184. esc = escape(ae);
  3185. }
  3186. rest = rest.split(ae).join(esc);
  3187. }
  3188. }
  3189. // chop off from the tail first.
  3190. var hash = rest.indexOf('#');
  3191. if (hash !== -1) {
  3192. // got a fragment string.
  3193. this.hash = rest.substr(hash);
  3194. rest = rest.slice(0, hash);
  3195. }
  3196. var qm = rest.indexOf('?');
  3197. if (qm !== -1) {
  3198. this.search = rest.substr(qm);
  3199. this.query = rest.substr(qm + 1);
  3200. if (parseQueryString) {
  3201. this.query = querystring.parse(this.query);
  3202. }
  3203. rest = rest.slice(0, qm);
  3204. } else if (parseQueryString) {
  3205. // no query string, but parseQueryString still requested
  3206. this.search = '';
  3207. this.query = {};
  3208. }
  3209. if (rest) { this.pathname = rest; }
  3210. if (slashedProtocol[lowerProto] &&
  3211. this.hostname && !this.pathname) {
  3212. this.pathname = '/';
  3213. }
  3214. //to support http.request
  3215. if (this.pathname || this.search) {
  3216. var p = this.pathname || '';
  3217. var s = this.search || '';
  3218. this.path = p + s;
  3219. }
  3220. // finally, reconstruct the href based on what has been validated.
  3221. this.href = this.format();
  3222. return this;
  3223. };
  3224. // format a parsed object into a url string
  3225. function urlFormat(obj) {
  3226. // ensure it's an object, and not a string url.
  3227. // If it's an obj, this is a no-op.
  3228. // this way, you can call url_format() on strings
  3229. // to clean up potentially wonky urls.
  3230. if (util.isString(obj)) { obj = urlParse(obj); }
  3231. if (!(obj instanceof Url)) { return Url.prototype.format.call(obj); }
  3232. return obj.format();
  3233. }
  3234. Url.prototype.format = function() {
  3235. var auth = this.auth || '';
  3236. if (auth) {
  3237. auth = encodeURIComponent(auth);
  3238. auth = auth.replace(/%3A/i, ':');
  3239. auth += '@';
  3240. }
  3241. var protocol = this.protocol || '',
  3242. pathname = this.pathname || '',
  3243. hash = this.hash || '',
  3244. host = false,
  3245. query = '';
  3246. if (this.host) {
  3247. host = auth + this.host;
  3248. } else if (this.hostname) {
  3249. host = auth + (this.hostname.indexOf(':') === -1 ?
  3250. this.hostname :
  3251. '[' + this.hostname + ']');
  3252. if (this.port) {
  3253. host += ':' + this.port;
  3254. }
  3255. }
  3256. if (this.query &&
  3257. util.isObject(this.query) &&
  3258. Object.keys(this.query).length) {
  3259. query = querystring.stringify(this.query);
  3260. }
  3261. var search = this.search || (query && ('?' + query)) || '';
  3262. if (protocol && protocol.substr(-1) !== ':') { protocol += ':'; }
  3263. // only the slashedProtocols get the //. Not mailto:, xmpp:, etc.
  3264. // unless they had them to begin with.
  3265. if (this.slashes ||
  3266. (!protocol || slashedProtocol[protocol]) && host !== false) {
  3267. host = '//' + (host || '');
  3268. if (pathname && pathname.charAt(0) !== '/') { pathname = '/' + pathname; }
  3269. } else if (!host) {
  3270. host = '';
  3271. }
  3272. if (hash && hash.charAt(0) !== '#') { hash = '#' + hash; }
  3273. if (search && search.charAt(0) !== '?') { search = '?' + search; }
  3274. pathname = pathname.replace(/[?#]/g, function(match) {
  3275. return encodeURIComponent(match);
  3276. });
  3277. search = search.replace('#', '%23');
  3278. return protocol + host + pathname + search + hash;
  3279. };
  3280. function urlResolve(source, relative) {
  3281. return urlParse(source, false, true).resolve(relative);
  3282. }
  3283. Url.prototype.resolve = function(relative) {
  3284. return this.resolveObject(urlParse(relative, false, true)).format();
  3285. };
  3286. function urlResolveObject(source, relative) {
  3287. if (!source) { return relative; }
  3288. return urlParse(source, false, true).resolveObject(relative);
  3289. }
  3290. Url.prototype.resolveObject = function(relative) {
  3291. if (util.isString(relative)) {
  3292. var rel = new Url();
  3293. rel.parse(relative, false, true);
  3294. relative = rel;
  3295. }
  3296. var result = new Url();
  3297. var tkeys = Object.keys(this);
  3298. for (var tk = 0; tk < tkeys.length; tk++) {
  3299. var tkey = tkeys[tk];
  3300. result[tkey] = this[tkey];
  3301. }
  3302. // hash is always overridden, no matter what.
  3303. // even href="" will remove it.
  3304. result.hash = relative.hash;
  3305. // if the relative url is empty, then there's nothing left to do here.
  3306. if (relative.href === '') {
  3307. result.href = result.format();
  3308. return result;
  3309. }
  3310. // hrefs like //foo/bar always cut to the protocol.
  3311. if (relative.slashes && !relative.protocol) {
  3312. // take everything except the protocol from relative
  3313. var rkeys = Object.keys(relative);
  3314. for (var rk = 0; rk < rkeys.length; rk++) {
  3315. var rkey = rkeys[rk];
  3316. if (rkey !== 'protocol')
  3317. { result[rkey] = relative[rkey]; }
  3318. }
  3319. //urlParse appends trailing / to urls like http://www.example.com
  3320. if (slashedProtocol[result.protocol] &&
  3321. result.hostname && !result.pathname) {
  3322. result.path = result.pathname = '/';
  3323. }
  3324. result.href = result.format();
  3325. return result;
  3326. }
  3327. if (relative.protocol && relative.protocol !== result.protocol) {
  3328. // if it's a known url protocol, then changing
  3329. // the protocol does weird things
  3330. // first, if it's not file:, then we MUST have a host,
  3331. // and if there was a path
  3332. // to begin with, then we MUST have a path.
  3333. // if it is file:, then the host is dropped,
  3334. // because that's known to be hostless.
  3335. // anything else is assumed to be absolute.
  3336. if (!slashedProtocol[relative.protocol]) {
  3337. var keys = Object.keys(relative);
  3338. for (var v = 0; v < keys.length; v++) {
  3339. var k = keys[v];
  3340. result[k] = relative[k];
  3341. }
  3342. result.href = result.format();
  3343. return result;
  3344. }
  3345. result.protocol = relative.protocol;
  3346. if (!relative.host && !hostlessProtocol[relative.protocol]) {
  3347. var relPath = (relative.pathname || '').split('/');
  3348. while (relPath.length && !(relative.host = relPath.shift())){ ; }
  3349. if (!relative.host) { relative.host = ''; }
  3350. if (!relative.hostname) { relative.hostname = ''; }
  3351. if (relPath[0] !== '') { relPath.unshift(''); }
  3352. if (relPath.length < 2) { relPath.unshift(''); }
  3353. result.pathname = relPath.join('/');
  3354. } else {
  3355. result.pathname = relative.pathname;
  3356. }
  3357. result.search = relative.search;
  3358. result.query = relative.query;
  3359. result.host = relative.host || '';
  3360. result.auth = relative.auth;
  3361. result.hostname = relative.hostname || relative.host;
  3362. result.port = relative.port;
  3363. // to support http.request
  3364. if (result.pathname || result.search) {
  3365. var p = result.pathname || '';
  3366. var s = result.search || '';
  3367. result.path = p + s;
  3368. }
  3369. result.slashes = result.slashes || relative.slashes;
  3370. result.href = result.format();
  3371. return result;
  3372. }
  3373. var isSourceAbs = (result.pathname && result.pathname.charAt(0) === '/'),
  3374. isRelAbs = (
  3375. relative.host ||
  3376. relative.pathname && relative.pathname.charAt(0) === '/'
  3377. ),
  3378. mustEndAbs = (isRelAbs || isSourceAbs ||
  3379. (result.host && relative.pathname)),
  3380. removeAllDots = mustEndAbs,
  3381. srcPath = result.pathname && result.pathname.split('/') || [],
  3382. relPath = relative.pathname && relative.pathname.split('/') || [],
  3383. psychotic = result.protocol && !slashedProtocol[result.protocol];
  3384. // if the url is a non-slashed url, then relative
  3385. // links like ../.. should be able
  3386. // to crawl up to the hostname, as well. This is strange.
  3387. // result.protocol has already been set by now.
  3388. // Later on, put the first path part into the host field.
  3389. if (psychotic) {
  3390. result.hostname = '';
  3391. result.port = null;
  3392. if (result.host) {
  3393. if (srcPath[0] === '') { srcPath[0] = result.host; }
  3394. else { srcPath.unshift(result.host); }
  3395. }
  3396. result.host = '';
  3397. if (relative.protocol) {
  3398. relative.hostname = null;
  3399. relative.port = null;
  3400. if (relative.host) {
  3401. if (relPath[0] === '') { relPath[0] = relative.host; }
  3402. else { relPath.unshift(relative.host); }
  3403. }
  3404. relative.host = null;
  3405. }
  3406. mustEndAbs = mustEndAbs && (relPath[0] === '' || srcPath[0] === '');
  3407. }
  3408. if (isRelAbs) {
  3409. // it's absolute.
  3410. result.host = (relative.host || relative.host === '') ?
  3411. relative.host : result.host;
  3412. result.hostname = (relative.hostname || relative.hostname === '') ?
  3413. relative.hostname : result.hostname;
  3414. result.search = relative.search;
  3415. result.query = relative.query;
  3416. srcPath = relPath;
  3417. // fall through to the dot-handling below.
  3418. } else if (relPath.length) {
  3419. // it's relative
  3420. // throw away the existing file, and take the new path instead.
  3421. if (!srcPath) { srcPath = []; }
  3422. srcPath.pop();
  3423. srcPath = srcPath.concat(relPath);
  3424. result.search = relative.search;
  3425. result.query = relative.query;
  3426. } else if (!util.isNullOrUndefined(relative.search)) {
  3427. // just pull out the search.
  3428. // like href='?foo'.
  3429. // Put this after the other two cases because it simplifies the booleans
  3430. if (psychotic) {
  3431. result.hostname = result.host = srcPath.shift();
  3432. //occationaly the auth can get stuck only in host
  3433. //this especially happens in cases like
  3434. //url.resolveObject('mailto:local1@domain1', 'local2@domain2')
  3435. var authInHost = result.host && result.host.indexOf('@') > 0 ?
  3436. result.host.split('@') : false;
  3437. if (authInHost) {
  3438. result.auth = authInHost.shift();
  3439. result.host = result.hostname = authInHost.shift();
  3440. }
  3441. }
  3442. result.search = relative.search;
  3443. result.query = relative.query;
  3444. //to support http.request
  3445. if (!util.isNull(result.pathname) || !util.isNull(result.search)) {
  3446. result.path = (result.pathname ? result.pathname : '') +
  3447. (result.search ? result.search : '');
  3448. }
  3449. result.href = result.format();
  3450. return result;
  3451. }
  3452. if (!srcPath.length) {
  3453. // no path at all. easy.
  3454. // we've already handled the other stuff above.
  3455. result.pathname = null;
  3456. //to support http.request
  3457. if (result.search) {
  3458. result.path = '/' + result.search;
  3459. } else {
  3460. result.path = null;
  3461. }
  3462. result.href = result.format();
  3463. return result;
  3464. }
  3465. // if a url ENDs in . or .., then it must get a trailing slash.
  3466. // however, if it ends in anything else non-slashy,
  3467. // then it must NOT get a trailing slash.
  3468. var last = srcPath.slice(-1)[0];
  3469. var hasTrailingSlash = (
  3470. (result.host || relative.host || srcPath.length > 1) &&
  3471. (last === '.' || last === '..') || last === '');
  3472. // strip single dots, resolve double dots to parent dir
  3473. // if the path tries to go above the root, `up` ends up > 0
  3474. var up = 0;
  3475. for (var i = srcPath.length; i >= 0; i--) {
  3476. last = srcPath[i];
  3477. if (last === '.') {
  3478. srcPath.splice(i, 1);
  3479. } else if (last === '..') {
  3480. srcPath.splice(i, 1);
  3481. up++;
  3482. } else if (up) {
  3483. srcPath.splice(i, 1);
  3484. up--;
  3485. }
  3486. }
  3487. // if the path is allowed to go above the root, restore leading ..s
  3488. if (!mustEndAbs && !removeAllDots) {
  3489. for (; up--; up) {
  3490. srcPath.unshift('..');
  3491. }
  3492. }
  3493. if (mustEndAbs && srcPath[0] !== '' &&
  3494. (!srcPath[0] || srcPath[0].charAt(0) !== '/')) {
  3495. srcPath.unshift('');
  3496. }
  3497. if (hasTrailingSlash && (srcPath.join('/').substr(-1) !== '/')) {
  3498. srcPath.push('');
  3499. }
  3500. var isAbsolute = srcPath[0] === '' ||
  3501. (srcPath[0] && srcPath[0].charAt(0) === '/');
  3502. // put the host back
  3503. if (psychotic) {
  3504. result.hostname = result.host = isAbsolute ? '' :
  3505. srcPath.length ? srcPath.shift() : '';
  3506. //occationaly the auth can get stuck only in host
  3507. //this especially happens in cases like
  3508. //url.resolveObject('mailto:local1@domain1', 'local2@domain2')
  3509. var authInHost = result.host && result.host.indexOf('@') > 0 ?
  3510. result.host.split('@') : false;
  3511. if (authInHost) {
  3512. result.auth = authInHost.shift();
  3513. result.host = result.hostname = authInHost.shift();
  3514. }
  3515. }
  3516. mustEndAbs = mustEndAbs || (result.host && srcPath.length);
  3517. if (mustEndAbs && !isAbsolute) {
  3518. srcPath.unshift('');
  3519. }
  3520. if (!srcPath.length) {
  3521. result.pathname = null;
  3522. result.path = null;
  3523. } else {
  3524. result.pathname = srcPath.join('/');
  3525. }
  3526. //to support request.http
  3527. if (!util.isNull(result.pathname) || !util.isNull(result.search)) {
  3528. result.path = (result.pathname ? result.pathname : '') +
  3529. (result.search ? result.search : '');
  3530. }
  3531. result.auth = relative.auth || result.auth;
  3532. result.slashes = result.slashes || relative.slashes;
  3533. result.href = result.format();
  3534. return result;
  3535. };
  3536. Url.prototype.parseHost = function() {
  3537. var host = this.host;
  3538. var port = portPattern.exec(host);
  3539. if (port) {
  3540. port = port[0];
  3541. if (port !== ':') {
  3542. this.port = port.substr(1);
  3543. }
  3544. host = host.substr(0, host.length - port.length);
  3545. }
  3546. if (host) { this.hostname = host; }
  3547. };
  3548. var url$1 = {
  3549. parse: parse,
  3550. resolve: resolve,
  3551. resolveObject: resolveObject,
  3552. format: format,
  3553. Url: Url_1
  3554. };
  3555. /*!
  3556. * @pixi/utils - v6.5.10
  3557. * Compiled Thu, 06 Jul 2023 15:25:11 UTC
  3558. *
  3559. * @pixi/utils is licensed under the MIT License.
  3560. * http://www.opensource.org/licenses/mit-license
  3561. */
  3562. /**
  3563. * This file contains redeclared types for Node `url` and `querystring` modules. These modules
  3564. * don't provide their own typings but instead are a part of the full Node typings. The purpose of
  3565. * this file is to redeclare the required types to avoid having the whole Node types as a
  3566. * dependency.
  3567. */
  3568. var url = {
  3569. parse: parse,
  3570. format: format,
  3571. resolve: resolve,
  3572. };
  3573. function assertPath(path) {
  3574. if (typeof path !== 'string') {
  3575. throw new TypeError("Path must be a string. Received " + JSON.stringify(path));
  3576. }
  3577. }
  3578. function removeUrlParams(url) {
  3579. var re = url.split('?')[0];
  3580. return re.split('#')[0];
  3581. }
  3582. function escapeRegExp(string) {
  3583. return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
  3584. }
  3585. function replaceAll(str, find, replace) {
  3586. return str.replace(new RegExp(escapeRegExp(find), 'g'), replace);
  3587. }
  3588. // Resolves . and .. elements in a path with directory names
  3589. function normalizeStringPosix(path, allowAboveRoot) {
  3590. var res = '';
  3591. var lastSegmentLength = 0;
  3592. var lastSlash = -1;
  3593. var dots = 0;
  3594. var code;
  3595. for (var i = 0; i <= path.length; ++i) {
  3596. if (i < path.length) {
  3597. code = path.charCodeAt(i);
  3598. }
  3599. else if (code === 47) {
  3600. break;
  3601. }
  3602. else {
  3603. code = 47;
  3604. }
  3605. if (code === 47) {
  3606. if (lastSlash === i - 1 || dots === 1) { ; }
  3607. else if (lastSlash !== i - 1 && dots === 2) {
  3608. if (res.length < 2
  3609. || lastSegmentLength !== 2
  3610. || res.charCodeAt(res.length - 1) !== 46
  3611. || res.charCodeAt(res.length - 2) !== 46) {
  3612. if (res.length > 2) {
  3613. var lastSlashIndex = res.lastIndexOf('/');
  3614. if (lastSlashIndex !== res.length - 1) {
  3615. if (lastSlashIndex === -1) {
  3616. res = '';
  3617. lastSegmentLength = 0;
  3618. }
  3619. else {
  3620. res = res.slice(0, lastSlashIndex);
  3621. lastSegmentLength = res.length - 1 - res.lastIndexOf('/');
  3622. }
  3623. lastSlash = i;
  3624. dots = 0;
  3625. continue;
  3626. }
  3627. }
  3628. else if (res.length === 2 || res.length === 1) {
  3629. res = '';
  3630. lastSegmentLength = 0;
  3631. lastSlash = i;
  3632. dots = 0;
  3633. continue;
  3634. }
  3635. }
  3636. if (allowAboveRoot) {
  3637. if (res.length > 0) {
  3638. res += '/..';
  3639. }
  3640. else {
  3641. res = '..';
  3642. }
  3643. lastSegmentLength = 2;
  3644. }
  3645. }
  3646. else {
  3647. if (res.length > 0) {
  3648. res += "/" + path.slice(lastSlash + 1, i);
  3649. }
  3650. else {
  3651. res = path.slice(lastSlash + 1, i);
  3652. }
  3653. lastSegmentLength = i - lastSlash - 1;
  3654. }
  3655. lastSlash = i;
  3656. dots = 0;
  3657. }
  3658. else if (code === 46 && dots !== -1) {
  3659. ++dots;
  3660. }
  3661. else {
  3662. dots = -1;
  3663. }
  3664. }
  3665. return res;
  3666. }
  3667. var path = {
  3668. /**
  3669. * Converts a path to posix format.
  3670. * @param path - The path to convert to posix
  3671. */
  3672. toPosix: function (path) { return replaceAll(path, '\\', '/'); },
  3673. /**
  3674. * Checks if the path is a URL
  3675. * @param path - The path to check
  3676. */
  3677. isUrl: function (path) { return (/^https?:/).test(this.toPosix(path)); },
  3678. /**
  3679. * Checks if the path is a data URL
  3680. * @param path - The path to check
  3681. */
  3682. isDataUrl: function (path) {
  3683. // eslint-disable-next-line max-len
  3684. return (/^data:([a-z]+\/[a-z0-9-+.]+(;[a-z0-9-.!#$%*+.{}|~`]+=[a-z0-9-.!#$%*+.{}()_|~`]+)*)?(;base64)?,([a-z0-9!$&',()*+;=\-._~:@\/?%\s<>]*?)$/i)
  3685. .test(path);
  3686. },
  3687. /**
  3688. * Checks if the path has a protocol e.g. http://
  3689. * This will return true for windows file paths
  3690. * @param path - The path to check
  3691. */
  3692. hasProtocol: function (path) { return (/^[^/:]+:\//).test(this.toPosix(path)); },
  3693. /**
  3694. * Returns the protocol of the path e.g. http://, C:/, file:///
  3695. * @param path - The path to get the protocol from
  3696. */
  3697. getProtocol: function (path) {
  3698. assertPath(path);
  3699. path = this.toPosix(path);
  3700. var protocol = '';
  3701. var isFile = (/^file:\/\/\//).exec(path);
  3702. var isHttp = (/^[^/:]+:\/\//).exec(path);
  3703. var isWindows = (/^[^/:]+:\//).exec(path);
  3704. if (isFile || isHttp || isWindows) {
  3705. var arr = (isFile === null || isFile === void 0 ? void 0 : isFile[0]) || (isHttp === null || isHttp === void 0 ? void 0 : isHttp[0]) || (isWindows === null || isWindows === void 0 ? void 0 : isWindows[0]);
  3706. protocol = arr;
  3707. path = path.slice(arr.length);
  3708. }
  3709. return protocol;
  3710. },
  3711. /**
  3712. * Converts URL to an absolute path.
  3713. * When loading from a Web Worker, we must use absolute paths.
  3714. * If the URL is already absolute we return it as is
  3715. * If it's not, we convert it
  3716. * @param url - The URL to test
  3717. * @param customBaseUrl - The base URL to use
  3718. * @param customRootUrl - The root URL to use
  3719. */
  3720. toAbsolute: function (url, customBaseUrl, customRootUrl) {
  3721. if (this.isDataUrl(url))
  3722. { return url; }
  3723. var baseUrl = removeUrlParams(this.toPosix(customBaseUrl !== null && customBaseUrl !== void 0 ? customBaseUrl : settings.ADAPTER.getBaseUrl()));
  3724. var rootUrl = removeUrlParams(this.toPosix(customRootUrl !== null && customRootUrl !== void 0 ? customRootUrl : this.rootname(baseUrl)));
  3725. assertPath(url);
  3726. url = this.toPosix(url);
  3727. // root relative url
  3728. if (url.startsWith('/')) {
  3729. return path.join(rootUrl, url.slice(1));
  3730. }
  3731. var absolutePath = this.isAbsolute(url) ? url : this.join(baseUrl, url);
  3732. return absolutePath;
  3733. },
  3734. /**
  3735. * Normalizes the given path, resolving '..' and '.' segments
  3736. * @param path - The path to normalize
  3737. */
  3738. normalize: function (path) {
  3739. path = this.toPosix(path);
  3740. assertPath(path);
  3741. if (path.length === 0)
  3742. { return '.'; }
  3743. var protocol = '';
  3744. var isAbsolute = path.startsWith('/');
  3745. if (this.hasProtocol(path)) {
  3746. protocol = this.rootname(path);
  3747. path = path.slice(protocol.length);
  3748. }
  3749. var trailingSeparator = path.endsWith('/');
  3750. // Normalize the path
  3751. path = normalizeStringPosix(path, false);
  3752. if (path.length > 0 && trailingSeparator)
  3753. { path += '/'; }
  3754. if (isAbsolute)
  3755. { return "/" + path; }
  3756. return protocol + path;
  3757. },
  3758. /**
  3759. * Determines if path is an absolute path.
  3760. * Absolute paths can be urls, data urls, or paths on disk
  3761. * @param path - The path to test
  3762. */
  3763. isAbsolute: function (path) {
  3764. assertPath(path);
  3765. path = this.toPosix(path);
  3766. if (this.hasProtocol(path))
  3767. { return true; }
  3768. return path.startsWith('/');
  3769. },
  3770. /**
  3771. * Joins all given path segments together using the platform-specific separator as a delimiter,
  3772. * then normalizes the resulting path
  3773. * @param segments - The segments of the path to join
  3774. */
  3775. join: function () {
  3776. var arguments$1 = arguments;
  3777. var _a;
  3778. var segments = [];
  3779. for (var _i = 0; _i < arguments.length; _i++) {
  3780. segments[_i] = arguments$1[_i];
  3781. }
  3782. if (segments.length === 0) {
  3783. return '.';
  3784. }
  3785. var joined;
  3786. for (var i = 0; i < segments.length; ++i) {
  3787. var arg = segments[i];
  3788. assertPath(arg);
  3789. if (arg.length > 0) {
  3790. if (joined === undefined)
  3791. { joined = arg; }
  3792. else {
  3793. var prevArg = (_a = segments[i - 1]) !== null && _a !== void 0 ? _a : '';
  3794. if (this.extname(prevArg)) {
  3795. joined += "/../" + arg;
  3796. }
  3797. else {
  3798. joined += "/" + arg;
  3799. }
  3800. }
  3801. }
  3802. }
  3803. if (joined === undefined) {
  3804. return '.';
  3805. }
  3806. return this.normalize(joined);
  3807. },
  3808. /**
  3809. * Returns the directory name of a path
  3810. * @param path - The path to parse
  3811. */
  3812. dirname: function (path) {
  3813. assertPath(path);
  3814. if (path.length === 0)
  3815. { return '.'; }
  3816. path = this.toPosix(path);
  3817. var code = path.charCodeAt(0);
  3818. var hasRoot = code === 47;
  3819. var end = -1;
  3820. var matchedSlash = true;
  3821. var proto = this.getProtocol(path);
  3822. var origpath = path;
  3823. path = path.slice(proto.length);
  3824. for (var i = path.length - 1; i >= 1; --i) {
  3825. code = path.charCodeAt(i);
  3826. if (code === 47) {
  3827. if (!matchedSlash) {
  3828. end = i;
  3829. break;
  3830. }
  3831. }
  3832. else {
  3833. // We saw the first non-path separator
  3834. matchedSlash = false;
  3835. }
  3836. }
  3837. // if end is -1 and its a url then we need to add the path back
  3838. // eslint-disable-next-line no-nested-ternary
  3839. if (end === -1)
  3840. { return hasRoot ? '/' : this.isUrl(origpath) ? proto + path : proto; }
  3841. if (hasRoot && end === 1)
  3842. { return '//'; }
  3843. return proto + path.slice(0, end);
  3844. },
  3845. /**
  3846. * Returns the root of the path e.g. /, C:/, file:///, http://domain.com/
  3847. * @param path - The path to parse
  3848. */
  3849. rootname: function (path) {
  3850. assertPath(path);
  3851. path = this.toPosix(path);
  3852. var root = '';
  3853. if (path.startsWith('/'))
  3854. { root = '/'; }
  3855. else {
  3856. root = this.getProtocol(path);
  3857. }
  3858. if (this.isUrl(path)) {
  3859. // need to find the first path separator
  3860. var index = path.indexOf('/', root.length);
  3861. if (index !== -1) {
  3862. root = path.slice(0, index);
  3863. }
  3864. else
  3865. { root = path; }
  3866. if (!root.endsWith('/'))
  3867. { root += '/'; }
  3868. }
  3869. return root;
  3870. },
  3871. /**
  3872. * Returns the last portion of a path
  3873. * @param path - The path to test
  3874. * @param ext - Optional extension to remove
  3875. */
  3876. basename: function (path, ext) {
  3877. assertPath(path);
  3878. if (ext)
  3879. { assertPath(ext); }
  3880. path = this.toPosix(path);
  3881. var start = 0;
  3882. var end = -1;
  3883. var matchedSlash = true;
  3884. var i;
  3885. if (ext !== undefined && ext.length > 0 && ext.length <= path.length) {
  3886. if (ext.length === path.length && ext === path)
  3887. { return ''; }
  3888. var extIdx = ext.length - 1;
  3889. var firstNonSlashEnd = -1;
  3890. for (i = path.length - 1; i >= 0; --i) {
  3891. var code = path.charCodeAt(i);
  3892. if (code === 47) {
  3893. // If we reached a path separator that was not part of a set of path
  3894. // separators at the end of the string, stop now
  3895. if (!matchedSlash) {
  3896. start = i + 1;
  3897. break;
  3898. }
  3899. }
  3900. else {
  3901. if (firstNonSlashEnd === -1) {
  3902. // We saw the first non-path separator, remember this index in case
  3903. // we need it if the extension ends up not matching
  3904. matchedSlash = false;
  3905. firstNonSlashEnd = i + 1;
  3906. }
  3907. if (extIdx >= 0) {
  3908. // Try to match the explicit extension
  3909. if (code === ext.charCodeAt(extIdx)) {
  3910. if (--extIdx === -1) {
  3911. // We matched the extension, so mark this as the end of our path
  3912. // component
  3913. end = i;
  3914. }
  3915. }
  3916. else {
  3917. // Extension does not match, so our result is the entire path
  3918. // component
  3919. extIdx = -1;
  3920. end = firstNonSlashEnd;
  3921. }
  3922. }
  3923. }
  3924. }
  3925. if (start === end)
  3926. { end = firstNonSlashEnd; }
  3927. else if (end === -1)
  3928. { end = path.length; }
  3929. return path.slice(start, end);
  3930. }
  3931. for (i = path.length - 1; i >= 0; --i) {
  3932. if (path.charCodeAt(i) === 47) {
  3933. // If we reached a path separator that was not part of a set of path
  3934. // separators at the end of the string, stop now
  3935. if (!matchedSlash) {
  3936. start = i + 1;
  3937. break;
  3938. }
  3939. }
  3940. else if (end === -1) {
  3941. // We saw the first non-path separator, mark this as the end of our
  3942. // path component
  3943. matchedSlash = false;
  3944. end = i + 1;
  3945. }
  3946. }
  3947. if (end === -1)
  3948. { return ''; }
  3949. return path.slice(start, end);
  3950. },
  3951. /**
  3952. * Returns the extension of the path, from the last occurrence of the . (period) character to end of string in the last
  3953. * portion of the path. If there is no . in the last portion of the path, or if there are no . characters other than
  3954. * the first character of the basename of path, an empty string is returned.
  3955. * @param path - The path to parse
  3956. */
  3957. extname: function (path) {
  3958. assertPath(path);
  3959. path = this.toPosix(path);
  3960. var startDot = -1;
  3961. var startPart = 0;
  3962. var end = -1;
  3963. var matchedSlash = true;
  3964. // Track the state of characters (if any) we see before our first dot and
  3965. // after any path separator we find
  3966. var preDotState = 0;
  3967. for (var i = path.length - 1; i >= 0; --i) {
  3968. var code = path.charCodeAt(i);
  3969. if (code === 47) {
  3970. // If we reached a path separator that was not part of a set of path
  3971. // separators at the end of the string, stop now
  3972. if (!matchedSlash) {
  3973. startPart = i + 1;
  3974. break;
  3975. }
  3976. continue;
  3977. }
  3978. if (end === -1) {
  3979. // We saw the first non-path separator, mark this as the end of our
  3980. // extension
  3981. matchedSlash = false;
  3982. end = i + 1;
  3983. }
  3984. if (code === 46) {
  3985. // If this is our first dot, mark it as the start of our extension
  3986. if (startDot === -1)
  3987. { startDot = i; }
  3988. else if (preDotState !== 1)
  3989. { preDotState = 1; }
  3990. }
  3991. else if (startDot !== -1) {
  3992. // We saw a non-dot and non-path separator before our dot, so we should
  3993. // have a good chance at having a non-empty extension
  3994. preDotState = -1;
  3995. }
  3996. }
  3997. if (startDot === -1 || end === -1
  3998. // We saw a non-dot character immediately before the dot
  3999. || preDotState === 0
  4000. // The (right-most) trimmed path component is exactly '..'
  4001. // eslint-disable-next-line no-mixed-operators
  4002. || preDotState === 1 && startDot === end - 1 && startDot === startPart + 1) {
  4003. return '';
  4004. }
  4005. return path.slice(startDot, end);
  4006. },
  4007. /**
  4008. * Parses a path into an object containing the 'root', `dir`, `base`, `ext`, and `name` properties.
  4009. * @param path - The path to parse
  4010. */
  4011. parse: function (path) {
  4012. assertPath(path);
  4013. var ret = { root: '', dir: '', base: '', ext: '', name: '' };
  4014. if (path.length === 0)
  4015. { return ret; }
  4016. path = this.toPosix(path);
  4017. var code = path.charCodeAt(0);
  4018. var isAbsolute = this.isAbsolute(path);
  4019. var start;
  4020. ret.root = this.rootname(path);
  4021. if (isAbsolute || this.hasProtocol(path)) {
  4022. start = 1;
  4023. }
  4024. else {
  4025. start = 0;
  4026. }
  4027. var startDot = -1;
  4028. var startPart = 0;
  4029. var end = -1;
  4030. var matchedSlash = true;
  4031. var i = path.length - 1;
  4032. // Track the state of characters (if any) we see before our first dot and
  4033. // after any path separator we find
  4034. var preDotState = 0;
  4035. // Get non-dir info
  4036. for (; i >= start; --i) {
  4037. code = path.charCodeAt(i);
  4038. if (code === 47) {
  4039. // If we reached a path separator that was not part of a set of path
  4040. // separators at the end of the string, stop now
  4041. if (!matchedSlash) {
  4042. startPart = i + 1;
  4043. break;
  4044. }
  4045. continue;
  4046. }
  4047. if (end === -1) {
  4048. // We saw the first non-path separator, mark this as the end of our
  4049. // extension
  4050. matchedSlash = false;
  4051. end = i + 1;
  4052. }
  4053. if (code === 46) {
  4054. // If this is our first dot, mark it as the start of our extension
  4055. if (startDot === -1)
  4056. { startDot = i; }
  4057. else if (preDotState !== 1)
  4058. { preDotState = 1; }
  4059. }
  4060. else if (startDot !== -1) {
  4061. // We saw a non-dot and non-path separator before our dot, so we should
  4062. // have a good chance at having a non-empty extension
  4063. preDotState = -1;
  4064. }
  4065. }
  4066. if (startDot === -1 || end === -1
  4067. // We saw a non-dot character immediately before the dot
  4068. || preDotState === 0
  4069. // The (right-most) trimmed path component is exactly '..'
  4070. // eslint-disable-next-line no-mixed-operators
  4071. || preDotState === 1 && startDot === end - 1 && startDot === startPart + 1) {
  4072. if (end !== -1) {
  4073. if (startPart === 0 && isAbsolute)
  4074. { ret.base = ret.name = path.slice(1, end); }
  4075. else
  4076. { ret.base = ret.name = path.slice(startPart, end); }
  4077. }
  4078. }
  4079. else {
  4080. if (startPart === 0 && isAbsolute) {
  4081. ret.name = path.slice(1, startDot);
  4082. ret.base = path.slice(1, end);
  4083. }
  4084. else {
  4085. ret.name = path.slice(startPart, startDot);
  4086. ret.base = path.slice(startPart, end);
  4087. }
  4088. ret.ext = path.slice(startDot, end);
  4089. }
  4090. ret.dir = this.dirname(path);
  4091. return ret;
  4092. },
  4093. sep: '/',
  4094. delimiter: ':'
  4095. };
  4096. /**
  4097. * The prefix that denotes a URL is for a retina asset.
  4098. * @static
  4099. * @name RETINA_PREFIX
  4100. * @memberof PIXI.settings
  4101. * @type {RegExp}
  4102. * @default /@([0-9\.]+)x/
  4103. * @example `@2x`
  4104. */
  4105. settings.RETINA_PREFIX = /@([0-9\.]+)x/;
  4106. /**
  4107. * Should the `failIfMajorPerformanceCaveat` flag be enabled as a context option used in the `isWebGLSupported` function.
  4108. * If set to true, a WebGL renderer can fail to be created if the browser thinks there could be performance issues when
  4109. * using WebGL.
  4110. *
  4111. * In PixiJS v6 this has changed from true to false by default, to allow WebGL to work in as many scenarios as possible.
  4112. * However, some users may have a poor experience, for example, if a user has a gpu or driver version blacklisted by the
  4113. * browser.
  4114. *
  4115. * If your application requires high performance rendering, you may wish to set this to false.
  4116. * We recommend one of two options if you decide to set this flag to false:
  4117. *
  4118. * 1: Use the `pixi.js-legacy` package, which includes a Canvas renderer as a fallback in case high performance WebGL is
  4119. * not supported.
  4120. *
  4121. * 2: Call `isWebGLSupported` (which if found in the PIXI.utils package) in your code before attempting to create a PixiJS
  4122. * renderer, and show an error message to the user if the function returns false, explaining that their device & browser
  4123. * combination does not support high performance WebGL.
  4124. * This is a much better strategy than trying to create a PixiJS renderer and finding it then fails.
  4125. * @static
  4126. * @name FAIL_IF_MAJOR_PERFORMANCE_CAVEAT
  4127. * @memberof PIXI.settings
  4128. * @type {boolean}
  4129. * @default false
  4130. */
  4131. settings.FAIL_IF_MAJOR_PERFORMANCE_CAVEAT = false;
  4132. var saidHello = false;
  4133. var VERSION$1 = '6.5.10';
  4134. /**
  4135. * Skips the hello message of renderers that are created after this is run.
  4136. * @function skipHello
  4137. * @memberof PIXI.utils
  4138. */
  4139. function skipHello() {
  4140. saidHello = true;
  4141. }
  4142. /**
  4143. * Logs out the version and renderer information for this running instance of PIXI.
  4144. * If you don't want to see this message you can run `PIXI.utils.skipHello()` before
  4145. * creating your renderer. Keep in mind that doing that will forever make you a jerk face.
  4146. * @static
  4147. * @function sayHello
  4148. * @memberof PIXI.utils
  4149. * @param {string} type - The string renderer type to log.
  4150. */
  4151. function sayHello(type) {
  4152. var _a;
  4153. if (saidHello) {
  4154. return;
  4155. }
  4156. if (settings.ADAPTER.getNavigator().userAgent.toLowerCase().indexOf('chrome') > -1) {
  4157. var args = [
  4158. "\n %c %c %c PixiJS " + VERSION$1 + " - \u2730 " + type + " \u2730 %c %c http://www.pixijs.com/ %c %c \u2665%c\u2665%c\u2665 \n\n",
  4159. 'background: #ff66a5; padding:5px 0;',
  4160. 'background: #ff66a5; padding:5px 0;',
  4161. 'color: #ff66a5; background: #030307; padding:5px 0;',
  4162. 'background: #ff66a5; padding:5px 0;',
  4163. 'background: #ffc3dc; padding:5px 0;',
  4164. 'background: #ff66a5; padding:5px 0;',
  4165. 'color: #ff2424; background: #fff; padding:5px 0;',
  4166. 'color: #ff2424; background: #fff; padding:5px 0;',
  4167. 'color: #ff2424; background: #fff; padding:5px 0;' ];
  4168. (_a = globalThis.console).log.apply(_a, args);
  4169. }
  4170. else if (globalThis.console) {
  4171. globalThis.console.log("PixiJS " + VERSION$1 + " - " + type + " - http://www.pixijs.com/");
  4172. }
  4173. saidHello = true;
  4174. }
  4175. var supported;
  4176. /**
  4177. * Helper for checking for WebGL support.
  4178. * @memberof PIXI.utils
  4179. * @function isWebGLSupported
  4180. * @returns {boolean} Is WebGL supported.
  4181. */
  4182. function isWebGLSupported() {
  4183. if (typeof supported === 'undefined') {
  4184. supported = (function supported() {
  4185. var contextOptions = {
  4186. stencil: true,
  4187. failIfMajorPerformanceCaveat: settings.FAIL_IF_MAJOR_PERFORMANCE_CAVEAT,
  4188. };
  4189. try {
  4190. if (!settings.ADAPTER.getWebGLRenderingContext()) {
  4191. return false;
  4192. }
  4193. var canvas = settings.ADAPTER.createCanvas();
  4194. var gl = (canvas.getContext('webgl', contextOptions)
  4195. || canvas.getContext('experimental-webgl', contextOptions));
  4196. var success = !!(gl && gl.getContextAttributes().stencil);
  4197. if (gl) {
  4198. var loseContext = gl.getExtension('WEBGL_lose_context');
  4199. if (loseContext) {
  4200. loseContext.loseContext();
  4201. }
  4202. }
  4203. gl = null;
  4204. return success;
  4205. }
  4206. catch (e) {
  4207. return false;
  4208. }
  4209. })();
  4210. }
  4211. return supported;
  4212. }
  4213. var aliceblue = "#f0f8ff";
  4214. var antiquewhite = "#faebd7";
  4215. var aqua = "#00ffff";
  4216. var aquamarine = "#7fffd4";
  4217. var azure = "#f0ffff";
  4218. var beige = "#f5f5dc";
  4219. var bisque = "#ffe4c4";
  4220. var black = "#000000";
  4221. var blanchedalmond = "#ffebcd";
  4222. var blue = "#0000ff";
  4223. var blueviolet = "#8a2be2";
  4224. var brown = "#a52a2a";
  4225. var burlywood = "#deb887";
  4226. var cadetblue = "#5f9ea0";
  4227. var chartreuse = "#7fff00";
  4228. var chocolate = "#d2691e";
  4229. var coral = "#ff7f50";
  4230. var cornflowerblue = "#6495ed";
  4231. var cornsilk = "#fff8dc";
  4232. var crimson = "#dc143c";
  4233. var cyan = "#00ffff";
  4234. var darkblue = "#00008b";
  4235. var darkcyan = "#008b8b";
  4236. var darkgoldenrod = "#b8860b";
  4237. var darkgray = "#a9a9a9";
  4238. var darkgreen = "#006400";
  4239. var darkgrey = "#a9a9a9";
  4240. var darkkhaki = "#bdb76b";
  4241. var darkmagenta = "#8b008b";
  4242. var darkolivegreen = "#556b2f";
  4243. var darkorange = "#ff8c00";
  4244. var darkorchid = "#9932cc";
  4245. var darkred = "#8b0000";
  4246. var darksalmon = "#e9967a";
  4247. var darkseagreen = "#8fbc8f";
  4248. var darkslateblue = "#483d8b";
  4249. var darkslategray = "#2f4f4f";
  4250. var darkslategrey = "#2f4f4f";
  4251. var darkturquoise = "#00ced1";
  4252. var darkviolet = "#9400d3";
  4253. var deeppink = "#ff1493";
  4254. var deepskyblue = "#00bfff";
  4255. var dimgray = "#696969";
  4256. var dimgrey = "#696969";
  4257. var dodgerblue = "#1e90ff";
  4258. var firebrick = "#b22222";
  4259. var floralwhite = "#fffaf0";
  4260. var forestgreen = "#228b22";
  4261. var fuchsia = "#ff00ff";
  4262. var gainsboro = "#dcdcdc";
  4263. var ghostwhite = "#f8f8ff";
  4264. var goldenrod = "#daa520";
  4265. var gold = "#ffd700";
  4266. var gray = "#808080";
  4267. var green = "#008000";
  4268. var greenyellow = "#adff2f";
  4269. var grey = "#808080";
  4270. var honeydew = "#f0fff0";
  4271. var hotpink = "#ff69b4";
  4272. var indianred = "#cd5c5c";
  4273. var indigo = "#4b0082";
  4274. var ivory = "#fffff0";
  4275. var khaki = "#f0e68c";
  4276. var lavenderblush = "#fff0f5";
  4277. var lavender = "#e6e6fa";
  4278. var lawngreen = "#7cfc00";
  4279. var lemonchiffon = "#fffacd";
  4280. var lightblue = "#add8e6";
  4281. var lightcoral = "#f08080";
  4282. var lightcyan = "#e0ffff";
  4283. var lightgoldenrodyellow = "#fafad2";
  4284. var lightgray = "#d3d3d3";
  4285. var lightgreen = "#90ee90";
  4286. var lightgrey = "#d3d3d3";
  4287. var lightpink = "#ffb6c1";
  4288. var lightsalmon = "#ffa07a";
  4289. var lightseagreen = "#20b2aa";
  4290. var lightskyblue = "#87cefa";
  4291. var lightslategray = "#778899";
  4292. var lightslategrey = "#778899";
  4293. var lightsteelblue = "#b0c4de";
  4294. var lightyellow = "#ffffe0";
  4295. var lime = "#00ff00";
  4296. var limegreen = "#32cd32";
  4297. var linen = "#faf0e6";
  4298. var magenta = "#ff00ff";
  4299. var maroon = "#800000";
  4300. var mediumaquamarine = "#66cdaa";
  4301. var mediumblue = "#0000cd";
  4302. var mediumorchid = "#ba55d3";
  4303. var mediumpurple = "#9370db";
  4304. var mediumseagreen = "#3cb371";
  4305. var mediumslateblue = "#7b68ee";
  4306. var mediumspringgreen = "#00fa9a";
  4307. var mediumturquoise = "#48d1cc";
  4308. var mediumvioletred = "#c71585";
  4309. var midnightblue = "#191970";
  4310. var mintcream = "#f5fffa";
  4311. var mistyrose = "#ffe4e1";
  4312. var moccasin = "#ffe4b5";
  4313. var navajowhite = "#ffdead";
  4314. var navy = "#000080";
  4315. var oldlace = "#fdf5e6";
  4316. var olive = "#808000";
  4317. var olivedrab = "#6b8e23";
  4318. var orange = "#ffa500";
  4319. var orangered = "#ff4500";
  4320. var orchid = "#da70d6";
  4321. var palegoldenrod = "#eee8aa";
  4322. var palegreen = "#98fb98";
  4323. var paleturquoise = "#afeeee";
  4324. var palevioletred = "#db7093";
  4325. var papayawhip = "#ffefd5";
  4326. var peachpuff = "#ffdab9";
  4327. var peru = "#cd853f";
  4328. var pink = "#ffc0cb";
  4329. var plum = "#dda0dd";
  4330. var powderblue = "#b0e0e6";
  4331. var purple = "#800080";
  4332. var rebeccapurple = "#663399";
  4333. var red = "#ff0000";
  4334. var rosybrown = "#bc8f8f";
  4335. var royalblue = "#4169e1";
  4336. var saddlebrown = "#8b4513";
  4337. var salmon = "#fa8072";
  4338. var sandybrown = "#f4a460";
  4339. var seagreen = "#2e8b57";
  4340. var seashell = "#fff5ee";
  4341. var sienna = "#a0522d";
  4342. var silver = "#c0c0c0";
  4343. var skyblue = "#87ceeb";
  4344. var slateblue = "#6a5acd";
  4345. var slategray = "#708090";
  4346. var slategrey = "#708090";
  4347. var snow = "#fffafa";
  4348. var springgreen = "#00ff7f";
  4349. var steelblue = "#4682b4";
  4350. var tan = "#d2b48c";
  4351. var teal = "#008080";
  4352. var thistle = "#d8bfd8";
  4353. var tomato = "#ff6347";
  4354. var turquoise = "#40e0d0";
  4355. var violet = "#ee82ee";
  4356. var wheat = "#f5deb3";
  4357. var white = "#ffffff";
  4358. var whitesmoke = "#f5f5f5";
  4359. var yellow = "#ffff00";
  4360. var yellowgreen = "#9acd32";
  4361. var cssColorNames = {
  4362. aliceblue: aliceblue,
  4363. antiquewhite: antiquewhite,
  4364. aqua: aqua,
  4365. aquamarine: aquamarine,
  4366. azure: azure,
  4367. beige: beige,
  4368. bisque: bisque,
  4369. black: black,
  4370. blanchedalmond: blanchedalmond,
  4371. blue: blue,
  4372. blueviolet: blueviolet,
  4373. brown: brown,
  4374. burlywood: burlywood,
  4375. cadetblue: cadetblue,
  4376. chartreuse: chartreuse,
  4377. chocolate: chocolate,
  4378. coral: coral,
  4379. cornflowerblue: cornflowerblue,
  4380. cornsilk: cornsilk,
  4381. crimson: crimson,
  4382. cyan: cyan,
  4383. darkblue: darkblue,
  4384. darkcyan: darkcyan,
  4385. darkgoldenrod: darkgoldenrod,
  4386. darkgray: darkgray,
  4387. darkgreen: darkgreen,
  4388. darkgrey: darkgrey,
  4389. darkkhaki: darkkhaki,
  4390. darkmagenta: darkmagenta,
  4391. darkolivegreen: darkolivegreen,
  4392. darkorange: darkorange,
  4393. darkorchid: darkorchid,
  4394. darkred: darkred,
  4395. darksalmon: darksalmon,
  4396. darkseagreen: darkseagreen,
  4397. darkslateblue: darkslateblue,
  4398. darkslategray: darkslategray,
  4399. darkslategrey: darkslategrey,
  4400. darkturquoise: darkturquoise,
  4401. darkviolet: darkviolet,
  4402. deeppink: deeppink,
  4403. deepskyblue: deepskyblue,
  4404. dimgray: dimgray,
  4405. dimgrey: dimgrey,
  4406. dodgerblue: dodgerblue,
  4407. firebrick: firebrick,
  4408. floralwhite: floralwhite,
  4409. forestgreen: forestgreen,
  4410. fuchsia: fuchsia,
  4411. gainsboro: gainsboro,
  4412. ghostwhite: ghostwhite,
  4413. goldenrod: goldenrod,
  4414. gold: gold,
  4415. gray: gray,
  4416. green: green,
  4417. greenyellow: greenyellow,
  4418. grey: grey,
  4419. honeydew: honeydew,
  4420. hotpink: hotpink,
  4421. indianred: indianred,
  4422. indigo: indigo,
  4423. ivory: ivory,
  4424. khaki: khaki,
  4425. lavenderblush: lavenderblush,
  4426. lavender: lavender,
  4427. lawngreen: lawngreen,
  4428. lemonchiffon: lemonchiffon,
  4429. lightblue: lightblue,
  4430. lightcoral: lightcoral,
  4431. lightcyan: lightcyan,
  4432. lightgoldenrodyellow: lightgoldenrodyellow,
  4433. lightgray: lightgray,
  4434. lightgreen: lightgreen,
  4435. lightgrey: lightgrey,
  4436. lightpink: lightpink,
  4437. lightsalmon: lightsalmon,
  4438. lightseagreen: lightseagreen,
  4439. lightskyblue: lightskyblue,
  4440. lightslategray: lightslategray,
  4441. lightslategrey: lightslategrey,
  4442. lightsteelblue: lightsteelblue,
  4443. lightyellow: lightyellow,
  4444. lime: lime,
  4445. limegreen: limegreen,
  4446. linen: linen,
  4447. magenta: magenta,
  4448. maroon: maroon,
  4449. mediumaquamarine: mediumaquamarine,
  4450. mediumblue: mediumblue,
  4451. mediumorchid: mediumorchid,
  4452. mediumpurple: mediumpurple,
  4453. mediumseagreen: mediumseagreen,
  4454. mediumslateblue: mediumslateblue,
  4455. mediumspringgreen: mediumspringgreen,
  4456. mediumturquoise: mediumturquoise,
  4457. mediumvioletred: mediumvioletred,
  4458. midnightblue: midnightblue,
  4459. mintcream: mintcream,
  4460. mistyrose: mistyrose,
  4461. moccasin: moccasin,
  4462. navajowhite: navajowhite,
  4463. navy: navy,
  4464. oldlace: oldlace,
  4465. olive: olive,
  4466. olivedrab: olivedrab,
  4467. orange: orange,
  4468. orangered: orangered,
  4469. orchid: orchid,
  4470. palegoldenrod: palegoldenrod,
  4471. palegreen: palegreen,
  4472. paleturquoise: paleturquoise,
  4473. palevioletred: palevioletred,
  4474. papayawhip: papayawhip,
  4475. peachpuff: peachpuff,
  4476. peru: peru,
  4477. pink: pink,
  4478. plum: plum,
  4479. powderblue: powderblue,
  4480. purple: purple,
  4481. rebeccapurple: rebeccapurple,
  4482. red: red,
  4483. rosybrown: rosybrown,
  4484. royalblue: royalblue,
  4485. saddlebrown: saddlebrown,
  4486. salmon: salmon,
  4487. sandybrown: sandybrown,
  4488. seagreen: seagreen,
  4489. seashell: seashell,
  4490. sienna: sienna,
  4491. silver: silver,
  4492. skyblue: skyblue,
  4493. slateblue: slateblue,
  4494. slategray: slategray,
  4495. slategrey: slategrey,
  4496. snow: snow,
  4497. springgreen: springgreen,
  4498. steelblue: steelblue,
  4499. tan: tan,
  4500. teal: teal,
  4501. thistle: thistle,
  4502. tomato: tomato,
  4503. turquoise: turquoise,
  4504. violet: violet,
  4505. wheat: wheat,
  4506. white: white,
  4507. whitesmoke: whitesmoke,
  4508. yellow: yellow,
  4509. yellowgreen: yellowgreen
  4510. };
  4511. /**
  4512. * Converts a hexadecimal color number to an [R, G, B] array of normalized floats (numbers from 0.0 to 1.0).
  4513. * @example
  4514. * PIXI.utils.hex2rgb(0xffffff); // returns [1, 1, 1]
  4515. * @memberof PIXI.utils
  4516. * @function hex2rgb
  4517. * @param {number} hex - The hexadecimal number to convert
  4518. * @param {number[]} [out=[]] - If supplied, this array will be used rather than returning a new one
  4519. * @returns {number[]} An array representing the [R, G, B] of the color where all values are floats.
  4520. */
  4521. function hex2rgb(hex, out) {
  4522. if (out === void 0) { out = []; }
  4523. out[0] = ((hex >> 16) & 0xFF) / 255;
  4524. out[1] = ((hex >> 8) & 0xFF) / 255;
  4525. out[2] = (hex & 0xFF) / 255;
  4526. return out;
  4527. }
  4528. /**
  4529. * Converts a hexadecimal color number to a string.
  4530. * @example
  4531. * PIXI.utils.hex2string(0xffffff); // returns "#ffffff"
  4532. * @memberof PIXI.utils
  4533. * @function hex2string
  4534. * @param {number} hex - Number in hex (e.g., `0xffffff`)
  4535. * @returns {string} The string color (e.g., `"#ffffff"`).
  4536. */
  4537. function hex2string(hex) {
  4538. var hexString = hex.toString(16);
  4539. hexString = '000000'.substring(0, 6 - hexString.length) + hexString;
  4540. return "#" + hexString;
  4541. }
  4542. /**
  4543. * Converts a string to a hexadecimal color number.
  4544. * It can handle:
  4545. * hex strings starting with #: "#ffffff"
  4546. * hex strings starting with 0x: "0xffffff"
  4547. * hex strings without prefix: "ffffff"
  4548. * css colors: "black"
  4549. * @example
  4550. * PIXI.utils.string2hex("#ffffff"); // returns 0xffffff, which is 16777215 as an integer
  4551. * @memberof PIXI.utils
  4552. * @function string2hex
  4553. * @param {string} string - The string color (e.g., `"#ffffff"`)
  4554. * @returns {number} Number in hexadecimal.
  4555. */
  4556. function string2hex(string) {
  4557. if (typeof string === 'string') {
  4558. string = cssColorNames[string.toLowerCase()] || string;
  4559. if (string[0] === '#') {
  4560. string = string.slice(1);
  4561. }
  4562. }
  4563. return parseInt(string, 16);
  4564. }
  4565. /**
  4566. * Converts a color as an [R, G, B] array of normalized floats to a hexadecimal number.
  4567. * @example
  4568. * PIXI.utils.rgb2hex([1, 1, 1]); // returns 0xffffff, which is 16777215 as an integer
  4569. * @memberof PIXI.utils
  4570. * @function rgb2hex
  4571. * @param {number[]} rgb - Array of numbers where all values are normalized floats from 0.0 to 1.0.
  4572. * @returns {number} Number in hexadecimal.
  4573. */
  4574. function rgb2hex(rgb) {
  4575. return (((rgb[0] * 255) << 16) + ((rgb[1] * 255) << 8) + (rgb[2] * 255 | 0));
  4576. }
  4577. /**
  4578. * Corrects PixiJS blend, takes premultiplied alpha into account
  4579. * @memberof PIXI.utils
  4580. * @function mapPremultipliedBlendModes
  4581. * @private
  4582. * @returns {Array<number[]>} Mapped modes.
  4583. */
  4584. function mapPremultipliedBlendModes() {
  4585. var pm = [];
  4586. var npm = [];
  4587. for (var i = 0; i < 32; i++) {
  4588. pm[i] = i;
  4589. npm[i] = i;
  4590. }
  4591. pm[BLEND_MODES.NORMAL_NPM] = BLEND_MODES.NORMAL;
  4592. pm[BLEND_MODES.ADD_NPM] = BLEND_MODES.ADD;
  4593. pm[BLEND_MODES.SCREEN_NPM] = BLEND_MODES.SCREEN;
  4594. npm[BLEND_MODES.NORMAL] = BLEND_MODES.NORMAL_NPM;
  4595. npm[BLEND_MODES.ADD] = BLEND_MODES.ADD_NPM;
  4596. npm[BLEND_MODES.SCREEN] = BLEND_MODES.SCREEN_NPM;
  4597. var array = [];
  4598. array.push(npm);
  4599. array.push(pm);
  4600. return array;
  4601. }
  4602. /**
  4603. * maps premultiply flag and blendMode to adjusted blendMode
  4604. * @memberof PIXI.utils
  4605. * @constant premultiplyBlendMode
  4606. * @type {Array<number[]>}
  4607. */
  4608. var premultiplyBlendMode = mapPremultipliedBlendModes();
  4609. /**
  4610. * changes blendMode according to texture format
  4611. * @memberof PIXI.utils
  4612. * @function correctBlendMode
  4613. * @param {number} blendMode - supposed blend mode
  4614. * @param {boolean} premultiplied - whether source is premultiplied
  4615. * @returns {number} true blend mode for this texture
  4616. */
  4617. function correctBlendMode(blendMode, premultiplied) {
  4618. return premultiplyBlendMode[premultiplied ? 1 : 0][blendMode];
  4619. }
  4620. /**
  4621. * combines rgb and alpha to out array
  4622. * @memberof PIXI.utils
  4623. * @function premultiplyRgba
  4624. * @param {Float32Array|number[]} rgb - input rgb
  4625. * @param {number} alpha - alpha param
  4626. * @param {Float32Array} [out] - output
  4627. * @param {boolean} [premultiply=true] - do premultiply it
  4628. * @returns {Float32Array} vec4 rgba
  4629. */
  4630. function premultiplyRgba(rgb, alpha, out, premultiply) {
  4631. out = out || new Float32Array(4);
  4632. if (premultiply || premultiply === undefined) {
  4633. out[0] = rgb[0] * alpha;
  4634. out[1] = rgb[1] * alpha;
  4635. out[2] = rgb[2] * alpha;
  4636. }
  4637. else {
  4638. out[0] = rgb[0];
  4639. out[1] = rgb[1];
  4640. out[2] = rgb[2];
  4641. }
  4642. out[3] = alpha;
  4643. return out;
  4644. }
  4645. /**
  4646. * premultiplies tint
  4647. * @memberof PIXI.utils
  4648. * @function premultiplyTint
  4649. * @param {number} tint - integer RGB
  4650. * @param {number} alpha - floating point alpha (0.0-1.0)
  4651. * @returns {number} tint multiplied by alpha
  4652. */
  4653. function premultiplyTint(tint, alpha) {
  4654. if (alpha === 1.0) {
  4655. return (alpha * 255 << 24) + tint;
  4656. }
  4657. if (alpha === 0.0) {
  4658. return 0;
  4659. }
  4660. var R = ((tint >> 16) & 0xFF);
  4661. var G = ((tint >> 8) & 0xFF);
  4662. var B = (tint & 0xFF);
  4663. R = ((R * alpha) + 0.5) | 0;
  4664. G = ((G * alpha) + 0.5) | 0;
  4665. B = ((B * alpha) + 0.5) | 0;
  4666. return (alpha * 255 << 24) + (R << 16) + (G << 8) + B;
  4667. }
  4668. /**
  4669. * converts integer tint and float alpha to vec4 form, premultiplies by default
  4670. * @memberof PIXI.utils
  4671. * @function premultiplyTintToRgba
  4672. * @param {number} tint - input tint
  4673. * @param {number} alpha - alpha param
  4674. * @param {Float32Array} [out] - output
  4675. * @param {boolean} [premultiply=true] - do premultiply it
  4676. * @returns {Float32Array} vec4 rgba
  4677. */
  4678. function premultiplyTintToRgba(tint, alpha, out, premultiply) {
  4679. out = out || new Float32Array(4);
  4680. out[0] = ((tint >> 16) & 0xFF) / 255.0;
  4681. out[1] = ((tint >> 8) & 0xFF) / 255.0;
  4682. out[2] = (tint & 0xFF) / 255.0;
  4683. if (premultiply || premultiply === undefined) {
  4684. out[0] *= alpha;
  4685. out[1] *= alpha;
  4686. out[2] *= alpha;
  4687. }
  4688. out[3] = alpha;
  4689. return out;
  4690. }
  4691. /**
  4692. * Generic Mask Stack data structure
  4693. * @memberof PIXI.utils
  4694. * @function createIndicesForQuads
  4695. * @param {number} size - Number of quads
  4696. * @param {Uint16Array|Uint32Array} [outBuffer] - Buffer for output, length has to be `6 * size`
  4697. * @returns {Uint16Array|Uint32Array} - Resulting index buffer
  4698. */
  4699. function createIndicesForQuads(size, outBuffer) {
  4700. if (outBuffer === void 0) { outBuffer = null; }
  4701. // the total number of indices in our array, there are 6 points per quad.
  4702. var totalIndices = size * 6;
  4703. outBuffer = outBuffer || new Uint16Array(totalIndices);
  4704. if (outBuffer.length !== totalIndices) {
  4705. throw new Error("Out buffer length is incorrect, got " + outBuffer.length + " and expected " + totalIndices);
  4706. }
  4707. // fill the indices with the quads to draw
  4708. for (var i = 0, j = 0; i < totalIndices; i += 6, j += 4) {
  4709. outBuffer[i + 0] = j + 0;
  4710. outBuffer[i + 1] = j + 1;
  4711. outBuffer[i + 2] = j + 2;
  4712. outBuffer[i + 3] = j + 0;
  4713. outBuffer[i + 4] = j + 2;
  4714. outBuffer[i + 5] = j + 3;
  4715. }
  4716. return outBuffer;
  4717. }
  4718. function getBufferType(array) {
  4719. if (array.BYTES_PER_ELEMENT === 4) {
  4720. if (array instanceof Float32Array) {
  4721. return 'Float32Array';
  4722. }
  4723. else if (array instanceof Uint32Array) {
  4724. return 'Uint32Array';
  4725. }
  4726. return 'Int32Array';
  4727. }
  4728. else if (array.BYTES_PER_ELEMENT === 2) {
  4729. if (array instanceof Uint16Array) {
  4730. return 'Uint16Array';
  4731. }
  4732. }
  4733. else if (array.BYTES_PER_ELEMENT === 1) {
  4734. if (array instanceof Uint8Array) {
  4735. return 'Uint8Array';
  4736. }
  4737. }
  4738. // TODO map out the rest of the array elements!
  4739. return null;
  4740. }
  4741. /* eslint-disable object-shorthand */
  4742. var map$2 = { Float32Array: Float32Array, Uint32Array: Uint32Array, Int32Array: Int32Array, Uint8Array: Uint8Array };
  4743. function interleaveTypedArrays$1(arrays, sizes) {
  4744. var outSize = 0;
  4745. var stride = 0;
  4746. var views = {};
  4747. for (var i = 0; i < arrays.length; i++) {
  4748. stride += sizes[i];
  4749. outSize += arrays[i].length;
  4750. }
  4751. var buffer = new ArrayBuffer(outSize * 4);
  4752. var out = null;
  4753. var littleOffset = 0;
  4754. for (var i = 0; i < arrays.length; i++) {
  4755. var size = sizes[i];
  4756. var array = arrays[i];
  4757. /*
  4758. @todo This is unsafe casting but consistent with how the code worked previously. Should it stay this way
  4759. or should and `getBufferTypeUnsafe` function be exposed that throws an Error if unsupported type is passed?
  4760. */
  4761. var type = getBufferType(array);
  4762. if (!views[type]) {
  4763. views[type] = new map$2[type](buffer);
  4764. }
  4765. out = views[type];
  4766. for (var j = 0; j < array.length; j++) {
  4767. var indexStart = ((j / size | 0) * stride) + littleOffset;
  4768. var index = j % size;
  4769. out[indexStart + index] = array[j];
  4770. }
  4771. littleOffset += size;
  4772. }
  4773. return new Float32Array(buffer);
  4774. }
  4775. // Taken from the bit-twiddle package
  4776. /**
  4777. * Rounds to next power of two.
  4778. * @function nextPow2
  4779. * @memberof PIXI.utils
  4780. * @param {number} v - input value
  4781. * @returns {number} - next rounded power of two
  4782. */
  4783. function nextPow2(v) {
  4784. v += v === 0 ? 1 : 0;
  4785. --v;
  4786. v |= v >>> 1;
  4787. v |= v >>> 2;
  4788. v |= v >>> 4;
  4789. v |= v >>> 8;
  4790. v |= v >>> 16;
  4791. return v + 1;
  4792. }
  4793. /**
  4794. * Checks if a number is a power of two.
  4795. * @function isPow2
  4796. * @memberof PIXI.utils
  4797. * @param {number} v - input value
  4798. * @returns {boolean} `true` if value is power of two
  4799. */
  4800. function isPow2(v) {
  4801. return !(v & (v - 1)) && (!!v);
  4802. }
  4803. /**
  4804. * Computes ceil of log base 2
  4805. * @function log2
  4806. * @memberof PIXI.utils
  4807. * @param {number} v - input value
  4808. * @returns {number} logarithm base 2
  4809. */
  4810. function log2(v) {
  4811. var r = (v > 0xFFFF ? 1 : 0) << 4;
  4812. v >>>= r;
  4813. var shift = (v > 0xFF ? 1 : 0) << 3;
  4814. v >>>= shift;
  4815. r |= shift;
  4816. shift = (v > 0xF ? 1 : 0) << 2;
  4817. v >>>= shift;
  4818. r |= shift;
  4819. shift = (v > 0x3 ? 1 : 0) << 1;
  4820. v >>>= shift;
  4821. r |= shift;
  4822. return r | (v >> 1);
  4823. }
  4824. /**
  4825. * Remove items from a javascript array without generating garbage
  4826. * @function removeItems
  4827. * @memberof PIXI.utils
  4828. * @param {Array<any>} arr - Array to remove elements from
  4829. * @param {number} startIdx - starting index
  4830. * @param {number} removeCount - how many to remove
  4831. */
  4832. function removeItems(arr, startIdx, removeCount) {
  4833. var length = arr.length;
  4834. var i;
  4835. if (startIdx >= length || removeCount === 0) {
  4836. return;
  4837. }
  4838. removeCount = (startIdx + removeCount > length ? length - startIdx : removeCount);
  4839. var len = length - removeCount;
  4840. for (i = startIdx; i < len; ++i) {
  4841. arr[i] = arr[i + removeCount];
  4842. }
  4843. arr.length = len;
  4844. }
  4845. /**
  4846. * Returns sign of number
  4847. * @memberof PIXI.utils
  4848. * @function sign
  4849. * @param {number} n - the number to check the sign of
  4850. * @returns {number} 0 if `n` is 0, -1 if `n` is negative, 1 if `n` is positive
  4851. */
  4852. function sign(n) {
  4853. if (n === 0)
  4854. { return 0; }
  4855. return n < 0 ? -1 : 1;
  4856. }
  4857. var nextUid = 0;
  4858. /**
  4859. * Gets the next unique identifier
  4860. * @memberof PIXI.utils
  4861. * @function uid
  4862. * @returns {number} The next unique identifier to use.
  4863. */
  4864. function uid() {
  4865. return ++nextUid;
  4866. }
  4867. // A map of warning messages already fired
  4868. var warnings = {};
  4869. /**
  4870. * Helper for warning developers about deprecated features & settings.
  4871. * A stack track for warnings is given; useful for tracking-down where
  4872. * deprecated methods/properties/classes are being used within the code.
  4873. * @memberof PIXI.utils
  4874. * @function deprecation
  4875. * @param {string} version - The version where the feature became deprecated
  4876. * @param {string} message - Message should include what is deprecated, where, and the new solution
  4877. * @param {number} [ignoreDepth=3] - The number of steps to ignore at the top of the error stack
  4878. * this is mostly to ignore internal deprecation calls.
  4879. */
  4880. function deprecation(version, message, ignoreDepth) {
  4881. if (ignoreDepth === void 0) { ignoreDepth = 3; }
  4882. // Ignore duplicat
  4883. if (warnings[message]) {
  4884. return;
  4885. }
  4886. /* eslint-disable no-console */
  4887. var stack = new Error().stack;
  4888. // Handle IE < 10 and Safari < 6
  4889. if (typeof stack === 'undefined') {
  4890. console.warn('PixiJS Deprecation Warning: ', message + "\nDeprecated since v" + version);
  4891. }
  4892. else {
  4893. // chop off the stack trace which includes PixiJS internal calls
  4894. stack = stack.split('\n').splice(ignoreDepth).join('\n');
  4895. if (console.groupCollapsed) {
  4896. console.groupCollapsed('%cPixiJS Deprecation Warning: %c%s', 'color:#614108;background:#fffbe6', 'font-weight:normal;color:#614108;background:#fffbe6', message + "\nDeprecated since v" + version);
  4897. console.warn(stack);
  4898. console.groupEnd();
  4899. }
  4900. else {
  4901. console.warn('PixiJS Deprecation Warning: ', message + "\nDeprecated since v" + version);
  4902. console.warn(stack);
  4903. }
  4904. }
  4905. /* eslint-enable no-console */
  4906. warnings[message] = true;
  4907. }
  4908. /**
  4909. * @todo Describe property usage
  4910. * @static
  4911. * @name ProgramCache
  4912. * @memberof PIXI.utils
  4913. * @type {object}
  4914. */
  4915. var ProgramCache = {};
  4916. /**
  4917. * @todo Describe property usage
  4918. * @static
  4919. * @name TextureCache
  4920. * @memberof PIXI.utils
  4921. * @type {object}
  4922. */
  4923. var TextureCache = Object.create(null);
  4924. /**
  4925. * @todo Describe property usage
  4926. * @static
  4927. * @name BaseTextureCache
  4928. * @memberof PIXI.utils
  4929. * @type {object}
  4930. */
  4931. var BaseTextureCache = Object.create(null);
  4932. /**
  4933. * Destroys all texture in the cache
  4934. * @memberof PIXI.utils
  4935. * @function destroyTextureCache
  4936. */
  4937. function destroyTextureCache() {
  4938. var key;
  4939. for (key in TextureCache) {
  4940. TextureCache[key].destroy();
  4941. }
  4942. for (key in BaseTextureCache) {
  4943. BaseTextureCache[key].destroy();
  4944. }
  4945. }
  4946. /**
  4947. * Removes all textures from cache, but does not destroy them
  4948. * @memberof PIXI.utils
  4949. * @function clearTextureCache
  4950. */
  4951. function clearTextureCache() {
  4952. var key;
  4953. for (key in TextureCache) {
  4954. delete TextureCache[key];
  4955. }
  4956. for (key in BaseTextureCache) {
  4957. delete BaseTextureCache[key];
  4958. }
  4959. }
  4960. /**
  4961. * Creates a Canvas element of the given size to be used as a target for rendering to.
  4962. * @class
  4963. * @memberof PIXI.utils
  4964. */
  4965. var CanvasRenderTarget = /** @class */ (function () {
  4966. /**
  4967. * @param width - the width for the newly created canvas
  4968. * @param height - the height for the newly created canvas
  4969. * @param {number} [resolution=PIXI.settings.RESOLUTION] - The resolution / device pixel ratio of the canvas
  4970. */
  4971. function CanvasRenderTarget(width, height, resolution) {
  4972. this.canvas = settings.ADAPTER.createCanvas();
  4973. this.context = this.canvas.getContext('2d');
  4974. this.resolution = resolution || settings.RESOLUTION;
  4975. this.resize(width, height);
  4976. }
  4977. /**
  4978. * Clears the canvas that was created by the CanvasRenderTarget class.
  4979. * @private
  4980. */
  4981. CanvasRenderTarget.prototype.clear = function () {
  4982. this.context.setTransform(1, 0, 0, 1, 0, 0);
  4983. this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
  4984. };
  4985. /**
  4986. * Resizes the canvas to the specified width and height.
  4987. * @param desiredWidth - the desired width of the canvas
  4988. * @param desiredHeight - the desired height of the canvas
  4989. */
  4990. CanvasRenderTarget.prototype.resize = function (desiredWidth, desiredHeight) {
  4991. this.canvas.width = Math.round(desiredWidth * this.resolution);
  4992. this.canvas.height = Math.round(desiredHeight * this.resolution);
  4993. };
  4994. /** Destroys this canvas. */
  4995. CanvasRenderTarget.prototype.destroy = function () {
  4996. this.context = null;
  4997. this.canvas = null;
  4998. };
  4999. Object.defineProperty(CanvasRenderTarget.prototype, "width", {
  5000. /**
  5001. * The width of the canvas buffer in pixels.
  5002. * @member {number}
  5003. */
  5004. get: function () {
  5005. return this.canvas.width;
  5006. },
  5007. set: function (val) {
  5008. this.canvas.width = Math.round(val);
  5009. },
  5010. enumerable: false,
  5011. configurable: true
  5012. });
  5013. Object.defineProperty(CanvasRenderTarget.prototype, "height", {
  5014. /**
  5015. * The height of the canvas buffer in pixels.
  5016. * @member {number}
  5017. */
  5018. get: function () {
  5019. return this.canvas.height;
  5020. },
  5021. set: function (val) {
  5022. this.canvas.height = Math.round(val);
  5023. },
  5024. enumerable: false,
  5025. configurable: true
  5026. });
  5027. return CanvasRenderTarget;
  5028. }());
  5029. /**
  5030. * Trim transparent borders from a canvas
  5031. * @memberof PIXI.utils
  5032. * @function trimCanvas
  5033. * @param {HTMLCanvasElement} canvas - the canvas to trim
  5034. * @returns {object} Trim data
  5035. */
  5036. function trimCanvas(canvas) {
  5037. // https://gist.github.com/remy/784508
  5038. var width = canvas.width;
  5039. var height = canvas.height;
  5040. var context = canvas.getContext('2d', {
  5041. willReadFrequently: true,
  5042. });
  5043. var imageData = context.getImageData(0, 0, width, height);
  5044. var pixels = imageData.data;
  5045. var len = pixels.length;
  5046. var bound = {
  5047. top: null,
  5048. left: null,
  5049. right: null,
  5050. bottom: null,
  5051. };
  5052. var data = null;
  5053. var i;
  5054. var x;
  5055. var y;
  5056. for (i = 0; i < len; i += 4) {
  5057. if (pixels[i + 3] !== 0) {
  5058. x = (i / 4) % width;
  5059. y = ~~((i / 4) / width);
  5060. if (bound.top === null) {
  5061. bound.top = y;
  5062. }
  5063. if (bound.left === null) {
  5064. bound.left = x;
  5065. }
  5066. else if (x < bound.left) {
  5067. bound.left = x;
  5068. }
  5069. if (bound.right === null) {
  5070. bound.right = x + 1;
  5071. }
  5072. else if (bound.right < x) {
  5073. bound.right = x + 1;
  5074. }
  5075. if (bound.bottom === null) {
  5076. bound.bottom = y;
  5077. }
  5078. else if (bound.bottom < y) {
  5079. bound.bottom = y;
  5080. }
  5081. }
  5082. }
  5083. if (bound.top !== null) {
  5084. width = bound.right - bound.left;
  5085. height = bound.bottom - bound.top + 1;
  5086. data = context.getImageData(bound.left, bound.top, width, height);
  5087. }
  5088. return {
  5089. height: height,
  5090. width: width,
  5091. data: data,
  5092. };
  5093. }
  5094. /**
  5095. * Regexp for data URI.
  5096. * Based on: {@link https://github.com/ragingwind/data-uri-regex}
  5097. * @static
  5098. * @constant {RegExp|string} DATA_URI
  5099. * @memberof PIXI
  5100. * @example data:image/png;base64
  5101. */
  5102. var DATA_URI = /^\s*data:(?:([\w-]+)\/([\w+.-]+))?(?:;charset=([\w-]+))?(?:;(base64))?,(.*)/i;
  5103. /**
  5104. * @memberof PIXI.utils
  5105. * @interface DecomposedDataUri
  5106. */
  5107. /**
  5108. * type, eg. `image`
  5109. * @memberof PIXI.utils.DecomposedDataUri#
  5110. * @member {string} mediaType
  5111. */
  5112. /**
  5113. * Sub type, eg. `png`
  5114. * @memberof PIXI.utils.DecomposedDataUri#
  5115. * @member {string} subType
  5116. */
  5117. /**
  5118. * @memberof PIXI.utils.DecomposedDataUri#
  5119. * @member {string} charset
  5120. */
  5121. /**
  5122. * Data encoding, eg. `base64`
  5123. * @memberof PIXI.utils.DecomposedDataUri#
  5124. * @member {string} encoding
  5125. */
  5126. /**
  5127. * The actual data
  5128. * @memberof PIXI.utils.DecomposedDataUri#
  5129. * @member {string} data
  5130. */
  5131. /**
  5132. * Split a data URI into components. Returns undefined if
  5133. * parameter `dataUri` is not a valid data URI.
  5134. * @memberof PIXI.utils
  5135. * @function decomposeDataUri
  5136. * @param {string} dataUri - the data URI to check
  5137. * @returns {PIXI.utils.DecomposedDataUri|undefined} The decomposed data uri or undefined
  5138. */
  5139. function decomposeDataUri(dataUri) {
  5140. var dataUriMatch = DATA_URI.exec(dataUri);
  5141. if (dataUriMatch) {
  5142. return {
  5143. mediaType: dataUriMatch[1] ? dataUriMatch[1].toLowerCase() : undefined,
  5144. subType: dataUriMatch[2] ? dataUriMatch[2].toLowerCase() : undefined,
  5145. charset: dataUriMatch[3] ? dataUriMatch[3].toLowerCase() : undefined,
  5146. encoding: dataUriMatch[4] ? dataUriMatch[4].toLowerCase() : undefined,
  5147. data: dataUriMatch[5],
  5148. };
  5149. }
  5150. return undefined;
  5151. }
  5152. var tempAnchor$1;
  5153. /**
  5154. * Sets the `crossOrigin` property for this resource based on if the url
  5155. * for this resource is cross-origin. If crossOrigin was manually set, this
  5156. * function does nothing.
  5157. * Nipped from the resource loader!
  5158. * @ignore
  5159. * @param {string} url - The url to test.
  5160. * @param {object} [loc=window.location] - The location object to test against.
  5161. * @returns {string} The crossOrigin value to use (or empty string for none).
  5162. */
  5163. function determineCrossOrigin(url$1, loc) {
  5164. if (loc === void 0) { loc = globalThis.location; }
  5165. // data: and javascript: urls are considered same-origin
  5166. if (url$1.indexOf('data:') === 0) {
  5167. return '';
  5168. }
  5169. // default is window.location
  5170. loc = loc || globalThis.location;
  5171. if (!tempAnchor$1) {
  5172. tempAnchor$1 = document.createElement('a');
  5173. }
  5174. // let the browser determine the full href for the url of this resource and then
  5175. // parse with the node url lib, we can't use the properties of the anchor element
  5176. // because they don't work in IE9 :(
  5177. tempAnchor$1.href = url$1;
  5178. var parsedUrl = url.parse(tempAnchor$1.href);
  5179. var samePort = (!parsedUrl.port && loc.port === '') || (parsedUrl.port === loc.port);
  5180. // if cross origin
  5181. if (parsedUrl.hostname !== loc.hostname || !samePort || parsedUrl.protocol !== loc.protocol) {
  5182. return 'anonymous';
  5183. }
  5184. return '';
  5185. }
  5186. /**
  5187. * get the resolution / device pixel ratio of an asset by looking for the prefix
  5188. * used by spritesheets and image urls
  5189. * @memberof PIXI.utils
  5190. * @function getResolutionOfUrl
  5191. * @param {string} url - the image path
  5192. * @param {number} [defaultValue=1] - the defaultValue if no filename prefix is set.
  5193. * @returns {number} resolution / device pixel ratio of an asset
  5194. */
  5195. function getResolutionOfUrl(url, defaultValue) {
  5196. var resolution = settings.RETINA_PREFIX.exec(url);
  5197. if (resolution) {
  5198. return parseFloat(resolution[1]);
  5199. }
  5200. return defaultValue !== undefined ? defaultValue : 1;
  5201. }
  5202. var utils = {
  5203. __proto__: null,
  5204. BaseTextureCache: BaseTextureCache,
  5205. CanvasRenderTarget: CanvasRenderTarget,
  5206. DATA_URI: DATA_URI,
  5207. ProgramCache: ProgramCache,
  5208. TextureCache: TextureCache,
  5209. clearTextureCache: clearTextureCache,
  5210. correctBlendMode: correctBlendMode,
  5211. createIndicesForQuads: createIndicesForQuads,
  5212. decomposeDataUri: decomposeDataUri,
  5213. deprecation: deprecation,
  5214. destroyTextureCache: destroyTextureCache,
  5215. determineCrossOrigin: determineCrossOrigin,
  5216. getBufferType: getBufferType,
  5217. getResolutionOfUrl: getResolutionOfUrl,
  5218. hex2rgb: hex2rgb,
  5219. hex2string: hex2string,
  5220. interleaveTypedArrays: interleaveTypedArrays$1,
  5221. isPow2: isPow2,
  5222. isWebGLSupported: isWebGLSupported,
  5223. log2: log2,
  5224. nextPow2: nextPow2,
  5225. path: path,
  5226. premultiplyBlendMode: premultiplyBlendMode,
  5227. premultiplyRgba: premultiplyRgba,
  5228. premultiplyTint: premultiplyTint,
  5229. premultiplyTintToRgba: premultiplyTintToRgba,
  5230. removeItems: removeItems,
  5231. rgb2hex: rgb2hex,
  5232. sayHello: sayHello,
  5233. sign: sign,
  5234. skipHello: skipHello,
  5235. string2hex: string2hex,
  5236. trimCanvas: trimCanvas,
  5237. uid: uid,
  5238. url: url,
  5239. isMobile: isMobile,
  5240. EventEmitter: eventemitter3,
  5241. earcut: earcut_1
  5242. };
  5243. /*!
  5244. * @pixi/math - v6.5.10
  5245. * Compiled Thu, 06 Jul 2023 15:25:11 UTC
  5246. *
  5247. * @pixi/math is licensed under the MIT License.
  5248. * http://www.opensource.org/licenses/mit-license
  5249. */
  5250. /**
  5251. * Two Pi.
  5252. * @static
  5253. * @member {number}
  5254. * @memberof PIXI
  5255. */
  5256. var PI_2 = Math.PI * 2;
  5257. /**
  5258. * Conversion factor for converting radians to degrees.
  5259. * @static
  5260. * @member {number} RAD_TO_DEG
  5261. * @memberof PIXI
  5262. */
  5263. var RAD_TO_DEG = 180 / Math.PI;
  5264. /**
  5265. * Conversion factor for converting degrees to radians.
  5266. * @static
  5267. * @member {number}
  5268. * @memberof PIXI
  5269. */
  5270. var DEG_TO_RAD = Math.PI / 180;
  5271. /**
  5272. * Constants that identify shapes, mainly to prevent `instanceof` calls.
  5273. * @static
  5274. * @memberof PIXI
  5275. * @enum {number}
  5276. * @property {number} POLY Polygon
  5277. * @property {number} RECT Rectangle
  5278. * @property {number} CIRC Circle
  5279. * @property {number} ELIP Ellipse
  5280. * @property {number} RREC Rounded Rectangle
  5281. */
  5282. var SHAPES;
  5283. (function (SHAPES) {
  5284. SHAPES[SHAPES["POLY"] = 0] = "POLY";
  5285. SHAPES[SHAPES["RECT"] = 1] = "RECT";
  5286. SHAPES[SHAPES["CIRC"] = 2] = "CIRC";
  5287. SHAPES[SHAPES["ELIP"] = 3] = "ELIP";
  5288. SHAPES[SHAPES["RREC"] = 4] = "RREC";
  5289. })(SHAPES || (SHAPES = {}));
  5290. /**
  5291. * The Point object represents a location in a two-dimensional coordinate system, where `x` represents
  5292. * the position on the horizontal axis and `y` represents the position on the vertical axis
  5293. * @class
  5294. * @memberof PIXI
  5295. * @implements {IPoint}
  5296. */
  5297. var Point = /** @class */ (function () {
  5298. /**
  5299. * Creates a new `Point`
  5300. * @param {number} [x=0] - position of the point on the x axis
  5301. * @param {number} [y=0] - position of the point on the y axis
  5302. */
  5303. function Point(x, y) {
  5304. if (x === void 0) { x = 0; }
  5305. if (y === void 0) { y = 0; }
  5306. /** Position of the point on the x axis */
  5307. this.x = 0;
  5308. /** Position of the point on the y axis */
  5309. this.y = 0;
  5310. this.x = x;
  5311. this.y = y;
  5312. }
  5313. /**
  5314. * Creates a clone of this point
  5315. * @returns A clone of this point
  5316. */
  5317. Point.prototype.clone = function () {
  5318. return new Point(this.x, this.y);
  5319. };
  5320. /**
  5321. * Copies `x` and `y` from the given point into this point
  5322. * @param p - The point to copy from
  5323. * @returns The point instance itself
  5324. */
  5325. Point.prototype.copyFrom = function (p) {
  5326. this.set(p.x, p.y);
  5327. return this;
  5328. };
  5329. /**
  5330. * Copies this point's x and y into the given point (`p`).
  5331. * @param p - The point to copy to. Can be any of type that is or extends `IPointData`
  5332. * @returns The point (`p`) with values updated
  5333. */
  5334. Point.prototype.copyTo = function (p) {
  5335. p.set(this.x, this.y);
  5336. return p;
  5337. };
  5338. /**
  5339. * Accepts another point (`p`) and returns `true` if the given point is equal to this point
  5340. * @param p - The point to check
  5341. * @returns Returns `true` if both `x` and `y` are equal
  5342. */
  5343. Point.prototype.equals = function (p) {
  5344. return (p.x === this.x) && (p.y === this.y);
  5345. };
  5346. /**
  5347. * Sets the point to a new `x` and `y` position.
  5348. * If `y` is omitted, both `x` and `y` will be set to `x`.
  5349. * @param {number} [x=0] - position of the point on the `x` axis
  5350. * @param {number} [y=x] - position of the point on the `y` axis
  5351. * @returns The point instance itself
  5352. */
  5353. Point.prototype.set = function (x, y) {
  5354. if (x === void 0) { x = 0; }
  5355. if (y === void 0) { y = x; }
  5356. this.x = x;
  5357. this.y = y;
  5358. return this;
  5359. };
  5360. Point.prototype.toString = function () {
  5361. return "[@pixi/math:Point x=" + this.x + " y=" + this.y + "]";
  5362. };
  5363. return Point;
  5364. }());
  5365. var tempPoints$1 = [new Point(), new Point(), new Point(), new Point()];
  5366. /**
  5367. * Size object, contains width and height
  5368. * @memberof PIXI
  5369. * @typedef {object} ISize
  5370. * @property {number} width - Width component
  5371. * @property {number} height - Height component
  5372. */
  5373. /**
  5374. * Rectangle object is an area defined by its position, as indicated by its top-left corner
  5375. * point (x, y) and by its width and its height.
  5376. * @memberof PIXI
  5377. */
  5378. var Rectangle = /** @class */ (function () {
  5379. /**
  5380. * @param x - The X coordinate of the upper-left corner of the rectangle
  5381. * @param y - The Y coordinate of the upper-left corner of the rectangle
  5382. * @param width - The overall width of the rectangle
  5383. * @param height - The overall height of the rectangle
  5384. */
  5385. function Rectangle(x, y, width, height) {
  5386. if (x === void 0) { x = 0; }
  5387. if (y === void 0) { y = 0; }
  5388. if (width === void 0) { width = 0; }
  5389. if (height === void 0) { height = 0; }
  5390. this.x = Number(x);
  5391. this.y = Number(y);
  5392. this.width = Number(width);
  5393. this.height = Number(height);
  5394. this.type = SHAPES.RECT;
  5395. }
  5396. Object.defineProperty(Rectangle.prototype, "left", {
  5397. /** Returns the left edge of the rectangle. */
  5398. get: function () {
  5399. return this.x;
  5400. },
  5401. enumerable: false,
  5402. configurable: true
  5403. });
  5404. Object.defineProperty(Rectangle.prototype, "right", {
  5405. /** Returns the right edge of the rectangle. */
  5406. get: function () {
  5407. return this.x + this.width;
  5408. },
  5409. enumerable: false,
  5410. configurable: true
  5411. });
  5412. Object.defineProperty(Rectangle.prototype, "top", {
  5413. /** Returns the top edge of the rectangle. */
  5414. get: function () {
  5415. return this.y;
  5416. },
  5417. enumerable: false,
  5418. configurable: true
  5419. });
  5420. Object.defineProperty(Rectangle.prototype, "bottom", {
  5421. /** Returns the bottom edge of the rectangle. */
  5422. get: function () {
  5423. return this.y + this.height;
  5424. },
  5425. enumerable: false,
  5426. configurable: true
  5427. });
  5428. Object.defineProperty(Rectangle, "EMPTY", {
  5429. /** A constant empty rectangle. */
  5430. get: function () {
  5431. return new Rectangle(0, 0, 0, 0);
  5432. },
  5433. enumerable: false,
  5434. configurable: true
  5435. });
  5436. /**
  5437. * Creates a clone of this Rectangle
  5438. * @returns a copy of the rectangle
  5439. */
  5440. Rectangle.prototype.clone = function () {
  5441. return new Rectangle(this.x, this.y, this.width, this.height);
  5442. };
  5443. /**
  5444. * Copies another rectangle to this one.
  5445. * @param rectangle - The rectangle to copy from.
  5446. * @returns Returns itself.
  5447. */
  5448. Rectangle.prototype.copyFrom = function (rectangle) {
  5449. this.x = rectangle.x;
  5450. this.y = rectangle.y;
  5451. this.width = rectangle.width;
  5452. this.height = rectangle.height;
  5453. return this;
  5454. };
  5455. /**
  5456. * Copies this rectangle to another one.
  5457. * @param rectangle - The rectangle to copy to.
  5458. * @returns Returns given parameter.
  5459. */
  5460. Rectangle.prototype.copyTo = function (rectangle) {
  5461. rectangle.x = this.x;
  5462. rectangle.y = this.y;
  5463. rectangle.width = this.width;
  5464. rectangle.height = this.height;
  5465. return rectangle;
  5466. };
  5467. /**
  5468. * Checks whether the x and y coordinates given are contained within this Rectangle
  5469. * @param x - The X coordinate of the point to test
  5470. * @param y - The Y coordinate of the point to test
  5471. * @returns Whether the x/y coordinates are within this Rectangle
  5472. */
  5473. Rectangle.prototype.contains = function (x, y) {
  5474. if (this.width <= 0 || this.height <= 0) {
  5475. return false;
  5476. }
  5477. if (x >= this.x && x < this.x + this.width) {
  5478. if (y >= this.y && y < this.y + this.height) {
  5479. return true;
  5480. }
  5481. }
  5482. return false;
  5483. };
  5484. /**
  5485. * Determines whether the `other` Rectangle transformed by `transform` intersects with `this` Rectangle object.
  5486. * Returns true only if the area of the intersection is >0, this means that Rectangles
  5487. * sharing a side are not overlapping. Another side effect is that an arealess rectangle
  5488. * (width or height equal to zero) can't intersect any other rectangle.
  5489. * @param {Rectangle} other - The Rectangle to intersect with `this`.
  5490. * @param {Matrix} transform - The transformation matrix of `other`.
  5491. * @returns {boolean} A value of `true` if the transformed `other` Rectangle intersects with `this`; otherwise `false`.
  5492. */
  5493. Rectangle.prototype.intersects = function (other, transform) {
  5494. if (!transform) {
  5495. var x0_1 = this.x < other.x ? other.x : this.x;
  5496. var x1_1 = this.right > other.right ? other.right : this.right;
  5497. if (x1_1 <= x0_1) {
  5498. return false;
  5499. }
  5500. var y0_1 = this.y < other.y ? other.y : this.y;
  5501. var y1_1 = this.bottom > other.bottom ? other.bottom : this.bottom;
  5502. return y1_1 > y0_1;
  5503. }
  5504. var x0 = this.left;
  5505. var x1 = this.right;
  5506. var y0 = this.top;
  5507. var y1 = this.bottom;
  5508. if (x1 <= x0 || y1 <= y0) {
  5509. return false;
  5510. }
  5511. var lt = tempPoints$1[0].set(other.left, other.top);
  5512. var lb = tempPoints$1[1].set(other.left, other.bottom);
  5513. var rt = tempPoints$1[2].set(other.right, other.top);
  5514. var rb = tempPoints$1[3].set(other.right, other.bottom);
  5515. if (rt.x <= lt.x || lb.y <= lt.y) {
  5516. return false;
  5517. }
  5518. var s = Math.sign((transform.a * transform.d) - (transform.b * transform.c));
  5519. if (s === 0) {
  5520. return false;
  5521. }
  5522. transform.apply(lt, lt);
  5523. transform.apply(lb, lb);
  5524. transform.apply(rt, rt);
  5525. transform.apply(rb, rb);
  5526. if (Math.max(lt.x, lb.x, rt.x, rb.x) <= x0
  5527. || Math.min(lt.x, lb.x, rt.x, rb.x) >= x1
  5528. || Math.max(lt.y, lb.y, rt.y, rb.y) <= y0
  5529. || Math.min(lt.y, lb.y, rt.y, rb.y) >= y1) {
  5530. return false;
  5531. }
  5532. var nx = s * (lb.y - lt.y);
  5533. var ny = s * (lt.x - lb.x);
  5534. var n00 = (nx * x0) + (ny * y0);
  5535. var n10 = (nx * x1) + (ny * y0);
  5536. var n01 = (nx * x0) + (ny * y1);
  5537. var n11 = (nx * x1) + (ny * y1);
  5538. if (Math.max(n00, n10, n01, n11) <= (nx * lt.x) + (ny * lt.y)
  5539. || Math.min(n00, n10, n01, n11) >= (nx * rb.x) + (ny * rb.y)) {
  5540. return false;
  5541. }
  5542. var mx = s * (lt.y - rt.y);
  5543. var my = s * (rt.x - lt.x);
  5544. var m00 = (mx * x0) + (my * y0);
  5545. var m10 = (mx * x1) + (my * y0);
  5546. var m01 = (mx * x0) + (my * y1);
  5547. var m11 = (mx * x1) + (my * y1);
  5548. if (Math.max(m00, m10, m01, m11) <= (mx * lt.x) + (my * lt.y)
  5549. || Math.min(m00, m10, m01, m11) >= (mx * rb.x) + (my * rb.y)) {
  5550. return false;
  5551. }
  5552. return true;
  5553. };
  5554. /**
  5555. * Pads the rectangle making it grow in all directions.
  5556. * If paddingY is omitted, both paddingX and paddingY will be set to paddingX.
  5557. * @param paddingX - The horizontal padding amount.
  5558. * @param paddingY - The vertical padding amount.
  5559. * @returns Returns itself.
  5560. */
  5561. Rectangle.prototype.pad = function (paddingX, paddingY) {
  5562. if (paddingX === void 0) { paddingX = 0; }
  5563. if (paddingY === void 0) { paddingY = paddingX; }
  5564. this.x -= paddingX;
  5565. this.y -= paddingY;
  5566. this.width += paddingX * 2;
  5567. this.height += paddingY * 2;
  5568. return this;
  5569. };
  5570. /**
  5571. * Fits this rectangle around the passed one.
  5572. * @param rectangle - The rectangle to fit.
  5573. * @returns Returns itself.
  5574. */
  5575. Rectangle.prototype.fit = function (rectangle) {
  5576. var x1 = Math.max(this.x, rectangle.x);
  5577. var x2 = Math.min(this.x + this.width, rectangle.x + rectangle.width);
  5578. var y1 = Math.max(this.y, rectangle.y);
  5579. var y2 = Math.min(this.y + this.height, rectangle.y + rectangle.height);
  5580. this.x = x1;
  5581. this.width = Math.max(x2 - x1, 0);
  5582. this.y = y1;
  5583. this.height = Math.max(y2 - y1, 0);
  5584. return this;
  5585. };
  5586. /**
  5587. * Enlarges rectangle that way its corners lie on grid
  5588. * @param resolution - resolution
  5589. * @param eps - precision
  5590. * @returns Returns itself.
  5591. */
  5592. Rectangle.prototype.ceil = function (resolution, eps) {
  5593. if (resolution === void 0) { resolution = 1; }
  5594. if (eps === void 0) { eps = 0.001; }
  5595. var x2 = Math.ceil((this.x + this.width - eps) * resolution) / resolution;
  5596. var y2 = Math.ceil((this.y + this.height - eps) * resolution) / resolution;
  5597. this.x = Math.floor((this.x + eps) * resolution) / resolution;
  5598. this.y = Math.floor((this.y + eps) * resolution) / resolution;
  5599. this.width = x2 - this.x;
  5600. this.height = y2 - this.y;
  5601. return this;
  5602. };
  5603. /**
  5604. * Enlarges this rectangle to include the passed rectangle.
  5605. * @param rectangle - The rectangle to include.
  5606. * @returns Returns itself.
  5607. */
  5608. Rectangle.prototype.enlarge = function (rectangle) {
  5609. var x1 = Math.min(this.x, rectangle.x);
  5610. var x2 = Math.max(this.x + this.width, rectangle.x + rectangle.width);
  5611. var y1 = Math.min(this.y, rectangle.y);
  5612. var y2 = Math.max(this.y + this.height, rectangle.y + rectangle.height);
  5613. this.x = x1;
  5614. this.width = x2 - x1;
  5615. this.y = y1;
  5616. this.height = y2 - y1;
  5617. return this;
  5618. };
  5619. Rectangle.prototype.toString = function () {
  5620. return "[@pixi/math:Rectangle x=" + this.x + " y=" + this.y + " width=" + this.width + " height=" + this.height + "]";
  5621. };
  5622. return Rectangle;
  5623. }());
  5624. /**
  5625. * The Circle object is used to help draw graphics and can also be used to specify a hit area for displayObjects.
  5626. * @memberof PIXI
  5627. */
  5628. var Circle = /** @class */ (function () {
  5629. /**
  5630. * @param x - The X coordinate of the center of this circle
  5631. * @param y - The Y coordinate of the center of this circle
  5632. * @param radius - The radius of the circle
  5633. */
  5634. function Circle(x, y, radius) {
  5635. if (x === void 0) { x = 0; }
  5636. if (y === void 0) { y = 0; }
  5637. if (radius === void 0) { radius = 0; }
  5638. this.x = x;
  5639. this.y = y;
  5640. this.radius = radius;
  5641. this.type = SHAPES.CIRC;
  5642. }
  5643. /**
  5644. * Creates a clone of this Circle instance
  5645. * @returns A copy of the Circle
  5646. */
  5647. Circle.prototype.clone = function () {
  5648. return new Circle(this.x, this.y, this.radius);
  5649. };
  5650. /**
  5651. * Checks whether the x and y coordinates given are contained within this circle
  5652. * @param x - The X coordinate of the point to test
  5653. * @param y - The Y coordinate of the point to test
  5654. * @returns Whether the x/y coordinates are within this Circle
  5655. */
  5656. Circle.prototype.contains = function (x, y) {
  5657. if (this.radius <= 0) {
  5658. return false;
  5659. }
  5660. var r2 = this.radius * this.radius;
  5661. var dx = (this.x - x);
  5662. var dy = (this.y - y);
  5663. dx *= dx;
  5664. dy *= dy;
  5665. return (dx + dy <= r2);
  5666. };
  5667. /**
  5668. * Returns the framing rectangle of the circle as a Rectangle object
  5669. * @returns The framing rectangle
  5670. */
  5671. Circle.prototype.getBounds = function () {
  5672. return new Rectangle(this.x - this.radius, this.y - this.radius, this.radius * 2, this.radius * 2);
  5673. };
  5674. Circle.prototype.toString = function () {
  5675. return "[@pixi/math:Circle x=" + this.x + " y=" + this.y + " radius=" + this.radius + "]";
  5676. };
  5677. return Circle;
  5678. }());
  5679. /**
  5680. * The Ellipse object is used to help draw graphics and can also be used to specify a hit area for displayObjects.
  5681. * @memberof PIXI
  5682. */
  5683. var Ellipse = /** @class */ (function () {
  5684. /**
  5685. * @param x - The X coordinate of the center of this ellipse
  5686. * @param y - The Y coordinate of the center of this ellipse
  5687. * @param halfWidth - The half width of this ellipse
  5688. * @param halfHeight - The half height of this ellipse
  5689. */
  5690. function Ellipse(x, y, halfWidth, halfHeight) {
  5691. if (x === void 0) { x = 0; }
  5692. if (y === void 0) { y = 0; }
  5693. if (halfWidth === void 0) { halfWidth = 0; }
  5694. if (halfHeight === void 0) { halfHeight = 0; }
  5695. this.x = x;
  5696. this.y = y;
  5697. this.width = halfWidth;
  5698. this.height = halfHeight;
  5699. this.type = SHAPES.ELIP;
  5700. }
  5701. /**
  5702. * Creates a clone of this Ellipse instance
  5703. * @returns {PIXI.Ellipse} A copy of the ellipse
  5704. */
  5705. Ellipse.prototype.clone = function () {
  5706. return new Ellipse(this.x, this.y, this.width, this.height);
  5707. };
  5708. /**
  5709. * Checks whether the x and y coordinates given are contained within this ellipse
  5710. * @param x - The X coordinate of the point to test
  5711. * @param y - The Y coordinate of the point to test
  5712. * @returns Whether the x/y coords are within this ellipse
  5713. */
  5714. Ellipse.prototype.contains = function (x, y) {
  5715. if (this.width <= 0 || this.height <= 0) {
  5716. return false;
  5717. }
  5718. // normalize the coords to an ellipse with center 0,0
  5719. var normx = ((x - this.x) / this.width);
  5720. var normy = ((y - this.y) / this.height);
  5721. normx *= normx;
  5722. normy *= normy;
  5723. return (normx + normy <= 1);
  5724. };
  5725. /**
  5726. * Returns the framing rectangle of the ellipse as a Rectangle object
  5727. * @returns The framing rectangle
  5728. */
  5729. Ellipse.prototype.getBounds = function () {
  5730. return new Rectangle(this.x - this.width, this.y - this.height, this.width, this.height);
  5731. };
  5732. Ellipse.prototype.toString = function () {
  5733. return "[@pixi/math:Ellipse x=" + this.x + " y=" + this.y + " width=" + this.width + " height=" + this.height + "]";
  5734. };
  5735. return Ellipse;
  5736. }());
  5737. /**
  5738. * A class to define a shape via user defined coordinates.
  5739. * @memberof PIXI
  5740. */
  5741. var Polygon = /** @class */ (function () {
  5742. /**
  5743. * @param {PIXI.IPointData[]|number[]} points - This can be an array of Points
  5744. * that form the polygon, a flat array of numbers that will be interpreted as [x,y, x,y, ...], or
  5745. * the arguments passed can be all the points of the polygon e.g.
  5746. * `new PIXI.Polygon(new PIXI.Point(), new PIXI.Point(), ...)`, or the arguments passed can be flat
  5747. * x,y values e.g. `new Polygon(x,y, x,y, x,y, ...)` where `x` and `y` are Numbers.
  5748. */
  5749. function Polygon() {
  5750. var arguments$1 = arguments;
  5751. var points = [];
  5752. for (var _i = 0; _i < arguments.length; _i++) {
  5753. points[_i] = arguments$1[_i];
  5754. }
  5755. var flat = Array.isArray(points[0]) ? points[0] : points;
  5756. // if this is an array of points, convert it to a flat array of numbers
  5757. if (typeof flat[0] !== 'number') {
  5758. var p = [];
  5759. for (var i = 0, il = flat.length; i < il; i++) {
  5760. p.push(flat[i].x, flat[i].y);
  5761. }
  5762. flat = p;
  5763. }
  5764. this.points = flat;
  5765. this.type = SHAPES.POLY;
  5766. this.closeStroke = true;
  5767. }
  5768. /**
  5769. * Creates a clone of this polygon.
  5770. * @returns - A copy of the polygon.
  5771. */
  5772. Polygon.prototype.clone = function () {
  5773. var points = this.points.slice();
  5774. var polygon = new Polygon(points);
  5775. polygon.closeStroke = this.closeStroke;
  5776. return polygon;
  5777. };
  5778. /**
  5779. * Checks whether the x and y coordinates passed to this function are contained within this polygon.
  5780. * @param x - The X coordinate of the point to test.
  5781. * @param y - The Y coordinate of the point to test.
  5782. * @returns - Whether the x/y coordinates are within this polygon.
  5783. */
  5784. Polygon.prototype.contains = function (x, y) {
  5785. var inside = false;
  5786. // use some raycasting to test hits
  5787. // https://github.com/substack/point-in-polygon/blob/master/index.js
  5788. var length = this.points.length / 2;
  5789. for (var i = 0, j = length - 1; i < length; j = i++) {
  5790. var xi = this.points[i * 2];
  5791. var yi = this.points[(i * 2) + 1];
  5792. var xj = this.points[j * 2];
  5793. var yj = this.points[(j * 2) + 1];
  5794. var intersect = ((yi > y) !== (yj > y)) && (x < ((xj - xi) * ((y - yi) / (yj - yi))) + xi);
  5795. if (intersect) {
  5796. inside = !inside;
  5797. }
  5798. }
  5799. return inside;
  5800. };
  5801. Polygon.prototype.toString = function () {
  5802. return "[@pixi/math:Polygon"
  5803. + ("closeStroke=" + this.closeStroke)
  5804. + ("points=" + this.points.reduce(function (pointsDesc, currentPoint) { return pointsDesc + ", " + currentPoint; }, '') + "]");
  5805. };
  5806. return Polygon;
  5807. }());
  5808. /**
  5809. * The Rounded Rectangle object is an area that has nice rounded corners, as indicated by its
  5810. * top-left corner point (x, y) and by its width and its height and its radius.
  5811. * @memberof PIXI
  5812. */
  5813. var RoundedRectangle = /** @class */ (function () {
  5814. /**
  5815. * @param x - The X coordinate of the upper-left corner of the rounded rectangle
  5816. * @param y - The Y coordinate of the upper-left corner of the rounded rectangle
  5817. * @param width - The overall width of this rounded rectangle
  5818. * @param height - The overall height of this rounded rectangle
  5819. * @param radius - Controls the radius of the rounded corners
  5820. */
  5821. function RoundedRectangle(x, y, width, height, radius) {
  5822. if (x === void 0) { x = 0; }
  5823. if (y === void 0) { y = 0; }
  5824. if (width === void 0) { width = 0; }
  5825. if (height === void 0) { height = 0; }
  5826. if (radius === void 0) { radius = 20; }
  5827. this.x = x;
  5828. this.y = y;
  5829. this.width = width;
  5830. this.height = height;
  5831. this.radius = radius;
  5832. this.type = SHAPES.RREC;
  5833. }
  5834. /**
  5835. * Creates a clone of this Rounded Rectangle.
  5836. * @returns - A copy of the rounded rectangle.
  5837. */
  5838. RoundedRectangle.prototype.clone = function () {
  5839. return new RoundedRectangle(this.x, this.y, this.width, this.height, this.radius);
  5840. };
  5841. /**
  5842. * Checks whether the x and y coordinates given are contained within this Rounded Rectangle
  5843. * @param x - The X coordinate of the point to test.
  5844. * @param y - The Y coordinate of the point to test.
  5845. * @returns - Whether the x/y coordinates are within this Rounded Rectangle.
  5846. */
  5847. RoundedRectangle.prototype.contains = function (x, y) {
  5848. if (this.width <= 0 || this.height <= 0) {
  5849. return false;
  5850. }
  5851. if (x >= this.x && x <= this.x + this.width) {
  5852. if (y >= this.y && y <= this.y + this.height) {
  5853. var radius = Math.max(0, Math.min(this.radius, Math.min(this.width, this.height) / 2));
  5854. if ((y >= this.y + radius && y <= this.y + this.height - radius)
  5855. || (x >= this.x + radius && x <= this.x + this.width - radius)) {
  5856. return true;
  5857. }
  5858. var dx = x - (this.x + radius);
  5859. var dy = y - (this.y + radius);
  5860. var radius2 = radius * radius;
  5861. if ((dx * dx) + (dy * dy) <= radius2) {
  5862. return true;
  5863. }
  5864. dx = x - (this.x + this.width - radius);
  5865. if ((dx * dx) + (dy * dy) <= radius2) {
  5866. return true;
  5867. }
  5868. dy = y - (this.y + this.height - radius);
  5869. if ((dx * dx) + (dy * dy) <= radius2) {
  5870. return true;
  5871. }
  5872. dx = x - (this.x + radius);
  5873. if ((dx * dx) + (dy * dy) <= radius2) {
  5874. return true;
  5875. }
  5876. }
  5877. }
  5878. return false;
  5879. };
  5880. RoundedRectangle.prototype.toString = function () {
  5881. return "[@pixi/math:RoundedRectangle x=" + this.x + " y=" + this.y
  5882. + ("width=" + this.width + " height=" + this.height + " radius=" + this.radius + "]");
  5883. };
  5884. return RoundedRectangle;
  5885. }());
  5886. /**
  5887. * The ObservablePoint object represents a location in a two-dimensional coordinate system, where `x` represents
  5888. * the position on the horizontal axis and `y` represents the position on the vertical axis.
  5889. *
  5890. * An `ObservablePoint` is a point that triggers a callback when the point's position is changed.
  5891. * @memberof PIXI
  5892. */
  5893. var ObservablePoint = /** @class */ (function () {
  5894. /**
  5895. * Creates a new `ObservablePoint`
  5896. * @param cb - callback function triggered when `x` and/or `y` are changed
  5897. * @param scope - owner of callback
  5898. * @param {number} [x=0] - position of the point on the x axis
  5899. * @param {number} [y=0] - position of the point on the y axis
  5900. */
  5901. function ObservablePoint(cb, scope, x, y) {
  5902. if (x === void 0) { x = 0; }
  5903. if (y === void 0) { y = 0; }
  5904. this._x = x;
  5905. this._y = y;
  5906. this.cb = cb;
  5907. this.scope = scope;
  5908. }
  5909. /**
  5910. * Creates a clone of this point.
  5911. * The callback and scope params can be overridden otherwise they will default
  5912. * to the clone object's values.
  5913. * @override
  5914. * @param cb - The callback function triggered when `x` and/or `y` are changed
  5915. * @param scope - The owner of the callback
  5916. * @returns a copy of this observable point
  5917. */
  5918. ObservablePoint.prototype.clone = function (cb, scope) {
  5919. if (cb === void 0) { cb = this.cb; }
  5920. if (scope === void 0) { scope = this.scope; }
  5921. return new ObservablePoint(cb, scope, this._x, this._y);
  5922. };
  5923. /**
  5924. * Sets the point to a new `x` and `y` position.
  5925. * If `y` is omitted, both `x` and `y` will be set to `x`.
  5926. * @param {number} [x=0] - position of the point on the x axis
  5927. * @param {number} [y=x] - position of the point on the y axis
  5928. * @returns The observable point instance itself
  5929. */
  5930. ObservablePoint.prototype.set = function (x, y) {
  5931. if (x === void 0) { x = 0; }
  5932. if (y === void 0) { y = x; }
  5933. if (this._x !== x || this._y !== y) {
  5934. this._x = x;
  5935. this._y = y;
  5936. this.cb.call(this.scope);
  5937. }
  5938. return this;
  5939. };
  5940. /**
  5941. * Copies x and y from the given point (`p`)
  5942. * @param p - The point to copy from. Can be any of type that is or extends `IPointData`
  5943. * @returns The observable point instance itself
  5944. */
  5945. ObservablePoint.prototype.copyFrom = function (p) {
  5946. if (this._x !== p.x || this._y !== p.y) {
  5947. this._x = p.x;
  5948. this._y = p.y;
  5949. this.cb.call(this.scope);
  5950. }
  5951. return this;
  5952. };
  5953. /**
  5954. * Copies this point's x and y into that of the given point (`p`)
  5955. * @param p - The point to copy to. Can be any of type that is or extends `IPointData`
  5956. * @returns The point (`p`) with values updated
  5957. */
  5958. ObservablePoint.prototype.copyTo = function (p) {
  5959. p.set(this._x, this._y);
  5960. return p;
  5961. };
  5962. /**
  5963. * Accepts another point (`p`) and returns `true` if the given point is equal to this point
  5964. * @param p - The point to check
  5965. * @returns Returns `true` if both `x` and `y` are equal
  5966. */
  5967. ObservablePoint.prototype.equals = function (p) {
  5968. return (p.x === this._x) && (p.y === this._y);
  5969. };
  5970. ObservablePoint.prototype.toString = function () {
  5971. return "[@pixi/math:ObservablePoint x=" + 0 + " y=" + 0 + " scope=" + this.scope + "]";
  5972. };
  5973. Object.defineProperty(ObservablePoint.prototype, "x", {
  5974. /** Position of the observable point on the x axis. */
  5975. get: function () {
  5976. return this._x;
  5977. },
  5978. set: function (value) {
  5979. if (this._x !== value) {
  5980. this._x = value;
  5981. this.cb.call(this.scope);
  5982. }
  5983. },
  5984. enumerable: false,
  5985. configurable: true
  5986. });
  5987. Object.defineProperty(ObservablePoint.prototype, "y", {
  5988. /** Position of the observable point on the y axis. */
  5989. get: function () {
  5990. return this._y;
  5991. },
  5992. set: function (value) {
  5993. if (this._y !== value) {
  5994. this._y = value;
  5995. this.cb.call(this.scope);
  5996. }
  5997. },
  5998. enumerable: false,
  5999. configurable: true
  6000. });
  6001. return ObservablePoint;
  6002. }());
  6003. /**
  6004. * The PixiJS Matrix as a class makes it a lot faster.
  6005. *
  6006. * Here is a representation of it:
  6007. * ```js
  6008. * | a | c | tx|
  6009. * | b | d | ty|
  6010. * | 0 | 0 | 1 |
  6011. * ```
  6012. * @memberof PIXI
  6013. */
  6014. var Matrix = /** @class */ (function () {
  6015. /**
  6016. * @param a - x scale
  6017. * @param b - y skew
  6018. * @param c - x skew
  6019. * @param d - y scale
  6020. * @param tx - x translation
  6021. * @param ty - y translation
  6022. */
  6023. function Matrix(a, b, c, d, tx, ty) {
  6024. if (a === void 0) { a = 1; }
  6025. if (b === void 0) { b = 0; }
  6026. if (c === void 0) { c = 0; }
  6027. if (d === void 0) { d = 1; }
  6028. if (tx === void 0) { tx = 0; }
  6029. if (ty === void 0) { ty = 0; }
  6030. this.array = null;
  6031. this.a = a;
  6032. this.b = b;
  6033. this.c = c;
  6034. this.d = d;
  6035. this.tx = tx;
  6036. this.ty = ty;
  6037. }
  6038. /**
  6039. * Creates a Matrix object based on the given array. The Element to Matrix mapping order is as follows:
  6040. *
  6041. * a = array[0]
  6042. * b = array[1]
  6043. * c = array[3]
  6044. * d = array[4]
  6045. * tx = array[2]
  6046. * ty = array[5]
  6047. * @param array - The array that the matrix will be populated from.
  6048. */
  6049. Matrix.prototype.fromArray = function (array) {
  6050. this.a = array[0];
  6051. this.b = array[1];
  6052. this.c = array[3];
  6053. this.d = array[4];
  6054. this.tx = array[2];
  6055. this.ty = array[5];
  6056. };
  6057. /**
  6058. * Sets the matrix properties.
  6059. * @param a - Matrix component
  6060. * @param b - Matrix component
  6061. * @param c - Matrix component
  6062. * @param d - Matrix component
  6063. * @param tx - Matrix component
  6064. * @param ty - Matrix component
  6065. * @returns This matrix. Good for chaining method calls.
  6066. */
  6067. Matrix.prototype.set = function (a, b, c, d, tx, ty) {
  6068. this.a = a;
  6069. this.b = b;
  6070. this.c = c;
  6071. this.d = d;
  6072. this.tx = tx;
  6073. this.ty = ty;
  6074. return this;
  6075. };
  6076. /**
  6077. * Creates an array from the current Matrix object.
  6078. * @param transpose - Whether we need to transpose the matrix or not
  6079. * @param [out=new Float32Array(9)] - If provided the array will be assigned to out
  6080. * @returns The newly created array which contains the matrix
  6081. */
  6082. Matrix.prototype.toArray = function (transpose, out) {
  6083. if (!this.array) {
  6084. this.array = new Float32Array(9);
  6085. }
  6086. var array = out || this.array;
  6087. if (transpose) {
  6088. array[0] = this.a;
  6089. array[1] = this.b;
  6090. array[2] = 0;
  6091. array[3] = this.c;
  6092. array[4] = this.d;
  6093. array[5] = 0;
  6094. array[6] = this.tx;
  6095. array[7] = this.ty;
  6096. array[8] = 1;
  6097. }
  6098. else {
  6099. array[0] = this.a;
  6100. array[1] = this.c;
  6101. array[2] = this.tx;
  6102. array[3] = this.b;
  6103. array[4] = this.d;
  6104. array[5] = this.ty;
  6105. array[6] = 0;
  6106. array[7] = 0;
  6107. array[8] = 1;
  6108. }
  6109. return array;
  6110. };
  6111. /**
  6112. * Get a new position with the current transformation applied.
  6113. * Can be used to go from a child's coordinate space to the world coordinate space. (e.g. rendering)
  6114. * @param pos - The origin
  6115. * @param {PIXI.Point} [newPos] - The point that the new position is assigned to (allowed to be same as input)
  6116. * @returns {PIXI.Point} The new point, transformed through this matrix
  6117. */
  6118. Matrix.prototype.apply = function (pos, newPos) {
  6119. newPos = (newPos || new Point());
  6120. var x = pos.x;
  6121. var y = pos.y;
  6122. newPos.x = (this.a * x) + (this.c * y) + this.tx;
  6123. newPos.y = (this.b * x) + (this.d * y) + this.ty;
  6124. return newPos;
  6125. };
  6126. /**
  6127. * Get a new position with the inverse of the current transformation applied.
  6128. * Can be used to go from the world coordinate space to a child's coordinate space. (e.g. input)
  6129. * @param pos - The origin
  6130. * @param {PIXI.Point} [newPos] - The point that the new position is assigned to (allowed to be same as input)
  6131. * @returns {PIXI.Point} The new point, inverse-transformed through this matrix
  6132. */
  6133. Matrix.prototype.applyInverse = function (pos, newPos) {
  6134. newPos = (newPos || new Point());
  6135. var id = 1 / ((this.a * this.d) + (this.c * -this.b));
  6136. var x = pos.x;
  6137. var y = pos.y;
  6138. newPos.x = (this.d * id * x) + (-this.c * id * y) + (((this.ty * this.c) - (this.tx * this.d)) * id);
  6139. newPos.y = (this.a * id * y) + (-this.b * id * x) + (((-this.ty * this.a) + (this.tx * this.b)) * id);
  6140. return newPos;
  6141. };
  6142. /**
  6143. * Translates the matrix on the x and y.
  6144. * @param x - How much to translate x by
  6145. * @param y - How much to translate y by
  6146. * @returns This matrix. Good for chaining method calls.
  6147. */
  6148. Matrix.prototype.translate = function (x, y) {
  6149. this.tx += x;
  6150. this.ty += y;
  6151. return this;
  6152. };
  6153. /**
  6154. * Applies a scale transformation to the matrix.
  6155. * @param x - The amount to scale horizontally
  6156. * @param y - The amount to scale vertically
  6157. * @returns This matrix. Good for chaining method calls.
  6158. */
  6159. Matrix.prototype.scale = function (x, y) {
  6160. this.a *= x;
  6161. this.d *= y;
  6162. this.c *= x;
  6163. this.b *= y;
  6164. this.tx *= x;
  6165. this.ty *= y;
  6166. return this;
  6167. };
  6168. /**
  6169. * Applies a rotation transformation to the matrix.
  6170. * @param angle - The angle in radians.
  6171. * @returns This matrix. Good for chaining method calls.
  6172. */
  6173. Matrix.prototype.rotate = function (angle) {
  6174. var cos = Math.cos(angle);
  6175. var sin = Math.sin(angle);
  6176. var a1 = this.a;
  6177. var c1 = this.c;
  6178. var tx1 = this.tx;
  6179. this.a = (a1 * cos) - (this.b * sin);
  6180. this.b = (a1 * sin) + (this.b * cos);
  6181. this.c = (c1 * cos) - (this.d * sin);
  6182. this.d = (c1 * sin) + (this.d * cos);
  6183. this.tx = (tx1 * cos) - (this.ty * sin);
  6184. this.ty = (tx1 * sin) + (this.ty * cos);
  6185. return this;
  6186. };
  6187. /**
  6188. * Appends the given Matrix to this Matrix.
  6189. * @param matrix - The matrix to append.
  6190. * @returns This matrix. Good for chaining method calls.
  6191. */
  6192. Matrix.prototype.append = function (matrix) {
  6193. var a1 = this.a;
  6194. var b1 = this.b;
  6195. var c1 = this.c;
  6196. var d1 = this.d;
  6197. this.a = (matrix.a * a1) + (matrix.b * c1);
  6198. this.b = (matrix.a * b1) + (matrix.b * d1);
  6199. this.c = (matrix.c * a1) + (matrix.d * c1);
  6200. this.d = (matrix.c * b1) + (matrix.d * d1);
  6201. this.tx = (matrix.tx * a1) + (matrix.ty * c1) + this.tx;
  6202. this.ty = (matrix.tx * b1) + (matrix.ty * d1) + this.ty;
  6203. return this;
  6204. };
  6205. /**
  6206. * Sets the matrix based on all the available properties
  6207. * @param x - Position on the x axis
  6208. * @param y - Position on the y axis
  6209. * @param pivotX - Pivot on the x axis
  6210. * @param pivotY - Pivot on the y axis
  6211. * @param scaleX - Scale on the x axis
  6212. * @param scaleY - Scale on the y axis
  6213. * @param rotation - Rotation in radians
  6214. * @param skewX - Skew on the x axis
  6215. * @param skewY - Skew on the y axis
  6216. * @returns This matrix. Good for chaining method calls.
  6217. */
  6218. Matrix.prototype.setTransform = function (x, y, pivotX, pivotY, scaleX, scaleY, rotation, skewX, skewY) {
  6219. this.a = Math.cos(rotation + skewY) * scaleX;
  6220. this.b = Math.sin(rotation + skewY) * scaleX;
  6221. this.c = -Math.sin(rotation - skewX) * scaleY;
  6222. this.d = Math.cos(rotation - skewX) * scaleY;
  6223. this.tx = x - ((pivotX * this.a) + (pivotY * this.c));
  6224. this.ty = y - ((pivotX * this.b) + (pivotY * this.d));
  6225. return this;
  6226. };
  6227. /**
  6228. * Prepends the given Matrix to this Matrix.
  6229. * @param matrix - The matrix to prepend
  6230. * @returns This matrix. Good for chaining method calls.
  6231. */
  6232. Matrix.prototype.prepend = function (matrix) {
  6233. var tx1 = this.tx;
  6234. if (matrix.a !== 1 || matrix.b !== 0 || matrix.c !== 0 || matrix.d !== 1) {
  6235. var a1 = this.a;
  6236. var c1 = this.c;
  6237. this.a = (a1 * matrix.a) + (this.b * matrix.c);
  6238. this.b = (a1 * matrix.b) + (this.b * matrix.d);
  6239. this.c = (c1 * matrix.a) + (this.d * matrix.c);
  6240. this.d = (c1 * matrix.b) + (this.d * matrix.d);
  6241. }
  6242. this.tx = (tx1 * matrix.a) + (this.ty * matrix.c) + matrix.tx;
  6243. this.ty = (tx1 * matrix.b) + (this.ty * matrix.d) + matrix.ty;
  6244. return this;
  6245. };
  6246. /**
  6247. * Decomposes the matrix (x, y, scaleX, scaleY, and rotation) and sets the properties on to a transform.
  6248. * @param transform - The transform to apply the properties to.
  6249. * @returns The transform with the newly applied properties
  6250. */
  6251. Matrix.prototype.decompose = function (transform) {
  6252. // sort out rotation / skew..
  6253. var a = this.a;
  6254. var b = this.b;
  6255. var c = this.c;
  6256. var d = this.d;
  6257. var pivot = transform.pivot;
  6258. var skewX = -Math.atan2(-c, d);
  6259. var skewY = Math.atan2(b, a);
  6260. var delta = Math.abs(skewX + skewY);
  6261. if (delta < 0.00001 || Math.abs(PI_2 - delta) < 0.00001) {
  6262. transform.rotation = skewY;
  6263. transform.skew.x = transform.skew.y = 0;
  6264. }
  6265. else {
  6266. transform.rotation = 0;
  6267. transform.skew.x = skewX;
  6268. transform.skew.y = skewY;
  6269. }
  6270. // next set scale
  6271. transform.scale.x = Math.sqrt((a * a) + (b * b));
  6272. transform.scale.y = Math.sqrt((c * c) + (d * d));
  6273. // next set position
  6274. transform.position.x = this.tx + ((pivot.x * a) + (pivot.y * c));
  6275. transform.position.y = this.ty + ((pivot.x * b) + (pivot.y * d));
  6276. return transform;
  6277. };
  6278. /**
  6279. * Inverts this matrix
  6280. * @returns This matrix. Good for chaining method calls.
  6281. */
  6282. Matrix.prototype.invert = function () {
  6283. var a1 = this.a;
  6284. var b1 = this.b;
  6285. var c1 = this.c;
  6286. var d1 = this.d;
  6287. var tx1 = this.tx;
  6288. var n = (a1 * d1) - (b1 * c1);
  6289. this.a = d1 / n;
  6290. this.b = -b1 / n;
  6291. this.c = -c1 / n;
  6292. this.d = a1 / n;
  6293. this.tx = ((c1 * this.ty) - (d1 * tx1)) / n;
  6294. this.ty = -((a1 * this.ty) - (b1 * tx1)) / n;
  6295. return this;
  6296. };
  6297. /**
  6298. * Resets this Matrix to an identity (default) matrix.
  6299. * @returns This matrix. Good for chaining method calls.
  6300. */
  6301. Matrix.prototype.identity = function () {
  6302. this.a = 1;
  6303. this.b = 0;
  6304. this.c = 0;
  6305. this.d = 1;
  6306. this.tx = 0;
  6307. this.ty = 0;
  6308. return this;
  6309. };
  6310. /**
  6311. * Creates a new Matrix object with the same values as this one.
  6312. * @returns A copy of this matrix. Good for chaining method calls.
  6313. */
  6314. Matrix.prototype.clone = function () {
  6315. var matrix = new Matrix();
  6316. matrix.a = this.a;
  6317. matrix.b = this.b;
  6318. matrix.c = this.c;
  6319. matrix.d = this.d;
  6320. matrix.tx = this.tx;
  6321. matrix.ty = this.ty;
  6322. return matrix;
  6323. };
  6324. /**
  6325. * Changes the values of the given matrix to be the same as the ones in this matrix
  6326. * @param matrix - The matrix to copy to.
  6327. * @returns The matrix given in parameter with its values updated.
  6328. */
  6329. Matrix.prototype.copyTo = function (matrix) {
  6330. matrix.a = this.a;
  6331. matrix.b = this.b;
  6332. matrix.c = this.c;
  6333. matrix.d = this.d;
  6334. matrix.tx = this.tx;
  6335. matrix.ty = this.ty;
  6336. return matrix;
  6337. };
  6338. /**
  6339. * Changes the values of the matrix to be the same as the ones in given matrix
  6340. * @param {PIXI.Matrix} matrix - The matrix to copy from.
  6341. * @returns {PIXI.Matrix} this
  6342. */
  6343. Matrix.prototype.copyFrom = function (matrix) {
  6344. this.a = matrix.a;
  6345. this.b = matrix.b;
  6346. this.c = matrix.c;
  6347. this.d = matrix.d;
  6348. this.tx = matrix.tx;
  6349. this.ty = matrix.ty;
  6350. return this;
  6351. };
  6352. Matrix.prototype.toString = function () {
  6353. return "[@pixi/math:Matrix a=" + this.a + " b=" + this.b + " c=" + this.c + " d=" + this.d + " tx=" + this.tx + " ty=" + this.ty + "]";
  6354. };
  6355. Object.defineProperty(Matrix, "IDENTITY", {
  6356. /**
  6357. * A default (identity) matrix
  6358. * @readonly
  6359. */
  6360. get: function () {
  6361. return new Matrix();
  6362. },
  6363. enumerable: false,
  6364. configurable: true
  6365. });
  6366. Object.defineProperty(Matrix, "TEMP_MATRIX", {
  6367. /**
  6368. * A temp matrix
  6369. * @readonly
  6370. */
  6371. get: function () {
  6372. return new Matrix();
  6373. },
  6374. enumerable: false,
  6375. configurable: true
  6376. });
  6377. return Matrix;
  6378. }());
  6379. // Your friendly neighbour https://en.wikipedia.org/wiki/Dihedral_group
  6380. /*
  6381. * Transform matrix for operation n is:
  6382. * | ux | vx |
  6383. * | uy | vy |
  6384. */
  6385. var ux = [1, 1, 0, -1, -1, -1, 0, 1, 1, 1, 0, -1, -1, -1, 0, 1];
  6386. var uy = [0, 1, 1, 1, 0, -1, -1, -1, 0, 1, 1, 1, 0, -1, -1, -1];
  6387. var vx = [0, -1, -1, -1, 0, 1, 1, 1, 0, 1, 1, 1, 0, -1, -1, -1];
  6388. var vy = [1, 1, 0, -1, -1, -1, 0, 1, -1, -1, 0, 1, 1, 1, 0, -1];
  6389. /**
  6390. * [Cayley Table]{@link https://en.wikipedia.org/wiki/Cayley_table}
  6391. * for the composition of each rotation in the dihederal group D8.
  6392. * @type {number[][]}
  6393. * @private
  6394. */
  6395. var rotationCayley = [];
  6396. /**
  6397. * Matrices for each `GD8Symmetry` rotation.
  6398. * @type {PIXI.Matrix[]}
  6399. * @private
  6400. */
  6401. var rotationMatrices = [];
  6402. /*
  6403. * Alias for {@code Math.sign}.
  6404. */
  6405. var signum = Math.sign;
  6406. /*
  6407. * Initializes `rotationCayley` and `rotationMatrices`. It is called
  6408. * only once below.
  6409. */
  6410. function init() {
  6411. for (var i = 0; i < 16; i++) {
  6412. var row = [];
  6413. rotationCayley.push(row);
  6414. for (var j = 0; j < 16; j++) {
  6415. /* Multiplies rotation matrices i and j. */
  6416. var _ux = signum((ux[i] * ux[j]) + (vx[i] * uy[j]));
  6417. var _uy = signum((uy[i] * ux[j]) + (vy[i] * uy[j]));
  6418. var _vx = signum((ux[i] * vx[j]) + (vx[i] * vy[j]));
  6419. var _vy = signum((uy[i] * vx[j]) + (vy[i] * vy[j]));
  6420. /* Finds rotation matrix matching the product and pushes it. */
  6421. for (var k = 0; k < 16; k++) {
  6422. if (ux[k] === _ux && uy[k] === _uy
  6423. && vx[k] === _vx && vy[k] === _vy) {
  6424. row.push(k);
  6425. break;
  6426. }
  6427. }
  6428. }
  6429. }
  6430. for (var i = 0; i < 16; i++) {
  6431. var mat = new Matrix();
  6432. mat.set(ux[i], uy[i], vx[i], vy[i], 0, 0);
  6433. rotationMatrices.push(mat);
  6434. }
  6435. }
  6436. init();
  6437. /**
  6438. * @memberof PIXI
  6439. * @typedef {number} GD8Symmetry
  6440. * @see PIXI.groupD8
  6441. */
  6442. /**
  6443. * Implements the dihedral group D8, which is similar to
  6444. * [group D4]{@link http://mathworld.wolfram.com/DihedralGroupD4.html};
  6445. * D8 is the same but with diagonals, and it is used for texture
  6446. * rotations.
  6447. *
  6448. * The directions the U- and V- axes after rotation
  6449. * of an angle of `a: GD8Constant` are the vectors `(uX(a), uY(a))`
  6450. * and `(vX(a), vY(a))`. These aren't necessarily unit vectors.
  6451. *
  6452. * **Origin:**<br>
  6453. * This is the small part of gameofbombs.com portal system. It works.
  6454. * @see PIXI.groupD8.E
  6455. * @see PIXI.groupD8.SE
  6456. * @see PIXI.groupD8.S
  6457. * @see PIXI.groupD8.SW
  6458. * @see PIXI.groupD8.W
  6459. * @see PIXI.groupD8.NW
  6460. * @see PIXI.groupD8.N
  6461. * @see PIXI.groupD8.NE
  6462. * @author Ivan @ivanpopelyshev
  6463. * @namespace PIXI.groupD8
  6464. * @memberof PIXI
  6465. */
  6466. var groupD8 = {
  6467. /**
  6468. * | Rotation | Direction |
  6469. * |----------|-----------|
  6470. * | 0° | East |
  6471. * @memberof PIXI.groupD8
  6472. * @constant {PIXI.GD8Symmetry}
  6473. */
  6474. E: 0,
  6475. /**
  6476. * | Rotation | Direction |
  6477. * |----------|-----------|
  6478. * | 45°↻ | Southeast |
  6479. * @memberof PIXI.groupD8
  6480. * @constant {PIXI.GD8Symmetry}
  6481. */
  6482. SE: 1,
  6483. /**
  6484. * | Rotation | Direction |
  6485. * |----------|-----------|
  6486. * | 90°↻ | South |
  6487. * @memberof PIXI.groupD8
  6488. * @constant {PIXI.GD8Symmetry}
  6489. */
  6490. S: 2,
  6491. /**
  6492. * | Rotation | Direction |
  6493. * |----------|-----------|
  6494. * | 135°↻ | Southwest |
  6495. * @memberof PIXI.groupD8
  6496. * @constant {PIXI.GD8Symmetry}
  6497. */
  6498. SW: 3,
  6499. /**
  6500. * | Rotation | Direction |
  6501. * |----------|-----------|
  6502. * | 180° | West |
  6503. * @memberof PIXI.groupD8
  6504. * @constant {PIXI.GD8Symmetry}
  6505. */
  6506. W: 4,
  6507. /**
  6508. * | Rotation | Direction |
  6509. * |-------------|--------------|
  6510. * | -135°/225°↻ | Northwest |
  6511. * @memberof PIXI.groupD8
  6512. * @constant {PIXI.GD8Symmetry}
  6513. */
  6514. NW: 5,
  6515. /**
  6516. * | Rotation | Direction |
  6517. * |-------------|--------------|
  6518. * | -90°/270°↻ | North |
  6519. * @memberof PIXI.groupD8
  6520. * @constant {PIXI.GD8Symmetry}
  6521. */
  6522. N: 6,
  6523. /**
  6524. * | Rotation | Direction |
  6525. * |-------------|--------------|
  6526. * | -45°/315°↻ | Northeast |
  6527. * @memberof PIXI.groupD8
  6528. * @constant {PIXI.GD8Symmetry}
  6529. */
  6530. NE: 7,
  6531. /**
  6532. * Reflection about Y-axis.
  6533. * @memberof PIXI.groupD8
  6534. * @constant {PIXI.GD8Symmetry}
  6535. */
  6536. MIRROR_VERTICAL: 8,
  6537. /**
  6538. * Reflection about the main diagonal.
  6539. * @memberof PIXI.groupD8
  6540. * @constant {PIXI.GD8Symmetry}
  6541. */
  6542. MAIN_DIAGONAL: 10,
  6543. /**
  6544. * Reflection about X-axis.
  6545. * @memberof PIXI.groupD8
  6546. * @constant {PIXI.GD8Symmetry}
  6547. */
  6548. MIRROR_HORIZONTAL: 12,
  6549. /**
  6550. * Reflection about reverse diagonal.
  6551. * @memberof PIXI.groupD8
  6552. * @constant {PIXI.GD8Symmetry}
  6553. */
  6554. REVERSE_DIAGONAL: 14,
  6555. /**
  6556. * @memberof PIXI.groupD8
  6557. * @param {PIXI.GD8Symmetry} ind - sprite rotation angle.
  6558. * @returns {PIXI.GD8Symmetry} The X-component of the U-axis
  6559. * after rotating the axes.
  6560. */
  6561. uX: function (ind) { return ux[ind]; },
  6562. /**
  6563. * @memberof PIXI.groupD8
  6564. * @param {PIXI.GD8Symmetry} ind - sprite rotation angle.
  6565. * @returns {PIXI.GD8Symmetry} The Y-component of the U-axis
  6566. * after rotating the axes.
  6567. */
  6568. uY: function (ind) { return uy[ind]; },
  6569. /**
  6570. * @memberof PIXI.groupD8
  6571. * @param {PIXI.GD8Symmetry} ind - sprite rotation angle.
  6572. * @returns {PIXI.GD8Symmetry} The X-component of the V-axis
  6573. * after rotating the axes.
  6574. */
  6575. vX: function (ind) { return vx[ind]; },
  6576. /**
  6577. * @memberof PIXI.groupD8
  6578. * @param {PIXI.GD8Symmetry} ind - sprite rotation angle.
  6579. * @returns {PIXI.GD8Symmetry} The Y-component of the V-axis
  6580. * after rotating the axes.
  6581. */
  6582. vY: function (ind) { return vy[ind]; },
  6583. /**
  6584. * @memberof PIXI.groupD8
  6585. * @param {PIXI.GD8Symmetry} rotation - symmetry whose opposite
  6586. * is needed. Only rotations have opposite symmetries while
  6587. * reflections don't.
  6588. * @returns {PIXI.GD8Symmetry} The opposite symmetry of `rotation`
  6589. */
  6590. inv: function (rotation) {
  6591. if (rotation & 8) // true only if between 8 & 15 (reflections)
  6592. {
  6593. return rotation & 15; // or rotation % 16
  6594. }
  6595. return (-rotation) & 7; // or (8 - rotation) % 8
  6596. },
  6597. /**
  6598. * Composes the two D8 operations.
  6599. *
  6600. * Taking `^` as reflection:
  6601. *
  6602. * | | E=0 | S=2 | W=4 | N=6 | E^=8 | S^=10 | W^=12 | N^=14 |
  6603. * |-------|-----|-----|-----|-----|------|-------|-------|-------|
  6604. * | E=0 | E | S | W | N | E^ | S^ | W^ | N^ |
  6605. * | S=2 | S | W | N | E | S^ | W^ | N^ | E^ |
  6606. * | W=4 | W | N | E | S | W^ | N^ | E^ | S^ |
  6607. * | N=6 | N | E | S | W | N^ | E^ | S^ | W^ |
  6608. * | E^=8 | E^ | N^ | W^ | S^ | E | N | W | S |
  6609. * | S^=10 | S^ | E^ | N^ | W^ | S | E | N | W |
  6610. * | W^=12 | W^ | S^ | E^ | N^ | W | S | E | N |
  6611. * | N^=14 | N^ | W^ | S^ | E^ | N | W | S | E |
  6612. *
  6613. * [This is a Cayley table]{@link https://en.wikipedia.org/wiki/Cayley_table}
  6614. * @memberof PIXI.groupD8
  6615. * @param {PIXI.GD8Symmetry} rotationSecond - Second operation, which
  6616. * is the row in the above cayley table.
  6617. * @param {PIXI.GD8Symmetry} rotationFirst - First operation, which
  6618. * is the column in the above cayley table.
  6619. * @returns {PIXI.GD8Symmetry} Composed operation
  6620. */
  6621. add: function (rotationSecond, rotationFirst) { return (rotationCayley[rotationSecond][rotationFirst]); },
  6622. /**
  6623. * Reverse of `add`.
  6624. * @memberof PIXI.groupD8
  6625. * @param {PIXI.GD8Symmetry} rotationSecond - Second operation
  6626. * @param {PIXI.GD8Symmetry} rotationFirst - First operation
  6627. * @returns {PIXI.GD8Symmetry} Result
  6628. */
  6629. sub: function (rotationSecond, rotationFirst) { return (rotationCayley[rotationSecond][groupD8.inv(rotationFirst)]); },
  6630. /**
  6631. * Adds 180 degrees to rotation, which is a commutative
  6632. * operation.
  6633. * @memberof PIXI.groupD8
  6634. * @param {number} rotation - The number to rotate.
  6635. * @returns {number} Rotated number
  6636. */
  6637. rotate180: function (rotation) { return rotation ^ 4; },
  6638. /**
  6639. * Checks if the rotation angle is vertical, i.e. south
  6640. * or north. It doesn't work for reflections.
  6641. * @memberof PIXI.groupD8
  6642. * @param {PIXI.GD8Symmetry} rotation - The number to check.
  6643. * @returns {boolean} Whether or not the direction is vertical
  6644. */
  6645. isVertical: function (rotation) { return (rotation & 3) === 2; },
  6646. /**
  6647. * Approximates the vector `V(dx,dy)` into one of the
  6648. * eight directions provided by `groupD8`.
  6649. * @memberof PIXI.groupD8
  6650. * @param {number} dx - X-component of the vector
  6651. * @param {number} dy - Y-component of the vector
  6652. * @returns {PIXI.GD8Symmetry} Approximation of the vector into
  6653. * one of the eight symmetries.
  6654. */
  6655. byDirection: function (dx, dy) {
  6656. if (Math.abs(dx) * 2 <= Math.abs(dy)) {
  6657. if (dy >= 0) {
  6658. return groupD8.S;
  6659. }
  6660. return groupD8.N;
  6661. }
  6662. else if (Math.abs(dy) * 2 <= Math.abs(dx)) {
  6663. if (dx > 0) {
  6664. return groupD8.E;
  6665. }
  6666. return groupD8.W;
  6667. }
  6668. else if (dy > 0) {
  6669. if (dx > 0) {
  6670. return groupD8.SE;
  6671. }
  6672. return groupD8.SW;
  6673. }
  6674. else if (dx > 0) {
  6675. return groupD8.NE;
  6676. }
  6677. return groupD8.NW;
  6678. },
  6679. /**
  6680. * Helps sprite to compensate texture packer rotation.
  6681. * @memberof PIXI.groupD8
  6682. * @param {PIXI.Matrix} matrix - sprite world matrix
  6683. * @param {PIXI.GD8Symmetry} rotation - The rotation factor to use.
  6684. * @param {number} tx - sprite anchoring
  6685. * @param {number} ty - sprite anchoring
  6686. */
  6687. matrixAppendRotationInv: function (matrix, rotation, tx, ty) {
  6688. if (tx === void 0) { tx = 0; }
  6689. if (ty === void 0) { ty = 0; }
  6690. // Packer used "rotation", we use "inv(rotation)"
  6691. var mat = rotationMatrices[groupD8.inv(rotation)];
  6692. mat.tx = tx;
  6693. mat.ty = ty;
  6694. matrix.append(mat);
  6695. },
  6696. };
  6697. /**
  6698. * Transform that takes care about its versions.
  6699. * @memberof PIXI
  6700. */
  6701. var Transform = /** @class */ (function () {
  6702. function Transform() {
  6703. this.worldTransform = new Matrix();
  6704. this.localTransform = new Matrix();
  6705. this.position = new ObservablePoint(this.onChange, this, 0, 0);
  6706. this.scale = new ObservablePoint(this.onChange, this, 1, 1);
  6707. this.pivot = new ObservablePoint(this.onChange, this, 0, 0);
  6708. this.skew = new ObservablePoint(this.updateSkew, this, 0, 0);
  6709. this._rotation = 0;
  6710. this._cx = 1;
  6711. this._sx = 0;
  6712. this._cy = 0;
  6713. this._sy = 1;
  6714. this._localID = 0;
  6715. this._currentLocalID = 0;
  6716. this._worldID = 0;
  6717. this._parentID = 0;
  6718. }
  6719. /** Called when a value changes. */
  6720. Transform.prototype.onChange = function () {
  6721. this._localID++;
  6722. };
  6723. /** Called when the skew or the rotation changes. */
  6724. Transform.prototype.updateSkew = function () {
  6725. this._cx = Math.cos(this._rotation + this.skew.y);
  6726. this._sx = Math.sin(this._rotation + this.skew.y);
  6727. this._cy = -Math.sin(this._rotation - this.skew.x); // cos, added PI/2
  6728. this._sy = Math.cos(this._rotation - this.skew.x); // sin, added PI/2
  6729. this._localID++;
  6730. };
  6731. Transform.prototype.toString = function () {
  6732. return "[@pixi/math:Transform "
  6733. + ("position=(" + this.position.x + ", " + this.position.y + ") ")
  6734. + ("rotation=" + this.rotation + " ")
  6735. + ("scale=(" + this.scale.x + ", " + this.scale.y + ") ")
  6736. + ("skew=(" + this.skew.x + ", " + this.skew.y + ") ")
  6737. + "]";
  6738. };
  6739. /** Updates the local transformation matrix. */
  6740. Transform.prototype.updateLocalTransform = function () {
  6741. var lt = this.localTransform;
  6742. if (this._localID !== this._currentLocalID) {
  6743. // get the matrix values of the displayobject based on its transform properties..
  6744. lt.a = this._cx * this.scale.x;
  6745. lt.b = this._sx * this.scale.x;
  6746. lt.c = this._cy * this.scale.y;
  6747. lt.d = this._sy * this.scale.y;
  6748. lt.tx = this.position.x - ((this.pivot.x * lt.a) + (this.pivot.y * lt.c));
  6749. lt.ty = this.position.y - ((this.pivot.x * lt.b) + (this.pivot.y * lt.d));
  6750. this._currentLocalID = this._localID;
  6751. // force an update..
  6752. this._parentID = -1;
  6753. }
  6754. };
  6755. /**
  6756. * Updates the local and the world transformation matrices.
  6757. * @param parentTransform - The parent transform
  6758. */
  6759. Transform.prototype.updateTransform = function (parentTransform) {
  6760. var lt = this.localTransform;
  6761. if (this._localID !== this._currentLocalID) {
  6762. // get the matrix values of the displayobject based on its transform properties..
  6763. lt.a = this._cx * this.scale.x;
  6764. lt.b = this._sx * this.scale.x;
  6765. lt.c = this._cy * this.scale.y;
  6766. lt.d = this._sy * this.scale.y;
  6767. lt.tx = this.position.x - ((this.pivot.x * lt.a) + (this.pivot.y * lt.c));
  6768. lt.ty = this.position.y - ((this.pivot.x * lt.b) + (this.pivot.y * lt.d));
  6769. this._currentLocalID = this._localID;
  6770. // force an update..
  6771. this._parentID = -1;
  6772. }
  6773. if (this._parentID !== parentTransform._worldID) {
  6774. // concat the parent matrix with the objects transform.
  6775. var pt = parentTransform.worldTransform;
  6776. var wt = this.worldTransform;
  6777. wt.a = (lt.a * pt.a) + (lt.b * pt.c);
  6778. wt.b = (lt.a * pt.b) + (lt.b * pt.d);
  6779. wt.c = (lt.c * pt.a) + (lt.d * pt.c);
  6780. wt.d = (lt.c * pt.b) + (lt.d * pt.d);
  6781. wt.tx = (lt.tx * pt.a) + (lt.ty * pt.c) + pt.tx;
  6782. wt.ty = (lt.tx * pt.b) + (lt.ty * pt.d) + pt.ty;
  6783. this._parentID = parentTransform._worldID;
  6784. // update the id of the transform..
  6785. this._worldID++;
  6786. }
  6787. };
  6788. /**
  6789. * Decomposes a matrix and sets the transforms properties based on it.
  6790. * @param matrix - The matrix to decompose
  6791. */
  6792. Transform.prototype.setFromMatrix = function (matrix) {
  6793. matrix.decompose(this);
  6794. this._localID++;
  6795. };
  6796. Object.defineProperty(Transform.prototype, "rotation", {
  6797. /** The rotation of the object in radians. */
  6798. get: function () {
  6799. return this._rotation;
  6800. },
  6801. set: function (value) {
  6802. if (this._rotation !== value) {
  6803. this._rotation = value;
  6804. this.updateSkew();
  6805. }
  6806. },
  6807. enumerable: false,
  6808. configurable: true
  6809. });
  6810. /** A default (identity) transform. */
  6811. Transform.IDENTITY = new Transform();
  6812. return Transform;
  6813. }());
  6814. /*!
  6815. * @pixi/display - v6.5.10
  6816. * Compiled Thu, 06 Jul 2023 15:25:11 UTC
  6817. *
  6818. * @pixi/display is licensed under the MIT License.
  6819. * http://www.opensource.org/licenses/mit-license
  6820. */
  6821. /**
  6822. * Sets the default value for the container property 'sortableChildren'.
  6823. * If set to true, the container will sort its children by zIndex value
  6824. * when updateTransform() is called, or manually if sortChildren() is called.
  6825. *
  6826. * This actually changes the order of elements in the array, so should be treated
  6827. * as a basic solution that is not performant compared to other solutions,
  6828. * such as @link https://github.com/pixijs/pixi-display
  6829. *
  6830. * Also be aware of that this may not work nicely with the addChildAt() function,
  6831. * as the zIndex sorting may cause the child to automatically sorted to another position.
  6832. * @static
  6833. * @constant
  6834. * @name SORTABLE_CHILDREN
  6835. * @memberof PIXI.settings
  6836. * @type {boolean}
  6837. * @default false
  6838. */
  6839. settings.SORTABLE_CHILDREN = false;
  6840. /**
  6841. * 'Builder' pattern for bounds rectangles.
  6842. *
  6843. * This could be called an Axis-Aligned Bounding Box.
  6844. * It is not an actual shape. It is a mutable thing; no 'EMPTY' or those kind of problems.
  6845. * @memberof PIXI
  6846. */
  6847. var Bounds = /** @class */ (function () {
  6848. function Bounds() {
  6849. this.minX = Infinity;
  6850. this.minY = Infinity;
  6851. this.maxX = -Infinity;
  6852. this.maxY = -Infinity;
  6853. this.rect = null;
  6854. this.updateID = -1;
  6855. }
  6856. /**
  6857. * Checks if bounds are empty.
  6858. * @returns - True if empty.
  6859. */
  6860. Bounds.prototype.isEmpty = function () {
  6861. return this.minX > this.maxX || this.minY > this.maxY;
  6862. };
  6863. /** Clears the bounds and resets. */
  6864. Bounds.prototype.clear = function () {
  6865. this.minX = Infinity;
  6866. this.minY = Infinity;
  6867. this.maxX = -Infinity;
  6868. this.maxY = -Infinity;
  6869. };
  6870. /**
  6871. * Can return Rectangle.EMPTY constant, either construct new rectangle, either use your rectangle
  6872. * It is not guaranteed that it will return tempRect
  6873. * @param rect - Temporary object will be used if AABB is not empty
  6874. * @returns - A rectangle of the bounds
  6875. */
  6876. Bounds.prototype.getRectangle = function (rect) {
  6877. if (this.minX > this.maxX || this.minY > this.maxY) {
  6878. return Rectangle.EMPTY;
  6879. }
  6880. rect = rect || new Rectangle(0, 0, 1, 1);
  6881. rect.x = this.minX;
  6882. rect.y = this.minY;
  6883. rect.width = this.maxX - this.minX;
  6884. rect.height = this.maxY - this.minY;
  6885. return rect;
  6886. };
  6887. /**
  6888. * This function should be inlined when its possible.
  6889. * @param point - The point to add.
  6890. */
  6891. Bounds.prototype.addPoint = function (point) {
  6892. this.minX = Math.min(this.minX, point.x);
  6893. this.maxX = Math.max(this.maxX, point.x);
  6894. this.minY = Math.min(this.minY, point.y);
  6895. this.maxY = Math.max(this.maxY, point.y);
  6896. };
  6897. /**
  6898. * Adds a point, after transformed. This should be inlined when its possible.
  6899. * @param matrix
  6900. * @param point
  6901. */
  6902. Bounds.prototype.addPointMatrix = function (matrix, point) {
  6903. var a = matrix.a, b = matrix.b, c = matrix.c, d = matrix.d, tx = matrix.tx, ty = matrix.ty;
  6904. var x = (a * point.x) + (c * point.y) + tx;
  6905. var y = (b * point.x) + (d * point.y) + ty;
  6906. this.minX = Math.min(this.minX, x);
  6907. this.maxX = Math.max(this.maxX, x);
  6908. this.minY = Math.min(this.minY, y);
  6909. this.maxY = Math.max(this.maxY, y);
  6910. };
  6911. /**
  6912. * Adds a quad, not transformed
  6913. * @param vertices - The verts to add.
  6914. */
  6915. Bounds.prototype.addQuad = function (vertices) {
  6916. var minX = this.minX;
  6917. var minY = this.minY;
  6918. var maxX = this.maxX;
  6919. var maxY = this.maxY;
  6920. var x = vertices[0];
  6921. var y = vertices[1];
  6922. minX = x < minX ? x : minX;
  6923. minY = y < minY ? y : minY;
  6924. maxX = x > maxX ? x : maxX;
  6925. maxY = y > maxY ? y : maxY;
  6926. x = vertices[2];
  6927. y = vertices[3];
  6928. minX = x < minX ? x : minX;
  6929. minY = y < minY ? y : minY;
  6930. maxX = x > maxX ? x : maxX;
  6931. maxY = y > maxY ? y : maxY;
  6932. x = vertices[4];
  6933. y = vertices[5];
  6934. minX = x < minX ? x : minX;
  6935. minY = y < minY ? y : minY;
  6936. maxX = x > maxX ? x : maxX;
  6937. maxY = y > maxY ? y : maxY;
  6938. x = vertices[6];
  6939. y = vertices[7];
  6940. minX = x < minX ? x : minX;
  6941. minY = y < minY ? y : minY;
  6942. maxX = x > maxX ? x : maxX;
  6943. maxY = y > maxY ? y : maxY;
  6944. this.minX = minX;
  6945. this.minY = minY;
  6946. this.maxX = maxX;
  6947. this.maxY = maxY;
  6948. };
  6949. /**
  6950. * Adds sprite frame, transformed.
  6951. * @param transform - transform to apply
  6952. * @param x0 - left X of frame
  6953. * @param y0 - top Y of frame
  6954. * @param x1 - right X of frame
  6955. * @param y1 - bottom Y of frame
  6956. */
  6957. Bounds.prototype.addFrame = function (transform, x0, y0, x1, y1) {
  6958. this.addFrameMatrix(transform.worldTransform, x0, y0, x1, y1);
  6959. };
  6960. /**
  6961. * Adds sprite frame, multiplied by matrix
  6962. * @param matrix - matrix to apply
  6963. * @param x0 - left X of frame
  6964. * @param y0 - top Y of frame
  6965. * @param x1 - right X of frame
  6966. * @param y1 - bottom Y of frame
  6967. */
  6968. Bounds.prototype.addFrameMatrix = function (matrix, x0, y0, x1, y1) {
  6969. var a = matrix.a;
  6970. var b = matrix.b;
  6971. var c = matrix.c;
  6972. var d = matrix.d;
  6973. var tx = matrix.tx;
  6974. var ty = matrix.ty;
  6975. var minX = this.minX;
  6976. var minY = this.minY;
  6977. var maxX = this.maxX;
  6978. var maxY = this.maxY;
  6979. var x = (a * x0) + (c * y0) + tx;
  6980. var y = (b * x0) + (d * y0) + ty;
  6981. minX = x < minX ? x : minX;
  6982. minY = y < minY ? y : minY;
  6983. maxX = x > maxX ? x : maxX;
  6984. maxY = y > maxY ? y : maxY;
  6985. x = (a * x1) + (c * y0) + tx;
  6986. y = (b * x1) + (d * y0) + ty;
  6987. minX = x < minX ? x : minX;
  6988. minY = y < minY ? y : minY;
  6989. maxX = x > maxX ? x : maxX;
  6990. maxY = y > maxY ? y : maxY;
  6991. x = (a * x0) + (c * y1) + tx;
  6992. y = (b * x0) + (d * y1) + ty;
  6993. minX = x < minX ? x : minX;
  6994. minY = y < minY ? y : minY;
  6995. maxX = x > maxX ? x : maxX;
  6996. maxY = y > maxY ? y : maxY;
  6997. x = (a * x1) + (c * y1) + tx;
  6998. y = (b * x1) + (d * y1) + ty;
  6999. minX = x < minX ? x : minX;
  7000. minY = y < minY ? y : minY;
  7001. maxX = x > maxX ? x : maxX;
  7002. maxY = y > maxY ? y : maxY;
  7003. this.minX = minX;
  7004. this.minY = minY;
  7005. this.maxX = maxX;
  7006. this.maxY = maxY;
  7007. };
  7008. /**
  7009. * Adds screen vertices from array
  7010. * @param vertexData - calculated vertices
  7011. * @param beginOffset - begin offset
  7012. * @param endOffset - end offset, excluded
  7013. */
  7014. Bounds.prototype.addVertexData = function (vertexData, beginOffset, endOffset) {
  7015. var minX = this.minX;
  7016. var minY = this.minY;
  7017. var maxX = this.maxX;
  7018. var maxY = this.maxY;
  7019. for (var i = beginOffset; i < endOffset; i += 2) {
  7020. var x = vertexData[i];
  7021. var y = vertexData[i + 1];
  7022. minX = x < minX ? x : minX;
  7023. minY = y < minY ? y : minY;
  7024. maxX = x > maxX ? x : maxX;
  7025. maxY = y > maxY ? y : maxY;
  7026. }
  7027. this.minX = minX;
  7028. this.minY = minY;
  7029. this.maxX = maxX;
  7030. this.maxY = maxY;
  7031. };
  7032. /**
  7033. * Add an array of mesh vertices
  7034. * @param transform - mesh transform
  7035. * @param vertices - mesh coordinates in array
  7036. * @param beginOffset - begin offset
  7037. * @param endOffset - end offset, excluded
  7038. */
  7039. Bounds.prototype.addVertices = function (transform, vertices, beginOffset, endOffset) {
  7040. this.addVerticesMatrix(transform.worldTransform, vertices, beginOffset, endOffset);
  7041. };
  7042. /**
  7043. * Add an array of mesh vertices.
  7044. * @param matrix - mesh matrix
  7045. * @param vertices - mesh coordinates in array
  7046. * @param beginOffset - begin offset
  7047. * @param endOffset - end offset, excluded
  7048. * @param padX - x padding
  7049. * @param padY - y padding
  7050. */
  7051. Bounds.prototype.addVerticesMatrix = function (matrix, vertices, beginOffset, endOffset, padX, padY) {
  7052. if (padX === void 0) { padX = 0; }
  7053. if (padY === void 0) { padY = padX; }
  7054. var a = matrix.a;
  7055. var b = matrix.b;
  7056. var c = matrix.c;
  7057. var d = matrix.d;
  7058. var tx = matrix.tx;
  7059. var ty = matrix.ty;
  7060. var minX = this.minX;
  7061. var minY = this.minY;
  7062. var maxX = this.maxX;
  7063. var maxY = this.maxY;
  7064. for (var i = beginOffset; i < endOffset; i += 2) {
  7065. var rawX = vertices[i];
  7066. var rawY = vertices[i + 1];
  7067. var x = (a * rawX) + (c * rawY) + tx;
  7068. var y = (d * rawY) + (b * rawX) + ty;
  7069. minX = Math.min(minX, x - padX);
  7070. maxX = Math.max(maxX, x + padX);
  7071. minY = Math.min(minY, y - padY);
  7072. maxY = Math.max(maxY, y + padY);
  7073. }
  7074. this.minX = minX;
  7075. this.minY = minY;
  7076. this.maxX = maxX;
  7077. this.maxY = maxY;
  7078. };
  7079. /**
  7080. * Adds other {@link Bounds}.
  7081. * @param bounds - The Bounds to be added
  7082. */
  7083. Bounds.prototype.addBounds = function (bounds) {
  7084. var minX = this.minX;
  7085. var minY = this.minY;
  7086. var maxX = this.maxX;
  7087. var maxY = this.maxY;
  7088. this.minX = bounds.minX < minX ? bounds.minX : minX;
  7089. this.minY = bounds.minY < minY ? bounds.minY : minY;
  7090. this.maxX = bounds.maxX > maxX ? bounds.maxX : maxX;
  7091. this.maxY = bounds.maxY > maxY ? bounds.maxY : maxY;
  7092. };
  7093. /**
  7094. * Adds other Bounds, masked with Bounds.
  7095. * @param bounds - The Bounds to be added.
  7096. * @param mask - TODO
  7097. */
  7098. Bounds.prototype.addBoundsMask = function (bounds, mask) {
  7099. var _minX = bounds.minX > mask.minX ? bounds.minX : mask.minX;
  7100. var _minY = bounds.minY > mask.minY ? bounds.minY : mask.minY;
  7101. var _maxX = bounds.maxX < mask.maxX ? bounds.maxX : mask.maxX;
  7102. var _maxY = bounds.maxY < mask.maxY ? bounds.maxY : mask.maxY;
  7103. if (_minX <= _maxX && _minY <= _maxY) {
  7104. var minX = this.minX;
  7105. var minY = this.minY;
  7106. var maxX = this.maxX;
  7107. var maxY = this.maxY;
  7108. this.minX = _minX < minX ? _minX : minX;
  7109. this.minY = _minY < minY ? _minY : minY;
  7110. this.maxX = _maxX > maxX ? _maxX : maxX;
  7111. this.maxY = _maxY > maxY ? _maxY : maxY;
  7112. }
  7113. };
  7114. /**
  7115. * Adds other Bounds, multiplied by matrix. Bounds shouldn't be empty.
  7116. * @param bounds - other bounds
  7117. * @param matrix - multiplicator
  7118. */
  7119. Bounds.prototype.addBoundsMatrix = function (bounds, matrix) {
  7120. this.addFrameMatrix(matrix, bounds.minX, bounds.minY, bounds.maxX, bounds.maxY);
  7121. };
  7122. /**
  7123. * Adds other Bounds, masked with Rectangle.
  7124. * @param bounds - TODO
  7125. * @param area - TODO
  7126. */
  7127. Bounds.prototype.addBoundsArea = function (bounds, area) {
  7128. var _minX = bounds.minX > area.x ? bounds.minX : area.x;
  7129. var _minY = bounds.minY > area.y ? bounds.minY : area.y;
  7130. var _maxX = bounds.maxX < area.x + area.width ? bounds.maxX : (area.x + area.width);
  7131. var _maxY = bounds.maxY < area.y + area.height ? bounds.maxY : (area.y + area.height);
  7132. if (_minX <= _maxX && _minY <= _maxY) {
  7133. var minX = this.minX;
  7134. var minY = this.minY;
  7135. var maxX = this.maxX;
  7136. var maxY = this.maxY;
  7137. this.minX = _minX < minX ? _minX : minX;
  7138. this.minY = _minY < minY ? _minY : minY;
  7139. this.maxX = _maxX > maxX ? _maxX : maxX;
  7140. this.maxY = _maxY > maxY ? _maxY : maxY;
  7141. }
  7142. };
  7143. /**
  7144. * Pads bounds object, making it grow in all directions.
  7145. * If paddingY is omitted, both paddingX and paddingY will be set to paddingX.
  7146. * @param paddingX - The horizontal padding amount.
  7147. * @param paddingY - The vertical padding amount.
  7148. */
  7149. Bounds.prototype.pad = function (paddingX, paddingY) {
  7150. if (paddingX === void 0) { paddingX = 0; }
  7151. if (paddingY === void 0) { paddingY = paddingX; }
  7152. if (!this.isEmpty()) {
  7153. this.minX -= paddingX;
  7154. this.maxX += paddingX;
  7155. this.minY -= paddingY;
  7156. this.maxY += paddingY;
  7157. }
  7158. };
  7159. /**
  7160. * Adds padded frame. (x0, y0) should be strictly less than (x1, y1)
  7161. * @param x0 - left X of frame
  7162. * @param y0 - top Y of frame
  7163. * @param x1 - right X of frame
  7164. * @param y1 - bottom Y of frame
  7165. * @param padX - padding X
  7166. * @param padY - padding Y
  7167. */
  7168. Bounds.prototype.addFramePad = function (x0, y0, x1, y1, padX, padY) {
  7169. x0 -= padX;
  7170. y0 -= padY;
  7171. x1 += padX;
  7172. y1 += padY;
  7173. this.minX = this.minX < x0 ? this.minX : x0;
  7174. this.maxX = this.maxX > x1 ? this.maxX : x1;
  7175. this.minY = this.minY < y0 ? this.minY : y0;
  7176. this.maxY = this.maxY > y1 ? this.maxY : y1;
  7177. };
  7178. return Bounds;
  7179. }());
  7180. /*! *****************************************************************************
  7181. Copyright (c) Microsoft Corporation.
  7182. Permission to use, copy, modify, and/or distribute this software for any
  7183. purpose with or without fee is hereby granted.
  7184. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  7185. REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
  7186. AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  7187. INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
  7188. LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
  7189. OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
  7190. PERFORMANCE OF THIS SOFTWARE.
  7191. ***************************************************************************** */
  7192. /* global Reflect, Promise */
  7193. var extendStatics$j = function(d, b) {
  7194. extendStatics$j = Object.setPrototypeOf ||
  7195. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  7196. function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } };
  7197. return extendStatics$j(d, b);
  7198. };
  7199. function __extends$j(d, b) {
  7200. extendStatics$j(d, b);
  7201. function __() { this.constructor = d; }
  7202. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  7203. }
  7204. /**
  7205. * The base class for all objects that are rendered on the screen.
  7206. *
  7207. * This is an abstract class and can not be used on its own; rather it should be extended.
  7208. *
  7209. * ## Display objects implemented in PixiJS
  7210. *
  7211. * | Display Object | Description |
  7212. * | ------------------------------- | --------------------------------------------------------------------- |
  7213. * | {@link PIXI.Container} | Adds support for `children` to DisplayObject |
  7214. * | {@link PIXI.Graphics} | Shape-drawing display object similar to the Canvas API |
  7215. * | {@link PIXI.Sprite} | Draws textures (i.e. images) |
  7216. * | {@link PIXI.Text} | Draws text using the Canvas API internally |
  7217. * | {@link PIXI.BitmapText} | More scaleable solution for text rendering, reusing glyph textures |
  7218. * | {@link PIXI.TilingSprite} | Draws textures/images in a tiled fashion |
  7219. * | {@link PIXI.AnimatedSprite} | Draws an animation of multiple images |
  7220. * | {@link PIXI.Mesh} | Provides a lower-level API for drawing meshes with custom data |
  7221. * | {@link PIXI.NineSlicePlane} | Mesh-related |
  7222. * | {@link PIXI.SimpleMesh} | v4-compatible mesh |
  7223. * | {@link PIXI.SimplePlane} | Mesh-related |
  7224. * | {@link PIXI.SimpleRope} | Mesh-related |
  7225. *
  7226. * ## Transforms
  7227. *
  7228. * The [transform]{@link DisplayObject#transform} of a display object describes the projection from its
  7229. * local coordinate space to its parent's local coordinate space. The following properties are derived
  7230. * from the transform:
  7231. *
  7232. * <table>
  7233. * <thead>
  7234. * <tr>
  7235. * <th>Property</th>
  7236. * <th>Description</th>
  7237. * </tr>
  7238. * </thead>
  7239. * <tbody>
  7240. * <tr>
  7241. * <td>[pivot]{@link PIXI.DisplayObject#pivot}</td>
  7242. * <td>
  7243. * Invariant under rotation, scaling, and skewing. The projection of into the parent's space of the pivot
  7244. * is equal to position, regardless of the other three transformations. In other words, It is the center of
  7245. * rotation, scaling, and skewing.
  7246. * </td>
  7247. * </tr>
  7248. * <tr>
  7249. * <td>[position]{@link PIXI.DisplayObject#position}</td>
  7250. * <td>
  7251. * Translation. This is the position of the [pivot]{@link PIXI.DisplayObject#pivot} in the parent's local
  7252. * space. The default value of the pivot is the origin (0,0). If the top-left corner of your display object
  7253. * is (0,0) in its local space, then the position will be its top-left corner in the parent's local space.
  7254. * </td>
  7255. * </tr>
  7256. * <tr>
  7257. * <td>[scale]{@link PIXI.DisplayObject#scale}</td>
  7258. * <td>
  7259. * Scaling. This will stretch (or compress) the display object's projection. The scale factors are along the
  7260. * local coordinate axes. In other words, the display object is scaled before rotated or skewed. The center
  7261. * of scaling is the [pivot]{@link PIXI.DisplayObject#pivot}.
  7262. * </td>
  7263. * </tr>
  7264. * <tr>
  7265. * <td>[rotation]{@link PIXI.DisplayObject#rotation}</td>
  7266. * <td>
  7267. * Rotation. This will rotate the display object's projection by this angle (in radians).
  7268. * </td>
  7269. * </tr>
  7270. * <tr>
  7271. * <td>[skew]{@link PIXI.DisplayObject#skew}</td>
  7272. * <td>
  7273. * <p>Skewing. This can be used to deform a rectangular display object into a parallelogram.</p>
  7274. * <p>
  7275. * In PixiJS, skew has a slightly different behaviour than the conventional meaning. It can be
  7276. * thought of the net rotation applied to the coordinate axes (separately). For example, if "skew.x" is
  7277. * ⍺ and "skew.y" is β, then the line x = 0 will be rotated by ⍺ (y = -x*cot⍺) and the line y = 0 will be
  7278. * rotated by β (y = x*tanβ). A line y = x*tanϴ (i.e. a line at angle ϴ to the x-axis in local-space) will
  7279. * be rotated by an angle between ⍺ and β.
  7280. * </p>
  7281. * <p>
  7282. * It can be observed that if skew is applied equally to both axes, then it will be equivalent to applying
  7283. * a rotation. Indeed, if "skew.x" = -ϴ and "skew.y" = ϴ, it will produce an equivalent of "rotation" = ϴ.
  7284. * </p>
  7285. * <p>
  7286. * Another quite interesting observation is that "skew.x", "skew.y", rotation are communtative operations. Indeed,
  7287. * because rotation is essentially a careful combination of the two.
  7288. * </p>
  7289. * </td>
  7290. * </tr>
  7291. * <tr>
  7292. * <td>angle</td>
  7293. * <td>Rotation. This is an alias for [rotation]{@link PIXI.DisplayObject#rotation}, but in degrees.</td>
  7294. * </tr>
  7295. * <tr>
  7296. * <td>x</td>
  7297. * <td>Translation. This is an alias for position.x!</td>
  7298. * </tr>
  7299. * <tr>
  7300. * <td>y</td>
  7301. * <td>Translation. This is an alias for position.y!</td>
  7302. * </tr>
  7303. * <tr>
  7304. * <td>width</td>
  7305. * <td>
  7306. * Implemented in [Container]{@link PIXI.Container}. Scaling. The width property calculates scale.x by dividing
  7307. * the "requested" width by the local bounding box width. It is indirectly an abstraction over scale.x, and there
  7308. * is no concept of user-defined width.
  7309. * </td>
  7310. * </tr>
  7311. * <tr>
  7312. * <td>height</td>
  7313. * <td>
  7314. * Implemented in [Container]{@link PIXI.Container}. Scaling. The height property calculates scale.y by dividing
  7315. * the "requested" height by the local bounding box height. It is indirectly an abstraction over scale.y, and there
  7316. * is no concept of user-defined height.
  7317. * </td>
  7318. * </tr>
  7319. * </tbody>
  7320. * </table>
  7321. *
  7322. * ## Bounds
  7323. *
  7324. * The bounds of a display object is defined by the minimum axis-aligned rectangle in world space that can fit
  7325. * around it. The abstract `calculateBounds` method is responsible for providing it (and it should use the
  7326. * `worldTransform` to calculate in world space).
  7327. *
  7328. * There are a few additional types of bounding boxes:
  7329. *
  7330. * | Bounds | Description |
  7331. * | --------------------- | ---------------------------------------------------------------------------------------- |
  7332. * | World Bounds | This is synonymous is the regular bounds described above. See `getBounds()`. |
  7333. * | Local Bounds | This the axis-aligned bounding box in the parent's local space. See `getLocalBounds()`. |
  7334. * | Render Bounds | The bounds, but including extra rendering effects like filter padding. |
  7335. * | Projected Bounds | The bounds of the projected display object onto the screen. Usually equals world bounds. |
  7336. * | Relative Bounds | The bounds of a display object when projected onto a ancestor's (or parent's) space. |
  7337. * | Natural Bounds | The bounds of an object in its own local space (not parent's space, like in local bounds)|
  7338. * | Content Bounds | The natural bounds when excluding all children of a `Container`. |
  7339. *
  7340. * ### calculateBounds
  7341. *
  7342. * [Container]{@link Container} already implements `calculateBounds` in a manner that includes children.
  7343. *
  7344. * But for a non-Container display object, the `calculateBounds` method must be overridden in order for `getBounds` and
  7345. * `getLocalBounds` to work. This method must write the bounds into `this._bounds`.
  7346. *
  7347. * Generally, the following technique works for most simple cases: take the list of points
  7348. * forming the "hull" of the object (i.e. outline of the object's shape), and then add them
  7349. * using {@link PIXI.Bounds#addPointMatrix}.
  7350. *
  7351. * ```js
  7352. * calculateBounds(): void
  7353. * {
  7354. * const points = [...];
  7355. *
  7356. * for (let i = 0, j = points.length; i < j; i++)
  7357. * {
  7358. * this._bounds.addPointMatrix(this.worldTransform, points[i]);
  7359. * }
  7360. * }
  7361. * ```
  7362. *
  7363. * You can optimize this for a large number of points by using {@link PIXI.Bounds#addVerticesMatrix} to pass them
  7364. * in one array together.
  7365. *
  7366. * ## Alpha
  7367. *
  7368. * This alpha sets a display object's **relative opacity** w.r.t its parent. For example, if the alpha of a display
  7369. * object is 0.5 and its parent's alpha is 0.5, then it will be rendered with 25% opacity (assuming alpha is not
  7370. * applied on any ancestor further up the chain).
  7371. *
  7372. * The alpha with which the display object will be rendered is called the [worldAlpha]{@link PIXI.DisplayObject#worldAlpha}.
  7373. *
  7374. * ## Renderable vs Visible
  7375. *
  7376. * The `renderable` and `visible` properties can be used to prevent a display object from being rendered to the
  7377. * screen. However, there is a subtle difference between the two. When using `renderable`, the transforms of the display
  7378. * object (and its children subtree) will continue to be calculated. When using `visible`, the transforms will not
  7379. * be calculated.
  7380. *
  7381. * It is recommended that applications use the `renderable` property for culling. See
  7382. * [@pixi-essentials/cull]{@link https://www.npmjs.com/package/@pixi-essentials/cull} or
  7383. * [pixi-cull]{@link https://www.npmjs.com/package/pixi-cull} for more details.
  7384. *
  7385. * Otherwise, to prevent an object from rendering in the general-purpose sense - `visible` is the property to use. This
  7386. * one is also better in terms of performance.
  7387. * @memberof PIXI
  7388. */
  7389. var DisplayObject = /** @class */ (function (_super) {
  7390. __extends$j(DisplayObject, _super);
  7391. function DisplayObject() {
  7392. var _this = _super.call(this) || this;
  7393. _this.tempDisplayObjectParent = null;
  7394. // TODO: need to create Transform from factory
  7395. _this.transform = new Transform();
  7396. _this.alpha = 1;
  7397. _this.visible = true;
  7398. _this.renderable = true;
  7399. _this.cullable = false;
  7400. _this.cullArea = null;
  7401. _this.parent = null;
  7402. _this.worldAlpha = 1;
  7403. _this._lastSortedIndex = 0;
  7404. _this._zIndex = 0;
  7405. _this.filterArea = null;
  7406. _this.filters = null;
  7407. _this._enabledFilters = null;
  7408. _this._bounds = new Bounds();
  7409. _this._localBounds = null;
  7410. _this._boundsID = 0;
  7411. _this._boundsRect = null;
  7412. _this._localBoundsRect = null;
  7413. _this._mask = null;
  7414. _this._maskRefCount = 0;
  7415. _this._destroyed = false;
  7416. _this.isSprite = false;
  7417. _this.isMask = false;
  7418. return _this;
  7419. }
  7420. /**
  7421. * Mixes all enumerable properties and methods from a source object to DisplayObject.
  7422. * @param source - The source of properties and methods to mix in.
  7423. */
  7424. DisplayObject.mixin = function (source) {
  7425. // in ES8/ES2017, this would be really easy:
  7426. // Object.defineProperties(DisplayObject.prototype, Object.getOwnPropertyDescriptors(source));
  7427. // get all the enumerable property keys
  7428. var keys = Object.keys(source);
  7429. // loop through properties
  7430. for (var i = 0; i < keys.length; ++i) {
  7431. var propertyName = keys[i];
  7432. // Set the property using the property descriptor - this works for accessors and normal value properties
  7433. Object.defineProperty(DisplayObject.prototype, propertyName, Object.getOwnPropertyDescriptor(source, propertyName));
  7434. }
  7435. };
  7436. Object.defineProperty(DisplayObject.prototype, "destroyed", {
  7437. /**
  7438. * Fired when this DisplayObject is added to a Container.
  7439. * @instance
  7440. * @event added
  7441. * @param {PIXI.Container} container - The container added to.
  7442. */
  7443. /**
  7444. * Fired when this DisplayObject is removed from a Container.
  7445. * @instance
  7446. * @event removed
  7447. * @param {PIXI.Container} container - The container removed from.
  7448. */
  7449. /**
  7450. * Fired when this DisplayObject is destroyed. This event is emitted once
  7451. * destroy is finished.
  7452. * @instance
  7453. * @event destroyed
  7454. */
  7455. /** Readonly flag for destroyed display objects. */
  7456. get: function () {
  7457. return this._destroyed;
  7458. },
  7459. enumerable: false,
  7460. configurable: true
  7461. });
  7462. /** Recursively updates transform of all objects from the root to this one internal function for toLocal() */
  7463. DisplayObject.prototype._recursivePostUpdateTransform = function () {
  7464. if (this.parent) {
  7465. this.parent._recursivePostUpdateTransform();
  7466. this.transform.updateTransform(this.parent.transform);
  7467. }
  7468. else {
  7469. this.transform.updateTransform(this._tempDisplayObjectParent.transform);
  7470. }
  7471. };
  7472. /** Updates the object transform for rendering. TODO - Optimization pass! */
  7473. DisplayObject.prototype.updateTransform = function () {
  7474. this._boundsID++;
  7475. this.transform.updateTransform(this.parent.transform);
  7476. // multiply the alphas..
  7477. this.worldAlpha = this.alpha * this.parent.worldAlpha;
  7478. };
  7479. /**
  7480. * Calculates and returns the (world) bounds of the display object as a [Rectangle]{@link PIXI.Rectangle}.
  7481. *
  7482. * This method is expensive on containers with a large subtree (like the stage). This is because the bounds
  7483. * of a container depend on its children's bounds, which recursively causes all bounds in the subtree to
  7484. * be recalculated. The upside, however, is that calling `getBounds` once on a container will indeed update
  7485. * the bounds of all children (the whole subtree, in fact). This side effect should be exploited by using
  7486. * `displayObject._bounds.getRectangle()` when traversing through all the bounds in a scene graph. Otherwise,
  7487. * calling `getBounds` on each object in a subtree will cause the total cost to increase quadratically as
  7488. * its height increases.
  7489. *
  7490. * The transforms of all objects in a container's **subtree** and of all **ancestors** are updated.
  7491. * The world bounds of all display objects in a container's **subtree** will also be recalculated.
  7492. *
  7493. * The `_bounds` object stores the last calculation of the bounds. You can use to entirely skip bounds
  7494. * calculation if needed.
  7495. *
  7496. * ```js
  7497. * const lastCalculatedBounds = displayObject._bounds.getRectangle(optionalRect);
  7498. * ```
  7499. *
  7500. * Do know that usage of `getLocalBounds` can corrupt the `_bounds` of children (the whole subtree, actually). This
  7501. * is a known issue that has not been solved. See [getLocalBounds]{@link PIXI.DisplayObject#getLocalBounds} for more
  7502. * details.
  7503. *
  7504. * `getBounds` should be called with `skipUpdate` equal to `true` in a render() call. This is because the transforms
  7505. * are guaranteed to be update-to-date. In fact, recalculating inside a render() call may cause corruption in certain
  7506. * cases.
  7507. * @param skipUpdate - Setting to `true` will stop the transforms of the scene graph from
  7508. * being updated. This means the calculation returned MAY be out of date BUT will give you a
  7509. * nice performance boost.
  7510. * @param rect - Optional rectangle to store the result of the bounds calculation.
  7511. * @returns - The minimum axis-aligned rectangle in world space that fits around this object.
  7512. */
  7513. DisplayObject.prototype.getBounds = function (skipUpdate, rect) {
  7514. if (!skipUpdate) {
  7515. if (!this.parent) {
  7516. this.parent = this._tempDisplayObjectParent;
  7517. this.updateTransform();
  7518. this.parent = null;
  7519. }
  7520. else {
  7521. this._recursivePostUpdateTransform();
  7522. this.updateTransform();
  7523. }
  7524. }
  7525. if (this._bounds.updateID !== this._boundsID) {
  7526. this.calculateBounds();
  7527. this._bounds.updateID = this._boundsID;
  7528. }
  7529. if (!rect) {
  7530. if (!this._boundsRect) {
  7531. this._boundsRect = new Rectangle();
  7532. }
  7533. rect = this._boundsRect;
  7534. }
  7535. return this._bounds.getRectangle(rect);
  7536. };
  7537. /**
  7538. * Retrieves the local bounds of the displayObject as a rectangle object.
  7539. * @param rect - Optional rectangle to store the result of the bounds calculation.
  7540. * @returns - The rectangular bounding area.
  7541. */
  7542. DisplayObject.prototype.getLocalBounds = function (rect) {
  7543. if (!rect) {
  7544. if (!this._localBoundsRect) {
  7545. this._localBoundsRect = new Rectangle();
  7546. }
  7547. rect = this._localBoundsRect;
  7548. }
  7549. if (!this._localBounds) {
  7550. this._localBounds = new Bounds();
  7551. }
  7552. var transformRef = this.transform;
  7553. var parentRef = this.parent;
  7554. this.parent = null;
  7555. this.transform = this._tempDisplayObjectParent.transform;
  7556. var worldBounds = this._bounds;
  7557. var worldBoundsID = this._boundsID;
  7558. this._bounds = this._localBounds;
  7559. var bounds = this.getBounds(false, rect);
  7560. this.parent = parentRef;
  7561. this.transform = transformRef;
  7562. this._bounds = worldBounds;
  7563. this._bounds.updateID += this._boundsID - worldBoundsID; // reflect side-effects
  7564. return bounds;
  7565. };
  7566. /**
  7567. * Calculates the global position of the display object.
  7568. * @param position - The world origin to calculate from.
  7569. * @param point - A Point object in which to store the value, optional
  7570. * (otherwise will create a new Point).
  7571. * @param skipUpdate - Should we skip the update transform.
  7572. * @returns - A point object representing the position of this object.
  7573. */
  7574. DisplayObject.prototype.toGlobal = function (position, point, skipUpdate) {
  7575. if (skipUpdate === void 0) { skipUpdate = false; }
  7576. if (!skipUpdate) {
  7577. this._recursivePostUpdateTransform();
  7578. // this parent check is for just in case the item is a root object.
  7579. // If it is we need to give it a temporary parent so that displayObjectUpdateTransform works correctly
  7580. // this is mainly to avoid a parent check in the main loop. Every little helps for performance :)
  7581. if (!this.parent) {
  7582. this.parent = this._tempDisplayObjectParent;
  7583. this.displayObjectUpdateTransform();
  7584. this.parent = null;
  7585. }
  7586. else {
  7587. this.displayObjectUpdateTransform();
  7588. }
  7589. }
  7590. // don't need to update the lot
  7591. return this.worldTransform.apply(position, point);
  7592. };
  7593. /**
  7594. * Calculates the local position of the display object relative to another point.
  7595. * @param position - The world origin to calculate from.
  7596. * @param from - The DisplayObject to calculate the global position from.
  7597. * @param point - A Point object in which to store the value, optional
  7598. * (otherwise will create a new Point).
  7599. * @param skipUpdate - Should we skip the update transform
  7600. * @returns - A point object representing the position of this object
  7601. */
  7602. DisplayObject.prototype.toLocal = function (position, from, point, skipUpdate) {
  7603. if (from) {
  7604. position = from.toGlobal(position, point, skipUpdate);
  7605. }
  7606. if (!skipUpdate) {
  7607. this._recursivePostUpdateTransform();
  7608. // this parent check is for just in case the item is a root object.
  7609. // If it is we need to give it a temporary parent so that displayObjectUpdateTransform works correctly
  7610. // this is mainly to avoid a parent check in the main loop. Every little helps for performance :)
  7611. if (!this.parent) {
  7612. this.parent = this._tempDisplayObjectParent;
  7613. this.displayObjectUpdateTransform();
  7614. this.parent = null;
  7615. }
  7616. else {
  7617. this.displayObjectUpdateTransform();
  7618. }
  7619. }
  7620. // simply apply the matrix..
  7621. return this.worldTransform.applyInverse(position, point);
  7622. };
  7623. /**
  7624. * Set the parent Container of this DisplayObject.
  7625. * @param container - The Container to add this DisplayObject to.
  7626. * @returns - The Container that this DisplayObject was added to.
  7627. */
  7628. DisplayObject.prototype.setParent = function (container) {
  7629. if (!container || !container.addChild) {
  7630. throw new Error('setParent: Argument must be a Container');
  7631. }
  7632. container.addChild(this);
  7633. return container;
  7634. };
  7635. /**
  7636. * Convenience function to set the position, scale, skew and pivot at once.
  7637. * @param x - The X position
  7638. * @param y - The Y position
  7639. * @param scaleX - The X scale value
  7640. * @param scaleY - The Y scale value
  7641. * @param rotation - The rotation
  7642. * @param skewX - The X skew value
  7643. * @param skewY - The Y skew value
  7644. * @param pivotX - The X pivot value
  7645. * @param pivotY - The Y pivot value
  7646. * @returns - The DisplayObject instance
  7647. */
  7648. DisplayObject.prototype.setTransform = function (x, y, scaleX, scaleY, rotation, skewX, skewY, pivotX, pivotY) {
  7649. if (x === void 0) { x = 0; }
  7650. if (y === void 0) { y = 0; }
  7651. if (scaleX === void 0) { scaleX = 1; }
  7652. if (scaleY === void 0) { scaleY = 1; }
  7653. if (rotation === void 0) { rotation = 0; }
  7654. if (skewX === void 0) { skewX = 0; }
  7655. if (skewY === void 0) { skewY = 0; }
  7656. if (pivotX === void 0) { pivotX = 0; }
  7657. if (pivotY === void 0) { pivotY = 0; }
  7658. this.position.x = x;
  7659. this.position.y = y;
  7660. this.scale.x = !scaleX ? 1 : scaleX;
  7661. this.scale.y = !scaleY ? 1 : scaleY;
  7662. this.rotation = rotation;
  7663. this.skew.x = skewX;
  7664. this.skew.y = skewY;
  7665. this.pivot.x = pivotX;
  7666. this.pivot.y = pivotY;
  7667. return this;
  7668. };
  7669. /**
  7670. * Base destroy method for generic display objects. This will automatically
  7671. * remove the display object from its parent Container as well as remove
  7672. * all current event listeners and internal references. Do not use a DisplayObject
  7673. * after calling `destroy()`.
  7674. * @param _options
  7675. */
  7676. DisplayObject.prototype.destroy = function (_options) {
  7677. if (this.parent) {
  7678. this.parent.removeChild(this);
  7679. }
  7680. this._destroyed = true;
  7681. this.transform = null;
  7682. this.parent = null;
  7683. this._bounds = null;
  7684. this.mask = null;
  7685. this.cullArea = null;
  7686. this.filters = null;
  7687. this.filterArea = null;
  7688. this.hitArea = null;
  7689. this.interactive = false;
  7690. this.interactiveChildren = false;
  7691. this.emit('destroyed');
  7692. this.removeAllListeners();
  7693. };
  7694. Object.defineProperty(DisplayObject.prototype, "_tempDisplayObjectParent", {
  7695. /**
  7696. * @protected
  7697. * @member {PIXI.Container}
  7698. */
  7699. get: function () {
  7700. if (this.tempDisplayObjectParent === null) {
  7701. // eslint-disable-next-line @typescript-eslint/no-use-before-define
  7702. this.tempDisplayObjectParent = new TemporaryDisplayObject();
  7703. }
  7704. return this.tempDisplayObjectParent;
  7705. },
  7706. enumerable: false,
  7707. configurable: true
  7708. });
  7709. /**
  7710. * Used in Renderer, cacheAsBitmap and other places where you call an `updateTransform` on root
  7711. *
  7712. * ```
  7713. * const cacheParent = elem.enableTempParent();
  7714. * elem.updateTransform();
  7715. * elem.disableTempParent(cacheParent);
  7716. * ```
  7717. * @returns - current parent
  7718. */
  7719. DisplayObject.prototype.enableTempParent = function () {
  7720. var myParent = this.parent;
  7721. this.parent = this._tempDisplayObjectParent;
  7722. return myParent;
  7723. };
  7724. /**
  7725. * Pair method for `enableTempParent`
  7726. * @param cacheParent - Actual parent of element
  7727. */
  7728. DisplayObject.prototype.disableTempParent = function (cacheParent) {
  7729. this.parent = cacheParent;
  7730. };
  7731. Object.defineProperty(DisplayObject.prototype, "x", {
  7732. /**
  7733. * The position of the displayObject on the x axis relative to the local coordinates of the parent.
  7734. * An alias to position.x
  7735. */
  7736. get: function () {
  7737. return this.position.x;
  7738. },
  7739. set: function (value) {
  7740. this.transform.position.x = value;
  7741. },
  7742. enumerable: false,
  7743. configurable: true
  7744. });
  7745. Object.defineProperty(DisplayObject.prototype, "y", {
  7746. /**
  7747. * The position of the displayObject on the y axis relative to the local coordinates of the parent.
  7748. * An alias to position.y
  7749. */
  7750. get: function () {
  7751. return this.position.y;
  7752. },
  7753. set: function (value) {
  7754. this.transform.position.y = value;
  7755. },
  7756. enumerable: false,
  7757. configurable: true
  7758. });
  7759. Object.defineProperty(DisplayObject.prototype, "worldTransform", {
  7760. /**
  7761. * Current transform of the object based on world (parent) factors.
  7762. * @readonly
  7763. */
  7764. get: function () {
  7765. return this.transform.worldTransform;
  7766. },
  7767. enumerable: false,
  7768. configurable: true
  7769. });
  7770. Object.defineProperty(DisplayObject.prototype, "localTransform", {
  7771. /**
  7772. * Current transform of the object based on local factors: position, scale, other stuff.
  7773. * @readonly
  7774. */
  7775. get: function () {
  7776. return this.transform.localTransform;
  7777. },
  7778. enumerable: false,
  7779. configurable: true
  7780. });
  7781. Object.defineProperty(DisplayObject.prototype, "position", {
  7782. /**
  7783. * The coordinate of the object relative to the local coordinates of the parent.
  7784. * @since 4.0.0
  7785. */
  7786. get: function () {
  7787. return this.transform.position;
  7788. },
  7789. set: function (value) {
  7790. this.transform.position.copyFrom(value);
  7791. },
  7792. enumerable: false,
  7793. configurable: true
  7794. });
  7795. Object.defineProperty(DisplayObject.prototype, "scale", {
  7796. /**
  7797. * The scale factors of this object along the local coordinate axes.
  7798. *
  7799. * The default scale is (1, 1).
  7800. * @since 4.0.0
  7801. */
  7802. get: function () {
  7803. return this.transform.scale;
  7804. },
  7805. set: function (value) {
  7806. this.transform.scale.copyFrom(value);
  7807. },
  7808. enumerable: false,
  7809. configurable: true
  7810. });
  7811. Object.defineProperty(DisplayObject.prototype, "pivot", {
  7812. /**
  7813. * The center of rotation, scaling, and skewing for this display object in its local space. The `position`
  7814. * is the projection of `pivot` in the parent's local space.
  7815. *
  7816. * By default, the pivot is the origin (0, 0).
  7817. * @since 4.0.0
  7818. */
  7819. get: function () {
  7820. return this.transform.pivot;
  7821. },
  7822. set: function (value) {
  7823. this.transform.pivot.copyFrom(value);
  7824. },
  7825. enumerable: false,
  7826. configurable: true
  7827. });
  7828. Object.defineProperty(DisplayObject.prototype, "skew", {
  7829. /**
  7830. * The skew factor for the object in radians.
  7831. * @since 4.0.0
  7832. */
  7833. get: function () {
  7834. return this.transform.skew;
  7835. },
  7836. set: function (value) {
  7837. this.transform.skew.copyFrom(value);
  7838. },
  7839. enumerable: false,
  7840. configurable: true
  7841. });
  7842. Object.defineProperty(DisplayObject.prototype, "rotation", {
  7843. /**
  7844. * The rotation of the object in radians.
  7845. * 'rotation' and 'angle' have the same effect on a display object; rotation is in radians, angle is in degrees.
  7846. */
  7847. get: function () {
  7848. return this.transform.rotation;
  7849. },
  7850. set: function (value) {
  7851. this.transform.rotation = value;
  7852. },
  7853. enumerable: false,
  7854. configurable: true
  7855. });
  7856. Object.defineProperty(DisplayObject.prototype, "angle", {
  7857. /**
  7858. * The angle of the object in degrees.
  7859. * 'rotation' and 'angle' have the same effect on a display object; rotation is in radians, angle is in degrees.
  7860. */
  7861. get: function () {
  7862. return this.transform.rotation * RAD_TO_DEG;
  7863. },
  7864. set: function (value) {
  7865. this.transform.rotation = value * DEG_TO_RAD;
  7866. },
  7867. enumerable: false,
  7868. configurable: true
  7869. });
  7870. Object.defineProperty(DisplayObject.prototype, "zIndex", {
  7871. /**
  7872. * The zIndex of the displayObject.
  7873. *
  7874. * If a container has the sortableChildren property set to true, children will be automatically
  7875. * sorted by zIndex value; a higher value will mean it will be moved towards the end of the array,
  7876. * and thus rendered on top of other display objects within the same container.
  7877. * @see PIXI.Container#sortableChildren
  7878. */
  7879. get: function () {
  7880. return this._zIndex;
  7881. },
  7882. set: function (value) {
  7883. this._zIndex = value;
  7884. if (this.parent) {
  7885. this.parent.sortDirty = true;
  7886. }
  7887. },
  7888. enumerable: false,
  7889. configurable: true
  7890. });
  7891. Object.defineProperty(DisplayObject.prototype, "worldVisible", {
  7892. /**
  7893. * Indicates if the object is globally visible.
  7894. * @readonly
  7895. */
  7896. get: function () {
  7897. var item = this;
  7898. do {
  7899. if (!item.visible) {
  7900. return false;
  7901. }
  7902. item = item.parent;
  7903. } while (item);
  7904. return true;
  7905. },
  7906. enumerable: false,
  7907. configurable: true
  7908. });
  7909. Object.defineProperty(DisplayObject.prototype, "mask", {
  7910. /**
  7911. * Sets a mask for the displayObject. A mask is an object that limits the visibility of an
  7912. * object to the shape of the mask applied to it. In PixiJS a regular mask must be a
  7913. * {@link PIXI.Graphics} or a {@link PIXI.Sprite} object. This allows for much faster masking in canvas as it
  7914. * utilities shape clipping. Furthermore, a mask of an object must be in the subtree of its parent.
  7915. * Otherwise, `getLocalBounds` may calculate incorrect bounds, which makes the container's width and height wrong.
  7916. * To remove a mask, set this property to `null`.
  7917. *
  7918. * For sprite mask both alpha and red channel are used. Black mask is the same as transparent mask.
  7919. * @example
  7920. * const graphics = new PIXI.Graphics();
  7921. * graphics.beginFill(0xFF3300);
  7922. * graphics.drawRect(50, 250, 100, 100);
  7923. * graphics.endFill();
  7924. *
  7925. * const sprite = new PIXI.Sprite(texture);
  7926. * sprite.mask = graphics;
  7927. * @todo At the moment, PIXI.CanvasRenderer doesn't support PIXI.Sprite as mask.
  7928. */
  7929. get: function () {
  7930. return this._mask;
  7931. },
  7932. set: function (value) {
  7933. if (this._mask === value) {
  7934. return;
  7935. }
  7936. if (this._mask) {
  7937. var maskObject = (this._mask.isMaskData
  7938. ? this._mask.maskObject : this._mask);
  7939. if (maskObject) {
  7940. maskObject._maskRefCount--;
  7941. if (maskObject._maskRefCount === 0) {
  7942. maskObject.renderable = true;
  7943. maskObject.isMask = false;
  7944. }
  7945. }
  7946. }
  7947. this._mask = value;
  7948. if (this._mask) {
  7949. var maskObject = (this._mask.isMaskData
  7950. ? this._mask.maskObject : this._mask);
  7951. if (maskObject) {
  7952. if (maskObject._maskRefCount === 0) {
  7953. maskObject.renderable = false;
  7954. maskObject.isMask = true;
  7955. }
  7956. maskObject._maskRefCount++;
  7957. }
  7958. }
  7959. },
  7960. enumerable: false,
  7961. configurable: true
  7962. });
  7963. return DisplayObject;
  7964. }(eventemitter3));
  7965. /**
  7966. * @private
  7967. */
  7968. var TemporaryDisplayObject = /** @class */ (function (_super) {
  7969. __extends$j(TemporaryDisplayObject, _super);
  7970. function TemporaryDisplayObject() {
  7971. var _this = _super !== null && _super.apply(this, arguments) || this;
  7972. _this.sortDirty = null;
  7973. return _this;
  7974. }
  7975. return TemporaryDisplayObject;
  7976. }(DisplayObject));
  7977. /**
  7978. * DisplayObject default updateTransform, does not update children of container.
  7979. * Will crash if there's no parent element.
  7980. * @memberof PIXI.DisplayObject#
  7981. * @method displayObjectUpdateTransform
  7982. */
  7983. DisplayObject.prototype.displayObjectUpdateTransform = DisplayObject.prototype.updateTransform;
  7984. function sortChildren(a, b) {
  7985. if (a.zIndex === b.zIndex) {
  7986. return a._lastSortedIndex - b._lastSortedIndex;
  7987. }
  7988. return a.zIndex - b.zIndex;
  7989. }
  7990. /**
  7991. * Container is a general-purpose display object that holds children. It also adds built-in support for advanced
  7992. * rendering features like masking and filtering.
  7993. *
  7994. * It is the base class of all display objects that act as a container for other objects, including Graphics
  7995. * and Sprite.
  7996. *
  7997. * ```js
  7998. * import { BlurFilter } from '@pixi/filter-blur';
  7999. * import { Container } from '@pixi/display';
  8000. * import { Graphics } from '@pixi/graphics';
  8001. * import { Sprite } from '@pixi/sprite';
  8002. *
  8003. * let container = new Container();
  8004. * let sprite = Sprite.from("https://s3-us-west-2.amazonaws.com/s.cdpn.io/693612/IaUrttj.png");
  8005. *
  8006. * sprite.width = 512;
  8007. * sprite.height = 512;
  8008. *
  8009. * // Adds a sprite as a child to this container. As a result, the sprite will be rendered whenever the container
  8010. * // is rendered.
  8011. * container.addChild(sprite);
  8012. *
  8013. * // Blurs whatever is rendered by the container
  8014. * container.filters = [new BlurFilter()];
  8015. *
  8016. * // Only the contents within a circle at the center should be rendered onto the screen.
  8017. * container.mask = new Graphics()
  8018. * .beginFill(0xffffff)
  8019. * .drawCircle(sprite.width / 2, sprite.height / 2, Math.min(sprite.width, sprite.height) / 2)
  8020. * .endFill();
  8021. * ```
  8022. * @memberof PIXI
  8023. */
  8024. var Container = /** @class */ (function (_super) {
  8025. __extends$j(Container, _super);
  8026. function Container() {
  8027. var _this = _super.call(this) || this;
  8028. _this.children = [];
  8029. _this.sortableChildren = settings.SORTABLE_CHILDREN;
  8030. _this.sortDirty = false;
  8031. return _this;
  8032. /**
  8033. * Fired when a DisplayObject is added to this Container.
  8034. * @event PIXI.Container#childAdded
  8035. * @param {PIXI.DisplayObject} child - The child added to the Container.
  8036. * @param {PIXI.Container} container - The container that added the child.
  8037. * @param {number} index - The children's index of the added child.
  8038. */
  8039. /**
  8040. * Fired when a DisplayObject is removed from this Container.
  8041. * @event PIXI.DisplayObject#childRemoved
  8042. * @param {PIXI.DisplayObject} child - The child removed from the Container.
  8043. * @param {PIXI.Container} container - The container that removed the child.
  8044. * @param {number} index - The former children's index of the removed child
  8045. */
  8046. }
  8047. /**
  8048. * Overridable method that can be used by Container subclasses whenever the children array is modified.
  8049. * @param _length
  8050. */
  8051. Container.prototype.onChildrenChange = function (_length) {
  8052. /* empty */
  8053. };
  8054. /**
  8055. * Adds one or more children to the container.
  8056. *
  8057. * Multiple items can be added like so: `myContainer.addChild(thingOne, thingTwo, thingThree)`
  8058. * @param {...PIXI.DisplayObject} children - The DisplayObject(s) to add to the container
  8059. * @returns {PIXI.DisplayObject} - The first child that was added.
  8060. */
  8061. Container.prototype.addChild = function () {
  8062. var arguments$1 = arguments;
  8063. var children = [];
  8064. for (var _i = 0; _i < arguments.length; _i++) {
  8065. children[_i] = arguments$1[_i];
  8066. }
  8067. // if there is only one argument we can bypass looping through the them
  8068. if (children.length > 1) {
  8069. // loop through the array and add all children
  8070. for (var i = 0; i < children.length; i++) {
  8071. // eslint-disable-next-line prefer-rest-params
  8072. this.addChild(children[i]);
  8073. }
  8074. }
  8075. else {
  8076. var child = children[0];
  8077. // if the child has a parent then lets remove it as PixiJS objects can only exist in one place
  8078. if (child.parent) {
  8079. child.parent.removeChild(child);
  8080. }
  8081. child.parent = this;
  8082. this.sortDirty = true;
  8083. // ensure child transform will be recalculated
  8084. child.transform._parentID = -1;
  8085. this.children.push(child);
  8086. // ensure bounds will be recalculated
  8087. this._boundsID++;
  8088. // TODO - lets either do all callbacks or all events.. not both!
  8089. this.onChildrenChange(this.children.length - 1);
  8090. this.emit('childAdded', child, this, this.children.length - 1);
  8091. child.emit('added', this);
  8092. }
  8093. return children[0];
  8094. };
  8095. /**
  8096. * Adds a child to the container at a specified index. If the index is out of bounds an error will be thrown
  8097. * @param {PIXI.DisplayObject} child - The child to add
  8098. * @param {number} index - The index to place the child in
  8099. * @returns {PIXI.DisplayObject} The child that was added.
  8100. */
  8101. Container.prototype.addChildAt = function (child, index) {
  8102. if (index < 0 || index > this.children.length) {
  8103. throw new Error(child + "addChildAt: The index " + index + " supplied is out of bounds " + this.children.length);
  8104. }
  8105. if (child.parent) {
  8106. child.parent.removeChild(child);
  8107. }
  8108. child.parent = this;
  8109. this.sortDirty = true;
  8110. // ensure child transform will be recalculated
  8111. child.transform._parentID = -1;
  8112. this.children.splice(index, 0, child);
  8113. // ensure bounds will be recalculated
  8114. this._boundsID++;
  8115. // TODO - lets either do all callbacks or all events.. not both!
  8116. this.onChildrenChange(index);
  8117. child.emit('added', this);
  8118. this.emit('childAdded', child, this, index);
  8119. return child;
  8120. };
  8121. /**
  8122. * Swaps the position of 2 Display Objects within this container.
  8123. * @param child - First display object to swap
  8124. * @param child2 - Second display object to swap
  8125. */
  8126. Container.prototype.swapChildren = function (child, child2) {
  8127. if (child === child2) {
  8128. return;
  8129. }
  8130. var index1 = this.getChildIndex(child);
  8131. var index2 = this.getChildIndex(child2);
  8132. this.children[index1] = child2;
  8133. this.children[index2] = child;
  8134. this.onChildrenChange(index1 < index2 ? index1 : index2);
  8135. };
  8136. /**
  8137. * Returns the index position of a child DisplayObject instance
  8138. * @param child - The DisplayObject instance to identify
  8139. * @returns - The index position of the child display object to identify
  8140. */
  8141. Container.prototype.getChildIndex = function (child) {
  8142. var index = this.children.indexOf(child);
  8143. if (index === -1) {
  8144. throw new Error('The supplied DisplayObject must be a child of the caller');
  8145. }
  8146. return index;
  8147. };
  8148. /**
  8149. * Changes the position of an existing child in the display object container
  8150. * @param child - The child DisplayObject instance for which you want to change the index number
  8151. * @param index - The resulting index number for the child display object
  8152. */
  8153. Container.prototype.setChildIndex = function (child, index) {
  8154. if (index < 0 || index >= this.children.length) {
  8155. throw new Error("The index " + index + " supplied is out of bounds " + this.children.length);
  8156. }
  8157. var currentIndex = this.getChildIndex(child);
  8158. removeItems(this.children, currentIndex, 1); // remove from old position
  8159. this.children.splice(index, 0, child); // add at new position
  8160. this.onChildrenChange(index);
  8161. };
  8162. /**
  8163. * Returns the child at the specified index
  8164. * @param index - The index to get the child at
  8165. * @returns - The child at the given index, if any.
  8166. */
  8167. Container.prototype.getChildAt = function (index) {
  8168. if (index < 0 || index >= this.children.length) {
  8169. throw new Error("getChildAt: Index (" + index + ") does not exist.");
  8170. }
  8171. return this.children[index];
  8172. };
  8173. /**
  8174. * Removes one or more children from the container.
  8175. * @param {...PIXI.DisplayObject} children - The DisplayObject(s) to remove
  8176. * @returns {PIXI.DisplayObject} The first child that was removed.
  8177. */
  8178. Container.prototype.removeChild = function () {
  8179. var arguments$1 = arguments;
  8180. var children = [];
  8181. for (var _i = 0; _i < arguments.length; _i++) {
  8182. children[_i] = arguments$1[_i];
  8183. }
  8184. // if there is only one argument we can bypass looping through the them
  8185. if (children.length > 1) {
  8186. // loop through the arguments property and remove all children
  8187. for (var i = 0; i < children.length; i++) {
  8188. this.removeChild(children[i]);
  8189. }
  8190. }
  8191. else {
  8192. var child = children[0];
  8193. var index = this.children.indexOf(child);
  8194. if (index === -1)
  8195. { return null; }
  8196. child.parent = null;
  8197. // ensure child transform will be recalculated
  8198. child.transform._parentID = -1;
  8199. removeItems(this.children, index, 1);
  8200. // ensure bounds will be recalculated
  8201. this._boundsID++;
  8202. // TODO - lets either do all callbacks or all events.. not both!
  8203. this.onChildrenChange(index);
  8204. child.emit('removed', this);
  8205. this.emit('childRemoved', child, this, index);
  8206. }
  8207. return children[0];
  8208. };
  8209. /**
  8210. * Removes a child from the specified index position.
  8211. * @param index - The index to get the child from
  8212. * @returns The child that was removed.
  8213. */
  8214. Container.prototype.removeChildAt = function (index) {
  8215. var child = this.getChildAt(index);
  8216. // ensure child transform will be recalculated..
  8217. child.parent = null;
  8218. child.transform._parentID = -1;
  8219. removeItems(this.children, index, 1);
  8220. // ensure bounds will be recalculated
  8221. this._boundsID++;
  8222. // TODO - lets either do all callbacks or all events.. not both!
  8223. this.onChildrenChange(index);
  8224. child.emit('removed', this);
  8225. this.emit('childRemoved', child, this, index);
  8226. return child;
  8227. };
  8228. /**
  8229. * Removes all children from this container that are within the begin and end indexes.
  8230. * @param beginIndex - The beginning position.
  8231. * @param endIndex - The ending position. Default value is size of the container.
  8232. * @returns - List of removed children
  8233. */
  8234. Container.prototype.removeChildren = function (beginIndex, endIndex) {
  8235. if (beginIndex === void 0) { beginIndex = 0; }
  8236. if (endIndex === void 0) { endIndex = this.children.length; }
  8237. var begin = beginIndex;
  8238. var end = endIndex;
  8239. var range = end - begin;
  8240. var removed;
  8241. if (range > 0 && range <= end) {
  8242. removed = this.children.splice(begin, range);
  8243. for (var i = 0; i < removed.length; ++i) {
  8244. removed[i].parent = null;
  8245. if (removed[i].transform) {
  8246. removed[i].transform._parentID = -1;
  8247. }
  8248. }
  8249. this._boundsID++;
  8250. this.onChildrenChange(beginIndex);
  8251. for (var i = 0; i < removed.length; ++i) {
  8252. removed[i].emit('removed', this);
  8253. this.emit('childRemoved', removed[i], this, i);
  8254. }
  8255. return removed;
  8256. }
  8257. else if (range === 0 && this.children.length === 0) {
  8258. return [];
  8259. }
  8260. throw new RangeError('removeChildren: numeric values are outside the acceptable range.');
  8261. };
  8262. /** Sorts children by zIndex. Previous order is maintained for 2 children with the same zIndex. */
  8263. Container.prototype.sortChildren = function () {
  8264. var sortRequired = false;
  8265. for (var i = 0, j = this.children.length; i < j; ++i) {
  8266. var child = this.children[i];
  8267. child._lastSortedIndex = i;
  8268. if (!sortRequired && child.zIndex !== 0) {
  8269. sortRequired = true;
  8270. }
  8271. }
  8272. if (sortRequired && this.children.length > 1) {
  8273. this.children.sort(sortChildren);
  8274. }
  8275. this.sortDirty = false;
  8276. };
  8277. /** Updates the transform on all children of this container for rendering. */
  8278. Container.prototype.updateTransform = function () {
  8279. if (this.sortableChildren && this.sortDirty) {
  8280. this.sortChildren();
  8281. }
  8282. this._boundsID++;
  8283. this.transform.updateTransform(this.parent.transform);
  8284. // TODO: check render flags, how to process stuff here
  8285. this.worldAlpha = this.alpha * this.parent.worldAlpha;
  8286. for (var i = 0, j = this.children.length; i < j; ++i) {
  8287. var child = this.children[i];
  8288. if (child.visible) {
  8289. child.updateTransform();
  8290. }
  8291. }
  8292. };
  8293. /**
  8294. * Recalculates the bounds of the container.
  8295. *
  8296. * This implementation will automatically fit the children's bounds into the calculation. Each child's bounds
  8297. * is limited to its mask's bounds or filterArea, if any is applied.
  8298. */
  8299. Container.prototype.calculateBounds = function () {
  8300. this._bounds.clear();
  8301. this._calculateBounds();
  8302. for (var i = 0; i < this.children.length; i++) {
  8303. var child = this.children[i];
  8304. if (!child.visible || !child.renderable) {
  8305. continue;
  8306. }
  8307. child.calculateBounds();
  8308. // TODO: filter+mask, need to mask both somehow
  8309. if (child._mask) {
  8310. var maskObject = (child._mask.isMaskData
  8311. ? child._mask.maskObject : child._mask);
  8312. if (maskObject) {
  8313. maskObject.calculateBounds();
  8314. this._bounds.addBoundsMask(child._bounds, maskObject._bounds);
  8315. }
  8316. else {
  8317. this._bounds.addBounds(child._bounds);
  8318. }
  8319. }
  8320. else if (child.filterArea) {
  8321. this._bounds.addBoundsArea(child._bounds, child.filterArea);
  8322. }
  8323. else {
  8324. this._bounds.addBounds(child._bounds);
  8325. }
  8326. }
  8327. this._bounds.updateID = this._boundsID;
  8328. };
  8329. /**
  8330. * Retrieves the local bounds of the displayObject as a rectangle object.
  8331. *
  8332. * Calling `getLocalBounds` may invalidate the `_bounds` of the whole subtree below. If using it inside a render()
  8333. * call, it is advised to call `getBounds()` immediately after to recalculate the world bounds of the subtree.
  8334. * @param rect - Optional rectangle to store the result of the bounds calculation.
  8335. * @param skipChildrenUpdate - Setting to `true` will stop re-calculation of children transforms,
  8336. * it was default behaviour of pixi 4.0-5.2 and caused many problems to users.
  8337. * @returns - The rectangular bounding area.
  8338. */
  8339. Container.prototype.getLocalBounds = function (rect, skipChildrenUpdate) {
  8340. if (skipChildrenUpdate === void 0) { skipChildrenUpdate = false; }
  8341. var result = _super.prototype.getLocalBounds.call(this, rect);
  8342. if (!skipChildrenUpdate) {
  8343. for (var i = 0, j = this.children.length; i < j; ++i) {
  8344. var child = this.children[i];
  8345. if (child.visible) {
  8346. child.updateTransform();
  8347. }
  8348. }
  8349. }
  8350. return result;
  8351. };
  8352. /**
  8353. * Recalculates the content bounds of this object. This should be overriden to
  8354. * calculate the bounds of this specific object (not including children).
  8355. * @protected
  8356. */
  8357. Container.prototype._calculateBounds = function () {
  8358. // FILL IN//
  8359. };
  8360. /**
  8361. * Renders this object and its children with culling.
  8362. * @protected
  8363. * @param {PIXI.Renderer} renderer - The renderer
  8364. */
  8365. Container.prototype._renderWithCulling = function (renderer) {
  8366. var sourceFrame = renderer.renderTexture.sourceFrame;
  8367. // If the source frame is empty, stop rendering.
  8368. if (!(sourceFrame.width > 0 && sourceFrame.height > 0)) {
  8369. return;
  8370. }
  8371. // Render the content of the container only if its bounds intersect with the source frame.
  8372. // All filters are on the stack at this point, and the filter source frame is bound:
  8373. // therefore, even if the bounds to non intersect the filter frame, the filter
  8374. // is still applied and any filter padding that is in the frame is rendered correctly.
  8375. var bounds;
  8376. var transform;
  8377. // If cullArea is set, we use this rectangle instead of the bounds of the object. The cullArea
  8378. // rectangle must completely contain the container and its children including filter padding.
  8379. if (this.cullArea) {
  8380. bounds = this.cullArea;
  8381. transform = this.worldTransform;
  8382. }
  8383. // If the container doesn't override _render, we can skip the bounds calculation and intersection test.
  8384. else if (this._render !== Container.prototype._render) {
  8385. bounds = this.getBounds(true);
  8386. }
  8387. // Render the container if the source frame intersects the bounds.
  8388. if (bounds && sourceFrame.intersects(bounds, transform)) {
  8389. this._render(renderer);
  8390. }
  8391. // If the bounds are defined by cullArea and do not intersect with the source frame, stop rendering.
  8392. else if (this.cullArea) {
  8393. return;
  8394. }
  8395. // Unless cullArea is set, we cannot skip the children if the bounds of the container do not intersect
  8396. // the source frame, because the children might have filters with nonzero padding, which may intersect
  8397. // with the source frame while the bounds do not: filter padding is not included in the bounds.
  8398. // If cullArea is not set, render the children with culling temporarily enabled so that they are not rendered
  8399. // if they are out of frame; otherwise, render the children normally.
  8400. for (var i = 0, j = this.children.length; i < j; ++i) {
  8401. var child = this.children[i];
  8402. var childCullable = child.cullable;
  8403. child.cullable = childCullable || !this.cullArea;
  8404. child.render(renderer);
  8405. child.cullable = childCullable;
  8406. }
  8407. };
  8408. /**
  8409. * Renders the object using the WebGL renderer.
  8410. *
  8411. * The [_render]{@link PIXI.Container#_render} method is be overriden for rendering the contents of the
  8412. * container itself. This `render` method will invoke it, and also invoke the `render` methods of all
  8413. * children afterward.
  8414. *
  8415. * If `renderable` or `visible` is false or if `worldAlpha` is not positive or if `cullable` is true and
  8416. * the bounds of this object are out of frame, this implementation will entirely skip rendering.
  8417. * See {@link PIXI.DisplayObject} for choosing between `renderable` or `visible`. Generally,
  8418. * setting alpha to zero is not recommended for purely skipping rendering.
  8419. *
  8420. * When your scene becomes large (especially when it is larger than can be viewed in a single screen), it is
  8421. * advised to employ **culling** to automatically skip rendering objects outside of the current screen.
  8422. * See [cullable]{@link PIXI.DisplayObject#cullable} and [cullArea]{@link PIXI.DisplayObject#cullArea}.
  8423. * Other culling methods might be better suited for a large number static objects; see
  8424. * [@pixi-essentials/cull]{@link https://www.npmjs.com/package/@pixi-essentials/cull} and
  8425. * [pixi-cull]{@link https://www.npmjs.com/package/pixi-cull}.
  8426. *
  8427. * The [renderAdvanced]{@link PIXI.Container#renderAdvanced} method is internally used when when masking or
  8428. * filtering is applied on a container. This does, however, break batching and can affect performance when
  8429. * masking and filtering is applied extensively throughout the scene graph.
  8430. * @param renderer - The renderer
  8431. */
  8432. Container.prototype.render = function (renderer) {
  8433. // if the object is not visible or the alpha is 0 then no need to render this element
  8434. if (!this.visible || this.worldAlpha <= 0 || !this.renderable) {
  8435. return;
  8436. }
  8437. // do a quick check to see if this element has a mask or a filter.
  8438. if (this._mask || (this.filters && this.filters.length)) {
  8439. this.renderAdvanced(renderer);
  8440. }
  8441. else if (this.cullable) {
  8442. this._renderWithCulling(renderer);
  8443. }
  8444. else {
  8445. this._render(renderer);
  8446. for (var i = 0, j = this.children.length; i < j; ++i) {
  8447. this.children[i].render(renderer);
  8448. }
  8449. }
  8450. };
  8451. /**
  8452. * Render the object using the WebGL renderer and advanced features.
  8453. * @param renderer - The renderer
  8454. */
  8455. Container.prototype.renderAdvanced = function (renderer) {
  8456. var filters = this.filters;
  8457. var mask = this._mask;
  8458. // push filter first as we need to ensure the stencil buffer is correct for any masking
  8459. if (filters) {
  8460. if (!this._enabledFilters) {
  8461. this._enabledFilters = [];
  8462. }
  8463. this._enabledFilters.length = 0;
  8464. for (var i = 0; i < filters.length; i++) {
  8465. if (filters[i].enabled) {
  8466. this._enabledFilters.push(filters[i]);
  8467. }
  8468. }
  8469. }
  8470. var flush = (filters && this._enabledFilters && this._enabledFilters.length)
  8471. || (mask && (!mask.isMaskData
  8472. || (mask.enabled && (mask.autoDetect || mask.type !== MASK_TYPES.NONE))));
  8473. if (flush) {
  8474. renderer.batch.flush();
  8475. }
  8476. if (filters && this._enabledFilters && this._enabledFilters.length) {
  8477. renderer.filter.push(this, this._enabledFilters);
  8478. }
  8479. if (mask) {
  8480. renderer.mask.push(this, this._mask);
  8481. }
  8482. if (this.cullable) {
  8483. this._renderWithCulling(renderer);
  8484. }
  8485. else {
  8486. this._render(renderer);
  8487. for (var i = 0, j = this.children.length; i < j; ++i) {
  8488. this.children[i].render(renderer);
  8489. }
  8490. }
  8491. if (flush) {
  8492. renderer.batch.flush();
  8493. }
  8494. if (mask) {
  8495. renderer.mask.pop(this);
  8496. }
  8497. if (filters && this._enabledFilters && this._enabledFilters.length) {
  8498. renderer.filter.pop();
  8499. }
  8500. };
  8501. /**
  8502. * To be overridden by the subclasses.
  8503. * @param _renderer - The renderer
  8504. */
  8505. Container.prototype._render = function (_renderer) {
  8506. // this is where content itself gets rendered...
  8507. };
  8508. /**
  8509. * Removes all internal references and listeners as well as removes children from the display list.
  8510. * Do not use a Container after calling `destroy`.
  8511. * @param options - Options parameter. A boolean will act as if all options
  8512. * have been set to that value
  8513. * @param {boolean} [options.children=false] - if set to true, all the children will have their destroy
  8514. * method called as well. 'options' will be passed on to those calls.
  8515. * @param {boolean} [options.texture=false] - Only used for child Sprites if options.children is set to true
  8516. * Should it destroy the texture of the child sprite
  8517. * @param {boolean} [options.baseTexture=false] - Only used for child Sprites if options.children is set to true
  8518. * Should it destroy the base texture of the child sprite
  8519. */
  8520. Container.prototype.destroy = function (options) {
  8521. _super.prototype.destroy.call(this);
  8522. this.sortDirty = false;
  8523. var destroyChildren = typeof options === 'boolean' ? options : options && options.children;
  8524. var oldChildren = this.removeChildren(0, this.children.length);
  8525. if (destroyChildren) {
  8526. for (var i = 0; i < oldChildren.length; ++i) {
  8527. oldChildren[i].destroy(options);
  8528. }
  8529. }
  8530. };
  8531. Object.defineProperty(Container.prototype, "width", {
  8532. /** The width of the Container, setting this will actually modify the scale to achieve the value set. */
  8533. get: function () {
  8534. return this.scale.x * this.getLocalBounds().width;
  8535. },
  8536. set: function (value) {
  8537. var width = this.getLocalBounds().width;
  8538. if (width !== 0) {
  8539. this.scale.x = value / width;
  8540. }
  8541. else {
  8542. this.scale.x = 1;
  8543. }
  8544. this._width = value;
  8545. },
  8546. enumerable: false,
  8547. configurable: true
  8548. });
  8549. Object.defineProperty(Container.prototype, "height", {
  8550. /** The height of the Container, setting this will actually modify the scale to achieve the value set. */
  8551. get: function () {
  8552. return this.scale.y * this.getLocalBounds().height;
  8553. },
  8554. set: function (value) {
  8555. var height = this.getLocalBounds().height;
  8556. if (height !== 0) {
  8557. this.scale.y = value / height;
  8558. }
  8559. else {
  8560. this.scale.y = 1;
  8561. }
  8562. this._height = value;
  8563. },
  8564. enumerable: false,
  8565. configurable: true
  8566. });
  8567. return Container;
  8568. }(DisplayObject));
  8569. /**
  8570. * Container default updateTransform, does update children of container.
  8571. * Will crash if there's no parent element.
  8572. * @memberof PIXI.Container#
  8573. * @method containerUpdateTransform
  8574. */
  8575. Container.prototype.containerUpdateTransform = Container.prototype.updateTransform;
  8576. /*!
  8577. * @pixi/extensions - v6.5.10
  8578. * Compiled Thu, 06 Jul 2023 15:25:11 UTC
  8579. *
  8580. * @pixi/extensions is licensed under the MIT License.
  8581. * http://www.opensource.org/licenses/mit-license
  8582. */
  8583. /*! *****************************************************************************
  8584. Copyright (c) Microsoft Corporation.
  8585. Permission to use, copy, modify, and/or distribute this software for any
  8586. purpose with or without fee is hereby granted.
  8587. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  8588. REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
  8589. AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  8590. INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
  8591. LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
  8592. OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
  8593. PERFORMANCE OF THIS SOFTWARE.
  8594. ***************************************************************************** */
  8595. var __assign$1 = function() {
  8596. __assign$1 = Object.assign || function __assign(t) {
  8597. var arguments$1 = arguments;
  8598. for (var s, i = 1, n = arguments.length; i < n; i++) {
  8599. s = arguments$1[i];
  8600. for (var p in s) { if (Object.prototype.hasOwnProperty.call(s, p)) { t[p] = s[p]; } }
  8601. }
  8602. return t;
  8603. };
  8604. return __assign$1.apply(this, arguments);
  8605. };
  8606. /**
  8607. * Collection of valid extension types.
  8608. * @memberof PIXI
  8609. * @property {string} Application - Application plugins
  8610. * @property {string} RendererPlugin - Plugins for Renderer
  8611. * @property {string} CanvasRendererPlugin - Plugins for CanvasRenderer
  8612. * @property {string} Loader - Plugins to use with Loader
  8613. * @property {string} LoadParser - Parsers for Assets loader.
  8614. * @property {string} ResolveParser - Parsers for Assets resolvers.
  8615. * @property {string} CacheParser - Parsers for Assets cache.
  8616. */
  8617. var ExtensionType;
  8618. (function (ExtensionType) {
  8619. ExtensionType["Application"] = "application";
  8620. ExtensionType["RendererPlugin"] = "renderer-webgl-plugin";
  8621. ExtensionType["CanvasRendererPlugin"] = "renderer-canvas-plugin";
  8622. ExtensionType["Loader"] = "loader";
  8623. ExtensionType["LoadParser"] = "load-parser";
  8624. ExtensionType["ResolveParser"] = "resolve-parser";
  8625. ExtensionType["CacheParser"] = "cache-parser";
  8626. ExtensionType["DetectionParser"] = "detection-parser";
  8627. })(ExtensionType || (ExtensionType = {}));
  8628. /**
  8629. * Convert input into extension format data.
  8630. * @ignore
  8631. */
  8632. var normalizeExtension = function (ext) {
  8633. // Class/Object submission, use extension object
  8634. if (typeof ext === 'function' || (typeof ext === 'object' && ext.extension)) {
  8635. if (!ext.extension) {
  8636. throw new Error('Extension class must have an extension object');
  8637. }
  8638. var metadata = (typeof ext.extension !== 'object')
  8639. ? { type: ext.extension }
  8640. : ext.extension;
  8641. ext = __assign$1(__assign$1({}, metadata), { ref: ext });
  8642. }
  8643. if (typeof ext === 'object') {
  8644. ext = __assign$1({}, ext);
  8645. }
  8646. else {
  8647. throw new Error('Invalid extension type');
  8648. }
  8649. if (typeof ext.type === 'string') {
  8650. ext.type = [ext.type];
  8651. }
  8652. return ext;
  8653. };
  8654. /**
  8655. * Global registration of all PixiJS extensions. One-stop-shop for extensibility.
  8656. * @memberof PIXI
  8657. * @namespace extensions
  8658. */
  8659. var extensions = {
  8660. /** @ignore */
  8661. _addHandlers: null,
  8662. /** @ignore */
  8663. _removeHandlers: null,
  8664. /** @ignore */
  8665. _queue: {},
  8666. /**
  8667. * Remove extensions from PixiJS.
  8668. * @param extensions - Extensions to be removed.
  8669. * @returns {PIXI.extensions} For chaining.
  8670. */
  8671. remove: function () {
  8672. var arguments$1 = arguments;
  8673. var _this = this;
  8674. var extensions = [];
  8675. for (var _i = 0; _i < arguments.length; _i++) {
  8676. extensions[_i] = arguments$1[_i];
  8677. }
  8678. extensions.map(normalizeExtension).forEach(function (ext) {
  8679. ext.type.forEach(function (type) { var _a, _b; return (_b = (_a = _this._removeHandlers)[type]) === null || _b === void 0 ? void 0 : _b.call(_a, ext); });
  8680. });
  8681. return this;
  8682. },
  8683. /**
  8684. * Register new extensions with PixiJS.
  8685. * @param extensions - The spread of extensions to add to PixiJS.
  8686. * @returns {PIXI.extensions} For chaining.
  8687. */
  8688. add: function () {
  8689. var arguments$1 = arguments;
  8690. var _this = this;
  8691. var extensions = [];
  8692. for (var _i = 0; _i < arguments.length; _i++) {
  8693. extensions[_i] = arguments$1[_i];
  8694. }
  8695. // Handle any extensions either passed as class w/ data or as data
  8696. extensions.map(normalizeExtension).forEach(function (ext) {
  8697. ext.type.forEach(function (type) {
  8698. var handlers = _this._addHandlers;
  8699. var queue = _this._queue;
  8700. if (!handlers[type]) {
  8701. queue[type] = queue[type] || [];
  8702. queue[type].push(ext);
  8703. }
  8704. else {
  8705. handlers[type](ext);
  8706. }
  8707. });
  8708. });
  8709. return this;
  8710. },
  8711. /**
  8712. * Internal method to handle extensions by name.
  8713. * @param type - The extension type.
  8714. * @param onAdd - Function for handling when extensions are added/registered passes {@link PIXI.ExtensionFormat}.
  8715. * @param onRemove - Function for handling when extensions are removed/unregistered passes {@link PIXI.ExtensionFormat}.
  8716. * @returns {PIXI.extensions} For chaining.
  8717. */
  8718. handle: function (type, onAdd, onRemove) {
  8719. var addHandlers = this._addHandlers = this._addHandlers || {};
  8720. var removeHandlers = this._removeHandlers = this._removeHandlers || {};
  8721. if (addHandlers[type] || removeHandlers[type]) {
  8722. throw new Error("Extension type " + type + " already has a handler");
  8723. }
  8724. addHandlers[type] = onAdd;
  8725. removeHandlers[type] = onRemove;
  8726. // Process the queue
  8727. var queue = this._queue;
  8728. // Process any plugins that have been registered before the handler
  8729. if (queue[type]) {
  8730. queue[type].forEach(function (ext) { return onAdd(ext); });
  8731. delete queue[type];
  8732. }
  8733. return this;
  8734. },
  8735. /**
  8736. * Handle a type, but using a map by `name` property.
  8737. * @param type - Type of extension to handle.
  8738. * @param map - The object map of named extensions.
  8739. * @returns {PIXI.extensions} For chaining.
  8740. */
  8741. handleByMap: function (type, map) {
  8742. return this.handle(type, function (extension) {
  8743. map[extension.name] = extension.ref;
  8744. }, function (extension) {
  8745. delete map[extension.name];
  8746. });
  8747. },
  8748. /**
  8749. * Handle a type, but using a list of extensions.
  8750. * @param type - Type of extension to handle.
  8751. * @param list - The list of extensions.
  8752. * @returns {PIXI.extensions} For chaining.
  8753. */
  8754. handleByList: function (type, list) {
  8755. return this.handle(type, function (extension) {
  8756. var _a, _b;
  8757. if (list.includes(extension.ref)) {
  8758. return;
  8759. }
  8760. list.push(extension.ref);
  8761. // TODO: remove me later, only added for @pixi/loaders
  8762. if (type === ExtensionType.Loader) {
  8763. (_b = (_a = extension.ref).add) === null || _b === void 0 ? void 0 : _b.call(_a);
  8764. }
  8765. }, function (extension) {
  8766. var index = list.indexOf(extension.ref);
  8767. if (index !== -1) {
  8768. list.splice(index, 1);
  8769. }
  8770. });
  8771. },
  8772. };
  8773. /*!
  8774. * @pixi/runner - v6.5.10
  8775. * Compiled Thu, 06 Jul 2023 15:25:11 UTC
  8776. *
  8777. * @pixi/runner is licensed under the MIT License.
  8778. * http://www.opensource.org/licenses/mit-license
  8779. */
  8780. /**
  8781. * A Runner is a highly performant and simple alternative to signals. Best used in situations
  8782. * where events are dispatched to many objects at high frequency (say every frame!)
  8783. *
  8784. *
  8785. * like a signal..
  8786. * ```
  8787. * import { Runner } from '@pixi/runner';
  8788. *
  8789. * const myObject = {
  8790. * loaded: new Runner('loaded')
  8791. * }
  8792. *
  8793. * const listener = {
  8794. * loaded: function(){
  8795. * // thin
  8796. * }
  8797. * }
  8798. *
  8799. * myObject.loaded.add(listener);
  8800. *
  8801. * myObject.loaded.emit();
  8802. * ```
  8803. *
  8804. * Or for handling calling the same function on many items
  8805. * ```
  8806. * import { Runner } from '@pixi/runner';
  8807. *
  8808. * const myGame = {
  8809. * update: new Runner('update')
  8810. * }
  8811. *
  8812. * const gameObject = {
  8813. * update: function(time){
  8814. * // update my gamey state
  8815. * }
  8816. * }
  8817. *
  8818. * myGame.update.add(gameObject);
  8819. *
  8820. * myGame.update.emit(time);
  8821. * ```
  8822. * @memberof PIXI
  8823. */
  8824. var Runner = /** @class */ (function () {
  8825. /**
  8826. * @param name - The function name that will be executed on the listeners added to this Runner.
  8827. */
  8828. function Runner(name) {
  8829. this.items = [];
  8830. this._name = name;
  8831. this._aliasCount = 0;
  8832. }
  8833. /* eslint-disable jsdoc/require-param, jsdoc/check-param-names */
  8834. /**
  8835. * Dispatch/Broadcast Runner to all listeners added to the queue.
  8836. * @param {...any} params - (optional) parameters to pass to each listener
  8837. */
  8838. /* eslint-enable jsdoc/require-param, jsdoc/check-param-names */
  8839. Runner.prototype.emit = function (a0, a1, a2, a3, a4, a5, a6, a7) {
  8840. if (arguments.length > 8) {
  8841. throw new Error('max arguments reached');
  8842. }
  8843. var _a = this, name = _a.name, items = _a.items;
  8844. this._aliasCount++;
  8845. for (var i = 0, len = items.length; i < len; i++) {
  8846. items[i][name](a0, a1, a2, a3, a4, a5, a6, a7);
  8847. }
  8848. if (items === this.items) {
  8849. this._aliasCount--;
  8850. }
  8851. return this;
  8852. };
  8853. Runner.prototype.ensureNonAliasedItems = function () {
  8854. if (this._aliasCount > 0 && this.items.length > 1) {
  8855. this._aliasCount = 0;
  8856. this.items = this.items.slice(0);
  8857. }
  8858. };
  8859. /**
  8860. * Add a listener to the Runner
  8861. *
  8862. * Runners do not need to have scope or functions passed to them.
  8863. * All that is required is to pass the listening object and ensure that it has contains a function that has the same name
  8864. * as the name provided to the Runner when it was created.
  8865. *
  8866. * Eg A listener passed to this Runner will require a 'complete' function.
  8867. *
  8868. * ```
  8869. * import { Runner } from '@pixi/runner';
  8870. *
  8871. * const complete = new Runner('complete');
  8872. * ```
  8873. *
  8874. * The scope used will be the object itself.
  8875. * @param {any} item - The object that will be listening.
  8876. */
  8877. Runner.prototype.add = function (item) {
  8878. if (item[this._name]) {
  8879. this.ensureNonAliasedItems();
  8880. this.remove(item);
  8881. this.items.push(item);
  8882. }
  8883. return this;
  8884. };
  8885. /**
  8886. * Remove a single listener from the dispatch queue.
  8887. * @param {any} item - The listener that you would like to remove.
  8888. */
  8889. Runner.prototype.remove = function (item) {
  8890. var index = this.items.indexOf(item);
  8891. if (index !== -1) {
  8892. this.ensureNonAliasedItems();
  8893. this.items.splice(index, 1);
  8894. }
  8895. return this;
  8896. };
  8897. /**
  8898. * Check to see if the listener is already in the Runner
  8899. * @param {any} item - The listener that you would like to check.
  8900. */
  8901. Runner.prototype.contains = function (item) {
  8902. return this.items.indexOf(item) !== -1;
  8903. };
  8904. /** Remove all listeners from the Runner */
  8905. Runner.prototype.removeAll = function () {
  8906. this.ensureNonAliasedItems();
  8907. this.items.length = 0;
  8908. return this;
  8909. };
  8910. /** Remove all references, don't use after this. */
  8911. Runner.prototype.destroy = function () {
  8912. this.removeAll();
  8913. this.items = null;
  8914. this._name = null;
  8915. };
  8916. Object.defineProperty(Runner.prototype, "empty", {
  8917. /**
  8918. * `true` if there are no this Runner contains no listeners
  8919. * @readonly
  8920. */
  8921. get: function () {
  8922. return this.items.length === 0;
  8923. },
  8924. enumerable: false,
  8925. configurable: true
  8926. });
  8927. Object.defineProperty(Runner.prototype, "name", {
  8928. /**
  8929. * The name of the runner.
  8930. * @readonly
  8931. */
  8932. get: function () {
  8933. return this._name;
  8934. },
  8935. enumerable: false,
  8936. configurable: true
  8937. });
  8938. return Runner;
  8939. }());
  8940. Object.defineProperties(Runner.prototype, {
  8941. /**
  8942. * Alias for `emit`
  8943. * @memberof PIXI.Runner#
  8944. * @method dispatch
  8945. * @see PIXI.Runner#emit
  8946. */
  8947. dispatch: { value: Runner.prototype.emit },
  8948. /**
  8949. * Alias for `emit`
  8950. * @memberof PIXI.Runner#
  8951. * @method run
  8952. * @see PIXI.Runner#emit
  8953. */
  8954. run: { value: Runner.prototype.emit },
  8955. });
  8956. /*!
  8957. * @pixi/ticker - v6.5.10
  8958. * Compiled Thu, 06 Jul 2023 15:25:11 UTC
  8959. *
  8960. * @pixi/ticker is licensed under the MIT License.
  8961. * http://www.opensource.org/licenses/mit-license
  8962. */
  8963. /**
  8964. * Target frames per millisecond.
  8965. * @static
  8966. * @name TARGET_FPMS
  8967. * @memberof PIXI.settings
  8968. * @type {number}
  8969. * @default 0.06
  8970. */
  8971. settings.TARGET_FPMS = 0.06;
  8972. /**
  8973. * Represents the update priorities used by internal PIXI classes when registered with
  8974. * the {@link PIXI.Ticker} object. Higher priority items are updated first and lower
  8975. * priority items, such as render, should go later.
  8976. * @static
  8977. * @constant
  8978. * @name UPDATE_PRIORITY
  8979. * @memberof PIXI
  8980. * @enum {number}
  8981. * @property {number} [INTERACTION=50] Highest priority, used for {@link PIXI.InteractionManager}
  8982. * @property {number} [HIGH=25] High priority updating, {@link PIXI.VideoBaseTexture} and {@link PIXI.AnimatedSprite}
  8983. * @property {number} [NORMAL=0] Default priority for ticker events, see {@link PIXI.Ticker#add}.
  8984. * @property {number} [LOW=-25] Low priority used for {@link PIXI.Application} rendering.
  8985. * @property {number} [UTILITY=-50] Lowest priority used for {@link PIXI.BasePrepare} utility.
  8986. */
  8987. var UPDATE_PRIORITY;
  8988. (function (UPDATE_PRIORITY) {
  8989. UPDATE_PRIORITY[UPDATE_PRIORITY["INTERACTION"] = 50] = "INTERACTION";
  8990. UPDATE_PRIORITY[UPDATE_PRIORITY["HIGH"] = 25] = "HIGH";
  8991. UPDATE_PRIORITY[UPDATE_PRIORITY["NORMAL"] = 0] = "NORMAL";
  8992. UPDATE_PRIORITY[UPDATE_PRIORITY["LOW"] = -25] = "LOW";
  8993. UPDATE_PRIORITY[UPDATE_PRIORITY["UTILITY"] = -50] = "UTILITY";
  8994. })(UPDATE_PRIORITY || (UPDATE_PRIORITY = {}));
  8995. /**
  8996. * Internal class for handling the priority sorting of ticker handlers.
  8997. * @private
  8998. * @class
  8999. * @memberof PIXI
  9000. */
  9001. var TickerListener = /** @class */ (function () {
  9002. /**
  9003. * Constructor
  9004. * @private
  9005. * @param fn - The listener function to be added for one update
  9006. * @param context - The listener context
  9007. * @param priority - The priority for emitting
  9008. * @param once - If the handler should fire once
  9009. */
  9010. function TickerListener(fn, context, priority, once) {
  9011. if (context === void 0) { context = null; }
  9012. if (priority === void 0) { priority = 0; }
  9013. if (once === void 0) { once = false; }
  9014. /** The next item in chain. */
  9015. this.next = null;
  9016. /** The previous item in chain. */
  9017. this.previous = null;
  9018. /** `true` if this listener has been destroyed already. */
  9019. this._destroyed = false;
  9020. this.fn = fn;
  9021. this.context = context;
  9022. this.priority = priority;
  9023. this.once = once;
  9024. }
  9025. /**
  9026. * Simple compare function to figure out if a function and context match.
  9027. * @private
  9028. * @param fn - The listener function to be added for one update
  9029. * @param context - The listener context
  9030. * @returns `true` if the listener match the arguments
  9031. */
  9032. TickerListener.prototype.match = function (fn, context) {
  9033. if (context === void 0) { context = null; }
  9034. return this.fn === fn && this.context === context;
  9035. };
  9036. /**
  9037. * Emit by calling the current function.
  9038. * @private
  9039. * @param deltaTime - time since the last emit.
  9040. * @returns Next ticker
  9041. */
  9042. TickerListener.prototype.emit = function (deltaTime) {
  9043. if (this.fn) {
  9044. if (this.context) {
  9045. this.fn.call(this.context, deltaTime);
  9046. }
  9047. else {
  9048. this.fn(deltaTime);
  9049. }
  9050. }
  9051. var redirect = this.next;
  9052. if (this.once) {
  9053. this.destroy(true);
  9054. }
  9055. // Soft-destroying should remove
  9056. // the next reference
  9057. if (this._destroyed) {
  9058. this.next = null;
  9059. }
  9060. return redirect;
  9061. };
  9062. /**
  9063. * Connect to the list.
  9064. * @private
  9065. * @param previous - Input node, previous listener
  9066. */
  9067. TickerListener.prototype.connect = function (previous) {
  9068. this.previous = previous;
  9069. if (previous.next) {
  9070. previous.next.previous = this;
  9071. }
  9072. this.next = previous.next;
  9073. previous.next = this;
  9074. };
  9075. /**
  9076. * Destroy and don't use after this.
  9077. * @private
  9078. * @param hard - `true` to remove the `next` reference, this
  9079. * is considered a hard destroy. Soft destroy maintains the next reference.
  9080. * @returns The listener to redirect while emitting or removing.
  9081. */
  9082. TickerListener.prototype.destroy = function (hard) {
  9083. if (hard === void 0) { hard = false; }
  9084. this._destroyed = true;
  9085. this.fn = null;
  9086. this.context = null;
  9087. // Disconnect, hook up next and previous
  9088. if (this.previous) {
  9089. this.previous.next = this.next;
  9090. }
  9091. if (this.next) {
  9092. this.next.previous = this.previous;
  9093. }
  9094. // Redirect to the next item
  9095. var redirect = this.next;
  9096. // Remove references
  9097. this.next = hard ? null : redirect;
  9098. this.previous = null;
  9099. return redirect;
  9100. };
  9101. return TickerListener;
  9102. }());
  9103. /**
  9104. * A Ticker class that runs an update loop that other objects listen to.
  9105. *
  9106. * This class is composed around listeners meant for execution on the next requested animation frame.
  9107. * Animation frames are requested only when necessary, e.g. When the ticker is started and the emitter has listeners.
  9108. * @class
  9109. * @memberof PIXI
  9110. */
  9111. var Ticker = /** @class */ (function () {
  9112. function Ticker() {
  9113. var _this = this;
  9114. /**
  9115. * Whether or not this ticker should invoke the method
  9116. * {@link PIXI.Ticker#start} automatically
  9117. * when a listener is added.
  9118. */
  9119. this.autoStart = false;
  9120. /**
  9121. * Scalar time value from last frame to this frame.
  9122. * This value is capped by setting {@link PIXI.Ticker#minFPS}
  9123. * and is scaled with {@link PIXI.Ticker#speed}.
  9124. * **Note:** The cap may be exceeded by scaling.
  9125. */
  9126. this.deltaTime = 1;
  9127. /**
  9128. * The last time {@link PIXI.Ticker#update} was invoked.
  9129. * This value is also reset internally outside of invoking
  9130. * update, but only when a new animation frame is requested.
  9131. * If the platform supports DOMHighResTimeStamp,
  9132. * this value will have a precision of 1 µs.
  9133. */
  9134. this.lastTime = -1;
  9135. /**
  9136. * Factor of current {@link PIXI.Ticker#deltaTime}.
  9137. * @example
  9138. * // Scales ticker.deltaTime to what would be
  9139. * // the equivalent of approximately 120 FPS
  9140. * ticker.speed = 2;
  9141. */
  9142. this.speed = 1;
  9143. /**
  9144. * Whether or not this ticker has been started.
  9145. * `true` if {@link PIXI.Ticker#start} has been called.
  9146. * `false` if {@link PIXI.Ticker#stop} has been called.
  9147. * While `false`, this value may change to `true` in the
  9148. * event of {@link PIXI.Ticker#autoStart} being `true`
  9149. * and a listener is added.
  9150. */
  9151. this.started = false;
  9152. /** Internal current frame request ID */
  9153. this._requestId = null;
  9154. /**
  9155. * Internal value managed by minFPS property setter and getter.
  9156. * This is the maximum allowed milliseconds between updates.
  9157. */
  9158. this._maxElapsedMS = 100;
  9159. /**
  9160. * Internal value managed by minFPS property setter and getter.
  9161. * This is the minimum allowed milliseconds between updates.
  9162. */
  9163. this._minElapsedMS = 0;
  9164. /** If enabled, deleting is disabled.*/
  9165. this._protected = false;
  9166. /** The last time keyframe was executed. Maintains a relatively fixed interval with the previous value. */
  9167. this._lastFrame = -1;
  9168. this._head = new TickerListener(null, null, Infinity);
  9169. this.deltaMS = 1 / settings.TARGET_FPMS;
  9170. this.elapsedMS = 1 / settings.TARGET_FPMS;
  9171. this._tick = function (time) {
  9172. _this._requestId = null;
  9173. if (_this.started) {
  9174. // Invoke listeners now
  9175. _this.update(time);
  9176. // Listener side effects may have modified ticker state.
  9177. if (_this.started && _this._requestId === null && _this._head.next) {
  9178. _this._requestId = requestAnimationFrame(_this._tick);
  9179. }
  9180. }
  9181. };
  9182. }
  9183. /**
  9184. * Conditionally requests a new animation frame.
  9185. * If a frame has not already been requested, and if the internal
  9186. * emitter has listeners, a new frame is requested.
  9187. * @private
  9188. */
  9189. Ticker.prototype._requestIfNeeded = function () {
  9190. if (this._requestId === null && this._head.next) {
  9191. // ensure callbacks get correct delta
  9192. this.lastTime = performance.now();
  9193. this._lastFrame = this.lastTime;
  9194. this._requestId = requestAnimationFrame(this._tick);
  9195. }
  9196. };
  9197. /**
  9198. * Conditionally cancels a pending animation frame.
  9199. * @private
  9200. */
  9201. Ticker.prototype._cancelIfNeeded = function () {
  9202. if (this._requestId !== null) {
  9203. cancelAnimationFrame(this._requestId);
  9204. this._requestId = null;
  9205. }
  9206. };
  9207. /**
  9208. * Conditionally requests a new animation frame.
  9209. * If the ticker has been started it checks if a frame has not already
  9210. * been requested, and if the internal emitter has listeners. If these
  9211. * conditions are met, a new frame is requested. If the ticker has not
  9212. * been started, but autoStart is `true`, then the ticker starts now,
  9213. * and continues with the previous conditions to request a new frame.
  9214. * @private
  9215. */
  9216. Ticker.prototype._startIfPossible = function () {
  9217. if (this.started) {
  9218. this._requestIfNeeded();
  9219. }
  9220. else if (this.autoStart) {
  9221. this.start();
  9222. }
  9223. };
  9224. /**
  9225. * Register a handler for tick events. Calls continuously unless
  9226. * it is removed or the ticker is stopped.
  9227. * @param fn - The listener function to be added for updates
  9228. * @param context - The listener context
  9229. * @param {number} [priority=PIXI.UPDATE_PRIORITY.NORMAL] - The priority for emitting
  9230. * @returns This instance of a ticker
  9231. */
  9232. Ticker.prototype.add = function (fn, context, priority) {
  9233. if (priority === void 0) { priority = UPDATE_PRIORITY.NORMAL; }
  9234. return this._addListener(new TickerListener(fn, context, priority));
  9235. };
  9236. /**
  9237. * Add a handler for the tick event which is only execute once.
  9238. * @param fn - The listener function to be added for one update
  9239. * @param context - The listener context
  9240. * @param {number} [priority=PIXI.UPDATE_PRIORITY.NORMAL] - The priority for emitting
  9241. * @returns This instance of a ticker
  9242. */
  9243. Ticker.prototype.addOnce = function (fn, context, priority) {
  9244. if (priority === void 0) { priority = UPDATE_PRIORITY.NORMAL; }
  9245. return this._addListener(new TickerListener(fn, context, priority, true));
  9246. };
  9247. /**
  9248. * Internally adds the event handler so that it can be sorted by priority.
  9249. * Priority allows certain handler (user, AnimatedSprite, Interaction) to be run
  9250. * before the rendering.
  9251. * @private
  9252. * @param listener - Current listener being added.
  9253. * @returns This instance of a ticker
  9254. */
  9255. Ticker.prototype._addListener = function (listener) {
  9256. // For attaching to head
  9257. var current = this._head.next;
  9258. var previous = this._head;
  9259. // Add the first item
  9260. if (!current) {
  9261. listener.connect(previous);
  9262. }
  9263. else {
  9264. // Go from highest to lowest priority
  9265. while (current) {
  9266. if (listener.priority > current.priority) {
  9267. listener.connect(previous);
  9268. break;
  9269. }
  9270. previous = current;
  9271. current = current.next;
  9272. }
  9273. // Not yet connected
  9274. if (!listener.previous) {
  9275. listener.connect(previous);
  9276. }
  9277. }
  9278. this._startIfPossible();
  9279. return this;
  9280. };
  9281. /**
  9282. * Removes any handlers matching the function and context parameters.
  9283. * If no handlers are left after removing, then it cancels the animation frame.
  9284. * @param fn - The listener function to be removed
  9285. * @param context - The listener context to be removed
  9286. * @returns This instance of a ticker
  9287. */
  9288. Ticker.prototype.remove = function (fn, context) {
  9289. var listener = this._head.next;
  9290. while (listener) {
  9291. // We found a match, lets remove it
  9292. // no break to delete all possible matches
  9293. // incase a listener was added 2+ times
  9294. if (listener.match(fn, context)) {
  9295. listener = listener.destroy();
  9296. }
  9297. else {
  9298. listener = listener.next;
  9299. }
  9300. }
  9301. if (!this._head.next) {
  9302. this._cancelIfNeeded();
  9303. }
  9304. return this;
  9305. };
  9306. Object.defineProperty(Ticker.prototype, "count", {
  9307. /**
  9308. * The number of listeners on this ticker, calculated by walking through linked list
  9309. * @readonly
  9310. * @member {number}
  9311. */
  9312. get: function () {
  9313. if (!this._head) {
  9314. return 0;
  9315. }
  9316. var count = 0;
  9317. var current = this._head;
  9318. while ((current = current.next)) {
  9319. count++;
  9320. }
  9321. return count;
  9322. },
  9323. enumerable: false,
  9324. configurable: true
  9325. });
  9326. /** Starts the ticker. If the ticker has listeners a new animation frame is requested at this point. */
  9327. Ticker.prototype.start = function () {
  9328. if (!this.started) {
  9329. this.started = true;
  9330. this._requestIfNeeded();
  9331. }
  9332. };
  9333. /** Stops the ticker. If the ticker has requested an animation frame it is canceled at this point. */
  9334. Ticker.prototype.stop = function () {
  9335. if (this.started) {
  9336. this.started = false;
  9337. this._cancelIfNeeded();
  9338. }
  9339. };
  9340. /** Destroy the ticker and don't use after this. Calling this method removes all references to internal events. */
  9341. Ticker.prototype.destroy = function () {
  9342. if (!this._protected) {
  9343. this.stop();
  9344. var listener = this._head.next;
  9345. while (listener) {
  9346. listener = listener.destroy(true);
  9347. }
  9348. this._head.destroy();
  9349. this._head = null;
  9350. }
  9351. };
  9352. /**
  9353. * Triggers an update. An update entails setting the
  9354. * current {@link PIXI.Ticker#elapsedMS},
  9355. * the current {@link PIXI.Ticker#deltaTime},
  9356. * invoking all listeners with current deltaTime,
  9357. * and then finally setting {@link PIXI.Ticker#lastTime}
  9358. * with the value of currentTime that was provided.
  9359. * This method will be called automatically by animation
  9360. * frame callbacks if the ticker instance has been started
  9361. * and listeners are added.
  9362. * @param {number} [currentTime=performance.now()] - the current time of execution
  9363. */
  9364. Ticker.prototype.update = function (currentTime) {
  9365. if (currentTime === void 0) { currentTime = performance.now(); }
  9366. var elapsedMS;
  9367. // If the difference in time is zero or negative, we ignore most of the work done here.
  9368. // If there is no valid difference, then should be no reason to let anyone know about it.
  9369. // A zero delta, is exactly that, nothing should update.
  9370. //
  9371. // The difference in time can be negative, and no this does not mean time traveling.
  9372. // This can be the result of a race condition between when an animation frame is requested
  9373. // on the current JavaScript engine event loop, and when the ticker's start method is invoked
  9374. // (which invokes the internal _requestIfNeeded method). If a frame is requested before
  9375. // _requestIfNeeded is invoked, then the callback for the animation frame the ticker requests,
  9376. // can receive a time argument that can be less than the lastTime value that was set within
  9377. // _requestIfNeeded. This difference is in microseconds, but this is enough to cause problems.
  9378. //
  9379. // This check covers this browser engine timing issue, as well as if consumers pass an invalid
  9380. // currentTime value. This may happen if consumers opt-out of the autoStart, and update themselves.
  9381. if (currentTime > this.lastTime) {
  9382. // Save uncapped elapsedMS for measurement
  9383. elapsedMS = this.elapsedMS = currentTime - this.lastTime;
  9384. // cap the milliseconds elapsed used for deltaTime
  9385. if (elapsedMS > this._maxElapsedMS) {
  9386. elapsedMS = this._maxElapsedMS;
  9387. }
  9388. elapsedMS *= this.speed;
  9389. // If not enough time has passed, exit the function.
  9390. // Get ready for next frame by setting _lastFrame, but based on _minElapsedMS
  9391. // adjustment to ensure a relatively stable interval.
  9392. if (this._minElapsedMS) {
  9393. var delta = currentTime - this._lastFrame | 0;
  9394. if (delta < this._minElapsedMS) {
  9395. return;
  9396. }
  9397. this._lastFrame = currentTime - (delta % this._minElapsedMS);
  9398. }
  9399. this.deltaMS = elapsedMS;
  9400. this.deltaTime = this.deltaMS * settings.TARGET_FPMS;
  9401. // Cache a local reference, in-case ticker is destroyed
  9402. // during the emit, we can still check for head.next
  9403. var head = this._head;
  9404. // Invoke listeners added to internal emitter
  9405. var listener = head.next;
  9406. while (listener) {
  9407. listener = listener.emit(this.deltaTime);
  9408. }
  9409. if (!head.next) {
  9410. this._cancelIfNeeded();
  9411. }
  9412. }
  9413. else {
  9414. this.deltaTime = this.deltaMS = this.elapsedMS = 0;
  9415. }
  9416. this.lastTime = currentTime;
  9417. };
  9418. Object.defineProperty(Ticker.prototype, "FPS", {
  9419. /**
  9420. * The frames per second at which this ticker is running.
  9421. * The default is approximately 60 in most modern browsers.
  9422. * **Note:** This does not factor in the value of
  9423. * {@link PIXI.Ticker#speed}, which is specific
  9424. * to scaling {@link PIXI.Ticker#deltaTime}.
  9425. * @member {number}
  9426. * @readonly
  9427. */
  9428. get: function () {
  9429. return 1000 / this.elapsedMS;
  9430. },
  9431. enumerable: false,
  9432. configurable: true
  9433. });
  9434. Object.defineProperty(Ticker.prototype, "minFPS", {
  9435. /**
  9436. * Manages the maximum amount of milliseconds allowed to
  9437. * elapse between invoking {@link PIXI.Ticker#update}.
  9438. * This value is used to cap {@link PIXI.Ticker#deltaTime},
  9439. * but does not effect the measured value of {@link PIXI.Ticker#FPS}.
  9440. * When setting this property it is clamped to a value between
  9441. * `0` and `PIXI.settings.TARGET_FPMS * 1000`.
  9442. * @member {number}
  9443. * @default 10
  9444. */
  9445. get: function () {
  9446. return 1000 / this._maxElapsedMS;
  9447. },
  9448. set: function (fps) {
  9449. // Minimum must be below the maxFPS
  9450. var minFPS = Math.min(this.maxFPS, fps);
  9451. // Must be at least 0, but below 1 / settings.TARGET_FPMS
  9452. var minFPMS = Math.min(Math.max(0, minFPS) / 1000, settings.TARGET_FPMS);
  9453. this._maxElapsedMS = 1 / minFPMS;
  9454. },
  9455. enumerable: false,
  9456. configurable: true
  9457. });
  9458. Object.defineProperty(Ticker.prototype, "maxFPS", {
  9459. /**
  9460. * Manages the minimum amount of milliseconds required to
  9461. * elapse between invoking {@link PIXI.Ticker#update}.
  9462. * This will effect the measured value of {@link PIXI.Ticker#FPS}.
  9463. * If it is set to `0`, then there is no limit; PixiJS will render as many frames as it can.
  9464. * Otherwise it will be at least `minFPS`
  9465. * @member {number}
  9466. * @default 0
  9467. */
  9468. get: function () {
  9469. if (this._minElapsedMS) {
  9470. return Math.round(1000 / this._minElapsedMS);
  9471. }
  9472. return 0;
  9473. },
  9474. set: function (fps) {
  9475. if (fps === 0) {
  9476. this._minElapsedMS = 0;
  9477. }
  9478. else {
  9479. // Max must be at least the minFPS
  9480. var maxFPS = Math.max(this.minFPS, fps);
  9481. this._minElapsedMS = 1 / (maxFPS / 1000);
  9482. }
  9483. },
  9484. enumerable: false,
  9485. configurable: true
  9486. });
  9487. Object.defineProperty(Ticker, "shared", {
  9488. /**
  9489. * The shared ticker instance used by {@link PIXI.AnimatedSprite} and by
  9490. * {@link PIXI.VideoResource} to update animation frames / video textures.
  9491. *
  9492. * It may also be used by {@link PIXI.Application} if created with the `sharedTicker` option property set to true.
  9493. *
  9494. * The property {@link PIXI.Ticker#autoStart} is set to `true` for this instance.
  9495. * Please follow the examples for usage, including how to opt-out of auto-starting the shared ticker.
  9496. * @example
  9497. * let ticker = PIXI.Ticker.shared;
  9498. * // Set this to prevent starting this ticker when listeners are added.
  9499. * // By default this is true only for the PIXI.Ticker.shared instance.
  9500. * ticker.autoStart = false;
  9501. * // FYI, call this to ensure the ticker is stopped. It should be stopped
  9502. * // if you have not attempted to render anything yet.
  9503. * ticker.stop();
  9504. * // Call this when you are ready for a running shared ticker.
  9505. * ticker.start();
  9506. * @example
  9507. * // You may use the shared ticker to render...
  9508. * let renderer = PIXI.autoDetectRenderer();
  9509. * let stage = new PIXI.Container();
  9510. * document.body.appendChild(renderer.view);
  9511. * ticker.add(function (time) {
  9512. * renderer.render(stage);
  9513. * });
  9514. * @example
  9515. * // Or you can just update it manually.
  9516. * ticker.autoStart = false;
  9517. * ticker.stop();
  9518. * function animate(time) {
  9519. * ticker.update(time);
  9520. * renderer.render(stage);
  9521. * requestAnimationFrame(animate);
  9522. * }
  9523. * animate(performance.now());
  9524. * @member {PIXI.Ticker}
  9525. * @static
  9526. */
  9527. get: function () {
  9528. if (!Ticker._shared) {
  9529. var shared = Ticker._shared = new Ticker();
  9530. shared.autoStart = true;
  9531. shared._protected = true;
  9532. }
  9533. return Ticker._shared;
  9534. },
  9535. enumerable: false,
  9536. configurable: true
  9537. });
  9538. Object.defineProperty(Ticker, "system", {
  9539. /**
  9540. * The system ticker instance used by {@link PIXI.InteractionManager} and by
  9541. * {@link PIXI.BasePrepare} for core timing functionality that shouldn't usually need to be paused,
  9542. * unlike the `shared` ticker which drives visual animations and rendering which may want to be paused.
  9543. *
  9544. * The property {@link PIXI.Ticker#autoStart} is set to `true` for this instance.
  9545. * @member {PIXI.Ticker}
  9546. * @static
  9547. */
  9548. get: function () {
  9549. if (!Ticker._system) {
  9550. var system = Ticker._system = new Ticker();
  9551. system.autoStart = true;
  9552. system._protected = true;
  9553. }
  9554. return Ticker._system;
  9555. },
  9556. enumerable: false,
  9557. configurable: true
  9558. });
  9559. return Ticker;
  9560. }());
  9561. /**
  9562. * Middleware for for Application Ticker.
  9563. * @example
  9564. * import {TickerPlugin} from '@pixi/ticker';
  9565. * import {Application} from '@pixi/app';
  9566. * import {extensions} from '@pixi/extensions';
  9567. * extensions.add(TickerPlugin);
  9568. * @class
  9569. * @memberof PIXI
  9570. */
  9571. var TickerPlugin = /** @class */ (function () {
  9572. function TickerPlugin() {
  9573. }
  9574. /**
  9575. * Initialize the plugin with scope of application instance
  9576. * @static
  9577. * @private
  9578. * @param {object} [options] - See application options
  9579. */
  9580. TickerPlugin.init = function (options) {
  9581. var _this = this;
  9582. // Set default
  9583. options = Object.assign({
  9584. autoStart: true,
  9585. sharedTicker: false,
  9586. }, options);
  9587. // Create ticker setter
  9588. Object.defineProperty(this, 'ticker', {
  9589. set: function (ticker) {
  9590. if (this._ticker) {
  9591. this._ticker.remove(this.render, this);
  9592. }
  9593. this._ticker = ticker;
  9594. if (ticker) {
  9595. ticker.add(this.render, this, UPDATE_PRIORITY.LOW);
  9596. }
  9597. },
  9598. get: function () {
  9599. return this._ticker;
  9600. },
  9601. });
  9602. /**
  9603. * Convenience method for stopping the render.
  9604. * @method
  9605. * @memberof PIXI.Application
  9606. * @instance
  9607. */
  9608. this.stop = function () {
  9609. _this._ticker.stop();
  9610. };
  9611. /**
  9612. * Convenience method for starting the render.
  9613. * @method
  9614. * @memberof PIXI.Application
  9615. * @instance
  9616. */
  9617. this.start = function () {
  9618. _this._ticker.start();
  9619. };
  9620. /**
  9621. * Internal reference to the ticker.
  9622. * @type {PIXI.Ticker}
  9623. * @name _ticker
  9624. * @memberof PIXI.Application#
  9625. * @private
  9626. */
  9627. this._ticker = null;
  9628. /**
  9629. * Ticker for doing render updates.
  9630. * @type {PIXI.Ticker}
  9631. * @name ticker
  9632. * @memberof PIXI.Application#
  9633. * @default PIXI.Ticker.shared
  9634. */
  9635. this.ticker = options.sharedTicker ? Ticker.shared : new Ticker();
  9636. // Start the rendering
  9637. if (options.autoStart) {
  9638. this.start();
  9639. }
  9640. };
  9641. /**
  9642. * Clean up the ticker, scoped to application.
  9643. * @static
  9644. * @private
  9645. */
  9646. TickerPlugin.destroy = function () {
  9647. if (this._ticker) {
  9648. var oldTicker = this._ticker;
  9649. this.ticker = null;
  9650. oldTicker.destroy();
  9651. }
  9652. };
  9653. /** @ignore */
  9654. TickerPlugin.extension = ExtensionType.Application;
  9655. return TickerPlugin;
  9656. }());
  9657. /*!
  9658. * @pixi/core - v6.5.10
  9659. * Compiled Thu, 06 Jul 2023 15:25:11 UTC
  9660. *
  9661. * @pixi/core is licensed under the MIT License.
  9662. * http://www.opensource.org/licenses/mit-license
  9663. */
  9664. /**
  9665. * The maximum support for using WebGL. If a device does not
  9666. * support WebGL version, for instance WebGL 2, it will still
  9667. * attempt to fallback support to WebGL 1. If you want to
  9668. * explicitly remove feature support to target a more stable
  9669. * baseline, prefer a lower environment.
  9670. *
  9671. * Due to {@link https://bugs.chromium.org/p/chromium/issues/detail?id=934823|bug in chromium}
  9672. * we disable webgl2 by default for all non-apple mobile devices.
  9673. * @static
  9674. * @name PREFER_ENV
  9675. * @memberof PIXI.settings
  9676. * @type {number}
  9677. * @default PIXI.ENV.WEBGL2
  9678. */
  9679. settings.PREFER_ENV = isMobile.any ? ENV.WEBGL : ENV.WEBGL2;
  9680. /**
  9681. * If set to `true`, *only* Textures and BaseTexture objects stored
  9682. * in the caches ({@link PIXI.utils.TextureCache TextureCache} and
  9683. * {@link PIXI.utils.BaseTextureCache BaseTextureCache}) can be
  9684. * used when calling {@link PIXI.Texture.from Texture.from} or
  9685. * {@link PIXI.BaseTexture.from BaseTexture.from}.
  9686. * Otherwise, these `from` calls throw an exception. Using this property
  9687. * can be useful if you want to enforce preloading all assets with
  9688. * {@link PIXI.Loader Loader}.
  9689. * @static
  9690. * @name STRICT_TEXTURE_CACHE
  9691. * @memberof PIXI.settings
  9692. * @type {boolean}
  9693. * @default false
  9694. */
  9695. settings.STRICT_TEXTURE_CACHE = false;
  9696. /**
  9697. * Collection of installed resource types, class must extend {@link PIXI.Resource}.
  9698. * @example
  9699. * class CustomResource extends PIXI.Resource {
  9700. * // MUST have source, options constructor signature
  9701. * // for auto-detected resources to be created.
  9702. * constructor(source, options) {
  9703. * super();
  9704. * }
  9705. * upload(renderer, baseTexture, glTexture) {
  9706. * // upload with GL
  9707. * return true;
  9708. * }
  9709. * // used to auto-detect resource
  9710. * static test(source, extension) {
  9711. * return extension === 'xyz'|| source instanceof SomeClass;
  9712. * }
  9713. * }
  9714. * // Install the new resource type
  9715. * PIXI.INSTALLED.push(CustomResource);
  9716. * @memberof PIXI
  9717. * @type {Array<PIXI.IResourcePlugin>}
  9718. * @static
  9719. * @readonly
  9720. */
  9721. var INSTALLED = [];
  9722. /**
  9723. * Create a resource element from a single source element. This
  9724. * auto-detects which type of resource to create. All resources that
  9725. * are auto-detectable must have a static `test` method and a constructor
  9726. * with the arguments `(source, options?)`. Currently, the supported
  9727. * resources for auto-detection include:
  9728. * - {@link PIXI.ImageResource}
  9729. * - {@link PIXI.CanvasResource}
  9730. * - {@link PIXI.VideoResource}
  9731. * - {@link PIXI.SVGResource}
  9732. * - {@link PIXI.BufferResource}
  9733. * @static
  9734. * @memberof PIXI
  9735. * @function autoDetectResource
  9736. * @param {string|*} source - Resource source, this can be the URL to the resource,
  9737. * a typed-array (for BufferResource), HTMLVideoElement, SVG data-uri
  9738. * or any other resource that can be auto-detected. If not resource is
  9739. * detected, it's assumed to be an ImageResource.
  9740. * @param {object} [options] - Pass-through options to use for Resource
  9741. * @param {number} [options.width] - Width of BufferResource or SVG rasterization
  9742. * @param {number} [options.height] - Height of BufferResource or SVG rasterization
  9743. * @param {boolean} [options.autoLoad=true] - Image, SVG and Video flag to start loading
  9744. * @param {number} [options.scale=1] - SVG source scale. Overridden by width, height
  9745. * @param {boolean} [options.createBitmap=PIXI.settings.CREATE_IMAGE_BITMAP] - Image option to create Bitmap object
  9746. * @param {boolean} [options.crossorigin=true] - Image and Video option to set crossOrigin
  9747. * @param {boolean} [options.autoPlay=true] - Video option to start playing video immediately
  9748. * @param {number} [options.updateFPS=0] - Video option to update how many times a second the
  9749. * texture should be updated from the video. Leave at 0 to update at every render
  9750. * @returns {PIXI.Resource} The created resource.
  9751. */
  9752. function autoDetectResource(source, options) {
  9753. if (!source) {
  9754. return null;
  9755. }
  9756. var extension = '';
  9757. if (typeof source === 'string') {
  9758. // search for file extension: period, 3-4 chars, then ?, # or EOL
  9759. var result = (/\.(\w{3,4})(?:$|\?|#)/i).exec(source);
  9760. if (result) {
  9761. extension = result[1].toLowerCase();
  9762. }
  9763. }
  9764. for (var i = INSTALLED.length - 1; i >= 0; --i) {
  9765. var ResourcePlugin = INSTALLED[i];
  9766. if (ResourcePlugin.test && ResourcePlugin.test(source, extension)) {
  9767. return new ResourcePlugin(source, options);
  9768. }
  9769. }
  9770. throw new Error('Unrecognized source type to auto-detect Resource');
  9771. }
  9772. /*! *****************************************************************************
  9773. Copyright (c) Microsoft Corporation.
  9774. Permission to use, copy, modify, and/or distribute this software for any
  9775. purpose with or without fee is hereby granted.
  9776. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  9777. REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
  9778. AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  9779. INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
  9780. LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
  9781. OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
  9782. PERFORMANCE OF THIS SOFTWARE.
  9783. ***************************************************************************** */
  9784. /* global Reflect, Promise */
  9785. var extendStatics$i = function(d, b) {
  9786. extendStatics$i = Object.setPrototypeOf ||
  9787. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  9788. function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } };
  9789. return extendStatics$i(d, b);
  9790. };
  9791. function __extends$i(d, b) {
  9792. extendStatics$i(d, b);
  9793. function __() { this.constructor = d; }
  9794. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  9795. }
  9796. var __assign = function() {
  9797. __assign = Object.assign || function __assign(t) {
  9798. var arguments$1 = arguments;
  9799. for (var s, i = 1, n = arguments.length; i < n; i++) {
  9800. s = arguments$1[i];
  9801. for (var p in s) { if (Object.prototype.hasOwnProperty.call(s, p)) { t[p] = s[p]; } }
  9802. }
  9803. return t;
  9804. };
  9805. return __assign.apply(this, arguments);
  9806. };
  9807. function __rest(s, e) {
  9808. var t = {};
  9809. for (var p in s) { if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
  9810. { t[p] = s[p]; } }
  9811. if (s != null && typeof Object.getOwnPropertySymbols === "function")
  9812. { for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
  9813. if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
  9814. { t[p[i]] = s[p[i]]; }
  9815. } }
  9816. return t;
  9817. }
  9818. /**
  9819. * Base resource class for textures that manages validation and uploading, depending on its type.
  9820. *
  9821. * Uploading of a base texture to the GPU is required.
  9822. * @memberof PIXI
  9823. */
  9824. var Resource = /** @class */ (function () {
  9825. /**
  9826. * @param width - Width of the resource
  9827. * @param height - Height of the resource
  9828. */
  9829. function Resource(width, height) {
  9830. if (width === void 0) { width = 0; }
  9831. if (height === void 0) { height = 0; }
  9832. this._width = width;
  9833. this._height = height;
  9834. this.destroyed = false;
  9835. this.internal = false;
  9836. this.onResize = new Runner('setRealSize');
  9837. this.onUpdate = new Runner('update');
  9838. this.onError = new Runner('onError');
  9839. }
  9840. /**
  9841. * Bind to a parent BaseTexture
  9842. * @param baseTexture - Parent texture
  9843. */
  9844. Resource.prototype.bind = function (baseTexture) {
  9845. this.onResize.add(baseTexture);
  9846. this.onUpdate.add(baseTexture);
  9847. this.onError.add(baseTexture);
  9848. // Call a resize immediate if we already
  9849. // have the width and height of the resource
  9850. if (this._width || this._height) {
  9851. this.onResize.emit(this._width, this._height);
  9852. }
  9853. };
  9854. /**
  9855. * Unbind to a parent BaseTexture
  9856. * @param baseTexture - Parent texture
  9857. */
  9858. Resource.prototype.unbind = function (baseTexture) {
  9859. this.onResize.remove(baseTexture);
  9860. this.onUpdate.remove(baseTexture);
  9861. this.onError.remove(baseTexture);
  9862. };
  9863. /**
  9864. * Trigger a resize event
  9865. * @param width - X dimension
  9866. * @param height - Y dimension
  9867. */
  9868. Resource.prototype.resize = function (width, height) {
  9869. if (width !== this._width || height !== this._height) {
  9870. this._width = width;
  9871. this._height = height;
  9872. this.onResize.emit(width, height);
  9873. }
  9874. };
  9875. Object.defineProperty(Resource.prototype, "valid", {
  9876. /**
  9877. * Has been validated
  9878. * @readonly
  9879. */
  9880. get: function () {
  9881. return !!this._width && !!this._height;
  9882. },
  9883. enumerable: false,
  9884. configurable: true
  9885. });
  9886. /** Has been updated trigger event. */
  9887. Resource.prototype.update = function () {
  9888. if (!this.destroyed) {
  9889. this.onUpdate.emit();
  9890. }
  9891. };
  9892. /**
  9893. * This can be overridden to start preloading a resource
  9894. * or do any other prepare step.
  9895. * @protected
  9896. * @returns Handle the validate event
  9897. */
  9898. Resource.prototype.load = function () {
  9899. return Promise.resolve(this);
  9900. };
  9901. Object.defineProperty(Resource.prototype, "width", {
  9902. /**
  9903. * The width of the resource.
  9904. * @readonly
  9905. */
  9906. get: function () {
  9907. return this._width;
  9908. },
  9909. enumerable: false,
  9910. configurable: true
  9911. });
  9912. Object.defineProperty(Resource.prototype, "height", {
  9913. /**
  9914. * The height of the resource.
  9915. * @readonly
  9916. */
  9917. get: function () {
  9918. return this._height;
  9919. },
  9920. enumerable: false,
  9921. configurable: true
  9922. });
  9923. /**
  9924. * Set the style, optional to override
  9925. * @param _renderer - yeah, renderer!
  9926. * @param _baseTexture - the texture
  9927. * @param _glTexture - texture instance for this webgl context
  9928. * @returns - `true` is success
  9929. */
  9930. Resource.prototype.style = function (_renderer, _baseTexture, _glTexture) {
  9931. return false;
  9932. };
  9933. /** Clean up anything, this happens when destroying is ready. */
  9934. Resource.prototype.dispose = function () {
  9935. // override
  9936. };
  9937. /**
  9938. * Call when destroying resource, unbind any BaseTexture object
  9939. * before calling this method, as reference counts are maintained
  9940. * internally.
  9941. */
  9942. Resource.prototype.destroy = function () {
  9943. if (!this.destroyed) {
  9944. this.destroyed = true;
  9945. this.dispose();
  9946. this.onError.removeAll();
  9947. this.onError = null;
  9948. this.onResize.removeAll();
  9949. this.onResize = null;
  9950. this.onUpdate.removeAll();
  9951. this.onUpdate = null;
  9952. }
  9953. };
  9954. /**
  9955. * Abstract, used to auto-detect resource type.
  9956. * @param {*} _source - The source object
  9957. * @param {string} _extension - The extension of source, if set
  9958. */
  9959. Resource.test = function (_source, _extension) {
  9960. return false;
  9961. };
  9962. return Resource;
  9963. }());
  9964. /**
  9965. * @interface SharedArrayBuffer
  9966. */
  9967. /**
  9968. * Buffer resource with data of typed array.
  9969. * @memberof PIXI
  9970. */
  9971. var BufferResource = /** @class */ (function (_super) {
  9972. __extends$i(BufferResource, _super);
  9973. /**
  9974. * @param source - Source buffer
  9975. * @param options - Options
  9976. * @param {number} options.width - Width of the texture
  9977. * @param {number} options.height - Height of the texture
  9978. */
  9979. function BufferResource(source, options) {
  9980. var _this = this;
  9981. var _a = options || {}, width = _a.width, height = _a.height;
  9982. if (!width || !height) {
  9983. throw new Error('BufferResource width or height invalid');
  9984. }
  9985. _this = _super.call(this, width, height) || this;
  9986. _this.data = source;
  9987. return _this;
  9988. }
  9989. /**
  9990. * Upload the texture to the GPU.
  9991. * @param renderer - Upload to the renderer
  9992. * @param baseTexture - Reference to parent texture
  9993. * @param glTexture - glTexture
  9994. * @returns - true is success
  9995. */
  9996. BufferResource.prototype.upload = function (renderer, baseTexture, glTexture) {
  9997. var gl = renderer.gl;
  9998. gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, baseTexture.alphaMode === ALPHA_MODES.UNPACK);
  9999. var width = baseTexture.realWidth;
  10000. var height = baseTexture.realHeight;
  10001. if (glTexture.width === width && glTexture.height === height) {
  10002. gl.texSubImage2D(baseTexture.target, 0, 0, 0, width, height, baseTexture.format, glTexture.type, this.data);
  10003. }
  10004. else {
  10005. glTexture.width = width;
  10006. glTexture.height = height;
  10007. gl.texImage2D(baseTexture.target, 0, glTexture.internalFormat, width, height, 0, baseTexture.format, glTexture.type, this.data);
  10008. }
  10009. return true;
  10010. };
  10011. /** Destroy and don't use after this. */
  10012. BufferResource.prototype.dispose = function () {
  10013. this.data = null;
  10014. };
  10015. /**
  10016. * Used to auto-detect the type of resource.
  10017. * @param {*} source - The source object
  10018. * @returns {boolean} `true` if <canvas>
  10019. */
  10020. BufferResource.test = function (source) {
  10021. return source instanceof Float32Array
  10022. || source instanceof Uint8Array
  10023. || source instanceof Uint32Array;
  10024. };
  10025. return BufferResource;
  10026. }(Resource));
  10027. var defaultBufferOptions = {
  10028. scaleMode: SCALE_MODES.NEAREST,
  10029. format: FORMATS.RGBA,
  10030. alphaMode: ALPHA_MODES.NPM,
  10031. };
  10032. /**
  10033. * A Texture stores the information that represents an image.
  10034. * All textures have a base texture, which contains information about the source.
  10035. * Therefore you can have many textures all using a single BaseTexture
  10036. * @memberof PIXI
  10037. * @typeParam R - The BaseTexture's Resource type.
  10038. * @typeParam RO - The options for constructing resource.
  10039. */
  10040. var BaseTexture = /** @class */ (function (_super) {
  10041. __extends$i(BaseTexture, _super);
  10042. /**
  10043. * @param {PIXI.Resource|string|HTMLImageElement|HTMLCanvasElement|HTMLVideoElement} [resource=null] -
  10044. * The current resource to use, for things that aren't Resource objects, will be converted
  10045. * into a Resource.
  10046. * @param options - Collection of options
  10047. * @param {PIXI.MIPMAP_MODES} [options.mipmap=PIXI.settings.MIPMAP_TEXTURES] - If mipmapping is enabled for texture
  10048. * @param {number} [options.anisotropicLevel=PIXI.settings.ANISOTROPIC_LEVEL] - Anisotropic filtering level of texture
  10049. * @param {PIXI.WRAP_MODES} [options.wrapMode=PIXI.settings.WRAP_MODE] - Wrap mode for textures
  10050. * @param {PIXI.SCALE_MODES} [options.scaleMode=PIXI.settings.SCALE_MODE] - Default scale mode, linear, nearest
  10051. * @param {PIXI.FORMATS} [options.format=PIXI.FORMATS.RGBA] - GL format type
  10052. * @param {PIXI.TYPES} [options.type=PIXI.TYPES.UNSIGNED_BYTE] - GL data type
  10053. * @param {PIXI.TARGETS} [options.target=PIXI.TARGETS.TEXTURE_2D] - GL texture target
  10054. * @param {PIXI.ALPHA_MODES} [options.alphaMode=PIXI.ALPHA_MODES.UNPACK] - Pre multiply the image alpha
  10055. * @param {number} [options.width=0] - Width of the texture
  10056. * @param {number} [options.height=0] - Height of the texture
  10057. * @param {number} [options.resolution=PIXI.settings.RESOLUTION] - Resolution of the base texture
  10058. * @param {object} [options.resourceOptions] - Optional resource options,
  10059. * see {@link PIXI.autoDetectResource autoDetectResource}
  10060. */
  10061. function BaseTexture(resource, options) {
  10062. if (resource === void 0) { resource = null; }
  10063. if (options === void 0) { options = null; }
  10064. var _this = _super.call(this) || this;
  10065. options = options || {};
  10066. var alphaMode = options.alphaMode, mipmap = options.mipmap, anisotropicLevel = options.anisotropicLevel, scaleMode = options.scaleMode, width = options.width, height = options.height, wrapMode = options.wrapMode, format = options.format, type = options.type, target = options.target, resolution = options.resolution, resourceOptions = options.resourceOptions;
  10067. // Convert the resource to a Resource object
  10068. if (resource && !(resource instanceof Resource)) {
  10069. resource = autoDetectResource(resource, resourceOptions);
  10070. resource.internal = true;
  10071. }
  10072. _this.resolution = resolution || settings.RESOLUTION;
  10073. _this.width = Math.round((width || 0) * _this.resolution) / _this.resolution;
  10074. _this.height = Math.round((height || 0) * _this.resolution) / _this.resolution;
  10075. _this._mipmap = mipmap !== undefined ? mipmap : settings.MIPMAP_TEXTURES;
  10076. _this.anisotropicLevel = anisotropicLevel !== undefined ? anisotropicLevel : settings.ANISOTROPIC_LEVEL;
  10077. _this._wrapMode = wrapMode || settings.WRAP_MODE;
  10078. _this._scaleMode = scaleMode !== undefined ? scaleMode : settings.SCALE_MODE;
  10079. _this.format = format || FORMATS.RGBA;
  10080. _this.type = type || TYPES.UNSIGNED_BYTE;
  10081. _this.target = target || TARGETS.TEXTURE_2D;
  10082. _this.alphaMode = alphaMode !== undefined ? alphaMode : ALPHA_MODES.UNPACK;
  10083. _this.uid = uid();
  10084. _this.touched = 0;
  10085. _this.isPowerOfTwo = false;
  10086. _this._refreshPOT();
  10087. _this._glTextures = {};
  10088. _this.dirtyId = 0;
  10089. _this.dirtyStyleId = 0;
  10090. _this.cacheId = null;
  10091. _this.valid = width > 0 && height > 0;
  10092. _this.textureCacheIds = [];
  10093. _this.destroyed = false;
  10094. _this.resource = null;
  10095. _this._batchEnabled = 0;
  10096. _this._batchLocation = 0;
  10097. _this.parentTextureArray = null;
  10098. /**
  10099. * Fired when a not-immediately-available source finishes loading.
  10100. * @protected
  10101. * @event PIXI.BaseTexture#loaded
  10102. * @param {PIXI.BaseTexture} baseTexture - Resource loaded.
  10103. */
  10104. /**
  10105. * Fired when a not-immediately-available source fails to load.
  10106. * @protected
  10107. * @event PIXI.BaseTexture#error
  10108. * @param {PIXI.BaseTexture} baseTexture - Resource errored.
  10109. * @param {ErrorEvent} event - Load error event.
  10110. */
  10111. /**
  10112. * Fired when BaseTexture is updated.
  10113. * @protected
  10114. * @event PIXI.BaseTexture#loaded
  10115. * @param {PIXI.BaseTexture} baseTexture - Resource loaded.
  10116. */
  10117. /**
  10118. * Fired when BaseTexture is updated.
  10119. * @protected
  10120. * @event PIXI.BaseTexture#update
  10121. * @param {PIXI.BaseTexture} baseTexture - Instance of texture being updated.
  10122. */
  10123. /**
  10124. * Fired when BaseTexture is destroyed.
  10125. * @protected
  10126. * @event PIXI.BaseTexture#dispose
  10127. * @param {PIXI.BaseTexture} baseTexture - Instance of texture being destroyed.
  10128. */
  10129. // Set the resource
  10130. _this.setResource(resource);
  10131. return _this;
  10132. }
  10133. Object.defineProperty(BaseTexture.prototype, "realWidth", {
  10134. /**
  10135. * Pixel width of the source of this texture
  10136. * @readonly
  10137. */
  10138. get: function () {
  10139. return Math.round(this.width * this.resolution);
  10140. },
  10141. enumerable: false,
  10142. configurable: true
  10143. });
  10144. Object.defineProperty(BaseTexture.prototype, "realHeight", {
  10145. /**
  10146. * Pixel height of the source of this texture
  10147. * @readonly
  10148. */
  10149. get: function () {
  10150. return Math.round(this.height * this.resolution);
  10151. },
  10152. enumerable: false,
  10153. configurable: true
  10154. });
  10155. Object.defineProperty(BaseTexture.prototype, "mipmap", {
  10156. /**
  10157. * Mipmap mode of the texture, affects downscaled images
  10158. * @default PIXI.settings.MIPMAP_TEXTURES
  10159. */
  10160. get: function () {
  10161. return this._mipmap;
  10162. },
  10163. set: function (value) {
  10164. if (this._mipmap !== value) {
  10165. this._mipmap = value;
  10166. this.dirtyStyleId++;
  10167. }
  10168. },
  10169. enumerable: false,
  10170. configurable: true
  10171. });
  10172. Object.defineProperty(BaseTexture.prototype, "scaleMode", {
  10173. /**
  10174. * The scale mode to apply when scaling this texture
  10175. * @default PIXI.settings.SCALE_MODE
  10176. */
  10177. get: function () {
  10178. return this._scaleMode;
  10179. },
  10180. set: function (value) {
  10181. if (this._scaleMode !== value) {
  10182. this._scaleMode = value;
  10183. this.dirtyStyleId++;
  10184. }
  10185. },
  10186. enumerable: false,
  10187. configurable: true
  10188. });
  10189. Object.defineProperty(BaseTexture.prototype, "wrapMode", {
  10190. /**
  10191. * How the texture wraps
  10192. * @default PIXI.settings.WRAP_MODE
  10193. */
  10194. get: function () {
  10195. return this._wrapMode;
  10196. },
  10197. set: function (value) {
  10198. if (this._wrapMode !== value) {
  10199. this._wrapMode = value;
  10200. this.dirtyStyleId++;
  10201. }
  10202. },
  10203. enumerable: false,
  10204. configurable: true
  10205. });
  10206. /**
  10207. * Changes style options of BaseTexture
  10208. * @param scaleMode - Pixi scalemode
  10209. * @param mipmap - enable mipmaps
  10210. * @returns - this
  10211. */
  10212. BaseTexture.prototype.setStyle = function (scaleMode, mipmap) {
  10213. var dirty;
  10214. if (scaleMode !== undefined && scaleMode !== this.scaleMode) {
  10215. this.scaleMode = scaleMode;
  10216. dirty = true;
  10217. }
  10218. if (mipmap !== undefined && mipmap !== this.mipmap) {
  10219. this.mipmap = mipmap;
  10220. dirty = true;
  10221. }
  10222. if (dirty) {
  10223. this.dirtyStyleId++;
  10224. }
  10225. return this;
  10226. };
  10227. /**
  10228. * Changes w/h/resolution. Texture becomes valid if width and height are greater than zero.
  10229. * @param desiredWidth - Desired visual width
  10230. * @param desiredHeight - Desired visual height
  10231. * @param resolution - Optionally set resolution
  10232. * @returns - this
  10233. */
  10234. BaseTexture.prototype.setSize = function (desiredWidth, desiredHeight, resolution) {
  10235. resolution = resolution || this.resolution;
  10236. return this.setRealSize(desiredWidth * resolution, desiredHeight * resolution, resolution);
  10237. };
  10238. /**
  10239. * Sets real size of baseTexture, preserves current resolution.
  10240. * @param realWidth - Full rendered width
  10241. * @param realHeight - Full rendered height
  10242. * @param resolution - Optionally set resolution
  10243. * @returns - this
  10244. */
  10245. BaseTexture.prototype.setRealSize = function (realWidth, realHeight, resolution) {
  10246. this.resolution = resolution || this.resolution;
  10247. this.width = Math.round(realWidth) / this.resolution;
  10248. this.height = Math.round(realHeight) / this.resolution;
  10249. this._refreshPOT();
  10250. this.update();
  10251. return this;
  10252. };
  10253. /**
  10254. * Refresh check for isPowerOfTwo texture based on size
  10255. * @private
  10256. */
  10257. BaseTexture.prototype._refreshPOT = function () {
  10258. this.isPowerOfTwo = isPow2(this.realWidth) && isPow2(this.realHeight);
  10259. };
  10260. /**
  10261. * Changes resolution
  10262. * @param resolution - res
  10263. * @returns - this
  10264. */
  10265. BaseTexture.prototype.setResolution = function (resolution) {
  10266. var oldResolution = this.resolution;
  10267. if (oldResolution === resolution) {
  10268. return this;
  10269. }
  10270. this.resolution = resolution;
  10271. if (this.valid) {
  10272. this.width = Math.round(this.width * oldResolution) / resolution;
  10273. this.height = Math.round(this.height * oldResolution) / resolution;
  10274. this.emit('update', this);
  10275. }
  10276. this._refreshPOT();
  10277. return this;
  10278. };
  10279. /**
  10280. * Sets the resource if it wasn't set. Throws error if resource already present
  10281. * @param resource - that is managing this BaseTexture
  10282. * @returns - this
  10283. */
  10284. BaseTexture.prototype.setResource = function (resource) {
  10285. if (this.resource === resource) {
  10286. return this;
  10287. }
  10288. if (this.resource) {
  10289. throw new Error('Resource can be set only once');
  10290. }
  10291. resource.bind(this);
  10292. this.resource = resource;
  10293. return this;
  10294. };
  10295. /** Invalidates the object. Texture becomes valid if width and height are greater than zero. */
  10296. BaseTexture.prototype.update = function () {
  10297. if (!this.valid) {
  10298. if (this.width > 0 && this.height > 0) {
  10299. this.valid = true;
  10300. this.emit('loaded', this);
  10301. this.emit('update', this);
  10302. }
  10303. }
  10304. else {
  10305. this.dirtyId++;
  10306. this.dirtyStyleId++;
  10307. this.emit('update', this);
  10308. }
  10309. };
  10310. /**
  10311. * Handle errors with resources.
  10312. * @private
  10313. * @param event - Error event emitted.
  10314. */
  10315. BaseTexture.prototype.onError = function (event) {
  10316. this.emit('error', this, event);
  10317. };
  10318. /**
  10319. * Destroys this base texture.
  10320. * The method stops if resource doesn't want this texture to be destroyed.
  10321. * Removes texture from all caches.
  10322. */
  10323. BaseTexture.prototype.destroy = function () {
  10324. // remove and destroy the resource
  10325. if (this.resource) {
  10326. this.resource.unbind(this);
  10327. // only destroy resourced created internally
  10328. if (this.resource.internal) {
  10329. this.resource.destroy();
  10330. }
  10331. this.resource = null;
  10332. }
  10333. if (this.cacheId) {
  10334. delete BaseTextureCache[this.cacheId];
  10335. delete TextureCache[this.cacheId];
  10336. this.cacheId = null;
  10337. }
  10338. // finally let the WebGL renderer know..
  10339. this.dispose();
  10340. BaseTexture.removeFromCache(this);
  10341. this.textureCacheIds = null;
  10342. this.destroyed = true;
  10343. };
  10344. /**
  10345. * Frees the texture from WebGL memory without destroying this texture object.
  10346. * This means you can still use the texture later which will upload it to GPU
  10347. * memory again.
  10348. * @fires PIXI.BaseTexture#dispose
  10349. */
  10350. BaseTexture.prototype.dispose = function () {
  10351. this.emit('dispose', this);
  10352. };
  10353. /** Utility function for BaseTexture|Texture cast. */
  10354. BaseTexture.prototype.castToBaseTexture = function () {
  10355. return this;
  10356. };
  10357. /**
  10358. * Helper function that creates a base texture based on the source you provide.
  10359. * The source can be - image url, image element, canvas element. If the
  10360. * source is an image url or an image element and not in the base texture
  10361. * cache, it will be created and loaded.
  10362. * @static
  10363. * @param {string|string[]|HTMLImageElement|HTMLCanvasElement|SVGElement|HTMLVideoElement} source - The
  10364. * source to create base texture from.
  10365. * @param options - See {@link PIXI.BaseTexture}'s constructor for options.
  10366. * @param {string} [options.pixiIdPrefix=pixiid] - If a source has no id, this is the prefix of the generated id
  10367. * @param {boolean} [strict] - Enforce strict-mode, see {@link PIXI.settings.STRICT_TEXTURE_CACHE}.
  10368. * @returns {PIXI.BaseTexture} The new base texture.
  10369. */
  10370. BaseTexture.from = function (source, options, strict) {
  10371. if (strict === void 0) { strict = settings.STRICT_TEXTURE_CACHE; }
  10372. var isFrame = typeof source === 'string';
  10373. var cacheId = null;
  10374. if (isFrame) {
  10375. cacheId = source;
  10376. }
  10377. else {
  10378. if (!source._pixiId) {
  10379. var prefix = (options && options.pixiIdPrefix) || 'pixiid';
  10380. source._pixiId = prefix + "_" + uid();
  10381. }
  10382. cacheId = source._pixiId;
  10383. }
  10384. var baseTexture = BaseTextureCache[cacheId];
  10385. // Strict-mode rejects invalid cacheIds
  10386. if (isFrame && strict && !baseTexture) {
  10387. throw new Error("The cacheId \"" + cacheId + "\" does not exist in BaseTextureCache.");
  10388. }
  10389. if (!baseTexture) {
  10390. baseTexture = new BaseTexture(source, options);
  10391. baseTexture.cacheId = cacheId;
  10392. BaseTexture.addToCache(baseTexture, cacheId);
  10393. }
  10394. return baseTexture;
  10395. };
  10396. /**
  10397. * Create a new BaseTexture with a BufferResource from a Float32Array.
  10398. * RGBA values are floats from 0 to 1.
  10399. * @param {Float32Array|Uint8Array} buffer - The optional array to use, if no data
  10400. * is provided, a new Float32Array is created.
  10401. * @param width - Width of the resource
  10402. * @param height - Height of the resource
  10403. * @param options - See {@link PIXI.BaseTexture}'s constructor for options.
  10404. * Default properties are different from the constructor's defaults.
  10405. * @param {PIXI.FORMATS} [options.format=PIXI.FORMATS.RGBA] - GL format type
  10406. * @param {PIXI.ALPHA_MODES} [options.alphaMode=PIXI.ALPHA_MODES.NPM] - Image alpha, not premultiplied by default
  10407. * @param {PIXI.SCALE_MODES} [options.scaleMode=PIXI.SCALE_MODES.NEAREST] - Scale mode, pixelating by default
  10408. * @returns - The resulting new BaseTexture
  10409. */
  10410. BaseTexture.fromBuffer = function (buffer, width, height, options) {
  10411. buffer = buffer || new Float32Array(width * height * 4);
  10412. var resource = new BufferResource(buffer, { width: width, height: height });
  10413. var type = buffer instanceof Float32Array ? TYPES.FLOAT : TYPES.UNSIGNED_BYTE;
  10414. return new BaseTexture(resource, Object.assign({}, defaultBufferOptions, options || { width: width, height: height, type: type }));
  10415. };
  10416. /**
  10417. * Adds a BaseTexture to the global BaseTextureCache. This cache is shared across the whole PIXI object.
  10418. * @param {PIXI.BaseTexture} baseTexture - The BaseTexture to add to the cache.
  10419. * @param {string} id - The id that the BaseTexture will be stored against.
  10420. */
  10421. BaseTexture.addToCache = function (baseTexture, id) {
  10422. if (id) {
  10423. if (baseTexture.textureCacheIds.indexOf(id) === -1) {
  10424. baseTexture.textureCacheIds.push(id);
  10425. }
  10426. if (BaseTextureCache[id]) {
  10427. // eslint-disable-next-line no-console
  10428. console.warn("BaseTexture added to the cache with an id [" + id + "] that already had an entry");
  10429. }
  10430. BaseTextureCache[id] = baseTexture;
  10431. }
  10432. };
  10433. /**
  10434. * Remove a BaseTexture from the global BaseTextureCache.
  10435. * @param {string|PIXI.BaseTexture} baseTexture - id of a BaseTexture to be removed, or a BaseTexture instance itself.
  10436. * @returns {PIXI.BaseTexture|null} The BaseTexture that was removed.
  10437. */
  10438. BaseTexture.removeFromCache = function (baseTexture) {
  10439. if (typeof baseTexture === 'string') {
  10440. var baseTextureFromCache = BaseTextureCache[baseTexture];
  10441. if (baseTextureFromCache) {
  10442. var index = baseTextureFromCache.textureCacheIds.indexOf(baseTexture);
  10443. if (index > -1) {
  10444. baseTextureFromCache.textureCacheIds.splice(index, 1);
  10445. }
  10446. delete BaseTextureCache[baseTexture];
  10447. return baseTextureFromCache;
  10448. }
  10449. }
  10450. else if (baseTexture && baseTexture.textureCacheIds) {
  10451. for (var i = 0; i < baseTexture.textureCacheIds.length; ++i) {
  10452. delete BaseTextureCache[baseTexture.textureCacheIds[i]];
  10453. }
  10454. baseTexture.textureCacheIds.length = 0;
  10455. return baseTexture;
  10456. }
  10457. return null;
  10458. };
  10459. /** Global number of the texture batch, used by multi-texture renderers. */
  10460. BaseTexture._globalBatch = 0;
  10461. return BaseTexture;
  10462. }(eventemitter3));
  10463. /**
  10464. * Resource that can manage several resource (items) inside.
  10465. * All resources need to have the same pixel size.
  10466. * Parent class for CubeResource and ArrayResource
  10467. * @memberof PIXI
  10468. */
  10469. var AbstractMultiResource = /** @class */ (function (_super) {
  10470. __extends$i(AbstractMultiResource, _super);
  10471. /**
  10472. * @param length
  10473. * @param options - Options to for Resource constructor
  10474. * @param {number} [options.width] - Width of the resource
  10475. * @param {number} [options.height] - Height of the resource
  10476. */
  10477. function AbstractMultiResource(length, options) {
  10478. var _this = this;
  10479. var _a = options || {}, width = _a.width, height = _a.height;
  10480. _this = _super.call(this, width, height) || this;
  10481. _this.items = [];
  10482. _this.itemDirtyIds = [];
  10483. for (var i = 0; i < length; i++) {
  10484. var partTexture = new BaseTexture();
  10485. _this.items.push(partTexture);
  10486. // -2 - first run of texture array upload
  10487. // -1 - texture item was allocated
  10488. // >=0 - texture item uploaded , in sync with items[i].dirtyId
  10489. _this.itemDirtyIds.push(-2);
  10490. }
  10491. _this.length = length;
  10492. _this._load = null;
  10493. _this.baseTexture = null;
  10494. return _this;
  10495. }
  10496. /**
  10497. * Used from ArrayResource and CubeResource constructors.
  10498. * @param resources - Can be resources, image elements, canvas, etc. ,
  10499. * length should be same as constructor length
  10500. * @param options - Detect options for resources
  10501. */
  10502. AbstractMultiResource.prototype.initFromArray = function (resources, options) {
  10503. for (var i = 0; i < this.length; i++) {
  10504. if (!resources[i]) {
  10505. continue;
  10506. }
  10507. if (resources[i].castToBaseTexture) {
  10508. this.addBaseTextureAt(resources[i].castToBaseTexture(), i);
  10509. }
  10510. else if (resources[i] instanceof Resource) {
  10511. this.addResourceAt(resources[i], i);
  10512. }
  10513. else {
  10514. this.addResourceAt(autoDetectResource(resources[i], options), i);
  10515. }
  10516. }
  10517. };
  10518. /** Destroy this BaseImageResource. */
  10519. AbstractMultiResource.prototype.dispose = function () {
  10520. for (var i = 0, len = this.length; i < len; i++) {
  10521. this.items[i].destroy();
  10522. }
  10523. this.items = null;
  10524. this.itemDirtyIds = null;
  10525. this._load = null;
  10526. };
  10527. /**
  10528. * Set a resource by ID
  10529. * @param resource
  10530. * @param index - Zero-based index of resource to set
  10531. * @returns - Instance for chaining
  10532. */
  10533. AbstractMultiResource.prototype.addResourceAt = function (resource, index) {
  10534. if (!this.items[index]) {
  10535. throw new Error("Index " + index + " is out of bounds");
  10536. }
  10537. // Inherit the first resource dimensions
  10538. if (resource.valid && !this.valid) {
  10539. this.resize(resource.width, resource.height);
  10540. }
  10541. this.items[index].setResource(resource);
  10542. return this;
  10543. };
  10544. /**
  10545. * Set the parent base texture.
  10546. * @param baseTexture
  10547. */
  10548. AbstractMultiResource.prototype.bind = function (baseTexture) {
  10549. if (this.baseTexture !== null) {
  10550. throw new Error('Only one base texture per TextureArray is allowed');
  10551. }
  10552. _super.prototype.bind.call(this, baseTexture);
  10553. for (var i = 0; i < this.length; i++) {
  10554. this.items[i].parentTextureArray = baseTexture;
  10555. this.items[i].on('update', baseTexture.update, baseTexture);
  10556. }
  10557. };
  10558. /**
  10559. * Unset the parent base texture.
  10560. * @param baseTexture
  10561. */
  10562. AbstractMultiResource.prototype.unbind = function (baseTexture) {
  10563. _super.prototype.unbind.call(this, baseTexture);
  10564. for (var i = 0; i < this.length; i++) {
  10565. this.items[i].parentTextureArray = null;
  10566. this.items[i].off('update', baseTexture.update, baseTexture);
  10567. }
  10568. };
  10569. /**
  10570. * Load all the resources simultaneously
  10571. * @returns - When load is resolved
  10572. */
  10573. AbstractMultiResource.prototype.load = function () {
  10574. var _this = this;
  10575. if (this._load) {
  10576. return this._load;
  10577. }
  10578. var resources = this.items.map(function (item) { return item.resource; }).filter(function (item) { return item; });
  10579. // TODO: also implement load part-by-part strategy
  10580. var promises = resources.map(function (item) { return item.load(); });
  10581. this._load = Promise.all(promises)
  10582. .then(function () {
  10583. var _a = _this.items[0], realWidth = _a.realWidth, realHeight = _a.realHeight;
  10584. _this.resize(realWidth, realHeight);
  10585. return Promise.resolve(_this);
  10586. });
  10587. return this._load;
  10588. };
  10589. return AbstractMultiResource;
  10590. }(Resource));
  10591. /**
  10592. * A resource that contains a number of sources.
  10593. * @memberof PIXI
  10594. */
  10595. var ArrayResource = /** @class */ (function (_super) {
  10596. __extends$i(ArrayResource, _super);
  10597. /**
  10598. * @param source - Number of items in array or the collection
  10599. * of image URLs to use. Can also be resources, image elements, canvas, etc.
  10600. * @param options - Options to apply to {@link PIXI.autoDetectResource}
  10601. * @param {number} [options.width] - Width of the resource
  10602. * @param {number} [options.height] - Height of the resource
  10603. */
  10604. function ArrayResource(source, options) {
  10605. var _this = this;
  10606. var _a = options || {}, width = _a.width, height = _a.height;
  10607. var urls;
  10608. var length;
  10609. if (Array.isArray(source)) {
  10610. urls = source;
  10611. length = source.length;
  10612. }
  10613. else {
  10614. length = source;
  10615. }
  10616. _this = _super.call(this, length, { width: width, height: height }) || this;
  10617. if (urls) {
  10618. _this.initFromArray(urls, options);
  10619. }
  10620. return _this;
  10621. }
  10622. /**
  10623. * Set a baseTexture by ID,
  10624. * ArrayResource just takes resource from it, nothing more
  10625. * @param baseTexture
  10626. * @param index - Zero-based index of resource to set
  10627. * @returns - Instance for chaining
  10628. */
  10629. ArrayResource.prototype.addBaseTextureAt = function (baseTexture, index) {
  10630. if (baseTexture.resource) {
  10631. this.addResourceAt(baseTexture.resource, index);
  10632. }
  10633. else {
  10634. throw new Error('ArrayResource does not support RenderTexture');
  10635. }
  10636. return this;
  10637. };
  10638. /**
  10639. * Add binding
  10640. * @param baseTexture
  10641. */
  10642. ArrayResource.prototype.bind = function (baseTexture) {
  10643. _super.prototype.bind.call(this, baseTexture);
  10644. baseTexture.target = TARGETS.TEXTURE_2D_ARRAY;
  10645. };
  10646. /**
  10647. * Upload the resources to the GPU.
  10648. * @param renderer
  10649. * @param texture
  10650. * @param glTexture
  10651. * @returns - whether texture was uploaded
  10652. */
  10653. ArrayResource.prototype.upload = function (renderer, texture, glTexture) {
  10654. var _a = this, length = _a.length, itemDirtyIds = _a.itemDirtyIds, items = _a.items;
  10655. var gl = renderer.gl;
  10656. if (glTexture.dirtyId < 0) {
  10657. gl.texImage3D(gl.TEXTURE_2D_ARRAY, 0, glTexture.internalFormat, this._width, this._height, length, 0, texture.format, glTexture.type, null);
  10658. }
  10659. for (var i = 0; i < length; i++) {
  10660. var item = items[i];
  10661. if (itemDirtyIds[i] < item.dirtyId) {
  10662. itemDirtyIds[i] = item.dirtyId;
  10663. if (item.valid) {
  10664. gl.texSubImage3D(gl.TEXTURE_2D_ARRAY, 0, 0, // xoffset
  10665. 0, // yoffset
  10666. i, // zoffset
  10667. item.resource.width, item.resource.height, 1, texture.format, glTexture.type, item.resource.source);
  10668. }
  10669. }
  10670. }
  10671. return true;
  10672. };
  10673. return ArrayResource;
  10674. }(AbstractMultiResource));
  10675. /**
  10676. * Base for all the image/canvas resources.
  10677. * @memberof PIXI
  10678. */
  10679. var BaseImageResource = /** @class */ (function (_super) {
  10680. __extends$i(BaseImageResource, _super);
  10681. /**
  10682. * @param {HTMLImageElement|HTMLCanvasElement|HTMLVideoElement|SVGElement} source
  10683. */
  10684. function BaseImageResource(source) {
  10685. var _this = this;
  10686. var sourceAny = source;
  10687. var width = sourceAny.naturalWidth || sourceAny.videoWidth || sourceAny.width;
  10688. var height = sourceAny.naturalHeight || sourceAny.videoHeight || sourceAny.height;
  10689. _this = _super.call(this, width, height) || this;
  10690. _this.source = source;
  10691. _this.noSubImage = false;
  10692. return _this;
  10693. }
  10694. /**
  10695. * Set cross origin based detecting the url and the crossorigin
  10696. * @param element - Element to apply crossOrigin
  10697. * @param url - URL to check
  10698. * @param crossorigin - Cross origin value to use
  10699. */
  10700. BaseImageResource.crossOrigin = function (element, url, crossorigin) {
  10701. if (crossorigin === undefined && url.indexOf('data:') !== 0) {
  10702. element.crossOrigin = determineCrossOrigin(url);
  10703. }
  10704. else if (crossorigin !== false) {
  10705. element.crossOrigin = typeof crossorigin === 'string' ? crossorigin : 'anonymous';
  10706. }
  10707. };
  10708. /**
  10709. * Upload the texture to the GPU.
  10710. * @param renderer - Upload to the renderer
  10711. * @param baseTexture - Reference to parent texture
  10712. * @param glTexture
  10713. * @param {HTMLImageElement|HTMLCanvasElement|HTMLVideoElement|SVGElement} [source] - (optional)
  10714. * @returns - true is success
  10715. */
  10716. BaseImageResource.prototype.upload = function (renderer, baseTexture, glTexture, source) {
  10717. var gl = renderer.gl;
  10718. var width = baseTexture.realWidth;
  10719. var height = baseTexture.realHeight;
  10720. source = source || this.source;
  10721. if (source instanceof HTMLImageElement) {
  10722. if (!source.complete || source.naturalWidth === 0) {
  10723. return false;
  10724. }
  10725. }
  10726. else if (source instanceof HTMLVideoElement) {
  10727. if (source.readyState <= 1) {
  10728. return false;
  10729. }
  10730. }
  10731. gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, baseTexture.alphaMode === ALPHA_MODES.UNPACK);
  10732. if (!this.noSubImage
  10733. && baseTexture.target === gl.TEXTURE_2D
  10734. && glTexture.width === width
  10735. && glTexture.height === height) {
  10736. gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, baseTexture.format, glTexture.type, source);
  10737. }
  10738. else {
  10739. glTexture.width = width;
  10740. glTexture.height = height;
  10741. gl.texImage2D(baseTexture.target, 0, glTexture.internalFormat, baseTexture.format, glTexture.type, source);
  10742. }
  10743. return true;
  10744. };
  10745. /**
  10746. * Checks if source width/height was changed, resize can cause extra baseTexture update.
  10747. * Triggers one update in any case.
  10748. */
  10749. BaseImageResource.prototype.update = function () {
  10750. if (this.destroyed) {
  10751. return;
  10752. }
  10753. var source = this.source;
  10754. var width = source.naturalWidth || source.videoWidth || source.width;
  10755. var height = source.naturalHeight || source.videoHeight || source.height;
  10756. this.resize(width, height);
  10757. _super.prototype.update.call(this);
  10758. };
  10759. /** Destroy this {@link BaseImageResource} */
  10760. BaseImageResource.prototype.dispose = function () {
  10761. this.source = null;
  10762. };
  10763. return BaseImageResource;
  10764. }(Resource));
  10765. /**
  10766. * @interface OffscreenCanvas
  10767. */
  10768. /**
  10769. * Resource type for HTMLCanvasElement.
  10770. * @memberof PIXI
  10771. */
  10772. var CanvasResource = /** @class */ (function (_super) {
  10773. __extends$i(CanvasResource, _super);
  10774. /**
  10775. * @param source - Canvas element to use
  10776. */
  10777. // eslint-disable-next-line @typescript-eslint/no-useless-constructor
  10778. function CanvasResource(source) {
  10779. return _super.call(this, source) || this;
  10780. }
  10781. /**
  10782. * Used to auto-detect the type of resource.
  10783. * @param {*} source - The source object
  10784. * @returns {boolean} `true` if source is HTMLCanvasElement or OffscreenCanvas
  10785. */
  10786. CanvasResource.test = function (source) {
  10787. var OffscreenCanvas = globalThis.OffscreenCanvas;
  10788. // Check for browsers that don't yet support OffscreenCanvas
  10789. if (OffscreenCanvas && source instanceof OffscreenCanvas) {
  10790. return true;
  10791. }
  10792. return globalThis.HTMLCanvasElement && source instanceof HTMLCanvasElement;
  10793. };
  10794. return CanvasResource;
  10795. }(BaseImageResource));
  10796. /**
  10797. * Resource for a CubeTexture which contains six resources.
  10798. * @memberof PIXI
  10799. */
  10800. var CubeResource = /** @class */ (function (_super) {
  10801. __extends$i(CubeResource, _super);
  10802. /**
  10803. * @param {Array<string|PIXI.Resource>} [source] - Collection of URLs or resources
  10804. * to use as the sides of the cube.
  10805. * @param options - ImageResource options
  10806. * @param {number} [options.width] - Width of resource
  10807. * @param {number} [options.height] - Height of resource
  10808. * @param {number} [options.autoLoad=true] - Whether to auto-load resources
  10809. * @param {number} [options.linkBaseTexture=true] - In case BaseTextures are supplied,
  10810. * whether to copy them or use
  10811. */
  10812. function CubeResource(source, options) {
  10813. var _this = this;
  10814. var _a = options || {}, width = _a.width, height = _a.height, autoLoad = _a.autoLoad, linkBaseTexture = _a.linkBaseTexture;
  10815. if (source && source.length !== CubeResource.SIDES) {
  10816. throw new Error("Invalid length. Got " + source.length + ", expected 6");
  10817. }
  10818. _this = _super.call(this, 6, { width: width, height: height }) || this;
  10819. for (var i = 0; i < CubeResource.SIDES; i++) {
  10820. _this.items[i].target = TARGETS.TEXTURE_CUBE_MAP_POSITIVE_X + i;
  10821. }
  10822. _this.linkBaseTexture = linkBaseTexture !== false;
  10823. if (source) {
  10824. _this.initFromArray(source, options);
  10825. }
  10826. if (autoLoad !== false) {
  10827. _this.load();
  10828. }
  10829. return _this;
  10830. }
  10831. /**
  10832. * Add binding.
  10833. * @param baseTexture - parent base texture
  10834. */
  10835. CubeResource.prototype.bind = function (baseTexture) {
  10836. _super.prototype.bind.call(this, baseTexture);
  10837. baseTexture.target = TARGETS.TEXTURE_CUBE_MAP;
  10838. };
  10839. CubeResource.prototype.addBaseTextureAt = function (baseTexture, index, linkBaseTexture) {
  10840. if (!this.items[index]) {
  10841. throw new Error("Index " + index + " is out of bounds");
  10842. }
  10843. if (!this.linkBaseTexture
  10844. || baseTexture.parentTextureArray
  10845. || Object.keys(baseTexture._glTextures).length > 0) {
  10846. // copy mode
  10847. if (baseTexture.resource) {
  10848. this.addResourceAt(baseTexture.resource, index);
  10849. }
  10850. else {
  10851. throw new Error("CubeResource does not support copying of renderTexture.");
  10852. }
  10853. }
  10854. else {
  10855. // link mode, the difficult one!
  10856. baseTexture.target = TARGETS.TEXTURE_CUBE_MAP_POSITIVE_X + index;
  10857. baseTexture.parentTextureArray = this.baseTexture;
  10858. this.items[index] = baseTexture;
  10859. }
  10860. if (baseTexture.valid && !this.valid) {
  10861. this.resize(baseTexture.realWidth, baseTexture.realHeight);
  10862. }
  10863. this.items[index] = baseTexture;
  10864. return this;
  10865. };
  10866. /**
  10867. * Upload the resource
  10868. * @param renderer
  10869. * @param _baseTexture
  10870. * @param glTexture
  10871. * @returns {boolean} true is success
  10872. */
  10873. CubeResource.prototype.upload = function (renderer, _baseTexture, glTexture) {
  10874. var dirty = this.itemDirtyIds;
  10875. for (var i = 0; i < CubeResource.SIDES; i++) {
  10876. var side = this.items[i];
  10877. if (dirty[i] < side.dirtyId || glTexture.dirtyId < _baseTexture.dirtyId) {
  10878. if (side.valid && side.resource) {
  10879. side.resource.upload(renderer, side, glTexture);
  10880. dirty[i] = side.dirtyId;
  10881. }
  10882. else if (dirty[i] < -1) {
  10883. // either item is not valid yet, either its a renderTexture
  10884. // allocate the memory
  10885. renderer.gl.texImage2D(side.target, 0, glTexture.internalFormat, _baseTexture.realWidth, _baseTexture.realHeight, 0, _baseTexture.format, glTexture.type, null);
  10886. dirty[i] = -1;
  10887. }
  10888. }
  10889. }
  10890. return true;
  10891. };
  10892. /**
  10893. * Used to auto-detect the type of resource.
  10894. * @param {*} source - The source object
  10895. * @returns {boolean} `true` if source is an array of 6 elements
  10896. */
  10897. CubeResource.test = function (source) {
  10898. return Array.isArray(source) && source.length === CubeResource.SIDES;
  10899. };
  10900. /** Number of texture sides to store for CubeResources. */
  10901. CubeResource.SIDES = 6;
  10902. return CubeResource;
  10903. }(AbstractMultiResource));
  10904. /**
  10905. * Resource type for HTMLImageElement.
  10906. * @memberof PIXI
  10907. */
  10908. var ImageResource = /** @class */ (function (_super) {
  10909. __extends$i(ImageResource, _super);
  10910. /**
  10911. * @param source - image source or URL
  10912. * @param options
  10913. * @param {boolean} [options.autoLoad=true] - start loading process
  10914. * @param {boolean} [options.createBitmap=PIXI.settings.CREATE_IMAGE_BITMAP] - whether its required to create
  10915. * a bitmap before upload
  10916. * @param {boolean} [options.crossorigin=true] - Load image using cross origin
  10917. * @param {PIXI.ALPHA_MODES} [options.alphaMode=PIXI.ALPHA_MODES.UNPACK] - Premultiply image alpha in bitmap
  10918. */
  10919. function ImageResource(source, options) {
  10920. var _this = this;
  10921. options = options || {};
  10922. if (!(source instanceof HTMLImageElement)) {
  10923. var imageElement = new Image();
  10924. BaseImageResource.crossOrigin(imageElement, source, options.crossorigin);
  10925. imageElement.src = source;
  10926. source = imageElement;
  10927. }
  10928. _this = _super.call(this, source) || this;
  10929. // FireFox 68, and possibly other versions, seems like setting the HTMLImageElement#width and #height
  10930. // to non-zero values before its loading completes if images are in a cache.
  10931. // Because of this, need to set the `_width` and the `_height` to zero to avoid uploading incomplete images.
  10932. // Please refer to the issue #5968 (https://github.com/pixijs/pixi.js/issues/5968).
  10933. if (!source.complete && !!_this._width && !!_this._height) {
  10934. _this._width = 0;
  10935. _this._height = 0;
  10936. }
  10937. _this.url = source.src;
  10938. _this._process = null;
  10939. _this.preserveBitmap = false;
  10940. _this.createBitmap = (options.createBitmap !== undefined
  10941. ? options.createBitmap : settings.CREATE_IMAGE_BITMAP) && !!globalThis.createImageBitmap;
  10942. _this.alphaMode = typeof options.alphaMode === 'number' ? options.alphaMode : null;
  10943. _this.bitmap = null;
  10944. _this._load = null;
  10945. if (options.autoLoad !== false) {
  10946. _this.load();
  10947. }
  10948. return _this;
  10949. }
  10950. /**
  10951. * Returns a promise when image will be loaded and processed.
  10952. * @param createBitmap - whether process image into bitmap
  10953. */
  10954. ImageResource.prototype.load = function (createBitmap) {
  10955. var _this = this;
  10956. if (this._load) {
  10957. return this._load;
  10958. }
  10959. if (createBitmap !== undefined) {
  10960. this.createBitmap = createBitmap;
  10961. }
  10962. this._load = new Promise(function (resolve, reject) {
  10963. var source = _this.source;
  10964. _this.url = source.src;
  10965. var completed = function () {
  10966. if (_this.destroyed) {
  10967. return;
  10968. }
  10969. source.onload = null;
  10970. source.onerror = null;
  10971. _this.resize(source.width, source.height);
  10972. _this._load = null;
  10973. if (_this.createBitmap) {
  10974. resolve(_this.process());
  10975. }
  10976. else {
  10977. resolve(_this);
  10978. }
  10979. };
  10980. if (source.complete && source.src) {
  10981. completed();
  10982. }
  10983. else {
  10984. source.onload = completed;
  10985. source.onerror = function (event) {
  10986. // Avoids Promise freezing when resource broken
  10987. reject(event);
  10988. _this.onError.emit(event);
  10989. };
  10990. }
  10991. });
  10992. return this._load;
  10993. };
  10994. /**
  10995. * Called when we need to convert image into BitmapImage.
  10996. * Can be called multiple times, real promise is cached inside.
  10997. * @returns - Cached promise to fill that bitmap
  10998. */
  10999. ImageResource.prototype.process = function () {
  11000. var _this = this;
  11001. var source = this.source;
  11002. if (this._process !== null) {
  11003. return this._process;
  11004. }
  11005. if (this.bitmap !== null || !globalThis.createImageBitmap) {
  11006. return Promise.resolve(this);
  11007. }
  11008. var createImageBitmap = globalThis.createImageBitmap;
  11009. var cors = !source.crossOrigin || source.crossOrigin === 'anonymous';
  11010. this._process = fetch(source.src, {
  11011. mode: cors ? 'cors' : 'no-cors'
  11012. })
  11013. .then(function (r) { return r.blob(); })
  11014. .then(function (blob) { return createImageBitmap(blob, 0, 0, source.width, source.height, {
  11015. premultiplyAlpha: _this.alphaMode === null || _this.alphaMode === ALPHA_MODES.UNPACK
  11016. ? 'premultiply' : 'none',
  11017. }); })
  11018. .then(function (bitmap) {
  11019. if (_this.destroyed) {
  11020. return Promise.reject();
  11021. }
  11022. _this.bitmap = bitmap;
  11023. _this.update();
  11024. _this._process = null;
  11025. return Promise.resolve(_this);
  11026. });
  11027. return this._process;
  11028. };
  11029. /**
  11030. * Upload the image resource to GPU.
  11031. * @param renderer - Renderer to upload to
  11032. * @param baseTexture - BaseTexture for this resource
  11033. * @param glTexture - GLTexture to use
  11034. * @returns {boolean} true is success
  11035. */
  11036. ImageResource.prototype.upload = function (renderer, baseTexture, glTexture) {
  11037. if (typeof this.alphaMode === 'number') {
  11038. // bitmap stores unpack premultiply flag, we dont have to notify texImage2D about it
  11039. baseTexture.alphaMode = this.alphaMode;
  11040. }
  11041. if (!this.createBitmap) {
  11042. return _super.prototype.upload.call(this, renderer, baseTexture, glTexture);
  11043. }
  11044. if (!this.bitmap) {
  11045. // yeah, ignore the output
  11046. this.process();
  11047. if (!this.bitmap) {
  11048. return false;
  11049. }
  11050. }
  11051. _super.prototype.upload.call(this, renderer, baseTexture, glTexture, this.bitmap);
  11052. if (!this.preserveBitmap) {
  11053. // checks if there are other renderers that possibly need this bitmap
  11054. var flag = true;
  11055. var glTextures = baseTexture._glTextures;
  11056. for (var key in glTextures) {
  11057. var otherTex = glTextures[key];
  11058. if (otherTex !== glTexture && otherTex.dirtyId !== baseTexture.dirtyId) {
  11059. flag = false;
  11060. break;
  11061. }
  11062. }
  11063. if (flag) {
  11064. if (this.bitmap.close) {
  11065. this.bitmap.close();
  11066. }
  11067. this.bitmap = null;
  11068. }
  11069. }
  11070. return true;
  11071. };
  11072. /** Destroys this resource. */
  11073. ImageResource.prototype.dispose = function () {
  11074. this.source.onload = null;
  11075. this.source.onerror = null;
  11076. _super.prototype.dispose.call(this);
  11077. if (this.bitmap) {
  11078. this.bitmap.close();
  11079. this.bitmap = null;
  11080. }
  11081. this._process = null;
  11082. this._load = null;
  11083. };
  11084. /**
  11085. * Used to auto-detect the type of resource.
  11086. * @param {*} source - The source object
  11087. * @returns {boolean} `true` if source is string or HTMLImageElement
  11088. */
  11089. ImageResource.test = function (source) {
  11090. return typeof source === 'string' || source instanceof HTMLImageElement;
  11091. };
  11092. return ImageResource;
  11093. }(BaseImageResource));
  11094. /**
  11095. * Resource type for SVG elements and graphics.
  11096. * @memberof PIXI
  11097. */
  11098. var SVGResource = /** @class */ (function (_super) {
  11099. __extends$i(SVGResource, _super);
  11100. /**
  11101. * @param sourceBase64 - Base64 encoded SVG element or URL for SVG file.
  11102. * @param {object} [options] - Options to use
  11103. * @param {number} [options.scale=1] - Scale to apply to SVG. Overridden by...
  11104. * @param {number} [options.width] - Rasterize SVG this wide. Aspect ratio preserved if height not specified.
  11105. * @param {number} [options.height] - Rasterize SVG this high. Aspect ratio preserved if width not specified.
  11106. * @param {boolean} [options.autoLoad=true] - Start loading right away.
  11107. */
  11108. function SVGResource(sourceBase64, options) {
  11109. var _this = this;
  11110. options = options || {};
  11111. _this = _super.call(this, settings.ADAPTER.createCanvas()) || this;
  11112. _this._width = 0;
  11113. _this._height = 0;
  11114. _this.svg = sourceBase64;
  11115. _this.scale = options.scale || 1;
  11116. _this._overrideWidth = options.width;
  11117. _this._overrideHeight = options.height;
  11118. _this._resolve = null;
  11119. _this._crossorigin = options.crossorigin;
  11120. _this._load = null;
  11121. if (options.autoLoad !== false) {
  11122. _this.load();
  11123. }
  11124. return _this;
  11125. }
  11126. SVGResource.prototype.load = function () {
  11127. var _this = this;
  11128. if (this._load) {
  11129. return this._load;
  11130. }
  11131. this._load = new Promise(function (resolve) {
  11132. // Save this until after load is finished
  11133. _this._resolve = function () {
  11134. _this.resize(_this.source.width, _this.source.height);
  11135. resolve(_this);
  11136. };
  11137. // Convert SVG inline string to data-uri
  11138. if (SVGResource.SVG_XML.test(_this.svg.trim())) {
  11139. if (!btoa) {
  11140. throw new Error('Your browser doesn\'t support base64 conversions.');
  11141. }
  11142. _this.svg = "data:image/svg+xml;base64," + btoa(unescape(encodeURIComponent(_this.svg)));
  11143. }
  11144. _this._loadSvg();
  11145. });
  11146. return this._load;
  11147. };
  11148. /** Loads an SVG image from `imageUrl` or `data URL`. */
  11149. SVGResource.prototype._loadSvg = function () {
  11150. var _this = this;
  11151. var tempImage = new Image();
  11152. BaseImageResource.crossOrigin(tempImage, this.svg, this._crossorigin);
  11153. tempImage.src = this.svg;
  11154. tempImage.onerror = function (event) {
  11155. if (!_this._resolve) {
  11156. return;
  11157. }
  11158. tempImage.onerror = null;
  11159. _this.onError.emit(event);
  11160. };
  11161. tempImage.onload = function () {
  11162. if (!_this._resolve) {
  11163. return;
  11164. }
  11165. var svgWidth = tempImage.width;
  11166. var svgHeight = tempImage.height;
  11167. if (!svgWidth || !svgHeight) {
  11168. throw new Error('The SVG image must have width and height defined (in pixels), canvas API needs them.');
  11169. }
  11170. // Set render size
  11171. var width = svgWidth * _this.scale;
  11172. var height = svgHeight * _this.scale;
  11173. if (_this._overrideWidth || _this._overrideHeight) {
  11174. width = _this._overrideWidth || _this._overrideHeight / svgHeight * svgWidth;
  11175. height = _this._overrideHeight || _this._overrideWidth / svgWidth * svgHeight;
  11176. }
  11177. width = Math.round(width);
  11178. height = Math.round(height);
  11179. // Create a canvas element
  11180. var canvas = _this.source;
  11181. canvas.width = width;
  11182. canvas.height = height;
  11183. canvas._pixiId = "canvas_" + uid();
  11184. // Draw the Svg to the canvas
  11185. canvas
  11186. .getContext('2d')
  11187. .drawImage(tempImage, 0, 0, svgWidth, svgHeight, 0, 0, width, height);
  11188. _this._resolve();
  11189. _this._resolve = null;
  11190. };
  11191. };
  11192. /**
  11193. * Get size from an svg string using a regular expression.
  11194. * @param svgString - a serialized svg element
  11195. * @returns - image extension
  11196. */
  11197. SVGResource.getSize = function (svgString) {
  11198. var sizeMatch = SVGResource.SVG_SIZE.exec(svgString);
  11199. var size = {};
  11200. if (sizeMatch) {
  11201. size[sizeMatch[1]] = Math.round(parseFloat(sizeMatch[3]));
  11202. size[sizeMatch[5]] = Math.round(parseFloat(sizeMatch[7]));
  11203. }
  11204. return size;
  11205. };
  11206. /** Destroys this texture. */
  11207. SVGResource.prototype.dispose = function () {
  11208. _super.prototype.dispose.call(this);
  11209. this._resolve = null;
  11210. this._crossorigin = null;
  11211. };
  11212. /**
  11213. * Used to auto-detect the type of resource.
  11214. * @param {*} source - The source object
  11215. * @param {string} extension - The extension of source, if set
  11216. * @returns {boolean} - If the source is a SVG source or data file
  11217. */
  11218. SVGResource.test = function (source, extension) {
  11219. // url file extension is SVG
  11220. return extension === 'svg'
  11221. // source is SVG data-uri
  11222. || (typeof source === 'string' && source.startsWith('data:image/svg+xml'))
  11223. // source is SVG inline
  11224. || (typeof source === 'string' && SVGResource.SVG_XML.test(source));
  11225. };
  11226. /**
  11227. * Regular expression for SVG XML document.
  11228. * @example &lt;?xml version="1.0" encoding="utf-8" ?&gt;&lt;!-- image/svg --&gt;&lt;svg
  11229. * @readonly
  11230. */
  11231. SVGResource.SVG_XML = /^(<\?xml[^?]+\?>)?\s*(<!--[^(-->)]*-->)?\s*\<svg/m;
  11232. /**
  11233. * Regular expression for SVG size.
  11234. * @example &lt;svg width="100" height="100"&gt;&lt;/svg&gt;
  11235. * @readonly
  11236. */
  11237. SVGResource.SVG_SIZE = /<svg[^>]*(?:\s(width|height)=('|")(\d*(?:\.\d+)?)(?:px)?('|"))[^>]*(?:\s(width|height)=('|")(\d*(?:\.\d+)?)(?:px)?('|"))[^>]*>/i; // eslint-disable-line max-len
  11238. return SVGResource;
  11239. }(BaseImageResource));
  11240. /**
  11241. * Resource type for {@code HTMLVideoElement}.
  11242. * @memberof PIXI
  11243. */
  11244. var VideoResource = /** @class */ (function (_super) {
  11245. __extends$i(VideoResource, _super);
  11246. /**
  11247. * @param {HTMLVideoElement|object|string|Array<string|object>} source - Video element to use.
  11248. * @param {object} [options] - Options to use
  11249. * @param {boolean} [options.autoLoad=true] - Start loading the video immediately
  11250. * @param {boolean} [options.autoPlay=true] - Start playing video immediately
  11251. * @param {number} [options.updateFPS=0] - How many times a second to update the texture from the video.
  11252. * Leave at 0 to update at every render.
  11253. * @param {boolean} [options.crossorigin=true] - Load image using cross origin
  11254. */
  11255. function VideoResource(source, options) {
  11256. var _this = this;
  11257. options = options || {};
  11258. if (!(source instanceof HTMLVideoElement)) {
  11259. var videoElement = document.createElement('video');
  11260. // workaround for https://github.com/pixijs/pixi.js/issues/5996
  11261. videoElement.setAttribute('preload', 'auto');
  11262. videoElement.setAttribute('webkit-playsinline', '');
  11263. videoElement.setAttribute('playsinline', '');
  11264. if (typeof source === 'string') {
  11265. source = [source];
  11266. }
  11267. var firstSrc = source[0].src || source[0];
  11268. BaseImageResource.crossOrigin(videoElement, firstSrc, options.crossorigin);
  11269. // array of objects or strings
  11270. for (var i = 0; i < source.length; ++i) {
  11271. var sourceElement = document.createElement('source');
  11272. var _a = source[i], src = _a.src, mime = _a.mime;
  11273. src = src || source[i];
  11274. var baseSrc = src.split('?').shift().toLowerCase();
  11275. var ext = baseSrc.slice(baseSrc.lastIndexOf('.') + 1);
  11276. mime = mime || VideoResource.MIME_TYPES[ext] || "video/" + ext;
  11277. sourceElement.src = src;
  11278. sourceElement.type = mime;
  11279. videoElement.appendChild(sourceElement);
  11280. }
  11281. // Override the source
  11282. source = videoElement;
  11283. }
  11284. _this = _super.call(this, source) || this;
  11285. _this.noSubImage = true;
  11286. _this._autoUpdate = true;
  11287. _this._isConnectedToTicker = false;
  11288. _this._updateFPS = options.updateFPS || 0;
  11289. _this._msToNextUpdate = 0;
  11290. _this.autoPlay = options.autoPlay !== false;
  11291. _this._load = null;
  11292. _this._resolve = null;
  11293. // Bind for listeners
  11294. _this._onCanPlay = _this._onCanPlay.bind(_this);
  11295. _this._onError = _this._onError.bind(_this);
  11296. if (options.autoLoad !== false) {
  11297. _this.load();
  11298. }
  11299. return _this;
  11300. }
  11301. /**
  11302. * Trigger updating of the texture.
  11303. * @param _deltaTime - time delta since last tick
  11304. */
  11305. VideoResource.prototype.update = function (_deltaTime) {
  11306. if (!this.destroyed) {
  11307. // account for if video has had its playbackRate changed
  11308. var elapsedMS = Ticker.shared.elapsedMS * this.source.playbackRate;
  11309. this._msToNextUpdate = Math.floor(this._msToNextUpdate - elapsedMS);
  11310. if (!this._updateFPS || this._msToNextUpdate <= 0) {
  11311. _super.prototype.update.call(this);
  11312. this._msToNextUpdate = this._updateFPS ? Math.floor(1000 / this._updateFPS) : 0;
  11313. }
  11314. }
  11315. };
  11316. /**
  11317. * Start preloading the video resource.
  11318. * @returns {Promise<void>} Handle the validate event
  11319. */
  11320. VideoResource.prototype.load = function () {
  11321. var _this = this;
  11322. if (this._load) {
  11323. return this._load;
  11324. }
  11325. var source = this.source;
  11326. if ((source.readyState === source.HAVE_ENOUGH_DATA || source.readyState === source.HAVE_FUTURE_DATA)
  11327. && source.width && source.height) {
  11328. source.complete = true;
  11329. }
  11330. source.addEventListener('play', this._onPlayStart.bind(this));
  11331. source.addEventListener('pause', this._onPlayStop.bind(this));
  11332. if (!this._isSourceReady()) {
  11333. source.addEventListener('canplay', this._onCanPlay);
  11334. source.addEventListener('canplaythrough', this._onCanPlay);
  11335. source.addEventListener('error', this._onError, true);
  11336. }
  11337. else {
  11338. this._onCanPlay();
  11339. }
  11340. this._load = new Promise(function (resolve) {
  11341. if (_this.valid) {
  11342. resolve(_this);
  11343. }
  11344. else {
  11345. _this._resolve = resolve;
  11346. source.load();
  11347. }
  11348. });
  11349. return this._load;
  11350. };
  11351. /**
  11352. * Handle video error events.
  11353. * @param event
  11354. */
  11355. VideoResource.prototype._onError = function (event) {
  11356. this.source.removeEventListener('error', this._onError, true);
  11357. this.onError.emit(event);
  11358. };
  11359. /**
  11360. * Returns true if the underlying source is playing.
  11361. * @returns - True if playing.
  11362. */
  11363. VideoResource.prototype._isSourcePlaying = function () {
  11364. var source = this.source;
  11365. return (!source.paused && !source.ended && this._isSourceReady());
  11366. };
  11367. /**
  11368. * Returns true if the underlying source is ready for playing.
  11369. * @returns - True if ready.
  11370. */
  11371. VideoResource.prototype._isSourceReady = function () {
  11372. var source = this.source;
  11373. return source.readyState > 2;
  11374. };
  11375. /** Runs the update loop when the video is ready to play. */
  11376. VideoResource.prototype._onPlayStart = function () {
  11377. // Just in case the video has not received its can play even yet..
  11378. if (!this.valid) {
  11379. this._onCanPlay();
  11380. }
  11381. if (this.autoUpdate && !this._isConnectedToTicker) {
  11382. Ticker.shared.add(this.update, this);
  11383. this._isConnectedToTicker = true;
  11384. }
  11385. };
  11386. /** Fired when a pause event is triggered, stops the update loop. */
  11387. VideoResource.prototype._onPlayStop = function () {
  11388. if (this._isConnectedToTicker) {
  11389. Ticker.shared.remove(this.update, this);
  11390. this._isConnectedToTicker = false;
  11391. }
  11392. };
  11393. /** Fired when the video is loaded and ready to play. */
  11394. VideoResource.prototype._onCanPlay = function () {
  11395. var source = this.source;
  11396. source.removeEventListener('canplay', this._onCanPlay);
  11397. source.removeEventListener('canplaythrough', this._onCanPlay);
  11398. var valid = this.valid;
  11399. this.resize(source.videoWidth, source.videoHeight);
  11400. // prevent multiple loaded dispatches..
  11401. if (!valid && this._resolve) {
  11402. this._resolve(this);
  11403. this._resolve = null;
  11404. }
  11405. if (this._isSourcePlaying()) {
  11406. this._onPlayStart();
  11407. }
  11408. else if (this.autoPlay) {
  11409. source.play();
  11410. }
  11411. };
  11412. /** Destroys this texture. */
  11413. VideoResource.prototype.dispose = function () {
  11414. if (this._isConnectedToTicker) {
  11415. Ticker.shared.remove(this.update, this);
  11416. this._isConnectedToTicker = false;
  11417. }
  11418. var source = this.source;
  11419. if (source) {
  11420. source.removeEventListener('error', this._onError, true);
  11421. source.pause();
  11422. source.src = '';
  11423. source.load();
  11424. }
  11425. _super.prototype.dispose.call(this);
  11426. };
  11427. Object.defineProperty(VideoResource.prototype, "autoUpdate", {
  11428. /** Should the base texture automatically update itself, set to true by default. */
  11429. get: function () {
  11430. return this._autoUpdate;
  11431. },
  11432. set: function (value) {
  11433. if (value !== this._autoUpdate) {
  11434. this._autoUpdate = value;
  11435. if (!this._autoUpdate && this._isConnectedToTicker) {
  11436. Ticker.shared.remove(this.update, this);
  11437. this._isConnectedToTicker = false;
  11438. }
  11439. else if (this._autoUpdate && !this._isConnectedToTicker && this._isSourcePlaying()) {
  11440. Ticker.shared.add(this.update, this);
  11441. this._isConnectedToTicker = true;
  11442. }
  11443. }
  11444. },
  11445. enumerable: false,
  11446. configurable: true
  11447. });
  11448. Object.defineProperty(VideoResource.prototype, "updateFPS", {
  11449. /**
  11450. * How many times a second to update the texture from the video. Leave at 0 to update at every render.
  11451. * A lower fps can help performance, as updating the texture at 60fps on a 30ps video may not be efficient.
  11452. */
  11453. get: function () {
  11454. return this._updateFPS;
  11455. },
  11456. set: function (value) {
  11457. if (value !== this._updateFPS) {
  11458. this._updateFPS = value;
  11459. }
  11460. },
  11461. enumerable: false,
  11462. configurable: true
  11463. });
  11464. /**
  11465. * Used to auto-detect the type of resource.
  11466. * @param {*} source - The source object
  11467. * @param {string} extension - The extension of source, if set
  11468. * @returns {boolean} `true` if video source
  11469. */
  11470. VideoResource.test = function (source, extension) {
  11471. return (globalThis.HTMLVideoElement && source instanceof HTMLVideoElement)
  11472. || VideoResource.TYPES.indexOf(extension) > -1;
  11473. };
  11474. /**
  11475. * List of common video file extensions supported by VideoResource.
  11476. * @readonly
  11477. */
  11478. VideoResource.TYPES = ['mp4', 'm4v', 'webm', 'ogg', 'ogv', 'h264', 'avi', 'mov'];
  11479. /**
  11480. * Map of video MIME types that can't be directly derived from file extensions.
  11481. * @readonly
  11482. */
  11483. VideoResource.MIME_TYPES = {
  11484. ogv: 'video/ogg',
  11485. mov: 'video/quicktime',
  11486. m4v: 'video/mp4',
  11487. };
  11488. return VideoResource;
  11489. }(BaseImageResource));
  11490. /**
  11491. * Resource type for ImageBitmap.
  11492. * @memberof PIXI
  11493. */
  11494. var ImageBitmapResource = /** @class */ (function (_super) {
  11495. __extends$i(ImageBitmapResource, _super);
  11496. /**
  11497. * @param source - Image element to use
  11498. */
  11499. // eslint-disable-next-line @typescript-eslint/no-useless-constructor
  11500. function ImageBitmapResource(source) {
  11501. return _super.call(this, source) || this;
  11502. }
  11503. /**
  11504. * Used to auto-detect the type of resource.
  11505. * @param {*} source - The source object
  11506. * @returns {boolean} `true` if source is an ImageBitmap
  11507. */
  11508. ImageBitmapResource.test = function (source) {
  11509. return !!globalThis.createImageBitmap && typeof ImageBitmap !== 'undefined' && source instanceof ImageBitmap;
  11510. };
  11511. return ImageBitmapResource;
  11512. }(BaseImageResource));
  11513. INSTALLED.push(ImageResource, ImageBitmapResource, CanvasResource, VideoResource, SVGResource, BufferResource, CubeResource, ArrayResource);
  11514. var _resources = {
  11515. __proto__: null,
  11516. Resource: Resource,
  11517. BaseImageResource: BaseImageResource,
  11518. INSTALLED: INSTALLED,
  11519. autoDetectResource: autoDetectResource,
  11520. AbstractMultiResource: AbstractMultiResource,
  11521. ArrayResource: ArrayResource,
  11522. BufferResource: BufferResource,
  11523. CanvasResource: CanvasResource,
  11524. CubeResource: CubeResource,
  11525. ImageResource: ImageResource,
  11526. SVGResource: SVGResource,
  11527. VideoResource: VideoResource,
  11528. ImageBitmapResource: ImageBitmapResource
  11529. };
  11530. /**
  11531. * Resource type for DepthTexture.
  11532. * @memberof PIXI
  11533. */
  11534. var DepthResource = /** @class */ (function (_super) {
  11535. __extends$i(DepthResource, _super);
  11536. function DepthResource() {
  11537. return _super !== null && _super.apply(this, arguments) || this;
  11538. }
  11539. /**
  11540. * Upload the texture to the GPU.
  11541. * @param renderer - Upload to the renderer
  11542. * @param baseTexture - Reference to parent texture
  11543. * @param glTexture - glTexture
  11544. * @returns - true is success
  11545. */
  11546. DepthResource.prototype.upload = function (renderer, baseTexture, glTexture) {
  11547. var gl = renderer.gl;
  11548. gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, baseTexture.alphaMode === ALPHA_MODES.UNPACK);
  11549. var width = baseTexture.realWidth;
  11550. var height = baseTexture.realHeight;
  11551. if (glTexture.width === width && glTexture.height === height) {
  11552. gl.texSubImage2D(baseTexture.target, 0, 0, 0, width, height, baseTexture.format, glTexture.type, this.data);
  11553. }
  11554. else {
  11555. glTexture.width = width;
  11556. glTexture.height = height;
  11557. gl.texImage2D(baseTexture.target, 0, glTexture.internalFormat, width, height, 0, baseTexture.format, glTexture.type, this.data);
  11558. }
  11559. return true;
  11560. };
  11561. return DepthResource;
  11562. }(BufferResource));
  11563. /**
  11564. * A framebuffer can be used to render contents off of the screen. {@link PIXI.BaseRenderTexture} uses
  11565. * one internally to render into itself. You can attach a depth or stencil buffer to a framebuffer.
  11566. *
  11567. * On WebGL 2 machines, shaders can output to multiple textures simultaneously with GLSL 300 ES.
  11568. * @memberof PIXI
  11569. */
  11570. var Framebuffer = /** @class */ (function () {
  11571. /**
  11572. * @param width - Width of the frame buffer
  11573. * @param height - Height of the frame buffer
  11574. */
  11575. function Framebuffer(width, height) {
  11576. this.width = Math.round(width || 100);
  11577. this.height = Math.round(height || 100);
  11578. this.stencil = false;
  11579. this.depth = false;
  11580. this.dirtyId = 0;
  11581. this.dirtyFormat = 0;
  11582. this.dirtySize = 0;
  11583. this.depthTexture = null;
  11584. this.colorTextures = [];
  11585. this.glFramebuffers = {};
  11586. this.disposeRunner = new Runner('disposeFramebuffer');
  11587. this.multisample = MSAA_QUALITY.NONE;
  11588. }
  11589. Object.defineProperty(Framebuffer.prototype, "colorTexture", {
  11590. /**
  11591. * Reference to the colorTexture.
  11592. * @readonly
  11593. */
  11594. get: function () {
  11595. return this.colorTextures[0];
  11596. },
  11597. enumerable: false,
  11598. configurable: true
  11599. });
  11600. /**
  11601. * Add texture to the colorTexture array.
  11602. * @param index - Index of the array to add the texture to
  11603. * @param texture - Texture to add to the array
  11604. */
  11605. Framebuffer.prototype.addColorTexture = function (index, texture) {
  11606. if (index === void 0) { index = 0; }
  11607. // TODO add some validation to the texture - same width / height etc?
  11608. this.colorTextures[index] = texture || new BaseTexture(null, {
  11609. scaleMode: SCALE_MODES.NEAREST,
  11610. resolution: 1,
  11611. mipmap: MIPMAP_MODES.OFF,
  11612. width: this.width,
  11613. height: this.height,
  11614. });
  11615. this.dirtyId++;
  11616. this.dirtyFormat++;
  11617. return this;
  11618. };
  11619. /**
  11620. * Add a depth texture to the frame buffer.
  11621. * @param texture - Texture to add.
  11622. */
  11623. Framebuffer.prototype.addDepthTexture = function (texture) {
  11624. /* eslint-disable max-len */
  11625. this.depthTexture = texture || new BaseTexture(new DepthResource(null, { width: this.width, height: this.height }), {
  11626. scaleMode: SCALE_MODES.NEAREST,
  11627. resolution: 1,
  11628. width: this.width,
  11629. height: this.height,
  11630. mipmap: MIPMAP_MODES.OFF,
  11631. format: FORMATS.DEPTH_COMPONENT,
  11632. type: TYPES.UNSIGNED_SHORT,
  11633. });
  11634. this.dirtyId++;
  11635. this.dirtyFormat++;
  11636. return this;
  11637. };
  11638. /** Enable depth on the frame buffer. */
  11639. Framebuffer.prototype.enableDepth = function () {
  11640. this.depth = true;
  11641. this.dirtyId++;
  11642. this.dirtyFormat++;
  11643. return this;
  11644. };
  11645. /** Enable stencil on the frame buffer. */
  11646. Framebuffer.prototype.enableStencil = function () {
  11647. this.stencil = true;
  11648. this.dirtyId++;
  11649. this.dirtyFormat++;
  11650. return this;
  11651. };
  11652. /**
  11653. * Resize the frame buffer
  11654. * @param width - Width of the frame buffer to resize to
  11655. * @param height - Height of the frame buffer to resize to
  11656. */
  11657. Framebuffer.prototype.resize = function (width, height) {
  11658. width = Math.round(width);
  11659. height = Math.round(height);
  11660. if (width === this.width && height === this.height)
  11661. { return; }
  11662. this.width = width;
  11663. this.height = height;
  11664. this.dirtyId++;
  11665. this.dirtySize++;
  11666. for (var i = 0; i < this.colorTextures.length; i++) {
  11667. var texture = this.colorTextures[i];
  11668. var resolution = texture.resolution;
  11669. // take into account the fact the texture may have a different resolution..
  11670. texture.setSize(width / resolution, height / resolution);
  11671. }
  11672. if (this.depthTexture) {
  11673. var resolution = this.depthTexture.resolution;
  11674. this.depthTexture.setSize(width / resolution, height / resolution);
  11675. }
  11676. };
  11677. /** Disposes WebGL resources that are connected to this geometry. */
  11678. Framebuffer.prototype.dispose = function () {
  11679. this.disposeRunner.emit(this, false);
  11680. };
  11681. /** Destroys and removes the depth texture added to this framebuffer. */
  11682. Framebuffer.prototype.destroyDepthTexture = function () {
  11683. if (this.depthTexture) {
  11684. this.depthTexture.destroy();
  11685. this.depthTexture = null;
  11686. ++this.dirtyId;
  11687. ++this.dirtyFormat;
  11688. }
  11689. };
  11690. return Framebuffer;
  11691. }());
  11692. /**
  11693. * A BaseRenderTexture is a special texture that allows any PixiJS display object to be rendered to it.
  11694. *
  11695. * __Hint__: All DisplayObjects (i.e. Sprites) that render to a BaseRenderTexture should be preloaded
  11696. * otherwise black rectangles will be drawn instead.
  11697. *
  11698. * A BaseRenderTexture takes a snapshot of any Display Object given to its render method. The position
  11699. * and rotation of the given Display Objects is ignored. For example:
  11700. *
  11701. * ```js
  11702. * let renderer = PIXI.autoDetectRenderer();
  11703. * let baseRenderTexture = new PIXI.BaseRenderTexture({ width: 800, height: 600 });
  11704. * let renderTexture = new PIXI.RenderTexture(baseRenderTexture);
  11705. * let sprite = PIXI.Sprite.from("spinObj_01.png");
  11706. *
  11707. * sprite.position.x = 800/2;
  11708. * sprite.position.y = 600/2;
  11709. * sprite.anchor.x = 0.5;
  11710. * sprite.anchor.y = 0.5;
  11711. *
  11712. * renderer.render(sprite, {renderTexture});
  11713. * ```
  11714. *
  11715. * The Sprite in this case will be rendered using its local transform. To render this sprite at 0,0
  11716. * you can clear the transform
  11717. *
  11718. * ```js
  11719. *
  11720. * sprite.setTransform()
  11721. *
  11722. * let baseRenderTexture = new PIXI.BaseRenderTexture({ width: 100, height: 100 });
  11723. * let renderTexture = new PIXI.RenderTexture(baseRenderTexture);
  11724. *
  11725. * renderer.render(sprite, {renderTexture}); // Renders to center of RenderTexture
  11726. * ```
  11727. * @memberof PIXI
  11728. */
  11729. var BaseRenderTexture = /** @class */ (function (_super) {
  11730. __extends$i(BaseRenderTexture, _super);
  11731. /**
  11732. * @param options
  11733. * @param {number} [options.width=100] - The width of the base render texture.
  11734. * @param {number} [options.height=100] - The height of the base render texture.
  11735. * @param {PIXI.SCALE_MODES} [options.scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES}
  11736. * for possible values.
  11737. * @param {number} [options.resolution=PIXI.settings.RESOLUTION] - The resolution / device pixel ratio
  11738. * of the texture being generated.
  11739. * @param {PIXI.MSAA_QUALITY} [options.multisample=PIXI.MSAA_QUALITY.NONE] - The number of samples of the frame buffer.
  11740. */
  11741. function BaseRenderTexture(options) {
  11742. if (options === void 0) { options = {}; }
  11743. var _this = this;
  11744. if (typeof options === 'number') {
  11745. /* eslint-disable prefer-rest-params */
  11746. // Backward compatibility of signature
  11747. var width = arguments[0];
  11748. var height = arguments[1];
  11749. var scaleMode = arguments[2];
  11750. var resolution = arguments[3];
  11751. options = { width: width, height: height, scaleMode: scaleMode, resolution: resolution };
  11752. /* eslint-enable prefer-rest-params */
  11753. }
  11754. options.width = options.width || 100;
  11755. options.height = options.height || 100;
  11756. options.multisample = options.multisample !== undefined ? options.multisample : MSAA_QUALITY.NONE;
  11757. _this = _super.call(this, null, options) || this;
  11758. // Set defaults
  11759. _this.mipmap = MIPMAP_MODES.OFF;
  11760. _this.valid = true;
  11761. _this.clearColor = [0, 0, 0, 0];
  11762. _this.framebuffer = new Framebuffer(_this.realWidth, _this.realHeight)
  11763. .addColorTexture(0, _this);
  11764. _this.framebuffer.multisample = options.multisample;
  11765. // TODO - could this be added the systems?
  11766. _this.maskStack = [];
  11767. _this.filterStack = [{}];
  11768. return _this;
  11769. }
  11770. /**
  11771. * Resizes the BaseRenderTexture.
  11772. * @param desiredWidth - The desired width to resize to.
  11773. * @param desiredHeight - The desired height to resize to.
  11774. */
  11775. BaseRenderTexture.prototype.resize = function (desiredWidth, desiredHeight) {
  11776. this.framebuffer.resize(desiredWidth * this.resolution, desiredHeight * this.resolution);
  11777. this.setRealSize(this.framebuffer.width, this.framebuffer.height);
  11778. };
  11779. /**
  11780. * Frees the texture and framebuffer from WebGL memory without destroying this texture object.
  11781. * This means you can still use the texture later which will upload it to GPU
  11782. * memory again.
  11783. * @fires PIXI.BaseTexture#dispose
  11784. */
  11785. BaseRenderTexture.prototype.dispose = function () {
  11786. this.framebuffer.dispose();
  11787. _super.prototype.dispose.call(this);
  11788. };
  11789. /** Destroys this texture. */
  11790. BaseRenderTexture.prototype.destroy = function () {
  11791. _super.prototype.destroy.call(this);
  11792. this.framebuffer.destroyDepthTexture();
  11793. this.framebuffer = null;
  11794. };
  11795. return BaseRenderTexture;
  11796. }(BaseTexture));
  11797. /**
  11798. * Stores a texture's frame in UV coordinates, in
  11799. * which everything lies in the rectangle `[(0,0), (1,0),
  11800. * (1,1), (0,1)]`.
  11801. *
  11802. * | Corner | Coordinates |
  11803. * |--------------|-------------|
  11804. * | Top-Left | `(x0,y0)` |
  11805. * | Top-Right | `(x1,y1)` |
  11806. * | Bottom-Right | `(x2,y2)` |
  11807. * | Bottom-Left | `(x3,y3)` |
  11808. * @protected
  11809. * @memberof PIXI
  11810. */
  11811. var TextureUvs = /** @class */ (function () {
  11812. function TextureUvs() {
  11813. this.x0 = 0;
  11814. this.y0 = 0;
  11815. this.x1 = 1;
  11816. this.y1 = 0;
  11817. this.x2 = 1;
  11818. this.y2 = 1;
  11819. this.x3 = 0;
  11820. this.y3 = 1;
  11821. this.uvsFloat32 = new Float32Array(8);
  11822. }
  11823. /**
  11824. * Sets the texture Uvs based on the given frame information.
  11825. * @protected
  11826. * @param frame - The frame of the texture
  11827. * @param baseFrame - The base frame of the texture
  11828. * @param rotate - Rotation of frame, see {@link PIXI.groupD8}
  11829. */
  11830. TextureUvs.prototype.set = function (frame, baseFrame, rotate) {
  11831. var tw = baseFrame.width;
  11832. var th = baseFrame.height;
  11833. if (rotate) {
  11834. // width and height div 2 div baseFrame size
  11835. var w2 = frame.width / 2 / tw;
  11836. var h2 = frame.height / 2 / th;
  11837. // coordinates of center
  11838. var cX = (frame.x / tw) + w2;
  11839. var cY = (frame.y / th) + h2;
  11840. rotate = groupD8.add(rotate, groupD8.NW); // NW is top-left corner
  11841. this.x0 = cX + (w2 * groupD8.uX(rotate));
  11842. this.y0 = cY + (h2 * groupD8.uY(rotate));
  11843. rotate = groupD8.add(rotate, 2); // rotate 90 degrees clockwise
  11844. this.x1 = cX + (w2 * groupD8.uX(rotate));
  11845. this.y1 = cY + (h2 * groupD8.uY(rotate));
  11846. rotate = groupD8.add(rotate, 2);
  11847. this.x2 = cX + (w2 * groupD8.uX(rotate));
  11848. this.y2 = cY + (h2 * groupD8.uY(rotate));
  11849. rotate = groupD8.add(rotate, 2);
  11850. this.x3 = cX + (w2 * groupD8.uX(rotate));
  11851. this.y3 = cY + (h2 * groupD8.uY(rotate));
  11852. }
  11853. else {
  11854. this.x0 = frame.x / tw;
  11855. this.y0 = frame.y / th;
  11856. this.x1 = (frame.x + frame.width) / tw;
  11857. this.y1 = frame.y / th;
  11858. this.x2 = (frame.x + frame.width) / tw;
  11859. this.y2 = (frame.y + frame.height) / th;
  11860. this.x3 = frame.x / tw;
  11861. this.y3 = (frame.y + frame.height) / th;
  11862. }
  11863. this.uvsFloat32[0] = this.x0;
  11864. this.uvsFloat32[1] = this.y0;
  11865. this.uvsFloat32[2] = this.x1;
  11866. this.uvsFloat32[3] = this.y1;
  11867. this.uvsFloat32[4] = this.x2;
  11868. this.uvsFloat32[5] = this.y2;
  11869. this.uvsFloat32[6] = this.x3;
  11870. this.uvsFloat32[7] = this.y3;
  11871. };
  11872. TextureUvs.prototype.toString = function () {
  11873. return "[@pixi/core:TextureUvs "
  11874. + ("x0=" + this.x0 + " y0=" + this.y0 + " ")
  11875. + ("x1=" + this.x1 + " y1=" + this.y1 + " x2=" + this.x2 + " ")
  11876. + ("y2=" + this.y2 + " x3=" + this.x3 + " y3=" + this.y3)
  11877. + "]";
  11878. };
  11879. return TextureUvs;
  11880. }());
  11881. var DEFAULT_UVS = new TextureUvs();
  11882. /**
  11883. * Used to remove listeners from WHITE and EMPTY Textures
  11884. * @ignore
  11885. */
  11886. function removeAllHandlers(tex) {
  11887. tex.destroy = function _emptyDestroy() { };
  11888. tex.on = function _emptyOn() { };
  11889. tex.once = function _emptyOnce() { };
  11890. tex.emit = function _emptyEmit() { };
  11891. }
  11892. /**
  11893. * A texture stores the information that represents an image or part of an image.
  11894. *
  11895. * It cannot be added to the display list directly; instead use it as the texture for a Sprite.
  11896. * If no frame is provided for a texture, then the whole image is used.
  11897. *
  11898. * You can directly create a texture from an image and then reuse it multiple times like this :
  11899. *
  11900. * ```js
  11901. * let texture = PIXI.Texture.from('assets/image.png');
  11902. * let sprite1 = new PIXI.Sprite(texture);
  11903. * let sprite2 = new PIXI.Sprite(texture);
  11904. * ```
  11905. *
  11906. * If you didnt pass the texture frame to constructor, it enables `noFrame` mode:
  11907. * it subscribes on baseTexture events, it automatically resizes at the same time as baseTexture.
  11908. *
  11909. * Textures made from SVGs, loaded or not, cannot be used before the file finishes processing.
  11910. * You can check for this by checking the sprite's _textureID property.
  11911. * ```js
  11912. * var texture = PIXI.Texture.from('assets/image.svg');
  11913. * var sprite1 = new PIXI.Sprite(texture);
  11914. * //sprite1._textureID should not be undefined if the texture has finished processing the SVG file
  11915. * ```
  11916. * You can use a ticker or rAF to ensure your sprites load the finished textures after processing. See issue #3068.
  11917. * @memberof PIXI
  11918. * @typeParam R - The BaseTexture's Resource type.
  11919. */
  11920. var Texture = /** @class */ (function (_super) {
  11921. __extends$i(Texture, _super);
  11922. /**
  11923. * @param baseTexture - The base texture source to create the texture from
  11924. * @param frame - The rectangle frame of the texture to show
  11925. * @param orig - The area of original texture
  11926. * @param trim - Trimmed rectangle of original texture
  11927. * @param rotate - indicates how the texture was rotated by texture packer. See {@link PIXI.groupD8}
  11928. * @param anchor - Default anchor point used for sprite placement / rotation
  11929. */
  11930. function Texture(baseTexture, frame, orig, trim, rotate, anchor) {
  11931. var _this = _super.call(this) || this;
  11932. _this.noFrame = false;
  11933. if (!frame) {
  11934. _this.noFrame = true;
  11935. frame = new Rectangle(0, 0, 1, 1);
  11936. }
  11937. if (baseTexture instanceof Texture) {
  11938. baseTexture = baseTexture.baseTexture;
  11939. }
  11940. _this.baseTexture = baseTexture;
  11941. _this._frame = frame;
  11942. _this.trim = trim;
  11943. _this.valid = false;
  11944. _this._uvs = DEFAULT_UVS;
  11945. _this.uvMatrix = null;
  11946. _this.orig = orig || frame; // new Rectangle(0, 0, 1, 1);
  11947. _this._rotate = Number(rotate || 0);
  11948. if (rotate === true) {
  11949. // this is old texturepacker legacy, some games/libraries are passing "true" for rotated textures
  11950. _this._rotate = 2;
  11951. }
  11952. else if (_this._rotate % 2 !== 0) {
  11953. throw new Error('attempt to use diamond-shaped UVs. If you are sure, set rotation manually');
  11954. }
  11955. _this.defaultAnchor = anchor ? new Point(anchor.x, anchor.y) : new Point(0, 0);
  11956. _this._updateID = 0;
  11957. _this.textureCacheIds = [];
  11958. if (!baseTexture.valid) {
  11959. baseTexture.once('loaded', _this.onBaseTextureUpdated, _this);
  11960. }
  11961. else if (_this.noFrame) {
  11962. // if there is no frame we should monitor for any base texture changes..
  11963. if (baseTexture.valid) {
  11964. _this.onBaseTextureUpdated(baseTexture);
  11965. }
  11966. }
  11967. else {
  11968. _this.frame = frame;
  11969. }
  11970. if (_this.noFrame) {
  11971. baseTexture.on('update', _this.onBaseTextureUpdated, _this);
  11972. }
  11973. return _this;
  11974. }
  11975. /**
  11976. * Updates this texture on the gpu.
  11977. *
  11978. * Calls the TextureResource update.
  11979. *
  11980. * If you adjusted `frame` manually, please call `updateUvs()` instead.
  11981. */
  11982. Texture.prototype.update = function () {
  11983. if (this.baseTexture.resource) {
  11984. this.baseTexture.resource.update();
  11985. }
  11986. };
  11987. /**
  11988. * Called when the base texture is updated
  11989. * @protected
  11990. * @param baseTexture - The base texture.
  11991. */
  11992. Texture.prototype.onBaseTextureUpdated = function (baseTexture) {
  11993. if (this.noFrame) {
  11994. if (!this.baseTexture.valid) {
  11995. return;
  11996. }
  11997. this._frame.width = baseTexture.width;
  11998. this._frame.height = baseTexture.height;
  11999. this.valid = true;
  12000. this.updateUvs();
  12001. }
  12002. else {
  12003. // TODO this code looks confusing.. boo to abusing getters and setters!
  12004. // if user gave us frame that has bigger size than resized texture it can be a problem
  12005. this.frame = this._frame;
  12006. }
  12007. this.emit('update', this);
  12008. };
  12009. /**
  12010. * Destroys this texture
  12011. * @param [destroyBase=false] - Whether to destroy the base texture as well
  12012. */
  12013. Texture.prototype.destroy = function (destroyBase) {
  12014. if (this.baseTexture) {
  12015. if (destroyBase) {
  12016. var resource = this.baseTexture.resource;
  12017. // delete the texture if it exists in the texture cache..
  12018. // this only needs to be removed if the base texture is actually destroyed too..
  12019. if (resource && resource.url && TextureCache[resource.url]) {
  12020. Texture.removeFromCache(resource.url);
  12021. }
  12022. this.baseTexture.destroy();
  12023. }
  12024. this.baseTexture.off('loaded', this.onBaseTextureUpdated, this);
  12025. this.baseTexture.off('update', this.onBaseTextureUpdated, this);
  12026. this.baseTexture = null;
  12027. }
  12028. this._frame = null;
  12029. this._uvs = null;
  12030. this.trim = null;
  12031. this.orig = null;
  12032. this.valid = false;
  12033. Texture.removeFromCache(this);
  12034. this.textureCacheIds = null;
  12035. };
  12036. /**
  12037. * Creates a new texture object that acts the same as this one.
  12038. * @returns - The new texture
  12039. */
  12040. Texture.prototype.clone = function () {
  12041. var clonedFrame = this._frame.clone();
  12042. var clonedOrig = this._frame === this.orig ? clonedFrame : this.orig.clone();
  12043. var clonedTexture = new Texture(this.baseTexture, !this.noFrame && clonedFrame, clonedOrig, this.trim && this.trim.clone(), this.rotate, this.defaultAnchor);
  12044. if (this.noFrame) {
  12045. clonedTexture._frame = clonedFrame;
  12046. }
  12047. return clonedTexture;
  12048. };
  12049. /**
  12050. * Updates the internal WebGL UV cache. Use it after you change `frame` or `trim` of the texture.
  12051. * Call it after changing the frame
  12052. */
  12053. Texture.prototype.updateUvs = function () {
  12054. if (this._uvs === DEFAULT_UVS) {
  12055. this._uvs = new TextureUvs();
  12056. }
  12057. this._uvs.set(this._frame, this.baseTexture, this.rotate);
  12058. this._updateID++;
  12059. };
  12060. /**
  12061. * Helper function that creates a new Texture based on the source you provide.
  12062. * The source can be - frame id, image url, video url, canvas element, video element, base texture
  12063. * @param {string|HTMLImageElement|HTMLCanvasElement|HTMLVideoElement|PIXI.BaseTexture} source -
  12064. * Source or array of sources to create texture from
  12065. * @param options - See {@link PIXI.BaseTexture}'s constructor for options.
  12066. * @param {string} [options.pixiIdPrefix=pixiid] - If a source has no id, this is the prefix of the generated id
  12067. * @param {boolean} [strict] - Enforce strict-mode, see {@link PIXI.settings.STRICT_TEXTURE_CACHE}.
  12068. * @returns {PIXI.Texture} The newly created texture
  12069. */
  12070. Texture.from = function (source, options, strict) {
  12071. if (options === void 0) { options = {}; }
  12072. if (strict === void 0) { strict = settings.STRICT_TEXTURE_CACHE; }
  12073. var isFrame = typeof source === 'string';
  12074. var cacheId = null;
  12075. if (isFrame) {
  12076. cacheId = source;
  12077. }
  12078. else if (source instanceof BaseTexture) {
  12079. if (!source.cacheId) {
  12080. var prefix = (options && options.pixiIdPrefix) || 'pixiid';
  12081. source.cacheId = prefix + "-" + uid();
  12082. BaseTexture.addToCache(source, source.cacheId);
  12083. }
  12084. cacheId = source.cacheId;
  12085. }
  12086. else {
  12087. if (!source._pixiId) {
  12088. var prefix = (options && options.pixiIdPrefix) || 'pixiid';
  12089. source._pixiId = prefix + "_" + uid();
  12090. }
  12091. cacheId = source._pixiId;
  12092. }
  12093. var texture = TextureCache[cacheId];
  12094. // Strict-mode rejects invalid cacheIds
  12095. if (isFrame && strict && !texture) {
  12096. throw new Error("The cacheId \"" + cacheId + "\" does not exist in TextureCache.");
  12097. }
  12098. if (!texture && !(source instanceof BaseTexture)) {
  12099. if (!options.resolution) {
  12100. options.resolution = getResolutionOfUrl(source);
  12101. }
  12102. texture = new Texture(new BaseTexture(source, options));
  12103. texture.baseTexture.cacheId = cacheId;
  12104. BaseTexture.addToCache(texture.baseTexture, cacheId);
  12105. Texture.addToCache(texture, cacheId);
  12106. }
  12107. else if (!texture && (source instanceof BaseTexture)) {
  12108. texture = new Texture(source);
  12109. Texture.addToCache(texture, cacheId);
  12110. }
  12111. // lets assume its a base texture!
  12112. return texture;
  12113. };
  12114. /**
  12115. * Useful for loading textures via URLs. Use instead of `Texture.from` because
  12116. * it does a better job of handling failed URLs more effectively. This also ignores
  12117. * `PIXI.settings.STRICT_TEXTURE_CACHE`. Works for Videos, SVGs, Images.
  12118. * @param url - The remote URL or array of URLs to load.
  12119. * @param options - Optional options to include
  12120. * @returns - A Promise that resolves to a Texture.
  12121. */
  12122. Texture.fromURL = function (url, options) {
  12123. var resourceOptions = Object.assign({ autoLoad: false }, options === null || options === void 0 ? void 0 : options.resourceOptions);
  12124. var texture = Texture.from(url, Object.assign({ resourceOptions: resourceOptions }, options), false);
  12125. var resource = texture.baseTexture.resource;
  12126. // The texture was already loaded
  12127. if (texture.baseTexture.valid) {
  12128. return Promise.resolve(texture);
  12129. }
  12130. // Manually load the texture, this should allow users to handle load errors
  12131. return resource.load().then(function () { return Promise.resolve(texture); });
  12132. };
  12133. /**
  12134. * Create a new Texture with a BufferResource from a Float32Array.
  12135. * RGBA values are floats from 0 to 1.
  12136. * @param {Float32Array|Uint8Array} buffer - The optional array to use, if no data
  12137. * is provided, a new Float32Array is created.
  12138. * @param width - Width of the resource
  12139. * @param height - Height of the resource
  12140. * @param options - See {@link PIXI.BaseTexture}'s constructor for options.
  12141. * @returns - The resulting new BaseTexture
  12142. */
  12143. Texture.fromBuffer = function (buffer, width, height, options) {
  12144. return new Texture(BaseTexture.fromBuffer(buffer, width, height, options));
  12145. };
  12146. /**
  12147. * Create a texture from a source and add to the cache.
  12148. * @param {HTMLImageElement|HTMLCanvasElement|string} source - The input source.
  12149. * @param imageUrl - File name of texture, for cache and resolving resolution.
  12150. * @param name - Human readable name for the texture cache. If no name is
  12151. * specified, only `imageUrl` will be used as the cache ID.
  12152. * @param options
  12153. * @returns - Output texture
  12154. */
  12155. Texture.fromLoader = function (source, imageUrl, name, options) {
  12156. var baseTexture = new BaseTexture(source, Object.assign({
  12157. scaleMode: settings.SCALE_MODE,
  12158. resolution: getResolutionOfUrl(imageUrl),
  12159. }, options));
  12160. var resource = baseTexture.resource;
  12161. if (resource instanceof ImageResource) {
  12162. resource.url = imageUrl;
  12163. }
  12164. var texture = new Texture(baseTexture);
  12165. // No name, use imageUrl instead
  12166. if (!name) {
  12167. name = imageUrl;
  12168. }
  12169. // lets also add the frame to pixi's global cache for 'fromLoader' function
  12170. BaseTexture.addToCache(texture.baseTexture, name);
  12171. Texture.addToCache(texture, name);
  12172. // also add references by url if they are different.
  12173. if (name !== imageUrl) {
  12174. BaseTexture.addToCache(texture.baseTexture, imageUrl);
  12175. Texture.addToCache(texture, imageUrl);
  12176. }
  12177. // Generally images are valid right away
  12178. if (texture.baseTexture.valid) {
  12179. return Promise.resolve(texture);
  12180. }
  12181. // SVG assets need to be parsed async, let's wait
  12182. return new Promise(function (resolve) {
  12183. texture.baseTexture.once('loaded', function () { return resolve(texture); });
  12184. });
  12185. };
  12186. /**
  12187. * Adds a Texture to the global TextureCache. This cache is shared across the whole PIXI object.
  12188. * @param texture - The Texture to add to the cache.
  12189. * @param id - The id that the Texture will be stored against.
  12190. */
  12191. Texture.addToCache = function (texture, id) {
  12192. if (id) {
  12193. if (texture.textureCacheIds.indexOf(id) === -1) {
  12194. texture.textureCacheIds.push(id);
  12195. }
  12196. if (TextureCache[id]) {
  12197. // eslint-disable-next-line no-console
  12198. console.warn("Texture added to the cache with an id [" + id + "] that already had an entry");
  12199. }
  12200. TextureCache[id] = texture;
  12201. }
  12202. };
  12203. /**
  12204. * Remove a Texture from the global TextureCache.
  12205. * @param texture - id of a Texture to be removed, or a Texture instance itself
  12206. * @returns - The Texture that was removed
  12207. */
  12208. Texture.removeFromCache = function (texture) {
  12209. if (typeof texture === 'string') {
  12210. var textureFromCache = TextureCache[texture];
  12211. if (textureFromCache) {
  12212. var index = textureFromCache.textureCacheIds.indexOf(texture);
  12213. if (index > -1) {
  12214. textureFromCache.textureCacheIds.splice(index, 1);
  12215. }
  12216. delete TextureCache[texture];
  12217. return textureFromCache;
  12218. }
  12219. }
  12220. else if (texture && texture.textureCacheIds) {
  12221. for (var i = 0; i < texture.textureCacheIds.length; ++i) {
  12222. // Check that texture matches the one being passed in before deleting it from the cache.
  12223. if (TextureCache[texture.textureCacheIds[i]] === texture) {
  12224. delete TextureCache[texture.textureCacheIds[i]];
  12225. }
  12226. }
  12227. texture.textureCacheIds.length = 0;
  12228. return texture;
  12229. }
  12230. return null;
  12231. };
  12232. Object.defineProperty(Texture.prototype, "resolution", {
  12233. /**
  12234. * Returns resolution of baseTexture
  12235. * @readonly
  12236. */
  12237. get: function () {
  12238. return this.baseTexture.resolution;
  12239. },
  12240. enumerable: false,
  12241. configurable: true
  12242. });
  12243. Object.defineProperty(Texture.prototype, "frame", {
  12244. /**
  12245. * The frame specifies the region of the base texture that this texture uses.
  12246. * Please call `updateUvs()` after you change coordinates of `frame` manually.
  12247. */
  12248. get: function () {
  12249. return this._frame;
  12250. },
  12251. set: function (frame) {
  12252. this._frame = frame;
  12253. this.noFrame = false;
  12254. var x = frame.x, y = frame.y, width = frame.width, height = frame.height;
  12255. var xNotFit = x + width > this.baseTexture.width;
  12256. var yNotFit = y + height > this.baseTexture.height;
  12257. if (xNotFit || yNotFit) {
  12258. var relationship = xNotFit && yNotFit ? 'and' : 'or';
  12259. var errorX = "X: " + x + " + " + width + " = " + (x + width) + " > " + this.baseTexture.width;
  12260. var errorY = "Y: " + y + " + " + height + " = " + (y + height) + " > " + this.baseTexture.height;
  12261. throw new Error('Texture Error: frame does not fit inside the base Texture dimensions: '
  12262. + (errorX + " " + relationship + " " + errorY));
  12263. }
  12264. this.valid = width && height && this.baseTexture.valid;
  12265. if (!this.trim && !this.rotate) {
  12266. this.orig = frame;
  12267. }
  12268. if (this.valid) {
  12269. this.updateUvs();
  12270. }
  12271. },
  12272. enumerable: false,
  12273. configurable: true
  12274. });
  12275. Object.defineProperty(Texture.prototype, "rotate", {
  12276. /**
  12277. * Indicates whether the texture is rotated inside the atlas
  12278. * set to 2 to compensate for texture packer rotation
  12279. * set to 6 to compensate for spine packer rotation
  12280. * can be used to rotate or mirror sprites
  12281. * See {@link PIXI.groupD8} for explanation
  12282. */
  12283. get: function () {
  12284. return this._rotate;
  12285. },
  12286. set: function (rotate) {
  12287. this._rotate = rotate;
  12288. if (this.valid) {
  12289. this.updateUvs();
  12290. }
  12291. },
  12292. enumerable: false,
  12293. configurable: true
  12294. });
  12295. Object.defineProperty(Texture.prototype, "width", {
  12296. /** The width of the Texture in pixels. */
  12297. get: function () {
  12298. return this.orig.width;
  12299. },
  12300. enumerable: false,
  12301. configurable: true
  12302. });
  12303. Object.defineProperty(Texture.prototype, "height", {
  12304. /** The height of the Texture in pixels. */
  12305. get: function () {
  12306. return this.orig.height;
  12307. },
  12308. enumerable: false,
  12309. configurable: true
  12310. });
  12311. /** Utility function for BaseTexture|Texture cast. */
  12312. Texture.prototype.castToBaseTexture = function () {
  12313. return this.baseTexture;
  12314. };
  12315. Object.defineProperty(Texture, "EMPTY", {
  12316. /** An empty texture, used often to not have to create multiple empty textures. Can not be destroyed. */
  12317. get: function () {
  12318. if (!Texture._EMPTY) {
  12319. Texture._EMPTY = new Texture(new BaseTexture());
  12320. removeAllHandlers(Texture._EMPTY);
  12321. removeAllHandlers(Texture._EMPTY.baseTexture);
  12322. }
  12323. return Texture._EMPTY;
  12324. },
  12325. enumerable: false,
  12326. configurable: true
  12327. });
  12328. Object.defineProperty(Texture, "WHITE", {
  12329. /** A white texture of 16x16 size, used for graphics and other things Can not be destroyed. */
  12330. get: function () {
  12331. if (!Texture._WHITE) {
  12332. var canvas = settings.ADAPTER.createCanvas(16, 16);
  12333. var context = canvas.getContext('2d');
  12334. canvas.width = 16;
  12335. canvas.height = 16;
  12336. context.fillStyle = 'white';
  12337. context.fillRect(0, 0, 16, 16);
  12338. Texture._WHITE = new Texture(BaseTexture.from(canvas));
  12339. removeAllHandlers(Texture._WHITE);
  12340. removeAllHandlers(Texture._WHITE.baseTexture);
  12341. }
  12342. return Texture._WHITE;
  12343. },
  12344. enumerable: false,
  12345. configurable: true
  12346. });
  12347. return Texture;
  12348. }(eventemitter3));
  12349. /**
  12350. * A RenderTexture is a special texture that allows any PixiJS display object to be rendered to it.
  12351. *
  12352. * __Hint__: All DisplayObjects (i.e. Sprites) that render to a RenderTexture should be preloaded
  12353. * otherwise black rectangles will be drawn instead.
  12354. *
  12355. * __Hint-2__: The actual memory allocation will happen on first render.
  12356. * You shouldn't create renderTextures each frame just to delete them after, try to reuse them.
  12357. *
  12358. * A RenderTexture takes a snapshot of any Display Object given to its render method. For example:
  12359. *
  12360. * ```js
  12361. * let renderer = PIXI.autoDetectRenderer();
  12362. * let renderTexture = PIXI.RenderTexture.create({ width: 800, height: 600 });
  12363. * let sprite = PIXI.Sprite.from("spinObj_01.png");
  12364. *
  12365. * sprite.position.x = 800/2;
  12366. * sprite.position.y = 600/2;
  12367. * sprite.anchor.x = 0.5;
  12368. * sprite.anchor.y = 0.5;
  12369. *
  12370. * renderer.render(sprite, {renderTexture});
  12371. * ```
  12372. * Note that you should not create a new renderer, but reuse the same one as the rest of the application.
  12373. *
  12374. * The Sprite in this case will be rendered using its local transform. To render this sprite at 0,0
  12375. * you can clear the transform
  12376. *
  12377. * ```js
  12378. *
  12379. * sprite.setTransform()
  12380. *
  12381. * let renderTexture = new PIXI.RenderTexture.create({ width: 100, height: 100 });
  12382. *
  12383. * renderer.render(sprite, {renderTexture}); // Renders to center of RenderTexture
  12384. * ```
  12385. * @memberof PIXI
  12386. */
  12387. var RenderTexture = /** @class */ (function (_super) {
  12388. __extends$i(RenderTexture, _super);
  12389. /**
  12390. * @param baseRenderTexture - The base texture object that this texture uses.
  12391. * @param frame - The rectangle frame of the texture to show.
  12392. */
  12393. function RenderTexture(baseRenderTexture, frame) {
  12394. var _this = _super.call(this, baseRenderTexture, frame) || this;
  12395. _this.valid = true;
  12396. _this.filterFrame = null;
  12397. _this.filterPoolKey = null;
  12398. _this.updateUvs();
  12399. return _this;
  12400. }
  12401. Object.defineProperty(RenderTexture.prototype, "framebuffer", {
  12402. /**
  12403. * Shortcut to `this.baseTexture.framebuffer`, saves baseTexture cast.
  12404. * @readonly
  12405. */
  12406. get: function () {
  12407. return this.baseTexture.framebuffer;
  12408. },
  12409. enumerable: false,
  12410. configurable: true
  12411. });
  12412. Object.defineProperty(RenderTexture.prototype, "multisample", {
  12413. /**
  12414. * Shortcut to `this.framebuffer.multisample`.
  12415. * @default PIXI.MSAA_QUALITY.NONE
  12416. */
  12417. get: function () {
  12418. return this.framebuffer.multisample;
  12419. },
  12420. set: function (value) {
  12421. this.framebuffer.multisample = value;
  12422. },
  12423. enumerable: false,
  12424. configurable: true
  12425. });
  12426. /**
  12427. * Resizes the RenderTexture.
  12428. * @param desiredWidth - The desired width to resize to.
  12429. * @param desiredHeight - The desired height to resize to.
  12430. * @param resizeBaseTexture - Should the baseTexture.width and height values be resized as well?
  12431. */
  12432. RenderTexture.prototype.resize = function (desiredWidth, desiredHeight, resizeBaseTexture) {
  12433. if (resizeBaseTexture === void 0) { resizeBaseTexture = true; }
  12434. var resolution = this.baseTexture.resolution;
  12435. var width = Math.round(desiredWidth * resolution) / resolution;
  12436. var height = Math.round(desiredHeight * resolution) / resolution;
  12437. // TODO - could be not required..
  12438. this.valid = (width > 0 && height > 0);
  12439. this._frame.width = this.orig.width = width;
  12440. this._frame.height = this.orig.height = height;
  12441. if (resizeBaseTexture) {
  12442. this.baseTexture.resize(width, height);
  12443. }
  12444. this.updateUvs();
  12445. };
  12446. /**
  12447. * Changes the resolution of baseTexture, but does not change framebuffer size.
  12448. * @param resolution - The new resolution to apply to RenderTexture
  12449. */
  12450. RenderTexture.prototype.setResolution = function (resolution) {
  12451. var baseTexture = this.baseTexture;
  12452. if (baseTexture.resolution === resolution) {
  12453. return;
  12454. }
  12455. baseTexture.setResolution(resolution);
  12456. this.resize(baseTexture.width, baseTexture.height, false);
  12457. };
  12458. RenderTexture.create = function (options) {
  12459. var arguments$1 = arguments;
  12460. var rest = [];
  12461. for (var _i = 1; _i < arguments.length; _i++) {
  12462. rest[_i - 1] = arguments$1[_i];
  12463. }
  12464. // @deprecated fallback, old-style: create(width, height, scaleMode, resolution)
  12465. if (typeof options === 'number') {
  12466. deprecation('6.0.0', 'Arguments (width, height, scaleMode, resolution) have been deprecated.');
  12467. /* eslint-disable prefer-rest-params */
  12468. options = {
  12469. width: options,
  12470. height: rest[0],
  12471. scaleMode: rest[1],
  12472. resolution: rest[2],
  12473. };
  12474. /* eslint-enable prefer-rest-params */
  12475. }
  12476. return new RenderTexture(new BaseRenderTexture(options));
  12477. };
  12478. return RenderTexture;
  12479. }(Texture));
  12480. /**
  12481. * Texture pool, used by FilterSystem and plugins.
  12482. *
  12483. * Stores collection of temporary pow2 or screen-sized renderTextures
  12484. *
  12485. * If you use custom RenderTexturePool for your filters, you can use methods
  12486. * `getFilterTexture` and `returnFilterTexture` same as in
  12487. * @memberof PIXI
  12488. */
  12489. var RenderTexturePool = /** @class */ (function () {
  12490. /**
  12491. * @param textureOptions - options that will be passed to BaseRenderTexture constructor
  12492. * @param {PIXI.SCALE_MODES} [textureOptions.scaleMode] - See {@link PIXI.SCALE_MODES} for possible values.
  12493. */
  12494. function RenderTexturePool(textureOptions) {
  12495. this.texturePool = {};
  12496. this.textureOptions = textureOptions || {};
  12497. this.enableFullScreen = false;
  12498. this._pixelsWidth = 0;
  12499. this._pixelsHeight = 0;
  12500. }
  12501. /**
  12502. * Creates texture with params that were specified in pool constructor.
  12503. * @param realWidth - Width of texture in pixels.
  12504. * @param realHeight - Height of texture in pixels.
  12505. * @param multisample - Number of samples of the framebuffer.
  12506. */
  12507. RenderTexturePool.prototype.createTexture = function (realWidth, realHeight, multisample) {
  12508. if (multisample === void 0) { multisample = MSAA_QUALITY.NONE; }
  12509. var baseRenderTexture = new BaseRenderTexture(Object.assign({
  12510. width: realWidth,
  12511. height: realHeight,
  12512. resolution: 1,
  12513. multisample: multisample,
  12514. }, this.textureOptions));
  12515. return new RenderTexture(baseRenderTexture);
  12516. };
  12517. /**
  12518. * Gets a Power-of-Two render texture or fullScreen texture
  12519. * @param minWidth - The minimum width of the render texture.
  12520. * @param minHeight - The minimum height of the render texture.
  12521. * @param resolution - The resolution of the render texture.
  12522. * @param multisample - Number of samples of the render texture.
  12523. * @returns The new render texture.
  12524. */
  12525. RenderTexturePool.prototype.getOptimalTexture = function (minWidth, minHeight, resolution, multisample) {
  12526. if (resolution === void 0) { resolution = 1; }
  12527. if (multisample === void 0) { multisample = MSAA_QUALITY.NONE; }
  12528. var key;
  12529. minWidth = Math.ceil((minWidth * resolution) - 1e-6);
  12530. minHeight = Math.ceil((minHeight * resolution) - 1e-6);
  12531. if (!this.enableFullScreen || minWidth !== this._pixelsWidth || minHeight !== this._pixelsHeight) {
  12532. minWidth = nextPow2(minWidth);
  12533. minHeight = nextPow2(minHeight);
  12534. key = (((minWidth & 0xFFFF) << 16) | (minHeight & 0xFFFF)) >>> 0;
  12535. if (multisample > 1) {
  12536. key += multisample * 0x100000000;
  12537. }
  12538. }
  12539. else {
  12540. key = multisample > 1 ? -multisample : -1;
  12541. }
  12542. if (!this.texturePool[key]) {
  12543. this.texturePool[key] = [];
  12544. }
  12545. var renderTexture = this.texturePool[key].pop();
  12546. if (!renderTexture) {
  12547. renderTexture = this.createTexture(minWidth, minHeight, multisample);
  12548. }
  12549. renderTexture.filterPoolKey = key;
  12550. renderTexture.setResolution(resolution);
  12551. return renderTexture;
  12552. };
  12553. /**
  12554. * Gets extra texture of the same size as input renderTexture
  12555. *
  12556. * `getFilterTexture(input, 0.5)` or `getFilterTexture(0.5, input)`
  12557. * @param input - renderTexture from which size and resolution will be copied
  12558. * @param resolution - override resolution of the renderTexture
  12559. * It overrides, it does not multiply
  12560. * @param multisample - number of samples of the renderTexture
  12561. */
  12562. RenderTexturePool.prototype.getFilterTexture = function (input, resolution, multisample) {
  12563. var filterTexture = this.getOptimalTexture(input.width, input.height, resolution || input.resolution, multisample || MSAA_QUALITY.NONE);
  12564. filterTexture.filterFrame = input.filterFrame;
  12565. return filterTexture;
  12566. };
  12567. /**
  12568. * Place a render texture back into the pool.
  12569. * @param renderTexture - The renderTexture to free
  12570. */
  12571. RenderTexturePool.prototype.returnTexture = function (renderTexture) {
  12572. var key = renderTexture.filterPoolKey;
  12573. renderTexture.filterFrame = null;
  12574. this.texturePool[key].push(renderTexture);
  12575. };
  12576. /**
  12577. * Alias for returnTexture, to be compliant with FilterSystem interface.
  12578. * @param renderTexture - The renderTexture to free
  12579. */
  12580. RenderTexturePool.prototype.returnFilterTexture = function (renderTexture) {
  12581. this.returnTexture(renderTexture);
  12582. };
  12583. /**
  12584. * Clears the pool.
  12585. * @param destroyTextures - Destroy all stored textures.
  12586. */
  12587. RenderTexturePool.prototype.clear = function (destroyTextures) {
  12588. destroyTextures = destroyTextures !== false;
  12589. if (destroyTextures) {
  12590. for (var i in this.texturePool) {
  12591. var textures = this.texturePool[i];
  12592. if (textures) {
  12593. for (var j = 0; j < textures.length; j++) {
  12594. textures[j].destroy(true);
  12595. }
  12596. }
  12597. }
  12598. }
  12599. this.texturePool = {};
  12600. };
  12601. /**
  12602. * If screen size was changed, drops all screen-sized textures,
  12603. * sets new screen size, sets `enableFullScreen` to true
  12604. *
  12605. * Size is measured in pixels, `renderer.view` can be passed here, not `renderer.screen`
  12606. * @param size - Initial size of screen.
  12607. */
  12608. RenderTexturePool.prototype.setScreenSize = function (size) {
  12609. if (size.width === this._pixelsWidth
  12610. && size.height === this._pixelsHeight) {
  12611. return;
  12612. }
  12613. this.enableFullScreen = size.width > 0 && size.height > 0;
  12614. for (var i in this.texturePool) {
  12615. if (!(Number(i) < 0)) {
  12616. continue;
  12617. }
  12618. var textures = this.texturePool[i];
  12619. if (textures) {
  12620. for (var j = 0; j < textures.length; j++) {
  12621. textures[j].destroy(true);
  12622. }
  12623. }
  12624. this.texturePool[i] = [];
  12625. }
  12626. this._pixelsWidth = size.width;
  12627. this._pixelsHeight = size.height;
  12628. };
  12629. /**
  12630. * Key that is used to store fullscreen renderTextures in a pool
  12631. * @constant
  12632. */
  12633. RenderTexturePool.SCREEN_KEY = -1;
  12634. return RenderTexturePool;
  12635. }());
  12636. /* eslint-disable max-len */
  12637. /**
  12638. * Holds the information for a single attribute structure required to render geometry.
  12639. *
  12640. * This does not contain the actual data, but instead has a buffer id that maps to a {@link PIXI.Buffer}
  12641. * This can include anything from positions, uvs, normals, colors etc.
  12642. * @memberof PIXI
  12643. */
  12644. var Attribute = /** @class */ (function () {
  12645. /**
  12646. * @param buffer - the id of the buffer that this attribute will look for
  12647. * @param size - the size of the attribute. If you have 2 floats per vertex (eg position x and y) this would be 2.
  12648. * @param normalized - should the data be normalized.
  12649. * @param {PIXI.TYPES} [type=PIXI.TYPES.FLOAT] - what type of number is the attribute. Check {@link PIXI.TYPES} to see the ones available
  12650. * @param [stride=0] - How far apart, in bytes, the start of each value is. (used for interleaving data)
  12651. * @param [start=0] - How far into the array to start reading values (used for interleaving data)
  12652. * @param [instance=false] - Whether the geometry is instanced.
  12653. */
  12654. function Attribute(buffer, size, normalized, type, stride, start, instance) {
  12655. if (size === void 0) { size = 0; }
  12656. if (normalized === void 0) { normalized = false; }
  12657. if (type === void 0) { type = TYPES.FLOAT; }
  12658. this.buffer = buffer;
  12659. this.size = size;
  12660. this.normalized = normalized;
  12661. this.type = type;
  12662. this.stride = stride;
  12663. this.start = start;
  12664. this.instance = instance;
  12665. }
  12666. /** Destroys the Attribute. */
  12667. Attribute.prototype.destroy = function () {
  12668. this.buffer = null;
  12669. };
  12670. /**
  12671. * Helper function that creates an Attribute based on the information provided
  12672. * @param buffer - the id of the buffer that this attribute will look for
  12673. * @param [size=0] - the size of the attribute. If you have 2 floats per vertex (eg position x and y) this would be 2
  12674. * @param [normalized=false] - should the data be normalized.
  12675. * @param [type=PIXI.TYPES.FLOAT] - what type of number is the attribute. Check {@link PIXI.TYPES} to see the ones available
  12676. * @param [stride=0] - How far apart, in bytes, the start of each value is. (used for interleaving data)
  12677. * @returns - A new {@link PIXI.Attribute} based on the information provided
  12678. */
  12679. Attribute.from = function (buffer, size, normalized, type, stride) {
  12680. return new Attribute(buffer, size, normalized, type, stride);
  12681. };
  12682. return Attribute;
  12683. }());
  12684. var UID$4 = 0;
  12685. /**
  12686. * A wrapper for data so that it can be used and uploaded by WebGL
  12687. * @memberof PIXI
  12688. */
  12689. var Buffer = /** @class */ (function () {
  12690. /**
  12691. * @param {PIXI.IArrayBuffer} data - the data to store in the buffer.
  12692. * @param _static - `true` for static buffer
  12693. * @param index - `true` for index buffer
  12694. */
  12695. function Buffer(data, _static, index) {
  12696. if (_static === void 0) { _static = true; }
  12697. if (index === void 0) { index = false; }
  12698. this.data = (data || new Float32Array(1));
  12699. this._glBuffers = {};
  12700. this._updateID = 0;
  12701. this.index = index;
  12702. this.static = _static;
  12703. this.id = UID$4++;
  12704. this.disposeRunner = new Runner('disposeBuffer');
  12705. }
  12706. // TODO could explore flagging only a partial upload?
  12707. /**
  12708. * Flags this buffer as requiring an upload to the GPU.
  12709. * @param {PIXI.IArrayBuffer|number[]} [data] - the data to update in the buffer.
  12710. */
  12711. Buffer.prototype.update = function (data) {
  12712. if (data instanceof Array) {
  12713. data = new Float32Array(data);
  12714. }
  12715. this.data = data || this.data;
  12716. this._updateID++;
  12717. };
  12718. /** Disposes WebGL resources that are connected to this geometry. */
  12719. Buffer.prototype.dispose = function () {
  12720. this.disposeRunner.emit(this, false);
  12721. };
  12722. /** Destroys the buffer. */
  12723. Buffer.prototype.destroy = function () {
  12724. this.dispose();
  12725. this.data = null;
  12726. };
  12727. Object.defineProperty(Buffer.prototype, "index", {
  12728. get: function () {
  12729. return this.type === BUFFER_TYPE.ELEMENT_ARRAY_BUFFER;
  12730. },
  12731. /**
  12732. * Flags whether this is an index buffer.
  12733. *
  12734. * Index buffers are of type `ELEMENT_ARRAY_BUFFER`. Note that setting this property to false will make
  12735. * the buffer of type `ARRAY_BUFFER`.
  12736. *
  12737. * For backwards compatibility.
  12738. */
  12739. set: function (value) {
  12740. this.type = value ? BUFFER_TYPE.ELEMENT_ARRAY_BUFFER : BUFFER_TYPE.ARRAY_BUFFER;
  12741. },
  12742. enumerable: false,
  12743. configurable: true
  12744. });
  12745. /**
  12746. * Helper function that creates a buffer based on an array or TypedArray
  12747. * @param {ArrayBufferView | number[]} data - the TypedArray that the buffer will store. If this is a regular Array it will be converted to a Float32Array.
  12748. * @returns - A new Buffer based on the data provided.
  12749. */
  12750. Buffer.from = function (data) {
  12751. if (data instanceof Array) {
  12752. data = new Float32Array(data);
  12753. }
  12754. return new Buffer(data);
  12755. };
  12756. return Buffer;
  12757. }());
  12758. /* eslint-disable object-shorthand */
  12759. var map$1 = {
  12760. Float32Array: Float32Array,
  12761. Uint32Array: Uint32Array,
  12762. Int32Array: Int32Array,
  12763. Uint8Array: Uint8Array,
  12764. };
  12765. function interleaveTypedArrays(arrays, sizes) {
  12766. var outSize = 0;
  12767. var stride = 0;
  12768. var views = {};
  12769. for (var i = 0; i < arrays.length; i++) {
  12770. stride += sizes[i];
  12771. outSize += arrays[i].length;
  12772. }
  12773. var buffer = new ArrayBuffer(outSize * 4);
  12774. var out = null;
  12775. var littleOffset = 0;
  12776. for (var i = 0; i < arrays.length; i++) {
  12777. var size = sizes[i];
  12778. var array = arrays[i];
  12779. var type = getBufferType(array);
  12780. if (!views[type]) {
  12781. views[type] = new map$1[type](buffer);
  12782. }
  12783. out = views[type];
  12784. for (var j = 0; j < array.length; j++) {
  12785. var indexStart = ((j / size | 0) * stride) + littleOffset;
  12786. var index = j % size;
  12787. out[indexStart + index] = array[j];
  12788. }
  12789. littleOffset += size;
  12790. }
  12791. return new Float32Array(buffer);
  12792. }
  12793. var byteSizeMap$1 = { 5126: 4, 5123: 2, 5121: 1 };
  12794. var UID$3 = 0;
  12795. /* eslint-disable object-shorthand */
  12796. var map = {
  12797. Float32Array: Float32Array,
  12798. Uint32Array: Uint32Array,
  12799. Int32Array: Int32Array,
  12800. Uint8Array: Uint8Array,
  12801. Uint16Array: Uint16Array,
  12802. };
  12803. /* eslint-disable max-len */
  12804. /**
  12805. * The Geometry represents a model. It consists of two components:
  12806. * - GeometryStyle - The structure of the model such as the attributes layout
  12807. * - GeometryData - the data of the model - this consists of buffers.
  12808. * This can include anything from positions, uvs, normals, colors etc.
  12809. *
  12810. * Geometry can be defined without passing in a style or data if required (thats how I prefer!)
  12811. *
  12812. * ```js
  12813. * let geometry = new PIXI.Geometry();
  12814. *
  12815. * geometry.addAttribute('positions', [0, 0, 100, 0, 100, 100, 0, 100], 2);
  12816. * geometry.addAttribute('uvs', [0,0,1,0,1,1,0,1],2)
  12817. * geometry.addIndex([0,1,2,1,3,2])
  12818. * ```
  12819. * @memberof PIXI
  12820. */
  12821. var Geometry = /** @class */ (function () {
  12822. /**
  12823. * @param buffers - An array of buffers. optional.
  12824. * @param attributes - Of the geometry, optional structure of the attributes layout
  12825. */
  12826. function Geometry(buffers, attributes) {
  12827. if (buffers === void 0) { buffers = []; }
  12828. if (attributes === void 0) { attributes = {}; }
  12829. this.buffers = buffers;
  12830. this.indexBuffer = null;
  12831. this.attributes = attributes;
  12832. this.glVertexArrayObjects = {};
  12833. this.id = UID$3++;
  12834. this.instanced = false;
  12835. this.instanceCount = 1;
  12836. this.disposeRunner = new Runner('disposeGeometry');
  12837. this.refCount = 0;
  12838. }
  12839. /**
  12840. *
  12841. * Adds an attribute to the geometry
  12842. * Note: `stride` and `start` should be `undefined` if you dont know them, not 0!
  12843. * @param id - the name of the attribute (matching up to a shader)
  12844. * @param {PIXI.Buffer|number[]} buffer - the buffer that holds the data of the attribute . You can also provide an Array and a buffer will be created from it.
  12845. * @param size - the size of the attribute. If you have 2 floats per vertex (eg position x and y) this would be 2
  12846. * @param normalized - should the data be normalized.
  12847. * @param [type=PIXI.TYPES.FLOAT] - what type of number is the attribute. Check {PIXI.TYPES} to see the ones available
  12848. * @param [stride=0] - How far apart, in bytes, the start of each value is. (used for interleaving data)
  12849. * @param [start=0] - How far into the array to start reading values (used for interleaving data)
  12850. * @param instance - Instancing flag
  12851. * @returns - Returns self, useful for chaining.
  12852. */
  12853. Geometry.prototype.addAttribute = function (id, buffer, size, normalized, type, stride, start, instance) {
  12854. if (size === void 0) { size = 0; }
  12855. if (normalized === void 0) { normalized = false; }
  12856. if (instance === void 0) { instance = false; }
  12857. if (!buffer) {
  12858. throw new Error('You must pass a buffer when creating an attribute');
  12859. }
  12860. // check if this is a buffer!
  12861. if (!(buffer instanceof Buffer)) {
  12862. // its an array!
  12863. if (buffer instanceof Array) {
  12864. buffer = new Float32Array(buffer);
  12865. }
  12866. buffer = new Buffer(buffer);
  12867. }
  12868. var ids = id.split('|');
  12869. if (ids.length > 1) {
  12870. for (var i = 0; i < ids.length; i++) {
  12871. this.addAttribute(ids[i], buffer, size, normalized, type);
  12872. }
  12873. return this;
  12874. }
  12875. var bufferIndex = this.buffers.indexOf(buffer);
  12876. if (bufferIndex === -1) {
  12877. this.buffers.push(buffer);
  12878. bufferIndex = this.buffers.length - 1;
  12879. }
  12880. this.attributes[id] = new Attribute(bufferIndex, size, normalized, type, stride, start, instance);
  12881. // assuming that if there is instanced data then this will be drawn with instancing!
  12882. this.instanced = this.instanced || instance;
  12883. return this;
  12884. };
  12885. /**
  12886. * Returns the requested attribute.
  12887. * @param id - The name of the attribute required
  12888. * @returns - The attribute requested.
  12889. */
  12890. Geometry.prototype.getAttribute = function (id) {
  12891. return this.attributes[id];
  12892. };
  12893. /**
  12894. * Returns the requested buffer.
  12895. * @param id - The name of the buffer required.
  12896. * @returns - The buffer requested.
  12897. */
  12898. Geometry.prototype.getBuffer = function (id) {
  12899. return this.buffers[this.getAttribute(id).buffer];
  12900. };
  12901. /**
  12902. *
  12903. * Adds an index buffer to the geometry
  12904. * The index buffer contains integers, three for each triangle in the geometry, which reference the various attribute buffers (position, colour, UV coordinates, other UV coordinates, normal, …). There is only ONE index buffer.
  12905. * @param {PIXI.Buffer|number[]} [buffer] - The buffer that holds the data of the index buffer. You can also provide an Array and a buffer will be created from it.
  12906. * @returns - Returns self, useful for chaining.
  12907. */
  12908. Geometry.prototype.addIndex = function (buffer) {
  12909. if (!(buffer instanceof Buffer)) {
  12910. // its an array!
  12911. if (buffer instanceof Array) {
  12912. buffer = new Uint16Array(buffer);
  12913. }
  12914. buffer = new Buffer(buffer);
  12915. }
  12916. buffer.type = BUFFER_TYPE.ELEMENT_ARRAY_BUFFER;
  12917. this.indexBuffer = buffer;
  12918. if (this.buffers.indexOf(buffer) === -1) {
  12919. this.buffers.push(buffer);
  12920. }
  12921. return this;
  12922. };
  12923. /**
  12924. * Returns the index buffer
  12925. * @returns - The index buffer.
  12926. */
  12927. Geometry.prototype.getIndex = function () {
  12928. return this.indexBuffer;
  12929. };
  12930. /**
  12931. * This function modifies the structure so that all current attributes become interleaved into a single buffer
  12932. * This can be useful if your model remains static as it offers a little performance boost
  12933. * @returns - Returns self, useful for chaining.
  12934. */
  12935. Geometry.prototype.interleave = function () {
  12936. // a simple check to see if buffers are already interleaved..
  12937. if (this.buffers.length === 1 || (this.buffers.length === 2 && this.indexBuffer))
  12938. { return this; }
  12939. // assume already that no buffers are interleaved
  12940. var arrays = [];
  12941. var sizes = [];
  12942. var interleavedBuffer = new Buffer();
  12943. var i;
  12944. for (i in this.attributes) {
  12945. var attribute = this.attributes[i];
  12946. var buffer = this.buffers[attribute.buffer];
  12947. arrays.push(buffer.data);
  12948. sizes.push((attribute.size * byteSizeMap$1[attribute.type]) / 4);
  12949. attribute.buffer = 0;
  12950. }
  12951. interleavedBuffer.data = interleaveTypedArrays(arrays, sizes);
  12952. for (i = 0; i < this.buffers.length; i++) {
  12953. if (this.buffers[i] !== this.indexBuffer) {
  12954. this.buffers[i].destroy();
  12955. }
  12956. }
  12957. this.buffers = [interleavedBuffer];
  12958. if (this.indexBuffer) {
  12959. this.buffers.push(this.indexBuffer);
  12960. }
  12961. return this;
  12962. };
  12963. /** Get the size of the geometries, in vertices. */
  12964. Geometry.prototype.getSize = function () {
  12965. for (var i in this.attributes) {
  12966. var attribute = this.attributes[i];
  12967. var buffer = this.buffers[attribute.buffer];
  12968. return buffer.data.length / ((attribute.stride / 4) || attribute.size);
  12969. }
  12970. return 0;
  12971. };
  12972. /** Disposes WebGL resources that are connected to this geometry. */
  12973. Geometry.prototype.dispose = function () {
  12974. this.disposeRunner.emit(this, false);
  12975. };
  12976. /** Destroys the geometry. */
  12977. Geometry.prototype.destroy = function () {
  12978. this.dispose();
  12979. this.buffers = null;
  12980. this.indexBuffer = null;
  12981. this.attributes = null;
  12982. };
  12983. /**
  12984. * Returns a clone of the geometry.
  12985. * @returns - A new clone of this geometry.
  12986. */
  12987. Geometry.prototype.clone = function () {
  12988. var geometry = new Geometry();
  12989. for (var i = 0; i < this.buffers.length; i++) {
  12990. geometry.buffers[i] = new Buffer(this.buffers[i].data.slice(0));
  12991. }
  12992. for (var i in this.attributes) {
  12993. var attrib = this.attributes[i];
  12994. geometry.attributes[i] = new Attribute(attrib.buffer, attrib.size, attrib.normalized, attrib.type, attrib.stride, attrib.start, attrib.instance);
  12995. }
  12996. if (this.indexBuffer) {
  12997. geometry.indexBuffer = geometry.buffers[this.buffers.indexOf(this.indexBuffer)];
  12998. geometry.indexBuffer.type = BUFFER_TYPE.ELEMENT_ARRAY_BUFFER;
  12999. }
  13000. return geometry;
  13001. };
  13002. /**
  13003. * Merges an array of geometries into a new single one.
  13004. *
  13005. * Geometry attribute styles must match for this operation to work.
  13006. * @param geometries - array of geometries to merge
  13007. * @returns - Shiny new geometry!
  13008. */
  13009. Geometry.merge = function (geometries) {
  13010. // todo add a geometry check!
  13011. // also a size check.. cant be too big!]
  13012. var geometryOut = new Geometry();
  13013. var arrays = [];
  13014. var sizes = [];
  13015. var offsets = [];
  13016. var geometry;
  13017. // pass one.. get sizes..
  13018. for (var i = 0; i < geometries.length; i++) {
  13019. geometry = geometries[i];
  13020. for (var j = 0; j < geometry.buffers.length; j++) {
  13021. sizes[j] = sizes[j] || 0;
  13022. sizes[j] += geometry.buffers[j].data.length;
  13023. offsets[j] = 0;
  13024. }
  13025. }
  13026. // build the correct size arrays..
  13027. for (var i = 0; i < geometry.buffers.length; i++) {
  13028. // TODO types!
  13029. arrays[i] = new map[getBufferType(geometry.buffers[i].data)](sizes[i]);
  13030. geometryOut.buffers[i] = new Buffer(arrays[i]);
  13031. }
  13032. // pass to set data..
  13033. for (var i = 0; i < geometries.length; i++) {
  13034. geometry = geometries[i];
  13035. for (var j = 0; j < geometry.buffers.length; j++) {
  13036. arrays[j].set(geometry.buffers[j].data, offsets[j]);
  13037. offsets[j] += geometry.buffers[j].data.length;
  13038. }
  13039. }
  13040. geometryOut.attributes = geometry.attributes;
  13041. if (geometry.indexBuffer) {
  13042. geometryOut.indexBuffer = geometryOut.buffers[geometry.buffers.indexOf(geometry.indexBuffer)];
  13043. geometryOut.indexBuffer.type = BUFFER_TYPE.ELEMENT_ARRAY_BUFFER;
  13044. var offset = 0;
  13045. var stride = 0;
  13046. var offset2 = 0;
  13047. var bufferIndexToCount = 0;
  13048. // get a buffer
  13049. for (var i = 0; i < geometry.buffers.length; i++) {
  13050. if (geometry.buffers[i] !== geometry.indexBuffer) {
  13051. bufferIndexToCount = i;
  13052. break;
  13053. }
  13054. }
  13055. // figure out the stride of one buffer..
  13056. for (var i in geometry.attributes) {
  13057. var attribute = geometry.attributes[i];
  13058. if ((attribute.buffer | 0) === bufferIndexToCount) {
  13059. stride += ((attribute.size * byteSizeMap$1[attribute.type]) / 4);
  13060. }
  13061. }
  13062. // time to off set all indexes..
  13063. for (var i = 0; i < geometries.length; i++) {
  13064. var indexBufferData = geometries[i].indexBuffer.data;
  13065. for (var j = 0; j < indexBufferData.length; j++) {
  13066. geometryOut.indexBuffer.data[j + offset2] += offset;
  13067. }
  13068. offset += geometries[i].buffers[bufferIndexToCount].data.length / (stride);
  13069. offset2 += indexBufferData.length;
  13070. }
  13071. }
  13072. return geometryOut;
  13073. };
  13074. return Geometry;
  13075. }());
  13076. /**
  13077. * Helper class to create a quad
  13078. * @memberof PIXI
  13079. */
  13080. var Quad = /** @class */ (function (_super) {
  13081. __extends$i(Quad, _super);
  13082. function Quad() {
  13083. var _this = _super.call(this) || this;
  13084. _this.addAttribute('aVertexPosition', new Float32Array([
  13085. 0, 0,
  13086. 1, 0,
  13087. 1, 1,
  13088. 0, 1 ]))
  13089. .addIndex([0, 1, 3, 2]);
  13090. return _this;
  13091. }
  13092. return Quad;
  13093. }(Geometry));
  13094. /**
  13095. * Helper class to create a quad with uvs like in v4
  13096. * @memberof PIXI
  13097. */
  13098. var QuadUv = /** @class */ (function (_super) {
  13099. __extends$i(QuadUv, _super);
  13100. function QuadUv() {
  13101. var _this = _super.call(this) || this;
  13102. _this.vertices = new Float32Array([
  13103. -1, -1,
  13104. 1, -1,
  13105. 1, 1,
  13106. -1, 1 ]);
  13107. _this.uvs = new Float32Array([
  13108. 0, 0,
  13109. 1, 0,
  13110. 1, 1,
  13111. 0, 1 ]);
  13112. _this.vertexBuffer = new Buffer(_this.vertices);
  13113. _this.uvBuffer = new Buffer(_this.uvs);
  13114. _this.addAttribute('aVertexPosition', _this.vertexBuffer)
  13115. .addAttribute('aTextureCoord', _this.uvBuffer)
  13116. .addIndex([0, 1, 2, 0, 2, 3]);
  13117. return _this;
  13118. }
  13119. /**
  13120. * Maps two Rectangle to the quad.
  13121. * @param targetTextureFrame - The first rectangle
  13122. * @param destinationFrame - The second rectangle
  13123. * @returns - Returns itself.
  13124. */
  13125. QuadUv.prototype.map = function (targetTextureFrame, destinationFrame) {
  13126. var x = 0; // destinationFrame.x / targetTextureFrame.width;
  13127. var y = 0; // destinationFrame.y / targetTextureFrame.height;
  13128. this.uvs[0] = x;
  13129. this.uvs[1] = y;
  13130. this.uvs[2] = x + (destinationFrame.width / targetTextureFrame.width);
  13131. this.uvs[3] = y;
  13132. this.uvs[4] = x + (destinationFrame.width / targetTextureFrame.width);
  13133. this.uvs[5] = y + (destinationFrame.height / targetTextureFrame.height);
  13134. this.uvs[6] = x;
  13135. this.uvs[7] = y + (destinationFrame.height / targetTextureFrame.height);
  13136. x = destinationFrame.x;
  13137. y = destinationFrame.y;
  13138. this.vertices[0] = x;
  13139. this.vertices[1] = y;
  13140. this.vertices[2] = x + destinationFrame.width;
  13141. this.vertices[3] = y;
  13142. this.vertices[4] = x + destinationFrame.width;
  13143. this.vertices[5] = y + destinationFrame.height;
  13144. this.vertices[6] = x;
  13145. this.vertices[7] = y + destinationFrame.height;
  13146. this.invalidate();
  13147. return this;
  13148. };
  13149. /**
  13150. * Legacy upload method, just marks buffers dirty.
  13151. * @returns - Returns itself.
  13152. */
  13153. QuadUv.prototype.invalidate = function () {
  13154. this.vertexBuffer._updateID++;
  13155. this.uvBuffer._updateID++;
  13156. return this;
  13157. };
  13158. return QuadUv;
  13159. }(Geometry));
  13160. var UID$2 = 0;
  13161. /**
  13162. * Uniform group holds uniform map and some ID's for work
  13163. *
  13164. * `UniformGroup` has two modes:
  13165. *
  13166. * 1: Normal mode
  13167. * Normal mode will upload the uniforms with individual function calls as required
  13168. *
  13169. * 2: Uniform buffer mode
  13170. * This mode will treat the uniforms as a uniform buffer. You can pass in either a buffer that you manually handle, or
  13171. * or a generic object that PixiJS will automatically map to a buffer for you.
  13172. * For maximum benefits, make Ubo UniformGroups static, and only update them each frame.
  13173. *
  13174. * Rules of UBOs:
  13175. * - UBOs only work with WebGL2, so make sure you have a fallback!
  13176. * - Only floats are supported (including vec[2,3,4], mat[2,3,4])
  13177. * - Samplers cannot be used in ubo's (a GPU limitation)
  13178. * - You must ensure that the object you pass in exactly matches in the shader ubo structure.
  13179. * Otherwise, weirdness will ensue!
  13180. * - The name of the ubo object added to the group must match exactly the name of the ubo in the shader.
  13181. *
  13182. * ```
  13183. * // ubo in shader:
  13184. * uniform myCoolData { // declaring a ubo..
  13185. * mat4 uCoolMatrix;
  13186. * float uFloatyMcFloatFace
  13187. *
  13188. *
  13189. * // a new uniform buffer object..
  13190. * const myCoolData = new UniformBufferGroup({
  13191. * uCoolMatrix: new Matrix(),
  13192. * uFloatyMcFloatFace: 23,
  13193. * }}
  13194. *
  13195. * // build a shader...
  13196. * const shader = Shader.from(srcVert, srcFrag, {
  13197. * myCoolData // name matches the ubo name in the shader. will be processed accordingly.
  13198. * })
  13199. *
  13200. * ```
  13201. * @memberof PIXI
  13202. */
  13203. var UniformGroup = /** @class */ (function () {
  13204. /**
  13205. * @param {object | Buffer} [uniforms] - Custom uniforms to use to augment the built-in ones. Or a pixi buffer.
  13206. * @param isStatic - Uniforms wont be changed after creation.
  13207. * @param isUbo - If true, will treat this uniform group as a uniform buffer object.
  13208. */
  13209. function UniformGroup(uniforms, isStatic, isUbo) {
  13210. this.group = true;
  13211. // lets generate this when the shader ?
  13212. this.syncUniforms = {};
  13213. this.dirtyId = 0;
  13214. this.id = UID$2++;
  13215. this.static = !!isStatic;
  13216. this.ubo = !!isUbo;
  13217. if (uniforms instanceof Buffer) {
  13218. this.buffer = uniforms;
  13219. this.buffer.type = BUFFER_TYPE.UNIFORM_BUFFER;
  13220. this.autoManage = false;
  13221. this.ubo = true;
  13222. }
  13223. else {
  13224. this.uniforms = uniforms;
  13225. if (this.ubo) {
  13226. this.buffer = new Buffer(new Float32Array(1));
  13227. this.buffer.type = BUFFER_TYPE.UNIFORM_BUFFER;
  13228. this.autoManage = true;
  13229. }
  13230. }
  13231. }
  13232. UniformGroup.prototype.update = function () {
  13233. this.dirtyId++;
  13234. if (!this.autoManage && this.buffer) {
  13235. this.buffer.update();
  13236. }
  13237. };
  13238. UniformGroup.prototype.add = function (name, uniforms, _static) {
  13239. if (!this.ubo) {
  13240. this.uniforms[name] = new UniformGroup(uniforms, _static);
  13241. }
  13242. else {
  13243. // eslint-disable-next-line max-len
  13244. throw new Error('[UniformGroup] uniform groups in ubo mode cannot be modified, or have uniform groups nested in them');
  13245. }
  13246. };
  13247. UniformGroup.from = function (uniforms, _static, _ubo) {
  13248. return new UniformGroup(uniforms, _static, _ubo);
  13249. };
  13250. /**
  13251. * A short hand function for creating a static UBO UniformGroup.
  13252. * @param uniforms - the ubo item
  13253. * @param _static - should this be updated each time it is used? defaults to true here!
  13254. */
  13255. UniformGroup.uboFrom = function (uniforms, _static) {
  13256. return new UniformGroup(uniforms, _static !== null && _static !== void 0 ? _static : true, true);
  13257. };
  13258. return UniformGroup;
  13259. }());
  13260. /**
  13261. * System plugin to the renderer to manage filter states.
  13262. * @ignore
  13263. */
  13264. var FilterState = /** @class */ (function () {
  13265. function FilterState() {
  13266. this.renderTexture = null;
  13267. this.target = null;
  13268. this.legacy = false;
  13269. this.resolution = 1;
  13270. this.multisample = MSAA_QUALITY.NONE;
  13271. // next three fields are created only for root
  13272. // re-assigned for everything else
  13273. this.sourceFrame = new Rectangle();
  13274. this.destinationFrame = new Rectangle();
  13275. this.bindingSourceFrame = new Rectangle();
  13276. this.bindingDestinationFrame = new Rectangle();
  13277. this.filters = [];
  13278. this.transform = null;
  13279. }
  13280. /** Clears the state */
  13281. FilterState.prototype.clear = function () {
  13282. this.target = null;
  13283. this.filters = null;
  13284. this.renderTexture = null;
  13285. };
  13286. return FilterState;
  13287. }());
  13288. var tempPoints = [new Point(), new Point(), new Point(), new Point()];
  13289. var tempMatrix$2 = new Matrix();
  13290. /**
  13291. * System plugin to the renderer to manage filters.
  13292. *
  13293. * ## Pipeline
  13294. *
  13295. * The FilterSystem executes the filtering pipeline by rendering the display-object into a texture, applying its
  13296. * [filters]{@link PIXI.Filter} in series, and the last filter outputs into the final render-target.
  13297. *
  13298. * The filter-frame is the rectangle in world space being filtered, and those contents are mapped into
  13299. * `(0, 0, filterFrame.width, filterFrame.height)` into the filter render-texture. The filter-frame is also called
  13300. * the source-frame, as it is used to bind the filter render-textures. The last filter outputs to the `filterFrame`
  13301. * in the final render-target.
  13302. *
  13303. * ## Usage
  13304. *
  13305. * {@link PIXI.Container#renderAdvanced} is an example of how to use the filter system. It is a 3 step process:
  13306. *
  13307. * **push**: Use {@link PIXI.FilterSystem#push} to push the set of filters to be applied on a filter-target.
  13308. * **render**: Render the contents to be filtered using the renderer. The filter-system will only capture the contents
  13309. * inside the bounds of the filter-target. NOTE: Using {@link PIXI.Renderer#render} is
  13310. * illegal during an existing render cycle, and it may reset the filter system.
  13311. * **pop**: Use {@link PIXI.FilterSystem#pop} to pop & execute the filters you initially pushed. It will apply them
  13312. * serially and output to the bounds of the filter-target.
  13313. * @memberof PIXI
  13314. */
  13315. var FilterSystem = /** @class */ (function () {
  13316. /**
  13317. * @param renderer - The renderer this System works for.
  13318. */
  13319. function FilterSystem(renderer) {
  13320. this.renderer = renderer;
  13321. this.defaultFilterStack = [{}];
  13322. this.texturePool = new RenderTexturePool();
  13323. this.texturePool.setScreenSize(renderer.view);
  13324. this.statePool = [];
  13325. this.quad = new Quad();
  13326. this.quadUv = new QuadUv();
  13327. this.tempRect = new Rectangle();
  13328. this.activeState = {};
  13329. this.globalUniforms = new UniformGroup({
  13330. outputFrame: new Rectangle(),
  13331. inputSize: new Float32Array(4),
  13332. inputPixel: new Float32Array(4),
  13333. inputClamp: new Float32Array(4),
  13334. resolution: 1,
  13335. // legacy variables
  13336. filterArea: new Float32Array(4),
  13337. filterClamp: new Float32Array(4),
  13338. }, true);
  13339. this.forceClear = false;
  13340. this.useMaxPadding = false;
  13341. }
  13342. /**
  13343. * Pushes a set of filters to be applied later to the system. This will redirect further rendering into an
  13344. * input render-texture for the rest of the filtering pipeline.
  13345. * @param {PIXI.DisplayObject} target - The target of the filter to render.
  13346. * @param filters - The filters to apply.
  13347. */
  13348. FilterSystem.prototype.push = function (target, filters) {
  13349. var _a, _b;
  13350. var renderer = this.renderer;
  13351. var filterStack = this.defaultFilterStack;
  13352. var state = this.statePool.pop() || new FilterState();
  13353. var renderTextureSystem = this.renderer.renderTexture;
  13354. var resolution = filters[0].resolution;
  13355. var multisample = filters[0].multisample;
  13356. var padding = filters[0].padding;
  13357. var autoFit = filters[0].autoFit;
  13358. // We don't know whether it's a legacy filter until it was bound for the first time,
  13359. // therefore we have to assume that it is if legacy is undefined.
  13360. var legacy = (_a = filters[0].legacy) !== null && _a !== void 0 ? _a : true;
  13361. for (var i = 1; i < filters.length; i++) {
  13362. var filter = filters[i];
  13363. // let's use the lowest resolution
  13364. resolution = Math.min(resolution, filter.resolution);
  13365. // let's use the lowest number of samples
  13366. multisample = Math.min(multisample, filter.multisample);
  13367. // figure out the padding required for filters
  13368. padding = this.useMaxPadding
  13369. // old behavior: use largest amount of padding!
  13370. ? Math.max(padding, filter.padding)
  13371. // new behavior: sum the padding
  13372. : padding + filter.padding;
  13373. // only auto fit if all filters are autofit
  13374. autoFit = autoFit && filter.autoFit;
  13375. legacy = legacy || ((_b = filter.legacy) !== null && _b !== void 0 ? _b : true);
  13376. }
  13377. if (filterStack.length === 1) {
  13378. this.defaultFilterStack[0].renderTexture = renderTextureSystem.current;
  13379. }
  13380. filterStack.push(state);
  13381. state.resolution = resolution;
  13382. state.multisample = multisample;
  13383. state.legacy = legacy;
  13384. state.target = target;
  13385. state.sourceFrame.copyFrom(target.filterArea || target.getBounds(true));
  13386. state.sourceFrame.pad(padding);
  13387. var sourceFrameProjected = this.tempRect.copyFrom(renderTextureSystem.sourceFrame);
  13388. // Project source frame into world space (if projection is applied)
  13389. if (renderer.projection.transform) {
  13390. this.transformAABB(tempMatrix$2.copyFrom(renderer.projection.transform).invert(), sourceFrameProjected);
  13391. }
  13392. if (autoFit) {
  13393. state.sourceFrame.fit(sourceFrameProjected);
  13394. if (state.sourceFrame.width <= 0 || state.sourceFrame.height <= 0) {
  13395. state.sourceFrame.width = 0;
  13396. state.sourceFrame.height = 0;
  13397. }
  13398. }
  13399. else if (!state.sourceFrame.intersects(sourceFrameProjected)) {
  13400. state.sourceFrame.width = 0;
  13401. state.sourceFrame.height = 0;
  13402. }
  13403. // Round sourceFrame in screen space based on render-texture.
  13404. this.roundFrame(state.sourceFrame, renderTextureSystem.current ? renderTextureSystem.current.resolution : renderer.resolution, renderTextureSystem.sourceFrame, renderTextureSystem.destinationFrame, renderer.projection.transform);
  13405. state.renderTexture = this.getOptimalFilterTexture(state.sourceFrame.width, state.sourceFrame.height, resolution, multisample);
  13406. state.filters = filters;
  13407. state.destinationFrame.width = state.renderTexture.width;
  13408. state.destinationFrame.height = state.renderTexture.height;
  13409. var destinationFrame = this.tempRect;
  13410. destinationFrame.x = 0;
  13411. destinationFrame.y = 0;
  13412. destinationFrame.width = state.sourceFrame.width;
  13413. destinationFrame.height = state.sourceFrame.height;
  13414. state.renderTexture.filterFrame = state.sourceFrame;
  13415. state.bindingSourceFrame.copyFrom(renderTextureSystem.sourceFrame);
  13416. state.bindingDestinationFrame.copyFrom(renderTextureSystem.destinationFrame);
  13417. state.transform = renderer.projection.transform;
  13418. renderer.projection.transform = null;
  13419. renderTextureSystem.bind(state.renderTexture, state.sourceFrame, destinationFrame);
  13420. renderer.framebuffer.clear(0, 0, 0, 0);
  13421. };
  13422. /** Pops off the filter and applies it. */
  13423. FilterSystem.prototype.pop = function () {
  13424. var filterStack = this.defaultFilterStack;
  13425. var state = filterStack.pop();
  13426. var filters = state.filters;
  13427. this.activeState = state;
  13428. var globalUniforms = this.globalUniforms.uniforms;
  13429. globalUniforms.outputFrame = state.sourceFrame;
  13430. globalUniforms.resolution = state.resolution;
  13431. var inputSize = globalUniforms.inputSize;
  13432. var inputPixel = globalUniforms.inputPixel;
  13433. var inputClamp = globalUniforms.inputClamp;
  13434. inputSize[0] = state.destinationFrame.width;
  13435. inputSize[1] = state.destinationFrame.height;
  13436. inputSize[2] = 1.0 / inputSize[0];
  13437. inputSize[3] = 1.0 / inputSize[1];
  13438. inputPixel[0] = Math.round(inputSize[0] * state.resolution);
  13439. inputPixel[1] = Math.round(inputSize[1] * state.resolution);
  13440. inputPixel[2] = 1.0 / inputPixel[0];
  13441. inputPixel[3] = 1.0 / inputPixel[1];
  13442. inputClamp[0] = 0.5 * inputPixel[2];
  13443. inputClamp[1] = 0.5 * inputPixel[3];
  13444. inputClamp[2] = (state.sourceFrame.width * inputSize[2]) - (0.5 * inputPixel[2]);
  13445. inputClamp[3] = (state.sourceFrame.height * inputSize[3]) - (0.5 * inputPixel[3]);
  13446. // only update the rect if its legacy..
  13447. if (state.legacy) {
  13448. var filterArea = globalUniforms.filterArea;
  13449. filterArea[0] = state.destinationFrame.width;
  13450. filterArea[1] = state.destinationFrame.height;
  13451. filterArea[2] = state.sourceFrame.x;
  13452. filterArea[3] = state.sourceFrame.y;
  13453. globalUniforms.filterClamp = globalUniforms.inputClamp;
  13454. }
  13455. this.globalUniforms.update();
  13456. var lastState = filterStack[filterStack.length - 1];
  13457. this.renderer.framebuffer.blit();
  13458. if (filters.length === 1) {
  13459. filters[0].apply(this, state.renderTexture, lastState.renderTexture, CLEAR_MODES.BLEND, state);
  13460. this.returnFilterTexture(state.renderTexture);
  13461. }
  13462. else {
  13463. var flip = state.renderTexture;
  13464. var flop = this.getOptimalFilterTexture(flip.width, flip.height, state.resolution);
  13465. flop.filterFrame = flip.filterFrame;
  13466. var i = 0;
  13467. for (i = 0; i < filters.length - 1; ++i) {
  13468. if (i === 1 && state.multisample > 1) {
  13469. flop = this.getOptimalFilterTexture(flip.width, flip.height, state.resolution);
  13470. flop.filterFrame = flip.filterFrame;
  13471. }
  13472. filters[i].apply(this, flip, flop, CLEAR_MODES.CLEAR, state);
  13473. var t = flip;
  13474. flip = flop;
  13475. flop = t;
  13476. }
  13477. filters[i].apply(this, flip, lastState.renderTexture, CLEAR_MODES.BLEND, state);
  13478. if (i > 1 && state.multisample > 1) {
  13479. this.returnFilterTexture(state.renderTexture);
  13480. }
  13481. this.returnFilterTexture(flip);
  13482. this.returnFilterTexture(flop);
  13483. }
  13484. // lastState.renderTexture is blitted when lastState is popped
  13485. state.clear();
  13486. this.statePool.push(state);
  13487. };
  13488. /**
  13489. * Binds a renderTexture with corresponding `filterFrame`, clears it if mode corresponds.
  13490. * @param filterTexture - renderTexture to bind, should belong to filter pool or filter stack
  13491. * @param clearMode - clearMode, by default its CLEAR/YES. See {@link PIXI.CLEAR_MODES}
  13492. */
  13493. FilterSystem.prototype.bindAndClear = function (filterTexture, clearMode) {
  13494. if (clearMode === void 0) { clearMode = CLEAR_MODES.CLEAR; }
  13495. var _a = this.renderer, renderTextureSystem = _a.renderTexture, stateSystem = _a.state;
  13496. if (filterTexture === this.defaultFilterStack[this.defaultFilterStack.length - 1].renderTexture) {
  13497. // Restore projection transform if rendering into the output render-target.
  13498. this.renderer.projection.transform = this.activeState.transform;
  13499. }
  13500. else {
  13501. // Prevent projection within filtering pipeline.
  13502. this.renderer.projection.transform = null;
  13503. }
  13504. if (filterTexture && filterTexture.filterFrame) {
  13505. var destinationFrame = this.tempRect;
  13506. destinationFrame.x = 0;
  13507. destinationFrame.y = 0;
  13508. destinationFrame.width = filterTexture.filterFrame.width;
  13509. destinationFrame.height = filterTexture.filterFrame.height;
  13510. renderTextureSystem.bind(filterTexture, filterTexture.filterFrame, destinationFrame);
  13511. }
  13512. else if (filterTexture !== this.defaultFilterStack[this.defaultFilterStack.length - 1].renderTexture) {
  13513. renderTextureSystem.bind(filterTexture);
  13514. }
  13515. else {
  13516. // Restore binding for output render-target.
  13517. this.renderer.renderTexture.bind(filterTexture, this.activeState.bindingSourceFrame, this.activeState.bindingDestinationFrame);
  13518. }
  13519. // Clear the texture in BLIT mode if blending is disabled or the forceClear flag is set. The blending
  13520. // is stored in the 0th bit of the state.
  13521. var autoClear = (stateSystem.stateId & 1) || this.forceClear;
  13522. if (clearMode === CLEAR_MODES.CLEAR
  13523. || (clearMode === CLEAR_MODES.BLIT && autoClear)) {
  13524. // Use framebuffer.clear because we want to clear the whole filter texture, not just the filtering
  13525. // area over which the shaders are run. This is because filters may sampling outside of it (e.g. blur)
  13526. // instead of clamping their arithmetic.
  13527. this.renderer.framebuffer.clear(0, 0, 0, 0);
  13528. }
  13529. };
  13530. /**
  13531. * Draws a filter using the default rendering process.
  13532. *
  13533. * This should be called only by {@link Filter#apply}.
  13534. * @param filter - The filter to draw.
  13535. * @param input - The input render target.
  13536. * @param output - The target to output to.
  13537. * @param clearMode - Should the output be cleared before rendering to it
  13538. */
  13539. FilterSystem.prototype.applyFilter = function (filter, input, output, clearMode) {
  13540. var renderer = this.renderer;
  13541. // Set state before binding, so bindAndClear gets the blend mode.
  13542. renderer.state.set(filter.state);
  13543. this.bindAndClear(output, clearMode);
  13544. // set the uniforms..
  13545. filter.uniforms.uSampler = input;
  13546. filter.uniforms.filterGlobals = this.globalUniforms;
  13547. // TODO make it so that the order of this does not matter..
  13548. // because it does at the moment cos of global uniforms.
  13549. // they need to get resynced
  13550. renderer.shader.bind(filter);
  13551. // check to see if the filter is a legacy one..
  13552. filter.legacy = !!filter.program.attributeData.aTextureCoord;
  13553. if (filter.legacy) {
  13554. this.quadUv.map(input._frame, input.filterFrame);
  13555. renderer.geometry.bind(this.quadUv);
  13556. renderer.geometry.draw(DRAW_MODES.TRIANGLES);
  13557. }
  13558. else {
  13559. renderer.geometry.bind(this.quad);
  13560. renderer.geometry.draw(DRAW_MODES.TRIANGLE_STRIP);
  13561. }
  13562. };
  13563. /**
  13564. * Multiply _input normalized coordinates_ to this matrix to get _sprite texture normalized coordinates_.
  13565. *
  13566. * Use `outputMatrix * vTextureCoord` in the shader.
  13567. * @param outputMatrix - The matrix to output to.
  13568. * @param {PIXI.Sprite} sprite - The sprite to map to.
  13569. * @returns The mapped matrix.
  13570. */
  13571. FilterSystem.prototype.calculateSpriteMatrix = function (outputMatrix, sprite) {
  13572. var _a = this.activeState, sourceFrame = _a.sourceFrame, destinationFrame = _a.destinationFrame;
  13573. var orig = sprite._texture.orig;
  13574. var mappedMatrix = outputMatrix.set(destinationFrame.width, 0, 0, destinationFrame.height, sourceFrame.x, sourceFrame.y);
  13575. var worldTransform = sprite.worldTransform.copyTo(Matrix.TEMP_MATRIX);
  13576. worldTransform.invert();
  13577. mappedMatrix.prepend(worldTransform);
  13578. mappedMatrix.scale(1.0 / orig.width, 1.0 / orig.height);
  13579. mappedMatrix.translate(sprite.anchor.x, sprite.anchor.y);
  13580. return mappedMatrix;
  13581. };
  13582. /** Destroys this Filter System. */
  13583. FilterSystem.prototype.destroy = function () {
  13584. this.renderer = null;
  13585. // Those textures has to be destroyed by RenderTextureSystem or FramebufferSystem
  13586. this.texturePool.clear(false);
  13587. };
  13588. /**
  13589. * Gets a Power-of-Two render texture or fullScreen texture
  13590. * @param minWidth - The minimum width of the render texture in real pixels.
  13591. * @param minHeight - The minimum height of the render texture in real pixels.
  13592. * @param resolution - The resolution of the render texture.
  13593. * @param multisample - Number of samples of the render texture.
  13594. * @returns - The new render texture.
  13595. */
  13596. FilterSystem.prototype.getOptimalFilterTexture = function (minWidth, minHeight, resolution, multisample) {
  13597. if (resolution === void 0) { resolution = 1; }
  13598. if (multisample === void 0) { multisample = MSAA_QUALITY.NONE; }
  13599. return this.texturePool.getOptimalTexture(minWidth, minHeight, resolution, multisample);
  13600. };
  13601. /**
  13602. * Gets extra render texture to use inside current filter
  13603. * To be compliant with older filters, you can use params in any order
  13604. * @param input - renderTexture from which size and resolution will be copied
  13605. * @param resolution - override resolution of the renderTexture
  13606. * @param multisample - number of samples of the renderTexture
  13607. */
  13608. FilterSystem.prototype.getFilterTexture = function (input, resolution, multisample) {
  13609. if (typeof input === 'number') {
  13610. var swap = input;
  13611. input = resolution;
  13612. resolution = swap;
  13613. }
  13614. input = input || this.activeState.renderTexture;
  13615. var filterTexture = this.texturePool.getOptimalTexture(input.width, input.height, resolution || input.resolution, multisample || MSAA_QUALITY.NONE);
  13616. filterTexture.filterFrame = input.filterFrame;
  13617. return filterTexture;
  13618. };
  13619. /**
  13620. * Frees a render texture back into the pool.
  13621. * @param renderTexture - The renderTarget to free
  13622. */
  13623. FilterSystem.prototype.returnFilterTexture = function (renderTexture) {
  13624. this.texturePool.returnTexture(renderTexture);
  13625. };
  13626. /** Empties the texture pool. */
  13627. FilterSystem.prototype.emptyPool = function () {
  13628. this.texturePool.clear(true);
  13629. };
  13630. /** Calls `texturePool.resize()`, affects fullScreen renderTextures. */
  13631. FilterSystem.prototype.resize = function () {
  13632. this.texturePool.setScreenSize(this.renderer.view);
  13633. };
  13634. /**
  13635. * @param matrix - first param
  13636. * @param rect - second param
  13637. */
  13638. FilterSystem.prototype.transformAABB = function (matrix, rect) {
  13639. var lt = tempPoints[0];
  13640. var lb = tempPoints[1];
  13641. var rt = tempPoints[2];
  13642. var rb = tempPoints[3];
  13643. lt.set(rect.left, rect.top);
  13644. lb.set(rect.left, rect.bottom);
  13645. rt.set(rect.right, rect.top);
  13646. rb.set(rect.right, rect.bottom);
  13647. matrix.apply(lt, lt);
  13648. matrix.apply(lb, lb);
  13649. matrix.apply(rt, rt);
  13650. matrix.apply(rb, rb);
  13651. var x0 = Math.min(lt.x, lb.x, rt.x, rb.x);
  13652. var y0 = Math.min(lt.y, lb.y, rt.y, rb.y);
  13653. var x1 = Math.max(lt.x, lb.x, rt.x, rb.x);
  13654. var y1 = Math.max(lt.y, lb.y, rt.y, rb.y);
  13655. rect.x = x0;
  13656. rect.y = y0;
  13657. rect.width = x1 - x0;
  13658. rect.height = y1 - y0;
  13659. };
  13660. FilterSystem.prototype.roundFrame = function (frame, resolution, bindingSourceFrame, bindingDestinationFrame, transform) {
  13661. if (frame.width <= 0 || frame.height <= 0 || bindingSourceFrame.width <= 0 || bindingSourceFrame.height <= 0) {
  13662. return;
  13663. }
  13664. if (transform) {
  13665. var a = transform.a, b = transform.b, c = transform.c, d = transform.d;
  13666. // Skip if skew/rotation present in matrix, except for multiple of 90° rotation. If rotation
  13667. // is a multiple of 90°, then either pair of (b,c) or (a,d) will be (0,0).
  13668. if ((Math.abs(b) > 1e-4 || Math.abs(c) > 1e-4)
  13669. && (Math.abs(a) > 1e-4 || Math.abs(d) > 1e-4)) {
  13670. return;
  13671. }
  13672. }
  13673. transform = transform ? tempMatrix$2.copyFrom(transform) : tempMatrix$2.identity();
  13674. // Get forward transform from world space to screen space
  13675. transform
  13676. .translate(-bindingSourceFrame.x, -bindingSourceFrame.y)
  13677. .scale(bindingDestinationFrame.width / bindingSourceFrame.width, bindingDestinationFrame.height / bindingSourceFrame.height)
  13678. .translate(bindingDestinationFrame.x, bindingDestinationFrame.y);
  13679. // Convert frame to screen space
  13680. this.transformAABB(transform, frame);
  13681. // Round frame in screen space
  13682. frame.ceil(resolution);
  13683. // Project back into world space.
  13684. this.transformAABB(transform.invert(), frame);
  13685. };
  13686. return FilterSystem;
  13687. }());
  13688. /**
  13689. * Base for a common object renderer that can be used as a
  13690. * system renderer plugin.
  13691. * @memberof PIXI
  13692. */
  13693. var ObjectRenderer = /** @class */ (function () {
  13694. /**
  13695. * @param renderer - The renderer this manager works for.
  13696. */
  13697. function ObjectRenderer(renderer) {
  13698. this.renderer = renderer;
  13699. }
  13700. /** Stub method that should be used to empty the current batch by rendering objects now. */
  13701. ObjectRenderer.prototype.flush = function () {
  13702. // flush!
  13703. };
  13704. /** Generic destruction method that frees all resources. This should be called by subclasses. */
  13705. ObjectRenderer.prototype.destroy = function () {
  13706. this.renderer = null;
  13707. };
  13708. /**
  13709. * Stub method that initializes any state required before
  13710. * rendering starts. It is different from the `prerender`
  13711. * signal, which occurs every frame, in that it is called
  13712. * whenever an object requests _this_ renderer specifically.
  13713. */
  13714. ObjectRenderer.prototype.start = function () {
  13715. // set the shader..
  13716. };
  13717. /** Stops the renderer. It should free up any state and become dormant. */
  13718. ObjectRenderer.prototype.stop = function () {
  13719. this.flush();
  13720. };
  13721. /**
  13722. * Keeps the object to render. It doesn't have to be
  13723. * rendered immediately.
  13724. * @param {PIXI.DisplayObject} _object - The object to render.
  13725. */
  13726. ObjectRenderer.prototype.render = function (_object) {
  13727. // render the object
  13728. };
  13729. return ObjectRenderer;
  13730. }());
  13731. /**
  13732. * System plugin to the renderer to manage batching.
  13733. * @memberof PIXI
  13734. */
  13735. var BatchSystem = /** @class */ (function () {
  13736. /**
  13737. * @param renderer - The renderer this System works for.
  13738. */
  13739. function BatchSystem(renderer) {
  13740. this.renderer = renderer;
  13741. this.emptyRenderer = new ObjectRenderer(renderer);
  13742. this.currentRenderer = this.emptyRenderer;
  13743. }
  13744. /**
  13745. * Changes the current renderer to the one given in parameter
  13746. * @param objectRenderer - The object renderer to use.
  13747. */
  13748. BatchSystem.prototype.setObjectRenderer = function (objectRenderer) {
  13749. if (this.currentRenderer === objectRenderer) {
  13750. return;
  13751. }
  13752. this.currentRenderer.stop();
  13753. this.currentRenderer = objectRenderer;
  13754. this.currentRenderer.start();
  13755. };
  13756. /**
  13757. * This should be called if you wish to do some custom rendering
  13758. * It will basically render anything that may be batched up such as sprites
  13759. */
  13760. BatchSystem.prototype.flush = function () {
  13761. this.setObjectRenderer(this.emptyRenderer);
  13762. };
  13763. /** Reset the system to an empty renderer */
  13764. BatchSystem.prototype.reset = function () {
  13765. this.setObjectRenderer(this.emptyRenderer);
  13766. };
  13767. /**
  13768. * Handy function for batch renderers: copies bound textures in first maxTextures locations to array
  13769. * sets actual _batchLocation for them
  13770. * @param arr - arr copy destination
  13771. * @param maxTextures - number of copied elements
  13772. */
  13773. BatchSystem.prototype.copyBoundTextures = function (arr, maxTextures) {
  13774. var boundTextures = this.renderer.texture.boundTextures;
  13775. for (var i = maxTextures - 1; i >= 0; --i) {
  13776. arr[i] = boundTextures[i] || null;
  13777. if (arr[i]) {
  13778. arr[i]._batchLocation = i;
  13779. }
  13780. }
  13781. };
  13782. /**
  13783. * Assigns batch locations to textures in array based on boundTextures state.
  13784. * All textures in texArray should have `_batchEnabled = _batchId`,
  13785. * and their count should be less than `maxTextures`.
  13786. * @param texArray - textures to bound
  13787. * @param boundTextures - current state of bound textures
  13788. * @param batchId - marker for _batchEnabled param of textures in texArray
  13789. * @param maxTextures - number of texture locations to manipulate
  13790. */
  13791. BatchSystem.prototype.boundArray = function (texArray, boundTextures, batchId, maxTextures) {
  13792. var elements = texArray.elements, ids = texArray.ids, count = texArray.count;
  13793. var j = 0;
  13794. for (var i = 0; i < count; i++) {
  13795. var tex = elements[i];
  13796. var loc = tex._batchLocation;
  13797. if (loc >= 0 && loc < maxTextures
  13798. && boundTextures[loc] === tex) {
  13799. ids[i] = loc;
  13800. continue;
  13801. }
  13802. while (j < maxTextures) {
  13803. var bound = boundTextures[j];
  13804. if (bound && bound._batchEnabled === batchId
  13805. && bound._batchLocation === j) {
  13806. j++;
  13807. continue;
  13808. }
  13809. ids[i] = j;
  13810. tex._batchLocation = j;
  13811. boundTextures[j] = tex;
  13812. break;
  13813. }
  13814. }
  13815. };
  13816. /**
  13817. * @ignore
  13818. */
  13819. BatchSystem.prototype.destroy = function () {
  13820. this.renderer = null;
  13821. };
  13822. return BatchSystem;
  13823. }());
  13824. var CONTEXT_UID_COUNTER = 0;
  13825. /**
  13826. * System plugin to the renderer to manage the context.
  13827. * @memberof PIXI
  13828. */
  13829. var ContextSystem = /** @class */ (function () {
  13830. /** @param renderer - The renderer this System works for. */
  13831. function ContextSystem(renderer) {
  13832. this.renderer = renderer;
  13833. this.webGLVersion = 1;
  13834. this.extensions = {};
  13835. this.supports = {
  13836. uint32Indices: false,
  13837. };
  13838. // Bind functions
  13839. this.handleContextLost = this.handleContextLost.bind(this);
  13840. this.handleContextRestored = this.handleContextRestored.bind(this);
  13841. renderer.view.addEventListener('webglcontextlost', this.handleContextLost, false);
  13842. renderer.view.addEventListener('webglcontextrestored', this.handleContextRestored, false);
  13843. }
  13844. Object.defineProperty(ContextSystem.prototype, "isLost", {
  13845. /**
  13846. * `true` if the context is lost
  13847. * @readonly
  13848. */
  13849. get: function () {
  13850. return (!this.gl || this.gl.isContextLost());
  13851. },
  13852. enumerable: false,
  13853. configurable: true
  13854. });
  13855. /**
  13856. * Handles the context change event.
  13857. * @param {WebGLRenderingContext} gl - New WebGL context.
  13858. */
  13859. ContextSystem.prototype.contextChange = function (gl) {
  13860. this.gl = gl;
  13861. this.renderer.gl = gl;
  13862. this.renderer.CONTEXT_UID = CONTEXT_UID_COUNTER++;
  13863. };
  13864. /**
  13865. * Initializes the context.
  13866. * @protected
  13867. * @param {WebGLRenderingContext} gl - WebGL context
  13868. */
  13869. ContextSystem.prototype.initFromContext = function (gl) {
  13870. this.gl = gl;
  13871. this.validateContext(gl);
  13872. this.renderer.gl = gl;
  13873. this.renderer.CONTEXT_UID = CONTEXT_UID_COUNTER++;
  13874. this.renderer.runners.contextChange.emit(gl);
  13875. };
  13876. /**
  13877. * Initialize from context options
  13878. * @protected
  13879. * @see https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/getContext
  13880. * @param {object} options - context attributes
  13881. */
  13882. ContextSystem.prototype.initFromOptions = function (options) {
  13883. var gl = this.createContext(this.renderer.view, options);
  13884. this.initFromContext(gl);
  13885. };
  13886. /**
  13887. * Helper class to create a WebGL Context
  13888. * @param canvas - the canvas element that we will get the context from
  13889. * @param options - An options object that gets passed in to the canvas element containing the
  13890. * context attributes
  13891. * @see https://developer.mozilla.org/en/docs/Web/API/HTMLCanvasElement/getContext
  13892. * @returns {WebGLRenderingContext} the WebGL context
  13893. */
  13894. ContextSystem.prototype.createContext = function (canvas, options) {
  13895. var gl;
  13896. if (settings.PREFER_ENV >= ENV.WEBGL2) {
  13897. gl = canvas.getContext('webgl2', options);
  13898. }
  13899. if (gl) {
  13900. this.webGLVersion = 2;
  13901. }
  13902. else {
  13903. this.webGLVersion = 1;
  13904. gl = canvas.getContext('webgl', options) || canvas.getContext('experimental-webgl', options);
  13905. if (!gl) {
  13906. // fail, not able to get a context
  13907. throw new Error('This browser does not support WebGL. Try using the canvas renderer');
  13908. }
  13909. }
  13910. this.gl = gl;
  13911. this.getExtensions();
  13912. return this.gl;
  13913. };
  13914. /** Auto-populate the {@link PIXI.ContextSystem.extensions extensions}. */
  13915. ContextSystem.prototype.getExtensions = function () {
  13916. // time to set up default extensions that Pixi uses.
  13917. var gl = this.gl;
  13918. var common = {
  13919. loseContext: gl.getExtension('WEBGL_lose_context'),
  13920. anisotropicFiltering: gl.getExtension('EXT_texture_filter_anisotropic'),
  13921. floatTextureLinear: gl.getExtension('OES_texture_float_linear'),
  13922. s3tc: gl.getExtension('WEBGL_compressed_texture_s3tc'),
  13923. s3tc_sRGB: gl.getExtension('WEBGL_compressed_texture_s3tc_srgb'),
  13924. etc: gl.getExtension('WEBGL_compressed_texture_etc'),
  13925. etc1: gl.getExtension('WEBGL_compressed_texture_etc1'),
  13926. pvrtc: gl.getExtension('WEBGL_compressed_texture_pvrtc')
  13927. || gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc'),
  13928. atc: gl.getExtension('WEBGL_compressed_texture_atc'),
  13929. astc: gl.getExtension('WEBGL_compressed_texture_astc')
  13930. };
  13931. if (this.webGLVersion === 1) {
  13932. Object.assign(this.extensions, common, {
  13933. drawBuffers: gl.getExtension('WEBGL_draw_buffers'),
  13934. depthTexture: gl.getExtension('WEBGL_depth_texture'),
  13935. vertexArrayObject: gl.getExtension('OES_vertex_array_object')
  13936. || gl.getExtension('MOZ_OES_vertex_array_object')
  13937. || gl.getExtension('WEBKIT_OES_vertex_array_object'),
  13938. uint32ElementIndex: gl.getExtension('OES_element_index_uint'),
  13939. // Floats and half-floats
  13940. floatTexture: gl.getExtension('OES_texture_float'),
  13941. floatTextureLinear: gl.getExtension('OES_texture_float_linear'),
  13942. textureHalfFloat: gl.getExtension('OES_texture_half_float'),
  13943. textureHalfFloatLinear: gl.getExtension('OES_texture_half_float_linear'),
  13944. });
  13945. }
  13946. else if (this.webGLVersion === 2) {
  13947. Object.assign(this.extensions, common, {
  13948. // Floats and half-floats
  13949. colorBufferFloat: gl.getExtension('EXT_color_buffer_float')
  13950. });
  13951. }
  13952. };
  13953. /**
  13954. * Handles a lost webgl context
  13955. * @param {WebGLContextEvent} event - The context lost event.
  13956. */
  13957. ContextSystem.prototype.handleContextLost = function (event) {
  13958. var _this = this;
  13959. // Prevent default to be able to restore the context
  13960. event.preventDefault();
  13961. // Restore the context after this event has exited
  13962. setTimeout(function () {
  13963. if (_this.gl.isContextLost() && _this.extensions.loseContext) {
  13964. _this.extensions.loseContext.restoreContext();
  13965. }
  13966. }, 0);
  13967. };
  13968. /** Handles a restored webgl context. */
  13969. ContextSystem.prototype.handleContextRestored = function () {
  13970. this.renderer.runners.contextChange.emit(this.gl);
  13971. };
  13972. ContextSystem.prototype.destroy = function () {
  13973. var view = this.renderer.view;
  13974. this.renderer = null;
  13975. // remove listeners
  13976. view.removeEventListener('webglcontextlost', this.handleContextLost);
  13977. view.removeEventListener('webglcontextrestored', this.handleContextRestored);
  13978. this.gl.useProgram(null);
  13979. if (this.extensions.loseContext) {
  13980. this.extensions.loseContext.loseContext();
  13981. }
  13982. };
  13983. /** Handle the post-render runner event. */
  13984. ContextSystem.prototype.postrender = function () {
  13985. if (this.renderer.renderingToScreen) {
  13986. this.gl.flush();
  13987. }
  13988. };
  13989. /**
  13990. * Validate context.
  13991. * @param {WebGLRenderingContext} gl - Render context.
  13992. */
  13993. ContextSystem.prototype.validateContext = function (gl) {
  13994. var attributes = gl.getContextAttributes();
  13995. var isWebGl2 = 'WebGL2RenderingContext' in globalThis && gl instanceof globalThis.WebGL2RenderingContext;
  13996. if (isWebGl2) {
  13997. this.webGLVersion = 2;
  13998. }
  13999. // this is going to be fairly simple for now.. but at least we have room to grow!
  14000. if (attributes && !attributes.stencil) {
  14001. /* eslint-disable max-len, no-console */
  14002. console.warn('Provided WebGL context does not have a stencil buffer, masks may not render correctly');
  14003. /* eslint-enable max-len, no-console */
  14004. }
  14005. var hasuint32 = isWebGl2 || !!gl.getExtension('OES_element_index_uint');
  14006. this.supports.uint32Indices = hasuint32;
  14007. if (!hasuint32) {
  14008. /* eslint-disable max-len, no-console */
  14009. console.warn('Provided WebGL context does not support 32 index buffer, complex graphics may not render correctly');
  14010. /* eslint-enable max-len, no-console */
  14011. }
  14012. };
  14013. return ContextSystem;
  14014. }());
  14015. /**
  14016. * Internal framebuffer for WebGL context.
  14017. * @memberof PIXI
  14018. */
  14019. var GLFramebuffer = /** @class */ (function () {
  14020. function GLFramebuffer(framebuffer) {
  14021. this.framebuffer = framebuffer;
  14022. this.stencil = null;
  14023. this.dirtyId = -1;
  14024. this.dirtyFormat = -1;
  14025. this.dirtySize = -1;
  14026. this.multisample = MSAA_QUALITY.NONE;
  14027. this.msaaBuffer = null;
  14028. this.blitFramebuffer = null;
  14029. this.mipLevel = 0;
  14030. }
  14031. return GLFramebuffer;
  14032. }());
  14033. var tempRectangle = new Rectangle();
  14034. /**
  14035. * System plugin to the renderer to manage framebuffers.
  14036. * @memberof PIXI
  14037. */
  14038. var FramebufferSystem = /** @class */ (function () {
  14039. /**
  14040. * @param renderer - The renderer this System works for.
  14041. */
  14042. function FramebufferSystem(renderer) {
  14043. this.renderer = renderer;
  14044. this.managedFramebuffers = [];
  14045. this.unknownFramebuffer = new Framebuffer(10, 10);
  14046. this.msaaSamples = null;
  14047. }
  14048. /** Sets up the renderer context and necessary buffers. */
  14049. FramebufferSystem.prototype.contextChange = function () {
  14050. this.disposeAll(true);
  14051. var gl = this.gl = this.renderer.gl;
  14052. this.CONTEXT_UID = this.renderer.CONTEXT_UID;
  14053. this.current = this.unknownFramebuffer;
  14054. this.viewport = new Rectangle();
  14055. this.hasMRT = true;
  14056. this.writeDepthTexture = true;
  14057. // webgl2
  14058. if (this.renderer.context.webGLVersion === 1) {
  14059. // webgl 1!
  14060. var nativeDrawBuffersExtension_1 = this.renderer.context.extensions.drawBuffers;
  14061. var nativeDepthTextureExtension = this.renderer.context.extensions.depthTexture;
  14062. if (settings.PREFER_ENV === ENV.WEBGL_LEGACY) {
  14063. nativeDrawBuffersExtension_1 = null;
  14064. nativeDepthTextureExtension = null;
  14065. }
  14066. if (nativeDrawBuffersExtension_1) {
  14067. gl.drawBuffers = function (activeTextures) {
  14068. return nativeDrawBuffersExtension_1.drawBuffersWEBGL(activeTextures);
  14069. };
  14070. }
  14071. else {
  14072. this.hasMRT = false;
  14073. gl.drawBuffers = function () {
  14074. // empty
  14075. };
  14076. }
  14077. if (!nativeDepthTextureExtension) {
  14078. this.writeDepthTexture = false;
  14079. }
  14080. }
  14081. else {
  14082. // WebGL2
  14083. // cache possible MSAA samples
  14084. this.msaaSamples = gl.getInternalformatParameter(gl.RENDERBUFFER, gl.RGBA8, gl.SAMPLES);
  14085. }
  14086. };
  14087. /**
  14088. * Bind a framebuffer.
  14089. * @param framebuffer
  14090. * @param frame - frame, default is framebuffer size
  14091. * @param mipLevel - optional mip level to set on the framebuffer - defaults to 0
  14092. */
  14093. FramebufferSystem.prototype.bind = function (framebuffer, frame, mipLevel) {
  14094. if (mipLevel === void 0) { mipLevel = 0; }
  14095. var gl = this.gl;
  14096. if (framebuffer) {
  14097. // TODO caching layer!
  14098. var fbo = framebuffer.glFramebuffers[this.CONTEXT_UID] || this.initFramebuffer(framebuffer);
  14099. if (this.current !== framebuffer) {
  14100. this.current = framebuffer;
  14101. gl.bindFramebuffer(gl.FRAMEBUFFER, fbo.framebuffer);
  14102. }
  14103. // make sure all textures are unbound..
  14104. if (fbo.mipLevel !== mipLevel) {
  14105. framebuffer.dirtyId++;
  14106. framebuffer.dirtyFormat++;
  14107. fbo.mipLevel = mipLevel;
  14108. }
  14109. // now check for updates...
  14110. if (fbo.dirtyId !== framebuffer.dirtyId) {
  14111. fbo.dirtyId = framebuffer.dirtyId;
  14112. if (fbo.dirtyFormat !== framebuffer.dirtyFormat) {
  14113. fbo.dirtyFormat = framebuffer.dirtyFormat;
  14114. fbo.dirtySize = framebuffer.dirtySize;
  14115. this.updateFramebuffer(framebuffer, mipLevel);
  14116. }
  14117. else if (fbo.dirtySize !== framebuffer.dirtySize) {
  14118. fbo.dirtySize = framebuffer.dirtySize;
  14119. this.resizeFramebuffer(framebuffer);
  14120. }
  14121. }
  14122. for (var i = 0; i < framebuffer.colorTextures.length; i++) {
  14123. var tex = framebuffer.colorTextures[i];
  14124. this.renderer.texture.unbind(tex.parentTextureArray || tex);
  14125. }
  14126. if (framebuffer.depthTexture) {
  14127. this.renderer.texture.unbind(framebuffer.depthTexture);
  14128. }
  14129. if (frame) {
  14130. var mipWidth = (frame.width >> mipLevel);
  14131. var mipHeight = (frame.height >> mipLevel);
  14132. var scale = mipWidth / frame.width;
  14133. this.setViewport(frame.x * scale, frame.y * scale, mipWidth, mipHeight);
  14134. }
  14135. else {
  14136. var mipWidth = (framebuffer.width >> mipLevel);
  14137. var mipHeight = (framebuffer.height >> mipLevel);
  14138. this.setViewport(0, 0, mipWidth, mipHeight);
  14139. }
  14140. }
  14141. else {
  14142. if (this.current) {
  14143. this.current = null;
  14144. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  14145. }
  14146. if (frame) {
  14147. this.setViewport(frame.x, frame.y, frame.width, frame.height);
  14148. }
  14149. else {
  14150. this.setViewport(0, 0, this.renderer.width, this.renderer.height);
  14151. }
  14152. }
  14153. };
  14154. /**
  14155. * Set the WebGLRenderingContext's viewport.
  14156. * @param x - X position of viewport
  14157. * @param y - Y position of viewport
  14158. * @param width - Width of viewport
  14159. * @param height - Height of viewport
  14160. */
  14161. FramebufferSystem.prototype.setViewport = function (x, y, width, height) {
  14162. var v = this.viewport;
  14163. x = Math.round(x);
  14164. y = Math.round(y);
  14165. width = Math.round(width);
  14166. height = Math.round(height);
  14167. if (v.width !== width || v.height !== height || v.x !== x || v.y !== y) {
  14168. v.x = x;
  14169. v.y = y;
  14170. v.width = width;
  14171. v.height = height;
  14172. this.gl.viewport(x, y, width, height);
  14173. }
  14174. };
  14175. Object.defineProperty(FramebufferSystem.prototype, "size", {
  14176. /**
  14177. * Get the size of the current width and height. Returns object with `width` and `height` values.
  14178. * @readonly
  14179. */
  14180. get: function () {
  14181. if (this.current) {
  14182. // TODO store temp
  14183. return { x: 0, y: 0, width: this.current.width, height: this.current.height };
  14184. }
  14185. return { x: 0, y: 0, width: this.renderer.width, height: this.renderer.height };
  14186. },
  14187. enumerable: false,
  14188. configurable: true
  14189. });
  14190. /**
  14191. * Clear the color of the context
  14192. * @param r - Red value from 0 to 1
  14193. * @param g - Green value from 0 to 1
  14194. * @param b - Blue value from 0 to 1
  14195. * @param a - Alpha value from 0 to 1
  14196. * @param {PIXI.BUFFER_BITS} [mask=BUFFER_BITS.COLOR | BUFFER_BITS.DEPTH] - Bitwise OR of masks
  14197. * that indicate the buffers to be cleared, by default COLOR and DEPTH buffers.
  14198. */
  14199. FramebufferSystem.prototype.clear = function (r, g, b, a, mask) {
  14200. if (mask === void 0) { mask = BUFFER_BITS.COLOR | BUFFER_BITS.DEPTH; }
  14201. var gl = this.gl;
  14202. // TODO clear color can be set only one right?
  14203. gl.clearColor(r, g, b, a);
  14204. gl.clear(mask);
  14205. };
  14206. /**
  14207. * Initialize framebuffer for this context
  14208. * @protected
  14209. * @param framebuffer
  14210. * @returns - created GLFramebuffer
  14211. */
  14212. FramebufferSystem.prototype.initFramebuffer = function (framebuffer) {
  14213. var gl = this.gl;
  14214. var fbo = new GLFramebuffer(gl.createFramebuffer());
  14215. fbo.multisample = this.detectSamples(framebuffer.multisample);
  14216. framebuffer.glFramebuffers[this.CONTEXT_UID] = fbo;
  14217. this.managedFramebuffers.push(framebuffer);
  14218. framebuffer.disposeRunner.add(this);
  14219. return fbo;
  14220. };
  14221. /**
  14222. * Resize the framebuffer
  14223. * @param framebuffer
  14224. * @protected
  14225. */
  14226. FramebufferSystem.prototype.resizeFramebuffer = function (framebuffer) {
  14227. var gl = this.gl;
  14228. var fbo = framebuffer.glFramebuffers[this.CONTEXT_UID];
  14229. if (fbo.msaaBuffer) {
  14230. gl.bindRenderbuffer(gl.RENDERBUFFER, fbo.msaaBuffer);
  14231. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, fbo.multisample, gl.RGBA8, framebuffer.width, framebuffer.height);
  14232. }
  14233. if (fbo.stencil) {
  14234. gl.bindRenderbuffer(gl.RENDERBUFFER, fbo.stencil);
  14235. if (fbo.msaaBuffer) {
  14236. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, fbo.multisample, gl.DEPTH24_STENCIL8, framebuffer.width, framebuffer.height);
  14237. }
  14238. else {
  14239. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width, framebuffer.height);
  14240. }
  14241. }
  14242. var colorTextures = framebuffer.colorTextures;
  14243. var count = colorTextures.length;
  14244. if (!gl.drawBuffers) {
  14245. count = Math.min(count, 1);
  14246. }
  14247. for (var i = 0; i < count; i++) {
  14248. var texture = colorTextures[i];
  14249. var parentTexture = texture.parentTextureArray || texture;
  14250. this.renderer.texture.bind(parentTexture, 0);
  14251. }
  14252. if (framebuffer.depthTexture && this.writeDepthTexture) {
  14253. this.renderer.texture.bind(framebuffer.depthTexture, 0);
  14254. }
  14255. };
  14256. /**
  14257. * Update the framebuffer
  14258. * @param framebuffer
  14259. * @param mipLevel
  14260. * @protected
  14261. */
  14262. FramebufferSystem.prototype.updateFramebuffer = function (framebuffer, mipLevel) {
  14263. var gl = this.gl;
  14264. var fbo = framebuffer.glFramebuffers[this.CONTEXT_UID];
  14265. // bind the color texture
  14266. var colorTextures = framebuffer.colorTextures;
  14267. var count = colorTextures.length;
  14268. if (!gl.drawBuffers) {
  14269. count = Math.min(count, 1);
  14270. }
  14271. if (fbo.multisample > 1 && this.canMultisampleFramebuffer(framebuffer)) {
  14272. fbo.msaaBuffer = fbo.msaaBuffer || gl.createRenderbuffer();
  14273. gl.bindRenderbuffer(gl.RENDERBUFFER, fbo.msaaBuffer);
  14274. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, fbo.multisample, gl.RGBA8, framebuffer.width, framebuffer.height);
  14275. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, fbo.msaaBuffer);
  14276. }
  14277. else if (fbo.msaaBuffer) {
  14278. gl.deleteRenderbuffer(fbo.msaaBuffer);
  14279. fbo.msaaBuffer = null;
  14280. if (fbo.blitFramebuffer) {
  14281. fbo.blitFramebuffer.dispose();
  14282. fbo.blitFramebuffer = null;
  14283. }
  14284. }
  14285. var activeTextures = [];
  14286. for (var i = 0; i < count; i++) {
  14287. var texture = colorTextures[i];
  14288. var parentTexture = texture.parentTextureArray || texture;
  14289. this.renderer.texture.bind(parentTexture, 0);
  14290. if (i === 0 && fbo.msaaBuffer) {
  14291. continue;
  14292. }
  14293. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0 + i, texture.target, parentTexture._glTextures[this.CONTEXT_UID].texture, mipLevel);
  14294. activeTextures.push(gl.COLOR_ATTACHMENT0 + i);
  14295. }
  14296. if (activeTextures.length > 1) {
  14297. gl.drawBuffers(activeTextures);
  14298. }
  14299. if (framebuffer.depthTexture) {
  14300. var writeDepthTexture = this.writeDepthTexture;
  14301. if (writeDepthTexture) {
  14302. var depthTexture = framebuffer.depthTexture;
  14303. this.renderer.texture.bind(depthTexture, 0);
  14304. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._glTextures[this.CONTEXT_UID].texture, mipLevel);
  14305. }
  14306. }
  14307. if ((framebuffer.stencil || framebuffer.depth) && !(framebuffer.depthTexture && this.writeDepthTexture)) {
  14308. fbo.stencil = fbo.stencil || gl.createRenderbuffer();
  14309. gl.bindRenderbuffer(gl.RENDERBUFFER, fbo.stencil);
  14310. if (fbo.msaaBuffer) {
  14311. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, fbo.multisample, gl.DEPTH24_STENCIL8, framebuffer.width, framebuffer.height);
  14312. }
  14313. else {
  14314. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width, framebuffer.height);
  14315. }
  14316. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, fbo.stencil);
  14317. }
  14318. else if (fbo.stencil) {
  14319. gl.deleteRenderbuffer(fbo.stencil);
  14320. fbo.stencil = null;
  14321. }
  14322. };
  14323. /**
  14324. * Returns true if the frame buffer can be multisampled.
  14325. * @param framebuffer
  14326. */
  14327. FramebufferSystem.prototype.canMultisampleFramebuffer = function (framebuffer) {
  14328. return this.renderer.context.webGLVersion !== 1
  14329. && framebuffer.colorTextures.length <= 1 && !framebuffer.depthTexture;
  14330. };
  14331. /**
  14332. * Detects number of samples that is not more than a param but as close to it as possible
  14333. * @param samples - number of samples
  14334. * @returns - recommended number of samples
  14335. */
  14336. FramebufferSystem.prototype.detectSamples = function (samples) {
  14337. var msaaSamples = this.msaaSamples;
  14338. var res = MSAA_QUALITY.NONE;
  14339. if (samples <= 1 || msaaSamples === null) {
  14340. return res;
  14341. }
  14342. for (var i = 0; i < msaaSamples.length; i++) {
  14343. if (msaaSamples[i] <= samples) {
  14344. res = msaaSamples[i];
  14345. break;
  14346. }
  14347. }
  14348. if (res === 1) {
  14349. res = MSAA_QUALITY.NONE;
  14350. }
  14351. return res;
  14352. };
  14353. /**
  14354. * Only works with WebGL2
  14355. *
  14356. * blits framebuffer to another of the same or bigger size
  14357. * after that target framebuffer is bound
  14358. *
  14359. * Fails with WebGL warning if blits multisample framebuffer to different size
  14360. * @param framebuffer - by default it blits "into itself", from renderBuffer to texture.
  14361. * @param sourcePixels - source rectangle in pixels
  14362. * @param destPixels - dest rectangle in pixels, assumed to be the same as sourcePixels
  14363. */
  14364. FramebufferSystem.prototype.blit = function (framebuffer, sourcePixels, destPixels) {
  14365. var _a = this, current = _a.current, renderer = _a.renderer, gl = _a.gl, CONTEXT_UID = _a.CONTEXT_UID;
  14366. if (renderer.context.webGLVersion !== 2) {
  14367. return;
  14368. }
  14369. if (!current) {
  14370. return;
  14371. }
  14372. var fbo = current.glFramebuffers[CONTEXT_UID];
  14373. if (!fbo) {
  14374. return;
  14375. }
  14376. if (!framebuffer) {
  14377. if (!fbo.msaaBuffer) {
  14378. return;
  14379. }
  14380. var colorTexture = current.colorTextures[0];
  14381. if (!colorTexture) {
  14382. return;
  14383. }
  14384. if (!fbo.blitFramebuffer) {
  14385. fbo.blitFramebuffer = new Framebuffer(current.width, current.height);
  14386. fbo.blitFramebuffer.addColorTexture(0, colorTexture);
  14387. }
  14388. framebuffer = fbo.blitFramebuffer;
  14389. if (framebuffer.colorTextures[0] !== colorTexture) {
  14390. framebuffer.colorTextures[0] = colorTexture;
  14391. framebuffer.dirtyId++;
  14392. framebuffer.dirtyFormat++;
  14393. }
  14394. if (framebuffer.width !== current.width || framebuffer.height !== current.height) {
  14395. framebuffer.width = current.width;
  14396. framebuffer.height = current.height;
  14397. framebuffer.dirtyId++;
  14398. framebuffer.dirtySize++;
  14399. }
  14400. }
  14401. if (!sourcePixels) {
  14402. sourcePixels = tempRectangle;
  14403. sourcePixels.width = current.width;
  14404. sourcePixels.height = current.height;
  14405. }
  14406. if (!destPixels) {
  14407. destPixels = sourcePixels;
  14408. }
  14409. var sameSize = sourcePixels.width === destPixels.width && sourcePixels.height === destPixels.height;
  14410. this.bind(framebuffer);
  14411. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, fbo.framebuffer);
  14412. gl.blitFramebuffer(sourcePixels.left, sourcePixels.top, sourcePixels.right, sourcePixels.bottom, destPixels.left, destPixels.top, destPixels.right, destPixels.bottom, gl.COLOR_BUFFER_BIT, sameSize ? gl.NEAREST : gl.LINEAR);
  14413. };
  14414. /**
  14415. * Disposes framebuffer.
  14416. * @param framebuffer - framebuffer that has to be disposed of
  14417. * @param contextLost - If context was lost, we suppress all delete function calls
  14418. */
  14419. FramebufferSystem.prototype.disposeFramebuffer = function (framebuffer, contextLost) {
  14420. var fbo = framebuffer.glFramebuffers[this.CONTEXT_UID];
  14421. var gl = this.gl;
  14422. if (!fbo) {
  14423. return;
  14424. }
  14425. delete framebuffer.glFramebuffers[this.CONTEXT_UID];
  14426. var index = this.managedFramebuffers.indexOf(framebuffer);
  14427. if (index >= 0) {
  14428. this.managedFramebuffers.splice(index, 1);
  14429. }
  14430. framebuffer.disposeRunner.remove(this);
  14431. if (!contextLost) {
  14432. gl.deleteFramebuffer(fbo.framebuffer);
  14433. if (fbo.msaaBuffer) {
  14434. gl.deleteRenderbuffer(fbo.msaaBuffer);
  14435. }
  14436. if (fbo.stencil) {
  14437. gl.deleteRenderbuffer(fbo.stencil);
  14438. }
  14439. }
  14440. if (fbo.blitFramebuffer) {
  14441. fbo.blitFramebuffer.dispose();
  14442. }
  14443. };
  14444. /**
  14445. * Disposes all framebuffers, but not textures bound to them.
  14446. * @param [contextLost=false] - If context was lost, we suppress all delete function calls
  14447. */
  14448. FramebufferSystem.prototype.disposeAll = function (contextLost) {
  14449. var list = this.managedFramebuffers;
  14450. this.managedFramebuffers = [];
  14451. for (var i = 0; i < list.length; i++) {
  14452. this.disposeFramebuffer(list[i], contextLost);
  14453. }
  14454. };
  14455. /**
  14456. * Forcing creation of stencil buffer for current framebuffer, if it wasn't done before.
  14457. * Used by MaskSystem, when its time to use stencil mask for Graphics element.
  14458. *
  14459. * Its an alternative for public lazy `framebuffer.enableStencil`, in case we need stencil without rebind.
  14460. * @private
  14461. */
  14462. FramebufferSystem.prototype.forceStencil = function () {
  14463. var framebuffer = this.current;
  14464. if (!framebuffer) {
  14465. return;
  14466. }
  14467. var fbo = framebuffer.glFramebuffers[this.CONTEXT_UID];
  14468. if (!fbo || fbo.stencil) {
  14469. return;
  14470. }
  14471. framebuffer.stencil = true;
  14472. var w = framebuffer.width;
  14473. var h = framebuffer.height;
  14474. var gl = this.gl;
  14475. var stencil = gl.createRenderbuffer();
  14476. gl.bindRenderbuffer(gl.RENDERBUFFER, stencil);
  14477. if (fbo.msaaBuffer) {
  14478. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, fbo.multisample, gl.DEPTH24_STENCIL8, w, h);
  14479. }
  14480. else {
  14481. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, w, h);
  14482. }
  14483. fbo.stencil = stencil;
  14484. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, stencil);
  14485. };
  14486. /** Resets framebuffer stored state, binds screen framebuffer. Should be called before renderTexture reset(). */
  14487. FramebufferSystem.prototype.reset = function () {
  14488. this.current = this.unknownFramebuffer;
  14489. this.viewport = new Rectangle();
  14490. };
  14491. FramebufferSystem.prototype.destroy = function () {
  14492. this.renderer = null;
  14493. };
  14494. return FramebufferSystem;
  14495. }());
  14496. var byteSizeMap = { 5126: 4, 5123: 2, 5121: 1 };
  14497. /**
  14498. * System plugin to the renderer to manage geometry.
  14499. * @memberof PIXI
  14500. */
  14501. var GeometrySystem = /** @class */ (function () {
  14502. /** @param renderer - The renderer this System works for. */
  14503. function GeometrySystem(renderer) {
  14504. this.renderer = renderer;
  14505. this._activeGeometry = null;
  14506. this._activeVao = null;
  14507. this.hasVao = true;
  14508. this.hasInstance = true;
  14509. this.canUseUInt32ElementIndex = false;
  14510. this.managedGeometries = {};
  14511. }
  14512. /** Sets up the renderer context and necessary buffers. */
  14513. GeometrySystem.prototype.contextChange = function () {
  14514. this.disposeAll(true);
  14515. var gl = this.gl = this.renderer.gl;
  14516. var context = this.renderer.context;
  14517. this.CONTEXT_UID = this.renderer.CONTEXT_UID;
  14518. // webgl2
  14519. if (context.webGLVersion !== 2) {
  14520. // webgl 1!
  14521. var nativeVaoExtension_1 = this.renderer.context.extensions.vertexArrayObject;
  14522. if (settings.PREFER_ENV === ENV.WEBGL_LEGACY) {
  14523. nativeVaoExtension_1 = null;
  14524. }
  14525. if (nativeVaoExtension_1) {
  14526. gl.createVertexArray = function () {
  14527. return nativeVaoExtension_1.createVertexArrayOES();
  14528. };
  14529. gl.bindVertexArray = function (vao) {
  14530. return nativeVaoExtension_1.bindVertexArrayOES(vao);
  14531. };
  14532. gl.deleteVertexArray = function (vao) {
  14533. return nativeVaoExtension_1.deleteVertexArrayOES(vao);
  14534. };
  14535. }
  14536. else {
  14537. this.hasVao = false;
  14538. gl.createVertexArray = function () {
  14539. return null;
  14540. };
  14541. gl.bindVertexArray = function () {
  14542. return null;
  14543. };
  14544. gl.deleteVertexArray = function () {
  14545. return null;
  14546. };
  14547. }
  14548. }
  14549. if (context.webGLVersion !== 2) {
  14550. var instanceExt_1 = gl.getExtension('ANGLE_instanced_arrays');
  14551. if (instanceExt_1) {
  14552. gl.vertexAttribDivisor = function (a, b) {
  14553. return instanceExt_1.vertexAttribDivisorANGLE(a, b);
  14554. };
  14555. gl.drawElementsInstanced = function (a, b, c, d, e) {
  14556. return instanceExt_1.drawElementsInstancedANGLE(a, b, c, d, e);
  14557. };
  14558. gl.drawArraysInstanced = function (a, b, c, d) {
  14559. return instanceExt_1.drawArraysInstancedANGLE(a, b, c, d);
  14560. };
  14561. }
  14562. else {
  14563. this.hasInstance = false;
  14564. }
  14565. }
  14566. this.canUseUInt32ElementIndex = context.webGLVersion === 2 || !!context.extensions.uint32ElementIndex;
  14567. };
  14568. /**
  14569. * Binds geometry so that is can be drawn. Creating a Vao if required
  14570. * @param geometry - Instance of geometry to bind.
  14571. * @param shader - Instance of shader to use vao for.
  14572. */
  14573. GeometrySystem.prototype.bind = function (geometry, shader) {
  14574. shader = shader || this.renderer.shader.shader;
  14575. var gl = this.gl;
  14576. // not sure the best way to address this..
  14577. // currently different shaders require different VAOs for the same geometry
  14578. // Still mulling over the best way to solve this one..
  14579. // will likely need to modify the shader attribute locations at run time!
  14580. var vaos = geometry.glVertexArrayObjects[this.CONTEXT_UID];
  14581. var incRefCount = false;
  14582. if (!vaos) {
  14583. this.managedGeometries[geometry.id] = geometry;
  14584. geometry.disposeRunner.add(this);
  14585. geometry.glVertexArrayObjects[this.CONTEXT_UID] = vaos = {};
  14586. incRefCount = true;
  14587. }
  14588. var vao = vaos[shader.program.id] || this.initGeometryVao(geometry, shader, incRefCount);
  14589. this._activeGeometry = geometry;
  14590. if (this._activeVao !== vao) {
  14591. this._activeVao = vao;
  14592. if (this.hasVao) {
  14593. gl.bindVertexArray(vao);
  14594. }
  14595. else {
  14596. this.activateVao(geometry, shader.program);
  14597. }
  14598. }
  14599. // TODO - optimise later!
  14600. // don't need to loop through if nothing changed!
  14601. // maybe look to add an 'autoupdate' to geometry?
  14602. this.updateBuffers();
  14603. };
  14604. /** Reset and unbind any active VAO and geometry. */
  14605. GeometrySystem.prototype.reset = function () {
  14606. this.unbind();
  14607. };
  14608. /** Update buffers of the currently bound geometry. */
  14609. GeometrySystem.prototype.updateBuffers = function () {
  14610. var geometry = this._activeGeometry;
  14611. var bufferSystem = this.renderer.buffer;
  14612. for (var i = 0; i < geometry.buffers.length; i++) {
  14613. var buffer = geometry.buffers[i];
  14614. bufferSystem.update(buffer);
  14615. }
  14616. };
  14617. /**
  14618. * Check compatibility between a geometry and a program
  14619. * @param geometry - Geometry instance.
  14620. * @param program - Program instance.
  14621. */
  14622. GeometrySystem.prototype.checkCompatibility = function (geometry, program) {
  14623. // geometry must have at least all the attributes that the shader requires.
  14624. var geometryAttributes = geometry.attributes;
  14625. var shaderAttributes = program.attributeData;
  14626. for (var j in shaderAttributes) {
  14627. if (!geometryAttributes[j]) {
  14628. throw new Error("shader and geometry incompatible, geometry missing the \"" + j + "\" attribute");
  14629. }
  14630. }
  14631. };
  14632. /**
  14633. * Takes a geometry and program and generates a unique signature for them.
  14634. * @param geometry - To get signature from.
  14635. * @param program - To test geometry against.
  14636. * @returns - Unique signature of the geometry and program
  14637. */
  14638. GeometrySystem.prototype.getSignature = function (geometry, program) {
  14639. var attribs = geometry.attributes;
  14640. var shaderAttributes = program.attributeData;
  14641. var strings = ['g', geometry.id];
  14642. for (var i in attribs) {
  14643. if (shaderAttributes[i]) {
  14644. strings.push(i, shaderAttributes[i].location);
  14645. }
  14646. }
  14647. return strings.join('-');
  14648. };
  14649. /**
  14650. * Creates or gets Vao with the same structure as the geometry and stores it on the geometry.
  14651. * If vao is created, it is bound automatically. We use a shader to infer what and how to set up the
  14652. * attribute locations.
  14653. * @param geometry - Instance of geometry to to generate Vao for.
  14654. * @param shader - Instance of the shader.
  14655. * @param incRefCount - Increment refCount of all geometry buffers.
  14656. */
  14657. GeometrySystem.prototype.initGeometryVao = function (geometry, shader, incRefCount) {
  14658. if (incRefCount === void 0) { incRefCount = true; }
  14659. var gl = this.gl;
  14660. var CONTEXT_UID = this.CONTEXT_UID;
  14661. var bufferSystem = this.renderer.buffer;
  14662. var program = shader.program;
  14663. if (!program.glPrograms[CONTEXT_UID]) {
  14664. this.renderer.shader.generateProgram(shader);
  14665. }
  14666. this.checkCompatibility(geometry, program);
  14667. var signature = this.getSignature(geometry, program);
  14668. var vaoObjectHash = geometry.glVertexArrayObjects[this.CONTEXT_UID];
  14669. var vao = vaoObjectHash[signature];
  14670. if (vao) {
  14671. // this will give us easy access to the vao
  14672. vaoObjectHash[program.id] = vao;
  14673. return vao;
  14674. }
  14675. var buffers = geometry.buffers;
  14676. var attributes = geometry.attributes;
  14677. var tempStride = {};
  14678. var tempStart = {};
  14679. for (var j in buffers) {
  14680. tempStride[j] = 0;
  14681. tempStart[j] = 0;
  14682. }
  14683. for (var j in attributes) {
  14684. if (!attributes[j].size && program.attributeData[j]) {
  14685. attributes[j].size = program.attributeData[j].size;
  14686. }
  14687. else if (!attributes[j].size) {
  14688. console.warn("PIXI Geometry attribute '" + j + "' size cannot be determined (likely the bound shader does not have the attribute)"); // eslint-disable-line
  14689. }
  14690. tempStride[attributes[j].buffer] += attributes[j].size * byteSizeMap[attributes[j].type];
  14691. }
  14692. for (var j in attributes) {
  14693. var attribute = attributes[j];
  14694. var attribSize = attribute.size;
  14695. if (attribute.stride === undefined) {
  14696. if (tempStride[attribute.buffer] === attribSize * byteSizeMap[attribute.type]) {
  14697. attribute.stride = 0;
  14698. }
  14699. else {
  14700. attribute.stride = tempStride[attribute.buffer];
  14701. }
  14702. }
  14703. if (attribute.start === undefined) {
  14704. attribute.start = tempStart[attribute.buffer];
  14705. tempStart[attribute.buffer] += attribSize * byteSizeMap[attribute.type];
  14706. }
  14707. }
  14708. vao = gl.createVertexArray();
  14709. gl.bindVertexArray(vao);
  14710. // first update - and create the buffers!
  14711. // only create a gl buffer if it actually gets
  14712. for (var i = 0; i < buffers.length; i++) {
  14713. var buffer = buffers[i];
  14714. bufferSystem.bind(buffer);
  14715. if (incRefCount) {
  14716. buffer._glBuffers[CONTEXT_UID].refCount++;
  14717. }
  14718. }
  14719. // TODO - maybe make this a data object?
  14720. // lets wait to see if we need to first!
  14721. this.activateVao(geometry, program);
  14722. this._activeVao = vao;
  14723. // add it to the cache!
  14724. vaoObjectHash[program.id] = vao;
  14725. vaoObjectHash[signature] = vao;
  14726. return vao;
  14727. };
  14728. /**
  14729. * Disposes geometry.
  14730. * @param geometry - Geometry with buffers. Only VAO will be disposed
  14731. * @param [contextLost=false] - If context was lost, we suppress deleteVertexArray
  14732. */
  14733. GeometrySystem.prototype.disposeGeometry = function (geometry, contextLost) {
  14734. var _a;
  14735. if (!this.managedGeometries[geometry.id]) {
  14736. return;
  14737. }
  14738. delete this.managedGeometries[geometry.id];
  14739. var vaos = geometry.glVertexArrayObjects[this.CONTEXT_UID];
  14740. var gl = this.gl;
  14741. var buffers = geometry.buffers;
  14742. var bufferSystem = (_a = this.renderer) === null || _a === void 0 ? void 0 : _a.buffer;
  14743. geometry.disposeRunner.remove(this);
  14744. if (!vaos) {
  14745. return;
  14746. }
  14747. // bufferSystem may have already been destroyed..
  14748. // if this is the case, there is no need to destroy the geometry buffers...
  14749. // they already have been!
  14750. if (bufferSystem) {
  14751. for (var i = 0; i < buffers.length; i++) {
  14752. var buf = buffers[i]._glBuffers[this.CONTEXT_UID];
  14753. // my be null as context may have changed right before the dispose is called
  14754. if (buf) {
  14755. buf.refCount--;
  14756. if (buf.refCount === 0 && !contextLost) {
  14757. bufferSystem.dispose(buffers[i], contextLost);
  14758. }
  14759. }
  14760. }
  14761. }
  14762. if (!contextLost) {
  14763. for (var vaoId in vaos) {
  14764. // delete only signatures, everything else are copies
  14765. if (vaoId[0] === 'g') {
  14766. var vao = vaos[vaoId];
  14767. if (this._activeVao === vao) {
  14768. this.unbind();
  14769. }
  14770. gl.deleteVertexArray(vao);
  14771. }
  14772. }
  14773. }
  14774. delete geometry.glVertexArrayObjects[this.CONTEXT_UID];
  14775. };
  14776. /**
  14777. * Dispose all WebGL resources of all managed geometries.
  14778. * @param [contextLost=false] - If context was lost, we suppress `gl.delete` calls
  14779. */
  14780. GeometrySystem.prototype.disposeAll = function (contextLost) {
  14781. var all = Object.keys(this.managedGeometries);
  14782. for (var i = 0; i < all.length; i++) {
  14783. this.disposeGeometry(this.managedGeometries[all[i]], contextLost);
  14784. }
  14785. };
  14786. /**
  14787. * Activate vertex array object.
  14788. * @param geometry - Geometry instance.
  14789. * @param program - Shader program instance.
  14790. */
  14791. GeometrySystem.prototype.activateVao = function (geometry, program) {
  14792. var gl = this.gl;
  14793. var CONTEXT_UID = this.CONTEXT_UID;
  14794. var bufferSystem = this.renderer.buffer;
  14795. var buffers = geometry.buffers;
  14796. var attributes = geometry.attributes;
  14797. if (geometry.indexBuffer) {
  14798. // first update the index buffer if we have one..
  14799. bufferSystem.bind(geometry.indexBuffer);
  14800. }
  14801. var lastBuffer = null;
  14802. // add a new one!
  14803. for (var j in attributes) {
  14804. var attribute = attributes[j];
  14805. var buffer = buffers[attribute.buffer];
  14806. var glBuffer = buffer._glBuffers[CONTEXT_UID];
  14807. if (program.attributeData[j]) {
  14808. if (lastBuffer !== glBuffer) {
  14809. bufferSystem.bind(buffer);
  14810. lastBuffer = glBuffer;
  14811. }
  14812. var location = program.attributeData[j].location;
  14813. // TODO introduce state again
  14814. // we can optimise this for older devices that have no VAOs
  14815. gl.enableVertexAttribArray(location);
  14816. gl.vertexAttribPointer(location, attribute.size, attribute.type || gl.FLOAT, attribute.normalized, attribute.stride, attribute.start);
  14817. if (attribute.instance) {
  14818. // TODO calculate instance count based of this...
  14819. if (this.hasInstance) {
  14820. gl.vertexAttribDivisor(location, 1);
  14821. }
  14822. else {
  14823. throw new Error('geometry error, GPU Instancing is not supported on this device');
  14824. }
  14825. }
  14826. }
  14827. }
  14828. };
  14829. /**
  14830. * Draws the currently bound geometry.
  14831. * @param type - The type primitive to render.
  14832. * @param size - The number of elements to be rendered. If not specified, all vertices after the
  14833. * starting vertex will be drawn.
  14834. * @param start - The starting vertex in the geometry to start drawing from. If not specified,
  14835. * drawing will start from the first vertex.
  14836. * @param instanceCount - The number of instances of the set of elements to execute. If not specified,
  14837. * all instances will be drawn.
  14838. */
  14839. GeometrySystem.prototype.draw = function (type, size, start, instanceCount) {
  14840. var gl = this.gl;
  14841. var geometry = this._activeGeometry;
  14842. // TODO.. this should not change so maybe cache the function?
  14843. if (geometry.indexBuffer) {
  14844. var byteSize = geometry.indexBuffer.data.BYTES_PER_ELEMENT;
  14845. var glType = byteSize === 2 ? gl.UNSIGNED_SHORT : gl.UNSIGNED_INT;
  14846. if (byteSize === 2 || (byteSize === 4 && this.canUseUInt32ElementIndex)) {
  14847. if (geometry.instanced) {
  14848. /* eslint-disable max-len */
  14849. gl.drawElementsInstanced(type, size || geometry.indexBuffer.data.length, glType, (start || 0) * byteSize, instanceCount || 1);
  14850. /* eslint-enable max-len */
  14851. }
  14852. else {
  14853. /* eslint-disable max-len */
  14854. gl.drawElements(type, size || geometry.indexBuffer.data.length, glType, (start || 0) * byteSize);
  14855. /* eslint-enable max-len */
  14856. }
  14857. }
  14858. else {
  14859. console.warn('unsupported index buffer type: uint32');
  14860. }
  14861. }
  14862. else if (geometry.instanced) {
  14863. // TODO need a better way to calculate size..
  14864. gl.drawArraysInstanced(type, start, size || geometry.getSize(), instanceCount || 1);
  14865. }
  14866. else {
  14867. gl.drawArrays(type, start, size || geometry.getSize());
  14868. }
  14869. return this;
  14870. };
  14871. /** Unbind/reset everything. */
  14872. GeometrySystem.prototype.unbind = function () {
  14873. this.gl.bindVertexArray(null);
  14874. this._activeVao = null;
  14875. this._activeGeometry = null;
  14876. };
  14877. GeometrySystem.prototype.destroy = function () {
  14878. this.renderer = null;
  14879. };
  14880. return GeometrySystem;
  14881. }());
  14882. /**
  14883. * Component for masked elements.
  14884. *
  14885. * Holds mask mode and temporary data about current mask.
  14886. * @memberof PIXI
  14887. */
  14888. var MaskData = /** @class */ (function () {
  14889. /**
  14890. * Create MaskData
  14891. * @param {PIXI.DisplayObject} [maskObject=null] - object that describes the mask
  14892. */
  14893. function MaskData(maskObject) {
  14894. if (maskObject === void 0) { maskObject = null; }
  14895. this.type = MASK_TYPES.NONE;
  14896. this.autoDetect = true;
  14897. this.maskObject = maskObject || null;
  14898. this.pooled = false;
  14899. this.isMaskData = true;
  14900. this.resolution = null;
  14901. this.multisample = settings.FILTER_MULTISAMPLE;
  14902. this.enabled = true;
  14903. this.colorMask = 0xf;
  14904. this._filters = null;
  14905. this._stencilCounter = 0;
  14906. this._scissorCounter = 0;
  14907. this._scissorRect = null;
  14908. this._scissorRectLocal = null;
  14909. this._colorMask = 0xf;
  14910. this._target = null;
  14911. }
  14912. Object.defineProperty(MaskData.prototype, "filter", {
  14913. /**
  14914. * The sprite mask filter.
  14915. * If set to `null`, the default sprite mask filter is used.
  14916. * @default null
  14917. */
  14918. get: function () {
  14919. return this._filters ? this._filters[0] : null;
  14920. },
  14921. set: function (value) {
  14922. if (value) {
  14923. if (this._filters) {
  14924. this._filters[0] = value;
  14925. }
  14926. else {
  14927. this._filters = [value];
  14928. }
  14929. }
  14930. else {
  14931. this._filters = null;
  14932. }
  14933. },
  14934. enumerable: false,
  14935. configurable: true
  14936. });
  14937. /** Resets the mask data after popMask(). */
  14938. MaskData.prototype.reset = function () {
  14939. if (this.pooled) {
  14940. this.maskObject = null;
  14941. this.type = MASK_TYPES.NONE;
  14942. this.autoDetect = true;
  14943. }
  14944. this._target = null;
  14945. this._scissorRectLocal = null;
  14946. };
  14947. /**
  14948. * Copies counters from maskData above, called from pushMask().
  14949. * @param maskAbove
  14950. */
  14951. MaskData.prototype.copyCountersOrReset = function (maskAbove) {
  14952. if (maskAbove) {
  14953. this._stencilCounter = maskAbove._stencilCounter;
  14954. this._scissorCounter = maskAbove._scissorCounter;
  14955. this._scissorRect = maskAbove._scissorRect;
  14956. }
  14957. else {
  14958. this._stencilCounter = 0;
  14959. this._scissorCounter = 0;
  14960. this._scissorRect = null;
  14961. }
  14962. };
  14963. return MaskData;
  14964. }());
  14965. /**
  14966. * @private
  14967. * @param {WebGLRenderingContext} gl - The current WebGL context {WebGLProgram}
  14968. * @param {number} type - the type, can be either VERTEX_SHADER or FRAGMENT_SHADER
  14969. * @param {string} src - The vertex shader source as an array of strings.
  14970. * @returns {WebGLShader} the shader
  14971. */
  14972. function compileShader(gl, type, src) {
  14973. var shader = gl.createShader(type);
  14974. gl.shaderSource(shader, src);
  14975. gl.compileShader(shader);
  14976. return shader;
  14977. }
  14978. /**
  14979. * will log a shader error highlighting the lines with the error
  14980. * also will add numbers along the side.
  14981. * @param gl - the WebGLContext
  14982. * @param shader - the shader to log errors for
  14983. */
  14984. function logPrettyShaderError(gl, shader) {
  14985. var shaderSrc = gl.getShaderSource(shader)
  14986. .split('\n')
  14987. .map(function (line, index) { return index + ": " + line; });
  14988. var shaderLog = gl.getShaderInfoLog(shader);
  14989. var splitShader = shaderLog.split('\n');
  14990. var dedupe = {};
  14991. var lineNumbers = splitShader.map(function (line) { return parseFloat(line.replace(/^ERROR\: 0\:([\d]+)\:.*$/, '$1')); })
  14992. .filter(function (n) {
  14993. if (n && !dedupe[n]) {
  14994. dedupe[n] = true;
  14995. return true;
  14996. }
  14997. return false;
  14998. });
  14999. var logArgs = [''];
  15000. lineNumbers.forEach(function (number) {
  15001. shaderSrc[number - 1] = "%c" + shaderSrc[number - 1] + "%c";
  15002. logArgs.push('background: #FF0000; color:#FFFFFF; font-size: 10px', 'font-size: 10px');
  15003. });
  15004. var fragmentSourceToLog = shaderSrc
  15005. .join('\n');
  15006. logArgs[0] = fragmentSourceToLog;
  15007. console.error(shaderLog);
  15008. // eslint-disable-next-line no-console
  15009. console.groupCollapsed('click to view full shader code');
  15010. console.warn.apply(console, logArgs);
  15011. // eslint-disable-next-line no-console
  15012. console.groupEnd();
  15013. }
  15014. /**
  15015. *
  15016. * logs out any program errors
  15017. * @param gl - The current WebGL context
  15018. * @param program - the WebGL program to display errors for
  15019. * @param vertexShader - the fragment WebGL shader program
  15020. * @param fragmentShader - the vertex WebGL shader program
  15021. */
  15022. function logProgramError(gl, program, vertexShader, fragmentShader) {
  15023. // if linking fails, then log and cleanup
  15024. if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
  15025. if (!gl.getShaderParameter(vertexShader, gl.COMPILE_STATUS)) {
  15026. logPrettyShaderError(gl, vertexShader);
  15027. }
  15028. if (!gl.getShaderParameter(fragmentShader, gl.COMPILE_STATUS)) {
  15029. logPrettyShaderError(gl, fragmentShader);
  15030. }
  15031. console.error('PixiJS Error: Could not initialize shader.');
  15032. // if there is a program info log, log it
  15033. if (gl.getProgramInfoLog(program) !== '') {
  15034. console.warn('PixiJS Warning: gl.getProgramInfoLog()', gl.getProgramInfoLog(program));
  15035. }
  15036. }
  15037. }
  15038. function booleanArray(size) {
  15039. var array = new Array(size);
  15040. for (var i = 0; i < array.length; i++) {
  15041. array[i] = false;
  15042. }
  15043. return array;
  15044. }
  15045. /**
  15046. * @method defaultValue
  15047. * @memberof PIXI.glCore.shader
  15048. * @param {string} type - Type of value
  15049. * @param {number} size
  15050. * @private
  15051. */
  15052. function defaultValue(type, size) {
  15053. switch (type) {
  15054. case 'float':
  15055. return 0;
  15056. case 'vec2':
  15057. return new Float32Array(2 * size);
  15058. case 'vec3':
  15059. return new Float32Array(3 * size);
  15060. case 'vec4':
  15061. return new Float32Array(4 * size);
  15062. case 'int':
  15063. case 'uint':
  15064. case 'sampler2D':
  15065. case 'sampler2DArray':
  15066. return 0;
  15067. case 'ivec2':
  15068. return new Int32Array(2 * size);
  15069. case 'ivec3':
  15070. return new Int32Array(3 * size);
  15071. case 'ivec4':
  15072. return new Int32Array(4 * size);
  15073. case 'uvec2':
  15074. return new Uint32Array(2 * size);
  15075. case 'uvec3':
  15076. return new Uint32Array(3 * size);
  15077. case 'uvec4':
  15078. return new Uint32Array(4 * size);
  15079. case 'bool':
  15080. return false;
  15081. case 'bvec2':
  15082. return booleanArray(2 * size);
  15083. case 'bvec3':
  15084. return booleanArray(3 * size);
  15085. case 'bvec4':
  15086. return booleanArray(4 * size);
  15087. case 'mat2':
  15088. return new Float32Array([1, 0,
  15089. 0, 1]);
  15090. case 'mat3':
  15091. return new Float32Array([1, 0, 0,
  15092. 0, 1, 0,
  15093. 0, 0, 1]);
  15094. case 'mat4':
  15095. return new Float32Array([1, 0, 0, 0,
  15096. 0, 1, 0, 0,
  15097. 0, 0, 1, 0,
  15098. 0, 0, 0, 1]);
  15099. }
  15100. return null;
  15101. }
  15102. var unknownContext = {};
  15103. var context = unknownContext;
  15104. /**
  15105. * returns a little WebGL context to use for program inspection.
  15106. * @static
  15107. * @private
  15108. * @returns {WebGLRenderingContext} a gl context to test with
  15109. */
  15110. function getTestContext() {
  15111. if (context === unknownContext || (context && context.isContextLost())) {
  15112. var canvas = settings.ADAPTER.createCanvas();
  15113. var gl = void 0;
  15114. if (settings.PREFER_ENV >= ENV.WEBGL2) {
  15115. gl = canvas.getContext('webgl2', {});
  15116. }
  15117. if (!gl) {
  15118. gl = (canvas.getContext('webgl', {})
  15119. || canvas.getContext('experimental-webgl', {}));
  15120. if (!gl) {
  15121. // fail, not able to get a context
  15122. gl = null;
  15123. }
  15124. else {
  15125. // for shader testing..
  15126. gl.getExtension('WEBGL_draw_buffers');
  15127. }
  15128. }
  15129. context = gl;
  15130. }
  15131. return context;
  15132. }
  15133. var maxFragmentPrecision;
  15134. function getMaxFragmentPrecision() {
  15135. if (!maxFragmentPrecision) {
  15136. maxFragmentPrecision = PRECISION.MEDIUM;
  15137. var gl = getTestContext();
  15138. if (gl) {
  15139. if (gl.getShaderPrecisionFormat) {
  15140. var shaderFragment = gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.HIGH_FLOAT);
  15141. maxFragmentPrecision = shaderFragment.precision ? PRECISION.HIGH : PRECISION.MEDIUM;
  15142. }
  15143. }
  15144. }
  15145. return maxFragmentPrecision;
  15146. }
  15147. /**
  15148. * Sets the float precision on the shader, ensuring the device supports the request precision.
  15149. * If the precision is already present, it just ensures that the device is able to handle it.
  15150. * @private
  15151. * @param {string} src - The shader source
  15152. * @param {PIXI.PRECISION} requestedPrecision - The request float precision of the shader.
  15153. * @param {PIXI.PRECISION} maxSupportedPrecision - The maximum precision the shader supports.
  15154. * @returns {string} modified shader source
  15155. */
  15156. function setPrecision(src, requestedPrecision, maxSupportedPrecision) {
  15157. if (src.substring(0, 9) !== 'precision') {
  15158. // no precision supplied, so PixiJS will add the requested level.
  15159. var precision = requestedPrecision;
  15160. // If highp is requested but not supported, downgrade precision to a level all devices support.
  15161. if (requestedPrecision === PRECISION.HIGH && maxSupportedPrecision !== PRECISION.HIGH) {
  15162. precision = PRECISION.MEDIUM;
  15163. }
  15164. return "precision " + precision + " float;\n" + src;
  15165. }
  15166. else if (maxSupportedPrecision !== PRECISION.HIGH && src.substring(0, 15) === 'precision highp') {
  15167. // precision was supplied, but at a level this device does not support, so downgrading to mediump.
  15168. return src.replace('precision highp', 'precision mediump');
  15169. }
  15170. return src;
  15171. }
  15172. var GLSL_TO_SIZE = {
  15173. float: 1,
  15174. vec2: 2,
  15175. vec3: 3,
  15176. vec4: 4,
  15177. int: 1,
  15178. ivec2: 2,
  15179. ivec3: 3,
  15180. ivec4: 4,
  15181. uint: 1,
  15182. uvec2: 2,
  15183. uvec3: 3,
  15184. uvec4: 4,
  15185. bool: 1,
  15186. bvec2: 2,
  15187. bvec3: 3,
  15188. bvec4: 4,
  15189. mat2: 4,
  15190. mat3: 9,
  15191. mat4: 16,
  15192. sampler2D: 1,
  15193. };
  15194. /**
  15195. * @private
  15196. * @method mapSize
  15197. * @memberof PIXI.glCore.shader
  15198. * @param {string} type
  15199. */
  15200. function mapSize(type) {
  15201. return GLSL_TO_SIZE[type];
  15202. }
  15203. var GL_TABLE = null;
  15204. var GL_TO_GLSL_TYPES = {
  15205. FLOAT: 'float',
  15206. FLOAT_VEC2: 'vec2',
  15207. FLOAT_VEC3: 'vec3',
  15208. FLOAT_VEC4: 'vec4',
  15209. INT: 'int',
  15210. INT_VEC2: 'ivec2',
  15211. INT_VEC3: 'ivec3',
  15212. INT_VEC4: 'ivec4',
  15213. UNSIGNED_INT: 'uint',
  15214. UNSIGNED_INT_VEC2: 'uvec2',
  15215. UNSIGNED_INT_VEC3: 'uvec3',
  15216. UNSIGNED_INT_VEC4: 'uvec4',
  15217. BOOL: 'bool',
  15218. BOOL_VEC2: 'bvec2',
  15219. BOOL_VEC3: 'bvec3',
  15220. BOOL_VEC4: 'bvec4',
  15221. FLOAT_MAT2: 'mat2',
  15222. FLOAT_MAT3: 'mat3',
  15223. FLOAT_MAT4: 'mat4',
  15224. SAMPLER_2D: 'sampler2D',
  15225. INT_SAMPLER_2D: 'sampler2D',
  15226. UNSIGNED_INT_SAMPLER_2D: 'sampler2D',
  15227. SAMPLER_CUBE: 'samplerCube',
  15228. INT_SAMPLER_CUBE: 'samplerCube',
  15229. UNSIGNED_INT_SAMPLER_CUBE: 'samplerCube',
  15230. SAMPLER_2D_ARRAY: 'sampler2DArray',
  15231. INT_SAMPLER_2D_ARRAY: 'sampler2DArray',
  15232. UNSIGNED_INT_SAMPLER_2D_ARRAY: 'sampler2DArray',
  15233. };
  15234. // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
  15235. function mapType(gl, type) {
  15236. if (!GL_TABLE) {
  15237. var typeNames = Object.keys(GL_TO_GLSL_TYPES);
  15238. GL_TABLE = {};
  15239. for (var i = 0; i < typeNames.length; ++i) {
  15240. var tn = typeNames[i];
  15241. GL_TABLE[gl[tn]] = GL_TO_GLSL_TYPES[tn];
  15242. }
  15243. }
  15244. return GL_TABLE[type];
  15245. }
  15246. /* eslint-disable @typescript-eslint/explicit-module-boundary-types */
  15247. // Parsers, each one of these will take a look at the type of shader property and uniform.
  15248. // if they pass the test function then the code function is called that returns a the shader upload code for that uniform.
  15249. // Shader upload code is automagically generated with these parsers.
  15250. // If no parser is valid then the default upload functions are used.
  15251. // exposing Parsers means that custom upload logic can be added to pixi's shaders.
  15252. // A good example would be a pixi rectangle can be directly set on a uniform.
  15253. // If the shader sees it it knows how to upload the rectangle structure as a vec4
  15254. // format is as follows:
  15255. //
  15256. // {
  15257. // test: (data, uniform) => {} <--- test is this code should be used for this uniform
  15258. // code: (name, uniform) => {} <--- returns the string of the piece of code that uploads the uniform
  15259. // codeUbo: (name, uniform) => {} <--- returns the string of the piece of code that uploads the
  15260. // uniform to a uniform buffer
  15261. // }
  15262. var uniformParsers = [
  15263. // a float cache layer
  15264. {
  15265. test: function (data) {
  15266. return data.type === 'float' && data.size === 1 && !data.isArray;
  15267. },
  15268. code: function (name) {
  15269. return "\n if(uv[\"" + name + "\"] !== ud[\"" + name + "\"].value)\n {\n ud[\"" + name + "\"].value = uv[\"" + name + "\"]\n gl.uniform1f(ud[\"" + name + "\"].location, uv[\"" + name + "\"])\n }\n ";
  15270. },
  15271. },
  15272. // handling samplers
  15273. {
  15274. test: function (data, uniform) {
  15275. // eslint-disable-next-line max-len,no-eq-null,eqeqeq
  15276. return (data.type === 'sampler2D' || data.type === 'samplerCube' || data.type === 'sampler2DArray') && data.size === 1 && !data.isArray && (uniform == null || uniform.castToBaseTexture !== undefined);
  15277. },
  15278. code: function (name) { return "t = syncData.textureCount++;\n\n renderer.texture.bind(uv[\"" + name + "\"], t);\n\n if(ud[\"" + name + "\"].value !== t)\n {\n ud[\"" + name + "\"].value = t;\n gl.uniform1i(ud[\"" + name + "\"].location, t);\n; // eslint-disable-line max-len\n }"; },
  15279. },
  15280. // uploading pixi matrix object to mat3
  15281. {
  15282. test: function (data, uniform) {
  15283. return data.type === 'mat3' && data.size === 1 && !data.isArray && uniform.a !== undefined;
  15284. },
  15285. code: function (name) {
  15286. // TODO and some smart caching dirty ids here!
  15287. return "\n gl.uniformMatrix3fv(ud[\"" + name + "\"].location, false, uv[\"" + name + "\"].toArray(true));\n ";
  15288. },
  15289. codeUbo: function (name) {
  15290. return "\n var " + name + "_matrix = uv." + name + ".toArray(true);\n\n data[offset] = " + name + "_matrix[0];\n data[offset+1] = " + name + "_matrix[1];\n data[offset+2] = " + name + "_matrix[2];\n \n data[offset + 4] = " + name + "_matrix[3];\n data[offset + 5] = " + name + "_matrix[4];\n data[offset + 6] = " + name + "_matrix[5];\n \n data[offset + 8] = " + name + "_matrix[6];\n data[offset + 9] = " + name + "_matrix[7];\n data[offset + 10] = " + name + "_matrix[8];\n ";
  15291. },
  15292. },
  15293. // uploading a pixi point as a vec2 with caching layer
  15294. {
  15295. test: function (data, uniform) {
  15296. return data.type === 'vec2' && data.size === 1 && !data.isArray && uniform.x !== undefined;
  15297. },
  15298. code: function (name) {
  15299. return "\n cv = ud[\"" + name + "\"].value;\n v = uv[\"" + name + "\"];\n\n if(cv[0] !== v.x || cv[1] !== v.y)\n {\n cv[0] = v.x;\n cv[1] = v.y;\n gl.uniform2f(ud[\"" + name + "\"].location, v.x, v.y);\n }";
  15300. },
  15301. codeUbo: function (name) {
  15302. return "\n v = uv." + name + ";\n\n data[offset] = v.x;\n data[offset+1] = v.y;\n ";
  15303. }
  15304. },
  15305. // caching layer for a vec2
  15306. {
  15307. test: function (data) {
  15308. return data.type === 'vec2' && data.size === 1 && !data.isArray;
  15309. },
  15310. code: function (name) {
  15311. return "\n cv = ud[\"" + name + "\"].value;\n v = uv[\"" + name + "\"];\n\n if(cv[0] !== v[0] || cv[1] !== v[1])\n {\n cv[0] = v[0];\n cv[1] = v[1];\n gl.uniform2f(ud[\"" + name + "\"].location, v[0], v[1]);\n }\n ";
  15312. },
  15313. },
  15314. // upload a pixi rectangle as a vec4 with caching layer
  15315. {
  15316. test: function (data, uniform) {
  15317. return data.type === 'vec4' && data.size === 1 && !data.isArray && uniform.width !== undefined;
  15318. },
  15319. code: function (name) {
  15320. return "\n cv = ud[\"" + name + "\"].value;\n v = uv[\"" + name + "\"];\n\n if(cv[0] !== v.x || cv[1] !== v.y || cv[2] !== v.width || cv[3] !== v.height)\n {\n cv[0] = v.x;\n cv[1] = v.y;\n cv[2] = v.width;\n cv[3] = v.height;\n gl.uniform4f(ud[\"" + name + "\"].location, v.x, v.y, v.width, v.height)\n }";
  15321. },
  15322. codeUbo: function (name) {
  15323. return "\n v = uv." + name + ";\n\n data[offset] = v.x;\n data[offset+1] = v.y;\n data[offset+2] = v.width;\n data[offset+3] = v.height;\n ";
  15324. }
  15325. },
  15326. // a caching layer for vec4 uploading
  15327. {
  15328. test: function (data) {
  15329. return data.type === 'vec4' && data.size === 1 && !data.isArray;
  15330. },
  15331. code: function (name) {
  15332. return "\n cv = ud[\"" + name + "\"].value;\n v = uv[\"" + name + "\"];\n\n if(cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2] || cv[3] !== v[3])\n {\n cv[0] = v[0];\n cv[1] = v[1];\n cv[2] = v[2];\n cv[3] = v[3];\n\n gl.uniform4f(ud[\"" + name + "\"].location, v[0], v[1], v[2], v[3])\n }";
  15333. },
  15334. } ];
  15335. // cu = Cached value's uniform data field
  15336. // cv = Cached value
  15337. // v = value to upload
  15338. // ud = uniformData
  15339. // uv = uniformValue
  15340. // l = location
  15341. var GLSL_TO_SINGLE_SETTERS_CACHED = {
  15342. float: "\n if (cv !== v)\n {\n cu.value = v;\n gl.uniform1f(location, v);\n }",
  15343. vec2: "\n if (cv[0] !== v[0] || cv[1] !== v[1])\n {\n cv[0] = v[0];\n cv[1] = v[1];\n\n gl.uniform2f(location, v[0], v[1])\n }",
  15344. vec3: "\n if (cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2])\n {\n cv[0] = v[0];\n cv[1] = v[1];\n cv[2] = v[2];\n\n gl.uniform3f(location, v[0], v[1], v[2])\n }",
  15345. vec4: "\n if (cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2] || cv[3] !== v[3])\n {\n cv[0] = v[0];\n cv[1] = v[1];\n cv[2] = v[2];\n cv[3] = v[3];\n\n gl.uniform4f(location, v[0], v[1], v[2], v[3]);\n }",
  15346. int: "\n if (cv !== v)\n {\n cu.value = v;\n\n gl.uniform1i(location, v);\n }",
  15347. ivec2: "\n if (cv[0] !== v[0] || cv[1] !== v[1])\n {\n cv[0] = v[0];\n cv[1] = v[1];\n\n gl.uniform2i(location, v[0], v[1]);\n }",
  15348. ivec3: "\n if (cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2])\n {\n cv[0] = v[0];\n cv[1] = v[1];\n cv[2] = v[2];\n\n gl.uniform3i(location, v[0], v[1], v[2]);\n }",
  15349. ivec4: "\n if (cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2] || cv[3] !== v[3])\n {\n cv[0] = v[0];\n cv[1] = v[1];\n cv[2] = v[2];\n cv[3] = v[3];\n\n gl.uniform4i(location, v[0], v[1], v[2], v[3]);\n }",
  15350. uint: "\n if (cv !== v)\n {\n cu.value = v;\n\n gl.uniform1ui(location, v);\n }",
  15351. uvec2: "\n if (cv[0] !== v[0] || cv[1] !== v[1])\n {\n cv[0] = v[0];\n cv[1] = v[1];\n\n gl.uniform2ui(location, v[0], v[1]);\n }",
  15352. uvec3: "\n if (cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2])\n {\n cv[0] = v[0];\n cv[1] = v[1];\n cv[2] = v[2];\n\n gl.uniform3ui(location, v[0], v[1], v[2]);\n }",
  15353. uvec4: "\n if (cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2] || cv[3] !== v[3])\n {\n cv[0] = v[0];\n cv[1] = v[1];\n cv[2] = v[2];\n cv[3] = v[3];\n\n gl.uniform4ui(location, v[0], v[1], v[2], v[3]);\n }",
  15354. bool: "\n if (cv !== v)\n {\n cu.value = v;\n gl.uniform1i(location, v);\n }",
  15355. bvec2: "\n if (cv[0] != v[0] || cv[1] != v[1])\n {\n cv[0] = v[0];\n cv[1] = v[1];\n\n gl.uniform2i(location, v[0], v[1]);\n }",
  15356. bvec3: "\n if (cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2])\n {\n cv[0] = v[0];\n cv[1] = v[1];\n cv[2] = v[2];\n\n gl.uniform3i(location, v[0], v[1], v[2]);\n }",
  15357. bvec4: "\n if (cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2] || cv[3] !== v[3])\n {\n cv[0] = v[0];\n cv[1] = v[1];\n cv[2] = v[2];\n cv[3] = v[3];\n\n gl.uniform4i(location, v[0], v[1], v[2], v[3]);\n }",
  15358. mat2: 'gl.uniformMatrix2fv(location, false, v)',
  15359. mat3: 'gl.uniformMatrix3fv(location, false, v)',
  15360. mat4: 'gl.uniformMatrix4fv(location, false, v)',
  15361. sampler2D: "\n if (cv !== v)\n {\n cu.value = v;\n\n gl.uniform1i(location, v);\n }",
  15362. samplerCube: "\n if (cv !== v)\n {\n cu.value = v;\n\n gl.uniform1i(location, v);\n }",
  15363. sampler2DArray: "\n if (cv !== v)\n {\n cu.value = v;\n\n gl.uniform1i(location, v);\n }",
  15364. };
  15365. var GLSL_TO_ARRAY_SETTERS = {
  15366. float: "gl.uniform1fv(location, v)",
  15367. vec2: "gl.uniform2fv(location, v)",
  15368. vec3: "gl.uniform3fv(location, v)",
  15369. vec4: 'gl.uniform4fv(location, v)',
  15370. mat4: 'gl.uniformMatrix4fv(location, false, v)',
  15371. mat3: 'gl.uniformMatrix3fv(location, false, v)',
  15372. mat2: 'gl.uniformMatrix2fv(location, false, v)',
  15373. int: 'gl.uniform1iv(location, v)',
  15374. ivec2: 'gl.uniform2iv(location, v)',
  15375. ivec3: 'gl.uniform3iv(location, v)',
  15376. ivec4: 'gl.uniform4iv(location, v)',
  15377. uint: 'gl.uniform1uiv(location, v)',
  15378. uvec2: 'gl.uniform2uiv(location, v)',
  15379. uvec3: 'gl.uniform3uiv(location, v)',
  15380. uvec4: 'gl.uniform4uiv(location, v)',
  15381. bool: 'gl.uniform1iv(location, v)',
  15382. bvec2: 'gl.uniform2iv(location, v)',
  15383. bvec3: 'gl.uniform3iv(location, v)',
  15384. bvec4: 'gl.uniform4iv(location, v)',
  15385. sampler2D: 'gl.uniform1iv(location, v)',
  15386. samplerCube: 'gl.uniform1iv(location, v)',
  15387. sampler2DArray: 'gl.uniform1iv(location, v)',
  15388. };
  15389. function generateUniformsSync(group, uniformData) {
  15390. var _a;
  15391. var funcFragments = ["\n var v = null;\n var cv = null;\n var cu = null;\n var t = 0;\n var gl = renderer.gl;\n "];
  15392. for (var i in group.uniforms) {
  15393. var data = uniformData[i];
  15394. if (!data) {
  15395. if ((_a = group.uniforms[i]) === null || _a === void 0 ? void 0 : _a.group) {
  15396. if (group.uniforms[i].ubo) {
  15397. funcFragments.push("\n renderer.shader.syncUniformBufferGroup(uv." + i + ", '" + i + "');\n ");
  15398. }
  15399. else {
  15400. funcFragments.push("\n renderer.shader.syncUniformGroup(uv." + i + ", syncData);\n ");
  15401. }
  15402. }
  15403. continue;
  15404. }
  15405. var uniform = group.uniforms[i];
  15406. var parsed = false;
  15407. for (var j = 0; j < uniformParsers.length; j++) {
  15408. if (uniformParsers[j].test(data, uniform)) {
  15409. funcFragments.push(uniformParsers[j].code(i, uniform));
  15410. parsed = true;
  15411. break;
  15412. }
  15413. }
  15414. if (!parsed) {
  15415. var templateType = data.size === 1 && !data.isArray ? GLSL_TO_SINGLE_SETTERS_CACHED : GLSL_TO_ARRAY_SETTERS;
  15416. var template = templateType[data.type].replace('location', "ud[\"" + i + "\"].location");
  15417. funcFragments.push("\n cu = ud[\"" + i + "\"];\n cv = cu.value;\n v = uv[\"" + i + "\"];\n " + template + ";");
  15418. }
  15419. }
  15420. /*
  15421. * the introduction of syncData is to solve an issue where textures in uniform groups are not set correctly
  15422. * the texture count was always starting from 0 in each group. This needs to increment each time a texture is used
  15423. * no matter which group is being used
  15424. *
  15425. */
  15426. // eslint-disable-next-line no-new-func
  15427. return new Function('ud', 'uv', 'renderer', 'syncData', funcFragments.join('\n'));
  15428. }
  15429. var fragTemplate$1 = [
  15430. 'precision mediump float;',
  15431. 'void main(void){',
  15432. 'float test = 0.1;',
  15433. '%forloop%',
  15434. 'gl_FragColor = vec4(0.0);',
  15435. '}' ].join('\n');
  15436. function generateIfTestSrc(maxIfs) {
  15437. var src = '';
  15438. for (var i = 0; i < maxIfs; ++i) {
  15439. if (i > 0) {
  15440. src += '\nelse ';
  15441. }
  15442. if (i < maxIfs - 1) {
  15443. src += "if(test == " + i + ".0){}";
  15444. }
  15445. }
  15446. return src;
  15447. }
  15448. function checkMaxIfStatementsInShader(maxIfs, gl) {
  15449. if (maxIfs === 0) {
  15450. throw new Error('Invalid value of `0` passed to `checkMaxIfStatementsInShader`');
  15451. }
  15452. var shader = gl.createShader(gl.FRAGMENT_SHADER);
  15453. while (true) // eslint-disable-line no-constant-condition
  15454. {
  15455. var fragmentSrc = fragTemplate$1.replace(/%forloop%/gi, generateIfTestSrc(maxIfs));
  15456. gl.shaderSource(shader, fragmentSrc);
  15457. gl.compileShader(shader);
  15458. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  15459. maxIfs = (maxIfs / 2) | 0;
  15460. }
  15461. else {
  15462. // valid!
  15463. break;
  15464. }
  15465. }
  15466. return maxIfs;
  15467. }
  15468. // Cache the result to prevent running this over and over
  15469. var unsafeEval;
  15470. /**
  15471. * Not all platforms allow to generate function code (e.g., `new Function`).
  15472. * this provides the platform-level detection.
  15473. * @private
  15474. * @returns {boolean} `true` if `new Function` is supported.
  15475. */
  15476. function unsafeEvalSupported() {
  15477. if (typeof unsafeEval === 'boolean') {
  15478. return unsafeEval;
  15479. }
  15480. try {
  15481. /* eslint-disable no-new-func */
  15482. var func = new Function('param1', 'param2', 'param3', 'return param1[param2] === param3;');
  15483. /* eslint-enable no-new-func */
  15484. unsafeEval = func({ a: 'b' }, 'a', 'b') === true;
  15485. }
  15486. catch (e) {
  15487. unsafeEval = false;
  15488. }
  15489. return unsafeEval;
  15490. }
  15491. var defaultFragment$2 = "varying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\n\nvoid main(void){\n gl_FragColor *= texture2D(uSampler, vTextureCoord);\n}";
  15492. var defaultVertex$3 = "attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void){\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n vTextureCoord = aTextureCoord;\n}\n";
  15493. var UID$1 = 0;
  15494. var nameCache = {};
  15495. /**
  15496. * Helper class to create a shader program.
  15497. * @memberof PIXI
  15498. */
  15499. var Program = /** @class */ (function () {
  15500. /**
  15501. * @param vertexSrc - The source of the vertex shader.
  15502. * @param fragmentSrc - The source of the fragment shader.
  15503. * @param name - Name for shader
  15504. */
  15505. function Program(vertexSrc, fragmentSrc, name) {
  15506. if (name === void 0) { name = 'pixi-shader'; }
  15507. this.id = UID$1++;
  15508. this.vertexSrc = vertexSrc || Program.defaultVertexSrc;
  15509. this.fragmentSrc = fragmentSrc || Program.defaultFragmentSrc;
  15510. this.vertexSrc = this.vertexSrc.trim();
  15511. this.fragmentSrc = this.fragmentSrc.trim();
  15512. if (this.vertexSrc.substring(0, 8) !== '#version') {
  15513. name = name.replace(/\s+/g, '-');
  15514. if (nameCache[name]) {
  15515. nameCache[name]++;
  15516. name += "-" + nameCache[name];
  15517. }
  15518. else {
  15519. nameCache[name] = 1;
  15520. }
  15521. this.vertexSrc = "#define SHADER_NAME " + name + "\n" + this.vertexSrc;
  15522. this.fragmentSrc = "#define SHADER_NAME " + name + "\n" + this.fragmentSrc;
  15523. this.vertexSrc = setPrecision(this.vertexSrc, settings.PRECISION_VERTEX, PRECISION.HIGH);
  15524. this.fragmentSrc = setPrecision(this.fragmentSrc, settings.PRECISION_FRAGMENT, getMaxFragmentPrecision());
  15525. }
  15526. // currently this does not extract structs only default types
  15527. // this is where we store shader references..
  15528. this.glPrograms = {};
  15529. this.syncUniforms = null;
  15530. }
  15531. Object.defineProperty(Program, "defaultVertexSrc", {
  15532. /**
  15533. * The default vertex shader source.
  15534. * @constant
  15535. */
  15536. get: function () {
  15537. return defaultVertex$3;
  15538. },
  15539. enumerable: false,
  15540. configurable: true
  15541. });
  15542. Object.defineProperty(Program, "defaultFragmentSrc", {
  15543. /**
  15544. * The default fragment shader source.
  15545. * @constant
  15546. */
  15547. get: function () {
  15548. return defaultFragment$2;
  15549. },
  15550. enumerable: false,
  15551. configurable: true
  15552. });
  15553. /**
  15554. * A short hand function to create a program based of a vertex and fragment shader.
  15555. *
  15556. * This method will also check to see if there is a cached program.
  15557. * @param vertexSrc - The source of the vertex shader.
  15558. * @param fragmentSrc - The source of the fragment shader.
  15559. * @param name - Name for shader
  15560. * @returns A shiny new PixiJS shader program!
  15561. */
  15562. Program.from = function (vertexSrc, fragmentSrc, name) {
  15563. var key = vertexSrc + fragmentSrc;
  15564. var program = ProgramCache[key];
  15565. if (!program) {
  15566. ProgramCache[key] = program = new Program(vertexSrc, fragmentSrc, name);
  15567. }
  15568. return program;
  15569. };
  15570. return Program;
  15571. }());
  15572. /**
  15573. * A helper class for shaders.
  15574. * @memberof PIXI
  15575. */
  15576. var Shader = /** @class */ (function () {
  15577. /**
  15578. * @param program - The program the shader will use.
  15579. * @param uniforms - Custom uniforms to use to augment the built-in ones.
  15580. */
  15581. function Shader(program, uniforms) {
  15582. /**
  15583. * Used internally to bind uniform buffer objects.
  15584. * @ignore
  15585. */
  15586. this.uniformBindCount = 0;
  15587. this.program = program;
  15588. // lets see whats been passed in
  15589. // uniforms should be converted to a uniform group
  15590. if (uniforms) {
  15591. if (uniforms instanceof UniformGroup) {
  15592. this.uniformGroup = uniforms;
  15593. }
  15594. else {
  15595. this.uniformGroup = new UniformGroup(uniforms);
  15596. }
  15597. }
  15598. else {
  15599. this.uniformGroup = new UniformGroup({});
  15600. }
  15601. this.disposeRunner = new Runner('disposeShader');
  15602. }
  15603. // TODO move to shader system..
  15604. Shader.prototype.checkUniformExists = function (name, group) {
  15605. if (group.uniforms[name]) {
  15606. return true;
  15607. }
  15608. for (var i in group.uniforms) {
  15609. var uniform = group.uniforms[i];
  15610. if (uniform.group) {
  15611. if (this.checkUniformExists(name, uniform)) {
  15612. return true;
  15613. }
  15614. }
  15615. }
  15616. return false;
  15617. };
  15618. Shader.prototype.destroy = function () {
  15619. // usage count on programs?
  15620. // remove if not used!
  15621. this.uniformGroup = null;
  15622. this.disposeRunner.emit(this);
  15623. this.disposeRunner.destroy();
  15624. };
  15625. Object.defineProperty(Shader.prototype, "uniforms", {
  15626. /**
  15627. * Shader uniform values, shortcut for `uniformGroup.uniforms`.
  15628. * @readonly
  15629. */
  15630. get: function () {
  15631. return this.uniformGroup.uniforms;
  15632. },
  15633. enumerable: false,
  15634. configurable: true
  15635. });
  15636. /**
  15637. * A short hand function to create a shader based of a vertex and fragment shader.
  15638. * @param vertexSrc - The source of the vertex shader.
  15639. * @param fragmentSrc - The source of the fragment shader.
  15640. * @param uniforms - Custom uniforms to use to augment the built-in ones.
  15641. * @returns A shiny new PixiJS shader!
  15642. */
  15643. Shader.from = function (vertexSrc, fragmentSrc, uniforms) {
  15644. var program = Program.from(vertexSrc, fragmentSrc);
  15645. return new Shader(program, uniforms);
  15646. };
  15647. return Shader;
  15648. }());
  15649. /* eslint-disable max-len */
  15650. var BLEND$1 = 0;
  15651. var OFFSET$1 = 1;
  15652. var CULLING$1 = 2;
  15653. var DEPTH_TEST$1 = 3;
  15654. var WINDING$1 = 4;
  15655. var DEPTH_MASK$1 = 5;
  15656. /**
  15657. * This is a WebGL state, and is is passed to {@link PIXI.StateSystem}.
  15658. *
  15659. * Each mesh rendered may require WebGL to be in a different state.
  15660. * For example you may want different blend mode or to enable polygon offsets
  15661. * @memberof PIXI
  15662. */
  15663. var State = /** @class */ (function () {
  15664. function State() {
  15665. this.data = 0;
  15666. this.blendMode = BLEND_MODES.NORMAL;
  15667. this.polygonOffset = 0;
  15668. this.blend = true;
  15669. this.depthMask = true;
  15670. // this.depthTest = true;
  15671. }
  15672. Object.defineProperty(State.prototype, "blend", {
  15673. /**
  15674. * Activates blending of the computed fragment color values.
  15675. * @default true
  15676. */
  15677. get: function () {
  15678. return !!(this.data & (1 << BLEND$1));
  15679. },
  15680. set: function (value) {
  15681. if (!!(this.data & (1 << BLEND$1)) !== value) {
  15682. this.data ^= (1 << BLEND$1);
  15683. }
  15684. },
  15685. enumerable: false,
  15686. configurable: true
  15687. });
  15688. Object.defineProperty(State.prototype, "offsets", {
  15689. /**
  15690. * Activates adding an offset to depth values of polygon's fragments
  15691. * @default false
  15692. */
  15693. get: function () {
  15694. return !!(this.data & (1 << OFFSET$1));
  15695. },
  15696. set: function (value) {
  15697. if (!!(this.data & (1 << OFFSET$1)) !== value) {
  15698. this.data ^= (1 << OFFSET$1);
  15699. }
  15700. },
  15701. enumerable: false,
  15702. configurable: true
  15703. });
  15704. Object.defineProperty(State.prototype, "culling", {
  15705. /**
  15706. * Activates culling of polygons.
  15707. * @default false
  15708. */
  15709. get: function () {
  15710. return !!(this.data & (1 << CULLING$1));
  15711. },
  15712. set: function (value) {
  15713. if (!!(this.data & (1 << CULLING$1)) !== value) {
  15714. this.data ^= (1 << CULLING$1);
  15715. }
  15716. },
  15717. enumerable: false,
  15718. configurable: true
  15719. });
  15720. Object.defineProperty(State.prototype, "depthTest", {
  15721. /**
  15722. * Activates depth comparisons and updates to the depth buffer.
  15723. * @default false
  15724. */
  15725. get: function () {
  15726. return !!(this.data & (1 << DEPTH_TEST$1));
  15727. },
  15728. set: function (value) {
  15729. if (!!(this.data & (1 << DEPTH_TEST$1)) !== value) {
  15730. this.data ^= (1 << DEPTH_TEST$1);
  15731. }
  15732. },
  15733. enumerable: false,
  15734. configurable: true
  15735. });
  15736. Object.defineProperty(State.prototype, "depthMask", {
  15737. /**
  15738. * Enables or disables writing to the depth buffer.
  15739. * @default true
  15740. */
  15741. get: function () {
  15742. return !!(this.data & (1 << DEPTH_MASK$1));
  15743. },
  15744. set: function (value) {
  15745. if (!!(this.data & (1 << DEPTH_MASK$1)) !== value) {
  15746. this.data ^= (1 << DEPTH_MASK$1);
  15747. }
  15748. },
  15749. enumerable: false,
  15750. configurable: true
  15751. });
  15752. Object.defineProperty(State.prototype, "clockwiseFrontFace", {
  15753. /**
  15754. * Specifies whether or not front or back-facing polygons can be culled.
  15755. * @default false
  15756. */
  15757. get: function () {
  15758. return !!(this.data & (1 << WINDING$1));
  15759. },
  15760. set: function (value) {
  15761. if (!!(this.data & (1 << WINDING$1)) !== value) {
  15762. this.data ^= (1 << WINDING$1);
  15763. }
  15764. },
  15765. enumerable: false,
  15766. configurable: true
  15767. });
  15768. Object.defineProperty(State.prototype, "blendMode", {
  15769. /**
  15770. * The blend mode to be applied when this state is set. Apply a value of `PIXI.BLEND_MODES.NORMAL` to reset the blend mode.
  15771. * Setting this mode to anything other than NO_BLEND will automatically switch blending on.
  15772. * @default PIXI.BLEND_MODES.NORMAL
  15773. */
  15774. get: function () {
  15775. return this._blendMode;
  15776. },
  15777. set: function (value) {
  15778. this.blend = (value !== BLEND_MODES.NONE);
  15779. this._blendMode = value;
  15780. },
  15781. enumerable: false,
  15782. configurable: true
  15783. });
  15784. Object.defineProperty(State.prototype, "polygonOffset", {
  15785. /**
  15786. * The polygon offset. Setting this property to anything other than 0 will automatically enable polygon offset fill.
  15787. * @default 0
  15788. */
  15789. get: function () {
  15790. return this._polygonOffset;
  15791. },
  15792. set: function (value) {
  15793. this.offsets = !!value;
  15794. this._polygonOffset = value;
  15795. },
  15796. enumerable: false,
  15797. configurable: true
  15798. });
  15799. State.prototype.toString = function () {
  15800. return "[@pixi/core:State "
  15801. + ("blendMode=" + this.blendMode + " ")
  15802. + ("clockwiseFrontFace=" + this.clockwiseFrontFace + " ")
  15803. + ("culling=" + this.culling + " ")
  15804. + ("depthMask=" + this.depthMask + " ")
  15805. + ("polygonOffset=" + this.polygonOffset)
  15806. + "]";
  15807. };
  15808. State.for2d = function () {
  15809. var state = new State();
  15810. state.depthTest = false;
  15811. state.blend = true;
  15812. return state;
  15813. };
  15814. return State;
  15815. }());
  15816. var defaultFragment$1 = "varying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\n\nvoid main(void){\n gl_FragColor = texture2D(uSampler, vTextureCoord);\n}\n";
  15817. var defaultVertex$2 = "attribute vec2 aVertexPosition;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nuniform vec4 inputSize;\nuniform vec4 outputFrame;\n\nvec4 filterVertexPosition( void )\n{\n vec2 position = aVertexPosition * max(outputFrame.zw, vec2(0.)) + outputFrame.xy;\n\n return vec4((projectionMatrix * vec3(position, 1.0)).xy, 0.0, 1.0);\n}\n\nvec2 filterTextureCoord( void )\n{\n return aVertexPosition * (outputFrame.zw * inputSize.zw);\n}\n\nvoid main(void)\n{\n gl_Position = filterVertexPosition();\n vTextureCoord = filterTextureCoord();\n}\n";
  15818. /**
  15819. * A filter is a special shader that applies post-processing effects to an input texture and writes into an output
  15820. * render-target.
  15821. *
  15822. * {@link http://pixijs.io/examples/#/filters/blur-filter.js Example} of the
  15823. * {@link PIXI.filters.BlurFilter BlurFilter}.
  15824. *
  15825. * ### Usage
  15826. * Filters can be applied to any DisplayObject or Container.
  15827. * PixiJS' `FilterSystem` renders the container into temporary Framebuffer,
  15828. * then filter renders it to the screen.
  15829. * Multiple filters can be added to the `filters` array property and stacked on each other.
  15830. *
  15831. * ```
  15832. * const filter = new PIXI.Filter(myShaderVert, myShaderFrag, { myUniform: 0.5 });
  15833. * const container = new PIXI.Container();
  15834. * container.filters = [filter];
  15835. * ```
  15836. *
  15837. * ### Previous Version Differences
  15838. *
  15839. * In PixiJS **v3**, a filter was always applied to _whole screen_.
  15840. *
  15841. * In PixiJS **v4**, a filter can be applied _only part of the screen_.
  15842. * Developers had to create a set of uniforms to deal with coordinates.
  15843. *
  15844. * In PixiJS **v5** combines _both approaches_.
  15845. * Developers can use normal coordinates of v3 and then allow filter to use partial Framebuffers,
  15846. * bringing those extra uniforms into account.
  15847. *
  15848. * Also be aware that we have changed default vertex shader, please consult
  15849. * {@link https://github.com/pixijs/pixi.js/wiki/v5-Creating-filters Wiki}.
  15850. *
  15851. * ### Frames
  15852. *
  15853. * The following table summarizes the coordinate spaces used in the filtering pipeline:
  15854. *
  15855. * <table>
  15856. * <thead>
  15857. * <tr>
  15858. * <th>Coordinate Space</th>
  15859. * <th>Description</th>
  15860. * </tr>
  15861. * </thead>
  15862. * <tbody>
  15863. * <tr>
  15864. * <td>Texture Coordinates</td>
  15865. * <td>
  15866. * The texture (or UV) coordinates in the input base-texture's space. These are normalized into the (0,1) range along
  15867. * both axes.
  15868. * </td>
  15869. * </tr>
  15870. * <tr>
  15871. * <td>World Space</td>
  15872. * <td>
  15873. * A point in the same space as the world bounds of any display-object (i.e. in the scene graph's space).
  15874. * </td>
  15875. * </tr>
  15876. * <tr>
  15877. * <td>Physical Pixels</td>
  15878. * <td>
  15879. * This is base-texture's space with the origin on the top-left. You can calculate these by multiplying the texture
  15880. * coordinates by the dimensions of the texture.
  15881. * </td>
  15882. * </tr>
  15883. * </tbody>
  15884. * </table>
  15885. *
  15886. * ### Built-in Uniforms
  15887. *
  15888. * PixiJS viewport uses screen (CSS) coordinates, `(0, 0, renderer.screen.width, renderer.screen.height)`,
  15889. * and `projectionMatrix` uniform maps it to the gl viewport.
  15890. *
  15891. * **uSampler**
  15892. *
  15893. * The most important uniform is the input texture that container was rendered into.
  15894. * _Important note: as with all Framebuffers in PixiJS, both input and output are
  15895. * premultiplied by alpha._
  15896. *
  15897. * By default, input normalized coordinates are passed to fragment shader with `vTextureCoord`.
  15898. * Use it to sample the input.
  15899. *
  15900. * ```
  15901. * const fragment = `
  15902. * varying vec2 vTextureCoord;
  15903. * uniform sampler2D uSampler;
  15904. * void main(void)
  15905. * {
  15906. * gl_FragColor = texture2D(uSampler, vTextureCoord);
  15907. * }
  15908. * `;
  15909. *
  15910. * const myFilter = new PIXI.Filter(null, fragment);
  15911. * ```
  15912. *
  15913. * This filter is just one uniform less than {@link PIXI.filters.AlphaFilter AlphaFilter}.
  15914. *
  15915. * **outputFrame**
  15916. *
  15917. * The `outputFrame` holds the rectangle where filter is applied in screen (CSS) coordinates.
  15918. * It's the same as `renderer.screen` for a fullscreen filter.
  15919. * Only a part of `outputFrame.zw` size of temporary Framebuffer is used,
  15920. * `(0, 0, outputFrame.width, outputFrame.height)`,
  15921. *
  15922. * Filters uses this quad to normalized (0-1) space, its passed into `aVertexPosition` attribute.
  15923. * To calculate vertex position in screen space using normalized (0-1) space:
  15924. *
  15925. * ```
  15926. * vec4 filterVertexPosition( void )
  15927. * {
  15928. * vec2 position = aVertexPosition * max(outputFrame.zw, vec2(0.)) + outputFrame.xy;
  15929. * return vec4((projectionMatrix * vec3(position, 1.0)).xy, 0.0, 1.0);
  15930. * }
  15931. * ```
  15932. *
  15933. * **inputSize**
  15934. *
  15935. * Temporary framebuffer is different, it can be either the size of screen, either power-of-two.
  15936. * The `inputSize.xy` are size of temporary framebuffer that holds input.
  15937. * The `inputSize.zw` is inverted, it's a shortcut to evade division inside the shader.
  15938. *
  15939. * Set `inputSize.xy = outputFrame.zw` for a fullscreen filter.
  15940. *
  15941. * To calculate input normalized coordinate, you have to map it to filter normalized space.
  15942. * Multiply by `outputFrame.zw` to get input coordinate.
  15943. * Divide by `inputSize.xy` to get input normalized coordinate.
  15944. *
  15945. * ```
  15946. * vec2 filterTextureCoord( void )
  15947. * {
  15948. * return aVertexPosition * (outputFrame.zw * inputSize.zw); // same as /inputSize.xy
  15949. * }
  15950. * ```
  15951. * **resolution**
  15952. *
  15953. * The `resolution` is the ratio of screen (CSS) pixels to real pixels.
  15954. *
  15955. * **inputPixel**
  15956. *
  15957. * `inputPixel.xy` is the size of framebuffer in real pixels, same as `inputSize.xy * resolution`
  15958. * `inputPixel.zw` is inverted `inputPixel.xy`.
  15959. *
  15960. * It's handy for filters that use neighbour pixels, like {@link PIXI.filters.FXAAFilter FXAAFilter}.
  15961. *
  15962. * **inputClamp**
  15963. *
  15964. * If you try to get info from outside of used part of Framebuffer - you'll get undefined behaviour.
  15965. * For displacements, coordinates has to be clamped.
  15966. *
  15967. * The `inputClamp.xy` is left-top pixel center, you may ignore it, because we use left-top part of Framebuffer
  15968. * `inputClamp.zw` is bottom-right pixel center.
  15969. *
  15970. * ```
  15971. * vec4 color = texture2D(uSampler, clamp(modifiedTextureCoord, inputClamp.xy, inputClamp.zw))
  15972. * ```
  15973. * OR
  15974. * ```
  15975. * vec4 color = texture2D(uSampler, min(modifigedTextureCoord, inputClamp.zw))
  15976. * ```
  15977. *
  15978. * ### Additional Information
  15979. *
  15980. * Complete documentation on Filter usage is located in the
  15981. * {@link https://github.com/pixijs/pixi.js/wiki/v5-Creating-filters Wiki}.
  15982. *
  15983. * Since PixiJS only had a handful of built-in filters, additional filters can be downloaded
  15984. * {@link https://github.com/pixijs/pixi-filters here} from the PixiJS Filters repository.
  15985. * @memberof PIXI
  15986. */
  15987. var Filter = /** @class */ (function (_super) {
  15988. __extends$i(Filter, _super);
  15989. /**
  15990. * @param vertexSrc - The source of the vertex shader.
  15991. * @param fragmentSrc - The source of the fragment shader.
  15992. * @param uniforms - Custom uniforms to use to augment the built-in ones.
  15993. */
  15994. function Filter(vertexSrc, fragmentSrc, uniforms) {
  15995. var _this = this;
  15996. var program = Program.from(vertexSrc || Filter.defaultVertexSrc, fragmentSrc || Filter.defaultFragmentSrc);
  15997. _this = _super.call(this, program, uniforms) || this;
  15998. _this.padding = 0;
  15999. _this.resolution = settings.FILTER_RESOLUTION;
  16000. _this.multisample = settings.FILTER_MULTISAMPLE;
  16001. _this.enabled = true;
  16002. _this.autoFit = true;
  16003. _this.state = new State();
  16004. return _this;
  16005. }
  16006. /**
  16007. * Applies the filter
  16008. * @param {PIXI.FilterSystem} filterManager - The renderer to retrieve the filter from
  16009. * @param {PIXI.RenderTexture} input - The input render target.
  16010. * @param {PIXI.RenderTexture} output - The target to output to.
  16011. * @param {PIXI.CLEAR_MODES} [clearMode] - Should the output be cleared before rendering to it.
  16012. * @param {object} [_currentState] - It's current state of filter.
  16013. * There are some useful properties in the currentState :
  16014. * target, filters, sourceFrame, destinationFrame, renderTarget, resolution
  16015. */
  16016. Filter.prototype.apply = function (filterManager, input, output, clearMode, _currentState) {
  16017. // do as you please!
  16018. filterManager.applyFilter(this, input, output, clearMode);
  16019. // or just do a regular render..
  16020. };
  16021. Object.defineProperty(Filter.prototype, "blendMode", {
  16022. /**
  16023. * Sets the blend mode of the filter.
  16024. * @default PIXI.BLEND_MODES.NORMAL
  16025. */
  16026. get: function () {
  16027. return this.state.blendMode;
  16028. },
  16029. set: function (value) {
  16030. this.state.blendMode = value;
  16031. },
  16032. enumerable: false,
  16033. configurable: true
  16034. });
  16035. Object.defineProperty(Filter.prototype, "resolution", {
  16036. /**
  16037. * The resolution of the filter. Setting this to be lower will lower the quality but
  16038. * increase the performance of the filter.
  16039. */
  16040. get: function () {
  16041. return this._resolution;
  16042. },
  16043. set: function (value) {
  16044. this._resolution = value;
  16045. },
  16046. enumerable: false,
  16047. configurable: true
  16048. });
  16049. Object.defineProperty(Filter, "defaultVertexSrc", {
  16050. /**
  16051. * The default vertex shader source
  16052. * @constant
  16053. */
  16054. get: function () {
  16055. return defaultVertex$2;
  16056. },
  16057. enumerable: false,
  16058. configurable: true
  16059. });
  16060. Object.defineProperty(Filter, "defaultFragmentSrc", {
  16061. /**
  16062. * The default fragment shader source
  16063. * @constant
  16064. */
  16065. get: function () {
  16066. return defaultFragment$1;
  16067. },
  16068. enumerable: false,
  16069. configurable: true
  16070. });
  16071. return Filter;
  16072. }(Shader));
  16073. var vertex$4 = "attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 otherMatrix;\n\nvarying vec2 vMaskCoord;\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = aTextureCoord;\n vMaskCoord = ( otherMatrix * vec3( aTextureCoord, 1.0) ).xy;\n}\n";
  16074. var fragment$7 = "varying vec2 vMaskCoord;\nvarying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform sampler2D mask;\nuniform float alpha;\nuniform float npmAlpha;\nuniform vec4 maskClamp;\n\nvoid main(void)\n{\n float clip = step(3.5,\n step(maskClamp.x, vMaskCoord.x) +\n step(maskClamp.y, vMaskCoord.y) +\n step(vMaskCoord.x, maskClamp.z) +\n step(vMaskCoord.y, maskClamp.w));\n\n vec4 original = texture2D(uSampler, vTextureCoord);\n vec4 masky = texture2D(mask, vMaskCoord);\n float alphaMul = 1.0 - npmAlpha * (1.0 - masky.a);\n\n original *= (alphaMul * masky.r * alpha * clip);\n\n gl_FragColor = original;\n}\n";
  16075. var tempMat$1 = new Matrix();
  16076. /**
  16077. * Class controls uv mapping from Texture normal space to BaseTexture normal space.
  16078. *
  16079. * Takes `trim` and `rotate` into account. May contain clamp settings for Meshes and TilingSprite.
  16080. *
  16081. * Can be used in Texture `uvMatrix` field, or separately, you can use different clamp settings on the same texture.
  16082. * If you want to add support for texture region of certain feature or filter, that's what you're looking for.
  16083. *
  16084. * Takes track of Texture changes through `_lastTextureID` private field.
  16085. * Use `update()` method call to track it from outside.
  16086. * @see PIXI.Texture
  16087. * @see PIXI.Mesh
  16088. * @see PIXI.TilingSprite
  16089. * @memberof PIXI
  16090. */
  16091. var TextureMatrix = /** @class */ (function () {
  16092. /**
  16093. * @param texture - observed texture
  16094. * @param clampMargin - Changes frame clamping, 0.5 by default. Use -0.5 for extra border.
  16095. */
  16096. function TextureMatrix(texture, clampMargin) {
  16097. this._texture = texture;
  16098. this.mapCoord = new Matrix();
  16099. this.uClampFrame = new Float32Array(4);
  16100. this.uClampOffset = new Float32Array(2);
  16101. this._textureID = -1;
  16102. this._updateID = 0;
  16103. this.clampOffset = 0;
  16104. this.clampMargin = (typeof clampMargin === 'undefined') ? 0.5 : clampMargin;
  16105. this.isSimple = false;
  16106. }
  16107. Object.defineProperty(TextureMatrix.prototype, "texture", {
  16108. /** Texture property. */
  16109. get: function () {
  16110. return this._texture;
  16111. },
  16112. set: function (value) {
  16113. this._texture = value;
  16114. this._textureID = -1;
  16115. },
  16116. enumerable: false,
  16117. configurable: true
  16118. });
  16119. /**
  16120. * Multiplies uvs array to transform
  16121. * @param uvs - mesh uvs
  16122. * @param [out=uvs] - output
  16123. * @returns - output
  16124. */
  16125. TextureMatrix.prototype.multiplyUvs = function (uvs, out) {
  16126. if (out === undefined) {
  16127. out = uvs;
  16128. }
  16129. var mat = this.mapCoord;
  16130. for (var i = 0; i < uvs.length; i += 2) {
  16131. var x = uvs[i];
  16132. var y = uvs[i + 1];
  16133. out[i] = (x * mat.a) + (y * mat.c) + mat.tx;
  16134. out[i + 1] = (x * mat.b) + (y * mat.d) + mat.ty;
  16135. }
  16136. return out;
  16137. };
  16138. /**
  16139. * Updates matrices if texture was changed.
  16140. * @param [forceUpdate=false] - if true, matrices will be updated any case
  16141. * @returns - Whether or not it was updated
  16142. */
  16143. TextureMatrix.prototype.update = function (forceUpdate) {
  16144. var tex = this._texture;
  16145. if (!tex || !tex.valid) {
  16146. return false;
  16147. }
  16148. if (!forceUpdate
  16149. && this._textureID === tex._updateID) {
  16150. return false;
  16151. }
  16152. this._textureID = tex._updateID;
  16153. this._updateID++;
  16154. var uvs = tex._uvs;
  16155. this.mapCoord.set(uvs.x1 - uvs.x0, uvs.y1 - uvs.y0, uvs.x3 - uvs.x0, uvs.y3 - uvs.y0, uvs.x0, uvs.y0);
  16156. var orig = tex.orig;
  16157. var trim = tex.trim;
  16158. if (trim) {
  16159. tempMat$1.set(orig.width / trim.width, 0, 0, orig.height / trim.height, -trim.x / trim.width, -trim.y / trim.height);
  16160. this.mapCoord.append(tempMat$1);
  16161. }
  16162. var texBase = tex.baseTexture;
  16163. var frame = this.uClampFrame;
  16164. var margin = this.clampMargin / texBase.resolution;
  16165. var offset = this.clampOffset;
  16166. frame[0] = (tex._frame.x + margin + offset) / texBase.width;
  16167. frame[1] = (tex._frame.y + margin + offset) / texBase.height;
  16168. frame[2] = (tex._frame.x + tex._frame.width - margin + offset) / texBase.width;
  16169. frame[3] = (tex._frame.y + tex._frame.height - margin + offset) / texBase.height;
  16170. this.uClampOffset[0] = offset / texBase.realWidth;
  16171. this.uClampOffset[1] = offset / texBase.realHeight;
  16172. this.isSimple = tex._frame.width === texBase.width
  16173. && tex._frame.height === texBase.height
  16174. && tex.rotate === 0;
  16175. return true;
  16176. };
  16177. return TextureMatrix;
  16178. }());
  16179. /**
  16180. * This handles a Sprite acting as a mask, as opposed to a Graphic.
  16181. *
  16182. * WebGL only.
  16183. * @memberof PIXI
  16184. */
  16185. var SpriteMaskFilter = /** @class */ (function (_super) {
  16186. __extends$i(SpriteMaskFilter, _super);
  16187. /** @ignore */
  16188. function SpriteMaskFilter(vertexSrc, fragmentSrc, uniforms) {
  16189. var _this = this;
  16190. var sprite = null;
  16191. if (typeof vertexSrc !== 'string' && fragmentSrc === undefined && uniforms === undefined) {
  16192. sprite = vertexSrc;
  16193. vertexSrc = undefined;
  16194. fragmentSrc = undefined;
  16195. uniforms = undefined;
  16196. }
  16197. _this = _super.call(this, vertexSrc || vertex$4, fragmentSrc || fragment$7, uniforms) || this;
  16198. _this.maskSprite = sprite;
  16199. _this.maskMatrix = new Matrix();
  16200. return _this;
  16201. }
  16202. Object.defineProperty(SpriteMaskFilter.prototype, "maskSprite", {
  16203. /**
  16204. * Sprite mask
  16205. * @type {PIXI.DisplayObject}
  16206. */
  16207. get: function () {
  16208. return this._maskSprite;
  16209. },
  16210. set: function (value) {
  16211. this._maskSprite = value;
  16212. if (this._maskSprite) {
  16213. this._maskSprite.renderable = false;
  16214. }
  16215. },
  16216. enumerable: false,
  16217. configurable: true
  16218. });
  16219. /**
  16220. * Applies the filter
  16221. * @param filterManager - The renderer to retrieve the filter from
  16222. * @param input - The input render target.
  16223. * @param output - The target to output to.
  16224. * @param clearMode - Should the output be cleared before rendering to it.
  16225. */
  16226. SpriteMaskFilter.prototype.apply = function (filterManager, input, output, clearMode) {
  16227. var maskSprite = this._maskSprite;
  16228. var tex = maskSprite._texture;
  16229. if (!tex.valid) {
  16230. return;
  16231. }
  16232. if (!tex.uvMatrix) {
  16233. // margin = 0.0, let it bleed a bit, shader code becomes easier
  16234. // assuming that atlas textures were made with 1-pixel padding
  16235. tex.uvMatrix = new TextureMatrix(tex, 0.0);
  16236. }
  16237. tex.uvMatrix.update();
  16238. this.uniforms.npmAlpha = tex.baseTexture.alphaMode ? 0.0 : 1.0;
  16239. this.uniforms.mask = tex;
  16240. // get _normalized sprite texture coords_ and convert them to _normalized atlas texture coords_ with `prepend`
  16241. this.uniforms.otherMatrix = filterManager.calculateSpriteMatrix(this.maskMatrix, maskSprite)
  16242. .prepend(tex.uvMatrix.mapCoord);
  16243. this.uniforms.alpha = maskSprite.worldAlpha;
  16244. this.uniforms.maskClamp = tex.uvMatrix.uClampFrame;
  16245. filterManager.applyFilter(this, input, output, clearMode);
  16246. };
  16247. return SpriteMaskFilter;
  16248. }(Filter));
  16249. /**
  16250. * System plugin to the renderer to manage masks.
  16251. *
  16252. * There are three built-in types of masking:
  16253. * **Scissor Masking**: Scissor masking discards pixels that are outside of a rectangle called the scissor box. It is
  16254. * the most performant as the scissor test is inexpensive. However, it can only be used when the mask is rectangular.
  16255. * **Stencil Masking**: Stencil masking discards pixels that don't overlap with the pixels rendered into the stencil
  16256. * buffer. It is the next fastest option as it does not require rendering into a separate framebuffer. However, it does
  16257. * cause the mask to be rendered **twice** for each masking operation; hence, minimize the rendering cost of your masks.
  16258. * **Sprite Mask Filtering**: Sprite mask filtering discards pixels based on the red channel of the sprite-mask's
  16259. * texture. (Generally, the masking texture is grayscale). Using advanced techniques, you might be able to embed this
  16260. * type of masking in a custom shader - and hence, bypassing the masking system fully for performance wins.
  16261. *
  16262. * The best type of masking is auto-detected when you `push` one. To use scissor masking, you must pass in a `Graphics`
  16263. * object with just a rectangle drawn.
  16264. *
  16265. * ## Mask Stacks
  16266. *
  16267. * In the scene graph, masks can be applied recursively, i.e. a mask can be applied during a masking operation. The mask
  16268. * stack stores the currently applied masks in order. Each {@link PIXI.BaseRenderTexture} holds its own mask stack, i.e.
  16269. * when you switch render-textures, the old masks only applied when you switch back to rendering to the old render-target.
  16270. * @memberof PIXI
  16271. */
  16272. var MaskSystem = /** @class */ (function () {
  16273. /**
  16274. * @param renderer - The renderer this System works for.
  16275. */
  16276. function MaskSystem(renderer) {
  16277. this.renderer = renderer;
  16278. this.enableScissor = true;
  16279. this.alphaMaskPool = [];
  16280. this.maskDataPool = [];
  16281. this.maskStack = [];
  16282. this.alphaMaskIndex = 0;
  16283. }
  16284. /**
  16285. * Changes the mask stack that is used by this System.
  16286. * @param maskStack - The mask stack
  16287. */
  16288. MaskSystem.prototype.setMaskStack = function (maskStack) {
  16289. this.maskStack = maskStack;
  16290. this.renderer.scissor.setMaskStack(maskStack);
  16291. this.renderer.stencil.setMaskStack(maskStack);
  16292. };
  16293. /**
  16294. * Enables the mask and appends it to the current mask stack.
  16295. *
  16296. * NOTE: The batch renderer should be flushed beforehand to prevent pending renders from being masked.
  16297. * @param {PIXI.DisplayObject} target - Display Object to push the mask to
  16298. * @param {PIXI.MaskData|PIXI.Sprite|PIXI.Graphics|PIXI.DisplayObject} maskDataOrTarget - The masking data.
  16299. */
  16300. MaskSystem.prototype.push = function (target, maskDataOrTarget) {
  16301. var maskData = maskDataOrTarget;
  16302. if (!maskData.isMaskData) {
  16303. var d = this.maskDataPool.pop() || new MaskData();
  16304. d.pooled = true;
  16305. d.maskObject = maskDataOrTarget;
  16306. maskData = d;
  16307. }
  16308. var maskAbove = this.maskStack.length !== 0 ? this.maskStack[this.maskStack.length - 1] : null;
  16309. maskData.copyCountersOrReset(maskAbove);
  16310. maskData._colorMask = maskAbove ? maskAbove._colorMask : 0xf;
  16311. if (maskData.autoDetect) {
  16312. this.detect(maskData);
  16313. }
  16314. maskData._target = target;
  16315. if (maskData.type !== MASK_TYPES.SPRITE) {
  16316. this.maskStack.push(maskData);
  16317. }
  16318. if (maskData.enabled) {
  16319. switch (maskData.type) {
  16320. case MASK_TYPES.SCISSOR:
  16321. this.renderer.scissor.push(maskData);
  16322. break;
  16323. case MASK_TYPES.STENCIL:
  16324. this.renderer.stencil.push(maskData);
  16325. break;
  16326. case MASK_TYPES.SPRITE:
  16327. maskData.copyCountersOrReset(null);
  16328. this.pushSpriteMask(maskData);
  16329. break;
  16330. case MASK_TYPES.COLOR:
  16331. this.pushColorMask(maskData);
  16332. break;
  16333. }
  16334. }
  16335. if (maskData.type === MASK_TYPES.SPRITE) {
  16336. this.maskStack.push(maskData);
  16337. }
  16338. };
  16339. /**
  16340. * Removes the last mask from the mask stack and doesn't return it.
  16341. *
  16342. * NOTE: The batch renderer should be flushed beforehand to render the masked contents before the mask is removed.
  16343. * @param {PIXI.IMaskTarget} target - Display Object to pop the mask from
  16344. */
  16345. MaskSystem.prototype.pop = function (target) {
  16346. var maskData = this.maskStack.pop();
  16347. if (!maskData || maskData._target !== target) {
  16348. // TODO: add an assert when we have it
  16349. return;
  16350. }
  16351. if (maskData.enabled) {
  16352. switch (maskData.type) {
  16353. case MASK_TYPES.SCISSOR:
  16354. this.renderer.scissor.pop(maskData);
  16355. break;
  16356. case MASK_TYPES.STENCIL:
  16357. this.renderer.stencil.pop(maskData.maskObject);
  16358. break;
  16359. case MASK_TYPES.SPRITE:
  16360. this.popSpriteMask(maskData);
  16361. break;
  16362. case MASK_TYPES.COLOR:
  16363. this.popColorMask(maskData);
  16364. break;
  16365. }
  16366. }
  16367. maskData.reset();
  16368. if (maskData.pooled) {
  16369. this.maskDataPool.push(maskData);
  16370. }
  16371. if (this.maskStack.length !== 0) {
  16372. var maskCurrent = this.maskStack[this.maskStack.length - 1];
  16373. if (maskCurrent.type === MASK_TYPES.SPRITE && maskCurrent._filters) {
  16374. maskCurrent._filters[0].maskSprite = maskCurrent.maskObject;
  16375. }
  16376. }
  16377. };
  16378. /**
  16379. * Sets type of MaskData based on its maskObject.
  16380. * @param maskData
  16381. */
  16382. MaskSystem.prototype.detect = function (maskData) {
  16383. var maskObject = maskData.maskObject;
  16384. if (!maskObject) {
  16385. maskData.type = MASK_TYPES.COLOR;
  16386. }
  16387. else if (maskObject.isSprite) {
  16388. maskData.type = MASK_TYPES.SPRITE;
  16389. }
  16390. else if (this.enableScissor && this.renderer.scissor.testScissor(maskData)) {
  16391. maskData.type = MASK_TYPES.SCISSOR;
  16392. }
  16393. else {
  16394. maskData.type = MASK_TYPES.STENCIL;
  16395. }
  16396. };
  16397. /**
  16398. * Applies the Mask and adds it to the current filter stack.
  16399. * @param maskData - Sprite to be used as the mask.
  16400. */
  16401. MaskSystem.prototype.pushSpriteMask = function (maskData) {
  16402. var _a, _b;
  16403. var maskObject = maskData.maskObject;
  16404. var target = maskData._target;
  16405. var alphaMaskFilter = maskData._filters;
  16406. if (!alphaMaskFilter) {
  16407. alphaMaskFilter = this.alphaMaskPool[this.alphaMaskIndex];
  16408. if (!alphaMaskFilter) {
  16409. alphaMaskFilter = this.alphaMaskPool[this.alphaMaskIndex] = [new SpriteMaskFilter()];
  16410. }
  16411. }
  16412. var renderer = this.renderer;
  16413. var renderTextureSystem = renderer.renderTexture;
  16414. var resolution;
  16415. var multisample;
  16416. if (renderTextureSystem.current) {
  16417. var renderTexture = renderTextureSystem.current;
  16418. resolution = maskData.resolution || renderTexture.resolution;
  16419. multisample = (_a = maskData.multisample) !== null && _a !== void 0 ? _a : renderTexture.multisample;
  16420. }
  16421. else {
  16422. resolution = maskData.resolution || renderer.resolution;
  16423. multisample = (_b = maskData.multisample) !== null && _b !== void 0 ? _b : renderer.multisample;
  16424. }
  16425. alphaMaskFilter[0].resolution = resolution;
  16426. alphaMaskFilter[0].multisample = multisample;
  16427. alphaMaskFilter[0].maskSprite = maskObject;
  16428. var stashFilterArea = target.filterArea;
  16429. target.filterArea = maskObject.getBounds(true);
  16430. renderer.filter.push(target, alphaMaskFilter);
  16431. target.filterArea = stashFilterArea;
  16432. if (!maskData._filters) {
  16433. this.alphaMaskIndex++;
  16434. }
  16435. };
  16436. /**
  16437. * Removes the last filter from the filter stack and doesn't return it.
  16438. * @param maskData - Sprite to be used as the mask.
  16439. */
  16440. MaskSystem.prototype.popSpriteMask = function (maskData) {
  16441. this.renderer.filter.pop();
  16442. if (maskData._filters) {
  16443. maskData._filters[0].maskSprite = null;
  16444. }
  16445. else {
  16446. this.alphaMaskIndex--;
  16447. this.alphaMaskPool[this.alphaMaskIndex][0].maskSprite = null;
  16448. }
  16449. };
  16450. /**
  16451. * Pushes the color mask.
  16452. * @param maskData - The mask data
  16453. */
  16454. MaskSystem.prototype.pushColorMask = function (maskData) {
  16455. var currColorMask = maskData._colorMask;
  16456. var nextColorMask = maskData._colorMask = currColorMask & maskData.colorMask;
  16457. if (nextColorMask !== currColorMask) {
  16458. this.renderer.gl.colorMask((nextColorMask & 0x1) !== 0, (nextColorMask & 0x2) !== 0, (nextColorMask & 0x4) !== 0, (nextColorMask & 0x8) !== 0);
  16459. }
  16460. };
  16461. /**
  16462. * Pops the color mask.
  16463. * @param maskData - The mask data
  16464. */
  16465. MaskSystem.prototype.popColorMask = function (maskData) {
  16466. var currColorMask = maskData._colorMask;
  16467. var nextColorMask = this.maskStack.length > 0
  16468. ? this.maskStack[this.maskStack.length - 1]._colorMask : 0xf;
  16469. if (nextColorMask !== currColorMask) {
  16470. this.renderer.gl.colorMask((nextColorMask & 0x1) !== 0, (nextColorMask & 0x2) !== 0, (nextColorMask & 0x4) !== 0, (nextColorMask & 0x8) !== 0);
  16471. }
  16472. };
  16473. MaskSystem.prototype.destroy = function () {
  16474. this.renderer = null;
  16475. };
  16476. return MaskSystem;
  16477. }());
  16478. /**
  16479. * System plugin to the renderer to manage specific types of masking operations.
  16480. * @memberof PIXI
  16481. */
  16482. var AbstractMaskSystem = /** @class */ (function () {
  16483. /**
  16484. * @param renderer - The renderer this System works for.
  16485. */
  16486. function AbstractMaskSystem(renderer) {
  16487. this.renderer = renderer;
  16488. this.maskStack = [];
  16489. this.glConst = 0;
  16490. }
  16491. /** Gets count of masks of certain type. */
  16492. AbstractMaskSystem.prototype.getStackLength = function () {
  16493. return this.maskStack.length;
  16494. };
  16495. /**
  16496. * Changes the mask stack that is used by this System.
  16497. * @param {PIXI.MaskData[]} maskStack - The mask stack
  16498. */
  16499. AbstractMaskSystem.prototype.setMaskStack = function (maskStack) {
  16500. var gl = this.renderer.gl;
  16501. var curStackLen = this.getStackLength();
  16502. this.maskStack = maskStack;
  16503. var newStackLen = this.getStackLength();
  16504. if (newStackLen !== curStackLen) {
  16505. if (newStackLen === 0) {
  16506. gl.disable(this.glConst);
  16507. }
  16508. else {
  16509. gl.enable(this.glConst);
  16510. this._useCurrent();
  16511. }
  16512. }
  16513. };
  16514. /**
  16515. * Setup renderer to use the current mask data.
  16516. * @private
  16517. */
  16518. AbstractMaskSystem.prototype._useCurrent = function () {
  16519. // OVERWRITE;
  16520. };
  16521. /** Destroys the mask stack. */
  16522. AbstractMaskSystem.prototype.destroy = function () {
  16523. this.renderer = null;
  16524. this.maskStack = null;
  16525. };
  16526. return AbstractMaskSystem;
  16527. }());
  16528. var tempMatrix$1 = new Matrix();
  16529. var rectPool = [];
  16530. /**
  16531. * System plugin to the renderer to manage scissor masking.
  16532. *
  16533. * Scissor masking discards pixels outside of a rectangle called the scissor box. The scissor box is in the framebuffer
  16534. * viewport's space; however, the mask's rectangle is projected from world-space to viewport space automatically
  16535. * by this system.
  16536. * @memberof PIXI
  16537. */
  16538. var ScissorSystem = /** @class */ (function (_super) {
  16539. __extends$i(ScissorSystem, _super);
  16540. /**
  16541. * @param {PIXI.Renderer} renderer - The renderer this System works for.
  16542. */
  16543. function ScissorSystem(renderer) {
  16544. var _this = _super.call(this, renderer) || this;
  16545. _this.glConst = settings.ADAPTER.getWebGLRenderingContext().SCISSOR_TEST;
  16546. return _this;
  16547. }
  16548. ScissorSystem.prototype.getStackLength = function () {
  16549. var maskData = this.maskStack[this.maskStack.length - 1];
  16550. if (maskData) {
  16551. return maskData._scissorCounter;
  16552. }
  16553. return 0;
  16554. };
  16555. /**
  16556. * evaluates _boundsTransformed, _scissorRect for MaskData
  16557. * @param maskData
  16558. */
  16559. ScissorSystem.prototype.calcScissorRect = function (maskData) {
  16560. var _a;
  16561. if (maskData._scissorRectLocal) {
  16562. return;
  16563. }
  16564. var prevData = maskData._scissorRect;
  16565. var maskObject = maskData.maskObject;
  16566. var renderer = this.renderer;
  16567. var renderTextureSystem = renderer.renderTexture;
  16568. var rect = maskObject.getBounds(true, (_a = rectPool.pop()) !== null && _a !== void 0 ? _a : new Rectangle());
  16569. this.roundFrameToPixels(rect, renderTextureSystem.current ? renderTextureSystem.current.resolution : renderer.resolution, renderTextureSystem.sourceFrame, renderTextureSystem.destinationFrame, renderer.projection.transform);
  16570. if (prevData) {
  16571. rect.fit(prevData);
  16572. }
  16573. maskData._scissorRectLocal = rect;
  16574. };
  16575. ScissorSystem.isMatrixRotated = function (matrix) {
  16576. if (!matrix) {
  16577. return false;
  16578. }
  16579. var a = matrix.a, b = matrix.b, c = matrix.c, d = matrix.d;
  16580. // Skip if skew/rotation present in matrix, except for multiple of 90° rotation. If rotation
  16581. // is a multiple of 90°, then either pair of (b,c) or (a,d) will be (0,0).
  16582. return ((Math.abs(b) > 1e-4 || Math.abs(c) > 1e-4)
  16583. && (Math.abs(a) > 1e-4 || Math.abs(d) > 1e-4));
  16584. };
  16585. /**
  16586. * Test, whether the object can be scissor mask with current renderer projection.
  16587. * Calls "calcScissorRect()" if its true.
  16588. * @param maskData - mask data
  16589. * @returns whether Whether the object can be scissor mask
  16590. */
  16591. ScissorSystem.prototype.testScissor = function (maskData) {
  16592. var maskObject = maskData.maskObject;
  16593. if (!maskObject.isFastRect || !maskObject.isFastRect()) {
  16594. return false;
  16595. }
  16596. if (ScissorSystem.isMatrixRotated(maskObject.worldTransform)) {
  16597. return false;
  16598. }
  16599. if (ScissorSystem.isMatrixRotated(this.renderer.projection.transform)) {
  16600. return false;
  16601. }
  16602. this.calcScissorRect(maskData);
  16603. var rect = maskData._scissorRectLocal;
  16604. return rect.width > 0 && rect.height > 0;
  16605. };
  16606. ScissorSystem.prototype.roundFrameToPixels = function (frame, resolution, bindingSourceFrame, bindingDestinationFrame, transform) {
  16607. if (ScissorSystem.isMatrixRotated(transform)) {
  16608. return;
  16609. }
  16610. transform = transform ? tempMatrix$1.copyFrom(transform) : tempMatrix$1.identity();
  16611. // Get forward transform from world space to screen space
  16612. transform
  16613. .translate(-bindingSourceFrame.x, -bindingSourceFrame.y)
  16614. .scale(bindingDestinationFrame.width / bindingSourceFrame.width, bindingDestinationFrame.height / bindingSourceFrame.height)
  16615. .translate(bindingDestinationFrame.x, bindingDestinationFrame.y);
  16616. // Convert frame to screen space
  16617. this.renderer.filter.transformAABB(transform, frame);
  16618. frame.fit(bindingDestinationFrame);
  16619. frame.x = Math.round(frame.x * resolution);
  16620. frame.y = Math.round(frame.y * resolution);
  16621. frame.width = Math.round(frame.width * resolution);
  16622. frame.height = Math.round(frame.height * resolution);
  16623. };
  16624. /**
  16625. * Applies the Mask and adds it to the current stencil stack.
  16626. * @author alvin
  16627. * @param maskData - The mask data.
  16628. */
  16629. ScissorSystem.prototype.push = function (maskData) {
  16630. if (!maskData._scissorRectLocal) {
  16631. this.calcScissorRect(maskData);
  16632. }
  16633. var gl = this.renderer.gl;
  16634. if (!maskData._scissorRect) {
  16635. gl.enable(gl.SCISSOR_TEST);
  16636. }
  16637. maskData._scissorCounter++;
  16638. maskData._scissorRect = maskData._scissorRectLocal;
  16639. this._useCurrent();
  16640. };
  16641. /**
  16642. * This should be called after a mask is popped off the mask stack. It will rebind the scissor box to be latest with the
  16643. * last mask in the stack.
  16644. *
  16645. * This can also be called when you directly modify the scissor box and want to restore PixiJS state.
  16646. * @param maskData - The mask data.
  16647. */
  16648. ScissorSystem.prototype.pop = function (maskData) {
  16649. var gl = this.renderer.gl;
  16650. if (maskData) {
  16651. rectPool.push(maskData._scissorRectLocal);
  16652. }
  16653. if (this.getStackLength() > 0) {
  16654. this._useCurrent();
  16655. }
  16656. else {
  16657. gl.disable(gl.SCISSOR_TEST);
  16658. }
  16659. };
  16660. /**
  16661. * Setup renderer to use the current scissor data.
  16662. * @private
  16663. */
  16664. ScissorSystem.prototype._useCurrent = function () {
  16665. var rect = this.maskStack[this.maskStack.length - 1]._scissorRect;
  16666. var y;
  16667. if (this.renderer.renderTexture.current) {
  16668. y = rect.y;
  16669. }
  16670. else {
  16671. // flipY. In future we'll have it over renderTextures as an option
  16672. y = this.renderer.height - rect.height - rect.y;
  16673. }
  16674. this.renderer.gl.scissor(rect.x, y, rect.width, rect.height);
  16675. };
  16676. return ScissorSystem;
  16677. }(AbstractMaskSystem));
  16678. /**
  16679. * System plugin to the renderer to manage stencils (used for masks).
  16680. * @memberof PIXI
  16681. */
  16682. var StencilSystem = /** @class */ (function (_super) {
  16683. __extends$i(StencilSystem, _super);
  16684. /**
  16685. * @param renderer - The renderer this System works for.
  16686. */
  16687. function StencilSystem(renderer) {
  16688. var _this = _super.call(this, renderer) || this;
  16689. _this.glConst = settings.ADAPTER.getWebGLRenderingContext().STENCIL_TEST;
  16690. return _this;
  16691. }
  16692. StencilSystem.prototype.getStackLength = function () {
  16693. var maskData = this.maskStack[this.maskStack.length - 1];
  16694. if (maskData) {
  16695. return maskData._stencilCounter;
  16696. }
  16697. return 0;
  16698. };
  16699. /**
  16700. * Applies the Mask and adds it to the current stencil stack.
  16701. * @param maskData - The mask data
  16702. */
  16703. StencilSystem.prototype.push = function (maskData) {
  16704. var maskObject = maskData.maskObject;
  16705. var gl = this.renderer.gl;
  16706. var prevMaskCount = maskData._stencilCounter;
  16707. if (prevMaskCount === 0) {
  16708. // force use stencil texture in current framebuffer
  16709. this.renderer.framebuffer.forceStencil();
  16710. gl.clearStencil(0);
  16711. gl.clear(gl.STENCIL_BUFFER_BIT);
  16712. gl.enable(gl.STENCIL_TEST);
  16713. }
  16714. maskData._stencilCounter++;
  16715. var colorMask = maskData._colorMask;
  16716. if (colorMask !== 0) {
  16717. maskData._colorMask = 0;
  16718. gl.colorMask(false, false, false, false);
  16719. }
  16720. // Increment the reference stencil value where the new mask overlaps with the old ones.
  16721. gl.stencilFunc(gl.EQUAL, prevMaskCount, 0xFFFFFFFF);
  16722. gl.stencilOp(gl.KEEP, gl.KEEP, gl.INCR);
  16723. maskObject.renderable = true;
  16724. maskObject.render(this.renderer);
  16725. this.renderer.batch.flush();
  16726. maskObject.renderable = false;
  16727. if (colorMask !== 0) {
  16728. maskData._colorMask = colorMask;
  16729. gl.colorMask((colorMask & 1) !== 0, (colorMask & 2) !== 0, (colorMask & 4) !== 0, (colorMask & 8) !== 0);
  16730. }
  16731. this._useCurrent();
  16732. };
  16733. /**
  16734. * Pops stencil mask. MaskData is already removed from stack
  16735. * @param {PIXI.DisplayObject} maskObject - object of popped mask data
  16736. */
  16737. StencilSystem.prototype.pop = function (maskObject) {
  16738. var gl = this.renderer.gl;
  16739. if (this.getStackLength() === 0) {
  16740. // the stack is empty!
  16741. gl.disable(gl.STENCIL_TEST);
  16742. }
  16743. else {
  16744. var maskData = this.maskStack.length !== 0 ? this.maskStack[this.maskStack.length - 1] : null;
  16745. var colorMask = maskData ? maskData._colorMask : 0xf;
  16746. if (colorMask !== 0) {
  16747. maskData._colorMask = 0;
  16748. gl.colorMask(false, false, false, false);
  16749. }
  16750. // Decrement the reference stencil value where the popped mask overlaps with the other ones
  16751. gl.stencilOp(gl.KEEP, gl.KEEP, gl.DECR);
  16752. maskObject.renderable = true;
  16753. maskObject.render(this.renderer);
  16754. this.renderer.batch.flush();
  16755. maskObject.renderable = false;
  16756. if (colorMask !== 0) {
  16757. maskData._colorMask = colorMask;
  16758. gl.colorMask((colorMask & 0x1) !== 0, (colorMask & 0x2) !== 0, (colorMask & 0x4) !== 0, (colorMask & 0x8) !== 0);
  16759. }
  16760. this._useCurrent();
  16761. }
  16762. };
  16763. /**
  16764. * Setup renderer to use the current stencil data.
  16765. * @private
  16766. */
  16767. StencilSystem.prototype._useCurrent = function () {
  16768. var gl = this.renderer.gl;
  16769. gl.stencilFunc(gl.EQUAL, this.getStackLength(), 0xFFFFFFFF);
  16770. gl.stencilOp(gl.KEEP, gl.KEEP, gl.KEEP);
  16771. };
  16772. return StencilSystem;
  16773. }(AbstractMaskSystem));
  16774. /**
  16775. * System plugin to the renderer to manage the projection matrix.
  16776. *
  16777. * The `projectionMatrix` is a global uniform provided to all shaders. It is used to transform points in world space to
  16778. * normalized device coordinates.
  16779. * @memberof PIXI
  16780. */
  16781. var ProjectionSystem = /** @class */ (function () {
  16782. /** @param renderer - The renderer this System works for. */
  16783. function ProjectionSystem(renderer) {
  16784. this.renderer = renderer;
  16785. this.destinationFrame = null;
  16786. this.sourceFrame = null;
  16787. this.defaultFrame = null;
  16788. this.projectionMatrix = new Matrix();
  16789. this.transform = null;
  16790. }
  16791. /**
  16792. * Updates the projection-matrix based on the sourceFrame → destinationFrame mapping provided.
  16793. *
  16794. * NOTE: It is expected you call `renderer.framebuffer.setViewport(destinationFrame)` after this. This is because
  16795. * the framebuffer viewport converts shader vertex output in normalized device coordinates to window coordinates.
  16796. *
  16797. * NOTE-2: {@link RenderTextureSystem#bind} updates the projection-matrix when you bind a render-texture. It is expected
  16798. * that you dirty the current bindings when calling this manually.
  16799. * @param destinationFrame - The rectangle in the render-target to render the contents into. If rendering to the canvas,
  16800. * the origin is on the top-left; if rendering to a render-texture, the origin is on the bottom-left.
  16801. * @param sourceFrame - The rectangle in world space that contains the contents being rendered.
  16802. * @param resolution - The resolution of the render-target, which is the ratio of
  16803. * world-space (or CSS) pixels to physical pixels.
  16804. * @param root - Whether the render-target is the screen. This is required because rendering to textures
  16805. * is y-flipped (i.e. upside down relative to the screen).
  16806. */
  16807. ProjectionSystem.prototype.update = function (destinationFrame, sourceFrame, resolution, root) {
  16808. this.destinationFrame = destinationFrame || this.destinationFrame || this.defaultFrame;
  16809. this.sourceFrame = sourceFrame || this.sourceFrame || destinationFrame;
  16810. // Calculate object-space to clip-space projection
  16811. this.calculateProjection(this.destinationFrame, this.sourceFrame, resolution, root);
  16812. if (this.transform) {
  16813. this.projectionMatrix.append(this.transform);
  16814. }
  16815. var renderer = this.renderer;
  16816. renderer.globalUniforms.uniforms.projectionMatrix = this.projectionMatrix;
  16817. renderer.globalUniforms.update();
  16818. // this will work for now
  16819. // but would be sweet to stick and even on the global uniforms..
  16820. if (renderer.shader.shader) {
  16821. renderer.shader.syncUniformGroup(renderer.shader.shader.uniforms.globals);
  16822. }
  16823. };
  16824. /**
  16825. * Calculates the `projectionMatrix` to map points inside `sourceFrame` to inside `destinationFrame`.
  16826. * @param _destinationFrame - The destination frame in the render-target.
  16827. * @param sourceFrame - The source frame in world space.
  16828. * @param _resolution - The render-target's resolution, i.e. ratio of CSS to physical pixels.
  16829. * @param root - Whether rendering into the screen. Otherwise, if rendering to a framebuffer, the projection
  16830. * is y-flipped.
  16831. */
  16832. ProjectionSystem.prototype.calculateProjection = function (_destinationFrame, sourceFrame, _resolution, root) {
  16833. var pm = this.projectionMatrix;
  16834. var sign = !root ? 1 : -1;
  16835. pm.identity();
  16836. pm.a = (1 / sourceFrame.width * 2);
  16837. pm.d = sign * (1 / sourceFrame.height * 2);
  16838. pm.tx = -1 - (sourceFrame.x * pm.a);
  16839. pm.ty = -sign - (sourceFrame.y * pm.d);
  16840. };
  16841. /**
  16842. * Sets the transform of the active render target to the given matrix.
  16843. * @param _matrix - The transformation matrix
  16844. */
  16845. ProjectionSystem.prototype.setTransform = function (_matrix) {
  16846. // this._activeRenderTarget.transform = matrix;
  16847. };
  16848. ProjectionSystem.prototype.destroy = function () {
  16849. this.renderer = null;
  16850. };
  16851. return ProjectionSystem;
  16852. }());
  16853. // Temporary rectangle for assigned sourceFrame or destinationFrame
  16854. var tempRect = new Rectangle();
  16855. // Temporary rectangle for renderTexture destinationFrame
  16856. var tempRect2 = new Rectangle();
  16857. /* eslint-disable max-len */
  16858. /**
  16859. * System plugin to the renderer to manage render textures.
  16860. *
  16861. * Should be added after FramebufferSystem
  16862. *
  16863. * ### Frames
  16864. *
  16865. * The `RenderTextureSystem` holds a sourceFrame → destinationFrame projection. The following table explains the different
  16866. * coordinate spaces used:
  16867. *
  16868. * | Frame | Description | Coordinate System |
  16869. * | ---------------------- | ---------------------------------------------------------------- | ------------------------------------------------------- |
  16870. * | sourceFrame | The rectangle inside of which display-objects are being rendered | **World Space**: The origin on the top-left |
  16871. * | destinationFrame | The rectangle in the render-target (canvas or texture) into which contents should be rendered | If rendering to the canvas, this is in screen space and the origin is on the top-left. If rendering to a render-texture, this is in its base-texture's space with the origin on the bottom-left. |
  16872. * | viewportFrame | The framebuffer viewport corresponding to the destination-frame | **Window Coordinates**: The origin is always on the bottom-left. |
  16873. * @memberof PIXI
  16874. */
  16875. var RenderTextureSystem = /** @class */ (function () {
  16876. /**
  16877. * @param renderer - The renderer this System works for.
  16878. */
  16879. function RenderTextureSystem(renderer) {
  16880. this.renderer = renderer;
  16881. this.clearColor = renderer._backgroundColorRgba;
  16882. this.defaultMaskStack = [];
  16883. this.current = null;
  16884. this.sourceFrame = new Rectangle();
  16885. this.destinationFrame = new Rectangle();
  16886. this.viewportFrame = new Rectangle();
  16887. }
  16888. /**
  16889. * Bind the current render texture.
  16890. * @param renderTexture - RenderTexture to bind, by default its `null` - the screen.
  16891. * @param sourceFrame - Part of world that is mapped to the renderTexture.
  16892. * @param destinationFrame - Part of renderTexture, by default it has the same size as sourceFrame.
  16893. */
  16894. RenderTextureSystem.prototype.bind = function (renderTexture, sourceFrame, destinationFrame) {
  16895. if (renderTexture === void 0) { renderTexture = null; }
  16896. var renderer = this.renderer;
  16897. this.current = renderTexture;
  16898. var baseTexture;
  16899. var framebuffer;
  16900. var resolution;
  16901. if (renderTexture) {
  16902. baseTexture = renderTexture.baseTexture;
  16903. resolution = baseTexture.resolution;
  16904. if (!sourceFrame) {
  16905. tempRect.width = renderTexture.frame.width;
  16906. tempRect.height = renderTexture.frame.height;
  16907. sourceFrame = tempRect;
  16908. }
  16909. if (!destinationFrame) {
  16910. tempRect2.x = renderTexture.frame.x;
  16911. tempRect2.y = renderTexture.frame.y;
  16912. tempRect2.width = sourceFrame.width;
  16913. tempRect2.height = sourceFrame.height;
  16914. destinationFrame = tempRect2;
  16915. }
  16916. framebuffer = baseTexture.framebuffer;
  16917. }
  16918. else {
  16919. resolution = renderer.resolution;
  16920. if (!sourceFrame) {
  16921. tempRect.width = renderer.screen.width;
  16922. tempRect.height = renderer.screen.height;
  16923. sourceFrame = tempRect;
  16924. }
  16925. if (!destinationFrame) {
  16926. destinationFrame = tempRect;
  16927. destinationFrame.width = sourceFrame.width;
  16928. destinationFrame.height = sourceFrame.height;
  16929. }
  16930. }
  16931. var viewportFrame = this.viewportFrame;
  16932. viewportFrame.x = destinationFrame.x * resolution;
  16933. viewportFrame.y = destinationFrame.y * resolution;
  16934. viewportFrame.width = destinationFrame.width * resolution;
  16935. viewportFrame.height = destinationFrame.height * resolution;
  16936. if (!renderTexture) {
  16937. viewportFrame.y = renderer.view.height - (viewportFrame.y + viewportFrame.height);
  16938. }
  16939. viewportFrame.ceil();
  16940. this.renderer.framebuffer.bind(framebuffer, viewportFrame);
  16941. this.renderer.projection.update(destinationFrame, sourceFrame, resolution, !framebuffer);
  16942. if (renderTexture) {
  16943. this.renderer.mask.setMaskStack(baseTexture.maskStack);
  16944. }
  16945. else {
  16946. this.renderer.mask.setMaskStack(this.defaultMaskStack);
  16947. }
  16948. this.sourceFrame.copyFrom(sourceFrame);
  16949. this.destinationFrame.copyFrom(destinationFrame);
  16950. };
  16951. /**
  16952. * Erases the render texture and fills the drawing area with a colour.
  16953. * @param clearColor - The color as rgba, default to use the renderer backgroundColor
  16954. * @param [mask=BUFFER_BITS.COLOR | BUFFER_BITS.DEPTH] - Bitwise OR of masks
  16955. * that indicate the buffers to be cleared, by default COLOR and DEPTH buffers.
  16956. */
  16957. RenderTextureSystem.prototype.clear = function (clearColor, mask) {
  16958. if (this.current) {
  16959. clearColor = clearColor || this.current.baseTexture.clearColor;
  16960. }
  16961. else {
  16962. clearColor = clearColor || this.clearColor;
  16963. }
  16964. var destinationFrame = this.destinationFrame;
  16965. var baseFrame = this.current ? this.current.baseTexture : this.renderer.screen;
  16966. var clearMask = destinationFrame.width !== baseFrame.width || destinationFrame.height !== baseFrame.height;
  16967. if (clearMask) {
  16968. var _a = this.viewportFrame, x = _a.x, y = _a.y, width = _a.width, height = _a.height;
  16969. x = Math.round(x);
  16970. y = Math.round(y);
  16971. width = Math.round(width);
  16972. height = Math.round(height);
  16973. // TODO: ScissorSystem should cache whether the scissor test is enabled or not.
  16974. this.renderer.gl.enable(this.renderer.gl.SCISSOR_TEST);
  16975. this.renderer.gl.scissor(x, y, width, height);
  16976. }
  16977. this.renderer.framebuffer.clear(clearColor[0], clearColor[1], clearColor[2], clearColor[3], mask);
  16978. if (clearMask) {
  16979. // Restore the scissor box
  16980. this.renderer.scissor.pop();
  16981. }
  16982. };
  16983. RenderTextureSystem.prototype.resize = function () {
  16984. // resize the root only!
  16985. this.bind(null);
  16986. };
  16987. /** Resets render-texture state. */
  16988. RenderTextureSystem.prototype.reset = function () {
  16989. this.bind(null);
  16990. };
  16991. RenderTextureSystem.prototype.destroy = function () {
  16992. this.renderer = null;
  16993. };
  16994. return RenderTextureSystem;
  16995. }());
  16996. function uboUpdate(_ud, _uv, _renderer, _syncData, buffer) {
  16997. _renderer.buffer.update(buffer);
  16998. }
  16999. // cv = CachedValue
  17000. // v = value
  17001. // ud = uniformData
  17002. // uv = uniformValue
  17003. // l = location
  17004. var UBO_TO_SINGLE_SETTERS = {
  17005. float: "\n data[offset] = v;\n ",
  17006. vec2: "\n data[offset] = v[0];\n data[offset+1] = v[1];\n ",
  17007. vec3: "\n data[offset] = v[0];\n data[offset+1] = v[1];\n data[offset+2] = v[2];\n\n ",
  17008. vec4: "\n data[offset] = v[0];\n data[offset+1] = v[1];\n data[offset+2] = v[2];\n data[offset+3] = v[3];\n ",
  17009. mat2: "\n data[offset] = v[0];\n data[offset+1] = v[1];\n\n data[offset+4] = v[2];\n data[offset+5] = v[3];\n ",
  17010. mat3: "\n data[offset] = v[0];\n data[offset+1] = v[1];\n data[offset+2] = v[2];\n\n data[offset + 4] = v[3];\n data[offset + 5] = v[4];\n data[offset + 6] = v[5];\n\n data[offset + 8] = v[6];\n data[offset + 9] = v[7];\n data[offset + 10] = v[8];\n ",
  17011. mat4: "\n for(var i = 0; i < 16; i++)\n {\n data[offset + i] = v[i];\n }\n "
  17012. };
  17013. var GLSL_TO_STD40_SIZE = {
  17014. float: 4,
  17015. vec2: 8,
  17016. vec3: 12,
  17017. vec4: 16,
  17018. int: 4,
  17019. ivec2: 8,
  17020. ivec3: 12,
  17021. ivec4: 16,
  17022. uint: 4,
  17023. uvec2: 8,
  17024. uvec3: 12,
  17025. uvec4: 16,
  17026. bool: 4,
  17027. bvec2: 8,
  17028. bvec3: 12,
  17029. bvec4: 16,
  17030. mat2: 16 * 2,
  17031. mat3: 16 * 3,
  17032. mat4: 16 * 4,
  17033. };
  17034. /**
  17035. * logic originally from here: https://github.com/sketchpunk/FunWithWebGL2/blob/master/lesson_022/Shaders.js
  17036. * rewrote it, but this was a great starting point to get a solid understanding of whats going on :)
  17037. * @ignore
  17038. * @param uniformData
  17039. */
  17040. function createUBOElements(uniformData) {
  17041. var uboElements = uniformData.map(function (data) {
  17042. return ({
  17043. data: data,
  17044. offset: 0,
  17045. dataLen: 0,
  17046. dirty: 0
  17047. });
  17048. });
  17049. var size = 0;
  17050. var chunkSize = 0;
  17051. var offset = 0;
  17052. for (var i = 0; i < uboElements.length; i++) {
  17053. var uboElement = uboElements[i];
  17054. size = GLSL_TO_STD40_SIZE[uboElement.data.type];
  17055. if (uboElement.data.size > 1) {
  17056. size = Math.max(size, 16) * uboElement.data.size;
  17057. }
  17058. uboElement.dataLen = size;
  17059. // add some size offset..
  17060. // must align to the nearest 16 bytes or internally nearest round size
  17061. if (chunkSize % size !== 0 && chunkSize < 16) {
  17062. // diff required to line up..
  17063. var lineUpValue = (chunkSize % size) % 16;
  17064. chunkSize += lineUpValue;
  17065. offset += lineUpValue;
  17066. }
  17067. if ((chunkSize + size) > 16) {
  17068. offset = Math.ceil(offset / 16) * 16;
  17069. uboElement.offset = offset;
  17070. offset += size;
  17071. chunkSize = size;
  17072. }
  17073. else {
  17074. uboElement.offset = offset;
  17075. chunkSize += size;
  17076. offset += size;
  17077. }
  17078. }
  17079. offset = Math.ceil(offset / 16) * 16;
  17080. return { uboElements: uboElements, size: offset };
  17081. }
  17082. function getUBOData(uniforms, uniformData) {
  17083. var usedUniformDatas = [];
  17084. // build..
  17085. for (var i in uniforms) {
  17086. if (uniformData[i]) {
  17087. usedUniformDatas.push(uniformData[i]);
  17088. }
  17089. }
  17090. // sort them out by index!
  17091. usedUniformDatas.sort(function (a, b) { return a.index - b.index; });
  17092. return usedUniformDatas;
  17093. }
  17094. function generateUniformBufferSync(group, uniformData) {
  17095. if (!group.autoManage) {
  17096. // if the group is nott automatically managed, we don't need to generate a special function for it...
  17097. return { size: 0, syncFunc: uboUpdate };
  17098. }
  17099. var usedUniformDatas = getUBOData(group.uniforms, uniformData);
  17100. var _a = createUBOElements(usedUniformDatas), uboElements = _a.uboElements, size = _a.size;
  17101. var funcFragments = ["\n var v = null;\n var v2 = null;\n var cv = null;\n var t = 0;\n var gl = renderer.gl\n var index = 0;\n var data = buffer.data;\n "];
  17102. for (var i = 0; i < uboElements.length; i++) {
  17103. var uboElement = uboElements[i];
  17104. var uniform = group.uniforms[uboElement.data.name];
  17105. var name = uboElement.data.name;
  17106. var parsed = false;
  17107. for (var j = 0; j < uniformParsers.length; j++) {
  17108. var uniformParser = uniformParsers[j];
  17109. if (uniformParser.codeUbo && uniformParser.test(uboElement.data, uniform)) {
  17110. funcFragments.push("offset = " + uboElement.offset / 4 + ";", uniformParsers[j].codeUbo(uboElement.data.name, uniform));
  17111. parsed = true;
  17112. break;
  17113. }
  17114. }
  17115. if (!parsed) {
  17116. if (uboElement.data.size > 1) {
  17117. var size_1 = mapSize(uboElement.data.type);
  17118. var rowSize = Math.max(GLSL_TO_STD40_SIZE[uboElement.data.type] / 16, 1);
  17119. var elementSize = size_1 / rowSize;
  17120. var remainder = (4 - (elementSize % 4)) % 4;
  17121. funcFragments.push("\n cv = ud." + name + ".value;\n v = uv." + name + ";\n offset = " + uboElement.offset / 4 + ";\n\n t = 0;\n\n for(var i=0; i < " + uboElement.data.size * rowSize + "; i++)\n {\n for(var j = 0; j < " + elementSize + "; j++)\n {\n data[offset++] = v[t++];\n }\n offset += " + remainder + ";\n }\n\n ");
  17122. }
  17123. else {
  17124. var template = UBO_TO_SINGLE_SETTERS[uboElement.data.type];
  17125. funcFragments.push("\n cv = ud." + name + ".value;\n v = uv." + name + ";\n offset = " + uboElement.offset / 4 + ";\n " + template + ";\n ");
  17126. }
  17127. }
  17128. }
  17129. funcFragments.push("\n renderer.buffer.update(buffer);\n ");
  17130. return {
  17131. size: size,
  17132. // eslint-disable-next-line no-new-func
  17133. syncFunc: new Function('ud', 'uv', 'renderer', 'syncData', 'buffer', funcFragments.join('\n'))
  17134. };
  17135. }
  17136. /**
  17137. * @private
  17138. */
  17139. var IGLUniformData = /** @class */ (function () {
  17140. function IGLUniformData() {
  17141. }
  17142. return IGLUniformData;
  17143. }());
  17144. /**
  17145. * Helper class to create a WebGL Program
  17146. * @memberof PIXI
  17147. */
  17148. var GLProgram = /** @class */ (function () {
  17149. /**
  17150. * Makes a new Pixi program.
  17151. * @param program - webgl program
  17152. * @param uniformData - uniforms
  17153. */
  17154. function GLProgram(program, uniformData) {
  17155. this.program = program;
  17156. this.uniformData = uniformData;
  17157. this.uniformGroups = {};
  17158. this.uniformDirtyGroups = {};
  17159. this.uniformBufferBindings = {};
  17160. }
  17161. /** Destroys this program. */
  17162. GLProgram.prototype.destroy = function () {
  17163. this.uniformData = null;
  17164. this.uniformGroups = null;
  17165. this.uniformDirtyGroups = null;
  17166. this.uniformBufferBindings = null;
  17167. this.program = null;
  17168. };
  17169. return GLProgram;
  17170. }());
  17171. /**
  17172. * returns the attribute data from the program
  17173. * @private
  17174. * @param {WebGLProgram} [program] - the WebGL program
  17175. * @param {WebGLRenderingContext} [gl] - the WebGL context
  17176. * @returns {object} the attribute data for this program
  17177. */
  17178. function getAttributeData(program, gl) {
  17179. var attributes = {};
  17180. var totalAttributes = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES);
  17181. for (var i = 0; i < totalAttributes; i++) {
  17182. var attribData = gl.getActiveAttrib(program, i);
  17183. if (attribData.name.indexOf('gl_') === 0) {
  17184. continue;
  17185. }
  17186. var type = mapType(gl, attribData.type);
  17187. var data = {
  17188. type: type,
  17189. name: attribData.name,
  17190. size: mapSize(type),
  17191. location: gl.getAttribLocation(program, attribData.name),
  17192. };
  17193. attributes[attribData.name] = data;
  17194. }
  17195. return attributes;
  17196. }
  17197. /**
  17198. * returns the uniform data from the program
  17199. * @private
  17200. * @param program - the webgl program
  17201. * @param gl - the WebGL context
  17202. * @returns {object} the uniform data for this program
  17203. */
  17204. function getUniformData(program, gl) {
  17205. var uniforms = {};
  17206. var totalUniforms = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS);
  17207. for (var i = 0; i < totalUniforms; i++) {
  17208. var uniformData = gl.getActiveUniform(program, i);
  17209. var name = uniformData.name.replace(/\[.*?\]$/, '');
  17210. var isArray = !!(uniformData.name.match(/\[.*?\]$/));
  17211. var type = mapType(gl, uniformData.type);
  17212. uniforms[name] = {
  17213. name: name,
  17214. index: i,
  17215. type: type,
  17216. size: uniformData.size,
  17217. isArray: isArray,
  17218. value: defaultValue(type, uniformData.size),
  17219. };
  17220. }
  17221. return uniforms;
  17222. }
  17223. /**
  17224. * generates a WebGL Program object from a high level Pixi Program.
  17225. * @param gl - a rendering context on which to generate the program
  17226. * @param program - the high level Pixi Program.
  17227. */
  17228. function generateProgram(gl, program) {
  17229. var glVertShader = compileShader(gl, gl.VERTEX_SHADER, program.vertexSrc);
  17230. var glFragShader = compileShader(gl, gl.FRAGMENT_SHADER, program.fragmentSrc);
  17231. var webGLProgram = gl.createProgram();
  17232. gl.attachShader(webGLProgram, glVertShader);
  17233. gl.attachShader(webGLProgram, glFragShader);
  17234. gl.linkProgram(webGLProgram);
  17235. if (!gl.getProgramParameter(webGLProgram, gl.LINK_STATUS)) {
  17236. logProgramError(gl, webGLProgram, glVertShader, glFragShader);
  17237. }
  17238. program.attributeData = getAttributeData(webGLProgram, gl);
  17239. program.uniformData = getUniformData(webGLProgram, gl);
  17240. // GLSL 1.00: bind attributes sorted by name in ascending order
  17241. // GLSL 3.00: don't change the attribute locations that where chosen by the compiler
  17242. // or assigned by the layout specifier in the shader source code
  17243. if (!(/^[ \t]*#[ \t]*version[ \t]+300[ \t]+es[ \t]*$/m).test(program.vertexSrc)) {
  17244. var keys = Object.keys(program.attributeData);
  17245. keys.sort(function (a, b) { return (a > b) ? 1 : -1; }); // eslint-disable-line no-confusing-arrow
  17246. for (var i = 0; i < keys.length; i++) {
  17247. program.attributeData[keys[i]].location = i;
  17248. gl.bindAttribLocation(webGLProgram, i, keys[i]);
  17249. }
  17250. gl.linkProgram(webGLProgram);
  17251. }
  17252. gl.deleteShader(glVertShader);
  17253. gl.deleteShader(glFragShader);
  17254. var uniformData = {};
  17255. for (var i in program.uniformData) {
  17256. var data = program.uniformData[i];
  17257. uniformData[i] = {
  17258. location: gl.getUniformLocation(webGLProgram, i),
  17259. value: defaultValue(data.type, data.size),
  17260. };
  17261. }
  17262. var glProgram = new GLProgram(webGLProgram, uniformData);
  17263. return glProgram;
  17264. }
  17265. var UID = 0;
  17266. // default sync data so we don't create a new one each time!
  17267. var defaultSyncData = { textureCount: 0, uboCount: 0 };
  17268. /**
  17269. * System plugin to the renderer to manage shaders.
  17270. * @memberof PIXI
  17271. */
  17272. var ShaderSystem = /** @class */ (function () {
  17273. /** @param renderer - The renderer this System works for. */
  17274. function ShaderSystem(renderer) {
  17275. this.destroyed = false;
  17276. this.renderer = renderer;
  17277. // Validation check that this environment support `new Function`
  17278. this.systemCheck();
  17279. this.gl = null;
  17280. this.shader = null;
  17281. this.program = null;
  17282. this.cache = {};
  17283. this._uboCache = {};
  17284. this.id = UID++;
  17285. }
  17286. /**
  17287. * Overrideable function by `@pixi/unsafe-eval` to silence
  17288. * throwing an error if platform doesn't support unsafe-evals.
  17289. * @private
  17290. */
  17291. ShaderSystem.prototype.systemCheck = function () {
  17292. if (!unsafeEvalSupported()) {
  17293. throw new Error('Current environment does not allow unsafe-eval, '
  17294. + 'please use @pixi/unsafe-eval module to enable support.');
  17295. }
  17296. };
  17297. ShaderSystem.prototype.contextChange = function (gl) {
  17298. this.gl = gl;
  17299. this.reset();
  17300. };
  17301. /**
  17302. * Changes the current shader to the one given in parameter.
  17303. * @param shader - the new shader
  17304. * @param dontSync - false if the shader should automatically sync its uniforms.
  17305. * @returns the glProgram that belongs to the shader.
  17306. */
  17307. ShaderSystem.prototype.bind = function (shader, dontSync) {
  17308. shader.disposeRunner.add(this);
  17309. shader.uniforms.globals = this.renderer.globalUniforms;
  17310. var program = shader.program;
  17311. var glProgram = program.glPrograms[this.renderer.CONTEXT_UID] || this.generateProgram(shader);
  17312. this.shader = shader;
  17313. // TODO - some current Pixi plugins bypass this.. so it not safe to use yet..
  17314. if (this.program !== program) {
  17315. this.program = program;
  17316. this.gl.useProgram(glProgram.program);
  17317. }
  17318. if (!dontSync) {
  17319. defaultSyncData.textureCount = 0;
  17320. defaultSyncData.uboCount = 0;
  17321. this.syncUniformGroup(shader.uniformGroup, defaultSyncData);
  17322. }
  17323. return glProgram;
  17324. };
  17325. /**
  17326. * Uploads the uniforms values to the currently bound shader.
  17327. * @param uniforms - the uniforms values that be applied to the current shader
  17328. */
  17329. ShaderSystem.prototype.setUniforms = function (uniforms) {
  17330. var shader = this.shader.program;
  17331. var glProgram = shader.glPrograms[this.renderer.CONTEXT_UID];
  17332. shader.syncUniforms(glProgram.uniformData, uniforms, this.renderer);
  17333. };
  17334. /* eslint-disable @typescript-eslint/explicit-module-boundary-types */
  17335. /**
  17336. * Syncs uniforms on the group
  17337. * @param group - the uniform group to sync
  17338. * @param syncData - this is data that is passed to the sync function and any nested sync functions
  17339. */
  17340. ShaderSystem.prototype.syncUniformGroup = function (group, syncData) {
  17341. var glProgram = this.getGlProgram();
  17342. if (!group.static || group.dirtyId !== glProgram.uniformDirtyGroups[group.id]) {
  17343. glProgram.uniformDirtyGroups[group.id] = group.dirtyId;
  17344. this.syncUniforms(group, glProgram, syncData);
  17345. }
  17346. };
  17347. /**
  17348. * Overrideable by the @pixi/unsafe-eval package to use static syncUniforms instead.
  17349. * @param group
  17350. * @param glProgram
  17351. * @param syncData
  17352. */
  17353. ShaderSystem.prototype.syncUniforms = function (group, glProgram, syncData) {
  17354. var syncFunc = group.syncUniforms[this.shader.program.id] || this.createSyncGroups(group);
  17355. syncFunc(glProgram.uniformData, group.uniforms, this.renderer, syncData);
  17356. };
  17357. ShaderSystem.prototype.createSyncGroups = function (group) {
  17358. var id = this.getSignature(group, this.shader.program.uniformData, 'u');
  17359. if (!this.cache[id]) {
  17360. this.cache[id] = generateUniformsSync(group, this.shader.program.uniformData);
  17361. }
  17362. group.syncUniforms[this.shader.program.id] = this.cache[id];
  17363. return group.syncUniforms[this.shader.program.id];
  17364. };
  17365. /**
  17366. * Syncs uniform buffers
  17367. * @param group - the uniform buffer group to sync
  17368. * @param name - the name of the uniform buffer
  17369. */
  17370. ShaderSystem.prototype.syncUniformBufferGroup = function (group, name) {
  17371. var glProgram = this.getGlProgram();
  17372. if (!group.static || group.dirtyId !== 0 || !glProgram.uniformGroups[group.id]) {
  17373. group.dirtyId = 0;
  17374. var syncFunc = glProgram.uniformGroups[group.id]
  17375. || this.createSyncBufferGroup(group, glProgram, name);
  17376. // TODO wrap update in a cache??
  17377. group.buffer.update();
  17378. syncFunc(glProgram.uniformData, group.uniforms, this.renderer, defaultSyncData, group.buffer);
  17379. }
  17380. this.renderer.buffer.bindBufferBase(group.buffer, glProgram.uniformBufferBindings[name]);
  17381. };
  17382. /**
  17383. * Will create a function that uploads a uniform buffer using the STD140 standard.
  17384. * The upload function will then be cached for future calls
  17385. * If a group is manually managed, then a simple upload function is generated
  17386. * @param group - the uniform buffer group to sync
  17387. * @param glProgram - the gl program to attach the uniform bindings to
  17388. * @param name - the name of the uniform buffer (must exist on the shader)
  17389. */
  17390. ShaderSystem.prototype.createSyncBufferGroup = function (group, glProgram, name) {
  17391. var gl = this.renderer.gl;
  17392. this.renderer.buffer.bind(group.buffer);
  17393. // bind them...
  17394. var uniformBlockIndex = this.gl.getUniformBlockIndex(glProgram.program, name);
  17395. glProgram.uniformBufferBindings[name] = this.shader.uniformBindCount;
  17396. gl.uniformBlockBinding(glProgram.program, uniformBlockIndex, this.shader.uniformBindCount);
  17397. this.shader.uniformBindCount++;
  17398. var id = this.getSignature(group, this.shader.program.uniformData, 'ubo');
  17399. var uboData = this._uboCache[id];
  17400. if (!uboData) {
  17401. uboData = this._uboCache[id] = generateUniformBufferSync(group, this.shader.program.uniformData);
  17402. }
  17403. if (group.autoManage) {
  17404. var data = new Float32Array(uboData.size / 4);
  17405. group.buffer.update(data);
  17406. }
  17407. glProgram.uniformGroups[group.id] = uboData.syncFunc;
  17408. return glProgram.uniformGroups[group.id];
  17409. };
  17410. /**
  17411. * Takes a uniform group and data and generates a unique signature for them.
  17412. * @param group - The uniform group to get signature of
  17413. * @param group.uniforms
  17414. * @param uniformData - Uniform information generated by the shader
  17415. * @param preFix
  17416. * @returns Unique signature of the uniform group
  17417. */
  17418. ShaderSystem.prototype.getSignature = function (group, uniformData, preFix) {
  17419. var uniforms = group.uniforms;
  17420. var strings = [preFix + "-"];
  17421. for (var i in uniforms) {
  17422. strings.push(i);
  17423. if (uniformData[i]) {
  17424. strings.push(uniformData[i].type);
  17425. }
  17426. }
  17427. return strings.join('-');
  17428. };
  17429. /**
  17430. * Returns the underlying GLShade rof the currently bound shader.
  17431. *
  17432. * This can be handy for when you to have a little more control over the setting of your uniforms.
  17433. * @returns The glProgram for the currently bound Shader for this context
  17434. */
  17435. ShaderSystem.prototype.getGlProgram = function () {
  17436. if (this.shader) {
  17437. return this.shader.program.glPrograms[this.renderer.CONTEXT_UID];
  17438. }
  17439. return null;
  17440. };
  17441. /**
  17442. * Generates a glProgram version of the Shader provided.
  17443. * @param shader - The shader that the glProgram will be based on.
  17444. * @returns A shiny new glProgram!
  17445. */
  17446. ShaderSystem.prototype.generateProgram = function (shader) {
  17447. var gl = this.gl;
  17448. var program = shader.program;
  17449. var glProgram = generateProgram(gl, program);
  17450. program.glPrograms[this.renderer.CONTEXT_UID] = glProgram;
  17451. return glProgram;
  17452. };
  17453. /** Resets ShaderSystem state, does not affect WebGL state. */
  17454. ShaderSystem.prototype.reset = function () {
  17455. this.program = null;
  17456. this.shader = null;
  17457. };
  17458. /**
  17459. * Disposes shader.
  17460. * If disposing one equals with current shader, set current as null.
  17461. * @param shader - Shader object
  17462. */
  17463. ShaderSystem.prototype.disposeShader = function (shader) {
  17464. if (this.shader === shader) {
  17465. this.shader = null;
  17466. }
  17467. };
  17468. /** Destroys this System and removes all its textures. */
  17469. ShaderSystem.prototype.destroy = function () {
  17470. this.renderer = null;
  17471. // TODO implement destroy method for ShaderSystem
  17472. this.destroyed = true;
  17473. };
  17474. return ShaderSystem;
  17475. }());
  17476. /**
  17477. * Maps gl blend combinations to WebGL.
  17478. * @memberof PIXI
  17479. * @function mapWebGLBlendModesToPixi
  17480. * @private
  17481. * @param {WebGLRenderingContext} gl - The rendering context.
  17482. * @param {number[][]} [array=[]] - The array to output into.
  17483. * @returns {number[][]} Mapped modes.
  17484. */
  17485. function mapWebGLBlendModesToPixi(gl, array) {
  17486. if (array === void 0) { array = []; }
  17487. // TODO - premultiply alpha would be different.
  17488. // add a boolean for that!
  17489. array[BLEND_MODES.NORMAL] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
  17490. array[BLEND_MODES.ADD] = [gl.ONE, gl.ONE];
  17491. array[BLEND_MODES.MULTIPLY] = [gl.DST_COLOR, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
  17492. array[BLEND_MODES.SCREEN] = [gl.ONE, gl.ONE_MINUS_SRC_COLOR, gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
  17493. array[BLEND_MODES.OVERLAY] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
  17494. array[BLEND_MODES.DARKEN] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
  17495. array[BLEND_MODES.LIGHTEN] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
  17496. array[BLEND_MODES.COLOR_DODGE] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
  17497. array[BLEND_MODES.COLOR_BURN] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
  17498. array[BLEND_MODES.HARD_LIGHT] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
  17499. array[BLEND_MODES.SOFT_LIGHT] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
  17500. array[BLEND_MODES.DIFFERENCE] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
  17501. array[BLEND_MODES.EXCLUSION] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
  17502. array[BLEND_MODES.HUE] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
  17503. array[BLEND_MODES.SATURATION] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
  17504. array[BLEND_MODES.COLOR] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
  17505. array[BLEND_MODES.LUMINOSITY] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
  17506. array[BLEND_MODES.NONE] = [0, 0];
  17507. // not-premultiplied blend modes
  17508. array[BLEND_MODES.NORMAL_NPM] = [gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
  17509. array[BLEND_MODES.ADD_NPM] = [gl.SRC_ALPHA, gl.ONE, gl.ONE, gl.ONE];
  17510. array[BLEND_MODES.SCREEN_NPM] = [gl.SRC_ALPHA, gl.ONE_MINUS_SRC_COLOR, gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
  17511. // composite operations
  17512. array[BLEND_MODES.SRC_IN] = [gl.DST_ALPHA, gl.ZERO];
  17513. array[BLEND_MODES.SRC_OUT] = [gl.ONE_MINUS_DST_ALPHA, gl.ZERO];
  17514. array[BLEND_MODES.SRC_ATOP] = [gl.DST_ALPHA, gl.ONE_MINUS_SRC_ALPHA];
  17515. array[BLEND_MODES.DST_OVER] = [gl.ONE_MINUS_DST_ALPHA, gl.ONE];
  17516. array[BLEND_MODES.DST_IN] = [gl.ZERO, gl.SRC_ALPHA];
  17517. array[BLEND_MODES.DST_OUT] = [gl.ZERO, gl.ONE_MINUS_SRC_ALPHA];
  17518. array[BLEND_MODES.DST_ATOP] = [gl.ONE_MINUS_DST_ALPHA, gl.SRC_ALPHA];
  17519. array[BLEND_MODES.XOR] = [gl.ONE_MINUS_DST_ALPHA, gl.ONE_MINUS_SRC_ALPHA];
  17520. // SUBTRACT from flash
  17521. array[BLEND_MODES.SUBTRACT] = [gl.ONE, gl.ONE, gl.ONE, gl.ONE, gl.FUNC_REVERSE_SUBTRACT, gl.FUNC_ADD];
  17522. return array;
  17523. }
  17524. var BLEND = 0;
  17525. var OFFSET = 1;
  17526. var CULLING = 2;
  17527. var DEPTH_TEST = 3;
  17528. var WINDING = 4;
  17529. var DEPTH_MASK = 5;
  17530. /**
  17531. * System plugin to the renderer to manage WebGL state machines.
  17532. * @memberof PIXI
  17533. */
  17534. var StateSystem = /** @class */ (function () {
  17535. function StateSystem() {
  17536. this.gl = null;
  17537. this.stateId = 0;
  17538. this.polygonOffset = 0;
  17539. this.blendMode = BLEND_MODES.NONE;
  17540. this._blendEq = false;
  17541. // map functions for when we set state..
  17542. this.map = [];
  17543. this.map[BLEND] = this.setBlend;
  17544. this.map[OFFSET] = this.setOffset;
  17545. this.map[CULLING] = this.setCullFace;
  17546. this.map[DEPTH_TEST] = this.setDepthTest;
  17547. this.map[WINDING] = this.setFrontFace;
  17548. this.map[DEPTH_MASK] = this.setDepthMask;
  17549. this.checks = [];
  17550. this.defaultState = new State();
  17551. this.defaultState.blend = true;
  17552. }
  17553. StateSystem.prototype.contextChange = function (gl) {
  17554. this.gl = gl;
  17555. this.blendModes = mapWebGLBlendModesToPixi(gl);
  17556. this.set(this.defaultState);
  17557. this.reset();
  17558. };
  17559. /**
  17560. * Sets the current state
  17561. * @param {*} state - The state to set.
  17562. */
  17563. StateSystem.prototype.set = function (state) {
  17564. state = state || this.defaultState;
  17565. // TODO maybe to an object check? ( this.state === state )?
  17566. if (this.stateId !== state.data) {
  17567. var diff = this.stateId ^ state.data;
  17568. var i = 0;
  17569. // order from least to most common
  17570. while (diff) {
  17571. if (diff & 1) {
  17572. // state change!
  17573. this.map[i].call(this, !!(state.data & (1 << i)));
  17574. }
  17575. diff = diff >> 1;
  17576. i++;
  17577. }
  17578. this.stateId = state.data;
  17579. }
  17580. // based on the above settings we check for specific modes..
  17581. // for example if blend is active we check and set the blend modes
  17582. // or of polygon offset is active we check the poly depth.
  17583. for (var i = 0; i < this.checks.length; i++) {
  17584. this.checks[i](this, state);
  17585. }
  17586. };
  17587. /**
  17588. * Sets the state, when previous state is unknown.
  17589. * @param {*} state - The state to set
  17590. */
  17591. StateSystem.prototype.forceState = function (state) {
  17592. state = state || this.defaultState;
  17593. for (var i = 0; i < this.map.length; i++) {
  17594. this.map[i].call(this, !!(state.data & (1 << i)));
  17595. }
  17596. for (var i = 0; i < this.checks.length; i++) {
  17597. this.checks[i](this, state);
  17598. }
  17599. this.stateId = state.data;
  17600. };
  17601. /**
  17602. * Sets whether to enable or disable blending.
  17603. * @param value - Turn on or off WebGl blending.
  17604. */
  17605. StateSystem.prototype.setBlend = function (value) {
  17606. this.updateCheck(StateSystem.checkBlendMode, value);
  17607. this.gl[value ? 'enable' : 'disable'](this.gl.BLEND);
  17608. };
  17609. /**
  17610. * Sets whether to enable or disable polygon offset fill.
  17611. * @param value - Turn on or off webgl polygon offset testing.
  17612. */
  17613. StateSystem.prototype.setOffset = function (value) {
  17614. this.updateCheck(StateSystem.checkPolygonOffset, value);
  17615. this.gl[value ? 'enable' : 'disable'](this.gl.POLYGON_OFFSET_FILL);
  17616. };
  17617. /**
  17618. * Sets whether to enable or disable depth test.
  17619. * @param value - Turn on or off webgl depth testing.
  17620. */
  17621. StateSystem.prototype.setDepthTest = function (value) {
  17622. this.gl[value ? 'enable' : 'disable'](this.gl.DEPTH_TEST);
  17623. };
  17624. /**
  17625. * Sets whether to enable or disable depth mask.
  17626. * @param value - Turn on or off webgl depth mask.
  17627. */
  17628. StateSystem.prototype.setDepthMask = function (value) {
  17629. this.gl.depthMask(value);
  17630. };
  17631. /**
  17632. * Sets whether to enable or disable cull face.
  17633. * @param {boolean} value - Turn on or off webgl cull face.
  17634. */
  17635. StateSystem.prototype.setCullFace = function (value) {
  17636. this.gl[value ? 'enable' : 'disable'](this.gl.CULL_FACE);
  17637. };
  17638. /**
  17639. * Sets the gl front face.
  17640. * @param {boolean} value - true is clockwise and false is counter-clockwise
  17641. */
  17642. StateSystem.prototype.setFrontFace = function (value) {
  17643. this.gl.frontFace(this.gl[value ? 'CW' : 'CCW']);
  17644. };
  17645. /**
  17646. * Sets the blend mode.
  17647. * @param {number} value - The blend mode to set to.
  17648. */
  17649. StateSystem.prototype.setBlendMode = function (value) {
  17650. if (value === this.blendMode) {
  17651. return;
  17652. }
  17653. this.blendMode = value;
  17654. var mode = this.blendModes[value];
  17655. var gl = this.gl;
  17656. if (mode.length === 2) {
  17657. gl.blendFunc(mode[0], mode[1]);
  17658. }
  17659. else {
  17660. gl.blendFuncSeparate(mode[0], mode[1], mode[2], mode[3]);
  17661. }
  17662. if (mode.length === 6) {
  17663. this._blendEq = true;
  17664. gl.blendEquationSeparate(mode[4], mode[5]);
  17665. }
  17666. else if (this._blendEq) {
  17667. this._blendEq = false;
  17668. gl.blendEquationSeparate(gl.FUNC_ADD, gl.FUNC_ADD);
  17669. }
  17670. };
  17671. /**
  17672. * Sets the polygon offset.
  17673. * @param {number} value - the polygon offset
  17674. * @param {number} scale - the polygon offset scale
  17675. */
  17676. StateSystem.prototype.setPolygonOffset = function (value, scale) {
  17677. this.gl.polygonOffset(value, scale);
  17678. };
  17679. // used
  17680. /** Resets all the logic and disables the VAOs. */
  17681. StateSystem.prototype.reset = function () {
  17682. this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL, false);
  17683. this.forceState(this.defaultState);
  17684. this._blendEq = true;
  17685. this.blendMode = -1;
  17686. this.setBlendMode(0);
  17687. };
  17688. /**
  17689. * Checks to see which updates should be checked based on which settings have been activated.
  17690. *
  17691. * For example, if blend is enabled then we should check the blend modes each time the state is changed
  17692. * or if polygon fill is activated then we need to check if the polygon offset changes.
  17693. * The idea is that we only check what we have too.
  17694. * @param func - the checking function to add or remove
  17695. * @param value - should the check function be added or removed.
  17696. */
  17697. StateSystem.prototype.updateCheck = function (func, value) {
  17698. var index = this.checks.indexOf(func);
  17699. if (value && index === -1) {
  17700. this.checks.push(func);
  17701. }
  17702. else if (!value && index !== -1) {
  17703. this.checks.splice(index, 1);
  17704. }
  17705. };
  17706. /**
  17707. * A private little wrapper function that we call to check the blend mode.
  17708. * @param system - the System to perform the state check on
  17709. * @param state - the state that the blendMode will pulled from
  17710. */
  17711. StateSystem.checkBlendMode = function (system, state) {
  17712. system.setBlendMode(state.blendMode);
  17713. };
  17714. /**
  17715. * A private little wrapper function that we call to check the polygon offset.
  17716. * @param system - the System to perform the state check on
  17717. * @param state - the state that the blendMode will pulled from
  17718. */
  17719. StateSystem.checkPolygonOffset = function (system, state) {
  17720. system.setPolygonOffset(1, state.polygonOffset);
  17721. };
  17722. /**
  17723. * @ignore
  17724. */
  17725. StateSystem.prototype.destroy = function () {
  17726. this.gl = null;
  17727. };
  17728. return StateSystem;
  17729. }());
  17730. /**
  17731. * System plugin to the renderer to manage texture garbage collection on the GPU,
  17732. * ensuring that it does not get clogged up with textures that are no longer being used.
  17733. * @memberof PIXI
  17734. */
  17735. var TextureGCSystem = /** @class */ (function () {
  17736. /** @param renderer - The renderer this System works for. */
  17737. function TextureGCSystem(renderer) {
  17738. this.renderer = renderer;
  17739. this.count = 0;
  17740. this.checkCount = 0;
  17741. this.maxIdle = settings.GC_MAX_IDLE;
  17742. this.checkCountMax = settings.GC_MAX_CHECK_COUNT;
  17743. this.mode = settings.GC_MODE;
  17744. }
  17745. /**
  17746. * Checks to see when the last time a texture was used
  17747. * if the texture has not been used for a specified amount of time it will be removed from the GPU
  17748. */
  17749. TextureGCSystem.prototype.postrender = function () {
  17750. if (!this.renderer.renderingToScreen) {
  17751. return;
  17752. }
  17753. this.count++;
  17754. if (this.mode === GC_MODES.MANUAL) {
  17755. return;
  17756. }
  17757. this.checkCount++;
  17758. if (this.checkCount > this.checkCountMax) {
  17759. this.checkCount = 0;
  17760. this.run();
  17761. }
  17762. };
  17763. /**
  17764. * Checks to see when the last time a texture was used
  17765. * if the texture has not been used for a specified amount of time it will be removed from the GPU
  17766. */
  17767. TextureGCSystem.prototype.run = function () {
  17768. var tm = this.renderer.texture;
  17769. var managedTextures = tm.managedTextures;
  17770. var wasRemoved = false;
  17771. for (var i = 0; i < managedTextures.length; i++) {
  17772. var texture = managedTextures[i];
  17773. // only supports non generated textures at the moment!
  17774. if (!texture.framebuffer && this.count - texture.touched > this.maxIdle) {
  17775. tm.destroyTexture(texture, true);
  17776. managedTextures[i] = null;
  17777. wasRemoved = true;
  17778. }
  17779. }
  17780. if (wasRemoved) {
  17781. var j = 0;
  17782. for (var i = 0; i < managedTextures.length; i++) {
  17783. if (managedTextures[i] !== null) {
  17784. managedTextures[j++] = managedTextures[i];
  17785. }
  17786. }
  17787. managedTextures.length = j;
  17788. }
  17789. };
  17790. /**
  17791. * Removes all the textures within the specified displayObject and its children from the GPU
  17792. * @param {PIXI.DisplayObject} displayObject - the displayObject to remove the textures from.
  17793. */
  17794. TextureGCSystem.prototype.unload = function (displayObject) {
  17795. var tm = this.renderer.texture;
  17796. var texture = displayObject._texture;
  17797. // only destroy non generated textures
  17798. if (texture && !texture.framebuffer) {
  17799. tm.destroyTexture(texture);
  17800. }
  17801. for (var i = displayObject.children.length - 1; i >= 0; i--) {
  17802. this.unload(displayObject.children[i]);
  17803. }
  17804. };
  17805. TextureGCSystem.prototype.destroy = function () {
  17806. this.renderer = null;
  17807. };
  17808. return TextureGCSystem;
  17809. }());
  17810. /**
  17811. * Returns a lookup table that maps each type-format pair to a compatible internal format.
  17812. * @memberof PIXI
  17813. * @function mapTypeAndFormatToInternalFormat
  17814. * @private
  17815. * @param {WebGLRenderingContext} gl - The rendering context.
  17816. * @returns Lookup table.
  17817. */
  17818. function mapTypeAndFormatToInternalFormat(gl) {
  17819. var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x;
  17820. var table;
  17821. if ('WebGL2RenderingContext' in globalThis && gl instanceof globalThis.WebGL2RenderingContext) {
  17822. table = (_a = {},
  17823. _a[TYPES.UNSIGNED_BYTE] = (_b = {},
  17824. _b[FORMATS.RGBA] = gl.RGBA8,
  17825. _b[FORMATS.RGB] = gl.RGB8,
  17826. _b[FORMATS.RG] = gl.RG8,
  17827. _b[FORMATS.RED] = gl.R8,
  17828. _b[FORMATS.RGBA_INTEGER] = gl.RGBA8UI,
  17829. _b[FORMATS.RGB_INTEGER] = gl.RGB8UI,
  17830. _b[FORMATS.RG_INTEGER] = gl.RG8UI,
  17831. _b[FORMATS.RED_INTEGER] = gl.R8UI,
  17832. _b[FORMATS.ALPHA] = gl.ALPHA,
  17833. _b[FORMATS.LUMINANCE] = gl.LUMINANCE,
  17834. _b[FORMATS.LUMINANCE_ALPHA] = gl.LUMINANCE_ALPHA,
  17835. _b),
  17836. _a[TYPES.BYTE] = (_c = {},
  17837. _c[FORMATS.RGBA] = gl.RGBA8_SNORM,
  17838. _c[FORMATS.RGB] = gl.RGB8_SNORM,
  17839. _c[FORMATS.RG] = gl.RG8_SNORM,
  17840. _c[FORMATS.RED] = gl.R8_SNORM,
  17841. _c[FORMATS.RGBA_INTEGER] = gl.RGBA8I,
  17842. _c[FORMATS.RGB_INTEGER] = gl.RGB8I,
  17843. _c[FORMATS.RG_INTEGER] = gl.RG8I,
  17844. _c[FORMATS.RED_INTEGER] = gl.R8I,
  17845. _c),
  17846. _a[TYPES.UNSIGNED_SHORT] = (_d = {},
  17847. _d[FORMATS.RGBA_INTEGER] = gl.RGBA16UI,
  17848. _d[FORMATS.RGB_INTEGER] = gl.RGB16UI,
  17849. _d[FORMATS.RG_INTEGER] = gl.RG16UI,
  17850. _d[FORMATS.RED_INTEGER] = gl.R16UI,
  17851. _d[FORMATS.DEPTH_COMPONENT] = gl.DEPTH_COMPONENT16,
  17852. _d),
  17853. _a[TYPES.SHORT] = (_e = {},
  17854. _e[FORMATS.RGBA_INTEGER] = gl.RGBA16I,
  17855. _e[FORMATS.RGB_INTEGER] = gl.RGB16I,
  17856. _e[FORMATS.RG_INTEGER] = gl.RG16I,
  17857. _e[FORMATS.RED_INTEGER] = gl.R16I,
  17858. _e),
  17859. _a[TYPES.UNSIGNED_INT] = (_f = {},
  17860. _f[FORMATS.RGBA_INTEGER] = gl.RGBA32UI,
  17861. _f[FORMATS.RGB_INTEGER] = gl.RGB32UI,
  17862. _f[FORMATS.RG_INTEGER] = gl.RG32UI,
  17863. _f[FORMATS.RED_INTEGER] = gl.R32UI,
  17864. _f[FORMATS.DEPTH_COMPONENT] = gl.DEPTH_COMPONENT24,
  17865. _f),
  17866. _a[TYPES.INT] = (_g = {},
  17867. _g[FORMATS.RGBA_INTEGER] = gl.RGBA32I,
  17868. _g[FORMATS.RGB_INTEGER] = gl.RGB32I,
  17869. _g[FORMATS.RG_INTEGER] = gl.RG32I,
  17870. _g[FORMATS.RED_INTEGER] = gl.R32I,
  17871. _g),
  17872. _a[TYPES.FLOAT] = (_h = {},
  17873. _h[FORMATS.RGBA] = gl.RGBA32F,
  17874. _h[FORMATS.RGB] = gl.RGB32F,
  17875. _h[FORMATS.RG] = gl.RG32F,
  17876. _h[FORMATS.RED] = gl.R32F,
  17877. _h[FORMATS.DEPTH_COMPONENT] = gl.DEPTH_COMPONENT32F,
  17878. _h),
  17879. _a[TYPES.HALF_FLOAT] = (_j = {},
  17880. _j[FORMATS.RGBA] = gl.RGBA16F,
  17881. _j[FORMATS.RGB] = gl.RGB16F,
  17882. _j[FORMATS.RG] = gl.RG16F,
  17883. _j[FORMATS.RED] = gl.R16F,
  17884. _j),
  17885. _a[TYPES.UNSIGNED_SHORT_5_6_5] = (_k = {},
  17886. _k[FORMATS.RGB] = gl.RGB565,
  17887. _k),
  17888. _a[TYPES.UNSIGNED_SHORT_4_4_4_4] = (_l = {},
  17889. _l[FORMATS.RGBA] = gl.RGBA4,
  17890. _l),
  17891. _a[TYPES.UNSIGNED_SHORT_5_5_5_1] = (_m = {},
  17892. _m[FORMATS.RGBA] = gl.RGB5_A1,
  17893. _m),
  17894. _a[TYPES.UNSIGNED_INT_2_10_10_10_REV] = (_o = {},
  17895. _o[FORMATS.RGBA] = gl.RGB10_A2,
  17896. _o[FORMATS.RGBA_INTEGER] = gl.RGB10_A2UI,
  17897. _o),
  17898. _a[TYPES.UNSIGNED_INT_10F_11F_11F_REV] = (_p = {},
  17899. _p[FORMATS.RGB] = gl.R11F_G11F_B10F,
  17900. _p),
  17901. _a[TYPES.UNSIGNED_INT_5_9_9_9_REV] = (_q = {},
  17902. _q[FORMATS.RGB] = gl.RGB9_E5,
  17903. _q),
  17904. _a[TYPES.UNSIGNED_INT_24_8] = (_r = {},
  17905. _r[FORMATS.DEPTH_STENCIL] = gl.DEPTH24_STENCIL8,
  17906. _r),
  17907. _a[TYPES.FLOAT_32_UNSIGNED_INT_24_8_REV] = (_s = {},
  17908. _s[FORMATS.DEPTH_STENCIL] = gl.DEPTH32F_STENCIL8,
  17909. _s),
  17910. _a);
  17911. }
  17912. else {
  17913. table = (_t = {},
  17914. _t[TYPES.UNSIGNED_BYTE] = (_u = {},
  17915. _u[FORMATS.RGBA] = gl.RGBA,
  17916. _u[FORMATS.RGB] = gl.RGB,
  17917. _u[FORMATS.ALPHA] = gl.ALPHA,
  17918. _u[FORMATS.LUMINANCE] = gl.LUMINANCE,
  17919. _u[FORMATS.LUMINANCE_ALPHA] = gl.LUMINANCE_ALPHA,
  17920. _u),
  17921. _t[TYPES.UNSIGNED_SHORT_5_6_5] = (_v = {},
  17922. _v[FORMATS.RGB] = gl.RGB,
  17923. _v),
  17924. _t[TYPES.UNSIGNED_SHORT_4_4_4_4] = (_w = {},
  17925. _w[FORMATS.RGBA] = gl.RGBA,
  17926. _w),
  17927. _t[TYPES.UNSIGNED_SHORT_5_5_5_1] = (_x = {},
  17928. _x[FORMATS.RGBA] = gl.RGBA,
  17929. _x),
  17930. _t);
  17931. }
  17932. return table;
  17933. }
  17934. /**
  17935. * Internal texture for WebGL context.
  17936. * @memberof PIXI
  17937. */
  17938. var GLTexture = /** @class */ (function () {
  17939. function GLTexture(texture) {
  17940. this.texture = texture;
  17941. this.width = -1;
  17942. this.height = -1;
  17943. this.dirtyId = -1;
  17944. this.dirtyStyleId = -1;
  17945. this.mipmap = false;
  17946. this.wrapMode = 33071;
  17947. this.type = TYPES.UNSIGNED_BYTE;
  17948. this.internalFormat = FORMATS.RGBA;
  17949. this.samplerType = 0;
  17950. }
  17951. return GLTexture;
  17952. }());
  17953. /**
  17954. * System plugin to the renderer to manage textures.
  17955. * @memberof PIXI
  17956. */
  17957. var TextureSystem = /** @class */ (function () {
  17958. /**
  17959. * @param renderer - The renderer this system works for.
  17960. */
  17961. function TextureSystem(renderer) {
  17962. this.renderer = renderer;
  17963. // TODO set to max textures...
  17964. this.boundTextures = [];
  17965. this.currentLocation = -1;
  17966. this.managedTextures = [];
  17967. this._unknownBoundTextures = false;
  17968. this.unknownTexture = new BaseTexture();
  17969. this.hasIntegerTextures = false;
  17970. }
  17971. /** Sets up the renderer context and necessary buffers. */
  17972. TextureSystem.prototype.contextChange = function () {
  17973. var gl = this.gl = this.renderer.gl;
  17974. this.CONTEXT_UID = this.renderer.CONTEXT_UID;
  17975. this.webGLVersion = this.renderer.context.webGLVersion;
  17976. this.internalFormats = mapTypeAndFormatToInternalFormat(gl);
  17977. var maxTextures = gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS);
  17978. this.boundTextures.length = maxTextures;
  17979. for (var i = 0; i < maxTextures; i++) {
  17980. this.boundTextures[i] = null;
  17981. }
  17982. // TODO move this.. to a nice make empty textures class..
  17983. this.emptyTextures = {};
  17984. var emptyTexture2D = new GLTexture(gl.createTexture());
  17985. gl.bindTexture(gl.TEXTURE_2D, emptyTexture2D.texture);
  17986. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, new Uint8Array(4));
  17987. this.emptyTextures[gl.TEXTURE_2D] = emptyTexture2D;
  17988. this.emptyTextures[gl.TEXTURE_CUBE_MAP] = new GLTexture(gl.createTexture());
  17989. gl.bindTexture(gl.TEXTURE_CUBE_MAP, this.emptyTextures[gl.TEXTURE_CUBE_MAP].texture);
  17990. for (var i = 0; i < 6; i++) {
  17991. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  17992. }
  17993. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  17994. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  17995. for (var i = 0; i < this.boundTextures.length; i++) {
  17996. this.bind(null, i);
  17997. }
  17998. };
  17999. /**
  18000. * Bind a texture to a specific location
  18001. *
  18002. * If you want to unbind something, please use `unbind(texture)` instead of `bind(null, textureLocation)`
  18003. * @param texture - Texture to bind
  18004. * @param [location=0] - Location to bind at
  18005. */
  18006. TextureSystem.prototype.bind = function (texture, location) {
  18007. if (location === void 0) { location = 0; }
  18008. var gl = this.gl;
  18009. texture = texture === null || texture === void 0 ? void 0 : texture.castToBaseTexture();
  18010. // cannot bind partial texture
  18011. // TODO: report a warning
  18012. if (texture && texture.valid && !texture.parentTextureArray) {
  18013. texture.touched = this.renderer.textureGC.count;
  18014. var glTexture = texture._glTextures[this.CONTEXT_UID] || this.initTexture(texture);
  18015. if (this.boundTextures[location] !== texture) {
  18016. if (this.currentLocation !== location) {
  18017. this.currentLocation = location;
  18018. gl.activeTexture(gl.TEXTURE0 + location);
  18019. }
  18020. gl.bindTexture(texture.target, glTexture.texture);
  18021. }
  18022. if (glTexture.dirtyId !== texture.dirtyId) {
  18023. if (this.currentLocation !== location) {
  18024. this.currentLocation = location;
  18025. gl.activeTexture(gl.TEXTURE0 + location);
  18026. }
  18027. this.updateTexture(texture);
  18028. }
  18029. else if (glTexture.dirtyStyleId !== texture.dirtyStyleId) {
  18030. this.updateTextureStyle(texture);
  18031. }
  18032. this.boundTextures[location] = texture;
  18033. }
  18034. else {
  18035. if (this.currentLocation !== location) {
  18036. this.currentLocation = location;
  18037. gl.activeTexture(gl.TEXTURE0 + location);
  18038. }
  18039. gl.bindTexture(gl.TEXTURE_2D, this.emptyTextures[gl.TEXTURE_2D].texture);
  18040. this.boundTextures[location] = null;
  18041. }
  18042. };
  18043. /** Resets texture location and bound textures Actual `bind(null, i)` calls will be performed at next `unbind()` call */
  18044. TextureSystem.prototype.reset = function () {
  18045. this._unknownBoundTextures = true;
  18046. this.hasIntegerTextures = false;
  18047. this.currentLocation = -1;
  18048. for (var i = 0; i < this.boundTextures.length; i++) {
  18049. this.boundTextures[i] = this.unknownTexture;
  18050. }
  18051. };
  18052. /**
  18053. * Unbind a texture.
  18054. * @param texture - Texture to bind
  18055. */
  18056. TextureSystem.prototype.unbind = function (texture) {
  18057. var _a = this, gl = _a.gl, boundTextures = _a.boundTextures;
  18058. if (this._unknownBoundTextures) {
  18059. this._unknownBoundTextures = false;
  18060. // someone changed webGL state,
  18061. // we have to be sure that our texture does not appear in multi-texture renderer samplers
  18062. for (var i = 0; i < boundTextures.length; i++) {
  18063. if (boundTextures[i] === this.unknownTexture) {
  18064. this.bind(null, i);
  18065. }
  18066. }
  18067. }
  18068. for (var i = 0; i < boundTextures.length; i++) {
  18069. if (boundTextures[i] === texture) {
  18070. if (this.currentLocation !== i) {
  18071. gl.activeTexture(gl.TEXTURE0 + i);
  18072. this.currentLocation = i;
  18073. }
  18074. gl.bindTexture(texture.target, this.emptyTextures[texture.target].texture);
  18075. boundTextures[i] = null;
  18076. }
  18077. }
  18078. };
  18079. /**
  18080. * Ensures that current boundTextures all have FLOAT sampler type,
  18081. * see {@link PIXI.SAMPLER_TYPES} for explanation.
  18082. * @param maxTextures - number of locations to check
  18083. */
  18084. TextureSystem.prototype.ensureSamplerType = function (maxTextures) {
  18085. var _a = this, boundTextures = _a.boundTextures, hasIntegerTextures = _a.hasIntegerTextures, CONTEXT_UID = _a.CONTEXT_UID;
  18086. if (!hasIntegerTextures) {
  18087. return;
  18088. }
  18089. for (var i = maxTextures - 1; i >= 0; --i) {
  18090. var tex = boundTextures[i];
  18091. if (tex) {
  18092. var glTexture = tex._glTextures[CONTEXT_UID];
  18093. if (glTexture.samplerType !== SAMPLER_TYPES.FLOAT) {
  18094. this.renderer.texture.unbind(tex);
  18095. }
  18096. }
  18097. }
  18098. };
  18099. /**
  18100. * Initialize a texture
  18101. * @private
  18102. * @param texture - Texture to initialize
  18103. */
  18104. TextureSystem.prototype.initTexture = function (texture) {
  18105. var glTexture = new GLTexture(this.gl.createTexture());
  18106. // guarantee an update..
  18107. glTexture.dirtyId = -1;
  18108. texture._glTextures[this.CONTEXT_UID] = glTexture;
  18109. this.managedTextures.push(texture);
  18110. texture.on('dispose', this.destroyTexture, this);
  18111. return glTexture;
  18112. };
  18113. TextureSystem.prototype.initTextureType = function (texture, glTexture) {
  18114. var _a, _b;
  18115. glTexture.internalFormat = (_b = (_a = this.internalFormats[texture.type]) === null || _a === void 0 ? void 0 : _a[texture.format]) !== null && _b !== void 0 ? _b : texture.format;
  18116. if (this.webGLVersion === 2 && texture.type === TYPES.HALF_FLOAT) {
  18117. // TYPES.HALF_FLOAT is WebGL1 HALF_FLOAT_OES
  18118. // we have to convert it to WebGL HALF_FLOAT
  18119. glTexture.type = this.gl.HALF_FLOAT;
  18120. }
  18121. else {
  18122. glTexture.type = texture.type;
  18123. }
  18124. };
  18125. /**
  18126. * Update a texture
  18127. * @private
  18128. * @param {PIXI.BaseTexture} texture - Texture to initialize
  18129. */
  18130. TextureSystem.prototype.updateTexture = function (texture) {
  18131. var glTexture = texture._glTextures[this.CONTEXT_UID];
  18132. if (!glTexture) {
  18133. return;
  18134. }
  18135. var renderer = this.renderer;
  18136. this.initTextureType(texture, glTexture);
  18137. if (texture.resource && texture.resource.upload(renderer, texture, glTexture)) {
  18138. // texture is uploaded, dont do anything!
  18139. if (glTexture.samplerType !== SAMPLER_TYPES.FLOAT) {
  18140. this.hasIntegerTextures = true;
  18141. }
  18142. }
  18143. else {
  18144. // default, renderTexture-like logic
  18145. var width = texture.realWidth;
  18146. var height = texture.realHeight;
  18147. var gl = renderer.gl;
  18148. if (glTexture.width !== width
  18149. || glTexture.height !== height
  18150. || glTexture.dirtyId < 0) {
  18151. glTexture.width = width;
  18152. glTexture.height = height;
  18153. gl.texImage2D(texture.target, 0, glTexture.internalFormat, width, height, 0, texture.format, glTexture.type, null);
  18154. }
  18155. }
  18156. // lets only update what changes..
  18157. if (texture.dirtyStyleId !== glTexture.dirtyStyleId) {
  18158. this.updateTextureStyle(texture);
  18159. }
  18160. glTexture.dirtyId = texture.dirtyId;
  18161. };
  18162. /**
  18163. * Deletes the texture from WebGL
  18164. * @private
  18165. * @param texture - the texture to destroy
  18166. * @param [skipRemove=false] - Whether to skip removing the texture from the TextureManager.
  18167. */
  18168. TextureSystem.prototype.destroyTexture = function (texture, skipRemove) {
  18169. var gl = this.gl;
  18170. texture = texture.castToBaseTexture();
  18171. if (texture._glTextures[this.CONTEXT_UID]) {
  18172. this.unbind(texture);
  18173. gl.deleteTexture(texture._glTextures[this.CONTEXT_UID].texture);
  18174. texture.off('dispose', this.destroyTexture, this);
  18175. delete texture._glTextures[this.CONTEXT_UID];
  18176. if (!skipRemove) {
  18177. var i = this.managedTextures.indexOf(texture);
  18178. if (i !== -1) {
  18179. removeItems(this.managedTextures, i, 1);
  18180. }
  18181. }
  18182. }
  18183. };
  18184. /**
  18185. * Update texture style such as mipmap flag
  18186. * @private
  18187. * @param {PIXI.BaseTexture} texture - Texture to update
  18188. */
  18189. TextureSystem.prototype.updateTextureStyle = function (texture) {
  18190. var glTexture = texture._glTextures[this.CONTEXT_UID];
  18191. if (!glTexture) {
  18192. return;
  18193. }
  18194. if ((texture.mipmap === MIPMAP_MODES.POW2 || this.webGLVersion !== 2) && !texture.isPowerOfTwo) {
  18195. glTexture.mipmap = false;
  18196. }
  18197. else {
  18198. glTexture.mipmap = texture.mipmap >= 1;
  18199. }
  18200. if (this.webGLVersion !== 2 && !texture.isPowerOfTwo) {
  18201. glTexture.wrapMode = WRAP_MODES.CLAMP;
  18202. }
  18203. else {
  18204. glTexture.wrapMode = texture.wrapMode;
  18205. }
  18206. if (texture.resource && texture.resource.style(this.renderer, texture, glTexture)) { ; }
  18207. else {
  18208. this.setStyle(texture, glTexture);
  18209. }
  18210. glTexture.dirtyStyleId = texture.dirtyStyleId;
  18211. };
  18212. /**
  18213. * Set style for texture
  18214. * @private
  18215. * @param texture - Texture to update
  18216. * @param glTexture
  18217. */
  18218. TextureSystem.prototype.setStyle = function (texture, glTexture) {
  18219. var gl = this.gl;
  18220. if (glTexture.mipmap && texture.mipmap !== MIPMAP_MODES.ON_MANUAL) {
  18221. gl.generateMipmap(texture.target);
  18222. }
  18223. gl.texParameteri(texture.target, gl.TEXTURE_WRAP_S, glTexture.wrapMode);
  18224. gl.texParameteri(texture.target, gl.TEXTURE_WRAP_T, glTexture.wrapMode);
  18225. if (glTexture.mipmap) {
  18226. /* eslint-disable max-len */
  18227. gl.texParameteri(texture.target, gl.TEXTURE_MIN_FILTER, texture.scaleMode === SCALE_MODES.LINEAR ? gl.LINEAR_MIPMAP_LINEAR : gl.NEAREST_MIPMAP_NEAREST);
  18228. /* eslint-disable max-len */
  18229. var anisotropicExt = this.renderer.context.extensions.anisotropicFiltering;
  18230. if (anisotropicExt && texture.anisotropicLevel > 0 && texture.scaleMode === SCALE_MODES.LINEAR) {
  18231. var level = Math.min(texture.anisotropicLevel, gl.getParameter(anisotropicExt.MAX_TEXTURE_MAX_ANISOTROPY_EXT));
  18232. gl.texParameterf(texture.target, anisotropicExt.TEXTURE_MAX_ANISOTROPY_EXT, level);
  18233. }
  18234. }
  18235. else {
  18236. gl.texParameteri(texture.target, gl.TEXTURE_MIN_FILTER, texture.scaleMode === SCALE_MODES.LINEAR ? gl.LINEAR : gl.NEAREST);
  18237. }
  18238. gl.texParameteri(texture.target, gl.TEXTURE_MAG_FILTER, texture.scaleMode === SCALE_MODES.LINEAR ? gl.LINEAR : gl.NEAREST);
  18239. };
  18240. TextureSystem.prototype.destroy = function () {
  18241. this.renderer = null;
  18242. };
  18243. return TextureSystem;
  18244. }());
  18245. var _systems = {
  18246. __proto__: null,
  18247. FilterSystem: FilterSystem,
  18248. BatchSystem: BatchSystem,
  18249. ContextSystem: ContextSystem,
  18250. FramebufferSystem: FramebufferSystem,
  18251. GeometrySystem: GeometrySystem,
  18252. MaskSystem: MaskSystem,
  18253. ScissorSystem: ScissorSystem,
  18254. StencilSystem: StencilSystem,
  18255. ProjectionSystem: ProjectionSystem,
  18256. RenderTextureSystem: RenderTextureSystem,
  18257. ShaderSystem: ShaderSystem,
  18258. StateSystem: StateSystem,
  18259. TextureGCSystem: TextureGCSystem,
  18260. TextureSystem: TextureSystem
  18261. };
  18262. var tempMatrix = new Matrix();
  18263. /**
  18264. * The AbstractRenderer is the base for a PixiJS Renderer. It is extended by the {@link PIXI.CanvasRenderer}
  18265. * and {@link PIXI.Renderer} which can be used for rendering a PixiJS scene.
  18266. * @abstract
  18267. * @class
  18268. * @extends PIXI.utils.EventEmitter
  18269. * @memberof PIXI
  18270. */
  18271. var AbstractRenderer = /** @class */ (function (_super) {
  18272. __extends$i(AbstractRenderer, _super);
  18273. /**
  18274. * @param type - The renderer type.
  18275. * @param {PIXI.IRendererOptions} [options] - The optional renderer parameters.
  18276. * @param {boolean} [options.antialias=false] -
  18277. * **WebGL Only.** Whether to enable anti-aliasing. This may affect performance.
  18278. * @param {boolean} [options.autoDensity=false] -
  18279. * Whether the CSS dimensions of the renderer's view should be resized automatically.
  18280. * @param {number} [options.backgroundAlpha=1] -
  18281. * Transparency of the background color, value from `0` (fully transparent) to `1` (fully opaque).
  18282. * @param {number} [options.backgroundColor=0x000000] -
  18283. * The background color used to clear the canvas. It accepts hex numbers (e.g. `0xff0000`).
  18284. * @param {boolean} [options.clearBeforeRender=true] - Whether to clear the canvas before new render passes.
  18285. * @param {PIXI.IRenderingContext} [options.context] - **WebGL Only.** User-provided WebGL rendering context object.
  18286. * @param {number} [options.height=600] - The height of the renderer's view.
  18287. * @param {string} [options.powerPreference] -
  18288. * **WebGL Only.** A hint indicating what configuration of GPU is suitable for the WebGL context,
  18289. * can be `'default'`, `'high-performance'` or `'low-power'`.
  18290. * Setting to `'high-performance'` will prioritize rendering performance over power consumption,
  18291. * while setting to `'low-power'` will prioritize power saving over rendering performance.
  18292. * @param {boolean} [options.premultipliedAlpha=true] -
  18293. * **WebGL Only.** Whether the compositor will assume the drawing buffer contains colors with premultiplied alpha.
  18294. * @param {boolean} [options.preserveDrawingBuffer=false] -
  18295. * **WebGL Only.** Whether to enable drawing buffer preservation. If enabled, the drawing buffer will preserve
  18296. * its value until cleared or overwritten. Enable this if you need to call `toDataUrl` on the WebGL context.
  18297. * @param {number} [options.resolution=PIXI.settings.RESOLUTION] -
  18298. * The resolution / device pixel ratio of the renderer.
  18299. * @param {boolean} [options.transparent] -
  18300. * **Deprecated since 6.0.0, Use `backgroundAlpha` instead.** \
  18301. * `true` sets `backgroundAlpha` to `0`, `false` sets `backgroundAlpha` to `1`.
  18302. * @param {boolean|'notMultiplied'} [options.useContextAlpha=true] -
  18303. * Pass-through value for canvas' context attribute `alpha`. This option is for cases where the
  18304. * canvas needs to be opaque, possibly for performance reasons on some older devices.
  18305. * If you want to set transparency, please use `backgroundAlpha`. \
  18306. * **WebGL Only:** When set to `'notMultiplied'`, the canvas' context attribute `alpha` will be
  18307. * set to `true` and `premultipliedAlpha` will be to `false`.
  18308. * @param {HTMLCanvasElement} [options.view=null] -
  18309. * The canvas to use as the view. If omitted, a new canvas will be created.
  18310. * @param {number} [options.width=800] - The width of the renderer's view.
  18311. */
  18312. function AbstractRenderer(type, options) {
  18313. if (type === void 0) { type = RENDERER_TYPE.UNKNOWN; }
  18314. var _this = _super.call(this) || this;
  18315. // Add the default render options
  18316. options = Object.assign({}, settings.RENDER_OPTIONS, options);
  18317. /**
  18318. * The supplied constructor options.
  18319. * @member {object}
  18320. * @readonly
  18321. */
  18322. _this.options = options;
  18323. /**
  18324. * The type of the renderer.
  18325. * @member {number}
  18326. * @default PIXI.RENDERER_TYPE.UNKNOWN
  18327. * @see PIXI.RENDERER_TYPE
  18328. */
  18329. _this.type = type;
  18330. /**
  18331. * Measurements of the screen. (0, 0, screenWidth, screenHeight).
  18332. *
  18333. * Its safe to use as filterArea or hitArea for the whole stage.
  18334. * @member {PIXI.Rectangle}
  18335. */
  18336. _this.screen = new Rectangle(0, 0, options.width, options.height);
  18337. /**
  18338. * The canvas element that everything is drawn to.
  18339. * @member {HTMLCanvasElement}
  18340. */
  18341. _this.view = options.view || settings.ADAPTER.createCanvas();
  18342. /**
  18343. * The resolution / device pixel ratio of the renderer.
  18344. * @member {number}
  18345. * @default PIXI.settings.RESOLUTION
  18346. */
  18347. _this.resolution = options.resolution || settings.RESOLUTION;
  18348. /**
  18349. * Pass-thru setting for the canvas' context `alpha` property. This is typically
  18350. * not something you need to fiddle with. If you want transparency, use `backgroundAlpha`.
  18351. * @member {boolean}
  18352. */
  18353. _this.useContextAlpha = options.useContextAlpha;
  18354. /**
  18355. * Whether CSS dimensions of canvas view should be resized to screen dimensions automatically.
  18356. * @member {boolean}
  18357. */
  18358. _this.autoDensity = !!options.autoDensity;
  18359. /**
  18360. * The value of the preserveDrawingBuffer flag affects whether or not the contents of
  18361. * the stencil buffer is retained after rendering.
  18362. * @member {boolean}
  18363. */
  18364. _this.preserveDrawingBuffer = options.preserveDrawingBuffer;
  18365. /**
  18366. * This sets if the CanvasRenderer will clear the canvas or not before the new render pass.
  18367. * If the scene is NOT transparent PixiJS will use a canvas sized fillRect operation every
  18368. * frame to set the canvas background color. If the scene is transparent PixiJS will use clearRect
  18369. * to clear the canvas every frame. Disable this by setting this to false. For example, if
  18370. * your game has a canvas filling background image you often don't need this set.
  18371. * @member {boolean}
  18372. * @default
  18373. */
  18374. _this.clearBeforeRender = options.clearBeforeRender;
  18375. /**
  18376. * The background color as a number.
  18377. * @member {number}
  18378. * @protected
  18379. */
  18380. _this._backgroundColor = 0x000000;
  18381. /**
  18382. * The background color as an [R, G, B, A] array.
  18383. * @member {number[]}
  18384. * @protected
  18385. */
  18386. _this._backgroundColorRgba = [0, 0, 0, 1];
  18387. /**
  18388. * The background color as a string.
  18389. * @member {string}
  18390. * @protected
  18391. */
  18392. _this._backgroundColorString = '#000000';
  18393. _this.backgroundColor = options.backgroundColor || _this._backgroundColor; // run bg color setter
  18394. _this.backgroundAlpha = options.backgroundAlpha;
  18395. // @deprecated
  18396. if (options.transparent !== undefined) {
  18397. deprecation('6.0.0', 'Option transparent is deprecated, please use backgroundAlpha instead.');
  18398. _this.useContextAlpha = options.transparent;
  18399. _this.backgroundAlpha = options.transparent ? 0 : 1;
  18400. }
  18401. /**
  18402. * The last root object that the renderer tried to render.
  18403. * @member {PIXI.DisplayObject}
  18404. * @protected
  18405. */
  18406. _this._lastObjectRendered = null;
  18407. /**
  18408. * Collection of plugins.
  18409. * @readonly
  18410. * @member {object}
  18411. */
  18412. _this.plugins = {};
  18413. return _this;
  18414. }
  18415. /**
  18416. * Initialize the plugins.
  18417. * @protected
  18418. * @param {object} staticMap - The dictionary of statically saved plugins.
  18419. */
  18420. AbstractRenderer.prototype.initPlugins = function (staticMap) {
  18421. for (var o in staticMap) {
  18422. this.plugins[o] = new (staticMap[o])(this);
  18423. }
  18424. };
  18425. Object.defineProperty(AbstractRenderer.prototype, "width", {
  18426. /**
  18427. * Same as view.width, actual number of pixels in the canvas by horizontal.
  18428. * @member {number}
  18429. * @readonly
  18430. * @default 800
  18431. */
  18432. get: function () {
  18433. return this.view.width;
  18434. },
  18435. enumerable: false,
  18436. configurable: true
  18437. });
  18438. Object.defineProperty(AbstractRenderer.prototype, "height", {
  18439. /**
  18440. * Same as view.height, actual number of pixels in the canvas by vertical.
  18441. * @member {number}
  18442. * @readonly
  18443. * @default 600
  18444. */
  18445. get: function () {
  18446. return this.view.height;
  18447. },
  18448. enumerable: false,
  18449. configurable: true
  18450. });
  18451. /**
  18452. * Resizes the screen and canvas as close as possible to the specified width and height.
  18453. * Canvas dimensions are multiplied by resolution and rounded to the nearest integers.
  18454. * The new canvas dimensions divided by the resolution become the new screen dimensions.
  18455. * @param desiredScreenWidth - The desired width of the screen.
  18456. * @param desiredScreenHeight - The desired height of the screen.
  18457. */
  18458. AbstractRenderer.prototype.resize = function (desiredScreenWidth, desiredScreenHeight) {
  18459. this.view.width = Math.round(desiredScreenWidth * this.resolution);
  18460. this.view.height = Math.round(desiredScreenHeight * this.resolution);
  18461. var screenWidth = this.view.width / this.resolution;
  18462. var screenHeight = this.view.height / this.resolution;
  18463. this.screen.width = screenWidth;
  18464. this.screen.height = screenHeight;
  18465. if (this.autoDensity) {
  18466. this.view.style.width = screenWidth + "px";
  18467. this.view.style.height = screenHeight + "px";
  18468. }
  18469. /**
  18470. * Fired after view has been resized.
  18471. * @event PIXI.Renderer#resize
  18472. * @param {number} screenWidth - The new width of the screen.
  18473. * @param {number} screenHeight - The new height of the screen.
  18474. */
  18475. this.emit('resize', screenWidth, screenHeight);
  18476. };
  18477. /**
  18478. * @ignore
  18479. */
  18480. AbstractRenderer.prototype.generateTexture = function (displayObject, options, resolution, region) {
  18481. if (options === void 0) { options = {}; }
  18482. // @deprecated parameters spread, use options instead
  18483. if (typeof options === 'number') {
  18484. deprecation('6.1.0', 'generateTexture options (scaleMode, resolution, region) are now object options.');
  18485. options = { scaleMode: options, resolution: resolution, region: region };
  18486. }
  18487. var manualRegion = options.region, textureOptions = __rest(options, ["region"]);
  18488. region = manualRegion || displayObject.getLocalBounds(null, true);
  18489. // minimum texture size is 1x1, 0x0 will throw an error
  18490. if (region.width === 0)
  18491. { region.width = 1; }
  18492. if (region.height === 0)
  18493. { region.height = 1; }
  18494. var renderTexture = RenderTexture.create(__assign({ width: region.width, height: region.height }, textureOptions));
  18495. tempMatrix.tx = -region.x;
  18496. tempMatrix.ty = -region.y;
  18497. this.render(displayObject, {
  18498. renderTexture: renderTexture,
  18499. clear: false,
  18500. transform: tempMatrix,
  18501. skipUpdateTransform: !!displayObject.parent
  18502. });
  18503. return renderTexture;
  18504. };
  18505. /**
  18506. * Removes everything from the renderer and optionally removes the Canvas DOM element.
  18507. * @param [removeView=false] - Removes the Canvas element from the DOM.
  18508. */
  18509. AbstractRenderer.prototype.destroy = function (removeView) {
  18510. for (var o in this.plugins) {
  18511. this.plugins[o].destroy();
  18512. this.plugins[o] = null;
  18513. }
  18514. if (removeView && this.view.parentNode) {
  18515. this.view.parentNode.removeChild(this.view);
  18516. }
  18517. var thisAny = this;
  18518. // null-ing all objects, that's a tradition!
  18519. thisAny.plugins = null;
  18520. thisAny.type = RENDERER_TYPE.UNKNOWN;
  18521. thisAny.view = null;
  18522. thisAny.screen = null;
  18523. thisAny._tempDisplayObjectParent = null;
  18524. thisAny.options = null;
  18525. this._backgroundColorRgba = null;
  18526. this._backgroundColorString = null;
  18527. this._lastObjectRendered = null;
  18528. };
  18529. Object.defineProperty(AbstractRenderer.prototype, "backgroundColor", {
  18530. /**
  18531. * The background color to fill if not transparent
  18532. * @member {number}
  18533. */
  18534. get: function () {
  18535. return this._backgroundColor;
  18536. },
  18537. set: function (value) {
  18538. this._backgroundColor = value;
  18539. this._backgroundColorString = hex2string(value);
  18540. hex2rgb(value, this._backgroundColorRgba);
  18541. },
  18542. enumerable: false,
  18543. configurable: true
  18544. });
  18545. Object.defineProperty(AbstractRenderer.prototype, "backgroundAlpha", {
  18546. /**
  18547. * The background color alpha. Setting this to 0 will make the canvas transparent.
  18548. * @member {number}
  18549. */
  18550. get: function () {
  18551. return this._backgroundColorRgba[3];
  18552. },
  18553. set: function (value) {
  18554. this._backgroundColorRgba[3] = value;
  18555. },
  18556. enumerable: false,
  18557. configurable: true
  18558. });
  18559. return AbstractRenderer;
  18560. }(eventemitter3));
  18561. var GLBuffer = /** @class */ (function () {
  18562. function GLBuffer(buffer) {
  18563. this.buffer = buffer || null;
  18564. this.updateID = -1;
  18565. this.byteLength = -1;
  18566. this.refCount = 0;
  18567. }
  18568. return GLBuffer;
  18569. }());
  18570. /**
  18571. * System plugin to the renderer to manage buffers.
  18572. *
  18573. * WebGL uses Buffers as a way to store objects to the GPU.
  18574. * This system makes working with them a lot easier.
  18575. *
  18576. * Buffers are used in three main places in WebGL
  18577. * - geometry information
  18578. * - Uniform information (via uniform buffer objects - a WebGL 2 only feature)
  18579. * - Transform feedback information. (WebGL 2 only feature)
  18580. *
  18581. * This system will handle the binding of buffers to the GPU as well as uploading
  18582. * them. With this system, you never need to work directly with GPU buffers, but instead work with
  18583. * the PIXI.Buffer class.
  18584. * @class
  18585. * @memberof PIXI
  18586. */
  18587. var BufferSystem = /** @class */ (function () {
  18588. /**
  18589. * @param {PIXI.Renderer} renderer - The renderer this System works for.
  18590. */
  18591. function BufferSystem(renderer) {
  18592. this.renderer = renderer;
  18593. this.managedBuffers = {};
  18594. this.boundBufferBases = {};
  18595. }
  18596. /**
  18597. * @ignore
  18598. */
  18599. BufferSystem.prototype.destroy = function () {
  18600. this.renderer = null;
  18601. };
  18602. /** Sets up the renderer context and necessary buffers. */
  18603. BufferSystem.prototype.contextChange = function () {
  18604. this.disposeAll(true);
  18605. this.gl = this.renderer.gl;
  18606. // TODO fill out...
  18607. this.CONTEXT_UID = this.renderer.CONTEXT_UID;
  18608. };
  18609. /**
  18610. * This binds specified buffer. On first run, it will create the webGL buffers for the context too
  18611. * @param buffer - the buffer to bind to the renderer
  18612. */
  18613. BufferSystem.prototype.bind = function (buffer) {
  18614. var _a = this, gl = _a.gl, CONTEXT_UID = _a.CONTEXT_UID;
  18615. var glBuffer = buffer._glBuffers[CONTEXT_UID] || this.createGLBuffer(buffer);
  18616. gl.bindBuffer(buffer.type, glBuffer.buffer);
  18617. };
  18618. /**
  18619. * Binds an uniform buffer to at the given index.
  18620. *
  18621. * A cache is used so a buffer will not be bound again if already bound.
  18622. * @param buffer - the buffer to bind
  18623. * @param index - the base index to bind it to.
  18624. */
  18625. BufferSystem.prototype.bindBufferBase = function (buffer, index) {
  18626. var _a = this, gl = _a.gl, CONTEXT_UID = _a.CONTEXT_UID;
  18627. if (this.boundBufferBases[index] !== buffer) {
  18628. var glBuffer = buffer._glBuffers[CONTEXT_UID] || this.createGLBuffer(buffer);
  18629. this.boundBufferBases[index] = buffer;
  18630. gl.bindBufferBase(gl.UNIFORM_BUFFER, index, glBuffer.buffer);
  18631. }
  18632. };
  18633. /**
  18634. * Binds a buffer whilst also binding its range.
  18635. * This will make the buffer start from the offset supplied rather than 0 when it is read.
  18636. * @param buffer - the buffer to bind
  18637. * @param index - the base index to bind at, defaults to 0
  18638. * @param offset - the offset to bind at (this is blocks of 256). 0 = 0, 1 = 256, 2 = 512 etc
  18639. */
  18640. BufferSystem.prototype.bindBufferRange = function (buffer, index, offset) {
  18641. var _a = this, gl = _a.gl, CONTEXT_UID = _a.CONTEXT_UID;
  18642. offset = offset || 0;
  18643. var glBuffer = buffer._glBuffers[CONTEXT_UID] || this.createGLBuffer(buffer);
  18644. gl.bindBufferRange(gl.UNIFORM_BUFFER, index || 0, glBuffer.buffer, offset * 256, 256);
  18645. };
  18646. /**
  18647. * Will ensure the data in the buffer is uploaded to the GPU.
  18648. * @param {PIXI.Buffer} buffer - the buffer to update
  18649. */
  18650. BufferSystem.prototype.update = function (buffer) {
  18651. var _a = this, gl = _a.gl, CONTEXT_UID = _a.CONTEXT_UID;
  18652. var glBuffer = buffer._glBuffers[CONTEXT_UID];
  18653. if (buffer._updateID === glBuffer.updateID) {
  18654. return;
  18655. }
  18656. glBuffer.updateID = buffer._updateID;
  18657. gl.bindBuffer(buffer.type, glBuffer.buffer);
  18658. if (glBuffer.byteLength >= buffer.data.byteLength) {
  18659. // offset is always zero for now!
  18660. gl.bufferSubData(buffer.type, 0, buffer.data);
  18661. }
  18662. else {
  18663. var drawType = buffer.static ? gl.STATIC_DRAW : gl.DYNAMIC_DRAW;
  18664. glBuffer.byteLength = buffer.data.byteLength;
  18665. gl.bufferData(buffer.type, buffer.data, drawType);
  18666. }
  18667. };
  18668. /**
  18669. * Disposes buffer
  18670. * @param {PIXI.Buffer} buffer - buffer with data
  18671. * @param {boolean} [contextLost=false] - If context was lost, we suppress deleteVertexArray
  18672. */
  18673. BufferSystem.prototype.dispose = function (buffer, contextLost) {
  18674. if (!this.managedBuffers[buffer.id]) {
  18675. return;
  18676. }
  18677. delete this.managedBuffers[buffer.id];
  18678. var glBuffer = buffer._glBuffers[this.CONTEXT_UID];
  18679. var gl = this.gl;
  18680. buffer.disposeRunner.remove(this);
  18681. if (!glBuffer) {
  18682. return;
  18683. }
  18684. if (!contextLost) {
  18685. gl.deleteBuffer(glBuffer.buffer);
  18686. }
  18687. delete buffer._glBuffers[this.CONTEXT_UID];
  18688. };
  18689. /**
  18690. * dispose all WebGL resources of all managed buffers
  18691. * @param {boolean} [contextLost=false] - If context was lost, we suppress `gl.delete` calls
  18692. */
  18693. BufferSystem.prototype.disposeAll = function (contextLost) {
  18694. var all = Object.keys(this.managedBuffers);
  18695. for (var i = 0; i < all.length; i++) {
  18696. this.dispose(this.managedBuffers[all[i]], contextLost);
  18697. }
  18698. };
  18699. /**
  18700. * creates and attaches a GLBuffer object tied to the current context.
  18701. * @param buffer
  18702. * @protected
  18703. */
  18704. BufferSystem.prototype.createGLBuffer = function (buffer) {
  18705. var _a = this, CONTEXT_UID = _a.CONTEXT_UID, gl = _a.gl;
  18706. buffer._glBuffers[CONTEXT_UID] = new GLBuffer(gl.createBuffer());
  18707. this.managedBuffers[buffer.id] = buffer;
  18708. buffer.disposeRunner.add(this);
  18709. return buffer._glBuffers[CONTEXT_UID];
  18710. };
  18711. return BufferSystem;
  18712. }());
  18713. /**
  18714. * The Renderer draws the scene and all its content onto a WebGL enabled canvas.
  18715. *
  18716. * This renderer should be used for browsers that support WebGL.
  18717. *
  18718. * This renderer works by automatically managing WebGLBatchesm, so no need for Sprite Batches or Sprite Clouds.
  18719. * Don't forget to add the view to your DOM or you will not see anything!
  18720. *
  18721. * Renderer is composed of systems that manage specific tasks. The following systems are added by default
  18722. * whenever you create a renderer:
  18723. *
  18724. * | System | Description |
  18725. * | ------------------------------------ | ----------------------------------------------------------------------------- |
  18726. * | {@link PIXI.BatchSystem} | This manages object renderers that defer rendering until a flush. |
  18727. * | {@link PIXI.ContextSystem} | This manages the WebGL context and extensions. |
  18728. * | {@link PIXI.EventSystem} | This manages UI events. |
  18729. * | {@link PIXI.FilterSystem} | This manages the filtering pipeline for post-processing effects. |
  18730. * | {@link PIXI.FramebufferSystem} | This manages framebuffers, which are used for offscreen rendering. |
  18731. * | {@link PIXI.GeometrySystem} | This manages geometries & buffers, which are used to draw object meshes. |
  18732. * | {@link PIXI.MaskSystem} | This manages masking operations. |
  18733. * | {@link PIXI.ProjectionSystem} | This manages the `projectionMatrix`, used by shaders to get NDC coordinates. |
  18734. * | {@link PIXI.RenderTextureSystem} | This manages render-textures, which are an abstraction over framebuffers. |
  18735. * | {@link PIXI.ScissorSystem} | This handles scissor masking, and is used internally by {@link MaskSystem} |
  18736. * | {@link PIXI.ShaderSystem} | This manages shaders, programs that run on the GPU to calculate 'em pixels. |
  18737. * | {@link PIXI.StateSystem} | This manages the WebGL state variables like blend mode, depth testing, etc. |
  18738. * | {@link PIXI.StencilSystem} | This handles stencil masking, and is used internally by {@link MaskSystem} |
  18739. * | {@link PIXI.TextureSystem} | This manages textures and their resources on the GPU. |
  18740. * | {@link PIXI.TextureGCSystem} | This will automatically remove textures from the GPU if they are not used. |
  18741. *
  18742. * The breadth of the API surface provided by the renderer is contained within these systems.
  18743. * @memberof PIXI
  18744. */
  18745. var Renderer = /** @class */ (function (_super) {
  18746. __extends$i(Renderer, _super);
  18747. /**
  18748. * @param {PIXI.IRendererOptions} [options] - The optional renderer parameters.
  18749. * @param {boolean} [options.antialias=false] -
  18750. * **WebGL Only.** Whether to enable anti-aliasing. This may affect performance.
  18751. * @param {boolean} [options.autoDensity=false] -
  18752. * Whether the CSS dimensions of the renderer's view should be resized automatically.
  18753. * @param {number} [options.backgroundAlpha=1] -
  18754. * Transparency of the background color, value from `0` (fully transparent) to `1` (fully opaque).
  18755. * @param {number} [options.backgroundColor=0x000000] -
  18756. * The background color used to clear the canvas. It accepts hex numbers (e.g. `0xff0000`).
  18757. * @param {boolean} [options.clearBeforeRender=true] - Whether to clear the canvas before new render passes.
  18758. * @param {PIXI.IRenderingContext} [options.context] - **WebGL Only.** User-provided WebGL rendering context object.
  18759. * @param {number} [options.height=600] - The height of the renderer's view.
  18760. * @param {string} [options.powerPreference] -
  18761. * **WebGL Only.** A hint indicating what configuration of GPU is suitable for the WebGL context,
  18762. * can be `'default'`, `'high-performance'` or `'low-power'`.
  18763. * Setting to `'high-performance'` will prioritize rendering performance over power consumption,
  18764. * while setting to `'low-power'` will prioritize power saving over rendering performance.
  18765. * @param {boolean} [options.premultipliedAlpha=true] -
  18766. * **WebGL Only.** Whether the compositor will assume the drawing buffer contains colors with premultiplied alpha.
  18767. * @param {boolean} [options.preserveDrawingBuffer=false] -
  18768. * **WebGL Only.** Whether to enable drawing buffer preservation. If enabled, the drawing buffer will preserve
  18769. * its value until cleared or overwritten. Enable this if you need to call `toDataUrl` on the WebGL context.
  18770. * @param {number} [options.resolution=PIXI.settings.RESOLUTION] -
  18771. * The resolution / device pixel ratio of the renderer.
  18772. * @param {boolean} [options.transparent] -
  18773. * **Deprecated since 6.0.0, Use `backgroundAlpha` instead.** \
  18774. * `true` sets `backgroundAlpha` to `0`, `false` sets `backgroundAlpha` to `1`.
  18775. * @param {boolean|'notMultiplied'} [options.useContextAlpha=true] -
  18776. * Pass-through value for canvas' context attribute `alpha`. This option is for cases where the
  18777. * canvas needs to be opaque, possibly for performance reasons on some older devices.
  18778. * If you want to set transparency, please use `backgroundAlpha`. \
  18779. * **WebGL Only:** When set to `'notMultiplied'`, the canvas' context attribute `alpha` will be
  18780. * set to `true` and `premultipliedAlpha` will be to `false`.
  18781. * @param {HTMLCanvasElement} [options.view=null] -
  18782. * The canvas to use as the view. If omitted, a new canvas will be created.
  18783. * @param {number} [options.width=800] - The width of the renderer's view.
  18784. */
  18785. function Renderer(options) {
  18786. var _this = _super.call(this, RENDERER_TYPE.WEBGL, options) || this;
  18787. // the options will have been modified here in the super constructor with pixi's default settings..
  18788. options = _this.options;
  18789. _this.gl = null;
  18790. _this.CONTEXT_UID = 0;
  18791. _this.runners = {
  18792. destroy: new Runner('destroy'),
  18793. contextChange: new Runner('contextChange'),
  18794. reset: new Runner('reset'),
  18795. update: new Runner('update'),
  18796. postrender: new Runner('postrender'),
  18797. prerender: new Runner('prerender'),
  18798. resize: new Runner('resize'),
  18799. };
  18800. _this.runners.contextChange.add(_this);
  18801. _this.globalUniforms = new UniformGroup({
  18802. projectionMatrix: new Matrix(),
  18803. }, true);
  18804. _this.addSystem(MaskSystem, 'mask')
  18805. .addSystem(ContextSystem, 'context')
  18806. .addSystem(StateSystem, 'state')
  18807. .addSystem(ShaderSystem, 'shader')
  18808. .addSystem(TextureSystem, 'texture')
  18809. .addSystem(BufferSystem, 'buffer')
  18810. .addSystem(GeometrySystem, 'geometry')
  18811. .addSystem(FramebufferSystem, 'framebuffer')
  18812. .addSystem(ScissorSystem, 'scissor')
  18813. .addSystem(StencilSystem, 'stencil')
  18814. .addSystem(ProjectionSystem, 'projection')
  18815. .addSystem(TextureGCSystem, 'textureGC')
  18816. .addSystem(FilterSystem, 'filter')
  18817. .addSystem(RenderTextureSystem, 'renderTexture')
  18818. .addSystem(BatchSystem, 'batch');
  18819. _this.initPlugins(Renderer.__plugins);
  18820. _this.multisample = undefined;
  18821. /*
  18822. * The options passed in to create a new WebGL context.
  18823. */
  18824. if (options.context) {
  18825. _this.context.initFromContext(options.context);
  18826. }
  18827. else {
  18828. _this.context.initFromOptions({
  18829. alpha: !!_this.useContextAlpha,
  18830. antialias: options.antialias,
  18831. premultipliedAlpha: _this.useContextAlpha && _this.useContextAlpha !== 'notMultiplied',
  18832. stencil: true,
  18833. preserveDrawingBuffer: options.preserveDrawingBuffer,
  18834. powerPreference: _this.options.powerPreference,
  18835. });
  18836. }
  18837. _this.renderingToScreen = true;
  18838. sayHello(_this.context.webGLVersion === 2 ? 'WebGL 2' : 'WebGL 1');
  18839. _this.resize(_this.options.width, _this.options.height);
  18840. return _this;
  18841. }
  18842. /**
  18843. * Create renderer if WebGL is available. Overrideable
  18844. * by the **@pixi/canvas-renderer** package to allow fallback.
  18845. * throws error if WebGL is not available.
  18846. * @param options
  18847. * @private
  18848. */
  18849. Renderer.create = function (options) {
  18850. if (isWebGLSupported()) {
  18851. return new Renderer(options);
  18852. }
  18853. throw new Error('WebGL unsupported in this browser, use "pixi.js-legacy" for fallback canvas2d support.');
  18854. };
  18855. Renderer.prototype.contextChange = function () {
  18856. var gl = this.gl;
  18857. var samples;
  18858. if (this.context.webGLVersion === 1) {
  18859. var framebuffer = gl.getParameter(gl.FRAMEBUFFER_BINDING);
  18860. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  18861. samples = gl.getParameter(gl.SAMPLES);
  18862. gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
  18863. }
  18864. else {
  18865. var framebuffer = gl.getParameter(gl.DRAW_FRAMEBUFFER_BINDING);
  18866. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, null);
  18867. samples = gl.getParameter(gl.SAMPLES);
  18868. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, framebuffer);
  18869. }
  18870. if (samples >= MSAA_QUALITY.HIGH) {
  18871. this.multisample = MSAA_QUALITY.HIGH;
  18872. }
  18873. else if (samples >= MSAA_QUALITY.MEDIUM) {
  18874. this.multisample = MSAA_QUALITY.MEDIUM;
  18875. }
  18876. else if (samples >= MSAA_QUALITY.LOW) {
  18877. this.multisample = MSAA_QUALITY.LOW;
  18878. }
  18879. else {
  18880. this.multisample = MSAA_QUALITY.NONE;
  18881. }
  18882. };
  18883. /**
  18884. * Add a new system to the renderer.
  18885. * @param ClassRef - Class reference
  18886. * @param name - Property name for system, if not specified
  18887. * will use a static `name` property on the class itself. This
  18888. * name will be assigned as s property on the Renderer so make
  18889. * sure it doesn't collide with properties on Renderer.
  18890. * @returns Return instance of renderer
  18891. */
  18892. Renderer.prototype.addSystem = function (ClassRef, name) {
  18893. var system = new ClassRef(this);
  18894. if (this[name]) {
  18895. throw new Error("Whoops! The name \"" + name + "\" is already in use");
  18896. }
  18897. this[name] = system;
  18898. for (var i in this.runners) {
  18899. this.runners[i].add(system);
  18900. }
  18901. /**
  18902. * Fired after rendering finishes.
  18903. * @event PIXI.Renderer#postrender
  18904. */
  18905. /**
  18906. * Fired before rendering starts.
  18907. * @event PIXI.Renderer#prerender
  18908. */
  18909. /**
  18910. * Fired when the WebGL context is set.
  18911. * @event PIXI.Renderer#context
  18912. * @param {WebGLRenderingContext} gl - WebGL context.
  18913. */
  18914. return this;
  18915. };
  18916. /**
  18917. * @ignore
  18918. */
  18919. Renderer.prototype.render = function (displayObject, options) {
  18920. var renderTexture;
  18921. var clear;
  18922. var transform;
  18923. var skipUpdateTransform;
  18924. if (options) {
  18925. if (options instanceof RenderTexture) {
  18926. deprecation('6.0.0', 'Renderer#render arguments changed, use options instead.');
  18927. /* eslint-disable prefer-rest-params */
  18928. renderTexture = options;
  18929. clear = arguments[2];
  18930. transform = arguments[3];
  18931. skipUpdateTransform = arguments[4];
  18932. /* eslint-enable prefer-rest-params */
  18933. }
  18934. else {
  18935. renderTexture = options.renderTexture;
  18936. clear = options.clear;
  18937. transform = options.transform;
  18938. skipUpdateTransform = options.skipUpdateTransform;
  18939. }
  18940. }
  18941. // can be handy to know!
  18942. this.renderingToScreen = !renderTexture;
  18943. this.runners.prerender.emit();
  18944. this.emit('prerender');
  18945. // apply a transform at a GPU level
  18946. this.projection.transform = transform;
  18947. // no point rendering if our context has been blown up!
  18948. if (this.context.isLost) {
  18949. return;
  18950. }
  18951. if (!renderTexture) {
  18952. this._lastObjectRendered = displayObject;
  18953. }
  18954. if (!skipUpdateTransform) {
  18955. // update the scene graph
  18956. var cacheParent = displayObject.enableTempParent();
  18957. displayObject.updateTransform();
  18958. displayObject.disableTempParent(cacheParent);
  18959. // displayObject.hitArea = //TODO add a temp hit area
  18960. }
  18961. this.renderTexture.bind(renderTexture);
  18962. this.batch.currentRenderer.start();
  18963. if (clear !== undefined ? clear : this.clearBeforeRender) {
  18964. this.renderTexture.clear();
  18965. }
  18966. displayObject.render(this);
  18967. // apply transform..
  18968. this.batch.currentRenderer.flush();
  18969. if (renderTexture) {
  18970. renderTexture.baseTexture.update();
  18971. }
  18972. this.runners.postrender.emit();
  18973. // reset transform after render
  18974. this.projection.transform = null;
  18975. this.emit('postrender');
  18976. };
  18977. /**
  18978. * @override
  18979. * @ignore
  18980. */
  18981. Renderer.prototype.generateTexture = function (displayObject, options, resolution, region) {
  18982. if (options === void 0) { options = {}; }
  18983. var renderTexture = _super.prototype.generateTexture.call(this, displayObject, options, resolution, region);
  18984. this.framebuffer.blit();
  18985. return renderTexture;
  18986. };
  18987. /**
  18988. * Resizes the WebGL view to the specified width and height.
  18989. * @param desiredScreenWidth - The desired width of the screen.
  18990. * @param desiredScreenHeight - The desired height of the screen.
  18991. */
  18992. Renderer.prototype.resize = function (desiredScreenWidth, desiredScreenHeight) {
  18993. _super.prototype.resize.call(this, desiredScreenWidth, desiredScreenHeight);
  18994. this.runners.resize.emit(this.screen.height, this.screen.width);
  18995. };
  18996. /**
  18997. * Resets the WebGL state so you can render things however you fancy!
  18998. * @returns Returns itself.
  18999. */
  19000. Renderer.prototype.reset = function () {
  19001. this.runners.reset.emit();
  19002. return this;
  19003. };
  19004. /** Clear the frame buffer. */
  19005. Renderer.prototype.clear = function () {
  19006. this.renderTexture.bind();
  19007. this.renderTexture.clear();
  19008. };
  19009. /**
  19010. * Removes everything from the renderer (event listeners, spritebatch, etc...)
  19011. * @param [removeView=false] - Removes the Canvas element from the DOM.
  19012. * See: https://github.com/pixijs/pixi.js/issues/2233
  19013. */
  19014. Renderer.prototype.destroy = function (removeView) {
  19015. this.runners.destroy.emit();
  19016. for (var r in this.runners) {
  19017. this.runners[r].destroy();
  19018. }
  19019. // call base destroy
  19020. _super.prototype.destroy.call(this, removeView);
  19021. // TODO nullify all the managers..
  19022. this.gl = null;
  19023. };
  19024. Object.defineProperty(Renderer.prototype, "extract", {
  19025. /**
  19026. * Please use `plugins.extract` instead.
  19027. * @member {PIXI.Extract} extract
  19028. * @deprecated since 6.0.0
  19029. * @readonly
  19030. */
  19031. get: function () {
  19032. deprecation('6.0.0', 'Renderer#extract has been deprecated, please use Renderer#plugins.extract instead.');
  19033. return this.plugins.extract;
  19034. },
  19035. enumerable: false,
  19036. configurable: true
  19037. });
  19038. /**
  19039. * Use the {@link PIXI.extensions.add} API to register plugins.
  19040. * @deprecated since 6.5.0
  19041. * @param pluginName - The name of the plugin.
  19042. * @param ctor - The constructor function or class for the plugin.
  19043. */
  19044. Renderer.registerPlugin = function (pluginName, ctor) {
  19045. deprecation('6.5.0', 'Renderer.registerPlugin() has been deprecated, please use extensions.add() instead.');
  19046. extensions.add({
  19047. name: pluginName,
  19048. type: ExtensionType.RendererPlugin,
  19049. ref: ctor,
  19050. });
  19051. };
  19052. /**
  19053. * Collection of installed plugins. These are included by default in PIXI, but can be excluded
  19054. * by creating a custom build. Consult the README for more information about creating custom
  19055. * builds and excluding plugins.
  19056. * @readonly
  19057. * @property {PIXI.AccessibilityManager} accessibility Support tabbing interactive elements.
  19058. * @property {PIXI.Extract} extract Extract image data from renderer.
  19059. * @property {PIXI.InteractionManager} interaction Handles mouse, touch and pointer events.
  19060. * @property {PIXI.ParticleRenderer} particle Renderer for ParticleContainer objects.
  19061. * @property {PIXI.Prepare} prepare Pre-render display objects.
  19062. * @property {PIXI.BatchRenderer} batch Batching of Sprite, Graphics and Mesh objects.
  19063. * @property {PIXI.TilingSpriteRenderer} tilingSprite Renderer for TilingSprite objects.
  19064. */
  19065. Renderer.__plugins = {};
  19066. return Renderer;
  19067. }(AbstractRenderer));
  19068. // Handle registration of extensions
  19069. extensions.handleByMap(ExtensionType.RendererPlugin, Renderer.__plugins);
  19070. /**
  19071. * This helper function will automatically detect which renderer you should be using.
  19072. * WebGL is the preferred renderer as it is a lot faster. If WebGL is not supported by
  19073. * the browser then this function will return a canvas renderer.
  19074. * @memberof PIXI
  19075. * @function autoDetectRenderer
  19076. * @param {PIXI.IRendererOptionsAuto} [options] - The optional renderer parameters.
  19077. * @param {boolean} [options.antialias=false] -
  19078. * **WebGL Only.** Whether to enable anti-aliasing. This may affect performance.
  19079. * @param {boolean} [options.autoDensity=false] -
  19080. * Whether the CSS dimensions of the renderer's view should be resized automatically.
  19081. * @param {number} [options.backgroundAlpha=1] -
  19082. * Transparency of the background color, value from `0` (fully transparent) to `1` (fully opaque).
  19083. * @param {number} [options.backgroundColor=0x000000] -
  19084. * The background color used to clear the canvas. It accepts hex numbers (e.g. `0xff0000`).
  19085. * @param {boolean} [options.clearBeforeRender=true] - Whether to clear the canvas before new render passes.
  19086. * @param {PIXI.IRenderingContext} [options.context] - **WebGL Only.** User-provided WebGL rendering context object.
  19087. * @param {boolean} [options.forceCanvas=false] -
  19088. * Force using {@link PIXI.CanvasRenderer}, even if WebGL is available. This option only is available when
  19089. * using **pixi.js-legacy** or **@pixi/canvas-renderer** packages, otherwise it is ignored.
  19090. * @param {number} [options.height=600] - The height of the renderer's view.
  19091. * @param {string} [options.powerPreference] -
  19092. * **WebGL Only.** A hint indicating what configuration of GPU is suitable for the WebGL context,
  19093. * can be `'default'`, `'high-performance'` or `'low-power'`.
  19094. * Setting to `'high-performance'` will prioritize rendering performance over power consumption,
  19095. * while setting to `'low-power'` will prioritize power saving over rendering performance.
  19096. * @param {boolean} [options.premultipliedAlpha=true] -
  19097. * **WebGL Only.** Whether the compositor will assume the drawing buffer contains colors with premultiplied alpha.
  19098. * @param {boolean} [options.preserveDrawingBuffer=false] -
  19099. * **WebGL Only.** Whether to enable drawing buffer preservation. If enabled, the drawing buffer will preserve
  19100. * its value until cleared or overwritten. Enable this if you need to call `toDataUrl` on the WebGL context.
  19101. * @param {number} [options.resolution=PIXI.settings.RESOLUTION] -
  19102. * The resolution / device pixel ratio of the renderer.
  19103. * @param {boolean} [options.transparent] -
  19104. * **Deprecated since 6.0.0, Use `backgroundAlpha` instead.** \
  19105. * `true` sets `backgroundAlpha` to `0`, `false` sets `backgroundAlpha` to `1`.
  19106. * @param {boolean|'notMultiplied'} [options.useContextAlpha=true] -
  19107. * Pass-through value for canvas' context attribute `alpha`. This option is for cases where the
  19108. * canvas needs to be opaque, possibly for performance reasons on some older devices.
  19109. * If you want to set transparency, please use `backgroundAlpha`. \
  19110. * **WebGL Only:** When set to `'notMultiplied'`, the canvas' context attribute `alpha` will be
  19111. * set to `true` and `premultipliedAlpha` will be to `false`.
  19112. * @param {HTMLCanvasElement} [options.view=null] -
  19113. * The canvas to use as the view. If omitted, a new canvas will be created.
  19114. * @param {number} [options.width=800] - The width of the renderer's view.
  19115. * @returns {PIXI.Renderer|PIXI.CanvasRenderer}
  19116. * Returns {@link PIXI.Renderer} if WebGL is available, otherwise {@link PIXI.CanvasRenderer}.
  19117. */
  19118. function autoDetectRenderer(options) {
  19119. return Renderer.create(options);
  19120. }
  19121. var $defaultVertex = "attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n vTextureCoord = aTextureCoord;\n}";
  19122. var $defaultFilterVertex = "attribute vec2 aVertexPosition;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nuniform vec4 inputSize;\nuniform vec4 outputFrame;\n\nvec4 filterVertexPosition( void )\n{\n vec2 position = aVertexPosition * max(outputFrame.zw, vec2(0.)) + outputFrame.xy;\n\n return vec4((projectionMatrix * vec3(position, 1.0)).xy, 0.0, 1.0);\n}\n\nvec2 filterTextureCoord( void )\n{\n return aVertexPosition * (outputFrame.zw * inputSize.zw);\n}\n\nvoid main(void)\n{\n gl_Position = filterVertexPosition();\n vTextureCoord = filterTextureCoord();\n}\n";
  19123. /**
  19124. * Default vertex shader
  19125. * @memberof PIXI
  19126. * @member {string} defaultVertex
  19127. */
  19128. /**
  19129. * Default filter vertex shader
  19130. * @memberof PIXI
  19131. * @member {string} defaultFilterVertex
  19132. */
  19133. // NOTE: This black magic is so that @microsoft/api-extractor does not complain! This explicitly specifies the types
  19134. // of defaultVertex, defaultFilterVertex.
  19135. var defaultVertex$1 = $defaultVertex;
  19136. var defaultFilterVertex = $defaultFilterVertex;
  19137. /**
  19138. * Use the ISystem interface instead.
  19139. * @deprecated since 6.1.0
  19140. * @memberof PIXI
  19141. */
  19142. var System = /** @class */ (function () {
  19143. /**
  19144. * @param renderer - Reference to Renderer
  19145. */
  19146. function System(renderer) {
  19147. deprecation('6.1.0', 'System class is deprecated, implemement ISystem interface instead.');
  19148. this.renderer = renderer;
  19149. }
  19150. /** Destroy and don't use after this. */
  19151. System.prototype.destroy = function () {
  19152. this.renderer = null;
  19153. };
  19154. return System;
  19155. }());
  19156. /**
  19157. * Used by the batcher to draw batches.
  19158. * Each one of these contains all information required to draw a bound geometry.
  19159. * @memberof PIXI
  19160. */
  19161. var BatchDrawCall = /** @class */ (function () {
  19162. function BatchDrawCall() {
  19163. this.texArray = null;
  19164. this.blend = 0;
  19165. this.type = DRAW_MODES.TRIANGLES;
  19166. this.start = 0;
  19167. this.size = 0;
  19168. this.data = null;
  19169. }
  19170. return BatchDrawCall;
  19171. }());
  19172. /**
  19173. * Used by the batcher to build texture batches.
  19174. * Holds list of textures and their respective locations.
  19175. * @memberof PIXI
  19176. */
  19177. var BatchTextureArray = /** @class */ (function () {
  19178. function BatchTextureArray() {
  19179. this.elements = [];
  19180. this.ids = [];
  19181. this.count = 0;
  19182. }
  19183. BatchTextureArray.prototype.clear = function () {
  19184. for (var i = 0; i < this.count; i++) {
  19185. this.elements[i] = null;
  19186. }
  19187. this.count = 0;
  19188. };
  19189. return BatchTextureArray;
  19190. }());
  19191. /**
  19192. * Flexible wrapper around `ArrayBuffer` that also provides typed array views on demand.
  19193. * @memberof PIXI
  19194. */
  19195. var ViewableBuffer = /** @class */ (function () {
  19196. function ViewableBuffer(sizeOrBuffer) {
  19197. if (typeof sizeOrBuffer === 'number') {
  19198. this.rawBinaryData = new ArrayBuffer(sizeOrBuffer);
  19199. }
  19200. else if (sizeOrBuffer instanceof Uint8Array) {
  19201. this.rawBinaryData = sizeOrBuffer.buffer;
  19202. }
  19203. else {
  19204. this.rawBinaryData = sizeOrBuffer;
  19205. }
  19206. this.uint32View = new Uint32Array(this.rawBinaryData);
  19207. this.float32View = new Float32Array(this.rawBinaryData);
  19208. }
  19209. Object.defineProperty(ViewableBuffer.prototype, "int8View", {
  19210. /** View on the raw binary data as a `Int8Array`. */
  19211. get: function () {
  19212. if (!this._int8View) {
  19213. this._int8View = new Int8Array(this.rawBinaryData);
  19214. }
  19215. return this._int8View;
  19216. },
  19217. enumerable: false,
  19218. configurable: true
  19219. });
  19220. Object.defineProperty(ViewableBuffer.prototype, "uint8View", {
  19221. /** View on the raw binary data as a `Uint8Array`. */
  19222. get: function () {
  19223. if (!this._uint8View) {
  19224. this._uint8View = new Uint8Array(this.rawBinaryData);
  19225. }
  19226. return this._uint8View;
  19227. },
  19228. enumerable: false,
  19229. configurable: true
  19230. });
  19231. Object.defineProperty(ViewableBuffer.prototype, "int16View", {
  19232. /** View on the raw binary data as a `Int16Array`. */
  19233. get: function () {
  19234. if (!this._int16View) {
  19235. this._int16View = new Int16Array(this.rawBinaryData);
  19236. }
  19237. return this._int16View;
  19238. },
  19239. enumerable: false,
  19240. configurable: true
  19241. });
  19242. Object.defineProperty(ViewableBuffer.prototype, "uint16View", {
  19243. /** View on the raw binary data as a `Uint16Array`. */
  19244. get: function () {
  19245. if (!this._uint16View) {
  19246. this._uint16View = new Uint16Array(this.rawBinaryData);
  19247. }
  19248. return this._uint16View;
  19249. },
  19250. enumerable: false,
  19251. configurable: true
  19252. });
  19253. Object.defineProperty(ViewableBuffer.prototype, "int32View", {
  19254. /** View on the raw binary data as a `Int32Array`. */
  19255. get: function () {
  19256. if (!this._int32View) {
  19257. this._int32View = new Int32Array(this.rawBinaryData);
  19258. }
  19259. return this._int32View;
  19260. },
  19261. enumerable: false,
  19262. configurable: true
  19263. });
  19264. /**
  19265. * Returns the view of the given type.
  19266. * @param type - One of `int8`, `uint8`, `int16`,
  19267. * `uint16`, `int32`, `uint32`, and `float32`.
  19268. * @returns - typed array of given type
  19269. */
  19270. ViewableBuffer.prototype.view = function (type) {
  19271. return this[type + "View"];
  19272. };
  19273. /** Destroys all buffer references. Do not use after calling this. */
  19274. ViewableBuffer.prototype.destroy = function () {
  19275. this.rawBinaryData = null;
  19276. this._int8View = null;
  19277. this._uint8View = null;
  19278. this._int16View = null;
  19279. this._uint16View = null;
  19280. this._int32View = null;
  19281. this.uint32View = null;
  19282. this.float32View = null;
  19283. };
  19284. ViewableBuffer.sizeOf = function (type) {
  19285. switch (type) {
  19286. case 'int8':
  19287. case 'uint8':
  19288. return 1;
  19289. case 'int16':
  19290. case 'uint16':
  19291. return 2;
  19292. case 'int32':
  19293. case 'uint32':
  19294. case 'float32':
  19295. return 4;
  19296. default:
  19297. throw new Error(type + " isn't a valid view type");
  19298. }
  19299. };
  19300. return ViewableBuffer;
  19301. }());
  19302. /**
  19303. * Renderer dedicated to drawing and batching sprites.
  19304. *
  19305. * This is the default batch renderer. It buffers objects
  19306. * with texture-based geometries and renders them in
  19307. * batches. It uploads multiple textures to the GPU to
  19308. * reduce to the number of draw calls.
  19309. * @memberof PIXI
  19310. */
  19311. var AbstractBatchRenderer = /** @class */ (function (_super) {
  19312. __extends$i(AbstractBatchRenderer, _super);
  19313. /**
  19314. * This will hook onto the renderer's `contextChange`
  19315. * and `prerender` signals.
  19316. * @param {PIXI.Renderer} renderer - The renderer this works for.
  19317. */
  19318. function AbstractBatchRenderer(renderer) {
  19319. var _this = _super.call(this, renderer) || this;
  19320. _this.shaderGenerator = null;
  19321. _this.geometryClass = null;
  19322. _this.vertexSize = null;
  19323. _this.state = State.for2d();
  19324. _this.size = settings.SPRITE_BATCH_SIZE * 4;
  19325. _this._vertexCount = 0;
  19326. _this._indexCount = 0;
  19327. _this._bufferedElements = [];
  19328. _this._bufferedTextures = [];
  19329. _this._bufferSize = 0;
  19330. _this._shader = null;
  19331. _this._packedGeometries = [];
  19332. _this._packedGeometryPoolSize = 2;
  19333. _this._flushId = 0;
  19334. _this._aBuffers = {};
  19335. _this._iBuffers = {};
  19336. _this.MAX_TEXTURES = 1;
  19337. _this.renderer.on('prerender', _this.onPrerender, _this);
  19338. renderer.runners.contextChange.add(_this);
  19339. _this._dcIndex = 0;
  19340. _this._aIndex = 0;
  19341. _this._iIndex = 0;
  19342. _this._attributeBuffer = null;
  19343. _this._indexBuffer = null;
  19344. _this._tempBoundTextures = [];
  19345. return _this;
  19346. }
  19347. /**
  19348. * Handles the `contextChange` signal.
  19349. *
  19350. * It calculates `this.MAX_TEXTURES` and allocating the packed-geometry object pool.
  19351. */
  19352. AbstractBatchRenderer.prototype.contextChange = function () {
  19353. var gl = this.renderer.gl;
  19354. if (settings.PREFER_ENV === ENV.WEBGL_LEGACY) {
  19355. this.MAX_TEXTURES = 1;
  19356. }
  19357. else {
  19358. // step 1: first check max textures the GPU can handle.
  19359. this.MAX_TEXTURES = Math.min(gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS), settings.SPRITE_MAX_TEXTURES);
  19360. // step 2: check the maximum number of if statements the shader can have too..
  19361. this.MAX_TEXTURES = checkMaxIfStatementsInShader(this.MAX_TEXTURES, gl);
  19362. }
  19363. this._shader = this.shaderGenerator.generateShader(this.MAX_TEXTURES);
  19364. // we use the second shader as the first one depending on your browser
  19365. // may omit aTextureId as it is not used by the shader so is optimized out.
  19366. for (var i = 0; i < this._packedGeometryPoolSize; i++) {
  19367. /* eslint-disable max-len */
  19368. this._packedGeometries[i] = new (this.geometryClass)();
  19369. }
  19370. this.initFlushBuffers();
  19371. };
  19372. /** Makes sure that static and dynamic flush pooled objects have correct dimensions. */
  19373. AbstractBatchRenderer.prototype.initFlushBuffers = function () {
  19374. var _drawCallPool = AbstractBatchRenderer._drawCallPool, _textureArrayPool = AbstractBatchRenderer._textureArrayPool;
  19375. // max draw calls
  19376. var MAX_SPRITES = this.size / 4;
  19377. // max texture arrays
  19378. var MAX_TA = Math.floor(MAX_SPRITES / this.MAX_TEXTURES) + 1;
  19379. while (_drawCallPool.length < MAX_SPRITES) {
  19380. _drawCallPool.push(new BatchDrawCall());
  19381. }
  19382. while (_textureArrayPool.length < MAX_TA) {
  19383. _textureArrayPool.push(new BatchTextureArray());
  19384. }
  19385. for (var i = 0; i < this.MAX_TEXTURES; i++) {
  19386. this._tempBoundTextures[i] = null;
  19387. }
  19388. };
  19389. /** Handles the `prerender` signal. It ensures that flushes start from the first geometry object again. */
  19390. AbstractBatchRenderer.prototype.onPrerender = function () {
  19391. this._flushId = 0;
  19392. };
  19393. /**
  19394. * Buffers the "batchable" object. It need not be rendered immediately.
  19395. * @param {PIXI.DisplayObject} element - the element to render when
  19396. * using this renderer
  19397. */
  19398. AbstractBatchRenderer.prototype.render = function (element) {
  19399. if (!element._texture.valid) {
  19400. return;
  19401. }
  19402. if (this._vertexCount + (element.vertexData.length / 2) > this.size) {
  19403. this.flush();
  19404. }
  19405. this._vertexCount += element.vertexData.length / 2;
  19406. this._indexCount += element.indices.length;
  19407. this._bufferedTextures[this._bufferSize] = element._texture.baseTexture;
  19408. this._bufferedElements[this._bufferSize++] = element;
  19409. };
  19410. AbstractBatchRenderer.prototype.buildTexturesAndDrawCalls = function () {
  19411. var _a = this, textures = _a._bufferedTextures, MAX_TEXTURES = _a.MAX_TEXTURES;
  19412. var textureArrays = AbstractBatchRenderer._textureArrayPool;
  19413. var batch = this.renderer.batch;
  19414. var boundTextures = this._tempBoundTextures;
  19415. var touch = this.renderer.textureGC.count;
  19416. var TICK = ++BaseTexture._globalBatch;
  19417. var countTexArrays = 0;
  19418. var texArray = textureArrays[0];
  19419. var start = 0;
  19420. batch.copyBoundTextures(boundTextures, MAX_TEXTURES);
  19421. for (var i = 0; i < this._bufferSize; ++i) {
  19422. var tex = textures[i];
  19423. textures[i] = null;
  19424. if (tex._batchEnabled === TICK) {
  19425. continue;
  19426. }
  19427. if (texArray.count >= MAX_TEXTURES) {
  19428. batch.boundArray(texArray, boundTextures, TICK, MAX_TEXTURES);
  19429. this.buildDrawCalls(texArray, start, i);
  19430. start = i;
  19431. texArray = textureArrays[++countTexArrays];
  19432. ++TICK;
  19433. }
  19434. tex._batchEnabled = TICK;
  19435. tex.touched = touch;
  19436. texArray.elements[texArray.count++] = tex;
  19437. }
  19438. if (texArray.count > 0) {
  19439. batch.boundArray(texArray, boundTextures, TICK, MAX_TEXTURES);
  19440. this.buildDrawCalls(texArray, start, this._bufferSize);
  19441. ++countTexArrays;
  19442. ++TICK;
  19443. }
  19444. // Clean-up
  19445. for (var i = 0; i < boundTextures.length; i++) {
  19446. boundTextures[i] = null;
  19447. }
  19448. BaseTexture._globalBatch = TICK;
  19449. };
  19450. /**
  19451. * Populating drawcalls for rendering
  19452. * @param texArray
  19453. * @param start
  19454. * @param finish
  19455. */
  19456. AbstractBatchRenderer.prototype.buildDrawCalls = function (texArray, start, finish) {
  19457. var _a = this, elements = _a._bufferedElements, _attributeBuffer = _a._attributeBuffer, _indexBuffer = _a._indexBuffer, vertexSize = _a.vertexSize;
  19458. var drawCalls = AbstractBatchRenderer._drawCallPool;
  19459. var dcIndex = this._dcIndex;
  19460. var aIndex = this._aIndex;
  19461. var iIndex = this._iIndex;
  19462. var drawCall = drawCalls[dcIndex];
  19463. drawCall.start = this._iIndex;
  19464. drawCall.texArray = texArray;
  19465. for (var i = start; i < finish; ++i) {
  19466. var sprite = elements[i];
  19467. var tex = sprite._texture.baseTexture;
  19468. var spriteBlendMode = premultiplyBlendMode[tex.alphaMode ? 1 : 0][sprite.blendMode];
  19469. elements[i] = null;
  19470. if (start < i && drawCall.blend !== spriteBlendMode) {
  19471. drawCall.size = iIndex - drawCall.start;
  19472. start = i;
  19473. drawCall = drawCalls[++dcIndex];
  19474. drawCall.texArray = texArray;
  19475. drawCall.start = iIndex;
  19476. }
  19477. this.packInterleavedGeometry(sprite, _attributeBuffer, _indexBuffer, aIndex, iIndex);
  19478. aIndex += sprite.vertexData.length / 2 * vertexSize;
  19479. iIndex += sprite.indices.length;
  19480. drawCall.blend = spriteBlendMode;
  19481. }
  19482. if (start < finish) {
  19483. drawCall.size = iIndex - drawCall.start;
  19484. ++dcIndex;
  19485. }
  19486. this._dcIndex = dcIndex;
  19487. this._aIndex = aIndex;
  19488. this._iIndex = iIndex;
  19489. };
  19490. /**
  19491. * Bind textures for current rendering
  19492. * @param texArray
  19493. */
  19494. AbstractBatchRenderer.prototype.bindAndClearTexArray = function (texArray) {
  19495. var textureSystem = this.renderer.texture;
  19496. for (var j = 0; j < texArray.count; j++) {
  19497. textureSystem.bind(texArray.elements[j], texArray.ids[j]);
  19498. texArray.elements[j] = null;
  19499. }
  19500. texArray.count = 0;
  19501. };
  19502. AbstractBatchRenderer.prototype.updateGeometry = function () {
  19503. var _a = this, packedGeometries = _a._packedGeometries, attributeBuffer = _a._attributeBuffer, indexBuffer = _a._indexBuffer;
  19504. if (!settings.CAN_UPLOAD_SAME_BUFFER) { /* Usually on iOS devices, where the browser doesn't
  19505. like uploads to the same buffer in a single frame. */
  19506. if (this._packedGeometryPoolSize <= this._flushId) {
  19507. this._packedGeometryPoolSize++;
  19508. packedGeometries[this._flushId] = new (this.geometryClass)();
  19509. }
  19510. packedGeometries[this._flushId]._buffer.update(attributeBuffer.rawBinaryData);
  19511. packedGeometries[this._flushId]._indexBuffer.update(indexBuffer);
  19512. this.renderer.geometry.bind(packedGeometries[this._flushId]);
  19513. this.renderer.geometry.updateBuffers();
  19514. this._flushId++;
  19515. }
  19516. else {
  19517. // lets use the faster option, always use buffer number 0
  19518. packedGeometries[this._flushId]._buffer.update(attributeBuffer.rawBinaryData);
  19519. packedGeometries[this._flushId]._indexBuffer.update(indexBuffer);
  19520. this.renderer.geometry.updateBuffers();
  19521. }
  19522. };
  19523. AbstractBatchRenderer.prototype.drawBatches = function () {
  19524. var dcCount = this._dcIndex;
  19525. var _a = this.renderer, gl = _a.gl, stateSystem = _a.state;
  19526. var drawCalls = AbstractBatchRenderer._drawCallPool;
  19527. var curTexArray = null;
  19528. // Upload textures and do the draw calls
  19529. for (var i = 0; i < dcCount; i++) {
  19530. var _b = drawCalls[i], texArray = _b.texArray, type = _b.type, size = _b.size, start = _b.start, blend = _b.blend;
  19531. if (curTexArray !== texArray) {
  19532. curTexArray = texArray;
  19533. this.bindAndClearTexArray(texArray);
  19534. }
  19535. this.state.blendMode = blend;
  19536. stateSystem.set(this.state);
  19537. gl.drawElements(type, size, gl.UNSIGNED_SHORT, start * 2);
  19538. }
  19539. };
  19540. /** Renders the content _now_ and empties the current batch. */
  19541. AbstractBatchRenderer.prototype.flush = function () {
  19542. if (this._vertexCount === 0) {
  19543. return;
  19544. }
  19545. this._attributeBuffer = this.getAttributeBuffer(this._vertexCount);
  19546. this._indexBuffer = this.getIndexBuffer(this._indexCount);
  19547. this._aIndex = 0;
  19548. this._iIndex = 0;
  19549. this._dcIndex = 0;
  19550. this.buildTexturesAndDrawCalls();
  19551. this.updateGeometry();
  19552. this.drawBatches();
  19553. // reset elements buffer for the next flush
  19554. this._bufferSize = 0;
  19555. this._vertexCount = 0;
  19556. this._indexCount = 0;
  19557. };
  19558. /** Starts a new sprite batch. */
  19559. AbstractBatchRenderer.prototype.start = function () {
  19560. this.renderer.state.set(this.state);
  19561. this.renderer.texture.ensureSamplerType(this.MAX_TEXTURES);
  19562. this.renderer.shader.bind(this._shader);
  19563. if (settings.CAN_UPLOAD_SAME_BUFFER) {
  19564. // bind buffer #0, we don't need others
  19565. this.renderer.geometry.bind(this._packedGeometries[this._flushId]);
  19566. }
  19567. };
  19568. /** Stops and flushes the current batch. */
  19569. AbstractBatchRenderer.prototype.stop = function () {
  19570. this.flush();
  19571. };
  19572. /** Destroys this `AbstractBatchRenderer`. It cannot be used again. */
  19573. AbstractBatchRenderer.prototype.destroy = function () {
  19574. for (var i = 0; i < this._packedGeometryPoolSize; i++) {
  19575. if (this._packedGeometries[i]) {
  19576. this._packedGeometries[i].destroy();
  19577. }
  19578. }
  19579. this.renderer.off('prerender', this.onPrerender, this);
  19580. this._aBuffers = null;
  19581. this._iBuffers = null;
  19582. this._packedGeometries = null;
  19583. this._attributeBuffer = null;
  19584. this._indexBuffer = null;
  19585. if (this._shader) {
  19586. this._shader.destroy();
  19587. this._shader = null;
  19588. }
  19589. _super.prototype.destroy.call(this);
  19590. };
  19591. /**
  19592. * Fetches an attribute buffer from `this._aBuffers` that can hold atleast `size` floats.
  19593. * @param size - minimum capacity required
  19594. * @returns - buffer than can hold atleast `size` floats
  19595. */
  19596. AbstractBatchRenderer.prototype.getAttributeBuffer = function (size) {
  19597. // 8 vertices is enough for 2 quads
  19598. var roundedP2 = nextPow2(Math.ceil(size / 8));
  19599. var roundedSizeIndex = log2(roundedP2);
  19600. var roundedSize = roundedP2 * 8;
  19601. if (this._aBuffers.length <= roundedSizeIndex) {
  19602. this._iBuffers.length = roundedSizeIndex + 1;
  19603. }
  19604. var buffer = this._aBuffers[roundedSize];
  19605. if (!buffer) {
  19606. this._aBuffers[roundedSize] = buffer = new ViewableBuffer(roundedSize * this.vertexSize * 4);
  19607. }
  19608. return buffer;
  19609. };
  19610. /**
  19611. * Fetches an index buffer from `this._iBuffers` that can
  19612. * have at least `size` capacity.
  19613. * @param size - minimum required capacity
  19614. * @returns - buffer that can fit `size` indices.
  19615. */
  19616. AbstractBatchRenderer.prototype.getIndexBuffer = function (size) {
  19617. // 12 indices is enough for 2 quads
  19618. var roundedP2 = nextPow2(Math.ceil(size / 12));
  19619. var roundedSizeIndex = log2(roundedP2);
  19620. var roundedSize = roundedP2 * 12;
  19621. if (this._iBuffers.length <= roundedSizeIndex) {
  19622. this._iBuffers.length = roundedSizeIndex + 1;
  19623. }
  19624. var buffer = this._iBuffers[roundedSizeIndex];
  19625. if (!buffer) {
  19626. this._iBuffers[roundedSizeIndex] = buffer = new Uint16Array(roundedSize);
  19627. }
  19628. return buffer;
  19629. };
  19630. /**
  19631. * Takes the four batching parameters of `element`, interleaves
  19632. * and pushes them into the batching attribute/index buffers given.
  19633. *
  19634. * It uses these properties: `vertexData` `uvs`, `textureId` and
  19635. * `indicies`. It also uses the "tint" of the base-texture, if
  19636. * present.
  19637. * @param {PIXI.DisplayObject} element - element being rendered
  19638. * @param attributeBuffer - attribute buffer.
  19639. * @param indexBuffer - index buffer
  19640. * @param aIndex - number of floats already in the attribute buffer
  19641. * @param iIndex - number of indices already in `indexBuffer`
  19642. */
  19643. AbstractBatchRenderer.prototype.packInterleavedGeometry = function (element, attributeBuffer, indexBuffer, aIndex, iIndex) {
  19644. var uint32View = attributeBuffer.uint32View, float32View = attributeBuffer.float32View;
  19645. var packedVertices = aIndex / this.vertexSize;
  19646. var uvs = element.uvs;
  19647. var indicies = element.indices;
  19648. var vertexData = element.vertexData;
  19649. var textureId = element._texture.baseTexture._batchLocation;
  19650. var alpha = Math.min(element.worldAlpha, 1.0);
  19651. var argb = (alpha < 1.0
  19652. && element._texture.baseTexture.alphaMode)
  19653. ? premultiplyTint(element._tintRGB, alpha)
  19654. : element._tintRGB + (alpha * 255 << 24);
  19655. // lets not worry about tint! for now..
  19656. for (var i = 0; i < vertexData.length; i += 2) {
  19657. float32View[aIndex++] = vertexData[i];
  19658. float32View[aIndex++] = vertexData[i + 1];
  19659. float32View[aIndex++] = uvs[i];
  19660. float32View[aIndex++] = uvs[i + 1];
  19661. uint32View[aIndex++] = argb;
  19662. float32View[aIndex++] = textureId;
  19663. }
  19664. for (var i = 0; i < indicies.length; i++) {
  19665. indexBuffer[iIndex++] = packedVertices + indicies[i];
  19666. }
  19667. };
  19668. /**
  19669. * Pool of `BatchDrawCall` objects that `flush` used
  19670. * to create "batches" of the objects being rendered.
  19671. *
  19672. * These are never re-allocated again.
  19673. * Shared between all batch renderers because it can be only one "flush" working at the moment.
  19674. * @member {PIXI.BatchDrawCall[]}
  19675. */
  19676. AbstractBatchRenderer._drawCallPool = [];
  19677. /**
  19678. * Pool of `BatchDrawCall` objects that `flush` used
  19679. * to create "batches" of the objects being rendered.
  19680. *
  19681. * These are never re-allocated again.
  19682. * Shared between all batch renderers because it can be only one "flush" working at the moment.
  19683. * @member {PIXI.BatchTextureArray[]}
  19684. */
  19685. AbstractBatchRenderer._textureArrayPool = [];
  19686. return AbstractBatchRenderer;
  19687. }(ObjectRenderer));
  19688. /**
  19689. * Helper that generates batching multi-texture shader. Use it with your new BatchRenderer
  19690. * @memberof PIXI
  19691. */
  19692. var BatchShaderGenerator = /** @class */ (function () {
  19693. /**
  19694. * @param vertexSrc - Vertex shader
  19695. * @param fragTemplate - Fragment shader template
  19696. */
  19697. function BatchShaderGenerator(vertexSrc, fragTemplate) {
  19698. this.vertexSrc = vertexSrc;
  19699. this.fragTemplate = fragTemplate;
  19700. this.programCache = {};
  19701. this.defaultGroupCache = {};
  19702. if (fragTemplate.indexOf('%count%') < 0) {
  19703. throw new Error('Fragment template must contain "%count%".');
  19704. }
  19705. if (fragTemplate.indexOf('%forloop%') < 0) {
  19706. throw new Error('Fragment template must contain "%forloop%".');
  19707. }
  19708. }
  19709. BatchShaderGenerator.prototype.generateShader = function (maxTextures) {
  19710. if (!this.programCache[maxTextures]) {
  19711. var sampleValues = new Int32Array(maxTextures);
  19712. for (var i = 0; i < maxTextures; i++) {
  19713. sampleValues[i] = i;
  19714. }
  19715. this.defaultGroupCache[maxTextures] = UniformGroup.from({ uSamplers: sampleValues }, true);
  19716. var fragmentSrc = this.fragTemplate;
  19717. fragmentSrc = fragmentSrc.replace(/%count%/gi, "" + maxTextures);
  19718. fragmentSrc = fragmentSrc.replace(/%forloop%/gi, this.generateSampleSrc(maxTextures));
  19719. this.programCache[maxTextures] = new Program(this.vertexSrc, fragmentSrc);
  19720. }
  19721. var uniforms = {
  19722. tint: new Float32Array([1, 1, 1, 1]),
  19723. translationMatrix: new Matrix(),
  19724. default: this.defaultGroupCache[maxTextures],
  19725. };
  19726. return new Shader(this.programCache[maxTextures], uniforms);
  19727. };
  19728. BatchShaderGenerator.prototype.generateSampleSrc = function (maxTextures) {
  19729. var src = '';
  19730. src += '\n';
  19731. src += '\n';
  19732. for (var i = 0; i < maxTextures; i++) {
  19733. if (i > 0) {
  19734. src += '\nelse ';
  19735. }
  19736. if (i < maxTextures - 1) {
  19737. src += "if(vTextureId < " + i + ".5)";
  19738. }
  19739. src += '\n{';
  19740. src += "\n\tcolor = texture2D(uSamplers[" + i + "], vTextureCoord);";
  19741. src += '\n}';
  19742. }
  19743. src += '\n';
  19744. src += '\n';
  19745. return src;
  19746. };
  19747. return BatchShaderGenerator;
  19748. }());
  19749. /**
  19750. * Geometry used to batch standard PIXI content (e.g. Mesh, Sprite, Graphics objects).
  19751. * @memberof PIXI
  19752. */
  19753. var BatchGeometry = /** @class */ (function (_super) {
  19754. __extends$i(BatchGeometry, _super);
  19755. /**
  19756. * @param {boolean} [_static=false] - Optimization flag, where `false`
  19757. * is updated every frame, `true` doesn't change frame-to-frame.
  19758. */
  19759. function BatchGeometry(_static) {
  19760. if (_static === void 0) { _static = false; }
  19761. var _this = _super.call(this) || this;
  19762. _this._buffer = new Buffer(null, _static, false);
  19763. _this._indexBuffer = new Buffer(null, _static, true);
  19764. _this.addAttribute('aVertexPosition', _this._buffer, 2, false, TYPES.FLOAT)
  19765. .addAttribute('aTextureCoord', _this._buffer, 2, false, TYPES.FLOAT)
  19766. .addAttribute('aColor', _this._buffer, 4, true, TYPES.UNSIGNED_BYTE)
  19767. .addAttribute('aTextureId', _this._buffer, 1, true, TYPES.FLOAT)
  19768. .addIndex(_this._indexBuffer);
  19769. return _this;
  19770. }
  19771. return BatchGeometry;
  19772. }(Geometry));
  19773. var defaultVertex = "precision highp float;\nattribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\nattribute vec4 aColor;\nattribute float aTextureId;\n\nuniform mat3 projectionMatrix;\nuniform mat3 translationMatrix;\nuniform vec4 tint;\n\nvarying vec2 vTextureCoord;\nvarying vec4 vColor;\nvarying float vTextureId;\n\nvoid main(void){\n gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = aTextureCoord;\n vTextureId = aTextureId;\n vColor = aColor * tint;\n}\n";
  19774. var defaultFragment = "varying vec2 vTextureCoord;\nvarying vec4 vColor;\nvarying float vTextureId;\nuniform sampler2D uSamplers[%count%];\n\nvoid main(void){\n vec4 color;\n %forloop%\n gl_FragColor = color * vColor;\n}\n";
  19775. /** @memberof PIXI */
  19776. var BatchPluginFactory = /** @class */ (function () {
  19777. function BatchPluginFactory() {
  19778. }
  19779. /**
  19780. * Create a new BatchRenderer plugin for Renderer. this convenience can provide an easy way
  19781. * to extend BatchRenderer with all the necessary pieces.
  19782. * @example
  19783. * const fragment = `
  19784. * varying vec2 vTextureCoord;
  19785. * varying vec4 vColor;
  19786. * varying float vTextureId;
  19787. * uniform sampler2D uSamplers[%count%];
  19788. *
  19789. * void main(void){
  19790. * vec4 color;
  19791. * %forloop%
  19792. * gl_FragColor = vColor * vec4(color.a - color.rgb, color.a);
  19793. * }
  19794. * `;
  19795. * const InvertBatchRenderer = PIXI.BatchPluginFactory.create({ fragment });
  19796. * PIXI.extensions.add({
  19797. * name: 'invert',
  19798. * ref: InvertBatchRenderer,
  19799. * type: PIXI.ExtensionType.RendererPlugin,
  19800. * });
  19801. * const sprite = new PIXI.Sprite();
  19802. * sprite.pluginName = 'invert';
  19803. * @param {object} [options]
  19804. * @param {string} [options.vertex=PIXI.BatchPluginFactory.defaultVertexSrc] - Vertex shader source
  19805. * @param {string} [options.fragment=PIXI.BatchPluginFactory.defaultFragmentTemplate] - Fragment shader template
  19806. * @param {number} [options.vertexSize=6] - Vertex size
  19807. * @param {object} [options.geometryClass=PIXI.BatchGeometry]
  19808. * @returns {*} New batch renderer plugin
  19809. */
  19810. BatchPluginFactory.create = function (options) {
  19811. var _a = Object.assign({
  19812. vertex: defaultVertex,
  19813. fragment: defaultFragment,
  19814. geometryClass: BatchGeometry,
  19815. vertexSize: 6,
  19816. }, options), vertex = _a.vertex, fragment = _a.fragment, vertexSize = _a.vertexSize, geometryClass = _a.geometryClass;
  19817. return /** @class */ (function (_super) {
  19818. __extends$i(BatchPlugin, _super);
  19819. function BatchPlugin(renderer) {
  19820. var _this = _super.call(this, renderer) || this;
  19821. _this.shaderGenerator = new BatchShaderGenerator(vertex, fragment);
  19822. _this.geometryClass = geometryClass;
  19823. _this.vertexSize = vertexSize;
  19824. return _this;
  19825. }
  19826. return BatchPlugin;
  19827. }(AbstractBatchRenderer));
  19828. };
  19829. Object.defineProperty(BatchPluginFactory, "defaultVertexSrc", {
  19830. /**
  19831. * The default vertex shader source
  19832. * @readonly
  19833. */
  19834. get: function () {
  19835. return defaultVertex;
  19836. },
  19837. enumerable: false,
  19838. configurable: true
  19839. });
  19840. Object.defineProperty(BatchPluginFactory, "defaultFragmentTemplate", {
  19841. /**
  19842. * The default fragment shader source
  19843. * @readonly
  19844. */
  19845. get: function () {
  19846. return defaultFragment;
  19847. },
  19848. enumerable: false,
  19849. configurable: true
  19850. });
  19851. return BatchPluginFactory;
  19852. }());
  19853. // Setup the default BatchRenderer plugin, this is what
  19854. // we'll actually export at the root level
  19855. var BatchRenderer = BatchPluginFactory.create();
  19856. Object.assign(BatchRenderer, {
  19857. extension: {
  19858. name: 'batch',
  19859. type: ExtensionType.RendererPlugin,
  19860. },
  19861. });
  19862. /**
  19863. * @memberof PIXI
  19864. * @namespace resources
  19865. * @see PIXI
  19866. * @deprecated since 6.0.0
  19867. */
  19868. var resources = {};
  19869. var _loop_1 = function (name) {
  19870. Object.defineProperty(resources, name, {
  19871. get: function () {
  19872. deprecation('6.0.0', "PIXI.systems." + name + " has moved to PIXI." + name);
  19873. return _resources[name];
  19874. },
  19875. });
  19876. };
  19877. for (var name in _resources) {
  19878. _loop_1(name);
  19879. }
  19880. /**
  19881. * @memberof PIXI
  19882. * @namespace systems
  19883. * @see PIXI
  19884. * @deprecated since 6.0.0
  19885. */
  19886. var systems = {};
  19887. var _loop_2 = function (name) {
  19888. Object.defineProperty(systems, name, {
  19889. get: function () {
  19890. deprecation('6.0.0', "PIXI.resources." + name + " has moved to PIXI." + name);
  19891. return _systems[name];
  19892. },
  19893. });
  19894. };
  19895. for (var name in _systems) {
  19896. _loop_2(name);
  19897. }
  19898. /**
  19899. * @namespace PIXI
  19900. */
  19901. /**
  19902. * String of the current PIXI version.
  19903. * @memberof PIXI
  19904. */
  19905. var VERSION = '6.5.10';
  19906. /*!
  19907. * @pixi/accessibility - v6.5.10
  19908. * Compiled Thu, 06 Jul 2023 15:25:11 UTC
  19909. *
  19910. * @pixi/accessibility is licensed under the MIT License.
  19911. * http://www.opensource.org/licenses/mit-license
  19912. */
  19913. /**
  19914. * Default property values of accessible objects
  19915. * used by {@link PIXI.AccessibilityManager}.
  19916. * @private
  19917. * @function accessibleTarget
  19918. * @memberof PIXI
  19919. * @type {object}
  19920. * @example
  19921. * function MyObject() {}
  19922. *
  19923. * Object.assign(
  19924. * MyObject.prototype,
  19925. * PIXI.accessibleTarget
  19926. * );
  19927. */
  19928. var accessibleTarget = {
  19929. /**
  19930. * Flag for if the object is accessible. If true AccessibilityManager will overlay a
  19931. * shadow div with attributes set
  19932. * @member {boolean}
  19933. * @memberof PIXI.DisplayObject#
  19934. */
  19935. accessible: false,
  19936. /**
  19937. * Sets the title attribute of the shadow div
  19938. * If accessibleTitle AND accessibleHint has not been this will default to 'displayObject [tabIndex]'
  19939. * @member {?string}
  19940. * @memberof PIXI.DisplayObject#
  19941. */
  19942. accessibleTitle: null,
  19943. /**
  19944. * Sets the aria-label attribute of the shadow div
  19945. * @member {string}
  19946. * @memberof PIXI.DisplayObject#
  19947. */
  19948. accessibleHint: null,
  19949. /**
  19950. * @member {number}
  19951. * @memberof PIXI.DisplayObject#
  19952. * @private
  19953. * @todo Needs docs.
  19954. */
  19955. tabIndex: 0,
  19956. /**
  19957. * @member {boolean}
  19958. * @memberof PIXI.DisplayObject#
  19959. * @todo Needs docs.
  19960. */
  19961. _accessibleActive: false,
  19962. /**
  19963. * @member {boolean}
  19964. * @memberof PIXI.DisplayObject#
  19965. * @todo Needs docs.
  19966. */
  19967. _accessibleDiv: null,
  19968. /**
  19969. * Specify the type of div the accessible layer is. Screen readers treat the element differently
  19970. * depending on this type. Defaults to button.
  19971. * @member {string}
  19972. * @memberof PIXI.DisplayObject#
  19973. * @default 'button'
  19974. */
  19975. accessibleType: 'button',
  19976. /**
  19977. * Specify the pointer-events the accessible div will use
  19978. * Defaults to auto.
  19979. * @member {string}
  19980. * @memberof PIXI.DisplayObject#
  19981. * @default 'auto'
  19982. */
  19983. accessiblePointerEvents: 'auto',
  19984. /**
  19985. * Setting to false will prevent any children inside this container to
  19986. * be accessible. Defaults to true.
  19987. * @member {boolean}
  19988. * @memberof PIXI.DisplayObject#
  19989. * @default true
  19990. */
  19991. accessibleChildren: true,
  19992. renderId: -1,
  19993. };
  19994. // add some extra variables to the container..
  19995. DisplayObject.mixin(accessibleTarget);
  19996. var KEY_CODE_TAB = 9;
  19997. var DIV_TOUCH_SIZE = 100;
  19998. var DIV_TOUCH_POS_X = 0;
  19999. var DIV_TOUCH_POS_Y = 0;
  20000. var DIV_TOUCH_ZINDEX = 2;
  20001. var DIV_HOOK_SIZE = 1;
  20002. var DIV_HOOK_POS_X = -1000;
  20003. var DIV_HOOK_POS_Y = -1000;
  20004. var DIV_HOOK_ZINDEX = 2;
  20005. /**
  20006. * The Accessibility manager recreates the ability to tab and have content read by screen readers.
  20007. * This is very important as it can possibly help people with disabilities access PixiJS content.
  20008. *
  20009. * A DisplayObject can be made accessible just like it can be made interactive. This manager will map the
  20010. * events as if the mouse was being used, minimizing the effort required to implement.
  20011. *
  20012. * An instance of this class is automatically created by default, and can be found at `renderer.plugins.accessibility`
  20013. * @class
  20014. * @memberof PIXI
  20015. */
  20016. var AccessibilityManager = /** @class */ (function () {
  20017. /**
  20018. * @param {PIXI.CanvasRenderer|PIXI.Renderer} renderer - A reference to the current renderer
  20019. */
  20020. function AccessibilityManager(renderer) {
  20021. /** Setting this to true will visually show the divs. */
  20022. this.debug = false;
  20023. /** Internal variable, see isActive getter. */
  20024. this._isActive = false;
  20025. /** Internal variable, see isMobileAccessibility getter. */
  20026. this._isMobileAccessibility = false;
  20027. /** A simple pool for storing divs. */
  20028. this.pool = [];
  20029. /** This is a tick used to check if an object is no longer being rendered. */
  20030. this.renderId = 0;
  20031. /** The array of currently active accessible items. */
  20032. this.children = [];
  20033. /** Count to throttle div updates on android devices. */
  20034. this.androidUpdateCount = 0;
  20035. /** The frequency to update the div elements. */
  20036. this.androidUpdateFrequency = 500; // 2fps
  20037. this._hookDiv = null;
  20038. if (isMobile.tablet || isMobile.phone) {
  20039. this.createTouchHook();
  20040. }
  20041. // first we create a div that will sit over the PixiJS element. This is where the div overlays will go.
  20042. var div = document.createElement('div');
  20043. div.style.width = DIV_TOUCH_SIZE + "px";
  20044. div.style.height = DIV_TOUCH_SIZE + "px";
  20045. div.style.position = 'absolute';
  20046. div.style.top = DIV_TOUCH_POS_X + "px";
  20047. div.style.left = DIV_TOUCH_POS_Y + "px";
  20048. div.style.zIndex = DIV_TOUCH_ZINDEX.toString();
  20049. this.div = div;
  20050. this.renderer = renderer;
  20051. /**
  20052. * pre-bind the functions
  20053. * @type {Function}
  20054. * @private
  20055. */
  20056. this._onKeyDown = this._onKeyDown.bind(this);
  20057. /**
  20058. * pre-bind the functions
  20059. * @type {Function}
  20060. * @private
  20061. */
  20062. this._onMouseMove = this._onMouseMove.bind(this);
  20063. // let listen for tab.. once pressed we can fire up and show the accessibility layer
  20064. globalThis.addEventListener('keydown', this._onKeyDown, false);
  20065. }
  20066. Object.defineProperty(AccessibilityManager.prototype, "isActive", {
  20067. /**
  20068. * Value of `true` if accessibility is currently active and accessibility layers are showing.
  20069. * @member {boolean}
  20070. * @readonly
  20071. */
  20072. get: function () {
  20073. return this._isActive;
  20074. },
  20075. enumerable: false,
  20076. configurable: true
  20077. });
  20078. Object.defineProperty(AccessibilityManager.prototype, "isMobileAccessibility", {
  20079. /**
  20080. * Value of `true` if accessibility is enabled for touch devices.
  20081. * @member {boolean}
  20082. * @readonly
  20083. */
  20084. get: function () {
  20085. return this._isMobileAccessibility;
  20086. },
  20087. enumerable: false,
  20088. configurable: true
  20089. });
  20090. /**
  20091. * Creates the touch hooks.
  20092. * @private
  20093. */
  20094. AccessibilityManager.prototype.createTouchHook = function () {
  20095. var _this = this;
  20096. var hookDiv = document.createElement('button');
  20097. hookDiv.style.width = DIV_HOOK_SIZE + "px";
  20098. hookDiv.style.height = DIV_HOOK_SIZE + "px";
  20099. hookDiv.style.position = 'absolute';
  20100. hookDiv.style.top = DIV_HOOK_POS_X + "px";
  20101. hookDiv.style.left = DIV_HOOK_POS_Y + "px";
  20102. hookDiv.style.zIndex = DIV_HOOK_ZINDEX.toString();
  20103. hookDiv.style.backgroundColor = '#FF0000';
  20104. hookDiv.title = 'select to enable accessibility for this content';
  20105. hookDiv.addEventListener('focus', function () {
  20106. _this._isMobileAccessibility = true;
  20107. _this.activate();
  20108. _this.destroyTouchHook();
  20109. });
  20110. document.body.appendChild(hookDiv);
  20111. this._hookDiv = hookDiv;
  20112. };
  20113. /**
  20114. * Destroys the touch hooks.
  20115. * @private
  20116. */
  20117. AccessibilityManager.prototype.destroyTouchHook = function () {
  20118. if (!this._hookDiv) {
  20119. return;
  20120. }
  20121. document.body.removeChild(this._hookDiv);
  20122. this._hookDiv = null;
  20123. };
  20124. /**
  20125. * Activating will cause the Accessibility layer to be shown.
  20126. * This is called when a user presses the tab key.
  20127. * @private
  20128. */
  20129. AccessibilityManager.prototype.activate = function () {
  20130. var _a;
  20131. if (this._isActive) {
  20132. return;
  20133. }
  20134. this._isActive = true;
  20135. globalThis.document.addEventListener('mousemove', this._onMouseMove, true);
  20136. globalThis.removeEventListener('keydown', this._onKeyDown, false);
  20137. this.renderer.on('postrender', this.update, this);
  20138. (_a = this.renderer.view.parentNode) === null || _a === void 0 ? void 0 : _a.appendChild(this.div);
  20139. };
  20140. /**
  20141. * Deactivating will cause the Accessibility layer to be hidden.
  20142. * This is called when a user moves the mouse.
  20143. * @private
  20144. */
  20145. AccessibilityManager.prototype.deactivate = function () {
  20146. var _a;
  20147. if (!this._isActive || this._isMobileAccessibility) {
  20148. return;
  20149. }
  20150. this._isActive = false;
  20151. globalThis.document.removeEventListener('mousemove', this._onMouseMove, true);
  20152. globalThis.addEventListener('keydown', this._onKeyDown, false);
  20153. this.renderer.off('postrender', this.update);
  20154. (_a = this.div.parentNode) === null || _a === void 0 ? void 0 : _a.removeChild(this.div);
  20155. };
  20156. /**
  20157. * This recursive function will run through the scene graph and add any new accessible objects to the DOM layer.
  20158. * @private
  20159. * @param {PIXI.Container} displayObject - The DisplayObject to check.
  20160. */
  20161. AccessibilityManager.prototype.updateAccessibleObjects = function (displayObject) {
  20162. if (!displayObject.visible || !displayObject.accessibleChildren) {
  20163. return;
  20164. }
  20165. if (displayObject.accessible && displayObject.interactive) {
  20166. if (!displayObject._accessibleActive) {
  20167. this.addChild(displayObject);
  20168. }
  20169. displayObject.renderId = this.renderId;
  20170. }
  20171. var children = displayObject.children;
  20172. if (children) {
  20173. for (var i = 0; i < children.length; i++) {
  20174. this.updateAccessibleObjects(children[i]);
  20175. }
  20176. }
  20177. };
  20178. /**
  20179. * Before each render this function will ensure that all divs are mapped correctly to their DisplayObjects.
  20180. * @private
  20181. */
  20182. AccessibilityManager.prototype.update = function () {
  20183. /* On Android default web browser, tab order seems to be calculated by position rather than tabIndex,
  20184. * moving buttons can cause focus to flicker between two buttons making it hard/impossible to navigate,
  20185. * so I am just running update every half a second, seems to fix it.
  20186. */
  20187. var now = performance.now();
  20188. if (isMobile.android.device && now < this.androidUpdateCount) {
  20189. return;
  20190. }
  20191. this.androidUpdateCount = now + this.androidUpdateFrequency;
  20192. if (!this.renderer.renderingToScreen) {
  20193. return;
  20194. }
  20195. // update children...
  20196. if (this.renderer._lastObjectRendered) {
  20197. this.updateAccessibleObjects(this.renderer._lastObjectRendered);
  20198. }
  20199. var _a = this.renderer.view.getBoundingClientRect(), left = _a.left, top = _a.top, width = _a.width, height = _a.height;
  20200. var _b = this.renderer, viewWidth = _b.width, viewHeight = _b.height, resolution = _b.resolution;
  20201. var sx = (width / viewWidth) * resolution;
  20202. var sy = (height / viewHeight) * resolution;
  20203. var div = this.div;
  20204. div.style.left = left + "px";
  20205. div.style.top = top + "px";
  20206. div.style.width = viewWidth + "px";
  20207. div.style.height = viewHeight + "px";
  20208. for (var i = 0; i < this.children.length; i++) {
  20209. var child = this.children[i];
  20210. if (child.renderId !== this.renderId) {
  20211. child._accessibleActive = false;
  20212. removeItems(this.children, i, 1);
  20213. this.div.removeChild(child._accessibleDiv);
  20214. this.pool.push(child._accessibleDiv);
  20215. child._accessibleDiv = null;
  20216. i--;
  20217. }
  20218. else {
  20219. // map div to display..
  20220. div = child._accessibleDiv;
  20221. var hitArea = child.hitArea;
  20222. var wt = child.worldTransform;
  20223. if (child.hitArea) {
  20224. div.style.left = (wt.tx + (hitArea.x * wt.a)) * sx + "px";
  20225. div.style.top = (wt.ty + (hitArea.y * wt.d)) * sy + "px";
  20226. div.style.width = hitArea.width * wt.a * sx + "px";
  20227. div.style.height = hitArea.height * wt.d * sy + "px";
  20228. }
  20229. else {
  20230. hitArea = child.getBounds();
  20231. this.capHitArea(hitArea);
  20232. div.style.left = hitArea.x * sx + "px";
  20233. div.style.top = hitArea.y * sy + "px";
  20234. div.style.width = hitArea.width * sx + "px";
  20235. div.style.height = hitArea.height * sy + "px";
  20236. // update button titles and hints if they exist and they've changed
  20237. if (div.title !== child.accessibleTitle && child.accessibleTitle !== null) {
  20238. div.title = child.accessibleTitle;
  20239. }
  20240. if (div.getAttribute('aria-label') !== child.accessibleHint
  20241. && child.accessibleHint !== null) {
  20242. div.setAttribute('aria-label', child.accessibleHint);
  20243. }
  20244. }
  20245. // the title or index may have changed, if so lets update it!
  20246. if (child.accessibleTitle !== div.title || child.tabIndex !== div.tabIndex) {
  20247. div.title = child.accessibleTitle;
  20248. div.tabIndex = child.tabIndex;
  20249. if (this.debug)
  20250. { this.updateDebugHTML(div); }
  20251. }
  20252. }
  20253. }
  20254. // increment the render id..
  20255. this.renderId++;
  20256. };
  20257. /**
  20258. * private function that will visually add the information to the
  20259. * accessability div
  20260. * @param {HTMLElement} div -
  20261. */
  20262. AccessibilityManager.prototype.updateDebugHTML = function (div) {
  20263. div.innerHTML = "type: " + div.type + "</br> title : " + div.title + "</br> tabIndex: " + div.tabIndex;
  20264. };
  20265. /**
  20266. * Adjust the hit area based on the bounds of a display object
  20267. * @param {PIXI.Rectangle} hitArea - Bounds of the child
  20268. */
  20269. AccessibilityManager.prototype.capHitArea = function (hitArea) {
  20270. if (hitArea.x < 0) {
  20271. hitArea.width += hitArea.x;
  20272. hitArea.x = 0;
  20273. }
  20274. if (hitArea.y < 0) {
  20275. hitArea.height += hitArea.y;
  20276. hitArea.y = 0;
  20277. }
  20278. var _a = this.renderer, viewWidth = _a.width, viewHeight = _a.height;
  20279. if (hitArea.x + hitArea.width > viewWidth) {
  20280. hitArea.width = viewWidth - hitArea.x;
  20281. }
  20282. if (hitArea.y + hitArea.height > viewHeight) {
  20283. hitArea.height = viewHeight - hitArea.y;
  20284. }
  20285. };
  20286. /**
  20287. * Adds a DisplayObject to the accessibility manager
  20288. * @private
  20289. * @param {PIXI.DisplayObject} displayObject - The child to make accessible.
  20290. */
  20291. AccessibilityManager.prototype.addChild = function (displayObject) {
  20292. // this.activate();
  20293. var div = this.pool.pop();
  20294. if (!div) {
  20295. div = document.createElement('button');
  20296. div.style.width = DIV_TOUCH_SIZE + "px";
  20297. div.style.height = DIV_TOUCH_SIZE + "px";
  20298. div.style.backgroundColor = this.debug ? 'rgba(255,255,255,0.5)' : 'transparent';
  20299. div.style.position = 'absolute';
  20300. div.style.zIndex = DIV_TOUCH_ZINDEX.toString();
  20301. div.style.borderStyle = 'none';
  20302. // ARIA attributes ensure that button title and hint updates are announced properly
  20303. if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) {
  20304. // Chrome doesn't need aria-live to work as intended; in fact it just gets more confused.
  20305. div.setAttribute('aria-live', 'off');
  20306. }
  20307. else {
  20308. div.setAttribute('aria-live', 'polite');
  20309. }
  20310. if (navigator.userAgent.match(/rv:.*Gecko\//)) {
  20311. // FireFox needs this to announce only the new button name
  20312. div.setAttribute('aria-relevant', 'additions');
  20313. }
  20314. else {
  20315. // required by IE, other browsers don't much care
  20316. div.setAttribute('aria-relevant', 'text');
  20317. }
  20318. div.addEventListener('click', this._onClick.bind(this));
  20319. div.addEventListener('focus', this._onFocus.bind(this));
  20320. div.addEventListener('focusout', this._onFocusOut.bind(this));
  20321. }
  20322. // set pointer events
  20323. div.style.pointerEvents = displayObject.accessiblePointerEvents;
  20324. // set the type, this defaults to button!
  20325. div.type = displayObject.accessibleType;
  20326. if (displayObject.accessibleTitle && displayObject.accessibleTitle !== null) {
  20327. div.title = displayObject.accessibleTitle;
  20328. }
  20329. else if (!displayObject.accessibleHint
  20330. || displayObject.accessibleHint === null) {
  20331. div.title = "displayObject " + displayObject.tabIndex;
  20332. }
  20333. if (displayObject.accessibleHint
  20334. && displayObject.accessibleHint !== null) {
  20335. div.setAttribute('aria-label', displayObject.accessibleHint);
  20336. }
  20337. if (this.debug)
  20338. { this.updateDebugHTML(div); }
  20339. displayObject._accessibleActive = true;
  20340. displayObject._accessibleDiv = div;
  20341. div.displayObject = displayObject;
  20342. this.children.push(displayObject);
  20343. this.div.appendChild(displayObject._accessibleDiv);
  20344. displayObject._accessibleDiv.tabIndex = displayObject.tabIndex;
  20345. };
  20346. /**
  20347. * Maps the div button press to pixi's InteractionManager (click)
  20348. * @private
  20349. * @param {MouseEvent} e - The click event.
  20350. */
  20351. AccessibilityManager.prototype._onClick = function (e) {
  20352. var interactionManager = this.renderer.plugins.interaction;
  20353. var displayObject = e.target.displayObject;
  20354. var eventData = interactionManager.eventData;
  20355. interactionManager.dispatchEvent(displayObject, 'click', eventData);
  20356. interactionManager.dispatchEvent(displayObject, 'pointertap', eventData);
  20357. interactionManager.dispatchEvent(displayObject, 'tap', eventData);
  20358. };
  20359. /**
  20360. * Maps the div focus events to pixi's InteractionManager (mouseover)
  20361. * @private
  20362. * @param {FocusEvent} e - The focus event.
  20363. */
  20364. AccessibilityManager.prototype._onFocus = function (e) {
  20365. if (!e.target.getAttribute('aria-live')) {
  20366. e.target.setAttribute('aria-live', 'assertive');
  20367. }
  20368. var interactionManager = this.renderer.plugins.interaction;
  20369. var displayObject = e.target.displayObject;
  20370. var eventData = interactionManager.eventData;
  20371. interactionManager.dispatchEvent(displayObject, 'mouseover', eventData);
  20372. };
  20373. /**
  20374. * Maps the div focus events to pixi's InteractionManager (mouseout)
  20375. * @private
  20376. * @param {FocusEvent} e - The focusout event.
  20377. */
  20378. AccessibilityManager.prototype._onFocusOut = function (e) {
  20379. if (!e.target.getAttribute('aria-live')) {
  20380. e.target.setAttribute('aria-live', 'polite');
  20381. }
  20382. var interactionManager = this.renderer.plugins.interaction;
  20383. var displayObject = e.target.displayObject;
  20384. var eventData = interactionManager.eventData;
  20385. interactionManager.dispatchEvent(displayObject, 'mouseout', eventData);
  20386. };
  20387. /**
  20388. * Is called when a key is pressed
  20389. * @private
  20390. * @param {KeyboardEvent} e - The keydown event.
  20391. */
  20392. AccessibilityManager.prototype._onKeyDown = function (e) {
  20393. if (e.keyCode !== KEY_CODE_TAB) {
  20394. return;
  20395. }
  20396. this.activate();
  20397. };
  20398. /**
  20399. * Is called when the mouse moves across the renderer element
  20400. * @private
  20401. * @param {MouseEvent} e - The mouse event.
  20402. */
  20403. AccessibilityManager.prototype._onMouseMove = function (e) {
  20404. if (e.movementX === 0 && e.movementY === 0) {
  20405. return;
  20406. }
  20407. this.deactivate();
  20408. };
  20409. /** Destroys the accessibility manager */
  20410. AccessibilityManager.prototype.destroy = function () {
  20411. this.destroyTouchHook();
  20412. this.div = null;
  20413. globalThis.document.removeEventListener('mousemove', this._onMouseMove, true);
  20414. globalThis.removeEventListener('keydown', this._onKeyDown);
  20415. this.pool = null;
  20416. this.children = null;
  20417. this.renderer = null;
  20418. };
  20419. /** @ignore */
  20420. AccessibilityManager.extension = {
  20421. name: 'accessibility',
  20422. type: [
  20423. ExtensionType.RendererPlugin,
  20424. ExtensionType.CanvasRendererPlugin ],
  20425. };
  20426. return AccessibilityManager;
  20427. }());
  20428. /*!
  20429. * @pixi/interaction - v6.5.10
  20430. * Compiled Thu, 06 Jul 2023 15:25:11 UTC
  20431. *
  20432. * @pixi/interaction is licensed under the MIT License.
  20433. * http://www.opensource.org/licenses/mit-license
  20434. */
  20435. /**
  20436. * Holds all information related to an Interaction event
  20437. * @memberof PIXI
  20438. */
  20439. var InteractionData = /** @class */ (function () {
  20440. function InteractionData() {
  20441. /**
  20442. * Pressure applied by the pointing device during the event. A Touch's force property
  20443. * will be represented by this value.
  20444. * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/pressure
  20445. */
  20446. this.pressure = 0;
  20447. /**
  20448. * From TouchEvents (not PointerEvents triggered by touches), the rotationAngle of the Touch.
  20449. * @see https://developer.mozilla.org/en-US/docs/Web/API/Touch/rotationAngle
  20450. */
  20451. this.rotationAngle = 0;
  20452. /**
  20453. * Twist of a stylus pointer.
  20454. * @see https://w3c.github.io/pointerevents/#pointerevent-interface
  20455. */
  20456. this.twist = 0;
  20457. /**
  20458. * Barrel pressure on a stylus pointer.
  20459. * @see https://w3c.github.io/pointerevents/#pointerevent-interface
  20460. */
  20461. this.tangentialPressure = 0;
  20462. this.global = new Point();
  20463. this.target = null;
  20464. this.originalEvent = null;
  20465. this.identifier = null;
  20466. this.isPrimary = false;
  20467. this.button = 0;
  20468. this.buttons = 0;
  20469. this.width = 0;
  20470. this.height = 0;
  20471. this.tiltX = 0;
  20472. this.tiltY = 0;
  20473. this.pointerType = null;
  20474. this.pressure = 0;
  20475. this.rotationAngle = 0;
  20476. this.twist = 0;
  20477. this.tangentialPressure = 0;
  20478. }
  20479. Object.defineProperty(InteractionData.prototype, "pointerId", {
  20480. /**
  20481. * The unique identifier of the pointer. It will be the same as `identifier`.
  20482. * @readonly
  20483. * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/pointerId
  20484. */
  20485. get: function () {
  20486. return this.identifier;
  20487. },
  20488. enumerable: false,
  20489. configurable: true
  20490. });
  20491. /**
  20492. * This will return the local coordinates of the specified displayObject for this InteractionData
  20493. * @param displayObject - The DisplayObject that you would like the local
  20494. * coords off
  20495. * @param point - A Point object in which to store the value, optional (otherwise
  20496. * will create a new point)
  20497. * @param globalPos - A Point object containing your custom global coords, optional
  20498. * (otherwise will use the current global coords)
  20499. * @returns - A point containing the coordinates of the InteractionData position relative
  20500. * to the DisplayObject
  20501. */
  20502. InteractionData.prototype.getLocalPosition = function (displayObject, point, globalPos) {
  20503. return displayObject.worldTransform.applyInverse(globalPos || this.global, point);
  20504. };
  20505. /**
  20506. * Copies properties from normalized event data.
  20507. * @param {Touch|MouseEvent|PointerEvent} event - The normalized event data
  20508. */
  20509. InteractionData.prototype.copyEvent = function (event) {
  20510. // isPrimary should only change on touchstart/pointerdown, so we don't want to overwrite
  20511. // it with "false" on later events when our shim for it on touch events might not be
  20512. // accurate
  20513. if ('isPrimary' in event && event.isPrimary) {
  20514. this.isPrimary = true;
  20515. }
  20516. this.button = 'button' in event && event.button;
  20517. // event.buttons is not available in all browsers (ie. Safari), but it does have a non-standard
  20518. // event.which property instead, which conveys the same information.
  20519. var buttons = 'buttons' in event && event.buttons;
  20520. this.buttons = Number.isInteger(buttons) ? buttons : 'which' in event && event.which;
  20521. this.width = 'width' in event && event.width;
  20522. this.height = 'height' in event && event.height;
  20523. this.tiltX = 'tiltX' in event && event.tiltX;
  20524. this.tiltY = 'tiltY' in event && event.tiltY;
  20525. this.pointerType = 'pointerType' in event && event.pointerType;
  20526. this.pressure = 'pressure' in event && event.pressure;
  20527. this.rotationAngle = 'rotationAngle' in event && event.rotationAngle;
  20528. this.twist = ('twist' in event && event.twist) || 0;
  20529. this.tangentialPressure = ('tangentialPressure' in event && event.tangentialPressure) || 0;
  20530. };
  20531. /** Resets the data for pooling. */
  20532. InteractionData.prototype.reset = function () {
  20533. // isPrimary is the only property that we really need to reset - everything else is
  20534. // guaranteed to be overwritten
  20535. this.isPrimary = false;
  20536. };
  20537. return InteractionData;
  20538. }());
  20539. /*! *****************************************************************************
  20540. Copyright (c) Microsoft Corporation.
  20541. Permission to use, copy, modify, and/or distribute this software for any
  20542. purpose with or without fee is hereby granted.
  20543. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  20544. REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
  20545. AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  20546. INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
  20547. LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
  20548. OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
  20549. PERFORMANCE OF THIS SOFTWARE.
  20550. ***************************************************************************** */
  20551. /* global Reflect, Promise */
  20552. var extendStatics$h = function(d, b) {
  20553. extendStatics$h = Object.setPrototypeOf ||
  20554. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  20555. function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } };
  20556. return extendStatics$h(d, b);
  20557. };
  20558. function __extends$h(d, b) {
  20559. extendStatics$h(d, b);
  20560. function __() { this.constructor = d; }
  20561. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  20562. }
  20563. /**
  20564. * Event class that mimics native DOM events.
  20565. * @memberof PIXI
  20566. */
  20567. var InteractionEvent = /** @class */ (function () {
  20568. function InteractionEvent() {
  20569. this.stopped = false;
  20570. this.stopsPropagatingAt = null;
  20571. this.stopPropagationHint = false;
  20572. this.target = null;
  20573. this.currentTarget = null;
  20574. this.type = null;
  20575. this.data = null;
  20576. }
  20577. /** Prevents event from reaching any objects other than the current object. */
  20578. InteractionEvent.prototype.stopPropagation = function () {
  20579. this.stopped = true;
  20580. this.stopPropagationHint = true;
  20581. this.stopsPropagatingAt = this.currentTarget;
  20582. };
  20583. /** Resets the event. */
  20584. InteractionEvent.prototype.reset = function () {
  20585. this.stopped = false;
  20586. this.stopsPropagatingAt = null;
  20587. this.stopPropagationHint = false;
  20588. this.currentTarget = null;
  20589. this.target = null;
  20590. };
  20591. return InteractionEvent;
  20592. }());
  20593. /**
  20594. * DisplayObjects with the {@link PIXI.interactiveTarget} mixin use this class to track interactions
  20595. * @class
  20596. * @private
  20597. * @memberof PIXI
  20598. */
  20599. var InteractionTrackingData = /** @class */ (function () {
  20600. /**
  20601. * @param {number} pointerId - Unique pointer id of the event
  20602. * @private
  20603. */
  20604. function InteractionTrackingData(pointerId) {
  20605. this._pointerId = pointerId;
  20606. this._flags = InteractionTrackingData.FLAGS.NONE;
  20607. }
  20608. /**
  20609. *
  20610. * @private
  20611. * @param {number} flag - The interaction flag to set
  20612. * @param {boolean} yn - Should the flag be set or unset
  20613. */
  20614. InteractionTrackingData.prototype._doSet = function (flag, yn) {
  20615. if (yn) {
  20616. this._flags = this._flags | flag;
  20617. }
  20618. else {
  20619. this._flags = this._flags & (~flag);
  20620. }
  20621. };
  20622. Object.defineProperty(InteractionTrackingData.prototype, "pointerId", {
  20623. /**
  20624. * Unique pointer id of the event
  20625. * @readonly
  20626. * @private
  20627. * @member {number}
  20628. */
  20629. get: function () {
  20630. return this._pointerId;
  20631. },
  20632. enumerable: false,
  20633. configurable: true
  20634. });
  20635. Object.defineProperty(InteractionTrackingData.prototype, "flags", {
  20636. /**
  20637. * State of the tracking data, expressed as bit flags
  20638. * @private
  20639. * @member {number}
  20640. */
  20641. get: function () {
  20642. return this._flags;
  20643. },
  20644. set: function (flags) {
  20645. this._flags = flags;
  20646. },
  20647. enumerable: false,
  20648. configurable: true
  20649. });
  20650. Object.defineProperty(InteractionTrackingData.prototype, "none", {
  20651. /**
  20652. * Is the tracked event inactive (not over or down)?
  20653. * @private
  20654. * @member {number}
  20655. */
  20656. get: function () {
  20657. return this._flags === InteractionTrackingData.FLAGS.NONE;
  20658. },
  20659. enumerable: false,
  20660. configurable: true
  20661. });
  20662. Object.defineProperty(InteractionTrackingData.prototype, "over", {
  20663. /**
  20664. * Is the tracked event over the DisplayObject?
  20665. * @private
  20666. * @member {boolean}
  20667. */
  20668. get: function () {
  20669. return (this._flags & InteractionTrackingData.FLAGS.OVER) !== 0;
  20670. },
  20671. set: function (yn) {
  20672. this._doSet(InteractionTrackingData.FLAGS.OVER, yn);
  20673. },
  20674. enumerable: false,
  20675. configurable: true
  20676. });
  20677. Object.defineProperty(InteractionTrackingData.prototype, "rightDown", {
  20678. /**
  20679. * Did the right mouse button come down in the DisplayObject?
  20680. * @private
  20681. * @member {boolean}
  20682. */
  20683. get: function () {
  20684. return (this._flags & InteractionTrackingData.FLAGS.RIGHT_DOWN) !== 0;
  20685. },
  20686. set: function (yn) {
  20687. this._doSet(InteractionTrackingData.FLAGS.RIGHT_DOWN, yn);
  20688. },
  20689. enumerable: false,
  20690. configurable: true
  20691. });
  20692. Object.defineProperty(InteractionTrackingData.prototype, "leftDown", {
  20693. /**
  20694. * Did the left mouse button come down in the DisplayObject?
  20695. * @private
  20696. * @member {boolean}
  20697. */
  20698. get: function () {
  20699. return (this._flags & InteractionTrackingData.FLAGS.LEFT_DOWN) !== 0;
  20700. },
  20701. set: function (yn) {
  20702. this._doSet(InteractionTrackingData.FLAGS.LEFT_DOWN, yn);
  20703. },
  20704. enumerable: false,
  20705. configurable: true
  20706. });
  20707. InteractionTrackingData.FLAGS = Object.freeze({
  20708. NONE: 0,
  20709. OVER: 1 << 0,
  20710. LEFT_DOWN: 1 << 1,
  20711. RIGHT_DOWN: 1 << 2,
  20712. });
  20713. return InteractionTrackingData;
  20714. }());
  20715. /**
  20716. * Strategy how to search through stage tree for interactive objects
  20717. * @memberof PIXI
  20718. */
  20719. var TreeSearch = /** @class */ (function () {
  20720. function TreeSearch() {
  20721. this._tempPoint = new Point();
  20722. }
  20723. /**
  20724. * Recursive implementation for findHit
  20725. * @private
  20726. * @param interactionEvent - event containing the point that
  20727. * is tested for collision
  20728. * @param displayObject - the displayObject
  20729. * that will be hit test (recursively crawls its children)
  20730. * @param func - the function that will be called on each interactive object. The
  20731. * interactionEvent, displayObject and hit will be passed to the function
  20732. * @param hitTest - this indicates if the objects inside should be hit test against the point
  20733. * @param interactive - Whether the displayObject is interactive
  20734. * @returns - Returns true if the displayObject hit the point
  20735. */
  20736. TreeSearch.prototype.recursiveFindHit = function (interactionEvent, displayObject, func, hitTest, interactive) {
  20737. var _a;
  20738. if (!displayObject || !displayObject.visible) {
  20739. return false;
  20740. }
  20741. var point = interactionEvent.data.global;
  20742. // Took a little while to rework this function correctly! But now it is done and nice and optimized! ^_^
  20743. //
  20744. // This function will now loop through all objects and then only hit test the objects it HAS
  20745. // to, not all of them. MUCH faster..
  20746. // An object will be hit test if the following is true:
  20747. //
  20748. // 1: It is interactive.
  20749. // 2: It belongs to a parent that is interactive AND one of the parents children have not already been hit.
  20750. //
  20751. // As another little optimization once an interactive object has been hit we can carry on
  20752. // through the scenegraph, but we know that there will be no more hits! So we can avoid extra hit tests
  20753. // A final optimization is that an object is not hit test directly if a child has already been hit.
  20754. interactive = displayObject.interactive || interactive;
  20755. var hit = false;
  20756. var interactiveParent = interactive;
  20757. // Flag here can set to false if the event is outside the parents hitArea or mask
  20758. var hitTestChildren = true;
  20759. // If there is a hitArea, no need to test against anything else if the pointer is not within the hitArea
  20760. // There is also no longer a need to hitTest children.
  20761. if (displayObject.hitArea) {
  20762. if (hitTest) {
  20763. displayObject.worldTransform.applyInverse(point, this._tempPoint);
  20764. if (!displayObject.hitArea.contains(this._tempPoint.x, this._tempPoint.y)) {
  20765. hitTest = false;
  20766. hitTestChildren = false;
  20767. }
  20768. else {
  20769. hit = true;
  20770. }
  20771. }
  20772. interactiveParent = false;
  20773. }
  20774. // If there is a mask, no need to hitTest against anything else if the pointer is not within the mask.
  20775. // We still want to hitTestChildren, however, to ensure a mouseout can still be generated.
  20776. // https://github.com/pixijs/pixi.js/issues/5135
  20777. else if (displayObject._mask) {
  20778. if (hitTest) {
  20779. var maskObject = (displayObject._mask.isMaskData
  20780. ? displayObject._mask.maskObject : displayObject._mask);
  20781. if (maskObject && !((_a = maskObject.containsPoint) === null || _a === void 0 ? void 0 : _a.call(maskObject, point))) {
  20782. hitTest = false;
  20783. }
  20784. }
  20785. }
  20786. // ** FREE TIP **! If an object is not interactive or has no buttons in it
  20787. // (such as a game scene!) set interactiveChildren to false for that displayObject.
  20788. // This will allow PixiJS to completely ignore and bypass checking the displayObjects children.
  20789. if (hitTestChildren && displayObject.interactiveChildren && displayObject.children) {
  20790. var children = displayObject.children;
  20791. for (var i = children.length - 1; i >= 0; i--) {
  20792. var child = children[i];
  20793. // time to get recursive.. if this function will return if something is hit..
  20794. var childHit = this.recursiveFindHit(interactionEvent, child, func, hitTest, interactiveParent);
  20795. if (childHit) {
  20796. // its a good idea to check if a child has lost its parent.
  20797. // this means it has been removed whilst looping so its best
  20798. if (!child.parent) {
  20799. continue;
  20800. }
  20801. // we no longer need to hit test any more objects in this container as we we
  20802. // now know the parent has been hit
  20803. interactiveParent = false;
  20804. // If the child is interactive , that means that the object hit was actually
  20805. // interactive and not just the child of an interactive object.
  20806. // This means we no longer need to hit test anything else. We still need to run
  20807. // through all objects, but we don't need to perform any hit tests.
  20808. if (childHit) {
  20809. if (interactionEvent.target) {
  20810. hitTest = false;
  20811. }
  20812. hit = true;
  20813. }
  20814. }
  20815. }
  20816. }
  20817. // no point running this if the item is not interactive or does not have an interactive parent.
  20818. if (interactive) {
  20819. // if we are hit testing (as in we have no hit any objects yet)
  20820. // We also don't need to worry about hit testing if once of the displayObjects children
  20821. // has already been hit - but only if it was interactive, otherwise we need to keep
  20822. // looking for an interactive child, just in case we hit one
  20823. if (hitTest && !interactionEvent.target) {
  20824. // already tested against hitArea if it is defined
  20825. if (!displayObject.hitArea && displayObject.containsPoint) {
  20826. if (displayObject.containsPoint(point)) {
  20827. hit = true;
  20828. }
  20829. }
  20830. }
  20831. if (displayObject.interactive) {
  20832. if (hit && !interactionEvent.target) {
  20833. interactionEvent.target = displayObject;
  20834. }
  20835. if (func) {
  20836. func(interactionEvent, displayObject, !!hit);
  20837. }
  20838. }
  20839. }
  20840. return hit;
  20841. };
  20842. /**
  20843. * This function is provides a neat way of crawling through the scene graph and running a
  20844. * specified function on all interactive objects it finds. It will also take care of hit
  20845. * testing the interactive objects and passes the hit across in the function.
  20846. * @private
  20847. * @param interactionEvent - event containing the point that
  20848. * is tested for collision
  20849. * @param displayObject - the displayObject
  20850. * that will be hit test (recursively crawls its children)
  20851. * @param func - the function that will be called on each interactive object. The
  20852. * interactionEvent, displayObject and hit will be passed to the function
  20853. * @param hitTest - this indicates if the objects inside should be hit test against the point
  20854. * @returns - Returns true if the displayObject hit the point
  20855. */
  20856. TreeSearch.prototype.findHit = function (interactionEvent, displayObject, func, hitTest) {
  20857. this.recursiveFindHit(interactionEvent, displayObject, func, hitTest, false);
  20858. };
  20859. return TreeSearch;
  20860. }());
  20861. /**
  20862. * Interface for classes that represent a hit area.
  20863. *
  20864. * It is implemented by the following classes:
  20865. * - {@link PIXI.Circle}
  20866. * - {@link PIXI.Ellipse}
  20867. * - {@link PIXI.Polygon}
  20868. * - {@link PIXI.RoundedRectangle}
  20869. * @interface IHitArea
  20870. * @memberof PIXI
  20871. */
  20872. /**
  20873. * Checks whether the x and y coordinates given are contained within this area
  20874. * @method
  20875. * @name contains
  20876. * @memberof PIXI.IHitArea#
  20877. * @param {number} x - The X coordinate of the point to test
  20878. * @param {number} y - The Y coordinate of the point to test
  20879. * @returns {boolean} Whether the x/y coordinates are within this area
  20880. */
  20881. /**
  20882. * Default property values of interactive objects
  20883. * Used by {@link PIXI.InteractionManager} to automatically give all DisplayObjects these properties
  20884. * @private
  20885. * @name interactiveTarget
  20886. * @type {object}
  20887. * @memberof PIXI
  20888. * @example
  20889. * function MyObject() {}
  20890. *
  20891. * Object.assign(
  20892. * DisplayObject.prototype,
  20893. * PIXI.interactiveTarget
  20894. * );
  20895. */
  20896. var interactiveTarget = {
  20897. interactive: false,
  20898. interactiveChildren: true,
  20899. hitArea: null,
  20900. /**
  20901. * If enabled, the mouse cursor use the pointer behavior when hovered over the displayObject if it is interactive
  20902. * Setting this changes the 'cursor' property to `'pointer'`.
  20903. * @example
  20904. * const sprite = new PIXI.Sprite(texture);
  20905. * sprite.interactive = true;
  20906. * sprite.buttonMode = true;
  20907. * @member {boolean}
  20908. * @memberof PIXI.DisplayObject#
  20909. */
  20910. get buttonMode() {
  20911. return this.cursor === 'pointer';
  20912. },
  20913. set buttonMode(value) {
  20914. if (value) {
  20915. this.cursor = 'pointer';
  20916. }
  20917. else if (this.cursor === 'pointer') {
  20918. this.cursor = null;
  20919. }
  20920. },
  20921. /**
  20922. * This defines what cursor mode is used when the mouse cursor
  20923. * is hovered over the displayObject.
  20924. * @example
  20925. * const sprite = new PIXI.Sprite(texture);
  20926. * sprite.interactive = true;
  20927. * sprite.cursor = 'wait';
  20928. * @see https://developer.mozilla.org/en/docs/Web/CSS/cursor
  20929. * @member {string}
  20930. * @memberof PIXI.DisplayObject#
  20931. */
  20932. cursor: null,
  20933. /**
  20934. * Internal set of all active pointers, by identifier
  20935. * @member {Map<number, InteractionTrackingData>}
  20936. * @memberof PIXI.DisplayObject#
  20937. * @private
  20938. */
  20939. get trackedPointers() {
  20940. if (this._trackedPointers === undefined)
  20941. { this._trackedPointers = {}; }
  20942. return this._trackedPointers;
  20943. },
  20944. /**
  20945. * Map of all tracked pointers, by identifier. Use trackedPointers to access.
  20946. * @private
  20947. * @type {Map<number, InteractionTrackingData>}
  20948. */
  20949. _trackedPointers: undefined,
  20950. };
  20951. // Mix interactiveTarget into DisplayObject.prototype
  20952. DisplayObject.mixin(interactiveTarget);
  20953. var MOUSE_POINTER_ID = 1;
  20954. // helpers for hitTest() - only used inside hitTest()
  20955. var hitTestEvent = {
  20956. target: null,
  20957. data: {
  20958. global: null,
  20959. },
  20960. };
  20961. /**
  20962. * The interaction manager deals with mouse, touch and pointer events.
  20963. *
  20964. * Any DisplayObject can be interactive if its `interactive` property is set to true.
  20965. *
  20966. * This manager also supports multitouch.
  20967. *
  20968. * An instance of this class is automatically created by default, and can be found at `renderer.plugins.interaction`
  20969. * @memberof PIXI
  20970. */
  20971. var InteractionManager = /** @class */ (function (_super) {
  20972. __extends$h(InteractionManager, _super);
  20973. /**
  20974. * @param {PIXI.CanvasRenderer|PIXI.Renderer} renderer - A reference to the current renderer
  20975. * @param options - The options for the manager.
  20976. * @param {boolean} [options.autoPreventDefault=true] - Should the manager automatically prevent default browser actions.
  20977. * @param {number} [options.interactionFrequency=10] - Maximum frequency (ms) at pointer over/out states will be checked.
  20978. * @param {number} [options.useSystemTicker=true] - Whether to add {@link tickerUpdate} to {@link PIXI.Ticker.system}.
  20979. */
  20980. function InteractionManager(renderer, options) {
  20981. var _this = _super.call(this) || this;
  20982. options = options || {};
  20983. _this.renderer = renderer;
  20984. _this.autoPreventDefault = options.autoPreventDefault !== undefined ? options.autoPreventDefault : true;
  20985. _this.interactionFrequency = options.interactionFrequency || 10;
  20986. _this.mouse = new InteractionData();
  20987. _this.mouse.identifier = MOUSE_POINTER_ID;
  20988. // setting the mouse to start off far off screen will mean that mouse over does
  20989. // not get called before we even move the mouse.
  20990. _this.mouse.global.set(-999999);
  20991. _this.activeInteractionData = {};
  20992. _this.activeInteractionData[MOUSE_POINTER_ID] = _this.mouse;
  20993. _this.interactionDataPool = [];
  20994. _this.eventData = new InteractionEvent();
  20995. _this.interactionDOMElement = null;
  20996. _this.moveWhenInside = false;
  20997. _this.eventsAdded = false;
  20998. _this.tickerAdded = false;
  20999. _this.mouseOverRenderer = !('PointerEvent' in globalThis);
  21000. _this.supportsTouchEvents = 'ontouchstart' in globalThis;
  21001. _this.supportsPointerEvents = !!globalThis.PointerEvent;
  21002. // this will make it so that you don't have to call bind all the time
  21003. _this.onPointerUp = _this.onPointerUp.bind(_this);
  21004. _this.processPointerUp = _this.processPointerUp.bind(_this);
  21005. _this.onPointerCancel = _this.onPointerCancel.bind(_this);
  21006. _this.processPointerCancel = _this.processPointerCancel.bind(_this);
  21007. _this.onPointerDown = _this.onPointerDown.bind(_this);
  21008. _this.processPointerDown = _this.processPointerDown.bind(_this);
  21009. _this.onPointerMove = _this.onPointerMove.bind(_this);
  21010. _this.processPointerMove = _this.processPointerMove.bind(_this);
  21011. _this.onPointerOut = _this.onPointerOut.bind(_this);
  21012. _this.processPointerOverOut = _this.processPointerOverOut.bind(_this);
  21013. _this.onPointerOver = _this.onPointerOver.bind(_this);
  21014. _this.cursorStyles = {
  21015. default: 'inherit',
  21016. pointer: 'pointer',
  21017. };
  21018. _this.currentCursorMode = null;
  21019. _this.cursor = null;
  21020. _this.resolution = 1;
  21021. _this.delayedEvents = [];
  21022. _this.search = new TreeSearch();
  21023. _this._tempDisplayObject = new TemporaryDisplayObject();
  21024. _this._eventListenerOptions = { capture: true, passive: false };
  21025. /**
  21026. * Fired when a pointer device button (usually a mouse left-button) is pressed on the display
  21027. * object.
  21028. * @event PIXI.InteractionManager#mousedown
  21029. * @param {PIXI.InteractionEvent} event - Interaction event
  21030. */
  21031. /**
  21032. * Fired when a pointer device secondary button (usually a mouse right-button) is pressed
  21033. * on the display object.
  21034. * @event PIXI.InteractionManager#rightdown
  21035. * @param {PIXI.InteractionEvent} event - Interaction event
  21036. */
  21037. /**
  21038. * Fired when a pointer device button (usually a mouse left-button) is released over the display
  21039. * object.
  21040. * @event PIXI.InteractionManager#mouseup
  21041. * @param {PIXI.InteractionEvent} event - Interaction event
  21042. */
  21043. /**
  21044. * Fired when a pointer device secondary button (usually a mouse right-button) is released
  21045. * over the display object.
  21046. * @event PIXI.InteractionManager#rightup
  21047. * @param {PIXI.InteractionEvent} event - Interaction event
  21048. */
  21049. /**
  21050. * Fired when a pointer device button (usually a mouse left-button) is pressed and released on
  21051. * the display object.
  21052. * @event PIXI.InteractionManager#click
  21053. * @param {PIXI.InteractionEvent} event - Interaction event
  21054. */
  21055. /**
  21056. * Fired when a pointer device secondary button (usually a mouse right-button) is pressed
  21057. * and released on the display object.
  21058. * @event PIXI.InteractionManager#rightclick
  21059. * @param {PIXI.InteractionEvent} event - Interaction event
  21060. */
  21061. /**
  21062. * Fired when a pointer device button (usually a mouse left-button) is released outside the
  21063. * display object that initially registered a
  21064. * [mousedown]{@link PIXI.InteractionManager#event:mousedown}.
  21065. * @event PIXI.InteractionManager#mouseupoutside
  21066. * @param {PIXI.InteractionEvent} event - Interaction event
  21067. */
  21068. /**
  21069. * Fired when a pointer device secondary button (usually a mouse right-button) is released
  21070. * outside the display object that initially registered a
  21071. * [rightdown]{@link PIXI.InteractionManager#event:rightdown}.
  21072. * @event PIXI.InteractionManager#rightupoutside
  21073. * @param {PIXI.InteractionEvent} event - Interaction event
  21074. */
  21075. /**
  21076. * Fired when a pointer device (usually a mouse) is moved while over the display object
  21077. * @event PIXI.InteractionManager#mousemove
  21078. * @param {PIXI.InteractionEvent} event - Interaction event
  21079. */
  21080. /**
  21081. * Fired when a pointer device (usually a mouse) is moved onto the display object
  21082. * @event PIXI.InteractionManager#mouseover
  21083. * @param {PIXI.InteractionEvent} event - Interaction event
  21084. */
  21085. /**
  21086. * Fired when a pointer device (usually a mouse) is moved off the display object
  21087. * @event PIXI.InteractionManager#mouseout
  21088. * @param {PIXI.InteractionEvent} event - Interaction event
  21089. */
  21090. /**
  21091. * Fired when a pointer device button is pressed on the display object.
  21092. * @event PIXI.InteractionManager#pointerdown
  21093. * @param {PIXI.InteractionEvent} event - Interaction event
  21094. */
  21095. /**
  21096. * Fired when a pointer device button is released over the display object.
  21097. * Not always fired when some buttons are held down while others are released. In those cases,
  21098. * use [mousedown]{@link PIXI.InteractionManager#event:mousedown} and
  21099. * [mouseup]{@link PIXI.InteractionManager#event:mouseup} instead.
  21100. * @event PIXI.InteractionManager#pointerup
  21101. * @param {PIXI.InteractionEvent} event - Interaction event
  21102. */
  21103. /**
  21104. * Fired when the operating system cancels a pointer event
  21105. * @event PIXI.InteractionManager#pointercancel
  21106. * @param {PIXI.InteractionEvent} event - Interaction event
  21107. */
  21108. /**
  21109. * Fired when a pointer device button is pressed and released on the display object.
  21110. * @event PIXI.InteractionManager#pointertap
  21111. * @param {PIXI.InteractionEvent} event - Interaction event
  21112. */
  21113. /**
  21114. * Fired when a pointer device button is released outside the display object that initially
  21115. * registered a [pointerdown]{@link PIXI.InteractionManager#event:pointerdown}.
  21116. * @event PIXI.InteractionManager#pointerupoutside
  21117. * @param {PIXI.InteractionEvent} event - Interaction event
  21118. */
  21119. /**
  21120. * Fired when a pointer device is moved while over the display object
  21121. * @event PIXI.InteractionManager#pointermove
  21122. * @param {PIXI.InteractionEvent} event - Interaction event
  21123. */
  21124. /**
  21125. * Fired when a pointer device is moved onto the display object
  21126. * @event PIXI.InteractionManager#pointerover
  21127. * @param {PIXI.InteractionEvent} event - Interaction event
  21128. */
  21129. /**
  21130. * Fired when a pointer device is moved off the display object
  21131. * @event PIXI.InteractionManager#pointerout
  21132. * @param {PIXI.InteractionEvent} event - Interaction event
  21133. */
  21134. /**
  21135. * Fired when a touch point is placed on the display object.
  21136. * @event PIXI.InteractionManager#touchstart
  21137. * @param {PIXI.InteractionEvent} event - Interaction event
  21138. */
  21139. /**
  21140. * Fired when a touch point is removed from the display object.
  21141. * @event PIXI.InteractionManager#touchend
  21142. * @param {PIXI.InteractionEvent} event - Interaction event
  21143. */
  21144. /**
  21145. * Fired when the operating system cancels a touch
  21146. * @event PIXI.InteractionManager#touchcancel
  21147. * @param {PIXI.InteractionEvent} event - Interaction event
  21148. */
  21149. /**
  21150. * Fired when a touch point is placed and removed from the display object.
  21151. * @event PIXI.InteractionManager#tap
  21152. * @param {PIXI.InteractionEvent} event - Interaction event
  21153. */
  21154. /**
  21155. * Fired when a touch point is removed outside of the display object that initially
  21156. * registered a [touchstart]{@link PIXI.InteractionManager#event:touchstart}.
  21157. * @event PIXI.InteractionManager#touchendoutside
  21158. * @param {PIXI.InteractionEvent} event - Interaction event
  21159. */
  21160. /**
  21161. * Fired when a touch point is moved along the display object.
  21162. * @event PIXI.InteractionManager#touchmove
  21163. * @param {PIXI.InteractionEvent} event - Interaction event
  21164. */
  21165. /**
  21166. * Fired when a pointer device button (usually a mouse left-button) is pressed on the display.
  21167. * object. DisplayObject's `interactive` property must be set to `true` to fire event.
  21168. *
  21169. * This comes from the @pixi/interaction package.
  21170. * @event PIXI.DisplayObject#mousedown
  21171. * @param {PIXI.InteractionEvent} event - Interaction event
  21172. */
  21173. /**
  21174. * Fired when a pointer device secondary button (usually a mouse right-button) is pressed
  21175. * on the display object. DisplayObject's `interactive` property must be set to `true` to fire event.
  21176. *
  21177. * This comes from the @pixi/interaction package.
  21178. * @event PIXI.DisplayObject#rightdown
  21179. * @param {PIXI.InteractionEvent} event - Interaction event
  21180. */
  21181. /**
  21182. * Fired when a pointer device button (usually a mouse left-button) is released over the display
  21183. * object. DisplayObject's `interactive` property must be set to `true` to fire event.
  21184. *
  21185. * This comes from the @pixi/interaction package.
  21186. * @event PIXI.DisplayObject#mouseup
  21187. * @param {PIXI.InteractionEvent} event - Interaction event
  21188. */
  21189. /**
  21190. * Fired when a pointer device secondary button (usually a mouse right-button) is released
  21191. * over the display object. DisplayObject's `interactive` property must be set to `true` to fire event.
  21192. *
  21193. * This comes from the @pixi/interaction package.
  21194. * @event PIXI.DisplayObject#rightup
  21195. * @param {PIXI.InteractionEvent} event - Interaction event
  21196. */
  21197. /**
  21198. * Fired when a pointer device button (usually a mouse left-button) is pressed and released on
  21199. * the display object. DisplayObject's `interactive` property must be set to `true` to fire event.
  21200. *
  21201. * This comes from the @pixi/interaction package.
  21202. * @event PIXI.DisplayObject#click
  21203. * @param {PIXI.InteractionEvent} event - Interaction event
  21204. */
  21205. /**
  21206. * Fired when a pointer device secondary button (usually a mouse right-button) is pressed
  21207. * and released on the display object. DisplayObject's `interactive` property must be set to `true` to fire event.
  21208. *
  21209. * This comes from the @pixi/interaction package.
  21210. * @event PIXI.DisplayObject#rightclick
  21211. * @param {PIXI.InteractionEvent} event - Interaction event
  21212. */
  21213. /**
  21214. * Fired when a pointer device button (usually a mouse left-button) is released outside the
  21215. * display object that initially registered a
  21216. * [mousedown]{@link PIXI.DisplayObject#event:mousedown}.
  21217. * DisplayObject's `interactive` property must be set to `true` to fire event.
  21218. *
  21219. * This comes from the @pixi/interaction package.
  21220. * @event PIXI.DisplayObject#mouseupoutside
  21221. * @param {PIXI.InteractionEvent} event - Interaction event
  21222. */
  21223. /**
  21224. * Fired when a pointer device secondary button (usually a mouse right-button) is released
  21225. * outside the display object that initially registered a
  21226. * [rightdown]{@link PIXI.DisplayObject#event:rightdown}.
  21227. * DisplayObject's `interactive` property must be set to `true` to fire event.
  21228. *
  21229. * This comes from the @pixi/interaction package.
  21230. * @event PIXI.DisplayObject#rightupoutside
  21231. * @param {PIXI.InteractionEvent} event - Interaction event
  21232. */
  21233. /**
  21234. * Fired when a pointer device (usually a mouse) is moved while over the display object.
  21235. * DisplayObject's `interactive` property must be set to `true` to fire event.
  21236. *
  21237. * This comes from the @pixi/interaction package.
  21238. * @event PIXI.DisplayObject#mousemove
  21239. * @param {PIXI.InteractionEvent} event - Interaction event
  21240. */
  21241. /**
  21242. * Fired when a pointer device (usually a mouse) is moved onto the display object.
  21243. * DisplayObject's `interactive` property must be set to `true` to fire event.
  21244. *
  21245. * This comes from the @pixi/interaction package.
  21246. * @event PIXI.DisplayObject#mouseover
  21247. * @param {PIXI.InteractionEvent} event - Interaction event
  21248. */
  21249. /**
  21250. * Fired when a pointer device (usually a mouse) is moved off the display object.
  21251. * DisplayObject's `interactive` property must be set to `true` to fire event.
  21252. *
  21253. * This comes from the @pixi/interaction package.
  21254. * @event PIXI.DisplayObject#mouseout
  21255. * @param {PIXI.InteractionEvent} event - Interaction event
  21256. */
  21257. /**
  21258. * Fired when a pointer device button is pressed on the display object.
  21259. * DisplayObject's `interactive` property must be set to `true` to fire event.
  21260. *
  21261. * This comes from the @pixi/interaction package.
  21262. * @event PIXI.DisplayObject#pointerdown
  21263. * @param {PIXI.InteractionEvent} event - Interaction event
  21264. */
  21265. /**
  21266. * Fired when a pointer device button is released over the display object.
  21267. * DisplayObject's `interactive` property must be set to `true` to fire event.
  21268. *
  21269. * This comes from the @pixi/interaction package.
  21270. * @event PIXI.DisplayObject#pointerup
  21271. * @param {PIXI.InteractionEvent} event - Interaction event
  21272. */
  21273. /**
  21274. * Fired when the operating system cancels a pointer event.
  21275. * DisplayObject's `interactive` property must be set to `true` to fire event.
  21276. *
  21277. * This comes from the @pixi/interaction package.
  21278. * @event PIXI.DisplayObject#pointercancel
  21279. * @param {PIXI.InteractionEvent} event - Interaction event
  21280. */
  21281. /**
  21282. * Fired when a pointer device button is pressed and released on the display object.
  21283. * DisplayObject's `interactive` property must be set to `true` to fire event.
  21284. *
  21285. * This comes from the @pixi/interaction package.
  21286. * @event PIXI.DisplayObject#pointertap
  21287. * @param {PIXI.InteractionEvent} event - Interaction event
  21288. */
  21289. /**
  21290. * Fired when a pointer device button is released outside the display object that initially
  21291. * registered a [pointerdown]{@link PIXI.DisplayObject#event:pointerdown}.
  21292. * DisplayObject's `interactive` property must be set to `true` to fire event.
  21293. *
  21294. * This comes from the @pixi/interaction package.
  21295. * @event PIXI.DisplayObject#pointerupoutside
  21296. * @param {PIXI.InteractionEvent} event - Interaction event
  21297. */
  21298. /**
  21299. * Fired when a pointer device is moved while over the display object.
  21300. * DisplayObject's `interactive` property must be set to `true` to fire event.
  21301. *
  21302. * This comes from the @pixi/interaction package.
  21303. * @event PIXI.DisplayObject#pointermove
  21304. * @param {PIXI.InteractionEvent} event - Interaction event
  21305. */
  21306. /**
  21307. * Fired when a pointer device is moved onto the display object.
  21308. * DisplayObject's `interactive` property must be set to `true` to fire event.
  21309. *
  21310. * This comes from the @pixi/interaction package.
  21311. * @event PIXI.DisplayObject#pointerover
  21312. * @param {PIXI.InteractionEvent} event - Interaction event
  21313. */
  21314. /**
  21315. * Fired when a pointer device is moved off the display object.
  21316. * DisplayObject's `interactive` property must be set to `true` to fire event.
  21317. *
  21318. * This comes from the @pixi/interaction package.
  21319. * @event PIXI.DisplayObject#pointerout
  21320. * @param {PIXI.InteractionEvent} event - Interaction event
  21321. */
  21322. /**
  21323. * Fired when a touch point is placed on the display object.
  21324. * DisplayObject's `interactive` property must be set to `true` to fire event.
  21325. *
  21326. * This comes from the @pixi/interaction package.
  21327. * @event PIXI.DisplayObject#touchstart
  21328. * @param {PIXI.InteractionEvent} event - Interaction event
  21329. */
  21330. /**
  21331. * Fired when a touch point is removed from the display object.
  21332. * DisplayObject's `interactive` property must be set to `true` to fire event.
  21333. *
  21334. * This comes from the @pixi/interaction package.
  21335. * @event PIXI.DisplayObject#touchend
  21336. * @param {PIXI.InteractionEvent} event - Interaction event
  21337. */
  21338. /**
  21339. * Fired when the operating system cancels a touch.
  21340. * DisplayObject's `interactive` property must be set to `true` to fire event.
  21341. *
  21342. * This comes from the @pixi/interaction package.
  21343. * @event PIXI.DisplayObject#touchcancel
  21344. * @param {PIXI.InteractionEvent} event - Interaction event
  21345. */
  21346. /**
  21347. * Fired when a touch point is placed and removed from the display object.
  21348. * DisplayObject's `interactive` property must be set to `true` to fire event.
  21349. *
  21350. * This comes from the @pixi/interaction package.
  21351. * @event PIXI.DisplayObject#tap
  21352. * @param {PIXI.InteractionEvent} event - Interaction event
  21353. */
  21354. /**
  21355. * Fired when a touch point is removed outside of the display object that initially
  21356. * registered a [touchstart]{@link PIXI.DisplayObject#event:touchstart}.
  21357. * DisplayObject's `interactive` property must be set to `true` to fire event.
  21358. *
  21359. * This comes from the @pixi/interaction package.
  21360. * @event PIXI.DisplayObject#touchendoutside
  21361. * @param {PIXI.InteractionEvent} event - Interaction event
  21362. */
  21363. /**
  21364. * Fired when a touch point is moved along the display object.
  21365. * DisplayObject's `interactive` property must be set to `true` to fire event.
  21366. *
  21367. * This comes from the @pixi/interaction package.
  21368. * @event PIXI.DisplayObject#touchmove
  21369. * @param {PIXI.InteractionEvent} event - Interaction event
  21370. */
  21371. _this._useSystemTicker = options.useSystemTicker !== undefined ? options.useSystemTicker : true;
  21372. _this.setTargetElement(_this.renderer.view, _this.renderer.resolution);
  21373. return _this;
  21374. }
  21375. Object.defineProperty(InteractionManager.prototype, "useSystemTicker", {
  21376. /**
  21377. * Should the InteractionManager automatically add {@link tickerUpdate} to {@link PIXI.Ticker.system}.
  21378. * @default true
  21379. */
  21380. get: function () {
  21381. return this._useSystemTicker;
  21382. },
  21383. set: function (useSystemTicker) {
  21384. this._useSystemTicker = useSystemTicker;
  21385. if (useSystemTicker) {
  21386. this.addTickerListener();
  21387. }
  21388. else {
  21389. this.removeTickerListener();
  21390. }
  21391. },
  21392. enumerable: false,
  21393. configurable: true
  21394. });
  21395. Object.defineProperty(InteractionManager.prototype, "lastObjectRendered", {
  21396. /**
  21397. * Last rendered object or temp object.
  21398. * @readonly
  21399. * @protected
  21400. */
  21401. get: function () {
  21402. return this.renderer._lastObjectRendered || this._tempDisplayObject;
  21403. },
  21404. enumerable: false,
  21405. configurable: true
  21406. });
  21407. /**
  21408. * Hit tests a point against the display tree, returning the first interactive object that is hit.
  21409. * @param globalPoint - A point to hit test with, in global space.
  21410. * @param root - The root display object to start from. If omitted, defaults
  21411. * to the last rendered root of the associated renderer.
  21412. * @returns - The hit display object, if any.
  21413. */
  21414. InteractionManager.prototype.hitTest = function (globalPoint, root) {
  21415. // clear the target for our hit test
  21416. hitTestEvent.target = null;
  21417. // assign the global point
  21418. hitTestEvent.data.global = globalPoint;
  21419. // ensure safety of the root
  21420. if (!root) {
  21421. root = this.lastObjectRendered;
  21422. }
  21423. // run the hit test
  21424. this.processInteractive(hitTestEvent, root, null, true);
  21425. // return our found object - it'll be null if we didn't hit anything
  21426. return hitTestEvent.target;
  21427. };
  21428. /**
  21429. * Sets the DOM element which will receive mouse/touch events. This is useful for when you have
  21430. * other DOM elements on top of the renderers Canvas element. With this you'll be bale to delegate
  21431. * another DOM element to receive those events.
  21432. * @param element - the DOM element which will receive mouse and touch events.
  21433. * @param resolution - The resolution / device pixel ratio of the new element (relative to the canvas).
  21434. */
  21435. InteractionManager.prototype.setTargetElement = function (element, resolution) {
  21436. if (resolution === void 0) { resolution = 1; }
  21437. this.removeTickerListener();
  21438. this.removeEvents();
  21439. this.interactionDOMElement = element;
  21440. this.resolution = resolution;
  21441. this.addEvents();
  21442. this.addTickerListener();
  21443. };
  21444. /** Adds the ticker listener. */
  21445. InteractionManager.prototype.addTickerListener = function () {
  21446. if (this.tickerAdded || !this.interactionDOMElement || !this._useSystemTicker) {
  21447. return;
  21448. }
  21449. Ticker.system.add(this.tickerUpdate, this, UPDATE_PRIORITY.INTERACTION);
  21450. this.tickerAdded = true;
  21451. };
  21452. /** Removes the ticker listener. */
  21453. InteractionManager.prototype.removeTickerListener = function () {
  21454. if (!this.tickerAdded) {
  21455. return;
  21456. }
  21457. Ticker.system.remove(this.tickerUpdate, this);
  21458. this.tickerAdded = false;
  21459. };
  21460. /** Registers all the DOM events. */
  21461. InteractionManager.prototype.addEvents = function () {
  21462. if (this.eventsAdded || !this.interactionDOMElement) {
  21463. return;
  21464. }
  21465. var style = this.interactionDOMElement.style;
  21466. if (globalThis.navigator.msPointerEnabled) {
  21467. style.msContentZooming = 'none';
  21468. style.msTouchAction = 'none';
  21469. }
  21470. else if (this.supportsPointerEvents) {
  21471. style.touchAction = 'none';
  21472. }
  21473. /*
  21474. * These events are added first, so that if pointer events are normalized, they are fired
  21475. * in the same order as non-normalized events. ie. pointer event 1st, mouse / touch 2nd
  21476. */
  21477. if (this.supportsPointerEvents) {
  21478. globalThis.document.addEventListener('pointermove', this.onPointerMove, this._eventListenerOptions);
  21479. this.interactionDOMElement.addEventListener('pointerdown', this.onPointerDown, this._eventListenerOptions);
  21480. // pointerout is fired in addition to pointerup (for touch events) and pointercancel
  21481. // we already handle those, so for the purposes of what we do in onPointerOut, we only
  21482. // care about the pointerleave event
  21483. this.interactionDOMElement.addEventListener('pointerleave', this.onPointerOut, this._eventListenerOptions);
  21484. this.interactionDOMElement.addEventListener('pointerover', this.onPointerOver, this._eventListenerOptions);
  21485. globalThis.addEventListener('pointercancel', this.onPointerCancel, this._eventListenerOptions);
  21486. globalThis.addEventListener('pointerup', this.onPointerUp, this._eventListenerOptions);
  21487. }
  21488. else {
  21489. globalThis.document.addEventListener('mousemove', this.onPointerMove, this._eventListenerOptions);
  21490. this.interactionDOMElement.addEventListener('mousedown', this.onPointerDown, this._eventListenerOptions);
  21491. this.interactionDOMElement.addEventListener('mouseout', this.onPointerOut, this._eventListenerOptions);
  21492. this.interactionDOMElement.addEventListener('mouseover', this.onPointerOver, this._eventListenerOptions);
  21493. globalThis.addEventListener('mouseup', this.onPointerUp, this._eventListenerOptions);
  21494. }
  21495. // always look directly for touch events so that we can provide original data
  21496. // In a future version we should change this to being just a fallback and rely solely on
  21497. // PointerEvents whenever available
  21498. if (this.supportsTouchEvents) {
  21499. this.interactionDOMElement.addEventListener('touchstart', this.onPointerDown, this._eventListenerOptions);
  21500. this.interactionDOMElement.addEventListener('touchcancel', this.onPointerCancel, this._eventListenerOptions);
  21501. this.interactionDOMElement.addEventListener('touchend', this.onPointerUp, this._eventListenerOptions);
  21502. this.interactionDOMElement.addEventListener('touchmove', this.onPointerMove, this._eventListenerOptions);
  21503. }
  21504. this.eventsAdded = true;
  21505. };
  21506. /** Removes all the DOM events that were previously registered. */
  21507. InteractionManager.prototype.removeEvents = function () {
  21508. if (!this.eventsAdded || !this.interactionDOMElement) {
  21509. return;
  21510. }
  21511. var style = this.interactionDOMElement.style;
  21512. if (globalThis.navigator.msPointerEnabled) {
  21513. style.msContentZooming = '';
  21514. style.msTouchAction = '';
  21515. }
  21516. else if (this.supportsPointerEvents) {
  21517. style.touchAction = '';
  21518. }
  21519. if (this.supportsPointerEvents) {
  21520. globalThis.document.removeEventListener('pointermove', this.onPointerMove, this._eventListenerOptions);
  21521. this.interactionDOMElement.removeEventListener('pointerdown', this.onPointerDown, this._eventListenerOptions);
  21522. this.interactionDOMElement.removeEventListener('pointerleave', this.onPointerOut, this._eventListenerOptions);
  21523. this.interactionDOMElement.removeEventListener('pointerover', this.onPointerOver, this._eventListenerOptions);
  21524. globalThis.removeEventListener('pointercancel', this.onPointerCancel, this._eventListenerOptions);
  21525. globalThis.removeEventListener('pointerup', this.onPointerUp, this._eventListenerOptions);
  21526. }
  21527. else {
  21528. globalThis.document.removeEventListener('mousemove', this.onPointerMove, this._eventListenerOptions);
  21529. this.interactionDOMElement.removeEventListener('mousedown', this.onPointerDown, this._eventListenerOptions);
  21530. this.interactionDOMElement.removeEventListener('mouseout', this.onPointerOut, this._eventListenerOptions);
  21531. this.interactionDOMElement.removeEventListener('mouseover', this.onPointerOver, this._eventListenerOptions);
  21532. globalThis.removeEventListener('mouseup', this.onPointerUp, this._eventListenerOptions);
  21533. }
  21534. if (this.supportsTouchEvents) {
  21535. this.interactionDOMElement.removeEventListener('touchstart', this.onPointerDown, this._eventListenerOptions);
  21536. this.interactionDOMElement.removeEventListener('touchcancel', this.onPointerCancel, this._eventListenerOptions);
  21537. this.interactionDOMElement.removeEventListener('touchend', this.onPointerUp, this._eventListenerOptions);
  21538. this.interactionDOMElement.removeEventListener('touchmove', this.onPointerMove, this._eventListenerOptions);
  21539. }
  21540. this.interactionDOMElement = null;
  21541. this.eventsAdded = false;
  21542. };
  21543. /**
  21544. * Updates the state of interactive objects if at least {@link interactionFrequency}
  21545. * milliseconds have passed since the last invocation.
  21546. *
  21547. * Invoked by a throttled ticker update from {@link PIXI.Ticker.system}.
  21548. * @param deltaTime - time delta since the last call
  21549. */
  21550. InteractionManager.prototype.tickerUpdate = function (deltaTime) {
  21551. this._deltaTime += deltaTime;
  21552. if (this._deltaTime < this.interactionFrequency) {
  21553. return;
  21554. }
  21555. this._deltaTime = 0;
  21556. this.update();
  21557. };
  21558. /** Updates the state of interactive objects. */
  21559. InteractionManager.prototype.update = function () {
  21560. if (!this.interactionDOMElement) {
  21561. return;
  21562. }
  21563. // if the user move the mouse this check has already been done using the mouse move!
  21564. if (this._didMove) {
  21565. this._didMove = false;
  21566. return;
  21567. }
  21568. this.cursor = null;
  21569. // Resets the flag as set by a stopPropagation call. This flag is usually reset by a user interaction of any kind,
  21570. // but there was a scenario of a display object moving under a static mouse cursor.
  21571. // In this case, mouseover and mouseevents would not pass the flag test in dispatchEvent function
  21572. for (var k in this.activeInteractionData) {
  21573. // eslint-disable-next-line no-prototype-builtins
  21574. if (this.activeInteractionData.hasOwnProperty(k)) {
  21575. var interactionData = this.activeInteractionData[k];
  21576. if (interactionData.originalEvent && interactionData.pointerType !== 'touch') {
  21577. var interactionEvent = this.configureInteractionEventForDOMEvent(this.eventData, interactionData.originalEvent, interactionData);
  21578. this.processInteractive(interactionEvent, this.lastObjectRendered, this.processPointerOverOut, true);
  21579. }
  21580. }
  21581. }
  21582. this.setCursorMode(this.cursor);
  21583. };
  21584. /**
  21585. * Sets the current cursor mode, handling any callbacks or CSS style changes.
  21586. * @param mode - cursor mode, a key from the cursorStyles dictionary
  21587. */
  21588. InteractionManager.prototype.setCursorMode = function (mode) {
  21589. mode = mode || 'default';
  21590. var applyStyles = true;
  21591. // offscreen canvas does not support setting styles, but cursor modes can be functions,
  21592. // in order to handle pixi rendered cursors, so we can't bail
  21593. if (globalThis.OffscreenCanvas && this.interactionDOMElement instanceof OffscreenCanvas) {
  21594. applyStyles = false;
  21595. }
  21596. // if the mode didn't actually change, bail early
  21597. if (this.currentCursorMode === mode) {
  21598. return;
  21599. }
  21600. this.currentCursorMode = mode;
  21601. var style = this.cursorStyles[mode];
  21602. // only do things if there is a cursor style for it
  21603. if (style) {
  21604. switch (typeof style) {
  21605. case 'string':
  21606. // string styles are handled as cursor CSS
  21607. if (applyStyles) {
  21608. this.interactionDOMElement.style.cursor = style;
  21609. }
  21610. break;
  21611. case 'function':
  21612. // functions are just called, and passed the cursor mode
  21613. style(mode);
  21614. break;
  21615. case 'object':
  21616. // if it is an object, assume that it is a dictionary of CSS styles,
  21617. // apply it to the interactionDOMElement
  21618. if (applyStyles) {
  21619. Object.assign(this.interactionDOMElement.style, style);
  21620. }
  21621. break;
  21622. }
  21623. }
  21624. else if (applyStyles && typeof mode === 'string' && !Object.prototype.hasOwnProperty.call(this.cursorStyles, mode)) {
  21625. // if it mode is a string (not a Symbol) and cursorStyles doesn't have any entry
  21626. // for the mode, then assume that the dev wants it to be CSS for the cursor.
  21627. this.interactionDOMElement.style.cursor = mode;
  21628. }
  21629. };
  21630. /**
  21631. * Dispatches an event on the display object that was interacted with.
  21632. * @param displayObject - the display object in question
  21633. * @param eventString - the name of the event (e.g, mousedown)
  21634. * @param eventData - the event data object
  21635. */
  21636. InteractionManager.prototype.dispatchEvent = function (displayObject, eventString, eventData) {
  21637. // Even if the event was stopped, at least dispatch any remaining events
  21638. // for the same display object.
  21639. if (!eventData.stopPropagationHint || displayObject === eventData.stopsPropagatingAt) {
  21640. eventData.currentTarget = displayObject;
  21641. eventData.type = eventString;
  21642. displayObject.emit(eventString, eventData);
  21643. if (displayObject[eventString]) {
  21644. displayObject[eventString](eventData);
  21645. }
  21646. }
  21647. };
  21648. /**
  21649. * Puts a event on a queue to be dispatched later. This is used to guarantee correct
  21650. * ordering of over/out events.
  21651. * @param displayObject - the display object in question
  21652. * @param eventString - the name of the event (e.g, mousedown)
  21653. * @param eventData - the event data object
  21654. */
  21655. InteractionManager.prototype.delayDispatchEvent = function (displayObject, eventString, eventData) {
  21656. this.delayedEvents.push({ displayObject: displayObject, eventString: eventString, eventData: eventData });
  21657. };
  21658. /**
  21659. * Maps x and y coords from a DOM object and maps them correctly to the PixiJS view. The
  21660. * resulting value is stored in the point. This takes into account the fact that the DOM
  21661. * element could be scaled and positioned anywhere on the screen.
  21662. * @param point - the point that the result will be stored in
  21663. * @param x - the x coord of the position to map
  21664. * @param y - the y coord of the position to map
  21665. */
  21666. InteractionManager.prototype.mapPositionToPoint = function (point, x, y) {
  21667. var rect;
  21668. // IE 11 fix
  21669. if (!this.interactionDOMElement.parentElement) {
  21670. rect = {
  21671. x: 0,
  21672. y: 0,
  21673. width: this.interactionDOMElement.width,
  21674. height: this.interactionDOMElement.height,
  21675. left: 0,
  21676. top: 0
  21677. };
  21678. }
  21679. else {
  21680. rect = this.interactionDOMElement.getBoundingClientRect();
  21681. }
  21682. var resolutionMultiplier = 1.0 / this.resolution;
  21683. point.x = ((x - rect.left) * (this.interactionDOMElement.width / rect.width)) * resolutionMultiplier;
  21684. point.y = ((y - rect.top) * (this.interactionDOMElement.height / rect.height)) * resolutionMultiplier;
  21685. };
  21686. /**
  21687. * This function is provides a neat way of crawling through the scene graph and running a
  21688. * specified function on all interactive objects it finds. It will also take care of hit
  21689. * testing the interactive objects and passes the hit across in the function.
  21690. * @protected
  21691. * @param interactionEvent - event containing the point that
  21692. * is tested for collision
  21693. * @param displayObject - the displayObject
  21694. * that will be hit test (recursively crawls its children)
  21695. * @param func - the function that will be called on each interactive object. The
  21696. * interactionEvent, displayObject and hit will be passed to the function
  21697. * @param hitTest - indicates whether we want to calculate hits
  21698. * or just iterate through all interactive objects
  21699. */
  21700. InteractionManager.prototype.processInteractive = function (interactionEvent, displayObject, func, hitTest) {
  21701. var hit = this.search.findHit(interactionEvent, displayObject, func, hitTest);
  21702. var delayedEvents = this.delayedEvents;
  21703. if (!delayedEvents.length) {
  21704. return hit;
  21705. }
  21706. // Reset the propagation hint, because we start deeper in the tree again.
  21707. interactionEvent.stopPropagationHint = false;
  21708. var delayedLen = delayedEvents.length;
  21709. this.delayedEvents = [];
  21710. for (var i = 0; i < delayedLen; i++) {
  21711. var _a = delayedEvents[i], displayObject_1 = _a.displayObject, eventString = _a.eventString, eventData = _a.eventData;
  21712. // When we reach the object we wanted to stop propagating at,
  21713. // set the propagation hint.
  21714. if (eventData.stopsPropagatingAt === displayObject_1) {
  21715. eventData.stopPropagationHint = true;
  21716. }
  21717. this.dispatchEvent(displayObject_1, eventString, eventData);
  21718. }
  21719. return hit;
  21720. };
  21721. /**
  21722. * Is called when the pointer button is pressed down on the renderer element
  21723. * @param originalEvent - The DOM event of a pointer button being pressed down
  21724. */
  21725. InteractionManager.prototype.onPointerDown = function (originalEvent) {
  21726. // if we support touch events, then only use those for touch events, not pointer events
  21727. if (this.supportsTouchEvents && originalEvent.pointerType === 'touch')
  21728. { return; }
  21729. var events = this.normalizeToPointerData(originalEvent);
  21730. /*
  21731. * No need to prevent default on natural pointer events, as there are no side effects
  21732. * Normalized events, however, may have the double mousedown/touchstart issue on the native android browser,
  21733. * so still need to be prevented.
  21734. */
  21735. // Guaranteed that there will be at least one event in events, and all events must have the same pointer type
  21736. if (this.autoPreventDefault && events[0].isNormalized) {
  21737. var cancelable = originalEvent.cancelable || !('cancelable' in originalEvent);
  21738. if (cancelable) {
  21739. originalEvent.preventDefault();
  21740. }
  21741. }
  21742. var eventLen = events.length;
  21743. for (var i = 0; i < eventLen; i++) {
  21744. var event = events[i];
  21745. var interactionData = this.getInteractionDataForPointerId(event);
  21746. var interactionEvent = this.configureInteractionEventForDOMEvent(this.eventData, event, interactionData);
  21747. interactionEvent.data.originalEvent = originalEvent;
  21748. this.processInteractive(interactionEvent, this.lastObjectRendered, this.processPointerDown, true);
  21749. this.emit('pointerdown', interactionEvent);
  21750. if (event.pointerType === 'touch') {
  21751. this.emit('touchstart', interactionEvent);
  21752. }
  21753. // emit a mouse event for "pen" pointers, the way a browser would emit a fallback event
  21754. else if (event.pointerType === 'mouse' || event.pointerType === 'pen') {
  21755. var isRightButton = event.button === 2;
  21756. this.emit(isRightButton ? 'rightdown' : 'mousedown', this.eventData);
  21757. }
  21758. }
  21759. };
  21760. /**
  21761. * Processes the result of the pointer down check and dispatches the event if need be
  21762. * @param interactionEvent - The interaction event wrapping the DOM event
  21763. * @param displayObject - The display object that was tested
  21764. * @param hit - the result of the hit test on the display object
  21765. */
  21766. InteractionManager.prototype.processPointerDown = function (interactionEvent, displayObject, hit) {
  21767. var data = interactionEvent.data;
  21768. var id = interactionEvent.data.identifier;
  21769. if (hit) {
  21770. if (!displayObject.trackedPointers[id]) {
  21771. displayObject.trackedPointers[id] = new InteractionTrackingData(id);
  21772. }
  21773. this.dispatchEvent(displayObject, 'pointerdown', interactionEvent);
  21774. if (data.pointerType === 'touch') {
  21775. this.dispatchEvent(displayObject, 'touchstart', interactionEvent);
  21776. }
  21777. else if (data.pointerType === 'mouse' || data.pointerType === 'pen') {
  21778. var isRightButton = data.button === 2;
  21779. if (isRightButton) {
  21780. displayObject.trackedPointers[id].rightDown = true;
  21781. }
  21782. else {
  21783. displayObject.trackedPointers[id].leftDown = true;
  21784. }
  21785. this.dispatchEvent(displayObject, isRightButton ? 'rightdown' : 'mousedown', interactionEvent);
  21786. }
  21787. }
  21788. };
  21789. /**
  21790. * Is called when the pointer button is released on the renderer element
  21791. * @param originalEvent - The DOM event of a pointer button being released
  21792. * @param cancelled - true if the pointer is cancelled
  21793. * @param func - Function passed to {@link processInteractive}
  21794. */
  21795. InteractionManager.prototype.onPointerComplete = function (originalEvent, cancelled, func) {
  21796. var events = this.normalizeToPointerData(originalEvent);
  21797. var eventLen = events.length;
  21798. // if the event wasn't targeting our canvas, then consider it to be pointerupoutside
  21799. // in all cases (unless it was a pointercancel)
  21800. var target = originalEvent.target;
  21801. // if in shadow DOM use composedPath to access target
  21802. if (originalEvent.composedPath && originalEvent.composedPath().length > 0) {
  21803. target = originalEvent.composedPath()[0];
  21804. }
  21805. var eventAppend = target !== this.interactionDOMElement ? 'outside' : '';
  21806. for (var i = 0; i < eventLen; i++) {
  21807. var event = events[i];
  21808. var interactionData = this.getInteractionDataForPointerId(event);
  21809. var interactionEvent = this.configureInteractionEventForDOMEvent(this.eventData, event, interactionData);
  21810. interactionEvent.data.originalEvent = originalEvent;
  21811. // perform hit testing for events targeting our canvas or cancel events
  21812. this.processInteractive(interactionEvent, this.lastObjectRendered, func, cancelled || !eventAppend);
  21813. this.emit(cancelled ? 'pointercancel' : "pointerup" + eventAppend, interactionEvent);
  21814. if (event.pointerType === 'mouse' || event.pointerType === 'pen') {
  21815. var isRightButton = event.button === 2;
  21816. this.emit(isRightButton ? "rightup" + eventAppend : "mouseup" + eventAppend, interactionEvent);
  21817. }
  21818. else if (event.pointerType === 'touch') {
  21819. this.emit(cancelled ? 'touchcancel' : "touchend" + eventAppend, interactionEvent);
  21820. this.releaseInteractionDataForPointerId(event.pointerId);
  21821. }
  21822. }
  21823. };
  21824. /**
  21825. * Is called when the pointer button is cancelled
  21826. * @param event - The DOM event of a pointer button being released
  21827. */
  21828. InteractionManager.prototype.onPointerCancel = function (event) {
  21829. // if we support touch events, then only use those for touch events, not pointer events
  21830. if (this.supportsTouchEvents && event.pointerType === 'touch')
  21831. { return; }
  21832. this.onPointerComplete(event, true, this.processPointerCancel);
  21833. };
  21834. /**
  21835. * Processes the result of the pointer cancel check and dispatches the event if need be
  21836. * @param interactionEvent - The interaction event wrapping the DOM event
  21837. * @param displayObject - The display object that was tested
  21838. */
  21839. InteractionManager.prototype.processPointerCancel = function (interactionEvent, displayObject) {
  21840. var data = interactionEvent.data;
  21841. var id = interactionEvent.data.identifier;
  21842. if (displayObject.trackedPointers[id] !== undefined) {
  21843. delete displayObject.trackedPointers[id];
  21844. this.dispatchEvent(displayObject, 'pointercancel', interactionEvent);
  21845. if (data.pointerType === 'touch') {
  21846. this.dispatchEvent(displayObject, 'touchcancel', interactionEvent);
  21847. }
  21848. }
  21849. };
  21850. /**
  21851. * Is called when the pointer button is released on the renderer element
  21852. * @param event - The DOM event of a pointer button being released
  21853. */
  21854. InteractionManager.prototype.onPointerUp = function (event) {
  21855. // if we support touch events, then only use those for touch events, not pointer events
  21856. if (this.supportsTouchEvents && event.pointerType === 'touch')
  21857. { return; }
  21858. this.onPointerComplete(event, false, this.processPointerUp);
  21859. };
  21860. /**
  21861. * Processes the result of the pointer up check and dispatches the event if need be
  21862. * @param interactionEvent - The interaction event wrapping the DOM event
  21863. * @param displayObject - The display object that was tested
  21864. * @param hit - the result of the hit test on the display object
  21865. */
  21866. InteractionManager.prototype.processPointerUp = function (interactionEvent, displayObject, hit) {
  21867. var data = interactionEvent.data;
  21868. var id = interactionEvent.data.identifier;
  21869. var trackingData = displayObject.trackedPointers[id];
  21870. var isTouch = data.pointerType === 'touch';
  21871. var isMouse = (data.pointerType === 'mouse' || data.pointerType === 'pen');
  21872. // need to track mouse down status in the mouse block so that we can emit
  21873. // event in a later block
  21874. var isMouseTap = false;
  21875. // Mouse only
  21876. if (isMouse) {
  21877. var isRightButton = data.button === 2;
  21878. var flags = InteractionTrackingData.FLAGS;
  21879. var test = isRightButton ? flags.RIGHT_DOWN : flags.LEFT_DOWN;
  21880. var isDown = trackingData !== undefined && (trackingData.flags & test);
  21881. if (hit) {
  21882. this.dispatchEvent(displayObject, isRightButton ? 'rightup' : 'mouseup', interactionEvent);
  21883. if (isDown) {
  21884. this.dispatchEvent(displayObject, isRightButton ? 'rightclick' : 'click', interactionEvent);
  21885. // because we can confirm that the mousedown happened on this object, flag for later emit of pointertap
  21886. isMouseTap = true;
  21887. }
  21888. }
  21889. else if (isDown) {
  21890. this.dispatchEvent(displayObject, isRightButton ? 'rightupoutside' : 'mouseupoutside', interactionEvent);
  21891. }
  21892. // update the down state of the tracking data
  21893. if (trackingData) {
  21894. if (isRightButton) {
  21895. trackingData.rightDown = false;
  21896. }
  21897. else {
  21898. trackingData.leftDown = false;
  21899. }
  21900. }
  21901. }
  21902. // Pointers and Touches, and Mouse
  21903. if (hit) {
  21904. this.dispatchEvent(displayObject, 'pointerup', interactionEvent);
  21905. if (isTouch)
  21906. { this.dispatchEvent(displayObject, 'touchend', interactionEvent); }
  21907. if (trackingData) {
  21908. // emit pointertap if not a mouse, or if the mouse block decided it was a tap
  21909. if (!isMouse || isMouseTap) {
  21910. this.dispatchEvent(displayObject, 'pointertap', interactionEvent);
  21911. }
  21912. if (isTouch) {
  21913. this.dispatchEvent(displayObject, 'tap', interactionEvent);
  21914. // touches are no longer over (if they ever were) when we get the touchend
  21915. // so we should ensure that we don't keep pretending that they are
  21916. trackingData.over = false;
  21917. }
  21918. }
  21919. }
  21920. else if (trackingData) {
  21921. this.dispatchEvent(displayObject, 'pointerupoutside', interactionEvent);
  21922. if (isTouch)
  21923. { this.dispatchEvent(displayObject, 'touchendoutside', interactionEvent); }
  21924. }
  21925. // Only remove the tracking data if there is no over/down state still associated with it
  21926. if (trackingData && trackingData.none) {
  21927. delete displayObject.trackedPointers[id];
  21928. }
  21929. };
  21930. /**
  21931. * Is called when the pointer moves across the renderer element
  21932. * @param originalEvent - The DOM event of a pointer moving
  21933. */
  21934. InteractionManager.prototype.onPointerMove = function (originalEvent) {
  21935. // if we support touch events, then only use those for touch events, not pointer events
  21936. if (this.supportsTouchEvents && originalEvent.pointerType === 'touch')
  21937. { return; }
  21938. var events = this.normalizeToPointerData(originalEvent);
  21939. if (events[0].pointerType === 'mouse' || events[0].pointerType === 'pen') {
  21940. this._didMove = true;
  21941. this.cursor = null;
  21942. }
  21943. var eventLen = events.length;
  21944. for (var i = 0; i < eventLen; i++) {
  21945. var event = events[i];
  21946. var interactionData = this.getInteractionDataForPointerId(event);
  21947. var interactionEvent = this.configureInteractionEventForDOMEvent(this.eventData, event, interactionData);
  21948. interactionEvent.data.originalEvent = originalEvent;
  21949. this.processInteractive(interactionEvent, this.lastObjectRendered, this.processPointerMove, true);
  21950. this.emit('pointermove', interactionEvent);
  21951. if (event.pointerType === 'touch')
  21952. { this.emit('touchmove', interactionEvent); }
  21953. if (event.pointerType === 'mouse' || event.pointerType === 'pen')
  21954. { this.emit('mousemove', interactionEvent); }
  21955. }
  21956. if (events[0].pointerType === 'mouse') {
  21957. this.setCursorMode(this.cursor);
  21958. // TODO BUG for parents interactive object (border order issue)
  21959. }
  21960. };
  21961. /**
  21962. * Processes the result of the pointer move check and dispatches the event if need be
  21963. * @param interactionEvent - The interaction event wrapping the DOM event
  21964. * @param displayObject - The display object that was tested
  21965. * @param hit - the result of the hit test on the display object
  21966. */
  21967. InteractionManager.prototype.processPointerMove = function (interactionEvent, displayObject, hit) {
  21968. var data = interactionEvent.data;
  21969. var isTouch = data.pointerType === 'touch';
  21970. var isMouse = (data.pointerType === 'mouse' || data.pointerType === 'pen');
  21971. if (isMouse) {
  21972. this.processPointerOverOut(interactionEvent, displayObject, hit);
  21973. }
  21974. if (!this.moveWhenInside || hit) {
  21975. this.dispatchEvent(displayObject, 'pointermove', interactionEvent);
  21976. if (isTouch)
  21977. { this.dispatchEvent(displayObject, 'touchmove', interactionEvent); }
  21978. if (isMouse)
  21979. { this.dispatchEvent(displayObject, 'mousemove', interactionEvent); }
  21980. }
  21981. };
  21982. /**
  21983. * Is called when the pointer is moved out of the renderer element
  21984. * @private
  21985. * @param {PointerEvent} originalEvent - The DOM event of a pointer being moved out
  21986. */
  21987. InteractionManager.prototype.onPointerOut = function (originalEvent) {
  21988. // if we support touch events, then only use those for touch events, not pointer events
  21989. if (this.supportsTouchEvents && originalEvent.pointerType === 'touch')
  21990. { return; }
  21991. var events = this.normalizeToPointerData(originalEvent);
  21992. // Only mouse and pointer can call onPointerOut, so events will always be length 1
  21993. var event = events[0];
  21994. if (event.pointerType === 'mouse') {
  21995. this.mouseOverRenderer = false;
  21996. this.setCursorMode(null);
  21997. }
  21998. var interactionData = this.getInteractionDataForPointerId(event);
  21999. var interactionEvent = this.configureInteractionEventForDOMEvent(this.eventData, event, interactionData);
  22000. interactionEvent.data.originalEvent = event;
  22001. this.processInteractive(interactionEvent, this.lastObjectRendered, this.processPointerOverOut, false);
  22002. this.emit('pointerout', interactionEvent);
  22003. if (event.pointerType === 'mouse' || event.pointerType === 'pen') {
  22004. this.emit('mouseout', interactionEvent);
  22005. }
  22006. else {
  22007. // we can get touchleave events after touchend, so we want to make sure we don't
  22008. // introduce memory leaks
  22009. this.releaseInteractionDataForPointerId(interactionData.identifier);
  22010. }
  22011. };
  22012. /**
  22013. * Processes the result of the pointer over/out check and dispatches the event if need be.
  22014. * @param interactionEvent - The interaction event wrapping the DOM event
  22015. * @param displayObject - The display object that was tested
  22016. * @param hit - the result of the hit test on the display object
  22017. */
  22018. InteractionManager.prototype.processPointerOverOut = function (interactionEvent, displayObject, hit) {
  22019. var data = interactionEvent.data;
  22020. var id = interactionEvent.data.identifier;
  22021. var isMouse = (data.pointerType === 'mouse' || data.pointerType === 'pen');
  22022. var trackingData = displayObject.trackedPointers[id];
  22023. // if we just moused over the display object, then we need to track that state
  22024. if (hit && !trackingData) {
  22025. trackingData = displayObject.trackedPointers[id] = new InteractionTrackingData(id);
  22026. }
  22027. if (trackingData === undefined)
  22028. { return; }
  22029. if (hit && this.mouseOverRenderer) {
  22030. if (!trackingData.over) {
  22031. trackingData.over = true;
  22032. this.delayDispatchEvent(displayObject, 'pointerover', interactionEvent);
  22033. if (isMouse) {
  22034. this.delayDispatchEvent(displayObject, 'mouseover', interactionEvent);
  22035. }
  22036. }
  22037. // only change the cursor if it has not already been changed (by something deeper in the
  22038. // display tree)
  22039. if (isMouse && this.cursor === null) {
  22040. this.cursor = displayObject.cursor;
  22041. }
  22042. }
  22043. else if (trackingData.over) {
  22044. trackingData.over = false;
  22045. this.dispatchEvent(displayObject, 'pointerout', this.eventData);
  22046. if (isMouse) {
  22047. this.dispatchEvent(displayObject, 'mouseout', interactionEvent);
  22048. }
  22049. // if there is no mouse down information for the pointer, then it is safe to delete
  22050. if (trackingData.none) {
  22051. delete displayObject.trackedPointers[id];
  22052. }
  22053. }
  22054. };
  22055. /**
  22056. * Is called when the pointer is moved into the renderer element.
  22057. * @param originalEvent - The DOM event of a pointer button being moved into the renderer view.
  22058. */
  22059. InteractionManager.prototype.onPointerOver = function (originalEvent) {
  22060. if (this.supportsTouchEvents && originalEvent.pointerType === 'touch')
  22061. { return; }
  22062. var events = this.normalizeToPointerData(originalEvent);
  22063. // Only mouse and pointer can call onPointerOver, so events will always be length 1
  22064. var event = events[0];
  22065. var interactionData = this.getInteractionDataForPointerId(event);
  22066. var interactionEvent = this.configureInteractionEventForDOMEvent(this.eventData, event, interactionData);
  22067. interactionEvent.data.originalEvent = event;
  22068. if (event.pointerType === 'mouse') {
  22069. this.mouseOverRenderer = true;
  22070. }
  22071. this.emit('pointerover', interactionEvent);
  22072. if (event.pointerType === 'mouse' || event.pointerType === 'pen') {
  22073. this.emit('mouseover', interactionEvent);
  22074. }
  22075. };
  22076. /**
  22077. * Get InteractionData for a given pointerId. Store that data as well.
  22078. * @param event - Normalized pointer event, output from normalizeToPointerData.
  22079. * @returns - Interaction data for the given pointer identifier.
  22080. */
  22081. InteractionManager.prototype.getInteractionDataForPointerId = function (event) {
  22082. var pointerId = event.pointerId;
  22083. var interactionData;
  22084. if (pointerId === MOUSE_POINTER_ID || event.pointerType === 'mouse') {
  22085. interactionData = this.mouse;
  22086. }
  22087. else if (this.activeInteractionData[pointerId]) {
  22088. interactionData = this.activeInteractionData[pointerId];
  22089. }
  22090. else {
  22091. interactionData = this.interactionDataPool.pop() || new InteractionData();
  22092. interactionData.identifier = pointerId;
  22093. this.activeInteractionData[pointerId] = interactionData;
  22094. }
  22095. // copy properties from the event, so that we can make sure that touch/pointer specific
  22096. // data is available
  22097. interactionData.copyEvent(event);
  22098. return interactionData;
  22099. };
  22100. /**
  22101. * Return unused InteractionData to the pool, for a given pointerId
  22102. * @param pointerId - Identifier from a pointer event
  22103. */
  22104. InteractionManager.prototype.releaseInteractionDataForPointerId = function (pointerId) {
  22105. var interactionData = this.activeInteractionData[pointerId];
  22106. if (interactionData) {
  22107. delete this.activeInteractionData[pointerId];
  22108. interactionData.reset();
  22109. this.interactionDataPool.push(interactionData);
  22110. }
  22111. };
  22112. /**
  22113. * Configure an InteractionEvent to wrap a DOM PointerEvent and InteractionData
  22114. * @param interactionEvent - The event to be configured
  22115. * @param pointerEvent - The DOM event that will be paired with the InteractionEvent
  22116. * @param interactionData - The InteractionData that will be paired
  22117. * with the InteractionEvent
  22118. * @returns - the interaction event that was passed in
  22119. */
  22120. InteractionManager.prototype.configureInteractionEventForDOMEvent = function (interactionEvent, pointerEvent, interactionData) {
  22121. interactionEvent.data = interactionData;
  22122. this.mapPositionToPoint(interactionData.global, pointerEvent.clientX, pointerEvent.clientY);
  22123. // Not really sure why this is happening, but it's how a previous version handled things
  22124. if (pointerEvent.pointerType === 'touch') {
  22125. pointerEvent.globalX = interactionData.global.x;
  22126. pointerEvent.globalY = interactionData.global.y;
  22127. }
  22128. interactionData.originalEvent = pointerEvent;
  22129. interactionEvent.reset();
  22130. return interactionEvent;
  22131. };
  22132. /**
  22133. * Ensures that the original event object contains all data that a regular pointer event would have
  22134. * @param {TouchEvent|MouseEvent|PointerEvent} event - The original event data from a touch or mouse event
  22135. * @returns - An array containing a single normalized pointer event, in the case of a pointer
  22136. * or mouse event, or a multiple normalized pointer events if there are multiple changed touches
  22137. */
  22138. InteractionManager.prototype.normalizeToPointerData = function (event) {
  22139. var normalizedEvents = [];
  22140. if (this.supportsTouchEvents && event instanceof TouchEvent) {
  22141. for (var i = 0, li = event.changedTouches.length; i < li; i++) {
  22142. var touch = event.changedTouches[i];
  22143. if (typeof touch.button === 'undefined')
  22144. { touch.button = event.touches.length ? 1 : 0; }
  22145. if (typeof touch.buttons === 'undefined')
  22146. { touch.buttons = event.touches.length ? 1 : 0; }
  22147. if (typeof touch.isPrimary === 'undefined') {
  22148. touch.isPrimary = event.touches.length === 1 && event.type === 'touchstart';
  22149. }
  22150. if (typeof touch.width === 'undefined')
  22151. { touch.width = touch.radiusX || 1; }
  22152. if (typeof touch.height === 'undefined')
  22153. { touch.height = touch.radiusY || 1; }
  22154. if (typeof touch.tiltX === 'undefined')
  22155. { touch.tiltX = 0; }
  22156. if (typeof touch.tiltY === 'undefined')
  22157. { touch.tiltY = 0; }
  22158. if (typeof touch.pointerType === 'undefined')
  22159. { touch.pointerType = 'touch'; }
  22160. if (typeof touch.pointerId === 'undefined')
  22161. { touch.pointerId = touch.identifier || 0; }
  22162. if (typeof touch.pressure === 'undefined')
  22163. { touch.pressure = touch.force || 0.5; }
  22164. if (typeof touch.twist === 'undefined')
  22165. { touch.twist = 0; }
  22166. if (typeof touch.tangentialPressure === 'undefined')
  22167. { touch.tangentialPressure = 0; }
  22168. // TODO: Remove these, as layerX/Y is not a standard, is deprecated, has uneven
  22169. // support, and the fill ins are not quite the same
  22170. // offsetX/Y might be okay, but is not the same as clientX/Y when the canvas's top
  22171. // left is not 0,0 on the page
  22172. if (typeof touch.layerX === 'undefined')
  22173. { touch.layerX = touch.offsetX = touch.clientX; }
  22174. if (typeof touch.layerY === 'undefined')
  22175. { touch.layerY = touch.offsetY = touch.clientY; }
  22176. // mark the touch as normalized, just so that we know we did it
  22177. touch.isNormalized = true;
  22178. normalizedEvents.push(touch);
  22179. }
  22180. }
  22181. // apparently PointerEvent subclasses MouseEvent, so yay
  22182. else if (!globalThis.MouseEvent
  22183. || (event instanceof MouseEvent && (!this.supportsPointerEvents || !(event instanceof globalThis.PointerEvent)))) {
  22184. var tempEvent = event;
  22185. if (typeof tempEvent.isPrimary === 'undefined')
  22186. { tempEvent.isPrimary = true; }
  22187. if (typeof tempEvent.width === 'undefined')
  22188. { tempEvent.width = 1; }
  22189. if (typeof tempEvent.height === 'undefined')
  22190. { tempEvent.height = 1; }
  22191. if (typeof tempEvent.tiltX === 'undefined')
  22192. { tempEvent.tiltX = 0; }
  22193. if (typeof tempEvent.tiltY === 'undefined')
  22194. { tempEvent.tiltY = 0; }
  22195. if (typeof tempEvent.pointerType === 'undefined')
  22196. { tempEvent.pointerType = 'mouse'; }
  22197. if (typeof tempEvent.pointerId === 'undefined')
  22198. { tempEvent.pointerId = MOUSE_POINTER_ID; }
  22199. if (typeof tempEvent.pressure === 'undefined')
  22200. { tempEvent.pressure = 0.5; }
  22201. if (typeof tempEvent.twist === 'undefined')
  22202. { tempEvent.twist = 0; }
  22203. if (typeof tempEvent.tangentialPressure === 'undefined')
  22204. { tempEvent.tangentialPressure = 0; }
  22205. // mark the mouse event as normalized, just so that we know we did it
  22206. tempEvent.isNormalized = true;
  22207. normalizedEvents.push(tempEvent);
  22208. }
  22209. else {
  22210. normalizedEvents.push(event);
  22211. }
  22212. return normalizedEvents;
  22213. };
  22214. /** Destroys the interaction manager. */
  22215. InteractionManager.prototype.destroy = function () {
  22216. this.removeEvents();
  22217. this.removeTickerListener();
  22218. this.removeAllListeners();
  22219. this.renderer = null;
  22220. this.mouse = null;
  22221. this.eventData = null;
  22222. this.interactionDOMElement = null;
  22223. this.onPointerDown = null;
  22224. this.processPointerDown = null;
  22225. this.onPointerUp = null;
  22226. this.processPointerUp = null;
  22227. this.onPointerCancel = null;
  22228. this.processPointerCancel = null;
  22229. this.onPointerMove = null;
  22230. this.processPointerMove = null;
  22231. this.onPointerOut = null;
  22232. this.processPointerOverOut = null;
  22233. this.onPointerOver = null;
  22234. this.search = null;
  22235. };
  22236. /** @ignore */
  22237. InteractionManager.extension = {
  22238. name: 'interaction',
  22239. type: [
  22240. ExtensionType.RendererPlugin,
  22241. ExtensionType.CanvasRendererPlugin ],
  22242. };
  22243. return InteractionManager;
  22244. }(eventemitter3));
  22245. /*!
  22246. * @pixi/extract - v6.5.10
  22247. * Compiled Thu, 06 Jul 2023 15:25:11 UTC
  22248. *
  22249. * @pixi/extract is licensed under the MIT License.
  22250. * http://www.opensource.org/licenses/mit-license
  22251. */
  22252. var TEMP_RECT = new Rectangle();
  22253. var BYTES_PER_PIXEL = 4;
  22254. /**
  22255. * This class provides renderer-specific plugins for exporting content from a renderer.
  22256. * For instance, these plugins can be used for saving an Image, Canvas element or for exporting the raw image data (pixels).
  22257. *
  22258. * Do not instantiate these plugins directly. It is available from the `renderer.plugins` property.
  22259. * See {@link PIXI.CanvasRenderer#plugins} or {@link PIXI.Renderer#plugins}.
  22260. * @example
  22261. * // Create a new app (will auto-add extract plugin to renderer)
  22262. * const app = new PIXI.Application();
  22263. *
  22264. * // Draw a red circle
  22265. * const graphics = new PIXI.Graphics()
  22266. * .beginFill(0xFF0000)
  22267. * .drawCircle(0, 0, 50);
  22268. *
  22269. * // Render the graphics as an HTMLImageElement
  22270. * const image = app.renderer.plugins.extract.image(graphics);
  22271. * document.body.appendChild(image);
  22272. * @memberof PIXI
  22273. */
  22274. var Extract = /** @class */ (function () {
  22275. /**
  22276. * @param renderer - A reference to the current renderer
  22277. */
  22278. function Extract(renderer) {
  22279. this.renderer = renderer;
  22280. }
  22281. /**
  22282. * Will return a HTML Image of the target
  22283. * @param target - A displayObject or renderTexture
  22284. * to convert. If left empty will use the main renderer
  22285. * @param format - Image format, e.g. "image/jpeg" or "image/webp".
  22286. * @param quality - JPEG or Webp compression from 0 to 1. Default is 0.92.
  22287. * @returns - HTML Image of the target
  22288. */
  22289. Extract.prototype.image = function (target, format, quality) {
  22290. var image = new Image();
  22291. image.src = this.base64(target, format, quality);
  22292. return image;
  22293. };
  22294. /**
  22295. * Will return a base64 encoded string of this target. It works by calling
  22296. * `Extract.getCanvas` and then running toDataURL on that.
  22297. * @param target - A displayObject or renderTexture
  22298. * to convert. If left empty will use the main renderer
  22299. * @param format - Image format, e.g. "image/jpeg" or "image/webp".
  22300. * @param quality - JPEG or Webp compression from 0 to 1. Default is 0.92.
  22301. * @returns - A base64 encoded string of the texture.
  22302. */
  22303. Extract.prototype.base64 = function (target, format, quality) {
  22304. return this.canvas(target).toDataURL(format, quality);
  22305. };
  22306. /**
  22307. * Creates a Canvas element, renders this target to it and then returns it.
  22308. * @param target - A displayObject or renderTexture
  22309. * to convert. If left empty will use the main renderer
  22310. * @param frame - The frame the extraction is restricted to.
  22311. * @returns - A Canvas element with the texture rendered on.
  22312. */
  22313. Extract.prototype.canvas = function (target, frame) {
  22314. var _a = this._rawPixels(target, frame), pixels = _a.pixels, width = _a.width, height = _a.height, flipY = _a.flipY;
  22315. var canvasBuffer = new CanvasRenderTarget(width, height, 1);
  22316. // Add the pixels to the canvas
  22317. var canvasData = canvasBuffer.context.getImageData(0, 0, width, height);
  22318. Extract.arrayPostDivide(pixels, canvasData.data);
  22319. canvasBuffer.context.putImageData(canvasData, 0, 0);
  22320. // Flipping pixels
  22321. if (flipY) {
  22322. var target_1 = new CanvasRenderTarget(canvasBuffer.width, canvasBuffer.height, 1);
  22323. target_1.context.scale(1, -1);
  22324. // We can't render to itself because we should be empty before render.
  22325. target_1.context.drawImage(canvasBuffer.canvas, 0, -height);
  22326. canvasBuffer.destroy();
  22327. canvasBuffer = target_1;
  22328. }
  22329. // Send the canvas back
  22330. return canvasBuffer.canvas;
  22331. };
  22332. /**
  22333. * Will return a one-dimensional array containing the pixel data of the entire texture in RGBA
  22334. * order, with integer values between 0 and 255 (included).
  22335. * @param target - A displayObject or renderTexture
  22336. * to convert. If left empty will use the main renderer
  22337. * @param frame - The frame the extraction is restricted to.
  22338. * @returns - One-dimensional array containing the pixel data of the entire texture
  22339. */
  22340. Extract.prototype.pixels = function (target, frame) {
  22341. var pixels = this._rawPixels(target, frame).pixels;
  22342. Extract.arrayPostDivide(pixels, pixels);
  22343. return pixels;
  22344. };
  22345. Extract.prototype._rawPixels = function (target, frame) {
  22346. var renderer = this.renderer;
  22347. var resolution;
  22348. var flipY = false;
  22349. var renderTexture;
  22350. var generated = false;
  22351. if (target) {
  22352. if (target instanceof RenderTexture) {
  22353. renderTexture = target;
  22354. }
  22355. else {
  22356. var multisample = renderer.context.webGLVersion >= 2 ? renderer.multisample : MSAA_QUALITY.NONE;
  22357. renderTexture = this.renderer.generateTexture(target, { multisample: multisample });
  22358. if (multisample !== MSAA_QUALITY.NONE) {
  22359. // Resolve the multisampled texture to a non-multisampled texture
  22360. var resolvedTexture = RenderTexture.create({
  22361. width: renderTexture.width,
  22362. height: renderTexture.height,
  22363. });
  22364. renderer.framebuffer.bind(renderTexture.framebuffer);
  22365. renderer.framebuffer.blit(resolvedTexture.framebuffer);
  22366. renderer.framebuffer.bind(null);
  22367. renderTexture.destroy(true);
  22368. renderTexture = resolvedTexture;
  22369. }
  22370. generated = true;
  22371. }
  22372. }
  22373. if (renderTexture) {
  22374. resolution = renderTexture.baseTexture.resolution;
  22375. frame = frame !== null && frame !== void 0 ? frame : renderTexture.frame;
  22376. flipY = false;
  22377. renderer.renderTexture.bind(renderTexture);
  22378. }
  22379. else {
  22380. resolution = renderer.resolution;
  22381. if (!frame) {
  22382. frame = TEMP_RECT;
  22383. frame.width = renderer.width;
  22384. frame.height = renderer.height;
  22385. }
  22386. flipY = true;
  22387. renderer.renderTexture.bind(null);
  22388. }
  22389. var width = Math.round(frame.width * resolution);
  22390. var height = Math.round(frame.height * resolution);
  22391. var pixels = new Uint8Array(BYTES_PER_PIXEL * width * height);
  22392. // Read pixels to the array
  22393. var gl = renderer.gl;
  22394. gl.readPixels(Math.round(frame.x * resolution), Math.round(frame.y * resolution), width, height, gl.RGBA, gl.UNSIGNED_BYTE, pixels);
  22395. if (generated) {
  22396. renderTexture.destroy(true);
  22397. }
  22398. return { pixels: pixels, width: width, height: height, flipY: flipY };
  22399. };
  22400. /** Destroys the extract. */
  22401. Extract.prototype.destroy = function () {
  22402. this.renderer = null;
  22403. };
  22404. /**
  22405. * Takes premultiplied pixel data and produces regular pixel data
  22406. * @private
  22407. * @param pixels - array of pixel data
  22408. * @param out - output array
  22409. */
  22410. Extract.arrayPostDivide = function (pixels, out) {
  22411. for (var i = 0; i < pixels.length; i += 4) {
  22412. var alpha = out[i + 3] = pixels[i + 3];
  22413. if (alpha !== 0) {
  22414. out[i] = Math.round(Math.min(pixels[i] * 255.0 / alpha, 255.0));
  22415. out[i + 1] = Math.round(Math.min(pixels[i + 1] * 255.0 / alpha, 255.0));
  22416. out[i + 2] = Math.round(Math.min(pixels[i + 2] * 255.0 / alpha, 255.0));
  22417. }
  22418. else {
  22419. out[i] = pixels[i];
  22420. out[i + 1] = pixels[i + 1];
  22421. out[i + 2] = pixels[i + 2];
  22422. }
  22423. }
  22424. };
  22425. /** @ignore */
  22426. Extract.extension = {
  22427. name: 'extract',
  22428. type: ExtensionType.RendererPlugin,
  22429. };
  22430. return Extract;
  22431. }());
  22432. /*!
  22433. * @pixi/loaders - v6.5.10
  22434. * Compiled Thu, 06 Jul 2023 15:25:11 UTC
  22435. *
  22436. * @pixi/loaders is licensed under the MIT License.
  22437. * http://www.opensource.org/licenses/mit-license
  22438. */
  22439. /* jshint -W097 */
  22440. /**
  22441. * @memberof PIXI
  22442. */
  22443. var SignalBinding = /** @class */ (function () {
  22444. /**
  22445. * SignalBinding constructor.
  22446. * @constructs SignalBinding
  22447. * @param {Function} fn - Event handler to be called.
  22448. * @param {boolean} [once=false] - Should this listener be removed after dispatch
  22449. * @param {object} [thisArg] - The context of the callback function.
  22450. * @api private
  22451. */
  22452. // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
  22453. function SignalBinding(fn, once, thisArg) {
  22454. if (once === void 0) { once = false; }
  22455. this._fn = fn;
  22456. this._once = once;
  22457. this._thisArg = thisArg;
  22458. this._next = this._prev = this._owner = null;
  22459. }
  22460. SignalBinding.prototype.detach = function () {
  22461. if (this._owner === null)
  22462. { return false; }
  22463. this._owner.detach(this);
  22464. return true;
  22465. };
  22466. return SignalBinding;
  22467. }());
  22468. /**
  22469. * @param self
  22470. * @param node
  22471. * @private
  22472. */
  22473. function _addSignalBinding(self, node) {
  22474. if (!self._head) {
  22475. self._head = node;
  22476. self._tail = node;
  22477. }
  22478. else {
  22479. self._tail._next = node;
  22480. node._prev = self._tail;
  22481. self._tail = node;
  22482. }
  22483. node._owner = self;
  22484. return node;
  22485. }
  22486. /**
  22487. * @memberof PIXI
  22488. */
  22489. var Signal = /** @class */ (function () {
  22490. /**
  22491. * MiniSignal constructor.
  22492. * @example
  22493. * let mySignal = new Signal();
  22494. * let binding = mySignal.add(onSignal);
  22495. * mySignal.dispatch('foo', 'bar');
  22496. * mySignal.detach(binding);
  22497. */
  22498. function Signal() {
  22499. this._head = this._tail = undefined;
  22500. }
  22501. /**
  22502. * Return an array of attached SignalBinding.
  22503. * @param {boolean} [exists=false] - We only need to know if there are handlers.
  22504. * @returns {PIXI.SignalBinding[] | boolean} Array of attached SignalBinding or Boolean if called with exists = true
  22505. * @api public
  22506. */
  22507. Signal.prototype.handlers = function (exists) {
  22508. if (exists === void 0) { exists = false; }
  22509. var node = this._head;
  22510. if (exists)
  22511. { return !!node; }
  22512. var ee = [];
  22513. while (node) {
  22514. ee.push(node);
  22515. node = node._next;
  22516. }
  22517. return ee;
  22518. };
  22519. /**
  22520. * Return true if node is a SignalBinding attached to this MiniSignal
  22521. * @param {PIXI.SignalBinding} node - Node to check.
  22522. * @returns {boolean} True if node is attache to mini-signal
  22523. */
  22524. Signal.prototype.has = function (node) {
  22525. if (!(node instanceof SignalBinding)) {
  22526. throw new Error('MiniSignal#has(): First arg must be a SignalBinding object.');
  22527. }
  22528. return node._owner === this;
  22529. };
  22530. /**
  22531. * Dispaches a signal to all registered listeners.
  22532. * @param {...any} args
  22533. * @returns {boolean} Indication if we've emitted an event.
  22534. */
  22535. Signal.prototype.dispatch = function () {
  22536. var arguments$1 = arguments;
  22537. var args = [];
  22538. for (var _i = 0; _i < arguments.length; _i++) {
  22539. args[_i] = arguments$1[_i];
  22540. }
  22541. var node = this._head;
  22542. if (!node)
  22543. { return false; }
  22544. while (node) {
  22545. if (node._once)
  22546. { this.detach(node); }
  22547. node._fn.apply(node._thisArg, args);
  22548. node = node._next;
  22549. }
  22550. return true;
  22551. };
  22552. /**
  22553. * Register a new listener.
  22554. * @param {Function} fn - Callback function.
  22555. * @param {object} [thisArg] - The context of the callback function.
  22556. * @returns {PIXI.SignalBinding} The SignalBinding node that was added.
  22557. */
  22558. Signal.prototype.add = function (fn, thisArg) {
  22559. if (thisArg === void 0) { thisArg = null; }
  22560. if (typeof fn !== 'function') {
  22561. throw new Error('MiniSignal#add(): First arg must be a Function.');
  22562. }
  22563. return _addSignalBinding(this, new SignalBinding(fn, false, thisArg));
  22564. };
  22565. /**
  22566. * Register a new listener that will be executed only once.
  22567. * @param {Function} fn - Callback function.
  22568. * @param {object} [thisArg] - The context of the callback function.
  22569. * @returns {PIXI.SignalBinding} The SignalBinding node that was added.
  22570. */
  22571. Signal.prototype.once = function (fn, thisArg) {
  22572. if (thisArg === void 0) { thisArg = null; }
  22573. if (typeof fn !== 'function') {
  22574. throw new Error('MiniSignal#once(): First arg must be a Function.');
  22575. }
  22576. return _addSignalBinding(this, new SignalBinding(fn, true, thisArg));
  22577. };
  22578. /**
  22579. * Remove binding object.
  22580. * @param {PIXI.SignalBinding} node - The binding node that will be removed.
  22581. * @returns {Signal} The instance on which this method was called.
  22582. @api public */
  22583. Signal.prototype.detach = function (node) {
  22584. if (!(node instanceof SignalBinding)) {
  22585. throw new Error('MiniSignal#detach(): First arg must be a SignalBinding object.');
  22586. }
  22587. if (node._owner !== this)
  22588. { return this; } // todo: or error?
  22589. if (node._prev)
  22590. { node._prev._next = node._next; }
  22591. if (node._next)
  22592. { node._next._prev = node._prev; }
  22593. if (node === this._head) { // first node
  22594. this._head = node._next;
  22595. if (node._next === null) {
  22596. this._tail = null;
  22597. }
  22598. }
  22599. else if (node === this._tail) { // last node
  22600. this._tail = node._prev;
  22601. this._tail._next = null;
  22602. }
  22603. node._owner = null;
  22604. return this;
  22605. };
  22606. /**
  22607. * Detach all listeners.
  22608. * @returns {Signal} The instance on which this method was called.
  22609. */
  22610. Signal.prototype.detachAll = function () {
  22611. var node = this._head;
  22612. if (!node)
  22613. { return this; }
  22614. this._head = this._tail = null;
  22615. while (node) {
  22616. node._owner = null;
  22617. node = node._next;
  22618. }
  22619. return this;
  22620. };
  22621. return Signal;
  22622. }());
  22623. /**
  22624. * function from npm package `parseUri`, converted to TS to avoid leftpad incident
  22625. * @param {string} str
  22626. * @param [opts] - options
  22627. * @param {boolean} [opts.strictMode] - type of parser
  22628. */
  22629. function parseUri(str, opts) {
  22630. opts = opts || {};
  22631. var o = {
  22632. // eslint-disable-next-line max-len
  22633. key: ['source', 'protocol', 'authority', 'userInfo', 'user', 'password', 'host', 'port', 'relative', 'path', 'directory', 'file', 'query', 'anchor'],
  22634. q: {
  22635. name: 'queryKey',
  22636. parser: /(?:^|&)([^&=]*)=?([^&]*)/g
  22637. },
  22638. parser: {
  22639. // eslint-disable-next-line max-len
  22640. strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,
  22641. // eslint-disable-next-line max-len
  22642. loose: /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/
  22643. }
  22644. };
  22645. var m = o.parser[opts.strictMode ? 'strict' : 'loose'].exec(str);
  22646. var uri = {};
  22647. var i = 14;
  22648. while (i--)
  22649. { uri[o.key[i]] = m[i] || ''; }
  22650. uri[o.q.name] = {};
  22651. uri[o.key[12]].replace(o.q.parser, function (_t0, t1, t2) {
  22652. if (t1)
  22653. { uri[o.q.name][t1] = t2; }
  22654. });
  22655. return uri;
  22656. }
  22657. // tests if CORS is supported in XHR, if not we need to use XDR
  22658. var useXdr;
  22659. var tempAnchor = null;
  22660. // some status constants
  22661. var STATUS_NONE = 0;
  22662. var STATUS_OK = 200;
  22663. var STATUS_EMPTY = 204;
  22664. var STATUS_IE_BUG_EMPTY = 1223;
  22665. var STATUS_TYPE_OK = 2;
  22666. // noop
  22667. function _noop$1() { }
  22668. /**
  22669. * Quick helper to set a value on one of the extension maps. Ensures there is no
  22670. * dot at the start of the extension.
  22671. * @ignore
  22672. * @param map - The map to set on.
  22673. * @param extname - The extension (or key) to set.
  22674. * @param val - The value to set.
  22675. */
  22676. function setExtMap(map, extname, val) {
  22677. if (extname && extname.indexOf('.') === 0) {
  22678. extname = extname.substring(1);
  22679. }
  22680. if (!extname) {
  22681. return;
  22682. }
  22683. map[extname] = val;
  22684. }
  22685. /**
  22686. * Quick helper to get string xhr type.
  22687. * @ignore
  22688. * @param xhr - The request to check.
  22689. * @returns The type.
  22690. */
  22691. function reqType(xhr) {
  22692. return xhr.toString().replace('object ', '');
  22693. }
  22694. /**
  22695. * Manages the state and loading of a resource and all child resources.
  22696. *
  22697. * Can be extended in `GlobalMixins.LoaderResource`.
  22698. * @memberof PIXI
  22699. */
  22700. var LoaderResource = /** @class */ (function () {
  22701. /**
  22702. * @param {string} name - The name of the resource to load.
  22703. * @param {string|string[]} url - The url for this resource, for audio/video loads you can pass
  22704. * an array of sources.
  22705. * @param {object} [options] - The options for the load.
  22706. * @param {string|boolean} [options.crossOrigin] - Is this request cross-origin? Default is to
  22707. * determine automatically.
  22708. * @param {number} [options.timeout=0] - A timeout in milliseconds for the load. If the load takes
  22709. * longer than this time it is cancelled and the load is considered a failure. If this value is
  22710. * set to `0` then there is no explicit timeout.
  22711. * @param {PIXI.LoaderResource.LOAD_TYPE} [options.loadType=LOAD_TYPE.XHR] - How should this resource
  22712. * be loaded?
  22713. * @param {PIXI.LoaderResource.XHR_RESPONSE_TYPE} [options.xhrType=XHR_RESPONSE_TYPE.DEFAULT] - How
  22714. * should the data being loaded be interpreted when using XHR?
  22715. * @param {PIXI.LoaderResource.IMetadata} [options.metadata] - Extra configuration for middleware
  22716. * and the Resource object.
  22717. */
  22718. function LoaderResource(name, url, options) {
  22719. /**
  22720. * The `dequeue` method that will be used a storage place for the async queue dequeue method
  22721. * used privately by the loader.
  22722. * @private
  22723. * @member {Function}
  22724. */
  22725. this._dequeue = _noop$1;
  22726. /**
  22727. * Used a storage place for the on load binding used privately by the loader.
  22728. * @private
  22729. * @member {Function}
  22730. */
  22731. this._onLoadBinding = null;
  22732. /**
  22733. * The timer for element loads to check if they timeout.
  22734. * @private
  22735. */
  22736. this._elementTimer = 0;
  22737. /**
  22738. * The `complete` function bound to this resource's context.
  22739. * @private
  22740. * @type {Function}
  22741. */
  22742. this._boundComplete = null;
  22743. /**
  22744. * The `_onError` function bound to this resource's context.
  22745. * @private
  22746. * @type {Function}
  22747. */
  22748. this._boundOnError = null;
  22749. /**
  22750. * The `_onProgress` function bound to this resource's context.
  22751. * @private
  22752. * @type {Function}
  22753. */
  22754. this._boundOnProgress = null;
  22755. /**
  22756. * The `_onTimeout` function bound to this resource's context.
  22757. * @private
  22758. * @type {Function}
  22759. */
  22760. this._boundOnTimeout = null;
  22761. this._boundXhrOnError = null;
  22762. this._boundXhrOnTimeout = null;
  22763. this._boundXhrOnAbort = null;
  22764. this._boundXhrOnLoad = null;
  22765. if (typeof name !== 'string' || typeof url !== 'string') {
  22766. throw new Error('Both name and url are required for constructing a resource.');
  22767. }
  22768. options = options || {};
  22769. this._flags = 0;
  22770. // set data url flag, needs to be set early for some _determineX checks to work.
  22771. this._setFlag(LoaderResource.STATUS_FLAGS.DATA_URL, url.indexOf('data:') === 0);
  22772. this.name = name;
  22773. this.url = url;
  22774. this.extension = this._getExtension();
  22775. this.data = null;
  22776. this.crossOrigin = options.crossOrigin === true ? 'anonymous' : options.crossOrigin;
  22777. this.timeout = options.timeout || 0;
  22778. this.loadType = options.loadType || this._determineLoadType();
  22779. // The type used to load the resource via XHR. If unset, determined automatically.
  22780. this.xhrType = options.xhrType;
  22781. // Extra info for middleware, and controlling specifics about how the resource loads.
  22782. // Note that if you pass in a `loadElement`, the Resource class takes ownership of it.
  22783. // Meaning it will modify it as it sees fit.
  22784. this.metadata = options.metadata || {};
  22785. // The error that occurred while loading (if any).
  22786. this.error = null;
  22787. // The XHR object that was used to load this resource. This is only set
  22788. // when `loadType` is `LoaderResource.LOAD_TYPE.XHR`.
  22789. this.xhr = null;
  22790. // The child resources this resource owns.
  22791. this.children = [];
  22792. // The resource type.
  22793. this.type = LoaderResource.TYPE.UNKNOWN;
  22794. // The progress chunk owned by this resource.
  22795. this.progressChunk = 0;
  22796. // The `dequeue` method that will be used a storage place for the async queue dequeue method
  22797. // used privately by the loader.
  22798. this._dequeue = _noop$1;
  22799. // Used a storage place for the on load binding used privately by the loader.
  22800. this._onLoadBinding = null;
  22801. // The timer for element loads to check if they timeout.
  22802. this._elementTimer = 0;
  22803. this._boundComplete = this.complete.bind(this);
  22804. this._boundOnError = this._onError.bind(this);
  22805. this._boundOnProgress = this._onProgress.bind(this);
  22806. this._boundOnTimeout = this._onTimeout.bind(this);
  22807. // xhr callbacks
  22808. this._boundXhrOnError = this._xhrOnError.bind(this);
  22809. this._boundXhrOnTimeout = this._xhrOnTimeout.bind(this);
  22810. this._boundXhrOnAbort = this._xhrOnAbort.bind(this);
  22811. this._boundXhrOnLoad = this._xhrOnLoad.bind(this);
  22812. // Dispatched when the resource beings to load.
  22813. this.onStart = new Signal();
  22814. // Dispatched each time progress of this resource load updates.
  22815. // Not all resources types and loader systems can support this event
  22816. // so sometimes it may not be available. If the resource
  22817. // is being loaded on a modern browser, using XHR, and the remote server
  22818. // properly sets Content-Length headers, then this will be available.
  22819. this.onProgress = new Signal();
  22820. // Dispatched once this resource has loaded, if there was an error it will
  22821. // be in the `error` property.
  22822. this.onComplete = new Signal();
  22823. // Dispatched after this resource has had all the *after* middleware run on it.
  22824. this.onAfterMiddleware = new Signal();
  22825. }
  22826. /**
  22827. * Sets the load type to be used for a specific extension.
  22828. * @static
  22829. * @param {string} extname - The extension to set the type for, e.g. "png" or "fnt"
  22830. * @param {PIXI.LoaderResource.LOAD_TYPE} loadType - The load type to set it to.
  22831. */
  22832. LoaderResource.setExtensionLoadType = function (extname, loadType) {
  22833. setExtMap(LoaderResource._loadTypeMap, extname, loadType);
  22834. };
  22835. /**
  22836. * Sets the load type to be used for a specific extension.
  22837. * @static
  22838. * @param {string} extname - The extension to set the type for, e.g. "png" or "fnt"
  22839. * @param {PIXI.LoaderResource.XHR_RESPONSE_TYPE} xhrType - The xhr type to set it to.
  22840. */
  22841. LoaderResource.setExtensionXhrType = function (extname, xhrType) {
  22842. setExtMap(LoaderResource._xhrTypeMap, extname, xhrType);
  22843. };
  22844. Object.defineProperty(LoaderResource.prototype, "isDataUrl", {
  22845. /**
  22846. * When the resource starts to load.
  22847. * @memberof PIXI.LoaderResource
  22848. * @callback OnStartSignal
  22849. * @param {PIXI.Resource} resource - The resource that the event happened on.
  22850. */
  22851. /**
  22852. * When the resource reports loading progress.
  22853. * @memberof PIXI.LoaderResource
  22854. * @callback OnProgressSignal
  22855. * @param {PIXI.Resource} resource - The resource that the event happened on.
  22856. * @param {number} percentage - The progress of the load in the range [0, 1].
  22857. */
  22858. /**
  22859. * When the resource finishes loading.
  22860. * @memberof PIXI.LoaderResource
  22861. * @callback OnCompleteSignal
  22862. * @param {PIXI.Resource} resource - The resource that the event happened on.
  22863. */
  22864. /**
  22865. * @memberof PIXI.LoaderResource
  22866. * @typedef {object} IMetadata
  22867. * @property {HTMLImageElement|HTMLAudioElement|HTMLVideoElement} [loadElement=null] - The
  22868. * element to use for loading, instead of creating one.
  22869. * @property {boolean} [skipSource=false] - Skips adding source(s) to the load element. This
  22870. * is useful if you want to pass in a `loadElement` that you already added load sources to.
  22871. * @property {string|string[]} [mimeType] - The mime type to use for the source element
  22872. * of a video/audio elment. If the urls are an array, you can pass this as an array as well
  22873. * where each index is the mime type to use for the corresponding url index.
  22874. */
  22875. /**
  22876. * Stores whether or not this url is a data url.
  22877. * @readonly
  22878. * @member {boolean}
  22879. */
  22880. get: function () {
  22881. return this._hasFlag(LoaderResource.STATUS_FLAGS.DATA_URL);
  22882. },
  22883. enumerable: false,
  22884. configurable: true
  22885. });
  22886. Object.defineProperty(LoaderResource.prototype, "isComplete", {
  22887. /**
  22888. * Describes if this resource has finished loading. Is true when the resource has completely
  22889. * loaded.
  22890. * @readonly
  22891. * @member {boolean}
  22892. */
  22893. get: function () {
  22894. return this._hasFlag(LoaderResource.STATUS_FLAGS.COMPLETE);
  22895. },
  22896. enumerable: false,
  22897. configurable: true
  22898. });
  22899. Object.defineProperty(LoaderResource.prototype, "isLoading", {
  22900. /**
  22901. * Describes if this resource is currently loading. Is true when the resource starts loading,
  22902. * and is false again when complete.
  22903. * @readonly
  22904. * @member {boolean}
  22905. */
  22906. get: function () {
  22907. return this._hasFlag(LoaderResource.STATUS_FLAGS.LOADING);
  22908. },
  22909. enumerable: false,
  22910. configurable: true
  22911. });
  22912. /** Marks the resource as complete. */
  22913. LoaderResource.prototype.complete = function () {
  22914. this._clearEvents();
  22915. this._finish();
  22916. };
  22917. /**
  22918. * Aborts the loading of this resource, with an optional message.
  22919. * @param {string} message - The message to use for the error
  22920. */
  22921. LoaderResource.prototype.abort = function (message) {
  22922. // abort can be called multiple times, ignore subsequent calls.
  22923. if (this.error) {
  22924. return;
  22925. }
  22926. // store error
  22927. this.error = new Error(message);
  22928. // clear events before calling aborts
  22929. this._clearEvents();
  22930. // abort the actual loading
  22931. if (this.xhr) {
  22932. this.xhr.abort();
  22933. }
  22934. else if (this.xdr) {
  22935. this.xdr.abort();
  22936. }
  22937. else if (this.data) {
  22938. // single source
  22939. if (this.data.src) {
  22940. this.data.src = LoaderResource.EMPTY_GIF;
  22941. }
  22942. // multi-source
  22943. else {
  22944. while (this.data.firstChild) {
  22945. this.data.removeChild(this.data.firstChild);
  22946. }
  22947. }
  22948. }
  22949. // done now.
  22950. this._finish();
  22951. };
  22952. /**
  22953. * Kicks off loading of this resource. This method is asynchronous.
  22954. * @param {PIXI.LoaderResource.OnCompleteSignal} [cb] - Optional callback to call once the resource is loaded.
  22955. */
  22956. LoaderResource.prototype.load = function (cb) {
  22957. var _this = this;
  22958. if (this.isLoading) {
  22959. return;
  22960. }
  22961. if (this.isComplete) {
  22962. if (cb) {
  22963. setTimeout(function () { return cb(_this); }, 1);
  22964. }
  22965. return;
  22966. }
  22967. else if (cb) {
  22968. this.onComplete.once(cb);
  22969. }
  22970. this._setFlag(LoaderResource.STATUS_FLAGS.LOADING, true);
  22971. this.onStart.dispatch(this);
  22972. // if unset, determine the value
  22973. if (this.crossOrigin === false || typeof this.crossOrigin !== 'string') {
  22974. this.crossOrigin = this._determineCrossOrigin(this.url);
  22975. }
  22976. switch (this.loadType) {
  22977. case LoaderResource.LOAD_TYPE.IMAGE:
  22978. this.type = LoaderResource.TYPE.IMAGE;
  22979. this._loadElement('image');
  22980. break;
  22981. case LoaderResource.LOAD_TYPE.AUDIO:
  22982. this.type = LoaderResource.TYPE.AUDIO;
  22983. this._loadSourceElement('audio');
  22984. break;
  22985. case LoaderResource.LOAD_TYPE.VIDEO:
  22986. this.type = LoaderResource.TYPE.VIDEO;
  22987. this._loadSourceElement('video');
  22988. break;
  22989. case LoaderResource.LOAD_TYPE.XHR:
  22990. /* falls through */
  22991. default:
  22992. if (typeof useXdr === 'undefined') {
  22993. useXdr = !!(globalThis.XDomainRequest && !('withCredentials' in (new XMLHttpRequest())));
  22994. }
  22995. if (useXdr && this.crossOrigin) {
  22996. this._loadXdr();
  22997. }
  22998. else {
  22999. this._loadXhr();
  23000. }
  23001. break;
  23002. }
  23003. };
  23004. /**
  23005. * Checks if the flag is set.
  23006. * @param flag - The flag to check.
  23007. * @returns True if the flag is set.
  23008. */
  23009. LoaderResource.prototype._hasFlag = function (flag) {
  23010. return (this._flags & flag) !== 0;
  23011. };
  23012. /**
  23013. * (Un)Sets the flag.
  23014. * @param flag - The flag to (un)set.
  23015. * @param value - Whether to set or (un)set the flag.
  23016. */
  23017. LoaderResource.prototype._setFlag = function (flag, value) {
  23018. this._flags = value ? (this._flags | flag) : (this._flags & ~flag);
  23019. };
  23020. /** Clears all the events from the underlying loading source. */
  23021. LoaderResource.prototype._clearEvents = function () {
  23022. clearTimeout(this._elementTimer);
  23023. if (this.data && this.data.removeEventListener) {
  23024. this.data.removeEventListener('error', this._boundOnError, false);
  23025. this.data.removeEventListener('load', this._boundComplete, false);
  23026. this.data.removeEventListener('progress', this._boundOnProgress, false);
  23027. this.data.removeEventListener('canplaythrough', this._boundComplete, false);
  23028. }
  23029. if (this.xhr) {
  23030. if (this.xhr.removeEventListener) {
  23031. this.xhr.removeEventListener('error', this._boundXhrOnError, false);
  23032. this.xhr.removeEventListener('timeout', this._boundXhrOnTimeout, false);
  23033. this.xhr.removeEventListener('abort', this._boundXhrOnAbort, false);
  23034. this.xhr.removeEventListener('progress', this._boundOnProgress, false);
  23035. this.xhr.removeEventListener('load', this._boundXhrOnLoad, false);
  23036. }
  23037. else {
  23038. this.xhr.onerror = null;
  23039. this.xhr.ontimeout = null;
  23040. this.xhr.onprogress = null;
  23041. this.xhr.onload = null;
  23042. }
  23043. }
  23044. };
  23045. /** Finalizes the load. */
  23046. LoaderResource.prototype._finish = function () {
  23047. if (this.isComplete) {
  23048. throw new Error('Complete called again for an already completed resource.');
  23049. }
  23050. this._setFlag(LoaderResource.STATUS_FLAGS.COMPLETE, true);
  23051. this._setFlag(LoaderResource.STATUS_FLAGS.LOADING, false);
  23052. this.onComplete.dispatch(this);
  23053. };
  23054. /**
  23055. * Loads this resources using an element that has a single source,
  23056. * like an HTMLImageElement.
  23057. * @private
  23058. * @param type - The type of element to use.
  23059. */
  23060. LoaderResource.prototype._loadElement = function (type) {
  23061. if (this.metadata.loadElement) {
  23062. this.data = this.metadata.loadElement;
  23063. }
  23064. else if (type === 'image' && typeof globalThis.Image !== 'undefined') {
  23065. this.data = new Image();
  23066. }
  23067. else {
  23068. this.data = document.createElement(type);
  23069. }
  23070. if (this.crossOrigin) {
  23071. this.data.crossOrigin = this.crossOrigin;
  23072. }
  23073. if (!this.metadata.skipSource) {
  23074. this.data.src = this.url;
  23075. }
  23076. this.data.addEventListener('error', this._boundOnError, false);
  23077. this.data.addEventListener('load', this._boundComplete, false);
  23078. this.data.addEventListener('progress', this._boundOnProgress, false);
  23079. if (this.timeout) {
  23080. this._elementTimer = setTimeout(this._boundOnTimeout, this.timeout);
  23081. }
  23082. };
  23083. /**
  23084. * Loads this resources using an element that has multiple sources,
  23085. * like an HTMLAudioElement or HTMLVideoElement.
  23086. * @param type - The type of element to use.
  23087. */
  23088. LoaderResource.prototype._loadSourceElement = function (type) {
  23089. if (this.metadata.loadElement) {
  23090. this.data = this.metadata.loadElement;
  23091. }
  23092. else if (type === 'audio' && typeof globalThis.Audio !== 'undefined') {
  23093. this.data = new Audio();
  23094. }
  23095. else {
  23096. this.data = document.createElement(type);
  23097. }
  23098. if (this.data === null) {
  23099. this.abort("Unsupported element: " + type);
  23100. return;
  23101. }
  23102. if (this.crossOrigin) {
  23103. this.data.crossOrigin = this.crossOrigin;
  23104. }
  23105. if (!this.metadata.skipSource) {
  23106. // support for CocoonJS Canvas+ runtime, lacks document.createElement('source')
  23107. if (navigator.isCocoonJS) {
  23108. this.data.src = Array.isArray(this.url) ? this.url[0] : this.url;
  23109. }
  23110. else if (Array.isArray(this.url)) {
  23111. var mimeTypes = this.metadata.mimeType;
  23112. for (var i = 0; i < this.url.length; ++i) {
  23113. this.data.appendChild(this._createSource(type, this.url[i], Array.isArray(mimeTypes) ? mimeTypes[i] : mimeTypes));
  23114. }
  23115. }
  23116. else {
  23117. var mimeTypes = this.metadata.mimeType;
  23118. this.data.appendChild(this._createSource(type, this.url, Array.isArray(mimeTypes) ? mimeTypes[0] : mimeTypes));
  23119. }
  23120. }
  23121. this.data.addEventListener('error', this._boundOnError, false);
  23122. this.data.addEventListener('load', this._boundComplete, false);
  23123. this.data.addEventListener('progress', this._boundOnProgress, false);
  23124. this.data.addEventListener('canplaythrough', this._boundComplete, false);
  23125. this.data.load();
  23126. if (this.timeout) {
  23127. this._elementTimer = setTimeout(this._boundOnTimeout, this.timeout);
  23128. }
  23129. };
  23130. /** Loads this resources using an XMLHttpRequest. */
  23131. LoaderResource.prototype._loadXhr = function () {
  23132. // if unset, determine the value
  23133. if (typeof this.xhrType !== 'string') {
  23134. this.xhrType = this._determineXhrType();
  23135. }
  23136. var xhr = this.xhr = new XMLHttpRequest();
  23137. // send credentials when crossOrigin with credentials requested
  23138. if (this.crossOrigin === 'use-credentials') {
  23139. xhr.withCredentials = true;
  23140. }
  23141. // set the request type and url
  23142. xhr.open('GET', this.url, true);
  23143. xhr.timeout = this.timeout;
  23144. // load json as text and parse it ourselves. We do this because some browsers
  23145. // *cough* safari *cough* can't deal with it.
  23146. if (this.xhrType === LoaderResource.XHR_RESPONSE_TYPE.JSON
  23147. || this.xhrType === LoaderResource.XHR_RESPONSE_TYPE.DOCUMENT) {
  23148. xhr.responseType = LoaderResource.XHR_RESPONSE_TYPE.TEXT;
  23149. }
  23150. else {
  23151. xhr.responseType = this.xhrType;
  23152. }
  23153. xhr.addEventListener('error', this._boundXhrOnError, false);
  23154. xhr.addEventListener('timeout', this._boundXhrOnTimeout, false);
  23155. xhr.addEventListener('abort', this._boundXhrOnAbort, false);
  23156. xhr.addEventListener('progress', this._boundOnProgress, false);
  23157. xhr.addEventListener('load', this._boundXhrOnLoad, false);
  23158. xhr.send();
  23159. };
  23160. /** Loads this resources using an XDomainRequest. This is here because we need to support IE9 (gross). */
  23161. LoaderResource.prototype._loadXdr = function () {
  23162. // if unset, determine the value
  23163. if (typeof this.xhrType !== 'string') {
  23164. this.xhrType = this._determineXhrType();
  23165. }
  23166. var xdr = this.xhr = new globalThis.XDomainRequest(); // eslint-disable-line no-undef
  23167. // XDomainRequest has a few quirks. Occasionally it will abort requests
  23168. // A way to avoid this is to make sure ALL callbacks are set even if not used
  23169. // More info here: http://stackoverflow.com/questions/15786966/xdomainrequest-aborts-post-on-ie-9
  23170. xdr.timeout = this.timeout || 5000; // XDR needs a timeout value or it breaks in IE9
  23171. xdr.onerror = this._boundXhrOnError;
  23172. xdr.ontimeout = this._boundXhrOnTimeout;
  23173. xdr.onprogress = this._boundOnProgress;
  23174. xdr.onload = this._boundXhrOnLoad;
  23175. xdr.open('GET', this.url, true);
  23176. // Note: The xdr.send() call is wrapped in a timeout to prevent an
  23177. // issue with the interface where some requests are lost if multiple
  23178. // XDomainRequests are being sent at the same time.
  23179. // Some info here: https://github.com/photonstorm/phaser/issues/1248
  23180. setTimeout(function () { return xdr.send(); }, 1);
  23181. };
  23182. /**
  23183. * Creates a source used in loading via an element.
  23184. * @param type - The element type (video or audio).
  23185. * @param url - The source URL to load from.
  23186. * @param [mime] - The mime type of the video
  23187. * @returns The source element.
  23188. */
  23189. LoaderResource.prototype._createSource = function (type, url, mime) {
  23190. if (!mime) {
  23191. mime = type + "/" + this._getExtension(url);
  23192. }
  23193. var source = document.createElement('source');
  23194. source.src = url;
  23195. source.type = mime;
  23196. return source;
  23197. };
  23198. /**
  23199. * Called if a load errors out.
  23200. * @param event - The error event from the element that emits it.
  23201. */
  23202. LoaderResource.prototype._onError = function (event) {
  23203. this.abort("Failed to load element using: " + event.target.nodeName);
  23204. };
  23205. /**
  23206. * Called if a load progress event fires for an element or xhr/xdr.
  23207. * @param event - Progress event.
  23208. */
  23209. LoaderResource.prototype._onProgress = function (event) {
  23210. if (event && event.lengthComputable) {
  23211. this.onProgress.dispatch(this, event.loaded / event.total);
  23212. }
  23213. };
  23214. /** Called if a timeout event fires for an element. */
  23215. LoaderResource.prototype._onTimeout = function () {
  23216. this.abort("Load timed out.");
  23217. };
  23218. /** Called if an error event fires for xhr/xdr. */
  23219. LoaderResource.prototype._xhrOnError = function () {
  23220. var xhr = this.xhr;
  23221. this.abort(reqType(xhr) + " Request failed. Status: " + xhr.status + ", text: \"" + xhr.statusText + "\"");
  23222. };
  23223. /** Called if an error event fires for xhr/xdr. */
  23224. LoaderResource.prototype._xhrOnTimeout = function () {
  23225. var xhr = this.xhr;
  23226. this.abort(reqType(xhr) + " Request timed out.");
  23227. };
  23228. /** Called if an abort event fires for xhr/xdr. */
  23229. LoaderResource.prototype._xhrOnAbort = function () {
  23230. var xhr = this.xhr;
  23231. this.abort(reqType(xhr) + " Request was aborted by the user.");
  23232. };
  23233. /** Called when data successfully loads from an xhr/xdr request. */
  23234. LoaderResource.prototype._xhrOnLoad = function () {
  23235. var xhr = this.xhr;
  23236. var text = '';
  23237. var status = typeof xhr.status === 'undefined' ? STATUS_OK : xhr.status; // XDR has no `.status`, assume 200.
  23238. // responseText is accessible only if responseType is '' or 'text' and on older browsers
  23239. if (xhr.responseType === '' || xhr.responseType === 'text' || typeof xhr.responseType === 'undefined') {
  23240. text = xhr.responseText;
  23241. }
  23242. // status can be 0 when using the `file://` protocol so we also check if a response is set.
  23243. // If it has a response, we assume 200; otherwise a 0 status code with no contents is an aborted request.
  23244. if (status === STATUS_NONE && (text.length > 0 || xhr.responseType === LoaderResource.XHR_RESPONSE_TYPE.BUFFER)) {
  23245. status = STATUS_OK;
  23246. }
  23247. // handle IE9 bug: http://stackoverflow.com/questions/10046972/msie-returns-status-code-of-1223-for-ajax-request
  23248. else if (status === STATUS_IE_BUG_EMPTY) {
  23249. status = STATUS_EMPTY;
  23250. }
  23251. var statusType = (status / 100) | 0;
  23252. if (statusType === STATUS_TYPE_OK) {
  23253. // if text, just return it
  23254. if (this.xhrType === LoaderResource.XHR_RESPONSE_TYPE.TEXT) {
  23255. this.data = text;
  23256. this.type = LoaderResource.TYPE.TEXT;
  23257. }
  23258. // if json, parse into json object
  23259. else if (this.xhrType === LoaderResource.XHR_RESPONSE_TYPE.JSON) {
  23260. try {
  23261. this.data = JSON.parse(text);
  23262. this.type = LoaderResource.TYPE.JSON;
  23263. }
  23264. catch (e) {
  23265. this.abort("Error trying to parse loaded json: " + e);
  23266. return;
  23267. }
  23268. }
  23269. // if xml, parse into an xml document or div element
  23270. else if (this.xhrType === LoaderResource.XHR_RESPONSE_TYPE.DOCUMENT) {
  23271. try {
  23272. if (globalThis.DOMParser) {
  23273. var domparser = new DOMParser();
  23274. this.data = domparser.parseFromString(text, 'text/xml');
  23275. }
  23276. else {
  23277. var div = document.createElement('div');
  23278. div.innerHTML = text;
  23279. this.data = div;
  23280. }
  23281. this.type = LoaderResource.TYPE.XML;
  23282. }
  23283. catch (e$1) {
  23284. this.abort("Error trying to parse loaded xml: " + e$1);
  23285. return;
  23286. }
  23287. }
  23288. // other types just return the response
  23289. else {
  23290. this.data = xhr.response || text;
  23291. }
  23292. }
  23293. else {
  23294. this.abort("[" + xhr.status + "] " + xhr.statusText + ": " + xhr.responseURL);
  23295. return;
  23296. }
  23297. this.complete();
  23298. };
  23299. /**
  23300. * Sets the `crossOrigin` property for this resource based on if the url
  23301. * for this resource is cross-origin. If crossOrigin was manually set, this
  23302. * function does nothing.
  23303. * @private
  23304. * @param url - The url to test.
  23305. * @param [loc=globalThis.location] - The location object to test against.
  23306. * @returns The crossOrigin value to use (or empty string for none).
  23307. */
  23308. // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
  23309. LoaderResource.prototype._determineCrossOrigin = function (url, loc) {
  23310. // data: and javascript: urls are considered same-origin
  23311. if (url.indexOf('data:') === 0) {
  23312. return '';
  23313. }
  23314. // A sandboxed iframe without the 'allow-same-origin' attribute will have a special
  23315. // origin designed not to match globalThis.location.origin, and will always require
  23316. // crossOrigin requests regardless of whether the location matches.
  23317. if (globalThis.origin !== globalThis.location.origin) {
  23318. return 'anonymous';
  23319. }
  23320. // default is globalThis.location
  23321. loc = loc || globalThis.location;
  23322. if (!tempAnchor) {
  23323. tempAnchor = document.createElement('a');
  23324. }
  23325. // let the browser determine the full href for the url of this resource and then
  23326. // parse with the node url lib, we can't use the properties of the anchor element
  23327. // because they don't work in IE9 :(
  23328. tempAnchor.href = url;
  23329. var parsedUrl = parseUri(tempAnchor.href, { strictMode: true });
  23330. var samePort = (!parsedUrl.port && loc.port === '') || (parsedUrl.port === loc.port);
  23331. var protocol = parsedUrl.protocol ? parsedUrl.protocol + ":" : '';
  23332. // if cross origin
  23333. if (parsedUrl.host !== loc.hostname || !samePort || protocol !== loc.protocol) {
  23334. return 'anonymous';
  23335. }
  23336. return '';
  23337. };
  23338. /**
  23339. * Determines the responseType of an XHR request based on the extension of the
  23340. * resource being loaded.
  23341. * @private
  23342. * @returns {PIXI.LoaderResource.XHR_RESPONSE_TYPE} The responseType to use.
  23343. */
  23344. LoaderResource.prototype._determineXhrType = function () {
  23345. return LoaderResource._xhrTypeMap[this.extension] || LoaderResource.XHR_RESPONSE_TYPE.TEXT;
  23346. };
  23347. /**
  23348. * Determines the loadType of a resource based on the extension of the
  23349. * resource being loaded.
  23350. * @private
  23351. * @returns {PIXI.LoaderResource.LOAD_TYPE} The loadType to use.
  23352. */
  23353. LoaderResource.prototype._determineLoadType = function () {
  23354. return LoaderResource._loadTypeMap[this.extension] || LoaderResource.LOAD_TYPE.XHR;
  23355. };
  23356. /**
  23357. * Extracts the extension (sans '.') of the file being loaded by the resource.
  23358. * @param [url] - url to parse, `this.url` by default.
  23359. * @returns The extension.
  23360. */
  23361. LoaderResource.prototype._getExtension = function (url) {
  23362. if (url === void 0) { url = this.url; }
  23363. var ext = '';
  23364. if (this.isDataUrl) {
  23365. var slashIndex = url.indexOf('/');
  23366. ext = url.substring(slashIndex + 1, url.indexOf(';', slashIndex));
  23367. }
  23368. else {
  23369. var queryStart = url.indexOf('?');
  23370. var hashStart = url.indexOf('#');
  23371. var index = Math.min(queryStart > -1 ? queryStart : url.length, hashStart > -1 ? hashStart : url.length);
  23372. url = url.substring(0, index);
  23373. ext = url.substring(url.lastIndexOf('.') + 1);
  23374. }
  23375. return ext.toLowerCase();
  23376. };
  23377. /**
  23378. * Determines the mime type of an XHR request based on the responseType of
  23379. * resource being loaded.
  23380. * @param type - The type to get a mime type for.
  23381. * @private
  23382. * @returns The mime type to use.
  23383. */
  23384. LoaderResource.prototype._getMimeFromXhrType = function (type) {
  23385. switch (type) {
  23386. case LoaderResource.XHR_RESPONSE_TYPE.BUFFER:
  23387. return 'application/octet-binary';
  23388. case LoaderResource.XHR_RESPONSE_TYPE.BLOB:
  23389. return 'application/blob';
  23390. case LoaderResource.XHR_RESPONSE_TYPE.DOCUMENT:
  23391. return 'application/xml';
  23392. case LoaderResource.XHR_RESPONSE_TYPE.JSON:
  23393. return 'application/json';
  23394. case LoaderResource.XHR_RESPONSE_TYPE.DEFAULT:
  23395. case LoaderResource.XHR_RESPONSE_TYPE.TEXT:
  23396. /* falls through */
  23397. default:
  23398. return 'text/plain';
  23399. }
  23400. };
  23401. return LoaderResource;
  23402. }());
  23403. // eslint-disable-next-line @typescript-eslint/no-namespace
  23404. (function (LoaderResource) {
  23405. (function (STATUS_FLAGS) {
  23406. /** None */
  23407. STATUS_FLAGS[STATUS_FLAGS["NONE"] = 0] = "NONE";
  23408. /** Data URL */
  23409. STATUS_FLAGS[STATUS_FLAGS["DATA_URL"] = 1] = "DATA_URL";
  23410. /** Complete */
  23411. STATUS_FLAGS[STATUS_FLAGS["COMPLETE"] = 2] = "COMPLETE";
  23412. /** Loading */
  23413. STATUS_FLAGS[STATUS_FLAGS["LOADING"] = 4] = "LOADING";
  23414. })(LoaderResource.STATUS_FLAGS || (LoaderResource.STATUS_FLAGS = {}));
  23415. (function (TYPE) {
  23416. /** Unknown */
  23417. TYPE[TYPE["UNKNOWN"] = 0] = "UNKNOWN";
  23418. /** JSON */
  23419. TYPE[TYPE["JSON"] = 1] = "JSON";
  23420. /** XML */
  23421. TYPE[TYPE["XML"] = 2] = "XML";
  23422. /** Image */
  23423. TYPE[TYPE["IMAGE"] = 3] = "IMAGE";
  23424. /** Audio */
  23425. TYPE[TYPE["AUDIO"] = 4] = "AUDIO";
  23426. /** Video */
  23427. TYPE[TYPE["VIDEO"] = 5] = "VIDEO";
  23428. /** Plain text */
  23429. TYPE[TYPE["TEXT"] = 6] = "TEXT";
  23430. })(LoaderResource.TYPE || (LoaderResource.TYPE = {}));
  23431. (function (LOAD_TYPE) {
  23432. /** Uses XMLHttpRequest to load the resource. */
  23433. LOAD_TYPE[LOAD_TYPE["XHR"] = 1] = "XHR";
  23434. /** Uses an `Image` object to load the resource. */
  23435. LOAD_TYPE[LOAD_TYPE["IMAGE"] = 2] = "IMAGE";
  23436. /** Uses an `Audio` object to load the resource. */
  23437. LOAD_TYPE[LOAD_TYPE["AUDIO"] = 3] = "AUDIO";
  23438. /** Uses a `Video` object to load the resource. */
  23439. LOAD_TYPE[LOAD_TYPE["VIDEO"] = 4] = "VIDEO";
  23440. })(LoaderResource.LOAD_TYPE || (LoaderResource.LOAD_TYPE = {}));
  23441. (function (XHR_RESPONSE_TYPE) {
  23442. /** string */
  23443. XHR_RESPONSE_TYPE["DEFAULT"] = "text";
  23444. /** ArrayBuffer */
  23445. XHR_RESPONSE_TYPE["BUFFER"] = "arraybuffer";
  23446. /** Blob */
  23447. XHR_RESPONSE_TYPE["BLOB"] = "blob";
  23448. /** Document */
  23449. XHR_RESPONSE_TYPE["DOCUMENT"] = "document";
  23450. /** Object */
  23451. XHR_RESPONSE_TYPE["JSON"] = "json";
  23452. /** String */
  23453. XHR_RESPONSE_TYPE["TEXT"] = "text";
  23454. })(LoaderResource.XHR_RESPONSE_TYPE || (LoaderResource.XHR_RESPONSE_TYPE = {}));
  23455. LoaderResource._loadTypeMap = {
  23456. // images
  23457. gif: LoaderResource.LOAD_TYPE.IMAGE,
  23458. png: LoaderResource.LOAD_TYPE.IMAGE,
  23459. bmp: LoaderResource.LOAD_TYPE.IMAGE,
  23460. jpg: LoaderResource.LOAD_TYPE.IMAGE,
  23461. jpeg: LoaderResource.LOAD_TYPE.IMAGE,
  23462. tif: LoaderResource.LOAD_TYPE.IMAGE,
  23463. tiff: LoaderResource.LOAD_TYPE.IMAGE,
  23464. webp: LoaderResource.LOAD_TYPE.IMAGE,
  23465. tga: LoaderResource.LOAD_TYPE.IMAGE,
  23466. avif: LoaderResource.LOAD_TYPE.IMAGE,
  23467. svg: LoaderResource.LOAD_TYPE.IMAGE,
  23468. 'svg+xml': LoaderResource.LOAD_TYPE.IMAGE,
  23469. // audio
  23470. mp3: LoaderResource.LOAD_TYPE.AUDIO,
  23471. ogg: LoaderResource.LOAD_TYPE.AUDIO,
  23472. wav: LoaderResource.LOAD_TYPE.AUDIO,
  23473. // videos
  23474. mp4: LoaderResource.LOAD_TYPE.VIDEO,
  23475. webm: LoaderResource.LOAD_TYPE.VIDEO,
  23476. };
  23477. LoaderResource._xhrTypeMap = {
  23478. // xml
  23479. xhtml: LoaderResource.XHR_RESPONSE_TYPE.DOCUMENT,
  23480. html: LoaderResource.XHR_RESPONSE_TYPE.DOCUMENT,
  23481. htm: LoaderResource.XHR_RESPONSE_TYPE.DOCUMENT,
  23482. xml: LoaderResource.XHR_RESPONSE_TYPE.DOCUMENT,
  23483. tmx: LoaderResource.XHR_RESPONSE_TYPE.DOCUMENT,
  23484. svg: LoaderResource.XHR_RESPONSE_TYPE.DOCUMENT,
  23485. // This was added to handle Tiled Tileset XML, but .tsx is also a TypeScript React Component.
  23486. // Since it is way less likely for people to be loading TypeScript files instead of Tiled files,
  23487. // this should probably be fine.
  23488. tsx: LoaderResource.XHR_RESPONSE_TYPE.DOCUMENT,
  23489. // images
  23490. gif: LoaderResource.XHR_RESPONSE_TYPE.BLOB,
  23491. png: LoaderResource.XHR_RESPONSE_TYPE.BLOB,
  23492. bmp: LoaderResource.XHR_RESPONSE_TYPE.BLOB,
  23493. jpg: LoaderResource.XHR_RESPONSE_TYPE.BLOB,
  23494. jpeg: LoaderResource.XHR_RESPONSE_TYPE.BLOB,
  23495. tif: LoaderResource.XHR_RESPONSE_TYPE.BLOB,
  23496. tiff: LoaderResource.XHR_RESPONSE_TYPE.BLOB,
  23497. webp: LoaderResource.XHR_RESPONSE_TYPE.BLOB,
  23498. tga: LoaderResource.XHR_RESPONSE_TYPE.BLOB,
  23499. avif: LoaderResource.XHR_RESPONSE_TYPE.BLOB,
  23500. // json
  23501. json: LoaderResource.XHR_RESPONSE_TYPE.JSON,
  23502. // text
  23503. text: LoaderResource.XHR_RESPONSE_TYPE.TEXT,
  23504. txt: LoaderResource.XHR_RESPONSE_TYPE.TEXT,
  23505. // fonts
  23506. ttf: LoaderResource.XHR_RESPONSE_TYPE.BUFFER,
  23507. otf: LoaderResource.XHR_RESPONSE_TYPE.BUFFER,
  23508. };
  23509. // We can't set the `src` attribute to empty string, so on abort we set it to this 1px transparent gif
  23510. LoaderResource.EMPTY_GIF = 'data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==';
  23511. })(LoaderResource || (LoaderResource = {}));
  23512. /**
  23513. * Smaller version of the async library constructs.
  23514. * @ignore
  23515. */
  23516. function _noop() {
  23517. }
  23518. /**
  23519. * Ensures a function is only called once.
  23520. * @ignore
  23521. * @param {Function} fn - The function to wrap.
  23522. * @returns {Function} The wrapping function.
  23523. */
  23524. function onlyOnce(fn) {
  23525. return function onceWrapper() {
  23526. var arguments$1 = arguments;
  23527. var args = [];
  23528. for (var _i = 0; _i < arguments.length; _i++) {
  23529. args[_i] = arguments$1[_i];
  23530. }
  23531. if (fn === null) {
  23532. throw new Error('Callback was already called.');
  23533. }
  23534. var callFn = fn;
  23535. fn = null;
  23536. callFn.apply(this, args);
  23537. };
  23538. }
  23539. /**
  23540. * @private
  23541. * @memberof PIXI
  23542. */
  23543. var AsyncQueueItem = /** @class */ (function () {
  23544. /**
  23545. * @param data
  23546. * @param callback
  23547. * @private
  23548. */
  23549. function AsyncQueueItem(data, callback) {
  23550. this.data = data;
  23551. this.callback = callback;
  23552. }
  23553. return AsyncQueueItem;
  23554. }());
  23555. /**
  23556. * @private
  23557. * @memberof PIXI
  23558. */
  23559. var AsyncQueue = /** @class */ (function () {
  23560. /**
  23561. * @param worker
  23562. * @param concurrency
  23563. * @private
  23564. */
  23565. function AsyncQueue(worker, concurrency) {
  23566. var _this = this;
  23567. if (concurrency === void 0) { concurrency = 1; }
  23568. this.workers = 0;
  23569. this.saturated = _noop;
  23570. this.unsaturated = _noop;
  23571. this.empty = _noop;
  23572. this.drain = _noop;
  23573. this.error = _noop;
  23574. this.started = false;
  23575. this.paused = false;
  23576. this._tasks = [];
  23577. this._insert = function (data, insertAtFront, callback) {
  23578. if (callback && typeof callback !== 'function') {
  23579. throw new Error('task callback must be a function');
  23580. }
  23581. _this.started = true;
  23582. // eslint-disable-next-line no-eq-null,eqeqeq
  23583. if (data == null && _this.idle()) {
  23584. // call drain immediately if there are no tasks
  23585. setTimeout(function () { return _this.drain(); }, 1);
  23586. return;
  23587. }
  23588. var item = new AsyncQueueItem(data, typeof callback === 'function' ? callback : _noop);
  23589. if (insertAtFront) {
  23590. _this._tasks.unshift(item);
  23591. }
  23592. else {
  23593. _this._tasks.push(item);
  23594. }
  23595. setTimeout(_this.process, 1);
  23596. };
  23597. this.process = function () {
  23598. while (!_this.paused && _this.workers < _this.concurrency && _this._tasks.length) {
  23599. var task = _this._tasks.shift();
  23600. if (_this._tasks.length === 0) {
  23601. _this.empty();
  23602. }
  23603. _this.workers += 1;
  23604. if (_this.workers === _this.concurrency) {
  23605. _this.saturated();
  23606. }
  23607. _this._worker(task.data, onlyOnce(_this._next(task)));
  23608. }
  23609. };
  23610. this._worker = worker;
  23611. if (concurrency === 0) {
  23612. throw new Error('Concurrency must not be zero');
  23613. }
  23614. this.concurrency = concurrency;
  23615. this.buffer = concurrency / 4.0;
  23616. }
  23617. /**
  23618. * @param task
  23619. * @private
  23620. */
  23621. AsyncQueue.prototype._next = function (task) {
  23622. var _this = this;
  23623. return function () {
  23624. var arguments$1 = arguments;
  23625. var args = [];
  23626. for (var _i = 0; _i < arguments.length; _i++) {
  23627. args[_i] = arguments$1[_i];
  23628. }
  23629. _this.workers -= 1;
  23630. task.callback.apply(task, args);
  23631. // eslint-disable-next-line no-eq-null,eqeqeq
  23632. if (args[0] != null) {
  23633. _this.error(args[0], task.data);
  23634. }
  23635. if (_this.workers <= (_this.concurrency - _this.buffer)) {
  23636. _this.unsaturated();
  23637. }
  23638. if (_this.idle()) {
  23639. _this.drain();
  23640. }
  23641. _this.process();
  23642. };
  23643. };
  23644. // That was in object
  23645. // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
  23646. AsyncQueue.prototype.push = function (data, callback) {
  23647. this._insert(data, false, callback);
  23648. };
  23649. AsyncQueue.prototype.kill = function () {
  23650. this.workers = 0;
  23651. this.drain = _noop;
  23652. this.started = false;
  23653. this._tasks = [];
  23654. };
  23655. // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
  23656. AsyncQueue.prototype.unshift = function (data, callback) {
  23657. this._insert(data, true, callback);
  23658. };
  23659. AsyncQueue.prototype.length = function () {
  23660. return this._tasks.length;
  23661. };
  23662. AsyncQueue.prototype.running = function () {
  23663. return this.workers;
  23664. };
  23665. AsyncQueue.prototype.idle = function () {
  23666. return this._tasks.length + this.workers === 0;
  23667. };
  23668. AsyncQueue.prototype.pause = function () {
  23669. if (this.paused === true) {
  23670. return;
  23671. }
  23672. this.paused = true;
  23673. };
  23674. AsyncQueue.prototype.resume = function () {
  23675. if (this.paused === false) {
  23676. return;
  23677. }
  23678. this.paused = false;
  23679. // Need to call this.process once per concurrent
  23680. // worker to preserve full concurrency after pause
  23681. for (var w = 1; w <= this.concurrency; w++) {
  23682. this.process();
  23683. }
  23684. };
  23685. /**
  23686. * Iterates an array in series.
  23687. * @param {Array.<*>} array - Array to iterate.
  23688. * @param {Function} iterator - Function to call for each element.
  23689. * @param {Function} callback - Function to call when done, or on error.
  23690. * @param {boolean} [deferNext=false] - Break synchronous each loop by calling next with a setTimeout of 1.
  23691. */
  23692. AsyncQueue.eachSeries = function (array, iterator, callback, deferNext) {
  23693. var i = 0;
  23694. var len = array.length;
  23695. function next(err) {
  23696. if (err || i === len) {
  23697. if (callback) {
  23698. callback(err);
  23699. }
  23700. return;
  23701. }
  23702. if (deferNext) {
  23703. setTimeout(function () {
  23704. iterator(array[i++], next);
  23705. }, 1);
  23706. }
  23707. else {
  23708. iterator(array[i++], next);
  23709. }
  23710. }
  23711. next();
  23712. };
  23713. /**
  23714. * Async queue implementation,
  23715. * @param {Function} worker - The worker function to call for each task.
  23716. * @param {number} concurrency - How many workers to run in parrallel.
  23717. * @returns {*} The async queue object.
  23718. */
  23719. AsyncQueue.queue = function (worker, concurrency) {
  23720. return new AsyncQueue(worker, concurrency);
  23721. };
  23722. return AsyncQueue;
  23723. }());
  23724. // some constants
  23725. var MAX_PROGRESS = 100;
  23726. var rgxExtractUrlHash = /(#[\w-]+)?$/;
  23727. /**
  23728. * The new loader, forked from Resource Loader by Chad Engler: https://github.com/englercj/resource-loader
  23729. *
  23730. * ```js
  23731. * const loader = PIXI.Loader.shared; // PixiJS exposes a premade instance for you to use.
  23732. * // or
  23733. * const loader = new PIXI.Loader(); // You can also create your own if you want
  23734. *
  23735. * const sprites = {};
  23736. *
  23737. * // Chainable `add` to enqueue a resource
  23738. * loader.add('bunny', 'data/bunny.png')
  23739. * .add('spaceship', 'assets/spritesheet.json');
  23740. * loader.add('scoreFont', 'assets/score.fnt');
  23741. *
  23742. * // Chainable `pre` to add a middleware that runs for each resource, *before* loading that resource.
  23743. * // This is useful to implement custom caching modules (using filesystem, indexeddb, memory, etc).
  23744. * loader.pre(cachingMiddleware);
  23745. *
  23746. * // Chainable `use` to add a middleware that runs for each resource, *after* loading that resource.
  23747. * // This is useful to implement custom parsing modules (like spritesheet parsers, spine parser, etc).
  23748. * loader.use(parsingMiddleware);
  23749. *
  23750. * // The `load` method loads the queue of resources, and calls the passed in callback called once all
  23751. * // resources have loaded.
  23752. * loader.load((loader, resources) => {
  23753. * // resources is an object where the key is the name of the resource loaded and the value is the resource object.
  23754. * // They have a couple default properties:
  23755. * // - `url`: The URL that the resource was loaded from
  23756. * // - `error`: The error that happened when trying to load (if any)
  23757. * // - `data`: The raw data that was loaded
  23758. * // also may contain other properties based on the middleware that runs.
  23759. * sprites.bunny = new PIXI.TilingSprite(resources.bunny.texture);
  23760. * sprites.spaceship = new PIXI.TilingSprite(resources.spaceship.texture);
  23761. * sprites.scoreFont = new PIXI.TilingSprite(resources.scoreFont.texture);
  23762. * });
  23763. *
  23764. * // throughout the process multiple signals can be dispatched.
  23765. * loader.onProgress.add(() => {}); // called once per loaded/errored file
  23766. * loader.onError.add(() => {}); // called once per errored file
  23767. * loader.onLoad.add(() => {}); // called once per loaded file
  23768. * loader.onComplete.add(() => {}); // called once when the queued resources all load.
  23769. * ```
  23770. * @memberof PIXI
  23771. */
  23772. var Loader = /** @class */ (function () {
  23773. /**
  23774. * @param baseUrl - The base url for all resources loaded by this loader.
  23775. * @param concurrency - The number of resources to load concurrently.
  23776. */
  23777. function Loader(baseUrl, concurrency) {
  23778. var _this = this;
  23779. if (baseUrl === void 0) { baseUrl = ''; }
  23780. if (concurrency === void 0) { concurrency = 10; }
  23781. /** The progress percent of the loader going through the queue. */
  23782. this.progress = 0;
  23783. /** Loading state of the loader, true if it is currently loading resources. */
  23784. this.loading = false;
  23785. /**
  23786. * A querystring to append to every URL added to the loader.
  23787. *
  23788. * This should be a valid query string *without* the question-mark (`?`). The loader will
  23789. * also *not* escape values for you. Make sure to escape your parameters with
  23790. * [`encodeURIComponent`](https://mdn.io/encodeURIComponent) before assigning this property.
  23791. * @example
  23792. * const loader = new Loader();
  23793. *
  23794. * loader.defaultQueryString = 'user=me&password=secret';
  23795. *
  23796. * // This will request 'image.png?user=me&password=secret'
  23797. * loader.add('image.png').load();
  23798. *
  23799. * loader.reset();
  23800. *
  23801. * // This will request 'image.png?v=1&user=me&password=secret'
  23802. * loader.add('iamge.png?v=1').load();
  23803. */
  23804. this.defaultQueryString = '';
  23805. /** The middleware to run before loading each resource. */
  23806. this._beforeMiddleware = [];
  23807. /** The middleware to run after loading each resource. */
  23808. this._afterMiddleware = [];
  23809. /** The tracks the resources we are currently completing parsing for. */
  23810. this._resourcesParsing = [];
  23811. /**
  23812. * The `_loadResource` function bound with this object context.
  23813. * @param r - The resource to load
  23814. * @param d - The dequeue function
  23815. */
  23816. this._boundLoadResource = function (r, d) { return _this._loadResource(r, d); };
  23817. /** All the resources for this loader keyed by name. */
  23818. this.resources = {};
  23819. this.baseUrl = baseUrl;
  23820. this._beforeMiddleware = [];
  23821. this._afterMiddleware = [];
  23822. this._resourcesParsing = [];
  23823. this._boundLoadResource = function (r, d) { return _this._loadResource(r, d); };
  23824. this._queue = AsyncQueue.queue(this._boundLoadResource, concurrency);
  23825. this._queue.pause();
  23826. this.resources = {};
  23827. this.onProgress = new Signal();
  23828. this.onError = new Signal();
  23829. this.onLoad = new Signal();
  23830. this.onStart = new Signal();
  23831. this.onComplete = new Signal();
  23832. for (var i = 0; i < Loader._plugins.length; ++i) {
  23833. var plugin = Loader._plugins[i];
  23834. var pre = plugin.pre, use = plugin.use;
  23835. if (pre) {
  23836. this.pre(pre);
  23837. }
  23838. if (use) {
  23839. this.use(use);
  23840. }
  23841. }
  23842. this._protected = false;
  23843. }
  23844. /**
  23845. * Same as add, params have strict order
  23846. * @private
  23847. * @param name - The name of the resource to load.
  23848. * @param url - The url for this resource, relative to the baseUrl of this loader.
  23849. * @param options - The options for the load.
  23850. * @param callback - Function to call when this specific resource completes loading.
  23851. * @returns The loader itself.
  23852. */
  23853. Loader.prototype._add = function (name, url, options, callback) {
  23854. // if loading already you can only add resources that have a parent.
  23855. if (this.loading && (!options || !options.parentResource)) {
  23856. throw new Error('Cannot add resources while the loader is running.');
  23857. }
  23858. // check if resource already exists.
  23859. if (this.resources[name]) {
  23860. throw new Error("Resource named \"" + name + "\" already exists.");
  23861. }
  23862. // add base url if this isn't an absolute url
  23863. url = this._prepareUrl(url);
  23864. // create the store the resource
  23865. this.resources[name] = new LoaderResource(name, url, options);
  23866. if (typeof callback === 'function') {
  23867. this.resources[name].onAfterMiddleware.once(callback);
  23868. }
  23869. // if actively loading, make sure to adjust progress chunks for that parent and its children
  23870. if (this.loading) {
  23871. var parent = options.parentResource;
  23872. var incompleteChildren = [];
  23873. for (var i = 0; i < parent.children.length; ++i) {
  23874. if (!parent.children[i].isComplete) {
  23875. incompleteChildren.push(parent.children[i]);
  23876. }
  23877. }
  23878. var fullChunk = parent.progressChunk * (incompleteChildren.length + 1); // +1 for parent
  23879. var eachChunk = fullChunk / (incompleteChildren.length + 2); // +2 for parent & new child
  23880. parent.children.push(this.resources[name]);
  23881. parent.progressChunk = eachChunk;
  23882. for (var i = 0; i < incompleteChildren.length; ++i) {
  23883. incompleteChildren[i].progressChunk = eachChunk;
  23884. }
  23885. this.resources[name].progressChunk = eachChunk;
  23886. }
  23887. // add the resource to the queue
  23888. this._queue.push(this.resources[name]);
  23889. return this;
  23890. };
  23891. /* eslint-enable require-jsdoc,valid-jsdoc */
  23892. /**
  23893. * Sets up a middleware function that will run *before* the
  23894. * resource is loaded.
  23895. * @param fn - The middleware function to register.
  23896. * @returns The loader itself.
  23897. */
  23898. Loader.prototype.pre = function (fn) {
  23899. this._beforeMiddleware.push(fn);
  23900. return this;
  23901. };
  23902. /**
  23903. * Sets up a middleware function that will run *after* the
  23904. * resource is loaded.
  23905. * @param fn - The middleware function to register.
  23906. * @returns The loader itself.
  23907. */
  23908. Loader.prototype.use = function (fn) {
  23909. this._afterMiddleware.push(fn);
  23910. return this;
  23911. };
  23912. /**
  23913. * Resets the queue of the loader to prepare for a new load.
  23914. * @returns The loader itself.
  23915. */
  23916. Loader.prototype.reset = function () {
  23917. this.progress = 0;
  23918. this.loading = false;
  23919. this._queue.kill();
  23920. this._queue.pause();
  23921. // abort all resource loads
  23922. for (var k in this.resources) {
  23923. var res = this.resources[k];
  23924. if (res._onLoadBinding) {
  23925. res._onLoadBinding.detach();
  23926. }
  23927. if (res.isLoading) {
  23928. res.abort('loader reset');
  23929. }
  23930. }
  23931. this.resources = {};
  23932. return this;
  23933. };
  23934. /**
  23935. * Starts loading the queued resources.
  23936. * @param cb - Optional callback that will be bound to the `complete` event.
  23937. * @returns The loader itself.
  23938. */
  23939. Loader.prototype.load = function (cb) {
  23940. deprecation('6.5.0', '@pixi/loaders is being replaced with @pixi/assets in the next major release.');
  23941. // register complete callback if they pass one
  23942. if (typeof cb === 'function') {
  23943. this.onComplete.once(cb);
  23944. }
  23945. // if the queue has already started we are done here
  23946. if (this.loading) {
  23947. return this;
  23948. }
  23949. if (this._queue.idle()) {
  23950. this._onStart();
  23951. this._onComplete();
  23952. }
  23953. else {
  23954. // distribute progress chunks
  23955. var numTasks = this._queue._tasks.length;
  23956. var chunk = MAX_PROGRESS / numTasks;
  23957. for (var i = 0; i < this._queue._tasks.length; ++i) {
  23958. this._queue._tasks[i].data.progressChunk = chunk;
  23959. }
  23960. // notify we are starting
  23961. this._onStart();
  23962. // start loading
  23963. this._queue.resume();
  23964. }
  23965. return this;
  23966. };
  23967. Object.defineProperty(Loader.prototype, "concurrency", {
  23968. /**
  23969. * The number of resources to load concurrently.
  23970. * @default 10
  23971. */
  23972. get: function () {
  23973. return this._queue.concurrency;
  23974. },
  23975. set: function (concurrency) {
  23976. this._queue.concurrency = concurrency;
  23977. },
  23978. enumerable: false,
  23979. configurable: true
  23980. });
  23981. /**
  23982. * Prepares a url for usage based on the configuration of this object
  23983. * @param url - The url to prepare.
  23984. * @returns The prepared url.
  23985. */
  23986. Loader.prototype._prepareUrl = function (url) {
  23987. var parsedUrl = parseUri(url, { strictMode: true });
  23988. var result;
  23989. // absolute url, just use it as is.
  23990. if (parsedUrl.protocol || !parsedUrl.path || url.indexOf('//') === 0) {
  23991. result = url;
  23992. }
  23993. // if baseUrl doesn't end in slash and url doesn't start with slash, then add a slash inbetween
  23994. else if (this.baseUrl.length
  23995. && this.baseUrl.lastIndexOf('/') !== this.baseUrl.length - 1
  23996. && url.charAt(0) !== '/') {
  23997. result = this.baseUrl + "/" + url;
  23998. }
  23999. else {
  24000. result = this.baseUrl + url;
  24001. }
  24002. // if we need to add a default querystring, there is a bit more work
  24003. if (this.defaultQueryString) {
  24004. var hash = rgxExtractUrlHash.exec(result)[0];
  24005. result = result.slice(0, result.length - hash.length);
  24006. if (result.indexOf('?') !== -1) {
  24007. result += "&" + this.defaultQueryString;
  24008. }
  24009. else {
  24010. result += "?" + this.defaultQueryString;
  24011. }
  24012. result += hash;
  24013. }
  24014. return result;
  24015. };
  24016. /**
  24017. * Loads a single resource.
  24018. * @param resource - The resource to load.
  24019. * @param dequeue - The function to call when we need to dequeue this item.
  24020. */
  24021. Loader.prototype._loadResource = function (resource, dequeue) {
  24022. var _this = this;
  24023. resource._dequeue = dequeue;
  24024. // run before middleware
  24025. AsyncQueue.eachSeries(this._beforeMiddleware, function (fn, next) {
  24026. fn.call(_this, resource, function () {
  24027. // if the before middleware marks the resource as complete,
  24028. // break and don't process any more before middleware
  24029. next(resource.isComplete ? {} : null);
  24030. });
  24031. }, function () {
  24032. if (resource.isComplete) {
  24033. _this._onLoad(resource);
  24034. }
  24035. else {
  24036. resource._onLoadBinding = resource.onComplete.once(_this._onLoad, _this);
  24037. resource.load();
  24038. }
  24039. }, true);
  24040. };
  24041. /** Called once loading has started. */
  24042. Loader.prototype._onStart = function () {
  24043. this.progress = 0;
  24044. this.loading = true;
  24045. this.onStart.dispatch(this);
  24046. };
  24047. /** Called once each resource has loaded. */
  24048. Loader.prototype._onComplete = function () {
  24049. this.progress = MAX_PROGRESS;
  24050. this.loading = false;
  24051. this.onComplete.dispatch(this, this.resources);
  24052. };
  24053. /**
  24054. * Called each time a resources is loaded.
  24055. * @param resource - The resource that was loaded
  24056. */
  24057. Loader.prototype._onLoad = function (resource) {
  24058. var _this = this;
  24059. resource._onLoadBinding = null;
  24060. // remove this resource from the async queue, and add it to our list of resources that are being parsed
  24061. this._resourcesParsing.push(resource);
  24062. resource._dequeue();
  24063. // run all the after middleware for this resource
  24064. AsyncQueue.eachSeries(this._afterMiddleware, function (fn, next) {
  24065. fn.call(_this, resource, next);
  24066. }, function () {
  24067. resource.onAfterMiddleware.dispatch(resource);
  24068. _this.progress = Math.min(MAX_PROGRESS, _this.progress + resource.progressChunk);
  24069. _this.onProgress.dispatch(_this, resource);
  24070. if (resource.error) {
  24071. _this.onError.dispatch(resource.error, _this, resource);
  24072. }
  24073. else {
  24074. _this.onLoad.dispatch(_this, resource);
  24075. }
  24076. _this._resourcesParsing.splice(_this._resourcesParsing.indexOf(resource), 1);
  24077. // do completion check
  24078. if (_this._queue.idle() && _this._resourcesParsing.length === 0) {
  24079. _this._onComplete();
  24080. }
  24081. }, true);
  24082. };
  24083. /** Destroy the loader, removes references. */
  24084. Loader.prototype.destroy = function () {
  24085. if (!this._protected) {
  24086. this.reset();
  24087. }
  24088. };
  24089. Object.defineProperty(Loader, "shared", {
  24090. /** A premade instance of the loader that can be used to load resources. */
  24091. get: function () {
  24092. var shared = Loader._shared;
  24093. if (!shared) {
  24094. shared = new Loader();
  24095. shared._protected = true;
  24096. Loader._shared = shared;
  24097. }
  24098. return shared;
  24099. },
  24100. enumerable: false,
  24101. configurable: true
  24102. });
  24103. /**
  24104. * Use the {@link PIXI.extensions.add} API to register plugins.
  24105. * @deprecated since 6.5.0
  24106. * @param plugin - The plugin to add
  24107. * @returns Reference to PIXI.Loader for chaining
  24108. */
  24109. Loader.registerPlugin = function (plugin) {
  24110. deprecation('6.5.0', 'Loader.registerPlugin() is deprecated, use extensions.add() instead.');
  24111. extensions.add({
  24112. type: ExtensionType.Loader,
  24113. ref: plugin,
  24114. });
  24115. return Loader;
  24116. };
  24117. Loader._plugins = [];
  24118. return Loader;
  24119. }());
  24120. extensions.handleByList(ExtensionType.Loader, Loader._plugins);
  24121. Loader.prototype.add = function add(name, url, options, callback) {
  24122. // special case of an array of objects or urls
  24123. if (Array.isArray(name)) {
  24124. for (var i = 0; i < name.length; ++i) {
  24125. this.add(name[i]);
  24126. }
  24127. return this;
  24128. }
  24129. // if an object is passed instead of params
  24130. if (typeof name === 'object') {
  24131. options = name;
  24132. callback = url || options.callback || options.onComplete;
  24133. url = options.url;
  24134. name = options.name || options.key || options.url;
  24135. }
  24136. // case where no name is passed shift all args over by one.
  24137. if (typeof url !== 'string') {
  24138. callback = options;
  24139. options = url;
  24140. url = name;
  24141. }
  24142. // now that we shifted make sure we have a proper url.
  24143. if (typeof url !== 'string') {
  24144. throw new Error('No url passed to add resource to loader.');
  24145. }
  24146. // options are optional so people might pass a function and no options
  24147. if (typeof options === 'function') {
  24148. callback = options;
  24149. options = null;
  24150. }
  24151. return this._add(name, url, options, callback);
  24152. };
  24153. /**
  24154. * Application plugin for supporting loader option. Installing the LoaderPlugin
  24155. * is not necessary if using **pixi.js** or **pixi.js-legacy**.
  24156. * @example
  24157. * import {AppLoaderPlugin} from '@pixi/loaders';
  24158. * import {extensions} from '@pixi/core';
  24159. * extensions.add(AppLoaderPlugin);
  24160. * @memberof PIXI
  24161. */
  24162. var AppLoaderPlugin = /** @class */ (function () {
  24163. function AppLoaderPlugin() {
  24164. }
  24165. /**
  24166. * Called on application constructor
  24167. * @param options
  24168. * @private
  24169. */
  24170. AppLoaderPlugin.init = function (options) {
  24171. options = Object.assign({
  24172. sharedLoader: false,
  24173. }, options);
  24174. this.loader = options.sharedLoader ? Loader.shared : new Loader();
  24175. };
  24176. /**
  24177. * Called when application destroyed
  24178. * @private
  24179. */
  24180. AppLoaderPlugin.destroy = function () {
  24181. if (this.loader) {
  24182. this.loader.destroy();
  24183. this.loader = null;
  24184. }
  24185. };
  24186. /** @ignore */
  24187. AppLoaderPlugin.extension = ExtensionType.Application;
  24188. return AppLoaderPlugin;
  24189. }());
  24190. /**
  24191. * Loader plugin for handling Texture resources.
  24192. * @memberof PIXI
  24193. */
  24194. var TextureLoader = /** @class */ (function () {
  24195. function TextureLoader() {
  24196. }
  24197. /** Handle SVG elements a text, render with SVGResource. */
  24198. TextureLoader.add = function () {
  24199. LoaderResource.setExtensionLoadType('svg', LoaderResource.LOAD_TYPE.XHR);
  24200. LoaderResource.setExtensionXhrType('svg', LoaderResource.XHR_RESPONSE_TYPE.TEXT);
  24201. };
  24202. /**
  24203. * Called after a resource is loaded.
  24204. * @see PIXI.Loader.loaderMiddleware
  24205. * @param resource
  24206. * @param {Function} next
  24207. */
  24208. TextureLoader.use = function (resource, next) {
  24209. // create a new texture if the data is an Image object
  24210. if (resource.data && (resource.type === LoaderResource.TYPE.IMAGE || resource.extension === 'svg')) {
  24211. var data = resource.data, url = resource.url, name = resource.name, metadata = resource.metadata;
  24212. Texture.fromLoader(data, url, name, metadata).then(function (texture) {
  24213. resource.texture = texture;
  24214. next();
  24215. })
  24216. // TODO: handle errors in Texture.fromLoader
  24217. // so we can pass them to the Loader
  24218. .catch(next);
  24219. }
  24220. else {
  24221. next();
  24222. }
  24223. };
  24224. /** @ignore */
  24225. TextureLoader.extension = ExtensionType.Loader;
  24226. return TextureLoader;
  24227. }());
  24228. var _keyStr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
  24229. /**
  24230. * Encodes binary into base64.
  24231. * @function encodeBinary
  24232. * @param {string} input - The input data to encode.
  24233. * @returns {string} The encoded base64 string
  24234. */
  24235. function encodeBinary(input) {
  24236. var output = '';
  24237. var inx = 0;
  24238. while (inx < input.length) {
  24239. // Fill byte buffer array
  24240. var bytebuffer = [0, 0, 0];
  24241. var encodedCharIndexes = [0, 0, 0, 0];
  24242. for (var jnx = 0; jnx < bytebuffer.length; ++jnx) {
  24243. if (inx < input.length) {
  24244. // throw away high-order byte, as documented at:
  24245. // https://developer.mozilla.org/En/Using_XMLHttpRequest#Handling_binary_data
  24246. bytebuffer[jnx] = input.charCodeAt(inx++) & 0xff;
  24247. }
  24248. else {
  24249. bytebuffer[jnx] = 0;
  24250. }
  24251. }
  24252. // Get each encoded character, 6 bits at a time
  24253. // index 1: first 6 bits
  24254. encodedCharIndexes[0] = bytebuffer[0] >> 2;
  24255. // index 2: second 6 bits (2 least significant bits from input byte 1 + 4 most significant bits from byte 2)
  24256. encodedCharIndexes[1] = ((bytebuffer[0] & 0x3) << 4) | (bytebuffer[1] >> 4);
  24257. // index 3: third 6 bits (4 least significant bits from input byte 2 + 2 most significant bits from byte 3)
  24258. encodedCharIndexes[2] = ((bytebuffer[1] & 0x0f) << 2) | (bytebuffer[2] >> 6);
  24259. // index 3: forth 6 bits (6 least significant bits from input byte 3)
  24260. encodedCharIndexes[3] = bytebuffer[2] & 0x3f;
  24261. // Determine whether padding happened, and adjust accordingly
  24262. var paddingBytes = inx - (input.length - 1);
  24263. switch (paddingBytes) {
  24264. case 2:
  24265. // Set last 2 characters to padding char
  24266. encodedCharIndexes[3] = 64;
  24267. encodedCharIndexes[2] = 64;
  24268. break;
  24269. case 1:
  24270. // Set last character to padding char
  24271. encodedCharIndexes[3] = 64;
  24272. break;
  24273. }
  24274. // Now we will grab each appropriate character out of our keystring
  24275. // based on our index array and append it to the output string
  24276. for (var jnx = 0; jnx < encodedCharIndexes.length; ++jnx) {
  24277. output += _keyStr.charAt(encodedCharIndexes[jnx]);
  24278. }
  24279. }
  24280. return output;
  24281. }
  24282. /**
  24283. * A middleware for transforming XHR loaded Blobs into more useful objects
  24284. * @ignore
  24285. * @function parsing
  24286. * @example
  24287. * import { Loader, middleware } from 'resource-loader';
  24288. * const loader = new Loader();
  24289. * loader.use(middleware.parsing);
  24290. * @param resource - Current Resource
  24291. * @param next - Callback when complete
  24292. */
  24293. function parsing(resource, next) {
  24294. if (!resource.data) {
  24295. next();
  24296. return;
  24297. }
  24298. // if this was an XHR load of a blob
  24299. if (resource.xhr && resource.xhrType === LoaderResource.XHR_RESPONSE_TYPE.BLOB) {
  24300. // if there is no blob support we probably got a binary string back
  24301. if (!self.Blob || typeof resource.data === 'string') {
  24302. var type = resource.xhr.getResponseHeader('content-type');
  24303. // this is an image, convert the binary string into a data url
  24304. if (type && type.indexOf('image') === 0) {
  24305. resource.data = new Image();
  24306. resource.data.src = "data:" + type + ";base64," + encodeBinary(resource.xhr.responseText);
  24307. resource.type = LoaderResource.TYPE.IMAGE;
  24308. // wait until the image loads and then callback
  24309. resource.data.onload = function () {
  24310. resource.data.onload = null;
  24311. next();
  24312. };
  24313. // next will be called on load
  24314. return;
  24315. }
  24316. }
  24317. // if content type says this is an image, then we should transform the blob into an Image object
  24318. else if (resource.data.type.indexOf('image') === 0) {
  24319. var Url_1 = globalThis.URL || globalThis.webkitURL;
  24320. var src_1 = Url_1.createObjectURL(resource.data);
  24321. resource.blob = resource.data;
  24322. resource.data = new Image();
  24323. resource.data.src = src_1;
  24324. resource.type = LoaderResource.TYPE.IMAGE;
  24325. // cleanup the no longer used blob after the image loads
  24326. // TODO: Is this correct? Will the image be invalid after revoking?
  24327. resource.data.onload = function () {
  24328. Url_1.revokeObjectURL(src_1);
  24329. resource.data.onload = null;
  24330. next();
  24331. };
  24332. // next will be called on load.
  24333. return;
  24334. }
  24335. }
  24336. next();
  24337. }
  24338. /**
  24339. * Parse any blob into more usable objects (e.g. Image).
  24340. * @memberof PIXI
  24341. */
  24342. var ParsingLoader = /** @class */ (function () {
  24343. function ParsingLoader() {
  24344. }
  24345. /** @ignore */
  24346. ParsingLoader.extension = ExtensionType.Loader;
  24347. ParsingLoader.use = parsing;
  24348. return ParsingLoader;
  24349. }());
  24350. extensions.add(TextureLoader, ParsingLoader);
  24351. /*!
  24352. * @pixi/compressed-textures - v6.5.10
  24353. * Compiled Thu, 06 Jul 2023 15:25:11 UTC
  24354. *
  24355. * @pixi/compressed-textures is licensed under the MIT License.
  24356. * http://www.opensource.org/licenses/mit-license
  24357. */
  24358. var _a$2;
  24359. /**
  24360. * WebGL internal formats, including compressed texture formats provided by extensions
  24361. * @memberof PIXI
  24362. * @static
  24363. * @name INTERNAL_FORMATS
  24364. * @enum {number}
  24365. * @property {number} [COMPRESSED_RGB_S3TC_DXT1_EXT=0x83F0] -
  24366. * @property {number} [COMPRESSED_RGBA_S3TC_DXT1_EXT=0x83F1] -
  24367. * @property {number} [COMPRESSED_RGBA_S3TC_DXT3_EXT=0x83F2] -
  24368. * @property {number} [COMPRESSED_RGBA_S3TC_DXT5_EXT=0x83F3] -
  24369. * @property {number} [COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT=35917] -
  24370. * @property {number} [COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT=35918] -
  24371. * @property {number} [COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT=35919] -
  24372. * @property {number} [COMPRESSED_SRGB_S3TC_DXT1_EXT=35916] -
  24373. * @property {number} [COMPRESSED_R11_EAC=0x9270] -
  24374. * @property {number} [COMPRESSED_SIGNED_R11_EAC=0x9271] -
  24375. * @property {number} [COMPRESSED_RG11_EAC=0x9272] -
  24376. * @property {number} [COMPRESSED_SIGNED_RG11_EAC=0x9273] -
  24377. * @property {number} [COMPRESSED_RGB8_ETC2=0x9274] -
  24378. * @property {number} [COMPRESSED_RGBA8_ETC2_EAC=0x9278] -
  24379. * @property {number} [COMPRESSED_SRGB8_ETC2=0x9275] -
  24380. * @property {number} [COMPRESSED_SRGB8_ALPHA8_ETC2_EAC=0x9279] -
  24381. * @property {number} [COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2=0x9276] -
  24382. * @property {number} [COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2=0x9277] -
  24383. * @property {number} [COMPRESSED_RGB_PVRTC_4BPPV1_IMG=0x8C00] -
  24384. * @property {number} [COMPRESSED_RGBA_PVRTC_4BPPV1_IMG=0x8C02] -
  24385. * @property {number} [COMPRESSED_RGB_PVRTC_2BPPV1_IMG=0x8C01] -
  24386. * @property {number} [COMPRESSED_RGBA_PVRTC_2BPPV1_IMG=0x8C03] -
  24387. * @property {number} [COMPRESSED_RGB_ETC1_WEBGL=0x8D64] -
  24388. * @property {number} [COMPRESSED_RGB_ATC_WEBGL=0x8C92] -
  24389. * @property {number} [COMPRESSED_RGBA_ATC_EXPLICIT_ALPHA_WEBGL=0x8C92] -
  24390. * @property {number} [COMPRESSED_RGBA_ATC_INTERPOLATED_ALPHA_WEBGL=0x87EE] -
  24391. * @property {number} [COMPRESSED_RGBA_ASTC_4x4_KHR=0x93B0] -
  24392. */
  24393. var INTERNAL_FORMATS;
  24394. (function (INTERNAL_FORMATS) {
  24395. // WEBGL_compressed_texture_s3tc
  24396. INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_RGB_S3TC_DXT1_EXT"] = 33776] = "COMPRESSED_RGB_S3TC_DXT1_EXT";
  24397. INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_RGBA_S3TC_DXT1_EXT"] = 33777] = "COMPRESSED_RGBA_S3TC_DXT1_EXT";
  24398. INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_RGBA_S3TC_DXT3_EXT"] = 33778] = "COMPRESSED_RGBA_S3TC_DXT3_EXT";
  24399. INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_RGBA_S3TC_DXT5_EXT"] = 33779] = "COMPRESSED_RGBA_S3TC_DXT5_EXT";
  24400. // WEBGL_compressed_texture_s3tc_srgb
  24401. INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT"] = 35917] = "COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT";
  24402. INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT"] = 35918] = "COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT";
  24403. INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT"] = 35919] = "COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT";
  24404. INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_SRGB_S3TC_DXT1_EXT"] = 35916] = "COMPRESSED_SRGB_S3TC_DXT1_EXT";
  24405. // WEBGL_compressed_texture_etc
  24406. INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_R11_EAC"] = 37488] = "COMPRESSED_R11_EAC";
  24407. INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_SIGNED_R11_EAC"] = 37489] = "COMPRESSED_SIGNED_R11_EAC";
  24408. INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_RG11_EAC"] = 37490] = "COMPRESSED_RG11_EAC";
  24409. INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_SIGNED_RG11_EAC"] = 37491] = "COMPRESSED_SIGNED_RG11_EAC";
  24410. INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_RGB8_ETC2"] = 37492] = "COMPRESSED_RGB8_ETC2";
  24411. INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_RGBA8_ETC2_EAC"] = 37496] = "COMPRESSED_RGBA8_ETC2_EAC";
  24412. INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_SRGB8_ETC2"] = 37493] = "COMPRESSED_SRGB8_ETC2";
  24413. INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_SRGB8_ALPHA8_ETC2_EAC"] = 37497] = "COMPRESSED_SRGB8_ALPHA8_ETC2_EAC";
  24414. INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2"] = 37494] = "COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2";
  24415. INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2"] = 37495] = "COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2";
  24416. // WEBGL_compressed_texture_pvrtc
  24417. INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_RGB_PVRTC_4BPPV1_IMG"] = 35840] = "COMPRESSED_RGB_PVRTC_4BPPV1_IMG";
  24418. INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_RGBA_PVRTC_4BPPV1_IMG"] = 35842] = "COMPRESSED_RGBA_PVRTC_4BPPV1_IMG";
  24419. INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_RGB_PVRTC_2BPPV1_IMG"] = 35841] = "COMPRESSED_RGB_PVRTC_2BPPV1_IMG";
  24420. INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_RGBA_PVRTC_2BPPV1_IMG"] = 35843] = "COMPRESSED_RGBA_PVRTC_2BPPV1_IMG";
  24421. // WEBGL_compressed_texture_etc1
  24422. INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_RGB_ETC1_WEBGL"] = 36196] = "COMPRESSED_RGB_ETC1_WEBGL";
  24423. // WEBGL_compressed_texture_atc
  24424. INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_RGB_ATC_WEBGL"] = 35986] = "COMPRESSED_RGB_ATC_WEBGL";
  24425. INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_RGBA_ATC_EXPLICIT_ALPHA_WEBGL"] = 35986] = "COMPRESSED_RGBA_ATC_EXPLICIT_ALPHA_WEBGL";
  24426. INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_RGBA_ATC_INTERPOLATED_ALPHA_WEBGL"] = 34798] = "COMPRESSED_RGBA_ATC_INTERPOLATED_ALPHA_WEBGL";
  24427. // WEBGL_compressed_texture_astc
  24428. /* eslint-disable-next-line camelcase */
  24429. INTERNAL_FORMATS[INTERNAL_FORMATS["COMPRESSED_RGBA_ASTC_4x4_KHR"] = 37808] = "COMPRESSED_RGBA_ASTC_4x4_KHR";
  24430. })(INTERNAL_FORMATS || (INTERNAL_FORMATS = {}));
  24431. /**
  24432. * Maps the compressed texture formats in {@link PIXI.INTERNAL_FORMATS} to the number of bytes taken by
  24433. * each texel.
  24434. * @memberof PIXI
  24435. * @static
  24436. * @ignore
  24437. */
  24438. var INTERNAL_FORMAT_TO_BYTES_PER_PIXEL = (_a$2 = {},
  24439. // WEBGL_compressed_texture_s3tc
  24440. _a$2[INTERNAL_FORMATS.COMPRESSED_RGB_S3TC_DXT1_EXT] = 0.5,
  24441. _a$2[INTERNAL_FORMATS.COMPRESSED_RGBA_S3TC_DXT1_EXT] = 0.5,
  24442. _a$2[INTERNAL_FORMATS.COMPRESSED_RGBA_S3TC_DXT3_EXT] = 1,
  24443. _a$2[INTERNAL_FORMATS.COMPRESSED_RGBA_S3TC_DXT5_EXT] = 1,
  24444. // WEBGL_compressed_texture_s3tc
  24445. _a$2[INTERNAL_FORMATS.COMPRESSED_SRGB_S3TC_DXT1_EXT] = 0.5,
  24446. _a$2[INTERNAL_FORMATS.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT] = 0.5,
  24447. _a$2[INTERNAL_FORMATS.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT] = 1,
  24448. _a$2[INTERNAL_FORMATS.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT] = 1,
  24449. // WEBGL_compressed_texture_etc
  24450. _a$2[INTERNAL_FORMATS.COMPRESSED_R11_EAC] = 0.5,
  24451. _a$2[INTERNAL_FORMATS.COMPRESSED_SIGNED_R11_EAC] = 0.5,
  24452. _a$2[INTERNAL_FORMATS.COMPRESSED_RG11_EAC] = 1,
  24453. _a$2[INTERNAL_FORMATS.COMPRESSED_SIGNED_RG11_EAC] = 1,
  24454. _a$2[INTERNAL_FORMATS.COMPRESSED_RGB8_ETC2] = 0.5,
  24455. _a$2[INTERNAL_FORMATS.COMPRESSED_RGBA8_ETC2_EAC] = 1,
  24456. _a$2[INTERNAL_FORMATS.COMPRESSED_SRGB8_ETC2] = 0.5,
  24457. _a$2[INTERNAL_FORMATS.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC] = 1,
  24458. _a$2[INTERNAL_FORMATS.COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2] = 0.5,
  24459. _a$2[INTERNAL_FORMATS.COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2] = 0.5,
  24460. // WEBGL_compressed_texture_pvrtc
  24461. _a$2[INTERNAL_FORMATS.COMPRESSED_RGB_PVRTC_4BPPV1_IMG] = 0.5,
  24462. _a$2[INTERNAL_FORMATS.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG] = 0.5,
  24463. _a$2[INTERNAL_FORMATS.COMPRESSED_RGB_PVRTC_2BPPV1_IMG] = 0.25,
  24464. _a$2[INTERNAL_FORMATS.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG] = 0.25,
  24465. // WEBGL_compressed_texture_etc1
  24466. _a$2[INTERNAL_FORMATS.COMPRESSED_RGB_ETC1_WEBGL] = 0.5,
  24467. // @see https://www.khronos.org/registry/OpenGL/extensions/AMD/AMD_compressed_ATC_texture.txt
  24468. // WEBGL_compressed_texture_atc
  24469. _a$2[INTERNAL_FORMATS.COMPRESSED_RGB_ATC_WEBGL] = 0.5,
  24470. _a$2[INTERNAL_FORMATS.COMPRESSED_RGBA_ATC_EXPLICIT_ALPHA_WEBGL] = 1,
  24471. _a$2[INTERNAL_FORMATS.COMPRESSED_RGBA_ATC_INTERPOLATED_ALPHA_WEBGL] = 1,
  24472. // @see https://registry.khronos.org/OpenGL/extensions/KHR/KHR_texture_compression_astc_hdr.txt
  24473. // WEBGL_compressed_texture_astc
  24474. /* eslint-disable-next-line camelcase */
  24475. _a$2[INTERNAL_FORMATS.COMPRESSED_RGBA_ASTC_4x4_KHR] = 1,
  24476. _a$2);
  24477. /*! *****************************************************************************
  24478. Copyright (c) Microsoft Corporation.
  24479. Permission to use, copy, modify, and/or distribute this software for any
  24480. purpose with or without fee is hereby granted.
  24481. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  24482. REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
  24483. AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  24484. INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
  24485. LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
  24486. OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
  24487. PERFORMANCE OF THIS SOFTWARE.
  24488. ***************************************************************************** */
  24489. /* global Reflect, Promise */
  24490. var extendStatics$g = function(d, b) {
  24491. extendStatics$g = Object.setPrototypeOf ||
  24492. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  24493. function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } };
  24494. return extendStatics$g(d, b);
  24495. };
  24496. function __extends$g(d, b) {
  24497. extendStatics$g(d, b);
  24498. function __() { this.constructor = d; }
  24499. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  24500. }
  24501. function __awaiter(thisArg, _arguments, P, generator) {
  24502. function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
  24503. return new (P || (P = Promise))(function (resolve, reject) {
  24504. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  24505. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  24506. function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
  24507. step((generator = generator.apply(thisArg, _arguments || [])).next());
  24508. });
  24509. }
  24510. function __generator(thisArg, body) {
  24511. var _ = { label: 0, sent: function() { if (t[0] & 1) { throw t[1]; } return t[1]; }, trys: [], ops: [] }, f, y, t, g;
  24512. return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
  24513. function verb(n) { return function (v) { return step([n, v]); }; }
  24514. function step(op) {
  24515. if (f) { throw new TypeError("Generator is already executing."); }
  24516. while (_) { try {
  24517. if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) { return t; }
  24518. if (y = 0, t) { op = [op[0] & 2, t.value]; }
  24519. switch (op[0]) {
  24520. case 0: case 1: t = op; break;
  24521. case 4: _.label++; return { value: op[1], done: false };
  24522. case 5: _.label++; y = op[1]; op = [0]; continue;
  24523. case 7: op = _.ops.pop(); _.trys.pop(); continue;
  24524. default:
  24525. if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
  24526. if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
  24527. if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
  24528. if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
  24529. if (t[2]) { _.ops.pop(); }
  24530. _.trys.pop(); continue;
  24531. }
  24532. op = body.call(thisArg, _);
  24533. } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } }
  24534. if (op[0] & 5) { throw op[1]; } return { value: op[0] ? op[1] : void 0, done: true };
  24535. }
  24536. }
  24537. /**
  24538. * Resource that fetches texture data over the network and stores it in a buffer.
  24539. * @class
  24540. * @extends PIXI.Resource
  24541. * @memberof PIXI
  24542. */
  24543. var BlobResource = /** @class */ (function (_super) {
  24544. __extends$g(BlobResource, _super);
  24545. /**
  24546. * @param {string} source - the URL of the texture file
  24547. * @param {PIXI.IBlobOptions} options
  24548. * @param {boolean}[options.autoLoad] - whether to fetch the data immediately;
  24549. * you can fetch it later via {@link BlobResource#load}
  24550. * @param {boolean}[options.width] - the width in pixels.
  24551. * @param {boolean}[options.height] - the height in pixels.
  24552. */
  24553. function BlobResource(source, options) {
  24554. if (options === void 0) { options = { width: 1, height: 1, autoLoad: true }; }
  24555. var _this = this;
  24556. var origin;
  24557. var data;
  24558. if (typeof source === 'string') {
  24559. origin = source;
  24560. data = new Uint8Array();
  24561. }
  24562. else {
  24563. origin = null;
  24564. data = source;
  24565. }
  24566. _this = _super.call(this, data, options) || this;
  24567. /**
  24568. * The URL of the texture file
  24569. * @member {string}
  24570. */
  24571. _this.origin = origin;
  24572. /**
  24573. * The viewable buffer on the data
  24574. * @member {ViewableBuffer}
  24575. */
  24576. // HINT: BlobResource allows "null" sources, assuming the child class provides an alternative
  24577. _this.buffer = data ? new ViewableBuffer(data) : null;
  24578. // Allow autoLoad = "undefined" still load the resource by default
  24579. if (_this.origin && options.autoLoad !== false) {
  24580. _this.load();
  24581. }
  24582. if (data && data.length) {
  24583. _this.loaded = true;
  24584. _this.onBlobLoaded(_this.buffer.rawBinaryData);
  24585. }
  24586. return _this;
  24587. }
  24588. BlobResource.prototype.onBlobLoaded = function (_data) {
  24589. // TODO: Override this method
  24590. };
  24591. /** Loads the blob */
  24592. BlobResource.prototype.load = function () {
  24593. return __awaiter(this, void 0, Promise, function () {
  24594. var response, blob, arrayBuffer;
  24595. return __generator(this, function (_a) {
  24596. switch (_a.label) {
  24597. case 0: return [4 /*yield*/, fetch(this.origin)];
  24598. case 1:
  24599. response = _a.sent();
  24600. return [4 /*yield*/, response.blob()];
  24601. case 2:
  24602. blob = _a.sent();
  24603. return [4 /*yield*/, blob.arrayBuffer()];
  24604. case 3:
  24605. arrayBuffer = _a.sent();
  24606. this.data = new Uint32Array(arrayBuffer);
  24607. this.buffer = new ViewableBuffer(arrayBuffer);
  24608. this.loaded = true;
  24609. this.onBlobLoaded(arrayBuffer);
  24610. this.update();
  24611. return [2 /*return*/, this];
  24612. }
  24613. });
  24614. });
  24615. };
  24616. return BlobResource;
  24617. }(BufferResource));
  24618. /**
  24619. * Resource for compressed texture formats, as follows: S3TC/DXTn (& their sRGB formats), ATC, ASTC, ETC 1/2, PVRTC.
  24620. *
  24621. * Compressed textures improve performance when rendering is texture-bound. The texture data stays compressed in
  24622. * graphics memory, increasing memory locality and speeding up texture fetches. These formats can also be used to store
  24623. * more detail in the same amount of memory.
  24624. *
  24625. * For most developers, container file formats are a better abstraction instead of directly handling raw texture
  24626. * data. PixiJS provides native support for the following texture file formats (via {@link PIXI.Loader}):
  24627. *
  24628. * **.dds** - the DirectDraw Surface file format stores DXTn (DXT-1,3,5) data. See {@link PIXI.DDSLoader}
  24629. * **.ktx** - the Khronos Texture Container file format supports storing all the supported WebGL compression formats.
  24630. * See {@link PIXI.KTXLoader}.
  24631. * **.basis** - the BASIS supercompressed file format stores texture data in an internal format that is transcoded
  24632. * to the compression format supported on the device at _runtime_. It also supports transcoding into a uncompressed
  24633. * format as a fallback; you must install the `@pixi/basis-loader`, `@pixi/basis-transcoder` packages separately to
  24634. * use these files. See {@link PIXI.BasisLoader}.
  24635. *
  24636. * The loaders for the aforementioned formats use `CompressedTextureResource` internally. It is strongly suggested that
  24637. * they be used instead.
  24638. *
  24639. * ## Working directly with CompressedTextureResource
  24640. *
  24641. * Since `CompressedTextureResource` inherits `BlobResource`, you can provide it a URL pointing to a file containing
  24642. * the raw texture data (with no file headers!):
  24643. *
  24644. * ```js
  24645. * // The resource backing the texture data for your textures.
  24646. * // NOTE: You can also provide a ArrayBufferView instead of a URL. This is used when loading data from a container file
  24647. * // format such as KTX, DDS, or BASIS.
  24648. * const compressedResource = new PIXI.CompressedTextureResource("bunny.dxt5", {
  24649. * format: PIXI.INTERNAL_FORMATS.COMPRESSED_RGBA_S3TC_DXT5_EXT,
  24650. * width: 256,
  24651. * height: 256
  24652. * });
  24653. *
  24654. * // You can create a base-texture to the cache, so that future `Texture`s can be created using the `Texture.from` API.
  24655. * const baseTexture = new PIXI.BaseTexture(compressedResource, { pmaMode: PIXI.ALPHA_MODES.NPM });
  24656. *
  24657. * // Create a Texture to add to the TextureCache
  24658. * const texture = new PIXI.Texture(baseTexture);
  24659. *
  24660. * // Add baseTexture & texture to the global texture cache
  24661. * PIXI.BaseTexture.addToCache(baseTexture, "bunny.dxt5");
  24662. * PIXI.Texture.addToCache(texture, "bunny.dxt5");
  24663. * ```
  24664. * @memberof PIXI
  24665. */
  24666. var CompressedTextureResource = /** @class */ (function (_super) {
  24667. __extends$g(CompressedTextureResource, _super);
  24668. /**
  24669. * @param source - the buffer/URL holding the compressed texture data
  24670. * @param options
  24671. * @param {PIXI.INTERNAL_FORMATS} options.format - the compression format
  24672. * @param {number} options.width - the image width in pixels.
  24673. * @param {number} options.height - the image height in pixels.
  24674. * @param {number} [options.level=1] - the mipmap levels stored in the compressed texture, including level 0.
  24675. * @param {number} [options.levelBuffers] - the buffers for each mipmap level. `CompressedTextureResource` can allows you
  24676. * to pass `null` for `source`, for cases where each level is stored in non-contiguous memory.
  24677. */
  24678. function CompressedTextureResource(source, options) {
  24679. var _this = _super.call(this, source, options) || this;
  24680. _this.format = options.format;
  24681. _this.levels = options.levels || 1;
  24682. _this._width = options.width;
  24683. _this._height = options.height;
  24684. _this._extension = CompressedTextureResource._formatToExtension(_this.format);
  24685. if (options.levelBuffers || _this.buffer) {
  24686. // ViewableBuffer doesn't support byteOffset :-( so allow source to be Uint8Array
  24687. _this._levelBuffers = options.levelBuffers
  24688. || CompressedTextureResource._createLevelBuffers(source instanceof Uint8Array ? source : _this.buffer.uint8View, _this.format, _this.levels, 4, 4, // PVRTC has 8x4 blocks in 2bpp mode
  24689. _this.width, _this.height);
  24690. }
  24691. return _this;
  24692. }
  24693. /**
  24694. * @override
  24695. * @param renderer - A reference to the current renderer
  24696. * @param _texture - the texture
  24697. * @param _glTexture - texture instance for this webgl context
  24698. */
  24699. CompressedTextureResource.prototype.upload = function (renderer, _texture, _glTexture) {
  24700. var gl = renderer.gl;
  24701. var extension = renderer.context.extensions[this._extension];
  24702. if (!extension) {
  24703. throw new Error(this._extension + " textures are not supported on the current machine");
  24704. }
  24705. if (!this._levelBuffers) {
  24706. // Do not try to upload data before BlobResource loads, unless the levelBuffers were provided directly!
  24707. return false;
  24708. }
  24709. for (var i = 0, j = this.levels; i < j; i++) {
  24710. var _a = this._levelBuffers[i], levelID = _a.levelID, levelWidth = _a.levelWidth, levelHeight = _a.levelHeight, levelBuffer = _a.levelBuffer;
  24711. gl.compressedTexImage2D(gl.TEXTURE_2D, levelID, this.format, levelWidth, levelHeight, 0, levelBuffer);
  24712. }
  24713. return true;
  24714. };
  24715. /** @protected */
  24716. CompressedTextureResource.prototype.onBlobLoaded = function () {
  24717. this._levelBuffers = CompressedTextureResource._createLevelBuffers(this.buffer.uint8View, this.format, this.levels, 4, 4, // PVRTC has 8x4 blocks in 2bpp mode
  24718. this.width, this.height);
  24719. };
  24720. /**
  24721. * Returns the key (to ContextSystem#extensions) for the WebGL extension supporting the compression format
  24722. * @private
  24723. * @param format - the compression format to get the extension for.
  24724. */
  24725. CompressedTextureResource._formatToExtension = function (format) {
  24726. if (format >= 0x83F0 && format <= 0x83F3) {
  24727. return 's3tc';
  24728. }
  24729. else if (format >= 0x9270 && format <= 0x9279) {
  24730. return 'etc';
  24731. }
  24732. else if (format >= 0x8C00 && format <= 0x8C03) {
  24733. return 'pvrtc';
  24734. }
  24735. else if (format >= 0x8D64) {
  24736. return 'etc1';
  24737. }
  24738. else if (format >= 0x8C92 && format <= 0x87EE) {
  24739. return 'atc';
  24740. }
  24741. throw new Error('Invalid (compressed) texture format given!');
  24742. };
  24743. /**
  24744. * Pre-creates buffer views for each mipmap level
  24745. * @private
  24746. * @param buffer -
  24747. * @param format - compression formats
  24748. * @param levels - mipmap levels
  24749. * @param blockWidth -
  24750. * @param blockHeight -
  24751. * @param imageWidth - width of the image in pixels
  24752. * @param imageHeight - height of the image in pixels
  24753. */
  24754. CompressedTextureResource._createLevelBuffers = function (buffer, format, levels, blockWidth, blockHeight, imageWidth, imageHeight) {
  24755. // The byte-size of the first level buffer
  24756. var buffers = new Array(levels);
  24757. var offset = buffer.byteOffset;
  24758. var levelWidth = imageWidth;
  24759. var levelHeight = imageHeight;
  24760. var alignedLevelWidth = (levelWidth + blockWidth - 1) & ~(blockWidth - 1);
  24761. var alignedLevelHeight = (levelHeight + blockHeight - 1) & ~(blockHeight - 1);
  24762. var levelSize = alignedLevelWidth * alignedLevelHeight * INTERNAL_FORMAT_TO_BYTES_PER_PIXEL[format];
  24763. for (var i = 0; i < levels; i++) {
  24764. buffers[i] = {
  24765. levelID: i,
  24766. levelWidth: levels > 1 ? levelWidth : alignedLevelWidth,
  24767. levelHeight: levels > 1 ? levelHeight : alignedLevelHeight,
  24768. levelBuffer: new Uint8Array(buffer.buffer, offset, levelSize)
  24769. };
  24770. offset += levelSize;
  24771. // Calculate levelBuffer dimensions for next iteration
  24772. levelWidth = (levelWidth >> 1) || 1;
  24773. levelHeight = (levelHeight >> 1) || 1;
  24774. alignedLevelWidth = (levelWidth + blockWidth - 1) & ~(blockWidth - 1);
  24775. alignedLevelHeight = (levelHeight + blockHeight - 1) & ~(blockHeight - 1);
  24776. levelSize = alignedLevelWidth * alignedLevelHeight * INTERNAL_FORMAT_TO_BYTES_PER_PIXEL[format];
  24777. }
  24778. return buffers;
  24779. };
  24780. return CompressedTextureResource;
  24781. }(BlobResource));
  24782. /* eslint-enable camelcase */
  24783. /**
  24784. * Loader plugin for handling compressed textures for all platforms.
  24785. * @class
  24786. * @memberof PIXI
  24787. * @implements {PIXI.ILoaderPlugin}
  24788. */
  24789. var CompressedTextureLoader = /** @class */ (function () {
  24790. function CompressedTextureLoader() {
  24791. }
  24792. /**
  24793. * Called after a compressed-textures manifest is loaded.
  24794. *
  24795. * This will then load the correct compression format for the device. Your manifest should adhere
  24796. * to the following schema:
  24797. *
  24798. * ```js
  24799. * import { INTERNAL_FORMATS } from '@pixi/constants';
  24800. *
  24801. * type CompressedTextureManifest = {
  24802. * textures: Array<{ src: string, format?: keyof INTERNAL_FORMATS}>,
  24803. * cacheID: string;
  24804. * };
  24805. * ```
  24806. *
  24807. * This is an example of a .json manifest file
  24808. *
  24809. * ```json
  24810. * {
  24811. * "cacheID":"asset",
  24812. * "textures":[
  24813. * { "src":"asset.fallback.png" },
  24814. * { "format":"COMPRESSED_RGBA_S3TC_DXT5_EXT", "src":"asset.s3tc.ktx" },
  24815. * { "format":"COMPRESSED_RGBA8_ETC2_EAC", "src":"asset.etc.ktx" },
  24816. * { "format":"RGBA_PVRTC_4BPPV1_IMG", "src":"asset.pvrtc.ktx" }
  24817. * ]
  24818. * }
  24819. * ```
  24820. */
  24821. CompressedTextureLoader.use = function (resource, next) {
  24822. var data = resource.data;
  24823. var loader = this;
  24824. if (resource.type === LoaderResource.TYPE.JSON
  24825. && data
  24826. && data.cacheID
  24827. && data.textures) {
  24828. var textures = data.textures;
  24829. var textureURL = void 0;
  24830. var fallbackURL = void 0;
  24831. // Search for an extension that holds one the formats
  24832. for (var i = 0, j = textures.length; i < j; i++) {
  24833. var texture = textures[i];
  24834. var url_1 = texture.src;
  24835. var format = texture.format;
  24836. if (!format) {
  24837. fallbackURL = url_1;
  24838. }
  24839. if (CompressedTextureLoader.textureFormats[format]) {
  24840. textureURL = url_1;
  24841. break;
  24842. }
  24843. }
  24844. textureURL = textureURL || fallbackURL;
  24845. // Make sure we have a URL
  24846. if (!textureURL) {
  24847. next(new Error("Cannot load compressed-textures in " + resource.url + ", make sure you provide a fallback"));
  24848. return;
  24849. }
  24850. if (textureURL === resource.url) {
  24851. // Prevent infinite loops
  24852. next(new Error('URL of compressed texture cannot be the same as the manifest\'s URL'));
  24853. return;
  24854. }
  24855. var loadOptions = {
  24856. crossOrigin: resource.crossOrigin,
  24857. metadata: resource.metadata.imageMetadata,
  24858. parentResource: resource
  24859. };
  24860. var resourcePath = url.resolve(resource.url.replace(loader.baseUrl, ''), textureURL);
  24861. var resourceName = data.cacheID;
  24862. // The appropriate loader should register the texture
  24863. loader.add(resourceName, resourcePath, loadOptions, function (res) {
  24864. if (res.error) {
  24865. next(res.error);
  24866. return;
  24867. }
  24868. var _a = res.texture, texture = _a === void 0 ? null : _a, _b = res.textures, textures = _b === void 0 ? {} : _b;
  24869. // Make sure texture/textures is assigned to parent resource
  24870. Object.assign(resource, { texture: texture, textures: textures });
  24871. // Pass along any error
  24872. next();
  24873. });
  24874. }
  24875. else {
  24876. next();
  24877. }
  24878. };
  24879. Object.defineProperty(CompressedTextureLoader, "textureExtensions", {
  24880. /** Map of available texture extensions. */
  24881. get: function () {
  24882. if (!CompressedTextureLoader._textureExtensions) {
  24883. // Auto-detect WebGL compressed-texture extensions
  24884. var canvas = settings.ADAPTER.createCanvas();
  24885. var gl = canvas.getContext('webgl');
  24886. if (!gl) {
  24887. console.warn('WebGL not available for compressed textures. Silently failing.');
  24888. return {};
  24889. }
  24890. var extensions = {
  24891. s3tc: gl.getExtension('WEBGL_compressed_texture_s3tc'),
  24892. s3tc_sRGB: gl.getExtension('WEBGL_compressed_texture_s3tc_srgb'),
  24893. etc: gl.getExtension('WEBGL_compressed_texture_etc'),
  24894. etc1: gl.getExtension('WEBGL_compressed_texture_etc1'),
  24895. pvrtc: gl.getExtension('WEBGL_compressed_texture_pvrtc')
  24896. || gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc'),
  24897. atc: gl.getExtension('WEBGL_compressed_texture_atc'),
  24898. astc: gl.getExtension('WEBGL_compressed_texture_astc')
  24899. };
  24900. CompressedTextureLoader._textureExtensions = extensions;
  24901. }
  24902. return CompressedTextureLoader._textureExtensions;
  24903. },
  24904. enumerable: false,
  24905. configurable: true
  24906. });
  24907. Object.defineProperty(CompressedTextureLoader, "textureFormats", {
  24908. /** Map of available texture formats. */
  24909. get: function () {
  24910. if (!CompressedTextureLoader._textureFormats) {
  24911. var extensions = CompressedTextureLoader.textureExtensions;
  24912. CompressedTextureLoader._textureFormats = {};
  24913. // Assign all available compressed-texture formats
  24914. for (var extensionName in extensions) {
  24915. var extension = extensions[extensionName];
  24916. if (!extension) {
  24917. continue;
  24918. }
  24919. Object.assign(CompressedTextureLoader._textureFormats, Object.getPrototypeOf(extension));
  24920. }
  24921. }
  24922. return CompressedTextureLoader._textureFormats;
  24923. },
  24924. enumerable: false,
  24925. configurable: true
  24926. });
  24927. /** @ignore */
  24928. CompressedTextureLoader.extension = ExtensionType.Loader;
  24929. return CompressedTextureLoader;
  24930. }());
  24931. /**
  24932. * Creates base-textures and textures for each compressed-texture resource and adds them into the global
  24933. * texture cache. The first texture has two IDs - `${url}`, `${url}-1`; while the rest have an ID of the
  24934. * form `${url}-i`.
  24935. * @param url - the original address of the resources
  24936. * @param resources - the resources backing texture data
  24937. * @ignore
  24938. */
  24939. function registerCompressedTextures(url, resources, metadata) {
  24940. var result = {
  24941. textures: {},
  24942. texture: null,
  24943. };
  24944. if (!resources) {
  24945. return result;
  24946. }
  24947. var textures = resources.map(function (resource) {
  24948. return (new Texture(new BaseTexture(resource, Object.assign({
  24949. mipmap: MIPMAP_MODES.OFF,
  24950. alphaMode: ALPHA_MODES.NO_PREMULTIPLIED_ALPHA
  24951. }, metadata))));
  24952. });
  24953. textures.forEach(function (texture, i) {
  24954. var baseTexture = texture.baseTexture;
  24955. var cacheID = url + "-" + (i + 1);
  24956. BaseTexture.addToCache(baseTexture, cacheID);
  24957. Texture.addToCache(texture, cacheID);
  24958. if (i === 0) {
  24959. BaseTexture.addToCache(baseTexture, url);
  24960. Texture.addToCache(texture, url);
  24961. result.texture = texture;
  24962. }
  24963. result.textures[cacheID] = texture;
  24964. });
  24965. return result;
  24966. }
  24967. var _a$1, _b$1;
  24968. var DDS_MAGIC_SIZE = 4;
  24969. var DDS_HEADER_SIZE = 124;
  24970. var DDS_HEADER_PF_SIZE = 32;
  24971. var DDS_HEADER_DX10_SIZE = 20;
  24972. // DDS file format magic word
  24973. var DDS_MAGIC = 0x20534444;
  24974. /**
  24975. * DWORD offsets of the DDS file header fields (relative to file start).
  24976. * @ignore
  24977. */
  24978. var DDS_FIELDS = {
  24979. SIZE: 1,
  24980. FLAGS: 2,
  24981. HEIGHT: 3,
  24982. WIDTH: 4,
  24983. MIPMAP_COUNT: 7,
  24984. PIXEL_FORMAT: 19,
  24985. };
  24986. /**
  24987. * DWORD offsets of the DDS PIXEL_FORMAT fields.
  24988. * @ignore
  24989. */
  24990. var DDS_PF_FIELDS = {
  24991. SIZE: 0,
  24992. FLAGS: 1,
  24993. FOURCC: 2,
  24994. RGB_BITCOUNT: 3,
  24995. R_BIT_MASK: 4,
  24996. G_BIT_MASK: 5,
  24997. B_BIT_MASK: 6,
  24998. A_BIT_MASK: 7
  24999. };
  25000. /**
  25001. * DWORD offsets of the DDS_HEADER_DX10 fields.
  25002. * @ignore
  25003. */
  25004. var DDS_DX10_FIELDS = {
  25005. DXGI_FORMAT: 0,
  25006. RESOURCE_DIMENSION: 1,
  25007. MISC_FLAG: 2,
  25008. ARRAY_SIZE: 3,
  25009. MISC_FLAGS2: 4
  25010. };
  25011. /**
  25012. * @see https://docs.microsoft.com/en-us/windows/win32/api/dxgiformat/ne-dxgiformat-dxgi_format
  25013. * @ignore
  25014. */
  25015. // This is way over-blown for us! Lend us a hand, and remove the ones that aren't used (but set the remaining
  25016. // ones to their correct value)
  25017. var DXGI_FORMAT;
  25018. (function (DXGI_FORMAT) {
  25019. DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_UNKNOWN"] = 0] = "DXGI_FORMAT_UNKNOWN";
  25020. DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R32G32B32A32_TYPELESS"] = 1] = "DXGI_FORMAT_R32G32B32A32_TYPELESS";
  25021. DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R32G32B32A32_FLOAT"] = 2] = "DXGI_FORMAT_R32G32B32A32_FLOAT";
  25022. DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R32G32B32A32_UINT"] = 3] = "DXGI_FORMAT_R32G32B32A32_UINT";
  25023. DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R32G32B32A32_SINT"] = 4] = "DXGI_FORMAT_R32G32B32A32_SINT";
  25024. DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R32G32B32_TYPELESS"] = 5] = "DXGI_FORMAT_R32G32B32_TYPELESS";
  25025. DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R32G32B32_FLOAT"] = 6] = "DXGI_FORMAT_R32G32B32_FLOAT";
  25026. DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R32G32B32_UINT"] = 7] = "DXGI_FORMAT_R32G32B32_UINT";
  25027. DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R32G32B32_SINT"] = 8] = "DXGI_FORMAT_R32G32B32_SINT";
  25028. DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R16G16B16A16_TYPELESS"] = 9] = "DXGI_FORMAT_R16G16B16A16_TYPELESS";
  25029. DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R16G16B16A16_FLOAT"] = 10] = "DXGI_FORMAT_R16G16B16A16_FLOAT";
  25030. DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R16G16B16A16_UNORM"] = 11] = "DXGI_FORMAT_R16G16B16A16_UNORM";
  25031. DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R16G16B16A16_UINT"] = 12] = "DXGI_FORMAT_R16G16B16A16_UINT";
  25032. DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R16G16B16A16_SNORM"] = 13] = "DXGI_FORMAT_R16G16B16A16_SNORM";
  25033. DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R16G16B16A16_SINT"] = 14] = "DXGI_FORMAT_R16G16B16A16_SINT";
  25034. DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R32G32_TYPELESS"] = 15] = "DXGI_FORMAT_R32G32_TYPELESS";
  25035. DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R32G32_FLOAT"] = 16] = "DXGI_FORMAT_R32G32_FLOAT";
  25036. DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R32G32_UINT"] = 17] = "DXGI_FORMAT_R32G32_UINT";
  25037. DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R32G32_SINT"] = 18] = "DXGI_FORMAT_R32G32_SINT";
  25038. DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R32G8X24_TYPELESS"] = 19] = "DXGI_FORMAT_R32G8X24_TYPELESS";
  25039. DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_D32_FLOAT_S8X24_UINT"] = 20] = "DXGI_FORMAT_D32_FLOAT_S8X24_UINT";
  25040. DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS"] = 21] = "DXGI_FORMAT_R32_FLOAT_X8X24_TYPELESS";
  25041. DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_X32_TYPELESS_G8X24_UINT"] = 22] = "DXGI_FORMAT_X32_TYPELESS_G8X24_UINT";
  25042. DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R10G10B10A2_TYPELESS"] = 23] = "DXGI_FORMAT_R10G10B10A2_TYPELESS";
  25043. DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R10G10B10A2_UNORM"] = 24] = "DXGI_FORMAT_R10G10B10A2_UNORM";
  25044. DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R10G10B10A2_UINT"] = 25] = "DXGI_FORMAT_R10G10B10A2_UINT";
  25045. DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R11G11B10_FLOAT"] = 26] = "DXGI_FORMAT_R11G11B10_FLOAT";
  25046. DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R8G8B8A8_TYPELESS"] = 27] = "DXGI_FORMAT_R8G8B8A8_TYPELESS";
  25047. DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R8G8B8A8_UNORM"] = 28] = "DXGI_FORMAT_R8G8B8A8_UNORM";
  25048. DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R8G8B8A8_UNORM_SRGB"] = 29] = "DXGI_FORMAT_R8G8B8A8_UNORM_SRGB";
  25049. DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R8G8B8A8_UINT"] = 30] = "DXGI_FORMAT_R8G8B8A8_UINT";
  25050. DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R8G8B8A8_SNORM"] = 31] = "DXGI_FORMAT_R8G8B8A8_SNORM";
  25051. DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R8G8B8A8_SINT"] = 32] = "DXGI_FORMAT_R8G8B8A8_SINT";
  25052. DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R16G16_TYPELESS"] = 33] = "DXGI_FORMAT_R16G16_TYPELESS";
  25053. DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R16G16_FLOAT"] = 34] = "DXGI_FORMAT_R16G16_FLOAT";
  25054. DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R16G16_UNORM"] = 35] = "DXGI_FORMAT_R16G16_UNORM";
  25055. DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R16G16_UINT"] = 36] = "DXGI_FORMAT_R16G16_UINT";
  25056. DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R16G16_SNORM"] = 37] = "DXGI_FORMAT_R16G16_SNORM";
  25057. DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R16G16_SINT"] = 38] = "DXGI_FORMAT_R16G16_SINT";
  25058. DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R32_TYPELESS"] = 39] = "DXGI_FORMAT_R32_TYPELESS";
  25059. DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_D32_FLOAT"] = 40] = "DXGI_FORMAT_D32_FLOAT";
  25060. DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R32_FLOAT"] = 41] = "DXGI_FORMAT_R32_FLOAT";
  25061. DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R32_UINT"] = 42] = "DXGI_FORMAT_R32_UINT";
  25062. DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R32_SINT"] = 43] = "DXGI_FORMAT_R32_SINT";
  25063. DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R24G8_TYPELESS"] = 44] = "DXGI_FORMAT_R24G8_TYPELESS";
  25064. DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_D24_UNORM_S8_UINT"] = 45] = "DXGI_FORMAT_D24_UNORM_S8_UINT";
  25065. DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R24_UNORM_X8_TYPELESS"] = 46] = "DXGI_FORMAT_R24_UNORM_X8_TYPELESS";
  25066. DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_X24_TYPELESS_G8_UINT"] = 47] = "DXGI_FORMAT_X24_TYPELESS_G8_UINT";
  25067. DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R8G8_TYPELESS"] = 48] = "DXGI_FORMAT_R8G8_TYPELESS";
  25068. DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R8G8_UNORM"] = 49] = "DXGI_FORMAT_R8G8_UNORM";
  25069. DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R8G8_UINT"] = 50] = "DXGI_FORMAT_R8G8_UINT";
  25070. DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R8G8_SNORM"] = 51] = "DXGI_FORMAT_R8G8_SNORM";
  25071. DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R8G8_SINT"] = 52] = "DXGI_FORMAT_R8G8_SINT";
  25072. DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R16_TYPELESS"] = 53] = "DXGI_FORMAT_R16_TYPELESS";
  25073. DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R16_FLOAT"] = 54] = "DXGI_FORMAT_R16_FLOAT";
  25074. DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_D16_UNORM"] = 55] = "DXGI_FORMAT_D16_UNORM";
  25075. DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R16_UNORM"] = 56] = "DXGI_FORMAT_R16_UNORM";
  25076. DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R16_UINT"] = 57] = "DXGI_FORMAT_R16_UINT";
  25077. DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R16_SNORM"] = 58] = "DXGI_FORMAT_R16_SNORM";
  25078. DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R16_SINT"] = 59] = "DXGI_FORMAT_R16_SINT";
  25079. DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R8_TYPELESS"] = 60] = "DXGI_FORMAT_R8_TYPELESS";
  25080. DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R8_UNORM"] = 61] = "DXGI_FORMAT_R8_UNORM";
  25081. DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R8_UINT"] = 62] = "DXGI_FORMAT_R8_UINT";
  25082. DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R8_SNORM"] = 63] = "DXGI_FORMAT_R8_SNORM";
  25083. DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R8_SINT"] = 64] = "DXGI_FORMAT_R8_SINT";
  25084. DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_A8_UNORM"] = 65] = "DXGI_FORMAT_A8_UNORM";
  25085. DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R1_UNORM"] = 66] = "DXGI_FORMAT_R1_UNORM";
  25086. DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R9G9B9E5_SHAREDEXP"] = 67] = "DXGI_FORMAT_R9G9B9E5_SHAREDEXP";
  25087. DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R8G8_B8G8_UNORM"] = 68] = "DXGI_FORMAT_R8G8_B8G8_UNORM";
  25088. DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_G8R8_G8B8_UNORM"] = 69] = "DXGI_FORMAT_G8R8_G8B8_UNORM";
  25089. DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_BC1_TYPELESS"] = 70] = "DXGI_FORMAT_BC1_TYPELESS";
  25090. DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_BC1_UNORM"] = 71] = "DXGI_FORMAT_BC1_UNORM";
  25091. DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_BC1_UNORM_SRGB"] = 72] = "DXGI_FORMAT_BC1_UNORM_SRGB";
  25092. DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_BC2_TYPELESS"] = 73] = "DXGI_FORMAT_BC2_TYPELESS";
  25093. DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_BC2_UNORM"] = 74] = "DXGI_FORMAT_BC2_UNORM";
  25094. DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_BC2_UNORM_SRGB"] = 75] = "DXGI_FORMAT_BC2_UNORM_SRGB";
  25095. DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_BC3_TYPELESS"] = 76] = "DXGI_FORMAT_BC3_TYPELESS";
  25096. DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_BC3_UNORM"] = 77] = "DXGI_FORMAT_BC3_UNORM";
  25097. DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_BC3_UNORM_SRGB"] = 78] = "DXGI_FORMAT_BC3_UNORM_SRGB";
  25098. DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_BC4_TYPELESS"] = 79] = "DXGI_FORMAT_BC4_TYPELESS";
  25099. DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_BC4_UNORM"] = 80] = "DXGI_FORMAT_BC4_UNORM";
  25100. DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_BC4_SNORM"] = 81] = "DXGI_FORMAT_BC4_SNORM";
  25101. DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_BC5_TYPELESS"] = 82] = "DXGI_FORMAT_BC5_TYPELESS";
  25102. DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_BC5_UNORM"] = 83] = "DXGI_FORMAT_BC5_UNORM";
  25103. DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_BC5_SNORM"] = 84] = "DXGI_FORMAT_BC5_SNORM";
  25104. DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_B5G6R5_UNORM"] = 85] = "DXGI_FORMAT_B5G6R5_UNORM";
  25105. DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_B5G5R5A1_UNORM"] = 86] = "DXGI_FORMAT_B5G5R5A1_UNORM";
  25106. DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_B8G8R8A8_UNORM"] = 87] = "DXGI_FORMAT_B8G8R8A8_UNORM";
  25107. DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_B8G8R8X8_UNORM"] = 88] = "DXGI_FORMAT_B8G8R8X8_UNORM";
  25108. DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_R10G10B10_XR_BIAS_A2_UNORM"] = 89] = "DXGI_FORMAT_R10G10B10_XR_BIAS_A2_UNORM";
  25109. DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_B8G8R8A8_TYPELESS"] = 90] = "DXGI_FORMAT_B8G8R8A8_TYPELESS";
  25110. DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_B8G8R8A8_UNORM_SRGB"] = 91] = "DXGI_FORMAT_B8G8R8A8_UNORM_SRGB";
  25111. DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_B8G8R8X8_TYPELESS"] = 92] = "DXGI_FORMAT_B8G8R8X8_TYPELESS";
  25112. DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_B8G8R8X8_UNORM_SRGB"] = 93] = "DXGI_FORMAT_B8G8R8X8_UNORM_SRGB";
  25113. DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_BC6H_TYPELESS"] = 94] = "DXGI_FORMAT_BC6H_TYPELESS";
  25114. DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_BC6H_UF16"] = 95] = "DXGI_FORMAT_BC6H_UF16";
  25115. DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_BC6H_SF16"] = 96] = "DXGI_FORMAT_BC6H_SF16";
  25116. DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_BC7_TYPELESS"] = 97] = "DXGI_FORMAT_BC7_TYPELESS";
  25117. DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_BC7_UNORM"] = 98] = "DXGI_FORMAT_BC7_UNORM";
  25118. DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_BC7_UNORM_SRGB"] = 99] = "DXGI_FORMAT_BC7_UNORM_SRGB";
  25119. DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_AYUV"] = 100] = "DXGI_FORMAT_AYUV";
  25120. DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_Y410"] = 101] = "DXGI_FORMAT_Y410";
  25121. DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_Y416"] = 102] = "DXGI_FORMAT_Y416";
  25122. DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_NV12"] = 103] = "DXGI_FORMAT_NV12";
  25123. DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_P010"] = 104] = "DXGI_FORMAT_P010";
  25124. DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_P016"] = 105] = "DXGI_FORMAT_P016";
  25125. DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_420_OPAQUE"] = 106] = "DXGI_FORMAT_420_OPAQUE";
  25126. DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_YUY2"] = 107] = "DXGI_FORMAT_YUY2";
  25127. DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_Y210"] = 108] = "DXGI_FORMAT_Y210";
  25128. DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_Y216"] = 109] = "DXGI_FORMAT_Y216";
  25129. DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_NV11"] = 110] = "DXGI_FORMAT_NV11";
  25130. DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_AI44"] = 111] = "DXGI_FORMAT_AI44";
  25131. DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_IA44"] = 112] = "DXGI_FORMAT_IA44";
  25132. DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_P8"] = 113] = "DXGI_FORMAT_P8";
  25133. DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_A8P8"] = 114] = "DXGI_FORMAT_A8P8";
  25134. DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_B4G4R4A4_UNORM"] = 115] = "DXGI_FORMAT_B4G4R4A4_UNORM";
  25135. DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_P208"] = 116] = "DXGI_FORMAT_P208";
  25136. DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_V208"] = 117] = "DXGI_FORMAT_V208";
  25137. DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_V408"] = 118] = "DXGI_FORMAT_V408";
  25138. DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_SAMPLER_FEEDBACK_MIN_MIP_OPAQUE"] = 119] = "DXGI_FORMAT_SAMPLER_FEEDBACK_MIN_MIP_OPAQUE";
  25139. DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_SAMPLER_FEEDBACK_MIP_REGION_USED_OPAQUE"] = 120] = "DXGI_FORMAT_SAMPLER_FEEDBACK_MIP_REGION_USED_OPAQUE";
  25140. DXGI_FORMAT[DXGI_FORMAT["DXGI_FORMAT_FORCE_UINT"] = 121] = "DXGI_FORMAT_FORCE_UINT";
  25141. })(DXGI_FORMAT || (DXGI_FORMAT = {}));
  25142. /**
  25143. * Possible values of the field {@link DDS_DX10_FIELDS.RESOURCE_DIMENSION}
  25144. * @ignore
  25145. */
  25146. var D3D10_RESOURCE_DIMENSION;
  25147. (function (D3D10_RESOURCE_DIMENSION) {
  25148. D3D10_RESOURCE_DIMENSION[D3D10_RESOURCE_DIMENSION["DDS_DIMENSION_TEXTURE1D"] = 2] = "DDS_DIMENSION_TEXTURE1D";
  25149. D3D10_RESOURCE_DIMENSION[D3D10_RESOURCE_DIMENSION["DDS_DIMENSION_TEXTURE2D"] = 3] = "DDS_DIMENSION_TEXTURE2D";
  25150. D3D10_RESOURCE_DIMENSION[D3D10_RESOURCE_DIMENSION["DDS_DIMENSION_TEXTURE3D"] = 6] = "DDS_DIMENSION_TEXTURE3D";
  25151. })(D3D10_RESOURCE_DIMENSION || (D3D10_RESOURCE_DIMENSION = {}));
  25152. var PF_FLAGS = 1;
  25153. // PIXEL_FORMAT flags
  25154. var DDPF_ALPHA = 0x2;
  25155. var DDPF_FOURCC = 0x4;
  25156. var DDPF_RGB = 0x40;
  25157. var DDPF_YUV = 0x200;
  25158. var DDPF_LUMINANCE = 0x20000;
  25159. // Four character codes for DXTn formats
  25160. var FOURCC_DXT1 = 0x31545844;
  25161. var FOURCC_DXT3 = 0x33545844;
  25162. var FOURCC_DXT5 = 0x35545844;
  25163. var FOURCC_DX10 = 0x30315844;
  25164. // Cubemap texture flag (for DDS_DX10_FIELDS.MISC_FLAG)
  25165. var DDS_RESOURCE_MISC_TEXTURECUBE = 0x4;
  25166. /**
  25167. * Maps `FOURCC_*` formats to internal formats (see {@link PIXI.INTERNAL_FORMATS}).
  25168. * @ignore
  25169. */
  25170. var FOURCC_TO_FORMAT = (_a$1 = {},
  25171. _a$1[FOURCC_DXT1] = INTERNAL_FORMATS.COMPRESSED_RGBA_S3TC_DXT1_EXT,
  25172. _a$1[FOURCC_DXT3] = INTERNAL_FORMATS.COMPRESSED_RGBA_S3TC_DXT3_EXT,
  25173. _a$1[FOURCC_DXT5] = INTERNAL_FORMATS.COMPRESSED_RGBA_S3TC_DXT5_EXT,
  25174. _a$1);
  25175. /**
  25176. * Maps {@link DXGI_FORMAT} to types/internal-formats (see {@link PIXI.TYPES}, {@link PIXI.INTERNAL_FORMATS})
  25177. * @ignore
  25178. */
  25179. var DXGI_TO_FORMAT = (_b$1 = {},
  25180. // WEBGL_compressed_texture_s3tc
  25181. _b$1[DXGI_FORMAT.DXGI_FORMAT_BC1_TYPELESS] = INTERNAL_FORMATS.COMPRESSED_RGBA_S3TC_DXT1_EXT,
  25182. _b$1[DXGI_FORMAT.DXGI_FORMAT_BC1_UNORM] = INTERNAL_FORMATS.COMPRESSED_RGBA_S3TC_DXT1_EXT,
  25183. _b$1[DXGI_FORMAT.DXGI_FORMAT_BC2_TYPELESS] = INTERNAL_FORMATS.COMPRESSED_RGBA_S3TC_DXT3_EXT,
  25184. _b$1[DXGI_FORMAT.DXGI_FORMAT_BC2_UNORM] = INTERNAL_FORMATS.COMPRESSED_RGBA_S3TC_DXT3_EXT,
  25185. _b$1[DXGI_FORMAT.DXGI_FORMAT_BC3_TYPELESS] = INTERNAL_FORMATS.COMPRESSED_RGBA_S3TC_DXT5_EXT,
  25186. _b$1[DXGI_FORMAT.DXGI_FORMAT_BC3_UNORM] = INTERNAL_FORMATS.COMPRESSED_RGBA_S3TC_DXT5_EXT,
  25187. // WEBGL_compressed_texture_s3tc_srgb
  25188. _b$1[DXGI_FORMAT.DXGI_FORMAT_BC1_UNORM_SRGB] = INTERNAL_FORMATS.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT,
  25189. _b$1[DXGI_FORMAT.DXGI_FORMAT_BC2_UNORM_SRGB] = INTERNAL_FORMATS.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT,
  25190. _b$1[DXGI_FORMAT.DXGI_FORMAT_BC3_UNORM_SRGB] = INTERNAL_FORMATS.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT,
  25191. _b$1);
  25192. /**
  25193. * @class
  25194. * @memberof PIXI
  25195. * @implements {PIXI.ILoaderPlugin}
  25196. * @see https://docs.microsoft.com/en-us/windows/win32/direct3ddds/dx-graphics-dds-pguide
  25197. */
  25198. /**
  25199. * Parses the DDS file header, generates base-textures, and puts them into the texture cache.
  25200. * @param arrayBuffer
  25201. */
  25202. function parseDDS(arrayBuffer) {
  25203. var data = new Uint32Array(arrayBuffer);
  25204. var magicWord = data[0];
  25205. if (magicWord !== DDS_MAGIC) {
  25206. throw new Error('Invalid DDS file magic word');
  25207. }
  25208. var header = new Uint32Array(arrayBuffer, 0, DDS_HEADER_SIZE / Uint32Array.BYTES_PER_ELEMENT);
  25209. // DDS header fields
  25210. var height = header[DDS_FIELDS.HEIGHT];
  25211. var width = header[DDS_FIELDS.WIDTH];
  25212. var mipmapCount = header[DDS_FIELDS.MIPMAP_COUNT];
  25213. // PIXEL_FORMAT fields
  25214. var pixelFormat = new Uint32Array(arrayBuffer, DDS_FIELDS.PIXEL_FORMAT * Uint32Array.BYTES_PER_ELEMENT, DDS_HEADER_PF_SIZE / Uint32Array.BYTES_PER_ELEMENT);
  25215. var formatFlags = pixelFormat[PF_FLAGS];
  25216. // File contains compressed texture(s)
  25217. if (formatFlags & DDPF_FOURCC) {
  25218. var fourCC = pixelFormat[DDS_PF_FIELDS.FOURCC];
  25219. // File contains one DXTn compressed texture
  25220. if (fourCC !== FOURCC_DX10) {
  25221. var internalFormat_1 = FOURCC_TO_FORMAT[fourCC];
  25222. var dataOffset_1 = DDS_MAGIC_SIZE + DDS_HEADER_SIZE;
  25223. var texData = new Uint8Array(arrayBuffer, dataOffset_1);
  25224. var resource = new CompressedTextureResource(texData, {
  25225. format: internalFormat_1,
  25226. width: width,
  25227. height: height,
  25228. levels: mipmapCount // CompressedTextureResource will separate the levelBuffers for us!
  25229. });
  25230. return [resource];
  25231. }
  25232. // FOURCC_DX10 indicates there is a 20-byte DDS_HEADER_DX10 after DDS_HEADER
  25233. var dx10Offset = DDS_MAGIC_SIZE + DDS_HEADER_SIZE;
  25234. var dx10Header = new Uint32Array(data.buffer, dx10Offset, DDS_HEADER_DX10_SIZE / Uint32Array.BYTES_PER_ELEMENT);
  25235. var dxgiFormat = dx10Header[DDS_DX10_FIELDS.DXGI_FORMAT];
  25236. var resourceDimension = dx10Header[DDS_DX10_FIELDS.RESOURCE_DIMENSION];
  25237. var miscFlag = dx10Header[DDS_DX10_FIELDS.MISC_FLAG];
  25238. var arraySize = dx10Header[DDS_DX10_FIELDS.ARRAY_SIZE];
  25239. // Map dxgiFormat to PIXI.INTERNAL_FORMATS
  25240. var internalFormat_2 = DXGI_TO_FORMAT[dxgiFormat];
  25241. if (internalFormat_2 === undefined) {
  25242. throw new Error("DDSParser cannot parse texture data with DXGI format " + dxgiFormat);
  25243. }
  25244. if (miscFlag === DDS_RESOURCE_MISC_TEXTURECUBE) {
  25245. // FIXME: Anybody excited about cubemap compressed textures?
  25246. throw new Error('DDSParser does not support cubemap textures');
  25247. }
  25248. if (resourceDimension === D3D10_RESOURCE_DIMENSION.DDS_DIMENSION_TEXTURE3D) {
  25249. // FIXME: Anybody excited about 3D compressed textures?
  25250. throw new Error('DDSParser does not supported 3D texture data');
  25251. }
  25252. // Uint8Array buffers of image data, including all mipmap levels in each image
  25253. var imageBuffers = new Array();
  25254. var dataOffset = DDS_MAGIC_SIZE
  25255. + DDS_HEADER_SIZE
  25256. + DDS_HEADER_DX10_SIZE;
  25257. if (arraySize === 1) {
  25258. // No need bothering with the imageSize calculation!
  25259. imageBuffers.push(new Uint8Array(arrayBuffer, dataOffset));
  25260. }
  25261. else {
  25262. // Calculate imageSize for each texture, and then locate each image's texture data
  25263. var pixelSize = INTERNAL_FORMAT_TO_BYTES_PER_PIXEL[internalFormat_2];
  25264. var imageSize = 0;
  25265. var levelWidth = width;
  25266. var levelHeight = height;
  25267. for (var i = 0; i < mipmapCount; i++) {
  25268. var alignedLevelWidth = Math.max(1, (levelWidth + 3) & ~3);
  25269. var alignedLevelHeight = Math.max(1, (levelHeight + 3) & ~3);
  25270. var levelSize = alignedLevelWidth * alignedLevelHeight * pixelSize;
  25271. imageSize += levelSize;
  25272. levelWidth = levelWidth >>> 1;
  25273. levelHeight = levelHeight >>> 1;
  25274. }
  25275. var imageOffset = dataOffset;
  25276. // NOTE: Cubemaps have 6-images per texture (but they aren't supported so ^_^)
  25277. for (var i = 0; i < arraySize; i++) {
  25278. imageBuffers.push(new Uint8Array(arrayBuffer, imageOffset, imageSize));
  25279. imageOffset += imageSize;
  25280. }
  25281. }
  25282. // Uint8Array -> CompressedTextureResource, and we're done!
  25283. return imageBuffers.map(function (buffer) { return new CompressedTextureResource(buffer, {
  25284. format: internalFormat_2,
  25285. width: width,
  25286. height: height,
  25287. levels: mipmapCount
  25288. }); });
  25289. }
  25290. if (formatFlags & DDPF_RGB) {
  25291. // FIXME: We might want to allow uncompressed *.dds files?
  25292. throw new Error('DDSParser does not support uncompressed texture data.');
  25293. }
  25294. if (formatFlags & DDPF_YUV) {
  25295. // FIXME: Does anybody need this feature?
  25296. throw new Error('DDSParser does not supported YUV uncompressed texture data.');
  25297. }
  25298. if (formatFlags & DDPF_LUMINANCE) {
  25299. // FIXME: Microsoft says older DDS filers use this feature! Probably not worth the effort!
  25300. throw new Error('DDSParser does not support single-channel (lumninance) texture data!');
  25301. }
  25302. if (formatFlags & DDPF_ALPHA) {
  25303. // FIXME: I'm tired! See above =)
  25304. throw new Error('DDSParser does not support single-channel (alpha) texture data!');
  25305. }
  25306. throw new Error('DDSParser failed to load a texture file due to an unknown reason!');
  25307. }
  25308. var _a$3, _b, _c;
  25309. /**
  25310. * The 12-byte KTX file identifier
  25311. * @see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/#2.1
  25312. * @ignore
  25313. */
  25314. var FILE_IDENTIFIER = [0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A];
  25315. /**
  25316. * The value stored in the "endianness" field.
  25317. * @see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/#2.2
  25318. * @ignore
  25319. */
  25320. var ENDIANNESS = 0x04030201;
  25321. /**
  25322. * Byte offsets of the KTX file header fields
  25323. * @ignore
  25324. */
  25325. var KTX_FIELDS = {
  25326. FILE_IDENTIFIER: 0,
  25327. ENDIANNESS: 12,
  25328. GL_TYPE: 16,
  25329. GL_TYPE_SIZE: 20,
  25330. GL_FORMAT: 24,
  25331. GL_INTERNAL_FORMAT: 28,
  25332. GL_BASE_INTERNAL_FORMAT: 32,
  25333. PIXEL_WIDTH: 36,
  25334. PIXEL_HEIGHT: 40,
  25335. PIXEL_DEPTH: 44,
  25336. NUMBER_OF_ARRAY_ELEMENTS: 48,
  25337. NUMBER_OF_FACES: 52,
  25338. NUMBER_OF_MIPMAP_LEVELS: 56,
  25339. BYTES_OF_KEY_VALUE_DATA: 60
  25340. };
  25341. /**
  25342. * Byte size of the file header fields in {@code KTX_FIELDS}
  25343. * @ignore
  25344. */
  25345. var FILE_HEADER_SIZE = 64;
  25346. /**
  25347. * Maps {@link PIXI.TYPES} to the bytes taken per component, excluding those ones that are bit-fields.
  25348. * @ignore
  25349. */
  25350. var TYPES_TO_BYTES_PER_COMPONENT = (_a$3 = {},
  25351. _a$3[TYPES.UNSIGNED_BYTE] = 1,
  25352. _a$3[TYPES.UNSIGNED_SHORT] = 2,
  25353. _a$3[TYPES.INT] = 4,
  25354. _a$3[TYPES.UNSIGNED_INT] = 4,
  25355. _a$3[TYPES.FLOAT] = 4,
  25356. _a$3[TYPES.HALF_FLOAT] = 8,
  25357. _a$3);
  25358. /**
  25359. * Number of components in each {@link PIXI.FORMATS}
  25360. * @ignore
  25361. */
  25362. var FORMATS_TO_COMPONENTS = (_b = {},
  25363. _b[FORMATS.RGBA] = 4,
  25364. _b[FORMATS.RGB] = 3,
  25365. _b[FORMATS.RG] = 2,
  25366. _b[FORMATS.RED] = 1,
  25367. _b[FORMATS.LUMINANCE] = 1,
  25368. _b[FORMATS.LUMINANCE_ALPHA] = 2,
  25369. _b[FORMATS.ALPHA] = 1,
  25370. _b);
  25371. /**
  25372. * Number of bytes per pixel in bit-field types in {@link PIXI.TYPES}
  25373. * @ignore
  25374. */
  25375. var TYPES_TO_BYTES_PER_PIXEL = (_c = {},
  25376. _c[TYPES.UNSIGNED_SHORT_4_4_4_4] = 2,
  25377. _c[TYPES.UNSIGNED_SHORT_5_5_5_1] = 2,
  25378. _c[TYPES.UNSIGNED_SHORT_5_6_5] = 2,
  25379. _c);
  25380. function parseKTX(url, arrayBuffer, loadKeyValueData) {
  25381. if (loadKeyValueData === void 0) { loadKeyValueData = false; }
  25382. var dataView = new DataView(arrayBuffer);
  25383. if (!validate(url, dataView)) {
  25384. return null;
  25385. }
  25386. var littleEndian = dataView.getUint32(KTX_FIELDS.ENDIANNESS, true) === ENDIANNESS;
  25387. var glType = dataView.getUint32(KTX_FIELDS.GL_TYPE, littleEndian);
  25388. // const glTypeSize = dataView.getUint32(KTX_FIELDS.GL_TYPE_SIZE, littleEndian);
  25389. var glFormat = dataView.getUint32(KTX_FIELDS.GL_FORMAT, littleEndian);
  25390. var glInternalFormat = dataView.getUint32(KTX_FIELDS.GL_INTERNAL_FORMAT, littleEndian);
  25391. var pixelWidth = dataView.getUint32(KTX_FIELDS.PIXEL_WIDTH, littleEndian);
  25392. var pixelHeight = dataView.getUint32(KTX_FIELDS.PIXEL_HEIGHT, littleEndian) || 1; // "pixelHeight = 0" -> "1"
  25393. var pixelDepth = dataView.getUint32(KTX_FIELDS.PIXEL_DEPTH, littleEndian) || 1; // ^^
  25394. var numberOfArrayElements = dataView.getUint32(KTX_FIELDS.NUMBER_OF_ARRAY_ELEMENTS, littleEndian) || 1; // ^^
  25395. var numberOfFaces = dataView.getUint32(KTX_FIELDS.NUMBER_OF_FACES, littleEndian);
  25396. var numberOfMipmapLevels = dataView.getUint32(KTX_FIELDS.NUMBER_OF_MIPMAP_LEVELS, littleEndian);
  25397. var bytesOfKeyValueData = dataView.getUint32(KTX_FIELDS.BYTES_OF_KEY_VALUE_DATA, littleEndian);
  25398. // Whether the platform architecture is little endian. If littleEndian !== platformLittleEndian, then the
  25399. // file contents must be endian-converted!
  25400. // TODO: Endianness conversion
  25401. // const platformLittleEndian = new Uint8Array((new Uint32Array([ENDIANNESS])).buffer)[0] === 0x01;
  25402. if (pixelHeight === 0 || pixelDepth !== 1) {
  25403. throw new Error('Only 2D textures are supported');
  25404. }
  25405. if (numberOfFaces !== 1) {
  25406. throw new Error('CubeTextures are not supported by KTXLoader yet!');
  25407. }
  25408. if (numberOfArrayElements !== 1) {
  25409. // TODO: Support splitting array-textures into multiple BaseTextures
  25410. throw new Error('WebGL does not support array textures');
  25411. }
  25412. // TODO: 8x4 blocks for 2bpp pvrtc
  25413. var blockWidth = 4;
  25414. var blockHeight = 4;
  25415. var alignedWidth = (pixelWidth + 3) & ~3;
  25416. var alignedHeight = (pixelHeight + 3) & ~3;
  25417. var imageBuffers = new Array(numberOfArrayElements);
  25418. var imagePixels = pixelWidth * pixelHeight;
  25419. if (glType === 0) {
  25420. // Align to 16 pixels (4x4 blocks)
  25421. imagePixels = alignedWidth * alignedHeight;
  25422. }
  25423. var imagePixelByteSize;
  25424. if (glType !== 0) {
  25425. // Uncompressed texture format
  25426. if (TYPES_TO_BYTES_PER_COMPONENT[glType]) {
  25427. imagePixelByteSize = TYPES_TO_BYTES_PER_COMPONENT[glType] * FORMATS_TO_COMPONENTS[glFormat];
  25428. }
  25429. else {
  25430. imagePixelByteSize = TYPES_TO_BYTES_PER_PIXEL[glType];
  25431. }
  25432. }
  25433. else {
  25434. imagePixelByteSize = INTERNAL_FORMAT_TO_BYTES_PER_PIXEL[glInternalFormat];
  25435. }
  25436. if (imagePixelByteSize === undefined) {
  25437. throw new Error('Unable to resolve the pixel format stored in the *.ktx file!');
  25438. }
  25439. var kvData = loadKeyValueData
  25440. ? parseKvData(dataView, bytesOfKeyValueData, littleEndian)
  25441. : null;
  25442. var imageByteSize = imagePixels * imagePixelByteSize;
  25443. var mipByteSize = imageByteSize;
  25444. var mipWidth = pixelWidth;
  25445. var mipHeight = pixelHeight;
  25446. var alignedMipWidth = alignedWidth;
  25447. var alignedMipHeight = alignedHeight;
  25448. var imageOffset = FILE_HEADER_SIZE + bytesOfKeyValueData;
  25449. for (var mipmapLevel = 0; mipmapLevel < numberOfMipmapLevels; mipmapLevel++) {
  25450. var imageSize = dataView.getUint32(imageOffset, littleEndian);
  25451. var elementOffset = imageOffset + 4;
  25452. for (var arrayElement = 0; arrayElement < numberOfArrayElements; arrayElement++) {
  25453. // TODO: Maybe support 3D textures? :-)
  25454. // for (let zSlice = 0; zSlice < pixelDepth; zSlice)
  25455. var mips = imageBuffers[arrayElement];
  25456. if (!mips) {
  25457. mips = imageBuffers[arrayElement] = new Array(numberOfMipmapLevels);
  25458. }
  25459. mips[mipmapLevel] = {
  25460. levelID: mipmapLevel,
  25461. // don't align mipWidth when texture not compressed! (glType not zero)
  25462. levelWidth: numberOfMipmapLevels > 1 || glType !== 0 ? mipWidth : alignedMipWidth,
  25463. levelHeight: numberOfMipmapLevels > 1 || glType !== 0 ? mipHeight : alignedMipHeight,
  25464. levelBuffer: new Uint8Array(arrayBuffer, elementOffset, mipByteSize)
  25465. };
  25466. elementOffset += mipByteSize;
  25467. }
  25468. // HINT: Aligns to 4-byte boundary after jumping imageSize (in lieu of mipPadding)
  25469. imageOffset += imageSize + 4; // (+4 to jump the imageSize field itself)
  25470. imageOffset = imageOffset % 4 !== 0 ? imageOffset + 4 - (imageOffset % 4) : imageOffset;
  25471. // Calculate mipWidth, mipHeight for _next_ iteration
  25472. mipWidth = (mipWidth >> 1) || 1;
  25473. mipHeight = (mipHeight >> 1) || 1;
  25474. alignedMipWidth = (mipWidth + blockWidth - 1) & ~(blockWidth - 1);
  25475. alignedMipHeight = (mipHeight + blockHeight - 1) & ~(blockHeight - 1);
  25476. // Each mipmap level is 4-times smaller?
  25477. mipByteSize = alignedMipWidth * alignedMipHeight * imagePixelByteSize;
  25478. }
  25479. // We use the levelBuffers feature of CompressedTextureResource b/c texture data is image-major, not level-major.
  25480. if (glType !== 0) {
  25481. return {
  25482. uncompressed: imageBuffers.map(function (levelBuffers) {
  25483. var buffer = levelBuffers[0].levelBuffer;
  25484. var convertToInt = false;
  25485. if (glType === TYPES.FLOAT) {
  25486. buffer = new Float32Array(levelBuffers[0].levelBuffer.buffer, levelBuffers[0].levelBuffer.byteOffset, levelBuffers[0].levelBuffer.byteLength / 4);
  25487. }
  25488. else if (glType === TYPES.UNSIGNED_INT) {
  25489. convertToInt = true;
  25490. buffer = new Uint32Array(levelBuffers[0].levelBuffer.buffer, levelBuffers[0].levelBuffer.byteOffset, levelBuffers[0].levelBuffer.byteLength / 4);
  25491. }
  25492. else if (glType === TYPES.INT) {
  25493. convertToInt = true;
  25494. buffer = new Int32Array(levelBuffers[0].levelBuffer.buffer, levelBuffers[0].levelBuffer.byteOffset, levelBuffers[0].levelBuffer.byteLength / 4);
  25495. }
  25496. return {
  25497. resource: new BufferResource(buffer, {
  25498. width: levelBuffers[0].levelWidth,
  25499. height: levelBuffers[0].levelHeight,
  25500. }),
  25501. type: glType,
  25502. format: convertToInt ? convertFormatToInteger(glFormat) : glFormat,
  25503. };
  25504. }),
  25505. kvData: kvData
  25506. };
  25507. }
  25508. return {
  25509. compressed: imageBuffers.map(function (levelBuffers) { return new CompressedTextureResource(null, {
  25510. format: glInternalFormat,
  25511. width: pixelWidth,
  25512. height: pixelHeight,
  25513. levels: numberOfMipmapLevels,
  25514. levelBuffers: levelBuffers,
  25515. }); }),
  25516. kvData: kvData
  25517. };
  25518. }
  25519. /**
  25520. * Checks whether the arrayBuffer contains a valid *.ktx file.
  25521. * @param url
  25522. * @param dataView
  25523. */
  25524. function validate(url, dataView) {
  25525. // NOTE: Do not optimize this into 3 32-bit integer comparison because the endianness
  25526. // of the data is not specified.
  25527. for (var i = 0; i < FILE_IDENTIFIER.length; i++) {
  25528. if (dataView.getUint8(i) !== FILE_IDENTIFIER[i]) {
  25529. console.error(url + " is not a valid *.ktx file!");
  25530. return false;
  25531. }
  25532. }
  25533. return true;
  25534. }
  25535. function convertFormatToInteger(format) {
  25536. switch (format) {
  25537. case FORMATS.RGBA: return FORMATS.RGBA_INTEGER;
  25538. case FORMATS.RGB: return FORMATS.RGB_INTEGER;
  25539. case FORMATS.RG: return FORMATS.RG_INTEGER;
  25540. case FORMATS.RED: return FORMATS.RED_INTEGER;
  25541. default: return format;
  25542. }
  25543. }
  25544. function parseKvData(dataView, bytesOfKeyValueData, littleEndian) {
  25545. var kvData = new Map();
  25546. var bytesIntoKeyValueData = 0;
  25547. while (bytesIntoKeyValueData < bytesOfKeyValueData) {
  25548. var keyAndValueByteSize = dataView.getUint32(FILE_HEADER_SIZE + bytesIntoKeyValueData, littleEndian);
  25549. var keyAndValueByteOffset = FILE_HEADER_SIZE + bytesIntoKeyValueData + 4;
  25550. var valuePadding = 3 - ((keyAndValueByteSize + 3) % 4);
  25551. // Bounds check
  25552. if (keyAndValueByteSize === 0 || keyAndValueByteSize > bytesOfKeyValueData - bytesIntoKeyValueData) {
  25553. console.error('KTXLoader: keyAndValueByteSize out of bounds');
  25554. break;
  25555. }
  25556. // Note: keyNulByte can't be 0 otherwise the key is an empty string.
  25557. var keyNulByte = 0;
  25558. for (; keyNulByte < keyAndValueByteSize; keyNulByte++) {
  25559. if (dataView.getUint8(keyAndValueByteOffset + keyNulByte) === 0x00) {
  25560. break;
  25561. }
  25562. }
  25563. if (keyNulByte === -1) {
  25564. console.error('KTXLoader: Failed to find null byte terminating kvData key');
  25565. break;
  25566. }
  25567. var key = new TextDecoder().decode(new Uint8Array(dataView.buffer, keyAndValueByteOffset, keyNulByte));
  25568. var value = new DataView(dataView.buffer, keyAndValueByteOffset + keyNulByte + 1, keyAndValueByteSize - keyNulByte - 1);
  25569. kvData.set(key, value);
  25570. // 4 = the keyAndValueByteSize field itself
  25571. // keyAndValueByteSize = the bytes taken by the key and value
  25572. // valuePadding = extra padding to align with 4 bytes
  25573. bytesIntoKeyValueData += 4 + keyAndValueByteSize + valuePadding;
  25574. }
  25575. return kvData;
  25576. }
  25577. // Set DDS files to be loaded as an ArrayBuffer
  25578. LoaderResource.setExtensionXhrType('dds', LoaderResource.XHR_RESPONSE_TYPE.BUFFER);
  25579. /**
  25580. * @class
  25581. * @memberof PIXI
  25582. * @implements {PIXI.ILoaderPlugin}
  25583. * @see https://docs.microsoft.com/en-us/windows/win32/direct3ddds/dx-graphics-dds-pguide
  25584. */
  25585. var DDSLoader = /** @class */ (function () {
  25586. function DDSLoader() {
  25587. }
  25588. /**
  25589. * Registers a DDS compressed texture
  25590. * @see PIXI.Loader.loaderMiddleware
  25591. * @param resource - loader resource that is checked to see if it is a DDS file
  25592. * @param next - callback Function to call when done
  25593. */
  25594. DDSLoader.use = function (resource, next) {
  25595. if (resource.extension === 'dds' && resource.data) {
  25596. try {
  25597. Object.assign(resource, registerCompressedTextures(resource.name || resource.url, parseDDS(resource.data), resource.metadata));
  25598. }
  25599. catch (err) {
  25600. next(err);
  25601. return;
  25602. }
  25603. }
  25604. next();
  25605. };
  25606. /** @ignore */
  25607. DDSLoader.extension = ExtensionType.Loader;
  25608. return DDSLoader;
  25609. }());
  25610. // Set KTX files to be loaded as an ArrayBuffer
  25611. LoaderResource.setExtensionXhrType('ktx', LoaderResource.XHR_RESPONSE_TYPE.BUFFER);
  25612. /**
  25613. * Loader plugin for handling KTX texture container files.
  25614. *
  25615. * This KTX loader does not currently support the following features:
  25616. * * cube textures
  25617. * * 3D textures
  25618. * * endianness conversion for big-endian machines
  25619. * * embedded *.basis files
  25620. *
  25621. * It does supports the following features:
  25622. * * multiple textures per file
  25623. * * mipmapping (only for compressed formats)
  25624. * * vendor-specific key/value data parsing (enable {@link PIXI.KTXLoader.loadKeyValueData})
  25625. * @class
  25626. * @memberof PIXI
  25627. * @implements {PIXI.ILoaderPlugin}
  25628. */
  25629. var KTXLoader = /** @class */ (function () {
  25630. function KTXLoader() {
  25631. }
  25632. /**
  25633. * Called after a KTX file is loaded.
  25634. *
  25635. * This will parse the KTX file header and add a {@code BaseTexture} to the texture
  25636. * cache.
  25637. * @see PIXI.Loader.loaderMiddleware
  25638. * @param resource - loader resource that is checked to see if it is a KTX file
  25639. * @param next - callback Function to call when done
  25640. */
  25641. KTXLoader.use = function (resource, next) {
  25642. if (resource.extension === 'ktx' && resource.data) {
  25643. try {
  25644. var url_1 = resource.name || resource.url;
  25645. var _a = parseKTX(url_1, resource.data, this.loadKeyValueData), compressed = _a.compressed, uncompressed = _a.uncompressed, kvData_1 = _a.kvData;
  25646. if (compressed) {
  25647. var result = registerCompressedTextures(url_1, compressed, resource.metadata);
  25648. if (kvData_1 && result.textures) {
  25649. for (var textureId in result.textures) {
  25650. result.textures[textureId].baseTexture.ktxKeyValueData = kvData_1;
  25651. }
  25652. }
  25653. Object.assign(resource, result);
  25654. }
  25655. else if (uncompressed) {
  25656. var textures_1 = {};
  25657. uncompressed.forEach(function (image, i) {
  25658. var texture = new Texture(new BaseTexture(image.resource, {
  25659. mipmap: MIPMAP_MODES.OFF,
  25660. alphaMode: ALPHA_MODES.NO_PREMULTIPLIED_ALPHA,
  25661. type: image.type,
  25662. format: image.format,
  25663. }));
  25664. var cacheID = url_1 + "-" + (i + 1);
  25665. if (kvData_1)
  25666. { texture.baseTexture.ktxKeyValueData = kvData_1; }
  25667. BaseTexture.addToCache(texture.baseTexture, cacheID);
  25668. Texture.addToCache(texture, cacheID);
  25669. if (i === 0) {
  25670. textures_1[url_1] = texture;
  25671. BaseTexture.addToCache(texture.baseTexture, url_1);
  25672. Texture.addToCache(texture, url_1);
  25673. }
  25674. textures_1[cacheID] = texture;
  25675. });
  25676. Object.assign(resource, { textures: textures_1 });
  25677. }
  25678. }
  25679. catch (err) {
  25680. next(err);
  25681. return;
  25682. }
  25683. }
  25684. next();
  25685. };
  25686. /** @ignore */
  25687. KTXLoader.extension = ExtensionType.Loader;
  25688. /**
  25689. * If set to `true`, {@link PIXI.KTXLoader} will parse key-value data in KTX textures. This feature relies
  25690. * on the [Encoding Standard]{@link https://encoding.spec.whatwg.org}.
  25691. *
  25692. * The key-value data will be available on the base-textures as {@code PIXI.BaseTexture.ktxKeyValueData}. They
  25693. * will hold a reference to the texture data buffer, so make sure to delete key-value data once you are done
  25694. * using it.
  25695. */
  25696. KTXLoader.loadKeyValueData = false;
  25697. return KTXLoader;
  25698. }());
  25699. /*!
  25700. * @pixi/particle-container - v6.5.10
  25701. * Compiled Thu, 06 Jul 2023 15:25:11 UTC
  25702. *
  25703. * @pixi/particle-container is licensed under the MIT License.
  25704. * http://www.opensource.org/licenses/mit-license
  25705. */
  25706. /*! *****************************************************************************
  25707. Copyright (c) Microsoft Corporation.
  25708. Permission to use, copy, modify, and/or distribute this software for any
  25709. purpose with or without fee is hereby granted.
  25710. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  25711. REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
  25712. AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  25713. INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
  25714. LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
  25715. OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
  25716. PERFORMANCE OF THIS SOFTWARE.
  25717. ***************************************************************************** */
  25718. /* global Reflect, Promise */
  25719. var extendStatics$f = function(d, b) {
  25720. extendStatics$f = Object.setPrototypeOf ||
  25721. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  25722. function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } };
  25723. return extendStatics$f(d, b);
  25724. };
  25725. function __extends$f(d, b) {
  25726. extendStatics$f(d, b);
  25727. function __() { this.constructor = d; }
  25728. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  25729. }
  25730. /**
  25731. * The ParticleContainer class is a really fast version of the Container built solely for speed,
  25732. * so use when you need a lot of sprites or particles.
  25733. *
  25734. * The tradeoff of the ParticleContainer is that most advanced functionality will not work.
  25735. * ParticleContainer implements the basic object transform (position, scale, rotation)
  25736. * and some advanced functionality like tint (as of v4.5.6).
  25737. *
  25738. * Other more advanced functionality like masking, children, filters, etc will not work on sprites in this batch.
  25739. *
  25740. * It's extremely easy to use:
  25741. * ```js
  25742. * let container = new ParticleContainer();
  25743. *
  25744. * for (let i = 0; i < 100; ++i)
  25745. * {
  25746. * let sprite = PIXI.Sprite.from("myImage.png");
  25747. * container.addChild(sprite);
  25748. * }
  25749. * ```
  25750. *
  25751. * And here you have a hundred sprites that will be rendered at the speed of light.
  25752. * @memberof PIXI
  25753. */
  25754. var ParticleContainer = /** @class */ (function (_super) {
  25755. __extends$f(ParticleContainer, _super);
  25756. /**
  25757. * @param maxSize - The maximum number of particles that can be rendered by the container.
  25758. * Affects size of allocated buffers.
  25759. * @param properties - The properties of children that should be uploaded to the gpu and applied.
  25760. * @param {boolean} [properties.vertices=false] - When true, vertices be uploaded and applied.
  25761. * if sprite's ` scale/anchor/trim/frame/orig` is dynamic, please set `true`.
  25762. * @param {boolean} [properties.position=true] - When true, position be uploaded and applied.
  25763. * @param {boolean} [properties.rotation=false] - When true, rotation be uploaded and applied.
  25764. * @param {boolean} [properties.uvs=false] - When true, uvs be uploaded and applied.
  25765. * @param {boolean} [properties.tint=false] - When true, alpha and tint be uploaded and applied.
  25766. * @param {number} [batchSize=16384] - Number of particles per batch. If less than maxSize, it uses maxSize instead.
  25767. * @param {boolean} [autoResize=false] - If true, container allocates more batches in case
  25768. * there are more than `maxSize` particles.
  25769. */
  25770. function ParticleContainer(maxSize, properties, batchSize, autoResize) {
  25771. if (maxSize === void 0) { maxSize = 1500; }
  25772. if (batchSize === void 0) { batchSize = 16384; }
  25773. if (autoResize === void 0) { autoResize = false; }
  25774. var _this = _super.call(this) || this;
  25775. // Making sure the batch size is valid
  25776. // 65535 is max vertex index in the index buffer (see ParticleRenderer)
  25777. // so max number of particles is 65536 / 4 = 16384
  25778. var maxBatchSize = 16384;
  25779. if (batchSize > maxBatchSize) {
  25780. batchSize = maxBatchSize;
  25781. }
  25782. _this._properties = [false, true, false, false, false];
  25783. _this._maxSize = maxSize;
  25784. _this._batchSize = batchSize;
  25785. _this._buffers = null;
  25786. _this._bufferUpdateIDs = [];
  25787. _this._updateID = 0;
  25788. _this.interactiveChildren = false;
  25789. _this.blendMode = BLEND_MODES.NORMAL;
  25790. _this.autoResize = autoResize;
  25791. _this.roundPixels = true;
  25792. _this.baseTexture = null;
  25793. _this.setProperties(properties);
  25794. _this._tint = 0;
  25795. _this.tintRgb = new Float32Array(4);
  25796. _this.tint = 0xFFFFFF;
  25797. return _this;
  25798. }
  25799. /**
  25800. * Sets the private properties array to dynamic / static based on the passed properties object
  25801. * @param properties - The properties to be uploaded
  25802. */
  25803. ParticleContainer.prototype.setProperties = function (properties) {
  25804. if (properties) {
  25805. this._properties[0] = 'vertices' in properties || 'scale' in properties
  25806. ? !!properties.vertices || !!properties.scale : this._properties[0];
  25807. this._properties[1] = 'position' in properties ? !!properties.position : this._properties[1];
  25808. this._properties[2] = 'rotation' in properties ? !!properties.rotation : this._properties[2];
  25809. this._properties[3] = 'uvs' in properties ? !!properties.uvs : this._properties[3];
  25810. this._properties[4] = 'tint' in properties || 'alpha' in properties
  25811. ? !!properties.tint || !!properties.alpha : this._properties[4];
  25812. }
  25813. };
  25814. ParticleContainer.prototype.updateTransform = function () {
  25815. // TODO don't need to!
  25816. this.displayObjectUpdateTransform();
  25817. };
  25818. Object.defineProperty(ParticleContainer.prototype, "tint", {
  25819. /**
  25820. * The tint applied to the container. This is a hex value.
  25821. * A value of 0xFFFFFF will remove any tint effect.
  25822. * IMPORTANT: This is a WebGL only feature and will be ignored by the canvas renderer.
  25823. * @default 0xFFFFFF
  25824. */
  25825. get: function () {
  25826. return this._tint;
  25827. },
  25828. set: function (value) {
  25829. this._tint = value;
  25830. hex2rgb(value, this.tintRgb);
  25831. },
  25832. enumerable: false,
  25833. configurable: true
  25834. });
  25835. /**
  25836. * Renders the container using the WebGL renderer.
  25837. * @param renderer - The WebGL renderer.
  25838. */
  25839. ParticleContainer.prototype.render = function (renderer) {
  25840. var _this = this;
  25841. if (!this.visible || this.worldAlpha <= 0 || !this.children.length || !this.renderable) {
  25842. return;
  25843. }
  25844. if (!this.baseTexture) {
  25845. this.baseTexture = this.children[0]._texture.baseTexture;
  25846. if (!this.baseTexture.valid) {
  25847. this.baseTexture.once('update', function () { return _this.onChildrenChange(0); });
  25848. }
  25849. }
  25850. renderer.batch.setObjectRenderer(renderer.plugins.particle);
  25851. renderer.plugins.particle.render(this);
  25852. };
  25853. /**
  25854. * Set the flag that static data should be updated to true
  25855. * @param smallestChildIndex - The smallest child index.
  25856. */
  25857. ParticleContainer.prototype.onChildrenChange = function (smallestChildIndex) {
  25858. var bufferIndex = Math.floor(smallestChildIndex / this._batchSize);
  25859. while (this._bufferUpdateIDs.length < bufferIndex) {
  25860. this._bufferUpdateIDs.push(0);
  25861. }
  25862. this._bufferUpdateIDs[bufferIndex] = ++this._updateID;
  25863. };
  25864. ParticleContainer.prototype.dispose = function () {
  25865. if (this._buffers) {
  25866. for (var i = 0; i < this._buffers.length; ++i) {
  25867. this._buffers[i].destroy();
  25868. }
  25869. this._buffers = null;
  25870. }
  25871. };
  25872. /**
  25873. * Destroys the container
  25874. * @param options - Options parameter. A boolean will act as if all options
  25875. * have been set to that value
  25876. * @param {boolean} [options.children=false] - if set to true, all the children will have their
  25877. * destroy method called as well. 'options' will be passed on to those calls.
  25878. * @param {boolean} [options.texture=false] - Only used for child Sprites if options.children is set to true
  25879. * Should it destroy the texture of the child sprite
  25880. * @param {boolean} [options.baseTexture=false] - Only used for child Sprites if options.children is set to true
  25881. * Should it destroy the base texture of the child sprite
  25882. */
  25883. ParticleContainer.prototype.destroy = function (options) {
  25884. _super.prototype.destroy.call(this, options);
  25885. this.dispose();
  25886. this._properties = null;
  25887. this._buffers = null;
  25888. this._bufferUpdateIDs = null;
  25889. };
  25890. return ParticleContainer;
  25891. }(Container));
  25892. /*
  25893. * @author Mat Groves
  25894. *
  25895. * Big thanks to the very clever Matt DesLauriers <mattdesl> https://github.com/mattdesl/
  25896. * for creating the original PixiJS version!
  25897. * Also a thanks to https://github.com/bchevalier for tweaking the tint and alpha so that
  25898. * they now share 4 bytes on the vertex buffer
  25899. *
  25900. * Heavily inspired by LibGDX's ParticleBuffer:
  25901. * https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/graphics/g2d/ParticleBuffer.java
  25902. */
  25903. /**
  25904. * The particle buffer manages the static and dynamic buffers for a particle container.
  25905. * @private
  25906. * @memberof PIXI
  25907. */
  25908. var ParticleBuffer = /** @class */ (function () {
  25909. /**
  25910. * @param {object} properties - The properties to upload.
  25911. * @param {boolean[]} dynamicPropertyFlags - Flags for which properties are dynamic.
  25912. * @param {number} size - The size of the batch.
  25913. */
  25914. function ParticleBuffer(properties, dynamicPropertyFlags, size) {
  25915. this.geometry = new Geometry();
  25916. this.indexBuffer = null;
  25917. this.size = size;
  25918. this.dynamicProperties = [];
  25919. this.staticProperties = [];
  25920. for (var i = 0; i < properties.length; ++i) {
  25921. var property = properties[i];
  25922. // Make copy of properties object so that when we edit the offset it doesn't
  25923. // change all other instances of the object literal
  25924. property = {
  25925. attributeName: property.attributeName,
  25926. size: property.size,
  25927. uploadFunction: property.uploadFunction,
  25928. type: property.type || TYPES.FLOAT,
  25929. offset: property.offset,
  25930. };
  25931. if (dynamicPropertyFlags[i]) {
  25932. this.dynamicProperties.push(property);
  25933. }
  25934. else {
  25935. this.staticProperties.push(property);
  25936. }
  25937. }
  25938. this.staticStride = 0;
  25939. this.staticBuffer = null;
  25940. this.staticData = null;
  25941. this.staticDataUint32 = null;
  25942. this.dynamicStride = 0;
  25943. this.dynamicBuffer = null;
  25944. this.dynamicData = null;
  25945. this.dynamicDataUint32 = null;
  25946. this._updateID = 0;
  25947. this.initBuffers();
  25948. }
  25949. /** Sets up the renderer context and necessary buffers. */
  25950. ParticleBuffer.prototype.initBuffers = function () {
  25951. var geometry = this.geometry;
  25952. var dynamicOffset = 0;
  25953. this.indexBuffer = new Buffer(createIndicesForQuads(this.size), true, true);
  25954. geometry.addIndex(this.indexBuffer);
  25955. this.dynamicStride = 0;
  25956. for (var i = 0; i < this.dynamicProperties.length; ++i) {
  25957. var property = this.dynamicProperties[i];
  25958. property.offset = dynamicOffset;
  25959. dynamicOffset += property.size;
  25960. this.dynamicStride += property.size;
  25961. }
  25962. var dynBuffer = new ArrayBuffer(this.size * this.dynamicStride * 4 * 4);
  25963. this.dynamicData = new Float32Array(dynBuffer);
  25964. this.dynamicDataUint32 = new Uint32Array(dynBuffer);
  25965. this.dynamicBuffer = new Buffer(this.dynamicData, false, false);
  25966. // static //
  25967. var staticOffset = 0;
  25968. this.staticStride = 0;
  25969. for (var i = 0; i < this.staticProperties.length; ++i) {
  25970. var property = this.staticProperties[i];
  25971. property.offset = staticOffset;
  25972. staticOffset += property.size;
  25973. this.staticStride += property.size;
  25974. }
  25975. var statBuffer = new ArrayBuffer(this.size * this.staticStride * 4 * 4);
  25976. this.staticData = new Float32Array(statBuffer);
  25977. this.staticDataUint32 = new Uint32Array(statBuffer);
  25978. this.staticBuffer = new Buffer(this.staticData, true, false);
  25979. for (var i = 0; i < this.dynamicProperties.length; ++i) {
  25980. var property = this.dynamicProperties[i];
  25981. geometry.addAttribute(property.attributeName, this.dynamicBuffer, 0, property.type === TYPES.UNSIGNED_BYTE, property.type, this.dynamicStride * 4, property.offset * 4);
  25982. }
  25983. for (var i = 0; i < this.staticProperties.length; ++i) {
  25984. var property = this.staticProperties[i];
  25985. geometry.addAttribute(property.attributeName, this.staticBuffer, 0, property.type === TYPES.UNSIGNED_BYTE, property.type, this.staticStride * 4, property.offset * 4);
  25986. }
  25987. };
  25988. /**
  25989. * Uploads the dynamic properties.
  25990. * @param children - The children to upload.
  25991. * @param startIndex - The index to start at.
  25992. * @param amount - The number to upload.
  25993. */
  25994. ParticleBuffer.prototype.uploadDynamic = function (children, startIndex, amount) {
  25995. for (var i = 0; i < this.dynamicProperties.length; i++) {
  25996. var property = this.dynamicProperties[i];
  25997. property.uploadFunction(children, startIndex, amount, property.type === TYPES.UNSIGNED_BYTE ? this.dynamicDataUint32 : this.dynamicData, this.dynamicStride, property.offset);
  25998. }
  25999. this.dynamicBuffer._updateID++;
  26000. };
  26001. /**
  26002. * Uploads the static properties.
  26003. * @param children - The children to upload.
  26004. * @param startIndex - The index to start at.
  26005. * @param amount - The number to upload.
  26006. */
  26007. ParticleBuffer.prototype.uploadStatic = function (children, startIndex, amount) {
  26008. for (var i = 0; i < this.staticProperties.length; i++) {
  26009. var property = this.staticProperties[i];
  26010. property.uploadFunction(children, startIndex, amount, property.type === TYPES.UNSIGNED_BYTE ? this.staticDataUint32 : this.staticData, this.staticStride, property.offset);
  26011. }
  26012. this.staticBuffer._updateID++;
  26013. };
  26014. /** Destroys the ParticleBuffer. */
  26015. ParticleBuffer.prototype.destroy = function () {
  26016. this.indexBuffer = null;
  26017. this.dynamicProperties = null;
  26018. this.dynamicBuffer = null;
  26019. this.dynamicData = null;
  26020. this.dynamicDataUint32 = null;
  26021. this.staticProperties = null;
  26022. this.staticBuffer = null;
  26023. this.staticData = null;
  26024. this.staticDataUint32 = null;
  26025. // all buffers are destroyed inside geometry
  26026. this.geometry.destroy();
  26027. };
  26028. return ParticleBuffer;
  26029. }());
  26030. var fragment$6 = "varying vec2 vTextureCoord;\nvarying vec4 vColor;\n\nuniform sampler2D uSampler;\n\nvoid main(void){\n vec4 color = texture2D(uSampler, vTextureCoord) * vColor;\n gl_FragColor = color;\n}";
  26031. var vertex$3 = "attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\nattribute vec4 aColor;\n\nattribute vec2 aPositionCoord;\nattribute float aRotation;\n\nuniform mat3 translationMatrix;\nuniform vec4 uColor;\n\nvarying vec2 vTextureCoord;\nvarying vec4 vColor;\n\nvoid main(void){\n float x = (aVertexPosition.x) * cos(aRotation) - (aVertexPosition.y) * sin(aRotation);\n float y = (aVertexPosition.x) * sin(aRotation) + (aVertexPosition.y) * cos(aRotation);\n\n vec2 v = vec2(x, y);\n v = v + aPositionCoord;\n\n gl_Position = vec4((translationMatrix * vec3(v, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = aTextureCoord;\n vColor = aColor * uColor;\n}\n";
  26032. /*
  26033. * @author Mat Groves
  26034. *
  26035. * Big thanks to the very clever Matt DesLauriers <mattdesl> https://github.com/mattdesl/
  26036. * for creating the original PixiJS version!
  26037. * Also a thanks to https://github.com/bchevalier for tweaking the tint and alpha so that they now
  26038. * share 4 bytes on the vertex buffer
  26039. *
  26040. * Heavily inspired by LibGDX's ParticleRenderer:
  26041. * https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/graphics/g2d/ParticleRenderer.java
  26042. */
  26043. /**
  26044. * Renderer for Particles that is designer for speed over feature set.
  26045. * @memberof PIXI
  26046. */
  26047. var ParticleRenderer = /** @class */ (function (_super) {
  26048. __extends$f(ParticleRenderer, _super);
  26049. /**
  26050. * @param renderer - The renderer this sprite batch works for.
  26051. */
  26052. function ParticleRenderer(renderer) {
  26053. var _this = _super.call(this, renderer) || this;
  26054. // 65535 is max vertex index in the index buffer (see ParticleRenderer)
  26055. // so max number of particles is 65536 / 4 = 16384
  26056. // and max number of element in the index buffer is 16384 * 6 = 98304
  26057. // Creating a full index buffer, overhead is 98304 * 2 = 196Ko
  26058. // let numIndices = 98304;
  26059. _this.shader = null;
  26060. _this.properties = null;
  26061. _this.tempMatrix = new Matrix();
  26062. _this.properties = [
  26063. // verticesData
  26064. {
  26065. attributeName: 'aVertexPosition',
  26066. size: 2,
  26067. uploadFunction: _this.uploadVertices,
  26068. offset: 0,
  26069. },
  26070. // positionData
  26071. {
  26072. attributeName: 'aPositionCoord',
  26073. size: 2,
  26074. uploadFunction: _this.uploadPosition,
  26075. offset: 0,
  26076. },
  26077. // rotationData
  26078. {
  26079. attributeName: 'aRotation',
  26080. size: 1,
  26081. uploadFunction: _this.uploadRotation,
  26082. offset: 0,
  26083. },
  26084. // uvsData
  26085. {
  26086. attributeName: 'aTextureCoord',
  26087. size: 2,
  26088. uploadFunction: _this.uploadUvs,
  26089. offset: 0,
  26090. },
  26091. // tintData
  26092. {
  26093. attributeName: 'aColor',
  26094. size: 1,
  26095. type: TYPES.UNSIGNED_BYTE,
  26096. uploadFunction: _this.uploadTint,
  26097. offset: 0,
  26098. } ];
  26099. _this.shader = Shader.from(vertex$3, fragment$6, {});
  26100. _this.state = State.for2d();
  26101. return _this;
  26102. }
  26103. /**
  26104. * Renders the particle container object.
  26105. * @param container - The container to render using this ParticleRenderer.
  26106. */
  26107. ParticleRenderer.prototype.render = function (container) {
  26108. var children = container.children;
  26109. var maxSize = container._maxSize;
  26110. var batchSize = container._batchSize;
  26111. var renderer = this.renderer;
  26112. var totalChildren = children.length;
  26113. if (totalChildren === 0) {
  26114. return;
  26115. }
  26116. else if (totalChildren > maxSize && !container.autoResize) {
  26117. totalChildren = maxSize;
  26118. }
  26119. var buffers = container._buffers;
  26120. if (!buffers) {
  26121. buffers = container._buffers = this.generateBuffers(container);
  26122. }
  26123. var baseTexture = children[0]._texture.baseTexture;
  26124. var premultiplied = baseTexture.alphaMode > 0;
  26125. // if the uvs have not updated then no point rendering just yet!
  26126. this.state.blendMode = correctBlendMode(container.blendMode, premultiplied);
  26127. renderer.state.set(this.state);
  26128. var gl = renderer.gl;
  26129. var m = container.worldTransform.copyTo(this.tempMatrix);
  26130. m.prepend(renderer.globalUniforms.uniforms.projectionMatrix);
  26131. this.shader.uniforms.translationMatrix = m.toArray(true);
  26132. this.shader.uniforms.uColor = premultiplyRgba(container.tintRgb, container.worldAlpha, this.shader.uniforms.uColor, premultiplied);
  26133. this.shader.uniforms.uSampler = baseTexture;
  26134. this.renderer.shader.bind(this.shader);
  26135. var updateStatic = false;
  26136. // now lets upload and render the buffers..
  26137. for (var i = 0, j = 0; i < totalChildren; i += batchSize, j += 1) {
  26138. var amount = (totalChildren - i);
  26139. if (amount > batchSize) {
  26140. amount = batchSize;
  26141. }
  26142. if (j >= buffers.length) {
  26143. buffers.push(this._generateOneMoreBuffer(container));
  26144. }
  26145. var buffer = buffers[j];
  26146. // we always upload the dynamic
  26147. buffer.uploadDynamic(children, i, amount);
  26148. var bid = container._bufferUpdateIDs[j] || 0;
  26149. updateStatic = updateStatic || (buffer._updateID < bid);
  26150. // we only upload the static content when we have to!
  26151. if (updateStatic) {
  26152. buffer._updateID = container._updateID;
  26153. buffer.uploadStatic(children, i, amount);
  26154. }
  26155. // bind the buffer
  26156. renderer.geometry.bind(buffer.geometry);
  26157. gl.drawElements(gl.TRIANGLES, amount * 6, gl.UNSIGNED_SHORT, 0);
  26158. }
  26159. };
  26160. /**
  26161. * Creates one particle buffer for each child in the container we want to render and updates internal properties.
  26162. * @param container - The container to render using this ParticleRenderer
  26163. * @returns - The buffers
  26164. */
  26165. ParticleRenderer.prototype.generateBuffers = function (container) {
  26166. var buffers = [];
  26167. var size = container._maxSize;
  26168. var batchSize = container._batchSize;
  26169. var dynamicPropertyFlags = container._properties;
  26170. for (var i = 0; i < size; i += batchSize) {
  26171. buffers.push(new ParticleBuffer(this.properties, dynamicPropertyFlags, batchSize));
  26172. }
  26173. return buffers;
  26174. };
  26175. /**
  26176. * Creates one more particle buffer, because container has autoResize feature.
  26177. * @param container - The container to render using this ParticleRenderer
  26178. * @returns - The generated buffer
  26179. */
  26180. ParticleRenderer.prototype._generateOneMoreBuffer = function (container) {
  26181. var batchSize = container._batchSize;
  26182. var dynamicPropertyFlags = container._properties;
  26183. return new ParticleBuffer(this.properties, dynamicPropertyFlags, batchSize);
  26184. };
  26185. /**
  26186. * Uploads the vertices.
  26187. * @param children - the array of sprites to render
  26188. * @param startIndex - the index to start from in the children array
  26189. * @param amount - the amount of children that will have their vertices uploaded
  26190. * @param array - The vertices to upload.
  26191. * @param stride - Stride to use for iteration.
  26192. * @param offset - Offset to start at.
  26193. */
  26194. ParticleRenderer.prototype.uploadVertices = function (children, startIndex, amount, array, stride, offset) {
  26195. var w0 = 0;
  26196. var w1 = 0;
  26197. var h0 = 0;
  26198. var h1 = 0;
  26199. for (var i = 0; i < amount; ++i) {
  26200. var sprite = children[startIndex + i];
  26201. var texture = sprite._texture;
  26202. var sx = sprite.scale.x;
  26203. var sy = sprite.scale.y;
  26204. var trim = texture.trim;
  26205. var orig = texture.orig;
  26206. if (trim) {
  26207. // if the sprite is trimmed and is not a tilingsprite then we need to add the
  26208. // extra space before transforming the sprite coords..
  26209. w1 = trim.x - (sprite.anchor.x * orig.width);
  26210. w0 = w1 + trim.width;
  26211. h1 = trim.y - (sprite.anchor.y * orig.height);
  26212. h0 = h1 + trim.height;
  26213. }
  26214. else {
  26215. w0 = (orig.width) * (1 - sprite.anchor.x);
  26216. w1 = (orig.width) * -sprite.anchor.x;
  26217. h0 = orig.height * (1 - sprite.anchor.y);
  26218. h1 = orig.height * -sprite.anchor.y;
  26219. }
  26220. array[offset] = w1 * sx;
  26221. array[offset + 1] = h1 * sy;
  26222. array[offset + stride] = w0 * sx;
  26223. array[offset + stride + 1] = h1 * sy;
  26224. array[offset + (stride * 2)] = w0 * sx;
  26225. array[offset + (stride * 2) + 1] = h0 * sy;
  26226. array[offset + (stride * 3)] = w1 * sx;
  26227. array[offset + (stride * 3) + 1] = h0 * sy;
  26228. offset += stride * 4;
  26229. }
  26230. };
  26231. /**
  26232. * Uploads the position.
  26233. * @param children - the array of sprites to render
  26234. * @param startIndex - the index to start from in the children array
  26235. * @param amount - the amount of children that will have their positions uploaded
  26236. * @param array - The vertices to upload.
  26237. * @param stride - Stride to use for iteration.
  26238. * @param offset - Offset to start at.
  26239. */
  26240. ParticleRenderer.prototype.uploadPosition = function (children, startIndex, amount, array, stride, offset) {
  26241. for (var i = 0; i < amount; i++) {
  26242. var spritePosition = children[startIndex + i].position;
  26243. array[offset] = spritePosition.x;
  26244. array[offset + 1] = spritePosition.y;
  26245. array[offset + stride] = spritePosition.x;
  26246. array[offset + stride + 1] = spritePosition.y;
  26247. array[offset + (stride * 2)] = spritePosition.x;
  26248. array[offset + (stride * 2) + 1] = spritePosition.y;
  26249. array[offset + (stride * 3)] = spritePosition.x;
  26250. array[offset + (stride * 3) + 1] = spritePosition.y;
  26251. offset += stride * 4;
  26252. }
  26253. };
  26254. /**
  26255. * Uploads the rotation.
  26256. * @param children - the array of sprites to render
  26257. * @param startIndex - the index to start from in the children array
  26258. * @param amount - the amount of children that will have their rotation uploaded
  26259. * @param array - The vertices to upload.
  26260. * @param stride - Stride to use for iteration.
  26261. * @param offset - Offset to start at.
  26262. */
  26263. ParticleRenderer.prototype.uploadRotation = function (children, startIndex, amount, array, stride, offset) {
  26264. for (var i = 0; i < amount; i++) {
  26265. var spriteRotation = children[startIndex + i].rotation;
  26266. array[offset] = spriteRotation;
  26267. array[offset + stride] = spriteRotation;
  26268. array[offset + (stride * 2)] = spriteRotation;
  26269. array[offset + (stride * 3)] = spriteRotation;
  26270. offset += stride * 4;
  26271. }
  26272. };
  26273. /**
  26274. * Uploads the UVs.
  26275. * @param children - the array of sprites to render
  26276. * @param startIndex - the index to start from in the children array
  26277. * @param amount - the amount of children that will have their rotation uploaded
  26278. * @param array - The vertices to upload.
  26279. * @param stride - Stride to use for iteration.
  26280. * @param offset - Offset to start at.
  26281. */
  26282. ParticleRenderer.prototype.uploadUvs = function (children, startIndex, amount, array, stride, offset) {
  26283. for (var i = 0; i < amount; ++i) {
  26284. var textureUvs = children[startIndex + i]._texture._uvs;
  26285. if (textureUvs) {
  26286. array[offset] = textureUvs.x0;
  26287. array[offset + 1] = textureUvs.y0;
  26288. array[offset + stride] = textureUvs.x1;
  26289. array[offset + stride + 1] = textureUvs.y1;
  26290. array[offset + (stride * 2)] = textureUvs.x2;
  26291. array[offset + (stride * 2) + 1] = textureUvs.y2;
  26292. array[offset + (stride * 3)] = textureUvs.x3;
  26293. array[offset + (stride * 3) + 1] = textureUvs.y3;
  26294. offset += stride * 4;
  26295. }
  26296. else {
  26297. // TODO you know this can be easier!
  26298. array[offset] = 0;
  26299. array[offset + 1] = 0;
  26300. array[offset + stride] = 0;
  26301. array[offset + stride + 1] = 0;
  26302. array[offset + (stride * 2)] = 0;
  26303. array[offset + (stride * 2) + 1] = 0;
  26304. array[offset + (stride * 3)] = 0;
  26305. array[offset + (stride * 3) + 1] = 0;
  26306. offset += stride * 4;
  26307. }
  26308. }
  26309. };
  26310. /**
  26311. * Uploads the tint.
  26312. * @param children - the array of sprites to render
  26313. * @param startIndex - the index to start from in the children array
  26314. * @param amount - the amount of children that will have their rotation uploaded
  26315. * @param array - The vertices to upload.
  26316. * @param stride - Stride to use for iteration.
  26317. * @param offset - Offset to start at.
  26318. */
  26319. ParticleRenderer.prototype.uploadTint = function (children, startIndex, amount, array, stride, offset) {
  26320. for (var i = 0; i < amount; ++i) {
  26321. var sprite = children[startIndex + i];
  26322. var premultiplied = sprite._texture.baseTexture.alphaMode > 0;
  26323. var alpha = sprite.alpha;
  26324. // we dont call extra function if alpha is 1.0, that's faster
  26325. var argb = alpha < 1.0 && premultiplied
  26326. ? premultiplyTint(sprite._tintRGB, alpha) : sprite._tintRGB + (alpha * 255 << 24);
  26327. array[offset] = argb;
  26328. array[offset + stride] = argb;
  26329. array[offset + (stride * 2)] = argb;
  26330. array[offset + (stride * 3)] = argb;
  26331. offset += stride * 4;
  26332. }
  26333. };
  26334. /** Destroys the ParticleRenderer. */
  26335. ParticleRenderer.prototype.destroy = function () {
  26336. _super.prototype.destroy.call(this);
  26337. if (this.shader) {
  26338. this.shader.destroy();
  26339. this.shader = null;
  26340. }
  26341. this.tempMatrix = null;
  26342. };
  26343. /** @ignore */
  26344. ParticleRenderer.extension = {
  26345. name: 'particle',
  26346. type: ExtensionType.RendererPlugin,
  26347. };
  26348. return ParticleRenderer;
  26349. }(ObjectRenderer));
  26350. /*!
  26351. * @pixi/graphics - v6.5.10
  26352. * Compiled Thu, 06 Jul 2023 15:25:11 UTC
  26353. *
  26354. * @pixi/graphics is licensed under the MIT License.
  26355. * http://www.opensource.org/licenses/mit-license
  26356. */
  26357. /**
  26358. * Supported line joints in `PIXI.LineStyle` for graphics.
  26359. * @see PIXI.Graphics#lineStyle
  26360. * @see https://graphicdesign.stackexchange.com/questions/59018/what-is-a-bevel-join-of-two-lines-exactly-illustrator
  26361. * @name LINE_JOIN
  26362. * @memberof PIXI
  26363. * @static
  26364. * @enum {string}
  26365. * @property {string} MITER - 'miter': make a sharp corner where outer part of lines meet
  26366. * @property {string} BEVEL - 'bevel': add a square butt at each end of line segment and fill the triangle at turn
  26367. * @property {string} ROUND - 'round': add an arc at the joint
  26368. */
  26369. var LINE_JOIN;
  26370. (function (LINE_JOIN) {
  26371. LINE_JOIN["MITER"] = "miter";
  26372. LINE_JOIN["BEVEL"] = "bevel";
  26373. LINE_JOIN["ROUND"] = "round";
  26374. })(LINE_JOIN || (LINE_JOIN = {}));
  26375. /**
  26376. * Support line caps in `PIXI.LineStyle` for graphics.
  26377. * @see PIXI.Graphics#lineStyle
  26378. * @name LINE_CAP
  26379. * @memberof PIXI
  26380. * @static
  26381. * @enum {string}
  26382. * @property {string} BUTT - 'butt': don't add any cap at line ends (leaves orthogonal edges)
  26383. * @property {string} ROUND - 'round': add semicircle at ends
  26384. * @property {string} SQUARE - 'square': add square at end (like `BUTT` except more length at end)
  26385. */
  26386. var LINE_CAP;
  26387. (function (LINE_CAP) {
  26388. LINE_CAP["BUTT"] = "butt";
  26389. LINE_CAP["ROUND"] = "round";
  26390. LINE_CAP["SQUARE"] = "square";
  26391. })(LINE_CAP || (LINE_CAP = {}));
  26392. /**
  26393. * Graphics curves resolution settings. If `adaptive` flag is set to `true`,
  26394. * the resolution is calculated based on the curve's length to ensure better visual quality.
  26395. * Adaptive draw works with `bezierCurveTo` and `quadraticCurveTo`.
  26396. * @static
  26397. * @constant
  26398. * @memberof PIXI
  26399. * @name GRAPHICS_CURVES
  26400. * @type {object}
  26401. * @property {boolean} [adaptive=true] - flag indicating if the resolution should be adaptive
  26402. * @property {number} [maxLength=10] - maximal length of a single segment of the curve (if adaptive = false, ignored)
  26403. * @property {number} [minSegments=8] - minimal number of segments in the curve (if adaptive = false, ignored)
  26404. * @property {number} [maxSegments=2048] - maximal number of segments in the curve (if adaptive = false, ignored)
  26405. */
  26406. var GRAPHICS_CURVES = {
  26407. adaptive: true,
  26408. maxLength: 10,
  26409. minSegments: 8,
  26410. maxSegments: 2048,
  26411. epsilon: 0.0001,
  26412. _segmentsCount: function (length, defaultSegments) {
  26413. if (defaultSegments === void 0) { defaultSegments = 20; }
  26414. if (!this.adaptive || !length || isNaN(length)) {
  26415. return defaultSegments;
  26416. }
  26417. var result = Math.ceil(length / this.maxLength);
  26418. if (result < this.minSegments) {
  26419. result = this.minSegments;
  26420. }
  26421. else if (result > this.maxSegments) {
  26422. result = this.maxSegments;
  26423. }
  26424. return result;
  26425. },
  26426. };
  26427. /**
  26428. * Fill style object for Graphics.
  26429. * @memberof PIXI
  26430. */
  26431. var FillStyle = /** @class */ (function () {
  26432. function FillStyle() {
  26433. /**
  26434. * The hex color value used when coloring the Graphics object.
  26435. * @default 0xFFFFFF
  26436. */
  26437. this.color = 0xFFFFFF;
  26438. /** The alpha value used when filling the Graphics object. */
  26439. this.alpha = 1.0;
  26440. /**
  26441. * The texture to be used for the fill.
  26442. * @default 0
  26443. */
  26444. this.texture = Texture.WHITE;
  26445. /**
  26446. * The transform applied to the texture.
  26447. * @default null
  26448. */
  26449. this.matrix = null;
  26450. /** If the current fill is visible. */
  26451. this.visible = false;
  26452. this.reset();
  26453. }
  26454. /** Clones the object */
  26455. FillStyle.prototype.clone = function () {
  26456. var obj = new FillStyle();
  26457. obj.color = this.color;
  26458. obj.alpha = this.alpha;
  26459. obj.texture = this.texture;
  26460. obj.matrix = this.matrix;
  26461. obj.visible = this.visible;
  26462. return obj;
  26463. };
  26464. /** Reset */
  26465. FillStyle.prototype.reset = function () {
  26466. this.color = 0xFFFFFF;
  26467. this.alpha = 1;
  26468. this.texture = Texture.WHITE;
  26469. this.matrix = null;
  26470. this.visible = false;
  26471. };
  26472. /** Destroy and don't use after this. */
  26473. FillStyle.prototype.destroy = function () {
  26474. this.texture = null;
  26475. this.matrix = null;
  26476. };
  26477. return FillStyle;
  26478. }());
  26479. /*! *****************************************************************************
  26480. Copyright (c) Microsoft Corporation.
  26481. Permission to use, copy, modify, and/or distribute this software for any
  26482. purpose with or without fee is hereby granted.
  26483. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  26484. REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
  26485. AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  26486. INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
  26487. LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
  26488. OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
  26489. PERFORMANCE OF THIS SOFTWARE.
  26490. ***************************************************************************** */
  26491. /* global Reflect, Promise */
  26492. var extendStatics$e = function(d, b) {
  26493. extendStatics$e = Object.setPrototypeOf ||
  26494. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  26495. function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } };
  26496. return extendStatics$e(d, b);
  26497. };
  26498. function __extends$e(d, b) {
  26499. extendStatics$e(d, b);
  26500. function __() { this.constructor = d; }
  26501. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  26502. }
  26503. function fixOrientation(points, hole) {
  26504. var _a, _b;
  26505. if (hole === void 0) { hole = false; }
  26506. var m = points.length;
  26507. if (m < 6) {
  26508. return;
  26509. }
  26510. var area = 0;
  26511. for (var i = 0, x1 = points[m - 2], y1 = points[m - 1]; i < m; i += 2) {
  26512. var x2 = points[i];
  26513. var y2 = points[i + 1];
  26514. area += (x2 - x1) * (y2 + y1);
  26515. x1 = x2;
  26516. y1 = y2;
  26517. }
  26518. if ((!hole && area > 0) || (hole && area <= 0)) {
  26519. var n = m / 2;
  26520. for (var i = n + (n % 2); i < m; i += 2) {
  26521. var i1 = m - i - 2;
  26522. var i2 = m - i - 1;
  26523. var i3 = i;
  26524. var i4 = i + 1;
  26525. _a = [points[i3], points[i1]], points[i1] = _a[0], points[i3] = _a[1];
  26526. _b = [points[i4], points[i2]], points[i2] = _b[0], points[i4] = _b[1];
  26527. }
  26528. }
  26529. }
  26530. /**
  26531. * Builds a polygon to draw
  26532. *
  26533. * Ignored from docs since it is not directly exposed.
  26534. * @ignore
  26535. * @private
  26536. * @param {PIXI.WebGLGraphicsData} graphicsData - The graphics object containing all the necessary properties
  26537. * @param {object} webGLData - an object containing all the WebGL-specific information to create this shape
  26538. * @param {object} webGLDataNativeLines - an object containing all the WebGL-specific information to create nativeLines
  26539. */
  26540. var buildPoly = {
  26541. build: function (graphicsData) {
  26542. graphicsData.points = graphicsData.shape.points.slice();
  26543. },
  26544. triangulate: function (graphicsData, graphicsGeometry) {
  26545. var points = graphicsData.points;
  26546. var holes = graphicsData.holes;
  26547. var verts = graphicsGeometry.points;
  26548. var indices = graphicsGeometry.indices;
  26549. if (points.length >= 6) {
  26550. fixOrientation(points, false);
  26551. var holeArray = [];
  26552. // Process holes..
  26553. for (var i = 0; i < holes.length; i++) {
  26554. var hole = holes[i];
  26555. fixOrientation(hole.points, true);
  26556. holeArray.push(points.length / 2);
  26557. points = points.concat(hole.points);
  26558. }
  26559. // sort color
  26560. var triangles = earcut_1(points, holeArray, 2);
  26561. if (!triangles) {
  26562. return;
  26563. }
  26564. var vertPos = verts.length / 2;
  26565. for (var i = 0; i < triangles.length; i += 3) {
  26566. indices.push(triangles[i] + vertPos);
  26567. indices.push(triangles[i + 1] + vertPos);
  26568. indices.push(triangles[i + 2] + vertPos);
  26569. }
  26570. for (var i = 0; i < points.length; i++) {
  26571. verts.push(points[i]);
  26572. }
  26573. }
  26574. },
  26575. };
  26576. // for type only
  26577. /**
  26578. * Builds a circle to draw
  26579. *
  26580. * Ignored from docs since it is not directly exposed.
  26581. * @ignore
  26582. * @private
  26583. * @param {PIXI.WebGLGraphicsData} graphicsData - The graphics object to draw
  26584. * @param {object} webGLData - an object containing all the WebGL-specific information to create this shape
  26585. * @param {object} webGLDataNativeLines - an object containing all the WebGL-specific information to create nativeLines
  26586. */
  26587. var buildCircle = {
  26588. build: function (graphicsData) {
  26589. // need to convert points to a nice regular data
  26590. var points = graphicsData.points;
  26591. var x;
  26592. var y;
  26593. var dx;
  26594. var dy;
  26595. var rx;
  26596. var ry;
  26597. if (graphicsData.type === SHAPES.CIRC) {
  26598. var circle = graphicsData.shape;
  26599. x = circle.x;
  26600. y = circle.y;
  26601. rx = ry = circle.radius;
  26602. dx = dy = 0;
  26603. }
  26604. else if (graphicsData.type === SHAPES.ELIP) {
  26605. var ellipse = graphicsData.shape;
  26606. x = ellipse.x;
  26607. y = ellipse.y;
  26608. rx = ellipse.width;
  26609. ry = ellipse.height;
  26610. dx = dy = 0;
  26611. }
  26612. else {
  26613. var roundedRect = graphicsData.shape;
  26614. var halfWidth = roundedRect.width / 2;
  26615. var halfHeight = roundedRect.height / 2;
  26616. x = roundedRect.x + halfWidth;
  26617. y = roundedRect.y + halfHeight;
  26618. rx = ry = Math.max(0, Math.min(roundedRect.radius, Math.min(halfWidth, halfHeight)));
  26619. dx = halfWidth - rx;
  26620. dy = halfHeight - ry;
  26621. }
  26622. if (!(rx >= 0 && ry >= 0 && dx >= 0 && dy >= 0)) {
  26623. points.length = 0;
  26624. return;
  26625. }
  26626. // Choose a number of segments such that the maximum absolute deviation from the circle is approximately 0.029
  26627. var n = Math.ceil(2.3 * Math.sqrt(rx + ry));
  26628. var m = (n * 8) + (dx ? 4 : 0) + (dy ? 4 : 0);
  26629. points.length = m;
  26630. if (m === 0) {
  26631. return;
  26632. }
  26633. if (n === 0) {
  26634. points.length = 8;
  26635. points[0] = points[6] = x + dx;
  26636. points[1] = points[3] = y + dy;
  26637. points[2] = points[4] = x - dx;
  26638. points[5] = points[7] = y - dy;
  26639. return;
  26640. }
  26641. var j1 = 0;
  26642. var j2 = (n * 4) + (dx ? 2 : 0) + 2;
  26643. var j3 = j2;
  26644. var j4 = m;
  26645. {
  26646. var x0 = dx + rx;
  26647. var y0 = dy;
  26648. var x1 = x + x0;
  26649. var x2 = x - x0;
  26650. var y1 = y + y0;
  26651. points[j1++] = x1;
  26652. points[j1++] = y1;
  26653. points[--j2] = y1;
  26654. points[--j2] = x2;
  26655. if (dy) {
  26656. var y2 = y - y0;
  26657. points[j3++] = x2;
  26658. points[j3++] = y2;
  26659. points[--j4] = y2;
  26660. points[--j4] = x1;
  26661. }
  26662. }
  26663. for (var i = 1; i < n; i++) {
  26664. var a = Math.PI / 2 * (i / n);
  26665. var x0 = dx + (Math.cos(a) * rx);
  26666. var y0 = dy + (Math.sin(a) * ry);
  26667. var x1 = x + x0;
  26668. var x2 = x - x0;
  26669. var y1 = y + y0;
  26670. var y2 = y - y0;
  26671. points[j1++] = x1;
  26672. points[j1++] = y1;
  26673. points[--j2] = y1;
  26674. points[--j2] = x2;
  26675. points[j3++] = x2;
  26676. points[j3++] = y2;
  26677. points[--j4] = y2;
  26678. points[--j4] = x1;
  26679. }
  26680. {
  26681. var x0 = dx;
  26682. var y0 = dy + ry;
  26683. var x1 = x + x0;
  26684. var x2 = x - x0;
  26685. var y1 = y + y0;
  26686. var y2 = y - y0;
  26687. points[j1++] = x1;
  26688. points[j1++] = y1;
  26689. points[--j4] = y2;
  26690. points[--j4] = x1;
  26691. if (dx) {
  26692. points[j1++] = x2;
  26693. points[j1++] = y1;
  26694. points[--j4] = y2;
  26695. points[--j4] = x2;
  26696. }
  26697. }
  26698. },
  26699. triangulate: function (graphicsData, graphicsGeometry) {
  26700. var points = graphicsData.points;
  26701. var verts = graphicsGeometry.points;
  26702. var indices = graphicsGeometry.indices;
  26703. if (points.length === 0) {
  26704. return;
  26705. }
  26706. var vertPos = verts.length / 2;
  26707. var center = vertPos;
  26708. var x;
  26709. var y;
  26710. if (graphicsData.type !== SHAPES.RREC) {
  26711. var circle = graphicsData.shape;
  26712. x = circle.x;
  26713. y = circle.y;
  26714. }
  26715. else {
  26716. var roundedRect = graphicsData.shape;
  26717. x = roundedRect.x + (roundedRect.width / 2);
  26718. y = roundedRect.y + (roundedRect.height / 2);
  26719. }
  26720. var matrix = graphicsData.matrix;
  26721. // Push center (special point)
  26722. verts.push(graphicsData.matrix ? (matrix.a * x) + (matrix.c * y) + matrix.tx : x, graphicsData.matrix ? (matrix.b * x) + (matrix.d * y) + matrix.ty : y);
  26723. vertPos++;
  26724. verts.push(points[0], points[1]);
  26725. for (var i = 2; i < points.length; i += 2) {
  26726. verts.push(points[i], points[i + 1]);
  26727. // add some uvs
  26728. indices.push(vertPos++, center, vertPos);
  26729. }
  26730. indices.push(center + 1, center, vertPos);
  26731. },
  26732. };
  26733. /**
  26734. * Builds a rectangle to draw
  26735. *
  26736. * Ignored from docs since it is not directly exposed.
  26737. * @ignore
  26738. * @private
  26739. * @param {PIXI.WebGLGraphicsData} graphicsData - The graphics object containing all the necessary properties
  26740. * @param {object} webGLData - an object containing all the WebGL-specific information to create this shape
  26741. * @param {object} webGLDataNativeLines - an object containing all the WebGL-specific information to create nativeLines
  26742. */
  26743. var buildRectangle = {
  26744. build: function (graphicsData) {
  26745. // --- //
  26746. // need to convert points to a nice regular data
  26747. //
  26748. var rectData = graphicsData.shape;
  26749. var x = rectData.x;
  26750. var y = rectData.y;
  26751. var width = rectData.width;
  26752. var height = rectData.height;
  26753. var points = graphicsData.points;
  26754. points.length = 0;
  26755. points.push(x, y, x + width, y, x + width, y + height, x, y + height);
  26756. },
  26757. triangulate: function (graphicsData, graphicsGeometry) {
  26758. var points = graphicsData.points;
  26759. var verts = graphicsGeometry.points;
  26760. var vertPos = verts.length / 2;
  26761. verts.push(points[0], points[1], points[2], points[3], points[6], points[7], points[4], points[5]);
  26762. graphicsGeometry.indices.push(vertPos, vertPos + 1, vertPos + 2, vertPos + 1, vertPos + 2, vertPos + 3);
  26763. },
  26764. };
  26765. /**
  26766. * Calculate a single point for a quadratic bezier curve.
  26767. * Utility function used by quadraticBezierCurve.
  26768. * Ignored from docs since it is not directly exposed.
  26769. * @ignore
  26770. * @private
  26771. * @param {number} n1 - first number
  26772. * @param {number} n2 - second number
  26773. * @param {number} perc - percentage
  26774. * @returns {number} the result
  26775. */
  26776. function getPt(n1, n2, perc) {
  26777. var diff = n2 - n1;
  26778. return n1 + (diff * perc);
  26779. }
  26780. /**
  26781. * Calculate the points for a quadratic bezier curve. (helper function..)
  26782. * Based on: https://stackoverflow.com/questions/785097/how-do-i-implement-a-bezier-curve-in-c
  26783. *
  26784. * Ignored from docs since it is not directly exposed.
  26785. * @ignore
  26786. * @private
  26787. * @param {number} fromX - Origin point x
  26788. * @param {number} fromY - Origin point x
  26789. * @param {number} cpX - Control point x
  26790. * @param {number} cpY - Control point y
  26791. * @param {number} toX - Destination point x
  26792. * @param {number} toY - Destination point y
  26793. * @param {number[]} [out=[]] - The output array to add points into. If not passed, a new array is created.
  26794. * @returns {number[]} an array of points
  26795. */
  26796. function quadraticBezierCurve(fromX, fromY, cpX, cpY, toX, toY, out) {
  26797. if (out === void 0) { out = []; }
  26798. var n = 20;
  26799. var points = out;
  26800. var xa = 0;
  26801. var ya = 0;
  26802. var xb = 0;
  26803. var yb = 0;
  26804. var x = 0;
  26805. var y = 0;
  26806. for (var i = 0, j = 0; i <= n; ++i) {
  26807. j = i / n;
  26808. // The Green Line
  26809. xa = getPt(fromX, cpX, j);
  26810. ya = getPt(fromY, cpY, j);
  26811. xb = getPt(cpX, toX, j);
  26812. yb = getPt(cpY, toY, j);
  26813. // The Black Dot
  26814. x = getPt(xa, xb, j);
  26815. y = getPt(ya, yb, j);
  26816. // Handle case when first curve points overlaps and earcut fails to triangulate
  26817. if (i === 0 && points[points.length - 2] === x && points[points.length - 1] === y) {
  26818. continue;
  26819. }
  26820. points.push(x, y);
  26821. }
  26822. return points;
  26823. }
  26824. /**
  26825. * Builds a rounded rectangle to draw
  26826. *
  26827. * Ignored from docs since it is not directly exposed.
  26828. * @ignore
  26829. * @private
  26830. * @param {PIXI.WebGLGraphicsData} graphicsData - The graphics object containing all the necessary properties
  26831. * @param {object} webGLData - an object containing all the WebGL-specific information to create this shape
  26832. * @param {object} webGLDataNativeLines - an object containing all the WebGL-specific information to create nativeLines
  26833. */
  26834. var buildRoundedRectangle = {
  26835. build: function (graphicsData) {
  26836. if (Graphics.nextRoundedRectBehavior) {
  26837. buildCircle.build(graphicsData);
  26838. return;
  26839. }
  26840. var rrectData = graphicsData.shape;
  26841. var points = graphicsData.points;
  26842. var x = rrectData.x;
  26843. var y = rrectData.y;
  26844. var width = rrectData.width;
  26845. var height = rrectData.height;
  26846. // Don't allow negative radius or greater than half the smallest width
  26847. var radius = Math.max(0, Math.min(rrectData.radius, Math.min(width, height) / 2));
  26848. points.length = 0;
  26849. // No radius, do a simple rectangle
  26850. if (!radius) {
  26851. points.push(x, y, x + width, y, x + width, y + height, x, y + height);
  26852. }
  26853. else {
  26854. quadraticBezierCurve(x, y + radius, x, y, x + radius, y, points);
  26855. quadraticBezierCurve(x + width - radius, y, x + width, y, x + width, y + radius, points);
  26856. quadraticBezierCurve(x + width, y + height - radius, x + width, y + height, x + width - radius, y + height, points);
  26857. quadraticBezierCurve(x + radius, y + height, x, y + height, x, y + height - radius, points);
  26858. }
  26859. },
  26860. triangulate: function (graphicsData, graphicsGeometry) {
  26861. if (Graphics.nextRoundedRectBehavior) {
  26862. buildCircle.triangulate(graphicsData, graphicsGeometry);
  26863. return;
  26864. }
  26865. var points = graphicsData.points;
  26866. var verts = graphicsGeometry.points;
  26867. var indices = graphicsGeometry.indices;
  26868. var vecPos = verts.length / 2;
  26869. var triangles = earcut_1(points, null, 2);
  26870. for (var i = 0, j = triangles.length; i < j; i += 3) {
  26871. indices.push(triangles[i] + vecPos);
  26872. // indices.push(triangles[i] + vecPos);
  26873. indices.push(triangles[i + 1] + vecPos);
  26874. // indices.push(triangles[i + 2] + vecPos);
  26875. indices.push(triangles[i + 2] + vecPos);
  26876. }
  26877. for (var i = 0, j = points.length; i < j; i++) {
  26878. verts.push(points[i], points[++i]);
  26879. }
  26880. },
  26881. };
  26882. /**
  26883. * Buffers vertices to draw a square cap.
  26884. *
  26885. * Ignored from docs since it is not directly exposed.
  26886. * @ignore
  26887. * @private
  26888. * @param {number} x - X-coord of end point
  26889. * @param {number} y - Y-coord of end point
  26890. * @param {number} nx - X-coord of line normal pointing inside
  26891. * @param {number} ny - Y-coord of line normal pointing inside
  26892. * @param {number} innerWeight - Weight of inner points
  26893. * @param {number} outerWeight - Weight of outer points
  26894. * @param {boolean} clockwise - Whether the cap is drawn clockwise
  26895. * @param {Array<number>} verts - vertex buffer
  26896. * @returns {number} - no. of vertices pushed
  26897. */
  26898. function square(x, y, nx, ny, innerWeight, outerWeight, clockwise, /* rotation for square (true at left end, false at right end) */ verts) {
  26899. var ix = x - (nx * innerWeight);
  26900. var iy = y - (ny * innerWeight);
  26901. var ox = x + (nx * outerWeight);
  26902. var oy = y + (ny * outerWeight);
  26903. /* Rotate nx,ny for extension vector */
  26904. var exx;
  26905. var eyy;
  26906. if (clockwise) {
  26907. exx = ny;
  26908. eyy = -nx;
  26909. }
  26910. else {
  26911. exx = -ny;
  26912. eyy = nx;
  26913. }
  26914. /* [i|0]x,y extended at cap */
  26915. var eix = ix + exx;
  26916. var eiy = iy + eyy;
  26917. var eox = ox + exx;
  26918. var eoy = oy + eyy;
  26919. /* Square itself must be inserted clockwise*/
  26920. verts.push(eix, eiy);
  26921. verts.push(eox, eoy);
  26922. return 2;
  26923. }
  26924. /**
  26925. * Buffers vertices to draw an arc at the line joint or cap.
  26926. *
  26927. * Ignored from docs since it is not directly exposed.
  26928. * @ignore
  26929. * @private
  26930. * @param {number} cx - X-coord of center
  26931. * @param {number} cy - Y-coord of center
  26932. * @param {number} sx - X-coord of arc start
  26933. * @param {number} sy - Y-coord of arc start
  26934. * @param {number} ex - X-coord of arc end
  26935. * @param {number} ey - Y-coord of arc end
  26936. * @param {Array<number>} verts - buffer of vertices
  26937. * @param {boolean} clockwise - orientation of vertices
  26938. * @returns {number} - no. of vertices pushed
  26939. */
  26940. function round(cx, cy, sx, sy, ex, ey, verts, clockwise) {
  26941. var cx2p0x = sx - cx;
  26942. var cy2p0y = sy - cy;
  26943. var angle0 = Math.atan2(cx2p0x, cy2p0y);
  26944. var angle1 = Math.atan2(ex - cx, ey - cy);
  26945. if (clockwise && angle0 < angle1) {
  26946. angle0 += Math.PI * 2;
  26947. }
  26948. else if (!clockwise && angle0 > angle1) {
  26949. angle1 += Math.PI * 2;
  26950. }
  26951. var startAngle = angle0;
  26952. var angleDiff = angle1 - angle0;
  26953. var absAngleDiff = Math.abs(angleDiff);
  26954. /* if (absAngleDiff >= PI_LBOUND && absAngleDiff <= PI_UBOUND)
  26955. {
  26956. const r1x = cx - nxtPx;
  26957. const r1y = cy - nxtPy;
  26958. if (r1x === 0)
  26959. {
  26960. if (r1y > 0)
  26961. {
  26962. angleDiff = -angleDiff;
  26963. }
  26964. }
  26965. else if (r1x >= -GRAPHICS_CURVES.epsilon)
  26966. {
  26967. angleDiff = -angleDiff;
  26968. }
  26969. }*/
  26970. var radius = Math.sqrt((cx2p0x * cx2p0x) + (cy2p0y * cy2p0y));
  26971. var segCount = ((15 * absAngleDiff * Math.sqrt(radius) / Math.PI) >> 0) + 1;
  26972. var angleInc = angleDiff / segCount;
  26973. startAngle += angleInc;
  26974. if (clockwise) {
  26975. verts.push(cx, cy);
  26976. verts.push(sx, sy);
  26977. for (var i = 1, angle = startAngle; i < segCount; i++, angle += angleInc) {
  26978. verts.push(cx, cy);
  26979. verts.push(cx + ((Math.sin(angle) * radius)), cy + ((Math.cos(angle) * radius)));
  26980. }
  26981. verts.push(cx, cy);
  26982. verts.push(ex, ey);
  26983. }
  26984. else {
  26985. verts.push(sx, sy);
  26986. verts.push(cx, cy);
  26987. for (var i = 1, angle = startAngle; i < segCount; i++, angle += angleInc) {
  26988. verts.push(cx + ((Math.sin(angle) * radius)), cy + ((Math.cos(angle) * radius)));
  26989. verts.push(cx, cy);
  26990. }
  26991. verts.push(ex, ey);
  26992. verts.push(cx, cy);
  26993. }
  26994. return segCount * 2;
  26995. }
  26996. /**
  26997. * Builds a line to draw using the polygon method.
  26998. *
  26999. * Ignored from docs since it is not directly exposed.
  27000. * @ignore
  27001. * @private
  27002. * @param {PIXI.GraphicsData} graphicsData - The graphics object containing all the necessary properties
  27003. * @param {PIXI.GraphicsGeometry} graphicsGeometry - Geometry where to append output
  27004. */
  27005. function buildNonNativeLine(graphicsData, graphicsGeometry) {
  27006. var shape = graphicsData.shape;
  27007. var points = graphicsData.points || shape.points.slice();
  27008. var eps = graphicsGeometry.closePointEps;
  27009. if (points.length === 0) {
  27010. return;
  27011. }
  27012. // if the line width is an odd number add 0.5 to align to a whole pixel
  27013. // commenting this out fixes #711 and #1620
  27014. // if (graphicsData.lineWidth%2)
  27015. // {
  27016. // for (i = 0; i < points.length; i++)
  27017. // {
  27018. // points[i] += 0.5;
  27019. // }
  27020. // }
  27021. var style = graphicsData.lineStyle;
  27022. // get first and last point.. figure out the middle!
  27023. var firstPoint = new Point(points[0], points[1]);
  27024. var lastPoint = new Point(points[points.length - 2], points[points.length - 1]);
  27025. var closedShape = shape.type !== SHAPES.POLY || shape.closeStroke;
  27026. var closedPath = Math.abs(firstPoint.x - lastPoint.x) < eps
  27027. && Math.abs(firstPoint.y - lastPoint.y) < eps;
  27028. // if the first point is the last point - gonna have issues :)
  27029. if (closedShape) {
  27030. // need to clone as we are going to slightly modify the shape..
  27031. points = points.slice();
  27032. if (closedPath) {
  27033. points.pop();
  27034. points.pop();
  27035. lastPoint.set(points[points.length - 2], points[points.length - 1]);
  27036. }
  27037. var midPointX = (firstPoint.x + lastPoint.x) * 0.5;
  27038. var midPointY = (lastPoint.y + firstPoint.y) * 0.5;
  27039. points.unshift(midPointX, midPointY);
  27040. points.push(midPointX, midPointY);
  27041. }
  27042. var verts = graphicsGeometry.points;
  27043. var length = points.length / 2;
  27044. var indexCount = points.length;
  27045. var indexStart = verts.length / 2;
  27046. // Max. inner and outer width
  27047. var width = style.width / 2;
  27048. var widthSquared = width * width;
  27049. var miterLimitSquared = style.miterLimit * style.miterLimit;
  27050. /* Line segments of interest where (x1,y1) forms the corner. */
  27051. var x0 = points[0];
  27052. var y0 = points[1];
  27053. var x1 = points[2];
  27054. var y1 = points[3];
  27055. var x2 = 0;
  27056. var y2 = 0;
  27057. /* perp[?](x|y) = the line normal with magnitude lineWidth. */
  27058. var perpx = -(y0 - y1);
  27059. var perpy = x0 - x1;
  27060. var perp1x = 0;
  27061. var perp1y = 0;
  27062. var dist = Math.sqrt((perpx * perpx) + (perpy * perpy));
  27063. perpx /= dist;
  27064. perpy /= dist;
  27065. perpx *= width;
  27066. perpy *= width;
  27067. var ratio = style.alignment; // 0.5;
  27068. var innerWeight = (1 - ratio) * 2;
  27069. var outerWeight = ratio * 2;
  27070. if (!closedShape) {
  27071. if (style.cap === LINE_CAP.ROUND) {
  27072. indexCount += round(x0 - (perpx * (innerWeight - outerWeight) * 0.5), y0 - (perpy * (innerWeight - outerWeight) * 0.5), x0 - (perpx * innerWeight), y0 - (perpy * innerWeight), x0 + (perpx * outerWeight), y0 + (perpy * outerWeight), verts, true) + 2;
  27073. }
  27074. else if (style.cap === LINE_CAP.SQUARE) {
  27075. indexCount += square(x0, y0, perpx, perpy, innerWeight, outerWeight, true, verts);
  27076. }
  27077. }
  27078. // Push first point (below & above vertices)
  27079. verts.push(x0 - (perpx * innerWeight), y0 - (perpy * innerWeight));
  27080. verts.push(x0 + (perpx * outerWeight), y0 + (perpy * outerWeight));
  27081. for (var i = 1; i < length - 1; ++i) {
  27082. x0 = points[(i - 1) * 2];
  27083. y0 = points[((i - 1) * 2) + 1];
  27084. x1 = points[i * 2];
  27085. y1 = points[(i * 2) + 1];
  27086. x2 = points[(i + 1) * 2];
  27087. y2 = points[((i + 1) * 2) + 1];
  27088. perpx = -(y0 - y1);
  27089. perpy = x0 - x1;
  27090. dist = Math.sqrt((perpx * perpx) + (perpy * perpy));
  27091. perpx /= dist;
  27092. perpy /= dist;
  27093. perpx *= width;
  27094. perpy *= width;
  27095. perp1x = -(y1 - y2);
  27096. perp1y = x1 - x2;
  27097. dist = Math.sqrt((perp1x * perp1x) + (perp1y * perp1y));
  27098. perp1x /= dist;
  27099. perp1y /= dist;
  27100. perp1x *= width;
  27101. perp1y *= width;
  27102. /* d[x|y](0|1) = the component displacement between points p(0,1|1,2) */
  27103. var dx0 = x1 - x0;
  27104. var dy0 = y0 - y1;
  27105. var dx1 = x1 - x2;
  27106. var dy1 = y2 - y1;
  27107. /* +ve if internal angle < 90 degree, -ve if internal angle > 90 degree. */
  27108. var dot = (dx0 * dx1) + (dy0 * dy1);
  27109. /* +ve if internal angle counterclockwise, -ve if internal angle clockwise. */
  27110. var cross = (dy0 * dx1) - (dy1 * dx0);
  27111. var clockwise = (cross < 0);
  27112. /* Going nearly parallel? */
  27113. /* atan(0.001) ~= 0.001 rad ~= 0.057 degree */
  27114. if (Math.abs(cross) < 0.001 * Math.abs(dot)) {
  27115. verts.push(x1 - (perpx * innerWeight), y1 - (perpy * innerWeight));
  27116. verts.push(x1 + (perpx * outerWeight), y1 + (perpy * outerWeight));
  27117. /* 180 degree corner? */
  27118. if (dot >= 0) {
  27119. if (style.join === LINE_JOIN.ROUND) {
  27120. indexCount += round(x1, y1, x1 - (perpx * innerWeight), y1 - (perpy * innerWeight), x1 - (perp1x * innerWeight), y1 - (perp1y * innerWeight), verts, false) + 4;
  27121. }
  27122. else {
  27123. indexCount += 2;
  27124. }
  27125. verts.push(x1 - (perp1x * outerWeight), y1 - (perp1y * outerWeight));
  27126. verts.push(x1 + (perp1x * innerWeight), y1 + (perp1y * innerWeight));
  27127. }
  27128. continue;
  27129. }
  27130. /* p[x|y] is the miter point. pdist is the distance between miter point and p1. */
  27131. var c1 = ((-perpx + x0) * (-perpy + y1)) - ((-perpx + x1) * (-perpy + y0));
  27132. var c2 = ((-perp1x + x2) * (-perp1y + y1)) - ((-perp1x + x1) * (-perp1y + y2));
  27133. var px = ((dx0 * c2) - (dx1 * c1)) / cross;
  27134. var py = ((dy1 * c1) - (dy0 * c2)) / cross;
  27135. var pdist = ((px - x1) * (px - x1)) + ((py - y1) * (py - y1));
  27136. /* Inner miter point */
  27137. var imx = x1 + ((px - x1) * innerWeight);
  27138. var imy = y1 + ((py - y1) * innerWeight);
  27139. /* Outer miter point */
  27140. var omx = x1 - ((px - x1) * outerWeight);
  27141. var omy = y1 - ((py - y1) * outerWeight);
  27142. /* Is the inside miter point too far away, creating a spike? */
  27143. var smallerInsideSegmentSq = Math.min((dx0 * dx0) + (dy0 * dy0), (dx1 * dx1) + (dy1 * dy1));
  27144. var insideWeight = clockwise ? innerWeight : outerWeight;
  27145. var smallerInsideDiagonalSq = smallerInsideSegmentSq + (insideWeight * insideWeight * widthSquared);
  27146. var insideMiterOk = pdist <= smallerInsideDiagonalSq;
  27147. if (insideMiterOk) {
  27148. if (style.join === LINE_JOIN.BEVEL || pdist / widthSquared > miterLimitSquared) {
  27149. if (clockwise) /* rotating at inner angle */ {
  27150. verts.push(imx, imy); // inner miter point
  27151. verts.push(x1 + (perpx * outerWeight), y1 + (perpy * outerWeight)); // first segment's outer vertex
  27152. verts.push(imx, imy); // inner miter point
  27153. verts.push(x1 + (perp1x * outerWeight), y1 + (perp1y * outerWeight)); // second segment's outer vertex
  27154. }
  27155. else /* rotating at outer angle */ {
  27156. verts.push(x1 - (perpx * innerWeight), y1 - (perpy * innerWeight)); // first segment's inner vertex
  27157. verts.push(omx, omy); // outer miter point
  27158. verts.push(x1 - (perp1x * innerWeight), y1 - (perp1y * innerWeight)); // second segment's outer vertex
  27159. verts.push(omx, omy); // outer miter point
  27160. }
  27161. indexCount += 2;
  27162. }
  27163. else if (style.join === LINE_JOIN.ROUND) {
  27164. if (clockwise) /* arc is outside */ {
  27165. verts.push(imx, imy);
  27166. verts.push(x1 + (perpx * outerWeight), y1 + (perpy * outerWeight));
  27167. indexCount += round(x1, y1, x1 + (perpx * outerWeight), y1 + (perpy * outerWeight), x1 + (perp1x * outerWeight), y1 + (perp1y * outerWeight), verts, true) + 4;
  27168. verts.push(imx, imy);
  27169. verts.push(x1 + (perp1x * outerWeight), y1 + (perp1y * outerWeight));
  27170. }
  27171. else /* arc is inside */ {
  27172. verts.push(x1 - (perpx * innerWeight), y1 - (perpy * innerWeight));
  27173. verts.push(omx, omy);
  27174. indexCount += round(x1, y1, x1 - (perpx * innerWeight), y1 - (perpy * innerWeight), x1 - (perp1x * innerWeight), y1 - (perp1y * innerWeight), verts, false) + 4;
  27175. verts.push(x1 - (perp1x * innerWeight), y1 - (perp1y * innerWeight));
  27176. verts.push(omx, omy);
  27177. }
  27178. }
  27179. else {
  27180. verts.push(imx, imy);
  27181. verts.push(omx, omy);
  27182. }
  27183. }
  27184. else // inside miter is NOT ok
  27185. {
  27186. verts.push(x1 - (perpx * innerWeight), y1 - (perpy * innerWeight)); // first segment's inner vertex
  27187. verts.push(x1 + (perpx * outerWeight), y1 + (perpy * outerWeight)); // first segment's outer vertex
  27188. if (style.join === LINE_JOIN.ROUND) {
  27189. if (clockwise) /* arc is outside */ {
  27190. indexCount += round(x1, y1, x1 + (perpx * outerWeight), y1 + (perpy * outerWeight), x1 + (perp1x * outerWeight), y1 + (perp1y * outerWeight), verts, true) + 2;
  27191. }
  27192. else /* arc is inside */ {
  27193. indexCount += round(x1, y1, x1 - (perpx * innerWeight), y1 - (perpy * innerWeight), x1 - (perp1x * innerWeight), y1 - (perp1y * innerWeight), verts, false) + 2;
  27194. }
  27195. }
  27196. else if (style.join === LINE_JOIN.MITER && pdist / widthSquared <= miterLimitSquared) {
  27197. if (clockwise) {
  27198. verts.push(omx, omy); // inner miter point
  27199. verts.push(omx, omy); // inner miter point
  27200. }
  27201. else {
  27202. verts.push(imx, imy); // outer miter point
  27203. verts.push(imx, imy); // outer miter point
  27204. }
  27205. indexCount += 2;
  27206. }
  27207. verts.push(x1 - (perp1x * innerWeight), y1 - (perp1y * innerWeight)); // second segment's inner vertex
  27208. verts.push(x1 + (perp1x * outerWeight), y1 + (perp1y * outerWeight)); // second segment's outer vertex
  27209. indexCount += 2;
  27210. }
  27211. }
  27212. x0 = points[(length - 2) * 2];
  27213. y0 = points[((length - 2) * 2) + 1];
  27214. x1 = points[(length - 1) * 2];
  27215. y1 = points[((length - 1) * 2) + 1];
  27216. perpx = -(y0 - y1);
  27217. perpy = x0 - x1;
  27218. dist = Math.sqrt((perpx * perpx) + (perpy * perpy));
  27219. perpx /= dist;
  27220. perpy /= dist;
  27221. perpx *= width;
  27222. perpy *= width;
  27223. verts.push(x1 - (perpx * innerWeight), y1 - (perpy * innerWeight));
  27224. verts.push(x1 + (perpx * outerWeight), y1 + (perpy * outerWeight));
  27225. if (!closedShape) {
  27226. if (style.cap === LINE_CAP.ROUND) {
  27227. indexCount += round(x1 - (perpx * (innerWeight - outerWeight) * 0.5), y1 - (perpy * (innerWeight - outerWeight) * 0.5), x1 - (perpx * innerWeight), y1 - (perpy * innerWeight), x1 + (perpx * outerWeight), y1 + (perpy * outerWeight), verts, false) + 2;
  27228. }
  27229. else if (style.cap === LINE_CAP.SQUARE) {
  27230. indexCount += square(x1, y1, perpx, perpy, innerWeight, outerWeight, false, verts);
  27231. }
  27232. }
  27233. var indices = graphicsGeometry.indices;
  27234. var eps2 = GRAPHICS_CURVES.epsilon * GRAPHICS_CURVES.epsilon;
  27235. // indices.push(indexStart);
  27236. for (var i = indexStart; i < indexCount + indexStart - 2; ++i) {
  27237. x0 = verts[(i * 2)];
  27238. y0 = verts[(i * 2) + 1];
  27239. x1 = verts[(i + 1) * 2];
  27240. y1 = verts[((i + 1) * 2) + 1];
  27241. x2 = verts[(i + 2) * 2];
  27242. y2 = verts[((i + 2) * 2) + 1];
  27243. /* Skip zero area triangles */
  27244. if (Math.abs((x0 * (y1 - y2)) + (x1 * (y2 - y0)) + (x2 * (y0 - y1))) < eps2) {
  27245. continue;
  27246. }
  27247. indices.push(i, i + 1, i + 2);
  27248. }
  27249. }
  27250. /**
  27251. * Builds a line to draw using the gl.drawArrays(gl.LINES) method
  27252. *
  27253. * Ignored from docs since it is not directly exposed.
  27254. * @ignore
  27255. * @private
  27256. * @param {PIXI.GraphicsData} graphicsData - The graphics object containing all the necessary properties
  27257. * @param {PIXI.GraphicsGeometry} graphicsGeometry - Geometry where to append output
  27258. */
  27259. function buildNativeLine(graphicsData, graphicsGeometry) {
  27260. var i = 0;
  27261. var shape = graphicsData.shape;
  27262. var points = graphicsData.points || shape.points;
  27263. var closedShape = shape.type !== SHAPES.POLY || shape.closeStroke;
  27264. if (points.length === 0)
  27265. { return; }
  27266. var verts = graphicsGeometry.points;
  27267. var indices = graphicsGeometry.indices;
  27268. var length = points.length / 2;
  27269. var startIndex = verts.length / 2;
  27270. var currentIndex = startIndex;
  27271. verts.push(points[0], points[1]);
  27272. for (i = 1; i < length; i++) {
  27273. verts.push(points[i * 2], points[(i * 2) + 1]);
  27274. indices.push(currentIndex, currentIndex + 1);
  27275. currentIndex++;
  27276. }
  27277. if (closedShape) {
  27278. indices.push(currentIndex, startIndex);
  27279. }
  27280. }
  27281. /**
  27282. * Builds a line to draw
  27283. *
  27284. * Ignored from docs since it is not directly exposed.
  27285. * @ignore
  27286. * @private
  27287. * @param {PIXI.GraphicsData} graphicsData - The graphics object containing all the necessary properties
  27288. * @param {PIXI.GraphicsGeometry} graphicsGeometry - Geometry where to append output
  27289. */
  27290. function buildLine(graphicsData, graphicsGeometry) {
  27291. if (graphicsData.lineStyle.native) {
  27292. buildNativeLine(graphicsData, graphicsGeometry);
  27293. }
  27294. else {
  27295. buildNonNativeLine(graphicsData, graphicsGeometry);
  27296. }
  27297. }
  27298. /**
  27299. * Utilities for arc curves.
  27300. * @private
  27301. */
  27302. var ArcUtils = /** @class */ (function () {
  27303. function ArcUtils() {
  27304. }
  27305. /**
  27306. * The arcTo() method creates an arc/curve between two tangents on the canvas.
  27307. *
  27308. * "borrowed" from https://code.google.com/p/fxcanvas/ - thanks google!
  27309. * @private
  27310. * @param x1 - The x-coordinate of the beginning of the arc
  27311. * @param y1 - The y-coordinate of the beginning of the arc
  27312. * @param x2 - The x-coordinate of the end of the arc
  27313. * @param y2 - The y-coordinate of the end of the arc
  27314. * @param radius - The radius of the arc
  27315. * @param points -
  27316. * @returns - If the arc length is valid, return center of circle, radius and other info otherwise `null`.
  27317. */
  27318. ArcUtils.curveTo = function (x1, y1, x2, y2, radius, points) {
  27319. var fromX = points[points.length - 2];
  27320. var fromY = points[points.length - 1];
  27321. var a1 = fromY - y1;
  27322. var b1 = fromX - x1;
  27323. var a2 = y2 - y1;
  27324. var b2 = x2 - x1;
  27325. var mm = Math.abs((a1 * b2) - (b1 * a2));
  27326. if (mm < 1.0e-8 || radius === 0) {
  27327. if (points[points.length - 2] !== x1 || points[points.length - 1] !== y1) {
  27328. points.push(x1, y1);
  27329. }
  27330. return null;
  27331. }
  27332. var dd = (a1 * a1) + (b1 * b1);
  27333. var cc = (a2 * a2) + (b2 * b2);
  27334. var tt = (a1 * a2) + (b1 * b2);
  27335. var k1 = radius * Math.sqrt(dd) / mm;
  27336. var k2 = radius * Math.sqrt(cc) / mm;
  27337. var j1 = k1 * tt / dd;
  27338. var j2 = k2 * tt / cc;
  27339. var cx = (k1 * b2) + (k2 * b1);
  27340. var cy = (k1 * a2) + (k2 * a1);
  27341. var px = b1 * (k2 + j1);
  27342. var py = a1 * (k2 + j1);
  27343. var qx = b2 * (k1 + j2);
  27344. var qy = a2 * (k1 + j2);
  27345. var startAngle = Math.atan2(py - cy, px - cx);
  27346. var endAngle = Math.atan2(qy - cy, qx - cx);
  27347. return {
  27348. cx: (cx + x1),
  27349. cy: (cy + y1),
  27350. radius: radius,
  27351. startAngle: startAngle,
  27352. endAngle: endAngle,
  27353. anticlockwise: (b1 * a2 > b2 * a1),
  27354. };
  27355. };
  27356. /* eslint-disable max-len */
  27357. /**
  27358. * The arc method creates an arc/curve (used to create circles, or parts of circles).
  27359. * @private
  27360. * @param _startX - Start x location of arc
  27361. * @param _startY - Start y location of arc
  27362. * @param cx - The x-coordinate of the center of the circle
  27363. * @param cy - The y-coordinate of the center of the circle
  27364. * @param radius - The radius of the circle
  27365. * @param startAngle - The starting angle, in radians (0 is at the 3 o'clock position
  27366. * of the arc's circle)
  27367. * @param endAngle - The ending angle, in radians
  27368. * @param _anticlockwise - Specifies whether the drawing should be
  27369. * counter-clockwise or clockwise. False is default, and indicates clockwise, while true
  27370. * indicates counter-clockwise.
  27371. * @param points - Collection of points to add to
  27372. */
  27373. ArcUtils.arc = function (_startX, _startY, cx, cy, radius, startAngle, endAngle, _anticlockwise, points) {
  27374. var sweep = endAngle - startAngle;
  27375. var n = GRAPHICS_CURVES._segmentsCount(Math.abs(sweep) * radius, Math.ceil(Math.abs(sweep) / PI_2) * 40);
  27376. var theta = (sweep) / (n * 2);
  27377. var theta2 = theta * 2;
  27378. var cTheta = Math.cos(theta);
  27379. var sTheta = Math.sin(theta);
  27380. var segMinus = n - 1;
  27381. var remainder = (segMinus % 1) / segMinus;
  27382. for (var i = 0; i <= segMinus; ++i) {
  27383. var real = i + (remainder * i);
  27384. var angle = ((theta) + startAngle + (theta2 * real));
  27385. var c = Math.cos(angle);
  27386. var s = -Math.sin(angle);
  27387. points.push((((cTheta * c) + (sTheta * s)) * radius) + cx, (((cTheta * -s) + (sTheta * c)) * radius) + cy);
  27388. }
  27389. };
  27390. return ArcUtils;
  27391. }());
  27392. /**
  27393. * Utilities for bezier curves
  27394. * @private
  27395. */
  27396. var BezierUtils = /** @class */ (function () {
  27397. function BezierUtils() {
  27398. }
  27399. /**
  27400. * Calculate length of bezier curve.
  27401. * Analytical solution is impossible, since it involves an integral that does not integrate in general.
  27402. * Therefore numerical solution is used.
  27403. * @private
  27404. * @param fromX - Starting point x
  27405. * @param fromY - Starting point y
  27406. * @param cpX - Control point x
  27407. * @param cpY - Control point y
  27408. * @param cpX2 - Second Control point x
  27409. * @param cpY2 - Second Control point y
  27410. * @param toX - Destination point x
  27411. * @param toY - Destination point y
  27412. * @returns - Length of bezier curve
  27413. */
  27414. BezierUtils.curveLength = function (fromX, fromY, cpX, cpY, cpX2, cpY2, toX, toY) {
  27415. var n = 10;
  27416. var result = 0.0;
  27417. var t = 0.0;
  27418. var t2 = 0.0;
  27419. var t3 = 0.0;
  27420. var nt = 0.0;
  27421. var nt2 = 0.0;
  27422. var nt3 = 0.0;
  27423. var x = 0.0;
  27424. var y = 0.0;
  27425. var dx = 0.0;
  27426. var dy = 0.0;
  27427. var prevX = fromX;
  27428. var prevY = fromY;
  27429. for (var i = 1; i <= n; ++i) {
  27430. t = i / n;
  27431. t2 = t * t;
  27432. t3 = t2 * t;
  27433. nt = (1.0 - t);
  27434. nt2 = nt * nt;
  27435. nt3 = nt2 * nt;
  27436. x = (nt3 * fromX) + (3.0 * nt2 * t * cpX) + (3.0 * nt * t2 * cpX2) + (t3 * toX);
  27437. y = (nt3 * fromY) + (3.0 * nt2 * t * cpY) + (3 * nt * t2 * cpY2) + (t3 * toY);
  27438. dx = prevX - x;
  27439. dy = prevY - y;
  27440. prevX = x;
  27441. prevY = y;
  27442. result += Math.sqrt((dx * dx) + (dy * dy));
  27443. }
  27444. return result;
  27445. };
  27446. /**
  27447. * Calculate the points for a bezier curve and then draws it.
  27448. *
  27449. * Ignored from docs since it is not directly exposed.
  27450. * @ignore
  27451. * @param cpX - Control point x
  27452. * @param cpY - Control point y
  27453. * @param cpX2 - Second Control point x
  27454. * @param cpY2 - Second Control point y
  27455. * @param toX - Destination point x
  27456. * @param toY - Destination point y
  27457. * @param points - Path array to push points into
  27458. */
  27459. BezierUtils.curveTo = function (cpX, cpY, cpX2, cpY2, toX, toY, points) {
  27460. var fromX = points[points.length - 2];
  27461. var fromY = points[points.length - 1];
  27462. points.length -= 2;
  27463. var n = GRAPHICS_CURVES._segmentsCount(BezierUtils.curveLength(fromX, fromY, cpX, cpY, cpX2, cpY2, toX, toY));
  27464. var dt = 0;
  27465. var dt2 = 0;
  27466. var dt3 = 0;
  27467. var t2 = 0;
  27468. var t3 = 0;
  27469. points.push(fromX, fromY);
  27470. for (var i = 1, j = 0; i <= n; ++i) {
  27471. j = i / n;
  27472. dt = (1 - j);
  27473. dt2 = dt * dt;
  27474. dt3 = dt2 * dt;
  27475. t2 = j * j;
  27476. t3 = t2 * j;
  27477. points.push((dt3 * fromX) + (3 * dt2 * j * cpX) + (3 * dt * t2 * cpX2) + (t3 * toX), (dt3 * fromY) + (3 * dt2 * j * cpY) + (3 * dt * t2 * cpY2) + (t3 * toY));
  27478. }
  27479. };
  27480. return BezierUtils;
  27481. }());
  27482. /**
  27483. * Utilities for quadratic curves.
  27484. * @private
  27485. */
  27486. var QuadraticUtils = /** @class */ (function () {
  27487. function QuadraticUtils() {
  27488. }
  27489. /**
  27490. * Calculate length of quadratic curve
  27491. * @see {@link http://www.malczak.linuxpl.com/blog/quadratic-bezier-curve-length/}
  27492. * for the detailed explanation of math behind this.
  27493. * @private
  27494. * @param fromX - x-coordinate of curve start point
  27495. * @param fromY - y-coordinate of curve start point
  27496. * @param cpX - x-coordinate of curve control point
  27497. * @param cpY - y-coordinate of curve control point
  27498. * @param toX - x-coordinate of curve end point
  27499. * @param toY - y-coordinate of curve end point
  27500. * @returns - Length of quadratic curve
  27501. */
  27502. QuadraticUtils.curveLength = function (fromX, fromY, cpX, cpY, toX, toY) {
  27503. var ax = fromX - (2.0 * cpX) + toX;
  27504. var ay = fromY - (2.0 * cpY) + toY;
  27505. var bx = (2.0 * cpX) - (2.0 * fromX);
  27506. var by = (2.0 * cpY) - (2.0 * fromY);
  27507. var a = 4.0 * ((ax * ax) + (ay * ay));
  27508. var b = 4.0 * ((ax * bx) + (ay * by));
  27509. var c = (bx * bx) + (by * by);
  27510. var s = 2.0 * Math.sqrt(a + b + c);
  27511. var a2 = Math.sqrt(a);
  27512. var a32 = 2.0 * a * a2;
  27513. var c2 = 2.0 * Math.sqrt(c);
  27514. var ba = b / a2;
  27515. return ((a32 * s)
  27516. + (a2 * b * (s - c2))
  27517. + (((4.0 * c * a) - (b * b))
  27518. * Math.log(((2.0 * a2) + ba + s) / (ba + c2)))) / (4.0 * a32);
  27519. };
  27520. /**
  27521. * Calculate the points for a quadratic bezier curve and then draws it.
  27522. * Based on: https://stackoverflow.com/questions/785097/how-do-i-implement-a-bezier-curve-in-c
  27523. * @private
  27524. * @param cpX - Control point x
  27525. * @param cpY - Control point y
  27526. * @param toX - Destination point x
  27527. * @param toY - Destination point y
  27528. * @param points - Points to add segments to.
  27529. */
  27530. QuadraticUtils.curveTo = function (cpX, cpY, toX, toY, points) {
  27531. var fromX = points[points.length - 2];
  27532. var fromY = points[points.length - 1];
  27533. var n = GRAPHICS_CURVES._segmentsCount(QuadraticUtils.curveLength(fromX, fromY, cpX, cpY, toX, toY));
  27534. var xa = 0;
  27535. var ya = 0;
  27536. for (var i = 1; i <= n; ++i) {
  27537. var j = i / n;
  27538. xa = fromX + ((cpX - fromX) * j);
  27539. ya = fromY + ((cpY - fromY) * j);
  27540. points.push(xa + (((cpX + ((toX - cpX) * j)) - xa) * j), ya + (((cpY + ((toY - cpY) * j)) - ya) * j));
  27541. }
  27542. };
  27543. return QuadraticUtils;
  27544. }());
  27545. /**
  27546. * A structure to hold interim batch objects for Graphics.
  27547. * @memberof PIXI.graphicsUtils
  27548. */
  27549. var BatchPart = /** @class */ (function () {
  27550. function BatchPart() {
  27551. this.reset();
  27552. }
  27553. /**
  27554. * Begin batch part.
  27555. * @param style
  27556. * @param startIndex
  27557. * @param attribStart
  27558. */
  27559. BatchPart.prototype.begin = function (style, startIndex, attribStart) {
  27560. this.reset();
  27561. this.style = style;
  27562. this.start = startIndex;
  27563. this.attribStart = attribStart;
  27564. };
  27565. /**
  27566. * End batch part.
  27567. * @param endIndex
  27568. * @param endAttrib
  27569. */
  27570. BatchPart.prototype.end = function (endIndex, endAttrib) {
  27571. this.attribSize = endAttrib - this.attribStart;
  27572. this.size = endIndex - this.start;
  27573. };
  27574. BatchPart.prototype.reset = function () {
  27575. this.style = null;
  27576. this.size = 0;
  27577. this.start = 0;
  27578. this.attribStart = 0;
  27579. this.attribSize = 0;
  27580. };
  27581. return BatchPart;
  27582. }());
  27583. /**
  27584. * Generalized convenience utilities for Graphics.
  27585. * @namespace graphicsUtils
  27586. * @memberof PIXI
  27587. */
  27588. var _a;
  27589. /**
  27590. * Map of fill commands for each shape type.
  27591. * @memberof PIXI.graphicsUtils
  27592. * @member {object} FILL_COMMANDS
  27593. */
  27594. var FILL_COMMANDS = (_a = {},
  27595. _a[SHAPES.POLY] = buildPoly,
  27596. _a[SHAPES.CIRC] = buildCircle,
  27597. _a[SHAPES.ELIP] = buildCircle,
  27598. _a[SHAPES.RECT] = buildRectangle,
  27599. _a[SHAPES.RREC] = buildRoundedRectangle,
  27600. _a);
  27601. /**
  27602. * Batch pool, stores unused batches for preventing allocations.
  27603. * @memberof PIXI.graphicsUtils
  27604. * @member {Array<PIXI.graphicsUtils.BatchPart>} BATCH_POOL
  27605. */
  27606. var BATCH_POOL = [];
  27607. /**
  27608. * Draw call pool, stores unused draw calls for preventing allocations.
  27609. * @memberof PIXI.graphicsUtils
  27610. * @member {Array<PIXI.BatchDrawCall>} DRAW_CALL_POOL
  27611. */
  27612. var DRAW_CALL_POOL = [];
  27613. /**
  27614. * A class to contain data useful for Graphics objects
  27615. * @memberof PIXI
  27616. */
  27617. var GraphicsData = /** @class */ (function () {
  27618. /**
  27619. * @param {PIXI.Circle|PIXI.Ellipse|PIXI.Polygon|PIXI.Rectangle|PIXI.RoundedRectangle} shape - The shape object to draw.
  27620. * @param fillStyle - the width of the line to draw
  27621. * @param lineStyle - the color of the line to draw
  27622. * @param matrix - Transform matrix
  27623. */
  27624. function GraphicsData(shape, fillStyle, lineStyle, matrix) {
  27625. if (fillStyle === void 0) { fillStyle = null; }
  27626. if (lineStyle === void 0) { lineStyle = null; }
  27627. if (matrix === void 0) { matrix = null; }
  27628. /** The collection of points. */
  27629. this.points = [];
  27630. /** The collection of holes. */
  27631. this.holes = [];
  27632. this.shape = shape;
  27633. this.lineStyle = lineStyle;
  27634. this.fillStyle = fillStyle;
  27635. this.matrix = matrix;
  27636. this.type = shape.type;
  27637. }
  27638. /**
  27639. * Creates a new GraphicsData object with the same values as this one.
  27640. * @returns - Cloned GraphicsData object
  27641. */
  27642. GraphicsData.prototype.clone = function () {
  27643. return new GraphicsData(this.shape, this.fillStyle, this.lineStyle, this.matrix);
  27644. };
  27645. /** Destroys the Graphics data. */
  27646. GraphicsData.prototype.destroy = function () {
  27647. this.shape = null;
  27648. this.holes.length = 0;
  27649. this.holes = null;
  27650. this.points.length = 0;
  27651. this.points = null;
  27652. this.lineStyle = null;
  27653. this.fillStyle = null;
  27654. };
  27655. return GraphicsData;
  27656. }());
  27657. var tmpPoint = new Point();
  27658. /**
  27659. * The Graphics class contains methods used to draw primitive shapes such as lines, circles and
  27660. * rectangles to the display, and to color and fill them.
  27661. *
  27662. * GraphicsGeometry is designed to not be continually updating the geometry since it's expensive
  27663. * to re-tesselate using **earcut**. Consider using {@link PIXI.Mesh} for this use-case, it's much faster.
  27664. * @memberof PIXI
  27665. */
  27666. var GraphicsGeometry = /** @class */ (function (_super) {
  27667. __extends$e(GraphicsGeometry, _super);
  27668. // eslint-disable-next-line @typescript-eslint/no-useless-constructor
  27669. function GraphicsGeometry() {
  27670. var _this = _super.call(this) || this;
  27671. /** Minimal distance between points that are considered different. Affects line tesselation. */
  27672. _this.closePointEps = 1e-4;
  27673. /** Padding to add to the bounds. */
  27674. _this.boundsPadding = 0;
  27675. _this.uvsFloat32 = null;
  27676. _this.indicesUint16 = null;
  27677. _this.batchable = false;
  27678. /** An array of points to draw, 2 numbers per point */
  27679. _this.points = [];
  27680. /** The collection of colors */
  27681. _this.colors = [];
  27682. /** The UVs collection */
  27683. _this.uvs = [];
  27684. /** The indices of the vertices */
  27685. _this.indices = [];
  27686. /** Reference to the texture IDs. */
  27687. _this.textureIds = [];
  27688. /**
  27689. * The collection of drawn shapes.
  27690. * @member {PIXI.GraphicsData[]}
  27691. */
  27692. _this.graphicsData = [];
  27693. /**
  27694. * List of current draw calls drived from the batches.
  27695. * @member {PIXI.BatchDrawCall[]}
  27696. */
  27697. _this.drawCalls = [];
  27698. /** Batches need to regenerated if the geometry is updated. */
  27699. _this.batchDirty = -1;
  27700. /**
  27701. * Intermediate abstract format sent to batch system.
  27702. * Can be converted to drawCalls or to batchable objects.
  27703. * @member {PIXI.graphicsUtils.BatchPart[]}
  27704. */
  27705. _this.batches = [];
  27706. /** Used to detect if the graphics object has changed. */
  27707. _this.dirty = 0;
  27708. /** Used to check if the cache is dirty. */
  27709. _this.cacheDirty = -1;
  27710. /** Used to detect if we cleared the graphicsData. */
  27711. _this.clearDirty = 0;
  27712. /** Index of the last batched shape in the stack of calls. */
  27713. _this.shapeIndex = 0;
  27714. /** Cached bounds. */
  27715. _this._bounds = new Bounds();
  27716. /** The bounds dirty flag. */
  27717. _this.boundsDirty = -1;
  27718. return _this;
  27719. }
  27720. Object.defineProperty(GraphicsGeometry.prototype, "bounds", {
  27721. /**
  27722. * Get the current bounds of the graphic geometry.
  27723. * @readonly
  27724. */
  27725. get: function () {
  27726. this.updateBatches();
  27727. if (this.boundsDirty !== this.dirty) {
  27728. this.boundsDirty = this.dirty;
  27729. this.calculateBounds();
  27730. }
  27731. return this._bounds;
  27732. },
  27733. enumerable: false,
  27734. configurable: true
  27735. });
  27736. /** Call if you changed graphicsData manually. Empties all batch buffers. */
  27737. GraphicsGeometry.prototype.invalidate = function () {
  27738. this.boundsDirty = -1;
  27739. this.dirty++;
  27740. this.batchDirty++;
  27741. this.shapeIndex = 0;
  27742. this.points.length = 0;
  27743. this.colors.length = 0;
  27744. this.uvs.length = 0;
  27745. this.indices.length = 0;
  27746. this.textureIds.length = 0;
  27747. for (var i = 0; i < this.drawCalls.length; i++) {
  27748. this.drawCalls[i].texArray.clear();
  27749. DRAW_CALL_POOL.push(this.drawCalls[i]);
  27750. }
  27751. this.drawCalls.length = 0;
  27752. for (var i = 0; i < this.batches.length; i++) {
  27753. var batchPart = this.batches[i];
  27754. batchPart.reset();
  27755. BATCH_POOL.push(batchPart);
  27756. }
  27757. this.batches.length = 0;
  27758. };
  27759. /**
  27760. * Clears the graphics that were drawn to this Graphics object, and resets fill and line style settings.
  27761. * @returns - This GraphicsGeometry object. Good for chaining method calls
  27762. */
  27763. GraphicsGeometry.prototype.clear = function () {
  27764. if (this.graphicsData.length > 0) {
  27765. this.invalidate();
  27766. this.clearDirty++;
  27767. this.graphicsData.length = 0;
  27768. }
  27769. return this;
  27770. };
  27771. /**
  27772. * Draws the given shape to this Graphics object. Can be any of Circle, Rectangle, Ellipse, Line or Polygon.
  27773. * @param {PIXI.Circle|PIXI.Ellipse|PIXI.Polygon|PIXI.Rectangle|PIXI.RoundedRectangle} shape - The shape object to draw.
  27774. * @param fillStyle - Defines style of the fill.
  27775. * @param lineStyle - Defines style of the lines.
  27776. * @param matrix - Transform applied to the points of the shape.
  27777. * @returns - Returns geometry for chaining.
  27778. */
  27779. GraphicsGeometry.prototype.drawShape = function (shape, fillStyle, lineStyle, matrix) {
  27780. if (fillStyle === void 0) { fillStyle = null; }
  27781. if (lineStyle === void 0) { lineStyle = null; }
  27782. if (matrix === void 0) { matrix = null; }
  27783. var data = new GraphicsData(shape, fillStyle, lineStyle, matrix);
  27784. this.graphicsData.push(data);
  27785. this.dirty++;
  27786. return this;
  27787. };
  27788. /**
  27789. * Draws the given shape to this Graphics object. Can be any of Circle, Rectangle, Ellipse, Line or Polygon.
  27790. * @param {PIXI.Circle|PIXI.Ellipse|PIXI.Polygon|PIXI.Rectangle|PIXI.RoundedRectangle} shape - The shape object to draw.
  27791. * @param matrix - Transform applied to the points of the shape.
  27792. * @returns - Returns geometry for chaining.
  27793. */
  27794. GraphicsGeometry.prototype.drawHole = function (shape, matrix) {
  27795. if (matrix === void 0) { matrix = null; }
  27796. if (!this.graphicsData.length) {
  27797. return null;
  27798. }
  27799. var data = new GraphicsData(shape, null, null, matrix);
  27800. var lastShape = this.graphicsData[this.graphicsData.length - 1];
  27801. data.lineStyle = lastShape.lineStyle;
  27802. lastShape.holes.push(data);
  27803. this.dirty++;
  27804. return this;
  27805. };
  27806. /** Destroys the GraphicsGeometry object. */
  27807. GraphicsGeometry.prototype.destroy = function () {
  27808. _super.prototype.destroy.call(this);
  27809. // destroy each of the GraphicsData objects
  27810. for (var i = 0; i < this.graphicsData.length; ++i) {
  27811. this.graphicsData[i].destroy();
  27812. }
  27813. this.points.length = 0;
  27814. this.points = null;
  27815. this.colors.length = 0;
  27816. this.colors = null;
  27817. this.uvs.length = 0;
  27818. this.uvs = null;
  27819. this.indices.length = 0;
  27820. this.indices = null;
  27821. this.indexBuffer.destroy();
  27822. this.indexBuffer = null;
  27823. this.graphicsData.length = 0;
  27824. this.graphicsData = null;
  27825. this.drawCalls.length = 0;
  27826. this.drawCalls = null;
  27827. this.batches.length = 0;
  27828. this.batches = null;
  27829. this._bounds = null;
  27830. };
  27831. /**
  27832. * Check to see if a point is contained within this geometry.
  27833. * @param point - Point to check if it's contained.
  27834. * @returns {boolean} `true` if the point is contained within geometry.
  27835. */
  27836. GraphicsGeometry.prototype.containsPoint = function (point) {
  27837. var graphicsData = this.graphicsData;
  27838. for (var i = 0; i < graphicsData.length; ++i) {
  27839. var data = graphicsData[i];
  27840. if (!data.fillStyle.visible) {
  27841. continue;
  27842. }
  27843. // only deal with fills..
  27844. if (data.shape) {
  27845. if (data.matrix) {
  27846. data.matrix.applyInverse(point, tmpPoint);
  27847. }
  27848. else {
  27849. tmpPoint.copyFrom(point);
  27850. }
  27851. if (data.shape.contains(tmpPoint.x, tmpPoint.y)) {
  27852. var hitHole = false;
  27853. if (data.holes) {
  27854. for (var i_1 = 0; i_1 < data.holes.length; i_1++) {
  27855. var hole = data.holes[i_1];
  27856. if (hole.shape.contains(tmpPoint.x, tmpPoint.y)) {
  27857. hitHole = true;
  27858. break;
  27859. }
  27860. }
  27861. }
  27862. if (!hitHole) {
  27863. return true;
  27864. }
  27865. }
  27866. }
  27867. }
  27868. return false;
  27869. };
  27870. /**
  27871. * Generates intermediate batch data. Either gets converted to drawCalls
  27872. * or used to convert to batch objects directly by the Graphics object.
  27873. */
  27874. GraphicsGeometry.prototype.updateBatches = function () {
  27875. if (!this.graphicsData.length) {
  27876. this.batchable = true;
  27877. return;
  27878. }
  27879. if (!this.validateBatching()) {
  27880. return;
  27881. }
  27882. this.cacheDirty = this.dirty;
  27883. var uvs = this.uvs;
  27884. var graphicsData = this.graphicsData;
  27885. var batchPart = null;
  27886. var currentStyle = null;
  27887. if (this.batches.length > 0) {
  27888. batchPart = this.batches[this.batches.length - 1];
  27889. currentStyle = batchPart.style;
  27890. }
  27891. for (var i = this.shapeIndex; i < graphicsData.length; i++) {
  27892. this.shapeIndex++;
  27893. var data = graphicsData[i];
  27894. var fillStyle = data.fillStyle;
  27895. var lineStyle = data.lineStyle;
  27896. var command = FILL_COMMANDS[data.type];
  27897. // build out the shapes points..
  27898. command.build(data);
  27899. if (data.matrix) {
  27900. this.transformPoints(data.points, data.matrix);
  27901. }
  27902. if (fillStyle.visible || lineStyle.visible) {
  27903. this.processHoles(data.holes);
  27904. }
  27905. for (var j = 0; j < 2; j++) {
  27906. var style = (j === 0) ? fillStyle : lineStyle;
  27907. if (!style.visible)
  27908. { continue; }
  27909. var nextTexture = style.texture.baseTexture;
  27910. var index_1 = this.indices.length;
  27911. var attribIndex = this.points.length / 2;
  27912. nextTexture.wrapMode = WRAP_MODES.REPEAT;
  27913. if (j === 0) {
  27914. this.processFill(data);
  27915. }
  27916. else {
  27917. this.processLine(data);
  27918. }
  27919. var size = (this.points.length / 2) - attribIndex;
  27920. if (size === 0)
  27921. { continue; }
  27922. // close batch if style is different
  27923. if (batchPart && !this._compareStyles(currentStyle, style)) {
  27924. batchPart.end(index_1, attribIndex);
  27925. batchPart = null;
  27926. }
  27927. // spawn new batch if its first batch or previous was closed
  27928. if (!batchPart) {
  27929. batchPart = BATCH_POOL.pop() || new BatchPart();
  27930. batchPart.begin(style, index_1, attribIndex);
  27931. this.batches.push(batchPart);
  27932. currentStyle = style;
  27933. }
  27934. this.addUvs(this.points, uvs, style.texture, attribIndex, size, style.matrix);
  27935. }
  27936. }
  27937. var index = this.indices.length;
  27938. var attrib = this.points.length / 2;
  27939. if (batchPart) {
  27940. batchPart.end(index, attrib);
  27941. }
  27942. if (this.batches.length === 0) {
  27943. // there are no visible styles in GraphicsData
  27944. // its possible that someone wants Graphics just for the bounds
  27945. this.batchable = true;
  27946. return;
  27947. }
  27948. var need32 = attrib > 0xffff;
  27949. // prevent allocation when length is same as buffer
  27950. if (this.indicesUint16 && this.indices.length === this.indicesUint16.length
  27951. && need32 === (this.indicesUint16.BYTES_PER_ELEMENT > 2)) {
  27952. this.indicesUint16.set(this.indices);
  27953. }
  27954. else {
  27955. this.indicesUint16 = need32 ? new Uint32Array(this.indices) : new Uint16Array(this.indices);
  27956. }
  27957. // TODO make this a const..
  27958. this.batchable = this.isBatchable();
  27959. if (this.batchable) {
  27960. this.packBatches();
  27961. }
  27962. else {
  27963. this.buildDrawCalls();
  27964. }
  27965. };
  27966. /**
  27967. * Affinity check
  27968. * @param styleA
  27969. * @param styleB
  27970. */
  27971. GraphicsGeometry.prototype._compareStyles = function (styleA, styleB) {
  27972. if (!styleA || !styleB) {
  27973. return false;
  27974. }
  27975. if (styleA.texture.baseTexture !== styleB.texture.baseTexture) {
  27976. return false;
  27977. }
  27978. if (styleA.color + styleA.alpha !== styleB.color + styleB.alpha) {
  27979. return false;
  27980. }
  27981. if (!!styleA.native !== !!styleB.native) {
  27982. return false;
  27983. }
  27984. return true;
  27985. };
  27986. /** Test geometry for batching process. */
  27987. GraphicsGeometry.prototype.validateBatching = function () {
  27988. if (this.dirty === this.cacheDirty || !this.graphicsData.length) {
  27989. return false;
  27990. }
  27991. for (var i = 0, l = this.graphicsData.length; i < l; i++) {
  27992. var data = this.graphicsData[i];
  27993. var fill = data.fillStyle;
  27994. var line = data.lineStyle;
  27995. if (fill && !fill.texture.baseTexture.valid)
  27996. { return false; }
  27997. if (line && !line.texture.baseTexture.valid)
  27998. { return false; }
  27999. }
  28000. return true;
  28001. };
  28002. /** Offset the indices so that it works with the batcher. */
  28003. GraphicsGeometry.prototype.packBatches = function () {
  28004. this.batchDirty++;
  28005. this.uvsFloat32 = new Float32Array(this.uvs);
  28006. var batches = this.batches;
  28007. for (var i = 0, l = batches.length; i < l; i++) {
  28008. var batch = batches[i];
  28009. for (var j = 0; j < batch.size; j++) {
  28010. var index = batch.start + j;
  28011. this.indicesUint16[index] = this.indicesUint16[index] - batch.attribStart;
  28012. }
  28013. }
  28014. };
  28015. /**
  28016. * Checks to see if this graphics geometry can be batched.
  28017. * Currently it needs to be small enough and not contain any native lines.
  28018. */
  28019. GraphicsGeometry.prototype.isBatchable = function () {
  28020. // prevent heavy mesh batching
  28021. if (this.points.length > 0xffff * 2) {
  28022. return false;
  28023. }
  28024. var batches = this.batches;
  28025. for (var i = 0; i < batches.length; i++) {
  28026. if (batches[i].style.native) {
  28027. return false;
  28028. }
  28029. }
  28030. return (this.points.length < GraphicsGeometry.BATCHABLE_SIZE * 2);
  28031. };
  28032. /** Converts intermediate batches data to drawCalls. */
  28033. GraphicsGeometry.prototype.buildDrawCalls = function () {
  28034. var TICK = ++BaseTexture._globalBatch;
  28035. for (var i = 0; i < this.drawCalls.length; i++) {
  28036. this.drawCalls[i].texArray.clear();
  28037. DRAW_CALL_POOL.push(this.drawCalls[i]);
  28038. }
  28039. this.drawCalls.length = 0;
  28040. var colors = this.colors;
  28041. var textureIds = this.textureIds;
  28042. var currentGroup = DRAW_CALL_POOL.pop();
  28043. if (!currentGroup) {
  28044. currentGroup = new BatchDrawCall();
  28045. currentGroup.texArray = new BatchTextureArray();
  28046. }
  28047. currentGroup.texArray.count = 0;
  28048. currentGroup.start = 0;
  28049. currentGroup.size = 0;
  28050. currentGroup.type = DRAW_MODES.TRIANGLES;
  28051. var textureCount = 0;
  28052. var currentTexture = null;
  28053. var textureId = 0;
  28054. var native = false;
  28055. var drawMode = DRAW_MODES.TRIANGLES;
  28056. var index = 0;
  28057. this.drawCalls.push(currentGroup);
  28058. // TODO - this can be simplified
  28059. for (var i = 0; i < this.batches.length; i++) {
  28060. var data = this.batches[i];
  28061. // TODO add some full on MAX_TEXTURE CODE..
  28062. var MAX_TEXTURES = 8;
  28063. // Forced cast for checking `native` without errors
  28064. var style = data.style;
  28065. var nextTexture = style.texture.baseTexture;
  28066. if (native !== !!style.native) {
  28067. native = !!style.native;
  28068. drawMode = native ? DRAW_MODES.LINES : DRAW_MODES.TRIANGLES;
  28069. // force the batch to break!
  28070. currentTexture = null;
  28071. textureCount = MAX_TEXTURES;
  28072. TICK++;
  28073. }
  28074. if (currentTexture !== nextTexture) {
  28075. currentTexture = nextTexture;
  28076. if (nextTexture._batchEnabled !== TICK) {
  28077. if (textureCount === MAX_TEXTURES) {
  28078. TICK++;
  28079. textureCount = 0;
  28080. if (currentGroup.size > 0) {
  28081. currentGroup = DRAW_CALL_POOL.pop();
  28082. if (!currentGroup) {
  28083. currentGroup = new BatchDrawCall();
  28084. currentGroup.texArray = new BatchTextureArray();
  28085. }
  28086. this.drawCalls.push(currentGroup);
  28087. }
  28088. currentGroup.start = index;
  28089. currentGroup.size = 0;
  28090. currentGroup.texArray.count = 0;
  28091. currentGroup.type = drawMode;
  28092. }
  28093. // TODO add this to the render part..
  28094. // Hack! Because texture has protected `touched`
  28095. nextTexture.touched = 1; // touch;
  28096. nextTexture._batchEnabled = TICK;
  28097. nextTexture._batchLocation = textureCount;
  28098. nextTexture.wrapMode = WRAP_MODES.REPEAT;
  28099. currentGroup.texArray.elements[currentGroup.texArray.count++] = nextTexture;
  28100. textureCount++;
  28101. }
  28102. }
  28103. currentGroup.size += data.size;
  28104. index += data.size;
  28105. textureId = nextTexture._batchLocation;
  28106. this.addColors(colors, style.color, style.alpha, data.attribSize, data.attribStart);
  28107. this.addTextureIds(textureIds, textureId, data.attribSize, data.attribStart);
  28108. }
  28109. BaseTexture._globalBatch = TICK;
  28110. // upload..
  28111. // merge for now!
  28112. this.packAttributes();
  28113. };
  28114. /** Packs attributes to single buffer. */
  28115. GraphicsGeometry.prototype.packAttributes = function () {
  28116. var verts = this.points;
  28117. var uvs = this.uvs;
  28118. var colors = this.colors;
  28119. var textureIds = this.textureIds;
  28120. // verts are 2 positions.. so we * by 3 as there are 6 properties.. then 4 cos its bytes
  28121. var glPoints = new ArrayBuffer(verts.length * 3 * 4);
  28122. var f32 = new Float32Array(glPoints);
  28123. var u32 = new Uint32Array(glPoints);
  28124. var p = 0;
  28125. for (var i = 0; i < verts.length / 2; i++) {
  28126. f32[p++] = verts[i * 2];
  28127. f32[p++] = verts[(i * 2) + 1];
  28128. f32[p++] = uvs[i * 2];
  28129. f32[p++] = uvs[(i * 2) + 1];
  28130. u32[p++] = colors[i];
  28131. f32[p++] = textureIds[i];
  28132. }
  28133. this._buffer.update(glPoints);
  28134. this._indexBuffer.update(this.indicesUint16);
  28135. };
  28136. /**
  28137. * Process fill part of Graphics.
  28138. * @param data
  28139. */
  28140. GraphicsGeometry.prototype.processFill = function (data) {
  28141. if (data.holes.length) {
  28142. buildPoly.triangulate(data, this);
  28143. }
  28144. else {
  28145. var command = FILL_COMMANDS[data.type];
  28146. command.triangulate(data, this);
  28147. }
  28148. };
  28149. /**
  28150. * Process line part of Graphics.
  28151. * @param data
  28152. */
  28153. GraphicsGeometry.prototype.processLine = function (data) {
  28154. buildLine(data, this);
  28155. for (var i = 0; i < data.holes.length; i++) {
  28156. buildLine(data.holes[i], this);
  28157. }
  28158. };
  28159. /**
  28160. * Process the holes data.
  28161. * @param holes
  28162. */
  28163. GraphicsGeometry.prototype.processHoles = function (holes) {
  28164. for (var i = 0; i < holes.length; i++) {
  28165. var hole = holes[i];
  28166. var command = FILL_COMMANDS[hole.type];
  28167. command.build(hole);
  28168. if (hole.matrix) {
  28169. this.transformPoints(hole.points, hole.matrix);
  28170. }
  28171. }
  28172. };
  28173. /** Update the local bounds of the object. Expensive to use performance-wise. */
  28174. GraphicsGeometry.prototype.calculateBounds = function () {
  28175. var bounds = this._bounds;
  28176. bounds.clear();
  28177. bounds.addVertexData(this.points, 0, this.points.length);
  28178. bounds.pad(this.boundsPadding, this.boundsPadding);
  28179. };
  28180. /**
  28181. * Transform points using matrix.
  28182. * @param points - Points to transform
  28183. * @param matrix - Transform matrix
  28184. */
  28185. GraphicsGeometry.prototype.transformPoints = function (points, matrix) {
  28186. for (var i = 0; i < points.length / 2; i++) {
  28187. var x = points[(i * 2)];
  28188. var y = points[(i * 2) + 1];
  28189. points[(i * 2)] = (matrix.a * x) + (matrix.c * y) + matrix.tx;
  28190. points[(i * 2) + 1] = (matrix.b * x) + (matrix.d * y) + matrix.ty;
  28191. }
  28192. };
  28193. /**
  28194. * Add colors.
  28195. * @param colors - List of colors to add to
  28196. * @param color - Color to add
  28197. * @param alpha - Alpha to use
  28198. * @param size - Number of colors to add
  28199. * @param offset
  28200. */
  28201. GraphicsGeometry.prototype.addColors = function (colors, color, alpha, size, offset) {
  28202. if (offset === void 0) { offset = 0; }
  28203. // TODO use the premultiply bits Ivan added
  28204. var rgb = (color >> 16) + (color & 0xff00) + ((color & 0xff) << 16);
  28205. var rgba = premultiplyTint(rgb, alpha);
  28206. colors.length = Math.max(colors.length, offset + size);
  28207. for (var i = 0; i < size; i++) {
  28208. colors[offset + i] = rgba;
  28209. }
  28210. };
  28211. /**
  28212. * Add texture id that the shader/fragment wants to use.
  28213. * @param textureIds
  28214. * @param id
  28215. * @param size
  28216. * @param offset
  28217. */
  28218. GraphicsGeometry.prototype.addTextureIds = function (textureIds, id, size, offset) {
  28219. if (offset === void 0) { offset = 0; }
  28220. textureIds.length = Math.max(textureIds.length, offset + size);
  28221. for (var i = 0; i < size; i++) {
  28222. textureIds[offset + i] = id;
  28223. }
  28224. };
  28225. /**
  28226. * Generates the UVs for a shape.
  28227. * @param verts - Vertices
  28228. * @param uvs - UVs
  28229. * @param texture - Reference to Texture
  28230. * @param start - Index buffer start index.
  28231. * @param size - The size/length for index buffer.
  28232. * @param matrix - Optional transform for all points.
  28233. */
  28234. GraphicsGeometry.prototype.addUvs = function (verts, uvs, texture, start, size, matrix) {
  28235. if (matrix === void 0) { matrix = null; }
  28236. var index = 0;
  28237. var uvsStart = uvs.length;
  28238. var frame = texture.frame;
  28239. while (index < size) {
  28240. var x = verts[(start + index) * 2];
  28241. var y = verts[((start + index) * 2) + 1];
  28242. if (matrix) {
  28243. var nx = (matrix.a * x) + (matrix.c * y) + matrix.tx;
  28244. y = (matrix.b * x) + (matrix.d * y) + matrix.ty;
  28245. x = nx;
  28246. }
  28247. index++;
  28248. uvs.push(x / frame.width, y / frame.height);
  28249. }
  28250. var baseTexture = texture.baseTexture;
  28251. if (frame.width < baseTexture.width
  28252. || frame.height < baseTexture.height) {
  28253. this.adjustUvs(uvs, texture, uvsStart, size);
  28254. }
  28255. };
  28256. /**
  28257. * Modify uvs array according to position of texture region
  28258. * Does not work with rotated or trimmed textures
  28259. * @param uvs - array
  28260. * @param texture - region
  28261. * @param start - starting index for uvs
  28262. * @param size - how many points to adjust
  28263. */
  28264. GraphicsGeometry.prototype.adjustUvs = function (uvs, texture, start, size) {
  28265. var baseTexture = texture.baseTexture;
  28266. var eps = 1e-6;
  28267. var finish = start + (size * 2);
  28268. var frame = texture.frame;
  28269. var scaleX = frame.width / baseTexture.width;
  28270. var scaleY = frame.height / baseTexture.height;
  28271. var offsetX = frame.x / frame.width;
  28272. var offsetY = frame.y / frame.height;
  28273. var minX = Math.floor(uvs[start] + eps);
  28274. var minY = Math.floor(uvs[start + 1] + eps);
  28275. for (var i = start + 2; i < finish; i += 2) {
  28276. minX = Math.min(minX, Math.floor(uvs[i] + eps));
  28277. minY = Math.min(minY, Math.floor(uvs[i + 1] + eps));
  28278. }
  28279. offsetX -= minX;
  28280. offsetY -= minY;
  28281. for (var i = start; i < finish; i += 2) {
  28282. uvs[i] = (uvs[i] + offsetX) * scaleX;
  28283. uvs[i + 1] = (uvs[i + 1] + offsetY) * scaleY;
  28284. }
  28285. };
  28286. /**
  28287. * The maximum number of points to consider an object "batchable",
  28288. * able to be batched by the renderer's batch system.
  28289. \
  28290. */
  28291. GraphicsGeometry.BATCHABLE_SIZE = 100;
  28292. return GraphicsGeometry;
  28293. }(BatchGeometry));
  28294. /**
  28295. * Represents the line style for Graphics.
  28296. * @memberof PIXI
  28297. */
  28298. var LineStyle = /** @class */ (function (_super) {
  28299. __extends$e(LineStyle, _super);
  28300. function LineStyle() {
  28301. var _this = _super !== null && _super.apply(this, arguments) || this;
  28302. /** The width (thickness) of any lines drawn. */
  28303. _this.width = 0;
  28304. /** The alignment of any lines drawn (0.5 = middle, 1 = outer, 0 = inner). WebGL only. */
  28305. _this.alignment = 0.5;
  28306. /** If true the lines will be draw using LINES instead of TRIANGLE_STRIP. */
  28307. _this.native = false;
  28308. /**
  28309. * Line cap style.
  28310. * @member {PIXI.LINE_CAP}
  28311. * @default PIXI.LINE_CAP.BUTT
  28312. */
  28313. _this.cap = LINE_CAP.BUTT;
  28314. /**
  28315. * Line join style.
  28316. * @member {PIXI.LINE_JOIN}
  28317. * @default PIXI.LINE_JOIN.MITER
  28318. */
  28319. _this.join = LINE_JOIN.MITER;
  28320. /** Miter limit. */
  28321. _this.miterLimit = 10;
  28322. return _this;
  28323. }
  28324. /** Clones the object. */
  28325. LineStyle.prototype.clone = function () {
  28326. var obj = new LineStyle();
  28327. obj.color = this.color;
  28328. obj.alpha = this.alpha;
  28329. obj.texture = this.texture;
  28330. obj.matrix = this.matrix;
  28331. obj.visible = this.visible;
  28332. obj.width = this.width;
  28333. obj.alignment = this.alignment;
  28334. obj.native = this.native;
  28335. obj.cap = this.cap;
  28336. obj.join = this.join;
  28337. obj.miterLimit = this.miterLimit;
  28338. return obj;
  28339. };
  28340. /** Reset the line style to default. */
  28341. LineStyle.prototype.reset = function () {
  28342. _super.prototype.reset.call(this);
  28343. // Override default line style color
  28344. this.color = 0x0;
  28345. this.alignment = 0.5;
  28346. this.width = 0;
  28347. this.native = false;
  28348. };
  28349. return LineStyle;
  28350. }(FillStyle));
  28351. var temp = new Float32Array(3);
  28352. // a default shaders map used by graphics..
  28353. var DEFAULT_SHADERS = {};
  28354. /**
  28355. * The Graphics class is primarily used to render primitive shapes such as lines, circles and
  28356. * rectangles to the display, and to color and fill them. However, you can also use a Graphics
  28357. * object to build a list of primitives to use as a mask, or as a complex hitArea.
  28358. *
  28359. * Please note that due to legacy naming conventions, the behavior of some functions in this class
  28360. * can be confusing. Each call to `drawRect()`, `drawPolygon()`, etc. actually stores that primitive
  28361. * in the Geometry class's GraphicsGeometry object for later use in rendering or hit testing - the
  28362. * functions do not directly draw anything to the screen. Similarly, the `clear()` function doesn't
  28363. * change the screen, it simply resets the list of primitives, which can be useful if you want to
  28364. * rebuild the contents of an existing Graphics object.
  28365. *
  28366. * Once a GraphicsGeometry list is built, you can re-use it in other Geometry objects as
  28367. * an optimization, by passing it into a new Geometry object's constructor. Because of this
  28368. * ability, it's important to call `destroy()` on Geometry objects once you are done with them, to
  28369. * properly dereference each GraphicsGeometry and prevent memory leaks.
  28370. * @memberof PIXI
  28371. */
  28372. var Graphics = /** @class */ (function (_super) {
  28373. __extends$e(Graphics, _super);
  28374. /**
  28375. * @param geometry - Geometry to use, if omitted will create a new GraphicsGeometry instance.
  28376. */
  28377. function Graphics(geometry) {
  28378. if (geometry === void 0) { geometry = null; }
  28379. var _this = _super.call(this) || this;
  28380. /**
  28381. * Represents the vertex and fragment shaders that processes the geometry and runs on the GPU.
  28382. * Can be shared between multiple Graphics objects.
  28383. */
  28384. _this.shader = null;
  28385. /** Renderer plugin for batching */
  28386. _this.pluginName = 'batch';
  28387. /**
  28388. * Current path
  28389. * @readonly
  28390. */
  28391. _this.currentPath = null;
  28392. /** A collections of batches! These can be drawn by the renderer batch system. */
  28393. _this.batches = [];
  28394. /** Update dirty for limiting calculating tints for batches. */
  28395. _this.batchTint = -1;
  28396. /** Update dirty for limiting calculating batches.*/
  28397. _this.batchDirty = -1;
  28398. /** Copy of the object vertex data. */
  28399. _this.vertexData = null;
  28400. /** Current fill style. */
  28401. _this._fillStyle = new FillStyle();
  28402. /** Current line style. */
  28403. _this._lineStyle = new LineStyle();
  28404. /** Current shape transform matrix. */
  28405. _this._matrix = null;
  28406. /** Current hole mode is enabled. */
  28407. _this._holeMode = false;
  28408. /**
  28409. * Represents the WebGL state the Graphics required to render, excludes shader and geometry. E.g.,
  28410. * blend mode, culling, depth testing, direction of rendering triangles, backface, etc.
  28411. */
  28412. _this.state = State.for2d();
  28413. _this._geometry = geometry || new GraphicsGeometry();
  28414. _this._geometry.refCount++;
  28415. /**
  28416. * When cacheAsBitmap is set to true the graphics object will be rendered as if it was a sprite.
  28417. * This is useful if your graphics element does not change often, as it will speed up the rendering
  28418. * of the object in exchange for taking up texture memory. It is also useful if you need the graphics
  28419. * object to be anti-aliased, because it will be rendered using canvas. This is not recommended if
  28420. * you are constantly redrawing the graphics element.
  28421. * @name cacheAsBitmap
  28422. * @member {boolean}
  28423. * @memberof PIXI.Graphics#
  28424. * @default false
  28425. */
  28426. _this._transformID = -1;
  28427. // Set default
  28428. _this.tint = 0xFFFFFF;
  28429. _this.blendMode = BLEND_MODES.NORMAL;
  28430. return _this;
  28431. }
  28432. Object.defineProperty(Graphics.prototype, "geometry", {
  28433. /**
  28434. * Includes vertex positions, face indices, normals, colors, UVs, and
  28435. * custom attributes within buffers, reducing the cost of passing all
  28436. * this data to the GPU. Can be shared between multiple Mesh or Graphics objects.
  28437. * @readonly
  28438. */
  28439. get: function () {
  28440. return this._geometry;
  28441. },
  28442. enumerable: false,
  28443. configurable: true
  28444. });
  28445. /**
  28446. * Creates a new Graphics object with the same values as this one.
  28447. * Note that only the geometry of the object is cloned, not its transform (position,scale,etc)
  28448. * @returns - A clone of the graphics object
  28449. */
  28450. Graphics.prototype.clone = function () {
  28451. this.finishPoly();
  28452. return new Graphics(this._geometry);
  28453. };
  28454. Object.defineProperty(Graphics.prototype, "blendMode", {
  28455. get: function () {
  28456. return this.state.blendMode;
  28457. },
  28458. /**
  28459. * The blend mode to be applied to the graphic shape. Apply a value of
  28460. * `PIXI.BLEND_MODES.NORMAL` to reset the blend mode. Note that, since each
  28461. * primitive in the GraphicsGeometry list is rendered sequentially, modes
  28462. * such as `PIXI.BLEND_MODES.ADD` and `PIXI.BLEND_MODES.MULTIPLY` will
  28463. * be applied per-primitive.
  28464. * @default PIXI.BLEND_MODES.NORMAL
  28465. */
  28466. set: function (value) {
  28467. this.state.blendMode = value;
  28468. },
  28469. enumerable: false,
  28470. configurable: true
  28471. });
  28472. Object.defineProperty(Graphics.prototype, "tint", {
  28473. /**
  28474. * The tint applied to each graphic shape. This is a hex value. A value of
  28475. * 0xFFFFFF will remove any tint effect.
  28476. * @default 0xFFFFFF
  28477. */
  28478. get: function () {
  28479. return this._tint;
  28480. },
  28481. set: function (value) {
  28482. this._tint = value;
  28483. },
  28484. enumerable: false,
  28485. configurable: true
  28486. });
  28487. Object.defineProperty(Graphics.prototype, "fill", {
  28488. /**
  28489. * The current fill style.
  28490. * @readonly
  28491. */
  28492. get: function () {
  28493. return this._fillStyle;
  28494. },
  28495. enumerable: false,
  28496. configurable: true
  28497. });
  28498. Object.defineProperty(Graphics.prototype, "line", {
  28499. /**
  28500. * The current line style.
  28501. * @readonly
  28502. */
  28503. get: function () {
  28504. return this._lineStyle;
  28505. },
  28506. enumerable: false,
  28507. configurable: true
  28508. });
  28509. Graphics.prototype.lineStyle = function (options, color, alpha, alignment, native) {
  28510. if (options === void 0) { options = null; }
  28511. if (color === void 0) { color = 0x0; }
  28512. if (alpha === void 0) { alpha = 1; }
  28513. if (alignment === void 0) { alignment = 0.5; }
  28514. if (native === void 0) { native = false; }
  28515. // Support non-object params: (width, color, alpha, alignment, native)
  28516. if (typeof options === 'number') {
  28517. options = { width: options, color: color, alpha: alpha, alignment: alignment, native: native };
  28518. }
  28519. return this.lineTextureStyle(options);
  28520. };
  28521. /**
  28522. * Like line style but support texture for line fill.
  28523. * @param [options] - Collection of options for setting line style.
  28524. * @param {number} [options.width=0] - width of the line to draw, will update the objects stored style
  28525. * @param {PIXI.Texture} [options.texture=PIXI.Texture.WHITE] - Texture to use
  28526. * @param {number} [options.color=0x0] - color of the line to draw, will update the objects stored style.
  28527. * Default 0xFFFFFF if texture present.
  28528. * @param {number} [options.alpha=1] - alpha of the line to draw, will update the objects stored style
  28529. * @param {PIXI.Matrix} [options.matrix=null] - Texture matrix to transform texture
  28530. * @param {number} [options.alignment=0.5] - alignment of the line to draw, (0 = inner, 0.5 = middle, 1 = outer).
  28531. * WebGL only.
  28532. * @param {boolean} [options.native=false] - If true the lines will be draw using LINES instead of TRIANGLE_STRIP
  28533. * @param {PIXI.LINE_CAP}[options.cap=PIXI.LINE_CAP.BUTT] - line cap style
  28534. * @param {PIXI.LINE_JOIN}[options.join=PIXI.LINE_JOIN.MITER] - line join style
  28535. * @param {number}[options.miterLimit=10] - miter limit ratio
  28536. * @returns {PIXI.Graphics} This Graphics object. Good for chaining method calls
  28537. */
  28538. Graphics.prototype.lineTextureStyle = function (options) {
  28539. // Apply defaults
  28540. options = Object.assign({
  28541. width: 0,
  28542. texture: Texture.WHITE,
  28543. color: (options && options.texture) ? 0xFFFFFF : 0x0,
  28544. alpha: 1,
  28545. matrix: null,
  28546. alignment: 0.5,
  28547. native: false,
  28548. cap: LINE_CAP.BUTT,
  28549. join: LINE_JOIN.MITER,
  28550. miterLimit: 10,
  28551. }, options);
  28552. if (this.currentPath) {
  28553. this.startPoly();
  28554. }
  28555. var visible = options.width > 0 && options.alpha > 0;
  28556. if (!visible) {
  28557. this._lineStyle.reset();
  28558. }
  28559. else {
  28560. if (options.matrix) {
  28561. options.matrix = options.matrix.clone();
  28562. options.matrix.invert();
  28563. }
  28564. Object.assign(this._lineStyle, { visible: visible }, options);
  28565. }
  28566. return this;
  28567. };
  28568. /**
  28569. * Start a polygon object internally.
  28570. * @protected
  28571. */
  28572. Graphics.prototype.startPoly = function () {
  28573. if (this.currentPath) {
  28574. var points = this.currentPath.points;
  28575. var len = this.currentPath.points.length;
  28576. if (len > 2) {
  28577. this.drawShape(this.currentPath);
  28578. this.currentPath = new Polygon();
  28579. this.currentPath.closeStroke = false;
  28580. this.currentPath.points.push(points[len - 2], points[len - 1]);
  28581. }
  28582. }
  28583. else {
  28584. this.currentPath = new Polygon();
  28585. this.currentPath.closeStroke = false;
  28586. }
  28587. };
  28588. /**
  28589. * Finish the polygon object.
  28590. * @protected
  28591. */
  28592. Graphics.prototype.finishPoly = function () {
  28593. if (this.currentPath) {
  28594. if (this.currentPath.points.length > 2) {
  28595. this.drawShape(this.currentPath);
  28596. this.currentPath = null;
  28597. }
  28598. else {
  28599. this.currentPath.points.length = 0;
  28600. }
  28601. }
  28602. };
  28603. /**
  28604. * Moves the current drawing position to x, y.
  28605. * @param x - the X coordinate to move to
  28606. * @param y - the Y coordinate to move to
  28607. * @returns - This Graphics object. Good for chaining method calls
  28608. */
  28609. Graphics.prototype.moveTo = function (x, y) {
  28610. this.startPoly();
  28611. this.currentPath.points[0] = x;
  28612. this.currentPath.points[1] = y;
  28613. return this;
  28614. };
  28615. /**
  28616. * Draws a line using the current line style from the current drawing position to (x, y);
  28617. * The current drawing position is then set to (x, y).
  28618. * @param x - the X coordinate to draw to
  28619. * @param y - the Y coordinate to draw to
  28620. * @returns - This Graphics object. Good for chaining method calls
  28621. */
  28622. Graphics.prototype.lineTo = function (x, y) {
  28623. if (!this.currentPath) {
  28624. this.moveTo(0, 0);
  28625. }
  28626. // remove duplicates..
  28627. var points = this.currentPath.points;
  28628. var fromX = points[points.length - 2];
  28629. var fromY = points[points.length - 1];
  28630. if (fromX !== x || fromY !== y) {
  28631. points.push(x, y);
  28632. }
  28633. return this;
  28634. };
  28635. /**
  28636. * Initialize the curve
  28637. * @param x
  28638. * @param y
  28639. */
  28640. Graphics.prototype._initCurve = function (x, y) {
  28641. if (x === void 0) { x = 0; }
  28642. if (y === void 0) { y = 0; }
  28643. if (this.currentPath) {
  28644. if (this.currentPath.points.length === 0) {
  28645. this.currentPath.points = [x, y];
  28646. }
  28647. }
  28648. else {
  28649. this.moveTo(x, y);
  28650. }
  28651. };
  28652. /**
  28653. * Calculate the points for a quadratic bezier curve and then draws it.
  28654. * Based on: https://stackoverflow.com/questions/785097/how-do-i-implement-a-bezier-curve-in-c
  28655. * @param cpX - Control point x
  28656. * @param cpY - Control point y
  28657. * @param toX - Destination point x
  28658. * @param toY - Destination point y
  28659. * @returns - This Graphics object. Good for chaining method calls
  28660. */
  28661. Graphics.prototype.quadraticCurveTo = function (cpX, cpY, toX, toY) {
  28662. this._initCurve();
  28663. var points = this.currentPath.points;
  28664. if (points.length === 0) {
  28665. this.moveTo(0, 0);
  28666. }
  28667. QuadraticUtils.curveTo(cpX, cpY, toX, toY, points);
  28668. return this;
  28669. };
  28670. /**
  28671. * Calculate the points for a bezier curve and then draws it.
  28672. * @param cpX - Control point x
  28673. * @param cpY - Control point y
  28674. * @param cpX2 - Second Control point x
  28675. * @param cpY2 - Second Control point y
  28676. * @param toX - Destination point x
  28677. * @param toY - Destination point y
  28678. * @returns This Graphics object. Good for chaining method calls
  28679. */
  28680. Graphics.prototype.bezierCurveTo = function (cpX, cpY, cpX2, cpY2, toX, toY) {
  28681. this._initCurve();
  28682. BezierUtils.curveTo(cpX, cpY, cpX2, cpY2, toX, toY, this.currentPath.points);
  28683. return this;
  28684. };
  28685. /**
  28686. * The arcTo() method creates an arc/curve between two tangents on the canvas.
  28687. *
  28688. * "borrowed" from https://code.google.com/p/fxcanvas/ - thanks google!
  28689. * @param x1 - The x-coordinate of the first tangent point of the arc
  28690. * @param y1 - The y-coordinate of the first tangent point of the arc
  28691. * @param x2 - The x-coordinate of the end of the arc
  28692. * @param y2 - The y-coordinate of the end of the arc
  28693. * @param radius - The radius of the arc
  28694. * @returns - This Graphics object. Good for chaining method calls
  28695. */
  28696. Graphics.prototype.arcTo = function (x1, y1, x2, y2, radius) {
  28697. this._initCurve(x1, y1);
  28698. var points = this.currentPath.points;
  28699. var result = ArcUtils.curveTo(x1, y1, x2, y2, radius, points);
  28700. if (result) {
  28701. var cx = result.cx, cy = result.cy, radius_1 = result.radius, startAngle = result.startAngle, endAngle = result.endAngle, anticlockwise = result.anticlockwise;
  28702. this.arc(cx, cy, radius_1, startAngle, endAngle, anticlockwise);
  28703. }
  28704. return this;
  28705. };
  28706. /**
  28707. * The arc method creates an arc/curve (used to create circles, or parts of circles).
  28708. * @param cx - The x-coordinate of the center of the circle
  28709. * @param cy - The y-coordinate of the center of the circle
  28710. * @param radius - The radius of the circle
  28711. * @param startAngle - The starting angle, in radians (0 is at the 3 o'clock position
  28712. * of the arc's circle)
  28713. * @param endAngle - The ending angle, in radians
  28714. * @param anticlockwise - Specifies whether the drawing should be
  28715. * counter-clockwise or clockwise. False is default, and indicates clockwise, while true
  28716. * indicates counter-clockwise.
  28717. * @returns - This Graphics object. Good for chaining method calls
  28718. */
  28719. Graphics.prototype.arc = function (cx, cy, radius, startAngle, endAngle, anticlockwise) {
  28720. if (anticlockwise === void 0) { anticlockwise = false; }
  28721. if (startAngle === endAngle) {
  28722. return this;
  28723. }
  28724. if (!anticlockwise && endAngle <= startAngle) {
  28725. endAngle += PI_2;
  28726. }
  28727. else if (anticlockwise && startAngle <= endAngle) {
  28728. startAngle += PI_2;
  28729. }
  28730. var sweep = endAngle - startAngle;
  28731. if (sweep === 0) {
  28732. return this;
  28733. }
  28734. var startX = cx + (Math.cos(startAngle) * radius);
  28735. var startY = cy + (Math.sin(startAngle) * radius);
  28736. var eps = this._geometry.closePointEps;
  28737. // If the currentPath exists, take its points. Otherwise call `moveTo` to start a path.
  28738. var points = this.currentPath ? this.currentPath.points : null;
  28739. if (points) {
  28740. // TODO: make a better fix.
  28741. // We check how far our start is from the last existing point
  28742. var xDiff = Math.abs(points[points.length - 2] - startX);
  28743. var yDiff = Math.abs(points[points.length - 1] - startY);
  28744. if (xDiff < eps && yDiff < eps) { ; }
  28745. else {
  28746. points.push(startX, startY);
  28747. }
  28748. }
  28749. else {
  28750. this.moveTo(startX, startY);
  28751. points = this.currentPath.points;
  28752. }
  28753. ArcUtils.arc(startX, startY, cx, cy, radius, startAngle, endAngle, anticlockwise, points);
  28754. return this;
  28755. };
  28756. /**
  28757. * Specifies a simple one-color fill that subsequent calls to other Graphics methods
  28758. * (such as lineTo() or drawCircle()) use when drawing.
  28759. * @param color - the color of the fill
  28760. * @param alpha - the alpha of the fill
  28761. * @returns - This Graphics object. Good for chaining method calls
  28762. */
  28763. Graphics.prototype.beginFill = function (color, alpha) {
  28764. if (color === void 0) { color = 0; }
  28765. if (alpha === void 0) { alpha = 1; }
  28766. return this.beginTextureFill({ texture: Texture.WHITE, color: color, alpha: alpha });
  28767. };
  28768. /**
  28769. * Begin the texture fill
  28770. * @param options - Object object.
  28771. * @param {PIXI.Texture} [options.texture=PIXI.Texture.WHITE] - Texture to fill
  28772. * @param {number} [options.color=0xffffff] - Background to fill behind texture
  28773. * @param {number} [options.alpha=1] - Alpha of fill
  28774. * @param {PIXI.Matrix} [options.matrix=null] - Transform matrix
  28775. * @returns {PIXI.Graphics} This Graphics object. Good for chaining method calls
  28776. */
  28777. Graphics.prototype.beginTextureFill = function (options) {
  28778. // Apply defaults
  28779. options = Object.assign({
  28780. texture: Texture.WHITE,
  28781. color: 0xFFFFFF,
  28782. alpha: 1,
  28783. matrix: null,
  28784. }, options);
  28785. if (this.currentPath) {
  28786. this.startPoly();
  28787. }
  28788. var visible = options.alpha > 0;
  28789. if (!visible) {
  28790. this._fillStyle.reset();
  28791. }
  28792. else {
  28793. if (options.matrix) {
  28794. options.matrix = options.matrix.clone();
  28795. options.matrix.invert();
  28796. }
  28797. Object.assign(this._fillStyle, { visible: visible }, options);
  28798. }
  28799. return this;
  28800. };
  28801. /**
  28802. * Applies a fill to the lines and shapes that were added since the last call to the beginFill() method.
  28803. * @returns - This Graphics object. Good for chaining method calls
  28804. */
  28805. Graphics.prototype.endFill = function () {
  28806. this.finishPoly();
  28807. this._fillStyle.reset();
  28808. return this;
  28809. };
  28810. /**
  28811. * Draws a rectangle shape.
  28812. * @param x - The X coord of the top-left of the rectangle
  28813. * @param y - The Y coord of the top-left of the rectangle
  28814. * @param width - The width of the rectangle
  28815. * @param height - The height of the rectangle
  28816. * @returns - This Graphics object. Good for chaining method calls
  28817. */
  28818. Graphics.prototype.drawRect = function (x, y, width, height) {
  28819. return this.drawShape(new Rectangle(x, y, width, height));
  28820. };
  28821. /**
  28822. * Draw a rectangle shape with rounded/beveled corners.
  28823. * @param x - The X coord of the top-left of the rectangle
  28824. * @param y - The Y coord of the top-left of the rectangle
  28825. * @param width - The width of the rectangle
  28826. * @param height - The height of the rectangle
  28827. * @param radius - Radius of the rectangle corners
  28828. * @returns - This Graphics object. Good for chaining method calls
  28829. */
  28830. Graphics.prototype.drawRoundedRect = function (x, y, width, height, radius) {
  28831. return this.drawShape(new RoundedRectangle(x, y, width, height, radius));
  28832. };
  28833. /**
  28834. * Draws a circle.
  28835. * @param x - The X coordinate of the center of the circle
  28836. * @param y - The Y coordinate of the center of the circle
  28837. * @param radius - The radius of the circle
  28838. * @returns - This Graphics object. Good for chaining method calls
  28839. */
  28840. Graphics.prototype.drawCircle = function (x, y, radius) {
  28841. return this.drawShape(new Circle(x, y, radius));
  28842. };
  28843. /**
  28844. * Draws an ellipse.
  28845. * @param x - The X coordinate of the center of the ellipse
  28846. * @param y - The Y coordinate of the center of the ellipse
  28847. * @param width - The half width of the ellipse
  28848. * @param height - The half height of the ellipse
  28849. * @returns - This Graphics object. Good for chaining method calls
  28850. */
  28851. Graphics.prototype.drawEllipse = function (x, y, width, height) {
  28852. return this.drawShape(new Ellipse(x, y, width, height));
  28853. };
  28854. /**
  28855. * Draws a polygon using the given path.
  28856. * @param {number[]|PIXI.IPointData[]|PIXI.Polygon} path - The path data used to construct the polygon.
  28857. * @returns - This Graphics object. Good for chaining method calls
  28858. */
  28859. Graphics.prototype.drawPolygon = function () {
  28860. var arguments$1 = arguments;
  28861. var path = [];
  28862. for (var _i = 0; _i < arguments.length; _i++) {
  28863. path[_i] = arguments$1[_i];
  28864. }
  28865. var points;
  28866. var closeStroke = true; // !!this._fillStyle;
  28867. var poly = path[0];
  28868. // check if data has points..
  28869. if (poly.points) {
  28870. closeStroke = poly.closeStroke;
  28871. points = poly.points;
  28872. }
  28873. else if (Array.isArray(path[0])) {
  28874. points = path[0];
  28875. }
  28876. else {
  28877. points = path;
  28878. }
  28879. var shape = new Polygon(points);
  28880. shape.closeStroke = closeStroke;
  28881. this.drawShape(shape);
  28882. return this;
  28883. };
  28884. /**
  28885. * Draw any shape.
  28886. * @param {PIXI.Circle|PIXI.Ellipse|PIXI.Polygon|PIXI.Rectangle|PIXI.RoundedRectangle} shape - Shape to draw
  28887. * @returns - This Graphics object. Good for chaining method calls
  28888. */
  28889. Graphics.prototype.drawShape = function (shape) {
  28890. if (!this._holeMode) {
  28891. this._geometry.drawShape(shape, this._fillStyle.clone(), this._lineStyle.clone(), this._matrix);
  28892. }
  28893. else {
  28894. this._geometry.drawHole(shape, this._matrix);
  28895. }
  28896. return this;
  28897. };
  28898. /**
  28899. * Clears the graphics that were drawn to this Graphics object, and resets fill and line style settings.
  28900. * @returns - This Graphics object. Good for chaining method calls
  28901. */
  28902. Graphics.prototype.clear = function () {
  28903. this._geometry.clear();
  28904. this._lineStyle.reset();
  28905. this._fillStyle.reset();
  28906. this._boundsID++;
  28907. this._matrix = null;
  28908. this._holeMode = false;
  28909. this.currentPath = null;
  28910. return this;
  28911. };
  28912. /**
  28913. * True if graphics consists of one rectangle, and thus, can be drawn like a Sprite and
  28914. * masked with gl.scissor.
  28915. * @returns - True if only 1 rect.
  28916. */
  28917. Graphics.prototype.isFastRect = function () {
  28918. var data = this._geometry.graphicsData;
  28919. return data.length === 1
  28920. && data[0].shape.type === SHAPES.RECT
  28921. && !data[0].matrix
  28922. && !data[0].holes.length
  28923. && !(data[0].lineStyle.visible && data[0].lineStyle.width);
  28924. };
  28925. /**
  28926. * Renders the object using the WebGL renderer
  28927. * @param renderer - The renderer
  28928. */
  28929. Graphics.prototype._render = function (renderer) {
  28930. this.finishPoly();
  28931. var geometry = this._geometry;
  28932. // batch part..
  28933. // batch it!
  28934. geometry.updateBatches();
  28935. if (geometry.batchable) {
  28936. if (this.batchDirty !== geometry.batchDirty) {
  28937. this._populateBatches();
  28938. }
  28939. this._renderBatched(renderer);
  28940. }
  28941. else {
  28942. // no batching...
  28943. renderer.batch.flush();
  28944. this._renderDirect(renderer);
  28945. }
  28946. };
  28947. /** Populating batches for rendering. */
  28948. Graphics.prototype._populateBatches = function () {
  28949. var geometry = this._geometry;
  28950. var blendMode = this.blendMode;
  28951. var len = geometry.batches.length;
  28952. this.batchTint = -1;
  28953. this._transformID = -1;
  28954. this.batchDirty = geometry.batchDirty;
  28955. this.batches.length = len;
  28956. this.vertexData = new Float32Array(geometry.points);
  28957. for (var i = 0; i < len; i++) {
  28958. var gI = geometry.batches[i];
  28959. var color = gI.style.color;
  28960. var vertexData = new Float32Array(this.vertexData.buffer, gI.attribStart * 4 * 2, gI.attribSize * 2);
  28961. var uvs = new Float32Array(geometry.uvsFloat32.buffer, gI.attribStart * 4 * 2, gI.attribSize * 2);
  28962. var indices = new Uint16Array(geometry.indicesUint16.buffer, gI.start * 2, gI.size);
  28963. var batch = {
  28964. vertexData: vertexData,
  28965. blendMode: blendMode,
  28966. indices: indices,
  28967. uvs: uvs,
  28968. _batchRGB: hex2rgb(color),
  28969. _tintRGB: color,
  28970. _texture: gI.style.texture,
  28971. alpha: gI.style.alpha,
  28972. worldAlpha: 1
  28973. };
  28974. this.batches[i] = batch;
  28975. }
  28976. };
  28977. /**
  28978. * Renders the batches using the BathedRenderer plugin
  28979. * @param renderer - The renderer
  28980. */
  28981. Graphics.prototype._renderBatched = function (renderer) {
  28982. if (!this.batches.length) {
  28983. return;
  28984. }
  28985. renderer.batch.setObjectRenderer(renderer.plugins[this.pluginName]);
  28986. this.calculateVertices();
  28987. this.calculateTints();
  28988. for (var i = 0, l = this.batches.length; i < l; i++) {
  28989. var batch = this.batches[i];
  28990. batch.worldAlpha = this.worldAlpha * batch.alpha;
  28991. renderer.plugins[this.pluginName].render(batch);
  28992. }
  28993. };
  28994. /**
  28995. * Renders the graphics direct
  28996. * @param renderer - The renderer
  28997. */
  28998. Graphics.prototype._renderDirect = function (renderer) {
  28999. var shader = this._resolveDirectShader(renderer);
  29000. var geometry = this._geometry;
  29001. var tint = this.tint;
  29002. var worldAlpha = this.worldAlpha;
  29003. var uniforms = shader.uniforms;
  29004. var drawCalls = geometry.drawCalls;
  29005. // lets set the transfomr
  29006. uniforms.translationMatrix = this.transform.worldTransform;
  29007. // and then lets set the tint..
  29008. uniforms.tint[0] = (((tint >> 16) & 0xFF) / 255) * worldAlpha;
  29009. uniforms.tint[1] = (((tint >> 8) & 0xFF) / 255) * worldAlpha;
  29010. uniforms.tint[2] = ((tint & 0xFF) / 255) * worldAlpha;
  29011. uniforms.tint[3] = worldAlpha;
  29012. // the first draw call, we can set the uniforms of the shader directly here.
  29013. // this means that we can tack advantage of the sync function of pixi!
  29014. // bind and sync uniforms..
  29015. // there is a way to optimise this..
  29016. renderer.shader.bind(shader);
  29017. renderer.geometry.bind(geometry, shader);
  29018. // set state..
  29019. renderer.state.set(this.state);
  29020. // then render the rest of them...
  29021. for (var i = 0, l = drawCalls.length; i < l; i++) {
  29022. this._renderDrawCallDirect(renderer, geometry.drawCalls[i]);
  29023. }
  29024. };
  29025. /**
  29026. * Renders specific DrawCall
  29027. * @param renderer
  29028. * @param drawCall
  29029. */
  29030. Graphics.prototype._renderDrawCallDirect = function (renderer, drawCall) {
  29031. var texArray = drawCall.texArray, type = drawCall.type, size = drawCall.size, start = drawCall.start;
  29032. var groupTextureCount = texArray.count;
  29033. for (var j = 0; j < groupTextureCount; j++) {
  29034. renderer.texture.bind(texArray.elements[j], j);
  29035. }
  29036. renderer.geometry.draw(type, size, start);
  29037. };
  29038. /**
  29039. * Resolves shader for direct rendering
  29040. * @param renderer - The renderer
  29041. */
  29042. Graphics.prototype._resolveDirectShader = function (renderer) {
  29043. var shader = this.shader;
  29044. var pluginName = this.pluginName;
  29045. if (!shader) {
  29046. // if there is no shader here, we can use the default shader.
  29047. // and that only gets created if we actually need it..
  29048. // but may be more than one plugins for graphics
  29049. if (!DEFAULT_SHADERS[pluginName]) {
  29050. var MAX_TEXTURES = renderer.plugins[pluginName].MAX_TEXTURES;
  29051. var sampleValues = new Int32Array(MAX_TEXTURES);
  29052. for (var i = 0; i < MAX_TEXTURES; i++) {
  29053. sampleValues[i] = i;
  29054. }
  29055. var uniforms = {
  29056. tint: new Float32Array([1, 1, 1, 1]),
  29057. translationMatrix: new Matrix(),
  29058. default: UniformGroup.from({ uSamplers: sampleValues }, true),
  29059. };
  29060. var program = renderer.plugins[pluginName]._shader.program;
  29061. DEFAULT_SHADERS[pluginName] = new Shader(program, uniforms);
  29062. }
  29063. shader = DEFAULT_SHADERS[pluginName];
  29064. }
  29065. return shader;
  29066. };
  29067. /** Retrieves the bounds of the graphic shape as a rectangle object. */
  29068. Graphics.prototype._calculateBounds = function () {
  29069. this.finishPoly();
  29070. var geometry = this._geometry;
  29071. // skipping when graphics is empty, like a container
  29072. if (!geometry.graphicsData.length) {
  29073. return;
  29074. }
  29075. var _a = geometry.bounds, minX = _a.minX, minY = _a.minY, maxX = _a.maxX, maxY = _a.maxY;
  29076. this._bounds.addFrame(this.transform, minX, minY, maxX, maxY);
  29077. };
  29078. /**
  29079. * Tests if a point is inside this graphics object
  29080. * @param point - the point to test
  29081. * @returns - the result of the test
  29082. */
  29083. Graphics.prototype.containsPoint = function (point) {
  29084. this.worldTransform.applyInverse(point, Graphics._TEMP_POINT);
  29085. return this._geometry.containsPoint(Graphics._TEMP_POINT);
  29086. };
  29087. /** Recalculate the tint by applying tint to batches using Graphics tint. */
  29088. Graphics.prototype.calculateTints = function () {
  29089. if (this.batchTint !== this.tint) {
  29090. this.batchTint = this.tint;
  29091. var tintRGB = hex2rgb(this.tint, temp);
  29092. for (var i = 0; i < this.batches.length; i++) {
  29093. var batch = this.batches[i];
  29094. var batchTint = batch._batchRGB;
  29095. var r = (tintRGB[0] * batchTint[0]) * 255;
  29096. var g = (tintRGB[1] * batchTint[1]) * 255;
  29097. var b = (tintRGB[2] * batchTint[2]) * 255;
  29098. // TODO Ivan, can this be done in one go?
  29099. var color = (r << 16) + (g << 8) + (b | 0);
  29100. batch._tintRGB = (color >> 16)
  29101. + (color & 0xff00)
  29102. + ((color & 0xff) << 16);
  29103. }
  29104. }
  29105. };
  29106. /** If there's a transform update or a change to the shape of the geometry, recalculate the vertices. */
  29107. Graphics.prototype.calculateVertices = function () {
  29108. var wtID = this.transform._worldID;
  29109. if (this._transformID === wtID) {
  29110. return;
  29111. }
  29112. this._transformID = wtID;
  29113. var wt = this.transform.worldTransform;
  29114. var a = wt.a;
  29115. var b = wt.b;
  29116. var c = wt.c;
  29117. var d = wt.d;
  29118. var tx = wt.tx;
  29119. var ty = wt.ty;
  29120. var data = this._geometry.points; // batch.vertexDataOriginal;
  29121. var vertexData = this.vertexData;
  29122. var count = 0;
  29123. for (var i = 0; i < data.length; i += 2) {
  29124. var x = data[i];
  29125. var y = data[i + 1];
  29126. vertexData[count++] = (a * x) + (c * y) + tx;
  29127. vertexData[count++] = (d * y) + (b * x) + ty;
  29128. }
  29129. };
  29130. /**
  29131. * Closes the current path.
  29132. * @returns - Returns itself.
  29133. */
  29134. Graphics.prototype.closePath = function () {
  29135. var currentPath = this.currentPath;
  29136. if (currentPath) {
  29137. // we don't need to add extra point in the end because buildLine will take care of that
  29138. currentPath.closeStroke = true;
  29139. // ensure that the polygon is completed, and is available for hit detection
  29140. // (even if the graphics is not rendered yet)
  29141. this.finishPoly();
  29142. }
  29143. return this;
  29144. };
  29145. /**
  29146. * Apply a matrix to the positional data.
  29147. * @param matrix - Matrix to use for transform current shape.
  29148. * @returns - Returns itself.
  29149. */
  29150. Graphics.prototype.setMatrix = function (matrix) {
  29151. this._matrix = matrix;
  29152. return this;
  29153. };
  29154. /**
  29155. * Begin adding holes to the last draw shape
  29156. * IMPORTANT: holes must be fully inside a shape to work
  29157. * Also weirdness ensues if holes overlap!
  29158. * Ellipses, Circles, Rectangles and Rounded Rectangles cannot be holes or host for holes in CanvasRenderer,
  29159. * please use `moveTo` `lineTo`, `quadraticCurveTo` if you rely on pixi-legacy bundle.
  29160. * @returns - Returns itself.
  29161. */
  29162. Graphics.prototype.beginHole = function () {
  29163. this.finishPoly();
  29164. this._holeMode = true;
  29165. return this;
  29166. };
  29167. /**
  29168. * End adding holes to the last draw shape.
  29169. * @returns - Returns itself.
  29170. */
  29171. Graphics.prototype.endHole = function () {
  29172. this.finishPoly();
  29173. this._holeMode = false;
  29174. return this;
  29175. };
  29176. /**
  29177. * Destroys the Graphics object.
  29178. * @param options - Options parameter. A boolean will act as if all
  29179. * options have been set to that value
  29180. * @param {boolean} [options.children=false] - if set to true, all the children will have
  29181. * their destroy method called as well. 'options' will be passed on to those calls.
  29182. * @param {boolean} [options.texture=false] - Only used for child Sprites if options.children is set to true
  29183. * Should it destroy the texture of the child sprite
  29184. * @param {boolean} [options.baseTexture=false] - Only used for child Sprites if options.children is set to true
  29185. * Should it destroy the base texture of the child sprite
  29186. */
  29187. Graphics.prototype.destroy = function (options) {
  29188. this._geometry.refCount--;
  29189. if (this._geometry.refCount === 0) {
  29190. this._geometry.dispose();
  29191. }
  29192. this._matrix = null;
  29193. this.currentPath = null;
  29194. this._lineStyle.destroy();
  29195. this._lineStyle = null;
  29196. this._fillStyle.destroy();
  29197. this._fillStyle = null;
  29198. this._geometry = null;
  29199. this.shader = null;
  29200. this.vertexData = null;
  29201. this.batches.length = 0;
  29202. this.batches = null;
  29203. _super.prototype.destroy.call(this, options);
  29204. };
  29205. /**
  29206. * New rendering behavior for rounded rectangles: circular arcs instead of quadratic bezier curves.
  29207. * In the next major release, we'll enable this by default.
  29208. */
  29209. Graphics.nextRoundedRectBehavior = false;
  29210. /**
  29211. * Temporary point to use for containsPoint.
  29212. * @private
  29213. */
  29214. Graphics._TEMP_POINT = new Point();
  29215. return Graphics;
  29216. }(Container));
  29217. var graphicsUtils = {
  29218. buildPoly: buildPoly,
  29219. buildCircle: buildCircle,
  29220. buildRectangle: buildRectangle,
  29221. buildRoundedRectangle: buildRoundedRectangle,
  29222. buildLine: buildLine,
  29223. ArcUtils: ArcUtils,
  29224. BezierUtils: BezierUtils,
  29225. QuadraticUtils: QuadraticUtils,
  29226. BatchPart: BatchPart,
  29227. FILL_COMMANDS: FILL_COMMANDS,
  29228. BATCH_POOL: BATCH_POOL,
  29229. DRAW_CALL_POOL: DRAW_CALL_POOL
  29230. };
  29231. /*!
  29232. * @pixi/sprite - v6.5.10
  29233. * Compiled Thu, 06 Jul 2023 15:25:11 UTC
  29234. *
  29235. * @pixi/sprite is licensed under the MIT License.
  29236. * http://www.opensource.org/licenses/mit-license
  29237. */
  29238. /*! *****************************************************************************
  29239. Copyright (c) Microsoft Corporation.
  29240. Permission to use, copy, modify, and/or distribute this software for any
  29241. purpose with or without fee is hereby granted.
  29242. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  29243. REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
  29244. AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  29245. INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
  29246. LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
  29247. OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
  29248. PERFORMANCE OF THIS SOFTWARE.
  29249. ***************************************************************************** */
  29250. /* global Reflect, Promise */
  29251. var extendStatics$d = function(d, b) {
  29252. extendStatics$d = Object.setPrototypeOf ||
  29253. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  29254. function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } };
  29255. return extendStatics$d(d, b);
  29256. };
  29257. function __extends$d(d, b) {
  29258. extendStatics$d(d, b);
  29259. function __() { this.constructor = d; }
  29260. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  29261. }
  29262. var tempPoint$2 = new Point();
  29263. var indices = new Uint16Array([0, 1, 2, 0, 2, 3]);
  29264. /**
  29265. * The Sprite object is the base for all textured objects that are rendered to the screen
  29266. *
  29267. * A sprite can be created directly from an image like this:
  29268. *
  29269. * ```js
  29270. * let sprite = PIXI.Sprite.from('assets/image.png');
  29271. * ```
  29272. *
  29273. * The more efficient way to create sprites is using a {@link PIXI.Spritesheet},
  29274. * as swapping base textures when rendering to the screen is inefficient.
  29275. *
  29276. * ```js
  29277. * PIXI.Loader.shared.add("assets/spritesheet.json").load(setup);
  29278. *
  29279. * function setup() {
  29280. * let sheet = PIXI.Loader.shared.resources["assets/spritesheet.json"].spritesheet;
  29281. * let sprite = new PIXI.Sprite(sheet.textures["image.png"]);
  29282. * ...
  29283. * }
  29284. * ```
  29285. * @memberof PIXI
  29286. */
  29287. var Sprite = /** @class */ (function (_super) {
  29288. __extends$d(Sprite, _super);
  29289. /** @param texture - The texture for this sprite. */
  29290. function Sprite(texture) {
  29291. var _this = _super.call(this) || this;
  29292. _this._anchor = new ObservablePoint(_this._onAnchorUpdate, _this, (texture ? texture.defaultAnchor.x : 0), (texture ? texture.defaultAnchor.y : 0));
  29293. _this._texture = null;
  29294. _this._width = 0;
  29295. _this._height = 0;
  29296. _this._tint = null;
  29297. _this._tintRGB = null;
  29298. _this.tint = 0xFFFFFF;
  29299. _this.blendMode = BLEND_MODES.NORMAL;
  29300. _this._cachedTint = 0xFFFFFF;
  29301. _this.uvs = null;
  29302. // call texture setter
  29303. _this.texture = texture || Texture.EMPTY;
  29304. _this.vertexData = new Float32Array(8);
  29305. _this.vertexTrimmedData = null;
  29306. _this._transformID = -1;
  29307. _this._textureID = -1;
  29308. _this._transformTrimmedID = -1;
  29309. _this._textureTrimmedID = -1;
  29310. // Batchable stuff..
  29311. // TODO could make this a mixin?
  29312. _this.indices = indices;
  29313. _this.pluginName = 'batch';
  29314. /**
  29315. * Used to fast check if a sprite is.. a sprite!
  29316. * @member {boolean}
  29317. */
  29318. _this.isSprite = true;
  29319. _this._roundPixels = settings.ROUND_PIXELS;
  29320. return _this;
  29321. }
  29322. /** When the texture is updated, this event will fire to update the scale and frame. */
  29323. Sprite.prototype._onTextureUpdate = function () {
  29324. this._textureID = -1;
  29325. this._textureTrimmedID = -1;
  29326. this._cachedTint = 0xFFFFFF;
  29327. // so if _width is 0 then width was not set..
  29328. if (this._width) {
  29329. this.scale.x = sign(this.scale.x) * this._width / this._texture.orig.width;
  29330. }
  29331. if (this._height) {
  29332. this.scale.y = sign(this.scale.y) * this._height / this._texture.orig.height;
  29333. }
  29334. };
  29335. /** Called when the anchor position updates. */
  29336. Sprite.prototype._onAnchorUpdate = function () {
  29337. this._transformID = -1;
  29338. this._transformTrimmedID = -1;
  29339. };
  29340. /** Calculates worldTransform * vertices, store it in vertexData. */
  29341. Sprite.prototype.calculateVertices = function () {
  29342. var texture = this._texture;
  29343. if (this._transformID === this.transform._worldID && this._textureID === texture._updateID) {
  29344. return;
  29345. }
  29346. // update texture UV here, because base texture can be changed without calling `_onTextureUpdate`
  29347. if (this._textureID !== texture._updateID) {
  29348. this.uvs = this._texture._uvs.uvsFloat32;
  29349. }
  29350. this._transformID = this.transform._worldID;
  29351. this._textureID = texture._updateID;
  29352. // set the vertex data
  29353. var wt = this.transform.worldTransform;
  29354. var a = wt.a;
  29355. var b = wt.b;
  29356. var c = wt.c;
  29357. var d = wt.d;
  29358. var tx = wt.tx;
  29359. var ty = wt.ty;
  29360. var vertexData = this.vertexData;
  29361. var trim = texture.trim;
  29362. var orig = texture.orig;
  29363. var anchor = this._anchor;
  29364. var w0 = 0;
  29365. var w1 = 0;
  29366. var h0 = 0;
  29367. var h1 = 0;
  29368. if (trim) {
  29369. // if the sprite is trimmed and is not a tilingsprite then we need to add the extra
  29370. // space before transforming the sprite coords.
  29371. w1 = trim.x - (anchor._x * orig.width);
  29372. w0 = w1 + trim.width;
  29373. h1 = trim.y - (anchor._y * orig.height);
  29374. h0 = h1 + trim.height;
  29375. }
  29376. else {
  29377. w1 = -anchor._x * orig.width;
  29378. w0 = w1 + orig.width;
  29379. h1 = -anchor._y * orig.height;
  29380. h0 = h1 + orig.height;
  29381. }
  29382. // xy
  29383. vertexData[0] = (a * w1) + (c * h1) + tx;
  29384. vertexData[1] = (d * h1) + (b * w1) + ty;
  29385. // xy
  29386. vertexData[2] = (a * w0) + (c * h1) + tx;
  29387. vertexData[3] = (d * h1) + (b * w0) + ty;
  29388. // xy
  29389. vertexData[4] = (a * w0) + (c * h0) + tx;
  29390. vertexData[5] = (d * h0) + (b * w0) + ty;
  29391. // xy
  29392. vertexData[6] = (a * w1) + (c * h0) + tx;
  29393. vertexData[7] = (d * h0) + (b * w1) + ty;
  29394. if (this._roundPixels) {
  29395. var resolution = settings.RESOLUTION;
  29396. for (var i = 0; i < vertexData.length; ++i) {
  29397. vertexData[i] = Math.round((vertexData[i] * resolution | 0) / resolution);
  29398. }
  29399. }
  29400. };
  29401. /**
  29402. * Calculates worldTransform * vertices for a non texture with a trim. store it in vertexTrimmedData.
  29403. *
  29404. * This is used to ensure that the true width and height of a trimmed texture is respected.
  29405. */
  29406. Sprite.prototype.calculateTrimmedVertices = function () {
  29407. if (!this.vertexTrimmedData) {
  29408. this.vertexTrimmedData = new Float32Array(8);
  29409. }
  29410. else if (this._transformTrimmedID === this.transform._worldID && this._textureTrimmedID === this._texture._updateID) {
  29411. return;
  29412. }
  29413. this._transformTrimmedID = this.transform._worldID;
  29414. this._textureTrimmedID = this._texture._updateID;
  29415. // lets do some special trim code!
  29416. var texture = this._texture;
  29417. var vertexData = this.vertexTrimmedData;
  29418. var orig = texture.orig;
  29419. var anchor = this._anchor;
  29420. // lets calculate the new untrimmed bounds..
  29421. var wt = this.transform.worldTransform;
  29422. var a = wt.a;
  29423. var b = wt.b;
  29424. var c = wt.c;
  29425. var d = wt.d;
  29426. var tx = wt.tx;
  29427. var ty = wt.ty;
  29428. var w1 = -anchor._x * orig.width;
  29429. var w0 = w1 + orig.width;
  29430. var h1 = -anchor._y * orig.height;
  29431. var h0 = h1 + orig.height;
  29432. // xy
  29433. vertexData[0] = (a * w1) + (c * h1) + tx;
  29434. vertexData[1] = (d * h1) + (b * w1) + ty;
  29435. // xy
  29436. vertexData[2] = (a * w0) + (c * h1) + tx;
  29437. vertexData[3] = (d * h1) + (b * w0) + ty;
  29438. // xy
  29439. vertexData[4] = (a * w0) + (c * h0) + tx;
  29440. vertexData[5] = (d * h0) + (b * w0) + ty;
  29441. // xy
  29442. vertexData[6] = (a * w1) + (c * h0) + tx;
  29443. vertexData[7] = (d * h0) + (b * w1) + ty;
  29444. };
  29445. /**
  29446. *
  29447. * Renders the object using the WebGL renderer
  29448. * @param renderer - The webgl renderer to use.
  29449. */
  29450. Sprite.prototype._render = function (renderer) {
  29451. this.calculateVertices();
  29452. renderer.batch.setObjectRenderer(renderer.plugins[this.pluginName]);
  29453. renderer.plugins[this.pluginName].render(this);
  29454. };
  29455. /** Updates the bounds of the sprite. */
  29456. Sprite.prototype._calculateBounds = function () {
  29457. var trim = this._texture.trim;
  29458. var orig = this._texture.orig;
  29459. // First lets check to see if the current texture has a trim..
  29460. if (!trim || (trim.width === orig.width && trim.height === orig.height)) {
  29461. // no trim! lets use the usual calculations..
  29462. this.calculateVertices();
  29463. this._bounds.addQuad(this.vertexData);
  29464. }
  29465. else {
  29466. // lets calculate a special trimmed bounds...
  29467. this.calculateTrimmedVertices();
  29468. this._bounds.addQuad(this.vertexTrimmedData);
  29469. }
  29470. };
  29471. /**
  29472. * Gets the local bounds of the sprite object.
  29473. * @param rect - Optional output rectangle.
  29474. * @returns The bounds.
  29475. */
  29476. Sprite.prototype.getLocalBounds = function (rect) {
  29477. // we can do a fast local bounds if the sprite has no children!
  29478. if (this.children.length === 0) {
  29479. if (!this._localBounds) {
  29480. this._localBounds = new Bounds();
  29481. }
  29482. this._localBounds.minX = this._texture.orig.width * -this._anchor._x;
  29483. this._localBounds.minY = this._texture.orig.height * -this._anchor._y;
  29484. this._localBounds.maxX = this._texture.orig.width * (1 - this._anchor._x);
  29485. this._localBounds.maxY = this._texture.orig.height * (1 - this._anchor._y);
  29486. if (!rect) {
  29487. if (!this._localBoundsRect) {
  29488. this._localBoundsRect = new Rectangle();
  29489. }
  29490. rect = this._localBoundsRect;
  29491. }
  29492. return this._localBounds.getRectangle(rect);
  29493. }
  29494. return _super.prototype.getLocalBounds.call(this, rect);
  29495. };
  29496. /**
  29497. * Tests if a point is inside this sprite
  29498. * @param point - the point to test
  29499. * @returns The result of the test
  29500. */
  29501. Sprite.prototype.containsPoint = function (point) {
  29502. this.worldTransform.applyInverse(point, tempPoint$2);
  29503. var width = this._texture.orig.width;
  29504. var height = this._texture.orig.height;
  29505. var x1 = -width * this.anchor.x;
  29506. var y1 = 0;
  29507. if (tempPoint$2.x >= x1 && tempPoint$2.x < x1 + width) {
  29508. y1 = -height * this.anchor.y;
  29509. if (tempPoint$2.y >= y1 && tempPoint$2.y < y1 + height) {
  29510. return true;
  29511. }
  29512. }
  29513. return false;
  29514. };
  29515. /**
  29516. * Destroys this sprite and optionally its texture and children.
  29517. * @param options - Options parameter. A boolean will act as if all options
  29518. * have been set to that value
  29519. * @param [options.children=false] - if set to true, all the children will have their destroy
  29520. * method called as well. 'options' will be passed on to those calls.
  29521. * @param [options.texture=false] - Should it destroy the current texture of the sprite as well
  29522. * @param [options.baseTexture=false] - Should it destroy the base texture of the sprite as well
  29523. */
  29524. Sprite.prototype.destroy = function (options) {
  29525. _super.prototype.destroy.call(this, options);
  29526. this._texture.off('update', this._onTextureUpdate, this);
  29527. this._anchor = null;
  29528. var destroyTexture = typeof options === 'boolean' ? options : options && options.texture;
  29529. if (destroyTexture) {
  29530. var destroyBaseTexture = typeof options === 'boolean' ? options : options && options.baseTexture;
  29531. this._texture.destroy(!!destroyBaseTexture);
  29532. }
  29533. this._texture = null;
  29534. };
  29535. // some helper functions..
  29536. /**
  29537. * Helper function that creates a new sprite based on the source you provide.
  29538. * The source can be - frame id, image url, video url, canvas element, video element, base texture
  29539. * @param {string|PIXI.Texture|HTMLCanvasElement|HTMLVideoElement} source - Source to create texture from
  29540. * @param {object} [options] - See {@link PIXI.BaseTexture}'s constructor for options.
  29541. * @returns The newly created sprite
  29542. */
  29543. Sprite.from = function (source, options) {
  29544. var texture = (source instanceof Texture)
  29545. ? source
  29546. : Texture.from(source, options);
  29547. return new Sprite(texture);
  29548. };
  29549. Object.defineProperty(Sprite.prototype, "roundPixels", {
  29550. get: function () {
  29551. return this._roundPixels;
  29552. },
  29553. /**
  29554. * If true PixiJS will Math.floor() x/y values when rendering, stopping pixel interpolation.
  29555. *
  29556. * Advantages can include sharper image quality (like text) and faster rendering on canvas.
  29557. * The main disadvantage is movement of objects may appear less smooth.
  29558. *
  29559. * To set the global default, change {@link PIXI.settings.ROUND_PIXELS}.
  29560. * @default false
  29561. */
  29562. set: function (value) {
  29563. if (this._roundPixels !== value) {
  29564. this._transformID = -1;
  29565. }
  29566. this._roundPixels = value;
  29567. },
  29568. enumerable: false,
  29569. configurable: true
  29570. });
  29571. Object.defineProperty(Sprite.prototype, "width", {
  29572. /** The width of the sprite, setting this will actually modify the scale to achieve the value set. */
  29573. get: function () {
  29574. return Math.abs(this.scale.x) * this._texture.orig.width;
  29575. },
  29576. set: function (value) {
  29577. var s = sign(this.scale.x) || 1;
  29578. this.scale.x = s * value / this._texture.orig.width;
  29579. this._width = value;
  29580. },
  29581. enumerable: false,
  29582. configurable: true
  29583. });
  29584. Object.defineProperty(Sprite.prototype, "height", {
  29585. /** The height of the sprite, setting this will actually modify the scale to achieve the value set. */
  29586. get: function () {
  29587. return Math.abs(this.scale.y) * this._texture.orig.height;
  29588. },
  29589. set: function (value) {
  29590. var s = sign(this.scale.y) || 1;
  29591. this.scale.y = s * value / this._texture.orig.height;
  29592. this._height = value;
  29593. },
  29594. enumerable: false,
  29595. configurable: true
  29596. });
  29597. Object.defineProperty(Sprite.prototype, "anchor", {
  29598. /**
  29599. * The anchor sets the origin point of the sprite. The default value is taken from the {@link PIXI.Texture|Texture}
  29600. * and passed to the constructor.
  29601. *
  29602. * The default is `(0,0)`, this means the sprite's origin is the top left.
  29603. *
  29604. * Setting the anchor to `(0.5,0.5)` means the sprite's origin is centered.
  29605. *
  29606. * Setting the anchor to `(1,1)` would mean the sprite's origin point will be the bottom right corner.
  29607. *
  29608. * If you pass only single parameter, it will set both x and y to the same value as shown in the example below.
  29609. * @example
  29610. * const sprite = new PIXI.Sprite(texture);
  29611. * sprite.anchor.set(0.5); // This will set the origin to center. (0.5) is same as (0.5, 0.5).
  29612. */
  29613. get: function () {
  29614. return this._anchor;
  29615. },
  29616. set: function (value) {
  29617. this._anchor.copyFrom(value);
  29618. },
  29619. enumerable: false,
  29620. configurable: true
  29621. });
  29622. Object.defineProperty(Sprite.prototype, "tint", {
  29623. /**
  29624. * The tint applied to the sprite. This is a hex value.
  29625. *
  29626. * A value of 0xFFFFFF will remove any tint effect.
  29627. * @default 0xFFFFFF
  29628. */
  29629. get: function () {
  29630. return this._tint;
  29631. },
  29632. set: function (value) {
  29633. this._tint = value;
  29634. this._tintRGB = (value >> 16) + (value & 0xff00) + ((value & 0xff) << 16);
  29635. },
  29636. enumerable: false,
  29637. configurable: true
  29638. });
  29639. Object.defineProperty(Sprite.prototype, "texture", {
  29640. /** The texture that the sprite is using. */
  29641. get: function () {
  29642. return this._texture;
  29643. },
  29644. set: function (value) {
  29645. if (this._texture === value) {
  29646. return;
  29647. }
  29648. if (this._texture) {
  29649. this._texture.off('update', this._onTextureUpdate, this);
  29650. }
  29651. this._texture = value || Texture.EMPTY;
  29652. this._cachedTint = 0xFFFFFF;
  29653. this._textureID = -1;
  29654. this._textureTrimmedID = -1;
  29655. if (value) {
  29656. // wait for the texture to load
  29657. if (value.baseTexture.valid) {
  29658. this._onTextureUpdate();
  29659. }
  29660. else {
  29661. value.once('update', this._onTextureUpdate, this);
  29662. }
  29663. }
  29664. },
  29665. enumerable: false,
  29666. configurable: true
  29667. });
  29668. return Sprite;
  29669. }(Container));
  29670. /*!
  29671. * @pixi/text - v6.5.10
  29672. * Compiled Thu, 06 Jul 2023 15:25:11 UTC
  29673. *
  29674. * @pixi/text is licensed under the MIT License.
  29675. * http://www.opensource.org/licenses/mit-license
  29676. */
  29677. /*! *****************************************************************************
  29678. Copyright (c) Microsoft Corporation.
  29679. Permission to use, copy, modify, and/or distribute this software for any
  29680. purpose with or without fee is hereby granted.
  29681. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  29682. REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
  29683. AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  29684. INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
  29685. LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
  29686. OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
  29687. PERFORMANCE OF THIS SOFTWARE.
  29688. ***************************************************************************** */
  29689. /* global Reflect, Promise */
  29690. var extendStatics$c = function(d, b) {
  29691. extendStatics$c = Object.setPrototypeOf ||
  29692. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  29693. function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } };
  29694. return extendStatics$c(d, b);
  29695. };
  29696. function __extends$c(d, b) {
  29697. extendStatics$c(d, b);
  29698. function __() { this.constructor = d; }
  29699. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  29700. }
  29701. /**
  29702. * Constants that define the type of gradient on text.
  29703. * @static
  29704. * @constant
  29705. * @name TEXT_GRADIENT
  29706. * @memberof PIXI
  29707. * @type {object}
  29708. * @property {number} LINEAR_VERTICAL Vertical gradient
  29709. * @property {number} LINEAR_HORIZONTAL Linear gradient
  29710. */
  29711. var TEXT_GRADIENT;
  29712. (function (TEXT_GRADIENT) {
  29713. TEXT_GRADIENT[TEXT_GRADIENT["LINEAR_VERTICAL"] = 0] = "LINEAR_VERTICAL";
  29714. TEXT_GRADIENT[TEXT_GRADIENT["LINEAR_HORIZONTAL"] = 1] = "LINEAR_HORIZONTAL";
  29715. })(TEXT_GRADIENT || (TEXT_GRADIENT = {}));
  29716. // disabling eslint for now, going to rewrite this in v5
  29717. var defaultStyle = {
  29718. align: 'left',
  29719. breakWords: false,
  29720. dropShadow: false,
  29721. dropShadowAlpha: 1,
  29722. dropShadowAngle: Math.PI / 6,
  29723. dropShadowBlur: 0,
  29724. dropShadowColor: 'black',
  29725. dropShadowDistance: 5,
  29726. fill: 'black',
  29727. fillGradientType: TEXT_GRADIENT.LINEAR_VERTICAL,
  29728. fillGradientStops: [],
  29729. fontFamily: 'Arial',
  29730. fontSize: 26,
  29731. fontStyle: 'normal',
  29732. fontVariant: 'normal',
  29733. fontWeight: 'normal',
  29734. letterSpacing: 0,
  29735. lineHeight: 0,
  29736. lineJoin: 'miter',
  29737. miterLimit: 10,
  29738. padding: 0,
  29739. stroke: 'black',
  29740. strokeThickness: 0,
  29741. textBaseline: 'alphabetic',
  29742. trim: false,
  29743. whiteSpace: 'pre',
  29744. wordWrap: false,
  29745. wordWrapWidth: 100,
  29746. leading: 0,
  29747. };
  29748. var genericFontFamilies = [
  29749. 'serif',
  29750. 'sans-serif',
  29751. 'monospace',
  29752. 'cursive',
  29753. 'fantasy',
  29754. 'system-ui' ];
  29755. /**
  29756. * A TextStyle Object contains information to decorate a Text objects.
  29757. *
  29758. * An instance can be shared between multiple Text objects; then changing the style will update all text objects using it.
  29759. *
  29760. * A tool can be used to generate a text style [here](https://pixijs.io/pixi-text-style).
  29761. *
  29762. * @memberof PIXI
  29763. */
  29764. var TextStyle = /** @class */ (function () {
  29765. /**
  29766. * @param {object} [style] - The style parameters
  29767. * @param {string} [style.align='left'] - Alignment for multiline text ('left', 'center' or 'right'),
  29768. * does not affect single line text
  29769. * @param {boolean} [style.breakWords=false] - Indicates if lines can be wrapped within words, it
  29770. * needs wordWrap to be set to true
  29771. * @param {boolean} [style.dropShadow=false] - Set a drop shadow for the text
  29772. * @param {number} [style.dropShadowAlpha=1] - Set alpha for the drop shadow
  29773. * @param {number} [style.dropShadowAngle=Math.PI/6] - Set a angle of the drop shadow
  29774. * @param {number} [style.dropShadowBlur=0] - Set a shadow blur radius
  29775. * @param {string|number} [style.dropShadowColor='black'] - A fill style to be used on the dropshadow e.g 'red', '#00FF00'
  29776. * @param {number} [style.dropShadowDistance=5] - Set a distance of the drop shadow
  29777. * @param {string|string[]|number|number[]|CanvasGradient|CanvasPattern} [style.fill='black'] - A canvas
  29778. * fillstyle that will be used on the text e.g 'red', '#00FF00'. Can be an array to create a gradient
  29779. * eg ['#000000','#FFFFFF']
  29780. * {@link https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/fillStyle|MDN}
  29781. * @param {number} [style.fillGradientType=PIXI.TEXT_GRADIENT.LINEAR_VERTICAL] - If fill is an array of colours
  29782. * to create a gradient, this can change the type/direction of the gradient. See {@link PIXI.TEXT_GRADIENT}
  29783. * @param {number[]} [style.fillGradientStops] - If fill is an array of colours to create a gradient, this array can set
  29784. * the stop points (numbers between 0 and 1) for the color, overriding the default behaviour of evenly spacing them.
  29785. * @param {string|string[]} [style.fontFamily='Arial'] - The font family
  29786. * @param {number|string} [style.fontSize=26] - The font size (as a number it converts to px, but as a string,
  29787. * equivalents are '26px','20pt','160%' or '1.6em')
  29788. * @param {string} [style.fontStyle='normal'] - The font style ('normal', 'italic' or 'oblique')
  29789. * @param {string} [style.fontVariant='normal'] - The font variant ('normal' or 'small-caps')
  29790. * @param {string} [style.fontWeight='normal'] - The font weight ('normal', 'bold', 'bolder', 'lighter' and '100',
  29791. * '200', '300', '400', '500', '600', '700', '800' or '900')
  29792. * @param {number} [style.leading=0] - The space between lines
  29793. * @param {number} [style.letterSpacing=0] - The amount of spacing between letters, default is 0
  29794. * @param {number} [style.lineHeight] - The line height, a number that represents the vertical space that a letter uses
  29795. * @param {string} [style.lineJoin='miter'] - The lineJoin property sets the type of corner created, it can resolve
  29796. * spiked text issues. Possible values "miter" (creates a sharp corner), "round" (creates a round corner) or "bevel"
  29797. * (creates a squared corner).
  29798. * @param {number} [style.miterLimit=10] - The miter limit to use when using the 'miter' lineJoin mode. This can reduce
  29799. * or increase the spikiness of rendered text.
  29800. * @param {number} [style.padding=0] - Occasionally some fonts are cropped. Adding some padding will prevent this from
  29801. * happening by adding padding to all sides of the text.
  29802. * @param {string|number} [style.stroke='black'] - A canvas fillstyle that will be used on the text stroke
  29803. * e.g 'blue', '#FCFF00'
  29804. * @param {number} [style.strokeThickness=0] - A number that represents the thickness of the stroke.
  29805. * Default is 0 (no stroke)
  29806. * @param {boolean} [style.trim=false] - Trim transparent borders
  29807. * @param {string} [style.textBaseline='alphabetic'] - The baseline of the text that is rendered.
  29808. * @param {string} [style.whiteSpace='pre'] - Determines whether newlines & spaces are collapsed or preserved "normal"
  29809. * (collapse, collapse), "pre" (preserve, preserve) | "pre-line" (preserve, collapse). It needs wordWrap to be set to true
  29810. * @param {boolean} [style.wordWrap=false] - Indicates if word wrap should be used
  29811. * @param {number} [style.wordWrapWidth=100] - The width at which text will wrap, it needs wordWrap to be set to true
  29812. */
  29813. function TextStyle(style) {
  29814. this.styleID = 0;
  29815. this.reset();
  29816. deepCopyProperties(this, style, style);
  29817. }
  29818. /**
  29819. * Creates a new TextStyle object with the same values as this one.
  29820. * Note that the only the properties of the object are cloned.
  29821. *
  29822. * @return New cloned TextStyle object
  29823. */
  29824. TextStyle.prototype.clone = function () {
  29825. var clonedProperties = {};
  29826. deepCopyProperties(clonedProperties, this, defaultStyle);
  29827. return new TextStyle(clonedProperties);
  29828. };
  29829. /** Resets all properties to the defaults specified in TextStyle.prototype._default */
  29830. TextStyle.prototype.reset = function () {
  29831. deepCopyProperties(this, defaultStyle, defaultStyle);
  29832. };
  29833. Object.defineProperty(TextStyle.prototype, "align", {
  29834. /**
  29835. * Alignment for multiline text ('left', 'center' or 'right'), does not affect single line text
  29836. *
  29837. * @member {string}
  29838. */
  29839. get: function () {
  29840. return this._align;
  29841. },
  29842. set: function (align) {
  29843. if (this._align !== align) {
  29844. this._align = align;
  29845. this.styleID++;
  29846. }
  29847. },
  29848. enumerable: false,
  29849. configurable: true
  29850. });
  29851. Object.defineProperty(TextStyle.prototype, "breakWords", {
  29852. /** Indicates if lines can be wrapped within words, it needs wordWrap to be set to true. */
  29853. get: function () {
  29854. return this._breakWords;
  29855. },
  29856. set: function (breakWords) {
  29857. if (this._breakWords !== breakWords) {
  29858. this._breakWords = breakWords;
  29859. this.styleID++;
  29860. }
  29861. },
  29862. enumerable: false,
  29863. configurable: true
  29864. });
  29865. Object.defineProperty(TextStyle.prototype, "dropShadow", {
  29866. /** Set a drop shadow for the text. */
  29867. get: function () {
  29868. return this._dropShadow;
  29869. },
  29870. set: function (dropShadow) {
  29871. if (this._dropShadow !== dropShadow) {
  29872. this._dropShadow = dropShadow;
  29873. this.styleID++;
  29874. }
  29875. },
  29876. enumerable: false,
  29877. configurable: true
  29878. });
  29879. Object.defineProperty(TextStyle.prototype, "dropShadowAlpha", {
  29880. /** Set alpha for the drop shadow. */
  29881. get: function () {
  29882. return this._dropShadowAlpha;
  29883. },
  29884. set: function (dropShadowAlpha) {
  29885. if (this._dropShadowAlpha !== dropShadowAlpha) {
  29886. this._dropShadowAlpha = dropShadowAlpha;
  29887. this.styleID++;
  29888. }
  29889. },
  29890. enumerable: false,
  29891. configurable: true
  29892. });
  29893. Object.defineProperty(TextStyle.prototype, "dropShadowAngle", {
  29894. /** Set a angle of the drop shadow. */
  29895. get: function () {
  29896. return this._dropShadowAngle;
  29897. },
  29898. set: function (dropShadowAngle) {
  29899. if (this._dropShadowAngle !== dropShadowAngle) {
  29900. this._dropShadowAngle = dropShadowAngle;
  29901. this.styleID++;
  29902. }
  29903. },
  29904. enumerable: false,
  29905. configurable: true
  29906. });
  29907. Object.defineProperty(TextStyle.prototype, "dropShadowBlur", {
  29908. /** Set a shadow blur radius. */
  29909. get: function () {
  29910. return this._dropShadowBlur;
  29911. },
  29912. set: function (dropShadowBlur) {
  29913. if (this._dropShadowBlur !== dropShadowBlur) {
  29914. this._dropShadowBlur = dropShadowBlur;
  29915. this.styleID++;
  29916. }
  29917. },
  29918. enumerable: false,
  29919. configurable: true
  29920. });
  29921. Object.defineProperty(TextStyle.prototype, "dropShadowColor", {
  29922. /** A fill style to be used on the dropshadow e.g 'red', '#00FF00'. */
  29923. get: function () {
  29924. return this._dropShadowColor;
  29925. },
  29926. set: function (dropShadowColor) {
  29927. var outputColor = getColor(dropShadowColor);
  29928. if (this._dropShadowColor !== outputColor) {
  29929. this._dropShadowColor = outputColor;
  29930. this.styleID++;
  29931. }
  29932. },
  29933. enumerable: false,
  29934. configurable: true
  29935. });
  29936. Object.defineProperty(TextStyle.prototype, "dropShadowDistance", {
  29937. /** Set a distance of the drop shadow. */
  29938. get: function () {
  29939. return this._dropShadowDistance;
  29940. },
  29941. set: function (dropShadowDistance) {
  29942. if (this._dropShadowDistance !== dropShadowDistance) {
  29943. this._dropShadowDistance = dropShadowDistance;
  29944. this.styleID++;
  29945. }
  29946. },
  29947. enumerable: false,
  29948. configurable: true
  29949. });
  29950. Object.defineProperty(TextStyle.prototype, "fill", {
  29951. /**
  29952. * A canvas fillstyle that will be used on the text e.g 'red', '#00FF00'.
  29953. *
  29954. * Can be an array to create a gradient eg ['#000000','#FFFFFF']
  29955. * {@link https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/fillStyle|MDN}
  29956. *
  29957. * @member {string|string[]|number|number[]|CanvasGradient|CanvasPattern}
  29958. */
  29959. get: function () {
  29960. return this._fill;
  29961. },
  29962. set: function (fill) {
  29963. // TODO: Can't have different types for getter and setter. The getter shouldn't have the number type as
  29964. // the setter converts to string. See this thread for more details:
  29965. // https://github.com/microsoft/TypeScript/issues/2521
  29966. // TODO: Not sure if getColor works properly with CanvasGradient and/or CanvasPattern, can't pass in
  29967. // without casting here.
  29968. var outputColor = getColor(fill);
  29969. if (this._fill !== outputColor) {
  29970. this._fill = outputColor;
  29971. this.styleID++;
  29972. }
  29973. },
  29974. enumerable: false,
  29975. configurable: true
  29976. });
  29977. Object.defineProperty(TextStyle.prototype, "fillGradientType", {
  29978. /**
  29979. * If fill is an array of colours to create a gradient, this can change the type/direction of the gradient.
  29980. *
  29981. * @see PIXI.TEXT_GRADIENT
  29982. */
  29983. get: function () {
  29984. return this._fillGradientType;
  29985. },
  29986. set: function (fillGradientType) {
  29987. if (this._fillGradientType !== fillGradientType) {
  29988. this._fillGradientType = fillGradientType;
  29989. this.styleID++;
  29990. }
  29991. },
  29992. enumerable: false,
  29993. configurable: true
  29994. });
  29995. Object.defineProperty(TextStyle.prototype, "fillGradientStops", {
  29996. /**
  29997. * If fill is an array of colours to create a gradient, this array can set the stop points
  29998. * (numbers between 0 and 1) for the color, overriding the default behaviour of evenly spacing them.
  29999. */
  30000. get: function () {
  30001. return this._fillGradientStops;
  30002. },
  30003. set: function (fillGradientStops) {
  30004. if (!areArraysEqual(this._fillGradientStops, fillGradientStops)) {
  30005. this._fillGradientStops = fillGradientStops;
  30006. this.styleID++;
  30007. }
  30008. },
  30009. enumerable: false,
  30010. configurable: true
  30011. });
  30012. Object.defineProperty(TextStyle.prototype, "fontFamily", {
  30013. /** The font family. */
  30014. get: function () {
  30015. return this._fontFamily;
  30016. },
  30017. set: function (fontFamily) {
  30018. if (this.fontFamily !== fontFamily) {
  30019. this._fontFamily = fontFamily;
  30020. this.styleID++;
  30021. }
  30022. },
  30023. enumerable: false,
  30024. configurable: true
  30025. });
  30026. Object.defineProperty(TextStyle.prototype, "fontSize", {
  30027. /**
  30028. * The font size
  30029. * (as a number it converts to px, but as a string, equivalents are '26px','20pt','160%' or '1.6em')
  30030. */
  30031. get: function () {
  30032. return this._fontSize;
  30033. },
  30034. set: function (fontSize) {
  30035. if (this._fontSize !== fontSize) {
  30036. this._fontSize = fontSize;
  30037. this.styleID++;
  30038. }
  30039. },
  30040. enumerable: false,
  30041. configurable: true
  30042. });
  30043. Object.defineProperty(TextStyle.prototype, "fontStyle", {
  30044. /**
  30045. * The font style
  30046. * ('normal', 'italic' or 'oblique')
  30047. *
  30048. * @member {string}
  30049. */
  30050. get: function () {
  30051. return this._fontStyle;
  30052. },
  30053. set: function (fontStyle) {
  30054. if (this._fontStyle !== fontStyle) {
  30055. this._fontStyle = fontStyle;
  30056. this.styleID++;
  30057. }
  30058. },
  30059. enumerable: false,
  30060. configurable: true
  30061. });
  30062. Object.defineProperty(TextStyle.prototype, "fontVariant", {
  30063. /**
  30064. * The font variant
  30065. * ('normal' or 'small-caps')
  30066. *
  30067. * @member {string}
  30068. */
  30069. get: function () {
  30070. return this._fontVariant;
  30071. },
  30072. set: function (fontVariant) {
  30073. if (this._fontVariant !== fontVariant) {
  30074. this._fontVariant = fontVariant;
  30075. this.styleID++;
  30076. }
  30077. },
  30078. enumerable: false,
  30079. configurable: true
  30080. });
  30081. Object.defineProperty(TextStyle.prototype, "fontWeight", {
  30082. /**
  30083. * The font weight
  30084. * ('normal', 'bold', 'bolder', 'lighter' and '100', '200', '300', '400', '500', '600', '700', 800' or '900')
  30085. *
  30086. * @member {string}
  30087. */
  30088. get: function () {
  30089. return this._fontWeight;
  30090. },
  30091. set: function (fontWeight) {
  30092. if (this._fontWeight !== fontWeight) {
  30093. this._fontWeight = fontWeight;
  30094. this.styleID++;
  30095. }
  30096. },
  30097. enumerable: false,
  30098. configurable: true
  30099. });
  30100. Object.defineProperty(TextStyle.prototype, "letterSpacing", {
  30101. /** The amount of spacing between letters, default is 0. */
  30102. get: function () {
  30103. return this._letterSpacing;
  30104. },
  30105. set: function (letterSpacing) {
  30106. if (this._letterSpacing !== letterSpacing) {
  30107. this._letterSpacing = letterSpacing;
  30108. this.styleID++;
  30109. }
  30110. },
  30111. enumerable: false,
  30112. configurable: true
  30113. });
  30114. Object.defineProperty(TextStyle.prototype, "lineHeight", {
  30115. /** The line height, a number that represents the vertical space that a letter uses. */
  30116. get: function () {
  30117. return this._lineHeight;
  30118. },
  30119. set: function (lineHeight) {
  30120. if (this._lineHeight !== lineHeight) {
  30121. this._lineHeight = lineHeight;
  30122. this.styleID++;
  30123. }
  30124. },
  30125. enumerable: false,
  30126. configurable: true
  30127. });
  30128. Object.defineProperty(TextStyle.prototype, "leading", {
  30129. /** The space between lines. */
  30130. get: function () {
  30131. return this._leading;
  30132. },
  30133. set: function (leading) {
  30134. if (this._leading !== leading) {
  30135. this._leading = leading;
  30136. this.styleID++;
  30137. }
  30138. },
  30139. enumerable: false,
  30140. configurable: true
  30141. });
  30142. Object.defineProperty(TextStyle.prototype, "lineJoin", {
  30143. /**
  30144. * The lineJoin property sets the type of corner created, it can resolve spiked text issues.
  30145. * Default is 'miter' (creates a sharp corner).
  30146. *
  30147. * @member {string}
  30148. */
  30149. get: function () {
  30150. return this._lineJoin;
  30151. },
  30152. set: function (lineJoin) {
  30153. if (this._lineJoin !== lineJoin) {
  30154. this._lineJoin = lineJoin;
  30155. this.styleID++;
  30156. }
  30157. },
  30158. enumerable: false,
  30159. configurable: true
  30160. });
  30161. Object.defineProperty(TextStyle.prototype, "miterLimit", {
  30162. /**
  30163. * The miter limit to use when using the 'miter' lineJoin mode.
  30164. *
  30165. * This can reduce or increase the spikiness of rendered text.
  30166. */
  30167. get: function () {
  30168. return this._miterLimit;
  30169. },
  30170. set: function (miterLimit) {
  30171. if (this._miterLimit !== miterLimit) {
  30172. this._miterLimit = miterLimit;
  30173. this.styleID++;
  30174. }
  30175. },
  30176. enumerable: false,
  30177. configurable: true
  30178. });
  30179. Object.defineProperty(TextStyle.prototype, "padding", {
  30180. /**
  30181. * Occasionally some fonts are cropped. Adding some padding will prevent this from happening
  30182. * by adding padding to all sides of the text.
  30183. */
  30184. get: function () {
  30185. return this._padding;
  30186. },
  30187. set: function (padding) {
  30188. if (this._padding !== padding) {
  30189. this._padding = padding;
  30190. this.styleID++;
  30191. }
  30192. },
  30193. enumerable: false,
  30194. configurable: true
  30195. });
  30196. Object.defineProperty(TextStyle.prototype, "stroke", {
  30197. /**
  30198. * A canvas fillstyle that will be used on the text stroke
  30199. * e.g 'blue', '#FCFF00'
  30200. */
  30201. get: function () {
  30202. return this._stroke;
  30203. },
  30204. set: function (stroke) {
  30205. // TODO: Can't have different types for getter and setter. The getter shouldn't have the number type as
  30206. // the setter converts to string. See this thread for more details:
  30207. // https://github.com/microsoft/TypeScript/issues/2521
  30208. var outputColor = getColor(stroke);
  30209. if (this._stroke !== outputColor) {
  30210. this._stroke = outputColor;
  30211. this.styleID++;
  30212. }
  30213. },
  30214. enumerable: false,
  30215. configurable: true
  30216. });
  30217. Object.defineProperty(TextStyle.prototype, "strokeThickness", {
  30218. /**
  30219. * A number that represents the thickness of the stroke.
  30220. *
  30221. * @default 0
  30222. */
  30223. get: function () {
  30224. return this._strokeThickness;
  30225. },
  30226. set: function (strokeThickness) {
  30227. if (this._strokeThickness !== strokeThickness) {
  30228. this._strokeThickness = strokeThickness;
  30229. this.styleID++;
  30230. }
  30231. },
  30232. enumerable: false,
  30233. configurable: true
  30234. });
  30235. Object.defineProperty(TextStyle.prototype, "textBaseline", {
  30236. /**
  30237. * The baseline of the text that is rendered.
  30238. *
  30239. * @member {string}
  30240. */
  30241. get: function () {
  30242. return this._textBaseline;
  30243. },
  30244. set: function (textBaseline) {
  30245. if (this._textBaseline !== textBaseline) {
  30246. this._textBaseline = textBaseline;
  30247. this.styleID++;
  30248. }
  30249. },
  30250. enumerable: false,
  30251. configurable: true
  30252. });
  30253. Object.defineProperty(TextStyle.prototype, "trim", {
  30254. /** Trim transparent borders. */
  30255. get: function () {
  30256. return this._trim;
  30257. },
  30258. set: function (trim) {
  30259. if (this._trim !== trim) {
  30260. this._trim = trim;
  30261. this.styleID++;
  30262. }
  30263. },
  30264. enumerable: false,
  30265. configurable: true
  30266. });
  30267. Object.defineProperty(TextStyle.prototype, "whiteSpace", {
  30268. /**
  30269. * How newlines and spaces should be handled.
  30270. * Default is 'pre' (preserve, preserve).
  30271. *
  30272. * value | New lines | Spaces
  30273. * --- | --- | ---
  30274. * 'normal' | Collapse | Collapse
  30275. * 'pre' | Preserve | Preserve
  30276. * 'pre-line' | Preserve | Collapse
  30277. *
  30278. * @member {string}
  30279. */
  30280. get: function () {
  30281. return this._whiteSpace;
  30282. },
  30283. set: function (whiteSpace) {
  30284. if (this._whiteSpace !== whiteSpace) {
  30285. this._whiteSpace = whiteSpace;
  30286. this.styleID++;
  30287. }
  30288. },
  30289. enumerable: false,
  30290. configurable: true
  30291. });
  30292. Object.defineProperty(TextStyle.prototype, "wordWrap", {
  30293. /** Indicates if word wrap should be used. */
  30294. get: function () {
  30295. return this._wordWrap;
  30296. },
  30297. set: function (wordWrap) {
  30298. if (this._wordWrap !== wordWrap) {
  30299. this._wordWrap = wordWrap;
  30300. this.styleID++;
  30301. }
  30302. },
  30303. enumerable: false,
  30304. configurable: true
  30305. });
  30306. Object.defineProperty(TextStyle.prototype, "wordWrapWidth", {
  30307. /** The width at which text will wrap, it needs wordWrap to be set to true. */
  30308. get: function () {
  30309. return this._wordWrapWidth;
  30310. },
  30311. set: function (wordWrapWidth) {
  30312. if (this._wordWrapWidth !== wordWrapWidth) {
  30313. this._wordWrapWidth = wordWrapWidth;
  30314. this.styleID++;
  30315. }
  30316. },
  30317. enumerable: false,
  30318. configurable: true
  30319. });
  30320. /**
  30321. * Generates a font style string to use for `TextMetrics.measureFont()`.
  30322. *
  30323. * @return Font style string, for passing to `TextMetrics.measureFont()`
  30324. */
  30325. TextStyle.prototype.toFontString = function () {
  30326. // build canvas api font setting from individual components. Convert a numeric this.fontSize to px
  30327. var fontSizeString = (typeof this.fontSize === 'number') ? this.fontSize + "px" : this.fontSize;
  30328. // Clean-up fontFamily property by quoting each font name
  30329. // this will support font names with spaces
  30330. var fontFamilies = this.fontFamily;
  30331. if (!Array.isArray(this.fontFamily)) {
  30332. fontFamilies = this.fontFamily.split(',');
  30333. }
  30334. for (var i = fontFamilies.length - 1; i >= 0; i--) {
  30335. // Trim any extra white-space
  30336. var fontFamily = fontFamilies[i].trim();
  30337. // Check if font already contains strings
  30338. if (!(/([\"\'])[^\'\"]+\1/).test(fontFamily) && genericFontFamilies.indexOf(fontFamily) < 0) {
  30339. fontFamily = "\"" + fontFamily + "\"";
  30340. }
  30341. fontFamilies[i] = fontFamily;
  30342. }
  30343. return this.fontStyle + " " + this.fontVariant + " " + this.fontWeight + " " + fontSizeString + " " + fontFamilies.join(',');
  30344. };
  30345. return TextStyle;
  30346. }());
  30347. /**
  30348. * Utility function to convert hexadecimal colors to strings, and simply return the color if it's a string.
  30349. * @private
  30350. * @param color
  30351. * @return The color as a string.
  30352. */
  30353. function getSingleColor(color) {
  30354. if (typeof color === 'number') {
  30355. return hex2string(color);
  30356. }
  30357. else if (typeof color === 'string') {
  30358. if (color.indexOf('0x') === 0) {
  30359. color = color.replace('0x', '#');
  30360. }
  30361. }
  30362. return color;
  30363. }
  30364. function getColor(color) {
  30365. if (!Array.isArray(color)) {
  30366. return getSingleColor(color);
  30367. }
  30368. else {
  30369. for (var i = 0; i < color.length; ++i) {
  30370. color[i] = getSingleColor(color[i]);
  30371. }
  30372. return color;
  30373. }
  30374. }
  30375. /**
  30376. * Utility function to convert hexadecimal colors to strings, and simply return the color if it's a string.
  30377. * This version can also convert array of colors
  30378. * @private
  30379. * @param array1 - First array to compare
  30380. * @param array2 - Second array to compare
  30381. * @return Do the arrays contain the same values in the same order
  30382. */
  30383. function areArraysEqual(array1, array2) {
  30384. if (!Array.isArray(array1) || !Array.isArray(array2)) {
  30385. return false;
  30386. }
  30387. if (array1.length !== array2.length) {
  30388. return false;
  30389. }
  30390. for (var i = 0; i < array1.length; ++i) {
  30391. if (array1[i] !== array2[i]) {
  30392. return false;
  30393. }
  30394. }
  30395. return true;
  30396. }
  30397. /**
  30398. * Utility function to ensure that object properties are copied by value, and not by reference
  30399. * @private
  30400. * @param target - Target object to copy properties into
  30401. * @param source - Source object for the properties to copy
  30402. * @param propertyObj - Object containing properties names we want to loop over
  30403. */
  30404. function deepCopyProperties(target, source, propertyObj) {
  30405. for (var prop in propertyObj) {
  30406. if (Array.isArray(source[prop])) {
  30407. target[prop] = source[prop].slice();
  30408. }
  30409. else {
  30410. target[prop] = source[prop];
  30411. }
  30412. }
  30413. }
  30414. // Default settings used for all getContext calls
  30415. var contextSettings = {
  30416. // TextMetrics requires getImageData readback for measuring fonts.
  30417. willReadFrequently: true,
  30418. };
  30419. /**
  30420. * The TextMetrics object represents the measurement of a block of text with a specified style.
  30421. *
  30422. * ```js
  30423. * let style = new PIXI.TextStyle({fontFamily : 'Arial', fontSize: 24, fill : 0xff1010, align : 'center'})
  30424. * let textMetrics = PIXI.TextMetrics.measureText('Your text', style)
  30425. * ```
  30426. * @memberof PIXI
  30427. */
  30428. var TextMetrics = /** @class */ (function () {
  30429. /**
  30430. * @param text - the text that was measured
  30431. * @param style - the style that was measured
  30432. * @param width - the measured width of the text
  30433. * @param height - the measured height of the text
  30434. * @param lines - an array of the lines of text broken by new lines and wrapping if specified in style
  30435. * @param lineWidths - an array of the line widths for each line matched to `lines`
  30436. * @param lineHeight - the measured line height for this style
  30437. * @param maxLineWidth - the maximum line width for all measured lines
  30438. * @param {PIXI.IFontMetrics} fontProperties - the font properties object from TextMetrics.measureFont
  30439. */
  30440. function TextMetrics(text, style, width, height, lines, lineWidths, lineHeight, maxLineWidth, fontProperties) {
  30441. this.text = text;
  30442. this.style = style;
  30443. this.width = width;
  30444. this.height = height;
  30445. this.lines = lines;
  30446. this.lineWidths = lineWidths;
  30447. this.lineHeight = lineHeight;
  30448. this.maxLineWidth = maxLineWidth;
  30449. this.fontProperties = fontProperties;
  30450. }
  30451. /**
  30452. * Measures the supplied string of text and returns a Rectangle.
  30453. * @param text - The text to measure.
  30454. * @param style - The text style to use for measuring
  30455. * @param wordWrap - Override for if word-wrap should be applied to the text.
  30456. * @param canvas - optional specification of the canvas to use for measuring.
  30457. * @returns Measured width and height of the text.
  30458. */
  30459. TextMetrics.measureText = function (text, style, wordWrap, canvas) {
  30460. if (canvas === void 0) { canvas = TextMetrics._canvas; }
  30461. wordWrap = (wordWrap === undefined || wordWrap === null) ? style.wordWrap : wordWrap;
  30462. var font = style.toFontString();
  30463. var fontProperties = TextMetrics.measureFont(font);
  30464. // fallback in case UA disallow canvas data extraction
  30465. // (toDataURI, getImageData functions)
  30466. if (fontProperties.fontSize === 0) {
  30467. fontProperties.fontSize = style.fontSize;
  30468. fontProperties.ascent = style.fontSize;
  30469. }
  30470. var context = canvas.getContext('2d', contextSettings);
  30471. context.font = font;
  30472. var outputText = wordWrap ? TextMetrics.wordWrap(text, style, canvas) : text;
  30473. var lines = outputText.split(/(?:\r\n|\r|\n)/);
  30474. var lineWidths = new Array(lines.length);
  30475. var maxLineWidth = 0;
  30476. for (var i = 0; i < lines.length; i++) {
  30477. var lineWidth = context.measureText(lines[i]).width + ((lines[i].length - 1) * style.letterSpacing);
  30478. lineWidths[i] = lineWidth;
  30479. maxLineWidth = Math.max(maxLineWidth, lineWidth);
  30480. }
  30481. var width = maxLineWidth + style.strokeThickness;
  30482. if (style.dropShadow) {
  30483. width += style.dropShadowDistance;
  30484. }
  30485. var lineHeight = style.lineHeight || fontProperties.fontSize + style.strokeThickness;
  30486. var height = Math.max(lineHeight, fontProperties.fontSize + style.strokeThickness)
  30487. + ((lines.length - 1) * (lineHeight + style.leading));
  30488. if (style.dropShadow) {
  30489. height += style.dropShadowDistance;
  30490. }
  30491. return new TextMetrics(text, style, width, height, lines, lineWidths, lineHeight + style.leading, maxLineWidth, fontProperties);
  30492. };
  30493. /**
  30494. * Applies newlines to a string to have it optimally fit into the horizontal
  30495. * bounds set by the Text object's wordWrapWidth property.
  30496. * @param text - String to apply word wrapping to
  30497. * @param style - the style to use when wrapping
  30498. * @param canvas - optional specification of the canvas to use for measuring.
  30499. * @returns New string with new lines applied where required
  30500. */
  30501. TextMetrics.wordWrap = function (text, style, canvas) {
  30502. if (canvas === void 0) { canvas = TextMetrics._canvas; }
  30503. var context = canvas.getContext('2d', contextSettings);
  30504. var width = 0;
  30505. var line = '';
  30506. var lines = '';
  30507. var cache = Object.create(null);
  30508. var letterSpacing = style.letterSpacing, whiteSpace = style.whiteSpace;
  30509. // How to handle whitespaces
  30510. var collapseSpaces = TextMetrics.collapseSpaces(whiteSpace);
  30511. var collapseNewlines = TextMetrics.collapseNewlines(whiteSpace);
  30512. // whether or not spaces may be added to the beginning of lines
  30513. var canPrependSpaces = !collapseSpaces;
  30514. // There is letterSpacing after every char except the last one
  30515. // t_h_i_s_' '_i_s_' '_a_n_' '_e_x_a_m_p_l_e_' '_!
  30516. // so for convenience the above needs to be compared to width + 1 extra letterSpace
  30517. // t_h_i_s_' '_i_s_' '_a_n_' '_e_x_a_m_p_l_e_' '_!_
  30518. // ________________________________________________
  30519. // And then the final space is simply no appended to each line
  30520. var wordWrapWidth = style.wordWrapWidth + letterSpacing;
  30521. // break text into words, spaces and newline chars
  30522. var tokens = TextMetrics.tokenize(text);
  30523. for (var i = 0; i < tokens.length; i++) {
  30524. // get the word, space or newlineChar
  30525. var token = tokens[i];
  30526. // if word is a new line
  30527. if (TextMetrics.isNewline(token)) {
  30528. // keep the new line
  30529. if (!collapseNewlines) {
  30530. lines += TextMetrics.addLine(line);
  30531. canPrependSpaces = !collapseSpaces;
  30532. line = '';
  30533. width = 0;
  30534. continue;
  30535. }
  30536. // if we should collapse new lines
  30537. // we simply convert it into a space
  30538. token = ' ';
  30539. }
  30540. // if we should collapse repeated whitespaces
  30541. if (collapseSpaces) {
  30542. // check both this and the last tokens for spaces
  30543. var currIsBreakingSpace = TextMetrics.isBreakingSpace(token);
  30544. var lastIsBreakingSpace = TextMetrics.isBreakingSpace(line[line.length - 1]);
  30545. if (currIsBreakingSpace && lastIsBreakingSpace) {
  30546. continue;
  30547. }
  30548. }
  30549. // get word width from cache if possible
  30550. var tokenWidth = TextMetrics.getFromCache(token, letterSpacing, cache, context);
  30551. // word is longer than desired bounds
  30552. if (tokenWidth > wordWrapWidth) {
  30553. // if we are not already at the beginning of a line
  30554. if (line !== '') {
  30555. // start newlines for overflow words
  30556. lines += TextMetrics.addLine(line);
  30557. line = '';
  30558. width = 0;
  30559. }
  30560. // break large word over multiple lines
  30561. if (TextMetrics.canBreakWords(token, style.breakWords)) {
  30562. // break word into characters
  30563. var characters = TextMetrics.wordWrapSplit(token);
  30564. // loop the characters
  30565. for (var j = 0; j < characters.length; j++) {
  30566. var char = characters[j];
  30567. var k = 1;
  30568. // we are not at the end of the token
  30569. while (characters[j + k]) {
  30570. var nextChar = characters[j + k];
  30571. var lastChar = char[char.length - 1];
  30572. // should not split chars
  30573. if (!TextMetrics.canBreakChars(lastChar, nextChar, token, j, style.breakWords)) {
  30574. // combine chars & move forward one
  30575. char += nextChar;
  30576. }
  30577. else {
  30578. break;
  30579. }
  30580. k++;
  30581. }
  30582. j += char.length - 1;
  30583. var characterWidth = TextMetrics.getFromCache(char, letterSpacing, cache, context);
  30584. if (characterWidth + width > wordWrapWidth) {
  30585. lines += TextMetrics.addLine(line);
  30586. canPrependSpaces = false;
  30587. line = '';
  30588. width = 0;
  30589. }
  30590. line += char;
  30591. width += characterWidth;
  30592. }
  30593. }
  30594. // run word out of the bounds
  30595. else {
  30596. // if there are words in this line already
  30597. // finish that line and start a new one
  30598. if (line.length > 0) {
  30599. lines += TextMetrics.addLine(line);
  30600. line = '';
  30601. width = 0;
  30602. }
  30603. var isLastToken = i === tokens.length - 1;
  30604. // give it its own line if it's not the end
  30605. lines += TextMetrics.addLine(token, !isLastToken);
  30606. canPrependSpaces = false;
  30607. line = '';
  30608. width = 0;
  30609. }
  30610. }
  30611. // word could fit
  30612. else {
  30613. // word won't fit because of existing words
  30614. // start a new line
  30615. if (tokenWidth + width > wordWrapWidth) {
  30616. // if its a space we don't want it
  30617. canPrependSpaces = false;
  30618. // add a new line
  30619. lines += TextMetrics.addLine(line);
  30620. // start a new line
  30621. line = '';
  30622. width = 0;
  30623. }
  30624. // don't add spaces to the beginning of lines
  30625. if (line.length > 0 || !TextMetrics.isBreakingSpace(token) || canPrependSpaces) {
  30626. // add the word to the current line
  30627. line += token;
  30628. // update width counter
  30629. width += tokenWidth;
  30630. }
  30631. }
  30632. }
  30633. lines += TextMetrics.addLine(line, false);
  30634. return lines;
  30635. };
  30636. /**
  30637. * Convienience function for logging each line added during the wordWrap method.
  30638. * @param line - The line of text to add
  30639. * @param newLine - Add new line character to end
  30640. * @returns A formatted line
  30641. */
  30642. TextMetrics.addLine = function (line, newLine) {
  30643. if (newLine === void 0) { newLine = true; }
  30644. line = TextMetrics.trimRight(line);
  30645. line = (newLine) ? line + "\n" : line;
  30646. return line;
  30647. };
  30648. /**
  30649. * Gets & sets the widths of calculated characters in a cache object
  30650. * @param key - The key
  30651. * @param letterSpacing - The letter spacing
  30652. * @param cache - The cache
  30653. * @param context - The canvas context
  30654. * @returns The from cache.
  30655. */
  30656. TextMetrics.getFromCache = function (key, letterSpacing, cache, context) {
  30657. var width = cache[key];
  30658. if (typeof width !== 'number') {
  30659. var spacing = ((key.length) * letterSpacing);
  30660. width = context.measureText(key).width + spacing;
  30661. cache[key] = width;
  30662. }
  30663. return width;
  30664. };
  30665. /**
  30666. * Determines whether we should collapse breaking spaces.
  30667. * @param whiteSpace - The TextStyle property whiteSpace
  30668. * @returns Should collapse
  30669. */
  30670. TextMetrics.collapseSpaces = function (whiteSpace) {
  30671. return (whiteSpace === 'normal' || whiteSpace === 'pre-line');
  30672. };
  30673. /**
  30674. * Determines whether we should collapse newLine chars.
  30675. * @param whiteSpace - The white space
  30676. * @returns should collapse
  30677. */
  30678. TextMetrics.collapseNewlines = function (whiteSpace) {
  30679. return (whiteSpace === 'normal');
  30680. };
  30681. /**
  30682. * Trims breaking whitespaces from string.
  30683. * @param text - The text
  30684. * @returns Trimmed string
  30685. */
  30686. TextMetrics.trimRight = function (text) {
  30687. if (typeof text !== 'string') {
  30688. return '';
  30689. }
  30690. for (var i = text.length - 1; i >= 0; i--) {
  30691. var char = text[i];
  30692. if (!TextMetrics.isBreakingSpace(char)) {
  30693. break;
  30694. }
  30695. text = text.slice(0, -1);
  30696. }
  30697. return text;
  30698. };
  30699. /**
  30700. * Determines if char is a newline.
  30701. * @param char - The character
  30702. * @returns True if newline, False otherwise.
  30703. */
  30704. TextMetrics.isNewline = function (char) {
  30705. if (typeof char !== 'string') {
  30706. return false;
  30707. }
  30708. return (TextMetrics._newlines.indexOf(char.charCodeAt(0)) >= 0);
  30709. };
  30710. /**
  30711. * Determines if char is a breaking whitespace.
  30712. *
  30713. * It allows one to determine whether char should be a breaking whitespace
  30714. * For example certain characters in CJK langs or numbers.
  30715. * It must return a boolean.
  30716. * @param char - The character
  30717. * @param [_nextChar] - The next character
  30718. * @returns True if whitespace, False otherwise.
  30719. */
  30720. TextMetrics.isBreakingSpace = function (char, _nextChar) {
  30721. if (typeof char !== 'string') {
  30722. return false;
  30723. }
  30724. return (TextMetrics._breakingSpaces.indexOf(char.charCodeAt(0)) >= 0);
  30725. };
  30726. /**
  30727. * Splits a string into words, breaking-spaces and newLine characters
  30728. * @param text - The text
  30729. * @returns A tokenized array
  30730. */
  30731. TextMetrics.tokenize = function (text) {
  30732. var tokens = [];
  30733. var token = '';
  30734. if (typeof text !== 'string') {
  30735. return tokens;
  30736. }
  30737. for (var i = 0; i < text.length; i++) {
  30738. var char = text[i];
  30739. var nextChar = text[i + 1];
  30740. if (TextMetrics.isBreakingSpace(char, nextChar) || TextMetrics.isNewline(char)) {
  30741. if (token !== '') {
  30742. tokens.push(token);
  30743. token = '';
  30744. }
  30745. tokens.push(char);
  30746. continue;
  30747. }
  30748. token += char;
  30749. }
  30750. if (token !== '') {
  30751. tokens.push(token);
  30752. }
  30753. return tokens;
  30754. };
  30755. /**
  30756. * Overridable helper method used internally by TextMetrics, exposed to allow customizing the class's behavior.
  30757. *
  30758. * It allows one to customise which words should break
  30759. * Examples are if the token is CJK or numbers.
  30760. * It must return a boolean.
  30761. * @param _token - The token
  30762. * @param breakWords - The style attr break words
  30763. * @returns Whether to break word or not
  30764. */
  30765. TextMetrics.canBreakWords = function (_token, breakWords) {
  30766. return breakWords;
  30767. };
  30768. /**
  30769. * Overridable helper method used internally by TextMetrics, exposed to allow customizing the class's behavior.
  30770. *
  30771. * It allows one to determine whether a pair of characters
  30772. * should be broken by newlines
  30773. * For example certain characters in CJK langs or numbers.
  30774. * It must return a boolean.
  30775. * @param _char - The character
  30776. * @param _nextChar - The next character
  30777. * @param _token - The token/word the characters are from
  30778. * @param _index - The index in the token of the char
  30779. * @param _breakWords - The style attr break words
  30780. * @returns whether to break word or not
  30781. */
  30782. TextMetrics.canBreakChars = function (_char, _nextChar, _token, _index, _breakWords) {
  30783. return true;
  30784. };
  30785. /**
  30786. * Overridable helper method used internally by TextMetrics, exposed to allow customizing the class's behavior.
  30787. *
  30788. * It is called when a token (usually a word) has to be split into separate pieces
  30789. * in order to determine the point to break a word.
  30790. * It must return an array of characters.
  30791. * @example
  30792. * // Correctly splits emojis, eg "🤪🤪" will result in two element array, each with one emoji.
  30793. * TextMetrics.wordWrapSplit = (token) => [...token];
  30794. * @param token - The token to split
  30795. * @returns The characters of the token
  30796. */
  30797. TextMetrics.wordWrapSplit = function (token) {
  30798. return token.split('');
  30799. };
  30800. /**
  30801. * Calculates the ascent, descent and fontSize of a given font-style
  30802. * @param font - String representing the style of the font
  30803. * @returns Font properties object
  30804. */
  30805. TextMetrics.measureFont = function (font) {
  30806. // as this method is used for preparing assets, don't recalculate things if we don't need to
  30807. if (TextMetrics._fonts[font]) {
  30808. return TextMetrics._fonts[font];
  30809. }
  30810. var properties = {
  30811. ascent: 0,
  30812. descent: 0,
  30813. fontSize: 0,
  30814. };
  30815. var canvas = TextMetrics._canvas;
  30816. var context = TextMetrics._context;
  30817. context.font = font;
  30818. var metricsString = TextMetrics.METRICS_STRING + TextMetrics.BASELINE_SYMBOL;
  30819. var width = Math.ceil(context.measureText(metricsString).width);
  30820. var baseline = Math.ceil(context.measureText(TextMetrics.BASELINE_SYMBOL).width);
  30821. var height = Math.ceil(TextMetrics.HEIGHT_MULTIPLIER * baseline);
  30822. baseline = baseline * TextMetrics.BASELINE_MULTIPLIER | 0;
  30823. canvas.width = width;
  30824. canvas.height = height;
  30825. context.fillStyle = '#f00';
  30826. context.fillRect(0, 0, width, height);
  30827. context.font = font;
  30828. context.textBaseline = 'alphabetic';
  30829. context.fillStyle = '#000';
  30830. context.fillText(metricsString, 0, baseline);
  30831. var imagedata = context.getImageData(0, 0, width, height).data;
  30832. var pixels = imagedata.length;
  30833. var line = width * 4;
  30834. var i = 0;
  30835. var idx = 0;
  30836. var stop = false;
  30837. // ascent. scan from top to bottom until we find a non red pixel
  30838. for (i = 0; i < baseline; ++i) {
  30839. for (var j = 0; j < line; j += 4) {
  30840. if (imagedata[idx + j] !== 255) {
  30841. stop = true;
  30842. break;
  30843. }
  30844. }
  30845. if (!stop) {
  30846. idx += line;
  30847. }
  30848. else {
  30849. break;
  30850. }
  30851. }
  30852. properties.ascent = baseline - i;
  30853. idx = pixels - line;
  30854. stop = false;
  30855. // descent. scan from bottom to top until we find a non red pixel
  30856. for (i = height; i > baseline; --i) {
  30857. for (var j = 0; j < line; j += 4) {
  30858. if (imagedata[idx + j] !== 255) {
  30859. stop = true;
  30860. break;
  30861. }
  30862. }
  30863. if (!stop) {
  30864. idx -= line;
  30865. }
  30866. else {
  30867. break;
  30868. }
  30869. }
  30870. properties.descent = i - baseline;
  30871. properties.fontSize = properties.ascent + properties.descent;
  30872. TextMetrics._fonts[font] = properties;
  30873. return properties;
  30874. };
  30875. /**
  30876. * Clear font metrics in metrics cache.
  30877. * @param {string} [font] - font name. If font name not set then clear cache for all fonts.
  30878. */
  30879. TextMetrics.clearMetrics = function (font) {
  30880. if (font === void 0) { font = ''; }
  30881. if (font) {
  30882. delete TextMetrics._fonts[font];
  30883. }
  30884. else {
  30885. TextMetrics._fonts = {};
  30886. }
  30887. };
  30888. Object.defineProperty(TextMetrics, "_canvas", {
  30889. /**
  30890. * Cached canvas element for measuring text
  30891. * TODO: this should be private, but isn't because of backward compat, will fix later.
  30892. * @ignore
  30893. */
  30894. get: function () {
  30895. if (!TextMetrics.__canvas) {
  30896. var canvas = void 0;
  30897. try {
  30898. // OffscreenCanvas2D measureText can be up to 40% faster.
  30899. var c = new OffscreenCanvas(0, 0);
  30900. var context = c.getContext('2d', contextSettings);
  30901. if (context && context.measureText) {
  30902. TextMetrics.__canvas = c;
  30903. return c;
  30904. }
  30905. canvas = settings.ADAPTER.createCanvas();
  30906. }
  30907. catch (ex) {
  30908. canvas = settings.ADAPTER.createCanvas();
  30909. }
  30910. canvas.width = canvas.height = 10;
  30911. TextMetrics.__canvas = canvas;
  30912. }
  30913. return TextMetrics.__canvas;
  30914. },
  30915. enumerable: false,
  30916. configurable: true
  30917. });
  30918. Object.defineProperty(TextMetrics, "_context", {
  30919. /**
  30920. * TODO: this should be private, but isn't because of backward compat, will fix later.
  30921. * @ignore
  30922. */
  30923. get: function () {
  30924. if (!TextMetrics.__context) {
  30925. TextMetrics.__context = TextMetrics._canvas.getContext('2d', contextSettings);
  30926. }
  30927. return TextMetrics.__context;
  30928. },
  30929. enumerable: false,
  30930. configurable: true
  30931. });
  30932. return TextMetrics;
  30933. }());
  30934. /**
  30935. * Internal return object for {@link PIXI.TextMetrics.measureFont `TextMetrics.measureFont`}.
  30936. * @typedef {object} FontMetrics
  30937. * @property {number} ascent - The ascent distance
  30938. * @property {number} descent - The descent distance
  30939. * @property {number} fontSize - Font size from ascent to descent
  30940. * @memberof PIXI.TextMetrics
  30941. * @private
  30942. */
  30943. /**
  30944. * Cache of {@see PIXI.TextMetrics.FontMetrics} objects.
  30945. * @memberof PIXI.TextMetrics
  30946. * @type {object}
  30947. * @private
  30948. */
  30949. TextMetrics._fonts = {};
  30950. /**
  30951. * String used for calculate font metrics.
  30952. * These characters are all tall to help calculate the height required for text.
  30953. * @static
  30954. * @memberof PIXI.TextMetrics
  30955. * @name METRICS_STRING
  30956. * @type {string}
  30957. * @default |ÉqÅ
  30958. */
  30959. TextMetrics.METRICS_STRING = '|ÉqÅ';
  30960. /**
  30961. * Baseline symbol for calculate font metrics.
  30962. * @static
  30963. * @memberof PIXI.TextMetrics
  30964. * @name BASELINE_SYMBOL
  30965. * @type {string}
  30966. * @default M
  30967. */
  30968. TextMetrics.BASELINE_SYMBOL = 'M';
  30969. /**
  30970. * Baseline multiplier for calculate font metrics.
  30971. * @static
  30972. * @memberof PIXI.TextMetrics
  30973. * @name BASELINE_MULTIPLIER
  30974. * @type {number}
  30975. * @default 1.4
  30976. */
  30977. TextMetrics.BASELINE_MULTIPLIER = 1.4;
  30978. /**
  30979. * Height multiplier for setting height of canvas to calculate font metrics.
  30980. * @static
  30981. * @memberof PIXI.TextMetrics
  30982. * @name HEIGHT_MULTIPLIER
  30983. * @type {number}
  30984. * @default 2.00
  30985. */
  30986. TextMetrics.HEIGHT_MULTIPLIER = 2.0;
  30987. /**
  30988. * Cache of new line chars.
  30989. * @memberof PIXI.TextMetrics
  30990. * @type {number[]}
  30991. * @private
  30992. */
  30993. TextMetrics._newlines = [
  30994. 0x000A,
  30995. 0x000D ];
  30996. /**
  30997. * Cache of breaking spaces.
  30998. * @memberof PIXI.TextMetrics
  30999. * @type {number[]}
  31000. * @private
  31001. */
  31002. TextMetrics._breakingSpaces = [
  31003. 0x0009,
  31004. 0x0020,
  31005. 0x2000,
  31006. 0x2001,
  31007. 0x2002,
  31008. 0x2003,
  31009. 0x2004,
  31010. 0x2005,
  31011. 0x2006,
  31012. 0x2008,
  31013. 0x2009,
  31014. 0x200A,
  31015. 0x205F,
  31016. 0x3000 ];
  31017. /**
  31018. * A number, or a string containing a number.
  31019. * @memberof PIXI
  31020. * @typedef {object} IFontMetrics
  31021. * @property {number} ascent - Font ascent
  31022. * @property {number} descent - Font descent
  31023. * @property {number} fontSize - Font size
  31024. */
  31025. var defaultDestroyOptions = {
  31026. texture: true,
  31027. children: false,
  31028. baseTexture: true,
  31029. };
  31030. /**
  31031. * A Text Object will create a line or multiple lines of text.
  31032. *
  31033. * The text is created using the [Canvas API](https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API).
  31034. *
  31035. * The primary advantage of this class over BitmapText is that you have great control over the style of the text,
  31036. * which you can change at runtime.
  31037. *
  31038. * The primary disadvantages is that each piece of text has it's own texture, which can use more memory.
  31039. * When text changes, this texture has to be re-generated and re-uploaded to the GPU, taking up time.
  31040. *
  31041. * To split a line you can use '\n' in your text string, or, on the `style` object,
  31042. * change its `wordWrap` property to true and and give the `wordWrapWidth` property a value.
  31043. *
  31044. * A Text can be created directly from a string and a style object,
  31045. * which can be generated [here](https://pixijs.io/pixi-text-style).
  31046. *
  31047. * ```js
  31048. * let text = new PIXI.Text('This is a PixiJS text',{fontFamily : 'Arial', fontSize: 24, fill : 0xff1010, align : 'center'});
  31049. * ```
  31050. * @memberof PIXI
  31051. */
  31052. var Text = /** @class */ (function (_super) {
  31053. __extends$c(Text, _super);
  31054. /**
  31055. * @param text - The string that you would like the text to display
  31056. * @param {object|PIXI.TextStyle} [style] - The style parameters
  31057. * @param canvas - The canvas element for drawing text
  31058. */
  31059. function Text(text, style, canvas) {
  31060. var _this = this;
  31061. var ownCanvas = false;
  31062. if (!canvas) {
  31063. canvas = settings.ADAPTER.createCanvas();
  31064. ownCanvas = true;
  31065. }
  31066. canvas.width = 3;
  31067. canvas.height = 3;
  31068. var texture = Texture.from(canvas);
  31069. texture.orig = new Rectangle();
  31070. texture.trim = new Rectangle();
  31071. _this = _super.call(this, texture) || this;
  31072. _this._ownCanvas = ownCanvas;
  31073. _this.canvas = canvas;
  31074. _this.context = canvas.getContext('2d', {
  31075. // required for trimming to work without warnings
  31076. willReadFrequently: true,
  31077. });
  31078. _this._resolution = settings.RESOLUTION;
  31079. _this._autoResolution = true;
  31080. _this._text = null;
  31081. _this._style = null;
  31082. _this._styleListener = null;
  31083. _this._font = '';
  31084. _this.text = text;
  31085. _this.style = style;
  31086. _this.localStyleID = -1;
  31087. return _this;
  31088. }
  31089. /**
  31090. * Renders text to its canvas, and updates its texture.
  31091. *
  31092. * By default this is used internally to ensure the texture is correct before rendering,
  31093. * but it can be used called externally, for example from this class to 'pre-generate' the texture from a piece of text,
  31094. * and then shared across multiple Sprites.
  31095. * @param respectDirty - Whether to abort updating the text if the Text isn't dirty and the function is called.
  31096. */
  31097. Text.prototype.updateText = function (respectDirty) {
  31098. var style = this._style;
  31099. // check if style has changed..
  31100. if (this.localStyleID !== style.styleID) {
  31101. this.dirty = true;
  31102. this.localStyleID = style.styleID;
  31103. }
  31104. if (!this.dirty && respectDirty) {
  31105. return;
  31106. }
  31107. this._font = this._style.toFontString();
  31108. var context = this.context;
  31109. var measured = TextMetrics.measureText(this._text || ' ', this._style, this._style.wordWrap, this.canvas);
  31110. var width = measured.width;
  31111. var height = measured.height;
  31112. var lines = measured.lines;
  31113. var lineHeight = measured.lineHeight;
  31114. var lineWidths = measured.lineWidths;
  31115. var maxLineWidth = measured.maxLineWidth;
  31116. var fontProperties = measured.fontProperties;
  31117. this.canvas.width = Math.ceil(Math.ceil((Math.max(1, width) + (style.padding * 2))) * this._resolution);
  31118. this.canvas.height = Math.ceil(Math.ceil((Math.max(1, height) + (style.padding * 2))) * this._resolution);
  31119. context.scale(this._resolution, this._resolution);
  31120. context.clearRect(0, 0, this.canvas.width, this.canvas.height);
  31121. context.font = this._font;
  31122. context.lineWidth = style.strokeThickness;
  31123. context.textBaseline = style.textBaseline;
  31124. context.lineJoin = style.lineJoin;
  31125. context.miterLimit = style.miterLimit;
  31126. var linePositionX;
  31127. var linePositionY;
  31128. // require 2 passes if a shadow; the first to draw the drop shadow, the second to draw the text
  31129. var passesCount = style.dropShadow ? 2 : 1;
  31130. // For v4, we drew text at the colours of the drop shadow underneath the normal text. This gave the correct zIndex,
  31131. // but features such as alpha and shadowblur did not look right at all, since we were using actual text as a shadow.
  31132. //
  31133. // For v5.0.0, we moved over to just use the canvas API for drop shadows, which made them look much nicer and more
  31134. // visually please, but now because the stroke is drawn and then the fill, drop shadows would appear on both the fill
  31135. // and the stroke; and fill drop shadows would appear over the top of the stroke.
  31136. //
  31137. // For v5.1.1, the new route is to revert to v4 style of drawing text first to get the drop shadows underneath normal
  31138. // text, but instead drawing text in the correct location, we'll draw it off screen (-paddingY), and then adjust the
  31139. // drop shadow so only that appears on screen (+paddingY). Now we'll have the correct draw order of the shadow
  31140. // beneath the text, whilst also having the proper text shadow styling.
  31141. for (var i = 0; i < passesCount; ++i) {
  31142. var isShadowPass = style.dropShadow && i === 0;
  31143. // we only want the drop shadow, so put text way off-screen
  31144. var dsOffsetText = isShadowPass ? Math.ceil(Math.max(1, height) + (style.padding * 2)) : 0;
  31145. var dsOffsetShadow = dsOffsetText * this._resolution;
  31146. if (isShadowPass) {
  31147. // On Safari, text with gradient and drop shadows together do not position correctly
  31148. // if the scale of the canvas is not 1: https://bugs.webkit.org/show_bug.cgi?id=197689
  31149. // Therefore we'll set the styles to be a plain black whilst generating this drop shadow
  31150. context.fillStyle = 'black';
  31151. context.strokeStyle = 'black';
  31152. var dropShadowColor = style.dropShadowColor;
  31153. var rgb = hex2rgb(typeof dropShadowColor === 'number' ? dropShadowColor : string2hex(dropShadowColor));
  31154. var dropShadowBlur = style.dropShadowBlur * this._resolution;
  31155. var dropShadowDistance = style.dropShadowDistance * this._resolution;
  31156. context.shadowColor = "rgba(" + rgb[0] * 255 + "," + rgb[1] * 255 + "," + rgb[2] * 255 + "," + style.dropShadowAlpha + ")";
  31157. context.shadowBlur = dropShadowBlur;
  31158. context.shadowOffsetX = Math.cos(style.dropShadowAngle) * dropShadowDistance;
  31159. context.shadowOffsetY = (Math.sin(style.dropShadowAngle) * dropShadowDistance) + dsOffsetShadow;
  31160. }
  31161. else {
  31162. // set canvas text styles
  31163. context.fillStyle = this._generateFillStyle(style, lines, measured);
  31164. // TODO: Can't have different types for getter and setter. The getter shouldn't have the number type as
  31165. // the setter converts to string. See this thread for more details:
  31166. // https://github.com/microsoft/TypeScript/issues/2521
  31167. context.strokeStyle = style.stroke;
  31168. context.shadowColor = 'black';
  31169. context.shadowBlur = 0;
  31170. context.shadowOffsetX = 0;
  31171. context.shadowOffsetY = 0;
  31172. }
  31173. var linePositionYShift = (lineHeight - fontProperties.fontSize) / 2;
  31174. if (!Text.nextLineHeightBehavior || lineHeight - fontProperties.fontSize < 0) {
  31175. linePositionYShift = 0;
  31176. }
  31177. // draw lines line by line
  31178. for (var i_1 = 0; i_1 < lines.length; i_1++) {
  31179. linePositionX = style.strokeThickness / 2;
  31180. linePositionY = ((style.strokeThickness / 2) + (i_1 * lineHeight)) + fontProperties.ascent
  31181. + linePositionYShift;
  31182. if (style.align === 'right') {
  31183. linePositionX += maxLineWidth - lineWidths[i_1];
  31184. }
  31185. else if (style.align === 'center') {
  31186. linePositionX += (maxLineWidth - lineWidths[i_1]) / 2;
  31187. }
  31188. if (style.stroke && style.strokeThickness) {
  31189. this.drawLetterSpacing(lines[i_1], linePositionX + style.padding, linePositionY + style.padding - dsOffsetText, true);
  31190. }
  31191. if (style.fill) {
  31192. this.drawLetterSpacing(lines[i_1], linePositionX + style.padding, linePositionY + style.padding - dsOffsetText);
  31193. }
  31194. }
  31195. }
  31196. this.updateTexture();
  31197. };
  31198. /**
  31199. * Render the text with letter-spacing.
  31200. * @param text - The text to draw
  31201. * @param x - Horizontal position to draw the text
  31202. * @param y - Vertical position to draw the text
  31203. * @param isStroke - Is this drawing for the outside stroke of the
  31204. * text? If not, it's for the inside fill
  31205. */
  31206. Text.prototype.drawLetterSpacing = function (text, x, y, isStroke) {
  31207. if (isStroke === void 0) { isStroke = false; }
  31208. var style = this._style;
  31209. // letterSpacing of 0 means normal
  31210. var letterSpacing = style.letterSpacing;
  31211. // Checking that we can use moddern canvas2D api
  31212. // https://developer.chrome.com/origintrials/#/view_trial/3585991203293757441
  31213. // note: this is unstable API, Chrome less 94 use a `textLetterSpacing`, newest use a letterSpacing
  31214. // eslint-disable-next-line max-len
  31215. var supportLetterSpacing = Text.experimentalLetterSpacing
  31216. && ('letterSpacing' in CanvasRenderingContext2D.prototype
  31217. || 'textLetterSpacing' in CanvasRenderingContext2D.prototype);
  31218. if (letterSpacing === 0 || supportLetterSpacing) {
  31219. if (supportLetterSpacing) {
  31220. this.context.letterSpacing = letterSpacing;
  31221. this.context.textLetterSpacing = letterSpacing;
  31222. }
  31223. if (isStroke) {
  31224. this.context.strokeText(text, x, y);
  31225. }
  31226. else {
  31227. this.context.fillText(text, x, y);
  31228. }
  31229. return;
  31230. }
  31231. var currentPosition = x;
  31232. // Using Array.from correctly splits characters whilst keeping emoji together.
  31233. // This is not supported on IE as it requires ES6, so regular text splitting occurs.
  31234. // This also doesn't account for emoji that are multiple emoji put together to make something else.
  31235. // Handling all of this would require a big library itself.
  31236. // https://medium.com/@giltayar/iterating-over-emoji-characters-the-es6-way-f06e4589516
  31237. // https://github.com/orling/grapheme-splitter
  31238. var stringArray = Array.from ? Array.from(text) : text.split('');
  31239. var previousWidth = this.context.measureText(text).width;
  31240. var currentWidth = 0;
  31241. for (var i = 0; i < stringArray.length; ++i) {
  31242. var currentChar = stringArray[i];
  31243. if (isStroke) {
  31244. this.context.strokeText(currentChar, currentPosition, y);
  31245. }
  31246. else {
  31247. this.context.fillText(currentChar, currentPosition, y);
  31248. }
  31249. var textStr = '';
  31250. for (var j = i + 1; j < stringArray.length; ++j) {
  31251. textStr += stringArray[j];
  31252. }
  31253. currentWidth = this.context.measureText(textStr).width;
  31254. currentPosition += previousWidth - currentWidth + letterSpacing;
  31255. previousWidth = currentWidth;
  31256. }
  31257. };
  31258. /** Updates texture size based on canvas size. */
  31259. Text.prototype.updateTexture = function () {
  31260. var canvas = this.canvas;
  31261. if (this._style.trim) {
  31262. var trimmed = trimCanvas(canvas);
  31263. if (trimmed.data) {
  31264. canvas.width = trimmed.width;
  31265. canvas.height = trimmed.height;
  31266. this.context.putImageData(trimmed.data, 0, 0);
  31267. }
  31268. }
  31269. var texture = this._texture;
  31270. var style = this._style;
  31271. var padding = style.trim ? 0 : style.padding;
  31272. var baseTexture = texture.baseTexture;
  31273. texture.trim.width = texture._frame.width = canvas.width / this._resolution;
  31274. texture.trim.height = texture._frame.height = canvas.height / this._resolution;
  31275. texture.trim.x = -padding;
  31276. texture.trim.y = -padding;
  31277. texture.orig.width = texture._frame.width - (padding * 2);
  31278. texture.orig.height = texture._frame.height - (padding * 2);
  31279. // call sprite onTextureUpdate to update scale if _width or _height were set
  31280. this._onTextureUpdate();
  31281. baseTexture.setRealSize(canvas.width, canvas.height, this._resolution);
  31282. texture.updateUvs();
  31283. this.dirty = false;
  31284. };
  31285. /**
  31286. * Renders the object using the WebGL renderer
  31287. * @param renderer - The renderer
  31288. */
  31289. Text.prototype._render = function (renderer) {
  31290. if (this._autoResolution && this._resolution !== renderer.resolution) {
  31291. this._resolution = renderer.resolution;
  31292. this.dirty = true;
  31293. }
  31294. this.updateText(true);
  31295. _super.prototype._render.call(this, renderer);
  31296. };
  31297. /** Updates the transform on all children of this container for rendering. */
  31298. Text.prototype.updateTransform = function () {
  31299. this.updateText(true);
  31300. _super.prototype.updateTransform.call(this);
  31301. };
  31302. Text.prototype.getBounds = function (skipUpdate, rect) {
  31303. this.updateText(true);
  31304. if (this._textureID === -1) {
  31305. // texture was updated: recalculate transforms
  31306. skipUpdate = false;
  31307. }
  31308. return _super.prototype.getBounds.call(this, skipUpdate, rect);
  31309. };
  31310. /**
  31311. * Gets the local bounds of the text object.
  31312. * @param rect - The output rectangle.
  31313. * @returns The bounds.
  31314. */
  31315. Text.prototype.getLocalBounds = function (rect) {
  31316. this.updateText(true);
  31317. return _super.prototype.getLocalBounds.call(this, rect);
  31318. };
  31319. /** Calculates the bounds of the Text as a rectangle. The bounds calculation takes the worldTransform into account. */
  31320. Text.prototype._calculateBounds = function () {
  31321. this.calculateVertices();
  31322. // if we have already done this on THIS frame.
  31323. this._bounds.addQuad(this.vertexData);
  31324. };
  31325. /**
  31326. * Generates the fill style. Can automatically generate a gradient based on the fill style being an array
  31327. * @param style - The style.
  31328. * @param lines - The lines of text.
  31329. * @param metrics
  31330. * @returns The fill style
  31331. */
  31332. Text.prototype._generateFillStyle = function (style, lines, metrics) {
  31333. // TODO: Can't have different types for getter and setter. The getter shouldn't have the number type as
  31334. // the setter converts to string. See this thread for more details:
  31335. // https://github.com/microsoft/TypeScript/issues/2521
  31336. var fillStyle = style.fill;
  31337. if (!Array.isArray(fillStyle)) {
  31338. return fillStyle;
  31339. }
  31340. else if (fillStyle.length === 1) {
  31341. return fillStyle[0];
  31342. }
  31343. // the gradient will be evenly spaced out according to how large the array is.
  31344. // ['#FF0000', '#00FF00', '#0000FF'] would created stops at 0.25, 0.5 and 0.75
  31345. var gradient;
  31346. // a dropshadow will enlarge the canvas and result in the gradient being
  31347. // generated with the incorrect dimensions
  31348. var dropShadowCorrection = (style.dropShadow) ? style.dropShadowDistance : 0;
  31349. // should also take padding into account, padding can offset the gradient
  31350. var padding = style.padding || 0;
  31351. var width = (this.canvas.width / this._resolution) - dropShadowCorrection - (padding * 2);
  31352. var height = (this.canvas.height / this._resolution) - dropShadowCorrection - (padding * 2);
  31353. // make a copy of the style settings, so we can manipulate them later
  31354. var fill = fillStyle.slice();
  31355. var fillGradientStops = style.fillGradientStops.slice();
  31356. // wanting to evenly distribute the fills. So an array of 4 colours should give fills of 0.25, 0.5 and 0.75
  31357. if (!fillGradientStops.length) {
  31358. var lengthPlus1 = fill.length + 1;
  31359. for (var i = 1; i < lengthPlus1; ++i) {
  31360. fillGradientStops.push(i / lengthPlus1);
  31361. }
  31362. }
  31363. // stop the bleeding of the last gradient on the line above to the top gradient of the this line
  31364. // by hard defining the first gradient colour at point 0, and last gradient colour at point 1
  31365. fill.unshift(fillStyle[0]);
  31366. fillGradientStops.unshift(0);
  31367. fill.push(fillStyle[fillStyle.length - 1]);
  31368. fillGradientStops.push(1);
  31369. if (style.fillGradientType === TEXT_GRADIENT.LINEAR_VERTICAL) {
  31370. // start the gradient at the top center of the canvas, and end at the bottom middle of the canvas
  31371. gradient = this.context.createLinearGradient(width / 2, padding, width / 2, height + padding);
  31372. // we need to repeat the gradient so that each individual line of text has the same vertical gradient effect
  31373. // ['#FF0000', '#00FF00', '#0000FF'] over 2 lines would create stops at 0.125, 0.25, 0.375, 0.625, 0.75, 0.875
  31374. // Actual height of the text itself, not counting spacing for lineHeight/leading/dropShadow etc
  31375. var textHeight = metrics.fontProperties.fontSize + style.strokeThickness;
  31376. for (var i = 0; i < lines.length; i++) {
  31377. var lastLineBottom = (metrics.lineHeight * (i - 1)) + textHeight;
  31378. var thisLineTop = metrics.lineHeight * i;
  31379. var thisLineGradientStart = thisLineTop;
  31380. // Handle case where last & this line overlap
  31381. if (i > 0 && lastLineBottom > thisLineTop) {
  31382. thisLineGradientStart = (thisLineTop + lastLineBottom) / 2;
  31383. }
  31384. var thisLineBottom = thisLineTop + textHeight;
  31385. var nextLineTop = metrics.lineHeight * (i + 1);
  31386. var thisLineGradientEnd = thisLineBottom;
  31387. // Handle case where this & next line overlap
  31388. if (i + 1 < lines.length && nextLineTop < thisLineBottom) {
  31389. thisLineGradientEnd = (thisLineBottom + nextLineTop) / 2;
  31390. }
  31391. // textHeight, but as a 0-1 size in global gradient stop space
  31392. var gradStopLineHeight = (thisLineGradientEnd - thisLineGradientStart) / height;
  31393. for (var j = 0; j < fill.length; j++) {
  31394. // 0-1 stop point for the current line, multiplied to global space afterwards
  31395. var lineStop = 0;
  31396. if (typeof fillGradientStops[j] === 'number') {
  31397. lineStop = fillGradientStops[j];
  31398. }
  31399. else {
  31400. lineStop = j / fill.length;
  31401. }
  31402. var globalStop = Math.min(1, Math.max(0, (thisLineGradientStart / height) + (lineStop * gradStopLineHeight)));
  31403. // There's potential for floating point precision issues at the seams between gradient repeats.
  31404. globalStop = Number(globalStop.toFixed(5));
  31405. gradient.addColorStop(globalStop, fill[j]);
  31406. }
  31407. }
  31408. }
  31409. else {
  31410. // start the gradient at the center left of the canvas, and end at the center right of the canvas
  31411. gradient = this.context.createLinearGradient(padding, height / 2, width + padding, height / 2);
  31412. // can just evenly space out the gradients in this case, as multiple lines makes no difference
  31413. // to an even left to right gradient
  31414. var totalIterations = fill.length + 1;
  31415. var currentIteration = 1;
  31416. for (var i = 0; i < fill.length; i++) {
  31417. var stop = void 0;
  31418. if (typeof fillGradientStops[i] === 'number') {
  31419. stop = fillGradientStops[i];
  31420. }
  31421. else {
  31422. stop = currentIteration / totalIterations;
  31423. }
  31424. gradient.addColorStop(stop, fill[i]);
  31425. currentIteration++;
  31426. }
  31427. }
  31428. return gradient;
  31429. };
  31430. /**
  31431. * Destroys this text object.
  31432. *
  31433. * Note* Unlike a Sprite, a Text object will automatically destroy its baseTexture and texture as
  31434. * the majority of the time the texture will not be shared with any other Sprites.
  31435. * @param options - Options parameter. A boolean will act as if all options
  31436. * have been set to that value
  31437. * @param {boolean} [options.children=false] - if set to true, all the children will have their
  31438. * destroy method called as well. 'options' will be passed on to those calls.
  31439. * @param {boolean} [options.texture=true] - Should it destroy the current texture of the sprite as well
  31440. * @param {boolean} [options.baseTexture=true] - Should it destroy the base texture of the sprite as well
  31441. */
  31442. Text.prototype.destroy = function (options) {
  31443. if (typeof options === 'boolean') {
  31444. options = { children: options };
  31445. }
  31446. options = Object.assign({}, defaultDestroyOptions, options);
  31447. _super.prototype.destroy.call(this, options);
  31448. // set canvas width and height to 0 to workaround memory leak in Safari < 13
  31449. // https://stackoverflow.com/questions/52532614/total-canvas-memory-use-exceeds-the-maximum-limit-safari-12
  31450. if (this._ownCanvas) {
  31451. this.canvas.height = this.canvas.width = 0;
  31452. }
  31453. // make sure to reset the context and canvas.. dont want this hanging around in memory!
  31454. this.context = null;
  31455. this.canvas = null;
  31456. this._style = null;
  31457. };
  31458. Object.defineProperty(Text.prototype, "width", {
  31459. /** The width of the Text, setting this will actually modify the scale to achieve the value set. */
  31460. get: function () {
  31461. this.updateText(true);
  31462. return Math.abs(this.scale.x) * this._texture.orig.width;
  31463. },
  31464. set: function (value) {
  31465. this.updateText(true);
  31466. var s = sign(this.scale.x) || 1;
  31467. this.scale.x = s * value / this._texture.orig.width;
  31468. this._width = value;
  31469. },
  31470. enumerable: false,
  31471. configurable: true
  31472. });
  31473. Object.defineProperty(Text.prototype, "height", {
  31474. /** The height of the Text, setting this will actually modify the scale to achieve the value set. */
  31475. get: function () {
  31476. this.updateText(true);
  31477. return Math.abs(this.scale.y) * this._texture.orig.height;
  31478. },
  31479. set: function (value) {
  31480. this.updateText(true);
  31481. var s = sign(this.scale.y) || 1;
  31482. this.scale.y = s * value / this._texture.orig.height;
  31483. this._height = value;
  31484. },
  31485. enumerable: false,
  31486. configurable: true
  31487. });
  31488. Object.defineProperty(Text.prototype, "style", {
  31489. /**
  31490. * Set the style of the text.
  31491. *
  31492. * Set up an event listener to listen for changes on the style object and mark the text as dirty.
  31493. */
  31494. get: function () {
  31495. // TODO: Can't have different types for getter and setter. The getter shouldn't have the ITextStyle
  31496. // since the setter creates the TextStyle. See this thread for more details:
  31497. // https://github.com/microsoft/TypeScript/issues/2521
  31498. return this._style;
  31499. },
  31500. set: function (style) {
  31501. style = style || {};
  31502. if (style instanceof TextStyle) {
  31503. this._style = style;
  31504. }
  31505. else {
  31506. this._style = new TextStyle(style);
  31507. }
  31508. this.localStyleID = -1;
  31509. this.dirty = true;
  31510. },
  31511. enumerable: false,
  31512. configurable: true
  31513. });
  31514. Object.defineProperty(Text.prototype, "text", {
  31515. /** Set the copy for the text object. To split a line you can use '\n'. */
  31516. get: function () {
  31517. return this._text;
  31518. },
  31519. set: function (text) {
  31520. text = String(text === null || text === undefined ? '' : text);
  31521. if (this._text === text) {
  31522. return;
  31523. }
  31524. this._text = text;
  31525. this.dirty = true;
  31526. },
  31527. enumerable: false,
  31528. configurable: true
  31529. });
  31530. Object.defineProperty(Text.prototype, "resolution", {
  31531. /**
  31532. * The resolution / device pixel ratio of the canvas.
  31533. *
  31534. * This is set to automatically match the renderer resolution by default, but can be overridden by setting manually.
  31535. * @default 1
  31536. */
  31537. get: function () {
  31538. return this._resolution;
  31539. },
  31540. set: function (value) {
  31541. this._autoResolution = false;
  31542. if (this._resolution === value) {
  31543. return;
  31544. }
  31545. this._resolution = value;
  31546. this.dirty = true;
  31547. },
  31548. enumerable: false,
  31549. configurable: true
  31550. });
  31551. /**
  31552. * New behavior for `lineHeight` that's meant to mimic HTML text. A value of `true` will
  31553. * make sure the first baseline is offset by the `lineHeight` value if it is greater than `fontSize`.
  31554. * A value of `false` will use the legacy behavior and not change the baseline of the first line.
  31555. * In the next major release, we'll enable this by default.
  31556. */
  31557. Text.nextLineHeightBehavior = false;
  31558. /**
  31559. * New rendering behavior for letter-spacing which uses Chrome's new native API. This will
  31560. * lead to more accurate letter-spacing results because it does not try to manually draw
  31561. * each character. However, this Chrome API is experimental and may not serve all cases yet.
  31562. */
  31563. Text.experimentalLetterSpacing = false;
  31564. return Text;
  31565. }(Sprite));
  31566. /*!
  31567. * @pixi/prepare - v6.5.10
  31568. * Compiled Thu, 06 Jul 2023 15:25:11 UTC
  31569. *
  31570. * @pixi/prepare is licensed under the MIT License.
  31571. * http://www.opensource.org/licenses/mit-license
  31572. */
  31573. /**
  31574. * Default number of uploads per frame using prepare plugin.
  31575. * @static
  31576. * @memberof PIXI.settings
  31577. * @name UPLOADS_PER_FRAME
  31578. * @type {number}
  31579. * @default 4
  31580. */
  31581. settings.UPLOADS_PER_FRAME = 4;
  31582. /*! *****************************************************************************
  31583. Copyright (c) Microsoft Corporation.
  31584. Permission to use, copy, modify, and/or distribute this software for any
  31585. purpose with or without fee is hereby granted.
  31586. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  31587. REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
  31588. AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  31589. INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
  31590. LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
  31591. OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
  31592. PERFORMANCE OF THIS SOFTWARE.
  31593. ***************************************************************************** */
  31594. /* global Reflect, Promise */
  31595. var extendStatics$b = function(d, b) {
  31596. extendStatics$b = Object.setPrototypeOf ||
  31597. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  31598. function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } };
  31599. return extendStatics$b(d, b);
  31600. };
  31601. function __extends$b(d, b) {
  31602. extendStatics$b(d, b);
  31603. function __() { this.constructor = d; }
  31604. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  31605. }
  31606. /**
  31607. * CountLimiter limits the number of items handled by a {@link PIXI.BasePrepare} to a specified
  31608. * number of items per frame.
  31609. * @memberof PIXI
  31610. */
  31611. var CountLimiter = /** @class */ (function () {
  31612. /**
  31613. * @param maxItemsPerFrame - The maximum number of items that can be prepared each frame.
  31614. */
  31615. function CountLimiter(maxItemsPerFrame) {
  31616. this.maxItemsPerFrame = maxItemsPerFrame;
  31617. this.itemsLeft = 0;
  31618. }
  31619. /** Resets any counting properties to start fresh on a new frame. */
  31620. CountLimiter.prototype.beginFrame = function () {
  31621. this.itemsLeft = this.maxItemsPerFrame;
  31622. };
  31623. /**
  31624. * Checks to see if another item can be uploaded. This should only be called once per item.
  31625. * @returns If the item is allowed to be uploaded.
  31626. */
  31627. CountLimiter.prototype.allowedToUpload = function () {
  31628. return this.itemsLeft-- > 0;
  31629. };
  31630. return CountLimiter;
  31631. }());
  31632. /**
  31633. * Built-in hook to find multiple textures from objects like AnimatedSprites.
  31634. * @private
  31635. * @param item - Display object to check
  31636. * @param queue - Collection of items to upload
  31637. * @returns If a PIXI.Texture object was found.
  31638. */
  31639. function findMultipleBaseTextures(item, queue) {
  31640. var result = false;
  31641. // Objects with multiple textures
  31642. if (item && item._textures && item._textures.length) {
  31643. for (var i = 0; i < item._textures.length; i++) {
  31644. if (item._textures[i] instanceof Texture) {
  31645. var baseTexture = item._textures[i].baseTexture;
  31646. if (queue.indexOf(baseTexture) === -1) {
  31647. queue.push(baseTexture);
  31648. result = true;
  31649. }
  31650. }
  31651. }
  31652. }
  31653. return result;
  31654. }
  31655. /**
  31656. * Built-in hook to find BaseTextures from Texture.
  31657. * @private
  31658. * @param item - Display object to check
  31659. * @param queue - Collection of items to upload
  31660. * @returns If a PIXI.Texture object was found.
  31661. */
  31662. function findBaseTexture(item, queue) {
  31663. if (item.baseTexture instanceof BaseTexture) {
  31664. var texture = item.baseTexture;
  31665. if (queue.indexOf(texture) === -1) {
  31666. queue.push(texture);
  31667. }
  31668. return true;
  31669. }
  31670. return false;
  31671. }
  31672. /**
  31673. * Built-in hook to find textures from objects.
  31674. * @private
  31675. * @param item - Display object to check
  31676. * @param queue - Collection of items to upload
  31677. * @returns If a PIXI.Texture object was found.
  31678. */
  31679. function findTexture(item, queue) {
  31680. if (item._texture && item._texture instanceof Texture) {
  31681. var texture = item._texture.baseTexture;
  31682. if (queue.indexOf(texture) === -1) {
  31683. queue.push(texture);
  31684. }
  31685. return true;
  31686. }
  31687. return false;
  31688. }
  31689. /**
  31690. * Built-in hook to draw PIXI.Text to its texture.
  31691. * @private
  31692. * @param _helper - Not used by this upload handler
  31693. * @param item - Item to check
  31694. * @returns If item was uploaded.
  31695. */
  31696. function drawText(_helper, item) {
  31697. if (item instanceof Text) {
  31698. // updating text will return early if it is not dirty
  31699. item.updateText(true);
  31700. return true;
  31701. }
  31702. return false;
  31703. }
  31704. /**
  31705. * Built-in hook to calculate a text style for a PIXI.Text object.
  31706. * @private
  31707. * @param _helper - Not used by this upload handler
  31708. * @param item - Item to check
  31709. * @returns If item was uploaded.
  31710. */
  31711. function calculateTextStyle(_helper, item) {
  31712. if (item instanceof TextStyle) {
  31713. var font = item.toFontString();
  31714. TextMetrics.measureFont(font);
  31715. return true;
  31716. }
  31717. return false;
  31718. }
  31719. /**
  31720. * Built-in hook to find Text objects.
  31721. * @private
  31722. * @param item - Display object to check
  31723. * @param queue - Collection of items to upload
  31724. * @returns if a PIXI.Text object was found.
  31725. */
  31726. function findText(item, queue) {
  31727. if (item instanceof Text) {
  31728. // push the text style to prepare it - this can be really expensive
  31729. if (queue.indexOf(item.style) === -1) {
  31730. queue.push(item.style);
  31731. }
  31732. // also push the text object so that we can render it (to canvas/texture) if needed
  31733. if (queue.indexOf(item) === -1) {
  31734. queue.push(item);
  31735. }
  31736. // also push the Text's texture for upload to GPU
  31737. var texture = item._texture.baseTexture;
  31738. if (queue.indexOf(texture) === -1) {
  31739. queue.push(texture);
  31740. }
  31741. return true;
  31742. }
  31743. return false;
  31744. }
  31745. /**
  31746. * Built-in hook to find TextStyle objects.
  31747. * @private
  31748. * @param item - Display object to check
  31749. * @param queue - Collection of items to upload
  31750. * @returns If a PIXI.TextStyle object was found.
  31751. */
  31752. function findTextStyle(item, queue) {
  31753. if (item instanceof TextStyle) {
  31754. if (queue.indexOf(item) === -1) {
  31755. queue.push(item);
  31756. }
  31757. return true;
  31758. }
  31759. return false;
  31760. }
  31761. /**
  31762. * The prepare manager provides functionality to upload content to the GPU.
  31763. *
  31764. * BasePrepare handles basic queuing functionality and is extended by
  31765. * {@link PIXI.Prepare} and {@link PIXI.CanvasPrepare}
  31766. * to provide preparation capabilities specific to their respective renderers.
  31767. * @example
  31768. * // Create a sprite
  31769. * const sprite = PIXI.Sprite.from('something.png');
  31770. *
  31771. * // Load object into GPU
  31772. * app.renderer.plugins.prepare.upload(sprite, () => {
  31773. *
  31774. * //Texture(s) has been uploaded to GPU
  31775. * app.stage.addChild(sprite);
  31776. *
  31777. * })
  31778. * @abstract
  31779. * @memberof PIXI
  31780. */
  31781. var BasePrepare = /** @class */ (function () {
  31782. /**
  31783. * @param {PIXI.AbstractRenderer} renderer - A reference to the current renderer
  31784. */
  31785. function BasePrepare(renderer) {
  31786. var _this = this;
  31787. this.limiter = new CountLimiter(settings.UPLOADS_PER_FRAME);
  31788. this.renderer = renderer;
  31789. this.uploadHookHelper = null;
  31790. this.queue = [];
  31791. this.addHooks = [];
  31792. this.uploadHooks = [];
  31793. this.completes = [];
  31794. this.ticking = false;
  31795. this.delayedTick = function () {
  31796. // unlikely, but in case we were destroyed between tick() and delayedTick()
  31797. if (!_this.queue) {
  31798. return;
  31799. }
  31800. _this.prepareItems();
  31801. };
  31802. // hooks to find the correct texture
  31803. this.registerFindHook(findText);
  31804. this.registerFindHook(findTextStyle);
  31805. this.registerFindHook(findMultipleBaseTextures);
  31806. this.registerFindHook(findBaseTexture);
  31807. this.registerFindHook(findTexture);
  31808. // upload hooks
  31809. this.registerUploadHook(drawText);
  31810. this.registerUploadHook(calculateTextStyle);
  31811. }
  31812. /** @ignore */
  31813. BasePrepare.prototype.upload = function (item, done) {
  31814. var _this = this;
  31815. if (typeof item === 'function') {
  31816. done = item;
  31817. item = null;
  31818. }
  31819. if (done) {
  31820. deprecation('6.5.0', 'BasePrepare.upload callback is deprecated, use the return Promise instead.');
  31821. }
  31822. return new Promise(function (resolve) {
  31823. // If a display object, search for items
  31824. // that we could upload
  31825. if (item) {
  31826. _this.add(item);
  31827. }
  31828. // TODO: remove done callback and just use resolve
  31829. var complete = function () {
  31830. done === null || done === void 0 ? void 0 : done();
  31831. resolve();
  31832. };
  31833. // Get the items for upload from the display
  31834. if (_this.queue.length) {
  31835. _this.completes.push(complete);
  31836. if (!_this.ticking) {
  31837. _this.ticking = true;
  31838. Ticker.system.addOnce(_this.tick, _this, UPDATE_PRIORITY.UTILITY);
  31839. }
  31840. }
  31841. else {
  31842. complete();
  31843. }
  31844. });
  31845. };
  31846. /**
  31847. * Handle tick update
  31848. * @private
  31849. */
  31850. BasePrepare.prototype.tick = function () {
  31851. setTimeout(this.delayedTick, 0);
  31852. };
  31853. /**
  31854. * Actually prepare items. This is handled outside of the tick because it will take a while
  31855. * and we do NOT want to block the current animation frame from rendering.
  31856. * @private
  31857. */
  31858. BasePrepare.prototype.prepareItems = function () {
  31859. this.limiter.beginFrame();
  31860. // Upload the graphics
  31861. while (this.queue.length && this.limiter.allowedToUpload()) {
  31862. var item = this.queue[0];
  31863. var uploaded = false;
  31864. if (item && !item._destroyed) {
  31865. for (var i = 0, len = this.uploadHooks.length; i < len; i++) {
  31866. if (this.uploadHooks[i](this.uploadHookHelper, item)) {
  31867. this.queue.shift();
  31868. uploaded = true;
  31869. break;
  31870. }
  31871. }
  31872. }
  31873. if (!uploaded) {
  31874. this.queue.shift();
  31875. }
  31876. }
  31877. // We're finished
  31878. if (!this.queue.length) {
  31879. this.ticking = false;
  31880. var completes = this.completes.slice(0);
  31881. this.completes.length = 0;
  31882. for (var i = 0, len = completes.length; i < len; i++) {
  31883. completes[i]();
  31884. }
  31885. }
  31886. else {
  31887. // if we are not finished, on the next rAF do this again
  31888. Ticker.system.addOnce(this.tick, this, UPDATE_PRIORITY.UTILITY);
  31889. }
  31890. };
  31891. /**
  31892. * Adds hooks for finding items.
  31893. * @param {Function} addHook - Function call that takes two parameters: `item:*, queue:Array`
  31894. * function must return `true` if it was able to add item to the queue.
  31895. * @returns Instance of plugin for chaining.
  31896. */
  31897. BasePrepare.prototype.registerFindHook = function (addHook) {
  31898. if (addHook) {
  31899. this.addHooks.push(addHook);
  31900. }
  31901. return this;
  31902. };
  31903. /**
  31904. * Adds hooks for uploading items.
  31905. * @param {Function} uploadHook - Function call that takes two parameters: `prepare:CanvasPrepare, item:*` and
  31906. * function must return `true` if it was able to handle upload of item.
  31907. * @returns Instance of plugin for chaining.
  31908. */
  31909. BasePrepare.prototype.registerUploadHook = function (uploadHook) {
  31910. if (uploadHook) {
  31911. this.uploadHooks.push(uploadHook);
  31912. }
  31913. return this;
  31914. };
  31915. /**
  31916. * Manually add an item to the uploading queue.
  31917. * @param {PIXI.DisplayObject|PIXI.Container|PIXI.BaseTexture|PIXI.Texture|PIXI.Graphics|PIXI.Text|*} item - Object to
  31918. * add to the queue
  31919. * @returns Instance of plugin for chaining.
  31920. */
  31921. BasePrepare.prototype.add = function (item) {
  31922. // Add additional hooks for finding elements on special
  31923. // types of objects that
  31924. for (var i = 0, len = this.addHooks.length; i < len; i++) {
  31925. if (this.addHooks[i](item, this.queue)) {
  31926. break;
  31927. }
  31928. }
  31929. // Get children recursively
  31930. if (item instanceof Container) {
  31931. for (var i = item.children.length - 1; i >= 0; i--) {
  31932. this.add(item.children[i]);
  31933. }
  31934. }
  31935. return this;
  31936. };
  31937. /** Destroys the plugin, don't use after this. */
  31938. BasePrepare.prototype.destroy = function () {
  31939. if (this.ticking) {
  31940. Ticker.system.remove(this.tick, this);
  31941. }
  31942. this.ticking = false;
  31943. this.addHooks = null;
  31944. this.uploadHooks = null;
  31945. this.renderer = null;
  31946. this.completes = null;
  31947. this.queue = null;
  31948. this.limiter = null;
  31949. this.uploadHookHelper = null;
  31950. };
  31951. return BasePrepare;
  31952. }());
  31953. /**
  31954. * Built-in hook to upload PIXI.Texture objects to the GPU.
  31955. * @private
  31956. * @param renderer - instance of the webgl renderer
  31957. * @param item - Item to check
  31958. * @returns If item was uploaded.
  31959. */
  31960. function uploadBaseTextures(renderer, item) {
  31961. if (item instanceof BaseTexture) {
  31962. // if the texture already has a GL texture, then the texture has been prepared or rendered
  31963. // before now. If the texture changed, then the changer should be calling texture.update() which
  31964. // reuploads the texture without need for preparing it again
  31965. if (!item._glTextures[renderer.CONTEXT_UID]) {
  31966. renderer.texture.bind(item);
  31967. }
  31968. return true;
  31969. }
  31970. return false;
  31971. }
  31972. /**
  31973. * Built-in hook to upload PIXI.Graphics to the GPU.
  31974. * @private
  31975. * @param renderer - instance of the webgl renderer
  31976. * @param item - Item to check
  31977. * @returns If item was uploaded.
  31978. */
  31979. function uploadGraphics(renderer, item) {
  31980. if (!(item instanceof Graphics)) {
  31981. return false;
  31982. }
  31983. var geometry = item.geometry;
  31984. // update dirty graphics to get batches
  31985. item.finishPoly();
  31986. geometry.updateBatches();
  31987. var batches = geometry.batches;
  31988. // upload all textures found in styles
  31989. for (var i = 0; i < batches.length; i++) {
  31990. var texture = batches[i].style.texture;
  31991. if (texture) {
  31992. uploadBaseTextures(renderer, texture.baseTexture);
  31993. }
  31994. }
  31995. // if its not batchable - update vao for particular shader
  31996. if (!geometry.batchable) {
  31997. renderer.geometry.bind(geometry, item._resolveDirectShader(renderer));
  31998. }
  31999. return true;
  32000. }
  32001. /**
  32002. * Built-in hook to find graphics.
  32003. * @private
  32004. * @param item - Display object to check
  32005. * @param queue - Collection of items to upload
  32006. * @returns if a PIXI.Graphics object was found.
  32007. */
  32008. function findGraphics(item, queue) {
  32009. if (item instanceof Graphics) {
  32010. queue.push(item);
  32011. return true;
  32012. }
  32013. return false;
  32014. }
  32015. /**
  32016. * The prepare plugin provides renderer-specific plugins for pre-rendering DisplayObjects. These plugins are useful for
  32017. * asynchronously preparing and uploading to the GPU assets, textures, graphics waiting to be displayed.
  32018. *
  32019. * Do not instantiate this plugin directly. It is available from the `renderer.plugins` property.
  32020. * See {@link PIXI.CanvasRenderer#plugins} or {@link PIXI.Renderer#plugins}.
  32021. * @example
  32022. * // Create a new application
  32023. * const app = new PIXI.Application();
  32024. * document.body.appendChild(app.view);
  32025. *
  32026. * // Don't start rendering right away
  32027. * app.stop();
  32028. *
  32029. * // create a display object
  32030. * const rect = new PIXI.Graphics()
  32031. * .beginFill(0x00ff00)
  32032. * .drawRect(40, 40, 200, 200);
  32033. *
  32034. * // Add to the stage
  32035. * app.stage.addChild(rect);
  32036. *
  32037. * // Don't start rendering until the graphic is uploaded to the GPU
  32038. * app.renderer.plugins.prepare.upload(app.stage, () => {
  32039. * app.start();
  32040. * });
  32041. * @memberof PIXI
  32042. */
  32043. var Prepare = /** @class */ (function (_super) {
  32044. __extends$b(Prepare, _super);
  32045. /**
  32046. * @param {PIXI.Renderer} renderer - A reference to the current renderer
  32047. */
  32048. function Prepare(renderer) {
  32049. var _this = _super.call(this, renderer) || this;
  32050. _this.uploadHookHelper = _this.renderer;
  32051. // Add textures and graphics to upload
  32052. _this.registerFindHook(findGraphics);
  32053. _this.registerUploadHook(uploadBaseTextures);
  32054. _this.registerUploadHook(uploadGraphics);
  32055. return _this;
  32056. }
  32057. /** @ignore */
  32058. Prepare.extension = {
  32059. name: 'prepare',
  32060. type: ExtensionType.RendererPlugin,
  32061. };
  32062. return Prepare;
  32063. }(BasePrepare));
  32064. /**
  32065. * TimeLimiter limits the number of items handled by a {@link PIXI.BasePrepare} to a specified
  32066. * number of milliseconds per frame.
  32067. * @memberof PIXI
  32068. */
  32069. var TimeLimiter = /** @class */ (function () {
  32070. /** @param maxMilliseconds - The maximum milliseconds that can be spent preparing items each frame. */
  32071. function TimeLimiter(maxMilliseconds) {
  32072. this.maxMilliseconds = maxMilliseconds;
  32073. this.frameStart = 0;
  32074. }
  32075. /** Resets any counting properties to start fresh on a new frame. */
  32076. TimeLimiter.prototype.beginFrame = function () {
  32077. this.frameStart = Date.now();
  32078. };
  32079. /**
  32080. * Checks to see if another item can be uploaded. This should only be called once per item.
  32081. * @returns - If the item is allowed to be uploaded.
  32082. */
  32083. TimeLimiter.prototype.allowedToUpload = function () {
  32084. return Date.now() - this.frameStart < this.maxMilliseconds;
  32085. };
  32086. return TimeLimiter;
  32087. }());
  32088. /*!
  32089. * @pixi/spritesheet - v6.5.10
  32090. * Compiled Thu, 06 Jul 2023 15:25:11 UTC
  32091. *
  32092. * @pixi/spritesheet is licensed under the MIT License.
  32093. * http://www.opensource.org/licenses/mit-license
  32094. */
  32095. /**
  32096. * Utility class for maintaining reference to a collection
  32097. * of Textures on a single Spritesheet.
  32098. *
  32099. * To access a sprite sheet from your code you may pass its JSON data file to Pixi's loader:
  32100. *
  32101. * ```js
  32102. * PIXI.Loader.shared.add("images/spritesheet.json").load(setup);
  32103. *
  32104. * function setup() {
  32105. * let sheet = PIXI.Loader.shared.resources["images/spritesheet.json"].spritesheet;
  32106. * ...
  32107. * }
  32108. * ```
  32109. *
  32110. * Alternately, you may circumvent the loader by instantiating the Spritesheet directly:
  32111. * ```js
  32112. * const sheet = new PIXI.Spritesheet(texture, spritesheetData);
  32113. * await sheet.parse();
  32114. * console.log('Spritesheet ready to use!');
  32115. * ```
  32116. *
  32117. * With the `sheet.textures` you can create Sprite objects,`sheet.animations` can be used to create an AnimatedSprite.
  32118. *
  32119. * Sprite sheets can be packed using tools like {@link https://codeandweb.com/texturepacker|TexturePacker},
  32120. * {@link https://renderhjs.net/shoebox/|Shoebox} or {@link https://github.com/krzysztof-o/spritesheet.js|Spritesheet.js}.
  32121. * Default anchor points (see {@link PIXI.Texture#defaultAnchor}) and grouping of animation sprites are currently only
  32122. * supported by TexturePacker.
  32123. * @memberof PIXI
  32124. */
  32125. var Spritesheet = /** @class */ (function () {
  32126. /**
  32127. * @param texture - Reference to the source BaseTexture object.
  32128. * @param {object} data - Spritesheet image data.
  32129. * @param resolutionFilename - The filename to consider when determining
  32130. * the resolution of the spritesheet. If not provided, the imageUrl will
  32131. * be used on the BaseTexture.
  32132. */
  32133. function Spritesheet(texture, data, resolutionFilename) {
  32134. if (resolutionFilename === void 0) { resolutionFilename = null; }
  32135. /** For multi-packed spritesheets, this contains a reference to all the other spritesheets it depends on. */
  32136. this.linkedSheets = [];
  32137. this._texture = texture instanceof Texture ? texture : null;
  32138. this.baseTexture = texture instanceof BaseTexture ? texture : this._texture.baseTexture;
  32139. this.textures = {};
  32140. this.animations = {};
  32141. this.data = data;
  32142. var resource = this.baseTexture.resource;
  32143. this.resolution = this._updateResolution(resolutionFilename || (resource ? resource.url : null));
  32144. this._frames = this.data.frames;
  32145. this._frameKeys = Object.keys(this._frames);
  32146. this._batchIndex = 0;
  32147. this._callback = null;
  32148. }
  32149. /**
  32150. * Generate the resolution from the filename or fallback
  32151. * to the meta.scale field of the JSON data.
  32152. * @param resolutionFilename - The filename to use for resolving
  32153. * the default resolution.
  32154. * @returns Resolution to use for spritesheet.
  32155. */
  32156. Spritesheet.prototype._updateResolution = function (resolutionFilename) {
  32157. if (resolutionFilename === void 0) { resolutionFilename = null; }
  32158. var scale = this.data.meta.scale;
  32159. // Use a defaultValue of `null` to check if a url-based resolution is set
  32160. var resolution = getResolutionOfUrl(resolutionFilename, null);
  32161. // No resolution found via URL
  32162. if (resolution === null) {
  32163. // Use the scale value or default to 1
  32164. resolution = scale !== undefined ? parseFloat(scale) : 1;
  32165. }
  32166. // For non-1 resolutions, update baseTexture
  32167. if (resolution !== 1) {
  32168. this.baseTexture.setResolution(resolution);
  32169. }
  32170. return resolution;
  32171. };
  32172. /** @ignore */
  32173. Spritesheet.prototype.parse = function (callback) {
  32174. var _this = this;
  32175. if (callback) {
  32176. deprecation('6.5.0', 'Spritesheet.parse callback is deprecated, use the return Promise instead.');
  32177. }
  32178. return new Promise(function (resolve) {
  32179. _this._callback = function (textures) {
  32180. callback === null || callback === void 0 ? void 0 : callback(textures);
  32181. resolve(textures);
  32182. };
  32183. _this._batchIndex = 0;
  32184. if (_this._frameKeys.length <= Spritesheet.BATCH_SIZE) {
  32185. _this._processFrames(0);
  32186. _this._processAnimations();
  32187. _this._parseComplete();
  32188. }
  32189. else {
  32190. _this._nextBatch();
  32191. }
  32192. });
  32193. };
  32194. /**
  32195. * Process a batch of frames
  32196. * @param initialFrameIndex - The index of frame to start.
  32197. */
  32198. Spritesheet.prototype._processFrames = function (initialFrameIndex) {
  32199. var frameIndex = initialFrameIndex;
  32200. var maxFrames = Spritesheet.BATCH_SIZE;
  32201. while (frameIndex - initialFrameIndex < maxFrames && frameIndex < this._frameKeys.length) {
  32202. var i = this._frameKeys[frameIndex];
  32203. var data = this._frames[i];
  32204. var rect = data.frame;
  32205. if (rect) {
  32206. var frame = null;
  32207. var trim = null;
  32208. var sourceSize = data.trimmed !== false && data.sourceSize
  32209. ? data.sourceSize : data.frame;
  32210. var orig = new Rectangle(0, 0, Math.floor(sourceSize.w) / this.resolution, Math.floor(sourceSize.h) / this.resolution);
  32211. if (data.rotated) {
  32212. frame = new Rectangle(Math.floor(rect.x) / this.resolution, Math.floor(rect.y) / this.resolution, Math.floor(rect.h) / this.resolution, Math.floor(rect.w) / this.resolution);
  32213. }
  32214. else {
  32215. frame = new Rectangle(Math.floor(rect.x) / this.resolution, Math.floor(rect.y) / this.resolution, Math.floor(rect.w) / this.resolution, Math.floor(rect.h) / this.resolution);
  32216. }
  32217. // Check to see if the sprite is trimmed
  32218. if (data.trimmed !== false && data.spriteSourceSize) {
  32219. trim = new Rectangle(Math.floor(data.spriteSourceSize.x) / this.resolution, Math.floor(data.spriteSourceSize.y) / this.resolution, Math.floor(rect.w) / this.resolution, Math.floor(rect.h) / this.resolution);
  32220. }
  32221. this.textures[i] = new Texture(this.baseTexture, frame, orig, trim, data.rotated ? 2 : 0, data.anchor);
  32222. // lets also add the frame to pixi's global cache for 'from' and 'fromLoader' functions
  32223. Texture.addToCache(this.textures[i], i);
  32224. }
  32225. frameIndex++;
  32226. }
  32227. };
  32228. /** Parse animations config. */
  32229. Spritesheet.prototype._processAnimations = function () {
  32230. var animations = this.data.animations || {};
  32231. for (var animName in animations) {
  32232. this.animations[animName] = [];
  32233. for (var i = 0; i < animations[animName].length; i++) {
  32234. var frameName = animations[animName][i];
  32235. this.animations[animName].push(this.textures[frameName]);
  32236. }
  32237. }
  32238. };
  32239. /** The parse has completed. */
  32240. Spritesheet.prototype._parseComplete = function () {
  32241. var callback = this._callback;
  32242. this._callback = null;
  32243. this._batchIndex = 0;
  32244. callback.call(this, this.textures);
  32245. };
  32246. /** Begin the next batch of textures. */
  32247. Spritesheet.prototype._nextBatch = function () {
  32248. var _this = this;
  32249. this._processFrames(this._batchIndex * Spritesheet.BATCH_SIZE);
  32250. this._batchIndex++;
  32251. setTimeout(function () {
  32252. if (_this._batchIndex * Spritesheet.BATCH_SIZE < _this._frameKeys.length) {
  32253. _this._nextBatch();
  32254. }
  32255. else {
  32256. _this._processAnimations();
  32257. _this._parseComplete();
  32258. }
  32259. }, 0);
  32260. };
  32261. /**
  32262. * Destroy Spritesheet and don't use after this.
  32263. * @param {boolean} [destroyBase=false] - Whether to destroy the base texture as well
  32264. */
  32265. Spritesheet.prototype.destroy = function (destroyBase) {
  32266. var _a;
  32267. if (destroyBase === void 0) { destroyBase = false; }
  32268. for (var i in this.textures) {
  32269. this.textures[i].destroy();
  32270. }
  32271. this._frames = null;
  32272. this._frameKeys = null;
  32273. this.data = null;
  32274. this.textures = null;
  32275. if (destroyBase) {
  32276. (_a = this._texture) === null || _a === void 0 ? void 0 : _a.destroy();
  32277. this.baseTexture.destroy();
  32278. }
  32279. this._texture = null;
  32280. this.baseTexture = null;
  32281. this.linkedSheets = [];
  32282. };
  32283. /** The maximum number of Textures to build per process. */
  32284. Spritesheet.BATCH_SIZE = 1000;
  32285. return Spritesheet;
  32286. }());
  32287. /**
  32288. * Reference to Spritesheet object created.
  32289. * @member {PIXI.Spritesheet} spritesheet
  32290. * @memberof PIXI.LoaderResource
  32291. * @instance
  32292. */
  32293. /**
  32294. * Dictionary of textures from Spritesheet.
  32295. * @member {Object<string, PIXI.Texture>} textures
  32296. * @memberof PIXI.LoaderResource
  32297. * @instance
  32298. */
  32299. /**
  32300. * {@link PIXI.Loader} middleware for loading texture atlases that have been created with
  32301. * TexturePacker or similar JSON-based spritesheet.
  32302. *
  32303. * This middleware automatically generates Texture resources.
  32304. *
  32305. * If you're using Webpack or other bundlers and plan on bundling the atlas' JSON,
  32306. * use the {@link PIXI.Spritesheet} class to directly parse the JSON.
  32307. *
  32308. * The Loader's image Resource name is automatically appended with `"_image"`.
  32309. * If a Resource with this name is already loaded, the Loader will skip parsing the
  32310. * Spritesheet. The code below will generate an internal Loader Resource called `"myatlas_image"`.
  32311. * @example
  32312. * loader.add('myatlas', 'path/to/myatlas.json');
  32313. * loader.load(() => {
  32314. * loader.resources.myatlas; // atlas JSON resource
  32315. * loader.resources.myatlas_image; // atlas Image resource
  32316. * });
  32317. * @memberof PIXI
  32318. */
  32319. var SpritesheetLoader = /** @class */ (function () {
  32320. function SpritesheetLoader() {
  32321. }
  32322. /**
  32323. * Called after a resource is loaded.
  32324. * @see PIXI.Loader.loaderMiddleware
  32325. * @param resource
  32326. * @param next
  32327. */
  32328. SpritesheetLoader.use = function (resource, next) {
  32329. var _a, _b;
  32330. // because this is middleware, it execute in loader context. `this` = loader
  32331. var loader = this;
  32332. var imageResourceName = resource.name + "_image";
  32333. // skip if no data, its not json, it isn't spritesheet data, or the image resource already exists
  32334. if (!resource.data
  32335. || resource.type !== LoaderResource.TYPE.JSON
  32336. || !resource.data.frames
  32337. || loader.resources[imageResourceName]) {
  32338. next();
  32339. return;
  32340. }
  32341. // Check and add the multi atlas
  32342. // Heavily influenced and based on https://github.com/rocket-ua/pixi-tps-loader/blob/master/src/ResourceLoader.js
  32343. // eslint-disable-next-line camelcase
  32344. var multiPacks = (_b = (_a = resource.data) === null || _a === void 0 ? void 0 : _a.meta) === null || _b === void 0 ? void 0 : _b.related_multi_packs;
  32345. if (Array.isArray(multiPacks)) {
  32346. var _loop_1 = function (item) {
  32347. if (typeof item !== 'string') {
  32348. return "continue";
  32349. }
  32350. var itemName = item.replace('.json', '');
  32351. var itemUrl = url.resolve(resource.url.replace(loader.baseUrl, ''), item);
  32352. // Check if the file wasn't already added as multipacks are redundant
  32353. if (loader.resources[itemName]
  32354. || Object.values(loader.resources).some(function (r) { return url.format(url.parse(r.url)) === itemUrl; })) {
  32355. return "continue";
  32356. }
  32357. var options = {
  32358. crossOrigin: resource.crossOrigin,
  32359. loadType: LoaderResource.LOAD_TYPE.XHR,
  32360. xhrType: LoaderResource.XHR_RESPONSE_TYPE.JSON,
  32361. parentResource: resource,
  32362. metadata: resource.metadata
  32363. };
  32364. loader.add(itemName, itemUrl, options);
  32365. };
  32366. for (var _i = 0, multiPacks_1 = multiPacks; _i < multiPacks_1.length; _i++) {
  32367. var item = multiPacks_1[_i];
  32368. _loop_1(item);
  32369. }
  32370. }
  32371. var loadOptions = {
  32372. crossOrigin: resource.crossOrigin,
  32373. metadata: resource.metadata.imageMetadata,
  32374. parentResource: resource,
  32375. };
  32376. var resourcePath = SpritesheetLoader.getResourcePath(resource, loader.baseUrl);
  32377. // load the image for this sheet
  32378. loader.add(imageResourceName, resourcePath, loadOptions, function onImageLoad(res) {
  32379. if (res.error) {
  32380. next(res.error);
  32381. return;
  32382. }
  32383. var spritesheet = new Spritesheet(res.texture, resource.data, resource.url);
  32384. spritesheet.parse().then(function () {
  32385. resource.spritesheet = spritesheet;
  32386. resource.textures = spritesheet.textures;
  32387. next();
  32388. });
  32389. });
  32390. };
  32391. /**
  32392. * Get the spritesheets root path
  32393. * @param resource - Resource to check path
  32394. * @param baseUrl - Base root url
  32395. */
  32396. SpritesheetLoader.getResourcePath = function (resource, baseUrl) {
  32397. // Prepend url path unless the resource image is a data url
  32398. if (resource.isDataUrl) {
  32399. return resource.data.meta.image;
  32400. }
  32401. return url.resolve(resource.url.replace(baseUrl, ''), resource.data.meta.image);
  32402. };
  32403. /** @ignore */
  32404. SpritesheetLoader.extension = ExtensionType.Loader;
  32405. return SpritesheetLoader;
  32406. }());
  32407. /*!
  32408. * @pixi/sprite-tiling - v6.5.10
  32409. * Compiled Thu, 06 Jul 2023 15:25:11 UTC
  32410. *
  32411. * @pixi/sprite-tiling is licensed under the MIT License.
  32412. * http://www.opensource.org/licenses/mit-license
  32413. */
  32414. /*! *****************************************************************************
  32415. Copyright (c) Microsoft Corporation.
  32416. Permission to use, copy, modify, and/or distribute this software for any
  32417. purpose with or without fee is hereby granted.
  32418. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  32419. REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
  32420. AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  32421. INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
  32422. LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
  32423. OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
  32424. PERFORMANCE OF THIS SOFTWARE.
  32425. ***************************************************************************** */
  32426. /* global Reflect, Promise */
  32427. var extendStatics$a = function(d, b) {
  32428. extendStatics$a = Object.setPrototypeOf ||
  32429. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  32430. function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } };
  32431. return extendStatics$a(d, b);
  32432. };
  32433. function __extends$a(d, b) {
  32434. extendStatics$a(d, b);
  32435. function __() { this.constructor = d; }
  32436. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  32437. }
  32438. var tempPoint$1 = new Point();
  32439. /**
  32440. * A tiling sprite is a fast way of rendering a tiling image.
  32441. * @memberof PIXI
  32442. */
  32443. var TilingSprite = /** @class */ (function (_super) {
  32444. __extends$a(TilingSprite, _super);
  32445. /**
  32446. * @param texture - The texture of the tiling sprite.
  32447. * @param width - The width of the tiling sprite.
  32448. * @param height - The height of the tiling sprite.
  32449. */
  32450. function TilingSprite(texture, width, height) {
  32451. if (width === void 0) { width = 100; }
  32452. if (height === void 0) { height = 100; }
  32453. var _this = _super.call(this, texture) || this;
  32454. _this.tileTransform = new Transform();
  32455. // The width of the tiling sprite
  32456. _this._width = width;
  32457. // The height of the tiling sprite
  32458. _this._height = height;
  32459. _this.uvMatrix = _this.texture.uvMatrix || new TextureMatrix(texture);
  32460. /**
  32461. * Plugin that is responsible for rendering this element.
  32462. * Allows to customize the rendering process without overriding '_render' method.
  32463. * @default 'tilingSprite'
  32464. */
  32465. _this.pluginName = 'tilingSprite';
  32466. _this.uvRespectAnchor = false;
  32467. return _this;
  32468. }
  32469. Object.defineProperty(TilingSprite.prototype, "clampMargin", {
  32470. /**
  32471. * Changes frame clamping in corresponding textureTransform, shortcut
  32472. * Change to -0.5 to add a pixel to the edge, recommended for transparent trimmed textures in atlas
  32473. * @default 0.5
  32474. * @member {number}
  32475. */
  32476. get: function () {
  32477. return this.uvMatrix.clampMargin;
  32478. },
  32479. set: function (value) {
  32480. this.uvMatrix.clampMargin = value;
  32481. this.uvMatrix.update(true);
  32482. },
  32483. enumerable: false,
  32484. configurable: true
  32485. });
  32486. Object.defineProperty(TilingSprite.prototype, "tileScale", {
  32487. /** The scaling of the image that is being tiled. */
  32488. get: function () {
  32489. return this.tileTransform.scale;
  32490. },
  32491. set: function (value) {
  32492. this.tileTransform.scale.copyFrom(value);
  32493. },
  32494. enumerable: false,
  32495. configurable: true
  32496. });
  32497. Object.defineProperty(TilingSprite.prototype, "tilePosition", {
  32498. /** The offset of the image that is being tiled. */
  32499. get: function () {
  32500. return this.tileTransform.position;
  32501. },
  32502. set: function (value) {
  32503. this.tileTransform.position.copyFrom(value);
  32504. },
  32505. enumerable: false,
  32506. configurable: true
  32507. });
  32508. /**
  32509. * @protected
  32510. */
  32511. TilingSprite.prototype._onTextureUpdate = function () {
  32512. if (this.uvMatrix) {
  32513. this.uvMatrix.texture = this._texture;
  32514. }
  32515. this._cachedTint = 0xFFFFFF;
  32516. };
  32517. /**
  32518. * Renders the object using the WebGL renderer
  32519. * @param renderer - The renderer
  32520. */
  32521. TilingSprite.prototype._render = function (renderer) {
  32522. // tweak our texture temporarily..
  32523. var texture = this._texture;
  32524. if (!texture || !texture.valid) {
  32525. return;
  32526. }
  32527. this.tileTransform.updateLocalTransform();
  32528. this.uvMatrix.update();
  32529. renderer.batch.setObjectRenderer(renderer.plugins[this.pluginName]);
  32530. renderer.plugins[this.pluginName].render(this);
  32531. };
  32532. /** Updates the bounds of the tiling sprite. */
  32533. TilingSprite.prototype._calculateBounds = function () {
  32534. var minX = this._width * -this._anchor._x;
  32535. var minY = this._height * -this._anchor._y;
  32536. var maxX = this._width * (1 - this._anchor._x);
  32537. var maxY = this._height * (1 - this._anchor._y);
  32538. this._bounds.addFrame(this.transform, minX, minY, maxX, maxY);
  32539. };
  32540. /**
  32541. * Gets the local bounds of the sprite object.
  32542. * @param rect - Optional output rectangle.
  32543. * @returns The bounds.
  32544. */
  32545. TilingSprite.prototype.getLocalBounds = function (rect) {
  32546. // we can do a fast local bounds if the sprite has no children!
  32547. if (this.children.length === 0) {
  32548. this._bounds.minX = this._width * -this._anchor._x;
  32549. this._bounds.minY = this._height * -this._anchor._y;
  32550. this._bounds.maxX = this._width * (1 - this._anchor._x);
  32551. this._bounds.maxY = this._height * (1 - this._anchor._y);
  32552. if (!rect) {
  32553. if (!this._localBoundsRect) {
  32554. this._localBoundsRect = new Rectangle();
  32555. }
  32556. rect = this._localBoundsRect;
  32557. }
  32558. return this._bounds.getRectangle(rect);
  32559. }
  32560. return _super.prototype.getLocalBounds.call(this, rect);
  32561. };
  32562. /**
  32563. * Checks if a point is inside this tiling sprite.
  32564. * @param point - The point to check.
  32565. * @returns Whether or not the sprite contains the point.
  32566. */
  32567. TilingSprite.prototype.containsPoint = function (point) {
  32568. this.worldTransform.applyInverse(point, tempPoint$1);
  32569. var width = this._width;
  32570. var height = this._height;
  32571. var x1 = -width * this.anchor._x;
  32572. if (tempPoint$1.x >= x1 && tempPoint$1.x < x1 + width) {
  32573. var y1 = -height * this.anchor._y;
  32574. if (tempPoint$1.y >= y1 && tempPoint$1.y < y1 + height) {
  32575. return true;
  32576. }
  32577. }
  32578. return false;
  32579. };
  32580. /**
  32581. * Destroys this sprite and optionally its texture and children
  32582. * @param {object|boolean} [options] - Options parameter. A boolean will act as if all options
  32583. * have been set to that value
  32584. * @param {boolean} [options.children=false] - if set to true, all the children will have their destroy
  32585. * method called as well. 'options' will be passed on to those calls.
  32586. * @param {boolean} [options.texture=false] - Should it destroy the current texture of the sprite as well
  32587. * @param {boolean} [options.baseTexture=false] - Should it destroy the base texture of the sprite as well
  32588. */
  32589. TilingSprite.prototype.destroy = function (options) {
  32590. _super.prototype.destroy.call(this, options);
  32591. this.tileTransform = null;
  32592. this.uvMatrix = null;
  32593. };
  32594. /**
  32595. * Helper function that creates a new tiling sprite based on the source you provide.
  32596. * The source can be - frame id, image url, video url, canvas element, video element, base texture
  32597. * @static
  32598. * @param {string|PIXI.Texture|HTMLCanvasElement|HTMLVideoElement} source - Source to create texture from
  32599. * @param {object} options - See {@link PIXI.BaseTexture}'s constructor for options.
  32600. * @param {number} options.width - required width of the tiling sprite
  32601. * @param {number} options.height - required height of the tiling sprite
  32602. * @returns {PIXI.TilingSprite} The newly created texture
  32603. */
  32604. TilingSprite.from = function (source, options) {
  32605. var texture = (source instanceof Texture)
  32606. ? source
  32607. : Texture.from(source, options);
  32608. return new TilingSprite(texture, options.width, options.height);
  32609. };
  32610. Object.defineProperty(TilingSprite.prototype, "width", {
  32611. /** The width of the sprite, setting this will actually modify the scale to achieve the value set. */
  32612. get: function () {
  32613. return this._width;
  32614. },
  32615. set: function (value) {
  32616. this._width = value;
  32617. },
  32618. enumerable: false,
  32619. configurable: true
  32620. });
  32621. Object.defineProperty(TilingSprite.prototype, "height", {
  32622. /** The height of the TilingSprite, setting this will actually modify the scale to achieve the value set. */
  32623. get: function () {
  32624. return this._height;
  32625. },
  32626. set: function (value) {
  32627. this._height = value;
  32628. },
  32629. enumerable: false,
  32630. configurable: true
  32631. });
  32632. return TilingSprite;
  32633. }(Sprite));
  32634. var fragmentSimpleSrc = "#version 100\n#define SHADER_NAME Tiling-Sprite-Simple-100\n\nprecision lowp float;\n\nvarying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform vec4 uColor;\n\nvoid main(void)\n{\n vec4 texSample = texture2D(uSampler, vTextureCoord);\n gl_FragColor = texSample * uColor;\n}\n";
  32635. var gl1VertexSrc = "#version 100\n#define SHADER_NAME Tiling-Sprite-100\n\nprecision lowp float;\n\nattribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 translationMatrix;\nuniform mat3 uTransform;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = (uTransform * vec3(aTextureCoord, 1.0)).xy;\n}\n";
  32636. var gl1FragmentSrc = "#version 100\n#ifdef GL_EXT_shader_texture_lod\n #extension GL_EXT_shader_texture_lod : enable\n#endif\n#define SHADER_NAME Tiling-Sprite-100\n\nprecision lowp float;\n\nvarying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform vec4 uColor;\nuniform mat3 uMapCoord;\nuniform vec4 uClampFrame;\nuniform vec2 uClampOffset;\n\nvoid main(void)\n{\n vec2 coord = vTextureCoord + ceil(uClampOffset - vTextureCoord);\n coord = (uMapCoord * vec3(coord, 1.0)).xy;\n vec2 unclamped = coord;\n coord = clamp(coord, uClampFrame.xy, uClampFrame.zw);\n\n #ifdef GL_EXT_shader_texture_lod\n vec4 texSample = unclamped == coord\n ? texture2D(uSampler, coord) \n : texture2DLodEXT(uSampler, coord, 0);\n #else\n vec4 texSample = texture2D(uSampler, coord);\n #endif\n\n gl_FragColor = texSample * uColor;\n}\n";
  32637. var gl2VertexSrc = "#version 300 es\n#define SHADER_NAME Tiling-Sprite-300\n\nprecision lowp float;\n\nin vec2 aVertexPosition;\nin vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 translationMatrix;\nuniform mat3 uTransform;\n\nout vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = (uTransform * vec3(aTextureCoord, 1.0)).xy;\n}\n";
  32638. var gl2FragmentSrc = "#version 300 es\n#define SHADER_NAME Tiling-Sprite-100\n\nprecision lowp float;\n\nin vec2 vTextureCoord;\n\nout vec4 fragmentColor;\n\nuniform sampler2D uSampler;\nuniform vec4 uColor;\nuniform mat3 uMapCoord;\nuniform vec4 uClampFrame;\nuniform vec2 uClampOffset;\n\nvoid main(void)\n{\n vec2 coord = vTextureCoord + ceil(uClampOffset - vTextureCoord);\n coord = (uMapCoord * vec3(coord, 1.0)).xy;\n vec2 unclamped = coord;\n coord = clamp(coord, uClampFrame.xy, uClampFrame.zw);\n\n vec4 texSample = texture(uSampler, coord, unclamped == coord ? 0.0f : -32.0f);// lod-bias very negative to force lod 0\n\n fragmentColor = texSample * uColor;\n}\n";
  32639. var tempMat = new Matrix();
  32640. /**
  32641. * WebGL renderer plugin for tiling sprites
  32642. * @class
  32643. * @memberof PIXI
  32644. * @extends PIXI.ObjectRenderer
  32645. */
  32646. var TilingSpriteRenderer = /** @class */ (function (_super) {
  32647. __extends$a(TilingSpriteRenderer, _super);
  32648. /**
  32649. * constructor for renderer
  32650. * @param {PIXI.Renderer} renderer - The renderer this tiling awesomeness works for.
  32651. */
  32652. function TilingSpriteRenderer(renderer) {
  32653. var _this = _super.call(this, renderer) || this;
  32654. // WebGL version is not available during initialization!
  32655. renderer.runners.contextChange.add(_this);
  32656. _this.quad = new QuadUv();
  32657. /**
  32658. * The WebGL state in which this renderer will work.
  32659. * @member {PIXI.State}
  32660. * @readonly
  32661. */
  32662. _this.state = State.for2d();
  32663. return _this;
  32664. }
  32665. /** Creates shaders when context is initialized. */
  32666. TilingSpriteRenderer.prototype.contextChange = function () {
  32667. var renderer = this.renderer;
  32668. var uniforms = { globals: renderer.globalUniforms };
  32669. this.simpleShader = Shader.from(gl1VertexSrc, fragmentSimpleSrc, uniforms);
  32670. this.shader = renderer.context.webGLVersion > 1
  32671. ? Shader.from(gl2VertexSrc, gl2FragmentSrc, uniforms)
  32672. : Shader.from(gl1VertexSrc, gl1FragmentSrc, uniforms);
  32673. };
  32674. /**
  32675. * @param {PIXI.TilingSprite} ts - tilingSprite to be rendered
  32676. */
  32677. TilingSpriteRenderer.prototype.render = function (ts) {
  32678. var renderer = this.renderer;
  32679. var quad = this.quad;
  32680. var vertices = quad.vertices;
  32681. vertices[0] = vertices[6] = (ts._width) * -ts.anchor.x;
  32682. vertices[1] = vertices[3] = ts._height * -ts.anchor.y;
  32683. vertices[2] = vertices[4] = (ts._width) * (1.0 - ts.anchor.x);
  32684. vertices[5] = vertices[7] = ts._height * (1.0 - ts.anchor.y);
  32685. var anchorX = ts.uvRespectAnchor ? ts.anchor.x : 0;
  32686. var anchorY = ts.uvRespectAnchor ? ts.anchor.y : 0;
  32687. vertices = quad.uvs;
  32688. vertices[0] = vertices[6] = -anchorX;
  32689. vertices[1] = vertices[3] = -anchorY;
  32690. vertices[2] = vertices[4] = 1.0 - anchorX;
  32691. vertices[5] = vertices[7] = 1.0 - anchorY;
  32692. quad.invalidate();
  32693. var tex = ts._texture;
  32694. var baseTex = tex.baseTexture;
  32695. var premultiplied = baseTex.alphaMode > 0;
  32696. var lt = ts.tileTransform.localTransform;
  32697. var uv = ts.uvMatrix;
  32698. var isSimple = baseTex.isPowerOfTwo
  32699. && tex.frame.width === baseTex.width && tex.frame.height === baseTex.height;
  32700. // auto, force repeat wrapMode for big tiling textures
  32701. if (isSimple) {
  32702. if (!baseTex._glTextures[renderer.CONTEXT_UID]) {
  32703. if (baseTex.wrapMode === WRAP_MODES.CLAMP) {
  32704. baseTex.wrapMode = WRAP_MODES.REPEAT;
  32705. }
  32706. }
  32707. else {
  32708. isSimple = baseTex.wrapMode !== WRAP_MODES.CLAMP;
  32709. }
  32710. }
  32711. var shader = isSimple ? this.simpleShader : this.shader;
  32712. var w = tex.width;
  32713. var h = tex.height;
  32714. var W = ts._width;
  32715. var H = ts._height;
  32716. tempMat.set(lt.a * w / W, lt.b * w / H, lt.c * h / W, lt.d * h / H, lt.tx / W, lt.ty / H);
  32717. // that part is the same as above:
  32718. // tempMat.identity();
  32719. // tempMat.scale(tex.width, tex.height);
  32720. // tempMat.prepend(lt);
  32721. // tempMat.scale(1.0 / ts._width, 1.0 / ts._height);
  32722. tempMat.invert();
  32723. if (isSimple) {
  32724. tempMat.prepend(uv.mapCoord);
  32725. }
  32726. else {
  32727. shader.uniforms.uMapCoord = uv.mapCoord.toArray(true);
  32728. shader.uniforms.uClampFrame = uv.uClampFrame;
  32729. shader.uniforms.uClampOffset = uv.uClampOffset;
  32730. }
  32731. shader.uniforms.uTransform = tempMat.toArray(true);
  32732. shader.uniforms.uColor = premultiplyTintToRgba(ts.tint, ts.worldAlpha, shader.uniforms.uColor, premultiplied);
  32733. shader.uniforms.translationMatrix = ts.transform.worldTransform.toArray(true);
  32734. shader.uniforms.uSampler = tex;
  32735. renderer.shader.bind(shader);
  32736. renderer.geometry.bind(quad);
  32737. this.state.blendMode = correctBlendMode(ts.blendMode, premultiplied);
  32738. renderer.state.set(this.state);
  32739. renderer.geometry.draw(this.renderer.gl.TRIANGLES, 6, 0);
  32740. };
  32741. /** @ignore */
  32742. TilingSpriteRenderer.extension = {
  32743. name: 'tilingSprite',
  32744. type: ExtensionType.RendererPlugin,
  32745. };
  32746. return TilingSpriteRenderer;
  32747. }(ObjectRenderer));
  32748. /*!
  32749. * @pixi/mesh - v6.5.10
  32750. * Compiled Thu, 06 Jul 2023 15:25:11 UTC
  32751. *
  32752. * @pixi/mesh is licensed under the MIT License.
  32753. * http://www.opensource.org/licenses/mit-license
  32754. */
  32755. /*! *****************************************************************************
  32756. Copyright (c) Microsoft Corporation.
  32757. Permission to use, copy, modify, and/or distribute this software for any
  32758. purpose with or without fee is hereby granted.
  32759. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  32760. REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
  32761. AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  32762. INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
  32763. LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
  32764. OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
  32765. PERFORMANCE OF THIS SOFTWARE.
  32766. ***************************************************************************** */
  32767. /* global Reflect, Promise */
  32768. var extendStatics$9 = function(d, b) {
  32769. extendStatics$9 = Object.setPrototypeOf ||
  32770. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  32771. function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } };
  32772. return extendStatics$9(d, b);
  32773. };
  32774. function __extends$9(d, b) {
  32775. extendStatics$9(d, b);
  32776. function __() { this.constructor = d; }
  32777. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  32778. }
  32779. /**
  32780. * Class controls cache for UV mapping from Texture normal space to BaseTexture normal space.
  32781. * @memberof PIXI
  32782. */
  32783. var MeshBatchUvs = /** @class */ (function () {
  32784. /**
  32785. * @param uvBuffer - Buffer with normalized uv's
  32786. * @param uvMatrix - Material UV matrix
  32787. */
  32788. function MeshBatchUvs(uvBuffer, uvMatrix) {
  32789. this.uvBuffer = uvBuffer;
  32790. this.uvMatrix = uvMatrix;
  32791. this.data = null;
  32792. this._bufferUpdateId = -1;
  32793. this._textureUpdateId = -1;
  32794. this._updateID = 0;
  32795. }
  32796. /**
  32797. * Updates
  32798. * @param forceUpdate - force the update
  32799. */
  32800. MeshBatchUvs.prototype.update = function (forceUpdate) {
  32801. if (!forceUpdate
  32802. && this._bufferUpdateId === this.uvBuffer._updateID
  32803. && this._textureUpdateId === this.uvMatrix._updateID) {
  32804. return;
  32805. }
  32806. this._bufferUpdateId = this.uvBuffer._updateID;
  32807. this._textureUpdateId = this.uvMatrix._updateID;
  32808. var data = this.uvBuffer.data;
  32809. if (!this.data || this.data.length !== data.length) {
  32810. this.data = new Float32Array(data.length);
  32811. }
  32812. this.uvMatrix.multiplyUvs(data, this.data);
  32813. this._updateID++;
  32814. };
  32815. return MeshBatchUvs;
  32816. }());
  32817. var tempPoint = new Point();
  32818. var tempPolygon = new Polygon();
  32819. /**
  32820. * Base mesh class.
  32821. *
  32822. * This class empowers you to have maximum flexibility to render any kind of WebGL visuals you can think of.
  32823. * This class assumes a certain level of WebGL knowledge.
  32824. * If you know a bit this should abstract enough away to make your life easier!
  32825. *
  32826. * Pretty much ALL WebGL can be broken down into the following:
  32827. * - Geometry - The structure and data for the mesh. This can include anything from positions, uvs, normals, colors etc..
  32828. * - Shader - This is the shader that PixiJS will render the geometry with (attributes in the shader must match the geometry)
  32829. * - State - This is the state of WebGL required to render the mesh.
  32830. *
  32831. * Through a combination of the above elements you can render anything you want, 2D or 3D!
  32832. * @memberof PIXI
  32833. */
  32834. var Mesh = /** @class */ (function (_super) {
  32835. __extends$9(Mesh, _super);
  32836. /**
  32837. * @param geometry - The geometry the mesh will use.
  32838. * @param {PIXI.MeshMaterial} shader - The shader the mesh will use.
  32839. * @param state - The state that the WebGL context is required to be in to render the mesh
  32840. * if no state is provided, uses {@link PIXI.State.for2d} to create a 2D state for PixiJS.
  32841. * @param drawMode - The drawMode, can be any of the {@link PIXI.DRAW_MODES} constants.
  32842. */
  32843. function Mesh(geometry, shader, state, drawMode) {
  32844. if (drawMode === void 0) { drawMode = DRAW_MODES.TRIANGLES; }
  32845. var _this = _super.call(this) || this;
  32846. _this.geometry = geometry;
  32847. _this.shader = shader;
  32848. _this.state = state || State.for2d();
  32849. _this.drawMode = drawMode;
  32850. _this.start = 0;
  32851. _this.size = 0;
  32852. _this.uvs = null;
  32853. _this.indices = null;
  32854. _this.vertexData = new Float32Array(1);
  32855. _this.vertexDirty = -1;
  32856. _this._transformID = -1;
  32857. _this._roundPixels = settings.ROUND_PIXELS;
  32858. _this.batchUvs = null;
  32859. return _this;
  32860. }
  32861. Object.defineProperty(Mesh.prototype, "geometry", {
  32862. /**
  32863. * Includes vertex positions, face indices, normals, colors, UVs, and
  32864. * custom attributes within buffers, reducing the cost of passing all
  32865. * this data to the GPU. Can be shared between multiple Mesh objects.
  32866. */
  32867. get: function () {
  32868. return this._geometry;
  32869. },
  32870. set: function (value) {
  32871. if (this._geometry === value) {
  32872. return;
  32873. }
  32874. if (this._geometry) {
  32875. this._geometry.refCount--;
  32876. if (this._geometry.refCount === 0) {
  32877. this._geometry.dispose();
  32878. }
  32879. }
  32880. this._geometry = value;
  32881. if (this._geometry) {
  32882. this._geometry.refCount++;
  32883. }
  32884. this.vertexDirty = -1;
  32885. },
  32886. enumerable: false,
  32887. configurable: true
  32888. });
  32889. Object.defineProperty(Mesh.prototype, "uvBuffer", {
  32890. /**
  32891. * To change mesh uv's, change its uvBuffer data and increment its _updateID.
  32892. * @readonly
  32893. */
  32894. get: function () {
  32895. return this.geometry.buffers[1];
  32896. },
  32897. enumerable: false,
  32898. configurable: true
  32899. });
  32900. Object.defineProperty(Mesh.prototype, "verticesBuffer", {
  32901. /**
  32902. * To change mesh vertices, change its uvBuffer data and increment its _updateID.
  32903. * Incrementing _updateID is optional because most of Mesh objects do it anyway.
  32904. * @readonly
  32905. */
  32906. get: function () {
  32907. return this.geometry.buffers[0];
  32908. },
  32909. enumerable: false,
  32910. configurable: true
  32911. });
  32912. Object.defineProperty(Mesh.prototype, "material", {
  32913. get: function () {
  32914. return this.shader;
  32915. },
  32916. /** Alias for {@link PIXI.Mesh#shader}. */
  32917. set: function (value) {
  32918. this.shader = value;
  32919. },
  32920. enumerable: false,
  32921. configurable: true
  32922. });
  32923. Object.defineProperty(Mesh.prototype, "blendMode", {
  32924. get: function () {
  32925. return this.state.blendMode;
  32926. },
  32927. /**
  32928. * The blend mode to be applied to the Mesh. Apply a value of
  32929. * `PIXI.BLEND_MODES.NORMAL` to reset the blend mode.
  32930. * @default PIXI.BLEND_MODES.NORMAL;
  32931. */
  32932. set: function (value) {
  32933. this.state.blendMode = value;
  32934. },
  32935. enumerable: false,
  32936. configurable: true
  32937. });
  32938. Object.defineProperty(Mesh.prototype, "roundPixels", {
  32939. get: function () {
  32940. return this._roundPixels;
  32941. },
  32942. /**
  32943. * If true PixiJS will Math.floor() x/y values when rendering, stopping pixel interpolation.
  32944. * Advantages can include sharper image quality (like text) and faster rendering on canvas.
  32945. * The main disadvantage is movement of objects may appear less smooth.
  32946. * To set the global default, change {@link PIXI.settings.ROUND_PIXELS}
  32947. * @default false
  32948. */
  32949. set: function (value) {
  32950. if (this._roundPixels !== value) {
  32951. this._transformID = -1;
  32952. }
  32953. this._roundPixels = value;
  32954. },
  32955. enumerable: false,
  32956. configurable: true
  32957. });
  32958. Object.defineProperty(Mesh.prototype, "tint", {
  32959. /**
  32960. * The multiply tint applied to the Mesh. This is a hex value. A value of
  32961. * `0xFFFFFF` will remove any tint effect.
  32962. *
  32963. * Null for non-MeshMaterial shaders
  32964. * @default 0xFFFFFF
  32965. */
  32966. get: function () {
  32967. return 'tint' in this.shader ? this.shader.tint : null;
  32968. },
  32969. set: function (value) {
  32970. this.shader.tint = value;
  32971. },
  32972. enumerable: false,
  32973. configurable: true
  32974. });
  32975. Object.defineProperty(Mesh.prototype, "texture", {
  32976. /** The texture that the Mesh uses. Null for non-MeshMaterial shaders */
  32977. get: function () {
  32978. return 'texture' in this.shader ? this.shader.texture : null;
  32979. },
  32980. set: function (value) {
  32981. this.shader.texture = value;
  32982. },
  32983. enumerable: false,
  32984. configurable: true
  32985. });
  32986. /**
  32987. * Standard renderer draw.
  32988. * @param renderer - Instance to renderer.
  32989. */
  32990. Mesh.prototype._render = function (renderer) {
  32991. // set properties for batching..
  32992. // TODO could use a different way to grab verts?
  32993. var vertices = this.geometry.buffers[0].data;
  32994. var shader = this.shader;
  32995. // TODO benchmark check for attribute size..
  32996. if (shader.batchable
  32997. && this.drawMode === DRAW_MODES.TRIANGLES
  32998. && vertices.length < Mesh.BATCHABLE_SIZE * 2) {
  32999. this._renderToBatch(renderer);
  33000. }
  33001. else {
  33002. this._renderDefault(renderer);
  33003. }
  33004. };
  33005. /**
  33006. * Standard non-batching way of rendering.
  33007. * @param renderer - Instance to renderer.
  33008. */
  33009. Mesh.prototype._renderDefault = function (renderer) {
  33010. var shader = this.shader;
  33011. shader.alpha = this.worldAlpha;
  33012. if (shader.update) {
  33013. shader.update();
  33014. }
  33015. renderer.batch.flush();
  33016. // bind and sync uniforms..
  33017. shader.uniforms.translationMatrix = this.transform.worldTransform.toArray(true);
  33018. renderer.shader.bind(shader);
  33019. // set state..
  33020. renderer.state.set(this.state);
  33021. // bind the geometry...
  33022. renderer.geometry.bind(this.geometry, shader);
  33023. // then render it
  33024. renderer.geometry.draw(this.drawMode, this.size, this.start, this.geometry.instanceCount);
  33025. };
  33026. /**
  33027. * Rendering by using the Batch system.
  33028. * @param renderer - Instance to renderer.
  33029. */
  33030. Mesh.prototype._renderToBatch = function (renderer) {
  33031. var geometry = this.geometry;
  33032. var shader = this.shader;
  33033. if (shader.uvMatrix) {
  33034. shader.uvMatrix.update();
  33035. this.calculateUvs();
  33036. }
  33037. // set properties for batching..
  33038. this.calculateVertices();
  33039. this.indices = geometry.indexBuffer.data;
  33040. this._tintRGB = shader._tintRGB;
  33041. this._texture = shader.texture;
  33042. var pluginName = this.material.pluginName;
  33043. renderer.batch.setObjectRenderer(renderer.plugins[pluginName]);
  33044. renderer.plugins[pluginName].render(this);
  33045. };
  33046. /** Updates vertexData field based on transform and vertices. */
  33047. Mesh.prototype.calculateVertices = function () {
  33048. var geometry = this.geometry;
  33049. var verticesBuffer = geometry.buffers[0];
  33050. var vertices = verticesBuffer.data;
  33051. var vertexDirtyId = verticesBuffer._updateID;
  33052. if (vertexDirtyId === this.vertexDirty && this._transformID === this.transform._worldID) {
  33053. return;
  33054. }
  33055. this._transformID = this.transform._worldID;
  33056. if (this.vertexData.length !== vertices.length) {
  33057. this.vertexData = new Float32Array(vertices.length);
  33058. }
  33059. var wt = this.transform.worldTransform;
  33060. var a = wt.a;
  33061. var b = wt.b;
  33062. var c = wt.c;
  33063. var d = wt.d;
  33064. var tx = wt.tx;
  33065. var ty = wt.ty;
  33066. var vertexData = this.vertexData;
  33067. for (var i = 0; i < vertexData.length / 2; i++) {
  33068. var x = vertices[(i * 2)];
  33069. var y = vertices[(i * 2) + 1];
  33070. vertexData[(i * 2)] = (a * x) + (c * y) + tx;
  33071. vertexData[(i * 2) + 1] = (b * x) + (d * y) + ty;
  33072. }
  33073. if (this._roundPixels) {
  33074. var resolution = settings.RESOLUTION;
  33075. for (var i = 0; i < vertexData.length; ++i) {
  33076. vertexData[i] = Math.round((vertexData[i] * resolution | 0) / resolution);
  33077. }
  33078. }
  33079. this.vertexDirty = vertexDirtyId;
  33080. };
  33081. /** Updates uv field based on from geometry uv's or batchUvs. */
  33082. Mesh.prototype.calculateUvs = function () {
  33083. var geomUvs = this.geometry.buffers[1];
  33084. var shader = this.shader;
  33085. if (!shader.uvMatrix.isSimple) {
  33086. if (!this.batchUvs) {
  33087. this.batchUvs = new MeshBatchUvs(geomUvs, shader.uvMatrix);
  33088. }
  33089. this.batchUvs.update();
  33090. this.uvs = this.batchUvs.data;
  33091. }
  33092. else {
  33093. this.uvs = geomUvs.data;
  33094. }
  33095. };
  33096. /**
  33097. * Updates the bounds of the mesh as a rectangle. The bounds calculation takes the worldTransform into account.
  33098. * there must be a aVertexPosition attribute present in the geometry for bounds to be calculated correctly.
  33099. */
  33100. Mesh.prototype._calculateBounds = function () {
  33101. this.calculateVertices();
  33102. this._bounds.addVertexData(this.vertexData, 0, this.vertexData.length);
  33103. };
  33104. /**
  33105. * Tests if a point is inside this mesh. Works only for PIXI.DRAW_MODES.TRIANGLES.
  33106. * @param point - The point to test.
  33107. * @returns - The result of the test.
  33108. */
  33109. Mesh.prototype.containsPoint = function (point) {
  33110. if (!this.getBounds().contains(point.x, point.y)) {
  33111. return false;
  33112. }
  33113. this.worldTransform.applyInverse(point, tempPoint);
  33114. var vertices = this.geometry.getBuffer('aVertexPosition').data;
  33115. var points = tempPolygon.points;
  33116. var indices = this.geometry.getIndex().data;
  33117. var len = indices.length;
  33118. var step = this.drawMode === 4 ? 3 : 1;
  33119. for (var i = 0; i + 2 < len; i += step) {
  33120. var ind0 = indices[i] * 2;
  33121. var ind1 = indices[i + 1] * 2;
  33122. var ind2 = indices[i + 2] * 2;
  33123. points[0] = vertices[ind0];
  33124. points[1] = vertices[ind0 + 1];
  33125. points[2] = vertices[ind1];
  33126. points[3] = vertices[ind1 + 1];
  33127. points[4] = vertices[ind2];
  33128. points[5] = vertices[ind2 + 1];
  33129. if (tempPolygon.contains(tempPoint.x, tempPoint.y)) {
  33130. return true;
  33131. }
  33132. }
  33133. return false;
  33134. };
  33135. Mesh.prototype.destroy = function (options) {
  33136. _super.prototype.destroy.call(this, options);
  33137. if (this._cachedTexture) {
  33138. this._cachedTexture.destroy();
  33139. this._cachedTexture = null;
  33140. }
  33141. this.geometry = null;
  33142. this.shader = null;
  33143. this.state = null;
  33144. this.uvs = null;
  33145. this.indices = null;
  33146. this.vertexData = null;
  33147. };
  33148. /** The maximum number of vertices to consider batchable. Generally, the complexity of the geometry. */
  33149. Mesh.BATCHABLE_SIZE = 100;
  33150. return Mesh;
  33151. }(Container));
  33152. var fragment$5 = "varying vec2 vTextureCoord;\nuniform vec4 uColor;\n\nuniform sampler2D uSampler;\n\nvoid main(void)\n{\n gl_FragColor = texture2D(uSampler, vTextureCoord) * uColor;\n}\n";
  33153. var vertex$2 = "attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 translationMatrix;\nuniform mat3 uTextureMatrix;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = (uTextureMatrix * vec3(aTextureCoord, 1.0)).xy;\n}\n";
  33154. /**
  33155. * Slightly opinionated default shader for PixiJS 2D objects.
  33156. * @memberof PIXI
  33157. */
  33158. var MeshMaterial = /** @class */ (function (_super) {
  33159. __extends$9(MeshMaterial, _super);
  33160. /**
  33161. * @param uSampler - Texture that material uses to render.
  33162. * @param options - Additional options
  33163. * @param {number} [options.alpha=1] - Default alpha.
  33164. * @param {number} [options.tint=0xFFFFFF] - Default tint.
  33165. * @param {string} [options.pluginName='batch'] - Renderer plugin for batching.
  33166. * @param {PIXI.Program} [options.program=0xFFFFFF] - Custom program.
  33167. * @param {object} [options.uniforms] - Custom uniforms.
  33168. */
  33169. function MeshMaterial(uSampler, options) {
  33170. var _this = this;
  33171. var uniforms = {
  33172. uSampler: uSampler,
  33173. alpha: 1,
  33174. uTextureMatrix: Matrix.IDENTITY,
  33175. uColor: new Float32Array([1, 1, 1, 1]),
  33176. };
  33177. // Set defaults
  33178. options = Object.assign({
  33179. tint: 0xFFFFFF,
  33180. alpha: 1,
  33181. pluginName: 'batch',
  33182. }, options);
  33183. if (options.uniforms) {
  33184. Object.assign(uniforms, options.uniforms);
  33185. }
  33186. _this = _super.call(this, options.program || Program.from(vertex$2, fragment$5), uniforms) || this;
  33187. _this._colorDirty = false;
  33188. _this.uvMatrix = new TextureMatrix(uSampler);
  33189. _this.batchable = options.program === undefined;
  33190. _this.pluginName = options.pluginName;
  33191. _this.tint = options.tint;
  33192. _this.alpha = options.alpha;
  33193. return _this;
  33194. }
  33195. Object.defineProperty(MeshMaterial.prototype, "texture", {
  33196. /** Reference to the texture being rendered. */
  33197. get: function () {
  33198. return this.uniforms.uSampler;
  33199. },
  33200. set: function (value) {
  33201. if (this.uniforms.uSampler !== value) {
  33202. if (!this.uniforms.uSampler.baseTexture.alphaMode !== !value.baseTexture.alphaMode) {
  33203. this._colorDirty = true;
  33204. }
  33205. this.uniforms.uSampler = value;
  33206. this.uvMatrix.texture = value;
  33207. }
  33208. },
  33209. enumerable: false,
  33210. configurable: true
  33211. });
  33212. Object.defineProperty(MeshMaterial.prototype, "alpha", {
  33213. get: function () {
  33214. return this._alpha;
  33215. },
  33216. /**
  33217. * This gets automatically set by the object using this.
  33218. * @default 1
  33219. */
  33220. set: function (value) {
  33221. if (value === this._alpha)
  33222. { return; }
  33223. this._alpha = value;
  33224. this._colorDirty = true;
  33225. },
  33226. enumerable: false,
  33227. configurable: true
  33228. });
  33229. Object.defineProperty(MeshMaterial.prototype, "tint", {
  33230. get: function () {
  33231. return this._tint;
  33232. },
  33233. /**
  33234. * Multiply tint for the material.
  33235. * @default 0xFFFFFF
  33236. */
  33237. set: function (value) {
  33238. if (value === this._tint)
  33239. { return; }
  33240. this._tint = value;
  33241. this._tintRGB = (value >> 16) + (value & 0xff00) + ((value & 0xff) << 16);
  33242. this._colorDirty = true;
  33243. },
  33244. enumerable: false,
  33245. configurable: true
  33246. });
  33247. /** Gets called automatically by the Mesh. Intended to be overridden for custom {@link MeshMaterial} objects. */
  33248. MeshMaterial.prototype.update = function () {
  33249. if (this._colorDirty) {
  33250. this._colorDirty = false;
  33251. var baseTexture = this.texture.baseTexture;
  33252. premultiplyTintToRgba(this._tint, this._alpha, this.uniforms.uColor, baseTexture.alphaMode);
  33253. }
  33254. if (this.uvMatrix.update()) {
  33255. this.uniforms.uTextureMatrix = this.uvMatrix.mapCoord;
  33256. }
  33257. };
  33258. return MeshMaterial;
  33259. }(Shader));
  33260. /**
  33261. * Standard 2D geometry used in PixiJS.
  33262. *
  33263. * Geometry can be defined without passing in a style or data if required.
  33264. *
  33265. * ```js
  33266. * const geometry = new PIXI.Geometry();
  33267. *
  33268. * geometry.addAttribute('positions', [0, 0, 100, 0, 100, 100, 0, 100], 2);
  33269. * geometry.addAttribute('uvs', [0,0,1,0,1,1,0,1], 2);
  33270. * geometry.addIndex([0,1,2,1,3,2]);
  33271. *
  33272. * ```
  33273. * @memberof PIXI
  33274. */
  33275. var MeshGeometry = /** @class */ (function (_super) {
  33276. __extends$9(MeshGeometry, _super);
  33277. /**
  33278. * @param {Float32Array|number[]} [vertices] - Positional data on geometry.
  33279. * @param {Float32Array|number[]} [uvs] - Texture UVs.
  33280. * @param {Uint16Array|number[]} [index] - IndexBuffer
  33281. */
  33282. function MeshGeometry(vertices, uvs, index) {
  33283. var _this = _super.call(this) || this;
  33284. var verticesBuffer = new Buffer(vertices);
  33285. var uvsBuffer = new Buffer(uvs, true);
  33286. var indexBuffer = new Buffer(index, true, true);
  33287. _this.addAttribute('aVertexPosition', verticesBuffer, 2, false, TYPES.FLOAT)
  33288. .addAttribute('aTextureCoord', uvsBuffer, 2, false, TYPES.FLOAT)
  33289. .addIndex(indexBuffer);
  33290. _this._updateId = -1;
  33291. return _this;
  33292. }
  33293. Object.defineProperty(MeshGeometry.prototype, "vertexDirtyId", {
  33294. /**
  33295. * If the vertex position is updated.
  33296. * @readonly
  33297. * @private
  33298. */
  33299. get: function () {
  33300. return this.buffers[0]._updateID;
  33301. },
  33302. enumerable: false,
  33303. configurable: true
  33304. });
  33305. return MeshGeometry;
  33306. }(Geometry));
  33307. /*!
  33308. * @pixi/text-bitmap - v6.5.10
  33309. * Compiled Thu, 06 Jul 2023 15:25:11 UTC
  33310. *
  33311. * @pixi/text-bitmap is licensed under the MIT License.
  33312. * http://www.opensource.org/licenses/mit-license
  33313. */
  33314. /*! *****************************************************************************
  33315. Copyright (c) Microsoft Corporation.
  33316. Permission to use, copy, modify, and/or distribute this software for any
  33317. purpose with or without fee is hereby granted.
  33318. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  33319. REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
  33320. AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  33321. INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
  33322. LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
  33323. OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
  33324. PERFORMANCE OF THIS SOFTWARE.
  33325. ***************************************************************************** */
  33326. /* global Reflect, Promise */
  33327. var extendStatics$8 = function(d, b) {
  33328. extendStatics$8 = Object.setPrototypeOf ||
  33329. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  33330. function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } };
  33331. return extendStatics$8(d, b);
  33332. };
  33333. function __extends$8(d, b) {
  33334. extendStatics$8(d, b);
  33335. function __() { this.constructor = d; }
  33336. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  33337. }
  33338. /* eslint-disable max-len */
  33339. /**
  33340. * Normalized parsed data from .fnt files.
  33341. * @memberof PIXI
  33342. */
  33343. var BitmapFontData = /** @class */ (function () {
  33344. function BitmapFontData() {
  33345. this.info = [];
  33346. this.common = [];
  33347. this.page = [];
  33348. this.char = [];
  33349. this.kerning = [];
  33350. this.distanceField = [];
  33351. }
  33352. return BitmapFontData;
  33353. }());
  33354. /**
  33355. * BitmapFont format that's Text-based.
  33356. * @private
  33357. */
  33358. var TextFormat = /** @class */ (function () {
  33359. function TextFormat() {
  33360. }
  33361. /**
  33362. * Check if resource refers to txt font data.
  33363. * @param data
  33364. * @returns - True if resource could be treated as font data, false otherwise.
  33365. */
  33366. TextFormat.test = function (data) {
  33367. return typeof data === 'string' && data.indexOf('info face=') === 0;
  33368. };
  33369. /**
  33370. * Convert text font data to a javascript object.
  33371. * @param txt - Raw string data to be converted
  33372. * @returns - Parsed font data
  33373. */
  33374. TextFormat.parse = function (txt) {
  33375. // Retrieve data item
  33376. var items = txt.match(/^[a-z]+\s+.+$/gm);
  33377. var rawData = {
  33378. info: [],
  33379. common: [],
  33380. page: [],
  33381. char: [],
  33382. chars: [],
  33383. kerning: [],
  33384. kernings: [],
  33385. distanceField: [],
  33386. };
  33387. for (var i in items) {
  33388. // Extract item name
  33389. var name = items[i].match(/^[a-z]+/gm)[0];
  33390. // Extract item attribute list as string ex.: "width=10"
  33391. var attributeList = items[i].match(/[a-zA-Z]+=([^\s"']+|"([^"]*)")/gm);
  33392. // Convert attribute list into an object
  33393. var itemData = {};
  33394. for (var i_1 in attributeList) {
  33395. // Split key-value pairs
  33396. var split = attributeList[i_1].split('=');
  33397. var key = split[0];
  33398. // Remove eventual quotes from value
  33399. var strValue = split[1].replace(/"/gm, '');
  33400. // Try to convert value into float
  33401. var floatValue = parseFloat(strValue);
  33402. // Use string value case float value is NaN
  33403. var value = isNaN(floatValue) ? strValue : floatValue;
  33404. itemData[key] = value;
  33405. }
  33406. // Push current item to the resulting data
  33407. rawData[name].push(itemData);
  33408. }
  33409. var font = new BitmapFontData();
  33410. rawData.info.forEach(function (info) { return font.info.push({
  33411. face: info.face,
  33412. size: parseInt(info.size, 10),
  33413. }); });
  33414. rawData.common.forEach(function (common) { return font.common.push({
  33415. lineHeight: parseInt(common.lineHeight, 10),
  33416. }); });
  33417. rawData.page.forEach(function (page) { return font.page.push({
  33418. id: parseInt(page.id, 10),
  33419. file: page.file,
  33420. }); });
  33421. rawData.char.forEach(function (char) { return font.char.push({
  33422. id: parseInt(char.id, 10),
  33423. page: parseInt(char.page, 10),
  33424. x: parseInt(char.x, 10),
  33425. y: parseInt(char.y, 10),
  33426. width: parseInt(char.width, 10),
  33427. height: parseInt(char.height, 10),
  33428. xoffset: parseInt(char.xoffset, 10),
  33429. yoffset: parseInt(char.yoffset, 10),
  33430. xadvance: parseInt(char.xadvance, 10),
  33431. }); });
  33432. rawData.kerning.forEach(function (kerning) { return font.kerning.push({
  33433. first: parseInt(kerning.first, 10),
  33434. second: parseInt(kerning.second, 10),
  33435. amount: parseInt(kerning.amount, 10),
  33436. }); });
  33437. rawData.distanceField.forEach(function (df) { return font.distanceField.push({
  33438. distanceRange: parseInt(df.distanceRange, 10),
  33439. fieldType: df.fieldType,
  33440. }); });
  33441. return font;
  33442. };
  33443. return TextFormat;
  33444. }());
  33445. /**
  33446. * BitmapFont format that's XML-based.
  33447. * @private
  33448. */
  33449. var XMLFormat = /** @class */ (function () {
  33450. function XMLFormat() {
  33451. }
  33452. /**
  33453. * Check if resource refers to xml font data.
  33454. * @param data
  33455. * @returns - True if resource could be treated as font data, false otherwise.
  33456. */
  33457. XMLFormat.test = function (data) {
  33458. return data instanceof XMLDocument
  33459. && data.getElementsByTagName('page').length
  33460. && data.getElementsByTagName('info')[0].getAttribute('face') !== null;
  33461. };
  33462. /**
  33463. * Convert the XML into BitmapFontData that we can use.
  33464. * @param xml
  33465. * @returns - Data to use for BitmapFont
  33466. */
  33467. XMLFormat.parse = function (xml) {
  33468. var data = new BitmapFontData();
  33469. var info = xml.getElementsByTagName('info');
  33470. var common = xml.getElementsByTagName('common');
  33471. var page = xml.getElementsByTagName('page');
  33472. var char = xml.getElementsByTagName('char');
  33473. var kerning = xml.getElementsByTagName('kerning');
  33474. var distanceField = xml.getElementsByTagName('distanceField');
  33475. for (var i = 0; i < info.length; i++) {
  33476. data.info.push({
  33477. face: info[i].getAttribute('face'),
  33478. size: parseInt(info[i].getAttribute('size'), 10),
  33479. });
  33480. }
  33481. for (var i = 0; i < common.length; i++) {
  33482. data.common.push({
  33483. lineHeight: parseInt(common[i].getAttribute('lineHeight'), 10),
  33484. });
  33485. }
  33486. for (var i = 0; i < page.length; i++) {
  33487. data.page.push({
  33488. id: parseInt(page[i].getAttribute('id'), 10) || 0,
  33489. file: page[i].getAttribute('file'),
  33490. });
  33491. }
  33492. for (var i = 0; i < char.length; i++) {
  33493. var letter = char[i];
  33494. data.char.push({
  33495. id: parseInt(letter.getAttribute('id'), 10),
  33496. page: parseInt(letter.getAttribute('page'), 10) || 0,
  33497. x: parseInt(letter.getAttribute('x'), 10),
  33498. y: parseInt(letter.getAttribute('y'), 10),
  33499. width: parseInt(letter.getAttribute('width'), 10),
  33500. height: parseInt(letter.getAttribute('height'), 10),
  33501. xoffset: parseInt(letter.getAttribute('xoffset'), 10),
  33502. yoffset: parseInt(letter.getAttribute('yoffset'), 10),
  33503. xadvance: parseInt(letter.getAttribute('xadvance'), 10),
  33504. });
  33505. }
  33506. for (var i = 0; i < kerning.length; i++) {
  33507. data.kerning.push({
  33508. first: parseInt(kerning[i].getAttribute('first'), 10),
  33509. second: parseInt(kerning[i].getAttribute('second'), 10),
  33510. amount: parseInt(kerning[i].getAttribute('amount'), 10),
  33511. });
  33512. }
  33513. for (var i = 0; i < distanceField.length; i++) {
  33514. data.distanceField.push({
  33515. fieldType: distanceField[i].getAttribute('fieldType'),
  33516. distanceRange: parseInt(distanceField[i].getAttribute('distanceRange'), 10),
  33517. });
  33518. }
  33519. return data;
  33520. };
  33521. return XMLFormat;
  33522. }());
  33523. /**
  33524. * BitmapFont format that's XML-based.
  33525. * @private
  33526. */
  33527. var XMLStringFormat = /** @class */ (function () {
  33528. function XMLStringFormat() {
  33529. }
  33530. /**
  33531. * Check if resource refers to text xml font data.
  33532. * @param data
  33533. * @returns - True if resource could be treated as font data, false otherwise.
  33534. */
  33535. XMLStringFormat.test = function (data) {
  33536. if (typeof data === 'string' && data.indexOf('<font>') > -1) {
  33537. var xml = new globalThis.DOMParser().parseFromString(data, 'text/xml');
  33538. return XMLFormat.test(xml);
  33539. }
  33540. return false;
  33541. };
  33542. /**
  33543. * Convert the text XML into BitmapFontData that we can use.
  33544. * @param xmlTxt
  33545. * @returns - Data to use for BitmapFont
  33546. */
  33547. XMLStringFormat.parse = function (xmlTxt) {
  33548. var xml = new globalThis.DOMParser().parseFromString(xmlTxt, 'text/xml');
  33549. return XMLFormat.parse(xml);
  33550. };
  33551. return XMLStringFormat;
  33552. }());
  33553. // Registered formats, maybe make this extensible in the future?
  33554. var formats = [
  33555. TextFormat,
  33556. XMLFormat,
  33557. XMLStringFormat ];
  33558. /**
  33559. * Auto-detect BitmapFont parsing format based on data.
  33560. * @private
  33561. * @param {any} data - Data to detect format
  33562. * @returns {any} Format or null
  33563. */
  33564. function autoDetectFormat(data) {
  33565. for (var i = 0; i < formats.length; i++) {
  33566. if (formats[i].test(data)) {
  33567. return formats[i];
  33568. }
  33569. }
  33570. return null;
  33571. }
  33572. // TODO: Prevent code duplication b/w generateFillStyle & Text#generateFillStyle
  33573. /**
  33574. * Generates the fill style. Can automatically generate a gradient based on the fill style being an array
  33575. * @private
  33576. * @param canvas
  33577. * @param context
  33578. * @param {object} style - The style.
  33579. * @param resolution
  33580. * @param {string[]} lines - The lines of text.
  33581. * @param metrics
  33582. * @returns {string|number|CanvasGradient} The fill style
  33583. */
  33584. function generateFillStyle(canvas, context, style, resolution, lines, metrics) {
  33585. // TODO: Can't have different types for getter and setter. The getter shouldn't have the number type as
  33586. // the setter converts to string. See this thread for more details:
  33587. // https://github.com/microsoft/TypeScript/issues/2521
  33588. var fillStyle = style.fill;
  33589. if (!Array.isArray(fillStyle)) {
  33590. return fillStyle;
  33591. }
  33592. else if (fillStyle.length === 1) {
  33593. return fillStyle[0];
  33594. }
  33595. // the gradient will be evenly spaced out according to how large the array is.
  33596. // ['#FF0000', '#00FF00', '#0000FF'] would created stops at 0.25, 0.5 and 0.75
  33597. var gradient;
  33598. // a dropshadow will enlarge the canvas and result in the gradient being
  33599. // generated with the incorrect dimensions
  33600. var dropShadowCorrection = (style.dropShadow) ? style.dropShadowDistance : 0;
  33601. // should also take padding into account, padding can offset the gradient
  33602. var padding = style.padding || 0;
  33603. var width = (canvas.width / resolution) - dropShadowCorrection - (padding * 2);
  33604. var height = (canvas.height / resolution) - dropShadowCorrection - (padding * 2);
  33605. // make a copy of the style settings, so we can manipulate them later
  33606. var fill = fillStyle.slice();
  33607. var fillGradientStops = style.fillGradientStops.slice();
  33608. // wanting to evenly distribute the fills. So an array of 4 colours should give fills of 0.25, 0.5 and 0.75
  33609. if (!fillGradientStops.length) {
  33610. var lengthPlus1 = fill.length + 1;
  33611. for (var i = 1; i < lengthPlus1; ++i) {
  33612. fillGradientStops.push(i / lengthPlus1);
  33613. }
  33614. }
  33615. // stop the bleeding of the last gradient on the line above to the top gradient of the this line
  33616. // by hard defining the first gradient colour at point 0, and last gradient colour at point 1
  33617. fill.unshift(fillStyle[0]);
  33618. fillGradientStops.unshift(0);
  33619. fill.push(fillStyle[fillStyle.length - 1]);
  33620. fillGradientStops.push(1);
  33621. if (style.fillGradientType === TEXT_GRADIENT.LINEAR_VERTICAL) {
  33622. // start the gradient at the top center of the canvas, and end at the bottom middle of the canvas
  33623. gradient = context.createLinearGradient(width / 2, padding, width / 2, height + padding);
  33624. // we need to repeat the gradient so that each individual line of text has the same vertical gradient effect
  33625. // ['#FF0000', '#00FF00', '#0000FF'] over 2 lines would create stops at 0.125, 0.25, 0.375, 0.625, 0.75, 0.875
  33626. // There's potential for floating point precision issues at the seams between gradient repeats.
  33627. // The loop below generates the stops in order, so track the last generated one to prevent
  33628. // floating point precision from making us go the teeniest bit backwards, resulting in
  33629. // the first and last colors getting swapped.
  33630. var lastIterationStop = 0;
  33631. // Actual height of the text itself, not counting spacing for lineHeight/leading/dropShadow etc
  33632. var textHeight = metrics.fontProperties.fontSize + style.strokeThickness;
  33633. // textHeight, but as a 0-1 size in global gradient stop space
  33634. var gradStopLineHeight = textHeight / height;
  33635. for (var i = 0; i < lines.length; i++) {
  33636. var thisLineTop = metrics.lineHeight * i;
  33637. for (var j = 0; j < fill.length; j++) {
  33638. // 0-1 stop point for the current line, multiplied to global space afterwards
  33639. var lineStop = 0;
  33640. if (typeof fillGradientStops[j] === 'number') {
  33641. lineStop = fillGradientStops[j];
  33642. }
  33643. else {
  33644. lineStop = j / fill.length;
  33645. }
  33646. var globalStop = (thisLineTop / height) + (lineStop * gradStopLineHeight);
  33647. // Prevent color stop generation going backwards from floating point imprecision
  33648. var clampedStop = Math.max(lastIterationStop, globalStop);
  33649. clampedStop = Math.min(clampedStop, 1); // Cap at 1 as well for safety's sake to avoid a possible throw.
  33650. gradient.addColorStop(clampedStop, fill[j]);
  33651. lastIterationStop = clampedStop;
  33652. }
  33653. }
  33654. }
  33655. else {
  33656. // start the gradient at the center left of the canvas, and end at the center right of the canvas
  33657. gradient = context.createLinearGradient(padding, height / 2, width + padding, height / 2);
  33658. // can just evenly space out the gradients in this case, as multiple lines makes no difference
  33659. // to an even left to right gradient
  33660. var totalIterations = fill.length + 1;
  33661. var currentIteration = 1;
  33662. for (var i = 0; i < fill.length; i++) {
  33663. var stop = void 0;
  33664. if (typeof fillGradientStops[i] === 'number') {
  33665. stop = fillGradientStops[i];
  33666. }
  33667. else {
  33668. stop = currentIteration / totalIterations;
  33669. }
  33670. gradient.addColorStop(stop, fill[i]);
  33671. currentIteration++;
  33672. }
  33673. }
  33674. return gradient;
  33675. }
  33676. // TODO: Prevent code duplication b/w drawGlyph & Text#updateText
  33677. /**
  33678. * Draws the glyph `metrics.text` on the given canvas.
  33679. *
  33680. * Ignored because not directly exposed.
  33681. * @ignore
  33682. * @param {HTMLCanvasElement} canvas
  33683. * @param {CanvasRenderingContext2D} context
  33684. * @param {TextMetrics} metrics
  33685. * @param {number} x
  33686. * @param {number} y
  33687. * @param {number} resolution
  33688. * @param {TextStyle} style
  33689. */
  33690. function drawGlyph(canvas, context, metrics, x, y, resolution, style) {
  33691. var char = metrics.text;
  33692. var fontProperties = metrics.fontProperties;
  33693. context.translate(x, y);
  33694. context.scale(resolution, resolution);
  33695. var tx = style.strokeThickness / 2;
  33696. var ty = -(style.strokeThickness / 2);
  33697. context.font = style.toFontString();
  33698. context.lineWidth = style.strokeThickness;
  33699. context.textBaseline = style.textBaseline;
  33700. context.lineJoin = style.lineJoin;
  33701. context.miterLimit = style.miterLimit;
  33702. // set canvas text styles
  33703. context.fillStyle = generateFillStyle(canvas, context, style, resolution, [char], metrics);
  33704. context.strokeStyle = style.stroke;
  33705. if (style.dropShadow) {
  33706. var dropShadowColor = style.dropShadowColor;
  33707. var rgb = hex2rgb(typeof dropShadowColor === 'number' ? dropShadowColor : string2hex(dropShadowColor));
  33708. var dropShadowBlur = style.dropShadowBlur * resolution;
  33709. var dropShadowDistance = style.dropShadowDistance * resolution;
  33710. context.shadowColor = "rgba(" + rgb[0] * 255 + "," + rgb[1] * 255 + "," + rgb[2] * 255 + "," + style.dropShadowAlpha + ")";
  33711. context.shadowBlur = dropShadowBlur;
  33712. context.shadowOffsetX = Math.cos(style.dropShadowAngle) * dropShadowDistance;
  33713. context.shadowOffsetY = Math.sin(style.dropShadowAngle) * dropShadowDistance;
  33714. }
  33715. else {
  33716. context.shadowColor = 'black';
  33717. context.shadowBlur = 0;
  33718. context.shadowOffsetX = 0;
  33719. context.shadowOffsetY = 0;
  33720. }
  33721. if (style.stroke && style.strokeThickness) {
  33722. context.strokeText(char, tx, ty + metrics.lineHeight - fontProperties.descent);
  33723. }
  33724. if (style.fill) {
  33725. context.fillText(char, tx, ty + metrics.lineHeight - fontProperties.descent);
  33726. }
  33727. context.setTransform(1, 0, 0, 1, 0, 0); // defaults needed for older browsers (e.g. Opera 29)
  33728. context.fillStyle = 'rgba(0, 0, 0, 0)';
  33729. }
  33730. /**
  33731. * Ponyfill for IE because it doesn't support `Array.from`
  33732. * @param text
  33733. * @private
  33734. */
  33735. function splitTextToCharacters(text) {
  33736. return Array.from ? Array.from(text) : text.split('');
  33737. }
  33738. /**
  33739. * Processes the passed character set data and returns a flattened array of all the characters.
  33740. *
  33741. * Ignored because not directly exposed.
  33742. * @ignore
  33743. * @param {string | string[] | string[][] } chars
  33744. * @returns {string[]} the flattened array of characters
  33745. */
  33746. function resolveCharacters(chars) {
  33747. // Split the chars string into individual characters
  33748. if (typeof chars === 'string') {
  33749. chars = [chars];
  33750. }
  33751. // Handle an array of characters+ranges
  33752. var result = [];
  33753. for (var i = 0, j = chars.length; i < j; i++) {
  33754. var item = chars[i];
  33755. // Handle range delimited by start/end chars
  33756. if (Array.isArray(item)) {
  33757. if (item.length !== 2) {
  33758. throw new Error("[BitmapFont]: Invalid character range length, expecting 2 got " + item.length + ".");
  33759. }
  33760. var startCode = item[0].charCodeAt(0);
  33761. var endCode = item[1].charCodeAt(0);
  33762. if (endCode < startCode) {
  33763. throw new Error('[BitmapFont]: Invalid character range.');
  33764. }
  33765. for (var i_1 = startCode, j_1 = endCode; i_1 <= j_1; i_1++) {
  33766. result.push(String.fromCharCode(i_1));
  33767. }
  33768. }
  33769. // Handle a character set string
  33770. else {
  33771. result.push.apply(result, splitTextToCharacters(item));
  33772. }
  33773. }
  33774. if (result.length === 0) {
  33775. throw new Error('[BitmapFont]: Empty set when resolving characters.');
  33776. }
  33777. return result;
  33778. }
  33779. /**
  33780. * Ponyfill for IE because it doesn't support `codePointAt`
  33781. * @param str
  33782. * @private
  33783. */
  33784. function extractCharCode(str) {
  33785. return str.codePointAt ? str.codePointAt(0) : str.charCodeAt(0);
  33786. }
  33787. /**
  33788. * BitmapFont represents a typeface available for use with the BitmapText class. Use the `install`
  33789. * method for adding a font to be used.
  33790. * @memberof PIXI
  33791. */
  33792. var BitmapFont = /** @class */ (function () {
  33793. /**
  33794. * @param data
  33795. * @param textures
  33796. * @param ownsTextures - Setting to `true` will destroy page textures
  33797. * when the font is uninstalled.
  33798. */
  33799. function BitmapFont(data, textures, ownsTextures) {
  33800. var _a, _b;
  33801. var info = data.info[0];
  33802. var common = data.common[0];
  33803. var page = data.page[0];
  33804. var distanceField = data.distanceField[0];
  33805. var res = getResolutionOfUrl(page.file);
  33806. var pageTextures = {};
  33807. this._ownsTextures = ownsTextures;
  33808. this.font = info.face;
  33809. this.size = info.size;
  33810. this.lineHeight = common.lineHeight / res;
  33811. this.chars = {};
  33812. this.pageTextures = pageTextures;
  33813. // Convert the input Texture, Textures or object
  33814. // into a page Texture lookup by "id"
  33815. for (var i = 0; i < data.page.length; i++) {
  33816. var _c = data.page[i], id = _c.id, file = _c.file;
  33817. pageTextures[id] = textures instanceof Array
  33818. ? textures[i] : textures[file];
  33819. // only MSDF and SDF fonts need no-premultiplied-alpha
  33820. if ((distanceField === null || distanceField === void 0 ? void 0 : distanceField.fieldType) && distanceField.fieldType !== 'none') {
  33821. pageTextures[id].baseTexture.alphaMode = ALPHA_MODES.NO_PREMULTIPLIED_ALPHA;
  33822. pageTextures[id].baseTexture.mipmap = MIPMAP_MODES.OFF;
  33823. }
  33824. }
  33825. // parse letters
  33826. for (var i = 0; i < data.char.length; i++) {
  33827. var _d = data.char[i], id = _d.id, page_1 = _d.page;
  33828. var _e = data.char[i], x = _e.x, y = _e.y, width = _e.width, height = _e.height, xoffset = _e.xoffset, yoffset = _e.yoffset, xadvance = _e.xadvance;
  33829. x /= res;
  33830. y /= res;
  33831. width /= res;
  33832. height /= res;
  33833. xoffset /= res;
  33834. yoffset /= res;
  33835. xadvance /= res;
  33836. var rect = new Rectangle(x + (pageTextures[page_1].frame.x / res), y + (pageTextures[page_1].frame.y / res), width, height);
  33837. this.chars[id] = {
  33838. xOffset: xoffset,
  33839. yOffset: yoffset,
  33840. xAdvance: xadvance,
  33841. kerning: {},
  33842. texture: new Texture(pageTextures[page_1].baseTexture, rect),
  33843. page: page_1,
  33844. };
  33845. }
  33846. // parse kernings
  33847. for (var i = 0; i < data.kerning.length; i++) {
  33848. var _f = data.kerning[i], first = _f.first, second = _f.second, amount = _f.amount;
  33849. first /= res;
  33850. second /= res;
  33851. amount /= res;
  33852. if (this.chars[second]) {
  33853. this.chars[second].kerning[first] = amount;
  33854. }
  33855. }
  33856. // Store distance field information
  33857. this.distanceFieldRange = distanceField === null || distanceField === void 0 ? void 0 : distanceField.distanceRange;
  33858. this.distanceFieldType = (_b = (_a = distanceField === null || distanceField === void 0 ? void 0 : distanceField.fieldType) === null || _a === void 0 ? void 0 : _a.toLowerCase()) !== null && _b !== void 0 ? _b : 'none';
  33859. }
  33860. /** Remove references to created glyph textures. */
  33861. BitmapFont.prototype.destroy = function () {
  33862. for (var id in this.chars) {
  33863. this.chars[id].texture.destroy();
  33864. this.chars[id].texture = null;
  33865. }
  33866. for (var id in this.pageTextures) {
  33867. if (this._ownsTextures) {
  33868. this.pageTextures[id].destroy(true);
  33869. }
  33870. this.pageTextures[id] = null;
  33871. }
  33872. // Set readonly null.
  33873. this.chars = null;
  33874. this.pageTextures = null;
  33875. };
  33876. /**
  33877. * Register a new bitmap font.
  33878. * @param data - The
  33879. * characters map that could be provided as xml or raw string.
  33880. * @param textures - List of textures for each page.
  33881. * @param ownsTextures - Set to `true` to destroy page textures
  33882. * when the font is uninstalled. By default fonts created with
  33883. * `BitmapFont.from` or from the `BitmapFontLoader` are `true`.
  33884. * @returns {PIXI.BitmapFont} Result font object with font, size, lineHeight
  33885. * and char fields.
  33886. */
  33887. BitmapFont.install = function (data, textures, ownsTextures) {
  33888. var fontData;
  33889. if (data instanceof BitmapFontData) {
  33890. fontData = data;
  33891. }
  33892. else {
  33893. var format = autoDetectFormat(data);
  33894. if (!format) {
  33895. throw new Error('Unrecognized data format for font.');
  33896. }
  33897. fontData = format.parse(data);
  33898. }
  33899. // Single texture, convert to list
  33900. if (textures instanceof Texture) {
  33901. textures = [textures];
  33902. }
  33903. var font = new BitmapFont(fontData, textures, ownsTextures);
  33904. BitmapFont.available[font.font] = font;
  33905. return font;
  33906. };
  33907. /**
  33908. * Remove bitmap font by name.
  33909. * @param name - Name of the font to uninstall.
  33910. */
  33911. BitmapFont.uninstall = function (name) {
  33912. var font = BitmapFont.available[name];
  33913. if (!font) {
  33914. throw new Error("No font found named '" + name + "'");
  33915. }
  33916. font.destroy();
  33917. delete BitmapFont.available[name];
  33918. };
  33919. /**
  33920. * Generates a bitmap-font for the given style and character set. This does not support
  33921. * kernings yet. With `style` properties, only the following non-layout properties are used:
  33922. *
  33923. * - {@link PIXI.TextStyle#dropShadow|dropShadow}
  33924. * - {@link PIXI.TextStyle#dropShadowDistance|dropShadowDistance}
  33925. * - {@link PIXI.TextStyle#dropShadowColor|dropShadowColor}
  33926. * - {@link PIXI.TextStyle#dropShadowBlur|dropShadowBlur}
  33927. * - {@link PIXI.TextStyle#dropShadowAngle|dropShadowAngle}
  33928. * - {@link PIXI.TextStyle#fill|fill}
  33929. * - {@link PIXI.TextStyle#fillGradientStops|fillGradientStops}
  33930. * - {@link PIXI.TextStyle#fillGradientType|fillGradientType}
  33931. * - {@link PIXI.TextStyle#fontFamily|fontFamily}
  33932. * - {@link PIXI.TextStyle#fontSize|fontSize}
  33933. * - {@link PIXI.TextStyle#fontVariant|fontVariant}
  33934. * - {@link PIXI.TextStyle#fontWeight|fontWeight}
  33935. * - {@link PIXI.TextStyle#lineJoin|lineJoin}
  33936. * - {@link PIXI.TextStyle#miterLimit|miterLimit}
  33937. * - {@link PIXI.TextStyle#stroke|stroke}
  33938. * - {@link PIXI.TextStyle#strokeThickness|strokeThickness}
  33939. * - {@link PIXI.TextStyle#textBaseline|textBaseline}
  33940. * @param name - The name of the custom font to use with BitmapText.
  33941. * @param textStyle - Style options to render with BitmapFont.
  33942. * @param options - Setup options for font or name of the font.
  33943. * @param {string|string[]|string[][]} [options.chars=PIXI.BitmapFont.ALPHANUMERIC] - characters included
  33944. * in the font set. You can also use ranges. For example, `[['a', 'z'], ['A', 'Z'], "!@#$%^&*()~{}[] "]`.
  33945. * Don't forget to include spaces ' ' in your character set!
  33946. * @param {number} [options.resolution=1] - Render resolution for glyphs.
  33947. * @param {number} [options.textureWidth=512] - Optional width of atlas, smaller values to reduce memory.
  33948. * @param {number} [options.textureHeight=512] - Optional height of atlas, smaller values to reduce memory.
  33949. * @param {number} [options.padding=4] - Padding between glyphs on texture atlas.
  33950. * @returns Font generated by style options.
  33951. * @example
  33952. * PIXI.BitmapFont.from("TitleFont", {
  33953. * fontFamily: "Arial",
  33954. * fontSize: 12,
  33955. * strokeThickness: 2,
  33956. * fill: "purple"
  33957. * });
  33958. *
  33959. * const title = new PIXI.BitmapText("This is the title", { fontName: "TitleFont" });
  33960. */
  33961. BitmapFont.from = function (name, textStyle, options) {
  33962. if (!name) {
  33963. throw new Error('[BitmapFont] Property `name` is required.');
  33964. }
  33965. var _a = Object.assign({}, BitmapFont.defaultOptions, options), chars = _a.chars, padding = _a.padding, resolution = _a.resolution, textureWidth = _a.textureWidth, textureHeight = _a.textureHeight;
  33966. var charsList = resolveCharacters(chars);
  33967. var style = textStyle instanceof TextStyle ? textStyle : new TextStyle(textStyle);
  33968. var lineWidth = textureWidth;
  33969. var fontData = new BitmapFontData();
  33970. fontData.info[0] = {
  33971. face: style.fontFamily,
  33972. size: style.fontSize,
  33973. };
  33974. fontData.common[0] = {
  33975. lineHeight: style.fontSize,
  33976. };
  33977. var positionX = 0;
  33978. var positionY = 0;
  33979. var canvas;
  33980. var context;
  33981. var baseTexture;
  33982. var maxCharHeight = 0;
  33983. var textures = [];
  33984. for (var i = 0; i < charsList.length; i++) {
  33985. if (!canvas) {
  33986. canvas = settings.ADAPTER.createCanvas();
  33987. canvas.width = textureWidth;
  33988. canvas.height = textureHeight;
  33989. context = canvas.getContext('2d');
  33990. baseTexture = new BaseTexture(canvas, { resolution: resolution });
  33991. textures.push(new Texture(baseTexture));
  33992. fontData.page.push({
  33993. id: textures.length - 1,
  33994. file: '',
  33995. });
  33996. }
  33997. // Measure glyph dimensions
  33998. var character = charsList[i];
  33999. var metrics = TextMetrics.measureText(character, style, false, canvas);
  34000. var width = metrics.width;
  34001. var height = Math.ceil(metrics.height);
  34002. // This is ugly - but italics are given more space so they don't overlap
  34003. var textureGlyphWidth = Math.ceil((style.fontStyle === 'italic' ? 2 : 1) * width);
  34004. // Can't fit char anymore: next canvas please!
  34005. if (positionY >= textureHeight - (height * resolution)) {
  34006. if (positionY === 0) {
  34007. // We don't want user debugging an infinite loop (or do we? :)
  34008. throw new Error("[BitmapFont] textureHeight " + textureHeight + "px is too small "
  34009. + ("(fontFamily: '" + style.fontFamily + "', fontSize: " + style.fontSize + "px, char: '" + character + "')"));
  34010. }
  34011. --i;
  34012. // Create new atlas once current has filled up
  34013. canvas = null;
  34014. context = null;
  34015. baseTexture = null;
  34016. positionY = 0;
  34017. positionX = 0;
  34018. maxCharHeight = 0;
  34019. continue;
  34020. }
  34021. maxCharHeight = Math.max(height + metrics.fontProperties.descent, maxCharHeight);
  34022. // Wrap line once full row has been rendered
  34023. if ((textureGlyphWidth * resolution) + positionX >= lineWidth) {
  34024. if (positionX === 0) {
  34025. // Avoid infinite loop (There can be some very wide char like '\uFDFD'!)
  34026. throw new Error("[BitmapFont] textureWidth " + textureWidth + "px is too small "
  34027. + ("(fontFamily: '" + style.fontFamily + "', fontSize: " + style.fontSize + "px, char: '" + character + "')"));
  34028. }
  34029. --i;
  34030. positionY += maxCharHeight * resolution;
  34031. positionY = Math.ceil(positionY);
  34032. positionX = 0;
  34033. maxCharHeight = 0;
  34034. continue;
  34035. }
  34036. drawGlyph(canvas, context, metrics, positionX, positionY, resolution, style);
  34037. // Unique (numeric) ID mapping to this glyph
  34038. var id = extractCharCode(metrics.text);
  34039. // Create a texture holding just the glyph
  34040. fontData.char.push({
  34041. id: id,
  34042. page: textures.length - 1,
  34043. x: positionX / resolution,
  34044. y: positionY / resolution,
  34045. width: textureGlyphWidth,
  34046. height: height,
  34047. xoffset: 0,
  34048. yoffset: 0,
  34049. xadvance: Math.ceil(width
  34050. - (style.dropShadow ? style.dropShadowDistance : 0)
  34051. - (style.stroke ? style.strokeThickness : 0)),
  34052. });
  34053. positionX += (textureGlyphWidth + (2 * padding)) * resolution;
  34054. positionX = Math.ceil(positionX);
  34055. }
  34056. if (!(options === null || options === void 0 ? void 0 : options.skipKerning)) {
  34057. // Brute-force kerning info, this can be expensive b/c it's an O(n²),
  34058. // but we're using measureText which is native and fast.
  34059. for (var i = 0, len = charsList.length; i < len; i++) {
  34060. var first = charsList[i];
  34061. for (var j = 0; j < len; j++) {
  34062. var second = charsList[j];
  34063. var c1 = context.measureText(first).width;
  34064. var c2 = context.measureText(second).width;
  34065. var total = context.measureText(first + second).width;
  34066. var amount = total - (c1 + c2);
  34067. if (amount) {
  34068. fontData.kerning.push({
  34069. first: extractCharCode(first),
  34070. second: extractCharCode(second),
  34071. amount: amount,
  34072. });
  34073. }
  34074. }
  34075. }
  34076. }
  34077. var font = new BitmapFont(fontData, textures, true);
  34078. // Make it easier to replace a font
  34079. if (BitmapFont.available[name] !== undefined) {
  34080. BitmapFont.uninstall(name);
  34081. }
  34082. BitmapFont.available[name] = font;
  34083. return font;
  34084. };
  34085. /**
  34086. * This character set includes all the letters in the alphabet (both lower- and upper- case).
  34087. * @type {string[][]}
  34088. * @example
  34089. * BitmapFont.from("ExampleFont", style, { chars: BitmapFont.ALPHA })
  34090. */
  34091. BitmapFont.ALPHA = [['a', 'z'], ['A', 'Z'], ' '];
  34092. /**
  34093. * This character set includes all decimal digits (from 0 to 9).
  34094. * @type {string[][]}
  34095. * @example
  34096. * BitmapFont.from("ExampleFont", style, { chars: BitmapFont.NUMERIC })
  34097. */
  34098. BitmapFont.NUMERIC = [['0', '9']];
  34099. /**
  34100. * This character set is the union of `BitmapFont.ALPHA` and `BitmapFont.NUMERIC`.
  34101. * @type {string[][]}
  34102. */
  34103. BitmapFont.ALPHANUMERIC = [['a', 'z'], ['A', 'Z'], ['0', '9'], ' '];
  34104. /**
  34105. * This character set consists of all the ASCII table.
  34106. * @member {string[][]}
  34107. * @see http://www.asciitable.com/
  34108. */
  34109. BitmapFont.ASCII = [[' ', '~']];
  34110. /**
  34111. * Collection of default options when using `BitmapFont.from`.
  34112. * @property {number} [resolution=1] -
  34113. * @property {number} [textureWidth=512] -
  34114. * @property {number} [textureHeight=512] -
  34115. * @property {number} [padding=4] -
  34116. * @property {string|string[]|string[][]} chars = PIXI.BitmapFont.ALPHANUMERIC
  34117. */
  34118. BitmapFont.defaultOptions = {
  34119. resolution: 1,
  34120. textureWidth: 512,
  34121. textureHeight: 512,
  34122. padding: 4,
  34123. chars: BitmapFont.ALPHANUMERIC,
  34124. };
  34125. /** Collection of available/installed fonts. */
  34126. BitmapFont.available = {};
  34127. return BitmapFont;
  34128. }());
  34129. var msdfFrag = "// Pixi texture info\r\nvarying vec2 vTextureCoord;\r\nuniform sampler2D uSampler;\r\n\r\n// Tint\r\nuniform vec4 uColor;\r\n\r\n// on 2D applications fwidth is screenScale / glyphAtlasScale * distanceFieldRange\r\nuniform float uFWidth;\r\n\r\nvoid main(void) {\r\n\r\n // To stack MSDF and SDF we need a non-pre-multiplied-alpha texture.\r\n vec4 texColor = texture2D(uSampler, vTextureCoord);\r\n\r\n // MSDF\r\n float median = texColor.r + texColor.g + texColor.b -\r\n min(texColor.r, min(texColor.g, texColor.b)) -\r\n max(texColor.r, max(texColor.g, texColor.b));\r\n // SDF\r\n median = min(median, texColor.a);\r\n\r\n float screenPxDistance = uFWidth * (median - 0.5);\r\n float alpha = clamp(screenPxDistance + 0.5, 0.0, 1.0);\r\n if (median < 0.01) {\r\n alpha = 0.0;\r\n } else if (median > 0.99) {\r\n alpha = 1.0;\r\n }\r\n\r\n // NPM Textures, NPM outputs\r\n gl_FragColor = vec4(uColor.rgb, uColor.a * alpha);\r\n\r\n}\r\n";
  34130. var msdfVert = "// Mesh material default fragment\r\nattribute vec2 aVertexPosition;\r\nattribute vec2 aTextureCoord;\r\n\r\nuniform mat3 projectionMatrix;\r\nuniform mat3 translationMatrix;\r\nuniform mat3 uTextureMatrix;\r\n\r\nvarying vec2 vTextureCoord;\r\n\r\nvoid main(void)\r\n{\r\n gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\r\n\r\n vTextureCoord = (uTextureMatrix * vec3(aTextureCoord, 1.0)).xy;\r\n}\r\n";
  34131. // If we ever need more than two pools, please make a Dict or something better.
  34132. var pageMeshDataDefaultPageMeshData = [];
  34133. var pageMeshDataMSDFPageMeshData = [];
  34134. var charRenderDataPool = [];
  34135. /**
  34136. * A BitmapText object will create a line or multiple lines of text using bitmap font.
  34137. *
  34138. * The primary advantage of this class over Text is that all of your textures are pre-generated and loading,
  34139. * meaning that rendering is fast, and changing text has no performance implications.
  34140. *
  34141. * Supporting character sets other than latin, such as CJK languages, may be impractical due to the number of characters.
  34142. *
  34143. * To split a line you can use '\n', '\r' or '\r\n' in your string.
  34144. *
  34145. * PixiJS can auto-generate fonts on-the-fly using BitmapFont or use fnt files provided by:
  34146. * http://www.angelcode.com/products/bmfont/ for Windows or
  34147. * http://www.bmglyph.com/ for Mac.
  34148. *
  34149. * You can also use SDF, MSDF and MTSDF BitmapFonts for vector-like scaling appearance provided by:
  34150. * https://github.com/soimy/msdf-bmfont-xml for SDF and MSDF fnt files or
  34151. * https://github.com/Chlumsky/msdf-atlas-gen for SDF, MSDF and MTSDF json files
  34152. *
  34153. * A BitmapText can only be created when the font is loaded.
  34154. *
  34155. * ```js
  34156. * // in this case the font is in a file called 'desyrel.fnt'
  34157. * let bitmapText = new PIXI.BitmapText("text using a fancy font!", {
  34158. * fontName: "Desyrel",
  34159. * fontSize: 35,
  34160. * align: "right"
  34161. * });
  34162. * ```
  34163. * @memberof PIXI
  34164. */
  34165. var BitmapText = /** @class */ (function (_super) {
  34166. __extends$8(BitmapText, _super);
  34167. /**
  34168. * @param text - A string that you would like the text to display.
  34169. * @param style - The style parameters.
  34170. * @param {string} style.fontName - The installed BitmapFont name.
  34171. * @param {number} [style.fontSize] - The size of the font in pixels, e.g. 24. If undefined,
  34172. *. this will default to the BitmapFont size.
  34173. * @param {string} [style.align='left'] - Alignment for multiline text ('left', 'center', 'right' or 'justify'),
  34174. * does not affect single line text.
  34175. * @param {number} [style.tint=0xFFFFFF] - The tint color.
  34176. * @param {number} [style.letterSpacing=0] - The amount of spacing between letters.
  34177. * @param {number} [style.maxWidth=0] - The max width of the text before line wrapping.
  34178. */
  34179. function BitmapText(text, style) {
  34180. if (style === void 0) { style = {}; }
  34181. var _this = _super.call(this) || this;
  34182. /**
  34183. * Private tracker for the current tint.
  34184. * @private
  34185. */
  34186. _this._tint = 0xFFFFFF;
  34187. // Apply the defaults
  34188. var _a = Object.assign({}, BitmapText.styleDefaults, style), align = _a.align, tint = _a.tint, maxWidth = _a.maxWidth, letterSpacing = _a.letterSpacing, fontName = _a.fontName, fontSize = _a.fontSize;
  34189. if (!BitmapFont.available[fontName]) {
  34190. throw new Error("Missing BitmapFont \"" + fontName + "\"");
  34191. }
  34192. _this._activePagesMeshData = [];
  34193. _this._textWidth = 0;
  34194. _this._textHeight = 0;
  34195. _this._align = align;
  34196. _this._tint = tint;
  34197. _this._font = undefined;
  34198. _this._fontName = fontName;
  34199. _this._fontSize = fontSize;
  34200. _this.text = text;
  34201. _this._maxWidth = maxWidth;
  34202. _this._maxLineHeight = 0;
  34203. _this._letterSpacing = letterSpacing;
  34204. _this._anchor = new ObservablePoint(function () { _this.dirty = true; }, _this, 0, 0);
  34205. _this._roundPixels = settings.ROUND_PIXELS;
  34206. _this.dirty = true;
  34207. _this._resolution = settings.RESOLUTION;
  34208. _this._autoResolution = true;
  34209. _this._textureCache = {};
  34210. return _this;
  34211. }
  34212. /** Renders text and updates it when needed. This should only be called if the BitmapFont is regenerated. */
  34213. BitmapText.prototype.updateText = function () {
  34214. var _a;
  34215. var data = BitmapFont.available[this._fontName];
  34216. var fontSize = this.fontSize;
  34217. var scale = fontSize / data.size;
  34218. var pos = new Point();
  34219. var chars = [];
  34220. var lineWidths = [];
  34221. var lineSpaces = [];
  34222. var text = this._text.replace(/(?:\r\n|\r)/g, '\n') || ' ';
  34223. var charsInput = splitTextToCharacters(text);
  34224. var maxWidth = this._maxWidth * data.size / fontSize;
  34225. var pageMeshDataPool = data.distanceFieldType === 'none'
  34226. ? pageMeshDataDefaultPageMeshData : pageMeshDataMSDFPageMeshData;
  34227. var prevCharCode = null;
  34228. var lastLineWidth = 0;
  34229. var maxLineWidth = 0;
  34230. var line = 0;
  34231. var lastBreakPos = -1;
  34232. var lastBreakWidth = 0;
  34233. var spacesRemoved = 0;
  34234. var maxLineHeight = 0;
  34235. var spaceCount = 0;
  34236. for (var i = 0; i < charsInput.length; i++) {
  34237. var char = charsInput[i];
  34238. var charCode = extractCharCode(char);
  34239. if ((/(?:\s)/).test(char)) {
  34240. lastBreakPos = i;
  34241. lastBreakWidth = lastLineWidth;
  34242. spaceCount++;
  34243. }
  34244. if (char === '\r' || char === '\n') {
  34245. lineWidths.push(lastLineWidth);
  34246. lineSpaces.push(-1);
  34247. maxLineWidth = Math.max(maxLineWidth, lastLineWidth);
  34248. ++line;
  34249. ++spacesRemoved;
  34250. pos.x = 0;
  34251. pos.y += data.lineHeight;
  34252. prevCharCode = null;
  34253. spaceCount = 0;
  34254. continue;
  34255. }
  34256. var charData = data.chars[charCode];
  34257. if (!charData) {
  34258. continue;
  34259. }
  34260. if (prevCharCode && charData.kerning[prevCharCode]) {
  34261. pos.x += charData.kerning[prevCharCode];
  34262. }
  34263. var charRenderData = charRenderDataPool.pop() || {
  34264. texture: Texture.EMPTY,
  34265. line: 0,
  34266. charCode: 0,
  34267. prevSpaces: 0,
  34268. position: new Point(),
  34269. };
  34270. charRenderData.texture = charData.texture;
  34271. charRenderData.line = line;
  34272. charRenderData.charCode = charCode;
  34273. charRenderData.position.x = pos.x + charData.xOffset + (this._letterSpacing / 2);
  34274. charRenderData.position.y = pos.y + charData.yOffset;
  34275. charRenderData.prevSpaces = spaceCount;
  34276. chars.push(charRenderData);
  34277. lastLineWidth = charRenderData.position.x
  34278. + Math.max(charData.xAdvance - charData.xOffset, charData.texture.orig.width);
  34279. pos.x += charData.xAdvance + this._letterSpacing;
  34280. maxLineHeight = Math.max(maxLineHeight, (charData.yOffset + charData.texture.height));
  34281. prevCharCode = charCode;
  34282. if (lastBreakPos !== -1 && maxWidth > 0 && pos.x > maxWidth) {
  34283. ++spacesRemoved;
  34284. removeItems(chars, 1 + lastBreakPos - spacesRemoved, 1 + i - lastBreakPos);
  34285. i = lastBreakPos;
  34286. lastBreakPos = -1;
  34287. lineWidths.push(lastBreakWidth);
  34288. lineSpaces.push(chars.length > 0 ? chars[chars.length - 1].prevSpaces : 0);
  34289. maxLineWidth = Math.max(maxLineWidth, lastBreakWidth);
  34290. line++;
  34291. pos.x = 0;
  34292. pos.y += data.lineHeight;
  34293. prevCharCode = null;
  34294. spaceCount = 0;
  34295. }
  34296. }
  34297. var lastChar = charsInput[charsInput.length - 1];
  34298. if (lastChar !== '\r' && lastChar !== '\n') {
  34299. if ((/(?:\s)/).test(lastChar)) {
  34300. lastLineWidth = lastBreakWidth;
  34301. }
  34302. lineWidths.push(lastLineWidth);
  34303. maxLineWidth = Math.max(maxLineWidth, lastLineWidth);
  34304. lineSpaces.push(-1);
  34305. }
  34306. var lineAlignOffsets = [];
  34307. for (var i = 0; i <= line; i++) {
  34308. var alignOffset = 0;
  34309. if (this._align === 'right') {
  34310. alignOffset = maxLineWidth - lineWidths[i];
  34311. }
  34312. else if (this._align === 'center') {
  34313. alignOffset = (maxLineWidth - lineWidths[i]) / 2;
  34314. }
  34315. else if (this._align === 'justify') {
  34316. alignOffset = lineSpaces[i] < 0 ? 0 : (maxLineWidth - lineWidths[i]) / lineSpaces[i];
  34317. }
  34318. lineAlignOffsets.push(alignOffset);
  34319. }
  34320. var lenChars = chars.length;
  34321. var pagesMeshData = {};
  34322. var newPagesMeshData = [];
  34323. var activePagesMeshData = this._activePagesMeshData;
  34324. pageMeshDataPool.push.apply(pageMeshDataPool, activePagesMeshData);
  34325. for (var i = 0; i < lenChars; i++) {
  34326. var texture = chars[i].texture;
  34327. var baseTextureUid = texture.baseTexture.uid;
  34328. if (!pagesMeshData[baseTextureUid]) {
  34329. var pageMeshData = pageMeshDataPool.pop();
  34330. if (!pageMeshData) {
  34331. var geometry = new MeshGeometry();
  34332. var material = void 0;
  34333. var meshBlendMode = void 0;
  34334. if (data.distanceFieldType === 'none') {
  34335. material = new MeshMaterial(Texture.EMPTY);
  34336. meshBlendMode = BLEND_MODES.NORMAL;
  34337. }
  34338. else {
  34339. material = new MeshMaterial(Texture.EMPTY, { program: Program.from(msdfVert, msdfFrag), uniforms: { uFWidth: 0 } });
  34340. meshBlendMode = BLEND_MODES.NORMAL_NPM;
  34341. }
  34342. var mesh = new Mesh(geometry, material);
  34343. mesh.blendMode = meshBlendMode;
  34344. pageMeshData = {
  34345. index: 0,
  34346. indexCount: 0,
  34347. vertexCount: 0,
  34348. uvsCount: 0,
  34349. total: 0,
  34350. mesh: mesh,
  34351. vertices: null,
  34352. uvs: null,
  34353. indices: null,
  34354. };
  34355. }
  34356. // reset data..
  34357. pageMeshData.index = 0;
  34358. pageMeshData.indexCount = 0;
  34359. pageMeshData.vertexCount = 0;
  34360. pageMeshData.uvsCount = 0;
  34361. pageMeshData.total = 0;
  34362. // TODO need to get page texture here somehow..
  34363. var _textureCache = this._textureCache;
  34364. _textureCache[baseTextureUid] = _textureCache[baseTextureUid] || new Texture(texture.baseTexture);
  34365. pageMeshData.mesh.texture = _textureCache[baseTextureUid];
  34366. pageMeshData.mesh.tint = this._tint;
  34367. newPagesMeshData.push(pageMeshData);
  34368. pagesMeshData[baseTextureUid] = pageMeshData;
  34369. }
  34370. pagesMeshData[baseTextureUid].total++;
  34371. }
  34372. // lets find any previously active pageMeshDatas that are no longer required for
  34373. // the updated text (if any), removed and return them to the pool.
  34374. for (var i = 0; i < activePagesMeshData.length; i++) {
  34375. if (newPagesMeshData.indexOf(activePagesMeshData[i]) === -1) {
  34376. this.removeChild(activePagesMeshData[i].mesh);
  34377. }
  34378. }
  34379. // next lets add any new meshes, that have not yet been added to this BitmapText
  34380. // we only add if its not already a child of this BitmapObject
  34381. for (var i = 0; i < newPagesMeshData.length; i++) {
  34382. if (newPagesMeshData[i].mesh.parent !== this) {
  34383. this.addChild(newPagesMeshData[i].mesh);
  34384. }
  34385. }
  34386. // active page mesh datas are set to be the new pages added.
  34387. this._activePagesMeshData = newPagesMeshData;
  34388. for (var i in pagesMeshData) {
  34389. var pageMeshData = pagesMeshData[i];
  34390. var total = pageMeshData.total;
  34391. // lets only allocate new buffers if we can fit the new text in the current ones..
  34392. // unless that is, we will be batching. Currently batching dose not respect the size property of mesh
  34393. if (!(((_a = pageMeshData.indices) === null || _a === void 0 ? void 0 : _a.length) > 6 * total) || pageMeshData.vertices.length < Mesh.BATCHABLE_SIZE * 2) {
  34394. pageMeshData.vertices = new Float32Array(4 * 2 * total);
  34395. pageMeshData.uvs = new Float32Array(4 * 2 * total);
  34396. pageMeshData.indices = new Uint16Array(6 * total);
  34397. }
  34398. else {
  34399. var total_1 = pageMeshData.total;
  34400. var vertices = pageMeshData.vertices;
  34401. // Clear the garbage at the end of the vertices buffer. This will prevent the bounds miscalculation.
  34402. for (var i_1 = total_1 * 4 * 2; i_1 < vertices.length; i_1++) {
  34403. vertices[i_1] = 0;
  34404. }
  34405. }
  34406. // as a buffer maybe bigger than the current word, we set the size of the meshMaterial
  34407. // to match the number of letters needed
  34408. pageMeshData.mesh.size = 6 * total;
  34409. }
  34410. for (var i = 0; i < lenChars; i++) {
  34411. var char = chars[i];
  34412. var offset = char.position.x + (lineAlignOffsets[char.line] * (this._align === 'justify' ? char.prevSpaces : 1));
  34413. if (this._roundPixels) {
  34414. offset = Math.round(offset);
  34415. }
  34416. var xPos = offset * scale;
  34417. var yPos = char.position.y * scale;
  34418. var texture = char.texture;
  34419. var pageMesh = pagesMeshData[texture.baseTexture.uid];
  34420. var textureFrame = texture.frame;
  34421. var textureUvs = texture._uvs;
  34422. var index = pageMesh.index++;
  34423. pageMesh.indices[(index * 6) + 0] = 0 + (index * 4);
  34424. pageMesh.indices[(index * 6) + 1] = 1 + (index * 4);
  34425. pageMesh.indices[(index * 6) + 2] = 2 + (index * 4);
  34426. pageMesh.indices[(index * 6) + 3] = 0 + (index * 4);
  34427. pageMesh.indices[(index * 6) + 4] = 2 + (index * 4);
  34428. pageMesh.indices[(index * 6) + 5] = 3 + (index * 4);
  34429. pageMesh.vertices[(index * 8) + 0] = xPos;
  34430. pageMesh.vertices[(index * 8) + 1] = yPos;
  34431. pageMesh.vertices[(index * 8) + 2] = xPos + (textureFrame.width * scale);
  34432. pageMesh.vertices[(index * 8) + 3] = yPos;
  34433. pageMesh.vertices[(index * 8) + 4] = xPos + (textureFrame.width * scale);
  34434. pageMesh.vertices[(index * 8) + 5] = yPos + (textureFrame.height * scale);
  34435. pageMesh.vertices[(index * 8) + 6] = xPos;
  34436. pageMesh.vertices[(index * 8) + 7] = yPos + (textureFrame.height * scale);
  34437. pageMesh.uvs[(index * 8) + 0] = textureUvs.x0;
  34438. pageMesh.uvs[(index * 8) + 1] = textureUvs.y0;
  34439. pageMesh.uvs[(index * 8) + 2] = textureUvs.x1;
  34440. pageMesh.uvs[(index * 8) + 3] = textureUvs.y1;
  34441. pageMesh.uvs[(index * 8) + 4] = textureUvs.x2;
  34442. pageMesh.uvs[(index * 8) + 5] = textureUvs.y2;
  34443. pageMesh.uvs[(index * 8) + 6] = textureUvs.x3;
  34444. pageMesh.uvs[(index * 8) + 7] = textureUvs.y3;
  34445. }
  34446. this._textWidth = maxLineWidth * scale;
  34447. this._textHeight = (pos.y + data.lineHeight) * scale;
  34448. for (var i in pagesMeshData) {
  34449. var pageMeshData = pagesMeshData[i];
  34450. // apply anchor
  34451. if (this.anchor.x !== 0 || this.anchor.y !== 0) {
  34452. var vertexCount = 0;
  34453. var anchorOffsetX = this._textWidth * this.anchor.x;
  34454. var anchorOffsetY = this._textHeight * this.anchor.y;
  34455. for (var i_2 = 0; i_2 < pageMeshData.total; i_2++) {
  34456. pageMeshData.vertices[vertexCount++] -= anchorOffsetX;
  34457. pageMeshData.vertices[vertexCount++] -= anchorOffsetY;
  34458. pageMeshData.vertices[vertexCount++] -= anchorOffsetX;
  34459. pageMeshData.vertices[vertexCount++] -= anchorOffsetY;
  34460. pageMeshData.vertices[vertexCount++] -= anchorOffsetX;
  34461. pageMeshData.vertices[vertexCount++] -= anchorOffsetY;
  34462. pageMeshData.vertices[vertexCount++] -= anchorOffsetX;
  34463. pageMeshData.vertices[vertexCount++] -= anchorOffsetY;
  34464. }
  34465. }
  34466. this._maxLineHeight = maxLineHeight * scale;
  34467. var vertexBuffer = pageMeshData.mesh.geometry.getBuffer('aVertexPosition');
  34468. var textureBuffer = pageMeshData.mesh.geometry.getBuffer('aTextureCoord');
  34469. var indexBuffer = pageMeshData.mesh.geometry.getIndex();
  34470. vertexBuffer.data = pageMeshData.vertices;
  34471. textureBuffer.data = pageMeshData.uvs;
  34472. indexBuffer.data = pageMeshData.indices;
  34473. vertexBuffer.update();
  34474. textureBuffer.update();
  34475. indexBuffer.update();
  34476. }
  34477. for (var i = 0; i < chars.length; i++) {
  34478. charRenderDataPool.push(chars[i]);
  34479. }
  34480. this._font = data;
  34481. this.dirty = false;
  34482. };
  34483. BitmapText.prototype.updateTransform = function () {
  34484. this.validate();
  34485. this.containerUpdateTransform();
  34486. };
  34487. BitmapText.prototype._render = function (renderer) {
  34488. if (this._autoResolution && this._resolution !== renderer.resolution) {
  34489. this._resolution = renderer.resolution;
  34490. this.dirty = true;
  34491. }
  34492. // Update the uniform
  34493. var _a = BitmapFont.available[this._fontName], distanceFieldRange = _a.distanceFieldRange, distanceFieldType = _a.distanceFieldType, size = _a.size;
  34494. if (distanceFieldType !== 'none') {
  34495. // Inject the shader code with the correct value
  34496. var _b = this.worldTransform, a = _b.a, b = _b.b, c = _b.c, d = _b.d;
  34497. var dx = Math.sqrt((a * a) + (b * b));
  34498. var dy = Math.sqrt((c * c) + (d * d));
  34499. var worldScale = (Math.abs(dx) + Math.abs(dy)) / 2;
  34500. var fontScale = this.fontSize / size;
  34501. for (var _i = 0, _c = this._activePagesMeshData; _i < _c.length; _i++) {
  34502. var mesh = _c[_i];
  34503. mesh.mesh.shader.uniforms.uFWidth = worldScale * distanceFieldRange * fontScale * this._resolution;
  34504. }
  34505. }
  34506. _super.prototype._render.call(this, renderer);
  34507. };
  34508. /**
  34509. * Validates text before calling parent's getLocalBounds
  34510. * @returns - The rectangular bounding area
  34511. */
  34512. BitmapText.prototype.getLocalBounds = function () {
  34513. this.validate();
  34514. return _super.prototype.getLocalBounds.call(this);
  34515. };
  34516. /**
  34517. * Updates text when needed
  34518. * @private
  34519. */
  34520. BitmapText.prototype.validate = function () {
  34521. var font = BitmapFont.available[this._fontName];
  34522. if (!font) {
  34523. throw new Error("Missing BitmapFont \"" + this._fontName + "\"");
  34524. }
  34525. if (this._font !== font) {
  34526. this.dirty = true;
  34527. }
  34528. if (this.dirty) {
  34529. this.updateText();
  34530. }
  34531. };
  34532. Object.defineProperty(BitmapText.prototype, "tint", {
  34533. /**
  34534. * The tint of the BitmapText object.
  34535. * @default 0xffffff
  34536. */
  34537. get: function () {
  34538. return this._tint;
  34539. },
  34540. set: function (value) {
  34541. if (this._tint === value)
  34542. { return; }
  34543. this._tint = value;
  34544. for (var i = 0; i < this._activePagesMeshData.length; i++) {
  34545. this._activePagesMeshData[i].mesh.tint = value;
  34546. }
  34547. },
  34548. enumerable: false,
  34549. configurable: true
  34550. });
  34551. Object.defineProperty(BitmapText.prototype, "align", {
  34552. /**
  34553. * The alignment of the BitmapText object.
  34554. * @member {string}
  34555. * @default 'left'
  34556. */
  34557. get: function () {
  34558. return this._align;
  34559. },
  34560. set: function (value) {
  34561. if (this._align !== value) {
  34562. this._align = value;
  34563. this.dirty = true;
  34564. }
  34565. },
  34566. enumerable: false,
  34567. configurable: true
  34568. });
  34569. Object.defineProperty(BitmapText.prototype, "fontName", {
  34570. /** The name of the BitmapFont. */
  34571. get: function () {
  34572. return this._fontName;
  34573. },
  34574. set: function (value) {
  34575. if (!BitmapFont.available[value]) {
  34576. throw new Error("Missing BitmapFont \"" + value + "\"");
  34577. }
  34578. if (this._fontName !== value) {
  34579. this._fontName = value;
  34580. this.dirty = true;
  34581. }
  34582. },
  34583. enumerable: false,
  34584. configurable: true
  34585. });
  34586. Object.defineProperty(BitmapText.prototype, "fontSize", {
  34587. /** The size of the font to display. */
  34588. get: function () {
  34589. var _a;
  34590. return (_a = this._fontSize) !== null && _a !== void 0 ? _a : BitmapFont.available[this._fontName].size;
  34591. },
  34592. set: function (value) {
  34593. if (this._fontSize !== value) {
  34594. this._fontSize = value;
  34595. this.dirty = true;
  34596. }
  34597. },
  34598. enumerable: false,
  34599. configurable: true
  34600. });
  34601. Object.defineProperty(BitmapText.prototype, "anchor", {
  34602. /**
  34603. * The anchor sets the origin point of the text.
  34604. *
  34605. * The default is `(0,0)`, this means the text's origin is the top left.
  34606. *
  34607. * Setting the anchor to `(0.5,0.5)` means the text's origin is centered.
  34608. *
  34609. * Setting the anchor to `(1,1)` would mean the text's origin point will be the bottom right corner.
  34610. */
  34611. get: function () {
  34612. return this._anchor;
  34613. },
  34614. set: function (value) {
  34615. if (typeof value === 'number') {
  34616. this._anchor.set(value);
  34617. }
  34618. else {
  34619. this._anchor.copyFrom(value);
  34620. }
  34621. },
  34622. enumerable: false,
  34623. configurable: true
  34624. });
  34625. Object.defineProperty(BitmapText.prototype, "text", {
  34626. /** The text of the BitmapText object. */
  34627. get: function () {
  34628. return this._text;
  34629. },
  34630. set: function (text) {
  34631. text = String(text === null || text === undefined ? '' : text);
  34632. if (this._text === text) {
  34633. return;
  34634. }
  34635. this._text = text;
  34636. this.dirty = true;
  34637. },
  34638. enumerable: false,
  34639. configurable: true
  34640. });
  34641. Object.defineProperty(BitmapText.prototype, "maxWidth", {
  34642. /**
  34643. * The max width of this bitmap text in pixels. If the text provided is longer than the
  34644. * value provided, line breaks will be automatically inserted in the last whitespace.
  34645. * Disable by setting the value to 0.
  34646. */
  34647. get: function () {
  34648. return this._maxWidth;
  34649. },
  34650. set: function (value) {
  34651. if (this._maxWidth === value) {
  34652. return;
  34653. }
  34654. this._maxWidth = value;
  34655. this.dirty = true;
  34656. },
  34657. enumerable: false,
  34658. configurable: true
  34659. });
  34660. Object.defineProperty(BitmapText.prototype, "maxLineHeight", {
  34661. /**
  34662. * The max line height. This is useful when trying to use the total height of the Text,
  34663. * i.e. when trying to vertically align.
  34664. * @readonly
  34665. */
  34666. get: function () {
  34667. this.validate();
  34668. return this._maxLineHeight;
  34669. },
  34670. enumerable: false,
  34671. configurable: true
  34672. });
  34673. Object.defineProperty(BitmapText.prototype, "textWidth", {
  34674. /**
  34675. * The width of the overall text, different from fontSize,
  34676. * which is defined in the style object.
  34677. * @readonly
  34678. */
  34679. get: function () {
  34680. this.validate();
  34681. return this._textWidth;
  34682. },
  34683. enumerable: false,
  34684. configurable: true
  34685. });
  34686. Object.defineProperty(BitmapText.prototype, "letterSpacing", {
  34687. /** Additional space between characters. */
  34688. get: function () {
  34689. return this._letterSpacing;
  34690. },
  34691. set: function (value) {
  34692. if (this._letterSpacing !== value) {
  34693. this._letterSpacing = value;
  34694. this.dirty = true;
  34695. }
  34696. },
  34697. enumerable: false,
  34698. configurable: true
  34699. });
  34700. Object.defineProperty(BitmapText.prototype, "roundPixels", {
  34701. /**
  34702. * If true PixiJS will Math.floor() x/y values when rendering, stopping pixel interpolation.
  34703. * Advantages can include sharper image quality (like text) and faster rendering on canvas.
  34704. * The main disadvantage is movement of objects may appear less smooth.
  34705. * To set the global default, change {@link PIXI.settings.ROUND_PIXELS}
  34706. * @default PIXI.settings.ROUND_PIXELS
  34707. */
  34708. get: function () {
  34709. return this._roundPixels;
  34710. },
  34711. set: function (value) {
  34712. if (value !== this._roundPixels) {
  34713. this._roundPixels = value;
  34714. this.dirty = true;
  34715. }
  34716. },
  34717. enumerable: false,
  34718. configurable: true
  34719. });
  34720. Object.defineProperty(BitmapText.prototype, "textHeight", {
  34721. /**
  34722. * The height of the overall text, different from fontSize,
  34723. * which is defined in the style object.
  34724. * @readonly
  34725. */
  34726. get: function () {
  34727. this.validate();
  34728. return this._textHeight;
  34729. },
  34730. enumerable: false,
  34731. configurable: true
  34732. });
  34733. Object.defineProperty(BitmapText.prototype, "resolution", {
  34734. /**
  34735. * The resolution / device pixel ratio of the canvas.
  34736. *
  34737. * This is set to automatically match the renderer resolution by default, but can be overridden by setting manually.
  34738. * @default 1
  34739. */
  34740. get: function () {
  34741. return this._resolution;
  34742. },
  34743. set: function (value) {
  34744. this._autoResolution = false;
  34745. if (this._resolution === value) {
  34746. return;
  34747. }
  34748. this._resolution = value;
  34749. this.dirty = true;
  34750. },
  34751. enumerable: false,
  34752. configurable: true
  34753. });
  34754. BitmapText.prototype.destroy = function (options) {
  34755. var _textureCache = this._textureCache;
  34756. var data = BitmapFont.available[this._fontName];
  34757. var pageMeshDataPool = data.distanceFieldType === 'none'
  34758. ? pageMeshDataDefaultPageMeshData : pageMeshDataMSDFPageMeshData;
  34759. pageMeshDataPool.push.apply(pageMeshDataPool, this._activePagesMeshData);
  34760. for (var _i = 0, _a = this._activePagesMeshData; _i < _a.length; _i++) {
  34761. var pageMeshData = _a[_i];
  34762. this.removeChild(pageMeshData.mesh);
  34763. }
  34764. this._activePagesMeshData = [];
  34765. // Release references to any cached textures in page pool
  34766. pageMeshDataPool
  34767. .filter(function (page) { return _textureCache[page.mesh.texture.baseTexture.uid]; })
  34768. .forEach(function (page) {
  34769. page.mesh.texture = Texture.EMPTY;
  34770. });
  34771. for (var id in _textureCache) {
  34772. var texture = _textureCache[id];
  34773. texture.destroy();
  34774. delete _textureCache[id];
  34775. }
  34776. this._font = null;
  34777. this._textureCache = null;
  34778. _super.prototype.destroy.call(this, options);
  34779. };
  34780. BitmapText.styleDefaults = {
  34781. align: 'left',
  34782. tint: 0xFFFFFF,
  34783. maxWidth: 0,
  34784. letterSpacing: 0,
  34785. };
  34786. return BitmapText;
  34787. }(Container));
  34788. /**
  34789. * {@link PIXI.Loader Loader} middleware for loading
  34790. * bitmap-based fonts suitable for using with {@link PIXI.BitmapText}.
  34791. * @memberof PIXI
  34792. */
  34793. var BitmapFontLoader = /** @class */ (function () {
  34794. function BitmapFontLoader() {
  34795. }
  34796. /**
  34797. * Called when the plugin is installed.
  34798. * @see PIXI.extensions.add
  34799. */
  34800. BitmapFontLoader.add = function () {
  34801. LoaderResource.setExtensionXhrType('fnt', LoaderResource.XHR_RESPONSE_TYPE.TEXT);
  34802. };
  34803. /**
  34804. * Called after a resource is loaded.
  34805. * @see PIXI.Loader.loaderMiddleware
  34806. * @param this
  34807. * @param {PIXI.LoaderResource} resource
  34808. * @param {Function} next
  34809. */
  34810. BitmapFontLoader.use = function (resource, next) {
  34811. var format = autoDetectFormat(resource.data);
  34812. // Resource was not recognised as any of the expected font data format
  34813. if (!format) {
  34814. next();
  34815. return;
  34816. }
  34817. var baseUrl = BitmapFontLoader.getBaseUrl(this, resource);
  34818. var data = format.parse(resource.data);
  34819. var textures = {};
  34820. // Handle completed, when the number of textures
  34821. // load is the same number as references in the fnt file
  34822. var completed = function (page) {
  34823. textures[page.metadata.pageFile] = page.texture;
  34824. if (Object.keys(textures).length === data.page.length) {
  34825. resource.bitmapFont = BitmapFont.install(data, textures, true);
  34826. next();
  34827. }
  34828. };
  34829. for (var i = 0; i < data.page.length; ++i) {
  34830. var pageFile = data.page[i].file;
  34831. var url = baseUrl + pageFile;
  34832. var exists = false;
  34833. // incase the image is loaded outside
  34834. // using the same loader, resource will be available
  34835. for (var name in this.resources) {
  34836. var bitmapResource = this.resources[name];
  34837. if (bitmapResource.url === url) {
  34838. bitmapResource.metadata.pageFile = pageFile;
  34839. if (bitmapResource.texture) {
  34840. completed(bitmapResource);
  34841. }
  34842. else {
  34843. bitmapResource.onAfterMiddleware.add(completed);
  34844. }
  34845. exists = true;
  34846. break;
  34847. }
  34848. }
  34849. // texture is not loaded, we'll attempt to add
  34850. // it to the load and add the texture to the list
  34851. if (!exists) {
  34852. // Standard loading options for images
  34853. var options = {
  34854. crossOrigin: resource.crossOrigin,
  34855. loadType: LoaderResource.LOAD_TYPE.IMAGE,
  34856. metadata: Object.assign({ pageFile: pageFile }, resource.metadata.imageMetadata),
  34857. parentResource: resource,
  34858. };
  34859. this.add(url, options, completed);
  34860. }
  34861. }
  34862. };
  34863. /**
  34864. * Get folder path from a resource.
  34865. * @param loader
  34866. * @param resource
  34867. */
  34868. BitmapFontLoader.getBaseUrl = function (loader, resource) {
  34869. var resUrl = !resource.isDataUrl ? BitmapFontLoader.dirname(resource.url) : '';
  34870. if (resource.isDataUrl) {
  34871. if (resUrl === '.') {
  34872. resUrl = '';
  34873. }
  34874. if (loader.baseUrl && resUrl) {
  34875. // if baseurl has a trailing slash then add one to resUrl so the replace works below
  34876. if (loader.baseUrl.charAt(loader.baseUrl.length - 1) === '/') {
  34877. resUrl += '/';
  34878. }
  34879. }
  34880. }
  34881. // remove baseUrl from resUrl
  34882. resUrl = resUrl.replace(loader.baseUrl, '');
  34883. // if there is an resUrl now, it needs a trailing slash. Ensure that it does if the string isn't empty.
  34884. if (resUrl && resUrl.charAt(resUrl.length - 1) !== '/') {
  34885. resUrl += '/';
  34886. }
  34887. return resUrl;
  34888. };
  34889. /**
  34890. * Replacement for NodeJS's path.dirname
  34891. * @param {string} url - Path to get directory for
  34892. */
  34893. BitmapFontLoader.dirname = function (url) {
  34894. var dir = url
  34895. .replace(/\\/g, '/') // convert windows notation to UNIX notation, URL-safe because it's a forbidden character
  34896. .replace(/\/$/, '') // replace trailing slash
  34897. .replace(/\/[^\/]*$/, ''); // remove everything after the last
  34898. // File request is relative, use current directory
  34899. if (dir === url) {
  34900. return '.';
  34901. }
  34902. // Started with a slash
  34903. else if (dir === '') {
  34904. return '/';
  34905. }
  34906. return dir;
  34907. };
  34908. /** @ignore */
  34909. BitmapFontLoader.extension = ExtensionType.Loader;
  34910. return BitmapFontLoader;
  34911. }());
  34912. /*!
  34913. * @pixi/filter-alpha - v6.5.10
  34914. * Compiled Thu, 06 Jul 2023 15:25:11 UTC
  34915. *
  34916. * @pixi/filter-alpha is licensed under the MIT License.
  34917. * http://www.opensource.org/licenses/mit-license
  34918. */
  34919. /*! *****************************************************************************
  34920. Copyright (c) Microsoft Corporation.
  34921. Permission to use, copy, modify, and/or distribute this software for any
  34922. purpose with or without fee is hereby granted.
  34923. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  34924. REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
  34925. AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  34926. INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
  34927. LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
  34928. OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
  34929. PERFORMANCE OF THIS SOFTWARE.
  34930. ***************************************************************************** */
  34931. /* global Reflect, Promise */
  34932. var extendStatics$7 = function(d, b) {
  34933. extendStatics$7 = Object.setPrototypeOf ||
  34934. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  34935. function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } };
  34936. return extendStatics$7(d, b);
  34937. };
  34938. function __extends$7(d, b) {
  34939. extendStatics$7(d, b);
  34940. function __() { this.constructor = d; }
  34941. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  34942. }
  34943. var fragment$4 = "varying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform float uAlpha;\n\nvoid main(void)\n{\n gl_FragColor = texture2D(uSampler, vTextureCoord) * uAlpha;\n}\n";
  34944. /**
  34945. * Simplest filter - applies alpha.
  34946. *
  34947. * Use this instead of Container's alpha property to avoid visual layering of individual elements.
  34948. * AlphaFilter applies alpha evenly across the entire display object and any opaque elements it contains.
  34949. * If elements are not opaque, they will blend with each other anyway.
  34950. *
  34951. * Very handy if you want to use common features of all filters:
  34952. *
  34953. * 1. Assign a blendMode to this filter, blend all elements inside display object with background.
  34954. *
  34955. * 2. To use clipping in display coordinates, assign a filterArea to the same container that has this filter.
  34956. * @memberof PIXI.filters
  34957. */
  34958. var AlphaFilter = /** @class */ (function (_super) {
  34959. __extends$7(AlphaFilter, _super);
  34960. /**
  34961. * @param alpha - Amount of alpha from 0 to 1, where 0 is transparent
  34962. */
  34963. function AlphaFilter(alpha) {
  34964. if (alpha === void 0) { alpha = 1.0; }
  34965. var _this = _super.call(this, defaultVertex$1, fragment$4, { uAlpha: 1 }) || this;
  34966. _this.alpha = alpha;
  34967. return _this;
  34968. }
  34969. Object.defineProperty(AlphaFilter.prototype, "alpha", {
  34970. /**
  34971. * Coefficient for alpha multiplication
  34972. * @default 1
  34973. */
  34974. get: function () {
  34975. return this.uniforms.uAlpha;
  34976. },
  34977. set: function (value) {
  34978. this.uniforms.uAlpha = value;
  34979. },
  34980. enumerable: false,
  34981. configurable: true
  34982. });
  34983. return AlphaFilter;
  34984. }(Filter));
  34985. /*!
  34986. * @pixi/filter-blur - v6.5.10
  34987. * Compiled Thu, 06 Jul 2023 15:25:11 UTC
  34988. *
  34989. * @pixi/filter-blur is licensed under the MIT License.
  34990. * http://www.opensource.org/licenses/mit-license
  34991. */
  34992. /*! *****************************************************************************
  34993. Copyright (c) Microsoft Corporation.
  34994. Permission to use, copy, modify, and/or distribute this software for any
  34995. purpose with or without fee is hereby granted.
  34996. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  34997. REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
  34998. AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  34999. INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
  35000. LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
  35001. OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
  35002. PERFORMANCE OF THIS SOFTWARE.
  35003. ***************************************************************************** */
  35004. /* global Reflect, Promise */
  35005. var extendStatics$6 = function(d, b) {
  35006. extendStatics$6 = Object.setPrototypeOf ||
  35007. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  35008. function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } };
  35009. return extendStatics$6(d, b);
  35010. };
  35011. function __extends$6(d, b) {
  35012. extendStatics$6(d, b);
  35013. function __() { this.constructor = d; }
  35014. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  35015. }
  35016. var vertTemplate = "\n attribute vec2 aVertexPosition;\n\n uniform mat3 projectionMatrix;\n\n uniform float strength;\n\n varying vec2 vBlurTexCoords[%size%];\n\n uniform vec4 inputSize;\n uniform vec4 outputFrame;\n\n vec4 filterVertexPosition( void )\n {\n vec2 position = aVertexPosition * max(outputFrame.zw, vec2(0.)) + outputFrame.xy;\n\n return vec4((projectionMatrix * vec3(position, 1.0)).xy, 0.0, 1.0);\n }\n\n vec2 filterTextureCoord( void )\n {\n return aVertexPosition * (outputFrame.zw * inputSize.zw);\n }\n\n void main(void)\n {\n gl_Position = filterVertexPosition();\n\n vec2 textureCoord = filterTextureCoord();\n %blur%\n }";
  35017. function generateBlurVertSource(kernelSize, x) {
  35018. var halfLength = Math.ceil(kernelSize / 2);
  35019. var vertSource = vertTemplate;
  35020. var blurLoop = '';
  35021. var template;
  35022. if (x) {
  35023. template = 'vBlurTexCoords[%index%] = textureCoord + vec2(%sampleIndex% * strength, 0.0);';
  35024. }
  35025. else {
  35026. template = 'vBlurTexCoords[%index%] = textureCoord + vec2(0.0, %sampleIndex% * strength);';
  35027. }
  35028. for (var i = 0; i < kernelSize; i++) {
  35029. var blur = template.replace('%index%', i.toString());
  35030. blur = blur.replace('%sampleIndex%', i - (halfLength - 1) + ".0");
  35031. blurLoop += blur;
  35032. blurLoop += '\n';
  35033. }
  35034. vertSource = vertSource.replace('%blur%', blurLoop);
  35035. vertSource = vertSource.replace('%size%', kernelSize.toString());
  35036. return vertSource;
  35037. }
  35038. var GAUSSIAN_VALUES = {
  35039. 5: [0.153388, 0.221461, 0.250301],
  35040. 7: [0.071303, 0.131514, 0.189879, 0.214607],
  35041. 9: [0.028532, 0.067234, 0.124009, 0.179044, 0.20236],
  35042. 11: [0.0093, 0.028002, 0.065984, 0.121703, 0.175713, 0.198596],
  35043. 13: [0.002406, 0.009255, 0.027867, 0.065666, 0.121117, 0.174868, 0.197641],
  35044. 15: [0.000489, 0.002403, 0.009246, 0.02784, 0.065602, 0.120999, 0.174697, 0.197448],
  35045. };
  35046. var fragTemplate = [
  35047. 'varying vec2 vBlurTexCoords[%size%];',
  35048. 'uniform sampler2D uSampler;',
  35049. 'void main(void)',
  35050. '{',
  35051. ' gl_FragColor = vec4(0.0);',
  35052. ' %blur%',
  35053. '}' ].join('\n');
  35054. function generateBlurFragSource(kernelSize) {
  35055. var kernel = GAUSSIAN_VALUES[kernelSize];
  35056. var halfLength = kernel.length;
  35057. var fragSource = fragTemplate;
  35058. var blurLoop = '';
  35059. var template = 'gl_FragColor += texture2D(uSampler, vBlurTexCoords[%index%]) * %value%;';
  35060. var value;
  35061. for (var i = 0; i < kernelSize; i++) {
  35062. var blur = template.replace('%index%', i.toString());
  35063. value = i;
  35064. if (i >= halfLength) {
  35065. value = kernelSize - i - 1;
  35066. }
  35067. blur = blur.replace('%value%', kernel[value].toString());
  35068. blurLoop += blur;
  35069. blurLoop += '\n';
  35070. }
  35071. fragSource = fragSource.replace('%blur%', blurLoop);
  35072. fragSource = fragSource.replace('%size%', kernelSize.toString());
  35073. return fragSource;
  35074. }
  35075. /**
  35076. * The BlurFilterPass applies a horizontal or vertical Gaussian blur to an object.
  35077. * @memberof PIXI.filters
  35078. */
  35079. var BlurFilterPass = /** @class */ (function (_super) {
  35080. __extends$6(BlurFilterPass, _super);
  35081. /**
  35082. * @param horizontal - Do pass along the x-axis (`true`) or y-axis (`false`).
  35083. * @param strength - The strength of the blur filter.
  35084. * @param quality - The quality of the blur filter.
  35085. * @param resolution - The resolution of the blur filter.
  35086. * @param kernelSize - The kernelSize of the blur filter.Options: 5, 7, 9, 11, 13, 15.
  35087. */
  35088. function BlurFilterPass(horizontal, strength, quality, resolution, kernelSize) {
  35089. if (strength === void 0) { strength = 8; }
  35090. if (quality === void 0) { quality = 4; }
  35091. if (resolution === void 0) { resolution = settings.FILTER_RESOLUTION; }
  35092. if (kernelSize === void 0) { kernelSize = 5; }
  35093. var _this = this;
  35094. var vertSrc = generateBlurVertSource(kernelSize, horizontal);
  35095. var fragSrc = generateBlurFragSource(kernelSize);
  35096. _this = _super.call(this,
  35097. // vertex shader
  35098. vertSrc,
  35099. // fragment shader
  35100. fragSrc) || this;
  35101. _this.horizontal = horizontal;
  35102. _this.resolution = resolution;
  35103. _this._quality = 0;
  35104. _this.quality = quality;
  35105. _this.blur = strength;
  35106. return _this;
  35107. }
  35108. /**
  35109. * Applies the filter.
  35110. * @param filterManager - The manager.
  35111. * @param input - The input target.
  35112. * @param output - The output target.
  35113. * @param clearMode - How to clear
  35114. */
  35115. BlurFilterPass.prototype.apply = function (filterManager, input, output, clearMode) {
  35116. if (output) {
  35117. if (this.horizontal) {
  35118. this.uniforms.strength = (1 / output.width) * (output.width / input.width);
  35119. }
  35120. else {
  35121. this.uniforms.strength = (1 / output.height) * (output.height / input.height);
  35122. }
  35123. }
  35124. else {
  35125. if (this.horizontal) // eslint-disable-line
  35126. {
  35127. this.uniforms.strength = (1 / filterManager.renderer.width) * (filterManager.renderer.width / input.width);
  35128. }
  35129. else {
  35130. this.uniforms.strength = (1 / filterManager.renderer.height) * (filterManager.renderer.height / input.height); // eslint-disable-line
  35131. }
  35132. }
  35133. // screen space!
  35134. this.uniforms.strength *= this.strength;
  35135. this.uniforms.strength /= this.passes;
  35136. if (this.passes === 1) {
  35137. filterManager.applyFilter(this, input, output, clearMode);
  35138. }
  35139. else {
  35140. var renderTarget = filterManager.getFilterTexture();
  35141. var renderer = filterManager.renderer;
  35142. var flip = input;
  35143. var flop = renderTarget;
  35144. this.state.blend = false;
  35145. filterManager.applyFilter(this, flip, flop, CLEAR_MODES.CLEAR);
  35146. for (var i = 1; i < this.passes - 1; i++) {
  35147. filterManager.bindAndClear(flip, CLEAR_MODES.BLIT);
  35148. this.uniforms.uSampler = flop;
  35149. var temp = flop;
  35150. flop = flip;
  35151. flip = temp;
  35152. renderer.shader.bind(this);
  35153. renderer.geometry.draw(5);
  35154. }
  35155. this.state.blend = true;
  35156. filterManager.applyFilter(this, flop, output, clearMode);
  35157. filterManager.returnFilterTexture(renderTarget);
  35158. }
  35159. };
  35160. Object.defineProperty(BlurFilterPass.prototype, "blur", {
  35161. /**
  35162. * Sets the strength of both the blur.
  35163. * @default 16
  35164. */
  35165. get: function () {
  35166. return this.strength;
  35167. },
  35168. set: function (value) {
  35169. this.padding = 1 + (Math.abs(value) * 2);
  35170. this.strength = value;
  35171. },
  35172. enumerable: false,
  35173. configurable: true
  35174. });
  35175. Object.defineProperty(BlurFilterPass.prototype, "quality", {
  35176. /**
  35177. * Sets the quality of the blur by modifying the number of passes. More passes means higher
  35178. * quality bluring but the lower the performance.
  35179. * @default 4
  35180. */
  35181. get: function () {
  35182. return this._quality;
  35183. },
  35184. set: function (value) {
  35185. this._quality = value;
  35186. this.passes = value;
  35187. },
  35188. enumerable: false,
  35189. configurable: true
  35190. });
  35191. return BlurFilterPass;
  35192. }(Filter));
  35193. /**
  35194. * The BlurFilter applies a Gaussian blur to an object.
  35195. *
  35196. * The strength of the blur can be set for the x-axis and y-axis separately.
  35197. * @memberof PIXI.filters
  35198. */
  35199. var BlurFilter = /** @class */ (function (_super) {
  35200. __extends$6(BlurFilter, _super);
  35201. /**
  35202. * @param strength - The strength of the blur filter.
  35203. * @param quality - The quality of the blur filter.
  35204. * @param [resolution=PIXI.settings.FILTER_RESOLUTION] - The resolution of the blur filter.
  35205. * @param kernelSize - The kernelSize of the blur filter.Options: 5, 7, 9, 11, 13, 15.
  35206. */
  35207. function BlurFilter(strength, quality, resolution, kernelSize) {
  35208. if (strength === void 0) { strength = 8; }
  35209. if (quality === void 0) { quality = 4; }
  35210. if (resolution === void 0) { resolution = settings.FILTER_RESOLUTION; }
  35211. if (kernelSize === void 0) { kernelSize = 5; }
  35212. var _this = _super.call(this) || this;
  35213. _this.blurXFilter = new BlurFilterPass(true, strength, quality, resolution, kernelSize);
  35214. _this.blurYFilter = new BlurFilterPass(false, strength, quality, resolution, kernelSize);
  35215. _this.resolution = resolution;
  35216. _this.quality = quality;
  35217. _this.blur = strength;
  35218. _this.repeatEdgePixels = false;
  35219. return _this;
  35220. }
  35221. /**
  35222. * Applies the filter.
  35223. * @param filterManager - The manager.
  35224. * @param input - The input target.
  35225. * @param output - The output target.
  35226. * @param clearMode - How to clear
  35227. */
  35228. BlurFilter.prototype.apply = function (filterManager, input, output, clearMode) {
  35229. var xStrength = Math.abs(this.blurXFilter.strength);
  35230. var yStrength = Math.abs(this.blurYFilter.strength);
  35231. if (xStrength && yStrength) {
  35232. var renderTarget = filterManager.getFilterTexture();
  35233. this.blurXFilter.apply(filterManager, input, renderTarget, CLEAR_MODES.CLEAR);
  35234. this.blurYFilter.apply(filterManager, renderTarget, output, clearMode);
  35235. filterManager.returnFilterTexture(renderTarget);
  35236. }
  35237. else if (yStrength) {
  35238. this.blurYFilter.apply(filterManager, input, output, clearMode);
  35239. }
  35240. else {
  35241. this.blurXFilter.apply(filterManager, input, output, clearMode);
  35242. }
  35243. };
  35244. BlurFilter.prototype.updatePadding = function () {
  35245. if (this._repeatEdgePixels) {
  35246. this.padding = 0;
  35247. }
  35248. else {
  35249. this.padding = Math.max(Math.abs(this.blurXFilter.strength), Math.abs(this.blurYFilter.strength)) * 2;
  35250. }
  35251. };
  35252. Object.defineProperty(BlurFilter.prototype, "blur", {
  35253. /**
  35254. * Sets the strength of both the blurX and blurY properties simultaneously
  35255. * @default 2
  35256. */
  35257. get: function () {
  35258. return this.blurXFilter.blur;
  35259. },
  35260. set: function (value) {
  35261. this.blurXFilter.blur = this.blurYFilter.blur = value;
  35262. this.updatePadding();
  35263. },
  35264. enumerable: false,
  35265. configurable: true
  35266. });
  35267. Object.defineProperty(BlurFilter.prototype, "quality", {
  35268. /**
  35269. * Sets the number of passes for blur. More passes means higher quality bluring.
  35270. * @default 1
  35271. */
  35272. get: function () {
  35273. return this.blurXFilter.quality;
  35274. },
  35275. set: function (value) {
  35276. this.blurXFilter.quality = this.blurYFilter.quality = value;
  35277. },
  35278. enumerable: false,
  35279. configurable: true
  35280. });
  35281. Object.defineProperty(BlurFilter.prototype, "blurX", {
  35282. /**
  35283. * Sets the strength of the blurX property
  35284. * @default 2
  35285. */
  35286. get: function () {
  35287. return this.blurXFilter.blur;
  35288. },
  35289. set: function (value) {
  35290. this.blurXFilter.blur = value;
  35291. this.updatePadding();
  35292. },
  35293. enumerable: false,
  35294. configurable: true
  35295. });
  35296. Object.defineProperty(BlurFilter.prototype, "blurY", {
  35297. /**
  35298. * Sets the strength of the blurY property
  35299. * @default 2
  35300. */
  35301. get: function () {
  35302. return this.blurYFilter.blur;
  35303. },
  35304. set: function (value) {
  35305. this.blurYFilter.blur = value;
  35306. this.updatePadding();
  35307. },
  35308. enumerable: false,
  35309. configurable: true
  35310. });
  35311. Object.defineProperty(BlurFilter.prototype, "blendMode", {
  35312. /**
  35313. * Sets the blendmode of the filter
  35314. * @default PIXI.BLEND_MODES.NORMAL
  35315. */
  35316. get: function () {
  35317. return this.blurYFilter.blendMode;
  35318. },
  35319. set: function (value) {
  35320. this.blurYFilter.blendMode = value;
  35321. },
  35322. enumerable: false,
  35323. configurable: true
  35324. });
  35325. Object.defineProperty(BlurFilter.prototype, "repeatEdgePixels", {
  35326. /**
  35327. * If set to true the edge of the target will be clamped
  35328. * @default false
  35329. */
  35330. get: function () {
  35331. return this._repeatEdgePixels;
  35332. },
  35333. set: function (value) {
  35334. this._repeatEdgePixels = value;
  35335. this.updatePadding();
  35336. },
  35337. enumerable: false,
  35338. configurable: true
  35339. });
  35340. return BlurFilter;
  35341. }(Filter));
  35342. /*!
  35343. * @pixi/filter-color-matrix - v6.5.10
  35344. * Compiled Thu, 06 Jul 2023 15:25:11 UTC
  35345. *
  35346. * @pixi/filter-color-matrix is licensed under the MIT License.
  35347. * http://www.opensource.org/licenses/mit-license
  35348. */
  35349. /*! *****************************************************************************
  35350. Copyright (c) Microsoft Corporation.
  35351. Permission to use, copy, modify, and/or distribute this software for any
  35352. purpose with or without fee is hereby granted.
  35353. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  35354. REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
  35355. AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  35356. INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
  35357. LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
  35358. OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
  35359. PERFORMANCE OF THIS SOFTWARE.
  35360. ***************************************************************************** */
  35361. /* global Reflect, Promise */
  35362. var extendStatics$5 = function(d, b) {
  35363. extendStatics$5 = Object.setPrototypeOf ||
  35364. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  35365. function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } };
  35366. return extendStatics$5(d, b);
  35367. };
  35368. function __extends$5(d, b) {
  35369. extendStatics$5(d, b);
  35370. function __() { this.constructor = d; }
  35371. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  35372. }
  35373. var fragment$3 = "varying vec2 vTextureCoord;\nuniform sampler2D uSampler;\nuniform float m[20];\nuniform float uAlpha;\n\nvoid main(void)\n{\n vec4 c = texture2D(uSampler, vTextureCoord);\n\n if (uAlpha == 0.0) {\n gl_FragColor = c;\n return;\n }\n\n // Un-premultiply alpha before applying the color matrix. See issue #3539.\n if (c.a > 0.0) {\n c.rgb /= c.a;\n }\n\n vec4 result;\n\n result.r = (m[0] * c.r);\n result.r += (m[1] * c.g);\n result.r += (m[2] * c.b);\n result.r += (m[3] * c.a);\n result.r += m[4];\n\n result.g = (m[5] * c.r);\n result.g += (m[6] * c.g);\n result.g += (m[7] * c.b);\n result.g += (m[8] * c.a);\n result.g += m[9];\n\n result.b = (m[10] * c.r);\n result.b += (m[11] * c.g);\n result.b += (m[12] * c.b);\n result.b += (m[13] * c.a);\n result.b += m[14];\n\n result.a = (m[15] * c.r);\n result.a += (m[16] * c.g);\n result.a += (m[17] * c.b);\n result.a += (m[18] * c.a);\n result.a += m[19];\n\n vec3 rgb = mix(c.rgb, result.rgb, uAlpha);\n\n // Premultiply alpha again.\n rgb *= result.a;\n\n gl_FragColor = vec4(rgb, result.a);\n}\n";
  35374. /**
  35375. * The ColorMatrixFilter class lets you apply a 5x4 matrix transformation on the RGBA
  35376. * color and alpha values of every pixel on your displayObject to produce a result
  35377. * with a new set of RGBA color and alpha values. It's pretty powerful!
  35378. *
  35379. * ```js
  35380. * let colorMatrix = new PIXI.filters.ColorMatrixFilter();
  35381. * container.filters = [colorMatrix];
  35382. * colorMatrix.contrast(2);
  35383. * ```
  35384. * @author Clément Chenebault <clement@goodboydigital.com>
  35385. * @memberof PIXI.filters
  35386. */
  35387. var ColorMatrixFilter = /** @class */ (function (_super) {
  35388. __extends$5(ColorMatrixFilter, _super);
  35389. function ColorMatrixFilter() {
  35390. var _this = this;
  35391. var uniforms = {
  35392. m: new Float32Array([1, 0, 0, 0, 0,
  35393. 0, 1, 0, 0, 0,
  35394. 0, 0, 1, 0, 0,
  35395. 0, 0, 0, 1, 0]),
  35396. uAlpha: 1,
  35397. };
  35398. _this = _super.call(this, defaultFilterVertex, fragment$3, uniforms) || this;
  35399. _this.alpha = 1;
  35400. return _this;
  35401. }
  35402. /**
  35403. * Transforms current matrix and set the new one
  35404. * @param {number[]} matrix - 5x4 matrix
  35405. * @param multiply - if true, current matrix and matrix are multiplied. If false,
  35406. * just set the current matrix with @param matrix
  35407. */
  35408. ColorMatrixFilter.prototype._loadMatrix = function (matrix, multiply) {
  35409. if (multiply === void 0) { multiply = false; }
  35410. var newMatrix = matrix;
  35411. if (multiply) {
  35412. this._multiply(newMatrix, this.uniforms.m, matrix);
  35413. newMatrix = this._colorMatrix(newMatrix);
  35414. }
  35415. // set the new matrix
  35416. this.uniforms.m = newMatrix;
  35417. };
  35418. /**
  35419. * Multiplies two mat5's
  35420. * @private
  35421. * @param out - 5x4 matrix the receiving matrix
  35422. * @param a - 5x4 matrix the first operand
  35423. * @param b - 5x4 matrix the second operand
  35424. * @returns {number[]} 5x4 matrix
  35425. */
  35426. ColorMatrixFilter.prototype._multiply = function (out, a, b) {
  35427. // Red Channel
  35428. out[0] = (a[0] * b[0]) + (a[1] * b[5]) + (a[2] * b[10]) + (a[3] * b[15]);
  35429. out[1] = (a[0] * b[1]) + (a[1] * b[6]) + (a[2] * b[11]) + (a[3] * b[16]);
  35430. out[2] = (a[0] * b[2]) + (a[1] * b[7]) + (a[2] * b[12]) + (a[3] * b[17]);
  35431. out[3] = (a[0] * b[3]) + (a[1] * b[8]) + (a[2] * b[13]) + (a[3] * b[18]);
  35432. out[4] = (a[0] * b[4]) + (a[1] * b[9]) + (a[2] * b[14]) + (a[3] * b[19]) + a[4];
  35433. // Green Channel
  35434. out[5] = (a[5] * b[0]) + (a[6] * b[5]) + (a[7] * b[10]) + (a[8] * b[15]);
  35435. out[6] = (a[5] * b[1]) + (a[6] * b[6]) + (a[7] * b[11]) + (a[8] * b[16]);
  35436. out[7] = (a[5] * b[2]) + (a[6] * b[7]) + (a[7] * b[12]) + (a[8] * b[17]);
  35437. out[8] = (a[5] * b[3]) + (a[6] * b[8]) + (a[7] * b[13]) + (a[8] * b[18]);
  35438. out[9] = (a[5] * b[4]) + (a[6] * b[9]) + (a[7] * b[14]) + (a[8] * b[19]) + a[9];
  35439. // Blue Channel
  35440. out[10] = (a[10] * b[0]) + (a[11] * b[5]) + (a[12] * b[10]) + (a[13] * b[15]);
  35441. out[11] = (a[10] * b[1]) + (a[11] * b[6]) + (a[12] * b[11]) + (a[13] * b[16]);
  35442. out[12] = (a[10] * b[2]) + (a[11] * b[7]) + (a[12] * b[12]) + (a[13] * b[17]);
  35443. out[13] = (a[10] * b[3]) + (a[11] * b[8]) + (a[12] * b[13]) + (a[13] * b[18]);
  35444. out[14] = (a[10] * b[4]) + (a[11] * b[9]) + (a[12] * b[14]) + (a[13] * b[19]) + a[14];
  35445. // Alpha Channel
  35446. out[15] = (a[15] * b[0]) + (a[16] * b[5]) + (a[17] * b[10]) + (a[18] * b[15]);
  35447. out[16] = (a[15] * b[1]) + (a[16] * b[6]) + (a[17] * b[11]) + (a[18] * b[16]);
  35448. out[17] = (a[15] * b[2]) + (a[16] * b[7]) + (a[17] * b[12]) + (a[18] * b[17]);
  35449. out[18] = (a[15] * b[3]) + (a[16] * b[8]) + (a[17] * b[13]) + (a[18] * b[18]);
  35450. out[19] = (a[15] * b[4]) + (a[16] * b[9]) + (a[17] * b[14]) + (a[18] * b[19]) + a[19];
  35451. return out;
  35452. };
  35453. /**
  35454. * Create a Float32 Array and normalize the offset component to 0-1
  35455. * @param {number[]} matrix - 5x4 matrix
  35456. * @returns {number[]} 5x4 matrix with all values between 0-1
  35457. */
  35458. ColorMatrixFilter.prototype._colorMatrix = function (matrix) {
  35459. // Create a Float32 Array and normalize the offset component to 0-1
  35460. var m = new Float32Array(matrix);
  35461. m[4] /= 255;
  35462. m[9] /= 255;
  35463. m[14] /= 255;
  35464. m[19] /= 255;
  35465. return m;
  35466. };
  35467. /**
  35468. * Adjusts brightness
  35469. * @param b - value of the brigthness (0-1, where 0 is black)
  35470. * @param multiply - if true, current matrix and matrix are multiplied. If false,
  35471. * just set the current matrix with @param matrix
  35472. */
  35473. ColorMatrixFilter.prototype.brightness = function (b, multiply) {
  35474. var matrix = [
  35475. b, 0, 0, 0, 0,
  35476. 0, b, 0, 0, 0,
  35477. 0, 0, b, 0, 0,
  35478. 0, 0, 0, 1, 0 ];
  35479. this._loadMatrix(matrix, multiply);
  35480. };
  35481. /**
  35482. * Sets each channel on the diagonal of the color matrix.
  35483. * This can be used to achieve a tinting effect on Containers similar to the tint field of some
  35484. * display objects like Sprite, Text, Graphics, and Mesh.
  35485. * @param color - Color of the tint. This is a hex value.
  35486. * @param multiply - if true, current matrix and matrix are multiplied. If false,
  35487. * just set the current matrix with @param matrix
  35488. */
  35489. ColorMatrixFilter.prototype.tint = function (color, multiply) {
  35490. var r = (color >> 16) & 0xff;
  35491. var g = (color >> 8) & 0xff;
  35492. var b = color & 0xff;
  35493. var matrix = [
  35494. r / 255, 0, 0, 0, 0,
  35495. 0, g / 255, 0, 0, 0,
  35496. 0, 0, b / 255, 0, 0,
  35497. 0, 0, 0, 1, 0 ];
  35498. this._loadMatrix(matrix, multiply);
  35499. };
  35500. /**
  35501. * Set the matrices in grey scales
  35502. * @param scale - value of the grey (0-1, where 0 is black)
  35503. * @param multiply - if true, current matrix and matrix are multiplied. If false,
  35504. * just set the current matrix with @param matrix
  35505. */
  35506. ColorMatrixFilter.prototype.greyscale = function (scale, multiply) {
  35507. var matrix = [
  35508. scale, scale, scale, 0, 0,
  35509. scale, scale, scale, 0, 0,
  35510. scale, scale, scale, 0, 0,
  35511. 0, 0, 0, 1, 0 ];
  35512. this._loadMatrix(matrix, multiply);
  35513. };
  35514. /**
  35515. * Set the black and white matrice.
  35516. * @param multiply - if true, current matrix and matrix are multiplied. If false,
  35517. * just set the current matrix with @param matrix
  35518. */
  35519. ColorMatrixFilter.prototype.blackAndWhite = function (multiply) {
  35520. var matrix = [
  35521. 0.3, 0.6, 0.1, 0, 0,
  35522. 0.3, 0.6, 0.1, 0, 0,
  35523. 0.3, 0.6, 0.1, 0, 0,
  35524. 0, 0, 0, 1, 0 ];
  35525. this._loadMatrix(matrix, multiply);
  35526. };
  35527. /**
  35528. * Set the hue property of the color
  35529. * @param rotation - in degrees
  35530. * @param multiply - if true, current matrix and matrix are multiplied. If false,
  35531. * just set the current matrix with @param matrix
  35532. */
  35533. ColorMatrixFilter.prototype.hue = function (rotation, multiply) {
  35534. rotation = (rotation || 0) / 180 * Math.PI;
  35535. var cosR = Math.cos(rotation);
  35536. var sinR = Math.sin(rotation);
  35537. var sqrt = Math.sqrt;
  35538. /* a good approximation for hue rotation
  35539. This matrix is far better than the versions with magic luminance constants
  35540. formerly used here, but also used in the starling framework (flash) and known from this
  35541. old part of the internet: quasimondo.com/archives/000565.php
  35542. This new matrix is based on rgb cube rotation in space. Look here for a more descriptive
  35543. implementation as a shader not a general matrix:
  35544. https://github.com/evanw/glfx.js/blob/58841c23919bd59787effc0333a4897b43835412/src/filters/adjust/huesaturation.js
  35545. This is the source for the code:
  35546. see http://stackoverflow.com/questions/8507885/shift-hue-of-an-rgb-color/8510751#8510751
  35547. */
  35548. var w = 1 / 3;
  35549. var sqrW = sqrt(w); // weight is
  35550. var a00 = cosR + ((1.0 - cosR) * w);
  35551. var a01 = (w * (1.0 - cosR)) - (sqrW * sinR);
  35552. var a02 = (w * (1.0 - cosR)) + (sqrW * sinR);
  35553. var a10 = (w * (1.0 - cosR)) + (sqrW * sinR);
  35554. var a11 = cosR + (w * (1.0 - cosR));
  35555. var a12 = (w * (1.0 - cosR)) - (sqrW * sinR);
  35556. var a20 = (w * (1.0 - cosR)) - (sqrW * sinR);
  35557. var a21 = (w * (1.0 - cosR)) + (sqrW * sinR);
  35558. var a22 = cosR + (w * (1.0 - cosR));
  35559. var matrix = [
  35560. a00, a01, a02, 0, 0,
  35561. a10, a11, a12, 0, 0,
  35562. a20, a21, a22, 0, 0,
  35563. 0, 0, 0, 1, 0 ];
  35564. this._loadMatrix(matrix, multiply);
  35565. };
  35566. /**
  35567. * Set the contrast matrix, increase the separation between dark and bright
  35568. * Increase contrast : shadows darker and highlights brighter
  35569. * Decrease contrast : bring the shadows up and the highlights down
  35570. * @param amount - value of the contrast (0-1)
  35571. * @param multiply - if true, current matrix and matrix are multiplied. If false,
  35572. * just set the current matrix with @param matrix
  35573. */
  35574. ColorMatrixFilter.prototype.contrast = function (amount, multiply) {
  35575. var v = (amount || 0) + 1;
  35576. var o = -0.5 * (v - 1);
  35577. var matrix = [
  35578. v, 0, 0, 0, o,
  35579. 0, v, 0, 0, o,
  35580. 0, 0, v, 0, o,
  35581. 0, 0, 0, 1, 0 ];
  35582. this._loadMatrix(matrix, multiply);
  35583. };
  35584. /**
  35585. * Set the saturation matrix, increase the separation between colors
  35586. * Increase saturation : increase contrast, brightness, and sharpness
  35587. * @param amount - The saturation amount (0-1)
  35588. * @param multiply - if true, current matrix and matrix are multiplied. If false,
  35589. * just set the current matrix with @param matrix
  35590. */
  35591. ColorMatrixFilter.prototype.saturate = function (amount, multiply) {
  35592. if (amount === void 0) { amount = 0; }
  35593. var x = (amount * 2 / 3) + 1;
  35594. var y = ((x - 1) * -0.5);
  35595. var matrix = [
  35596. x, y, y, 0, 0,
  35597. y, x, y, 0, 0,
  35598. y, y, x, 0, 0,
  35599. 0, 0, 0, 1, 0 ];
  35600. this._loadMatrix(matrix, multiply);
  35601. };
  35602. /** Desaturate image (remove color) Call the saturate function */
  35603. ColorMatrixFilter.prototype.desaturate = function () {
  35604. this.saturate(-1);
  35605. };
  35606. /**
  35607. * Negative image (inverse of classic rgb matrix)
  35608. * @param multiply - if true, current matrix and matrix are multiplied. If false,
  35609. * just set the current matrix with @param matrix
  35610. */
  35611. ColorMatrixFilter.prototype.negative = function (multiply) {
  35612. var matrix = [
  35613. -1, 0, 0, 1, 0,
  35614. 0, -1, 0, 1, 0,
  35615. 0, 0, -1, 1, 0,
  35616. 0, 0, 0, 1, 0 ];
  35617. this._loadMatrix(matrix, multiply);
  35618. };
  35619. /**
  35620. * Sepia image
  35621. * @param multiply - if true, current matrix and matrix are multiplied. If false,
  35622. * just set the current matrix with @param matrix
  35623. */
  35624. ColorMatrixFilter.prototype.sepia = function (multiply) {
  35625. var matrix = [
  35626. 0.393, 0.7689999, 0.18899999, 0, 0,
  35627. 0.349, 0.6859999, 0.16799999, 0, 0,
  35628. 0.272, 0.5339999, 0.13099999, 0, 0,
  35629. 0, 0, 0, 1, 0 ];
  35630. this._loadMatrix(matrix, multiply);
  35631. };
  35632. /**
  35633. * Color motion picture process invented in 1916 (thanks Dominic Szablewski)
  35634. * @param multiply - if true, current matrix and matrix are multiplied. If false,
  35635. * just set the current matrix with @param matrix
  35636. */
  35637. ColorMatrixFilter.prototype.technicolor = function (multiply) {
  35638. var matrix = [
  35639. 1.9125277891456083, -0.8545344976951645, -0.09155508482755585, 0, 11.793603434377337,
  35640. -0.3087833385928097, 1.7658908555458428, -0.10601743074722245, 0, -70.35205161461398,
  35641. -0.231103377548616, -0.7501899197440212, 1.847597816108189, 0, 30.950940869491138,
  35642. 0, 0, 0, 1, 0 ];
  35643. this._loadMatrix(matrix, multiply);
  35644. };
  35645. /**
  35646. * Polaroid filter
  35647. * @param multiply - if true, current matrix and matrix are multiplied. If false,
  35648. * just set the current matrix with @param matrix
  35649. */
  35650. ColorMatrixFilter.prototype.polaroid = function (multiply) {
  35651. var matrix = [
  35652. 1.438, -0.062, -0.062, 0, 0,
  35653. -0.122, 1.378, -0.122, 0, 0,
  35654. -0.016, -0.016, 1.483, 0, 0,
  35655. 0, 0, 0, 1, 0 ];
  35656. this._loadMatrix(matrix, multiply);
  35657. };
  35658. /**
  35659. * Filter who transforms : Red -> Blue and Blue -> Red
  35660. * @param multiply - if true, current matrix and matrix are multiplied. If false,
  35661. * just set the current matrix with @param matrix
  35662. */
  35663. ColorMatrixFilter.prototype.toBGR = function (multiply) {
  35664. var matrix = [
  35665. 0, 0, 1, 0, 0,
  35666. 0, 1, 0, 0, 0,
  35667. 1, 0, 0, 0, 0,
  35668. 0, 0, 0, 1, 0 ];
  35669. this._loadMatrix(matrix, multiply);
  35670. };
  35671. /**
  35672. * Color reversal film introduced by Eastman Kodak in 1935. (thanks Dominic Szablewski)
  35673. * @param multiply - if true, current matrix and matrix are multiplied. If false,
  35674. * just set the current matrix with @param matrix
  35675. */
  35676. ColorMatrixFilter.prototype.kodachrome = function (multiply) {
  35677. var matrix = [
  35678. 1.1285582396593525, -0.3967382283601348, -0.03992559172921793, 0, 63.72958762196502,
  35679. -0.16404339962244616, 1.0835251566291304, -0.05498805115633132, 0, 24.732407896706203,
  35680. -0.16786010706155763, -0.5603416277695248, 1.6014850761964943, 0, 35.62982807460946,
  35681. 0, 0, 0, 1, 0 ];
  35682. this._loadMatrix(matrix, multiply);
  35683. };
  35684. /**
  35685. * Brown delicious browni filter (thanks Dominic Szablewski)
  35686. * @param multiply - if true, current matrix and matrix are multiplied. If false,
  35687. * just set the current matrix with @param matrix
  35688. */
  35689. ColorMatrixFilter.prototype.browni = function (multiply) {
  35690. var matrix = [
  35691. 0.5997023498159715, 0.34553243048391263, -0.2708298674538042, 0, 47.43192855600873,
  35692. -0.037703249837783157, 0.8609577587992641, 0.15059552388459913, 0, -36.96841498319127,
  35693. 0.24113635128153335, -0.07441037908422492, 0.44972182064877153, 0, -7.562075277591283,
  35694. 0, 0, 0, 1, 0 ];
  35695. this._loadMatrix(matrix, multiply);
  35696. };
  35697. /**
  35698. * Vintage filter (thanks Dominic Szablewski)
  35699. * @param multiply - if true, current matrix and matrix are multiplied. If false,
  35700. * just set the current matrix with @param matrix
  35701. */
  35702. ColorMatrixFilter.prototype.vintage = function (multiply) {
  35703. var matrix = [
  35704. 0.6279345635605994, 0.3202183420819367, -0.03965408211312453, 0, 9.651285835294123,
  35705. 0.02578397704808868, 0.6441188644374771, 0.03259127616149294, 0, 7.462829176470591,
  35706. 0.0466055556782719, -0.0851232987247891, 0.5241648018700465, 0, 5.159190588235296,
  35707. 0, 0, 0, 1, 0 ];
  35708. this._loadMatrix(matrix, multiply);
  35709. };
  35710. /**
  35711. * We don't know exactly what it does, kind of gradient map, but funny to play with!
  35712. * @param desaturation - Tone values.
  35713. * @param toned - Tone values.
  35714. * @param lightColor - Tone values, example: `0xFFE580`
  35715. * @param darkColor - Tone values, example: `0xFFE580`
  35716. * @param multiply - if true, current matrix and matrix are multiplied. If false,
  35717. * just set the current matrix with @param matrix
  35718. */
  35719. ColorMatrixFilter.prototype.colorTone = function (desaturation, toned, lightColor, darkColor, multiply) {
  35720. desaturation = desaturation || 0.2;
  35721. toned = toned || 0.15;
  35722. lightColor = lightColor || 0xFFE580;
  35723. darkColor = darkColor || 0x338000;
  35724. var lR = ((lightColor >> 16) & 0xFF) / 255;
  35725. var lG = ((lightColor >> 8) & 0xFF) / 255;
  35726. var lB = (lightColor & 0xFF) / 255;
  35727. var dR = ((darkColor >> 16) & 0xFF) / 255;
  35728. var dG = ((darkColor >> 8) & 0xFF) / 255;
  35729. var dB = (darkColor & 0xFF) / 255;
  35730. var matrix = [
  35731. 0.3, 0.59, 0.11, 0, 0,
  35732. lR, lG, lB, desaturation, 0,
  35733. dR, dG, dB, toned, 0,
  35734. lR - dR, lG - dG, lB - dB, 0, 0 ];
  35735. this._loadMatrix(matrix, multiply);
  35736. };
  35737. /**
  35738. * Night effect
  35739. * @param intensity - The intensity of the night effect.
  35740. * @param multiply - if true, current matrix and matrix are multiplied. If false,
  35741. * just set the current matrix with @param matrix
  35742. */
  35743. ColorMatrixFilter.prototype.night = function (intensity, multiply) {
  35744. intensity = intensity || 0.1;
  35745. var matrix = [
  35746. intensity * (-2.0), -intensity, 0, 0, 0,
  35747. -intensity, 0, intensity, 0, 0,
  35748. 0, intensity, intensity * 2.0, 0, 0,
  35749. 0, 0, 0, 1, 0 ];
  35750. this._loadMatrix(matrix, multiply);
  35751. };
  35752. /**
  35753. * Predator effect
  35754. *
  35755. * Erase the current matrix by setting a new indepent one
  35756. * @param amount - how much the predator feels his future victim
  35757. * @param multiply - if true, current matrix and matrix are multiplied. If false,
  35758. * just set the current matrix with @param matrix
  35759. */
  35760. ColorMatrixFilter.prototype.predator = function (amount, multiply) {
  35761. var matrix = [
  35762. // row 1
  35763. 11.224130630493164 * amount,
  35764. -4.794486999511719 * amount,
  35765. -2.8746118545532227 * amount,
  35766. 0 * amount,
  35767. 0.40342438220977783 * amount,
  35768. // row 2
  35769. -3.6330697536468506 * amount,
  35770. 9.193157196044922 * amount,
  35771. -2.951810836791992 * amount,
  35772. 0 * amount,
  35773. -1.316135048866272 * amount,
  35774. // row 3
  35775. -3.2184197902679443 * amount,
  35776. -4.2375030517578125 * amount,
  35777. 7.476448059082031 * amount,
  35778. 0 * amount,
  35779. 0.8044459223747253 * amount,
  35780. // row 4
  35781. 0, 0, 0, 1, 0 ];
  35782. this._loadMatrix(matrix, multiply);
  35783. };
  35784. /**
  35785. * LSD effect
  35786. *
  35787. * Multiply the current matrix
  35788. * @param multiply - if true, current matrix and matrix are multiplied. If false,
  35789. * just set the current matrix with @param matrix
  35790. */
  35791. ColorMatrixFilter.prototype.lsd = function (multiply) {
  35792. var matrix = [
  35793. 2, -0.4, 0.5, 0, 0,
  35794. -0.5, 2, -0.4, 0, 0,
  35795. -0.4, -0.5, 3, 0, 0,
  35796. 0, 0, 0, 1, 0 ];
  35797. this._loadMatrix(matrix, multiply);
  35798. };
  35799. /** Erase the current matrix by setting the default one. */
  35800. ColorMatrixFilter.prototype.reset = function () {
  35801. var matrix = [
  35802. 1, 0, 0, 0, 0,
  35803. 0, 1, 0, 0, 0,
  35804. 0, 0, 1, 0, 0,
  35805. 0, 0, 0, 1, 0 ];
  35806. this._loadMatrix(matrix, false);
  35807. };
  35808. Object.defineProperty(ColorMatrixFilter.prototype, "matrix", {
  35809. /**
  35810. * The matrix of the color matrix filter
  35811. * @member {number[]}
  35812. * @default [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0]
  35813. */
  35814. get: function () {
  35815. return this.uniforms.m;
  35816. },
  35817. set: function (value) {
  35818. this.uniforms.m = value;
  35819. },
  35820. enumerable: false,
  35821. configurable: true
  35822. });
  35823. Object.defineProperty(ColorMatrixFilter.prototype, "alpha", {
  35824. /**
  35825. * The opacity value to use when mixing the original and resultant colors.
  35826. *
  35827. * When the value is 0, the original color is used without modification.
  35828. * When the value is 1, the result color is used.
  35829. * When in the range (0, 1) the color is interpolated between the original and result by this amount.
  35830. * @default 1
  35831. */
  35832. get: function () {
  35833. return this.uniforms.uAlpha;
  35834. },
  35835. set: function (value) {
  35836. this.uniforms.uAlpha = value;
  35837. },
  35838. enumerable: false,
  35839. configurable: true
  35840. });
  35841. return ColorMatrixFilter;
  35842. }(Filter));
  35843. // Americanized alias
  35844. ColorMatrixFilter.prototype.grayscale = ColorMatrixFilter.prototype.greyscale;
  35845. /*!
  35846. * @pixi/filter-displacement - v6.5.10
  35847. * Compiled Thu, 06 Jul 2023 15:25:11 UTC
  35848. *
  35849. * @pixi/filter-displacement is licensed under the MIT License.
  35850. * http://www.opensource.org/licenses/mit-license
  35851. */
  35852. /*! *****************************************************************************
  35853. Copyright (c) Microsoft Corporation.
  35854. Permission to use, copy, modify, and/or distribute this software for any
  35855. purpose with or without fee is hereby granted.
  35856. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  35857. REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
  35858. AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  35859. INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
  35860. LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
  35861. OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
  35862. PERFORMANCE OF THIS SOFTWARE.
  35863. ***************************************************************************** */
  35864. /* global Reflect, Promise */
  35865. var extendStatics$4 = function(d, b) {
  35866. extendStatics$4 = Object.setPrototypeOf ||
  35867. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  35868. function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } };
  35869. return extendStatics$4(d, b);
  35870. };
  35871. function __extends$4(d, b) {
  35872. extendStatics$4(d, b);
  35873. function __() { this.constructor = d; }
  35874. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  35875. }
  35876. var fragment$2 = "varying vec2 vFilterCoord;\nvarying vec2 vTextureCoord;\n\nuniform vec2 scale;\nuniform mat2 rotation;\nuniform sampler2D uSampler;\nuniform sampler2D mapSampler;\n\nuniform highp vec4 inputSize;\nuniform vec4 inputClamp;\n\nvoid main(void)\n{\n vec4 map = texture2D(mapSampler, vFilterCoord);\n\n map -= 0.5;\n map.xy = scale * inputSize.zw * (rotation * map.xy);\n\n gl_FragColor = texture2D(uSampler, clamp(vec2(vTextureCoord.x + map.x, vTextureCoord.y + map.y), inputClamp.xy, inputClamp.zw));\n}\n";
  35877. var vertex$1 = "attribute vec2 aVertexPosition;\n\nuniform mat3 projectionMatrix;\nuniform mat3 filterMatrix;\n\nvarying vec2 vTextureCoord;\nvarying vec2 vFilterCoord;\n\nuniform vec4 inputSize;\nuniform vec4 outputFrame;\n\nvec4 filterVertexPosition( void )\n{\n vec2 position = aVertexPosition * max(outputFrame.zw, vec2(0.)) + outputFrame.xy;\n\n return vec4((projectionMatrix * vec3(position, 1.0)).xy, 0.0, 1.0);\n}\n\nvec2 filterTextureCoord( void )\n{\n return aVertexPosition * (outputFrame.zw * inputSize.zw);\n}\n\nvoid main(void)\n{\n\tgl_Position = filterVertexPosition();\n\tvTextureCoord = filterTextureCoord();\n\tvFilterCoord = ( filterMatrix * vec3( vTextureCoord, 1.0) ).xy;\n}\n";
  35878. /**
  35879. * The DisplacementFilter class uses the pixel values from the specified texture
  35880. * (called the displacement map) to perform a displacement of an object.
  35881. *
  35882. * You can use this filter to apply all manor of crazy warping effects.
  35883. * Currently the `r` property of the texture is used to offset the `x`
  35884. * and the `g` property of the texture is used to offset the `y`.
  35885. *
  35886. * The way it works is it uses the values of the displacement map to look up the
  35887. * correct pixels to output. This means it's not technically moving the original.
  35888. * Instead, it's starting at the output and asking "which pixel from the original goes here".
  35889. * For example, if a displacement map pixel has `red = 1` and the filter scale is `20`,
  35890. * this filter will output the pixel approximately 20 pixels to the right of the original.
  35891. * @memberof PIXI.filters
  35892. */
  35893. var DisplacementFilter = /** @class */ (function (_super) {
  35894. __extends$4(DisplacementFilter, _super);
  35895. /**
  35896. * @param {PIXI.Sprite} sprite - The sprite used for the displacement map. (make sure its added to the scene!)
  35897. * @param scale - The scale of the displacement
  35898. */
  35899. function DisplacementFilter(sprite, scale) {
  35900. var _this = this;
  35901. var maskMatrix = new Matrix();
  35902. sprite.renderable = false;
  35903. _this = _super.call(this, vertex$1, fragment$2, {
  35904. mapSampler: sprite._texture,
  35905. filterMatrix: maskMatrix,
  35906. scale: { x: 1, y: 1 },
  35907. rotation: new Float32Array([1, 0, 0, 1]),
  35908. }) || this;
  35909. _this.maskSprite = sprite;
  35910. _this.maskMatrix = maskMatrix;
  35911. if (scale === null || scale === undefined) {
  35912. scale = 20;
  35913. }
  35914. /**
  35915. * scaleX, scaleY for displacements
  35916. * @member {PIXI.Point}
  35917. */
  35918. _this.scale = new Point(scale, scale);
  35919. return _this;
  35920. }
  35921. /**
  35922. * Applies the filter.
  35923. * @param filterManager - The manager.
  35924. * @param input - The input target.
  35925. * @param output - The output target.
  35926. * @param clearMode - clearMode.
  35927. */
  35928. DisplacementFilter.prototype.apply = function (filterManager, input, output, clearMode) {
  35929. // fill maskMatrix with _normalized sprite texture coords_
  35930. this.uniforms.filterMatrix = filterManager.calculateSpriteMatrix(this.maskMatrix, this.maskSprite);
  35931. this.uniforms.scale.x = this.scale.x;
  35932. this.uniforms.scale.y = this.scale.y;
  35933. // Extract rotation from world transform
  35934. var wt = this.maskSprite.worldTransform;
  35935. var lenX = Math.sqrt((wt.a * wt.a) + (wt.b * wt.b));
  35936. var lenY = Math.sqrt((wt.c * wt.c) + (wt.d * wt.d));
  35937. if (lenX !== 0 && lenY !== 0) {
  35938. this.uniforms.rotation[0] = wt.a / lenX;
  35939. this.uniforms.rotation[1] = wt.b / lenX;
  35940. this.uniforms.rotation[2] = wt.c / lenY;
  35941. this.uniforms.rotation[3] = wt.d / lenY;
  35942. }
  35943. // draw the filter...
  35944. filterManager.applyFilter(this, input, output, clearMode);
  35945. };
  35946. Object.defineProperty(DisplacementFilter.prototype, "map", {
  35947. /** The texture used for the displacement map. Must be power of 2 sized texture. */
  35948. get: function () {
  35949. return this.uniforms.mapSampler;
  35950. },
  35951. set: function (value) {
  35952. this.uniforms.mapSampler = value;
  35953. },
  35954. enumerable: false,
  35955. configurable: true
  35956. });
  35957. return DisplacementFilter;
  35958. }(Filter));
  35959. /*!
  35960. * @pixi/filter-fxaa - v6.5.10
  35961. * Compiled Thu, 06 Jul 2023 15:25:11 UTC
  35962. *
  35963. * @pixi/filter-fxaa is licensed under the MIT License.
  35964. * http://www.opensource.org/licenses/mit-license
  35965. */
  35966. /*! *****************************************************************************
  35967. Copyright (c) Microsoft Corporation.
  35968. Permission to use, copy, modify, and/or distribute this software for any
  35969. purpose with or without fee is hereby granted.
  35970. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  35971. REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
  35972. AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  35973. INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
  35974. LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
  35975. OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
  35976. PERFORMANCE OF THIS SOFTWARE.
  35977. ***************************************************************************** */
  35978. /* global Reflect, Promise */
  35979. var extendStatics$3 = function(d, b) {
  35980. extendStatics$3 = Object.setPrototypeOf ||
  35981. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  35982. function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } };
  35983. return extendStatics$3(d, b);
  35984. };
  35985. function __extends$3(d, b) {
  35986. extendStatics$3(d, b);
  35987. function __() { this.constructor = d; }
  35988. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  35989. }
  35990. var vertex = "\nattribute vec2 aVertexPosition;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 v_rgbNW;\nvarying vec2 v_rgbNE;\nvarying vec2 v_rgbSW;\nvarying vec2 v_rgbSE;\nvarying vec2 v_rgbM;\n\nvarying vec2 vFragCoord;\n\nuniform vec4 inputSize;\nuniform vec4 outputFrame;\n\nvec4 filterVertexPosition( void )\n{\n vec2 position = aVertexPosition * max(outputFrame.zw, vec2(0.)) + outputFrame.xy;\n\n return vec4((projectionMatrix * vec3(position, 1.0)).xy, 0.0, 1.0);\n}\n\nvoid texcoords(vec2 fragCoord, vec2 inverseVP,\n out vec2 v_rgbNW, out vec2 v_rgbNE,\n out vec2 v_rgbSW, out vec2 v_rgbSE,\n out vec2 v_rgbM) {\n v_rgbNW = (fragCoord + vec2(-1.0, -1.0)) * inverseVP;\n v_rgbNE = (fragCoord + vec2(1.0, -1.0)) * inverseVP;\n v_rgbSW = (fragCoord + vec2(-1.0, 1.0)) * inverseVP;\n v_rgbSE = (fragCoord + vec2(1.0, 1.0)) * inverseVP;\n v_rgbM = vec2(fragCoord * inverseVP);\n}\n\nvoid main(void) {\n\n gl_Position = filterVertexPosition();\n\n vFragCoord = aVertexPosition * outputFrame.zw;\n\n texcoords(vFragCoord, inputSize.zw, v_rgbNW, v_rgbNE, v_rgbSW, v_rgbSE, v_rgbM);\n}\n";
  35991. var fragment$1 = "varying vec2 v_rgbNW;\nvarying vec2 v_rgbNE;\nvarying vec2 v_rgbSW;\nvarying vec2 v_rgbSE;\nvarying vec2 v_rgbM;\n\nvarying vec2 vFragCoord;\nuniform sampler2D uSampler;\nuniform highp vec4 inputSize;\n\n\n/**\n Basic FXAA implementation based on the code on geeks3d.com with the\n modification that the texture2DLod stuff was removed since it's\n unsupported by WebGL.\n\n --\n\n From:\n https://github.com/mitsuhiko/webgl-meincraft\n\n Copyright (c) 2011 by Armin Ronacher.\n\n Some rights reserved.\n\n Redistribution and use in source and binary forms, with or without\n modification, are permitted provided that the following conditions are\n met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n\n * Redistributions in binary form must reproduce the above\n copyright notice, this list of conditions and the following\n disclaimer in the documentation and/or other materials provided\n with the distribution.\n\n * The names of the contributors may not be used to endorse or\n promote products derived from this software without specific\n prior written permission.\n\n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n */\n\n#ifndef FXAA_REDUCE_MIN\n#define FXAA_REDUCE_MIN (1.0/ 128.0)\n#endif\n#ifndef FXAA_REDUCE_MUL\n#define FXAA_REDUCE_MUL (1.0 / 8.0)\n#endif\n#ifndef FXAA_SPAN_MAX\n#define FXAA_SPAN_MAX 8.0\n#endif\n\n//optimized version for mobile, where dependent\n//texture reads can be a bottleneck\nvec4 fxaa(sampler2D tex, vec2 fragCoord, vec2 inverseVP,\n vec2 v_rgbNW, vec2 v_rgbNE,\n vec2 v_rgbSW, vec2 v_rgbSE,\n vec2 v_rgbM) {\n vec4 color;\n vec3 rgbNW = texture2D(tex, v_rgbNW).xyz;\n vec3 rgbNE = texture2D(tex, v_rgbNE).xyz;\n vec3 rgbSW = texture2D(tex, v_rgbSW).xyz;\n vec3 rgbSE = texture2D(tex, v_rgbSE).xyz;\n vec4 texColor = texture2D(tex, v_rgbM);\n vec3 rgbM = texColor.xyz;\n vec3 luma = vec3(0.299, 0.587, 0.114);\n float lumaNW = dot(rgbNW, luma);\n float lumaNE = dot(rgbNE, luma);\n float lumaSW = dot(rgbSW, luma);\n float lumaSE = dot(rgbSE, luma);\n float lumaM = dot(rgbM, luma);\n float lumaMin = min(lumaM, min(min(lumaNW, lumaNE), min(lumaSW, lumaSE)));\n float lumaMax = max(lumaM, max(max(lumaNW, lumaNE), max(lumaSW, lumaSE)));\n\n mediump vec2 dir;\n dir.x = -((lumaNW + lumaNE) - (lumaSW + lumaSE));\n dir.y = ((lumaNW + lumaSW) - (lumaNE + lumaSE));\n\n float dirReduce = max((lumaNW + lumaNE + lumaSW + lumaSE) *\n (0.25 * FXAA_REDUCE_MUL), FXAA_REDUCE_MIN);\n\n float rcpDirMin = 1.0 / (min(abs(dir.x), abs(dir.y)) + dirReduce);\n dir = min(vec2(FXAA_SPAN_MAX, FXAA_SPAN_MAX),\n max(vec2(-FXAA_SPAN_MAX, -FXAA_SPAN_MAX),\n dir * rcpDirMin)) * inverseVP;\n\n vec3 rgbA = 0.5 * (\n texture2D(tex, fragCoord * inverseVP + dir * (1.0 / 3.0 - 0.5)).xyz +\n texture2D(tex, fragCoord * inverseVP + dir * (2.0 / 3.0 - 0.5)).xyz);\n vec3 rgbB = rgbA * 0.5 + 0.25 * (\n texture2D(tex, fragCoord * inverseVP + dir * -0.5).xyz +\n texture2D(tex, fragCoord * inverseVP + dir * 0.5).xyz);\n\n float lumaB = dot(rgbB, luma);\n if ((lumaB < lumaMin) || (lumaB > lumaMax))\n color = vec4(rgbA, texColor.a);\n else\n color = vec4(rgbB, texColor.a);\n return color;\n}\n\nvoid main() {\n\n vec4 color;\n\n color = fxaa(uSampler, vFragCoord, inputSize.zw, v_rgbNW, v_rgbNE, v_rgbSW, v_rgbSE, v_rgbM);\n\n gl_FragColor = color;\n}\n";
  35992. /**
  35993. * Basic FXAA (Fast Approximate Anti-Aliasing) implementation based on the code on geeks3d.com
  35994. * with the modification that the texture2DLod stuff was removed since it is unsupported by WebGL.
  35995. * @see https://github.com/mitsuhiko/webgl-meincraft
  35996. * @memberof PIXI.filters
  35997. */
  35998. var FXAAFilter = /** @class */ (function (_super) {
  35999. __extends$3(FXAAFilter, _super);
  36000. function FXAAFilter() {
  36001. // TODO - needs work
  36002. return _super.call(this, vertex, fragment$1) || this;
  36003. }
  36004. return FXAAFilter;
  36005. }(Filter));
  36006. /*!
  36007. * @pixi/filter-noise - v6.5.10
  36008. * Compiled Thu, 06 Jul 2023 15:25:11 UTC
  36009. *
  36010. * @pixi/filter-noise is licensed under the MIT License.
  36011. * http://www.opensource.org/licenses/mit-license
  36012. */
  36013. /*! *****************************************************************************
  36014. Copyright (c) Microsoft Corporation.
  36015. Permission to use, copy, modify, and/or distribute this software for any
  36016. purpose with or without fee is hereby granted.
  36017. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  36018. REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
  36019. AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  36020. INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
  36021. LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
  36022. OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
  36023. PERFORMANCE OF THIS SOFTWARE.
  36024. ***************************************************************************** */
  36025. /* global Reflect, Promise */
  36026. var extendStatics$2 = function(d, b) {
  36027. extendStatics$2 = Object.setPrototypeOf ||
  36028. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  36029. function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } };
  36030. return extendStatics$2(d, b);
  36031. };
  36032. function __extends$2(d, b) {
  36033. extendStatics$2(d, b);
  36034. function __() { this.constructor = d; }
  36035. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  36036. }
  36037. var fragment = "precision highp float;\n\nvarying vec2 vTextureCoord;\nvarying vec4 vColor;\n\nuniform float uNoise;\nuniform float uSeed;\nuniform sampler2D uSampler;\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 = texture2D(uSampler, 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 gl_FragColor = color;\n}\n";
  36038. /**
  36039. * A Noise effect filter.
  36040. *
  36041. * original filter: https://github.com/evanw/glfx.js/blob/master/src/filters/adjust/noise.js
  36042. * @memberof PIXI.filters
  36043. * @author Vico @vicocotea
  36044. */
  36045. var NoiseFilter = /** @class */ (function (_super) {
  36046. __extends$2(NoiseFilter, _super);
  36047. /**
  36048. * @param {number} [noise=0.5] - The noise intensity, should be a normalized value in the range [0, 1].
  36049. * @param {number} [seed] - A random seed for the noise generation. Default is `Math.random()`.
  36050. */
  36051. function NoiseFilter(noise, seed) {
  36052. if (noise === void 0) { noise = 0.5; }
  36053. if (seed === void 0) { seed = Math.random(); }
  36054. var _this = _super.call(this, defaultFilterVertex, fragment, {
  36055. uNoise: 0,
  36056. uSeed: 0,
  36057. }) || this;
  36058. _this.noise = noise;
  36059. _this.seed = seed;
  36060. return _this;
  36061. }
  36062. Object.defineProperty(NoiseFilter.prototype, "noise", {
  36063. /**
  36064. * The amount of noise to apply, this value should be in the range (0, 1].
  36065. * @default 0.5
  36066. */
  36067. get: function () {
  36068. return this.uniforms.uNoise;
  36069. },
  36070. set: function (value) {
  36071. this.uniforms.uNoise = value;
  36072. },
  36073. enumerable: false,
  36074. configurable: true
  36075. });
  36076. Object.defineProperty(NoiseFilter.prototype, "seed", {
  36077. /** A seed value to apply to the random noise generation. `Math.random()` is a good value to use. */
  36078. get: function () {
  36079. return this.uniforms.uSeed;
  36080. },
  36081. set: function (value) {
  36082. this.uniforms.uSeed = value;
  36083. },
  36084. enumerable: false,
  36085. configurable: true
  36086. });
  36087. return NoiseFilter;
  36088. }(Filter));
  36089. /*!
  36090. * @pixi/mixin-cache-as-bitmap - v6.5.10
  36091. * Compiled Thu, 06 Jul 2023 15:25:11 UTC
  36092. *
  36093. * @pixi/mixin-cache-as-bitmap is licensed under the MIT License.
  36094. * http://www.opensource.org/licenses/mit-license
  36095. */
  36096. var _tempMatrix = new Matrix();
  36097. DisplayObject.prototype._cacheAsBitmap = false;
  36098. DisplayObject.prototype._cacheData = null;
  36099. DisplayObject.prototype._cacheAsBitmapResolution = null;
  36100. DisplayObject.prototype._cacheAsBitmapMultisample = MSAA_QUALITY.NONE;
  36101. // figured there's no point adding ALL the extra variables to prototype.
  36102. // this model can hold the information needed. This can also be generated on demand as
  36103. // most objects are not cached as bitmaps.
  36104. /**
  36105. * @class
  36106. * @ignore
  36107. * @private
  36108. */
  36109. var CacheData = /** @class */ (function () {
  36110. function CacheData() {
  36111. this.textureCacheId = null;
  36112. this.originalRender = null;
  36113. this.originalRenderCanvas = null;
  36114. this.originalCalculateBounds = null;
  36115. this.originalGetLocalBounds = null;
  36116. this.originalUpdateTransform = null;
  36117. this.originalDestroy = null;
  36118. this.originalMask = null;
  36119. this.originalFilterArea = null;
  36120. this.originalContainsPoint = null;
  36121. this.sprite = null;
  36122. }
  36123. return CacheData;
  36124. }());
  36125. Object.defineProperties(DisplayObject.prototype, {
  36126. /**
  36127. * The resolution to use for cacheAsBitmap. By default this will use the renderer's resolution
  36128. * but can be overriden for performance. Lower values will reduce memory usage at the expense
  36129. * of render quality. A falsey value of `null` or `0` will default to the renderer's resolution.
  36130. * If `cacheAsBitmap` is set to `true`, this will re-render with the new resolution.
  36131. * @member {number} cacheAsBitmapResolution
  36132. * @memberof PIXI.DisplayObject#
  36133. * @default null
  36134. */
  36135. cacheAsBitmapResolution: {
  36136. get: function () {
  36137. return this._cacheAsBitmapResolution;
  36138. },
  36139. set: function (resolution) {
  36140. if (resolution === this._cacheAsBitmapResolution) {
  36141. return;
  36142. }
  36143. this._cacheAsBitmapResolution = resolution;
  36144. if (this.cacheAsBitmap) {
  36145. // Toggle to re-render at the new resolution
  36146. this.cacheAsBitmap = false;
  36147. this.cacheAsBitmap = true;
  36148. }
  36149. },
  36150. },
  36151. /**
  36152. * The number of samples to use for cacheAsBitmap. If set to `null`, the renderer's
  36153. * sample count is used.
  36154. * If `cacheAsBitmap` is set to `true`, this will re-render with the new number of samples.
  36155. * @member {number} cacheAsBitmapMultisample
  36156. * @memberof PIXI.DisplayObject#
  36157. * @default PIXI.MSAA_QUALITY.NONE
  36158. */
  36159. cacheAsBitmapMultisample: {
  36160. get: function () {
  36161. return this._cacheAsBitmapMultisample;
  36162. },
  36163. set: function (multisample) {
  36164. if (multisample === this._cacheAsBitmapMultisample) {
  36165. return;
  36166. }
  36167. this._cacheAsBitmapMultisample = multisample;
  36168. if (this.cacheAsBitmap) {
  36169. // Toggle to re-render with new multisample
  36170. this.cacheAsBitmap = false;
  36171. this.cacheAsBitmap = true;
  36172. }
  36173. },
  36174. },
  36175. /**
  36176. * Set this to true if you want this display object to be cached as a bitmap.
  36177. * This basically takes a snap shot of the display object as it is at that moment. It can
  36178. * provide a performance benefit for complex static displayObjects.
  36179. * To remove simply set this property to `false`
  36180. *
  36181. * IMPORTANT GOTCHA - Make sure that all your textures are preloaded BEFORE setting this property to true
  36182. * as it will take a snapshot of what is currently there. If the textures have not loaded then they will not appear.
  36183. * @member {boolean}
  36184. * @memberof PIXI.DisplayObject#
  36185. */
  36186. cacheAsBitmap: {
  36187. get: function () {
  36188. return this._cacheAsBitmap;
  36189. },
  36190. set: function (value) {
  36191. if (this._cacheAsBitmap === value) {
  36192. return;
  36193. }
  36194. this._cacheAsBitmap = value;
  36195. var data;
  36196. if (value) {
  36197. if (!this._cacheData) {
  36198. this._cacheData = new CacheData();
  36199. }
  36200. data = this._cacheData;
  36201. data.originalRender = this.render;
  36202. data.originalRenderCanvas = this.renderCanvas;
  36203. data.originalUpdateTransform = this.updateTransform;
  36204. data.originalCalculateBounds = this.calculateBounds;
  36205. data.originalGetLocalBounds = this.getLocalBounds;
  36206. data.originalDestroy = this.destroy;
  36207. data.originalContainsPoint = this.containsPoint;
  36208. data.originalMask = this._mask;
  36209. data.originalFilterArea = this.filterArea;
  36210. this.render = this._renderCached;
  36211. this.renderCanvas = this._renderCachedCanvas;
  36212. this.destroy = this._cacheAsBitmapDestroy;
  36213. }
  36214. else {
  36215. data = this._cacheData;
  36216. if (data.sprite) {
  36217. this._destroyCachedDisplayObject();
  36218. }
  36219. this.render = data.originalRender;
  36220. this.renderCanvas = data.originalRenderCanvas;
  36221. this.calculateBounds = data.originalCalculateBounds;
  36222. this.getLocalBounds = data.originalGetLocalBounds;
  36223. this.destroy = data.originalDestroy;
  36224. this.updateTransform = data.originalUpdateTransform;
  36225. this.containsPoint = data.originalContainsPoint;
  36226. this._mask = data.originalMask;
  36227. this.filterArea = data.originalFilterArea;
  36228. }
  36229. },
  36230. },
  36231. });
  36232. /**
  36233. * Renders a cached version of the sprite with WebGL
  36234. * @private
  36235. * @method _renderCached
  36236. * @memberof PIXI.DisplayObject#
  36237. * @param {PIXI.Renderer} renderer - the WebGL renderer
  36238. */
  36239. DisplayObject.prototype._renderCached = function _renderCached(renderer) {
  36240. if (!this.visible || this.worldAlpha <= 0 || !this.renderable) {
  36241. return;
  36242. }
  36243. this._initCachedDisplayObject(renderer);
  36244. this._cacheData.sprite.transform._worldID = this.transform._worldID;
  36245. this._cacheData.sprite.worldAlpha = this.worldAlpha;
  36246. this._cacheData.sprite._render(renderer);
  36247. };
  36248. /**
  36249. * Prepares the WebGL renderer to cache the sprite
  36250. * @private
  36251. * @method _initCachedDisplayObject
  36252. * @memberof PIXI.DisplayObject#
  36253. * @param {PIXI.Renderer} renderer - the WebGL renderer
  36254. */
  36255. DisplayObject.prototype._initCachedDisplayObject = function _initCachedDisplayObject(renderer) {
  36256. var _a;
  36257. if (this._cacheData && this._cacheData.sprite) {
  36258. return;
  36259. }
  36260. // make sure alpha is set to 1 otherwise it will get rendered as invisible!
  36261. var cacheAlpha = this.alpha;
  36262. this.alpha = 1;
  36263. // first we flush anything left in the renderer (otherwise it would get rendered to the cached texture)
  36264. renderer.batch.flush();
  36265. // this.filters= [];
  36266. // next we find the dimensions of the untransformed object
  36267. // this function also calls updatetransform on all its children as part of the measuring.
  36268. // This means we don't need to update the transform again in this function
  36269. // TODO pass an object to clone too? saves having to create a new one each time!
  36270. var bounds = this.getLocalBounds(null, true).clone();
  36271. // add some padding!
  36272. if (this.filters && this.filters.length) {
  36273. var padding = this.filters[0].padding;
  36274. bounds.pad(padding);
  36275. }
  36276. bounds.ceil(settings.RESOLUTION);
  36277. // for now we cache the current renderTarget that the WebGL renderer is currently using.
  36278. // this could be more elegant..
  36279. var cachedRenderTexture = renderer.renderTexture.current;
  36280. var cachedSourceFrame = renderer.renderTexture.sourceFrame.clone();
  36281. var cachedDestinationFrame = renderer.renderTexture.destinationFrame.clone();
  36282. var cachedProjectionTransform = renderer.projection.transform;
  36283. // We also store the filter stack - I will definitely look to change how this works a little later down the line.
  36284. // const stack = renderer.filterManager.filterStack;
  36285. // this renderTexture will be used to store the cached DisplayObject
  36286. var renderTexture = RenderTexture.create({
  36287. width: bounds.width,
  36288. height: bounds.height,
  36289. resolution: this.cacheAsBitmapResolution || renderer.resolution,
  36290. multisample: (_a = this.cacheAsBitmapMultisample) !== null && _a !== void 0 ? _a : renderer.multisample,
  36291. });
  36292. var textureCacheId = "cacheAsBitmap_" + uid();
  36293. this._cacheData.textureCacheId = textureCacheId;
  36294. BaseTexture.addToCache(renderTexture.baseTexture, textureCacheId);
  36295. Texture.addToCache(renderTexture, textureCacheId);
  36296. // need to set //
  36297. var m = this.transform.localTransform.copyTo(_tempMatrix).invert().translate(-bounds.x, -bounds.y);
  36298. // set all properties to there original so we can render to a texture
  36299. this.render = this._cacheData.originalRender;
  36300. renderer.render(this, { renderTexture: renderTexture, clear: true, transform: m, skipUpdateTransform: false });
  36301. renderer.framebuffer.blit();
  36302. // now restore the state be setting the new properties
  36303. renderer.projection.transform = cachedProjectionTransform;
  36304. renderer.renderTexture.bind(cachedRenderTexture, cachedSourceFrame, cachedDestinationFrame);
  36305. // renderer.filterManager.filterStack = stack;
  36306. this.render = this._renderCached;
  36307. // the rest is the same as for Canvas
  36308. this.updateTransform = this.displayObjectUpdateTransform;
  36309. this.calculateBounds = this._calculateCachedBounds;
  36310. this.getLocalBounds = this._getCachedLocalBounds;
  36311. this._mask = null;
  36312. this.filterArea = null;
  36313. this.alpha = cacheAlpha;
  36314. // create our cached sprite
  36315. var cachedSprite = new Sprite(renderTexture);
  36316. cachedSprite.transform.worldTransform = this.transform.worldTransform;
  36317. cachedSprite.anchor.x = -(bounds.x / bounds.width);
  36318. cachedSprite.anchor.y = -(bounds.y / bounds.height);
  36319. cachedSprite.alpha = cacheAlpha;
  36320. cachedSprite._bounds = this._bounds;
  36321. this._cacheData.sprite = cachedSprite;
  36322. this.transform._parentID = -1;
  36323. // restore the transform of the cached sprite to avoid the nasty flicker..
  36324. if (!this.parent) {
  36325. this.enableTempParent();
  36326. this.updateTransform();
  36327. this.disableTempParent(null);
  36328. }
  36329. else {
  36330. this.updateTransform();
  36331. }
  36332. // map the hit test..
  36333. this.containsPoint = cachedSprite.containsPoint.bind(cachedSprite);
  36334. };
  36335. /**
  36336. * Renders a cached version of the sprite with canvas
  36337. * @private
  36338. * @method _renderCachedCanvas
  36339. * @memberof PIXI.DisplayObject#
  36340. * @param {PIXI.CanvasRenderer} renderer - The canvas renderer
  36341. */
  36342. DisplayObject.prototype._renderCachedCanvas = function _renderCachedCanvas(renderer) {
  36343. if (!this.visible || this.worldAlpha <= 0 || !this.renderable) {
  36344. return;
  36345. }
  36346. this._initCachedDisplayObjectCanvas(renderer);
  36347. this._cacheData.sprite.worldAlpha = this.worldAlpha;
  36348. this._cacheData.sprite._renderCanvas(renderer);
  36349. };
  36350. // TODO this can be the same as the WebGL version.. will need to do a little tweaking first though..
  36351. /**
  36352. * Prepares the Canvas renderer to cache the sprite
  36353. * @private
  36354. * @method _initCachedDisplayObjectCanvas
  36355. * @memberof PIXI.DisplayObject#
  36356. * @param {PIXI.CanvasRenderer} renderer - The canvas renderer
  36357. */
  36358. DisplayObject.prototype._initCachedDisplayObjectCanvas = function _initCachedDisplayObjectCanvas(renderer) {
  36359. if (this._cacheData && this._cacheData.sprite) {
  36360. return;
  36361. }
  36362. // get bounds actually transforms the object for us already!
  36363. var bounds = this.getLocalBounds(null, true);
  36364. var cacheAlpha = this.alpha;
  36365. this.alpha = 1;
  36366. var cachedRenderTarget = renderer.context;
  36367. var cachedProjectionTransform = renderer._projTransform;
  36368. bounds.ceil(settings.RESOLUTION);
  36369. var renderTexture = RenderTexture.create({ width: bounds.width, height: bounds.height });
  36370. var textureCacheId = "cacheAsBitmap_" + uid();
  36371. this._cacheData.textureCacheId = textureCacheId;
  36372. BaseTexture.addToCache(renderTexture.baseTexture, textureCacheId);
  36373. Texture.addToCache(renderTexture, textureCacheId);
  36374. // need to set //
  36375. var m = _tempMatrix;
  36376. this.transform.localTransform.copyTo(m);
  36377. m.invert();
  36378. m.tx -= bounds.x;
  36379. m.ty -= bounds.y;
  36380. // m.append(this.transform.worldTransform.)
  36381. // set all properties to there original so we can render to a texture
  36382. this.renderCanvas = this._cacheData.originalRenderCanvas;
  36383. renderer.render(this, { renderTexture: renderTexture, clear: true, transform: m, skipUpdateTransform: false });
  36384. // now restore the state be setting the new properties
  36385. renderer.context = cachedRenderTarget;
  36386. renderer._projTransform = cachedProjectionTransform;
  36387. this.renderCanvas = this._renderCachedCanvas;
  36388. // the rest is the same as for WebGL
  36389. this.updateTransform = this.displayObjectUpdateTransform;
  36390. this.calculateBounds = this._calculateCachedBounds;
  36391. this.getLocalBounds = this._getCachedLocalBounds;
  36392. this._mask = null;
  36393. this.filterArea = null;
  36394. this.alpha = cacheAlpha;
  36395. // create our cached sprite
  36396. var cachedSprite = new Sprite(renderTexture);
  36397. cachedSprite.transform.worldTransform = this.transform.worldTransform;
  36398. cachedSprite.anchor.x = -(bounds.x / bounds.width);
  36399. cachedSprite.anchor.y = -(bounds.y / bounds.height);
  36400. cachedSprite.alpha = cacheAlpha;
  36401. cachedSprite._bounds = this._bounds;
  36402. this._cacheData.sprite = cachedSprite;
  36403. this.transform._parentID = -1;
  36404. // restore the transform of the cached sprite to avoid the nasty flicker..
  36405. if (!this.parent) {
  36406. this.parent = renderer._tempDisplayObjectParent;
  36407. this.updateTransform();
  36408. this.parent = null;
  36409. }
  36410. else {
  36411. this.updateTransform();
  36412. }
  36413. // map the hit test..
  36414. this.containsPoint = cachedSprite.containsPoint.bind(cachedSprite);
  36415. };
  36416. /**
  36417. * Calculates the bounds of the cached sprite
  36418. * @private
  36419. * @method
  36420. */
  36421. DisplayObject.prototype._calculateCachedBounds = function _calculateCachedBounds() {
  36422. this._bounds.clear();
  36423. this._cacheData.sprite.transform._worldID = this.transform._worldID;
  36424. this._cacheData.sprite._calculateBounds();
  36425. this._bounds.updateID = this._boundsID;
  36426. };
  36427. /**
  36428. * Gets the bounds of the cached sprite.
  36429. * @private
  36430. * @method
  36431. * @returns {Rectangle} The local bounds.
  36432. */
  36433. DisplayObject.prototype._getCachedLocalBounds = function _getCachedLocalBounds() {
  36434. return this._cacheData.sprite.getLocalBounds(null);
  36435. };
  36436. /**
  36437. * Destroys the cached sprite.
  36438. * @private
  36439. * @method
  36440. */
  36441. DisplayObject.prototype._destroyCachedDisplayObject = function _destroyCachedDisplayObject() {
  36442. this._cacheData.sprite._texture.destroy(true);
  36443. this._cacheData.sprite = null;
  36444. BaseTexture.removeFromCache(this._cacheData.textureCacheId);
  36445. Texture.removeFromCache(this._cacheData.textureCacheId);
  36446. this._cacheData.textureCacheId = null;
  36447. };
  36448. /**
  36449. * Destroys the cached object.
  36450. * @private
  36451. * @method
  36452. * @param {object|boolean} [options] - Options parameter. A boolean will act as if all options
  36453. * have been set to that value.
  36454. * Used when destroying containers, see the Container.destroy method.
  36455. */
  36456. DisplayObject.prototype._cacheAsBitmapDestroy = function _cacheAsBitmapDestroy(options) {
  36457. this.cacheAsBitmap = false;
  36458. this.destroy(options);
  36459. };
  36460. /*!
  36461. * @pixi/mixin-get-child-by-name - v6.5.10
  36462. * Compiled Thu, 06 Jul 2023 15:25:11 UTC
  36463. *
  36464. * @pixi/mixin-get-child-by-name is licensed under the MIT License.
  36465. * http://www.opensource.org/licenses/mit-license
  36466. */
  36467. /**
  36468. * The instance name of the object.
  36469. * @memberof PIXI.DisplayObject#
  36470. * @member {string} name
  36471. */
  36472. DisplayObject.prototype.name = null;
  36473. /**
  36474. * Returns the display object in the container.
  36475. *
  36476. * Recursive searches are done in a preorder traversal.
  36477. * @method getChildByName
  36478. * @memberof PIXI.Container#
  36479. * @param {string} name - Instance name.
  36480. * @param {boolean}[deep=false] - Whether to search recursively
  36481. * @returns {PIXI.DisplayObject} The child with the specified name.
  36482. */
  36483. Container.prototype.getChildByName = function getChildByName(name, deep) {
  36484. for (var i = 0, j = this.children.length; i < j; i++) {
  36485. if (this.children[i].name === name) {
  36486. return this.children[i];
  36487. }
  36488. }
  36489. if (deep) {
  36490. for (var i = 0, j = this.children.length; i < j; i++) {
  36491. var child = this.children[i];
  36492. if (!child.getChildByName) {
  36493. continue;
  36494. }
  36495. var target = child.getChildByName(name, true);
  36496. if (target) {
  36497. return target;
  36498. }
  36499. }
  36500. }
  36501. return null;
  36502. };
  36503. /*!
  36504. * @pixi/mixin-get-global-position - v6.5.10
  36505. * Compiled Thu, 06 Jul 2023 15:25:11 UTC
  36506. *
  36507. * @pixi/mixin-get-global-position is licensed under the MIT License.
  36508. * http://www.opensource.org/licenses/mit-license
  36509. */
  36510. /**
  36511. * Returns the global position of the displayObject. Does not depend on object scale, rotation and pivot.
  36512. * @method getGlobalPosition
  36513. * @memberof PIXI.DisplayObject#
  36514. * @param {PIXI.Point} [point=new PIXI.Point()] - The point to write the global value to.
  36515. * @param {boolean} [skipUpdate=false] - Setting to true will stop the transforms of the scene graph from
  36516. * being updated. This means the calculation returned MAY be out of date BUT will give you a
  36517. * nice performance boost.
  36518. * @returns {PIXI.Point} The updated point.
  36519. */
  36520. DisplayObject.prototype.getGlobalPosition = function getGlobalPosition(point, skipUpdate) {
  36521. if (point === void 0) { point = new Point(); }
  36522. if (skipUpdate === void 0) { skipUpdate = false; }
  36523. if (this.parent) {
  36524. this.parent.toGlobal(this.position, point, skipUpdate);
  36525. }
  36526. else {
  36527. point.x = this.position.x;
  36528. point.y = this.position.y;
  36529. }
  36530. return point;
  36531. };
  36532. /*!
  36533. * @pixi/app - v6.5.10
  36534. * Compiled Thu, 06 Jul 2023 15:25:11 UTC
  36535. *
  36536. * @pixi/app is licensed under the MIT License.
  36537. * http://www.opensource.org/licenses/mit-license
  36538. */
  36539. /**
  36540. * Middleware for for Application's resize functionality
  36541. * @private
  36542. * @class
  36543. */
  36544. var ResizePlugin = /** @class */ (function () {
  36545. function ResizePlugin() {
  36546. }
  36547. /**
  36548. * Initialize the plugin with scope of application instance
  36549. * @static
  36550. * @private
  36551. * @param {object} [options] - See application options
  36552. */
  36553. ResizePlugin.init = function (options) {
  36554. var _this = this;
  36555. Object.defineProperty(this, 'resizeTo',
  36556. /**
  36557. * The HTML element or window to automatically resize the
  36558. * renderer's view element to match width and height.
  36559. * @member {Window|HTMLElement}
  36560. * @name resizeTo
  36561. * @memberof PIXI.Application#
  36562. */
  36563. {
  36564. set: function (dom) {
  36565. globalThis.removeEventListener('resize', this.queueResize);
  36566. this._resizeTo = dom;
  36567. if (dom) {
  36568. globalThis.addEventListener('resize', this.queueResize);
  36569. this.resize();
  36570. }
  36571. },
  36572. get: function () {
  36573. return this._resizeTo;
  36574. },
  36575. });
  36576. /**
  36577. * Resize is throttled, so it's safe to call this multiple times per frame and it'll
  36578. * only be called once.
  36579. * @memberof PIXI.Application#
  36580. * @method queueResize
  36581. * @private
  36582. */
  36583. this.queueResize = function () {
  36584. if (!_this._resizeTo) {
  36585. return;
  36586. }
  36587. _this.cancelResize();
  36588. // // Throttle resize events per raf
  36589. _this._resizeId = requestAnimationFrame(function () { return _this.resize(); });
  36590. };
  36591. /**
  36592. * Cancel the resize queue.
  36593. * @memberof PIXI.Application#
  36594. * @method cancelResize
  36595. * @private
  36596. */
  36597. this.cancelResize = function () {
  36598. if (_this._resizeId) {
  36599. cancelAnimationFrame(_this._resizeId);
  36600. _this._resizeId = null;
  36601. }
  36602. };
  36603. /**
  36604. * Execute an immediate resize on the renderer, this is not
  36605. * throttled and can be expensive to call many times in a row.
  36606. * Will resize only if `resizeTo` property is set.
  36607. * @memberof PIXI.Application#
  36608. * @method resize
  36609. */
  36610. this.resize = function () {
  36611. if (!_this._resizeTo) {
  36612. return;
  36613. }
  36614. // clear queue resize
  36615. _this.cancelResize();
  36616. var width;
  36617. var height;
  36618. // Resize to the window
  36619. if (_this._resizeTo === globalThis.window) {
  36620. width = globalThis.innerWidth;
  36621. height = globalThis.innerHeight;
  36622. }
  36623. // Resize to other HTML entities
  36624. else {
  36625. var _a = _this._resizeTo, clientWidth = _a.clientWidth, clientHeight = _a.clientHeight;
  36626. width = clientWidth;
  36627. height = clientHeight;
  36628. }
  36629. _this.renderer.resize(width, height);
  36630. };
  36631. // On resize
  36632. this._resizeId = null;
  36633. this._resizeTo = null;
  36634. this.resizeTo = options.resizeTo || null;
  36635. };
  36636. /**
  36637. * Clean up the ticker, scoped to application
  36638. * @static
  36639. * @private
  36640. */
  36641. ResizePlugin.destroy = function () {
  36642. globalThis.removeEventListener('resize', this.queueResize);
  36643. this.cancelResize();
  36644. this.cancelResize = null;
  36645. this.queueResize = null;
  36646. this.resizeTo = null;
  36647. this.resize = null;
  36648. };
  36649. /** @ignore */
  36650. ResizePlugin.extension = ExtensionType.Application;
  36651. return ResizePlugin;
  36652. }());
  36653. /**
  36654. * Convenience class to create a new PIXI application.
  36655. *
  36656. * This class automatically creates the renderer, ticker and root container.
  36657. * @example
  36658. * // Create the application
  36659. * const app = new PIXI.Application();
  36660. *
  36661. * // Add the view to the DOM
  36662. * document.body.appendChild(app.view);
  36663. *
  36664. * // ex, add display objects
  36665. * app.stage.addChild(PIXI.Sprite.from('something.png'));
  36666. * @class
  36667. * @memberof PIXI
  36668. */
  36669. var Application = /** @class */ (function () {
  36670. /**
  36671. * @param {PIXI.IApplicationOptions} [options] - The optional application and renderer parameters.
  36672. * @param {boolean} [options.antialias=false] -
  36673. * **WebGL Only.** Whether to enable anti-aliasing. This may affect performance.
  36674. * @param {boolean} [options.autoDensity=false] -
  36675. * Whether the CSS dimensions of the renderer's view should be resized automatically.
  36676. * @param {boolean} [options.autoStart=true] - Automatically starts the rendering after the construction.
  36677. * **Note**: Setting this parameter to false does NOT stop the shared ticker even if you set
  36678. * `options.sharedTicker` to `true` in case that it is already started. Stop it by your own.
  36679. * @param {number} [options.backgroundAlpha=1] -
  36680. * Transparency of the background color, value from `0` (fully transparent) to `1` (fully opaque).
  36681. * @param {number} [options.backgroundColor=0x000000] -
  36682. * The background color used to clear the canvas. It accepts hex numbers (e.g. `0xff0000`).
  36683. * @param {boolean} [options.clearBeforeRender=true] - Whether to clear the canvas before new render passes.
  36684. * @param {PIXI.IRenderingContext} [options.context] - **WebGL Only.** User-provided WebGL rendering context object.
  36685. * @param {boolean} [options.forceCanvas=false] -
  36686. * Force using {@link PIXI.CanvasRenderer}, even if WebGL is available. This option only is available when
  36687. * using **pixi.js-legacy** or **@pixi/canvas-renderer** packages, otherwise it is ignored.
  36688. * @param {number} [options.height=600] - The height of the renderer's view.
  36689. * @param {string} [options.powerPreference] -
  36690. * **WebGL Only.** A hint indicating what configuration of GPU is suitable for the WebGL context,
  36691. * can be `'default'`, `'high-performance'` or `'low-power'`.
  36692. * Setting to `'high-performance'` will prioritize rendering performance over power consumption,
  36693. * while setting to `'low-power'` will prioritize power saving over rendering performance.
  36694. * @param {boolean} [options.premultipliedAlpha=true] -
  36695. * **WebGL Only.** Whether the compositor will assume the drawing buffer contains colors with premultiplied alpha.
  36696. * @param {boolean} [options.preserveDrawingBuffer=false] -
  36697. * **WebGL Only.** Whether to enable drawing buffer preservation. If enabled, the drawing buffer will preserve
  36698. * its value until cleared or overwritten. Enable this if you need to call `toDataUrl` on the WebGL context.
  36699. * @param {Window|HTMLElement} [options.resizeTo] - Element to automatically resize stage to.
  36700. * @param {number} [options.resolution=PIXI.settings.RESOLUTION] -
  36701. * The resolution / device pixel ratio of the renderer.
  36702. * @param {boolean} [options.sharedLoader=false] - `true` to use PIXI.Loader.shared, `false` to create new Loader.
  36703. * @param {boolean} [options.sharedTicker=false] - `true` to use PIXI.Ticker.shared, `false` to create new ticker.
  36704. * If set to `false`, you cannot register a handler to occur before anything that runs on the shared ticker.
  36705. * The system ticker will always run before both the shared ticker and the app ticker.
  36706. * @param {boolean} [options.transparent] -
  36707. * **Deprecated since 6.0.0, Use `backgroundAlpha` instead.** \
  36708. * `true` sets `backgroundAlpha` to `0`, `false` sets `backgroundAlpha` to `1`.
  36709. * @param {boolean|'notMultiplied'} [options.useContextAlpha=true] -
  36710. * Pass-through value for canvas' context attribute `alpha`. This option is for cases where the
  36711. * canvas needs to be opaque, possibly for performance reasons on some older devices.
  36712. * If you want to set transparency, please use `backgroundAlpha`. \
  36713. * **WebGL Only:** When set to `'notMultiplied'`, the canvas' context attribute `alpha` will be
  36714. * set to `true` and `premultipliedAlpha` will be to `false`.
  36715. * @param {HTMLCanvasElement} [options.view=null] -
  36716. * The canvas to use as the view. If omitted, a new canvas will be created.
  36717. * @param {number} [options.width=800] - The width of the renderer's view.
  36718. */
  36719. function Application(options) {
  36720. var _this = this;
  36721. /**
  36722. * The root display container that's rendered.
  36723. * @member {PIXI.Container}
  36724. */
  36725. this.stage = new Container();
  36726. // The default options
  36727. options = Object.assign({
  36728. forceCanvas: false,
  36729. }, options);
  36730. this.renderer = autoDetectRenderer(options);
  36731. // install plugins here
  36732. Application._plugins.forEach(function (plugin) {
  36733. plugin.init.call(_this, options);
  36734. });
  36735. }
  36736. /**
  36737. * Use the {@link PIXI.extensions.add} API to register plugins.
  36738. * @deprecated since 6.5.0
  36739. * @static
  36740. * @param {PIXI.IApplicationPlugin} plugin - Plugin being installed
  36741. */
  36742. Application.registerPlugin = function (plugin) {
  36743. deprecation('6.5.0', 'Application.registerPlugin() is deprecated, use extensions.add()');
  36744. extensions.add({
  36745. type: ExtensionType.Application,
  36746. ref: plugin,
  36747. });
  36748. };
  36749. /** Render the current stage. */
  36750. Application.prototype.render = function () {
  36751. this.renderer.render(this.stage);
  36752. };
  36753. Object.defineProperty(Application.prototype, "view", {
  36754. /**
  36755. * Reference to the renderer's canvas element.
  36756. * @member {HTMLCanvasElement}
  36757. * @readonly
  36758. */
  36759. get: function () {
  36760. return this.renderer.view;
  36761. },
  36762. enumerable: false,
  36763. configurable: true
  36764. });
  36765. Object.defineProperty(Application.prototype, "screen", {
  36766. /**
  36767. * Reference to the renderer's screen rectangle. Its safe to use as `filterArea` or `hitArea` for the whole screen.
  36768. * @member {PIXI.Rectangle}
  36769. * @readonly
  36770. */
  36771. get: function () {
  36772. return this.renderer.screen;
  36773. },
  36774. enumerable: false,
  36775. configurable: true
  36776. });
  36777. /**
  36778. * Destroy and don't use after this.
  36779. * @param {boolean} [removeView=false] - Automatically remove canvas from DOM.
  36780. * @param {object|boolean} [stageOptions] - Options parameter. A boolean will act as if all options
  36781. * have been set to that value
  36782. * @param {boolean} [stageOptions.children=false] - if set to true, all the children will have their destroy
  36783. * method called as well. 'stageOptions' will be passed on to those calls.
  36784. * @param {boolean} [stageOptions.texture=false] - Only used for child Sprites if stageOptions.children is set
  36785. * to true. Should it destroy the texture of the child sprite
  36786. * @param {boolean} [stageOptions.baseTexture=false] - Only used for child Sprites if stageOptions.children is set
  36787. * to true. Should it destroy the base texture of the child sprite
  36788. */
  36789. Application.prototype.destroy = function (removeView, stageOptions) {
  36790. var _this = this;
  36791. // Destroy plugins in the opposite order
  36792. // which they were constructed
  36793. var plugins = Application._plugins.slice(0);
  36794. plugins.reverse();
  36795. plugins.forEach(function (plugin) {
  36796. plugin.destroy.call(_this);
  36797. });
  36798. this.stage.destroy(stageOptions);
  36799. this.stage = null;
  36800. this.renderer.destroy(removeView);
  36801. this.renderer = null;
  36802. };
  36803. /** Collection of installed plugins. */
  36804. Application._plugins = [];
  36805. return Application;
  36806. }());
  36807. extensions.handleByList(ExtensionType.Application, Application._plugins);
  36808. extensions.add(ResizePlugin);
  36809. /*!
  36810. * @pixi/mesh-extras - v6.5.10
  36811. * Compiled Thu, 06 Jul 2023 15:25:11 UTC
  36812. *
  36813. * @pixi/mesh-extras is licensed under the MIT License.
  36814. * http://www.opensource.org/licenses/mit-license
  36815. */
  36816. /*! *****************************************************************************
  36817. Copyright (c) Microsoft Corporation.
  36818. Permission to use, copy, modify, and/or distribute this software for any
  36819. purpose with or without fee is hereby granted.
  36820. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  36821. REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
  36822. AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  36823. INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
  36824. LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
  36825. OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
  36826. PERFORMANCE OF THIS SOFTWARE.
  36827. ***************************************************************************** */
  36828. /* global Reflect, Promise */
  36829. var extendStatics$1 = function(d, b) {
  36830. extendStatics$1 = Object.setPrototypeOf ||
  36831. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  36832. function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } };
  36833. return extendStatics$1(d, b);
  36834. };
  36835. function __extends$1(d, b) {
  36836. extendStatics$1(d, b);
  36837. function __() { this.constructor = d; }
  36838. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  36839. }
  36840. /**
  36841. * @memberof PIXI
  36842. */
  36843. var PlaneGeometry = /** @class */ (function (_super) {
  36844. __extends$1(PlaneGeometry, _super);
  36845. /**
  36846. * @param width - The width of the plane.
  36847. * @param height - The height of the plane.
  36848. * @param segWidth - Number of horizontal segments.
  36849. * @param segHeight - Number of vertical segments.
  36850. */
  36851. function PlaneGeometry(width, height, segWidth, segHeight) {
  36852. if (width === void 0) { width = 100; }
  36853. if (height === void 0) { height = 100; }
  36854. if (segWidth === void 0) { segWidth = 10; }
  36855. if (segHeight === void 0) { segHeight = 10; }
  36856. var _this = _super.call(this) || this;
  36857. _this.segWidth = segWidth;
  36858. _this.segHeight = segHeight;
  36859. _this.width = width;
  36860. _this.height = height;
  36861. _this.build();
  36862. return _this;
  36863. }
  36864. /**
  36865. * Refreshes plane coordinates
  36866. * @private
  36867. */
  36868. PlaneGeometry.prototype.build = function () {
  36869. var total = this.segWidth * this.segHeight;
  36870. var verts = [];
  36871. var uvs = [];
  36872. var indices = [];
  36873. var segmentsX = this.segWidth - 1;
  36874. var segmentsY = this.segHeight - 1;
  36875. var sizeX = (this.width) / segmentsX;
  36876. var sizeY = (this.height) / segmentsY;
  36877. for (var i = 0; i < total; i++) {
  36878. var x = (i % this.segWidth);
  36879. var y = ((i / this.segWidth) | 0);
  36880. verts.push(x * sizeX, y * sizeY);
  36881. uvs.push(x / segmentsX, y / segmentsY);
  36882. }
  36883. var totalSub = segmentsX * segmentsY;
  36884. for (var i = 0; i < totalSub; i++) {
  36885. var xpos = i % segmentsX;
  36886. var ypos = (i / segmentsX) | 0;
  36887. var value = (ypos * this.segWidth) + xpos;
  36888. var value2 = (ypos * this.segWidth) + xpos + 1;
  36889. var value3 = ((ypos + 1) * this.segWidth) + xpos;
  36890. var value4 = ((ypos + 1) * this.segWidth) + xpos + 1;
  36891. indices.push(value, value2, value3, value2, value4, value3);
  36892. }
  36893. this.buffers[0].data = new Float32Array(verts);
  36894. this.buffers[1].data = new Float32Array(uvs);
  36895. this.indexBuffer.data = new Uint16Array(indices);
  36896. // ensure that the changes are uploaded
  36897. this.buffers[0].update();
  36898. this.buffers[1].update();
  36899. this.indexBuffer.update();
  36900. };
  36901. return PlaneGeometry;
  36902. }(MeshGeometry));
  36903. /**
  36904. * RopeGeometry allows you to draw a geometry across several points and then manipulate these points.
  36905. *
  36906. * ```js
  36907. * for (let i = 0; i < 20; i++) {
  36908. * points.push(new PIXI.Point(i * 50, 0));
  36909. * };
  36910. * const rope = new PIXI.RopeGeometry(100, points);
  36911. * ```
  36912. * @memberof PIXI
  36913. */
  36914. var RopeGeometry = /** @class */ (function (_super) {
  36915. __extends$1(RopeGeometry, _super);
  36916. /**
  36917. * @param width - The width (i.e., thickness) of the rope.
  36918. * @param points - An array of {@link PIXI.Point} objects to construct this rope.
  36919. * @param textureScale - By default the rope texture will be stretched to match
  36920. * rope length. If textureScale is positive this value will be treated as a scaling
  36921. * factor and the texture will preserve its aspect ratio instead. To create a tiling rope
  36922. * set baseTexture.wrapMode to {@link PIXI.WRAP_MODES.REPEAT} and use a power of two texture,
  36923. * then set textureScale=1 to keep the original texture pixel size.
  36924. * In order to reduce alpha channel artifacts provide a larger texture and downsample -
  36925. * i.e. set textureScale=0.5 to scale it down twice.
  36926. */
  36927. function RopeGeometry(width, points, textureScale) {
  36928. if (width === void 0) { width = 200; }
  36929. if (textureScale === void 0) { textureScale = 0; }
  36930. var _this = _super.call(this, new Float32Array(points.length * 4), new Float32Array(points.length * 4), new Uint16Array((points.length - 1) * 6)) || this;
  36931. _this.points = points;
  36932. _this._width = width;
  36933. _this.textureScale = textureScale;
  36934. _this.build();
  36935. return _this;
  36936. }
  36937. Object.defineProperty(RopeGeometry.prototype, "width", {
  36938. /**
  36939. * The width (i.e., thickness) of the rope.
  36940. * @readonly
  36941. */
  36942. get: function () {
  36943. return this._width;
  36944. },
  36945. enumerable: false,
  36946. configurable: true
  36947. });
  36948. /** Refreshes Rope indices and uvs */
  36949. RopeGeometry.prototype.build = function () {
  36950. var points = this.points;
  36951. if (!points)
  36952. { return; }
  36953. var vertexBuffer = this.getBuffer('aVertexPosition');
  36954. var uvBuffer = this.getBuffer('aTextureCoord');
  36955. var indexBuffer = this.getIndex();
  36956. // if too little points, or texture hasn't got UVs set yet just move on.
  36957. if (points.length < 1) {
  36958. return;
  36959. }
  36960. // if the number of points has changed we will need to recreate the arraybuffers
  36961. if (vertexBuffer.data.length / 4 !== points.length) {
  36962. vertexBuffer.data = new Float32Array(points.length * 4);
  36963. uvBuffer.data = new Float32Array(points.length * 4);
  36964. indexBuffer.data = new Uint16Array((points.length - 1) * 6);
  36965. }
  36966. var uvs = uvBuffer.data;
  36967. var indices = indexBuffer.data;
  36968. uvs[0] = 0;
  36969. uvs[1] = 0;
  36970. uvs[2] = 0;
  36971. uvs[3] = 1;
  36972. var amount = 0;
  36973. var prev = points[0];
  36974. var textureWidth = this._width * this.textureScale;
  36975. var total = points.length; // - 1;
  36976. for (var i = 0; i < total; i++) {
  36977. // time to do some smart drawing!
  36978. var index = i * 4;
  36979. if (this.textureScale > 0) {
  36980. // calculate pixel distance from previous point
  36981. var dx = prev.x - points[i].x;
  36982. var dy = prev.y - points[i].y;
  36983. var distance = Math.sqrt((dx * dx) + (dy * dy));
  36984. prev = points[i];
  36985. amount += distance / textureWidth;
  36986. }
  36987. else {
  36988. // stretch texture
  36989. amount = i / (total - 1);
  36990. }
  36991. uvs[index] = amount;
  36992. uvs[index + 1] = 0;
  36993. uvs[index + 2] = amount;
  36994. uvs[index + 3] = 1;
  36995. }
  36996. var indexCount = 0;
  36997. for (var i = 0; i < total - 1; i++) {
  36998. var index = i * 2;
  36999. indices[indexCount++] = index;
  37000. indices[indexCount++] = index + 1;
  37001. indices[indexCount++] = index + 2;
  37002. indices[indexCount++] = index + 2;
  37003. indices[indexCount++] = index + 1;
  37004. indices[indexCount++] = index + 3;
  37005. }
  37006. // ensure that the changes are uploaded
  37007. uvBuffer.update();
  37008. indexBuffer.update();
  37009. this.updateVertices();
  37010. };
  37011. /** refreshes vertices of Rope mesh */
  37012. RopeGeometry.prototype.updateVertices = function () {
  37013. var points = this.points;
  37014. if (points.length < 1) {
  37015. return;
  37016. }
  37017. var lastPoint = points[0];
  37018. var nextPoint;
  37019. var perpX = 0;
  37020. var perpY = 0;
  37021. var vertices = this.buffers[0].data;
  37022. var total = points.length;
  37023. for (var i = 0; i < total; i++) {
  37024. var point = points[i];
  37025. var index = i * 4;
  37026. if (i < points.length - 1) {
  37027. nextPoint = points[i + 1];
  37028. }
  37029. else {
  37030. nextPoint = point;
  37031. }
  37032. perpY = -(nextPoint.x - lastPoint.x);
  37033. perpX = nextPoint.y - lastPoint.y;
  37034. var perpLength = Math.sqrt((perpX * perpX) + (perpY * perpY));
  37035. var num = this.textureScale > 0 ? this.textureScale * this._width / 2 : this._width / 2;
  37036. perpX /= perpLength;
  37037. perpY /= perpLength;
  37038. perpX *= num;
  37039. perpY *= num;
  37040. vertices[index] = point.x + perpX;
  37041. vertices[index + 1] = point.y + perpY;
  37042. vertices[index + 2] = point.x - perpX;
  37043. vertices[index + 3] = point.y - perpY;
  37044. lastPoint = point;
  37045. }
  37046. this.buffers[0].update();
  37047. };
  37048. RopeGeometry.prototype.update = function () {
  37049. if (this.textureScale > 0) {
  37050. this.build(); // we need to update UVs
  37051. }
  37052. else {
  37053. this.updateVertices();
  37054. }
  37055. };
  37056. return RopeGeometry;
  37057. }(MeshGeometry));
  37058. /**
  37059. * The rope allows you to draw a texture across several points and then manipulate these points
  37060. *
  37061. *```js
  37062. * for (let i = 0; i < 20; i++) {
  37063. * points.push(new PIXI.Point(i * 50, 0));
  37064. * };
  37065. * let rope = new PIXI.SimpleRope(PIXI.Texture.from("snake.png"), points);
  37066. * ```
  37067. * @memberof PIXI
  37068. */
  37069. var SimpleRope = /** @class */ (function (_super) {
  37070. __extends$1(SimpleRope, _super);
  37071. /**
  37072. * @param texture - The texture to use on the rope.
  37073. * @param points - An array of {@link PIXI.Point} objects to construct this rope.
  37074. * @param {number} textureScale - Optional. Positive values scale rope texture
  37075. * keeping its aspect ratio. You can reduce alpha channel artifacts by providing a larger texture
  37076. * and downsampling here. If set to zero, texture will be stretched instead.
  37077. */
  37078. function SimpleRope(texture, points, textureScale) {
  37079. if (textureScale === void 0) { textureScale = 0; }
  37080. var _this = this;
  37081. var ropeGeometry = new RopeGeometry(texture.height, points, textureScale);
  37082. var meshMaterial = new MeshMaterial(texture);
  37083. if (textureScale > 0) {
  37084. // attempt to set UV wrapping, will fail on non-power of two textures
  37085. texture.baseTexture.wrapMode = WRAP_MODES.REPEAT;
  37086. }
  37087. _this = _super.call(this, ropeGeometry, meshMaterial) || this;
  37088. /**
  37089. * re-calculate vertices by rope points each frame
  37090. * @member {boolean}
  37091. */
  37092. _this.autoUpdate = true;
  37093. return _this;
  37094. }
  37095. SimpleRope.prototype._render = function (renderer) {
  37096. var geometry = this.geometry;
  37097. if (this.autoUpdate || geometry._width !== this.shader.texture.height) {
  37098. geometry._width = this.shader.texture.height;
  37099. geometry.update();
  37100. }
  37101. _super.prototype._render.call(this, renderer);
  37102. };
  37103. return SimpleRope;
  37104. }(Mesh));
  37105. /**
  37106. * The SimplePlane allows you to draw a texture across several points and then manipulate these points
  37107. *
  37108. *```js
  37109. * for (let i = 0; i < 20; i++) {
  37110. * points.push(new PIXI.Point(i * 50, 0));
  37111. * };
  37112. * let SimplePlane = new PIXI.SimplePlane(PIXI.Texture.from("snake.png"), points);
  37113. * ```
  37114. * @memberof PIXI
  37115. */
  37116. var SimplePlane = /** @class */ (function (_super) {
  37117. __extends$1(SimplePlane, _super);
  37118. /**
  37119. * @param texture - The texture to use on the SimplePlane.
  37120. * @param verticesX - The number of vertices in the x-axis
  37121. * @param verticesY - The number of vertices in the y-axis
  37122. */
  37123. function SimplePlane(texture, verticesX, verticesY) {
  37124. var _this = this;
  37125. var planeGeometry = new PlaneGeometry(texture.width, texture.height, verticesX, verticesY);
  37126. var meshMaterial = new MeshMaterial(Texture.WHITE);
  37127. _this = _super.call(this, planeGeometry, meshMaterial) || this;
  37128. // lets call the setter to ensure all necessary updates are performed
  37129. _this.texture = texture;
  37130. _this.autoResize = true;
  37131. return _this;
  37132. }
  37133. /**
  37134. * Method used for overrides, to do something in case texture frame was changed.
  37135. * Meshes based on plane can override it and change more details based on texture.
  37136. */
  37137. SimplePlane.prototype.textureUpdated = function () {
  37138. this._textureID = this.shader.texture._updateID;
  37139. var geometry = this.geometry;
  37140. var _a = this.shader.texture, width = _a.width, height = _a.height;
  37141. if (this.autoResize && (geometry.width !== width || geometry.height !== height)) {
  37142. geometry.width = this.shader.texture.width;
  37143. geometry.height = this.shader.texture.height;
  37144. geometry.build();
  37145. }
  37146. };
  37147. Object.defineProperty(SimplePlane.prototype, "texture", {
  37148. get: function () {
  37149. return this.shader.texture;
  37150. },
  37151. set: function (value) {
  37152. // Track texture same way sprite does.
  37153. // For generated meshes like NineSlicePlane it can change the geometry.
  37154. // Unfortunately, this method might not work if you directly change texture in material.
  37155. if (this.shader.texture === value) {
  37156. return;
  37157. }
  37158. this.shader.texture = value;
  37159. this._textureID = -1;
  37160. if (value.baseTexture.valid) {
  37161. this.textureUpdated();
  37162. }
  37163. else {
  37164. value.once('update', this.textureUpdated, this);
  37165. }
  37166. },
  37167. enumerable: false,
  37168. configurable: true
  37169. });
  37170. SimplePlane.prototype._render = function (renderer) {
  37171. if (this._textureID !== this.shader.texture._updateID) {
  37172. this.textureUpdated();
  37173. }
  37174. _super.prototype._render.call(this, renderer);
  37175. };
  37176. SimplePlane.prototype.destroy = function (options) {
  37177. this.shader.texture.off('update', this.textureUpdated, this);
  37178. _super.prototype.destroy.call(this, options);
  37179. };
  37180. return SimplePlane;
  37181. }(Mesh));
  37182. /**
  37183. * The Simple Mesh class mimics Mesh in PixiJS v4, providing easy-to-use constructor arguments.
  37184. * For more robust customization, use {@link PIXI.Mesh}.
  37185. * @memberof PIXI
  37186. */
  37187. var SimpleMesh = /** @class */ (function (_super) {
  37188. __extends$1(SimpleMesh, _super);
  37189. /**
  37190. * @param texture - The texture to use
  37191. * @param {Float32Array} [vertices] - if you want to specify the vertices
  37192. * @param {Float32Array} [uvs] - if you want to specify the uvs
  37193. * @param {Uint16Array} [indices] - if you want to specify the indices
  37194. * @param drawMode - the drawMode, can be any of the Mesh.DRAW_MODES consts
  37195. */
  37196. function SimpleMesh(texture, vertices, uvs, indices, drawMode) {
  37197. if (texture === void 0) { texture = Texture.EMPTY; }
  37198. var _this = this;
  37199. var geometry = new MeshGeometry(vertices, uvs, indices);
  37200. geometry.getBuffer('aVertexPosition').static = false;
  37201. var meshMaterial = new MeshMaterial(texture);
  37202. _this = _super.call(this, geometry, meshMaterial, null, drawMode) || this;
  37203. _this.autoUpdate = true;
  37204. return _this;
  37205. }
  37206. Object.defineProperty(SimpleMesh.prototype, "vertices", {
  37207. /**
  37208. * Collection of vertices data.
  37209. * @type {Float32Array}
  37210. */
  37211. get: function () {
  37212. return this.geometry.getBuffer('aVertexPosition').data;
  37213. },
  37214. set: function (value) {
  37215. this.geometry.getBuffer('aVertexPosition').data = value;
  37216. },
  37217. enumerable: false,
  37218. configurable: true
  37219. });
  37220. SimpleMesh.prototype._render = function (renderer) {
  37221. if (this.autoUpdate) {
  37222. this.geometry.getBuffer('aVertexPosition').update();
  37223. }
  37224. _super.prototype._render.call(this, renderer);
  37225. };
  37226. return SimpleMesh;
  37227. }(Mesh));
  37228. var DEFAULT_BORDER_SIZE = 10;
  37229. /**
  37230. * The NineSlicePlane allows you to stretch a texture using 9-slice scaling. The corners will remain unscaled (useful
  37231. * for buttons with rounded corners for example) and the other areas will be scaled horizontally and or vertically
  37232. *
  37233. *```js
  37234. * let Plane9 = new PIXI.NineSlicePlane(PIXI.Texture.from('BoxWithRoundedCorners.png'), 15, 15, 15, 15);
  37235. * ```
  37236. * <pre>
  37237. * A B
  37238. * +---+----------------------+---+
  37239. * C | 1 | 2 | 3 |
  37240. * +---+----------------------+---+
  37241. * | | | |
  37242. * | 4 | 5 | 6 |
  37243. * | | | |
  37244. * +---+----------------------+---+
  37245. * D | 7 | 8 | 9 |
  37246. * +---+----------------------+---+
  37247. * When changing this objects width and/or height:
  37248. * areas 1 3 7 and 9 will remain unscaled.
  37249. * areas 2 and 8 will be stretched horizontally
  37250. * areas 4 and 6 will be stretched vertically
  37251. * area 5 will be stretched both horizontally and vertically
  37252. * </pre>
  37253. * @memberof PIXI
  37254. */
  37255. var NineSlicePlane = /** @class */ (function (_super) {
  37256. __extends$1(NineSlicePlane, _super);
  37257. /**
  37258. * @param texture - The texture to use on the NineSlicePlane.
  37259. * @param {number} [leftWidth=10] - size of the left vertical bar (A)
  37260. * @param {number} [topHeight=10] - size of the top horizontal bar (C)
  37261. * @param {number} [rightWidth=10] - size of the right vertical bar (B)
  37262. * @param {number} [bottomHeight=10] - size of the bottom horizontal bar (D)
  37263. */
  37264. function NineSlicePlane(texture, leftWidth, topHeight, rightWidth, bottomHeight) {
  37265. if (leftWidth === void 0) { leftWidth = DEFAULT_BORDER_SIZE; }
  37266. if (topHeight === void 0) { topHeight = DEFAULT_BORDER_SIZE; }
  37267. if (rightWidth === void 0) { rightWidth = DEFAULT_BORDER_SIZE; }
  37268. if (bottomHeight === void 0) { bottomHeight = DEFAULT_BORDER_SIZE; }
  37269. var _this = _super.call(this, Texture.WHITE, 4, 4) || this;
  37270. _this._origWidth = texture.orig.width;
  37271. _this._origHeight = texture.orig.height;
  37272. /** The width of the NineSlicePlane, setting this will actually modify the vertices and UV's of this plane. */
  37273. _this._width = _this._origWidth;
  37274. /** The height of the NineSlicePlane, setting this will actually modify the vertices and UV's of this plane. */
  37275. _this._height = _this._origHeight;
  37276. _this._leftWidth = leftWidth;
  37277. _this._rightWidth = rightWidth;
  37278. _this._topHeight = topHeight;
  37279. _this._bottomHeight = bottomHeight;
  37280. // lets call the setter to ensure all necessary updates are performed
  37281. _this.texture = texture;
  37282. return _this;
  37283. }
  37284. NineSlicePlane.prototype.textureUpdated = function () {
  37285. this._textureID = this.shader.texture._updateID;
  37286. this._refresh();
  37287. };
  37288. Object.defineProperty(NineSlicePlane.prototype, "vertices", {
  37289. get: function () {
  37290. return this.geometry.getBuffer('aVertexPosition').data;
  37291. },
  37292. set: function (value) {
  37293. this.geometry.getBuffer('aVertexPosition').data = value;
  37294. },
  37295. enumerable: false,
  37296. configurable: true
  37297. });
  37298. /** Updates the horizontal vertices. */
  37299. NineSlicePlane.prototype.updateHorizontalVertices = function () {
  37300. var vertices = this.vertices;
  37301. var scale = this._getMinScale();
  37302. vertices[9] = vertices[11] = vertices[13] = vertices[15] = this._topHeight * scale;
  37303. vertices[17] = vertices[19] = vertices[21] = vertices[23] = this._height - (this._bottomHeight * scale);
  37304. vertices[25] = vertices[27] = vertices[29] = vertices[31] = this._height;
  37305. };
  37306. /** Updates the vertical vertices. */
  37307. NineSlicePlane.prototype.updateVerticalVertices = function () {
  37308. var vertices = this.vertices;
  37309. var scale = this._getMinScale();
  37310. vertices[2] = vertices[10] = vertices[18] = vertices[26] = this._leftWidth * scale;
  37311. vertices[4] = vertices[12] = vertices[20] = vertices[28] = this._width - (this._rightWidth * scale);
  37312. vertices[6] = vertices[14] = vertices[22] = vertices[30] = this._width;
  37313. };
  37314. /**
  37315. * Returns the smaller of a set of vertical and horizontal scale of nine slice corners.
  37316. * @returns Smaller number of vertical and horizontal scale.
  37317. */
  37318. NineSlicePlane.prototype._getMinScale = function () {
  37319. var w = this._leftWidth + this._rightWidth;
  37320. var scaleW = this._width > w ? 1.0 : this._width / w;
  37321. var h = this._topHeight + this._bottomHeight;
  37322. var scaleH = this._height > h ? 1.0 : this._height / h;
  37323. var scale = Math.min(scaleW, scaleH);
  37324. return scale;
  37325. };
  37326. Object.defineProperty(NineSlicePlane.prototype, "width", {
  37327. /** The width of the NineSlicePlane, setting this will actually modify the vertices and UV's of this plane. */
  37328. get: function () {
  37329. return this._width;
  37330. },
  37331. set: function (value) {
  37332. this._width = value;
  37333. this._refresh();
  37334. },
  37335. enumerable: false,
  37336. configurable: true
  37337. });
  37338. Object.defineProperty(NineSlicePlane.prototype, "height", {
  37339. /** The height of the NineSlicePlane, setting this will actually modify the vertices and UV's of this plane. */
  37340. get: function () {
  37341. return this._height;
  37342. },
  37343. set: function (value) {
  37344. this._height = value;
  37345. this._refresh();
  37346. },
  37347. enumerable: false,
  37348. configurable: true
  37349. });
  37350. Object.defineProperty(NineSlicePlane.prototype, "leftWidth", {
  37351. /** The width of the left column. */
  37352. get: function () {
  37353. return this._leftWidth;
  37354. },
  37355. set: function (value) {
  37356. this._leftWidth = value;
  37357. this._refresh();
  37358. },
  37359. enumerable: false,
  37360. configurable: true
  37361. });
  37362. Object.defineProperty(NineSlicePlane.prototype, "rightWidth", {
  37363. /** The width of the right column. */
  37364. get: function () {
  37365. return this._rightWidth;
  37366. },
  37367. set: function (value) {
  37368. this._rightWidth = value;
  37369. this._refresh();
  37370. },
  37371. enumerable: false,
  37372. configurable: true
  37373. });
  37374. Object.defineProperty(NineSlicePlane.prototype, "topHeight", {
  37375. /** The height of the top row. */
  37376. get: function () {
  37377. return this._topHeight;
  37378. },
  37379. set: function (value) {
  37380. this._topHeight = value;
  37381. this._refresh();
  37382. },
  37383. enumerable: false,
  37384. configurable: true
  37385. });
  37386. Object.defineProperty(NineSlicePlane.prototype, "bottomHeight", {
  37387. /** The height of the bottom row. */
  37388. get: function () {
  37389. return this._bottomHeight;
  37390. },
  37391. set: function (value) {
  37392. this._bottomHeight = value;
  37393. this._refresh();
  37394. },
  37395. enumerable: false,
  37396. configurable: true
  37397. });
  37398. /** Refreshes NineSlicePlane coords. All of them. */
  37399. NineSlicePlane.prototype._refresh = function () {
  37400. var texture = this.texture;
  37401. var uvs = this.geometry.buffers[1].data;
  37402. this._origWidth = texture.orig.width;
  37403. this._origHeight = texture.orig.height;
  37404. var _uvw = 1.0 / this._origWidth;
  37405. var _uvh = 1.0 / this._origHeight;
  37406. uvs[0] = uvs[8] = uvs[16] = uvs[24] = 0;
  37407. uvs[1] = uvs[3] = uvs[5] = uvs[7] = 0;
  37408. uvs[6] = uvs[14] = uvs[22] = uvs[30] = 1;
  37409. uvs[25] = uvs[27] = uvs[29] = uvs[31] = 1;
  37410. uvs[2] = uvs[10] = uvs[18] = uvs[26] = _uvw * this._leftWidth;
  37411. uvs[4] = uvs[12] = uvs[20] = uvs[28] = 1 - (_uvw * this._rightWidth);
  37412. uvs[9] = uvs[11] = uvs[13] = uvs[15] = _uvh * this._topHeight;
  37413. uvs[17] = uvs[19] = uvs[21] = uvs[23] = 1 - (_uvh * this._bottomHeight);
  37414. this.updateHorizontalVertices();
  37415. this.updateVerticalVertices();
  37416. this.geometry.buffers[0].update();
  37417. this.geometry.buffers[1].update();
  37418. };
  37419. return NineSlicePlane;
  37420. }(SimplePlane));
  37421. /*!
  37422. * @pixi/sprite-animated - v6.5.10
  37423. * Compiled Thu, 06 Jul 2023 15:25:11 UTC
  37424. *
  37425. * @pixi/sprite-animated is licensed under the MIT License.
  37426. * http://www.opensource.org/licenses/mit-license
  37427. */
  37428. /*! *****************************************************************************
  37429. Copyright (c) Microsoft Corporation.
  37430. Permission to use, copy, modify, and/or distribute this software for any
  37431. purpose with or without fee is hereby granted.
  37432. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  37433. REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
  37434. AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  37435. INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
  37436. LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
  37437. OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
  37438. PERFORMANCE OF THIS SOFTWARE.
  37439. ***************************************************************************** */
  37440. /* global Reflect, Promise */
  37441. var extendStatics = function(d, b) {
  37442. extendStatics = Object.setPrototypeOf ||
  37443. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  37444. function (d, b) { for (var p in b) { if (b.hasOwnProperty(p)) { d[p] = b[p]; } } };
  37445. return extendStatics(d, b);
  37446. };
  37447. function __extends(d, b) {
  37448. extendStatics(d, b);
  37449. function __() { this.constructor = d; }
  37450. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  37451. }
  37452. /**
  37453. * An AnimatedSprite is a simple way to display an animation depicted by a list of textures.
  37454. *
  37455. * ```js
  37456. * let alienImages = ["image_sequence_01.png","image_sequence_02.png","image_sequence_03.png","image_sequence_04.png"];
  37457. * let textureArray = [];
  37458. *
  37459. * for (let i=0; i < 4; i++)
  37460. * {
  37461. * let texture = PIXI.Texture.from(alienImages[i]);
  37462. * textureArray.push(texture);
  37463. * };
  37464. *
  37465. * let animatedSprite = new PIXI.AnimatedSprite(textureArray);
  37466. * ```
  37467. *
  37468. * The more efficient and simpler way to create an animated sprite is using a {@link PIXI.Spritesheet}
  37469. * containing the animation definitions:
  37470. *
  37471. * ```js
  37472. * PIXI.Loader.shared.add("assets/spritesheet.json").load(setup);
  37473. *
  37474. * function setup() {
  37475. * let sheet = PIXI.Loader.shared.resources["assets/spritesheet.json"].spritesheet;
  37476. * animatedSprite = new PIXI.AnimatedSprite(sheet.animations["image_sequence"]);
  37477. * ...
  37478. * }
  37479. * ```
  37480. * @memberof PIXI
  37481. */
  37482. var AnimatedSprite = /** @class */ (function (_super) {
  37483. __extends(AnimatedSprite, _super);
  37484. /**
  37485. * @param textures - An array of {@link PIXI.Texture} or frame
  37486. * objects that make up the animation.
  37487. * @param {boolean} [autoUpdate=true] - Whether to use PIXI.Ticker.shared to auto update animation time.
  37488. */
  37489. function AnimatedSprite(textures, autoUpdate) {
  37490. if (autoUpdate === void 0) { autoUpdate = true; }
  37491. var _this = _super.call(this, textures[0] instanceof Texture ? textures[0] : textures[0].texture) || this;
  37492. _this._textures = null;
  37493. _this._durations = null;
  37494. _this._autoUpdate = autoUpdate;
  37495. _this._isConnectedToTicker = false;
  37496. _this.animationSpeed = 1;
  37497. _this.loop = true;
  37498. _this.updateAnchor = false;
  37499. _this.onComplete = null;
  37500. _this.onFrameChange = null;
  37501. _this.onLoop = null;
  37502. _this._currentTime = 0;
  37503. _this._playing = false;
  37504. _this._previousFrame = null;
  37505. _this.textures = textures;
  37506. return _this;
  37507. }
  37508. /** Stops the AnimatedSprite. */
  37509. AnimatedSprite.prototype.stop = function () {
  37510. if (!this._playing) {
  37511. return;
  37512. }
  37513. this._playing = false;
  37514. if (this._autoUpdate && this._isConnectedToTicker) {
  37515. Ticker.shared.remove(this.update, this);
  37516. this._isConnectedToTicker = false;
  37517. }
  37518. };
  37519. /** Plays the AnimatedSprite. */
  37520. AnimatedSprite.prototype.play = function () {
  37521. if (this._playing) {
  37522. return;
  37523. }
  37524. this._playing = true;
  37525. if (this._autoUpdate && !this._isConnectedToTicker) {
  37526. Ticker.shared.add(this.update, this, UPDATE_PRIORITY.HIGH);
  37527. this._isConnectedToTicker = true;
  37528. }
  37529. };
  37530. /**
  37531. * Stops the AnimatedSprite and goes to a specific frame.
  37532. * @param frameNumber - Frame index to stop at.
  37533. */
  37534. AnimatedSprite.prototype.gotoAndStop = function (frameNumber) {
  37535. this.stop();
  37536. var previousFrame = this.currentFrame;
  37537. this._currentTime = frameNumber;
  37538. if (previousFrame !== this.currentFrame) {
  37539. this.updateTexture();
  37540. }
  37541. };
  37542. /**
  37543. * Goes to a specific frame and begins playing the AnimatedSprite.
  37544. * @param frameNumber - Frame index to start at.
  37545. */
  37546. AnimatedSprite.prototype.gotoAndPlay = function (frameNumber) {
  37547. var previousFrame = this.currentFrame;
  37548. this._currentTime = frameNumber;
  37549. if (previousFrame !== this.currentFrame) {
  37550. this.updateTexture();
  37551. }
  37552. this.play();
  37553. };
  37554. /**
  37555. * Updates the object transform for rendering.
  37556. * @param deltaTime - Time since last tick.
  37557. */
  37558. AnimatedSprite.prototype.update = function (deltaTime) {
  37559. if (!this._playing) {
  37560. return;
  37561. }
  37562. var elapsed = this.animationSpeed * deltaTime;
  37563. var previousFrame = this.currentFrame;
  37564. if (this._durations !== null) {
  37565. var lag = this._currentTime % 1 * this._durations[this.currentFrame];
  37566. lag += elapsed / 60 * 1000;
  37567. while (lag < 0) {
  37568. this._currentTime--;
  37569. lag += this._durations[this.currentFrame];
  37570. }
  37571. var sign = Math.sign(this.animationSpeed * deltaTime);
  37572. this._currentTime = Math.floor(this._currentTime);
  37573. while (lag >= this._durations[this.currentFrame]) {
  37574. lag -= this._durations[this.currentFrame] * sign;
  37575. this._currentTime += sign;
  37576. }
  37577. this._currentTime += lag / this._durations[this.currentFrame];
  37578. }
  37579. else {
  37580. this._currentTime += elapsed;
  37581. }
  37582. if (this._currentTime < 0 && !this.loop) {
  37583. this.gotoAndStop(0);
  37584. if (this.onComplete) {
  37585. this.onComplete();
  37586. }
  37587. }
  37588. else if (this._currentTime >= this._textures.length && !this.loop) {
  37589. this.gotoAndStop(this._textures.length - 1);
  37590. if (this.onComplete) {
  37591. this.onComplete();
  37592. }
  37593. }
  37594. else if (previousFrame !== this.currentFrame) {
  37595. if (this.loop && this.onLoop) {
  37596. if (this.animationSpeed > 0 && this.currentFrame < previousFrame) {
  37597. this.onLoop();
  37598. }
  37599. else if (this.animationSpeed < 0 && this.currentFrame > previousFrame) {
  37600. this.onLoop();
  37601. }
  37602. }
  37603. this.updateTexture();
  37604. }
  37605. };
  37606. /** Updates the displayed texture to match the current frame index. */
  37607. AnimatedSprite.prototype.updateTexture = function () {
  37608. var currentFrame = this.currentFrame;
  37609. if (this._previousFrame === currentFrame) {
  37610. return;
  37611. }
  37612. this._previousFrame = currentFrame;
  37613. this._texture = this._textures[currentFrame];
  37614. this._textureID = -1;
  37615. this._textureTrimmedID = -1;
  37616. this._cachedTint = 0xFFFFFF;
  37617. this.uvs = this._texture._uvs.uvsFloat32;
  37618. if (this.updateAnchor) {
  37619. this._anchor.copyFrom(this._texture.defaultAnchor);
  37620. }
  37621. if (this.onFrameChange) {
  37622. this.onFrameChange(this.currentFrame);
  37623. }
  37624. };
  37625. /**
  37626. * Stops the AnimatedSprite and destroys it.
  37627. * @param {object|boolean} [options] - Options parameter. A boolean will act as if all options
  37628. * have been set to that value.
  37629. * @param {boolean} [options.children=false] - If set to true, all the children will have their destroy
  37630. * method called as well. 'options' will be passed on to those calls.
  37631. * @param {boolean} [options.texture=false] - Should it destroy the current texture of the sprite as well.
  37632. * @param {boolean} [options.baseTexture=false] - Should it destroy the base texture of the sprite as well.
  37633. */
  37634. AnimatedSprite.prototype.destroy = function (options) {
  37635. this.stop();
  37636. _super.prototype.destroy.call(this, options);
  37637. this.onComplete = null;
  37638. this.onFrameChange = null;
  37639. this.onLoop = null;
  37640. };
  37641. /**
  37642. * A short hand way of creating an AnimatedSprite from an array of frame ids.
  37643. * @param frames - The array of frames ids the AnimatedSprite will use as its texture frames.
  37644. * @returns - The new animated sprite with the specified frames.
  37645. */
  37646. AnimatedSprite.fromFrames = function (frames) {
  37647. var textures = [];
  37648. for (var i = 0; i < frames.length; ++i) {
  37649. textures.push(Texture.from(frames[i]));
  37650. }
  37651. return new AnimatedSprite(textures);
  37652. };
  37653. /**
  37654. * A short hand way of creating an AnimatedSprite from an array of image ids.
  37655. * @param images - The array of image urls the AnimatedSprite will use as its texture frames.
  37656. * @returns The new animate sprite with the specified images as frames.
  37657. */
  37658. AnimatedSprite.fromImages = function (images) {
  37659. var textures = [];
  37660. for (var i = 0; i < images.length; ++i) {
  37661. textures.push(Texture.from(images[i]));
  37662. }
  37663. return new AnimatedSprite(textures);
  37664. };
  37665. Object.defineProperty(AnimatedSprite.prototype, "totalFrames", {
  37666. /**
  37667. * The total number of frames in the AnimatedSprite. This is the same as number of textures
  37668. * assigned to the AnimatedSprite.
  37669. * @readonly
  37670. * @default 0
  37671. */
  37672. get: function () {
  37673. return this._textures.length;
  37674. },
  37675. enumerable: false,
  37676. configurable: true
  37677. });
  37678. Object.defineProperty(AnimatedSprite.prototype, "textures", {
  37679. /** The array of textures used for this AnimatedSprite. */
  37680. get: function () {
  37681. return this._textures;
  37682. },
  37683. set: function (value) {
  37684. if (value[0] instanceof Texture) {
  37685. this._textures = value;
  37686. this._durations = null;
  37687. }
  37688. else {
  37689. this._textures = [];
  37690. this._durations = [];
  37691. for (var i = 0; i < value.length; i++) {
  37692. this._textures.push(value[i].texture);
  37693. this._durations.push(value[i].time);
  37694. }
  37695. }
  37696. this._previousFrame = null;
  37697. this.gotoAndStop(0);
  37698. this.updateTexture();
  37699. },
  37700. enumerable: false,
  37701. configurable: true
  37702. });
  37703. Object.defineProperty(AnimatedSprite.prototype, "currentFrame", {
  37704. /**
  37705. * The AnimatedSprites current frame index.
  37706. * @readonly
  37707. */
  37708. get: function () {
  37709. var currentFrame = Math.floor(this._currentTime) % this._textures.length;
  37710. if (currentFrame < 0) {
  37711. currentFrame += this._textures.length;
  37712. }
  37713. return currentFrame;
  37714. },
  37715. enumerable: false,
  37716. configurable: true
  37717. });
  37718. Object.defineProperty(AnimatedSprite.prototype, "playing", {
  37719. /**
  37720. * Indicates if the AnimatedSprite is currently playing.
  37721. * @readonly
  37722. */
  37723. get: function () {
  37724. return this._playing;
  37725. },
  37726. enumerable: false,
  37727. configurable: true
  37728. });
  37729. Object.defineProperty(AnimatedSprite.prototype, "autoUpdate", {
  37730. /** Whether to use PIXI.Ticker.shared to auto update animation time. */
  37731. get: function () {
  37732. return this._autoUpdate;
  37733. },
  37734. set: function (value) {
  37735. if (value !== this._autoUpdate) {
  37736. this._autoUpdate = value;
  37737. if (!this._autoUpdate && this._isConnectedToTicker) {
  37738. Ticker.shared.remove(this.update, this);
  37739. this._isConnectedToTicker = false;
  37740. }
  37741. else if (this._autoUpdate && !this._isConnectedToTicker && this._playing) {
  37742. Ticker.shared.add(this.update, this);
  37743. this._isConnectedToTicker = true;
  37744. }
  37745. }
  37746. },
  37747. enumerable: false,
  37748. configurable: true
  37749. });
  37750. return AnimatedSprite;
  37751. }(Sprite));
  37752. extensions.add(
  37753. // Install renderer plugins
  37754. AccessibilityManager, Extract, InteractionManager, ParticleRenderer, Prepare, BatchRenderer, TilingSpriteRenderer,
  37755. // Install loader plugins
  37756. BitmapFontLoader, CompressedTextureLoader, DDSLoader, KTXLoader, SpritesheetLoader,
  37757. // Install application plugins
  37758. TickerPlugin, AppLoaderPlugin);
  37759. /**
  37760. * This namespace contains WebGL-only display filters that can be applied
  37761. * to DisplayObjects using the {@link PIXI.DisplayObject#filters filters} property.
  37762. *
  37763. * Since PixiJS only had a handful of built-in filters, additional filters
  37764. * can be downloaded {@link https://github.com/pixijs/pixi-filters here} from the
  37765. * PixiJS Filters repository.
  37766. *
  37767. * All filters must extend {@link PIXI.Filter}.
  37768. * @example
  37769. * // Create a new application
  37770. * const app = new PIXI.Application();
  37771. *
  37772. * // Draw a green rectangle
  37773. * const rect = new PIXI.Graphics()
  37774. * .beginFill(0x00ff00)
  37775. * .drawRect(40, 40, 200, 200);
  37776. *
  37777. * // Add a blur filter
  37778. * rect.filters = [new PIXI.filters.BlurFilter()];
  37779. *
  37780. * // Display rectangle
  37781. * app.stage.addChild(rect);
  37782. * document.body.appendChild(app.view);
  37783. * @namespace PIXI.filters
  37784. */
  37785. var filters = {
  37786. AlphaFilter: AlphaFilter,
  37787. BlurFilter: BlurFilter,
  37788. BlurFilterPass: BlurFilterPass,
  37789. ColorMatrixFilter: ColorMatrixFilter,
  37790. DisplacementFilter: DisplacementFilter,
  37791. FXAAFilter: FXAAFilter,
  37792. NoiseFilter: NoiseFilter,
  37793. };
  37794. export { ALPHA_MODES, AbstractBatchRenderer, AbstractMultiResource, AbstractRenderer, AccessibilityManager, AnimatedSprite, AppLoaderPlugin, Application, ArrayResource, Attribute, BLEND_MODES, BUFFER_BITS, BUFFER_TYPE, BaseImageResource, BasePrepare, BaseRenderTexture, BaseTexture, BatchDrawCall, BatchGeometry, BatchPluginFactory, BatchRenderer, BatchShaderGenerator, BatchSystem, BatchTextureArray, BitmapFont, BitmapFontData, BitmapFontLoader, BitmapText, BlobResource, Bounds, BrowserAdapter, Buffer, BufferResource, CLEAR_MODES, COLOR_MASK_BITS, CanvasResource, Circle, CompressedTextureLoader, CompressedTextureResource, Container, ContextSystem, CountLimiter, CubeResource, DDSLoader, DEG_TO_RAD, DRAW_MODES, DisplayObject, ENV, Ellipse, ExtensionType, Extract, FORMATS, FORMATS_TO_COMPONENTS, FillStyle, Filter, FilterState, FilterSystem, Framebuffer, FramebufferSystem, GC_MODES, GLFramebuffer, GLProgram, GLTexture, GRAPHICS_CURVES, Geometry, GeometrySystem, Graphics, GraphicsData, GraphicsGeometry, IGLUniformData, INSTALLED, INTERNAL_FORMATS, INTERNAL_FORMAT_TO_BYTES_PER_PIXEL, ImageBitmapResource, ImageResource, InteractionData, InteractionEvent, InteractionManager, InteractionTrackingData, KTXLoader, LINE_CAP, LINE_JOIN, LineStyle, Loader, LoaderResource, MASK_TYPES, MIPMAP_MODES, MSAA_QUALITY, MaskData, MaskSystem, Matrix, Mesh, MeshBatchUvs, MeshGeometry, MeshMaterial, NineSlicePlane, ObjectRenderer, ObservablePoint, PI_2, PRECISION, ParticleContainer, ParticleRenderer, PlaneGeometry, Point, Polygon, Prepare, Program, ProjectionSystem, Quad, QuadUv, RAD_TO_DEG, RENDERER_TYPE, Rectangle, RenderTexture, RenderTexturePool, RenderTextureSystem, Renderer, ResizePlugin, Resource, RopeGeometry, RoundedRectangle, Runner, SAMPLER_TYPES, SCALE_MODES, SHAPES, SVGResource, ScissorSystem, Shader, ShaderSystem, SimpleMesh, SimplePlane, SimpleRope, Sprite, SpriteMaskFilter, Spritesheet, SpritesheetLoader, State, StateSystem, StencilSystem, System, TARGETS, TEXT_GRADIENT, TYPES, TYPES_TO_BYTES_PER_COMPONENT, TYPES_TO_BYTES_PER_PIXEL, TemporaryDisplayObject, Text, TextFormat, TextMetrics, TextStyle, Texture, TextureGCSystem, TextureLoader, TextureMatrix, TextureSystem, TextureUvs, Ticker, TickerPlugin, TilingSprite, TilingSpriteRenderer, TimeLimiter, Transform, UPDATE_PRIORITY, UniformGroup, VERSION, VideoResource, ViewableBuffer, WRAP_MODES, XMLFormat, XMLStringFormat, accessibleTarget, autoDetectFormat, autoDetectRenderer, autoDetectResource, checkMaxIfStatementsInShader, createUBOElements, defaultFilterVertex, defaultVertex$1 as defaultVertex, extensions, filters, generateProgram, generateUniformBufferSync, getTestContext, getUBOData, graphicsUtils, groupD8, interactiveTarget, isMobile, parseDDS, parseKTX, resources, settings, systems, uniformParsers, utils };
  37795. //# sourceMappingURL=pixi.mjs.map