pixi.js 1.3 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214422154221642217422184221942220422214222242223422244222542226422274222842229422304223142232422334223442235422364223742238422394224042241422424224342244422454224642247422484224942250422514225242253422544225542256422574225842259422604226142262422634226442265422664226742268422694227042271422724227342274422754227642277422784227942280422814228242283422844228542286422874228842289422904229142292422934229442295422964229742298422994230042301423024230342304423054230642307423084230942310423114231242313423144231542316423174231842319423204232142322423234232442325423264232742328423294233042331423324233342334423354233642337423384233942340423414234242343423444234542346423474234842349423504235142352423534235442355423564235742358423594236042361423624236342364423654236642367423684236942370423714237242373423744237542376423774237842379423804238142382423834238442385423864238742388423894239042391423924239342394423954239642397423984239942400424014240242403424044240542406424074240842409424104241142412424134241442415424164241742418424194242042421424224242342424424254242642427424284242942430424314243242433424344243542436424374243842439424404244142442424434244442445424464244742448424494245042451424524245342454424554245642457424584245942460424614246242463424644246542466424674246842469424704247142472424734247442475424764247742478424794248042481424824248342484424854248642487424884248942490424914249242493424944249542496424974249842499425004250142502425034250442505425064250742508425094251042511425124251342514425154251642517425184251942520425214252242523425244252542526425274252842529425304253142532425334253442535425364253742538425394254042541425424254342544425454254642547425484254942550425514255242553425544255542556425574255842559425604256142562425634256442565425664256742568425694257042571425724257342574425754257642577425784257942580425814258242583425844258542586425874258842589425904259142592425934259442595425964259742598425994260042601426024260342604426054260642607426084260942610426114261242613426144261542616426174261842619426204262142622426234262442625426264262742628426294263042631426324263342634426354263642637426384263942640426414264242643426444264542646426474264842649426504265142652426534265442655426564265742658426594266042661426624266342664426654266642667426684266942670426714267242673426744267542676426774267842679426804268142682426834268442685426864268742688426894269042691426924269342694426954269642697426984269942700427014270242703427044270542706427074270842709427104271142712427134271442715427164271742718427194272042721427224272342724427254272642727427284272942730427314273242733427344273542736427374273842739427404274142742427434274442745427464274742748427494275042751427524275342754427554275642757427584275942760427614276242763427644276542766427674276842769427704277142772427734277442775427764277742778427794278042781427824278342784427854278642787427884278942790427914279242793427944279542796427974279842799428004280142802428034280442805428064280742808428094281042811428124281342814428154281642817428184281942820428214282242823428244282542826428274282842829428304283142832428334283442835428364283742838428394284042841428424284342844428454284642847428484284942850428514285242853428544285542856428574285842859428604286142862428634286442865428664286742868428694287042871428724287342874428754287642877428784287942880428814288242883428844288542886428874288842889428904289142892428934289442895428964289742898428994290042901429024290342904429054290642907429084290942910429114291242913429144291542916429174291842919429204292142922429234292442925429264292742928429294293042931429324293342934429354293642937429384293942940429414294242943429444294542946429474294842949429504295142952429534295442955429564295742958429594296042961429624296342964429654296642967429684296942970429714297242973429744297542976429774297842979429804298142982429834298442985429864298742988429894299042991429924299342994429954299642997429984299943000430014300243003430044300543006430074300843009430104301143012430134301443015430164301743018430194302043021430224302343024430254302643027430284302943030430314303243033430344303543036430374303843039430404304143042430434304443045430464304743048430494305043051430524305343054430554305643057430584305943060430614306243063430644306543066430674306843069430704307143072430734307443075430764307743078430794308043081430824308343084430854308643087430884308943090430914309243093430944309543096430974309843099431004310143102431034310443105431064310743108431094311043111431124311343114431154311643117431184311943120431214312243123431244312543126431274312843129431304313143132431334313443135431364313743138431394314043141431424314343144431454314643147431484314943150431514315243153431544315543156431574315843159431604316143162431634316443165431664316743168431694317043171431724317343174431754317643177431784317943180431814318243183431844318543186431874318843189431904319143192431934319443195431964319743198431994320043201432024320343204432054320643207432084320943210432114321243213432144321543216432174321843219432204322143222432234322443225432264322743228432294323043231432324323343234432354323643237432384323943240432414324243243432444324543246432474324843249432504325143252432534325443255432564325743258432594326043261432624326343264432654326643267432684326943270432714327243273432744327543276432774327843279432804328143282432834328443285432864328743288432894329043291432924329343294432954329643297432984329943300433014330243303433044330543306433074330843309433104331143312433134331443315433164331743318433194332043321433224332343324433254332643327433284332943330433314333243333433344333543336433374333843339433404334143342433434334443345433464334743348433494335043351433524335343354433554335643357433584335943360433614336243363433644336543366433674336843369433704337143372433734337443375433764337743378433794338043381433824338343384433854338643387433884338943390433914339243393433944339543396433974339843399434004340143402434034340443405434064340743408434094341043411434124341343414434154341643417434184341943420434214342243423434244342543426434274342843429434304343143432434334343443435434364343743438434394344043441434424344343444434454344643447434484344943450434514345243453434544345543456434574345843459434604346143462434634346443465434664346743468434694347043471434724347343474434754347643477434784347943480434814348243483434844348543486434874348843489434904349143492434934349443495434964349743498434994350043501435024350343504435054350643507435084350943510435114351243513435144351543516435174351843519435204352143522435234352443525435264352743528435294353043531435324353343534435354353643537435384353943540435414354243543435444354543546435474354843549435504355143552435534355443555435564355743558435594356043561435624356343564435654356643567435684356943570435714357243573435744357543576435774357843579435804358143582435834358443585435864358743588435894359043591435924359343594435954359643597435984359943600436014360243603436044360543606436074360843609436104361143612436134361443615436164361743618436194362043621436224362343624436254362643627436284362943630436314363243633436344363543636436374363843639436404364143642436434364443645436464364743648436494365043651436524365343654436554365643657436584365943660436614366243663436644366543666436674366843669436704367143672436734367443675436764367743678436794368043681436824368343684436854368643687436884368943690436914369243693436944369543696436974369843699437004370143702437034370443705437064370743708437094371043711437124371343714437154371643717437184371943720437214372243723437244372543726437274372843729437304373143732437334373443735437364373743738437394374043741437424374343744437454374643747437484374943750437514375243753437544375543756437574375843759437604376143762437634376443765437664376743768437694377043771437724377343774437754377643777437784377943780437814378243783437844378543786437874378843789437904379143792
  1. /*!
  2. * pixi.js - v5.0.4
  3. * Compiled Fri, 07 Jun 2019 17:17:49 UTC
  4. *
  5. * pixi.js is licensed under the MIT License.
  6. * http://www.opensource.org/licenses/mit-license
  7. */
  8. var PIXI = (function (exports) {
  9. 'use strict';
  10. var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
  11. function commonjsRequire () {
  12. throw new Error('Dynamic requires are not currently supported by rollup-plugin-commonjs');
  13. }
  14. function unwrapExports (x) {
  15. return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
  16. }
  17. function createCommonjsModule(fn, module) {
  18. return module = { exports: {} }, fn(module, module.exports), module.exports;
  19. }
  20. function getCjsExportFromNamespace (n) {
  21. return n && n['default'] || n;
  22. }
  23. var promise = createCommonjsModule(function (module, exports) {
  24. (function(global){
  25. //
  26. // Check for native Promise and it has correct interface
  27. //
  28. var NativePromise = global['Promise'];
  29. var nativePromiseSupported =
  30. NativePromise &&
  31. // Some of these methods are missing from
  32. // Firefox/Chrome experimental implementations
  33. 'resolve' in NativePromise &&
  34. 'reject' in NativePromise &&
  35. 'all' in NativePromise &&
  36. 'race' in NativePromise &&
  37. // Older version of the spec had a resolver object
  38. // as the arg rather than a function
  39. (function(){
  40. var resolve;
  41. new NativePromise(function(r){ resolve = r; });
  42. return typeof resolve === 'function';
  43. })();
  44. //
  45. // export if necessary
  46. //
  47. if ('object' !== 'undefined' && exports)
  48. {
  49. // node.js
  50. exports.Promise = nativePromiseSupported ? NativePromise : Promise;
  51. exports.Polyfill = Promise;
  52. }
  53. else
  54. {
  55. // AMD
  56. if (typeof undefined == 'function' && undefined.amd)
  57. {
  58. undefined(function(){
  59. return nativePromiseSupported ? NativePromise : Promise;
  60. });
  61. }
  62. else
  63. {
  64. // in browser add to global
  65. if (!nativePromiseSupported)
  66. { global['Promise'] = Promise; }
  67. }
  68. }
  69. //
  70. // Polyfill
  71. //
  72. var PENDING = 'pending';
  73. var SEALED = 'sealed';
  74. var FULFILLED = 'fulfilled';
  75. var REJECTED = 'rejected';
  76. var NOOP = function(){};
  77. function isArray(value) {
  78. return Object.prototype.toString.call(value) === '[object Array]';
  79. }
  80. // async calls
  81. var asyncSetTimer = typeof setImmediate !== 'undefined' ? setImmediate : setTimeout;
  82. var asyncQueue = [];
  83. var asyncTimer;
  84. function asyncFlush(){
  85. // run promise callbacks
  86. for (var i = 0; i < asyncQueue.length; i++)
  87. { asyncQueue[i][0](asyncQueue[i][1]); }
  88. // reset async asyncQueue
  89. asyncQueue = [];
  90. asyncTimer = false;
  91. }
  92. function asyncCall(callback, arg){
  93. asyncQueue.push([callback, arg]);
  94. if (!asyncTimer)
  95. {
  96. asyncTimer = true;
  97. asyncSetTimer(asyncFlush, 0);
  98. }
  99. }
  100. function invokeResolver(resolver, promise) {
  101. function resolvePromise(value) {
  102. resolve(promise, value);
  103. }
  104. function rejectPromise(reason) {
  105. reject(promise, reason);
  106. }
  107. try {
  108. resolver(resolvePromise, rejectPromise);
  109. } catch(e) {
  110. rejectPromise(e);
  111. }
  112. }
  113. function invokeCallback(subscriber){
  114. var owner = subscriber.owner;
  115. var settled = owner.state_;
  116. var value = owner.data_;
  117. var callback = subscriber[settled];
  118. var promise = subscriber.then;
  119. if (typeof callback === 'function')
  120. {
  121. settled = FULFILLED;
  122. try {
  123. value = callback(value);
  124. } catch(e) {
  125. reject(promise, e);
  126. }
  127. }
  128. if (!handleThenable(promise, value))
  129. {
  130. if (settled === FULFILLED)
  131. { resolve(promise, value); }
  132. if (settled === REJECTED)
  133. { reject(promise, value); }
  134. }
  135. }
  136. function handleThenable(promise, value) {
  137. var resolved;
  138. try {
  139. if (promise === value)
  140. { throw new TypeError('A promises callback cannot return that same promise.'); }
  141. if (value && (typeof value === 'function' || typeof value === 'object'))
  142. {
  143. var then = value.then; // then should be retrived only once
  144. if (typeof then === 'function')
  145. {
  146. then.call(value, function(val){
  147. if (!resolved)
  148. {
  149. resolved = true;
  150. if (value !== val)
  151. { resolve(promise, val); }
  152. else
  153. { fulfill(promise, val); }
  154. }
  155. }, function(reason){
  156. if (!resolved)
  157. {
  158. resolved = true;
  159. reject(promise, reason);
  160. }
  161. });
  162. return true;
  163. }
  164. }
  165. } catch (e) {
  166. if (!resolved)
  167. { reject(promise, e); }
  168. return true;
  169. }
  170. return false;
  171. }
  172. function resolve(promise, value){
  173. if (promise === value || !handleThenable(promise, value))
  174. { fulfill(promise, value); }
  175. }
  176. function fulfill(promise, value){
  177. if (promise.state_ === PENDING)
  178. {
  179. promise.state_ = SEALED;
  180. promise.data_ = value;
  181. asyncCall(publishFulfillment, promise);
  182. }
  183. }
  184. function reject(promise, reason){
  185. if (promise.state_ === PENDING)
  186. {
  187. promise.state_ = SEALED;
  188. promise.data_ = reason;
  189. asyncCall(publishRejection, promise);
  190. }
  191. }
  192. function publish(promise) {
  193. var callbacks = promise.then_;
  194. promise.then_ = undefined;
  195. for (var i = 0; i < callbacks.length; i++) {
  196. invokeCallback(callbacks[i]);
  197. }
  198. }
  199. function publishFulfillment(promise){
  200. promise.state_ = FULFILLED;
  201. publish(promise);
  202. }
  203. function publishRejection(promise){
  204. promise.state_ = REJECTED;
  205. publish(promise);
  206. }
  207. /**
  208. * @class
  209. */
  210. function Promise(resolver){
  211. if (typeof resolver !== 'function')
  212. { throw new TypeError('Promise constructor takes a function argument'); }
  213. if (this instanceof Promise === false)
  214. { throw new TypeError('Failed to construct \'Promise\': Please use the \'new\' operator, this object constructor cannot be called as a function.'); }
  215. this.then_ = [];
  216. invokeResolver(resolver, this);
  217. }
  218. Promise.prototype = {
  219. constructor: Promise,
  220. state_: PENDING,
  221. then_: null,
  222. data_: undefined,
  223. then: function(onFulfillment, onRejection){
  224. var subscriber = {
  225. owner: this,
  226. then: new this.constructor(NOOP),
  227. fulfilled: onFulfillment,
  228. rejected: onRejection
  229. };
  230. if (this.state_ === FULFILLED || this.state_ === REJECTED)
  231. {
  232. // already resolved, call callback async
  233. asyncCall(invokeCallback, subscriber);
  234. }
  235. else
  236. {
  237. // subscribe
  238. this.then_.push(subscriber);
  239. }
  240. return subscriber.then;
  241. },
  242. 'catch': function(onRejection) {
  243. return this.then(null, onRejection);
  244. }
  245. };
  246. Promise.all = function(promises){
  247. var Class = this;
  248. if (!isArray(promises))
  249. { throw new TypeError('You must pass an array to Promise.all().'); }
  250. return new Class(function(resolve, reject){
  251. var results = [];
  252. var remaining = 0;
  253. function resolver(index){
  254. remaining++;
  255. return function(value){
  256. results[index] = value;
  257. if (!--remaining)
  258. { resolve(results); }
  259. };
  260. }
  261. for (var i = 0, promise; i < promises.length; i++)
  262. {
  263. promise = promises[i];
  264. if (promise && typeof promise.then === 'function')
  265. { promise.then(resolver(i), reject); }
  266. else
  267. { results[i] = promise; }
  268. }
  269. if (!remaining)
  270. { resolve(results); }
  271. });
  272. };
  273. Promise.race = function(promises){
  274. var Class = this;
  275. if (!isArray(promises))
  276. { throw new TypeError('You must pass an array to Promise.race().'); }
  277. return new Class(function(resolve, reject) {
  278. for (var i = 0, promise; i < promises.length; i++)
  279. {
  280. promise = promises[i];
  281. if (promise && typeof promise.then === 'function')
  282. { promise.then(resolve, reject); }
  283. else
  284. { resolve(promise); }
  285. }
  286. });
  287. };
  288. Promise.resolve = function(value){
  289. var Class = this;
  290. if (value && typeof value === 'object' && value.constructor === Class)
  291. { return value; }
  292. return new Class(function(resolve){
  293. resolve(value);
  294. });
  295. };
  296. Promise.reject = function(reason){
  297. var Class = this;
  298. return new Class(function(resolve, reject){
  299. reject(reason);
  300. });
  301. };
  302. })(typeof window != 'undefined' ? window : typeof commonjsGlobal != 'undefined' ? commonjsGlobal : typeof self != 'undefined' ? self : commonjsGlobal);
  303. });
  304. var promise_1 = promise.Promise;
  305. var promise_2 = promise.Polyfill;
  306. /*
  307. object-assign
  308. (c) Sindre Sorhus
  309. @license MIT
  310. */
  311. 'use strict';
  312. /* eslint-disable no-unused-vars */
  313. var getOwnPropertySymbols = Object.getOwnPropertySymbols;
  314. var hasOwnProperty = Object.prototype.hasOwnProperty;
  315. var propIsEnumerable = Object.prototype.propertyIsEnumerable;
  316. function toObject(val) {
  317. if (val === null || val === undefined) {
  318. throw new TypeError('Object.assign cannot be called with null or undefined');
  319. }
  320. return Object(val);
  321. }
  322. function shouldUseNative() {
  323. try {
  324. if (!Object.assign) {
  325. return false;
  326. }
  327. // Detect buggy property enumeration order in older V8 versions.
  328. // https://bugs.chromium.org/p/v8/issues/detail?id=4118
  329. var test1 = new String('abc'); // eslint-disable-line no-new-wrappers
  330. test1[5] = 'de';
  331. if (Object.getOwnPropertyNames(test1)[0] === '5') {
  332. return false;
  333. }
  334. // https://bugs.chromium.org/p/v8/issues/detail?id=3056
  335. var test2 = {};
  336. for (var i = 0; i < 10; i++) {
  337. test2['_' + String.fromCharCode(i)] = i;
  338. }
  339. var order2 = Object.getOwnPropertyNames(test2).map(function (n) {
  340. return test2[n];
  341. });
  342. if (order2.join('') !== '0123456789') {
  343. return false;
  344. }
  345. // https://bugs.chromium.org/p/v8/issues/detail?id=3056
  346. var test3 = {};
  347. 'abcdefghijklmnopqrst'.split('').forEach(function (letter) {
  348. test3[letter] = letter;
  349. });
  350. if (Object.keys(Object.assign({}, test3)).join('') !==
  351. 'abcdefghijklmnopqrst') {
  352. return false;
  353. }
  354. return true;
  355. } catch (err) {
  356. // We don't expect any of the above to throw, but better to be safe.
  357. return false;
  358. }
  359. }
  360. var objectAssign = shouldUseNative() ? Object.assign : function (target, source) {
  361. var arguments$1 = arguments;
  362. var from;
  363. var to = toObject(target);
  364. var symbols;
  365. for (var s = 1; s < arguments.length; s++) {
  366. from = Object(arguments$1[s]);
  367. for (var key in from) {
  368. if (hasOwnProperty.call(from, key)) {
  369. to[key] = from[key];
  370. }
  371. }
  372. if (getOwnPropertySymbols) {
  373. symbols = getOwnPropertySymbols(from);
  374. for (var i = 0; i < symbols.length; i++) {
  375. if (propIsEnumerable.call(from, symbols[i])) {
  376. to[symbols[i]] = from[symbols[i]];
  377. }
  378. }
  379. }
  380. }
  381. return to;
  382. };
  383. /*!
  384. * @pixi/polyfill - v5.0.4
  385. * Compiled Fri, 07 Jun 2019 17:17:49 UTC
  386. *
  387. * @pixi/polyfill is licensed under the MIT License.
  388. * http://www.opensource.org/licenses/mit-license
  389. */
  390. // Support for IE 9 - 11 which does not include Promises
  391. if (!window.Promise)
  392. {
  393. window.Promise = promise_2;
  394. }
  395. // References:
  396. if (!Object.assign)
  397. {
  398. Object.assign = objectAssign;
  399. }
  400. var commonjsGlobal$1 = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
  401. // References:
  402. // http://paulirish.com/2011/requestanimationframe-for-smart-animating/
  403. // https://gist.github.com/1579671
  404. // http://updates.html5rocks.com/2012/05/requestAnimationFrame-API-now-with-sub-millisecond-precision
  405. // https://gist.github.com/timhall/4078614
  406. // https://github.com/Financial-Times/polyfill-service/tree/master/polyfills/requestAnimationFrame
  407. // Expected to be used with Browserfiy
  408. // Browserify automatically detects the use of `global` and passes the
  409. // correct reference of `global`, `self`, and finally `window`
  410. var ONE_FRAME_TIME = 16;
  411. // Date.now
  412. if (!(Date.now && Date.prototype.getTime))
  413. {
  414. Date.now = function now()
  415. {
  416. return new Date().getTime();
  417. };
  418. }
  419. // performance.now
  420. if (!(commonjsGlobal$1.performance && commonjsGlobal$1.performance.now))
  421. {
  422. var startTime = Date.now();
  423. if (!commonjsGlobal$1.performance)
  424. {
  425. commonjsGlobal$1.performance = {};
  426. }
  427. commonjsGlobal$1.performance.now = function () { return Date.now() - startTime; };
  428. }
  429. // requestAnimationFrame
  430. var lastTime = Date.now();
  431. var vendors = ['ms', 'moz', 'webkit', 'o'];
  432. for (var x = 0; x < vendors.length && !commonjsGlobal$1.requestAnimationFrame; ++x)
  433. {
  434. var p = vendors[x];
  435. commonjsGlobal$1.requestAnimationFrame = commonjsGlobal$1[(p + "RequestAnimationFrame")];
  436. commonjsGlobal$1.cancelAnimationFrame = commonjsGlobal$1[(p + "CancelAnimationFrame")] || commonjsGlobal$1[(p + "CancelRequestAnimationFrame")];
  437. }
  438. if (!commonjsGlobal$1.requestAnimationFrame)
  439. {
  440. commonjsGlobal$1.requestAnimationFrame = function (callback) {
  441. if (typeof callback !== 'function')
  442. {
  443. throw new TypeError((callback + "is not a function"));
  444. }
  445. var currentTime = Date.now();
  446. var delay = ONE_FRAME_TIME + lastTime - currentTime;
  447. if (delay < 0)
  448. {
  449. delay = 0;
  450. }
  451. lastTime = currentTime;
  452. return setTimeout(function () {
  453. lastTime = Date.now();
  454. callback(performance.now());
  455. }, delay);
  456. };
  457. }
  458. if (!commonjsGlobal$1.cancelAnimationFrame)
  459. {
  460. commonjsGlobal$1.cancelAnimationFrame = function (id) { return clearTimeout(id); };
  461. }
  462. // References:
  463. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sign
  464. if (!Math.sign)
  465. {
  466. Math.sign = function mathSign(x)
  467. {
  468. x = Number(x);
  469. if (x === 0 || isNaN(x))
  470. {
  471. return x;
  472. }
  473. return x > 0 ? 1 : -1;
  474. };
  475. }
  476. // References:
  477. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isInteger
  478. if (!Number.isInteger)
  479. {
  480. Number.isInteger = function numberIsInteger(value)
  481. {
  482. return typeof value === 'number' && isFinite(value) && Math.floor(value) === value;
  483. };
  484. }
  485. if (!window.ArrayBuffer)
  486. {
  487. window.ArrayBuffer = Array;
  488. }
  489. if (!window.Float32Array)
  490. {
  491. window.Float32Array = Array;
  492. }
  493. if (!window.Uint32Array)
  494. {
  495. window.Uint32Array = Array;
  496. }
  497. if (!window.Uint16Array)
  498. {
  499. window.Uint16Array = Array;
  500. }
  501. if (!window.Uint8Array)
  502. {
  503. window.Uint8Array = Array;
  504. }
  505. if (!window.Int32Array)
  506. {
  507. window.Int32Array = Array;
  508. }
  509. var isMobile_min = createCommonjsModule(function (module) {
  510. !function(e){var n=/iPhone/i,t=/iPod/i,r=/iPad/i,a=/\bAndroid(?:.+)Mobile\b/i,p=/Android/i,b=/\bAndroid(?:.+)SD4930UR\b/i,l=/\bAndroid(?:.+)(?:KF[A-Z]{2,4})\b/i,f=/Windows Phone/i,s=/\bWindows(?:.+)ARM\b/i,u=/BlackBerry/i,c=/BB10/i,h=/Opera Mini/i,v=/\b(CriOS|Chrome)(?:.+)Mobile/i,w=/Mobile(?:.+)Firefox\b/i;function m(e,i){return e.test(i)}function i(e){var i=e||("undefined"!=typeof navigator?navigator.userAgent:""),o=i.split("[FBAN");void 0!==o[1]&&(i=o[0]),void 0!==(o=i.split("Twitter"))[1]&&(i=o[0]);var d={apple:{phone:m(n,i)&&!m(f,i),ipod:m(t,i),tablet:!m(n,i)&&m(r,i)&&!m(f,i),device:(m(n,i)||m(t,i)||m(r,i))&&!m(f,i)},amazon:{phone:m(b,i),tablet:!m(b,i)&&m(l,i),device:m(b,i)||m(l,i)},android:{phone:!m(f,i)&&m(b,i)||!m(f,i)&&m(a,i),tablet:!m(f,i)&&!m(b,i)&&!m(a,i)&&(m(l,i)||m(p,i)),device:!m(f,i)&&(m(b,i)||m(l,i)||m(a,i)||m(p,i))||m(/\bokhttp\b/i,i)},windows:{phone:m(f,i),tablet:m(s,i),device:m(f,i)||m(s,i)},other:{blackberry:m(u,i),blackberry10:m(c,i),opera:m(h,i),firefox:m(w,i),chrome:m(v,i),device:m(u,i)||m(c,i)||m(h,i)||m(w,i)||m(v,i)}};return d.any=d.apple.device||d.android.device||d.windows.device||d.other.device,d.phone=d.apple.phone||d.android.phone||d.windows.phone,d.tablet=d.apple.tablet||d.android.tablet||d.windows.tablet,d}"undefined"!='object'&&module.exports&&"undefined"==typeof window?module.exports=i:"undefined"!='object'&&module.exports&&"undefined"!=typeof window?(module.exports=i(),module.exports.isMobile=i):"function"==typeof undefined&&undefined.amd?undefined([],e.isMobile=i()):e.isMobile=i();}(commonjsGlobal);
  511. });
  512. var isMobile_min_1 = isMobile_min.isMobile;
  513. /*!
  514. * @pixi/settings - v5.0.4
  515. * Compiled Fri, 07 Jun 2019 17:17:49 UTC
  516. *
  517. * @pixi/settings is licensed under the MIT License.
  518. * http://www.opensource.org/licenses/mit-license
  519. */
  520. /**
  521. * The maximum recommended texture units to use.
  522. * In theory the bigger the better, and for desktop we'll use as many as we can.
  523. * But some mobile devices slow down if there is to many branches in the shader.
  524. * So in practice there seems to be a sweet spot size that varies depending on the device.
  525. *
  526. * In v4, all mobile devices were limited to 4 texture units because for this.
  527. * In v5, we allow all texture units to be used on modern Apple or Android devices.
  528. *
  529. * @private
  530. * @param {number} max
  531. * @returns {number}
  532. */
  533. function maxRecommendedTextures(max)
  534. {
  535. var allowMax = true;
  536. if (isMobile_min.tablet || isMobile_min.phone)
  537. {
  538. allowMax = false;
  539. if (isMobile_min.apple.device)
  540. {
  541. var match = (navigator.userAgent).match(/OS (\d+)_(\d+)?/);
  542. if (match)
  543. {
  544. var majorVersion = parseInt(match[1], 10);
  545. // All texture units can be used on devices that support ios 11 or above
  546. if (majorVersion >= 11)
  547. {
  548. allowMax = true;
  549. }
  550. }
  551. }
  552. if (isMobile_min.android.device)
  553. {
  554. var match$1 = (navigator.userAgent).match(/Android\s([0-9.]*)/);
  555. if (match$1)
  556. {
  557. var majorVersion$1 = parseInt(match$1[1], 10);
  558. // All texture units can be used on devices that support Android 7 (Nougat) or above
  559. if (majorVersion$1 >= 7)
  560. {
  561. allowMax = true;
  562. }
  563. }
  564. }
  565. }
  566. return allowMax ? max : 4;
  567. }
  568. /**
  569. * Uploading the same buffer multiple times in a single frame can cause performance issues.
  570. * Apparent on iOS so only check for that at the moment
  571. * This check may become more complex if this issue pops up elsewhere.
  572. *
  573. * @private
  574. * @returns {boolean}
  575. */
  576. function canUploadSameBuffer()
  577. {
  578. return !isMobile_min.apple.device;
  579. }
  580. /**
  581. * User's customizable globals for overriding the default PIXI settings, such
  582. * as a renderer's default resolution, framerate, float precision, etc.
  583. * @example
  584. * // Use the native window resolution as the default resolution
  585. * // will support high-density displays when rendering
  586. * PIXI.settings.RESOLUTION = window.devicePixelRatio.
  587. *
  588. * // Disable interpolation when scaling, will make texture be pixelated
  589. * PIXI.settings.SCALE_MODE = PIXI.SCALE_MODES.NEAREST;
  590. * @namespace PIXI.settings
  591. */
  592. var settings = {
  593. /**
  594. * If set to true WebGL will attempt make textures mimpaped by default.
  595. * Mipmapping will only succeed if the base texture uploaded has power of two dimensions.
  596. *
  597. * @static
  598. * @name MIPMAP_TEXTURES
  599. * @memberof PIXI.settings
  600. * @type {PIXI.MIPMAP_MODES}
  601. * @default PIXI.MIPMAP_MODES.POW2
  602. */
  603. MIPMAP_TEXTURES: 1,
  604. /**
  605. * Default resolution / device pixel ratio of the renderer.
  606. *
  607. * @static
  608. * @name RESOLUTION
  609. * @memberof PIXI.settings
  610. * @type {number}
  611. * @default 1
  612. */
  613. RESOLUTION: 1,
  614. /**
  615. * Default filter resolution.
  616. *
  617. * @static
  618. * @name FILTER_RESOLUTION
  619. * @memberof PIXI.settings
  620. * @type {number}
  621. * @default 1
  622. */
  623. FILTER_RESOLUTION: 1,
  624. /**
  625. * The maximum textures that this device supports.
  626. *
  627. * @static
  628. * @name SPRITE_MAX_TEXTURES
  629. * @memberof PIXI.settings
  630. * @type {number}
  631. * @default 32
  632. */
  633. SPRITE_MAX_TEXTURES: maxRecommendedTextures(32),
  634. // TODO: maybe change to SPRITE.BATCH_SIZE: 2000
  635. // TODO: maybe add PARTICLE.BATCH_SIZE: 15000
  636. /**
  637. * The default sprite batch size.
  638. *
  639. * The default aims to balance desktop and mobile devices.
  640. *
  641. * @static
  642. * @name SPRITE_BATCH_SIZE
  643. * @memberof PIXI.settings
  644. * @type {number}
  645. * @default 4096
  646. */
  647. SPRITE_BATCH_SIZE: 4096,
  648. /**
  649. * The default render options if none are supplied to {@link PIXI.Renderer}
  650. * or {@link PIXI.CanvasRenderer}.
  651. *
  652. * @static
  653. * @name RENDER_OPTIONS
  654. * @memberof PIXI.settings
  655. * @type {object}
  656. * @property {HTMLCanvasElement} view=null
  657. * @property {number} resolution=1
  658. * @property {boolean} antialias=false
  659. * @property {boolean} forceFXAA=false
  660. * @property {boolean} autoDensity=false
  661. * @property {boolean} transparent=false
  662. * @property {number} backgroundColor=0x000000
  663. * @property {boolean} clearBeforeRender=true
  664. * @property {boolean} preserveDrawingBuffer=false
  665. * @property {number} width=800
  666. * @property {number} height=600
  667. * @property {boolean} legacy=false
  668. */
  669. RENDER_OPTIONS: {
  670. view: null,
  671. antialias: false,
  672. forceFXAA: false,
  673. autoDensity: false,
  674. transparent: false,
  675. backgroundColor: 0x000000,
  676. clearBeforeRender: true,
  677. preserveDrawingBuffer: false,
  678. width: 800,
  679. height: 600,
  680. legacy: false,
  681. },
  682. /**
  683. * Default Garbage Collection mode.
  684. *
  685. * @static
  686. * @name GC_MODE
  687. * @memberof PIXI.settings
  688. * @type {PIXI.GC_MODES}
  689. * @default PIXI.GC_MODES.AUTO
  690. */
  691. GC_MODE: 0,
  692. /**
  693. * Default Garbage Collection max idle.
  694. *
  695. * @static
  696. * @name GC_MAX_IDLE
  697. * @memberof PIXI.settings
  698. * @type {number}
  699. * @default 3600
  700. */
  701. GC_MAX_IDLE: 60 * 60,
  702. /**
  703. * Default Garbage Collection maximum check count.
  704. *
  705. * @static
  706. * @name GC_MAX_CHECK_COUNT
  707. * @memberof PIXI.settings
  708. * @type {number}
  709. * @default 600
  710. */
  711. GC_MAX_CHECK_COUNT: 60 * 10,
  712. /**
  713. * Default wrap modes that are supported by pixi.
  714. *
  715. * @static
  716. * @name WRAP_MODE
  717. * @memberof PIXI.settings
  718. * @type {PIXI.WRAP_MODES}
  719. * @default PIXI.WRAP_MODES.CLAMP
  720. */
  721. WRAP_MODE: 33071,
  722. /**
  723. * Default scale mode for textures.
  724. *
  725. * @static
  726. * @name SCALE_MODE
  727. * @memberof PIXI.settings
  728. * @type {PIXI.SCALE_MODES}
  729. * @default PIXI.SCALE_MODES.LINEAR
  730. */
  731. SCALE_MODE: 1,
  732. /**
  733. * Default specify float precision in vertex shader.
  734. *
  735. * @static
  736. * @name PRECISION_VERTEX
  737. * @memberof PIXI.settings
  738. * @type {PIXI.PRECISION}
  739. * @default PIXI.PRECISION.HIGH
  740. */
  741. PRECISION_VERTEX: 'highp',
  742. /**
  743. * Default specify float precision in fragment shader.
  744. * iOS is best set at highp due to https://github.com/pixijs/pixi.js/issues/3742
  745. *
  746. * @static
  747. * @name PRECISION_FRAGMENT
  748. * @memberof PIXI.settings
  749. * @type {PIXI.PRECISION}
  750. * @default PIXI.PRECISION.MEDIUM
  751. */
  752. PRECISION_FRAGMENT: isMobile_min.apple.device ? 'highp' : 'mediump',
  753. /**
  754. * Can we upload the same buffer in a single frame?
  755. *
  756. * @static
  757. * @name CAN_UPLOAD_SAME_BUFFER
  758. * @memberof PIXI.settings
  759. * @type {boolean}
  760. */
  761. CAN_UPLOAD_SAME_BUFFER: canUploadSameBuffer(),
  762. /**
  763. * Enables bitmap creation before image load. This feature is experimental.
  764. *
  765. * @static
  766. * @name CREATE_IMAGE_BITMAP
  767. * @memberof PIXI.settings
  768. * @type {boolean}
  769. * @default false
  770. */
  771. CREATE_IMAGE_BITMAP: false,
  772. /**
  773. * If true PixiJS will Math.floor() x/y values when rendering, stopping pixel interpolation.
  774. * Advantages can include sharper image quality (like text) and faster rendering on canvas.
  775. * The main disadvantage is movement of objects may appear less smooth.
  776. *
  777. * @static
  778. * @constant
  779. * @memberof PIXI.settings
  780. * @type {boolean}
  781. * @default false
  782. */
  783. ROUND_PIXELS: false,
  784. };
  785. var eventemitter3 = createCommonjsModule(function (module) {
  786. 'use strict';
  787. var has = Object.prototype.hasOwnProperty
  788. , prefix = '~';
  789. /**
  790. * Constructor to create a storage for our `EE` objects.
  791. * An `Events` instance is a plain object whose properties are event names.
  792. *
  793. * @constructor
  794. * @private
  795. */
  796. function Events() {}
  797. //
  798. // We try to not inherit from `Object.prototype`. In some engines creating an
  799. // instance in this way is faster than calling `Object.create(null)` directly.
  800. // If `Object.create(null)` is not supported we prefix the event names with a
  801. // character to make sure that the built-in object properties are not
  802. // overridden or used as an attack vector.
  803. //
  804. if (Object.create) {
  805. Events.prototype = Object.create(null);
  806. //
  807. // This hack is needed because the `__proto__` property is still inherited in
  808. // some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5.
  809. //
  810. if (!new Events().__proto__) { prefix = false; }
  811. }
  812. /**
  813. * Representation of a single event listener.
  814. *
  815. * @param {Function} fn The listener function.
  816. * @param {*} context The context to invoke the listener with.
  817. * @param {Boolean} [once=false] Specify if the listener is a one-time listener.
  818. * @constructor
  819. * @private
  820. */
  821. function EE(fn, context, once) {
  822. this.fn = fn;
  823. this.context = context;
  824. this.once = once || false;
  825. }
  826. /**
  827. * Add a listener for a given event.
  828. *
  829. * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.
  830. * @param {(String|Symbol)} event The event name.
  831. * @param {Function} fn The listener function.
  832. * @param {*} context The context to invoke the listener with.
  833. * @param {Boolean} once Specify if the listener is a one-time listener.
  834. * @returns {EventEmitter}
  835. * @private
  836. */
  837. function addListener(emitter, event, fn, context, once) {
  838. if (typeof fn !== 'function') {
  839. throw new TypeError('The listener must be a function');
  840. }
  841. var listener = new EE(fn, context || emitter, once)
  842. , evt = prefix ? prefix + event : event;
  843. if (!emitter._events[evt]) { emitter._events[evt] = listener, emitter._eventsCount++; }
  844. else if (!emitter._events[evt].fn) { emitter._events[evt].push(listener); }
  845. else { emitter._events[evt] = [emitter._events[evt], listener]; }
  846. return emitter;
  847. }
  848. /**
  849. * Clear event by name.
  850. *
  851. * @param {EventEmitter} emitter Reference to the `EventEmitter` instance.
  852. * @param {(String|Symbol)} evt The Event name.
  853. * @private
  854. */
  855. function clearEvent(emitter, evt) {
  856. if (--emitter._eventsCount === 0) { emitter._events = new Events(); }
  857. else { delete emitter._events[evt]; }
  858. }
  859. /**
  860. * Minimal `EventEmitter` interface that is molded against the Node.js
  861. * `EventEmitter` interface.
  862. *
  863. * @constructor
  864. * @public
  865. */
  866. function EventEmitter() {
  867. this._events = new Events();
  868. this._eventsCount = 0;
  869. }
  870. /**
  871. * Return an array listing the events for which the emitter has registered
  872. * listeners.
  873. *
  874. * @returns {Array}
  875. * @public
  876. */
  877. EventEmitter.prototype.eventNames = function eventNames() {
  878. var names = []
  879. , events
  880. , name;
  881. if (this._eventsCount === 0) { return names; }
  882. for (name in (events = this._events)) {
  883. if (has.call(events, name)) { names.push(prefix ? name.slice(1) : name); }
  884. }
  885. if (Object.getOwnPropertySymbols) {
  886. return names.concat(Object.getOwnPropertySymbols(events));
  887. }
  888. return names;
  889. };
  890. /**
  891. * Return the listeners registered for a given event.
  892. *
  893. * @param {(String|Symbol)} event The event name.
  894. * @returns {Array} The registered listeners.
  895. * @public
  896. */
  897. EventEmitter.prototype.listeners = function listeners(event) {
  898. var evt = prefix ? prefix + event : event
  899. , handlers = this._events[evt];
  900. if (!handlers) { return []; }
  901. if (handlers.fn) { return [handlers.fn]; }
  902. for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) {
  903. ee[i] = handlers[i].fn;
  904. }
  905. return ee;
  906. };
  907. /**
  908. * Return the number of listeners listening to a given event.
  909. *
  910. * @param {(String|Symbol)} event The event name.
  911. * @returns {Number} The number of listeners.
  912. * @public
  913. */
  914. EventEmitter.prototype.listenerCount = function listenerCount(event) {
  915. var evt = prefix ? prefix + event : event
  916. , listeners = this._events[evt];
  917. if (!listeners) { return 0; }
  918. if (listeners.fn) { return 1; }
  919. return listeners.length;
  920. };
  921. /**
  922. * Calls each of the listeners registered for a given event.
  923. *
  924. * @param {(String|Symbol)} event The event name.
  925. * @returns {Boolean} `true` if the event had listeners, else `false`.
  926. * @public
  927. */
  928. EventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) {
  929. var arguments$1 = arguments;
  930. var evt = prefix ? prefix + event : event;
  931. if (!this._events[evt]) { return false; }
  932. var listeners = this._events[evt]
  933. , len = arguments.length
  934. , args
  935. , i;
  936. if (listeners.fn) {
  937. if (listeners.once) { this.removeListener(event, listeners.fn, undefined, true); }
  938. switch (len) {
  939. case 1: return listeners.fn.call(listeners.context), true;
  940. case 2: return listeners.fn.call(listeners.context, a1), true;
  941. case 3: return listeners.fn.call(listeners.context, a1, a2), true;
  942. case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true;
  943. case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true;
  944. case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true;
  945. }
  946. for (i = 1, args = new Array(len -1); i < len; i++) {
  947. args[i - 1] = arguments$1[i];
  948. }
  949. listeners.fn.apply(listeners.context, args);
  950. } else {
  951. var length = listeners.length
  952. , j;
  953. for (i = 0; i < length; i++) {
  954. if (listeners[i].once) { this.removeListener(event, listeners[i].fn, undefined, true); }
  955. switch (len) {
  956. case 1: listeners[i].fn.call(listeners[i].context); break;
  957. case 2: listeners[i].fn.call(listeners[i].context, a1); break;
  958. case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break;
  959. case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break;
  960. default:
  961. if (!args) { for (j = 1, args = new Array(len -1); j < len; j++) {
  962. args[j - 1] = arguments$1[j];
  963. } }
  964. listeners[i].fn.apply(listeners[i].context, args);
  965. }
  966. }
  967. }
  968. return true;
  969. };
  970. /**
  971. * Add a listener for a given event.
  972. *
  973. * @param {(String|Symbol)} event The event name.
  974. * @param {Function} fn The listener function.
  975. * @param {*} [context=this] The context to invoke the listener with.
  976. * @returns {EventEmitter} `this`.
  977. * @public
  978. */
  979. EventEmitter.prototype.on = function on(event, fn, context) {
  980. return addListener(this, event, fn, context, false);
  981. };
  982. /**
  983. * Add a one-time listener for a given event.
  984. *
  985. * @param {(String|Symbol)} event The event name.
  986. * @param {Function} fn The listener function.
  987. * @param {*} [context=this] The context to invoke the listener with.
  988. * @returns {EventEmitter} `this`.
  989. * @public
  990. */
  991. EventEmitter.prototype.once = function once(event, fn, context) {
  992. return addListener(this, event, fn, context, true);
  993. };
  994. /**
  995. * Remove the listeners of a given event.
  996. *
  997. * @param {(String|Symbol)} event The event name.
  998. * @param {Function} fn Only remove the listeners that match this function.
  999. * @param {*} context Only remove the listeners that have this context.
  1000. * @param {Boolean} once Only remove one-time listeners.
  1001. * @returns {EventEmitter} `this`.
  1002. * @public
  1003. */
  1004. EventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) {
  1005. var evt = prefix ? prefix + event : event;
  1006. if (!this._events[evt]) { return this; }
  1007. if (!fn) {
  1008. clearEvent(this, evt);
  1009. return this;
  1010. }
  1011. var listeners = this._events[evt];
  1012. if (listeners.fn) {
  1013. if (
  1014. listeners.fn === fn &&
  1015. (!once || listeners.once) &&
  1016. (!context || listeners.context === context)
  1017. ) {
  1018. clearEvent(this, evt);
  1019. }
  1020. } else {
  1021. for (var i = 0, events = [], length = listeners.length; i < length; i++) {
  1022. if (
  1023. listeners[i].fn !== fn ||
  1024. (once && !listeners[i].once) ||
  1025. (context && listeners[i].context !== context)
  1026. ) {
  1027. events.push(listeners[i]);
  1028. }
  1029. }
  1030. //
  1031. // Reset the array, or remove it completely if we have no more listeners.
  1032. //
  1033. if (events.length) { this._events[evt] = events.length === 1 ? events[0] : events; }
  1034. else { clearEvent(this, evt); }
  1035. }
  1036. return this;
  1037. };
  1038. /**
  1039. * Remove all listeners, or those of the specified event.
  1040. *
  1041. * @param {(String|Symbol)} [event] The event name.
  1042. * @returns {EventEmitter} `this`.
  1043. * @public
  1044. */
  1045. EventEmitter.prototype.removeAllListeners = function removeAllListeners(event) {
  1046. var evt;
  1047. if (event) {
  1048. evt = prefix ? prefix + event : event;
  1049. if (this._events[evt]) { clearEvent(this, evt); }
  1050. } else {
  1051. this._events = new Events();
  1052. this._eventsCount = 0;
  1053. }
  1054. return this;
  1055. };
  1056. //
  1057. // Alias methods names because people roll like that.
  1058. //
  1059. EventEmitter.prototype.off = EventEmitter.prototype.removeListener;
  1060. EventEmitter.prototype.addListener = EventEmitter.prototype.on;
  1061. //
  1062. // Expose the prefix.
  1063. //
  1064. EventEmitter.prefixed = prefix;
  1065. //
  1066. // Allow `EventEmitter` to be imported as module namespace.
  1067. //
  1068. EventEmitter.EventEmitter = EventEmitter;
  1069. //
  1070. // Expose the module.
  1071. //
  1072. if ('undefined' !== 'object') {
  1073. module.exports = EventEmitter;
  1074. }
  1075. });
  1076. 'use strict';
  1077. var earcut_1 = earcut;
  1078. var default_1 = earcut;
  1079. function earcut(data, holeIndices, dim) {
  1080. dim = dim || 2;
  1081. var hasHoles = holeIndices && holeIndices.length,
  1082. outerLen = hasHoles ? holeIndices[0] * dim : data.length,
  1083. outerNode = linkedList(data, 0, outerLen, dim, true),
  1084. triangles = [];
  1085. if (!outerNode || outerNode.next === outerNode.prev) { return triangles; }
  1086. var minX, minY, maxX, maxY, x, y, invSize;
  1087. if (hasHoles) { outerNode = eliminateHoles(data, holeIndices, outerNode, dim); }
  1088. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  1089. if (data.length > 80 * dim) {
  1090. minX = maxX = data[0];
  1091. minY = maxY = data[1];
  1092. for (var i = dim; i < outerLen; i += dim) {
  1093. x = data[i];
  1094. y = data[i + 1];
  1095. if (x < minX) { minX = x; }
  1096. if (y < minY) { minY = y; }
  1097. if (x > maxX) { maxX = x; }
  1098. if (y > maxY) { maxY = y; }
  1099. }
  1100. // minX, minY and invSize are later used to transform coords into integers for z-order calculation
  1101. invSize = Math.max(maxX - minX, maxY - minY);
  1102. invSize = invSize !== 0 ? 1 / invSize : 0;
  1103. }
  1104. earcutLinked(outerNode, triangles, dim, minX, minY, invSize);
  1105. return triangles;
  1106. }
  1107. // create a circular doubly linked list from polygon points in the specified winding order
  1108. function linkedList(data, start, end, dim, clockwise) {
  1109. var i, last;
  1110. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  1111. for (i = start; i < end; i += dim) { last = insertNode(i, data[i], data[i + 1], last); }
  1112. } else {
  1113. for (i = end - dim; i >= start; i -= dim) { last = insertNode(i, data[i], data[i + 1], last); }
  1114. }
  1115. if (last && equals(last, last.next)) {
  1116. removeNode(last);
  1117. last = last.next;
  1118. }
  1119. return last;
  1120. }
  1121. // eliminate colinear or duplicate points
  1122. function filterPoints(start, end) {
  1123. if (!start) { return start; }
  1124. if (!end) { end = start; }
  1125. var p = start,
  1126. again;
  1127. do {
  1128. again = false;
  1129. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  1130. removeNode(p);
  1131. p = end = p.prev;
  1132. if (p === p.next) { break; }
  1133. again = true;
  1134. } else {
  1135. p = p.next;
  1136. }
  1137. } while (again || p !== end);
  1138. return end;
  1139. }
  1140. // main ear slicing loop which triangulates a polygon (given as a linked list)
  1141. function earcutLinked(ear, triangles, dim, minX, minY, invSize, pass) {
  1142. if (!ear) { return; }
  1143. // interlink polygon nodes in z-order
  1144. if (!pass && invSize) { indexCurve(ear, minX, minY, invSize); }
  1145. var stop = ear,
  1146. prev, next;
  1147. // iterate through ears, slicing them one by one
  1148. while (ear.prev !== ear.next) {
  1149. prev = ear.prev;
  1150. next = ear.next;
  1151. if (invSize ? isEarHashed(ear, minX, minY, invSize) : isEar(ear)) {
  1152. // cut off the triangle
  1153. triangles.push(prev.i / dim);
  1154. triangles.push(ear.i / dim);
  1155. triangles.push(next.i / dim);
  1156. removeNode(ear);
  1157. // skipping the next vertex leads to less sliver triangles
  1158. ear = next.next;
  1159. stop = next.next;
  1160. continue;
  1161. }
  1162. ear = next;
  1163. // if we looped through the whole remaining polygon and can't find any more ears
  1164. if (ear === stop) {
  1165. // try filtering points and slicing again
  1166. if (!pass) {
  1167. earcutLinked(filterPoints(ear), triangles, dim, minX, minY, invSize, 1);
  1168. // if this didn't work, try curing all small self-intersections locally
  1169. } else if (pass === 1) {
  1170. ear = cureLocalIntersections(ear, triangles, dim);
  1171. earcutLinked(ear, triangles, dim, minX, minY, invSize, 2);
  1172. // as a last resort, try splitting the remaining polygon into two
  1173. } else if (pass === 2) {
  1174. splitEarcut(ear, triangles, dim, minX, minY, invSize);
  1175. }
  1176. break;
  1177. }
  1178. }
  1179. }
  1180. // check whether a polygon node forms a valid ear with adjacent nodes
  1181. function isEar(ear) {
  1182. var a = ear.prev,
  1183. b = ear,
  1184. c = ear.next;
  1185. if (area(a, b, c) >= 0) { return false; } // reflex, can't be an ear
  1186. // now make sure we don't have other points inside the potential ear
  1187. var p = ear.next.next;
  1188. while (p !== ear.prev) {
  1189. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  1190. area(p.prev, p, p.next) >= 0) { return false; }
  1191. p = p.next;
  1192. }
  1193. return true;
  1194. }
  1195. function isEarHashed(ear, minX, minY, invSize) {
  1196. var a = ear.prev,
  1197. b = ear,
  1198. c = ear.next;
  1199. if (area(a, b, c) >= 0) { return false; } // reflex, can't be an ear
  1200. // triangle bbox; min & max are calculated like this for speed
  1201. var minTX = a.x < b.x ? (a.x < c.x ? a.x : c.x) : (b.x < c.x ? b.x : c.x),
  1202. minTY = a.y < b.y ? (a.y < c.y ? a.y : c.y) : (b.y < c.y ? b.y : c.y),
  1203. maxTX = a.x > b.x ? (a.x > c.x ? a.x : c.x) : (b.x > c.x ? b.x : c.x),
  1204. maxTY = a.y > b.y ? (a.y > c.y ? a.y : c.y) : (b.y > c.y ? b.y : c.y);
  1205. // z-order range for the current triangle bbox;
  1206. var minZ = zOrder(minTX, minTY, minX, minY, invSize),
  1207. maxZ = zOrder(maxTX, maxTY, minX, minY, invSize);
  1208. var p = ear.prevZ,
  1209. n = ear.nextZ;
  1210. // look for points inside the triangle in both directions
  1211. while (p && p.z >= minZ && n && n.z <= maxZ) {
  1212. if (p !== ear.prev && p !== ear.next &&
  1213. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  1214. area(p.prev, p, p.next) >= 0) { return false; }
  1215. p = p.prevZ;
  1216. if (n !== ear.prev && n !== ear.next &&
  1217. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, n.x, n.y) &&
  1218. area(n.prev, n, n.next) >= 0) { return false; }
  1219. n = n.nextZ;
  1220. }
  1221. // look for remaining points in decreasing z-order
  1222. while (p && p.z >= minZ) {
  1223. if (p !== ear.prev && p !== ear.next &&
  1224. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  1225. area(p.prev, p, p.next) >= 0) { return false; }
  1226. p = p.prevZ;
  1227. }
  1228. // look for remaining points in increasing z-order
  1229. while (n && n.z <= maxZ) {
  1230. if (n !== ear.prev && n !== ear.next &&
  1231. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, n.x, n.y) &&
  1232. area(n.prev, n, n.next) >= 0) { return false; }
  1233. n = n.nextZ;
  1234. }
  1235. return true;
  1236. }
  1237. // go through all polygon nodes and cure small local self-intersections
  1238. function cureLocalIntersections(start, triangles, dim) {
  1239. var p = start;
  1240. do {
  1241. var a = p.prev,
  1242. b = p.next.next;
  1243. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  1244. triangles.push(a.i / dim);
  1245. triangles.push(p.i / dim);
  1246. triangles.push(b.i / dim);
  1247. // remove two nodes involved
  1248. removeNode(p);
  1249. removeNode(p.next);
  1250. p = start = b;
  1251. }
  1252. p = p.next;
  1253. } while (p !== start);
  1254. return p;
  1255. }
  1256. // try splitting polygon into two and triangulate them independently
  1257. function splitEarcut(start, triangles, dim, minX, minY, invSize) {
  1258. // look for a valid diagonal that divides the polygon into two
  1259. var a = start;
  1260. do {
  1261. var b = a.next.next;
  1262. while (b !== a.prev) {
  1263. if (a.i !== b.i && isValidDiagonal(a, b)) {
  1264. // split the polygon in two by the diagonal
  1265. var c = splitPolygon(a, b);
  1266. // filter colinear points around the cuts
  1267. a = filterPoints(a, a.next);
  1268. c = filterPoints(c, c.next);
  1269. // run earcut on each half
  1270. earcutLinked(a, triangles, dim, minX, minY, invSize);
  1271. earcutLinked(c, triangles, dim, minX, minY, invSize);
  1272. return;
  1273. }
  1274. b = b.next;
  1275. }
  1276. a = a.next;
  1277. } while (a !== start);
  1278. }
  1279. // link every hole into the outer loop, producing a single-ring polygon without holes
  1280. function eliminateHoles(data, holeIndices, outerNode, dim) {
  1281. var queue = [],
  1282. i, len, start, end, list;
  1283. for (i = 0, len = holeIndices.length; i < len; i++) {
  1284. start = holeIndices[i] * dim;
  1285. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  1286. list = linkedList(data, start, end, dim, false);
  1287. if (list === list.next) { list.steiner = true; }
  1288. queue.push(getLeftmost(list));
  1289. }
  1290. queue.sort(compareX);
  1291. // process holes from left to right
  1292. for (i = 0; i < queue.length; i++) {
  1293. eliminateHole(queue[i], outerNode);
  1294. outerNode = filterPoints(outerNode, outerNode.next);
  1295. }
  1296. return outerNode;
  1297. }
  1298. function compareX(a, b) {
  1299. return a.x - b.x;
  1300. }
  1301. // find a bridge between vertices that connects hole with an outer ring and and link it
  1302. function eliminateHole(hole, outerNode) {
  1303. outerNode = findHoleBridge(hole, outerNode);
  1304. if (outerNode) {
  1305. var b = splitPolygon(outerNode, hole);
  1306. filterPoints(b, b.next);
  1307. }
  1308. }
  1309. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  1310. function findHoleBridge(hole, outerNode) {
  1311. var p = outerNode,
  1312. hx = hole.x,
  1313. hy = hole.y,
  1314. qx = -Infinity,
  1315. m;
  1316. // find a segment intersected by a ray from the hole's leftmost point to the left;
  1317. // segment's endpoint with lesser x will be potential connection point
  1318. do {
  1319. if (hy <= p.y && hy >= p.next.y && p.next.y !== p.y) {
  1320. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  1321. if (x <= hx && x > qx) {
  1322. qx = x;
  1323. if (x === hx) {
  1324. if (hy === p.y) { return p; }
  1325. if (hy === p.next.y) { return p.next; }
  1326. }
  1327. m = p.x < p.next.x ? p : p.next;
  1328. }
  1329. }
  1330. p = p.next;
  1331. } while (p !== outerNode);
  1332. if (!m) { return null; }
  1333. if (hx === qx) { return m.prev; } // hole touches outer segment; pick lower endpoint
  1334. // look for points inside the triangle of hole point, segment intersection and endpoint;
  1335. // if there are no points found, we have a valid connection;
  1336. // otherwise choose the point of the minimum angle with the ray as connection point
  1337. var stop = m,
  1338. mx = m.x,
  1339. my = m.y,
  1340. tanMin = Infinity,
  1341. tan;
  1342. p = m.next;
  1343. while (p !== stop) {
  1344. if (hx >= p.x && p.x >= mx && hx !== p.x &&
  1345. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  1346. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  1347. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  1348. m = p;
  1349. tanMin = tan;
  1350. }
  1351. }
  1352. p = p.next;
  1353. }
  1354. return m;
  1355. }
  1356. // interlink polygon nodes in z-order
  1357. function indexCurve(start, minX, minY, invSize) {
  1358. var p = start;
  1359. do {
  1360. if (p.z === null) { p.z = zOrder(p.x, p.y, minX, minY, invSize); }
  1361. p.prevZ = p.prev;
  1362. p.nextZ = p.next;
  1363. p = p.next;
  1364. } while (p !== start);
  1365. p.prevZ.nextZ = null;
  1366. p.prevZ = null;
  1367. sortLinked(p);
  1368. }
  1369. // Simon Tatham's linked list merge sort algorithm
  1370. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  1371. function sortLinked(list) {
  1372. var i, p, q, e, tail, numMerges, pSize, qSize,
  1373. inSize = 1;
  1374. do {
  1375. p = list;
  1376. list = null;
  1377. tail = null;
  1378. numMerges = 0;
  1379. while (p) {
  1380. numMerges++;
  1381. q = p;
  1382. pSize = 0;
  1383. for (i = 0; i < inSize; i++) {
  1384. pSize++;
  1385. q = q.nextZ;
  1386. if (!q) { break; }
  1387. }
  1388. qSize = inSize;
  1389. while (pSize > 0 || (qSize > 0 && q)) {
  1390. if (pSize !== 0 && (qSize === 0 || !q || p.z <= q.z)) {
  1391. e = p;
  1392. p = p.nextZ;
  1393. pSize--;
  1394. } else {
  1395. e = q;
  1396. q = q.nextZ;
  1397. qSize--;
  1398. }
  1399. if (tail) { tail.nextZ = e; }
  1400. else { list = e; }
  1401. e.prevZ = tail;
  1402. tail = e;
  1403. }
  1404. p = q;
  1405. }
  1406. tail.nextZ = null;
  1407. inSize *= 2;
  1408. } while (numMerges > 1);
  1409. return list;
  1410. }
  1411. // z-order of a point given coords and inverse of the longer side of data bbox
  1412. function zOrder(x, y, minX, minY, invSize) {
  1413. // coords are transformed into non-negative 15-bit integer range
  1414. x = 32767 * (x - minX) * invSize;
  1415. y = 32767 * (y - minY) * invSize;
  1416. x = (x | (x << 8)) & 0x00FF00FF;
  1417. x = (x | (x << 4)) & 0x0F0F0F0F;
  1418. x = (x | (x << 2)) & 0x33333333;
  1419. x = (x | (x << 1)) & 0x55555555;
  1420. y = (y | (y << 8)) & 0x00FF00FF;
  1421. y = (y | (y << 4)) & 0x0F0F0F0F;
  1422. y = (y | (y << 2)) & 0x33333333;
  1423. y = (y | (y << 1)) & 0x55555555;
  1424. return x | (y << 1);
  1425. }
  1426. // find the leftmost node of a polygon ring
  1427. function getLeftmost(start) {
  1428. var p = start,
  1429. leftmost = start;
  1430. do {
  1431. if (p.x < leftmost.x || (p.x === leftmost.x && p.y < leftmost.y)) { leftmost = p; }
  1432. p = p.next;
  1433. } while (p !== start);
  1434. return leftmost;
  1435. }
  1436. // check if a point lies within a convex triangle
  1437. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  1438. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  1439. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  1440. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  1441. }
  1442. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  1443. function isValidDiagonal(a, b) {
  1444. return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) &&
  1445. locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b);
  1446. }
  1447. // signed area of a triangle
  1448. function area(p, q, r) {
  1449. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  1450. }
  1451. // check if two points are equal
  1452. function equals(p1, p2) {
  1453. return p1.x === p2.x && p1.y === p2.y;
  1454. }
  1455. // check if two segments intersect
  1456. function intersects(p1, q1, p2, q2) {
  1457. if ((equals(p1, q1) && equals(p2, q2)) ||
  1458. (equals(p1, q2) && equals(p2, q1))) { return true; }
  1459. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  1460. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  1461. }
  1462. // check if a polygon diagonal intersects any polygon segments
  1463. function intersectsPolygon(a, b) {
  1464. var p = a;
  1465. do {
  1466. if (p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i &&
  1467. intersects(p, p.next, a, b)) { return true; }
  1468. p = p.next;
  1469. } while (p !== a);
  1470. return false;
  1471. }
  1472. // check if a polygon diagonal is locally inside the polygon
  1473. function locallyInside(a, b) {
  1474. return area(a.prev, a, a.next) < 0 ?
  1475. area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0 :
  1476. area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  1477. }
  1478. // check if the middle point of a polygon diagonal is inside the polygon
  1479. function middleInside(a, b) {
  1480. var p = a,
  1481. inside = false,
  1482. px = (a.x + b.x) / 2,
  1483. py = (a.y + b.y) / 2;
  1484. do {
  1485. if (((p.y > py) !== (p.next.y > py)) && p.next.y !== p.y &&
  1486. (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  1487. { inside = !inside; }
  1488. p = p.next;
  1489. } while (p !== a);
  1490. return inside;
  1491. }
  1492. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  1493. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  1494. function splitPolygon(a, b) {
  1495. var a2 = new Node(a.i, a.x, a.y),
  1496. b2 = new Node(b.i, b.x, b.y),
  1497. an = a.next,
  1498. bp = b.prev;
  1499. a.next = b;
  1500. b.prev = a;
  1501. a2.next = an;
  1502. an.prev = a2;
  1503. b2.next = a2;
  1504. a2.prev = b2;
  1505. bp.next = b2;
  1506. b2.prev = bp;
  1507. return b2;
  1508. }
  1509. // create a node and optionally link it with previous one (in a circular doubly linked list)
  1510. function insertNode(i, x, y, last) {
  1511. var p = new Node(i, x, y);
  1512. if (!last) {
  1513. p.prev = p;
  1514. p.next = p;
  1515. } else {
  1516. p.next = last.next;
  1517. p.prev = last;
  1518. last.next.prev = p;
  1519. last.next = p;
  1520. }
  1521. return p;
  1522. }
  1523. function removeNode(p) {
  1524. p.next.prev = p.prev;
  1525. p.prev.next = p.next;
  1526. if (p.prevZ) { p.prevZ.nextZ = p.nextZ; }
  1527. if (p.nextZ) { p.nextZ.prevZ = p.prevZ; }
  1528. }
  1529. function Node(i, x, y) {
  1530. // vertex index in coordinates array
  1531. this.i = i;
  1532. // vertex coordinates
  1533. this.x = x;
  1534. this.y = y;
  1535. // previous and next vertex nodes in a polygon ring
  1536. this.prev = null;
  1537. this.next = null;
  1538. // z-order curve value
  1539. this.z = null;
  1540. // previous and next nodes in z-order
  1541. this.prevZ = null;
  1542. this.nextZ = null;
  1543. // indicates whether this is a steiner point
  1544. this.steiner = false;
  1545. }
  1546. // return a percentage difference between the polygon area and its triangulation area;
  1547. // used to verify correctness of triangulation
  1548. earcut.deviation = function (data, holeIndices, dim, triangles) {
  1549. var hasHoles = holeIndices && holeIndices.length;
  1550. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  1551. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  1552. if (hasHoles) {
  1553. for (var i = 0, len = holeIndices.length; i < len; i++) {
  1554. var start = holeIndices[i] * dim;
  1555. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  1556. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  1557. }
  1558. }
  1559. var trianglesArea = 0;
  1560. for (i = 0; i < triangles.length; i += 3) {
  1561. var a = triangles[i] * dim;
  1562. var b = triangles[i + 1] * dim;
  1563. var c = triangles[i + 2] * dim;
  1564. trianglesArea += Math.abs(
  1565. (data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  1566. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  1567. }
  1568. return polygonArea === 0 && trianglesArea === 0 ? 0 :
  1569. Math.abs((trianglesArea - polygonArea) / polygonArea);
  1570. };
  1571. function signedArea(data, start, end, dim) {
  1572. var sum = 0;
  1573. for (var i = start, j = end - dim; i < end; i += dim) {
  1574. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  1575. j = i;
  1576. }
  1577. return sum;
  1578. }
  1579. // turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  1580. earcut.flatten = function (data) {
  1581. var dim = data[0][0].length,
  1582. result = {vertices: [], holes: [], dimensions: dim},
  1583. holeIndex = 0;
  1584. for (var i = 0; i < data.length; i++) {
  1585. for (var j = 0; j < data[i].length; j++) {
  1586. for (var d = 0; d < dim; d++) { result.vertices.push(data[i][j][d]); }
  1587. }
  1588. if (i > 0) {
  1589. holeIndex += data[i - 1].length;
  1590. result.holes.push(holeIndex);
  1591. }
  1592. }
  1593. return result;
  1594. };
  1595. earcut_1.default = default_1;
  1596. var punycode = createCommonjsModule(function (module, exports) {
  1597. /*! https://mths.be/punycode v1.3.2 by @mathias */
  1598. ;(function(root) {
  1599. /** Detect free variables */
  1600. var freeExports = 'object' == 'object' && exports &&
  1601. !exports.nodeType && exports;
  1602. var freeModule = 'object' == 'object' && module &&
  1603. !module.nodeType && module;
  1604. var freeGlobal = typeof commonjsGlobal == 'object' && commonjsGlobal;
  1605. if (
  1606. freeGlobal.global === freeGlobal ||
  1607. freeGlobal.window === freeGlobal ||
  1608. freeGlobal.self === freeGlobal
  1609. ) {
  1610. root = freeGlobal;
  1611. }
  1612. /**
  1613. * The `punycode` object.
  1614. * @name punycode
  1615. * @type Object
  1616. */
  1617. var punycode,
  1618. /** Highest positive signed 32-bit float value */
  1619. maxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1
  1620. /** Bootstring parameters */
  1621. base = 36,
  1622. tMin = 1,
  1623. tMax = 26,
  1624. skew = 38,
  1625. damp = 700,
  1626. initialBias = 72,
  1627. initialN = 128, // 0x80
  1628. delimiter = '-', // '\x2D'
  1629. /** Regular expressions */
  1630. regexPunycode = /^xn--/,
  1631. regexNonASCII = /[^\x20-\x7E]/, // unprintable ASCII chars + non-ASCII chars
  1632. regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g, // RFC 3490 separators
  1633. /** Error messages */
  1634. errors = {
  1635. 'overflow': 'Overflow: input needs wider integers to process',
  1636. 'not-basic': 'Illegal input >= 0x80 (not a basic code point)',
  1637. 'invalid-input': 'Invalid input'
  1638. },
  1639. /** Convenience shortcuts */
  1640. baseMinusTMin = base - tMin,
  1641. floor = Math.floor,
  1642. stringFromCharCode = String.fromCharCode,
  1643. /** Temporary variable */
  1644. key;
  1645. /*--------------------------------------------------------------------------*/
  1646. /**
  1647. * A generic error utility function.
  1648. * @private
  1649. * @param {String} type The error type.
  1650. * @returns {Error} Throws a `RangeError` with the applicable error message.
  1651. */
  1652. function error(type) {
  1653. throw RangeError(errors[type]);
  1654. }
  1655. /**
  1656. * A generic `Array#map` utility function.
  1657. * @private
  1658. * @param {Array} array The array to iterate over.
  1659. * @param {Function} callback The function that gets called for every array
  1660. * item.
  1661. * @returns {Array} A new array of values returned by the callback function.
  1662. */
  1663. function map(array, fn) {
  1664. var length = array.length;
  1665. var result = [];
  1666. while (length--) {
  1667. result[length] = fn(array[length]);
  1668. }
  1669. return result;
  1670. }
  1671. /**
  1672. * A simple `Array#map`-like wrapper to work with domain name strings or email
  1673. * addresses.
  1674. * @private
  1675. * @param {String} domain The domain name or email address.
  1676. * @param {Function} callback The function that gets called for every
  1677. * character.
  1678. * @returns {Array} A new string of characters returned by the callback
  1679. * function.
  1680. */
  1681. function mapDomain(string, fn) {
  1682. var parts = string.split('@');
  1683. var result = '';
  1684. if (parts.length > 1) {
  1685. // In email addresses, only the domain name should be punycoded. Leave
  1686. // the local part (i.e. everything up to `@`) intact.
  1687. result = parts[0] + '@';
  1688. string = parts[1];
  1689. }
  1690. // Avoid `split(regex)` for IE8 compatibility. See #17.
  1691. string = string.replace(regexSeparators, '\x2E');
  1692. var labels = string.split('.');
  1693. var encoded = map(labels, fn).join('.');
  1694. return result + encoded;
  1695. }
  1696. /**
  1697. * Creates an array containing the numeric code points of each Unicode
  1698. * character in the string. While JavaScript uses UCS-2 internally,
  1699. * this function will convert a pair of surrogate halves (each of which
  1700. * UCS-2 exposes as separate characters) into a single code point,
  1701. * matching UTF-16.
  1702. * @see `punycode.ucs2.encode`
  1703. * @see <https://mathiasbynens.be/notes/javascript-encoding>
  1704. * @memberOf punycode.ucs2
  1705. * @name decode
  1706. * @param {String} string The Unicode input string (UCS-2).
  1707. * @returns {Array} The new array of code points.
  1708. */
  1709. function ucs2decode(string) {
  1710. var output = [],
  1711. counter = 0,
  1712. length = string.length,
  1713. value,
  1714. extra;
  1715. while (counter < length) {
  1716. value = string.charCodeAt(counter++);
  1717. if (value >= 0xD800 && value <= 0xDBFF && counter < length) {
  1718. // high surrogate, and there is a next character
  1719. extra = string.charCodeAt(counter++);
  1720. if ((extra & 0xFC00) == 0xDC00) { // low surrogate
  1721. output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);
  1722. } else {
  1723. // unmatched surrogate; only append this code unit, in case the next
  1724. // code unit is the high surrogate of a surrogate pair
  1725. output.push(value);
  1726. counter--;
  1727. }
  1728. } else {
  1729. output.push(value);
  1730. }
  1731. }
  1732. return output;
  1733. }
  1734. /**
  1735. * Creates a string based on an array of numeric code points.
  1736. * @see `punycode.ucs2.decode`
  1737. * @memberOf punycode.ucs2
  1738. * @name encode
  1739. * @param {Array} codePoints The array of numeric code points.
  1740. * @returns {String} The new Unicode string (UCS-2).
  1741. */
  1742. function ucs2encode(array) {
  1743. return map(array, function(value) {
  1744. var output = '';
  1745. if (value > 0xFFFF) {
  1746. value -= 0x10000;
  1747. output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800);
  1748. value = 0xDC00 | value & 0x3FF;
  1749. }
  1750. output += stringFromCharCode(value);
  1751. return output;
  1752. }).join('');
  1753. }
  1754. /**
  1755. * Converts a basic code point into a digit/integer.
  1756. * @see `digitToBasic()`
  1757. * @private
  1758. * @param {Number} codePoint The basic numeric code point value.
  1759. * @returns {Number} The numeric value of a basic code point (for use in
  1760. * representing integers) in the range `0` to `base - 1`, or `base` if
  1761. * the code point does not represent a value.
  1762. */
  1763. function basicToDigit(codePoint) {
  1764. if (codePoint - 48 < 10) {
  1765. return codePoint - 22;
  1766. }
  1767. if (codePoint - 65 < 26) {
  1768. return codePoint - 65;
  1769. }
  1770. if (codePoint - 97 < 26) {
  1771. return codePoint - 97;
  1772. }
  1773. return base;
  1774. }
  1775. /**
  1776. * Converts a digit/integer into a basic code point.
  1777. * @see `basicToDigit()`
  1778. * @private
  1779. * @param {Number} digit The numeric value of a basic code point.
  1780. * @returns {Number} The basic code point whose value (when used for
  1781. * representing integers) is `digit`, which needs to be in the range
  1782. * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is
  1783. * used; else, the lowercase form is used. The behavior is undefined
  1784. * if `flag` is non-zero and `digit` has no uppercase form.
  1785. */
  1786. function digitToBasic(digit, flag) {
  1787. // 0..25 map to ASCII a..z or A..Z
  1788. // 26..35 map to ASCII 0..9
  1789. return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5);
  1790. }
  1791. /**
  1792. * Bias adaptation function as per section 3.4 of RFC 3492.
  1793. * http://tools.ietf.org/html/rfc3492#section-3.4
  1794. * @private
  1795. */
  1796. function adapt(delta, numPoints, firstTime) {
  1797. var k = 0;
  1798. delta = firstTime ? floor(delta / damp) : delta >> 1;
  1799. delta += floor(delta / numPoints);
  1800. for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) {
  1801. delta = floor(delta / baseMinusTMin);
  1802. }
  1803. return floor(k + (baseMinusTMin + 1) * delta / (delta + skew));
  1804. }
  1805. /**
  1806. * Converts a Punycode string of ASCII-only symbols to a string of Unicode
  1807. * symbols.
  1808. * @memberOf punycode
  1809. * @param {String} input The Punycode string of ASCII-only symbols.
  1810. * @returns {String} The resulting string of Unicode symbols.
  1811. */
  1812. function decode(input) {
  1813. // Don't use UCS-2
  1814. var output = [],
  1815. inputLength = input.length,
  1816. out,
  1817. i = 0,
  1818. n = initialN,
  1819. bias = initialBias,
  1820. basic,
  1821. j,
  1822. index,
  1823. oldi,
  1824. w,
  1825. k,
  1826. digit,
  1827. t,
  1828. /** Cached calculation results */
  1829. baseMinusT;
  1830. // Handle the basic code points: let `basic` be the number of input code
  1831. // points before the last delimiter, or `0` if there is none, then copy
  1832. // the first basic code points to the output.
  1833. basic = input.lastIndexOf(delimiter);
  1834. if (basic < 0) {
  1835. basic = 0;
  1836. }
  1837. for (j = 0; j < basic; ++j) {
  1838. // if it's not a basic code point
  1839. if (input.charCodeAt(j) >= 0x80) {
  1840. error('not-basic');
  1841. }
  1842. output.push(input.charCodeAt(j));
  1843. }
  1844. // Main decoding loop: start just after the last delimiter if any basic code
  1845. // points were copied; start at the beginning otherwise.
  1846. for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) {
  1847. // `index` is the index of the next character to be consumed.
  1848. // Decode a generalized variable-length integer into `delta`,
  1849. // which gets added to `i`. The overflow checking is easier
  1850. // if we increase `i` as we go, then subtract off its starting
  1851. // value at the end to obtain `delta`.
  1852. for (oldi = i, w = 1, k = base; /* no condition */; k += base) {
  1853. if (index >= inputLength) {
  1854. error('invalid-input');
  1855. }
  1856. digit = basicToDigit(input.charCodeAt(index++));
  1857. if (digit >= base || digit > floor((maxInt - i) / w)) {
  1858. error('overflow');
  1859. }
  1860. i += digit * w;
  1861. t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
  1862. if (digit < t) {
  1863. break;
  1864. }
  1865. baseMinusT = base - t;
  1866. if (w > floor(maxInt / baseMinusT)) {
  1867. error('overflow');
  1868. }
  1869. w *= baseMinusT;
  1870. }
  1871. out = output.length + 1;
  1872. bias = adapt(i - oldi, out, oldi == 0);
  1873. // `i` was supposed to wrap around from `out` to `0`,
  1874. // incrementing `n` each time, so we'll fix that now:
  1875. if (floor(i / out) > maxInt - n) {
  1876. error('overflow');
  1877. }
  1878. n += floor(i / out);
  1879. i %= out;
  1880. // Insert `n` at position `i` of the output
  1881. output.splice(i++, 0, n);
  1882. }
  1883. return ucs2encode(output);
  1884. }
  1885. /**
  1886. * Converts a string of Unicode symbols (e.g. a domain name label) to a
  1887. * Punycode string of ASCII-only symbols.
  1888. * @memberOf punycode
  1889. * @param {String} input The string of Unicode symbols.
  1890. * @returns {String} The resulting Punycode string of ASCII-only symbols.
  1891. */
  1892. function encode(input) {
  1893. var n,
  1894. delta,
  1895. handledCPCount,
  1896. basicLength,
  1897. bias,
  1898. j,
  1899. m,
  1900. q,
  1901. k,
  1902. t,
  1903. currentValue,
  1904. output = [],
  1905. /** `inputLength` will hold the number of code points in `input`. */
  1906. inputLength,
  1907. /** Cached calculation results */
  1908. handledCPCountPlusOne,
  1909. baseMinusT,
  1910. qMinusT;
  1911. // Convert the input in UCS-2 to Unicode
  1912. input = ucs2decode(input);
  1913. // Cache the length
  1914. inputLength = input.length;
  1915. // Initialize the state
  1916. n = initialN;
  1917. delta = 0;
  1918. bias = initialBias;
  1919. // Handle the basic code points
  1920. for (j = 0; j < inputLength; ++j) {
  1921. currentValue = input[j];
  1922. if (currentValue < 0x80) {
  1923. output.push(stringFromCharCode(currentValue));
  1924. }
  1925. }
  1926. handledCPCount = basicLength = output.length;
  1927. // `handledCPCount` is the number of code points that have been handled;
  1928. // `basicLength` is the number of basic code points.
  1929. // Finish the basic string - if it is not empty - with a delimiter
  1930. if (basicLength) {
  1931. output.push(delimiter);
  1932. }
  1933. // Main encoding loop:
  1934. while (handledCPCount < inputLength) {
  1935. // All non-basic code points < n have been handled already. Find the next
  1936. // larger one:
  1937. for (m = maxInt, j = 0; j < inputLength; ++j) {
  1938. currentValue = input[j];
  1939. if (currentValue >= n && currentValue < m) {
  1940. m = currentValue;
  1941. }
  1942. }
  1943. // Increase `delta` enough to advance the decoder's <n,i> state to <m,0>,
  1944. // but guard against overflow
  1945. handledCPCountPlusOne = handledCPCount + 1;
  1946. if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) {
  1947. error('overflow');
  1948. }
  1949. delta += (m - n) * handledCPCountPlusOne;
  1950. n = m;
  1951. for (j = 0; j < inputLength; ++j) {
  1952. currentValue = input[j];
  1953. if (currentValue < n && ++delta > maxInt) {
  1954. error('overflow');
  1955. }
  1956. if (currentValue == n) {
  1957. // Represent delta as a generalized variable-length integer
  1958. for (q = delta, k = base; /* no condition */; k += base) {
  1959. t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
  1960. if (q < t) {
  1961. break;
  1962. }
  1963. qMinusT = q - t;
  1964. baseMinusT = base - t;
  1965. output.push(
  1966. stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0))
  1967. );
  1968. q = floor(qMinusT / baseMinusT);
  1969. }
  1970. output.push(stringFromCharCode(digitToBasic(q, 0)));
  1971. bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength);
  1972. delta = 0;
  1973. ++handledCPCount;
  1974. }
  1975. }
  1976. ++delta;
  1977. ++n;
  1978. }
  1979. return output.join('');
  1980. }
  1981. /**
  1982. * Converts a Punycode string representing a domain name or an email address
  1983. * to Unicode. Only the Punycoded parts of the input will be converted, i.e.
  1984. * it doesn't matter if you call it on a string that has already been
  1985. * converted to Unicode.
  1986. * @memberOf punycode
  1987. * @param {String} input The Punycoded domain name or email address to
  1988. * convert to Unicode.
  1989. * @returns {String} The Unicode representation of the given Punycode
  1990. * string.
  1991. */
  1992. function toUnicode(input) {
  1993. return mapDomain(input, function(string) {
  1994. return regexPunycode.test(string)
  1995. ? decode(string.slice(4).toLowerCase())
  1996. : string;
  1997. });
  1998. }
  1999. /**
  2000. * Converts a Unicode string representing a domain name or an email address to
  2001. * Punycode. Only the non-ASCII parts of the domain name will be converted,
  2002. * i.e. it doesn't matter if you call it with a domain that's already in
  2003. * ASCII.
  2004. * @memberOf punycode
  2005. * @param {String} input The domain name or email address to convert, as a
  2006. * Unicode string.
  2007. * @returns {String} The Punycode representation of the given domain name or
  2008. * email address.
  2009. */
  2010. function toASCII(input) {
  2011. return mapDomain(input, function(string) {
  2012. return regexNonASCII.test(string)
  2013. ? 'xn--' + encode(string)
  2014. : string;
  2015. });
  2016. }
  2017. /*--------------------------------------------------------------------------*/
  2018. /** Define the public API */
  2019. punycode = {
  2020. /**
  2021. * A string representing the current Punycode.js version number.
  2022. * @memberOf punycode
  2023. * @type String
  2024. */
  2025. 'version': '1.3.2',
  2026. /**
  2027. * An object of methods to convert from JavaScript's internal character
  2028. * representation (UCS-2) to Unicode code points, and back.
  2029. * @see <https://mathiasbynens.be/notes/javascript-encoding>
  2030. * @memberOf punycode
  2031. * @type Object
  2032. */
  2033. 'ucs2': {
  2034. 'decode': ucs2decode,
  2035. 'encode': ucs2encode
  2036. },
  2037. 'decode': decode,
  2038. 'encode': encode,
  2039. 'toASCII': toASCII,
  2040. 'toUnicode': toUnicode
  2041. };
  2042. /** Expose `punycode` */
  2043. // Some AMD build optimizers, like r.js, check for specific condition patterns
  2044. // like the following:
  2045. if (
  2046. typeof undefined == 'function' &&
  2047. typeof undefined.amd == 'object' &&
  2048. undefined.amd
  2049. ) {
  2050. undefined('punycode', function() {
  2051. return punycode;
  2052. });
  2053. } else if (freeExports && freeModule) {
  2054. if (module.exports == freeExports) { // in Node.js or RingoJS v0.8.0+
  2055. freeModule.exports = punycode;
  2056. } else { // in Narwhal or RingoJS v0.7.0-
  2057. for (key in punycode) {
  2058. punycode.hasOwnProperty(key) && (freeExports[key] = punycode[key]);
  2059. }
  2060. }
  2061. } else { // in Rhino or a web browser
  2062. root.punycode = punycode;
  2063. }
  2064. }(commonjsGlobal));
  2065. });
  2066. 'use strict';
  2067. var util = {
  2068. isString: function(arg) {
  2069. return typeof(arg) === 'string';
  2070. },
  2071. isObject: function(arg) {
  2072. return typeof(arg) === 'object' && arg !== null;
  2073. },
  2074. isNull: function(arg) {
  2075. return arg === null;
  2076. },
  2077. isNullOrUndefined: function(arg) {
  2078. return arg == null;
  2079. }
  2080. };
  2081. var util_1 = util.isString;
  2082. var util_2 = util.isObject;
  2083. var util_3 = util.isNull;
  2084. var util_4 = util.isNullOrUndefined;
  2085. // Copyright Joyent, Inc. and other Node contributors.
  2086. //
  2087. // Permission is hereby granted, free of charge, to any person obtaining a
  2088. // copy of this software and associated documentation files (the
  2089. // "Software"), to deal in the Software without restriction, including
  2090. // without limitation the rights to use, copy, modify, merge, publish,
  2091. // distribute, sublicense, and/or sell copies of the Software, and to permit
  2092. // persons to whom the Software is furnished to do so, subject to the
  2093. // following conditions:
  2094. //
  2095. // The above copyright notice and this permission notice shall be included
  2096. // in all copies or substantial portions of the Software.
  2097. //
  2098. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  2099. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  2100. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  2101. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  2102. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  2103. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  2104. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  2105. 'use strict';
  2106. // If obj.hasOwnProperty has been overridden, then calling
  2107. // obj.hasOwnProperty(prop) will break.
  2108. // See: https://github.com/joyent/node/issues/1707
  2109. function hasOwnProperty$1(obj, prop) {
  2110. return Object.prototype.hasOwnProperty.call(obj, prop);
  2111. }
  2112. var decode = function(qs, sep, eq, options) {
  2113. sep = sep || '&';
  2114. eq = eq || '=';
  2115. var obj = {};
  2116. if (typeof qs !== 'string' || qs.length === 0) {
  2117. return obj;
  2118. }
  2119. var regexp = /\+/g;
  2120. qs = qs.split(sep);
  2121. var maxKeys = 1000;
  2122. if (options && typeof options.maxKeys === 'number') {
  2123. maxKeys = options.maxKeys;
  2124. }
  2125. var len = qs.length;
  2126. // maxKeys <= 0 means that we should not limit keys count
  2127. if (maxKeys > 0 && len > maxKeys) {
  2128. len = maxKeys;
  2129. }
  2130. for (var i = 0; i < len; ++i) {
  2131. var x = qs[i].replace(regexp, '%20'),
  2132. idx = x.indexOf(eq),
  2133. kstr, vstr, k, v;
  2134. if (idx >= 0) {
  2135. kstr = x.substr(0, idx);
  2136. vstr = x.substr(idx + 1);
  2137. } else {
  2138. kstr = x;
  2139. vstr = '';
  2140. }
  2141. k = decodeURIComponent(kstr);
  2142. v = decodeURIComponent(vstr);
  2143. if (!hasOwnProperty$1(obj, k)) {
  2144. obj[k] = v;
  2145. } else if (Array.isArray(obj[k])) {
  2146. obj[k].push(v);
  2147. } else {
  2148. obj[k] = [obj[k], v];
  2149. }
  2150. }
  2151. return obj;
  2152. };
  2153. // Copyright Joyent, Inc. and other Node contributors.
  2154. //
  2155. // Permission is hereby granted, free of charge, to any person obtaining a
  2156. // copy of this software and associated documentation files (the
  2157. // "Software"), to deal in the Software without restriction, including
  2158. // without limitation the rights to use, copy, modify, merge, publish,
  2159. // distribute, sublicense, and/or sell copies of the Software, and to permit
  2160. // persons to whom the Software is furnished to do so, subject to the
  2161. // following conditions:
  2162. //
  2163. // The above copyright notice and this permission notice shall be included
  2164. // in all copies or substantial portions of the Software.
  2165. //
  2166. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  2167. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  2168. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  2169. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  2170. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  2171. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  2172. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  2173. 'use strict';
  2174. var stringifyPrimitive = function(v) {
  2175. switch (typeof v) {
  2176. case 'string':
  2177. return v;
  2178. case 'boolean':
  2179. return v ? 'true' : 'false';
  2180. case 'number':
  2181. return isFinite(v) ? v : '';
  2182. default:
  2183. return '';
  2184. }
  2185. };
  2186. var encode = function(obj, sep, eq, name) {
  2187. sep = sep || '&';
  2188. eq = eq || '=';
  2189. if (obj === null) {
  2190. obj = undefined;
  2191. }
  2192. if (typeof obj === 'object') {
  2193. return Object.keys(obj).map(function(k) {
  2194. var ks = encodeURIComponent(stringifyPrimitive(k)) + eq;
  2195. if (Array.isArray(obj[k])) {
  2196. return obj[k].map(function(v) {
  2197. return ks + encodeURIComponent(stringifyPrimitive(v));
  2198. }).join(sep);
  2199. } else {
  2200. return ks + encodeURIComponent(stringifyPrimitive(obj[k]));
  2201. }
  2202. }).join(sep);
  2203. }
  2204. if (!name) { return ''; }
  2205. return encodeURIComponent(stringifyPrimitive(name)) + eq +
  2206. encodeURIComponent(stringifyPrimitive(obj));
  2207. };
  2208. var querystring = createCommonjsModule(function (module, exports) {
  2209. 'use strict';
  2210. exports.decode = exports.parse = decode;
  2211. exports.encode = exports.stringify = encode;
  2212. });
  2213. var querystring_1 = querystring.decode;
  2214. var querystring_2 = querystring.parse;
  2215. var querystring_3 = querystring.encode;
  2216. var querystring_4 = querystring.stringify;
  2217. // Copyright Joyent, Inc. and other Node contributors.
  2218. //
  2219. // Permission is hereby granted, free of charge, to any person obtaining a
  2220. // copy of this software and associated documentation files (the
  2221. // "Software"), to deal in the Software without restriction, including
  2222. // without limitation the rights to use, copy, modify, merge, publish,
  2223. // distribute, sublicense, and/or sell copies of the Software, and to permit
  2224. // persons to whom the Software is furnished to do so, subject to the
  2225. // following conditions:
  2226. //
  2227. // The above copyright notice and this permission notice shall be included
  2228. // in all copies or substantial portions of the Software.
  2229. //
  2230. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  2231. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  2232. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  2233. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  2234. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  2235. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  2236. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  2237. 'use strict';
  2238. var parse = urlParse;
  2239. var resolve = urlResolve;
  2240. var resolveObject = urlResolveObject;
  2241. var format = urlFormat;
  2242. var Url_1 = Url;
  2243. function Url() {
  2244. this.protocol = null;
  2245. this.slashes = null;
  2246. this.auth = null;
  2247. this.host = null;
  2248. this.port = null;
  2249. this.hostname = null;
  2250. this.hash = null;
  2251. this.search = null;
  2252. this.query = null;
  2253. this.pathname = null;
  2254. this.path = null;
  2255. this.href = null;
  2256. }
  2257. // Reference: RFC 3986, RFC 1808, RFC 2396
  2258. // define these here so at least they only have to be
  2259. // compiled once on the first module load.
  2260. var protocolPattern = /^([a-z0-9.+-]+:)/i,
  2261. portPattern = /:[0-9]*$/,
  2262. // Special case for a simple path URL
  2263. simplePathPattern = /^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/,
  2264. // RFC 2396: characters reserved for delimiting URLs.
  2265. // We actually just auto-escape these.
  2266. delims = ['<', '>', '"', '`', ' ', '\r', '\n', '\t'],
  2267. // RFC 2396: characters not allowed for various reasons.
  2268. unwise = ['{', '}', '|', '\\', '^', '`'].concat(delims),
  2269. // Allowed by RFCs, but cause of XSS attacks. Always escape these.
  2270. autoEscape = ['\''].concat(unwise),
  2271. // Characters that are never ever allowed in a hostname.
  2272. // Note that any invalid chars are also handled, but these
  2273. // are the ones that are *expected* to be seen, so we fast-path
  2274. // them.
  2275. nonHostChars = ['%', '/', '?', ';', '#'].concat(autoEscape),
  2276. hostEndingChars = ['/', '?', '#'],
  2277. hostnameMaxLen = 255,
  2278. hostnamePartPattern = /^[+a-z0-9A-Z_-]{0,63}$/,
  2279. hostnamePartStart = /^([+a-z0-9A-Z_-]{0,63})(.*)$/,
  2280. // protocols that can allow "unsafe" and "unwise" chars.
  2281. unsafeProtocol = {
  2282. 'javascript': true,
  2283. 'javascript:': true
  2284. },
  2285. // protocols that never have a hostname.
  2286. hostlessProtocol = {
  2287. 'javascript': true,
  2288. 'javascript:': true
  2289. },
  2290. // protocols that always contain a // bit.
  2291. slashedProtocol = {
  2292. 'http': true,
  2293. 'https': true,
  2294. 'ftp': true,
  2295. 'gopher': true,
  2296. 'file': true,
  2297. 'http:': true,
  2298. 'https:': true,
  2299. 'ftp:': true,
  2300. 'gopher:': true,
  2301. 'file:': true
  2302. };
  2303. function urlParse(url, parseQueryString, slashesDenoteHost) {
  2304. if (url && util.isObject(url) && url instanceof Url) { return url; }
  2305. var u = new Url;
  2306. u.parse(url, parseQueryString, slashesDenoteHost);
  2307. return u;
  2308. }
  2309. Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) {
  2310. if (!util.isString(url)) {
  2311. throw new TypeError("Parameter 'url' must be a string, not " + typeof url);
  2312. }
  2313. // Copy chrome, IE, opera backslash-handling behavior.
  2314. // Back slashes before the query string get converted to forward slashes
  2315. // See: https://code.google.com/p/chromium/issues/detail?id=25916
  2316. var queryIndex = url.indexOf('?'),
  2317. splitter =
  2318. (queryIndex !== -1 && queryIndex < url.indexOf('#')) ? '?' : '#',
  2319. uSplit = url.split(splitter),
  2320. slashRegex = /\\/g;
  2321. uSplit[0] = uSplit[0].replace(slashRegex, '/');
  2322. url = uSplit.join(splitter);
  2323. var rest = url;
  2324. // trim before proceeding.
  2325. // This is to support parse stuff like " http://foo.com \n"
  2326. rest = rest.trim();
  2327. if (!slashesDenoteHost && url.split('#').length === 1) {
  2328. // Try fast path regexp
  2329. var simplePath = simplePathPattern.exec(rest);
  2330. if (simplePath) {
  2331. this.path = rest;
  2332. this.href = rest;
  2333. this.pathname = simplePath[1];
  2334. if (simplePath[2]) {
  2335. this.search = simplePath[2];
  2336. if (parseQueryString) {
  2337. this.query = querystring.parse(this.search.substr(1));
  2338. } else {
  2339. this.query = this.search.substr(1);
  2340. }
  2341. } else if (parseQueryString) {
  2342. this.search = '';
  2343. this.query = {};
  2344. }
  2345. return this;
  2346. }
  2347. }
  2348. var proto = protocolPattern.exec(rest);
  2349. if (proto) {
  2350. proto = proto[0];
  2351. var lowerProto = proto.toLowerCase();
  2352. this.protocol = lowerProto;
  2353. rest = rest.substr(proto.length);
  2354. }
  2355. // figure out if it's got a host
  2356. // user@server is *always* interpreted as a hostname, and url
  2357. // resolution will treat //foo/bar as host=foo,path=bar because that's
  2358. // how the browser resolves relative URLs.
  2359. if (slashesDenoteHost || proto || rest.match(/^\/\/[^@\/]+@[^@\/]+/)) {
  2360. var slashes = rest.substr(0, 2) === '//';
  2361. if (slashes && !(proto && hostlessProtocol[proto])) {
  2362. rest = rest.substr(2);
  2363. this.slashes = true;
  2364. }
  2365. }
  2366. if (!hostlessProtocol[proto] &&
  2367. (slashes || (proto && !slashedProtocol[proto]))) {
  2368. // there's a hostname.
  2369. // the first instance of /, ?, ;, or # ends the host.
  2370. //
  2371. // If there is an @ in the hostname, then non-host chars *are* allowed
  2372. // to the left of the last @ sign, unless some host-ending character
  2373. // comes *before* the @-sign.
  2374. // URLs are obnoxious.
  2375. //
  2376. // ex:
  2377. // http://a@b@c/ => user:a@b host:c
  2378. // http://a@b?@c => user:a host:c path:/?@c
  2379. // v0.12 TODO(isaacs): This is not quite how Chrome does things.
  2380. // Review our test case against browsers more comprehensively.
  2381. // find the first instance of any hostEndingChars
  2382. var hostEnd = -1;
  2383. for (var i = 0; i < hostEndingChars.length; i++) {
  2384. var hec = rest.indexOf(hostEndingChars[i]);
  2385. if (hec !== -1 && (hostEnd === -1 || hec < hostEnd))
  2386. { hostEnd = hec; }
  2387. }
  2388. // at this point, either we have an explicit point where the
  2389. // auth portion cannot go past, or the last @ char is the decider.
  2390. var auth, atSign;
  2391. if (hostEnd === -1) {
  2392. // atSign can be anywhere.
  2393. atSign = rest.lastIndexOf('@');
  2394. } else {
  2395. // atSign must be in auth portion.
  2396. // http://a@b/c@d => host:b auth:a path:/c@d
  2397. atSign = rest.lastIndexOf('@', hostEnd);
  2398. }
  2399. // Now we have a portion which is definitely the auth.
  2400. // Pull that off.
  2401. if (atSign !== -1) {
  2402. auth = rest.slice(0, atSign);
  2403. rest = rest.slice(atSign + 1);
  2404. this.auth = decodeURIComponent(auth);
  2405. }
  2406. // the host is the remaining to the left of the first non-host char
  2407. hostEnd = -1;
  2408. for (var i = 0; i < nonHostChars.length; i++) {
  2409. var hec = rest.indexOf(nonHostChars[i]);
  2410. if (hec !== -1 && (hostEnd === -1 || hec < hostEnd))
  2411. { hostEnd = hec; }
  2412. }
  2413. // if we still have not hit it, then the entire thing is a host.
  2414. if (hostEnd === -1)
  2415. { hostEnd = rest.length; }
  2416. this.host = rest.slice(0, hostEnd);
  2417. rest = rest.slice(hostEnd);
  2418. // pull out port.
  2419. this.parseHost();
  2420. // we've indicated that there is a hostname,
  2421. // so even if it's empty, it has to be present.
  2422. this.hostname = this.hostname || '';
  2423. // if hostname begins with [ and ends with ]
  2424. // assume that it's an IPv6 address.
  2425. var ipv6Hostname = this.hostname[0] === '[' &&
  2426. this.hostname[this.hostname.length - 1] === ']';
  2427. // validate a little.
  2428. if (!ipv6Hostname) {
  2429. var hostparts = this.hostname.split(/\./);
  2430. for (var i = 0, l = hostparts.length; i < l; i++) {
  2431. var part = hostparts[i];
  2432. if (!part) { continue; }
  2433. if (!part.match(hostnamePartPattern)) {
  2434. var newpart = '';
  2435. for (var j = 0, k = part.length; j < k; j++) {
  2436. if (part.charCodeAt(j) > 127) {
  2437. // we replace non-ASCII char with a temporary placeholder
  2438. // we need this to make sure size of hostname is not
  2439. // broken by replacing non-ASCII by nothing
  2440. newpart += 'x';
  2441. } else {
  2442. newpart += part[j];
  2443. }
  2444. }
  2445. // we test again with ASCII char only
  2446. if (!newpart.match(hostnamePartPattern)) {
  2447. var validParts = hostparts.slice(0, i);
  2448. var notHost = hostparts.slice(i + 1);
  2449. var bit = part.match(hostnamePartStart);
  2450. if (bit) {
  2451. validParts.push(bit[1]);
  2452. notHost.unshift(bit[2]);
  2453. }
  2454. if (notHost.length) {
  2455. rest = '/' + notHost.join('.') + rest;
  2456. }
  2457. this.hostname = validParts.join('.');
  2458. break;
  2459. }
  2460. }
  2461. }
  2462. }
  2463. if (this.hostname.length > hostnameMaxLen) {
  2464. this.hostname = '';
  2465. } else {
  2466. // hostnames are always lower case.
  2467. this.hostname = this.hostname.toLowerCase();
  2468. }
  2469. if (!ipv6Hostname) {
  2470. // IDNA Support: Returns a punycoded representation of "domain".
  2471. // It only converts parts of the domain name that
  2472. // have non-ASCII characters, i.e. it doesn't matter if
  2473. // you call it with a domain that already is ASCII-only.
  2474. this.hostname = punycode.toASCII(this.hostname);
  2475. }
  2476. var p = this.port ? ':' + this.port : '';
  2477. var h = this.hostname || '';
  2478. this.host = h + p;
  2479. this.href += this.host;
  2480. // strip [ and ] from the hostname
  2481. // the host field still retains them, though
  2482. if (ipv6Hostname) {
  2483. this.hostname = this.hostname.substr(1, this.hostname.length - 2);
  2484. if (rest[0] !== '/') {
  2485. rest = '/' + rest;
  2486. }
  2487. }
  2488. }
  2489. // now rest is set to the post-host stuff.
  2490. // chop off any delim chars.
  2491. if (!unsafeProtocol[lowerProto]) {
  2492. // First, make 100% sure that any "autoEscape" chars get
  2493. // escaped, even if encodeURIComponent doesn't think they
  2494. // need to be.
  2495. for (var i = 0, l = autoEscape.length; i < l; i++) {
  2496. var ae = autoEscape[i];
  2497. if (rest.indexOf(ae) === -1)
  2498. { continue; }
  2499. var esc = encodeURIComponent(ae);
  2500. if (esc === ae) {
  2501. esc = escape(ae);
  2502. }
  2503. rest = rest.split(ae).join(esc);
  2504. }
  2505. }
  2506. // chop off from the tail first.
  2507. var hash = rest.indexOf('#');
  2508. if (hash !== -1) {
  2509. // got a fragment string.
  2510. this.hash = rest.substr(hash);
  2511. rest = rest.slice(0, hash);
  2512. }
  2513. var qm = rest.indexOf('?');
  2514. if (qm !== -1) {
  2515. this.search = rest.substr(qm);
  2516. this.query = rest.substr(qm + 1);
  2517. if (parseQueryString) {
  2518. this.query = querystring.parse(this.query);
  2519. }
  2520. rest = rest.slice(0, qm);
  2521. } else if (parseQueryString) {
  2522. // no query string, but parseQueryString still requested
  2523. this.search = '';
  2524. this.query = {};
  2525. }
  2526. if (rest) { this.pathname = rest; }
  2527. if (slashedProtocol[lowerProto] &&
  2528. this.hostname && !this.pathname) {
  2529. this.pathname = '/';
  2530. }
  2531. //to support http.request
  2532. if (this.pathname || this.search) {
  2533. var p = this.pathname || '';
  2534. var s = this.search || '';
  2535. this.path = p + s;
  2536. }
  2537. // finally, reconstruct the href based on what has been validated.
  2538. this.href = this.format();
  2539. return this;
  2540. };
  2541. // format a parsed object into a url string
  2542. function urlFormat(obj) {
  2543. // ensure it's an object, and not a string url.
  2544. // If it's an obj, this is a no-op.
  2545. // this way, you can call url_format() on strings
  2546. // to clean up potentially wonky urls.
  2547. if (util.isString(obj)) { obj = urlParse(obj); }
  2548. if (!(obj instanceof Url)) { return Url.prototype.format.call(obj); }
  2549. return obj.format();
  2550. }
  2551. Url.prototype.format = function() {
  2552. var auth = this.auth || '';
  2553. if (auth) {
  2554. auth = encodeURIComponent(auth);
  2555. auth = auth.replace(/%3A/i, ':');
  2556. auth += '@';
  2557. }
  2558. var protocol = this.protocol || '',
  2559. pathname = this.pathname || '',
  2560. hash = this.hash || '',
  2561. host = false,
  2562. query = '';
  2563. if (this.host) {
  2564. host = auth + this.host;
  2565. } else if (this.hostname) {
  2566. host = auth + (this.hostname.indexOf(':') === -1 ?
  2567. this.hostname :
  2568. '[' + this.hostname + ']');
  2569. if (this.port) {
  2570. host += ':' + this.port;
  2571. }
  2572. }
  2573. if (this.query &&
  2574. util.isObject(this.query) &&
  2575. Object.keys(this.query).length) {
  2576. query = querystring.stringify(this.query);
  2577. }
  2578. var search = this.search || (query && ('?' + query)) || '';
  2579. if (protocol && protocol.substr(-1) !== ':') { protocol += ':'; }
  2580. // only the slashedProtocols get the //. Not mailto:, xmpp:, etc.
  2581. // unless they had them to begin with.
  2582. if (this.slashes ||
  2583. (!protocol || slashedProtocol[protocol]) && host !== false) {
  2584. host = '//' + (host || '');
  2585. if (pathname && pathname.charAt(0) !== '/') { pathname = '/' + pathname; }
  2586. } else if (!host) {
  2587. host = '';
  2588. }
  2589. if (hash && hash.charAt(0) !== '#') { hash = '#' + hash; }
  2590. if (search && search.charAt(0) !== '?') { search = '?' + search; }
  2591. pathname = pathname.replace(/[?#]/g, function(match) {
  2592. return encodeURIComponent(match);
  2593. });
  2594. search = search.replace('#', '%23');
  2595. return protocol + host + pathname + search + hash;
  2596. };
  2597. function urlResolve(source, relative) {
  2598. return urlParse(source, false, true).resolve(relative);
  2599. }
  2600. Url.prototype.resolve = function(relative) {
  2601. return this.resolveObject(urlParse(relative, false, true)).format();
  2602. };
  2603. function urlResolveObject(source, relative) {
  2604. if (!source) { return relative; }
  2605. return urlParse(source, false, true).resolveObject(relative);
  2606. }
  2607. Url.prototype.resolveObject = function(relative) {
  2608. if (util.isString(relative)) {
  2609. var rel = new Url();
  2610. rel.parse(relative, false, true);
  2611. relative = rel;
  2612. }
  2613. var result = new Url();
  2614. var tkeys = Object.keys(this);
  2615. for (var tk = 0; tk < tkeys.length; tk++) {
  2616. var tkey = tkeys[tk];
  2617. result[tkey] = this[tkey];
  2618. }
  2619. // hash is always overridden, no matter what.
  2620. // even href="" will remove it.
  2621. result.hash = relative.hash;
  2622. // if the relative url is empty, then there's nothing left to do here.
  2623. if (relative.href === '') {
  2624. result.href = result.format();
  2625. return result;
  2626. }
  2627. // hrefs like //foo/bar always cut to the protocol.
  2628. if (relative.slashes && !relative.protocol) {
  2629. // take everything except the protocol from relative
  2630. var rkeys = Object.keys(relative);
  2631. for (var rk = 0; rk < rkeys.length; rk++) {
  2632. var rkey = rkeys[rk];
  2633. if (rkey !== 'protocol')
  2634. { result[rkey] = relative[rkey]; }
  2635. }
  2636. //urlParse appends trailing / to urls like http://www.example.com
  2637. if (slashedProtocol[result.protocol] &&
  2638. result.hostname && !result.pathname) {
  2639. result.path = result.pathname = '/';
  2640. }
  2641. result.href = result.format();
  2642. return result;
  2643. }
  2644. if (relative.protocol && relative.protocol !== result.protocol) {
  2645. // if it's a known url protocol, then changing
  2646. // the protocol does weird things
  2647. // first, if it's not file:, then we MUST have a host,
  2648. // and if there was a path
  2649. // to begin with, then we MUST have a path.
  2650. // if it is file:, then the host is dropped,
  2651. // because that's known to be hostless.
  2652. // anything else is assumed to be absolute.
  2653. if (!slashedProtocol[relative.protocol]) {
  2654. var keys = Object.keys(relative);
  2655. for (var v = 0; v < keys.length; v++) {
  2656. var k = keys[v];
  2657. result[k] = relative[k];
  2658. }
  2659. result.href = result.format();
  2660. return result;
  2661. }
  2662. result.protocol = relative.protocol;
  2663. if (!relative.host && !hostlessProtocol[relative.protocol]) {
  2664. var relPath = (relative.pathname || '').split('/');
  2665. while (relPath.length && !(relative.host = relPath.shift())){ ; }
  2666. if (!relative.host) { relative.host = ''; }
  2667. if (!relative.hostname) { relative.hostname = ''; }
  2668. if (relPath[0] !== '') { relPath.unshift(''); }
  2669. if (relPath.length < 2) { relPath.unshift(''); }
  2670. result.pathname = relPath.join('/');
  2671. } else {
  2672. result.pathname = relative.pathname;
  2673. }
  2674. result.search = relative.search;
  2675. result.query = relative.query;
  2676. result.host = relative.host || '';
  2677. result.auth = relative.auth;
  2678. result.hostname = relative.hostname || relative.host;
  2679. result.port = relative.port;
  2680. // to support http.request
  2681. if (result.pathname || result.search) {
  2682. var p = result.pathname || '';
  2683. var s = result.search || '';
  2684. result.path = p + s;
  2685. }
  2686. result.slashes = result.slashes || relative.slashes;
  2687. result.href = result.format();
  2688. return result;
  2689. }
  2690. var isSourceAbs = (result.pathname && result.pathname.charAt(0) === '/'),
  2691. isRelAbs = (
  2692. relative.host ||
  2693. relative.pathname && relative.pathname.charAt(0) === '/'
  2694. ),
  2695. mustEndAbs = (isRelAbs || isSourceAbs ||
  2696. (result.host && relative.pathname)),
  2697. removeAllDots = mustEndAbs,
  2698. srcPath = result.pathname && result.pathname.split('/') || [],
  2699. relPath = relative.pathname && relative.pathname.split('/') || [],
  2700. psychotic = result.protocol && !slashedProtocol[result.protocol];
  2701. // if the url is a non-slashed url, then relative
  2702. // links like ../.. should be able
  2703. // to crawl up to the hostname, as well. This is strange.
  2704. // result.protocol has already been set by now.
  2705. // Later on, put the first path part into the host field.
  2706. if (psychotic) {
  2707. result.hostname = '';
  2708. result.port = null;
  2709. if (result.host) {
  2710. if (srcPath[0] === '') { srcPath[0] = result.host; }
  2711. else { srcPath.unshift(result.host); }
  2712. }
  2713. result.host = '';
  2714. if (relative.protocol) {
  2715. relative.hostname = null;
  2716. relative.port = null;
  2717. if (relative.host) {
  2718. if (relPath[0] === '') { relPath[0] = relative.host; }
  2719. else { relPath.unshift(relative.host); }
  2720. }
  2721. relative.host = null;
  2722. }
  2723. mustEndAbs = mustEndAbs && (relPath[0] === '' || srcPath[0] === '');
  2724. }
  2725. if (isRelAbs) {
  2726. // it's absolute.
  2727. result.host = (relative.host || relative.host === '') ?
  2728. relative.host : result.host;
  2729. result.hostname = (relative.hostname || relative.hostname === '') ?
  2730. relative.hostname : result.hostname;
  2731. result.search = relative.search;
  2732. result.query = relative.query;
  2733. srcPath = relPath;
  2734. // fall through to the dot-handling below.
  2735. } else if (relPath.length) {
  2736. // it's relative
  2737. // throw away the existing file, and take the new path instead.
  2738. if (!srcPath) { srcPath = []; }
  2739. srcPath.pop();
  2740. srcPath = srcPath.concat(relPath);
  2741. result.search = relative.search;
  2742. result.query = relative.query;
  2743. } else if (!util.isNullOrUndefined(relative.search)) {
  2744. // just pull out the search.
  2745. // like href='?foo'.
  2746. // Put this after the other two cases because it simplifies the booleans
  2747. if (psychotic) {
  2748. result.hostname = result.host = srcPath.shift();
  2749. //occationaly the auth can get stuck only in host
  2750. //this especially happens in cases like
  2751. //url.resolveObject('mailto:local1@domain1', 'local2@domain2')
  2752. var authInHost = result.host && result.host.indexOf('@') > 0 ?
  2753. result.host.split('@') : false;
  2754. if (authInHost) {
  2755. result.auth = authInHost.shift();
  2756. result.host = result.hostname = authInHost.shift();
  2757. }
  2758. }
  2759. result.search = relative.search;
  2760. result.query = relative.query;
  2761. //to support http.request
  2762. if (!util.isNull(result.pathname) || !util.isNull(result.search)) {
  2763. result.path = (result.pathname ? result.pathname : '') +
  2764. (result.search ? result.search : '');
  2765. }
  2766. result.href = result.format();
  2767. return result;
  2768. }
  2769. if (!srcPath.length) {
  2770. // no path at all. easy.
  2771. // we've already handled the other stuff above.
  2772. result.pathname = null;
  2773. //to support http.request
  2774. if (result.search) {
  2775. result.path = '/' + result.search;
  2776. } else {
  2777. result.path = null;
  2778. }
  2779. result.href = result.format();
  2780. return result;
  2781. }
  2782. // if a url ENDs in . or .., then it must get a trailing slash.
  2783. // however, if it ends in anything else non-slashy,
  2784. // then it must NOT get a trailing slash.
  2785. var last = srcPath.slice(-1)[0];
  2786. var hasTrailingSlash = (
  2787. (result.host || relative.host || srcPath.length > 1) &&
  2788. (last === '.' || last === '..') || last === '');
  2789. // strip single dots, resolve double dots to parent dir
  2790. // if the path tries to go above the root, `up` ends up > 0
  2791. var up = 0;
  2792. for (var i = srcPath.length; i >= 0; i--) {
  2793. last = srcPath[i];
  2794. if (last === '.') {
  2795. srcPath.splice(i, 1);
  2796. } else if (last === '..') {
  2797. srcPath.splice(i, 1);
  2798. up++;
  2799. } else if (up) {
  2800. srcPath.splice(i, 1);
  2801. up--;
  2802. }
  2803. }
  2804. // if the path is allowed to go above the root, restore leading ..s
  2805. if (!mustEndAbs && !removeAllDots) {
  2806. for (; up--; up) {
  2807. srcPath.unshift('..');
  2808. }
  2809. }
  2810. if (mustEndAbs && srcPath[0] !== '' &&
  2811. (!srcPath[0] || srcPath[0].charAt(0) !== '/')) {
  2812. srcPath.unshift('');
  2813. }
  2814. if (hasTrailingSlash && (srcPath.join('/').substr(-1) !== '/')) {
  2815. srcPath.push('');
  2816. }
  2817. var isAbsolute = srcPath[0] === '' ||
  2818. (srcPath[0] && srcPath[0].charAt(0) === '/');
  2819. // put the host back
  2820. if (psychotic) {
  2821. result.hostname = result.host = isAbsolute ? '' :
  2822. srcPath.length ? srcPath.shift() : '';
  2823. //occationaly the auth can get stuck only in host
  2824. //this especially happens in cases like
  2825. //url.resolveObject('mailto:local1@domain1', 'local2@domain2')
  2826. var authInHost = result.host && result.host.indexOf('@') > 0 ?
  2827. result.host.split('@') : false;
  2828. if (authInHost) {
  2829. result.auth = authInHost.shift();
  2830. result.host = result.hostname = authInHost.shift();
  2831. }
  2832. }
  2833. mustEndAbs = mustEndAbs || (result.host && srcPath.length);
  2834. if (mustEndAbs && !isAbsolute) {
  2835. srcPath.unshift('');
  2836. }
  2837. if (!srcPath.length) {
  2838. result.pathname = null;
  2839. result.path = null;
  2840. } else {
  2841. result.pathname = srcPath.join('/');
  2842. }
  2843. //to support request.http
  2844. if (!util.isNull(result.pathname) || !util.isNull(result.search)) {
  2845. result.path = (result.pathname ? result.pathname : '') +
  2846. (result.search ? result.search : '');
  2847. }
  2848. result.auth = relative.auth || result.auth;
  2849. result.slashes = result.slashes || relative.slashes;
  2850. result.href = result.format();
  2851. return result;
  2852. };
  2853. Url.prototype.parseHost = function() {
  2854. var host = this.host;
  2855. var port = portPattern.exec(host);
  2856. if (port) {
  2857. port = port[0];
  2858. if (port !== ':') {
  2859. this.port = port.substr(1);
  2860. }
  2861. host = host.substr(0, host.length - port.length);
  2862. }
  2863. if (host) { this.hostname = host; }
  2864. };
  2865. var url = {
  2866. parse: parse,
  2867. resolve: resolve,
  2868. resolveObject: resolveObject,
  2869. format: format,
  2870. Url: Url_1
  2871. };
  2872. /*!
  2873. * @pixi/constants - v5.0.4
  2874. * Compiled Fri, 07 Jun 2019 17:17:49 UTC
  2875. *
  2876. * @pixi/constants is licensed under the MIT License.
  2877. * http://www.opensource.org/licenses/mit-license
  2878. */
  2879. /**
  2880. * Different types of environments for WebGL.
  2881. *
  2882. * @static
  2883. * @memberof PIXI
  2884. * @name ENV
  2885. * @enum {number}
  2886. * @property {number} WEBGL_LEGACY - Used for older v1 WebGL devices. PixiJS will aim to ensure compatibility
  2887. * with older / less advanced devices. If you experience unexplained flickering prefer this environment.
  2888. * @property {number} WEBGL - Version 1 of WebGL
  2889. * @property {number} WEBGL2 - Version 2 of WebGL
  2890. */
  2891. var ENV = {
  2892. WEBGL_LEGACY: 0,
  2893. WEBGL: 1,
  2894. WEBGL2: 2,
  2895. };
  2896. /**
  2897. * Constant to identify the Renderer Type.
  2898. *
  2899. * @static
  2900. * @memberof PIXI
  2901. * @name RENDERER_TYPE
  2902. * @enum {number}
  2903. * @property {number} UNKNOWN - Unknown render type.
  2904. * @property {number} WEBGL - WebGL render type.
  2905. * @property {number} CANVAS - Canvas render type.
  2906. */
  2907. var RENDERER_TYPE = {
  2908. UNKNOWN: 0,
  2909. WEBGL: 1,
  2910. CANVAS: 2,
  2911. };
  2912. /**
  2913. * Various blend modes supported by PIXI.
  2914. *
  2915. * IMPORTANT - The WebGL renderer only supports the NORMAL, ADD, MULTIPLY and SCREEN blend modes.
  2916. * Anything else will silently act like NORMAL.
  2917. *
  2918. * @memberof PIXI
  2919. * @name BLEND_MODES
  2920. * @enum {number}
  2921. * @property {number} NORMAL
  2922. * @property {number} ADD
  2923. * @property {number} MULTIPLY
  2924. * @property {number} SCREEN
  2925. * @property {number} OVERLAY
  2926. * @property {number} DARKEN
  2927. * @property {number} LIGHTEN
  2928. * @property {number} COLOR_DODGE
  2929. * @property {number} COLOR_BURN
  2930. * @property {number} HARD_LIGHT
  2931. * @property {number} SOFT_LIGHT
  2932. * @property {number} DIFFERENCE
  2933. * @property {number} EXCLUSION
  2934. * @property {number} HUE
  2935. * @property {number} SATURATION
  2936. * @property {number} COLOR
  2937. * @property {number} LUMINOSITY
  2938. * @property {number} NORMAL_NPM
  2939. * @property {number} ADD_NPM
  2940. * @property {number} SCREEN_NPM
  2941. * @property {number} NONE
  2942. * @property {number} SRC_IN
  2943. * @property {number} SRC_OUT
  2944. * @property {number} SRC_ATOP
  2945. * @property {number} DST_OVER
  2946. * @property {number} DST_IN
  2947. * @property {number} DST_OUT
  2948. * @property {number} DST_ATOP
  2949. * @property {number} SUBTRACT
  2950. * @property {number} SRC_OVER
  2951. * @property {number} ERASE
  2952. */
  2953. var BLEND_MODES = {
  2954. NORMAL: 0,
  2955. ADD: 1,
  2956. MULTIPLY: 2,
  2957. SCREEN: 3,
  2958. OVERLAY: 4,
  2959. DARKEN: 5,
  2960. LIGHTEN: 6,
  2961. COLOR_DODGE: 7,
  2962. COLOR_BURN: 8,
  2963. HARD_LIGHT: 9,
  2964. SOFT_LIGHT: 10,
  2965. DIFFERENCE: 11,
  2966. EXCLUSION: 12,
  2967. HUE: 13,
  2968. SATURATION: 14,
  2969. COLOR: 15,
  2970. LUMINOSITY: 16,
  2971. NORMAL_NPM: 17,
  2972. ADD_NPM: 18,
  2973. SCREEN_NPM: 19,
  2974. NONE: 20,
  2975. SRC_OVER: 0,
  2976. SRC_IN: 21,
  2977. SRC_OUT: 22,
  2978. SRC_ATOP: 23,
  2979. DST_OVER: 24,
  2980. DST_IN: 25,
  2981. DST_OUT: 26,
  2982. DST_ATOP: 27,
  2983. ERASE: 26,
  2984. SUBTRACT: 28,
  2985. };
  2986. /**
  2987. * Various webgl draw modes. These can be used to specify which GL drawMode to use
  2988. * under certain situations and renderers.
  2989. *
  2990. * @memberof PIXI
  2991. * @static
  2992. * @name DRAW_MODES
  2993. * @enum {number}
  2994. * @property {number} POINTS
  2995. * @property {number} LINES
  2996. * @property {number} LINE_LOOP
  2997. * @property {number} LINE_STRIP
  2998. * @property {number} TRIANGLES
  2999. * @property {number} TRIANGLE_STRIP
  3000. * @property {number} TRIANGLE_FAN
  3001. */
  3002. var DRAW_MODES = {
  3003. POINTS: 0,
  3004. LINES: 1,
  3005. LINE_LOOP: 2,
  3006. LINE_STRIP: 3,
  3007. TRIANGLES: 4,
  3008. TRIANGLE_STRIP: 5,
  3009. TRIANGLE_FAN: 6,
  3010. };
  3011. /**
  3012. * Various GL texture/resources formats.
  3013. *
  3014. * @memberof PIXI
  3015. * @static
  3016. * @name FORMATS
  3017. * @enum {number}
  3018. * @property {number} RGBA=6408
  3019. * @property {number} RGB=6407
  3020. * @property {number} ALPHA=6406
  3021. * @property {number} LUMINANCE=6409
  3022. * @property {number} LUMINANCE_ALPHA=6410
  3023. * @property {number} DEPTH_COMPONENT=6402
  3024. * @property {number} DEPTH_STENCIL=34041
  3025. */
  3026. var FORMATS = {
  3027. RGBA: 6408,
  3028. RGB: 6407,
  3029. ALPHA: 6406,
  3030. LUMINANCE: 6409,
  3031. LUMINANCE_ALPHA: 6410,
  3032. DEPTH_COMPONENT: 6402,
  3033. DEPTH_STENCIL: 34041,
  3034. };
  3035. /**
  3036. * Various GL target types.
  3037. *
  3038. * @memberof PIXI
  3039. * @static
  3040. * @name TARGETS
  3041. * @enum {number}
  3042. * @property {number} TEXTURE_2D=3553
  3043. * @property {number} TEXTURE_CUBE_MAP=34067
  3044. * @property {number} TEXTURE_2D_ARRAY=35866
  3045. * @property {number} TEXTURE_CUBE_MAP_POSITIVE_X=34069
  3046. * @property {number} TEXTURE_CUBE_MAP_NEGATIVE_X=34070
  3047. * @property {number} TEXTURE_CUBE_MAP_POSITIVE_Y=34071
  3048. * @property {number} TEXTURE_CUBE_MAP_NEGATIVE_Y=34072
  3049. * @property {number} TEXTURE_CUBE_MAP_POSITIVE_Z=34073
  3050. * @property {number} TEXTURE_CUBE_MAP_NEGATIVE_Z=34074
  3051. */
  3052. var TARGETS = {
  3053. TEXTURE_2D: 3553,
  3054. TEXTURE_CUBE_MAP: 34067,
  3055. TEXTURE_2D_ARRAY: 35866,
  3056. TEXTURE_CUBE_MAP_POSITIVE_X: 34069,
  3057. TEXTURE_CUBE_MAP_NEGATIVE_X: 34070,
  3058. TEXTURE_CUBE_MAP_POSITIVE_Y: 34071,
  3059. TEXTURE_CUBE_MAP_NEGATIVE_Y: 34072,
  3060. TEXTURE_CUBE_MAP_POSITIVE_Z: 34073,
  3061. TEXTURE_CUBE_MAP_NEGATIVE_Z: 34074,
  3062. };
  3063. /**
  3064. * Various GL data format types.
  3065. *
  3066. * @memberof PIXI
  3067. * @static
  3068. * @name TYPES
  3069. * @enum {number}
  3070. * @property {number} UNSIGNED_BYTE=5121
  3071. * @property {number} UNSIGNED_SHORT=5123
  3072. * @property {number} UNSIGNED_SHORT_5_6_5=33635
  3073. * @property {number} UNSIGNED_SHORT_4_4_4_4=32819
  3074. * @property {number} UNSIGNED_SHORT_5_5_5_1=32820
  3075. * @property {number} FLOAT=5126
  3076. * @property {number} HALF_FLOAT=36193
  3077. */
  3078. var TYPES = {
  3079. UNSIGNED_BYTE: 5121,
  3080. UNSIGNED_SHORT: 5123,
  3081. UNSIGNED_SHORT_5_6_5: 33635,
  3082. UNSIGNED_SHORT_4_4_4_4: 32819,
  3083. UNSIGNED_SHORT_5_5_5_1: 32820,
  3084. FLOAT: 5126,
  3085. HALF_FLOAT: 36193,
  3086. };
  3087. /**
  3088. * The scale modes that are supported by pixi.
  3089. *
  3090. * The {@link PIXI.settings.SCALE_MODE} scale mode affects the default scaling mode of future operations.
  3091. * It can be re-assigned to either LINEAR or NEAREST, depending upon suitability.
  3092. *
  3093. * @memberof PIXI
  3094. * @static
  3095. * @name SCALE_MODES
  3096. * @enum {number}
  3097. * @property {number} LINEAR Smooth scaling
  3098. * @property {number} NEAREST Pixelating scaling
  3099. */
  3100. var SCALE_MODES = {
  3101. LINEAR: 1,
  3102. NEAREST: 0,
  3103. };
  3104. /**
  3105. * The wrap modes that are supported by pixi.
  3106. *
  3107. * The {@link PIXI.settings.WRAP_MODE} wrap mode affects the default wrapping mode of future operations.
  3108. * It can be re-assigned to either CLAMP or REPEAT, depending upon suitability.
  3109. * If the texture is non power of two then clamp will be used regardless as WebGL can
  3110. * only use REPEAT if the texture is po2.
  3111. *
  3112. * This property only affects WebGL.
  3113. *
  3114. * @name WRAP_MODES
  3115. * @memberof PIXI
  3116. * @static
  3117. * @enum {number}
  3118. * @property {number} CLAMP - The textures uvs are clamped
  3119. * @property {number} REPEAT - The texture uvs tile and repeat
  3120. * @property {number} MIRRORED_REPEAT - The texture uvs tile and repeat with mirroring
  3121. */
  3122. var WRAP_MODES = {
  3123. CLAMP: 33071,
  3124. REPEAT: 10497,
  3125. MIRRORED_REPEAT: 33648,
  3126. };
  3127. /**
  3128. * Mipmap filtering modes that are supported by pixi.
  3129. *
  3130. * The {@link PIXI.settings.MIPMAP_TEXTURES} affects default texture filtering.
  3131. * Mipmaps are generated for a baseTexture if its `mipmap` field is `ON`,
  3132. * or its `POW2` and texture dimensions are powers of 2.
  3133. * Due to platform restriction, `ON` option will work like `POW2` for webgl-1.
  3134. *
  3135. * This property only affects WebGL.
  3136. *
  3137. * @name MIPMAP_MODES
  3138. * @memberof PIXI
  3139. * @static
  3140. * @enum {number}
  3141. * @property {number} OFF - No mipmaps
  3142. * @property {number} POW2 - Generate mipmaps if texture dimensions are pow2
  3143. * @property {number} ON - Always generate mipmaps
  3144. */
  3145. var MIPMAP_MODES = {
  3146. OFF: 0,
  3147. POW2: 1,
  3148. ON: 2,
  3149. };
  3150. /**
  3151. * The gc modes that are supported by pixi.
  3152. *
  3153. * The {@link PIXI.settings.GC_MODE} Garbage Collection mode for PixiJS textures is AUTO
  3154. * If set to GC_MODE, the renderer will occasionally check textures usage. If they are not
  3155. * used for a specified period of time they will be removed from the GPU. They will of course
  3156. * be uploaded again when they are required. This is a silent behind the scenes process that
  3157. * should ensure that the GPU does not get filled up.
  3158. *
  3159. * Handy for mobile devices!
  3160. * This property only affects WebGL.
  3161. *
  3162. * @name GC_MODES
  3163. * @enum {number}
  3164. * @static
  3165. * @memberof PIXI
  3166. * @property {number} AUTO - Garbage collection will happen periodically automatically
  3167. * @property {number} MANUAL - Garbage collection will need to be called manually
  3168. */
  3169. var GC_MODES = {
  3170. AUTO: 0,
  3171. MANUAL: 1,
  3172. };
  3173. /**
  3174. * Constants that specify float precision in shaders.
  3175. *
  3176. * @name PRECISION
  3177. * @memberof PIXI
  3178. * @static
  3179. * @enum {string}
  3180. * @constant
  3181. * @property {string} LOW='lowp'
  3182. * @property {string} MEDIUM='mediump'
  3183. * @property {string} HIGH='highp'
  3184. */
  3185. var PRECISION = {
  3186. LOW: 'lowp',
  3187. MEDIUM: 'mediump',
  3188. HIGH: 'highp',
  3189. };
  3190. /*!
  3191. * @pixi/utils - v5.0.4
  3192. * Compiled Fri, 07 Jun 2019 17:17:49 UTC
  3193. *
  3194. * @pixi/utils is licensed under the MIT License.
  3195. * http://www.opensource.org/licenses/mit-license
  3196. */
  3197. /**
  3198. * The prefix that denotes a URL is for a retina asset.
  3199. *
  3200. * @static
  3201. * @name RETINA_PREFIX
  3202. * @memberof PIXI.settings
  3203. * @type {RegExp}
  3204. * @default /@([0-9\.]+)x/
  3205. * @example `@2x`
  3206. */
  3207. settings.RETINA_PREFIX = /@([0-9\.]+)x/;
  3208. var saidHello = false;
  3209. var VERSION = '5.0.4';
  3210. /**
  3211. * Skips the hello message of renderers that are created after this is run.
  3212. *
  3213. * @function skipHello
  3214. * @memberof PIXI.utils
  3215. */
  3216. function skipHello()
  3217. {
  3218. saidHello = true;
  3219. }
  3220. /**
  3221. * Logs out the version and renderer information for this running instance of PIXI.
  3222. * If you don't want to see this message you can run `PIXI.utils.skipHello()` before
  3223. * creating your renderer. Keep in mind that doing that will forever makes you a jerk face.
  3224. *
  3225. * @static
  3226. * @function sayHello
  3227. * @memberof PIXI.utils
  3228. * @param {string} type - The string renderer type to log.
  3229. */
  3230. function sayHello(type)
  3231. {
  3232. if (saidHello)
  3233. {
  3234. return;
  3235. }
  3236. if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1)
  3237. {
  3238. var args = [
  3239. ("\n %c %c %c PixiJS " + VERSION + " - ✰ " + type + " ✰ %c %c http://www.pixijs.com/ %c %c ♥%c♥%c♥ \n\n"),
  3240. 'background: #ff66a5; padding:5px 0;',
  3241. 'background: #ff66a5; padding:5px 0;',
  3242. 'color: #ff66a5; background: #030307; padding:5px 0;',
  3243. 'background: #ff66a5; padding:5px 0;',
  3244. 'background: #ffc3dc; padding:5px 0;',
  3245. 'background: #ff66a5; padding:5px 0;',
  3246. 'color: #ff2424; background: #fff; padding:5px 0;',
  3247. 'color: #ff2424; background: #fff; padding:5px 0;',
  3248. 'color: #ff2424; background: #fff; padding:5px 0;' ];
  3249. window.console.log.apply(console, args);
  3250. }
  3251. else if (window.console)
  3252. {
  3253. window.console.log(("PixiJS " + VERSION + " - " + type + " - http://www.pixijs.com/"));
  3254. }
  3255. saidHello = true;
  3256. }
  3257. var supported;
  3258. /**
  3259. * Helper for checking for WebGL support.
  3260. *
  3261. * @memberof PIXI.utils
  3262. * @function isWebGLSupported
  3263. * @return {boolean} Is WebGL supported.
  3264. */
  3265. function isWebGLSupported()
  3266. {
  3267. if (typeof supported === 'undefined')
  3268. {
  3269. supported = (function supported()
  3270. {
  3271. var contextOptions = { stencil: true, failIfMajorPerformanceCaveat: true };
  3272. try
  3273. {
  3274. if (!window.WebGLRenderingContext)
  3275. {
  3276. return false;
  3277. }
  3278. var canvas = document.createElement('canvas');
  3279. var gl = canvas.getContext('webgl', contextOptions)
  3280. || canvas.getContext('experimental-webgl', contextOptions);
  3281. var success = !!(gl && gl.getContextAttributes().stencil);
  3282. if (gl)
  3283. {
  3284. var loseContext = gl.getExtension('WEBGL_lose_context');
  3285. if (loseContext)
  3286. {
  3287. loseContext.loseContext();
  3288. }
  3289. }
  3290. gl = null;
  3291. return success;
  3292. }
  3293. catch (e)
  3294. {
  3295. return false;
  3296. }
  3297. })();
  3298. }
  3299. return supported;
  3300. }
  3301. /**
  3302. * Converts a hexadecimal color number to an [R, G, B] array of normalized floats (numbers from 0.0 to 1.0).
  3303. *
  3304. * @example
  3305. * PIXI.utils.hex2rgb(0xffffff); // returns [1, 1, 1]
  3306. * @memberof PIXI.utils
  3307. * @function hex2rgb
  3308. * @param {number} hex - The hexadecimal number to convert
  3309. * @param {number[]} [out=[]] If supplied, this array will be used rather than returning a new one
  3310. * @return {number[]} An array representing the [R, G, B] of the color where all values are floats.
  3311. */
  3312. function hex2rgb(hex, out)
  3313. {
  3314. out = out || [];
  3315. out[0] = ((hex >> 16) & 0xFF) / 255;
  3316. out[1] = ((hex >> 8) & 0xFF) / 255;
  3317. out[2] = (hex & 0xFF) / 255;
  3318. return out;
  3319. }
  3320. /**
  3321. * Converts a hexadecimal color number to a string.
  3322. *
  3323. * @example
  3324. * PIXI.utils.hex2string(0xffffff); // returns "#ffffff"
  3325. * @memberof PIXI.utils
  3326. * @function hex2string
  3327. * @param {number} hex - Number in hex (e.g., `0xffffff`)
  3328. * @return {string} The string color (e.g., `"#ffffff"`).
  3329. */
  3330. function hex2string(hex)
  3331. {
  3332. hex = hex.toString(16);
  3333. hex = '000000'.substr(0, 6 - hex.length) + hex;
  3334. return ("#" + hex);
  3335. }
  3336. /**
  3337. * Converts a hexadecimal string to a hexadecimal color number.
  3338. *
  3339. * @example
  3340. * PIXI.utils.string2hex("#ffffff"); // returns 0xffffff
  3341. * @memberof PIXI.utils
  3342. * @function string2hex
  3343. * @param {string} The string color (e.g., `"#ffffff"`)
  3344. * @return {number} Number in hexadecimal.
  3345. */
  3346. function string2hex(string)
  3347. {
  3348. if (typeof string === 'string' && string[0] === '#')
  3349. {
  3350. string = string.substr(1);
  3351. }
  3352. return parseInt(string, 16);
  3353. }
  3354. /**
  3355. * Converts a color as an [R, G, B] array of normalized floats to a hexadecimal number.
  3356. *
  3357. * @example
  3358. * PIXI.utils.rgb2hex([1, 1, 1]); // returns 0xffffff
  3359. * @memberof PIXI.utils
  3360. * @function rgb2hex
  3361. * @param {number[]} rgb - Array of numbers where all values are normalized floats from 0.0 to 1.0.
  3362. * @return {number} Number in hexadecimal.
  3363. */
  3364. function rgb2hex(rgb)
  3365. {
  3366. return (((rgb[0] * 255) << 16) + ((rgb[1] * 255) << 8) + (rgb[2] * 255 | 0));
  3367. }
  3368. /**
  3369. * Corrects PixiJS blend, takes premultiplied alpha into account
  3370. *
  3371. * @memberof PIXI.utils
  3372. * @function mapPremultipliedBlendModes
  3373. * @private
  3374. * @param {Array<number[]>} [array] - The array to output into.
  3375. * @return {Array<number[]>} Mapped modes.
  3376. */
  3377. function mapPremultipliedBlendModes()
  3378. {
  3379. var pm = [];
  3380. var npm = [];
  3381. for (var i = 0; i < 32; i++)
  3382. {
  3383. pm[i] = i;
  3384. npm[i] = i;
  3385. }
  3386. pm[BLEND_MODES.NORMAL_NPM] = BLEND_MODES.NORMAL;
  3387. pm[BLEND_MODES.ADD_NPM] = BLEND_MODES.ADD;
  3388. pm[BLEND_MODES.SCREEN_NPM] = BLEND_MODES.SCREEN;
  3389. npm[BLEND_MODES.NORMAL] = BLEND_MODES.NORMAL_NPM;
  3390. npm[BLEND_MODES.ADD] = BLEND_MODES.ADD_NPM;
  3391. npm[BLEND_MODES.SCREEN] = BLEND_MODES.SCREEN_NPM;
  3392. var array = [];
  3393. array.push(npm);
  3394. array.push(pm);
  3395. return array;
  3396. }
  3397. /**
  3398. * maps premultiply flag and blendMode to adjusted blendMode
  3399. * @memberof PIXI.utils
  3400. * @const premultiplyBlendMode
  3401. * @type {Array<number[]>}
  3402. */
  3403. var premultiplyBlendMode = mapPremultipliedBlendModes();
  3404. /**
  3405. * changes blendMode according to texture format
  3406. *
  3407. * @memberof PIXI.utils
  3408. * @function correctBlendMode
  3409. * @param {number} blendMode supposed blend mode
  3410. * @param {boolean} premultiplied whether source is premultiplied
  3411. * @returns {number} true blend mode for this texture
  3412. */
  3413. function correctBlendMode(blendMode, premultiplied)
  3414. {
  3415. return premultiplyBlendMode[premultiplied ? 1 : 0][blendMode];
  3416. }
  3417. /**
  3418. * combines rgb and alpha to out array
  3419. *
  3420. * @memberof PIXI.utils
  3421. * @function premultiplyRgba
  3422. * @param {Float32Array|number[]} rgb input rgb
  3423. * @param {number} alpha alpha param
  3424. * @param {Float32Array} [out] output
  3425. * @param {boolean} [premultiply=true] do premultiply it
  3426. * @returns {Float32Array} vec4 rgba
  3427. */
  3428. function premultiplyRgba(rgb, alpha, out, premultiply)
  3429. {
  3430. out = out || new Float32Array(4);
  3431. if (premultiply || premultiply === undefined)
  3432. {
  3433. out[0] = rgb[0] * alpha;
  3434. out[1] = rgb[1] * alpha;
  3435. out[2] = rgb[2] * alpha;
  3436. }
  3437. else
  3438. {
  3439. out[0] = rgb[0];
  3440. out[1] = rgb[1];
  3441. out[2] = rgb[2];
  3442. }
  3443. out[3] = alpha;
  3444. return out;
  3445. }
  3446. /**
  3447. * premultiplies tint
  3448. *
  3449. * @memberof PIXI.utils
  3450. * @function premultiplyTint
  3451. * @param {number} tint integer RGB
  3452. * @param {number} alpha floating point alpha (0.0-1.0)
  3453. * @returns {number} tint multiplied by alpha
  3454. */
  3455. function premultiplyTint(tint, alpha)
  3456. {
  3457. if (alpha === 1.0)
  3458. {
  3459. return (alpha * 255 << 24) + tint;
  3460. }
  3461. if (alpha === 0.0)
  3462. {
  3463. return 0;
  3464. }
  3465. var R = ((tint >> 16) & 0xFF);
  3466. var G = ((tint >> 8) & 0xFF);
  3467. var B = (tint & 0xFF);
  3468. R = ((R * alpha) + 0.5) | 0;
  3469. G = ((G * alpha) + 0.5) | 0;
  3470. B = ((B * alpha) + 0.5) | 0;
  3471. return (alpha * 255 << 24) + (R << 16) + (G << 8) + B;
  3472. }
  3473. /**
  3474. * converts integer tint and float alpha to vec4 form, premultiplies by default
  3475. *
  3476. * @memberof PIXI.utils
  3477. * @function premultiplyTintToRgba
  3478. * @param {number} tint input tint
  3479. * @param {number} alpha alpha param
  3480. * @param {Float32Array} [out] output
  3481. * @param {boolean} [premultiply=true] do premultiply it
  3482. * @returns {Float32Array} vec4 rgba
  3483. */
  3484. function premultiplyTintToRgba(tint, alpha, out, premultiply)
  3485. {
  3486. out = out || new Float32Array(4);
  3487. out[0] = ((tint >> 16) & 0xFF) / 255.0;
  3488. out[1] = ((tint >> 8) & 0xFF) / 255.0;
  3489. out[2] = (tint & 0xFF) / 255.0;
  3490. if (premultiply || premultiply === undefined)
  3491. {
  3492. out[0] *= alpha;
  3493. out[1] *= alpha;
  3494. out[2] *= alpha;
  3495. }
  3496. out[3] = alpha;
  3497. return out;
  3498. }
  3499. /**
  3500. * Generic Mask Stack data structure
  3501. *
  3502. * @memberof PIXI
  3503. * @function createIndicesForQuads
  3504. * @private
  3505. * @param {number} size - Number of quads
  3506. * @return {Uint16Array} indices
  3507. */
  3508. function createIndicesForQuads(size)
  3509. {
  3510. // the total number of indices in our array, there are 6 points per quad.
  3511. var totalIndices = size * 6;
  3512. var indices = new Uint16Array(totalIndices);
  3513. // fill the indices with the quads to draw
  3514. for (var i = 0, j = 0; i < totalIndices; i += 6, j += 4)
  3515. {
  3516. indices[i + 0] = j + 0;
  3517. indices[i + 1] = j + 1;
  3518. indices[i + 2] = j + 2;
  3519. indices[i + 3] = j + 0;
  3520. indices[i + 4] = j + 2;
  3521. indices[i + 5] = j + 3;
  3522. }
  3523. return indices;
  3524. }
  3525. /**
  3526. * Remove items from a javascript array without generating garbage
  3527. *
  3528. * @function removeItems
  3529. * @memberof PIXI.utils
  3530. * @param {Array<any>} arr Array to remove elements from
  3531. * @param {number} startIdx starting index
  3532. * @param {number} removeCount how many to remove
  3533. */
  3534. function removeItems(arr, startIdx, removeCount)
  3535. {
  3536. var length = arr.length;
  3537. var i;
  3538. if (startIdx >= length || removeCount === 0)
  3539. {
  3540. return;
  3541. }
  3542. removeCount = (startIdx + removeCount > length ? length - startIdx : removeCount);
  3543. var len = length - removeCount;
  3544. for (i = startIdx; i < len; ++i)
  3545. {
  3546. arr[i] = arr[i + removeCount];
  3547. }
  3548. arr.length = len;
  3549. }
  3550. var nextUid = 0;
  3551. /**
  3552. * Gets the next unique identifier
  3553. *
  3554. * @memberof PIXI.utils
  3555. * @function uid
  3556. * @return {number} The next unique identifier to use.
  3557. */
  3558. function uid()
  3559. {
  3560. return ++nextUid;
  3561. }
  3562. /**
  3563. * Returns sign of number
  3564. *
  3565. * @memberof PIXI.utils
  3566. * @function sign
  3567. * @param {number} n - the number to check the sign of
  3568. * @returns {number} 0 if `n` is 0, -1 if `n` is negative, 1 if `n` is positive
  3569. */
  3570. function sign(n)
  3571. {
  3572. if (n === 0) { return 0; }
  3573. return n < 0 ? -1 : 1;
  3574. }
  3575. // Taken from the bit-twiddle package
  3576. /**
  3577. * Rounds to next power of two.
  3578. *
  3579. * @function isPow2
  3580. * @memberof PIXI.utils
  3581. * @param {number} v input value
  3582. * @return {number}
  3583. */
  3584. function nextPow2(v)
  3585. {
  3586. v += v === 0;
  3587. --v;
  3588. v |= v >>> 1;
  3589. v |= v >>> 2;
  3590. v |= v >>> 4;
  3591. v |= v >>> 8;
  3592. v |= v >>> 16;
  3593. return v + 1;
  3594. }
  3595. /**
  3596. * Checks if a number is a power of two.
  3597. *
  3598. * @function isPow2
  3599. * @memberof PIXI.utils
  3600. * @param {number} v input value
  3601. * @return {boolean} `true` if value is power of two
  3602. */
  3603. function isPow2(v)
  3604. {
  3605. return !(v & (v - 1)) && (!!v);
  3606. }
  3607. /**
  3608. * Computes ceil of log base 2
  3609. *
  3610. * @function log2
  3611. * @memberof PIXI.utils
  3612. * @param {number} v input value
  3613. * @return {number} logarithm base 2
  3614. */
  3615. function log2(v)
  3616. {
  3617. var r = (v > 0xFFFF) << 4;
  3618. v >>>= r;
  3619. var shift = (v > 0xFF) << 3;
  3620. v >>>= shift; r |= shift;
  3621. shift = (v > 0xF) << 2;
  3622. v >>>= shift; r |= shift;
  3623. shift = (v > 0x3) << 1;
  3624. v >>>= shift; r |= shift;
  3625. return r | (v >> 1);
  3626. }
  3627. /**
  3628. * @todo Describe property usage
  3629. *
  3630. * @static
  3631. * @name ProgramCache
  3632. * @memberof PIXI.utils
  3633. * @type {Object}
  3634. */
  3635. var ProgramCache = {};
  3636. /**
  3637. * @todo Describe property usage
  3638. *
  3639. * @static
  3640. * @name TextureCache
  3641. * @memberof PIXI.utils
  3642. * @type {Object}
  3643. */
  3644. var TextureCache = Object.create(null);
  3645. /**
  3646. * @todo Describe property usage
  3647. *
  3648. * @static
  3649. * @name BaseTextureCache
  3650. * @memberof PIXI.utils
  3651. * @type {Object}
  3652. */
  3653. var BaseTextureCache = Object.create(null);
  3654. /**
  3655. * Destroys all texture in the cache
  3656. *
  3657. * @memberof PIXI.utils
  3658. * @function destroyTextureCache
  3659. */
  3660. function destroyTextureCache()
  3661. {
  3662. var key;
  3663. for (key in TextureCache)
  3664. {
  3665. TextureCache[key].destroy();
  3666. }
  3667. for (key in BaseTextureCache)
  3668. {
  3669. BaseTextureCache[key].destroy();
  3670. }
  3671. }
  3672. /**
  3673. * Removes all textures from cache, but does not destroy them
  3674. *
  3675. * @memberof PIXI.utils
  3676. * @function clearTextureCache
  3677. */
  3678. function clearTextureCache()
  3679. {
  3680. var key;
  3681. for (key in TextureCache)
  3682. {
  3683. delete TextureCache[key];
  3684. }
  3685. for (key in BaseTextureCache)
  3686. {
  3687. delete BaseTextureCache[key];
  3688. }
  3689. }
  3690. /**
  3691. * Trim transparent borders from a canvas
  3692. *
  3693. * @memberof PIXI.utils
  3694. * @function trimCanvas
  3695. * @param {HTMLCanvasElement} canvas - the canvas to trim
  3696. * @returns {object} Trim data
  3697. */
  3698. function trimCanvas(canvas)
  3699. {
  3700. // https://gist.github.com/remy/784508
  3701. var width = canvas.width;
  3702. var height = canvas.height;
  3703. var context = canvas.getContext('2d');
  3704. var imageData = context.getImageData(0, 0, width, height);
  3705. var pixels = imageData.data;
  3706. var len = pixels.length;
  3707. var bound = {
  3708. top: null,
  3709. left: null,
  3710. right: null,
  3711. bottom: null,
  3712. };
  3713. var data = null;
  3714. var i;
  3715. var x;
  3716. var y;
  3717. for (i = 0; i < len; i += 4)
  3718. {
  3719. if (pixels[i + 3] !== 0)
  3720. {
  3721. x = (i / 4) % width;
  3722. y = ~~((i / 4) / width);
  3723. if (bound.top === null)
  3724. {
  3725. bound.top = y;
  3726. }
  3727. if (bound.left === null)
  3728. {
  3729. bound.left = x;
  3730. }
  3731. else if (x < bound.left)
  3732. {
  3733. bound.left = x;
  3734. }
  3735. if (bound.right === null)
  3736. {
  3737. bound.right = x + 1;
  3738. }
  3739. else if (bound.right < x)
  3740. {
  3741. bound.right = x + 1;
  3742. }
  3743. if (bound.bottom === null)
  3744. {
  3745. bound.bottom = y;
  3746. }
  3747. else if (bound.bottom < y)
  3748. {
  3749. bound.bottom = y;
  3750. }
  3751. }
  3752. }
  3753. if (bound.top !== null)
  3754. {
  3755. width = bound.right - bound.left;
  3756. height = bound.bottom - bound.top + 1;
  3757. data = context.getImageData(bound.left, bound.top, width, height);
  3758. }
  3759. return {
  3760. height: height,
  3761. width: width,
  3762. data: data,
  3763. };
  3764. }
  3765. /**
  3766. * Creates a Canvas element of the given size to be used as a target for rendering to.
  3767. *
  3768. * @class
  3769. * @memberof PIXI.utils
  3770. */
  3771. var CanvasRenderTarget = function CanvasRenderTarget(width, height, resolution)
  3772. {
  3773. /**
  3774. * The Canvas object that belongs to this CanvasRenderTarget.
  3775. *
  3776. * @member {HTMLCanvasElement}
  3777. */
  3778. this.canvas = document.createElement('canvas');
  3779. /**
  3780. * A CanvasRenderingContext2D object representing a two-dimensional rendering context.
  3781. *
  3782. * @member {CanvasRenderingContext2D}
  3783. */
  3784. this.context = this.canvas.getContext('2d');
  3785. this.resolution = resolution || settings.RESOLUTION;
  3786. this.resize(width, height);
  3787. };
  3788. var prototypeAccessors = { width: { configurable: true },height: { configurable: true } };
  3789. /**
  3790. * Clears the canvas that was created by the CanvasRenderTarget class.
  3791. *
  3792. * @private
  3793. */
  3794. CanvasRenderTarget.prototype.clear = function clear ()
  3795. {
  3796. this.context.setTransform(1, 0, 0, 1, 0, 0);
  3797. this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
  3798. };
  3799. /**
  3800. * Resizes the canvas to the specified width and height.
  3801. *
  3802. * @param {number} width - the new width of the canvas
  3803. * @param {number} height - the new height of the canvas
  3804. */
  3805. CanvasRenderTarget.prototype.resize = function resize (width, height)
  3806. {
  3807. this.canvas.width = width * this.resolution;
  3808. this.canvas.height = height * this.resolution;
  3809. };
  3810. /**
  3811. * Destroys this canvas.
  3812. *
  3813. */
  3814. CanvasRenderTarget.prototype.destroy = function destroy ()
  3815. {
  3816. this.context = null;
  3817. this.canvas = null;
  3818. };
  3819. /**
  3820. * The width of the canvas buffer in pixels.
  3821. *
  3822. * @member {number}
  3823. */
  3824. prototypeAccessors.width.get = function ()
  3825. {
  3826. return this.canvas.width;
  3827. };
  3828. prototypeAccessors.width.set = function (val) // eslint-disable-line require-jsdoc
  3829. {
  3830. this.canvas.width = val;
  3831. };
  3832. /**
  3833. * The height of the canvas buffer in pixels.
  3834. *
  3835. * @member {number}
  3836. */
  3837. prototypeAccessors.height.get = function ()
  3838. {
  3839. return this.canvas.height;
  3840. };
  3841. prototypeAccessors.height.set = function (val) // eslint-disable-line require-jsdoc
  3842. {
  3843. this.canvas.height = val;
  3844. };
  3845. Object.defineProperties( CanvasRenderTarget.prototype, prototypeAccessors );
  3846. /**
  3847. * Regexp for data URI.
  3848. * Based on: {@link https://github.com/ragingwind/data-uri-regex}
  3849. *
  3850. * @static
  3851. * @constant {RegExp|string} DATA_URI
  3852. * @memberof PIXI
  3853. * @example data:image/png;base64
  3854. */
  3855. var DATA_URI = /^\s*data:(?:([\w-]+)\/([\w+.-]+))?(?:;charset=([\w-]+))?(?:;(base64))?,(.*)/i;
  3856. /**
  3857. * Typedef for decomposeDataUri return object.
  3858. *
  3859. * @memberof PIXI.utils
  3860. * @typedef {object} DecomposedDataUri
  3861. * @property {string} mediaType Media type, eg. `image`
  3862. * @property {string} subType Sub type, eg. `png`
  3863. * @property {string} encoding Data encoding, eg. `base64`
  3864. * @property {string} data The actual data
  3865. */
  3866. /**
  3867. * Split a data URI into components. Returns undefined if
  3868. * parameter `dataUri` is not a valid data URI.
  3869. *
  3870. * @memberof PIXI.utils
  3871. * @function decomposeDataUri
  3872. * @param {string} dataUri - the data URI to check
  3873. * @return {PIXI.utils.DecomposedDataUri|undefined} The decomposed data uri or undefined
  3874. */
  3875. function decomposeDataUri(dataUri)
  3876. {
  3877. var dataUriMatch = DATA_URI.exec(dataUri);
  3878. if (dataUriMatch)
  3879. {
  3880. return {
  3881. mediaType: dataUriMatch[1] ? dataUriMatch[1].toLowerCase() : undefined,
  3882. subType: dataUriMatch[2] ? dataUriMatch[2].toLowerCase() : undefined,
  3883. charset: dataUriMatch[3] ? dataUriMatch[3].toLowerCase() : undefined,
  3884. encoding: dataUriMatch[4] ? dataUriMatch[4].toLowerCase() : undefined,
  3885. data: dataUriMatch[5],
  3886. };
  3887. }
  3888. return undefined;
  3889. }
  3890. var tempAnchor;
  3891. /**
  3892. * Sets the `crossOrigin` property for this resource based on if the url
  3893. * for this resource is cross-origin. If crossOrigin was manually set, this
  3894. * function does nothing.
  3895. * Nipped from the resource loader!
  3896. *
  3897. * @ignore
  3898. * @param {string} url - The url to test.
  3899. * @param {object} [loc=window.location] - The location object to test against.
  3900. * @return {string} The crossOrigin value to use (or empty string for none).
  3901. */
  3902. function determineCrossOrigin(url$1, loc)
  3903. {
  3904. if ( loc === void 0 ) { loc = window.location; }
  3905. // data: and javascript: urls are considered same-origin
  3906. if (url$1.indexOf('data:') === 0)
  3907. {
  3908. return '';
  3909. }
  3910. // default is window.location
  3911. loc = loc || window.location;
  3912. if (!tempAnchor)
  3913. {
  3914. tempAnchor = document.createElement('a');
  3915. }
  3916. // let the browser determine the full href for the url of this resource and then
  3917. // parse with the node url lib, we can't use the properties of the anchor element
  3918. // because they don't work in IE9 :(
  3919. tempAnchor.href = url$1;
  3920. url$1 = url.parse(tempAnchor.href);
  3921. var samePort = (!url$1.port && loc.port === '') || (url$1.port === loc.port);
  3922. // if cross origin
  3923. if (url$1.hostname !== loc.hostname || !samePort || url$1.protocol !== loc.protocol)
  3924. {
  3925. return 'anonymous';
  3926. }
  3927. return '';
  3928. }
  3929. /**
  3930. * get the resolution / device pixel ratio of an asset by looking for the prefix
  3931. * used by spritesheets and image urls
  3932. *
  3933. * @memberof PIXI.utils
  3934. * @function getResolutionOfUrl
  3935. * @param {string} url - the image path
  3936. * @param {number} [defaultValue=1] - the defaultValue if no filename prefix is set.
  3937. * @return {number} resolution / device pixel ratio of an asset
  3938. */
  3939. function getResolutionOfUrl(url, defaultValue)
  3940. {
  3941. var resolution = settings.RETINA_PREFIX.exec(url);
  3942. if (resolution)
  3943. {
  3944. return parseFloat(resolution[1]);
  3945. }
  3946. return defaultValue !== undefined ? defaultValue : 1;
  3947. }
  3948. // A map of warning messages already fired
  3949. var warnings = {};
  3950. /**
  3951. * Helper for warning developers about deprecated features & settings.
  3952. * A stack track for warnings is given; useful for tracking-down where
  3953. * deprecated methods/properties/classes are being used within the code.
  3954. *
  3955. * @memberof PIXI.utils
  3956. * @function deprecation
  3957. * @param {string} version - The version where the feature became deprecated
  3958. * @param {string} message - Message should include what is deprecated, where, and the new solution
  3959. * @param {number} [ignoreDepth=3] - The number of steps to ignore at the top of the error stack
  3960. * this is mostly to ignore internal deprecation calls.
  3961. */
  3962. function deprecation(version, message, ignoreDepth)
  3963. {
  3964. if ( ignoreDepth === void 0 ) { ignoreDepth = 3; }
  3965. // Ignore duplicat
  3966. if (warnings[message])
  3967. {
  3968. return;
  3969. }
  3970. /* eslint-disable no-console */
  3971. var stack = new Error().stack;
  3972. // Handle IE < 10 and Safari < 6
  3973. if (typeof stack === 'undefined')
  3974. {
  3975. console.warn('PixiJS Deprecation Warning: ', (message + "\nDeprecated since v" + version));
  3976. }
  3977. else
  3978. {
  3979. // chop off the stack trace which includes PixiJS internal calls
  3980. stack = stack.split('\n').splice(ignoreDepth).join('\n');
  3981. if (console.groupCollapsed)
  3982. {
  3983. console.groupCollapsed(
  3984. '%cPixiJS Deprecation Warning: %c%s',
  3985. 'color:#614108;background:#fffbe6',
  3986. 'font-weight:normal;color:#614108;background:#fffbe6',
  3987. (message + "\nDeprecated since v" + version)
  3988. );
  3989. console.warn(stack);
  3990. console.groupEnd();
  3991. }
  3992. else
  3993. {
  3994. console.warn('PixiJS Deprecation Warning: ', (message + "\nDeprecated since v" + version));
  3995. console.warn(stack);
  3996. }
  3997. }
  3998. /* eslint-enable no-console */
  3999. warnings[message] = true;
  4000. }
  4001. var utils_es = ({
  4002. BaseTextureCache: BaseTextureCache,
  4003. CanvasRenderTarget: CanvasRenderTarget,
  4004. DATA_URI: DATA_URI,
  4005. ProgramCache: ProgramCache,
  4006. TextureCache: TextureCache,
  4007. clearTextureCache: clearTextureCache,
  4008. correctBlendMode: correctBlendMode,
  4009. createIndicesForQuads: createIndicesForQuads,
  4010. decomposeDataUri: decomposeDataUri,
  4011. deprecation: deprecation,
  4012. destroyTextureCache: destroyTextureCache,
  4013. determineCrossOrigin: determineCrossOrigin,
  4014. getResolutionOfUrl: getResolutionOfUrl,
  4015. hex2rgb: hex2rgb,
  4016. hex2string: hex2string,
  4017. isPow2: isPow2,
  4018. isWebGLSupported: isWebGLSupported,
  4019. log2: log2,
  4020. nextPow2: nextPow2,
  4021. premultiplyBlendMode: premultiplyBlendMode,
  4022. premultiplyRgba: premultiplyRgba,
  4023. premultiplyTint: premultiplyTint,
  4024. premultiplyTintToRgba: premultiplyTintToRgba,
  4025. removeItems: removeItems,
  4026. rgb2hex: rgb2hex,
  4027. sayHello: sayHello,
  4028. sign: sign,
  4029. skipHello: skipHello,
  4030. string2hex: string2hex,
  4031. trimCanvas: trimCanvas,
  4032. uid: uid,
  4033. isMobile: isMobile_min,
  4034. EventEmitter: eventemitter3,
  4035. earcut: earcut_1,
  4036. url: url
  4037. });
  4038. /*!
  4039. * @pixi/math - v5.0.4
  4040. * Compiled Fri, 07 Jun 2019 17:17:49 UTC
  4041. *
  4042. * @pixi/math is licensed under the MIT License.
  4043. * http://www.opensource.org/licenses/mit-license
  4044. */
  4045. /**
  4046. * The Point object represents a location in a two-dimensional coordinate system, where x represents
  4047. * the horizontal axis and y represents the vertical axis.
  4048. *
  4049. * @class
  4050. * @memberof PIXI
  4051. */
  4052. var Point = function Point(x, y)
  4053. {
  4054. if ( x === void 0 ) { x = 0; }
  4055. if ( y === void 0 ) { y = 0; }
  4056. /**
  4057. * @member {number}
  4058. * @default 0
  4059. */
  4060. this.x = x;
  4061. /**
  4062. * @member {number}
  4063. * @default 0
  4064. */
  4065. this.y = y;
  4066. };
  4067. /**
  4068. * Creates a clone of this point
  4069. *
  4070. * @return {PIXI.Point} a copy of the point
  4071. */
  4072. Point.prototype.clone = function clone ()
  4073. {
  4074. return new Point(this.x, this.y);
  4075. };
  4076. /**
  4077. * Copies x and y from the given point
  4078. *
  4079. * @param {PIXI.IPoint} p - The point to copy from
  4080. * @returns {PIXI.IPoint} Returns itself.
  4081. */
  4082. Point.prototype.copyFrom = function copyFrom (p)
  4083. {
  4084. this.set(p.x, p.y);
  4085. return this;
  4086. };
  4087. /**
  4088. * Copies x and y into the given point
  4089. *
  4090. * @param {PIXI.IPoint} p - The point to copy.
  4091. * @returns {PIXI.IPoint} Given point with values updated
  4092. */
  4093. Point.prototype.copyTo = function copyTo (p)
  4094. {
  4095. p.set(this.x, this.y);
  4096. return p;
  4097. };
  4098. /**
  4099. * Returns true if the given point is equal to this point
  4100. *
  4101. * @param {PIXI.IPoint} p - The point to check
  4102. * @returns {boolean} Whether the given point equal to this point
  4103. */
  4104. Point.prototype.equals = function equals (p)
  4105. {
  4106. return (p.x === this.x) && (p.y === this.y);
  4107. };
  4108. /**
  4109. * Sets the point to a new x and y position.
  4110. * If y is omitted, both x and y will be set to x.
  4111. *
  4112. * @param {number} [x=0] - position of the point on the x axis
  4113. * @param {number} [y=0] - position of the point on the y axis
  4114. */
  4115. Point.prototype.set = function set (x, y)
  4116. {
  4117. this.x = x || 0;
  4118. this.y = y || ((y !== 0) ? this.x : 0);
  4119. };
  4120. /**
  4121. * The Point object represents a location in a two-dimensional coordinate system, where x represents
  4122. * the horizontal axis and y represents the vertical axis.
  4123. *
  4124. * An ObservablePoint is a point that triggers a callback when the point's position is changed.
  4125. *
  4126. * @class
  4127. * @memberof PIXI
  4128. */
  4129. var ObservablePoint = function ObservablePoint(cb, scope, x, y)
  4130. {
  4131. if ( x === void 0 ) { x = 0; }
  4132. if ( y === void 0 ) { y = 0; }
  4133. this._x = x;
  4134. this._y = y;
  4135. this.cb = cb;
  4136. this.scope = scope;
  4137. };
  4138. var prototypeAccessors$1 = { x: { configurable: true },y: { configurable: true } };
  4139. /**
  4140. * Creates a clone of this point.
  4141. * The callback and scope params can be overidden otherwise they will default
  4142. * to the clone object's values.
  4143. *
  4144. * @override
  4145. * @param {Function} [cb=null] - callback when changed
  4146. * @param {object} [scope=null] - owner of callback
  4147. * @return {PIXI.ObservablePoint} a copy of the point
  4148. */
  4149. ObservablePoint.prototype.clone = function clone (cb, scope)
  4150. {
  4151. if ( cb === void 0 ) { cb = null; }
  4152. if ( scope === void 0 ) { scope = null; }
  4153. var _cb = cb || this.cb;
  4154. var _scope = scope || this.scope;
  4155. return new ObservablePoint(_cb, _scope, this._x, this._y);
  4156. };
  4157. /**
  4158. * Sets the point to a new x and y position.
  4159. * If y is omitted, both x and y will be set to x.
  4160. *
  4161. * @param {number} [x=0] - position of the point on the x axis
  4162. * @param {number} [y=0] - position of the point on the y axis
  4163. */
  4164. ObservablePoint.prototype.set = function set (x, y)
  4165. {
  4166. var _x = x || 0;
  4167. var _y = y || ((y !== 0) ? _x : 0);
  4168. if (this._x !== _x || this._y !== _y)
  4169. {
  4170. this._x = _x;
  4171. this._y = _y;
  4172. this.cb.call(this.scope);
  4173. }
  4174. };
  4175. /**
  4176. * Copies x and y from the given point
  4177. *
  4178. * @param {PIXI.IPoint} p - The point to copy from.
  4179. * @returns {PIXI.IPoint} Returns itself.
  4180. */
  4181. ObservablePoint.prototype.copyFrom = function copyFrom (p)
  4182. {
  4183. if (this._x !== p.x || this._y !== p.y)
  4184. {
  4185. this._x = p.x;
  4186. this._y = p.y;
  4187. this.cb.call(this.scope);
  4188. }
  4189. return this;
  4190. };
  4191. /**
  4192. * Copies x and y into the given point
  4193. *
  4194. * @param {PIXI.IPoint} p - The point to copy.
  4195. * @returns {PIXI.IPoint} Given point with values updated
  4196. */
  4197. ObservablePoint.prototype.copyTo = function copyTo (p)
  4198. {
  4199. p.set(this._x, this._y);
  4200. return p;
  4201. };
  4202. /**
  4203. * Returns true if the given point is equal to this point
  4204. *
  4205. * @param {PIXI.IPoint} p - The point to check
  4206. * @returns {boolean} Whether the given point equal to this point
  4207. */
  4208. ObservablePoint.prototype.equals = function equals (p)
  4209. {
  4210. return (p.x === this._x) && (p.y === this._y);
  4211. };
  4212. /**
  4213. * The position of the displayObject on the x axis relative to the local coordinates of the parent.
  4214. *
  4215. * @member {number}
  4216. */
  4217. prototypeAccessors$1.x.get = function ()
  4218. {
  4219. return this._x;
  4220. };
  4221. prototypeAccessors$1.x.set = function (value) // eslint-disable-line require-jsdoc
  4222. {
  4223. if (this._x !== value)
  4224. {
  4225. this._x = value;
  4226. this.cb.call(this.scope);
  4227. }
  4228. };
  4229. /**
  4230. * The position of the displayObject on the x axis relative to the local coordinates of the parent.
  4231. *
  4232. * @member {number}
  4233. */
  4234. prototypeAccessors$1.y.get = function ()
  4235. {
  4236. return this._y;
  4237. };
  4238. prototypeAccessors$1.y.set = function (value) // eslint-disable-line require-jsdoc
  4239. {
  4240. if (this._y !== value)
  4241. {
  4242. this._y = value;
  4243. this.cb.call(this.scope);
  4244. }
  4245. };
  4246. Object.defineProperties( ObservablePoint.prototype, prototypeAccessors$1 );
  4247. /**
  4248. * A number, or a string containing a number.
  4249. * @memberof PIXI
  4250. * @typedef {(PIXI.Point|PIXI.ObservablePoint)} IPoint
  4251. */
  4252. /**
  4253. * Two Pi.
  4254. *
  4255. * @static
  4256. * @constant {number} PI_2
  4257. * @memberof PIXI
  4258. */
  4259. var PI_2 = Math.PI * 2;
  4260. /**
  4261. * Conversion factor for converting radians to degrees.
  4262. *
  4263. * @static
  4264. * @constant {number} RAD_TO_DEG
  4265. * @memberof PIXI
  4266. */
  4267. var RAD_TO_DEG = 180 / Math.PI;
  4268. /**
  4269. * Conversion factor for converting degrees to radians.
  4270. *
  4271. * @static
  4272. * @constant {number} DEG_TO_RAD
  4273. * @memberof PIXI
  4274. */
  4275. var DEG_TO_RAD = Math.PI / 180;
  4276. /**
  4277. * Constants that identify shapes, mainly to prevent `instanceof` calls.
  4278. *
  4279. * @static
  4280. * @constant
  4281. * @name SHAPES
  4282. * @memberof PIXI
  4283. * @type {object}
  4284. * @property {number} POLY Polygon
  4285. * @property {number} RECT Rectangle
  4286. * @property {number} CIRC Circle
  4287. * @property {number} ELIP Ellipse
  4288. * @property {number} RREC Rounded Rectangle
  4289. */
  4290. var SHAPES = {
  4291. POLY: 0,
  4292. RECT: 1,
  4293. CIRC: 2,
  4294. ELIP: 3,
  4295. RREC: 4,
  4296. };
  4297. /**
  4298. * The PixiJS Matrix as a class makes it a lot faster.
  4299. *
  4300. * Here is a representation of it:
  4301. * ```js
  4302. * | a | c | tx|
  4303. * | b | d | ty|
  4304. * | 0 | 0 | 1 |
  4305. * ```
  4306. * @class
  4307. * @memberof PIXI
  4308. */
  4309. var Matrix = function Matrix(a, b, c, d, tx, ty)
  4310. {
  4311. if ( a === void 0 ) { a = 1; }
  4312. if ( b === void 0 ) { b = 0; }
  4313. if ( c === void 0 ) { c = 0; }
  4314. if ( d === void 0 ) { d = 1; }
  4315. if ( tx === void 0 ) { tx = 0; }
  4316. if ( ty === void 0 ) { ty = 0; }
  4317. /**
  4318. * @member {number}
  4319. * @default 1
  4320. */
  4321. this.a = a;
  4322. /**
  4323. * @member {number}
  4324. * @default 0
  4325. */
  4326. this.b = b;
  4327. /**
  4328. * @member {number}
  4329. * @default 0
  4330. */
  4331. this.c = c;
  4332. /**
  4333. * @member {number}
  4334. * @default 1
  4335. */
  4336. this.d = d;
  4337. /**
  4338. * @member {number}
  4339. * @default 0
  4340. */
  4341. this.tx = tx;
  4342. /**
  4343. * @member {number}
  4344. * @default 0
  4345. */
  4346. this.ty = ty;
  4347. this.array = null;
  4348. };
  4349. var staticAccessors = { IDENTITY: { configurable: true },TEMP_MATRIX: { configurable: true } };
  4350. /**
  4351. * Creates a Matrix object based on the given array. The Element to Matrix mapping order is as follows:
  4352. *
  4353. * a = array[0]
  4354. * b = array[1]
  4355. * c = array[3]
  4356. * d = array[4]
  4357. * tx = array[2]
  4358. * ty = array[5]
  4359. *
  4360. * @param {number[]} array - The array that the matrix will be populated from.
  4361. */
  4362. Matrix.prototype.fromArray = function fromArray (array)
  4363. {
  4364. this.a = array[0];
  4365. this.b = array[1];
  4366. this.c = array[3];
  4367. this.d = array[4];
  4368. this.tx = array[2];
  4369. this.ty = array[5];
  4370. };
  4371. /**
  4372. * sets the matrix properties
  4373. *
  4374. * @param {number} a - Matrix component
  4375. * @param {number} b - Matrix component
  4376. * @param {number} c - Matrix component
  4377. * @param {number} d - Matrix component
  4378. * @param {number} tx - Matrix component
  4379. * @param {number} ty - Matrix component
  4380. *
  4381. * @return {PIXI.Matrix} This matrix. Good for chaining method calls.
  4382. */
  4383. Matrix.prototype.set = function set (a, b, c, d, tx, ty)
  4384. {
  4385. this.a = a;
  4386. this.b = b;
  4387. this.c = c;
  4388. this.d = d;
  4389. this.tx = tx;
  4390. this.ty = ty;
  4391. return this;
  4392. };
  4393. /**
  4394. * Creates an array from the current Matrix object.
  4395. *
  4396. * @param {boolean} transpose - Whether we need to transpose the matrix or not
  4397. * @param {Float32Array} [out=new Float32Array(9)] - If provided the array will be assigned to out
  4398. * @return {number[]} the newly created array which contains the matrix
  4399. */
  4400. Matrix.prototype.toArray = function toArray (transpose, out)
  4401. {
  4402. if (!this.array)
  4403. {
  4404. this.array = new Float32Array(9);
  4405. }
  4406. var array = out || this.array;
  4407. if (transpose)
  4408. {
  4409. array[0] = this.a;
  4410. array[1] = this.b;
  4411. array[2] = 0;
  4412. array[3] = this.c;
  4413. array[4] = this.d;
  4414. array[5] = 0;
  4415. array[6] = this.tx;
  4416. array[7] = this.ty;
  4417. array[8] = 1;
  4418. }
  4419. else
  4420. {
  4421. array[0] = this.a;
  4422. array[1] = this.c;
  4423. array[2] = this.tx;
  4424. array[3] = this.b;
  4425. array[4] = this.d;
  4426. array[5] = this.ty;
  4427. array[6] = 0;
  4428. array[7] = 0;
  4429. array[8] = 1;
  4430. }
  4431. return array;
  4432. };
  4433. /**
  4434. * Get a new position with the current transformation applied.
  4435. * Can be used to go from a child's coordinate space to the world coordinate space. (e.g. rendering)
  4436. *
  4437. * @param {PIXI.Point} pos - The origin
  4438. * @param {PIXI.Point} [newPos] - The point that the new position is assigned to (allowed to be same as input)
  4439. * @return {PIXI.Point} The new point, transformed through this matrix
  4440. */
  4441. Matrix.prototype.apply = function apply (pos, newPos)
  4442. {
  4443. newPos = newPos || new Point();
  4444. var x = pos.x;
  4445. var y = pos.y;
  4446. newPos.x = (this.a * x) + (this.c * y) + this.tx;
  4447. newPos.y = (this.b * x) + (this.d * y) + this.ty;
  4448. return newPos;
  4449. };
  4450. /**
  4451. * Get a new position with the inverse of the current transformation applied.
  4452. * Can be used to go from the world coordinate space to a child's coordinate space. (e.g. input)
  4453. *
  4454. * @param {PIXI.Point} pos - The origin
  4455. * @param {PIXI.Point} [newPos] - The point that the new position is assigned to (allowed to be same as input)
  4456. * @return {PIXI.Point} The new point, inverse-transformed through this matrix
  4457. */
  4458. Matrix.prototype.applyInverse = function applyInverse (pos, newPos)
  4459. {
  4460. newPos = newPos || new Point();
  4461. var id = 1 / ((this.a * this.d) + (this.c * -this.b));
  4462. var x = pos.x;
  4463. var y = pos.y;
  4464. newPos.x = (this.d * id * x) + (-this.c * id * y) + (((this.ty * this.c) - (this.tx * this.d)) * id);
  4465. newPos.y = (this.a * id * y) + (-this.b * id * x) + (((-this.ty * this.a) + (this.tx * this.b)) * id);
  4466. return newPos;
  4467. };
  4468. /**
  4469. * Translates the matrix on the x and y.
  4470. *
  4471. * @param {number} x How much to translate x by
  4472. * @param {number} y How much to translate y by
  4473. * @return {PIXI.Matrix} This matrix. Good for chaining method calls.
  4474. */
  4475. Matrix.prototype.translate = function translate (x, y)
  4476. {
  4477. this.tx += x;
  4478. this.ty += y;
  4479. return this;
  4480. };
  4481. /**
  4482. * Applies a scale transformation to the matrix.
  4483. *
  4484. * @param {number} x The amount to scale horizontally
  4485. * @param {number} y The amount to scale vertically
  4486. * @return {PIXI.Matrix} This matrix. Good for chaining method calls.
  4487. */
  4488. Matrix.prototype.scale = function scale (x, y)
  4489. {
  4490. this.a *= x;
  4491. this.d *= y;
  4492. this.c *= x;
  4493. this.b *= y;
  4494. this.tx *= x;
  4495. this.ty *= y;
  4496. return this;
  4497. };
  4498. /**
  4499. * Applies a rotation transformation to the matrix.
  4500. *
  4501. * @param {number} angle - The angle in radians.
  4502. * @return {PIXI.Matrix} This matrix. Good for chaining method calls.
  4503. */
  4504. Matrix.prototype.rotate = function rotate (angle)
  4505. {
  4506. var cos = Math.cos(angle);
  4507. var sin = Math.sin(angle);
  4508. var a1 = this.a;
  4509. var c1 = this.c;
  4510. var tx1 = this.tx;
  4511. this.a = (a1 * cos) - (this.b * sin);
  4512. this.b = (a1 * sin) + (this.b * cos);
  4513. this.c = (c1 * cos) - (this.d * sin);
  4514. this.d = (c1 * sin) + (this.d * cos);
  4515. this.tx = (tx1 * cos) - (this.ty * sin);
  4516. this.ty = (tx1 * sin) + (this.ty * cos);
  4517. return this;
  4518. };
  4519. /**
  4520. * Appends the given Matrix to this Matrix.
  4521. *
  4522. * @param {PIXI.Matrix} matrix - The matrix to append.
  4523. * @return {PIXI.Matrix} This matrix. Good for chaining method calls.
  4524. */
  4525. Matrix.prototype.append = function append (matrix)
  4526. {
  4527. var a1 = this.a;
  4528. var b1 = this.b;
  4529. var c1 = this.c;
  4530. var d1 = this.d;
  4531. this.a = (matrix.a * a1) + (matrix.b * c1);
  4532. this.b = (matrix.a * b1) + (matrix.b * d1);
  4533. this.c = (matrix.c * a1) + (matrix.d * c1);
  4534. this.d = (matrix.c * b1) + (matrix.d * d1);
  4535. this.tx = (matrix.tx * a1) + (matrix.ty * c1) + this.tx;
  4536. this.ty = (matrix.tx * b1) + (matrix.ty * d1) + this.ty;
  4537. return this;
  4538. };
  4539. /**
  4540. * Sets the matrix based on all the available properties
  4541. *
  4542. * @param {number} x - Position on the x axis
  4543. * @param {number} y - Position on the y axis
  4544. * @param {number} pivotX - Pivot on the x axis
  4545. * @param {number} pivotY - Pivot on the y axis
  4546. * @param {number} scaleX - Scale on the x axis
  4547. * @param {number} scaleY - Scale on the y axis
  4548. * @param {number} rotation - Rotation in radians
  4549. * @param {number} skewX - Skew on the x axis
  4550. * @param {number} skewY - Skew on the y axis
  4551. * @return {PIXI.Matrix} This matrix. Good for chaining method calls.
  4552. */
  4553. Matrix.prototype.setTransform = function setTransform (x, y, pivotX, pivotY, scaleX, scaleY, rotation, skewX, skewY)
  4554. {
  4555. this.a = Math.cos(rotation + skewY) * scaleX;
  4556. this.b = Math.sin(rotation + skewY) * scaleX;
  4557. this.c = -Math.sin(rotation - skewX) * scaleY;
  4558. this.d = Math.cos(rotation - skewX) * scaleY;
  4559. this.tx = x - ((pivotX * this.a) + (pivotY * this.c));
  4560. this.ty = y - ((pivotX * this.b) + (pivotY * this.d));
  4561. return this;
  4562. };
  4563. /**
  4564. * Prepends the given Matrix to this Matrix.
  4565. *
  4566. * @param {PIXI.Matrix} matrix - The matrix to prepend
  4567. * @return {PIXI.Matrix} This matrix. Good for chaining method calls.
  4568. */
  4569. Matrix.prototype.prepend = function prepend (matrix)
  4570. {
  4571. var tx1 = this.tx;
  4572. if (matrix.a !== 1 || matrix.b !== 0 || matrix.c !== 0 || matrix.d !== 1)
  4573. {
  4574. var a1 = this.a;
  4575. var c1 = this.c;
  4576. this.a = (a1 * matrix.a) + (this.b * matrix.c);
  4577. this.b = (a1 * matrix.b) + (this.b * matrix.d);
  4578. this.c = (c1 * matrix.a) + (this.d * matrix.c);
  4579. this.d = (c1 * matrix.b) + (this.d * matrix.d);
  4580. }
  4581. this.tx = (tx1 * matrix.a) + (this.ty * matrix.c) + matrix.tx;
  4582. this.ty = (tx1 * matrix.b) + (this.ty * matrix.d) + matrix.ty;
  4583. return this;
  4584. };
  4585. /**
  4586. * Decomposes the matrix (x, y, scaleX, scaleY, and rotation) and sets the properties on to a transform.
  4587. *
  4588. * @param {PIXI.Transform} transform - The transform to apply the properties to.
  4589. * @return {PIXI.Transform} The transform with the newly applied properties
  4590. */
  4591. Matrix.prototype.decompose = function decompose (transform)
  4592. {
  4593. // sort out rotation / skew..
  4594. var a = this.a;
  4595. var b = this.b;
  4596. var c = this.c;
  4597. var d = this.d;
  4598. var skewX = -Math.atan2(-c, d);
  4599. var skewY = Math.atan2(b, a);
  4600. var delta = Math.abs(skewX + skewY);
  4601. if (delta < 0.00001 || Math.abs(PI_2 - delta) < 0.00001)
  4602. {
  4603. transform.rotation = skewY;
  4604. transform.skew.x = transform.skew.y = 0;
  4605. }
  4606. else
  4607. {
  4608. transform.rotation = 0;
  4609. transform.skew.x = skewX;
  4610. transform.skew.y = skewY;
  4611. }
  4612. // next set scale
  4613. transform.scale.x = Math.sqrt((a * a) + (b * b));
  4614. transform.scale.y = Math.sqrt((c * c) + (d * d));
  4615. // next set position
  4616. transform.position.x = this.tx;
  4617. transform.position.y = this.ty;
  4618. return transform;
  4619. };
  4620. /**
  4621. * Inverts this matrix
  4622. *
  4623. * @return {PIXI.Matrix} This matrix. Good for chaining method calls.
  4624. */
  4625. Matrix.prototype.invert = function invert ()
  4626. {
  4627. var a1 = this.a;
  4628. var b1 = this.b;
  4629. var c1 = this.c;
  4630. var d1 = this.d;
  4631. var tx1 = this.tx;
  4632. var n = (a1 * d1) - (b1 * c1);
  4633. this.a = d1 / n;
  4634. this.b = -b1 / n;
  4635. this.c = -c1 / n;
  4636. this.d = a1 / n;
  4637. this.tx = ((c1 * this.ty) - (d1 * tx1)) / n;
  4638. this.ty = -((a1 * this.ty) - (b1 * tx1)) / n;
  4639. return this;
  4640. };
  4641. /**
  4642. * Resets this Matrix to an identity (default) matrix.
  4643. *
  4644. * @return {PIXI.Matrix} This matrix. Good for chaining method calls.
  4645. */
  4646. Matrix.prototype.identity = function identity ()
  4647. {
  4648. this.a = 1;
  4649. this.b = 0;
  4650. this.c = 0;
  4651. this.d = 1;
  4652. this.tx = 0;
  4653. this.ty = 0;
  4654. return this;
  4655. };
  4656. /**
  4657. * Creates a new Matrix object with the same values as this one.
  4658. *
  4659. * @return {PIXI.Matrix} A copy of this matrix. Good for chaining method calls.
  4660. */
  4661. Matrix.prototype.clone = function clone ()
  4662. {
  4663. var matrix = new Matrix();
  4664. matrix.a = this.a;
  4665. matrix.b = this.b;
  4666. matrix.c = this.c;
  4667. matrix.d = this.d;
  4668. matrix.tx = this.tx;
  4669. matrix.ty = this.ty;
  4670. return matrix;
  4671. };
  4672. /**
  4673. * Changes the values of the given matrix to be the same as the ones in this matrix
  4674. *
  4675. * @param {PIXI.Matrix} matrix - The matrix to copy to.
  4676. * @return {PIXI.Matrix} The matrix given in parameter with its values updated.
  4677. */
  4678. Matrix.prototype.copyTo = function copyTo (matrix)
  4679. {
  4680. matrix.a = this.a;
  4681. matrix.b = this.b;
  4682. matrix.c = this.c;
  4683. matrix.d = this.d;
  4684. matrix.tx = this.tx;
  4685. matrix.ty = this.ty;
  4686. return matrix;
  4687. };
  4688. /**
  4689. * Changes the values of the matrix to be the same as the ones in given matrix
  4690. *
  4691. * @param {PIXI.Matrix} matrix - The matrix to copy from.
  4692. * @return {PIXI.Matrix} this
  4693. */
  4694. Matrix.prototype.copyFrom = function copyFrom (matrix)
  4695. {
  4696. this.a = matrix.a;
  4697. this.b = matrix.b;
  4698. this.c = matrix.c;
  4699. this.d = matrix.d;
  4700. this.tx = matrix.tx;
  4701. this.ty = matrix.ty;
  4702. return this;
  4703. };
  4704. /**
  4705. * A default (identity) matrix
  4706. *
  4707. * @static
  4708. * @const
  4709. * @member {PIXI.Matrix}
  4710. */
  4711. staticAccessors.IDENTITY.get = function ()
  4712. {
  4713. return new Matrix();
  4714. };
  4715. /**
  4716. * A temp matrix
  4717. *
  4718. * @static
  4719. * @const
  4720. * @member {PIXI.Matrix}
  4721. */
  4722. staticAccessors.TEMP_MATRIX.get = function ()
  4723. {
  4724. return new Matrix();
  4725. };
  4726. Object.defineProperties( Matrix, staticAccessors );
  4727. // Your friendly neighbour https://en.wikipedia.org/wiki/Dihedral_group of order 16
  4728. var ux = [1, 1, 0, -1, -1, -1, 0, 1, 1, 1, 0, -1, -1, -1, 0, 1];
  4729. var uy = [0, 1, 1, 1, 0, -1, -1, -1, 0, 1, 1, 1, 0, -1, -1, -1];
  4730. var vx = [0, -1, -1, -1, 0, 1, 1, 1, 0, 1, 1, 1, 0, -1, -1, -1];
  4731. var vy = [1, 1, 0, -1, -1, -1, 0, 1, -1, -1, 0, 1, 1, 1, 0, -1];
  4732. var tempMatrices = [];
  4733. var mul = [];
  4734. function signum(x)
  4735. {
  4736. if (x < 0)
  4737. {
  4738. return -1;
  4739. }
  4740. if (x > 0)
  4741. {
  4742. return 1;
  4743. }
  4744. return 0;
  4745. }
  4746. function init()
  4747. {
  4748. for (var i = 0; i < 16; i++)
  4749. {
  4750. var row = [];
  4751. mul.push(row);
  4752. for (var j = 0; j < 16; j++)
  4753. {
  4754. var _ux = signum((ux[i] * ux[j]) + (vx[i] * uy[j]));
  4755. var _uy = signum((uy[i] * ux[j]) + (vy[i] * uy[j]));
  4756. var _vx = signum((ux[i] * vx[j]) + (vx[i] * vy[j]));
  4757. var _vy = signum((uy[i] * vx[j]) + (vy[i] * vy[j]));
  4758. for (var k = 0; k < 16; k++)
  4759. {
  4760. if (ux[k] === _ux && uy[k] === _uy && vx[k] === _vx && vy[k] === _vy)
  4761. {
  4762. row.push(k);
  4763. break;
  4764. }
  4765. }
  4766. }
  4767. }
  4768. for (var i$1 = 0; i$1 < 16; i$1++)
  4769. {
  4770. var mat = new Matrix();
  4771. mat.set(ux[i$1], uy[i$1], vx[i$1], vy[i$1], 0, 0);
  4772. tempMatrices.push(mat);
  4773. }
  4774. }
  4775. init();
  4776. /**
  4777. * Implements Dihedral Group D_8, see [group D4]{@link http://mathworld.wolfram.com/DihedralGroupD4.html},
  4778. * D8 is the same but with diagonals. Used for texture rotations.
  4779. *
  4780. * Vector xX(i), xY(i) is U-axis of sprite with rotation i
  4781. * Vector yY(i), yY(i) is V-axis of sprite with rotation i
  4782. * Rotations: 0 grad (0), 90 grad (2), 180 grad (4), 270 grad (6)
  4783. * Mirrors: vertical (8), main diagonal (10), horizontal (12), reverse diagonal (14)
  4784. * This is the small part of gameofbombs.com portal system. It works.
  4785. *
  4786. * @author Ivan @ivanpopelyshev
  4787. * @class
  4788. * @memberof PIXI
  4789. */
  4790. var GroupD8 = {
  4791. E: 0,
  4792. SE: 1,
  4793. S: 2,
  4794. SW: 3,
  4795. W: 4,
  4796. NW: 5,
  4797. N: 6,
  4798. NE: 7,
  4799. MIRROR_VERTICAL: 8,
  4800. MIRROR_HORIZONTAL: 12,
  4801. uX: function (ind) { return ux[ind]; },
  4802. uY: function (ind) { return uy[ind]; },
  4803. vX: function (ind) { return vx[ind]; },
  4804. vY: function (ind) { return vy[ind]; },
  4805. inv: function (rotation) {
  4806. if (rotation & 8)
  4807. {
  4808. return rotation & 15;
  4809. }
  4810. return (-rotation) & 7;
  4811. },
  4812. add: function (rotationSecond, rotationFirst) { return mul[rotationSecond][rotationFirst]; },
  4813. sub: function (rotationSecond, rotationFirst) { return mul[rotationSecond][GroupD8.inv(rotationFirst)]; },
  4814. /**
  4815. * Adds 180 degrees to rotation. Commutative operation.
  4816. *
  4817. * @memberof PIXI.GroupD8
  4818. * @param {number} rotation - The number to rotate.
  4819. * @returns {number} rotated number
  4820. */
  4821. rotate180: function (rotation) { return rotation ^ 4; },
  4822. /**
  4823. * Direction of main vector can be horizontal, vertical or diagonal.
  4824. * Some objects work with vertical directions different.
  4825. *
  4826. * @memberof PIXI.GroupD8
  4827. * @param {number} rotation - The number to check.
  4828. * @returns {boolean} Whether or not the direction is vertical
  4829. */
  4830. isVertical: function (rotation) { return (rotation & 3) === 2; },
  4831. /**
  4832. * @memberof PIXI.GroupD8
  4833. * @param {number} dx - TODO
  4834. * @param {number} dy - TODO
  4835. *
  4836. * @return {number} TODO
  4837. */
  4838. byDirection: function (dx, dy) {
  4839. if (Math.abs(dx) * 2 <= Math.abs(dy))
  4840. {
  4841. if (dy >= 0)
  4842. {
  4843. return GroupD8.S;
  4844. }
  4845. return GroupD8.N;
  4846. }
  4847. else if (Math.abs(dy) * 2 <= Math.abs(dx))
  4848. {
  4849. if (dx > 0)
  4850. {
  4851. return GroupD8.E;
  4852. }
  4853. return GroupD8.W;
  4854. }
  4855. else if (dy > 0)
  4856. {
  4857. if (dx > 0)
  4858. {
  4859. return GroupD8.SE;
  4860. }
  4861. return GroupD8.SW;
  4862. }
  4863. else if (dx > 0)
  4864. {
  4865. return GroupD8.NE;
  4866. }
  4867. return GroupD8.NW;
  4868. },
  4869. /**
  4870. * Helps sprite to compensate texture packer rotation.
  4871. *
  4872. * @memberof PIXI.GroupD8
  4873. * @param {PIXI.Matrix} matrix - sprite world matrix
  4874. * @param {number} rotation - The rotation factor to use.
  4875. * @param {number} tx - sprite anchoring
  4876. * @param {number} ty - sprite anchoring
  4877. */
  4878. matrixAppendRotationInv: function (matrix, rotation, tx, ty) {
  4879. if ( tx === void 0 ) { tx = 0; }
  4880. if ( ty === void 0 ) { ty = 0; }
  4881. // Packer used "rotation", we use "inv(rotation)"
  4882. var mat = tempMatrices[GroupD8.inv(rotation)];
  4883. mat.tx = tx;
  4884. mat.ty = ty;
  4885. matrix.append(mat);
  4886. },
  4887. };
  4888. /**
  4889. * Transform that takes care about its versions
  4890. *
  4891. * @class
  4892. * @memberof PIXI
  4893. */
  4894. var Transform = function Transform()
  4895. {
  4896. /**
  4897. * The global matrix transform. It can be swapped temporarily by some functions like getLocalBounds()
  4898. *
  4899. * @member {PIXI.Matrix}
  4900. */
  4901. this.worldTransform = new Matrix();
  4902. /**
  4903. * The local matrix transform
  4904. *
  4905. * @member {PIXI.Matrix}
  4906. */
  4907. this.localTransform = new Matrix();
  4908. /**
  4909. * The coordinate of the object relative to the local coordinates of the parent.
  4910. *
  4911. * @member {PIXI.ObservablePoint}
  4912. */
  4913. this.position = new ObservablePoint(this.onChange, this, 0, 0);
  4914. /**
  4915. * The scale factor of the object.
  4916. *
  4917. * @member {PIXI.ObservablePoint}
  4918. */
  4919. this.scale = new ObservablePoint(this.onChange, this, 1, 1);
  4920. /**
  4921. * The pivot point of the displayObject that it rotates around.
  4922. *
  4923. * @member {PIXI.ObservablePoint}
  4924. */
  4925. this.pivot = new ObservablePoint(this.onChange, this, 0, 0);
  4926. /**
  4927. * The skew amount, on the x and y axis.
  4928. *
  4929. * @member {PIXI.ObservablePoint}
  4930. */
  4931. this.skew = new ObservablePoint(this.updateSkew, this, 0, 0);
  4932. this._rotation = 0;
  4933. this._cx = 1; // cos rotation + skewY;
  4934. this._sx = 0; // sin rotation + skewY;
  4935. this._cy = 0; // cos rotation + Math.PI/2 - skewX;
  4936. this._sy = 1; // sin rotation + Math.PI/2 - skewX;
  4937. this._localID = 0;
  4938. this._currentLocalID = 0;
  4939. this._worldID = 0;
  4940. this._parentID = 0;
  4941. };
  4942. var prototypeAccessors$1$1 = { rotation: { configurable: true } };
  4943. /**
  4944. * Called when a value changes.
  4945. *
  4946. * @private
  4947. */
  4948. Transform.prototype.onChange = function onChange ()
  4949. {
  4950. this._localID++;
  4951. };
  4952. /**
  4953. * Called when skew or rotation changes
  4954. *
  4955. * @private
  4956. */
  4957. Transform.prototype.updateSkew = function updateSkew ()
  4958. {
  4959. this._cx = Math.cos(this._rotation + this.skew._y);
  4960. this._sx = Math.sin(this._rotation + this.skew._y);
  4961. this._cy = -Math.sin(this._rotation - this.skew._x); // cos, added PI/2
  4962. this._sy = Math.cos(this._rotation - this.skew._x); // sin, added PI/2
  4963. this._localID++;
  4964. };
  4965. /**
  4966. * Updates only local matrix
  4967. */
  4968. Transform.prototype.updateLocalTransform = function updateLocalTransform ()
  4969. {
  4970. var lt = this.localTransform;
  4971. if (this._localID !== this._currentLocalID)
  4972. {
  4973. // get the matrix values of the displayobject based on its transform properties..
  4974. lt.a = this._cx * this.scale._x;
  4975. lt.b = this._sx * this.scale._x;
  4976. lt.c = this._cy * this.scale._y;
  4977. lt.d = this._sy * this.scale._y;
  4978. lt.tx = this.position._x - ((this.pivot._x * lt.a) + (this.pivot._y * lt.c));
  4979. lt.ty = this.position._y - ((this.pivot._x * lt.b) + (this.pivot._y * lt.d));
  4980. this._currentLocalID = this._localID;
  4981. // force an update..
  4982. this._parentID = -1;
  4983. }
  4984. };
  4985. /**
  4986. * Updates the values of the object and applies the parent's transform.
  4987. *
  4988. * @param {PIXI.Transform} parentTransform - The transform of the parent of this object
  4989. */
  4990. Transform.prototype.updateTransform = function updateTransform (parentTransform)
  4991. {
  4992. var lt = this.localTransform;
  4993. if (this._localID !== this._currentLocalID)
  4994. {
  4995. // get the matrix values of the displayobject based on its transform properties..
  4996. lt.a = this._cx * this.scale._x;
  4997. lt.b = this._sx * this.scale._x;
  4998. lt.c = this._cy * this.scale._y;
  4999. lt.d = this._sy * this.scale._y;
  5000. lt.tx = this.position._x - ((this.pivot._x * lt.a) + (this.pivot._y * lt.c));
  5001. lt.ty = this.position._y - ((this.pivot._x * lt.b) + (this.pivot._y * lt.d));
  5002. this._currentLocalID = this._localID;
  5003. // force an update..
  5004. this._parentID = -1;
  5005. }
  5006. if (this._parentID !== parentTransform._worldID)
  5007. {
  5008. // concat the parent matrix with the objects transform.
  5009. var pt = parentTransform.worldTransform;
  5010. var wt = this.worldTransform;
  5011. wt.a = (lt.a * pt.a) + (lt.b * pt.c);
  5012. wt.b = (lt.a * pt.b) + (lt.b * pt.d);
  5013. wt.c = (lt.c * pt.a) + (lt.d * pt.c);
  5014. wt.d = (lt.c * pt.b) + (lt.d * pt.d);
  5015. wt.tx = (lt.tx * pt.a) + (lt.ty * pt.c) + pt.tx;
  5016. wt.ty = (lt.tx * pt.b) + (lt.ty * pt.d) + pt.ty;
  5017. this._parentID = parentTransform._worldID;
  5018. // update the id of the transform..
  5019. this._worldID++;
  5020. }
  5021. };
  5022. /**
  5023. * Decomposes a matrix and sets the transforms properties based on it.
  5024. *
  5025. * @param {PIXI.Matrix} matrix - The matrix to decompose
  5026. */
  5027. Transform.prototype.setFromMatrix = function setFromMatrix (matrix)
  5028. {
  5029. matrix.decompose(this);
  5030. this._localID++;
  5031. };
  5032. /**
  5033. * The rotation of the object in radians.
  5034. *
  5035. * @member {number}
  5036. */
  5037. prototypeAccessors$1$1.rotation.get = function ()
  5038. {
  5039. return this._rotation;
  5040. };
  5041. prototypeAccessors$1$1.rotation.set = function (value) // eslint-disable-line require-jsdoc
  5042. {
  5043. if (this._rotation !== value)
  5044. {
  5045. this._rotation = value;
  5046. this.updateSkew();
  5047. }
  5048. };
  5049. Object.defineProperties( Transform.prototype, prototypeAccessors$1$1 );
  5050. Transform.IDENTITY = new Transform();
  5051. /**
  5052. * Rectangle object is an area defined by its position, as indicated by its top-left corner
  5053. * point (x, y) and by its width and its height.
  5054. *
  5055. * @class
  5056. * @memberof PIXI
  5057. */
  5058. var Rectangle = function Rectangle(x, y, width, height)
  5059. {
  5060. if ( x === void 0 ) { x = 0; }
  5061. if ( y === void 0 ) { y = 0; }
  5062. if ( width === void 0 ) { width = 0; }
  5063. if ( height === void 0 ) { height = 0; }
  5064. /**
  5065. * @member {number}
  5066. * @default 0
  5067. */
  5068. this.x = Number(x);
  5069. /**
  5070. * @member {number}
  5071. * @default 0
  5072. */
  5073. this.y = Number(y);
  5074. /**
  5075. * @member {number}
  5076. * @default 0
  5077. */
  5078. this.width = Number(width);
  5079. /**
  5080. * @member {number}
  5081. * @default 0
  5082. */
  5083. this.height = Number(height);
  5084. /**
  5085. * The type of the object, mainly used to avoid `instanceof` checks
  5086. *
  5087. * @member {number}
  5088. * @readOnly
  5089. * @default PIXI.SHAPES.RECT
  5090. * @see PIXI.SHAPES
  5091. */
  5092. this.type = SHAPES.RECT;
  5093. };
  5094. var prototypeAccessors$2 = { left: { configurable: true },right: { configurable: true },top: { configurable: true },bottom: { configurable: true } };
  5095. var staticAccessors$1 = { EMPTY: { configurable: true } };
  5096. /**
  5097. * returns the left edge of the rectangle
  5098. *
  5099. * @member {number}
  5100. */
  5101. prototypeAccessors$2.left.get = function ()
  5102. {
  5103. return this.x;
  5104. };
  5105. /**
  5106. * returns the right edge of the rectangle
  5107. *
  5108. * @member {number}
  5109. */
  5110. prototypeAccessors$2.right.get = function ()
  5111. {
  5112. return this.x + this.width;
  5113. };
  5114. /**
  5115. * returns the top edge of the rectangle
  5116. *
  5117. * @member {number}
  5118. */
  5119. prototypeAccessors$2.top.get = function ()
  5120. {
  5121. return this.y;
  5122. };
  5123. /**
  5124. * returns the bottom edge of the rectangle
  5125. *
  5126. * @member {number}
  5127. */
  5128. prototypeAccessors$2.bottom.get = function ()
  5129. {
  5130. return this.y + this.height;
  5131. };
  5132. /**
  5133. * A constant empty rectangle.
  5134. *
  5135. * @static
  5136. * @constant
  5137. * @member {PIXI.Rectangle}
  5138. */
  5139. staticAccessors$1.EMPTY.get = function ()
  5140. {
  5141. return new Rectangle(0, 0, 0, 0);
  5142. };
  5143. /**
  5144. * Creates a clone of this Rectangle
  5145. *
  5146. * @return {PIXI.Rectangle} a copy of the rectangle
  5147. */
  5148. Rectangle.prototype.clone = function clone ()
  5149. {
  5150. return new Rectangle(this.x, this.y, this.width, this.height);
  5151. };
  5152. /**
  5153. * Copies another rectangle to this one.
  5154. *
  5155. * @param {PIXI.Rectangle} rectangle - The rectangle to copy from.
  5156. * @return {PIXI.Rectangle} Returns itself.
  5157. */
  5158. Rectangle.prototype.copyFrom = function copyFrom (rectangle)
  5159. {
  5160. this.x = rectangle.x;
  5161. this.y = rectangle.y;
  5162. this.width = rectangle.width;
  5163. this.height = rectangle.height;
  5164. return this;
  5165. };
  5166. /**
  5167. * Copies this rectangle to another one.
  5168. *
  5169. * @param {PIXI.Rectangle} rectangle - The rectangle to copy to.
  5170. * @return {PIXI.Rectangle} Returns given parameter.
  5171. */
  5172. Rectangle.prototype.copyTo = function copyTo (rectangle)
  5173. {
  5174. rectangle.x = this.x;
  5175. rectangle.y = this.y;
  5176. rectangle.width = this.width;
  5177. rectangle.height = this.height;
  5178. return rectangle;
  5179. };
  5180. /**
  5181. * Checks whether the x and y coordinates given are contained within this Rectangle
  5182. *
  5183. * @param {number} x - The X coordinate of the point to test
  5184. * @param {number} y - The Y coordinate of the point to test
  5185. * @return {boolean} Whether the x/y coordinates are within this Rectangle
  5186. */
  5187. Rectangle.prototype.contains = function contains (x, y)
  5188. {
  5189. if (this.width <= 0 || this.height <= 0)
  5190. {
  5191. return false;
  5192. }
  5193. if (x >= this.x && x < this.x + this.width)
  5194. {
  5195. if (y >= this.y && y < this.y + this.height)
  5196. {
  5197. return true;
  5198. }
  5199. }
  5200. return false;
  5201. };
  5202. /**
  5203. * Pads the rectangle making it grow in all directions.
  5204. *
  5205. * @param {number} paddingX - The horizontal padding amount.
  5206. * @param {number} paddingY - The vertical padding amount.
  5207. */
  5208. Rectangle.prototype.pad = function pad (paddingX, paddingY)
  5209. {
  5210. paddingX = paddingX || 0;
  5211. paddingY = paddingY || ((paddingY !== 0) ? paddingX : 0);
  5212. this.x -= paddingX;
  5213. this.y -= paddingY;
  5214. this.width += paddingX * 2;
  5215. this.height += paddingY * 2;
  5216. };
  5217. /**
  5218. * Fits this rectangle around the passed one.
  5219. *
  5220. * @param {PIXI.Rectangle} rectangle - The rectangle to fit.
  5221. */
  5222. Rectangle.prototype.fit = function fit (rectangle)
  5223. {
  5224. var x1 = Math.max(this.x, rectangle.x);
  5225. var x2 = Math.min(this.x + this.width, rectangle.x + rectangle.width);
  5226. var y1 = Math.max(this.y, rectangle.y);
  5227. var y2 = Math.min(this.y + this.height, rectangle.y + rectangle.height);
  5228. this.x = x1;
  5229. this.width = Math.max(x2 - x1, 0);
  5230. this.y = y1;
  5231. this.height = Math.max(y2 - y1, 0);
  5232. };
  5233. /**
  5234. * Enlarges rectangle that way its corners lie on grid
  5235. *
  5236. * @param {number} [resolution=1] resolution
  5237. * @param {number} [eps=0.001] precision
  5238. */
  5239. Rectangle.prototype.ceil = function ceil (resolution, eps)
  5240. {
  5241. if ( resolution === void 0 ) { resolution = 1; }
  5242. if ( eps === void 0 ) { eps = 0.001; }
  5243. var x2 = Math.ceil((this.x + this.width - eps) * resolution) / resolution;
  5244. var y2 = Math.ceil((this.y + this.height - eps) * resolution) / resolution;
  5245. this.x = Math.floor((this.x + eps) * resolution) / resolution;
  5246. this.y = Math.floor((this.y + eps) * resolution) / resolution;
  5247. this.width = x2 - this.x;
  5248. this.height = y2 - this.y;
  5249. };
  5250. /**
  5251. * Enlarges this rectangle to include the passed rectangle.
  5252. *
  5253. * @param {PIXI.Rectangle} rectangle - The rectangle to include.
  5254. */
  5255. Rectangle.prototype.enlarge = function enlarge (rectangle)
  5256. {
  5257. var x1 = Math.min(this.x, rectangle.x);
  5258. var x2 = Math.max(this.x + this.width, rectangle.x + rectangle.width);
  5259. var y1 = Math.min(this.y, rectangle.y);
  5260. var y2 = Math.max(this.y + this.height, rectangle.y + rectangle.height);
  5261. this.x = x1;
  5262. this.width = x2 - x1;
  5263. this.y = y1;
  5264. this.height = y2 - y1;
  5265. };
  5266. Object.defineProperties( Rectangle.prototype, prototypeAccessors$2 );
  5267. Object.defineProperties( Rectangle, staticAccessors$1 );
  5268. /**
  5269. * The Circle object is used to help draw graphics and can also be used to specify a hit area for displayObjects.
  5270. *
  5271. * @class
  5272. * @memberof PIXI
  5273. */
  5274. var Circle = function Circle(x, y, radius)
  5275. {
  5276. if ( x === void 0 ) { x = 0; }
  5277. if ( y === void 0 ) { y = 0; }
  5278. if ( radius === void 0 ) { radius = 0; }
  5279. /**
  5280. * @member {number}
  5281. * @default 0
  5282. */
  5283. this.x = x;
  5284. /**
  5285. * @member {number}
  5286. * @default 0
  5287. */
  5288. this.y = y;
  5289. /**
  5290. * @member {number}
  5291. * @default 0
  5292. */
  5293. this.radius = radius;
  5294. /**
  5295. * The type of the object, mainly used to avoid `instanceof` checks
  5296. *
  5297. * @member {number}
  5298. * @readOnly
  5299. * @default PIXI.SHAPES.CIRC
  5300. * @see PIXI.SHAPES
  5301. */
  5302. this.type = SHAPES.CIRC;
  5303. };
  5304. /**
  5305. * Creates a clone of this Circle instance
  5306. *
  5307. * @return {PIXI.Circle} a copy of the Circle
  5308. */
  5309. Circle.prototype.clone = function clone ()
  5310. {
  5311. return new Circle(this.x, this.y, this.radius);
  5312. };
  5313. /**
  5314. * Checks whether the x and y coordinates given are contained within this circle
  5315. *
  5316. * @param {number} x - The X coordinate of the point to test
  5317. * @param {number} y - The Y coordinate of the point to test
  5318. * @return {boolean} Whether the x/y coordinates are within this Circle
  5319. */
  5320. Circle.prototype.contains = function contains (x, y)
  5321. {
  5322. if (this.radius <= 0)
  5323. {
  5324. return false;
  5325. }
  5326. var r2 = this.radius * this.radius;
  5327. var dx = (this.x - x);
  5328. var dy = (this.y - y);
  5329. dx *= dx;
  5330. dy *= dy;
  5331. return (dx + dy <= r2);
  5332. };
  5333. /**
  5334. * Returns the framing rectangle of the circle as a Rectangle object
  5335. *
  5336. * @return {PIXI.Rectangle} the framing rectangle
  5337. */
  5338. Circle.prototype.getBounds = function getBounds ()
  5339. {
  5340. return new Rectangle(this.x - this.radius, this.y - this.radius, this.radius * 2, this.radius * 2);
  5341. };
  5342. /**
  5343. * The Ellipse object is used to help draw graphics and can also be used to specify a hit area for displayObjects.
  5344. *
  5345. * @class
  5346. * @memberof PIXI
  5347. */
  5348. var Ellipse = function Ellipse(x, y, halfWidth, halfHeight)
  5349. {
  5350. if ( x === void 0 ) { x = 0; }
  5351. if ( y === void 0 ) { y = 0; }
  5352. if ( halfWidth === void 0 ) { halfWidth = 0; }
  5353. if ( halfHeight === void 0 ) { halfHeight = 0; }
  5354. /**
  5355. * @member {number}
  5356. * @default 0
  5357. */
  5358. this.x = x;
  5359. /**
  5360. * @member {number}
  5361. * @default 0
  5362. */
  5363. this.y = y;
  5364. /**
  5365. * @member {number}
  5366. * @default 0
  5367. */
  5368. this.width = halfWidth;
  5369. /**
  5370. * @member {number}
  5371. * @default 0
  5372. */
  5373. this.height = halfHeight;
  5374. /**
  5375. * The type of the object, mainly used to avoid `instanceof` checks
  5376. *
  5377. * @member {number}
  5378. * @readOnly
  5379. * @default PIXI.SHAPES.ELIP
  5380. * @see PIXI.SHAPES
  5381. */
  5382. this.type = SHAPES.ELIP;
  5383. };
  5384. /**
  5385. * Creates a clone of this Ellipse instance
  5386. *
  5387. * @return {PIXI.Ellipse} a copy of the ellipse
  5388. */
  5389. Ellipse.prototype.clone = function clone ()
  5390. {
  5391. return new Ellipse(this.x, this.y, this.width, this.height);
  5392. };
  5393. /**
  5394. * Checks whether the x and y coordinates given are contained within this ellipse
  5395. *
  5396. * @param {number} x - The X coordinate of the point to test
  5397. * @param {number} y - The Y coordinate of the point to test
  5398. * @return {boolean} Whether the x/y coords are within this ellipse
  5399. */
  5400. Ellipse.prototype.contains = function contains (x, y)
  5401. {
  5402. if (this.width <= 0 || this.height <= 0)
  5403. {
  5404. return false;
  5405. }
  5406. // normalize the coords to an ellipse with center 0,0
  5407. var normx = ((x - this.x) / this.width);
  5408. var normy = ((y - this.y) / this.height);
  5409. normx *= normx;
  5410. normy *= normy;
  5411. return (normx + normy <= 1);
  5412. };
  5413. /**
  5414. * Returns the framing rectangle of the ellipse as a Rectangle object
  5415. *
  5416. * @return {PIXI.Rectangle} the framing rectangle
  5417. */
  5418. Ellipse.prototype.getBounds = function getBounds ()
  5419. {
  5420. return new Rectangle(this.x - this.width, this.y - this.height, this.width, this.height);
  5421. };
  5422. /**
  5423. * A class to define a shape via user defined co-orinates.
  5424. *
  5425. * @class
  5426. * @memberof PIXI
  5427. */
  5428. var Polygon = function Polygon()
  5429. {
  5430. var arguments$1 = arguments;
  5431. var points = [], len = arguments.length;
  5432. while ( len-- ) { points[ len ] = arguments$1[ len ]; }
  5433. if (Array.isArray(points[0]))
  5434. {
  5435. points = points[0];
  5436. }
  5437. // if this is an array of points, convert it to a flat array of numbers
  5438. if (points[0] instanceof Point)
  5439. {
  5440. var p = [];
  5441. for (var i = 0, il = points.length; i < il; i++)
  5442. {
  5443. p.push(points[i].x, points[i].y);
  5444. }
  5445. points = p;
  5446. }
  5447. /**
  5448. * An array of the points of this polygon
  5449. *
  5450. * @member {number[]}
  5451. */
  5452. this.points = points;
  5453. /**
  5454. * The type of the object, mainly used to avoid `instanceof` checks
  5455. *
  5456. * @member {number}
  5457. * @readOnly
  5458. * @default PIXI.SHAPES.POLY
  5459. * @see PIXI.SHAPES
  5460. */
  5461. this.type = SHAPES.POLY;
  5462. /**
  5463. * `false` after moveTo, `true` after `closePath`. In all other cases it is `true`.
  5464. * @member {boolean}
  5465. * @default true
  5466. */
  5467. this.closeStroke = true;
  5468. };
  5469. /**
  5470. * Creates a clone of this polygon
  5471. *
  5472. * @return {PIXI.Polygon} a copy of the polygon
  5473. */
  5474. Polygon.prototype.clone = function clone ()
  5475. {
  5476. var polygon = new Polygon(this.points.slice());
  5477. polygon.closeStroke = this.closeStroke;
  5478. return polygon;
  5479. };
  5480. /**
  5481. * Checks whether the x and y coordinates passed to this function are contained within this polygon
  5482. *
  5483. * @param {number} x - The X coordinate of the point to test
  5484. * @param {number} y - The Y coordinate of the point to test
  5485. * @return {boolean} Whether the x/y coordinates are within this polygon
  5486. */
  5487. Polygon.prototype.contains = function contains (x, y)
  5488. {
  5489. var inside = false;
  5490. // use some raycasting to test hits
  5491. // https://github.com/substack/point-in-polygon/blob/master/index.js
  5492. var length = this.points.length / 2;
  5493. for (var i = 0, j = length - 1; i < length; j = i++)
  5494. {
  5495. var xi = this.points[i * 2];
  5496. var yi = this.points[(i * 2) + 1];
  5497. var xj = this.points[j * 2];
  5498. var yj = this.points[(j * 2) + 1];
  5499. var intersect = ((yi > y) !== (yj > y)) && (x < ((xj - xi) * ((y - yi) / (yj - yi))) + xi);
  5500. if (intersect)
  5501. {
  5502. inside = !inside;
  5503. }
  5504. }
  5505. return inside;
  5506. };
  5507. /**
  5508. * The Rounded Rectangle object is an area that has nice rounded corners, as indicated by its
  5509. * top-left corner point (x, y) and by its width and its height and its radius.
  5510. *
  5511. * @class
  5512. * @memberof PIXI
  5513. */
  5514. var RoundedRectangle = function RoundedRectangle(x, y, width, height, radius)
  5515. {
  5516. if ( x === void 0 ) { x = 0; }
  5517. if ( y === void 0 ) { y = 0; }
  5518. if ( width === void 0 ) { width = 0; }
  5519. if ( height === void 0 ) { height = 0; }
  5520. if ( radius === void 0 ) { radius = 20; }
  5521. /**
  5522. * @member {number}
  5523. * @default 0
  5524. */
  5525. this.x = x;
  5526. /**
  5527. * @member {number}
  5528. * @default 0
  5529. */
  5530. this.y = y;
  5531. /**
  5532. * @member {number}
  5533. * @default 0
  5534. */
  5535. this.width = width;
  5536. /**
  5537. * @member {number}
  5538. * @default 0
  5539. */
  5540. this.height = height;
  5541. /**
  5542. * @member {number}
  5543. * @default 20
  5544. */
  5545. this.radius = radius;
  5546. /**
  5547. * The type of the object, mainly used to avoid `instanceof` checks
  5548. *
  5549. * @member {number}
  5550. * @readonly
  5551. * @default PIXI.SHAPES.RREC
  5552. * @see PIXI.SHAPES
  5553. */
  5554. this.type = SHAPES.RREC;
  5555. };
  5556. /**
  5557. * Creates a clone of this Rounded Rectangle
  5558. *
  5559. * @return {PIXI.RoundedRectangle} a copy of the rounded rectangle
  5560. */
  5561. RoundedRectangle.prototype.clone = function clone ()
  5562. {
  5563. return new RoundedRectangle(this.x, this.y, this.width, this.height, this.radius);
  5564. };
  5565. /**
  5566. * Checks whether the x and y coordinates given are contained within this Rounded Rectangle
  5567. *
  5568. * @param {number} x - The X coordinate of the point to test
  5569. * @param {number} y - The Y coordinate of the point to test
  5570. * @return {boolean} Whether the x/y coordinates are within this Rounded Rectangle
  5571. */
  5572. RoundedRectangle.prototype.contains = function contains (x, y)
  5573. {
  5574. if (this.width <= 0 || this.height <= 0)
  5575. {
  5576. return false;
  5577. }
  5578. if (x >= this.x && x <= this.x + this.width)
  5579. {
  5580. if (y >= this.y && y <= this.y + this.height)
  5581. {
  5582. if ((y >= this.y + this.radius && y <= this.y + this.height - this.radius)
  5583. || (x >= this.x + this.radius && x <= this.x + this.width - this.radius))
  5584. {
  5585. return true;
  5586. }
  5587. var dx = x - (this.x + this.radius);
  5588. var dy = y - (this.y + this.radius);
  5589. var radius2 = this.radius * this.radius;
  5590. if ((dx * dx) + (dy * dy) <= radius2)
  5591. {
  5592. return true;
  5593. }
  5594. dx = x - (this.x + this.width - this.radius);
  5595. if ((dx * dx) + (dy * dy) <= radius2)
  5596. {
  5597. return true;
  5598. }
  5599. dy = y - (this.y + this.height - this.radius);
  5600. if ((dx * dx) + (dy * dy) <= radius2)
  5601. {
  5602. return true;
  5603. }
  5604. dx = x - (this.x + this.radius);
  5605. if ((dx * dx) + (dy * dy) <= radius2)
  5606. {
  5607. return true;
  5608. }
  5609. }
  5610. }
  5611. return false;
  5612. };
  5613. /*!
  5614. * @pixi/display - v5.0.4
  5615. * Compiled Fri, 07 Jun 2019 17:17:49 UTC
  5616. *
  5617. * @pixi/display is licensed under the MIT License.
  5618. * http://www.opensource.org/licenses/mit-license
  5619. */
  5620. /**
  5621. * Sets the default value for the container property 'sortableChildren'.
  5622. * If set to true, the container will sort its children by zIndex value
  5623. * when updateTransform() is called, or manually if sortChildren() is called.
  5624. *
  5625. * This actually changes the order of elements in the array, so should be treated
  5626. * as a basic solution that is not performant compared to other solutions,
  5627. * such as @link https://github.com/pixijs/pixi-display
  5628. *
  5629. * Also be aware of that this may not work nicely with the addChildAt() function,
  5630. * as the zIndex sorting may cause the child to automatically sorted to another position.
  5631. *
  5632. * @static
  5633. * @constant
  5634. * @name SORTABLE_CHILDREN
  5635. * @memberof PIXI.settings
  5636. * @type {boolean}
  5637. * @default false
  5638. */
  5639. settings.SORTABLE_CHILDREN = false;
  5640. /**
  5641. * 'Builder' pattern for bounds rectangles.
  5642. *
  5643. * This could be called an Axis-Aligned Bounding Box.
  5644. * It is not an actual shape. It is a mutable thing; no 'EMPTY' or those kind of problems.
  5645. *
  5646. * @class
  5647. * @memberof PIXI
  5648. */
  5649. var Bounds = function Bounds()
  5650. {
  5651. /**
  5652. * @member {number}
  5653. * @default 0
  5654. */
  5655. this.minX = Infinity;
  5656. /**
  5657. * @member {number}
  5658. * @default 0
  5659. */
  5660. this.minY = Infinity;
  5661. /**
  5662. * @member {number}
  5663. * @default 0
  5664. */
  5665. this.maxX = -Infinity;
  5666. /**
  5667. * @member {number}
  5668. * @default 0
  5669. */
  5670. this.maxY = -Infinity;
  5671. this.rect = null;
  5672. };
  5673. /**
  5674. * Checks if bounds are empty.
  5675. *
  5676. * @return {boolean} True if empty.
  5677. */
  5678. Bounds.prototype.isEmpty = function isEmpty ()
  5679. {
  5680. return this.minX > this.maxX || this.minY > this.maxY;
  5681. };
  5682. /**
  5683. * Clears the bounds and resets.
  5684. *
  5685. */
  5686. Bounds.prototype.clear = function clear ()
  5687. {
  5688. this.updateID++;
  5689. this.minX = Infinity;
  5690. this.minY = Infinity;
  5691. this.maxX = -Infinity;
  5692. this.maxY = -Infinity;
  5693. };
  5694. /**
  5695. * Can return Rectangle.EMPTY constant, either construct new rectangle, either use your rectangle
  5696. * It is not guaranteed that it will return tempRect
  5697. *
  5698. * @param {PIXI.Rectangle} rect - temporary object will be used if AABB is not empty
  5699. * @returns {PIXI.Rectangle} A rectangle of the bounds
  5700. */
  5701. Bounds.prototype.getRectangle = function getRectangle (rect)
  5702. {
  5703. if (this.minX > this.maxX || this.minY > this.maxY)
  5704. {
  5705. return Rectangle.EMPTY;
  5706. }
  5707. rect = rect || new Rectangle(0, 0, 1, 1);
  5708. rect.x = this.minX;
  5709. rect.y = this.minY;
  5710. rect.width = this.maxX - this.minX;
  5711. rect.height = this.maxY - this.minY;
  5712. return rect;
  5713. };
  5714. /**
  5715. * This function should be inlined when its possible.
  5716. *
  5717. * @param {PIXI.Point} point - The point to add.
  5718. */
  5719. Bounds.prototype.addPoint = function addPoint (point)
  5720. {
  5721. this.minX = Math.min(this.minX, point.x);
  5722. this.maxX = Math.max(this.maxX, point.x);
  5723. this.minY = Math.min(this.minY, point.y);
  5724. this.maxY = Math.max(this.maxY, point.y);
  5725. };
  5726. /**
  5727. * Adds a quad, not transformed
  5728. *
  5729. * @param {Float32Array} vertices - The verts to add.
  5730. */
  5731. Bounds.prototype.addQuad = function addQuad (vertices)
  5732. {
  5733. var minX = this.minX;
  5734. var minY = this.minY;
  5735. var maxX = this.maxX;
  5736. var maxY = this.maxY;
  5737. var x = vertices[0];
  5738. var y = vertices[1];
  5739. minX = x < minX ? x : minX;
  5740. minY = y < minY ? y : minY;
  5741. maxX = x > maxX ? x : maxX;
  5742. maxY = y > maxY ? y : maxY;
  5743. x = vertices[2];
  5744. y = vertices[3];
  5745. minX = x < minX ? x : minX;
  5746. minY = y < minY ? y : minY;
  5747. maxX = x > maxX ? x : maxX;
  5748. maxY = y > maxY ? y : maxY;
  5749. x = vertices[4];
  5750. y = vertices[5];
  5751. minX = x < minX ? x : minX;
  5752. minY = y < minY ? y : minY;
  5753. maxX = x > maxX ? x : maxX;
  5754. maxY = y > maxY ? y : maxY;
  5755. x = vertices[6];
  5756. y = vertices[7];
  5757. minX = x < minX ? x : minX;
  5758. minY = y < minY ? y : minY;
  5759. maxX = x > maxX ? x : maxX;
  5760. maxY = y > maxY ? y : maxY;
  5761. this.minX = minX;
  5762. this.minY = minY;
  5763. this.maxX = maxX;
  5764. this.maxY = maxY;
  5765. };
  5766. /**
  5767. * Adds sprite frame, transformed.
  5768. *
  5769. * @param {PIXI.Transform} transform - TODO
  5770. * @param {number} x0 - TODO
  5771. * @param {number} y0 - TODO
  5772. * @param {number} x1 - TODO
  5773. * @param {number} y1 - TODO
  5774. */
  5775. Bounds.prototype.addFrame = function addFrame (transform, x0, y0, x1, y1)
  5776. {
  5777. var matrix = transform.worldTransform;
  5778. var a = matrix.a;
  5779. var b = matrix.b;
  5780. var c = matrix.c;
  5781. var d = matrix.d;
  5782. var tx = matrix.tx;
  5783. var ty = matrix.ty;
  5784. var minX = this.minX;
  5785. var minY = this.minY;
  5786. var maxX = this.maxX;
  5787. var maxY = this.maxY;
  5788. var x = (a * x0) + (c * y0) + tx;
  5789. var y = (b * x0) + (d * y0) + ty;
  5790. minX = x < minX ? x : minX;
  5791. minY = y < minY ? y : minY;
  5792. maxX = x > maxX ? x : maxX;
  5793. maxY = y > maxY ? y : maxY;
  5794. x = (a * x1) + (c * y0) + tx;
  5795. y = (b * x1) + (d * y0) + ty;
  5796. minX = x < minX ? x : minX;
  5797. minY = y < minY ? y : minY;
  5798. maxX = x > maxX ? x : maxX;
  5799. maxY = y > maxY ? y : maxY;
  5800. x = (a * x0) + (c * y1) + tx;
  5801. y = (b * x0) + (d * y1) + ty;
  5802. minX = x < minX ? x : minX;
  5803. minY = y < minY ? y : minY;
  5804. maxX = x > maxX ? x : maxX;
  5805. maxY = y > maxY ? y : maxY;
  5806. x = (a * x1) + (c * y1) + tx;
  5807. y = (b * x1) + (d * y1) + ty;
  5808. minX = x < minX ? x : minX;
  5809. minY = y < minY ? y : minY;
  5810. maxX = x > maxX ? x : maxX;
  5811. maxY = y > maxY ? y : maxY;
  5812. this.minX = minX;
  5813. this.minY = minY;
  5814. this.maxX = maxX;
  5815. this.maxY = maxY;
  5816. };
  5817. /**
  5818. * Adds screen vertices from array
  5819. *
  5820. * @param {Float32Array} vertexData - calculated vertices
  5821. * @param {number} beginOffset - begin offset
  5822. * @param {number} endOffset - end offset, excluded
  5823. */
  5824. Bounds.prototype.addVertexData = function addVertexData (vertexData, beginOffset, endOffset)
  5825. {
  5826. var minX = this.minX;
  5827. var minY = this.minY;
  5828. var maxX = this.maxX;
  5829. var maxY = this.maxY;
  5830. for (var i = beginOffset; i < endOffset; i += 2)
  5831. {
  5832. var x = vertexData[i];
  5833. var y = vertexData[i + 1];
  5834. minX = x < minX ? x : minX;
  5835. minY = y < minY ? y : minY;
  5836. maxX = x > maxX ? x : maxX;
  5837. maxY = y > maxY ? y : maxY;
  5838. }
  5839. this.minX = minX;
  5840. this.minY = minY;
  5841. this.maxX = maxX;
  5842. this.maxY = maxY;
  5843. };
  5844. /**
  5845. * Add an array of mesh vertices
  5846. *
  5847. * @param {PIXI.Transform} transform - mesh transform
  5848. * @param {Float32Array} vertices - mesh coordinates in array
  5849. * @param {number} beginOffset - begin offset
  5850. * @param {number} endOffset - end offset, excluded
  5851. */
  5852. Bounds.prototype.addVertices = function addVertices (transform, vertices, beginOffset, endOffset)
  5853. {
  5854. var matrix = transform.worldTransform;
  5855. var a = matrix.a;
  5856. var b = matrix.b;
  5857. var c = matrix.c;
  5858. var d = matrix.d;
  5859. var tx = matrix.tx;
  5860. var ty = matrix.ty;
  5861. var minX = this.minX;
  5862. var minY = this.minY;
  5863. var maxX = this.maxX;
  5864. var maxY = this.maxY;
  5865. for (var i = beginOffset; i < endOffset; i += 2)
  5866. {
  5867. var rawX = vertices[i];
  5868. var rawY = vertices[i + 1];
  5869. var x = (a * rawX) + (c * rawY) + tx;
  5870. var y = (d * rawY) + (b * rawX) + ty;
  5871. minX = x < minX ? x : minX;
  5872. minY = y < minY ? y : minY;
  5873. maxX = x > maxX ? x : maxX;
  5874. maxY = y > maxY ? y : maxY;
  5875. }
  5876. this.minX = minX;
  5877. this.minY = minY;
  5878. this.maxX = maxX;
  5879. this.maxY = maxY;
  5880. };
  5881. /**
  5882. * Adds other Bounds
  5883. *
  5884. * @param {PIXI.Bounds} bounds - TODO
  5885. */
  5886. Bounds.prototype.addBounds = function addBounds (bounds)
  5887. {
  5888. var minX = this.minX;
  5889. var minY = this.minY;
  5890. var maxX = this.maxX;
  5891. var maxY = this.maxY;
  5892. this.minX = bounds.minX < minX ? bounds.minX : minX;
  5893. this.minY = bounds.minY < minY ? bounds.minY : minY;
  5894. this.maxX = bounds.maxX > maxX ? bounds.maxX : maxX;
  5895. this.maxY = bounds.maxY > maxY ? bounds.maxY : maxY;
  5896. };
  5897. /**
  5898. * Adds other Bounds, masked with Bounds
  5899. *
  5900. * @param {PIXI.Bounds} bounds - TODO
  5901. * @param {PIXI.Bounds} mask - TODO
  5902. */
  5903. Bounds.prototype.addBoundsMask = function addBoundsMask (bounds, mask)
  5904. {
  5905. var _minX = bounds.minX > mask.minX ? bounds.minX : mask.minX;
  5906. var _minY = bounds.minY > mask.minY ? bounds.minY : mask.minY;
  5907. var _maxX = bounds.maxX < mask.maxX ? bounds.maxX : mask.maxX;
  5908. var _maxY = bounds.maxY < mask.maxY ? bounds.maxY : mask.maxY;
  5909. if (_minX <= _maxX && _minY <= _maxY)
  5910. {
  5911. var minX = this.minX;
  5912. var minY = this.minY;
  5913. var maxX = this.maxX;
  5914. var maxY = this.maxY;
  5915. this.minX = _minX < minX ? _minX : minX;
  5916. this.minY = _minY < minY ? _minY : minY;
  5917. this.maxX = _maxX > maxX ? _maxX : maxX;
  5918. this.maxY = _maxY > maxY ? _maxY : maxY;
  5919. }
  5920. };
  5921. /**
  5922. * Adds other Bounds, masked with Rectangle
  5923. *
  5924. * @param {PIXI.Bounds} bounds - TODO
  5925. * @param {PIXI.Rectangle} area - TODO
  5926. */
  5927. Bounds.prototype.addBoundsArea = function addBoundsArea (bounds, area)
  5928. {
  5929. var _minX = bounds.minX > area.x ? bounds.minX : area.x;
  5930. var _minY = bounds.minY > area.y ? bounds.minY : area.y;
  5931. var _maxX = bounds.maxX < area.x + area.width ? bounds.maxX : (area.x + area.width);
  5932. var _maxY = bounds.maxY < area.y + area.height ? bounds.maxY : (area.y + area.height);
  5933. if (_minX <= _maxX && _minY <= _maxY)
  5934. {
  5935. var minX = this.minX;
  5936. var minY = this.minY;
  5937. var maxX = this.maxX;
  5938. var maxY = this.maxY;
  5939. this.minX = _minX < minX ? _minX : minX;
  5940. this.minY = _minY < minY ? _minY : minY;
  5941. this.maxX = _maxX > maxX ? _maxX : maxX;
  5942. this.maxY = _maxY > maxY ? _maxY : maxY;
  5943. }
  5944. };
  5945. // _tempDisplayObjectParent = new DisplayObject();
  5946. /**
  5947. * The base class for all objects that are rendered on the screen.
  5948. *
  5949. * This is an abstract class and should not be used on its own; rather it should be extended.
  5950. *
  5951. * @class
  5952. * @extends PIXI.utils.EventEmitter
  5953. * @memberof PIXI
  5954. */
  5955. var DisplayObject = /*@__PURE__*/(function (EventEmitter) {
  5956. function DisplayObject()
  5957. {
  5958. EventEmitter.call(this);
  5959. this.tempDisplayObjectParent = null;
  5960. // TODO: need to create Transform from factory
  5961. /**
  5962. * World transform and local transform of this object.
  5963. * This will become read-only later, please do not assign anything there unless you know what are you doing.
  5964. *
  5965. * @member {PIXI.Transform}
  5966. */
  5967. this.transform = new Transform();
  5968. /**
  5969. * The opacity of the object.
  5970. *
  5971. * @member {number}
  5972. */
  5973. this.alpha = 1;
  5974. /**
  5975. * The visibility of the object. If false the object will not be drawn, and
  5976. * the updateTransform function will not be called.
  5977. *
  5978. * Only affects recursive calls from parent. You can ask for bounds or call updateTransform manually.
  5979. *
  5980. * @member {boolean}
  5981. */
  5982. this.visible = true;
  5983. /**
  5984. * Can this object be rendered, if false the object will not be drawn but the updateTransform
  5985. * methods will still be called.
  5986. *
  5987. * Only affects recursive calls from parent. You can ask for bounds manually.
  5988. *
  5989. * @member {boolean}
  5990. */
  5991. this.renderable = true;
  5992. /**
  5993. * The display object container that contains this display object.
  5994. *
  5995. * @member {PIXI.Container}
  5996. * @readonly
  5997. */
  5998. this.parent = null;
  5999. /**
  6000. * The multiplied alpha of the displayObject.
  6001. *
  6002. * @member {number}
  6003. * @readonly
  6004. */
  6005. this.worldAlpha = 1;
  6006. /**
  6007. * Which index in the children array the display component was before the previous zIndex sort.
  6008. * Used by containers to help sort objects with the same zIndex, by using previous array index as the decider.
  6009. *
  6010. * @member {number}
  6011. * @protected
  6012. */
  6013. this._lastSortedIndex = 0;
  6014. /**
  6015. * The zIndex of the displayObject.
  6016. * A higher value will mean it will be rendered on top of other displayObjects within the same container.
  6017. *
  6018. * @member {number}
  6019. * @protected
  6020. */
  6021. this._zIndex = 0;
  6022. /**
  6023. * The area the filter is applied to. This is used as more of an optimization
  6024. * rather than figuring out the dimensions of the displayObject each frame you can set this rectangle.
  6025. *
  6026. * Also works as an interaction mask.
  6027. *
  6028. * @member {?PIXI.Rectangle}
  6029. */
  6030. this.filterArea = null;
  6031. /**
  6032. * Sets the filters for the displayObject.
  6033. * * IMPORTANT: This is a WebGL only feature and will be ignored by the canvas renderer.
  6034. * To remove filters simply set this property to `'null'`.
  6035. *
  6036. * @member {?PIXI.Filter[]}
  6037. */
  6038. this.filters = null;
  6039. this._enabledFilters = null;
  6040. /**
  6041. * The bounds object, this is used to calculate and store the bounds of the displayObject.
  6042. *
  6043. * @member {PIXI.Bounds}
  6044. * @protected
  6045. */
  6046. this._bounds = new Bounds();
  6047. this._boundsID = 0;
  6048. this._lastBoundsID = -1;
  6049. this._boundsRect = null;
  6050. this._localBoundsRect = null;
  6051. /**
  6052. * The original, cached mask of the object.
  6053. *
  6054. * @member {PIXI.Graphics|PIXI.Sprite}
  6055. * @protected
  6056. */
  6057. this._mask = null;
  6058. /**
  6059. * Fired when this DisplayObject is added to a Container.
  6060. *
  6061. * @event PIXI.DisplayObject#added
  6062. * @param {PIXI.Container} container - The container added to.
  6063. */
  6064. /**
  6065. * Fired when this DisplayObject is removed from a Container.
  6066. *
  6067. * @event PIXI.DisplayObject#removed
  6068. * @param {PIXI.Container} container - The container removed from.
  6069. */
  6070. /**
  6071. * If the object has been destroyed via destroy(). If true, it should not be used.
  6072. *
  6073. * @member {boolean}
  6074. * @protected
  6075. */
  6076. this._destroyed = false;
  6077. /**
  6078. * used to fast check if a sprite is.. a sprite!
  6079. * @member {boolean}
  6080. */
  6081. this.isSprite = false;
  6082. }
  6083. if ( EventEmitter ) { DisplayObject.__proto__ = EventEmitter; }
  6084. DisplayObject.prototype = Object.create( EventEmitter && EventEmitter.prototype );
  6085. DisplayObject.prototype.constructor = DisplayObject;
  6086. var prototypeAccessors = { _tempDisplayObjectParent: { configurable: true },x: { configurable: true },y: { configurable: true },worldTransform: { configurable: true },localTransform: { configurable: true },position: { configurable: true },scale: { configurable: true },pivot: { configurable: true },skew: { configurable: true },rotation: { configurable: true },angle: { configurable: true },zIndex: { configurable: true },worldVisible: { configurable: true },mask: { configurable: true } };
  6087. /**
  6088. * @protected
  6089. * @member {PIXI.DisplayObject}
  6090. */
  6091. DisplayObject.mixin = function mixin (source)
  6092. {
  6093. // in ES8/ES2017, this would be really easy:
  6094. // Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
  6095. // get all the enumerable property keys
  6096. var keys = Object.keys(source);
  6097. // loop through properties
  6098. for (var i = 0; i < keys.length; ++i)
  6099. {
  6100. var propertyName = keys[i];
  6101. // Set the property using the property descriptor - this works for accessors and normal value properties
  6102. Object.defineProperty(
  6103. DisplayObject.prototype,
  6104. propertyName,
  6105. Object.getOwnPropertyDescriptor(source, propertyName)
  6106. );
  6107. }
  6108. };
  6109. prototypeAccessors._tempDisplayObjectParent.get = function ()
  6110. {
  6111. if (this.tempDisplayObjectParent === null)
  6112. {
  6113. this.tempDisplayObjectParent = new DisplayObject();
  6114. }
  6115. return this.tempDisplayObjectParent;
  6116. };
  6117. /**
  6118. * Updates the object transform for rendering.
  6119. *
  6120. * TODO - Optimization pass!
  6121. */
  6122. DisplayObject.prototype.updateTransform = function updateTransform ()
  6123. {
  6124. this.transform.updateTransform(this.parent.transform);
  6125. // multiply the alphas..
  6126. this.worldAlpha = this.alpha * this.parent.worldAlpha;
  6127. this._bounds.updateID++;
  6128. };
  6129. /**
  6130. * Recursively updates transform of all objects from the root to this one
  6131. * internal function for toLocal()
  6132. */
  6133. DisplayObject.prototype._recursivePostUpdateTransform = function _recursivePostUpdateTransform ()
  6134. {
  6135. if (this.parent)
  6136. {
  6137. this.parent._recursivePostUpdateTransform();
  6138. this.transform.updateTransform(this.parent.transform);
  6139. }
  6140. else
  6141. {
  6142. this.transform.updateTransform(this._tempDisplayObjectParent.transform);
  6143. }
  6144. };
  6145. /**
  6146. * Retrieves the bounds of the displayObject as a rectangle object.
  6147. *
  6148. * @param {boolean} [skipUpdate] - Setting to `true` will stop the transforms of the scene graph from
  6149. * being updated. This means the calculation returned MAY be out of date BUT will give you a
  6150. * nice performance boost.
  6151. * @param {PIXI.Rectangle} [rect] - Optional rectangle to store the result of the bounds calculation.
  6152. * @return {PIXI.Rectangle} The rectangular bounding area.
  6153. */
  6154. DisplayObject.prototype.getBounds = function getBounds (skipUpdate, rect)
  6155. {
  6156. if (!skipUpdate)
  6157. {
  6158. if (!this.parent)
  6159. {
  6160. this.parent = this._tempDisplayObjectParent;
  6161. this.updateTransform();
  6162. this.parent = null;
  6163. }
  6164. else
  6165. {
  6166. this._recursivePostUpdateTransform();
  6167. this.updateTransform();
  6168. }
  6169. }
  6170. if (this._boundsID !== this._lastBoundsID)
  6171. {
  6172. this.calculateBounds();
  6173. }
  6174. if (!rect)
  6175. {
  6176. if (!this._boundsRect)
  6177. {
  6178. this._boundsRect = new Rectangle();
  6179. }
  6180. rect = this._boundsRect;
  6181. }
  6182. return this._bounds.getRectangle(rect);
  6183. };
  6184. /**
  6185. * Retrieves the local bounds of the displayObject as a rectangle object.
  6186. *
  6187. * @param {PIXI.Rectangle} [rect] - Optional rectangle to store the result of the bounds calculation.
  6188. * @return {PIXI.Rectangle} The rectangular bounding area.
  6189. */
  6190. DisplayObject.prototype.getLocalBounds = function getLocalBounds (rect)
  6191. {
  6192. var transformRef = this.transform;
  6193. var parentRef = this.parent;
  6194. this.parent = null;
  6195. this.transform = this._tempDisplayObjectParent.transform;
  6196. if (!rect)
  6197. {
  6198. if (!this._localBoundsRect)
  6199. {
  6200. this._localBoundsRect = new Rectangle();
  6201. }
  6202. rect = this._localBoundsRect;
  6203. }
  6204. var bounds = this.getBounds(false, rect);
  6205. this.parent = parentRef;
  6206. this.transform = transformRef;
  6207. return bounds;
  6208. };
  6209. /**
  6210. * Calculates the global position of the display object.
  6211. *
  6212. * @param {PIXI.IPoint} position - The world origin to calculate from.
  6213. * @param {PIXI.IPoint} [point] - A Point object in which to store the value, optional
  6214. * (otherwise will create a new Point).
  6215. * @param {boolean} [skipUpdate=false] - Should we skip the update transform.
  6216. * @return {PIXI.IPoint} A point object representing the position of this object.
  6217. */
  6218. DisplayObject.prototype.toGlobal = function toGlobal (position, point, skipUpdate)
  6219. {
  6220. if ( skipUpdate === void 0 ) { skipUpdate = false; }
  6221. if (!skipUpdate)
  6222. {
  6223. this._recursivePostUpdateTransform();
  6224. // this parent check is for just in case the item is a root object.
  6225. // If it is we need to give it a temporary parent so that displayObjectUpdateTransform works correctly
  6226. // this is mainly to avoid a parent check in the main loop. Every little helps for performance :)
  6227. if (!this.parent)
  6228. {
  6229. this.parent = this._tempDisplayObjectParent;
  6230. this.displayObjectUpdateTransform();
  6231. this.parent = null;
  6232. }
  6233. else
  6234. {
  6235. this.displayObjectUpdateTransform();
  6236. }
  6237. }
  6238. // don't need to update the lot
  6239. return this.worldTransform.apply(position, point);
  6240. };
  6241. /**
  6242. * Calculates the local position of the display object relative to another point.
  6243. *
  6244. * @param {PIXI.IPoint} position - The world origin to calculate from.
  6245. * @param {PIXI.DisplayObject} [from] - The DisplayObject to calculate the global position from.
  6246. * @param {PIXI.IPoint} [point] - A Point object in which to store the value, optional
  6247. * (otherwise will create a new Point).
  6248. * @param {boolean} [skipUpdate=false] - Should we skip the update transform
  6249. * @return {PIXI.IPoint} A point object representing the position of this object
  6250. */
  6251. DisplayObject.prototype.toLocal = function toLocal (position, from, point, skipUpdate)
  6252. {
  6253. if (from)
  6254. {
  6255. position = from.toGlobal(position, point, skipUpdate);
  6256. }
  6257. if (!skipUpdate)
  6258. {
  6259. this._recursivePostUpdateTransform();
  6260. // this parent check is for just in case the item is a root object.
  6261. // If it is we need to give it a temporary parent so that displayObjectUpdateTransform works correctly
  6262. // this is mainly to avoid a parent check in the main loop. Every little helps for performance :)
  6263. if (!this.parent)
  6264. {
  6265. this.parent = this._tempDisplayObjectParent;
  6266. this.displayObjectUpdateTransform();
  6267. this.parent = null;
  6268. }
  6269. else
  6270. {
  6271. this.displayObjectUpdateTransform();
  6272. }
  6273. }
  6274. // simply apply the matrix..
  6275. return this.worldTransform.applyInverse(position, point);
  6276. };
  6277. /**
  6278. * Renders the object using the WebGL renderer.
  6279. *
  6280. * @param {PIXI.Renderer} renderer - The renderer.
  6281. */
  6282. DisplayObject.prototype.render = function render (renderer) // eslint-disable-line no-unused-vars
  6283. {
  6284. // OVERWRITE;
  6285. };
  6286. /**
  6287. * Set the parent Container of this DisplayObject.
  6288. *
  6289. * @param {PIXI.Container} container - The Container to add this DisplayObject to.
  6290. * @return {PIXI.Container} The Container that this DisplayObject was added to.
  6291. */
  6292. DisplayObject.prototype.setParent = function setParent (container)
  6293. {
  6294. if (!container || !container.addChild)
  6295. {
  6296. throw new Error('setParent: Argument must be a Container');
  6297. }
  6298. container.addChild(this);
  6299. return container;
  6300. };
  6301. /**
  6302. * Convenience function to set the position, scale, skew and pivot at once.
  6303. *
  6304. * @param {number} [x=0] - The X position
  6305. * @param {number} [y=0] - The Y position
  6306. * @param {number} [scaleX=1] - The X scale value
  6307. * @param {number} [scaleY=1] - The Y scale value
  6308. * @param {number} [rotation=0] - The rotation
  6309. * @param {number} [skewX=0] - The X skew value
  6310. * @param {number} [skewY=0] - The Y skew value
  6311. * @param {number} [pivotX=0] - The X pivot value
  6312. * @param {number} [pivotY=0] - The Y pivot value
  6313. * @return {PIXI.DisplayObject} The DisplayObject instance
  6314. */
  6315. DisplayObject.prototype.setTransform = function setTransform (x, y, scaleX, scaleY, rotation, skewX, skewY, pivotX, pivotY)
  6316. {
  6317. if ( x === void 0 ) { x = 0; }
  6318. if ( y === void 0 ) { y = 0; }
  6319. if ( scaleX === void 0 ) { scaleX = 1; }
  6320. if ( scaleY === void 0 ) { scaleY = 1; }
  6321. if ( rotation === void 0 ) { rotation = 0; }
  6322. if ( skewX === void 0 ) { skewX = 0; }
  6323. if ( skewY === void 0 ) { skewY = 0; }
  6324. if ( pivotX === void 0 ) { pivotX = 0; }
  6325. if ( pivotY === void 0 ) { pivotY = 0; }
  6326. this.position.x = x;
  6327. this.position.y = y;
  6328. this.scale.x = !scaleX ? 1 : scaleX;
  6329. this.scale.y = !scaleY ? 1 : scaleY;
  6330. this.rotation = rotation;
  6331. this.skew.x = skewX;
  6332. this.skew.y = skewY;
  6333. this.pivot.x = pivotX;
  6334. this.pivot.y = pivotY;
  6335. return this;
  6336. };
  6337. /**
  6338. * Base destroy method for generic display objects. This will automatically
  6339. * remove the display object from its parent Container as well as remove
  6340. * all current event listeners and internal references. Do not use a DisplayObject
  6341. * after calling `destroy()`.
  6342. *
  6343. */
  6344. DisplayObject.prototype.destroy = function destroy ()
  6345. {
  6346. this.removeAllListeners();
  6347. if (this.parent)
  6348. {
  6349. this.parent.removeChild(this);
  6350. }
  6351. this.transform = null;
  6352. this.parent = null;
  6353. this._bounds = null;
  6354. this._currentBounds = null;
  6355. this._mask = null;
  6356. this.filterArea = null;
  6357. this.interactive = false;
  6358. this.interactiveChildren = false;
  6359. this._destroyed = true;
  6360. };
  6361. /**
  6362. * The position of the displayObject on the x axis relative to the local coordinates of the parent.
  6363. * An alias to position.x
  6364. *
  6365. * @member {number}
  6366. */
  6367. prototypeAccessors.x.get = function ()
  6368. {
  6369. return this.position.x;
  6370. };
  6371. prototypeAccessors.x.set = function (value) // eslint-disable-line require-jsdoc
  6372. {
  6373. this.transform.position.x = value;
  6374. };
  6375. /**
  6376. * The position of the displayObject on the y axis relative to the local coordinates of the parent.
  6377. * An alias to position.y
  6378. *
  6379. * @member {number}
  6380. */
  6381. prototypeAccessors.y.get = function ()
  6382. {
  6383. return this.position.y;
  6384. };
  6385. prototypeAccessors.y.set = function (value) // eslint-disable-line require-jsdoc
  6386. {
  6387. this.transform.position.y = value;
  6388. };
  6389. /**
  6390. * Current transform of the object based on world (parent) factors.
  6391. *
  6392. * @member {PIXI.Matrix}
  6393. * @readonly
  6394. */
  6395. prototypeAccessors.worldTransform.get = function ()
  6396. {
  6397. return this.transform.worldTransform;
  6398. };
  6399. /**
  6400. * Current transform of the object based on local factors: position, scale, other stuff.
  6401. *
  6402. * @member {PIXI.Matrix}
  6403. * @readonly
  6404. */
  6405. prototypeAccessors.localTransform.get = function ()
  6406. {
  6407. return this.transform.localTransform;
  6408. };
  6409. /**
  6410. * The coordinate of the object relative to the local coordinates of the parent.
  6411. * Assignment by value since pixi-v4.
  6412. *
  6413. * @member {PIXI.IPoint}
  6414. */
  6415. prototypeAccessors.position.get = function ()
  6416. {
  6417. return this.transform.position;
  6418. };
  6419. prototypeAccessors.position.set = function (value) // eslint-disable-line require-jsdoc
  6420. {
  6421. this.transform.position.copyFrom(value);
  6422. };
  6423. /**
  6424. * The scale factor of the object.
  6425. * Assignment by value since pixi-v4.
  6426. *
  6427. * @member {PIXI.IPoint}
  6428. */
  6429. prototypeAccessors.scale.get = function ()
  6430. {
  6431. return this.transform.scale;
  6432. };
  6433. prototypeAccessors.scale.set = function (value) // eslint-disable-line require-jsdoc
  6434. {
  6435. this.transform.scale.copyFrom(value);
  6436. };
  6437. /**
  6438. * The pivot point of the displayObject that it rotates around.
  6439. * Assignment by value since pixi-v4.
  6440. *
  6441. * @member {PIXI.IPoint}
  6442. */
  6443. prototypeAccessors.pivot.get = function ()
  6444. {
  6445. return this.transform.pivot;
  6446. };
  6447. prototypeAccessors.pivot.set = function (value) // eslint-disable-line require-jsdoc
  6448. {
  6449. this.transform.pivot.copyFrom(value);
  6450. };
  6451. /**
  6452. * The skew factor for the object in radians.
  6453. * Assignment by value since pixi-v4.
  6454. *
  6455. * @member {PIXI.ObservablePoint}
  6456. */
  6457. prototypeAccessors.skew.get = function ()
  6458. {
  6459. return this.transform.skew;
  6460. };
  6461. prototypeAccessors.skew.set = function (value) // eslint-disable-line require-jsdoc
  6462. {
  6463. this.transform.skew.copyFrom(value);
  6464. };
  6465. /**
  6466. * The rotation of the object in radians.
  6467. * 'rotation' and 'angle' have the same effect on a display object; rotation is in radians, angle is in degrees.
  6468. *
  6469. * @member {number}
  6470. */
  6471. prototypeAccessors.rotation.get = function ()
  6472. {
  6473. return this.transform.rotation;
  6474. };
  6475. prototypeAccessors.rotation.set = function (value) // eslint-disable-line require-jsdoc
  6476. {
  6477. this.transform.rotation = value;
  6478. };
  6479. /**
  6480. * The angle of the object in degrees.
  6481. * 'rotation' and 'angle' have the same effect on a display object; rotation is in radians, angle is in degrees.
  6482. *
  6483. * @member {number}
  6484. */
  6485. prototypeAccessors.angle.get = function ()
  6486. {
  6487. return this.transform.rotation * RAD_TO_DEG;
  6488. };
  6489. prototypeAccessors.angle.set = function (value) // eslint-disable-line require-jsdoc
  6490. {
  6491. this.transform.rotation = value * DEG_TO_RAD;
  6492. };
  6493. /**
  6494. * The zIndex of the displayObject.
  6495. * If a container has the sortableChildren property set to true, children will be automatically
  6496. * sorted by zIndex value; a higher value will mean it will be moved towards the end of the array,
  6497. * and thus rendered on top of other displayObjects within the same container.
  6498. *
  6499. * @member {number}
  6500. */
  6501. prototypeAccessors.zIndex.get = function ()
  6502. {
  6503. return this._zIndex;
  6504. };
  6505. prototypeAccessors.zIndex.set = function (value) // eslint-disable-line require-jsdoc
  6506. {
  6507. this._zIndex = value;
  6508. if (this.parent)
  6509. {
  6510. this.parent.sortDirty = true;
  6511. }
  6512. };
  6513. /**
  6514. * Indicates if the object is globally visible.
  6515. *
  6516. * @member {boolean}
  6517. * @readonly
  6518. */
  6519. prototypeAccessors.worldVisible.get = function ()
  6520. {
  6521. var item = this;
  6522. do
  6523. {
  6524. if (!item.visible)
  6525. {
  6526. return false;
  6527. }
  6528. item = item.parent;
  6529. } while (item);
  6530. return true;
  6531. };
  6532. /**
  6533. * Sets a mask for the displayObject. A mask is an object that limits the visibility of an
  6534. * object to the shape of the mask applied to it. In PixiJS a regular mask must be a
  6535. * {@link PIXI.Graphics} or a {@link PIXI.Sprite} object. This allows for much faster masking in canvas as it
  6536. * utilities shape clipping. To remove a mask, set this property to `null`.
  6537. *
  6538. * For sprite mask both alpha and red channel are used. Black mask is the same as transparent mask.
  6539. * @example
  6540. * const graphics = new PIXI.Graphics();
  6541. * graphics.beginFill(0xFF3300);
  6542. * graphics.drawRect(50, 250, 100, 100);
  6543. * graphics.endFill();
  6544. *
  6545. * const sprite = new PIXI.Sprite(texture);
  6546. * sprite.mask = graphics;
  6547. * @todo At the moment, PIXI.CanvasRenderer doesn't support PIXI.Sprite as mask.
  6548. *
  6549. * @member {PIXI.Graphics|PIXI.Sprite}
  6550. */
  6551. prototypeAccessors.mask.get = function ()
  6552. {
  6553. return this._mask;
  6554. };
  6555. prototypeAccessors.mask.set = function (value) // eslint-disable-line require-jsdoc
  6556. {
  6557. if (this._mask)
  6558. {
  6559. this._mask.renderable = true;
  6560. this._mask.isMask = false;
  6561. }
  6562. this._mask = value;
  6563. if (this._mask)
  6564. {
  6565. this._mask.renderable = false;
  6566. this._mask.isMask = true;
  6567. }
  6568. };
  6569. Object.defineProperties( DisplayObject.prototype, prototypeAccessors );
  6570. return DisplayObject;
  6571. }(eventemitter3));
  6572. // performance increase to avoid using call.. (10x faster)
  6573. DisplayObject.prototype.displayObjectUpdateTransform = DisplayObject.prototype.updateTransform;
  6574. function sortChildren(a, b)
  6575. {
  6576. if (a.zIndex === b.zIndex)
  6577. {
  6578. return a._lastSortedIndex - b._lastSortedIndex;
  6579. }
  6580. return a.zIndex - b.zIndex;
  6581. }
  6582. /**
  6583. * A Container represents a collection of display objects.
  6584. *
  6585. * It is the base class of all display objects that act as a container for other objects (like Sprites).
  6586. *
  6587. *```js
  6588. * let container = new PIXI.Container();
  6589. * container.addChild(sprite);
  6590. * ```
  6591. *
  6592. * @class
  6593. * @extends PIXI.DisplayObject
  6594. * @memberof PIXI
  6595. */
  6596. var Container = /*@__PURE__*/(function (DisplayObject) {
  6597. function Container()
  6598. {
  6599. DisplayObject.call(this);
  6600. /**
  6601. * The array of children of this container.
  6602. *
  6603. * @member {PIXI.DisplayObject[]}
  6604. * @readonly
  6605. */
  6606. this.children = [];
  6607. /**
  6608. * If set to true, the container will sort its children by zIndex value
  6609. * when updateTransform() is called, or manually if sortChildren() is called.
  6610. *
  6611. * This actually changes the order of elements in the array, so should be treated
  6612. * as a basic solution that is not performant compared to other solutions,
  6613. * such as @link https://github.com/pixijs/pixi-display
  6614. *
  6615. * Also be aware of that this may not work nicely with the addChildAt() function,
  6616. * as the zIndex sorting may cause the child to automatically sorted to another position.
  6617. *
  6618. * @see PIXI.settings.SORTABLE_CHILDREN
  6619. *
  6620. * @member {boolean}
  6621. */
  6622. this.sortableChildren = settings.SORTABLE_CHILDREN;
  6623. /**
  6624. * Should children be sorted by zIndex at the next updateTransform call.
  6625. * Will get automatically set to true if a new child is added, or if a child's zIndex changes.
  6626. *
  6627. * @member {boolean}
  6628. */
  6629. this.sortDirty = false;
  6630. /**
  6631. * Fired when a DisplayObject is added to this Container.
  6632. *
  6633. * @event PIXI.Container#childAdded
  6634. * @param {PIXI.DisplayObject} child - The child added to the Container.
  6635. * @param {PIXI.Container} container - The container that added the child.
  6636. * @param {number} index - The children's index of the added child.
  6637. */
  6638. /**
  6639. * Fired when a DisplayObject is removed from this Container.
  6640. *
  6641. * @event PIXI.DisplayObject#removedFrom
  6642. * @param {PIXI.DisplayObject} child - The child removed from the Container.
  6643. * @param {PIXI.Container} container - The container that removed removed the child.
  6644. * @param {number} index - The former children's index of the removed child
  6645. */
  6646. }
  6647. if ( DisplayObject ) { Container.__proto__ = DisplayObject; }
  6648. Container.prototype = Object.create( DisplayObject && DisplayObject.prototype );
  6649. Container.prototype.constructor = Container;
  6650. var prototypeAccessors = { width: { configurable: true },height: { configurable: true } };
  6651. /**
  6652. * Overridable method that can be used by Container subclasses whenever the children array is modified
  6653. *
  6654. * @protected
  6655. */
  6656. Container.prototype.onChildrenChange = function onChildrenChange ()
  6657. {
  6658. /* empty */
  6659. };
  6660. /**
  6661. * Adds one or more children to the container.
  6662. *
  6663. * Multiple items can be added like so: `myContainer.addChild(thingOne, thingTwo, thingThree)`
  6664. *
  6665. * @param {...PIXI.DisplayObject} child - The DisplayObject(s) to add to the container
  6666. * @return {PIXI.DisplayObject} The first child that was added.
  6667. */
  6668. Container.prototype.addChild = function addChild (child)
  6669. {
  6670. var arguments$1 = arguments;
  6671. var argumentsLength = arguments.length;
  6672. // if there is only one argument we can bypass looping through the them
  6673. if (argumentsLength > 1)
  6674. {
  6675. // loop through the arguments property and add all children
  6676. // use it the right way (.length and [i]) so that this function can still be optimized by JS runtimes
  6677. for (var i = 0; i < argumentsLength; i++)
  6678. {
  6679. this.addChild(arguments$1[i]);
  6680. }
  6681. }
  6682. else
  6683. {
  6684. // if the child has a parent then lets remove it as PixiJS objects can only exist in one place
  6685. if (child.parent)
  6686. {
  6687. child.parent.removeChild(child);
  6688. }
  6689. child.parent = this;
  6690. this.sortDirty = true;
  6691. // ensure child transform will be recalculated
  6692. child.transform._parentID = -1;
  6693. this.children.push(child);
  6694. // ensure bounds will be recalculated
  6695. this._boundsID++;
  6696. // TODO - lets either do all callbacks or all events.. not both!
  6697. this.onChildrenChange(this.children.length - 1);
  6698. this.emit('childAdded', child, this, this.children.length - 1);
  6699. child.emit('added', this);
  6700. }
  6701. return child;
  6702. };
  6703. /**
  6704. * Adds a child to the container at a specified index. If the index is out of bounds an error will be thrown
  6705. *
  6706. * @param {PIXI.DisplayObject} child - The child to add
  6707. * @param {number} index - The index to place the child in
  6708. * @return {PIXI.DisplayObject} The child that was added.
  6709. */
  6710. Container.prototype.addChildAt = function addChildAt (child, index)
  6711. {
  6712. if (index < 0 || index > this.children.length)
  6713. {
  6714. throw new Error((child + "addChildAt: The index " + index + " supplied is out of bounds " + (this.children.length)));
  6715. }
  6716. if (child.parent)
  6717. {
  6718. child.parent.removeChild(child);
  6719. }
  6720. child.parent = this;
  6721. this.sortDirty = true;
  6722. // ensure child transform will be recalculated
  6723. child.transform._parentID = -1;
  6724. this.children.splice(index, 0, child);
  6725. // ensure bounds will be recalculated
  6726. this._boundsID++;
  6727. // TODO - lets either do all callbacks or all events.. not both!
  6728. this.onChildrenChange(index);
  6729. child.emit('added', this);
  6730. this.emit('childAdded', child, this, index);
  6731. return child;
  6732. };
  6733. /**
  6734. * Swaps the position of 2 Display Objects within this container.
  6735. *
  6736. * @param {PIXI.DisplayObject} child - First display object to swap
  6737. * @param {PIXI.DisplayObject} child2 - Second display object to swap
  6738. */
  6739. Container.prototype.swapChildren = function swapChildren (child, child2)
  6740. {
  6741. if (child === child2)
  6742. {
  6743. return;
  6744. }
  6745. var index1 = this.getChildIndex(child);
  6746. var index2 = this.getChildIndex(child2);
  6747. this.children[index1] = child2;
  6748. this.children[index2] = child;
  6749. this.onChildrenChange(index1 < index2 ? index1 : index2);
  6750. };
  6751. /**
  6752. * Returns the index position of a child DisplayObject instance
  6753. *
  6754. * @param {PIXI.DisplayObject} child - The DisplayObject instance to identify
  6755. * @return {number} The index position of the child display object to identify
  6756. */
  6757. Container.prototype.getChildIndex = function getChildIndex (child)
  6758. {
  6759. var index = this.children.indexOf(child);
  6760. if (index === -1)
  6761. {
  6762. throw new Error('The supplied DisplayObject must be a child of the caller');
  6763. }
  6764. return index;
  6765. };
  6766. /**
  6767. * Changes the position of an existing child in the display object container
  6768. *
  6769. * @param {PIXI.DisplayObject} child - The child DisplayObject instance for which you want to change the index number
  6770. * @param {number} index - The resulting index number for the child display object
  6771. */
  6772. Container.prototype.setChildIndex = function setChildIndex (child, index)
  6773. {
  6774. if (index < 0 || index >= this.children.length)
  6775. {
  6776. throw new Error(("The index " + index + " supplied is out of bounds " + (this.children.length)));
  6777. }
  6778. var currentIndex = this.getChildIndex(child);
  6779. removeItems(this.children, currentIndex, 1); // remove from old position
  6780. this.children.splice(index, 0, child); // add at new position
  6781. this.onChildrenChange(index);
  6782. };
  6783. /**
  6784. * Returns the child at the specified index
  6785. *
  6786. * @param {number} index - The index to get the child at
  6787. * @return {PIXI.DisplayObject} The child at the given index, if any.
  6788. */
  6789. Container.prototype.getChildAt = function getChildAt (index)
  6790. {
  6791. if (index < 0 || index >= this.children.length)
  6792. {
  6793. throw new Error(("getChildAt: Index (" + index + ") does not exist."));
  6794. }
  6795. return this.children[index];
  6796. };
  6797. /**
  6798. * Removes one or more children from the container.
  6799. *
  6800. * @param {...PIXI.DisplayObject} child - The DisplayObject(s) to remove
  6801. * @return {PIXI.DisplayObject} The first child that was removed.
  6802. */
  6803. Container.prototype.removeChild = function removeChild (child)
  6804. {
  6805. var arguments$1 = arguments;
  6806. var argumentsLength = arguments.length;
  6807. // if there is only one argument we can bypass looping through the them
  6808. if (argumentsLength > 1)
  6809. {
  6810. // loop through the arguments property and add all children
  6811. // use it the right way (.length and [i]) so that this function can still be optimized by JS runtimes
  6812. for (var i = 0; i < argumentsLength; i++)
  6813. {
  6814. this.removeChild(arguments$1[i]);
  6815. }
  6816. }
  6817. else
  6818. {
  6819. var index = this.children.indexOf(child);
  6820. if (index === -1) { return null; }
  6821. child.parent = null;
  6822. // ensure child transform will be recalculated
  6823. child.transform._parentID = -1;
  6824. removeItems(this.children, index, 1);
  6825. // ensure bounds will be recalculated
  6826. this._boundsID++;
  6827. // TODO - lets either do all callbacks or all events.. not both!
  6828. this.onChildrenChange(index);
  6829. child.emit('removed', this);
  6830. this.emit('childRemoved', child, this, index);
  6831. }
  6832. return child;
  6833. };
  6834. /**
  6835. * Removes a child from the specified index position.
  6836. *
  6837. * @param {number} index - The index to get the child from
  6838. * @return {PIXI.DisplayObject} The child that was removed.
  6839. */
  6840. Container.prototype.removeChildAt = function removeChildAt (index)
  6841. {
  6842. var child = this.getChildAt(index);
  6843. // ensure child transform will be recalculated..
  6844. child.parent = null;
  6845. child.transform._parentID = -1;
  6846. removeItems(this.children, index, 1);
  6847. // ensure bounds will be recalculated
  6848. this._boundsID++;
  6849. // TODO - lets either do all callbacks or all events.. not both!
  6850. this.onChildrenChange(index);
  6851. child.emit('removed', this);
  6852. this.emit('childRemoved', child, this, index);
  6853. return child;
  6854. };
  6855. /**
  6856. * Removes all children from this container that are within the begin and end indexes.
  6857. *
  6858. * @param {number} [beginIndex=0] - The beginning position.
  6859. * @param {number} [endIndex=this.children.length] - The ending position. Default value is size of the container.
  6860. * @returns {PIXI.DisplayObject[]} List of removed children
  6861. */
  6862. Container.prototype.removeChildren = function removeChildren (beginIndex, endIndex)
  6863. {
  6864. if ( beginIndex === void 0 ) { beginIndex = 0; }
  6865. var begin = beginIndex;
  6866. var end = typeof endIndex === 'number' ? endIndex : this.children.length;
  6867. var range = end - begin;
  6868. var removed;
  6869. if (range > 0 && range <= end)
  6870. {
  6871. removed = this.children.splice(begin, range);
  6872. for (var i = 0; i < removed.length; ++i)
  6873. {
  6874. removed[i].parent = null;
  6875. if (removed[i].transform)
  6876. {
  6877. removed[i].transform._parentID = -1;
  6878. }
  6879. }
  6880. this._boundsID++;
  6881. this.onChildrenChange(beginIndex);
  6882. for (var i$1 = 0; i$1 < removed.length; ++i$1)
  6883. {
  6884. removed[i$1].emit('removed', this);
  6885. this.emit('childRemoved', removed[i$1], this, i$1);
  6886. }
  6887. return removed;
  6888. }
  6889. else if (range === 0 && this.children.length === 0)
  6890. {
  6891. return [];
  6892. }
  6893. throw new RangeError('removeChildren: numeric values are outside the acceptable range.');
  6894. };
  6895. /**
  6896. * Sorts children by zIndex. Previous order is mantained for 2 children with the same zIndex.
  6897. */
  6898. Container.prototype.sortChildren = function sortChildren$1 ()
  6899. {
  6900. var sortRequired = false;
  6901. for (var i = 0, j = this.children.length; i < j; ++i)
  6902. {
  6903. var child = this.children[i];
  6904. child._lastSortedIndex = i;
  6905. if (!sortRequired && child.zIndex !== 0)
  6906. {
  6907. sortRequired = true;
  6908. }
  6909. }
  6910. if (sortRequired && this.children.length > 1)
  6911. {
  6912. this.children.sort(sortChildren);
  6913. }
  6914. this.sortDirty = false;
  6915. };
  6916. /**
  6917. * Updates the transform on all children of this container for rendering
  6918. */
  6919. Container.prototype.updateTransform = function updateTransform ()
  6920. {
  6921. if (this.sortableChildren && this.sortDirty)
  6922. {
  6923. this.sortChildren();
  6924. }
  6925. this._boundsID++;
  6926. this.transform.updateTransform(this.parent.transform);
  6927. // TODO: check render flags, how to process stuff here
  6928. this.worldAlpha = this.alpha * this.parent.worldAlpha;
  6929. for (var i = 0, j = this.children.length; i < j; ++i)
  6930. {
  6931. var child = this.children[i];
  6932. if (child.visible)
  6933. {
  6934. child.updateTransform();
  6935. }
  6936. }
  6937. };
  6938. /**
  6939. * Recalculates the bounds of the container.
  6940. *
  6941. */
  6942. Container.prototype.calculateBounds = function calculateBounds ()
  6943. {
  6944. this._bounds.clear();
  6945. this._calculateBounds();
  6946. for (var i = 0; i < this.children.length; i++)
  6947. {
  6948. var child = this.children[i];
  6949. if (!child.visible || !child.renderable)
  6950. {
  6951. continue;
  6952. }
  6953. child.calculateBounds();
  6954. // TODO: filter+mask, need to mask both somehow
  6955. if (child._mask)
  6956. {
  6957. child._mask.calculateBounds();
  6958. this._bounds.addBoundsMask(child._bounds, child._mask._bounds);
  6959. }
  6960. else if (child.filterArea)
  6961. {
  6962. this._bounds.addBoundsArea(child._bounds, child.filterArea);
  6963. }
  6964. else
  6965. {
  6966. this._bounds.addBounds(child._bounds);
  6967. }
  6968. }
  6969. this._lastBoundsID = this._boundsID;
  6970. };
  6971. /**
  6972. * Recalculates the bounds of the object. Override this to
  6973. * calculate the bounds of the specific object (not including children).
  6974. *
  6975. * @protected
  6976. */
  6977. Container.prototype._calculateBounds = function _calculateBounds ()
  6978. {
  6979. // FILL IN//
  6980. };
  6981. /**
  6982. * Renders the object using the WebGL renderer
  6983. *
  6984. * @param {PIXI.Renderer} renderer - The renderer
  6985. */
  6986. Container.prototype.render = function render (renderer)
  6987. {
  6988. // if the object is not visible or the alpha is 0 then no need to render this element
  6989. if (!this.visible || this.worldAlpha <= 0 || !this.renderable)
  6990. {
  6991. return;
  6992. }
  6993. // do a quick check to see if this element has a mask or a filter.
  6994. if (this._mask || this.filters)
  6995. {
  6996. this.renderAdvanced(renderer);
  6997. }
  6998. else
  6999. {
  7000. this._render(renderer);
  7001. // simple render children!
  7002. for (var i = 0, j = this.children.length; i < j; ++i)
  7003. {
  7004. this.children[i].render(renderer);
  7005. }
  7006. }
  7007. };
  7008. /**
  7009. * Render the object using the WebGL renderer and advanced features.
  7010. *
  7011. * @protected
  7012. * @param {PIXI.Renderer} renderer - The renderer
  7013. */
  7014. Container.prototype.renderAdvanced = function renderAdvanced (renderer)
  7015. {
  7016. renderer.batch.flush();
  7017. var filters = this.filters;
  7018. var mask = this._mask;
  7019. // push filter first as we need to ensure the stencil buffer is correct for any masking
  7020. if (filters)
  7021. {
  7022. if (!this._enabledFilters)
  7023. {
  7024. this._enabledFilters = [];
  7025. }
  7026. this._enabledFilters.length = 0;
  7027. for (var i = 0; i < filters.length; i++)
  7028. {
  7029. if (filters[i].enabled)
  7030. {
  7031. this._enabledFilters.push(filters[i]);
  7032. }
  7033. }
  7034. if (this._enabledFilters.length)
  7035. {
  7036. renderer.filter.push(this, this._enabledFilters);
  7037. }
  7038. }
  7039. if (mask)
  7040. {
  7041. renderer.mask.push(this, this._mask);
  7042. }
  7043. // add this object to the batch, only rendered if it has a texture.
  7044. this._render(renderer);
  7045. // now loop through the children and make sure they get rendered
  7046. for (var i$1 = 0, j = this.children.length; i$1 < j; i$1++)
  7047. {
  7048. this.children[i$1].render(renderer);
  7049. }
  7050. renderer.batch.flush();
  7051. if (mask)
  7052. {
  7053. renderer.mask.pop(this, this._mask);
  7054. }
  7055. if (filters && this._enabledFilters && this._enabledFilters.length)
  7056. {
  7057. renderer.filter.pop();
  7058. }
  7059. };
  7060. /**
  7061. * To be overridden by the subclasses.
  7062. *
  7063. * @protected
  7064. * @param {PIXI.Renderer} renderer - The renderer
  7065. */
  7066. Container.prototype._render = function _render (renderer) // eslint-disable-line no-unused-vars
  7067. {
  7068. // this is where content itself gets rendered...
  7069. };
  7070. /**
  7071. * Removes all internal references and listeners as well as removes children from the display list.
  7072. * Do not use a Container after calling `destroy`.
  7073. *
  7074. * @param {object|boolean} [options] - Options parameter. A boolean will act as if all options
  7075. * have been set to that value
  7076. * @param {boolean} [options.children=false] - if set to true, all the children will have their destroy
  7077. * method called as well. 'options' will be passed on to those calls.
  7078. * @param {boolean} [options.texture=false] - Only used for child Sprites if options.children is set to true
  7079. * Should it destroy the texture of the child sprite
  7080. * @param {boolean} [options.baseTexture=false] - Only used for child Sprites if options.children is set to true
  7081. * Should it destroy the base texture of the child sprite
  7082. */
  7083. Container.prototype.destroy = function destroy (options)
  7084. {
  7085. DisplayObject.prototype.destroy.call(this);
  7086. this.sortDirty = false;
  7087. var destroyChildren = typeof options === 'boolean' ? options : options && options.children;
  7088. var oldChildren = this.removeChildren(0, this.children.length);
  7089. if (destroyChildren)
  7090. {
  7091. for (var i = 0; i < oldChildren.length; ++i)
  7092. {
  7093. oldChildren[i].destroy(options);
  7094. }
  7095. }
  7096. };
  7097. /**
  7098. * The width of the Container, setting this will actually modify the scale to achieve the value set
  7099. *
  7100. * @member {number}
  7101. */
  7102. prototypeAccessors.width.get = function ()
  7103. {
  7104. return this.scale.x * this.getLocalBounds().width;
  7105. };
  7106. prototypeAccessors.width.set = function (value) // eslint-disable-line require-jsdoc
  7107. {
  7108. var width = this.getLocalBounds().width;
  7109. if (width !== 0)
  7110. {
  7111. this.scale.x = value / width;
  7112. }
  7113. else
  7114. {
  7115. this.scale.x = 1;
  7116. }
  7117. this._width = value;
  7118. };
  7119. /**
  7120. * The height of the Container, setting this will actually modify the scale to achieve the value set
  7121. *
  7122. * @member {number}
  7123. */
  7124. prototypeAccessors.height.get = function ()
  7125. {
  7126. return this.scale.y * this.getLocalBounds().height;
  7127. };
  7128. prototypeAccessors.height.set = function (value) // eslint-disable-line require-jsdoc
  7129. {
  7130. var height = this.getLocalBounds().height;
  7131. if (height !== 0)
  7132. {
  7133. this.scale.y = value / height;
  7134. }
  7135. else
  7136. {
  7137. this.scale.y = 1;
  7138. }
  7139. this._height = value;
  7140. };
  7141. Object.defineProperties( Container.prototype, prototypeAccessors );
  7142. return Container;
  7143. }(DisplayObject));
  7144. // performance increase to avoid using call.. (10x faster)
  7145. Container.prototype.containerUpdateTransform = Container.prototype.updateTransform;
  7146. /*!
  7147. * @pixi/accessibility - v5.0.4
  7148. * Compiled Fri, 07 Jun 2019 17:17:49 UTC
  7149. *
  7150. * @pixi/accessibility is licensed under the MIT License.
  7151. * http://www.opensource.org/licenses/mit-license
  7152. */
  7153. /**
  7154. * Default property values of accessible objects
  7155. * used by {@link PIXI.accessibility.AccessibilityManager}.
  7156. *
  7157. * @private
  7158. * @function accessibleTarget
  7159. * @memberof PIXI.accessibility
  7160. * @type {Object}
  7161. * @example
  7162. * function MyObject() {}
  7163. *
  7164. * Object.assign(
  7165. * MyObject.prototype,
  7166. * PIXI.accessibility.accessibleTarget
  7167. * );
  7168. */
  7169. var accessibleTarget = {
  7170. /**
  7171. * Flag for if the object is accessible. If true AccessibilityManager will overlay a
  7172. * shadow div with attributes set
  7173. *
  7174. * @member {boolean}
  7175. * @memberof PIXI.DisplayObject#
  7176. */
  7177. accessible: false,
  7178. /**
  7179. * Sets the title attribute of the shadow div
  7180. * If accessibleTitle AND accessibleHint has not been this will default to 'displayObject [tabIndex]'
  7181. *
  7182. * @member {?string}
  7183. * @memberof PIXI.DisplayObject#
  7184. */
  7185. accessibleTitle: null,
  7186. /**
  7187. * Sets the aria-label attribute of the shadow div
  7188. *
  7189. * @member {string}
  7190. * @memberof PIXI.DisplayObject#
  7191. */
  7192. accessibleHint: null,
  7193. /**
  7194. * @member {number}
  7195. * @memberof PIXI.DisplayObject#
  7196. * @private
  7197. * @todo Needs docs.
  7198. */
  7199. tabIndex: 0,
  7200. /**
  7201. * @member {boolean}
  7202. * @memberof PIXI.DisplayObject#
  7203. * @todo Needs docs.
  7204. */
  7205. _accessibleActive: false,
  7206. /**
  7207. * @member {boolean}
  7208. * @memberof PIXI.DisplayObject#
  7209. * @todo Needs docs.
  7210. */
  7211. _accessibleDiv: false,
  7212. };
  7213. // add some extra variables to the container..
  7214. DisplayObject.mixin(accessibleTarget);
  7215. var KEY_CODE_TAB = 9;
  7216. var DIV_TOUCH_SIZE = 100;
  7217. var DIV_TOUCH_POS_X = 0;
  7218. var DIV_TOUCH_POS_Y = 0;
  7219. var DIV_TOUCH_ZINDEX = 2;
  7220. var DIV_HOOK_SIZE = 1;
  7221. var DIV_HOOK_POS_X = -1000;
  7222. var DIV_HOOK_POS_Y = -1000;
  7223. var DIV_HOOK_ZINDEX = 2;
  7224. /**
  7225. * The Accessibility manager recreates the ability to tab and have content read by screen readers.
  7226. * This is very important as it can possibly help people with disabilities access PixiJS content.
  7227. *
  7228. * A DisplayObject can be made accessible just like it can be made interactive. This manager will map the
  7229. * events as if the mouse was being used, minimizing the effort required to implement.
  7230. *
  7231. * An instance of this class is automatically created by default, and can be found at `renderer.plugins.accessibility`
  7232. *
  7233. * @class
  7234. * @memberof PIXI.accessibility
  7235. */
  7236. var AccessibilityManager = function AccessibilityManager(renderer)
  7237. {
  7238. /**
  7239. * @type {?HTMLElement}
  7240. * @private
  7241. */
  7242. this._hookDiv = null;
  7243. if (isMobile_min.tablet || isMobile_min.phone)
  7244. {
  7245. this.createTouchHook();
  7246. }
  7247. // first we create a div that will sit over the PixiJS element. This is where the div overlays will go.
  7248. var div = document.createElement('div');
  7249. div.style.width = DIV_TOUCH_SIZE + "px";
  7250. div.style.height = DIV_TOUCH_SIZE + "px";
  7251. div.style.position = 'absolute';
  7252. div.style.top = DIV_TOUCH_POS_X + "px";
  7253. div.style.left = DIV_TOUCH_POS_Y + "px";
  7254. div.style.zIndex = DIV_TOUCH_ZINDEX;
  7255. /**
  7256. * This is the dom element that will sit over the PixiJS element. This is where the div overlays will go.
  7257. *
  7258. * @type {HTMLElement}
  7259. * @private
  7260. */
  7261. this.div = div;
  7262. /**
  7263. * A simple pool for storing divs.
  7264. *
  7265. * @type {*}
  7266. * @private
  7267. */
  7268. this.pool = [];
  7269. /**
  7270. * This is a tick used to check if an object is no longer being rendered.
  7271. *
  7272. * @type {Number}
  7273. * @private
  7274. */
  7275. this.renderId = 0;
  7276. /**
  7277. * Setting this to true will visually show the divs.
  7278. *
  7279. * @type {boolean}
  7280. */
  7281. this.debug = false;
  7282. /**
  7283. * The renderer this accessibility manager works for.
  7284. *
  7285. * @member {PIXI.AbstractRenderer}
  7286. */
  7287. this.renderer = renderer;
  7288. /**
  7289. * The array of currently active accessible items.
  7290. *
  7291. * @member {Array<*>}
  7292. * @private
  7293. */
  7294. this.children = [];
  7295. /**
  7296. * pre-bind the functions
  7297. *
  7298. * @type {Function}
  7299. * @private
  7300. */
  7301. this._onKeyDown = this._onKeyDown.bind(this);
  7302. /**
  7303. * pre-bind the functions
  7304. *
  7305. * @type {Function}
  7306. * @private
  7307. */
  7308. this._onMouseMove = this._onMouseMove.bind(this);
  7309. /**
  7310. * A flag
  7311. * @type {boolean}
  7312. * @readonly
  7313. */
  7314. this.isActive = false;
  7315. /**
  7316. * A flag
  7317. * @type {boolean}
  7318. * @readonly
  7319. */
  7320. this.isMobileAccessibility = false;
  7321. // let listen for tab.. once pressed we can fire up and show the accessibility layer
  7322. window.addEventListener('keydown', this._onKeyDown, false);
  7323. };
  7324. /**
  7325. * Creates the touch hooks.
  7326. *
  7327. * @private
  7328. */
  7329. AccessibilityManager.prototype.createTouchHook = function createTouchHook ()
  7330. {
  7331. var this$1 = this;
  7332. var hookDiv = document.createElement('button');
  7333. hookDiv.style.width = DIV_HOOK_SIZE + "px";
  7334. hookDiv.style.height = DIV_HOOK_SIZE + "px";
  7335. hookDiv.style.position = 'absolute';
  7336. hookDiv.style.top = DIV_HOOK_POS_X + "px";
  7337. hookDiv.style.left = DIV_HOOK_POS_Y + "px";
  7338. hookDiv.style.zIndex = DIV_HOOK_ZINDEX;
  7339. hookDiv.style.backgroundColor = '#FF0000';
  7340. hookDiv.title = 'HOOK DIV';
  7341. hookDiv.addEventListener('focus', function () {
  7342. this$1.isMobileAccessibility = true;
  7343. this$1.activate();
  7344. this$1.destroyTouchHook();
  7345. });
  7346. document.body.appendChild(hookDiv);
  7347. this._hookDiv = hookDiv;
  7348. };
  7349. /**
  7350. * Destroys the touch hooks.
  7351. *
  7352. * @private
  7353. */
  7354. AccessibilityManager.prototype.destroyTouchHook = function destroyTouchHook ()
  7355. {
  7356. if (!this._hookDiv)
  7357. {
  7358. return;
  7359. }
  7360. document.body.removeChild(this._hookDiv);
  7361. this._hookDiv = null;
  7362. };
  7363. /**
  7364. * Activating will cause the Accessibility layer to be shown.
  7365. * This is called when a user presses the tab key.
  7366. *
  7367. * @private
  7368. */
  7369. AccessibilityManager.prototype.activate = function activate ()
  7370. {
  7371. if (this.isActive)
  7372. {
  7373. return;
  7374. }
  7375. this.isActive = true;
  7376. window.document.addEventListener('mousemove', this._onMouseMove, true);
  7377. window.removeEventListener('keydown', this._onKeyDown, false);
  7378. this.renderer.on('postrender', this.update, this);
  7379. if (this.renderer.view.parentNode)
  7380. {
  7381. this.renderer.view.parentNode.appendChild(this.div);
  7382. }
  7383. };
  7384. /**
  7385. * Deactivating will cause the Accessibility layer to be hidden.
  7386. * This is called when a user moves the mouse.
  7387. *
  7388. * @private
  7389. */
  7390. AccessibilityManager.prototype.deactivate = function deactivate ()
  7391. {
  7392. if (!this.isActive || this.isMobileAccessibility)
  7393. {
  7394. return;
  7395. }
  7396. this.isActive = false;
  7397. window.document.removeEventListener('mousemove', this._onMouseMove, true);
  7398. window.addEventListener('keydown', this._onKeyDown, false);
  7399. this.renderer.off('postrender', this.update);
  7400. if (this.div.parentNode)
  7401. {
  7402. this.div.parentNode.removeChild(this.div);
  7403. }
  7404. };
  7405. /**
  7406. * This recursive function will run through the scene graph and add any new accessible objects to the DOM layer.
  7407. *
  7408. * @private
  7409. * @param {PIXI.Container} displayObject - The DisplayObject to check.
  7410. */
  7411. AccessibilityManager.prototype.updateAccessibleObjects = function updateAccessibleObjects (displayObject)
  7412. {
  7413. if (!displayObject.visible)
  7414. {
  7415. return;
  7416. }
  7417. if (displayObject.accessible && displayObject.interactive)
  7418. {
  7419. if (!displayObject._accessibleActive)
  7420. {
  7421. this.addChild(displayObject);
  7422. }
  7423. displayObject.renderId = this.renderId;
  7424. }
  7425. var children = displayObject.children;
  7426. for (var i = 0; i < children.length; i++)
  7427. {
  7428. this.updateAccessibleObjects(children[i]);
  7429. }
  7430. };
  7431. /**
  7432. * Before each render this function will ensure that all divs are mapped correctly to their DisplayObjects.
  7433. *
  7434. * @private
  7435. */
  7436. AccessibilityManager.prototype.update = function update ()
  7437. {
  7438. if (!this.renderer.renderingToScreen)
  7439. {
  7440. return;
  7441. }
  7442. // update children...
  7443. this.updateAccessibleObjects(this.renderer._lastObjectRendered);
  7444. var rect = this.renderer.view.getBoundingClientRect();
  7445. var sx = rect.width / this.renderer.width;
  7446. var sy = rect.height / this.renderer.height;
  7447. var div = this.div;
  7448. div.style.left = (rect.left) + "px";
  7449. div.style.top = (rect.top) + "px";
  7450. div.style.width = (this.renderer.width) + "px";
  7451. div.style.height = (this.renderer.height) + "px";
  7452. for (var i = 0; i < this.children.length; i++)
  7453. {
  7454. var child = this.children[i];
  7455. if (child.renderId !== this.renderId)
  7456. {
  7457. child._accessibleActive = false;
  7458. removeItems(this.children, i, 1);
  7459. this.div.removeChild(child._accessibleDiv);
  7460. this.pool.push(child._accessibleDiv);
  7461. child._accessibleDiv = null;
  7462. i--;
  7463. if (this.children.length === 0)
  7464. {
  7465. this.deactivate();
  7466. }
  7467. }
  7468. else
  7469. {
  7470. // map div to display..
  7471. div = child._accessibleDiv;
  7472. var hitArea = child.hitArea;
  7473. var wt = child.worldTransform;
  7474. if (child.hitArea)
  7475. {
  7476. div.style.left = ((wt.tx + (hitArea.x * wt.a)) * sx) + "px";
  7477. div.style.top = ((wt.ty + (hitArea.y * wt.d)) * sy) + "px";
  7478. div.style.width = (hitArea.width * wt.a * sx) + "px";
  7479. div.style.height = (hitArea.height * wt.d * sy) + "px";
  7480. }
  7481. else
  7482. {
  7483. hitArea = child.getBounds();
  7484. this.capHitArea(hitArea);
  7485. div.style.left = (hitArea.x * sx) + "px";
  7486. div.style.top = (hitArea.y * sy) + "px";
  7487. div.style.width = (hitArea.width * sx) + "px";
  7488. div.style.height = (hitArea.height * sy) + "px";
  7489. // update button titles and hints if they exist and they've changed
  7490. if (div.title !== child.accessibleTitle && child.accessibleTitle !== null)
  7491. {
  7492. div.title = child.accessibleTitle;
  7493. }
  7494. if (div.getAttribute('aria-label') !== child.accessibleHint
  7495. && child.accessibleHint !== null)
  7496. {
  7497. div.setAttribute('aria-label', child.accessibleHint);
  7498. }
  7499. }
  7500. }
  7501. }
  7502. // increment the render id..
  7503. this.renderId++;
  7504. };
  7505. /**
  7506. * Adjust the hit area based on the bounds of a display object
  7507. *
  7508. * @param {PIXI.Rectangle} hitArea - Bounds of the child
  7509. */
  7510. AccessibilityManager.prototype.capHitArea = function capHitArea (hitArea)
  7511. {
  7512. if (hitArea.x < 0)
  7513. {
  7514. hitArea.width += hitArea.x;
  7515. hitArea.x = 0;
  7516. }
  7517. if (hitArea.y < 0)
  7518. {
  7519. hitArea.height += hitArea.y;
  7520. hitArea.y = 0;
  7521. }
  7522. if (hitArea.x + hitArea.width > this.renderer.width)
  7523. {
  7524. hitArea.width = this.renderer.width - hitArea.x;
  7525. }
  7526. if (hitArea.y + hitArea.height > this.renderer.height)
  7527. {
  7528. hitArea.height = this.renderer.height - hitArea.y;
  7529. }
  7530. };
  7531. /**
  7532. * Adds a DisplayObject to the accessibility manager
  7533. *
  7534. * @private
  7535. * @param {PIXI.DisplayObject} displayObject - The child to make accessible.
  7536. */
  7537. AccessibilityManager.prototype.addChild = function addChild (displayObject)
  7538. {
  7539. //this.activate();
  7540. var div = this.pool.pop();
  7541. if (!div)
  7542. {
  7543. div = document.createElement('button');
  7544. div.style.width = DIV_TOUCH_SIZE + "px";
  7545. div.style.height = DIV_TOUCH_SIZE + "px";
  7546. div.style.backgroundColor = this.debug ? 'rgba(255,0,0,0.5)' : 'transparent';
  7547. div.style.position = 'absolute';
  7548. div.style.zIndex = DIV_TOUCH_ZINDEX;
  7549. div.style.borderStyle = 'none';
  7550. // ARIA attributes ensure that button title and hint updates are announced properly
  7551. if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1)
  7552. {
  7553. // Chrome doesn't need aria-live to work as intended; in fact it just gets more confused.
  7554. div.setAttribute('aria-live', 'off');
  7555. }
  7556. else
  7557. {
  7558. div.setAttribute('aria-live', 'polite');
  7559. }
  7560. if (navigator.userAgent.match(/rv:.*Gecko\//))
  7561. {
  7562. // FireFox needs this to announce only the new button name
  7563. div.setAttribute('aria-relevant', 'additions');
  7564. }
  7565. else
  7566. {
  7567. // required by IE, other browsers don't much care
  7568. div.setAttribute('aria-relevant', 'text');
  7569. }
  7570. div.addEventListener('click', this._onClick.bind(this));
  7571. div.addEventListener('focus', this._onFocus.bind(this));
  7572. div.addEventListener('focusout', this._onFocusOut.bind(this));
  7573. }
  7574. if (displayObject.accessibleTitle && displayObject.accessibleTitle !== null)
  7575. {
  7576. div.title = displayObject.accessibleTitle;
  7577. }
  7578. else if (!displayObject.accessibleHint
  7579. || displayObject.accessibleHint === null)
  7580. {
  7581. div.title = "displayObject " + (displayObject.tabIndex);
  7582. }
  7583. if (displayObject.accessibleHint
  7584. && displayObject.accessibleHint !== null)
  7585. {
  7586. div.setAttribute('aria-label', displayObject.accessibleHint);
  7587. }
  7588. //
  7589. displayObject._accessibleActive = true;
  7590. displayObject._accessibleDiv = div;
  7591. div.displayObject = displayObject;
  7592. this.children.push(displayObject);
  7593. this.div.appendChild(displayObject._accessibleDiv);
  7594. displayObject._accessibleDiv.tabIndex = displayObject.tabIndex;
  7595. };
  7596. /**
  7597. * Maps the div button press to pixi's InteractionManager (click)
  7598. *
  7599. * @private
  7600. * @param {MouseEvent} e - The click event.
  7601. */
  7602. AccessibilityManager.prototype._onClick = function _onClick (e)
  7603. {
  7604. var interactionManager = this.renderer.plugins.interaction;
  7605. interactionManager.dispatchEvent(e.target.displayObject, 'click', interactionManager.eventData);
  7606. };
  7607. /**
  7608. * Maps the div focus events to pixi's InteractionManager (mouseover)
  7609. *
  7610. * @private
  7611. * @param {FocusEvent} e - The focus event.
  7612. */
  7613. AccessibilityManager.prototype._onFocus = function _onFocus (e)
  7614. {
  7615. if (!e.target.getAttribute('aria-live', 'off'))
  7616. {
  7617. e.target.setAttribute('aria-live', 'assertive');
  7618. }
  7619. var interactionManager = this.renderer.plugins.interaction;
  7620. interactionManager.dispatchEvent(e.target.displayObject, 'mouseover', interactionManager.eventData);
  7621. };
  7622. /**
  7623. * Maps the div focus events to pixi's InteractionManager (mouseout)
  7624. *
  7625. * @private
  7626. * @param {FocusEvent} e - The focusout event.
  7627. */
  7628. AccessibilityManager.prototype._onFocusOut = function _onFocusOut (e)
  7629. {
  7630. if (!e.target.getAttribute('aria-live', 'off'))
  7631. {
  7632. e.target.setAttribute('aria-live', 'polite');
  7633. }
  7634. var interactionManager = this.renderer.plugins.interaction;
  7635. interactionManager.dispatchEvent(e.target.displayObject, 'mouseout', interactionManager.eventData);
  7636. };
  7637. /**
  7638. * Is called when a key is pressed
  7639. *
  7640. * @private
  7641. * @param {KeyboardEvent} e - The keydown event.
  7642. */
  7643. AccessibilityManager.prototype._onKeyDown = function _onKeyDown (e)
  7644. {
  7645. if (e.keyCode !== KEY_CODE_TAB)
  7646. {
  7647. return;
  7648. }
  7649. this.activate();
  7650. };
  7651. /**
  7652. * Is called when the mouse moves across the renderer element
  7653. *
  7654. * @private
  7655. * @param {MouseEvent} e - The mouse event.
  7656. */
  7657. AccessibilityManager.prototype._onMouseMove = function _onMouseMove (e)
  7658. {
  7659. if (e.movementX === 0 && e.movementY === 0)
  7660. {
  7661. return;
  7662. }
  7663. this.deactivate();
  7664. };
  7665. /**
  7666. * Destroys the accessibility manager
  7667. *
  7668. */
  7669. AccessibilityManager.prototype.destroy = function destroy ()
  7670. {
  7671. this.destroyTouchHook();
  7672. this.div = null;
  7673. for (var i = 0; i < this.children.length; i++)
  7674. {
  7675. this.children[i].div = null;
  7676. }
  7677. window.document.removeEventListener('mousemove', this._onMouseMove, true);
  7678. window.removeEventListener('keydown', this._onKeyDown);
  7679. this.pool = null;
  7680. this.children = null;
  7681. this.renderer = null;
  7682. };
  7683. var accessibility_es = ({
  7684. AccessibilityManager: AccessibilityManager,
  7685. accessibleTarget: accessibleTarget
  7686. });
  7687. /*!
  7688. * @pixi/runner - v5.0.4
  7689. * Compiled Fri, 07 Jun 2019 17:17:49 UTC
  7690. *
  7691. * @pixi/runner is licensed under the MIT License.
  7692. * http://www.opensource.org/licenses/mit-license
  7693. */
  7694. /**
  7695. * A Runner is a highly performant and simple alternative to signals. Best used in situations
  7696. * where events are dispatched to many objects at high frequency (say every frame!)
  7697. *
  7698. *
  7699. * like a signal..
  7700. * ```
  7701. * const myObject = {
  7702. * loaded: new PIXI.Runner('loaded')
  7703. * }
  7704. *
  7705. * const listener = {
  7706. * loaded: function(){
  7707. * // thin
  7708. * }
  7709. * }
  7710. *
  7711. * myObject.update.add(listener);
  7712. *
  7713. * myObject.loaded.emit();
  7714. * ```
  7715. *
  7716. * Or for handling calling the same function on many items
  7717. * ```
  7718. * const myGame = {
  7719. * update: new PIXI.Runner('update')
  7720. * }
  7721. *
  7722. * const gameObject = {
  7723. * update: function(time){
  7724. * // update my gamey state
  7725. * }
  7726. * }
  7727. *
  7728. * myGame.update.add(gameObject1);
  7729. *
  7730. * myGame.update.emit(time);
  7731. * ```
  7732. * @class
  7733. * @memberof PIXI
  7734. */
  7735. var Runner = function Runner(name)
  7736. {
  7737. this.items = [];
  7738. this._name = name;
  7739. };
  7740. var prototypeAccessors$3 = { empty: { configurable: true },name: { configurable: true } };
  7741. /**
  7742. * Dispatch/Broadcast Runner to all listeners added to the queue.
  7743. * @param {...any} params - optional parameters to pass to each listener
  7744. */
  7745. Runner.prototype.emit = function emit (a0, a1, a2, a3, a4, a5, a6, a7)
  7746. {
  7747. if (arguments.length > 8)
  7748. {
  7749. throw new Error('max arguments reached');
  7750. }
  7751. var ref = this;
  7752. var name = ref.name;
  7753. var items = ref.items;
  7754. for (var i = 0, len = items.length; i < len; i++)
  7755. {
  7756. items[i][name](a0, a1, a2, a3, a4, a5, a6, a7);
  7757. }
  7758. return this;
  7759. };
  7760. /**
  7761. * Add a listener to the Runner
  7762. *
  7763. * Runners do not need to have scope or functions passed to them.
  7764. * All that is required is to pass the listening object and ensure that it has contains a function that has the same name
  7765. * as the name provided to the Runner when it was created.
  7766. *
  7767. * Eg A listener passed to this Runner will require a 'complete' function.
  7768. *
  7769. * ```
  7770. * const complete = new PIXI.Runner('complete');
  7771. * ```
  7772. *
  7773. * The scope used will be the object itself.
  7774. *
  7775. * @param {any} item - The object that will be listening.
  7776. */
  7777. Runner.prototype.add = function add (item)
  7778. {
  7779. if (item[this._name])
  7780. {
  7781. this.remove(item);
  7782. this.items.push(item);
  7783. }
  7784. return this;
  7785. };
  7786. /**
  7787. * Remove a single listener from the dispatch queue.
  7788. * @param {any} item - The listenr that you would like to remove.
  7789. */
  7790. Runner.prototype.remove = function remove (item)
  7791. {
  7792. var index = this.items.indexOf(item);
  7793. if (index !== -1)
  7794. {
  7795. this.items.splice(index, 1);
  7796. }
  7797. return this;
  7798. };
  7799. /**
  7800. * Check to see if the listener is already in the Runner
  7801. * @param {any} item - The listener that you would like to check.
  7802. */
  7803. Runner.prototype.contains = function contains (item)
  7804. {
  7805. return this.items.indexOf(item) !== -1;
  7806. };
  7807. /**
  7808. * Remove all listeners from the Runner
  7809. */
  7810. Runner.prototype.removeAll = function removeAll ()
  7811. {
  7812. this.items.length = 0;
  7813. return this;
  7814. };
  7815. /**
  7816. * Remove all references, don't use after this.
  7817. */
  7818. Runner.prototype.destroy = function destroy ()
  7819. {
  7820. this.removeAll();
  7821. this.items = null;
  7822. this._name = null;
  7823. };
  7824. /**
  7825. * `true` if there are no this Runner contains no listeners
  7826. *
  7827. * @member {boolean}
  7828. * @readonly
  7829. */
  7830. prototypeAccessors$3.empty.get = function ()
  7831. {
  7832. return this.items.length === 0;
  7833. };
  7834. /**
  7835. * The name of the runner.
  7836. *
  7837. * @member {string}
  7838. * @readonly
  7839. */
  7840. prototypeAccessors$3.name.get = function ()
  7841. {
  7842. return this._name;
  7843. };
  7844. Object.defineProperties( Runner.prototype, prototypeAccessors$3 );
  7845. /**
  7846. * Alias for `emit`
  7847. * @memberof PIXI.Runner#
  7848. * @method dispatch
  7849. * @see PIXI.Runner#emit
  7850. */
  7851. Runner.prototype.dispatch = Runner.prototype.emit;
  7852. /**
  7853. * Alias for `emit`
  7854. * @memberof PIXI.Runner#
  7855. * @method run
  7856. * @see PIXI.Runner#emit
  7857. */
  7858. Runner.prototype.run = Runner.prototype.emit;
  7859. /*!
  7860. * @pixi/ticker - v5.0.4
  7861. * Compiled Fri, 07 Jun 2019 17:17:49 UTC
  7862. *
  7863. * @pixi/ticker is licensed under the MIT License.
  7864. * http://www.opensource.org/licenses/mit-license
  7865. */
  7866. /**
  7867. * Target frames per millisecond.
  7868. *
  7869. * @static
  7870. * @name TARGET_FPMS
  7871. * @memberof PIXI.settings
  7872. * @type {number}
  7873. * @default 0.06
  7874. */
  7875. settings.TARGET_FPMS = 0.06;
  7876. /**
  7877. * Represents the update priorities used by internal PIXI classes when registered with
  7878. * the {@link PIXI.Ticker} object. Higher priority items are updated first and lower
  7879. * priority items, such as render, should go later.
  7880. *
  7881. * @static
  7882. * @constant
  7883. * @name UPDATE_PRIORITY
  7884. * @memberof PIXI
  7885. * @type {object}
  7886. * @property {number} INTERACTION=50 Highest priority, used for {@link PIXI.interaction.InteractionManager}
  7887. * @property {number} HIGH=25 High priority updating, {@link PIXI.VideoBaseTexture} and {@link PIXI.AnimatedSprite}
  7888. * @property {number} NORMAL=0 Default priority for ticker events, see {@link PIXI.Ticker#add}.
  7889. * @property {number} LOW=-25 Low priority used for {@link PIXI.Application} rendering.
  7890. * @property {number} UTILITY=-50 Lowest priority used for {@link PIXI.prepare.BasePrepare} utility.
  7891. */
  7892. var UPDATE_PRIORITY = {
  7893. INTERACTION: 50,
  7894. HIGH: 25,
  7895. NORMAL: 0,
  7896. LOW: -25,
  7897. UTILITY: -50,
  7898. };
  7899. /**
  7900. * Internal class for handling the priority sorting of ticker handlers.
  7901. *
  7902. * @private
  7903. * @class
  7904. * @memberof PIXI
  7905. */
  7906. var TickerListener = function TickerListener(fn, context, priority, once)
  7907. {
  7908. if ( context === void 0 ) { context = null; }
  7909. if ( priority === void 0 ) { priority = 0; }
  7910. if ( once === void 0 ) { once = false; }
  7911. /**
  7912. * The handler function to execute.
  7913. * @private
  7914. * @member {Function}
  7915. */
  7916. this.fn = fn;
  7917. /**
  7918. * The calling to execute.
  7919. * @private
  7920. * @member {*}
  7921. */
  7922. this.context = context;
  7923. /**
  7924. * The current priority.
  7925. * @private
  7926. * @member {number}
  7927. */
  7928. this.priority = priority;
  7929. /**
  7930. * If this should only execute once.
  7931. * @private
  7932. * @member {boolean}
  7933. */
  7934. this.once = once;
  7935. /**
  7936. * The next item in chain.
  7937. * @private
  7938. * @member {TickerListener}
  7939. */
  7940. this.next = null;
  7941. /**
  7942. * The previous item in chain.
  7943. * @private
  7944. * @member {TickerListener}
  7945. */
  7946. this.previous = null;
  7947. /**
  7948. * `true` if this listener has been destroyed already.
  7949. * @member {boolean}
  7950. * @private
  7951. */
  7952. this._destroyed = false;
  7953. };
  7954. /**
  7955. * Simple compare function to figure out if a function and context match.
  7956. * @private
  7957. * @param {Function} fn - The listener function to be added for one update
  7958. * @param {Function} context - The listener context
  7959. * @return {boolean} `true` if the listener match the arguments
  7960. */
  7961. TickerListener.prototype.match = function match (fn, context)
  7962. {
  7963. context = context || null;
  7964. return this.fn === fn && this.context === context;
  7965. };
  7966. /**
  7967. * Emit by calling the current function.
  7968. * @private
  7969. * @param {number} deltaTime - time since the last emit.
  7970. * @return {TickerListener} Next ticker
  7971. */
  7972. TickerListener.prototype.emit = function emit (deltaTime)
  7973. {
  7974. if (this.fn)
  7975. {
  7976. if (this.context)
  7977. {
  7978. this.fn.call(this.context, deltaTime);
  7979. }
  7980. else
  7981. {
  7982. this.fn(deltaTime);
  7983. }
  7984. }
  7985. var redirect = this.next;
  7986. if (this.once)
  7987. {
  7988. this.destroy(true);
  7989. }
  7990. // Soft-destroying should remove
  7991. // the next reference
  7992. if (this._destroyed)
  7993. {
  7994. this.next = null;
  7995. }
  7996. return redirect;
  7997. };
  7998. /**
  7999. * Connect to the list.
  8000. * @private
  8001. * @param {TickerListener} previous - Input node, previous listener
  8002. */
  8003. TickerListener.prototype.connect = function connect (previous)
  8004. {
  8005. this.previous = previous;
  8006. if (previous.next)
  8007. {
  8008. previous.next.previous = this;
  8009. }
  8010. this.next = previous.next;
  8011. previous.next = this;
  8012. };
  8013. /**
  8014. * Destroy and don't use after this.
  8015. * @private
  8016. * @param {boolean} [hard = false] `true` to remove the `next` reference, this
  8017. * is considered a hard destroy. Soft destroy maintains the next reference.
  8018. * @return {TickerListener} The listener to redirect while emitting or removing.
  8019. */
  8020. TickerListener.prototype.destroy = function destroy (hard)
  8021. {
  8022. if ( hard === void 0 ) { hard = false; }
  8023. this._destroyed = true;
  8024. this.fn = null;
  8025. this.context = null;
  8026. // Disconnect, hook up next and previous
  8027. if (this.previous)
  8028. {
  8029. this.previous.next = this.next;
  8030. }
  8031. if (this.next)
  8032. {
  8033. this.next.previous = this.previous;
  8034. }
  8035. // Redirect to the next item
  8036. var redirect = this.next;
  8037. // Remove references
  8038. this.next = hard ? null : redirect;
  8039. this.previous = null;
  8040. return redirect;
  8041. };
  8042. /**
  8043. * A Ticker class that runs an update loop that other objects listen to.
  8044. *
  8045. * This class is composed around listeners meant for execution on the next requested animation frame.
  8046. * Animation frames are requested only when necessary, e.g. When the ticker is started and the emitter has listeners.
  8047. *
  8048. * @class
  8049. * @memberof PIXI
  8050. */
  8051. var Ticker = function Ticker()
  8052. {
  8053. var this$1 = this;
  8054. /**
  8055. * The first listener. All new listeners added are chained on this.
  8056. * @private
  8057. * @type {TickerListener}
  8058. */
  8059. this._head = new TickerListener(null, null, Infinity);
  8060. /**
  8061. * Internal current frame request ID
  8062. * @type {?number}
  8063. * @private
  8064. */
  8065. this._requestId = null;
  8066. /**
  8067. * Internal value managed by minFPS property setter and getter.
  8068. * This is the maximum allowed milliseconds between updates.
  8069. * @type {number}
  8070. * @private
  8071. */
  8072. this._maxElapsedMS = 100;
  8073. /**
  8074. * Internal value managed by maxFPS property setter and getter.
  8075. * This is the minimum allowed milliseconds between updates.
  8076. * @private
  8077. */
  8078. this._minElapsedMS = 0;
  8079. /**
  8080. * Whether or not this ticker should invoke the method
  8081. * {@link PIXI.Ticker#start} automatically
  8082. * when a listener is added.
  8083. *
  8084. * @member {boolean}
  8085. * @default false
  8086. */
  8087. this.autoStart = false;
  8088. /**
  8089. * Scalar time value from last frame to this frame.
  8090. * This value is capped by setting {@link PIXI.Ticker#minFPS}
  8091. * and is scaled with {@link PIXI.Ticker#speed}.
  8092. * **Note:** The cap may be exceeded by scaling.
  8093. *
  8094. * @member {number}
  8095. * @default 1
  8096. */
  8097. this.deltaTime = 1;
  8098. /**
  8099. * Scaler time elapsed in milliseconds from last frame to this frame.
  8100. * This value is capped by setting {@link PIXI.Ticker#minFPS}
  8101. * and is scaled with {@link PIXI.Ticker#speed}.
  8102. * **Note:** The cap may be exceeded by scaling.
  8103. * If the platform supports DOMHighResTimeStamp,
  8104. * this value will have a precision of 1 µs.
  8105. * Defaults to target frame time
  8106. *
  8107. * @member {number}
  8108. * @default 16.66
  8109. */
  8110. this.deltaMS = 1 / settings.TARGET_FPMS;
  8111. /**
  8112. * Time elapsed in milliseconds from last frame to this frame.
  8113. * Opposed to what the scalar {@link PIXI.Ticker#deltaTime}
  8114. * is based, this value is neither capped nor scaled.
  8115. * If the platform supports DOMHighResTimeStamp,
  8116. * this value will have a precision of 1 µs.
  8117. * Defaults to target frame time
  8118. *
  8119. * @member {number}
  8120. * @default 16.66
  8121. */
  8122. this.elapsedMS = 1 / settings.TARGET_FPMS;
  8123. /**
  8124. * The last time {@link PIXI.Ticker#update} was invoked.
  8125. * This value is also reset internally outside of invoking
  8126. * update, but only when a new animation frame is requested.
  8127. * If the platform supports DOMHighResTimeStamp,
  8128. * this value will have a precision of 1 µs.
  8129. *
  8130. * @member {number}
  8131. * @default -1
  8132. */
  8133. this.lastTime = -1;
  8134. /**
  8135. * Factor of current {@link PIXI.Ticker#deltaTime}.
  8136. * @example
  8137. * // Scales ticker.deltaTime to what would be
  8138. * // the equivalent of approximately 120 FPS
  8139. * ticker.speed = 2;
  8140. *
  8141. * @member {number}
  8142. * @default 1
  8143. */
  8144. this.speed = 1;
  8145. /**
  8146. * Whether or not this ticker has been started.
  8147. * `true` if {@link PIXI.Ticker#start} has been called.
  8148. * `false` if {@link PIXI.Ticker#stop} has been called.
  8149. * While `false`, this value may change to `true` in the
  8150. * event of {@link PIXI.Ticker#autoStart} being `true`
  8151. * and a listener is added.
  8152. *
  8153. * @member {boolean}
  8154. * @default false
  8155. */
  8156. this.started = false;
  8157. /**
  8158. * If enabled, deleting is disabled.
  8159. * @member {boolean}
  8160. * @default false
  8161. * @private
  8162. */
  8163. this._protected = false;
  8164. /**
  8165. * Internal tick method bound to ticker instance.
  8166. * This is because in early 2015, Function.bind
  8167. * is still 60% slower in high performance scenarios.
  8168. * Also separating frame requests from update method
  8169. * so listeners may be called at any time and with
  8170. * any animation API, just invoke ticker.update(time).
  8171. *
  8172. * @private
  8173. * @param {number} time - Time since last tick.
  8174. */
  8175. this._tick = function (time) {
  8176. this$1._requestId = null;
  8177. if (this$1.started)
  8178. {
  8179. // Invoke listeners now
  8180. this$1.update(time);
  8181. // Listener side effects may have modified ticker state.
  8182. if (this$1.started && this$1._requestId === null && this$1._head.next)
  8183. {
  8184. this$1._requestId = requestAnimationFrame(this$1._tick);
  8185. }
  8186. }
  8187. };
  8188. };
  8189. var prototypeAccessors$4 = { FPS: { configurable: true },minFPS: { configurable: true },maxFPS: { configurable: true } };
  8190. var staticAccessors$2 = { shared: { configurable: true },system: { configurable: true } };
  8191. /**
  8192. * Conditionally requests a new animation frame.
  8193. * If a frame has not already been requested, and if the internal
  8194. * emitter has listeners, a new frame is requested.
  8195. *
  8196. * @private
  8197. */
  8198. Ticker.prototype._requestIfNeeded = function _requestIfNeeded ()
  8199. {
  8200. if (this._requestId === null && this._head.next)
  8201. {
  8202. // ensure callbacks get correct delta
  8203. this.lastTime = performance.now();
  8204. this._requestId = requestAnimationFrame(this._tick);
  8205. }
  8206. };
  8207. /**
  8208. * Conditionally cancels a pending animation frame.
  8209. *
  8210. * @private
  8211. */
  8212. Ticker.prototype._cancelIfNeeded = function _cancelIfNeeded ()
  8213. {
  8214. if (this._requestId !== null)
  8215. {
  8216. cancelAnimationFrame(this._requestId);
  8217. this._requestId = null;
  8218. }
  8219. };
  8220. /**
  8221. * Conditionally requests a new animation frame.
  8222. * If the ticker has been started it checks if a frame has not already
  8223. * been requested, and if the internal emitter has listeners. If these
  8224. * conditions are met, a new frame is requested. If the ticker has not
  8225. * been started, but autoStart is `true`, then the ticker starts now,
  8226. * and continues with the previous conditions to request a new frame.
  8227. *
  8228. * @private
  8229. */
  8230. Ticker.prototype._startIfPossible = function _startIfPossible ()
  8231. {
  8232. if (this.started)
  8233. {
  8234. this._requestIfNeeded();
  8235. }
  8236. else if (this.autoStart)
  8237. {
  8238. this.start();
  8239. }
  8240. };
  8241. /**
  8242. * Register a handler for tick events. Calls continuously unless
  8243. * it is removed or the ticker is stopped.
  8244. *
  8245. * @param {Function} fn - The listener function to be added for updates
  8246. * @param {*} [context] - The listener context
  8247. * @param {number} [priority=PIXI.UPDATE_PRIORITY.NORMAL] - The priority for emitting
  8248. * @returns {PIXI.Ticker} This instance of a ticker
  8249. */
  8250. Ticker.prototype.add = function add (fn, context, priority)
  8251. {
  8252. if ( priority === void 0 ) { priority = UPDATE_PRIORITY.NORMAL; }
  8253. return this._addListener(new TickerListener(fn, context, priority));
  8254. };
  8255. /**
  8256. * Add a handler for the tick event which is only execute once.
  8257. *
  8258. * @param {Function} fn - The listener function to be added for one update
  8259. * @param {*} [context] - The listener context
  8260. * @param {number} [priority=PIXI.UPDATE_PRIORITY.NORMAL] - The priority for emitting
  8261. * @returns {PIXI.Ticker} This instance of a ticker
  8262. */
  8263. Ticker.prototype.addOnce = function addOnce (fn, context, priority)
  8264. {
  8265. if ( priority === void 0 ) { priority = UPDATE_PRIORITY.NORMAL; }
  8266. return this._addListener(new TickerListener(fn, context, priority, true));
  8267. };
  8268. /**
  8269. * Internally adds the event handler so that it can be sorted by priority.
  8270. * Priority allows certain handler (user, AnimatedSprite, Interaction) to be run
  8271. * before the rendering.
  8272. *
  8273. * @private
  8274. * @param {TickerListener} listener - Current listener being added.
  8275. * @returns {PIXI.Ticker} This instance of a ticker
  8276. */
  8277. Ticker.prototype._addListener = function _addListener (listener)
  8278. {
  8279. // For attaching to head
  8280. var current = this._head.next;
  8281. var previous = this._head;
  8282. // Add the first item
  8283. if (!current)
  8284. {
  8285. listener.connect(previous);
  8286. }
  8287. else
  8288. {
  8289. // Go from highest to lowest priority
  8290. while (current)
  8291. {
  8292. if (listener.priority > current.priority)
  8293. {
  8294. listener.connect(previous);
  8295. break;
  8296. }
  8297. previous = current;
  8298. current = current.next;
  8299. }
  8300. // Not yet connected
  8301. if (!listener.previous)
  8302. {
  8303. listener.connect(previous);
  8304. }
  8305. }
  8306. this._startIfPossible();
  8307. return this;
  8308. };
  8309. /**
  8310. * Removes any handlers matching the function and context parameters.
  8311. * If no handlers are left after removing, then it cancels the animation frame.
  8312. *
  8313. * @param {Function} fn - The listener function to be removed
  8314. * @param {*} [context] - The listener context to be removed
  8315. * @returns {PIXI.Ticker} This instance of a ticker
  8316. */
  8317. Ticker.prototype.remove = function remove (fn, context)
  8318. {
  8319. var listener = this._head.next;
  8320. while (listener)
  8321. {
  8322. // We found a match, lets remove it
  8323. // no break to delete all possible matches
  8324. // incase a listener was added 2+ times
  8325. if (listener.match(fn, context))
  8326. {
  8327. listener = listener.destroy();
  8328. }
  8329. else
  8330. {
  8331. listener = listener.next;
  8332. }
  8333. }
  8334. if (!this._head.next)
  8335. {
  8336. this._cancelIfNeeded();
  8337. }
  8338. return this;
  8339. };
  8340. /**
  8341. * Starts the ticker. If the ticker has listeners
  8342. * a new animation frame is requested at this point.
  8343. */
  8344. Ticker.prototype.start = function start ()
  8345. {
  8346. if (!this.started)
  8347. {
  8348. this.started = true;
  8349. this._requestIfNeeded();
  8350. }
  8351. };
  8352. /**
  8353. * Stops the ticker. If the ticker has requested
  8354. * an animation frame it is canceled at this point.
  8355. */
  8356. Ticker.prototype.stop = function stop ()
  8357. {
  8358. if (this.started)
  8359. {
  8360. this.started = false;
  8361. this._cancelIfNeeded();
  8362. }
  8363. };
  8364. /**
  8365. * Destroy the ticker and don't use after this. Calling
  8366. * this method removes all references to internal events.
  8367. */
  8368. Ticker.prototype.destroy = function destroy ()
  8369. {
  8370. if (!this._protected)
  8371. {
  8372. this.stop();
  8373. var listener = this._head.next;
  8374. while (listener)
  8375. {
  8376. listener = listener.destroy(true);
  8377. }
  8378. this._head.destroy();
  8379. this._head = null;
  8380. }
  8381. };
  8382. /**
  8383. * Triggers an update. An update entails setting the
  8384. * current {@link PIXI.Ticker#elapsedMS},
  8385. * the current {@link PIXI.Ticker#deltaTime},
  8386. * invoking all listeners with current deltaTime,
  8387. * and then finally setting {@link PIXI.Ticker#lastTime}
  8388. * with the value of currentTime that was provided.
  8389. * This method will be called automatically by animation
  8390. * frame callbacks if the ticker instance has been started
  8391. * and listeners are added.
  8392. *
  8393. * @param {number} [currentTime=performance.now()] - the current time of execution
  8394. */
  8395. Ticker.prototype.update = function update (currentTime)
  8396. {
  8397. if ( currentTime === void 0 ) { currentTime = performance.now(); }
  8398. var elapsedMS;
  8399. // If the difference in time is zero or negative, we ignore most of the work done here.
  8400. // If there is no valid difference, then should be no reason to let anyone know about it.
  8401. // A zero delta, is exactly that, nothing should update.
  8402. //
  8403. // The difference in time can be negative, and no this does not mean time traveling.
  8404. // This can be the result of a race condition between when an animation frame is requested
  8405. // on the current JavaScript engine event loop, and when the ticker's start method is invoked
  8406. // (which invokes the internal _requestIfNeeded method). If a frame is requested before
  8407. // _requestIfNeeded is invoked, then the callback for the animation frame the ticker requests,
  8408. // can receive a time argument that can be less than the lastTime value that was set within
  8409. // _requestIfNeeded. This difference is in microseconds, but this is enough to cause problems.
  8410. //
  8411. // This check covers this browser engine timing issue, as well as if consumers pass an invalid
  8412. // currentTime value. This may happen if consumers opt-out of the autoStart, and update themselves.
  8413. if (currentTime > this.lastTime)
  8414. {
  8415. // Save uncapped elapsedMS for measurement
  8416. elapsedMS = this.elapsedMS = currentTime - this.lastTime;
  8417. // cap the milliseconds elapsed used for deltaTime
  8418. if (elapsedMS > this._maxElapsedMS)
  8419. {
  8420. elapsedMS = this._maxElapsedMS;
  8421. }
  8422. elapsedMS *= this.speed;
  8423. // if not enough time has passed, exit the function.
  8424. // We give an extra ms to elapsedMS for this check, because the nature of
  8425. // request animation frame means that not all browsers will return precise values.
  8426. // However, because rAF works based on v-sync, it's won't change the effective FPS.
  8427. if (this._minElapsedMS && elapsedMS + 1 < this._minElapsedMS)
  8428. {
  8429. return;
  8430. }
  8431. this.deltaMS = elapsedMS;
  8432. this.deltaTime = this.deltaMS * settings.TARGET_FPMS;
  8433. // Cache a local reference, in-case ticker is destroyed
  8434. // during the emit, we can still check for head.next
  8435. var head = this._head;
  8436. // Invoke listeners added to internal emitter
  8437. var listener = head.next;
  8438. while (listener)
  8439. {
  8440. listener = listener.emit(this.deltaTime);
  8441. }
  8442. if (!head.next)
  8443. {
  8444. this._cancelIfNeeded();
  8445. }
  8446. }
  8447. else
  8448. {
  8449. this.deltaTime = this.deltaMS = this.elapsedMS = 0;
  8450. }
  8451. this.lastTime = currentTime;
  8452. };
  8453. /**
  8454. * The frames per second at which this ticker is running.
  8455. * The default is approximately 60 in most modern browsers.
  8456. * **Note:** This does not factor in the value of
  8457. * {@link PIXI.Ticker#speed}, which is specific
  8458. * to scaling {@link PIXI.Ticker#deltaTime}.
  8459. *
  8460. * @member {number}
  8461. * @readonly
  8462. */
  8463. prototypeAccessors$4.FPS.get = function ()
  8464. {
  8465. return 1000 / this.elapsedMS;
  8466. };
  8467. /**
  8468. * Manages the maximum amount of milliseconds allowed to
  8469. * elapse between invoking {@link PIXI.Ticker#update}.
  8470. * This value is used to cap {@link PIXI.Ticker#deltaTime},
  8471. * but does not effect the measured value of {@link PIXI.Ticker#FPS}.
  8472. * When setting this property it is clamped to a value between
  8473. * `0` and `PIXI.settings.TARGET_FPMS * 1000`.
  8474. *
  8475. * @member {number}
  8476. * @default 10
  8477. */
  8478. prototypeAccessors$4.minFPS.get = function ()
  8479. {
  8480. return 1000 / this._maxElapsedMS;
  8481. };
  8482. prototypeAccessors$4.minFPS.set = function (fps) // eslint-disable-line require-jsdoc
  8483. {
  8484. // Minimum must be below the maxFPS
  8485. var minFPS = Math.min(this.maxFPS, fps);
  8486. // Must be at least 0, but below 1 / settings.TARGET_FPMS
  8487. var minFPMS = Math.min(Math.max(0, minFPS) / 1000, settings.TARGET_FPMS);
  8488. this._maxElapsedMS = 1 / minFPMS;
  8489. };
  8490. /**
  8491. * Manages the minimum amount of milliseconds allowed to
  8492. * elapse between invoking {@link PIXI.Ticker#update}.
  8493. * This will effect the measured value of {@link PIXI.Ticker#FPS}.
  8494. * When setting this property it is clamped to a value between
  8495. * `1` and `TARGET_FPMS * 1000`.
  8496. *
  8497. * @member {number}
  8498. * @default 60
  8499. */
  8500. prototypeAccessors$4.maxFPS.get = function ()
  8501. {
  8502. if (this._minElapsedMS)
  8503. {
  8504. return 1000 / this._minElapsedMS;
  8505. }
  8506. return settings.TARGET_FPMS * 1000;
  8507. };
  8508. prototypeAccessors$4.maxFPS.set = function (fps)
  8509. {
  8510. if (fps / 1000 >= settings.TARGET_FPMS)
  8511. {
  8512. this._minElapsedMS = 0;
  8513. }
  8514. else
  8515. {
  8516. // Max must be at least the minFPS
  8517. var maxFPS = Math.max(this.minFPS, fps);
  8518. // Must be at least 1, but below 1 / settings.TARGET_FPMS
  8519. var maxFPMS = Math.min(Math.max(1, maxFPS) / 1000, settings.TARGET_FPMS);
  8520. this._minElapsedMS = 1 / maxFPMS;
  8521. }
  8522. };
  8523. /**
  8524. * The shared ticker instance used by {@link PIXI.AnimatedSprite} and by
  8525. * {@link PIXI.VideoResource} to update animation frames / video textures.
  8526. *
  8527. * It may also be used by {@link PIXI.Application} if created with the `sharedTicker` option property set to true.
  8528. *
  8529. * The property {@link PIXI.Ticker#autoStart} is set to `true` for this instance.
  8530. * Please follow the examples for usage, including how to opt-out of auto-starting the shared ticker.
  8531. *
  8532. * @example
  8533. * let ticker = PIXI.Ticker.shared;
  8534. * // Set this to prevent starting this ticker when listeners are added.
  8535. * // By default this is true only for the PIXI.Ticker.shared instance.
  8536. * ticker.autoStart = false;
  8537. * // FYI, call this to ensure the ticker is stopped. It should be stopped
  8538. * // if you have not attempted to render anything yet.
  8539. * ticker.stop();
  8540. * // Call this when you are ready for a running shared ticker.
  8541. * ticker.start();
  8542. *
  8543. * @example
  8544. * // You may use the shared ticker to render...
  8545. * let renderer = PIXI.autoDetectRenderer();
  8546. * let stage = new PIXI.Container();
  8547. * document.body.appendChild(renderer.view);
  8548. * ticker.add(function (time) {
  8549. * renderer.render(stage);
  8550. * });
  8551. *
  8552. * @example
  8553. * // Or you can just update it manually.
  8554. * ticker.autoStart = false;
  8555. * ticker.stop();
  8556. * function animate(time) {
  8557. * ticker.update(time);
  8558. * renderer.render(stage);
  8559. * requestAnimationFrame(animate);
  8560. * }
  8561. * animate(performance.now());
  8562. *
  8563. * @member {PIXI.Ticker}
  8564. * @static
  8565. */
  8566. staticAccessors$2.shared.get = function ()
  8567. {
  8568. if (!Ticker._shared)
  8569. {
  8570. var shared = Ticker._shared = new Ticker();
  8571. shared.autoStart = true;
  8572. shared._protected = true;
  8573. }
  8574. return Ticker._shared;
  8575. };
  8576. /**
  8577. * The system ticker instance used by {@link PIXI.interaction.InteractionManager} and by
  8578. * {@link PIXI.BasePrepare} for core timing functionality that shouldn't usually need to be paused,
  8579. * unlike the `shared` ticker which drives visual animations and rendering which may want to be paused.
  8580. *
  8581. * The property {@link PIXI.Ticker#autoStart} is set to `true` for this instance.
  8582. *
  8583. * @member {PIXI.Ticker}
  8584. * @static
  8585. */
  8586. staticAccessors$2.system.get = function ()
  8587. {
  8588. if (!Ticker._system)
  8589. {
  8590. var system = Ticker._system = new Ticker();
  8591. system.autoStart = true;
  8592. system._protected = true;
  8593. }
  8594. return Ticker._system;
  8595. };
  8596. Object.defineProperties( Ticker.prototype, prototypeAccessors$4 );
  8597. Object.defineProperties( Ticker, staticAccessors$2 );
  8598. /**
  8599. * Middleware for for Application Ticker.
  8600. *
  8601. * @example
  8602. * import {TickerPlugin} from '@pixi/ticker';
  8603. * import {Application} from '@pixi/app';
  8604. * Application.registerPlugin(TickerPlugin);
  8605. *
  8606. * @class
  8607. * @memberof PIXI
  8608. */
  8609. var TickerPlugin = function TickerPlugin () {};
  8610. TickerPlugin.init = function init (options)
  8611. {
  8612. var this$1 = this;
  8613. // Set default
  8614. options = Object.assign({
  8615. autoStart: true,
  8616. sharedTicker: false,
  8617. }, options);
  8618. // Create ticker setter
  8619. Object.defineProperty(this, 'ticker',
  8620. {
  8621. set: function set(ticker)
  8622. {
  8623. if (this._ticker)
  8624. {
  8625. this._ticker.remove(this.render, this);
  8626. }
  8627. this._ticker = ticker;
  8628. if (ticker)
  8629. {
  8630. ticker.add(this.render, this, UPDATE_PRIORITY.LOW);
  8631. }
  8632. },
  8633. get: function get()
  8634. {
  8635. return this._ticker;
  8636. },
  8637. });
  8638. /**
  8639. * Convenience method for stopping the render.
  8640. *
  8641. * @method PIXI.Application#stop
  8642. */
  8643. this.stop = function () {
  8644. this$1._ticker.stop();
  8645. };
  8646. /**
  8647. * Convenience method for starting the render.
  8648. *
  8649. * @method PIXI.Application#start
  8650. */
  8651. this.start = function () {
  8652. this$1._ticker.start();
  8653. };
  8654. /**
  8655. * Internal reference to the ticker.
  8656. *
  8657. * @type {PIXI.Ticker}
  8658. * @name _ticker
  8659. * @memberof PIXI.Application#
  8660. * @private
  8661. */
  8662. this._ticker = null;
  8663. /**
  8664. * Ticker for doing render updates.
  8665. *
  8666. * @type {PIXI.Ticker}
  8667. * @name ticker
  8668. * @memberof PIXI.Application#
  8669. * @default PIXI.Ticker.shared
  8670. */
  8671. this.ticker = options.sharedTicker ? Ticker.shared : new Ticker();
  8672. // Start the rendering
  8673. if (options.autoStart)
  8674. {
  8675. this.start();
  8676. }
  8677. };
  8678. /**
  8679. * Clean up the ticker, scoped to application.
  8680. *
  8681. * @static
  8682. * @private
  8683. */
  8684. TickerPlugin.destroy = function destroy ()
  8685. {
  8686. if (this._ticker)
  8687. {
  8688. var oldTicker = this._ticker;
  8689. this.ticker = null;
  8690. oldTicker.destroy();
  8691. }
  8692. };
  8693. /*!
  8694. * @pixi/core - v5.0.4
  8695. * Compiled Fri, 07 Jun 2019 17:17:49 UTC
  8696. *
  8697. * @pixi/core is licensed under the MIT License.
  8698. * http://www.opensource.org/licenses/mit-license
  8699. */
  8700. /**
  8701. * Base resource class for textures that manages validation and uploading, depending on its type.
  8702. *
  8703. * Uploading of a base texture to the GPU is required.
  8704. *
  8705. * @class
  8706. * @memberof PIXI.resources
  8707. */
  8708. var Resource = function Resource(width, height)
  8709. {
  8710. if ( width === void 0 ) { width = 0; }
  8711. if ( height === void 0 ) { height = 0; }
  8712. /**
  8713. * Internal width of the resource
  8714. * @member {number}
  8715. * @protected
  8716. */
  8717. this._width = width;
  8718. /**
  8719. * Internal height of the resource
  8720. * @member {number}
  8721. * @protected
  8722. */
  8723. this._height = height;
  8724. /**
  8725. * If resource has been destroyed
  8726. * @member {boolean}
  8727. * @readonly
  8728. * @default false
  8729. */
  8730. this.destroyed = false;
  8731. /**
  8732. * `true` if resource is created by BaseTexture
  8733. * useful for doing cleanup with BaseTexture destroy
  8734. * and not cleaning up resources that were created
  8735. * externally.
  8736. * @member {boolean}
  8737. * @protected
  8738. */
  8739. this.internal = false;
  8740. /**
  8741. * Mini-runner for handling resize events
  8742. *
  8743. * @member {Runner}
  8744. * @private
  8745. */
  8746. this.onResize = new Runner('setRealSize', 2);
  8747. /**
  8748. * Mini-runner for handling update events
  8749. *
  8750. * @member {Runner}
  8751. * @private
  8752. */
  8753. this.onUpdate = new Runner('update');
  8754. };
  8755. var prototypeAccessors$5 = { valid: { configurable: true },width: { configurable: true },height: { configurable: true } };
  8756. /**
  8757. * Bind to a parent BaseTexture
  8758. *
  8759. * @param {PIXI.BaseTexture} baseTexture - Parent texture
  8760. */
  8761. Resource.prototype.bind = function bind (baseTexture)
  8762. {
  8763. this.onResize.add(baseTexture);
  8764. this.onUpdate.add(baseTexture);
  8765. // Call a resize immediate if we already
  8766. // have the width and height of the resource
  8767. if (this._width || this._height)
  8768. {
  8769. this.onResize.run(this._width, this._height);
  8770. }
  8771. };
  8772. /**
  8773. * Unbind to a parent BaseTexture
  8774. *
  8775. * @param {PIXI.BaseTexture} baseTexture - Parent texture
  8776. */
  8777. Resource.prototype.unbind = function unbind (baseTexture)
  8778. {
  8779. this.onResize.remove(baseTexture);
  8780. this.onUpdate.remove(baseTexture);
  8781. };
  8782. /**
  8783. * Trigger a resize event
  8784. */
  8785. Resource.prototype.resize = function resize (width, height)
  8786. {
  8787. if (width !== this._width || height !== this._height)
  8788. {
  8789. this._width = width;
  8790. this._height = height;
  8791. this.onResize.run(width, height);
  8792. }
  8793. };
  8794. /**
  8795. * Has been validated
  8796. * @readonly
  8797. * @member {boolean}
  8798. */
  8799. prototypeAccessors$5.valid.get = function ()
  8800. {
  8801. return !!this._width && !!this._height;
  8802. };
  8803. /**
  8804. * Has been updated trigger event
  8805. */
  8806. Resource.prototype.update = function update ()
  8807. {
  8808. if (!this.destroyed)
  8809. {
  8810. this.onUpdate.run();
  8811. }
  8812. };
  8813. /**
  8814. * This can be overridden to start preloading a resource
  8815. * or do any other prepare step.
  8816. * @protected
  8817. * @return {Promise<void>} Handle the validate event
  8818. */
  8819. Resource.prototype.load = function load ()
  8820. {
  8821. return Promise.resolve();
  8822. };
  8823. /**
  8824. * The width of the resource.
  8825. *
  8826. * @member {number}
  8827. * @readonly
  8828. */
  8829. prototypeAccessors$5.width.get = function ()
  8830. {
  8831. return this._width;
  8832. };
  8833. /**
  8834. * The height of the resource.
  8835. *
  8836. * @member {number}
  8837. * @readonly
  8838. */
  8839. prototypeAccessors$5.height.get = function ()
  8840. {
  8841. return this._height;
  8842. };
  8843. /**
  8844. * Uploads the texture or returns false if it cant for some reason. Override this.
  8845. *
  8846. * @param {PIXI.Renderer} renderer - yeah, renderer!
  8847. * @param {PIXI.BaseTexture} baseTexture - the texture
  8848. * @param {PIXI.GLTexture} glTexture - texture instance for this webgl context
  8849. * @returns {boolean} true is success
  8850. */
  8851. Resource.prototype.upload = function upload (renderer, baseTexture, glTexture) // eslint-disable-line no-unused-vars
  8852. {
  8853. return false;
  8854. };
  8855. /**
  8856. * Set the style, optional to override
  8857. *
  8858. * @param {PIXI.Renderer} renderer - yeah, renderer!
  8859. * @param {PIXI.BaseTexture} baseTexture - the texture
  8860. * @param {PIXI.GLTexture} glTexture - texture instance for this webgl context
  8861. * @returns {boolean} `true` is success
  8862. */
  8863. Resource.prototype.style = function style (renderer, baseTexture, glTexture) // eslint-disable-line no-unused-vars
  8864. {
  8865. return false;
  8866. };
  8867. /**
  8868. * Clean up anything, this happens when destroying is ready.
  8869. *
  8870. * @protected
  8871. */
  8872. Resource.prototype.dispose = function dispose ()
  8873. {
  8874. // override
  8875. };
  8876. /**
  8877. * Call when destroying resource, unbind any BaseTexture object
  8878. * before calling this method, as reference counts are maintained
  8879. * internally.
  8880. */
  8881. Resource.prototype.destroy = function destroy ()
  8882. {
  8883. if (!this.destroyed)
  8884. {
  8885. this.onResize.removeAll();
  8886. this.onResize = null;
  8887. this.onUpdate.removeAll();
  8888. this.onUpdate = null;
  8889. this.destroyed = true;
  8890. this.dispose();
  8891. }
  8892. };
  8893. Object.defineProperties( Resource.prototype, prototypeAccessors$5 );
  8894. /**
  8895. * Base for all the image/canvas resources
  8896. * @class
  8897. * @extends PIXI.resources.Resource
  8898. * @memberof PIXI.resources
  8899. */
  8900. var BaseImageResource = /*@__PURE__*/(function (Resource) {
  8901. function BaseImageResource(source)
  8902. {
  8903. var width = source.naturalWidth || source.videoWidth || source.width;
  8904. var height = source.naturalHeight || source.videoHeight || source.height;
  8905. Resource.call(this, width, height);
  8906. /**
  8907. * The source element
  8908. * @member {HTMLImageElement|HTMLCanvasElement|HTMLVideoElement|SVGElement}
  8909. * @readonly
  8910. */
  8911. this.source = source;
  8912. }
  8913. if ( Resource ) { BaseImageResource.__proto__ = Resource; }
  8914. BaseImageResource.prototype = Object.create( Resource && Resource.prototype );
  8915. BaseImageResource.prototype.constructor = BaseImageResource;
  8916. /**
  8917. * Set cross origin based detecting the url and the crossorigin
  8918. * @protected
  8919. * @param {HTMLElement} element - Element to apply crossOrigin
  8920. * @param {string} url - URL to check
  8921. * @param {boolean|string} [crossorigin=true] - Cross origin value to use
  8922. */
  8923. BaseImageResource.crossOrigin = function crossOrigin (element, url, crossorigin)
  8924. {
  8925. if (crossorigin === undefined && url.indexOf('data:') !== 0)
  8926. {
  8927. element.crossOrigin = determineCrossOrigin(url);
  8928. }
  8929. else if (crossorigin !== false)
  8930. {
  8931. element.crossOrigin = typeof crossorigin === 'string' ? crossorigin : 'anonymous';
  8932. }
  8933. };
  8934. /**
  8935. * Upload the texture to the GPU.
  8936. * @param {PIXI.Renderer} renderer Upload to the renderer
  8937. * @param {PIXI.BaseTexture} baseTexture Reference to parent texture
  8938. * @param {PIXI.GLTexture} glTexture
  8939. * @param {HTMLImageElement|HTMLCanvasElement|HTMLVideoElement|SVGElement} [source] (optional)
  8940. * @returns {boolean} true is success
  8941. */
  8942. BaseImageResource.prototype.upload = function upload (renderer, baseTexture, glTexture, source)
  8943. {
  8944. var gl = renderer.gl;
  8945. var width = baseTexture.realWidth;
  8946. var height = baseTexture.realHeight;
  8947. source = source || this.source;
  8948. gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, baseTexture.premultiplyAlpha);
  8949. if (baseTexture.target === gl.TEXTURE_2D && glTexture.width === width && glTexture.height === height)
  8950. {
  8951. gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, baseTexture.format, baseTexture.type, source);
  8952. }
  8953. else
  8954. {
  8955. glTexture.width = width;
  8956. glTexture.height = height;
  8957. gl.texImage2D(baseTexture.target, 0, baseTexture.format, baseTexture.format, baseTexture.type, source);
  8958. }
  8959. return true;
  8960. };
  8961. /**
  8962. * Checks if source width/height was changed, resize can cause extra baseTexture update.
  8963. * Triggers one update in any case.
  8964. */
  8965. BaseImageResource.prototype.update = function update ()
  8966. {
  8967. if (this.destroyed)
  8968. {
  8969. return;
  8970. }
  8971. var width = this.source.naturalWidth || this.source.videoWidth || this.source.width;
  8972. var height = this.source.naturalHeight || this.source.videoHeight || this.source.height;
  8973. this.resize(width, height);
  8974. Resource.prototype.update.call(this);
  8975. };
  8976. /**
  8977. * Destroy this BaseImageResource
  8978. * @override
  8979. * @param {PIXI.BaseTexture} [fromTexture] Optional base texture
  8980. * @return {boolean} Destroy was successful
  8981. */
  8982. BaseImageResource.prototype.dispose = function dispose ()
  8983. {
  8984. this.source = null;
  8985. };
  8986. return BaseImageResource;
  8987. }(Resource));
  8988. /**
  8989. * Resource type for HTMLImageElement.
  8990. * @class
  8991. * @extends PIXI.resources.BaseImageResource
  8992. * @memberof PIXI.resources
  8993. */
  8994. var ImageResource = /*@__PURE__*/(function (BaseImageResource) {
  8995. function ImageResource(source, options)
  8996. {
  8997. options = options || {};
  8998. if (!(source instanceof HTMLImageElement))
  8999. {
  9000. var imageElement = new Image();
  9001. BaseImageResource.crossOrigin(imageElement, source, options.crossorigin);
  9002. imageElement.src = source;
  9003. source = imageElement;
  9004. }
  9005. BaseImageResource.call(this, source);
  9006. /**
  9007. * URL of the image source
  9008. * @member {string}
  9009. */
  9010. this.url = source.src;
  9011. /**
  9012. * When process is completed
  9013. * @member {Promise<void>}
  9014. * @private
  9015. */
  9016. this._process = null;
  9017. /**
  9018. * If the image should be disposed after upload
  9019. * @member {boolean}
  9020. * @default false
  9021. */
  9022. this.preserveBitmap = false;
  9023. /**
  9024. * If capable, convert the image using createImageBitmap API
  9025. * @member {boolean}
  9026. * @default PIXI.settings.CREATE_IMAGE_BITMAP
  9027. */
  9028. this.createBitmap = (options.createBitmap !== undefined
  9029. ? options.createBitmap : settings.CREATE_IMAGE_BITMAP) && !!window.createImageBitmap;
  9030. /**
  9031. * Controls texture premultiplyAlpha field
  9032. * Copies from options
  9033. * @member {boolean|null}
  9034. * @readonly
  9035. */
  9036. this.premultiplyAlpha = options.premultiplyAlpha !== false;
  9037. /**
  9038. * The ImageBitmap element created for HTMLImageElement
  9039. * @member {ImageBitmap}
  9040. * @default null
  9041. */
  9042. this.bitmap = null;
  9043. /**
  9044. * Promise when loading
  9045. * @member {Promise<void>}
  9046. * @private
  9047. * @default null
  9048. */
  9049. this._load = null;
  9050. if (options.autoLoad !== false)
  9051. {
  9052. this.load();
  9053. }
  9054. }
  9055. if ( BaseImageResource ) { ImageResource.__proto__ = BaseImageResource; }
  9056. ImageResource.prototype = Object.create( BaseImageResource && BaseImageResource.prototype );
  9057. ImageResource.prototype.constructor = ImageResource;
  9058. /**
  9059. * returns a promise when image will be loaded and processed
  9060. *
  9061. * @param {boolean} [createBitmap=true] whether process image into bitmap
  9062. * @returns {Promise<void>}
  9063. */
  9064. ImageResource.prototype.load = function load (createBitmap)
  9065. {
  9066. var this$1 = this;
  9067. if (createBitmap !== undefined)
  9068. {
  9069. this.createBitmap = createBitmap;
  9070. }
  9071. if (this._load)
  9072. {
  9073. return this._load;
  9074. }
  9075. this._load = new Promise(function (resolve) {
  9076. this$1.url = this$1.source.src;
  9077. var ref = this$1;
  9078. var source = ref.source;
  9079. var completed = function () {
  9080. if (this$1.destroyed)
  9081. {
  9082. return;
  9083. }
  9084. source.onload = null;
  9085. source.onerror = null;
  9086. this$1.resize(source.width, source.height);
  9087. this$1._load = null;
  9088. if (this$1.createBitmap)
  9089. {
  9090. resolve(this$1.process());
  9091. }
  9092. else
  9093. {
  9094. resolve(this$1);
  9095. }
  9096. };
  9097. if (source.complete && source.src)
  9098. {
  9099. completed();
  9100. }
  9101. else
  9102. {
  9103. source.onload = completed;
  9104. }
  9105. });
  9106. return this._load;
  9107. };
  9108. /**
  9109. * Called when we need to convert image into BitmapImage.
  9110. * Can be called multiple times, real promise is cached inside.
  9111. *
  9112. * @returns {Promise<void>} cached promise to fill that bitmap
  9113. */
  9114. ImageResource.prototype.process = function process ()
  9115. {
  9116. var this$1 = this;
  9117. if (this._process !== null)
  9118. {
  9119. return this._process;
  9120. }
  9121. if (this.bitmap !== null || !window.createImageBitmap)
  9122. {
  9123. return Promise.resolve(this);
  9124. }
  9125. this._process = window.createImageBitmap(this.source,
  9126. 0, 0, this.source.width, this.source.height,
  9127. {
  9128. premultiplyAlpha: this.premultiplyAlpha ? 'premultiply' : 'none',
  9129. })
  9130. .then(function (bitmap) {
  9131. if (this$1.destroyed)
  9132. {
  9133. return Promise.reject();
  9134. }
  9135. this$1.bitmap = bitmap;
  9136. this$1.update();
  9137. this$1._process = null;
  9138. return Promise.resolve(this$1);
  9139. });
  9140. return this._process;
  9141. };
  9142. /**
  9143. * Upload the image resource to GPU.
  9144. *
  9145. * @param {PIXI.Renderer} renderer - Renderer to upload to
  9146. * @param {PIXI.BaseTexture} baseTexture - BaseTexture for this resource
  9147. * @param {PIXI.GLTexture} glTexture - GLTexture to use
  9148. * @returns {boolean} true is success
  9149. */
  9150. ImageResource.prototype.upload = function upload (renderer, baseTexture, glTexture)
  9151. {
  9152. baseTexture.premultiplyAlpha = this.premultiplyAlpha;
  9153. if (!this.createBitmap)
  9154. {
  9155. return BaseImageResource.prototype.upload.call(this, renderer, baseTexture, glTexture);
  9156. }
  9157. if (!this.bitmap)
  9158. {
  9159. // yeah, ignore the output
  9160. this.process();
  9161. if (!this.bitmap)
  9162. {
  9163. return false;
  9164. }
  9165. }
  9166. BaseImageResource.prototype.upload.call(this, renderer, baseTexture, glTexture, this.bitmap);
  9167. if (!this.preserveBitmap)
  9168. {
  9169. // checks if there are other renderers that possibly need this bitmap
  9170. var flag = true;
  9171. for (var key in baseTexture._glTextures)
  9172. {
  9173. var otherTex = baseTexture._glTextures[key];
  9174. if (otherTex !== glTexture && otherTex.dirtyId !== baseTexture.dirtyId)
  9175. {
  9176. flag = false;
  9177. break;
  9178. }
  9179. }
  9180. if (flag)
  9181. {
  9182. if (this.bitmap.close)
  9183. {
  9184. this.bitmap.close();
  9185. }
  9186. this.bitmap = null;
  9187. }
  9188. }
  9189. return true;
  9190. };
  9191. /**
  9192. * Destroys this texture
  9193. * @override
  9194. */
  9195. ImageResource.prototype.dispose = function dispose ()
  9196. {
  9197. BaseImageResource.prototype.dispose.call(this);
  9198. if (this.bitmap)
  9199. {
  9200. this.bitmap.close();
  9201. this.bitmap = null;
  9202. }
  9203. this._process = null;
  9204. this._load = null;
  9205. };
  9206. return ImageResource;
  9207. }(BaseImageResource));
  9208. /**
  9209. * Collection of installed resource types, class must extend {@link PIXI.resources.Resource}.
  9210. * @example
  9211. * class CustomResource extends PIXI.resources.Resource {
  9212. * // MUST have source, options constructor signature
  9213. * // for auto-detected resources to be created.
  9214. * constructor(source, options) {
  9215. * super();
  9216. * }
  9217. * upload(renderer, baseTexture, glTexture) {
  9218. * // upload with GL
  9219. * return true;
  9220. * }
  9221. * // used to auto-detect resource
  9222. * static test(source, extension) {
  9223. * return extension === 'xyz'|| source instanceof SomeClass;
  9224. * }
  9225. * }
  9226. * // Install the new resource type
  9227. * PIXI.resources.INSTALLED.push(CustomResource);
  9228. *
  9229. * @name PIXI.resources.INSTALLED
  9230. * @type {Array<*>}
  9231. * @static
  9232. * @readonly
  9233. */
  9234. var INSTALLED = [];
  9235. /**
  9236. * Create a resource element from a single source element. This
  9237. * auto-detects which type of resource to create. All resources that
  9238. * are auto-detectable must have a static `test` method and a constructor
  9239. * with the arguments `(source, options?)`. Currently, the supported
  9240. * resources for auto-detection include:
  9241. * - {@link PIXI.resources.ImageResource}
  9242. * - {@link PIXI.resources.CanvasResource}
  9243. * - {@link PIXI.resources.VideoResource}
  9244. * - {@link PIXI.resources.SVGResource}
  9245. * - {@link PIXI.resources.BufferResource}
  9246. * @static
  9247. * @function PIXI.resources.autoDetectResource
  9248. * @param {string|*} source - Resource source, this can be the URL to the resource,
  9249. * a typed-array (for BufferResource), HTMLVideoElement, SVG data-uri
  9250. * or any other resource that can be auto-detected. If not resource is
  9251. * detected, it's assumed to be an ImageResource.
  9252. * @param {object} [options] - Pass-through options to use for Resource
  9253. * @param {number} [options.width] - BufferResource's width
  9254. * @param {number} [options.height] - BufferResource's height
  9255. * @param {boolean} [options.autoLoad=true] - Image, SVG and Video flag to start loading
  9256. * @param {number} [options.scale=1] - SVG source scale
  9257. * @param {boolean} [options.createBitmap=PIXI.settings.CREATE_IMAGE_BITMAP] - Image option to create Bitmap object
  9258. * @param {boolean} [options.crossorigin=true] - Image and Video option to set crossOrigin
  9259. * @param {boolean} [options.autoPlay=true] - Video option to start playing video immediately
  9260. * @param {number} [options.updateFPS=0] - Video option to update how many times a second the
  9261. * texture should be updated from the video. Leave at 0 to update at every render
  9262. * @return {PIXI.resources.Resource} The created resource.
  9263. */
  9264. function autoDetectResource(source, options)
  9265. {
  9266. if (!source)
  9267. {
  9268. return null;
  9269. }
  9270. var extension = '';
  9271. if (typeof source === 'string')
  9272. {
  9273. // search for file extension: period, 3-4 chars, then ?, # or EOL
  9274. var result = (/\.(\w{3,4})(?:$|\?|#)/i).exec(source);
  9275. if (result)
  9276. {
  9277. extension = result[1].toLowerCase();
  9278. }
  9279. }
  9280. for (var i = INSTALLED.length - 1; i >= 0; --i)
  9281. {
  9282. var ResourcePlugin = INSTALLED[i];
  9283. if (ResourcePlugin.test && ResourcePlugin.test(source, extension))
  9284. {
  9285. return new ResourcePlugin(source, options);
  9286. }
  9287. }
  9288. // When in doubt: probably an image
  9289. // might be appropriate to throw an error or return null
  9290. return new ImageResource(source, options);
  9291. }
  9292. /**
  9293. * @interface SharedArrayBuffer
  9294. */
  9295. /**
  9296. * Buffer resource with data of typed array.
  9297. * @class
  9298. * @extends PIXI.resources.Resource
  9299. * @memberof PIXI.resources
  9300. */
  9301. var BufferResource = /*@__PURE__*/(function (Resource) {
  9302. function BufferResource(source, options)
  9303. {
  9304. var ref = options || {};
  9305. var width = ref.width;
  9306. var height = ref.height;
  9307. if (!width || !height)
  9308. {
  9309. throw new Error('BufferResource width or height invalid');
  9310. }
  9311. Resource.call(this, width, height);
  9312. /**
  9313. * Source array
  9314. * Cannot be ClampedUint8Array because it cant be uploaded to WebGL
  9315. *
  9316. * @member {Float32Array|Uint8Array|Uint32Array}
  9317. */
  9318. this.data = source;
  9319. }
  9320. if ( Resource ) { BufferResource.__proto__ = Resource; }
  9321. BufferResource.prototype = Object.create( Resource && Resource.prototype );
  9322. BufferResource.prototype.constructor = BufferResource;
  9323. /**
  9324. * Upload the texture to the GPU.
  9325. * @param {PIXI.Renderer} renderer Upload to the renderer
  9326. * @param {PIXI.BaseTexture} baseTexture Reference to parent texture
  9327. * @param {PIXI.GLTexture} glTexture glTexture
  9328. * @returns {boolean} true is success
  9329. */
  9330. BufferResource.prototype.upload = function upload (renderer, baseTexture, glTexture)
  9331. {
  9332. var gl = renderer.gl;
  9333. gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, baseTexture.premultiplyAlpha);
  9334. if (glTexture.width === baseTexture.width && glTexture.height === baseTexture.height)
  9335. {
  9336. gl.texSubImage2D(
  9337. baseTexture.target,
  9338. 0,
  9339. 0,
  9340. 0,
  9341. baseTexture.width,
  9342. baseTexture.height,
  9343. baseTexture.format,
  9344. baseTexture.type,
  9345. this.data
  9346. );
  9347. }
  9348. else
  9349. {
  9350. glTexture.width = baseTexture.width;
  9351. glTexture.height = baseTexture.height;
  9352. var internalFormat = baseTexture.format;
  9353. // guess sized format by type and format
  9354. // https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/texImage2D
  9355. if (renderer.context.webGLVersion === 2
  9356. && baseTexture.type === renderer.gl.FLOAT
  9357. && baseTexture.format === renderer.gl.RGBA)
  9358. {
  9359. internalFormat = renderer.gl.RGBA32F;
  9360. }
  9361. gl.texImage2D(
  9362. baseTexture.target,
  9363. 0,
  9364. internalFormat,
  9365. baseTexture.width,
  9366. baseTexture.height,
  9367. 0,
  9368. baseTexture.format,
  9369. baseTexture.type,
  9370. this.data
  9371. );
  9372. }
  9373. return true;
  9374. };
  9375. /**
  9376. * Destroy and don't use after this
  9377. * @override
  9378. */
  9379. BufferResource.prototype.dispose = function dispose ()
  9380. {
  9381. this.data = null;
  9382. };
  9383. /**
  9384. * Used to auto-detect the type of resource.
  9385. *
  9386. * @static
  9387. * @param {*} source - The source object
  9388. * @return {boolean} `true` if <canvas>
  9389. */
  9390. BufferResource.test = function test (source)
  9391. {
  9392. return source instanceof Float32Array
  9393. || source instanceof Uint8Array
  9394. || source instanceof Uint32Array;
  9395. };
  9396. return BufferResource;
  9397. }(Resource));
  9398. var defaultBufferOptions = {
  9399. scaleMode: SCALE_MODES.NEAREST,
  9400. format: FORMATS.RGBA,
  9401. premultiplyAlpha: false,
  9402. };
  9403. /**
  9404. * A Texture stores the information that represents an image.
  9405. * All textures have a base texture, which contains information about the source.
  9406. * Therefore you can have many textures all using a single BaseTexture
  9407. *
  9408. * @class
  9409. * @extends PIXI.utils.EventEmitter
  9410. * @memberof PIXI
  9411. * @param {PIXI.resources.Resource|string|HTMLImageElement|HTMLCanvasElement|HTMLVideoElement} [resource=null]
  9412. * The current resource to use, for things that aren't Resource objects, will be converted
  9413. * into a Resource.
  9414. * @param {Object} [options] - Collection of options
  9415. * @param {PIXI.MIPMAP_MODES} [options.mipmap=PIXI.settings.MIPMAP_TEXTURES] - If mipmapping is enabled for texture
  9416. * @param {PIXI.WRAP_MODES} [options.wrapMode=PIXI.settings.WRAP_MODE] - Wrap mode for textures
  9417. * @param {PIXI.SCALE_MODES} [options.scaleMode=PIXI.settings.SCALE_MODE] - Default scale mode, linear, nearest
  9418. * @param {PIXI.FORMATS} [options.format=PIXI.FORMATS.RGBA] - GL format type
  9419. * @param {PIXI.TYPES} [options.type=PIXI.TYPES.UNSIGNED_BYTE] - GL data type
  9420. * @param {PIXI.TARGETS} [options.target=PIXI.TARGETS.TEXTURE_2D] - GL texture target
  9421. * @param {boolean} [options.premultiplyAlpha=true] - Pre multiply the image alpha
  9422. * @param {number} [options.width=0] - Width of the texture
  9423. * @param {number} [options.height=0] - Height of the texture
  9424. * @param {object} [options.resourceOptions] - Optional resource options,
  9425. * see {@link PIXI.resources.autoDetectResource autoDetectResource}
  9426. */
  9427. var BaseTexture = /*@__PURE__*/(function (EventEmitter) {
  9428. function BaseTexture(resource, options)
  9429. {
  9430. if ( resource === void 0 ) { resource = null; }
  9431. if ( options === void 0 ) { options = null; }
  9432. EventEmitter.call(this);
  9433. options = options || {};
  9434. var premultiplyAlpha = options.premultiplyAlpha;
  9435. var mipmap = options.mipmap;
  9436. var scaleMode = options.scaleMode;
  9437. var width = options.width;
  9438. var height = options.height;
  9439. var wrapMode = options.wrapMode;
  9440. var format = options.format;
  9441. var type = options.type;
  9442. var target = options.target;
  9443. var resolution = options.resolution;
  9444. var resourceOptions = options.resourceOptions;
  9445. // Convert the resource to a Resource object
  9446. if (resource && !(resource instanceof Resource))
  9447. {
  9448. resource = autoDetectResource(resource, resourceOptions);
  9449. resource.internal = true;
  9450. }
  9451. /**
  9452. * The width of the base texture set when the image has loaded
  9453. *
  9454. * @readonly
  9455. * @member {number}
  9456. */
  9457. this.width = width || 0;
  9458. /**
  9459. * The height of the base texture set when the image has loaded
  9460. *
  9461. * @readonly
  9462. * @member {number}
  9463. */
  9464. this.height = height || 0;
  9465. /**
  9466. * The resolution / device pixel ratio of the texture
  9467. *
  9468. * @member {number}
  9469. * @default PIXI.settings.RESOLUTION
  9470. */
  9471. this.resolution = resolution || settings.RESOLUTION;
  9472. /**
  9473. * Mipmap mode of the texture, affects downscaled images
  9474. *
  9475. * @member {PIXI.MIPMAP_MODES}
  9476. * @default PIXI.settings.MIPMAP_TEXTURES
  9477. */
  9478. this.mipmap = mipmap !== undefined ? mipmap : settings.MIPMAP_TEXTURES;
  9479. /**
  9480. * How the texture wraps
  9481. * @member {number}
  9482. */
  9483. this.wrapMode = wrapMode || settings.WRAP_MODE;
  9484. /**
  9485. * The scale mode to apply when scaling this texture
  9486. *
  9487. * @member {PIXI.SCALE_MODES}
  9488. * @default PIXI.settings.SCALE_MODE
  9489. */
  9490. this.scaleMode = scaleMode !== undefined ? scaleMode : settings.SCALE_MODE;
  9491. /**
  9492. * The pixel format of the texture
  9493. *
  9494. * @member {PIXI.FORMATS}
  9495. * @default PIXI.FORMATS.RGBA
  9496. */
  9497. this.format = format || FORMATS.RGBA;
  9498. /**
  9499. * The type of resource data
  9500. *
  9501. * @member {PIXI.TYPES}
  9502. * @default PIXI.TYPES.UNSIGNED_BYTE
  9503. */
  9504. this.type = type || TYPES.UNSIGNED_BYTE;
  9505. /**
  9506. * The target type
  9507. *
  9508. * @member {PIXI.TARGETS}
  9509. * @default PIXI.TARGETS.TEXTURE_2D
  9510. */
  9511. this.target = target || TARGETS.TEXTURE_2D;
  9512. /**
  9513. * Set to true to enable pre-multiplied alpha
  9514. *
  9515. * @member {boolean}
  9516. * @default true
  9517. */
  9518. this.premultiplyAlpha = premultiplyAlpha !== false;
  9519. /**
  9520. * Global unique identifier for this BaseTexture
  9521. *
  9522. * @member {string}
  9523. * @protected
  9524. */
  9525. this.uid = uid();
  9526. /**
  9527. * Used by automatic texture Garbage Collection, stores last GC tick when it was bound
  9528. *
  9529. * @member {number}
  9530. * @protected
  9531. */
  9532. this.touched = 0;
  9533. /**
  9534. * Whether or not the texture is a power of two, try to use power of two textures as much
  9535. * as you can
  9536. *
  9537. * @readonly
  9538. * @member {boolean}
  9539. * @default false
  9540. */
  9541. this.isPowerOfTwo = false;
  9542. this._refreshPOT();
  9543. /**
  9544. * The map of render context textures where this is bound
  9545. *
  9546. * @member {Object}
  9547. * @private
  9548. */
  9549. this._glTextures = {};
  9550. /**
  9551. * Used by TextureSystem to only update texture to the GPU when needed.
  9552. *
  9553. * @protected
  9554. * @member {number}
  9555. */
  9556. this.dirtyId = 0;
  9557. /**
  9558. * Used by TextureSystem to only update texture style when needed.
  9559. *
  9560. * @protected
  9561. * @member {number}
  9562. */
  9563. this.dirtyStyleId = 0;
  9564. /**
  9565. * Currently default cache ID.
  9566. *
  9567. * @member {string}
  9568. */
  9569. this.cacheId = null;
  9570. /**
  9571. * Generally speaking means when resource is loaded.
  9572. * @readonly
  9573. * @member {boolean}
  9574. */
  9575. this.valid = width > 0 && height > 0;
  9576. /**
  9577. * The collection of alternative cache ids, since some BaseTextures
  9578. * can have more than one ID, short name and longer full URL
  9579. *
  9580. * @member {Array<string>}
  9581. * @readonly
  9582. */
  9583. this.textureCacheIds = [];
  9584. /**
  9585. * Flag if BaseTexture has been destroyed.
  9586. *
  9587. * @member {boolean}
  9588. * @readonly
  9589. */
  9590. this.destroyed = false;
  9591. /**
  9592. * The resource used by this BaseTexture, there can only
  9593. * be one resource per BaseTexture, but textures can share
  9594. * resources.
  9595. *
  9596. * @member {PIXI.resources.Resource}
  9597. * @readonly
  9598. */
  9599. this.resource = null;
  9600. /**
  9601. * Number of the texture batch, used by multi-texture renderers
  9602. *
  9603. * @member {number}
  9604. */
  9605. this._batchEnabled = 0;
  9606. /**
  9607. * Fired when a not-immediately-available source finishes loading.
  9608. *
  9609. * @protected
  9610. * @event PIXI.BaseTexture#loaded
  9611. * @param {PIXI.BaseTexture} baseTexture - Resource loaded.
  9612. */
  9613. /**
  9614. * Fired when a not-immediately-available source fails to load.
  9615. *
  9616. * @protected
  9617. * @event PIXI.BaseTexture#error
  9618. * @param {PIXI.BaseTexture} baseTexture - Resource errored.
  9619. */
  9620. /**
  9621. * Fired when BaseTexture is updated.
  9622. *
  9623. * @protected
  9624. * @event PIXI.BaseTexture#loaded
  9625. * @param {PIXI.BaseTexture} baseTexture - Resource loaded.
  9626. */
  9627. /**
  9628. * Fired when BaseTexture is destroyed.
  9629. *
  9630. * @protected
  9631. * @event PIXI.BaseTexture#error
  9632. * @param {PIXI.BaseTexture} baseTexture - Resource errored.
  9633. */
  9634. /**
  9635. * Fired when BaseTexture is updated.
  9636. *
  9637. * @protected
  9638. * @event PIXI.BaseTexture#update
  9639. * @param {PIXI.BaseTexture} baseTexture - Instance of texture being updated.
  9640. */
  9641. /**
  9642. * Fired when BaseTexture is destroyed.
  9643. *
  9644. * @protected
  9645. * @event PIXI.BaseTexture#dispose
  9646. * @param {PIXI.BaseTexture} baseTexture - Instance of texture being destroyed.
  9647. */
  9648. // Set the resource
  9649. this.setResource(resource);
  9650. }
  9651. if ( EventEmitter ) { BaseTexture.__proto__ = EventEmitter; }
  9652. BaseTexture.prototype = Object.create( EventEmitter && EventEmitter.prototype );
  9653. BaseTexture.prototype.constructor = BaseTexture;
  9654. var prototypeAccessors = { realWidth: { configurable: true },realHeight: { configurable: true } };
  9655. /**
  9656. * Pixel width of the source of this texture
  9657. *
  9658. * @readonly
  9659. * @member {number}
  9660. */
  9661. prototypeAccessors.realWidth.get = function ()
  9662. {
  9663. return this.width * this.resolution;
  9664. };
  9665. /**
  9666. * Pixel height of the source of this texture
  9667. *
  9668. * @readonly
  9669. * @member {number}
  9670. */
  9671. prototypeAccessors.realHeight.get = function ()
  9672. {
  9673. return this.height * this.resolution;
  9674. };
  9675. /**
  9676. * Changes style options of BaseTexture
  9677. *
  9678. * @param {PIXI.SCALE_MODES} [scaleMode] - Pixi scalemode
  9679. * @param {PIXI.MIPMAP_MODES} [mipmap] - enable mipmaps
  9680. * @returns {PIXI.BaseTexture} this
  9681. */
  9682. BaseTexture.prototype.setStyle = function setStyle (scaleMode, mipmap)
  9683. {
  9684. var dirty;
  9685. if (scaleMode !== undefined && scaleMode !== this.scaleMode)
  9686. {
  9687. this.scaleMode = scaleMode;
  9688. dirty = true;
  9689. }
  9690. if (mipmap !== undefined && mipmap !== this.mipmap)
  9691. {
  9692. this.mipmap = mipmap;
  9693. dirty = true;
  9694. }
  9695. if (dirty)
  9696. {
  9697. this.dirtyStyleId++;
  9698. }
  9699. return this;
  9700. };
  9701. /**
  9702. * Changes w/h/resolution. Texture becomes valid if width and height are greater than zero.
  9703. *
  9704. * @param {number} width Visual width
  9705. * @param {number} height Visual height
  9706. * @param {number} [resolution] Optionally set resolution
  9707. * @returns {PIXI.BaseTexture} this
  9708. */
  9709. BaseTexture.prototype.setSize = function setSize (width, height, resolution)
  9710. {
  9711. this.resolution = resolution || this.resolution;
  9712. this.width = width;
  9713. this.height = height;
  9714. this._refreshPOT();
  9715. this.update();
  9716. return this;
  9717. };
  9718. /**
  9719. * Sets real size of baseTexture, preserves current resolution.
  9720. *
  9721. * @param {number} realWidth Full rendered width
  9722. * @param {number} realHeight Full rendered height
  9723. * @param {number} [resolution] Optionally set resolution
  9724. * @returns {PIXI.BaseTexture} this
  9725. */
  9726. BaseTexture.prototype.setRealSize = function setRealSize (realWidth, realHeight, resolution)
  9727. {
  9728. this.resolution = resolution || this.resolution;
  9729. this.width = realWidth / this.resolution;
  9730. this.height = realHeight / this.resolution;
  9731. this._refreshPOT();
  9732. this.update();
  9733. return this;
  9734. };
  9735. /**
  9736. * Refresh check for isPowerOfTwo texture based on size
  9737. *
  9738. * @private
  9739. */
  9740. BaseTexture.prototype._refreshPOT = function _refreshPOT ()
  9741. {
  9742. this.isPowerOfTwo = isPow2(this.realWidth) && isPow2(this.realHeight);
  9743. };
  9744. /**
  9745. * Changes resolution
  9746. *
  9747. * @param {number} [resolution] res
  9748. * @returns {PIXI.BaseTexture} this
  9749. */
  9750. BaseTexture.prototype.setResolution = function setResolution (resolution)
  9751. {
  9752. var oldResolution = this.resolution;
  9753. if (oldResolution === resolution)
  9754. {
  9755. return this;
  9756. }
  9757. this.resolution = resolution;
  9758. if (this.valid)
  9759. {
  9760. this.width = this.width * oldResolution / resolution;
  9761. this.height = this.height * oldResolution / resolution;
  9762. this.emit('update', this);
  9763. }
  9764. this._refreshPOT();
  9765. return this;
  9766. };
  9767. /**
  9768. * Sets the resource if it wasn't set. Throws error if resource already present
  9769. *
  9770. * @param {PIXI.resources.Resource} resource - that is managing this BaseTexture
  9771. * @returns {PIXI.BaseTexture} this
  9772. */
  9773. BaseTexture.prototype.setResource = function setResource (resource)
  9774. {
  9775. if (this.resource === resource)
  9776. {
  9777. return this;
  9778. }
  9779. if (this.resource)
  9780. {
  9781. throw new Error('Resource can be set only once');
  9782. }
  9783. resource.bind(this);
  9784. this.resource = resource;
  9785. return this;
  9786. };
  9787. /**
  9788. * Invalidates the object. Texture becomes valid if width and height are greater than zero.
  9789. */
  9790. BaseTexture.prototype.update = function update ()
  9791. {
  9792. if (!this.valid)
  9793. {
  9794. if (this.width > 0 && this.height > 0)
  9795. {
  9796. this.valid = true;
  9797. this.emit('loaded', this);
  9798. this.emit('update', this);
  9799. }
  9800. }
  9801. else
  9802. {
  9803. this.dirtyId++;
  9804. this.dirtyStyleId++;
  9805. this.emit('update', this);
  9806. }
  9807. };
  9808. /**
  9809. * Destroys this base texture.
  9810. * The method stops if resource doesn't want this texture to be destroyed.
  9811. * Removes texture from all caches.
  9812. */
  9813. BaseTexture.prototype.destroy = function destroy ()
  9814. {
  9815. // remove and destroy the resource
  9816. if (this.resource)
  9817. {
  9818. this.resource.unbind(this);
  9819. // only destroy resourced created internally
  9820. if (this.resource.internal)
  9821. {
  9822. this.resource.destroy();
  9823. }
  9824. this.resource = null;
  9825. }
  9826. if (this.cacheId)
  9827. {
  9828. delete BaseTextureCache[this.cacheId];
  9829. delete TextureCache[this.cacheId];
  9830. this.cacheId = null;
  9831. }
  9832. // finally let the WebGL renderer know..
  9833. this.dispose();
  9834. BaseTexture.removeFromCache(this);
  9835. this.textureCacheIds = null;
  9836. this.destroyed = true;
  9837. };
  9838. /**
  9839. * Frees the texture from WebGL memory without destroying this texture object.
  9840. * This means you can still use the texture later which will upload it to GPU
  9841. * memory again.
  9842. *
  9843. * @fires PIXI.BaseTexture#dispose
  9844. */
  9845. BaseTexture.prototype.dispose = function dispose ()
  9846. {
  9847. this.emit('dispose', this);
  9848. };
  9849. /**
  9850. * Helper function that creates a base texture based on the source you provide.
  9851. * The source can be - image url, image element, canvas element. If the
  9852. * source is an image url or an image element and not in the base texture
  9853. * cache, it will be created and loaded.
  9854. *
  9855. * @static
  9856. * @param {string|HTMLImageElement|HTMLCanvasElement|SVGElement|HTMLVideoElement} source - The
  9857. * source to create base texture from.
  9858. * @param {object} [options] See {@link PIXI.BaseTexture}'s constructor for options.
  9859. * @returns {PIXI.BaseTexture} The new base texture.
  9860. */
  9861. BaseTexture.from = function from (source, options)
  9862. {
  9863. var cacheId = null;
  9864. if (typeof source === 'string')
  9865. {
  9866. cacheId = source;
  9867. }
  9868. else
  9869. {
  9870. if (!source._pixiId)
  9871. {
  9872. source._pixiId = "pixiid_" + (uid());
  9873. }
  9874. cacheId = source._pixiId;
  9875. }
  9876. var baseTexture = BaseTextureCache[cacheId];
  9877. if (!baseTexture)
  9878. {
  9879. baseTexture = new BaseTexture(source, options);
  9880. baseTexture.cacheId = cacheId;
  9881. BaseTexture.addToCache(baseTexture, cacheId);
  9882. }
  9883. return baseTexture;
  9884. };
  9885. /**
  9886. * Create a new BaseTexture with a BufferResource from a Float32Array.
  9887. * RGBA values are floats from 0 to 1.
  9888. * @static
  9889. * @param {Float32Array|Uint8Array} buffer The optional array to use, if no data
  9890. * is provided, a new Float32Array is created.
  9891. * @param {number} width - Width of the resource
  9892. * @param {number} height - Height of the resource
  9893. * @param {object} [options] See {@link PIXI.BaseTexture}'s constructor for options.
  9894. * @return {PIXI.BaseTexture} The resulting new BaseTexture
  9895. */
  9896. BaseTexture.fromBuffer = function fromBuffer (buffer, width, height, options)
  9897. {
  9898. buffer = buffer || new Float32Array(width * height * 4);
  9899. var resource = new BufferResource(buffer, { width: width, height: height });
  9900. var type = buffer instanceof Float32Array ? TYPES.FLOAT : TYPES.UNSIGNED_BYTE;
  9901. return new BaseTexture(resource, Object.assign(defaultBufferOptions, options || { width: width, height: height, type: type }));
  9902. };
  9903. /**
  9904. * Adds a BaseTexture to the global BaseTextureCache. This cache is shared across the whole PIXI object.
  9905. *
  9906. * @static
  9907. * @param {PIXI.BaseTexture} baseTexture - The BaseTexture to add to the cache.
  9908. * @param {string} id - The id that the BaseTexture will be stored against.
  9909. */
  9910. BaseTexture.addToCache = function addToCache (baseTexture, id)
  9911. {
  9912. if (id)
  9913. {
  9914. if (baseTexture.textureCacheIds.indexOf(id) === -1)
  9915. {
  9916. baseTexture.textureCacheIds.push(id);
  9917. }
  9918. if (BaseTextureCache[id])
  9919. {
  9920. // eslint-disable-next-line no-console
  9921. console.warn(("BaseTexture added to the cache with an id [" + id + "] that already had an entry"));
  9922. }
  9923. BaseTextureCache[id] = baseTexture;
  9924. }
  9925. };
  9926. /**
  9927. * Remove a BaseTexture from the global BaseTextureCache.
  9928. *
  9929. * @static
  9930. * @param {string|PIXI.BaseTexture} baseTexture - id of a BaseTexture to be removed, or a BaseTexture instance itself.
  9931. * @return {PIXI.BaseTexture|null} The BaseTexture that was removed.
  9932. */
  9933. BaseTexture.removeFromCache = function removeFromCache (baseTexture)
  9934. {
  9935. if (typeof baseTexture === 'string')
  9936. {
  9937. var baseTextureFromCache = BaseTextureCache[baseTexture];
  9938. if (baseTextureFromCache)
  9939. {
  9940. var index = baseTextureFromCache.textureCacheIds.indexOf(baseTexture);
  9941. if (index > -1)
  9942. {
  9943. baseTextureFromCache.textureCacheIds.splice(index, 1);
  9944. }
  9945. delete BaseTextureCache[baseTexture];
  9946. return baseTextureFromCache;
  9947. }
  9948. }
  9949. else if (baseTexture && baseTexture.textureCacheIds)
  9950. {
  9951. for (var i = 0; i < baseTexture.textureCacheIds.length; ++i)
  9952. {
  9953. delete BaseTextureCache[baseTexture.textureCacheIds[i]];
  9954. }
  9955. baseTexture.textureCacheIds.length = 0;
  9956. return baseTexture;
  9957. }
  9958. return null;
  9959. };
  9960. Object.defineProperties( BaseTexture.prototype, prototypeAccessors );
  9961. return BaseTexture;
  9962. }(eventemitter3));
  9963. /**
  9964. * Global number of the texture batch, used by multi-texture renderers
  9965. *
  9966. * @static
  9967. * @member {number}
  9968. */
  9969. BaseTexture._globalBatch = 0;
  9970. /**
  9971. * A resource that contains a number of sources.
  9972. *
  9973. * @class
  9974. * @extends PIXI.resources.Resource
  9975. * @memberof PIXI.resources
  9976. * @param {number|Array<*>} source - Number of items in array or the collection
  9977. * of image URLs to use. Can also be resources, image elements, canvas, etc.
  9978. * @param {object} [options] Options to apply to {@link PIXI.resources.autoDetectResource}
  9979. * @param {number} [options.width] - Width of the resource
  9980. * @param {number} [options.height] - Height of the resource
  9981. */
  9982. var ArrayResource = /*@__PURE__*/(function (Resource) {
  9983. function ArrayResource(source, options)
  9984. {
  9985. options = options || {};
  9986. var urls;
  9987. var length = source;
  9988. if (Array.isArray(source))
  9989. {
  9990. urls = source;
  9991. length = source.length;
  9992. }
  9993. Resource.call(this, options.width, options.height);
  9994. /**
  9995. * Collection of resources.
  9996. * @member {Array<PIXI.BaseTexture>}
  9997. * @readonly
  9998. */
  9999. this.items = [];
  10000. /**
  10001. * Dirty IDs for each part
  10002. * @member {Array<number>}
  10003. * @readonly
  10004. */
  10005. this.itemDirtyIds = [];
  10006. for (var i = 0; i < length; i++)
  10007. {
  10008. var partTexture = new BaseTexture();
  10009. this.items.push(partTexture);
  10010. this.itemDirtyIds.push(-1);
  10011. }
  10012. /**
  10013. * Number of elements in array
  10014. *
  10015. * @member {number}
  10016. * @readonly
  10017. */
  10018. this.length = length;
  10019. /**
  10020. * Promise when loading
  10021. * @member {Promise}
  10022. * @private
  10023. * @default null
  10024. */
  10025. this._load = null;
  10026. if (urls)
  10027. {
  10028. for (var i$1 = 0; i$1 < length; i$1++)
  10029. {
  10030. this.addResourceAt(autoDetectResource(urls[i$1], options), i$1);
  10031. }
  10032. }
  10033. }
  10034. if ( Resource ) { ArrayResource.__proto__ = Resource; }
  10035. ArrayResource.prototype = Object.create( Resource && Resource.prototype );
  10036. ArrayResource.prototype.constructor = ArrayResource;
  10037. /**
  10038. * Destroy this BaseImageResource
  10039. * @override
  10040. */
  10041. ArrayResource.prototype.dispose = function dispose ()
  10042. {
  10043. for (var i = 0, len = this.length; i < len; i++)
  10044. {
  10045. this.items[i].destroy();
  10046. }
  10047. this.items = null;
  10048. this.itemDirtyIds = null;
  10049. this._load = null;
  10050. };
  10051. /**
  10052. * Set a resource by ID
  10053. *
  10054. * @param {PIXI.resources.Resource} resource
  10055. * @param {number} index - Zero-based index of resource to set
  10056. * @return {PIXI.resources.ArrayResource} Instance for chaining
  10057. */
  10058. ArrayResource.prototype.addResourceAt = function addResourceAt (resource, index)
  10059. {
  10060. var baseTexture = this.items[index];
  10061. if (!baseTexture)
  10062. {
  10063. throw new Error(("Index " + index + " is out of bounds"));
  10064. }
  10065. // Inherit the first resource dimensions
  10066. if (resource.valid && !this.valid)
  10067. {
  10068. this.resize(resource.width, resource.height);
  10069. }
  10070. this.items[index].setResource(resource);
  10071. return this;
  10072. };
  10073. /**
  10074. * Set the parent base texture
  10075. * @member {PIXI.BaseTexture}
  10076. * @override
  10077. */
  10078. ArrayResource.prototype.bind = function bind (baseTexture)
  10079. {
  10080. Resource.prototype.bind.call(this, baseTexture);
  10081. baseTexture.target = TARGETS.TEXTURE_2D_ARRAY;
  10082. for (var i = 0; i < this.length; i++)
  10083. {
  10084. this.items[i].on('update', baseTexture.update, baseTexture);
  10085. }
  10086. };
  10087. /**
  10088. * Unset the parent base texture
  10089. * @member {PIXI.BaseTexture}
  10090. * @override
  10091. */
  10092. ArrayResource.prototype.unbind = function unbind (baseTexture)
  10093. {
  10094. Resource.prototype.unbind.call(this, baseTexture);
  10095. for (var i = 0; i < this.length; i++)
  10096. {
  10097. this.items[i].off('update', baseTexture.update, baseTexture);
  10098. }
  10099. };
  10100. /**
  10101. * Load all the resources simultaneously
  10102. * @override
  10103. * @return {Promise<void>} When load is resolved
  10104. */
  10105. ArrayResource.prototype.load = function load ()
  10106. {
  10107. var this$1 = this;
  10108. if (this._load)
  10109. {
  10110. return this._load;
  10111. }
  10112. var resources = this.items.map(function (item) { return item.resource; });
  10113. // TODO: also implement load part-by-part strategy
  10114. var promises = resources.map(function (item) { return item.load(); });
  10115. this._load = Promise.all(promises)
  10116. .then(function () {
  10117. var ref = resources[0];
  10118. var width = ref.width;
  10119. var height = ref.height;
  10120. this$1.resize(width, height);
  10121. return Promise.resolve(this$1);
  10122. }
  10123. );
  10124. return this._load;
  10125. };
  10126. /**
  10127. * Upload the resources to the GPU.
  10128. * @param {PIXI.Renderer} renderer
  10129. * @param {PIXI.BaseTexture} texture
  10130. * @param {PIXI.GLTexture} glTexture
  10131. * @returns {boolean} whether texture was uploaded
  10132. */
  10133. ArrayResource.prototype.upload = function upload (renderer, texture, glTexture)
  10134. {
  10135. var ref = this;
  10136. var length = ref.length;
  10137. var itemDirtyIds = ref.itemDirtyIds;
  10138. var items = ref.items;
  10139. var gl = renderer.gl;
  10140. if (glTexture.dirtyId < 0)
  10141. {
  10142. gl.texImage3D(
  10143. gl.TEXTURE_2D_ARRAY,
  10144. 0,
  10145. texture.format,
  10146. this._width,
  10147. this._height,
  10148. length,
  10149. 0,
  10150. texture.format,
  10151. texture.type,
  10152. null
  10153. );
  10154. }
  10155. for (var i = 0; i < length; i++)
  10156. {
  10157. var item = items[i];
  10158. if (itemDirtyIds[i] < item.dirtyId)
  10159. {
  10160. itemDirtyIds[i] = item.dirtyId;
  10161. if (item.valid)
  10162. {
  10163. gl.texSubImage3D(
  10164. gl.TEXTURE_2D_ARRAY,
  10165. 0,
  10166. 0, // xoffset
  10167. 0, // yoffset
  10168. i, // zoffset
  10169. item.resource.width,
  10170. item.resource.height,
  10171. 1,
  10172. texture.format,
  10173. texture.type,
  10174. item.resource.source
  10175. );
  10176. }
  10177. }
  10178. }
  10179. return true;
  10180. };
  10181. return ArrayResource;
  10182. }(Resource));
  10183. /**
  10184. * Resource type for HTMLCanvasElement.
  10185. * @class
  10186. * @extends PIXI.resources.BaseImageResource
  10187. * @memberof PIXI.resources
  10188. * @param {HTMLCanvasElement} source - Canvas element to use
  10189. */
  10190. var CanvasResource = /*@__PURE__*/(function (BaseImageResource) {
  10191. function CanvasResource () {
  10192. BaseImageResource.apply(this, arguments);
  10193. }
  10194. if ( BaseImageResource ) { CanvasResource.__proto__ = BaseImageResource; }
  10195. CanvasResource.prototype = Object.create( BaseImageResource && BaseImageResource.prototype );
  10196. CanvasResource.prototype.constructor = CanvasResource;
  10197. CanvasResource.test = function test (source)
  10198. {
  10199. return (source instanceof HTMLCanvasElement);
  10200. };
  10201. return CanvasResource;
  10202. }(BaseImageResource));
  10203. /**
  10204. * Resource for a CubeTexture which contains six resources.
  10205. *
  10206. * @class
  10207. * @extends PIXI.resources.ArrayResource
  10208. * @memberof PIXI.resources
  10209. * @param {Array<string|PIXI.resources.Resource>} [source] Collection of URLs or resources
  10210. * to use as the sides of the cube.
  10211. * @param {object} [options] - ImageResource options
  10212. * @param {number} [options.width] - Width of resource
  10213. * @param {number} [options.height] - Height of resource
  10214. */
  10215. var CubeResource = /*@__PURE__*/(function (ArrayResource) {
  10216. function CubeResource(source, options)
  10217. {
  10218. options = options || {};
  10219. ArrayResource.call(this, source, options);
  10220. if (this.length !== CubeResource.SIDES)
  10221. {
  10222. throw new Error(("Invalid length. Got " + (this.length) + ", expected 6"));
  10223. }
  10224. for (var i = 0; i < CubeResource.SIDES; i++)
  10225. {
  10226. this.items[i].target = TARGETS.TEXTURE_CUBE_MAP_POSITIVE_X + i;
  10227. }
  10228. if (options.autoLoad !== false)
  10229. {
  10230. this.load();
  10231. }
  10232. }
  10233. if ( ArrayResource ) { CubeResource.__proto__ = ArrayResource; }
  10234. CubeResource.prototype = Object.create( ArrayResource && ArrayResource.prototype );
  10235. CubeResource.prototype.constructor = CubeResource;
  10236. /**
  10237. * Add binding
  10238. *
  10239. * @override
  10240. * @param {PIXI.BaseTexture} baseTexture - parent base texture
  10241. */
  10242. CubeResource.prototype.bind = function bind (baseTexture)
  10243. {
  10244. ArrayResource.prototype.bind.call(this, baseTexture);
  10245. baseTexture.target = TARGETS.TEXTURE_CUBE_MAP;
  10246. };
  10247. /**
  10248. * Upload the resource
  10249. *
  10250. * @returns {boolean} true is success
  10251. */
  10252. CubeResource.prototype.upload = function upload (renderer, baseTexture, glTexture)
  10253. {
  10254. var dirty = this.itemDirtyIds;
  10255. for (var i = 0; i < CubeResource.SIDES; i++)
  10256. {
  10257. var side = this.items[i];
  10258. if (dirty[i] < side.dirtyId)
  10259. {
  10260. dirty[i] = side.dirtyId;
  10261. if (side.valid)
  10262. {
  10263. side.resource.upload(renderer, side, glTexture);
  10264. }
  10265. }
  10266. }
  10267. return true;
  10268. };
  10269. return CubeResource;
  10270. }(ArrayResource));
  10271. /**
  10272. * Number of texture sides to store for CubeResources
  10273. *
  10274. * @name PIXI.resources.CubeResource.SIDES
  10275. * @static
  10276. * @member {number}
  10277. * @default 6
  10278. */
  10279. CubeResource.SIDES = 6;
  10280. /**
  10281. * Resource type for SVG elements and graphics.
  10282. * @class
  10283. * @extends PIXI.resources.BaseImageResource
  10284. * @memberof PIXI.resources
  10285. * @param {string} source - Base64 encoded SVG element or URL for SVG file.
  10286. * @param {object} [options] - Options to use
  10287. * @param {number} [options.scale=1] Scale to apply to SVG.
  10288. * @param {boolean} [options.autoLoad=true] Start loading right away.
  10289. */
  10290. var SVGResource = /*@__PURE__*/(function (BaseImageResource) {
  10291. function SVGResource(source, options)
  10292. {
  10293. options = options || {};
  10294. BaseImageResource.call(this, document.createElement('canvas'));
  10295. /**
  10296. * Base64 encoded SVG element or URL for SVG file
  10297. * @readonly
  10298. * @member {string}
  10299. */
  10300. this.svg = source;
  10301. /**
  10302. * The source scale to apply to render
  10303. * @readonly
  10304. * @member {number}
  10305. */
  10306. this.scale = options.scale || 1;
  10307. /**
  10308. * Call when completely loaded
  10309. * @private
  10310. * @member {function}
  10311. */
  10312. this._resolve = null;
  10313. /**
  10314. * Cross origin value to use
  10315. * @private
  10316. * @member {boolean|string}
  10317. */
  10318. this._crossorigin = options.crossorigin;
  10319. /**
  10320. * Promise when loading
  10321. * @member {Promise<void>}
  10322. * @private
  10323. * @default null
  10324. */
  10325. this._load = null;
  10326. if (options.autoLoad !== false)
  10327. {
  10328. this.load();
  10329. }
  10330. }
  10331. if ( BaseImageResource ) { SVGResource.__proto__ = BaseImageResource; }
  10332. SVGResource.prototype = Object.create( BaseImageResource && BaseImageResource.prototype );
  10333. SVGResource.prototype.constructor = SVGResource;
  10334. SVGResource.prototype.load = function load ()
  10335. {
  10336. var this$1 = this;
  10337. if (this._load)
  10338. {
  10339. return this._load;
  10340. }
  10341. this._load = new Promise(function (resolve) {
  10342. // Save this until after load is finished
  10343. this$1._resolve = function () {
  10344. this$1.resize(this$1.source.width, this$1.source.height);
  10345. resolve(this$1);
  10346. };
  10347. // Convert SVG inline string to data-uri
  10348. if ((/^\<svg/).test(this$1.svg.trim()))
  10349. {
  10350. if (!btoa)
  10351. {
  10352. throw new Error('Your browser doesn\'t support base64 conversions.');
  10353. }
  10354. this$1.svg = "data:image/svg+xml;base64," + (btoa(unescape(encodeURIComponent(this$1.svg))));
  10355. }
  10356. this$1._loadSvg();
  10357. });
  10358. return this._load;
  10359. };
  10360. /**
  10361. * Loads an SVG image from `imageUrl` or `data URL`.
  10362. *
  10363. * @private
  10364. */
  10365. SVGResource.prototype._loadSvg = function _loadSvg ()
  10366. {
  10367. var this$1 = this;
  10368. var tempImage = new Image();
  10369. BaseImageResource.crossOrigin(tempImage, this.svg, this._crossorigin);
  10370. tempImage.src = this.svg;
  10371. tempImage.onload = function () {
  10372. var svgWidth = tempImage.width;
  10373. var svgHeight = tempImage.height;
  10374. if (!svgWidth || !svgHeight)
  10375. {
  10376. throw new Error('The SVG image must have width and height defined (in pixels), canvas API needs them.');
  10377. }
  10378. // Scale realWidth and realHeight
  10379. var width = Math.round(svgWidth * this$1.scale);
  10380. var height = Math.round(svgHeight * this$1.scale);
  10381. // Create a canvas element
  10382. var canvas = this$1.source;
  10383. canvas.width = width;
  10384. canvas.height = height;
  10385. canvas._pixiId = "canvas_" + (uid());
  10386. // Draw the Svg to the canvas
  10387. canvas
  10388. .getContext('2d')
  10389. .drawImage(tempImage, 0, 0, svgWidth, svgHeight, 0, 0, width, height);
  10390. this$1._resolve();
  10391. this$1._resolve = null;
  10392. };
  10393. };
  10394. /**
  10395. * Typedef for Size object.
  10396. *
  10397. * @memberof PIXI.resources.SVGResource
  10398. * @typedef {object} Size
  10399. * @property {number} width - Width component
  10400. * @property {number} height - Height component
  10401. */
  10402. /**
  10403. * Get size from an svg string using regexp.
  10404. *
  10405. * @method
  10406. * @param {string} svgString - a serialized svg element
  10407. * @return {PIXI.resources.SVGResource.Size} image extension
  10408. */
  10409. SVGResource.getSize = function getSize (svgString)
  10410. {
  10411. var sizeMatch = SVGResource.SVG_SIZE.exec(svgString);
  10412. var size = {};
  10413. if (sizeMatch)
  10414. {
  10415. size[sizeMatch[1]] = Math.round(parseFloat(sizeMatch[3]));
  10416. size[sizeMatch[5]] = Math.round(parseFloat(sizeMatch[7]));
  10417. }
  10418. return size;
  10419. };
  10420. /**
  10421. * Destroys this texture
  10422. * @override
  10423. */
  10424. SVGResource.prototype.dispose = function dispose ()
  10425. {
  10426. BaseImageResource.prototype.dispose.call(this);
  10427. this._resolve = null;
  10428. this._crossorigin = null;
  10429. };
  10430. /**
  10431. * Used to auto-detect the type of resource.
  10432. *
  10433. * @static
  10434. * @param {*} source - The source object
  10435. * @param {string} extension - The extension of source, if set
  10436. */
  10437. SVGResource.test = function test (source, extension)
  10438. {
  10439. // url file extension is SVG
  10440. return extension === 'svg'
  10441. // source is SVG data-uri
  10442. || (typeof source === 'string' && source.indexOf('data:image/svg+xml;base64') === 0)
  10443. // source is SVG inline
  10444. || (typeof source === 'string' && source.indexOf('<svg') === 0);
  10445. };
  10446. return SVGResource;
  10447. }(BaseImageResource));
  10448. /**
  10449. * RegExp for SVG size.
  10450. *
  10451. * @static
  10452. * @constant {RegExp|string} SVG_SIZE
  10453. * @memberof PIXI.resources.SVGResource
  10454. * @example &lt;svg width="100" height="100"&gt;&lt;/svg&gt;
  10455. */
  10456. SVGResource.SVG_SIZE = /<svg[^>]*(?:\s(width|height)=('|")(\d*(?:\.\d+)?)(?:px)?('|"))[^>]*(?:\s(width|height)=('|")(\d*(?:\.\d+)?)(?:px)?('|"))[^>]*>/i; // eslint-disable-line max-len
  10457. /**
  10458. * Resource type for HTMLVideoElement.
  10459. * @class
  10460. * @extends PIXI.resources.BaseImageResource
  10461. * @memberof PIXI.resources
  10462. * @param {HTMLVideoElement|object|string|Array<string|object>} source - Video element to use.
  10463. * @param {object} [options] - Options to use
  10464. * @param {boolean} [options.autoLoad=true] - Start loading the video immediately
  10465. * @param {boolean} [options.autoPlay=true] - Start playing video immediately
  10466. * @param {number} [options.updateFPS=0] - How many times a second to update the texture from the video.
  10467. * Leave at 0 to update at every render.
  10468. * @param {boolean} [options.crossorigin=true] - Load image using cross origin
  10469. */
  10470. var VideoResource = /*@__PURE__*/(function (BaseImageResource) {
  10471. function VideoResource(source, options)
  10472. {
  10473. options = options || {};
  10474. if (!(source instanceof HTMLVideoElement))
  10475. {
  10476. var videoElement = document.createElement('video');
  10477. videoElement.setAttribute('webkit-playsinline', '');
  10478. videoElement.setAttribute('playsinline', '');
  10479. if (typeof source === 'string')
  10480. {
  10481. source = [source];
  10482. }
  10483. BaseImageResource.crossOrigin(videoElement, (source[0].src || source[0]), options.crossorigin);
  10484. // array of objects or strings
  10485. for (var i = 0; i < source.length; ++i)
  10486. {
  10487. var sourceElement = document.createElement('source');
  10488. var ref = source[i];
  10489. var src = ref.src;
  10490. var mime = ref.mime;
  10491. src = src || source[i];
  10492. var baseSrc = src.split('?').shift().toLowerCase();
  10493. var ext = baseSrc.substr(baseSrc.lastIndexOf('.') + 1);
  10494. mime = mime || ("video/" + ext);
  10495. sourceElement.src = src;
  10496. sourceElement.type = mime;
  10497. videoElement.appendChild(sourceElement);
  10498. }
  10499. // Override the source
  10500. source = videoElement;
  10501. }
  10502. BaseImageResource.call(this, source);
  10503. this._autoUpdate = true;
  10504. this._isAutoUpdating = false;
  10505. this._updateFPS = options.updateFPS || 0;
  10506. this._msToNextUpdate = 0;
  10507. /**
  10508. * When set to true will automatically play videos used by this texture once
  10509. * they are loaded. If false, it will not modify the playing state.
  10510. *
  10511. * @member {boolean}
  10512. * @default true
  10513. */
  10514. this.autoPlay = options.autoPlay !== false;
  10515. /**
  10516. * Promise when loading
  10517. * @member {Promise<void>}
  10518. * @private
  10519. * @default null
  10520. */
  10521. this._load = null;
  10522. /**
  10523. * Callback when completed with load.
  10524. * @member {function}
  10525. * @private
  10526. */
  10527. this._resolve = null;
  10528. // Bind for listeners
  10529. this._onCanPlay = this._onCanPlay.bind(this);
  10530. if (options.autoLoad !== false)
  10531. {
  10532. this.load();
  10533. }
  10534. }
  10535. if ( BaseImageResource ) { VideoResource.__proto__ = BaseImageResource; }
  10536. VideoResource.prototype = Object.create( BaseImageResource && BaseImageResource.prototype );
  10537. VideoResource.prototype.constructor = VideoResource;
  10538. var prototypeAccessors = { autoUpdate: { configurable: true },updateFPS: { configurable: true } };
  10539. /**
  10540. * Trigger updating of the texture
  10541. *
  10542. * @param {number} [deltaTime=0] - time delta since last tick
  10543. */
  10544. VideoResource.prototype.update = function update (deltaTime)
  10545. {
  10546. if ( deltaTime === void 0 ) { deltaTime = 0; }
  10547. if (!this.destroyed)
  10548. {
  10549. // account for if video has had its playbackRate changed
  10550. var elapsedMS = Ticker.shared.elapsedMS * this.source.playbackRate;
  10551. this._msToNextUpdate = Math.floor(this._msToNextUpdate - elapsedMS);
  10552. if (!this._updateFPS || this._msToNextUpdate <= 0)
  10553. {
  10554. BaseImageResource.prototype.update.call(this, deltaTime);
  10555. this._msToNextUpdate = this._updateFPS ? Math.floor(1000 / this._updateFPS) : 0;
  10556. }
  10557. }
  10558. };
  10559. /**
  10560. * Start preloading the video resource.
  10561. *
  10562. * @protected
  10563. * @return {Promise<void>} Handle the validate event
  10564. */
  10565. VideoResource.prototype.load = function load ()
  10566. {
  10567. var this$1 = this;
  10568. if (this._load)
  10569. {
  10570. return this._load;
  10571. }
  10572. var source = this.source;
  10573. if ((source.readyState === source.HAVE_ENOUGH_DATA || source.readyState === source.HAVE_FUTURE_DATA)
  10574. && source.width && source.height)
  10575. {
  10576. source.complete = true;
  10577. }
  10578. source.addEventListener('play', this._onPlayStart.bind(this));
  10579. source.addEventListener('pause', this._onPlayStop.bind(this));
  10580. if (!this._isSourceReady())
  10581. {
  10582. source.addEventListener('canplay', this._onCanPlay);
  10583. source.addEventListener('canplaythrough', this._onCanPlay);
  10584. }
  10585. else
  10586. {
  10587. this._onCanPlay();
  10588. }
  10589. this._load = new Promise(function (resolve) {
  10590. if (this$1.valid)
  10591. {
  10592. resolve(this$1);
  10593. }
  10594. else
  10595. {
  10596. this$1._resolve = resolve;
  10597. source.load();
  10598. }
  10599. });
  10600. return this._load;
  10601. };
  10602. /**
  10603. * Returns true if the underlying source is playing.
  10604. *
  10605. * @private
  10606. * @return {boolean} True if playing.
  10607. */
  10608. VideoResource.prototype._isSourcePlaying = function _isSourcePlaying ()
  10609. {
  10610. var source = this.source;
  10611. return (source.currentTime > 0 && source.paused === false && source.ended === false && source.readyState > 2);
  10612. };
  10613. /**
  10614. * Returns true if the underlying source is ready for playing.
  10615. *
  10616. * @private
  10617. * @return {boolean} True if ready.
  10618. */
  10619. VideoResource.prototype._isSourceReady = function _isSourceReady ()
  10620. {
  10621. return this.source.readyState === 3 || this.source.readyState === 4;
  10622. };
  10623. /**
  10624. * Runs the update loop when the video is ready to play
  10625. *
  10626. * @private
  10627. */
  10628. VideoResource.prototype._onPlayStart = function _onPlayStart ()
  10629. {
  10630. // Just in case the video has not received its can play even yet..
  10631. if (!this.valid)
  10632. {
  10633. this._onCanPlay();
  10634. }
  10635. if (!this._isAutoUpdating && this.autoUpdate)
  10636. {
  10637. Ticker.shared.add(this.update, this);
  10638. this._isAutoUpdating = true;
  10639. }
  10640. };
  10641. /**
  10642. * Fired when a pause event is triggered, stops the update loop
  10643. *
  10644. * @private
  10645. */
  10646. VideoResource.prototype._onPlayStop = function _onPlayStop ()
  10647. {
  10648. if (this._isAutoUpdating)
  10649. {
  10650. Ticker.shared.remove(this.update, this);
  10651. this._isAutoUpdating = false;
  10652. }
  10653. };
  10654. /**
  10655. * Fired when the video is loaded and ready to play
  10656. *
  10657. * @private
  10658. */
  10659. VideoResource.prototype._onCanPlay = function _onCanPlay ()
  10660. {
  10661. var ref = this;
  10662. var source = ref.source;
  10663. source.removeEventListener('canplay', this._onCanPlay);
  10664. source.removeEventListener('canplaythrough', this._onCanPlay);
  10665. var valid = this.valid;
  10666. this.resize(source.videoWidth, source.videoHeight);
  10667. // prevent multiple loaded dispatches..
  10668. if (!valid && this._resolve)
  10669. {
  10670. this._resolve(this);
  10671. this._resolve = null;
  10672. }
  10673. if (this._isSourcePlaying())
  10674. {
  10675. this._onPlayStart();
  10676. }
  10677. else if (this.autoPlay)
  10678. {
  10679. source.play();
  10680. }
  10681. };
  10682. /**
  10683. * Destroys this texture
  10684. * @override
  10685. */
  10686. VideoResource.prototype.dispose = function dispose ()
  10687. {
  10688. if (this._isAutoUpdating)
  10689. {
  10690. Ticker.shared.remove(this.update, this);
  10691. }
  10692. if (this.source)
  10693. {
  10694. this.source.pause();
  10695. this.source.src = '';
  10696. this.source.load();
  10697. }
  10698. BaseImageResource.prototype.dispose.call(this);
  10699. };
  10700. /**
  10701. * Should the base texture automatically update itself, set to true by default
  10702. *
  10703. * @member {boolean}
  10704. */
  10705. prototypeAccessors.autoUpdate.get = function ()
  10706. {
  10707. return this._autoUpdate;
  10708. };
  10709. prototypeAccessors.autoUpdate.set = function (value) // eslint-disable-line require-jsdoc
  10710. {
  10711. if (value !== this._autoUpdate)
  10712. {
  10713. this._autoUpdate = value;
  10714. if (!this._autoUpdate && this._isAutoUpdating)
  10715. {
  10716. Ticker.shared.remove(this.update, this);
  10717. this._isAutoUpdating = false;
  10718. }
  10719. else if (this._autoUpdate && !this._isAutoUpdating)
  10720. {
  10721. Ticker.shared.add(this.update, this);
  10722. this._isAutoUpdating = true;
  10723. }
  10724. }
  10725. };
  10726. /**
  10727. * How many times a second to update the texture from the video. Leave at 0 to update at every render.
  10728. * A lower fps can help performance, as updating the texture at 60fps on a 30ps video may not be efficient.
  10729. *
  10730. * @member {number}
  10731. */
  10732. prototypeAccessors.updateFPS.get = function ()
  10733. {
  10734. return this._updateFPS;
  10735. };
  10736. prototypeAccessors.updateFPS.set = function (value) // eslint-disable-line require-jsdoc
  10737. {
  10738. if (value !== this._updateFPS)
  10739. {
  10740. this._updateFPS = value;
  10741. }
  10742. };
  10743. /**
  10744. * Used to auto-detect the type of resource.
  10745. *
  10746. * @static
  10747. * @param {*} source - The source object
  10748. * @param {string} extension - The extension of source, if set
  10749. * @return {boolean} `true` if video source
  10750. */
  10751. VideoResource.test = function test (source, extension)
  10752. {
  10753. return (source instanceof HTMLVideoElement)
  10754. || VideoResource.TYPES.indexOf(extension) > -1;
  10755. };
  10756. Object.defineProperties( VideoResource.prototype, prototypeAccessors );
  10757. return VideoResource;
  10758. }(BaseImageResource));
  10759. /**
  10760. * List of common video file extensions supported by VideoResource.
  10761. * @constant
  10762. * @member {Array<string>}
  10763. * @static
  10764. * @readonly
  10765. */
  10766. VideoResource.TYPES = ['mp4', 'm4v', 'webm', 'ogg', 'ogv', 'h264', 'avi', 'mov'];
  10767. INSTALLED.push(
  10768. ImageResource,
  10769. CanvasResource,
  10770. VideoResource,
  10771. SVGResource,
  10772. BufferResource,
  10773. CubeResource,
  10774. ArrayResource
  10775. );
  10776. var index = ({
  10777. INSTALLED: INSTALLED,
  10778. autoDetectResource: autoDetectResource,
  10779. ArrayResource: ArrayResource,
  10780. BufferResource: BufferResource,
  10781. CanvasResource: CanvasResource,
  10782. CubeResource: CubeResource,
  10783. ImageResource: ImageResource,
  10784. SVGResource: SVGResource,
  10785. VideoResource: VideoResource,
  10786. Resource: Resource,
  10787. BaseImageResource: BaseImageResource
  10788. });
  10789. /**
  10790. * System is a base class used for extending systems used by the {@link PIXI.Renderer}
  10791. *
  10792. * @see PIXI.Renderer#addSystem
  10793. * @class
  10794. * @memberof PIXI
  10795. */
  10796. var System = function System(renderer)
  10797. {
  10798. /**
  10799. * The renderer this manager works for.
  10800. *
  10801. * @member {PIXI.Renderer}
  10802. */
  10803. this.renderer = renderer;
  10804. this.renderer.runners.contextChange.add(this);
  10805. };
  10806. /**
  10807. * Generic method called when there is a WebGL context change.
  10808. *
  10809. * @param {WebGLRenderingContext} gl new webgl context
  10810. */
  10811. System.prototype.contextChange = function contextChange (gl) // eslint-disable-line no-unused-vars
  10812. {
  10813. // do some codes init!
  10814. };
  10815. /**
  10816. * Generic destroy methods to be overridden by the subclass
  10817. */
  10818. System.prototype.destroy = function destroy ()
  10819. {
  10820. this.renderer.runners.contextChange.remove(this);
  10821. this.renderer = null;
  10822. };
  10823. /**
  10824. * Resource type for DepthTexture.
  10825. * @class
  10826. * @extends PIXI.resources.BufferResource
  10827. * @memberof PIXI.resources
  10828. */
  10829. var DepthResource = /*@__PURE__*/(function (BufferResource) {
  10830. function DepthResource () {
  10831. BufferResource.apply(this, arguments);
  10832. }
  10833. if ( BufferResource ) { DepthResource.__proto__ = BufferResource; }
  10834. DepthResource.prototype = Object.create( BufferResource && BufferResource.prototype );
  10835. DepthResource.prototype.constructor = DepthResource;
  10836. DepthResource.prototype.upload = function upload (renderer, baseTexture, glTexture)
  10837. {
  10838. var gl = renderer.gl;
  10839. gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, baseTexture.premultiplyAlpha);
  10840. if (glTexture.width === baseTexture.width && glTexture.height === baseTexture.height)
  10841. {
  10842. gl.texSubImage2D(
  10843. baseTexture.target,
  10844. 0,
  10845. 0,
  10846. 0,
  10847. baseTexture.width,
  10848. baseTexture.height,
  10849. baseTexture.format,
  10850. baseTexture.type,
  10851. this.data
  10852. );
  10853. }
  10854. else
  10855. {
  10856. glTexture.width = baseTexture.width;
  10857. glTexture.height = baseTexture.height;
  10858. gl.texImage2D(
  10859. baseTexture.target,
  10860. 0,
  10861. gl.DEPTH_COMPONENT16, // Needed for depth to render properly in webgl2.0
  10862. baseTexture.width,
  10863. baseTexture.height,
  10864. 0,
  10865. baseTexture.format,
  10866. baseTexture.type,
  10867. this.data
  10868. );
  10869. }
  10870. return true;
  10871. };
  10872. return DepthResource;
  10873. }(BufferResource));
  10874. /**
  10875. * Frame buffer used by the BaseRenderTexture
  10876. *
  10877. * @class
  10878. * @memberof PIXI
  10879. */
  10880. var Framebuffer = function Framebuffer(width, height)
  10881. {
  10882. this.width = Math.ceil(width || 100);
  10883. this.height = Math.ceil(height || 100);
  10884. this.stencil = false;
  10885. this.depth = false;
  10886. this.dirtyId = 0;
  10887. this.dirtyFormat = 0;
  10888. this.dirtySize = 0;
  10889. this.depthTexture = null;
  10890. this.colorTextures = [];
  10891. this.glFramebuffers = {};
  10892. this.disposeRunner = new Runner('disposeFramebuffer', 2);
  10893. };
  10894. var prototypeAccessors$1$2 = { colorTexture: { configurable: true } };
  10895. /**
  10896. * Reference to the colorTexture.
  10897. *
  10898. * @member {PIXI.Texture[]}
  10899. * @readonly
  10900. */
  10901. prototypeAccessors$1$2.colorTexture.get = function ()
  10902. {
  10903. return this.colorTextures[0];
  10904. };
  10905. /**
  10906. * Add texture to the colorTexture array
  10907. *
  10908. * @param {number} [index=0] - Index of the array to add the texture to
  10909. * @param {PIXI.Texture} [texture] - Texture to add to the array
  10910. */
  10911. Framebuffer.prototype.addColorTexture = function addColorTexture (index, texture)
  10912. {
  10913. if ( index === void 0 ) { index = 0; }
  10914. // TODO add some validation to the texture - same width / height etc?
  10915. this.colorTextures[index] = texture || new BaseTexture(null, { scaleMode: 0,
  10916. resolution: 1,
  10917. mipmap: false,
  10918. width: this.width,
  10919. height: this.height });// || new Texture();
  10920. this.dirtyId++;
  10921. this.dirtyFormat++;
  10922. return this;
  10923. };
  10924. /**
  10925. * Add a depth texture to the frame buffer
  10926. *
  10927. * @param {PIXI.Texture} [texture] - Texture to add
  10928. */
  10929. Framebuffer.prototype.addDepthTexture = function addDepthTexture (texture)
  10930. {
  10931. /* eslint-disable max-len */
  10932. this.depthTexture = texture || new BaseTexture(new DepthResource(null, { width: this.width, height: this.height }), { scaleMode: 0,
  10933. resolution: 1,
  10934. width: this.width,
  10935. height: this.height,
  10936. mipmap: false,
  10937. format: FORMATS.DEPTH_COMPONENT,
  10938. type: TYPES.UNSIGNED_SHORT });// UNSIGNED_SHORT;
  10939. /* eslint-disable max-len */
  10940. this.dirtyId++;
  10941. this.dirtyFormat++;
  10942. return this;
  10943. };
  10944. /**
  10945. * Enable depth on the frame buffer
  10946. */
  10947. Framebuffer.prototype.enableDepth = function enableDepth ()
  10948. {
  10949. this.depth = true;
  10950. this.dirtyId++;
  10951. this.dirtyFormat++;
  10952. return this;
  10953. };
  10954. /**
  10955. * Enable stencil on the frame buffer
  10956. */
  10957. Framebuffer.prototype.enableStencil = function enableStencil ()
  10958. {
  10959. this.stencil = true;
  10960. this.dirtyId++;
  10961. this.dirtyFormat++;
  10962. return this;
  10963. };
  10964. /**
  10965. * Resize the frame buffer
  10966. *
  10967. * @param {number} width - Width of the frame buffer to resize to
  10968. * @param {number} height - Height of the frame buffer to resize to
  10969. */
  10970. Framebuffer.prototype.resize = function resize (width, height)
  10971. {
  10972. width = Math.ceil(width);
  10973. height = Math.ceil(height);
  10974. if (width === this.width && height === this.height) { return; }
  10975. this.width = width;
  10976. this.height = height;
  10977. this.dirtyId++;
  10978. this.dirtySize++;
  10979. for (var i = 0; i < this.colorTextures.length; i++)
  10980. {
  10981. var texture = this.colorTextures[i];
  10982. var resolution = texture.resolution;
  10983. // take into acount the fact the texture may have a different resolution..
  10984. texture.setSize(width / resolution, height / resolution);
  10985. }
  10986. if (this.depthTexture)
  10987. {
  10988. var resolution$1 = this.depthTexture.resolution;
  10989. this.depthTexture.setSize(width / resolution$1, height / resolution$1);
  10990. }
  10991. };
  10992. /**
  10993. * disposes WebGL resources that are connected to this geometry
  10994. */
  10995. Framebuffer.prototype.dispose = function dispose ()
  10996. {
  10997. this.disposeRunner.run(this, false);
  10998. };
  10999. Object.defineProperties( Framebuffer.prototype, prototypeAccessors$1$2 );
  11000. /**
  11001. * A BaseRenderTexture is a special texture that allows any PixiJS display object to be rendered to it.
  11002. *
  11003. * __Hint__: All DisplayObjects (i.e. Sprites) that render to a BaseRenderTexture should be preloaded
  11004. * otherwise black rectangles will be drawn instead.
  11005. *
  11006. * A BaseRenderTexture takes a snapshot of any Display Object given to its render method. The position
  11007. * and rotation of the given Display Objects is ignored. For example:
  11008. *
  11009. * ```js
  11010. * let renderer = PIXI.autoDetectRenderer();
  11011. * let baseRenderTexture = new PIXI.BaseRenderTexture({ width: 800, height: 600 });
  11012. * let renderTexture = new PIXI.RenderTexture(baseRenderTexture);
  11013. * let sprite = PIXI.Sprite.from("spinObj_01.png");
  11014. *
  11015. * sprite.position.x = 800/2;
  11016. * sprite.position.y = 600/2;
  11017. * sprite.anchor.x = 0.5;
  11018. * sprite.anchor.y = 0.5;
  11019. *
  11020. * renderer.render(sprite, renderTexture);
  11021. * ```
  11022. *
  11023. * The Sprite in this case will be rendered using its local transform. To render this sprite at 0,0
  11024. * you can clear the transform
  11025. *
  11026. * ```js
  11027. *
  11028. * sprite.setTransform()
  11029. *
  11030. * let baseRenderTexture = new PIXI.BaseRenderTexture({ width: 100, height: 100 });
  11031. * let renderTexture = new PIXI.RenderTexture(baseRenderTexture);
  11032. *
  11033. * renderer.render(sprite, renderTexture); // Renders to center of RenderTexture
  11034. * ```
  11035. *
  11036. * @class
  11037. * @extends PIXI.BaseTexture
  11038. * @memberof PIXI
  11039. */
  11040. var BaseRenderTexture = /*@__PURE__*/(function (BaseTexture) {
  11041. function BaseRenderTexture(options)
  11042. {
  11043. if (typeof options === 'number')
  11044. {
  11045. /* eslint-disable prefer-rest-params */
  11046. // Backward compatibility of signature
  11047. var width$1 = arguments[0];
  11048. var height$1 = arguments[1];
  11049. var scaleMode = arguments[2];
  11050. var resolution = arguments[3];
  11051. options = { width: width$1, height: height$1, scaleMode: scaleMode, resolution: resolution };
  11052. /* eslint-enable prefer-rest-params */
  11053. }
  11054. BaseTexture.call(this, null, options);
  11055. var ref = options || {};
  11056. var width = ref.width;
  11057. var height = ref.height;
  11058. // Set defaults
  11059. this.mipmap = false;
  11060. this.width = Math.ceil(width) || 100;
  11061. this.height = Math.ceil(height) || 100;
  11062. this.valid = true;
  11063. /**
  11064. * A reference to the canvas render target (we only need one as this can be shared across renderers)
  11065. *
  11066. * @protected
  11067. * @member {object}
  11068. */
  11069. this._canvasRenderTarget = null;
  11070. this.clearColor = [0, 0, 0, 0];
  11071. this.framebuffer = new Framebuffer(this.width * this.resolution, this.height * this.resolution)
  11072. .addColorTexture(0, this)
  11073. .enableStencil();
  11074. // TODO - could this be added the systems?
  11075. /**
  11076. * The data structure for the stencil masks.
  11077. *
  11078. * @member {PIXI.Graphics[]}
  11079. */
  11080. this.stencilMaskStack = [];
  11081. /**
  11082. * The data structure for the filters.
  11083. *
  11084. * @member {PIXI.Graphics[]}
  11085. */
  11086. this.filterStack = [{}];
  11087. }
  11088. if ( BaseTexture ) { BaseRenderTexture.__proto__ = BaseTexture; }
  11089. BaseRenderTexture.prototype = Object.create( BaseTexture && BaseTexture.prototype );
  11090. BaseRenderTexture.prototype.constructor = BaseRenderTexture;
  11091. /**
  11092. * Resizes the BaseRenderTexture.
  11093. *
  11094. * @param {number} width - The width to resize to.
  11095. * @param {number} height - The height to resize to.
  11096. */
  11097. BaseRenderTexture.prototype.resize = function resize (width, height)
  11098. {
  11099. width = Math.ceil(width);
  11100. height = Math.ceil(height);
  11101. this.framebuffer.resize(width * this.resolution, height * this.resolution);
  11102. };
  11103. /**
  11104. * Frees the texture and framebuffer from WebGL memory without destroying this texture object.
  11105. * This means you can still use the texture later which will upload it to GPU
  11106. * memory again.
  11107. *
  11108. * @fires PIXI.BaseTexture#dispose
  11109. */
  11110. BaseRenderTexture.prototype.dispose = function dispose ()
  11111. {
  11112. this.framebuffer.dispose();
  11113. BaseTexture.prototype.dispose.call(this);
  11114. };
  11115. /**
  11116. * Destroys this texture.
  11117. *
  11118. */
  11119. BaseRenderTexture.prototype.destroy = function destroy ()
  11120. {
  11121. BaseTexture.prototype.destroy.call(this, true);
  11122. this.framebuffer = null;
  11123. this.renderer = null;
  11124. };
  11125. return BaseRenderTexture;
  11126. }(BaseTexture));
  11127. /**
  11128. * A standard object to store the Uvs of a texture
  11129. *
  11130. * @class
  11131. * @protected
  11132. * @memberof PIXI
  11133. */
  11134. var TextureUvs = function TextureUvs()
  11135. {
  11136. this.x0 = 0;
  11137. this.y0 = 0;
  11138. this.x1 = 1;
  11139. this.y1 = 0;
  11140. this.x2 = 1;
  11141. this.y2 = 1;
  11142. this.x3 = 0;
  11143. this.y3 = 1;
  11144. this.uvsFloat32 = new Float32Array(8);
  11145. };
  11146. /**
  11147. * Sets the texture Uvs based on the given frame information.
  11148. *
  11149. * @protected
  11150. * @param {PIXI.Rectangle} frame - The frame of the texture
  11151. * @param {PIXI.Rectangle} baseFrame - The base frame of the texture
  11152. * @param {number} rotate - Rotation of frame, see {@link PIXI.GroupD8}
  11153. */
  11154. TextureUvs.prototype.set = function set (frame, baseFrame, rotate)
  11155. {
  11156. var tw = baseFrame.width;
  11157. var th = baseFrame.height;
  11158. if (rotate)
  11159. {
  11160. // width and height div 2 div baseFrame size
  11161. var w2 = frame.width / 2 / tw;
  11162. var h2 = frame.height / 2 / th;
  11163. // coordinates of center
  11164. var cX = (frame.x / tw) + w2;
  11165. var cY = (frame.y / th) + h2;
  11166. rotate = GroupD8.add(rotate, GroupD8.NW); // NW is top-left corner
  11167. this.x0 = cX + (w2 * GroupD8.uX(rotate));
  11168. this.y0 = cY + (h2 * GroupD8.uY(rotate));
  11169. rotate = GroupD8.add(rotate, 2); // rotate 90 degrees clockwise
  11170. this.x1 = cX + (w2 * GroupD8.uX(rotate));
  11171. this.y1 = cY + (h2 * GroupD8.uY(rotate));
  11172. rotate = GroupD8.add(rotate, 2);
  11173. this.x2 = cX + (w2 * GroupD8.uX(rotate));
  11174. this.y2 = cY + (h2 * GroupD8.uY(rotate));
  11175. rotate = GroupD8.add(rotate, 2);
  11176. this.x3 = cX + (w2 * GroupD8.uX(rotate));
  11177. this.y3 = cY + (h2 * GroupD8.uY(rotate));
  11178. }
  11179. else
  11180. {
  11181. this.x0 = frame.x / tw;
  11182. this.y0 = frame.y / th;
  11183. this.x1 = (frame.x + frame.width) / tw;
  11184. this.y1 = frame.y / th;
  11185. this.x2 = (frame.x + frame.width) / tw;
  11186. this.y2 = (frame.y + frame.height) / th;
  11187. this.x3 = frame.x / tw;
  11188. this.y3 = (frame.y + frame.height) / th;
  11189. }
  11190. this.uvsFloat32[0] = this.x0;
  11191. this.uvsFloat32[1] = this.y0;
  11192. this.uvsFloat32[2] = this.x1;
  11193. this.uvsFloat32[3] = this.y1;
  11194. this.uvsFloat32[4] = this.x2;
  11195. this.uvsFloat32[5] = this.y2;
  11196. this.uvsFloat32[6] = this.x3;
  11197. this.uvsFloat32[7] = this.y3;
  11198. };
  11199. var DEFAULT_UVS = new TextureUvs();
  11200. /**
  11201. * A texture stores the information that represents an image or part of an image.
  11202. *
  11203. * It cannot be added to the display list directly; instead use it as the texture for a Sprite.
  11204. * If no frame is provided for a texture, then the whole image is used.
  11205. *
  11206. * You can directly create a texture from an image and then reuse it multiple times like this :
  11207. *
  11208. * ```js
  11209. * let texture = PIXI.Texture.from('assets/image.png');
  11210. * let sprite1 = new PIXI.Sprite(texture);
  11211. * let sprite2 = new PIXI.Sprite(texture);
  11212. * ```
  11213. *
  11214. * If you didnt pass the texture frame to constructor, it enables `noFrame` mode:
  11215. * it subscribes on baseTexture events, it automatically resizes at the same time as baseTexture.
  11216. *
  11217. * Textures made from SVGs, loaded or not, cannot be used before the file finishes processing.
  11218. * You can check for this by checking the sprite's _textureID property.
  11219. * ```js
  11220. * var texture = PIXI.Texture.from('assets/image.svg');
  11221. * var sprite1 = new PIXI.Sprite(texture);
  11222. * //sprite1._textureID should not be undefined if the texture has finished processing the SVG file
  11223. * ```
  11224. * You can use a ticker or rAF to ensure your sprites load the finished textures after processing. See issue #3068.
  11225. *
  11226. * @class
  11227. * @extends PIXI.utils.EventEmitter
  11228. * @memberof PIXI
  11229. */
  11230. var Texture = /*@__PURE__*/(function (EventEmitter) {
  11231. function Texture(baseTexture, frame, orig, trim, rotate, anchor)
  11232. {
  11233. EventEmitter.call(this);
  11234. /**
  11235. * Does this Texture have any frame data assigned to it?
  11236. *
  11237. * This mode is enabled automatically if no frame was passed inside constructor.
  11238. *
  11239. * In this mode texture is subscribed to baseTexture events, and fires `update` on any change.
  11240. *
  11241. * Beware, after loading or resize of baseTexture event can fired two times!
  11242. * If you want more control, subscribe on baseTexture itself.
  11243. *
  11244. * ```js
  11245. * texture.on('update', () => {});
  11246. * ```
  11247. *
  11248. * Any assignment of `frame` switches off `noFrame` mode.
  11249. *
  11250. * @member {boolean}
  11251. */
  11252. this.noFrame = false;
  11253. if (!frame)
  11254. {
  11255. this.noFrame = true;
  11256. frame = new Rectangle(0, 0, 1, 1);
  11257. }
  11258. if (baseTexture instanceof Texture)
  11259. {
  11260. baseTexture = baseTexture.baseTexture;
  11261. }
  11262. /**
  11263. * The base texture that this texture uses.
  11264. *
  11265. * @member {PIXI.BaseTexture}
  11266. */
  11267. this.baseTexture = baseTexture;
  11268. /**
  11269. * This is the area of the BaseTexture image to actually copy to the Canvas / WebGL when rendering,
  11270. * irrespective of the actual frame size or placement (which can be influenced by trimmed texture atlases)
  11271. *
  11272. * @member {PIXI.Rectangle}
  11273. */
  11274. this._frame = frame;
  11275. /**
  11276. * This is the trimmed area of original texture, before it was put in atlas
  11277. * Please call `updateUvs()` after you change coordinates of `trim` manually.
  11278. *
  11279. * @member {PIXI.Rectangle}
  11280. */
  11281. this.trim = trim;
  11282. /**
  11283. * This will let the renderer know if the texture is valid. If it's not then it cannot be rendered.
  11284. *
  11285. * @member {boolean}
  11286. */
  11287. this.valid = false;
  11288. /**
  11289. * This will let a renderer know that a texture has been updated (used mainly for WebGL uv updates)
  11290. *
  11291. * @member {boolean}
  11292. */
  11293. this.requiresUpdate = false;
  11294. /**
  11295. * The WebGL UV data cache. Can be used as quad UV
  11296. *
  11297. * @member {PIXI.TextureUvs}
  11298. * @protected
  11299. */
  11300. this._uvs = DEFAULT_UVS;
  11301. /**
  11302. * Default TextureMatrix instance for this texture
  11303. * By default that object is not created because its heavy
  11304. *
  11305. * @member {PIXI.TextureMatrix}
  11306. */
  11307. this.uvMatrix = null;
  11308. /**
  11309. * This is the area of original texture, before it was put in atlas
  11310. *
  11311. * @member {PIXI.Rectangle}
  11312. */
  11313. this.orig = orig || frame;// new Rectangle(0, 0, 1, 1);
  11314. this._rotate = Number(rotate || 0);
  11315. if (rotate === true)
  11316. {
  11317. // this is old texturepacker legacy, some games/libraries are passing "true" for rotated textures
  11318. this._rotate = 2;
  11319. }
  11320. else if (this._rotate % 2 !== 0)
  11321. {
  11322. throw new Error('attempt to use diamond-shaped UVs. If you are sure, set rotation manually');
  11323. }
  11324. /**
  11325. * Anchor point that is used as default if sprite is created with this texture.
  11326. * Changing the `defaultAnchor` at a later point of time will not update Sprite's anchor point.
  11327. * @member {PIXI.Point}
  11328. * @default {0,0}
  11329. */
  11330. this.defaultAnchor = anchor ? new Point(anchor.x, anchor.y) : new Point(0, 0);
  11331. /**
  11332. * Update ID is observed by sprites and TextureMatrix instances.
  11333. * Call updateUvs() to increment it.
  11334. *
  11335. * @member {number}
  11336. * @protected
  11337. */
  11338. this._updateID = 0;
  11339. /**
  11340. * The ids under which this Texture has been added to the texture cache. This is
  11341. * automatically set as long as Texture.addToCache is used, but may not be set if a
  11342. * Texture is added directly to the TextureCache array.
  11343. *
  11344. * @member {string[]}
  11345. */
  11346. this.textureCacheIds = [];
  11347. if (!baseTexture.valid)
  11348. {
  11349. baseTexture.once('loaded', this.onBaseTextureUpdated, this);
  11350. }
  11351. else if (this.noFrame)
  11352. {
  11353. // if there is no frame we should monitor for any base texture changes..
  11354. if (baseTexture.valid)
  11355. {
  11356. this.onBaseTextureUpdated(baseTexture);
  11357. }
  11358. }
  11359. else
  11360. {
  11361. this.frame = frame;
  11362. }
  11363. if (this.noFrame)
  11364. {
  11365. baseTexture.on('update', this.onBaseTextureUpdated, this);
  11366. }
  11367. }
  11368. if ( EventEmitter ) { Texture.__proto__ = EventEmitter; }
  11369. Texture.prototype = Object.create( EventEmitter && EventEmitter.prototype );
  11370. Texture.prototype.constructor = Texture;
  11371. var prototypeAccessors = { frame: { configurable: true },rotate: { configurable: true },width: { configurable: true },height: { configurable: true } };
  11372. /**
  11373. * Updates this texture on the gpu.
  11374. *
  11375. * Calls the TextureResource update.
  11376. *
  11377. * If you adjusted `frame` manually, please call `updateUvs()` instead.
  11378. *
  11379. */
  11380. Texture.prototype.update = function update ()
  11381. {
  11382. if (this.baseTexture.resource)
  11383. {
  11384. this.baseTexture.resource.update();
  11385. }
  11386. };
  11387. /**
  11388. * Called when the base texture is updated
  11389. *
  11390. * @protected
  11391. * @param {PIXI.BaseTexture} baseTexture - The base texture.
  11392. */
  11393. Texture.prototype.onBaseTextureUpdated = function onBaseTextureUpdated (baseTexture)
  11394. {
  11395. if (this.noFrame)
  11396. {
  11397. if (!this.baseTexture.valid)
  11398. {
  11399. return;
  11400. }
  11401. this._frame.width = baseTexture.width;
  11402. this._frame.height = baseTexture.height;
  11403. this.valid = true;
  11404. this.updateUvs();
  11405. }
  11406. else
  11407. {
  11408. // TODO this code looks confusing.. boo to abusing getters and setters!
  11409. // if user gave us frame that has bigger size than resized texture it can be a problem
  11410. this.frame = this._frame;
  11411. }
  11412. this.emit('update', this);
  11413. };
  11414. /**
  11415. * Destroys this texture
  11416. *
  11417. * @param {boolean} [destroyBase=false] Whether to destroy the base texture as well
  11418. */
  11419. Texture.prototype.destroy = function destroy (destroyBase)
  11420. {
  11421. if (this.baseTexture)
  11422. {
  11423. if (destroyBase)
  11424. {
  11425. var ref = this.baseTexture;
  11426. var resource = ref.resource;
  11427. // delete the texture if it exists in the texture cache..
  11428. // this only needs to be removed if the base texture is actually destroyed too..
  11429. if (resource && TextureCache[resource.url])
  11430. {
  11431. Texture.removeFromCache(resource.url);
  11432. }
  11433. this.baseTexture.destroy();
  11434. }
  11435. this.baseTexture.off('update', this.onBaseTextureUpdated, this);
  11436. this.baseTexture = null;
  11437. }
  11438. this._frame = null;
  11439. this._uvs = null;
  11440. this.trim = null;
  11441. this.orig = null;
  11442. this.valid = false;
  11443. Texture.removeFromCache(this);
  11444. this.textureCacheIds = null;
  11445. };
  11446. /**
  11447. * Creates a new texture object that acts the same as this one.
  11448. *
  11449. * @return {PIXI.Texture} The new texture
  11450. */
  11451. Texture.prototype.clone = function clone ()
  11452. {
  11453. return new Texture(this.baseTexture, this.frame, this.orig, this.trim, this.rotate, this.defaultAnchor);
  11454. };
  11455. /**
  11456. * Updates the internal WebGL UV cache. Use it after you change `frame` or `trim` of the texture.
  11457. * Call it after changing the frame
  11458. */
  11459. Texture.prototype.updateUvs = function updateUvs ()
  11460. {
  11461. if (this._uvs === DEFAULT_UVS)
  11462. {
  11463. this._uvs = new TextureUvs();
  11464. }
  11465. this._uvs.set(this._frame, this.baseTexture, this.rotate);
  11466. this._updateID++;
  11467. };
  11468. /**
  11469. * Helper function that creates a new Texture based on the source you provide.
  11470. * The source can be - frame id, image url, video url, canvas element, video element, base texture
  11471. *
  11472. * @static
  11473. * @param {number|string|HTMLImageElement|HTMLCanvasElement|HTMLVideoElement|PIXI.BaseTexture} source
  11474. * Source to create texture from
  11475. * @param {object} [options] See {@link PIXI.BaseTexture}'s constructor for options.
  11476. * @return {PIXI.Texture} The newly created texture
  11477. */
  11478. Texture.from = function from (source, options)
  11479. {
  11480. if ( options === void 0 ) { options = {}; }
  11481. var cacheId = null;
  11482. if (typeof source === 'string')
  11483. {
  11484. cacheId = source;
  11485. }
  11486. else
  11487. {
  11488. if (!source._pixiId)
  11489. {
  11490. source._pixiId = "pixiid_" + (uid());
  11491. }
  11492. cacheId = source._pixiId;
  11493. }
  11494. var texture = TextureCache[cacheId];
  11495. if (!texture)
  11496. {
  11497. if (!options.resolution)
  11498. {
  11499. options.resolution = getResolutionOfUrl(source);
  11500. }
  11501. texture = new Texture(new BaseTexture(source, options));
  11502. texture.baseTexture.cacheId = cacheId;
  11503. BaseTexture.addToCache(texture.baseTexture, cacheId);
  11504. Texture.addToCache(texture, cacheId);
  11505. }
  11506. // lets assume its a base texture!
  11507. return texture;
  11508. };
  11509. /**
  11510. * Create a new Texture with a BufferResource from a Float32Array.
  11511. * RGBA values are floats from 0 to 1.
  11512. * @static
  11513. * @param {Float32Array|Uint8Array} buffer The optional array to use, if no data
  11514. * is provided, a new Float32Array is created.
  11515. * @param {number} width - Width of the resource
  11516. * @param {number} height - Height of the resource
  11517. * @param {object} [options] See {@link PIXI.BaseTexture}'s constructor for options.
  11518. * @return {PIXI.Texture} The resulting new BaseTexture
  11519. */
  11520. Texture.fromBuffer = function fromBuffer (buffer, width, height, options)
  11521. {
  11522. return new Texture(BaseTexture.fromBuffer(buffer, width, height, options));
  11523. };
  11524. /**
  11525. * Create a texture from a source and add to the cache.
  11526. *
  11527. * @static
  11528. * @param {HTMLImageElement|HTMLCanvasElement} source - The input source.
  11529. * @param {String} imageUrl - File name of texture, for cache and resolving resolution.
  11530. * @param {String} [name] - Human readable name for the texture cache. If no name is
  11531. * specified, only `imageUrl` will be used as the cache ID.
  11532. * @return {PIXI.Texture} Output texture
  11533. */
  11534. Texture.fromLoader = function fromLoader (source, imageUrl, name)
  11535. {
  11536. var resource = new ImageResource(source);
  11537. resource.url = imageUrl;
  11538. var baseTexture = new BaseTexture(resource, {
  11539. scaleMode: settings.SCALE_MODE,
  11540. resolution: getResolutionOfUrl(imageUrl),
  11541. });
  11542. var texture = new Texture(baseTexture);
  11543. // No name, use imageUrl instead
  11544. if (!name)
  11545. {
  11546. name = imageUrl;
  11547. }
  11548. // lets also add the frame to pixi's global cache for 'fromLoader' function
  11549. BaseTexture.addToCache(texture.baseTexture, name);
  11550. Texture.addToCache(texture, name);
  11551. // also add references by url if they are different.
  11552. if (name !== imageUrl)
  11553. {
  11554. BaseTexture.addToCache(texture.baseTexture, imageUrl);
  11555. Texture.addToCache(texture, imageUrl);
  11556. }
  11557. return texture;
  11558. };
  11559. /**
  11560. * Adds a Texture to the global TextureCache. This cache is shared across the whole PIXI object.
  11561. *
  11562. * @static
  11563. * @param {PIXI.Texture} texture - The Texture to add to the cache.
  11564. * @param {string} id - The id that the Texture will be stored against.
  11565. */
  11566. Texture.addToCache = function addToCache (texture, id)
  11567. {
  11568. if (id)
  11569. {
  11570. if (texture.textureCacheIds.indexOf(id) === -1)
  11571. {
  11572. texture.textureCacheIds.push(id);
  11573. }
  11574. if (TextureCache[id])
  11575. {
  11576. // eslint-disable-next-line no-console
  11577. console.warn(("Texture added to the cache with an id [" + id + "] that already had an entry"));
  11578. }
  11579. TextureCache[id] = texture;
  11580. }
  11581. };
  11582. /**
  11583. * Remove a Texture from the global TextureCache.
  11584. *
  11585. * @static
  11586. * @param {string|PIXI.Texture} texture - id of a Texture to be removed, or a Texture instance itself
  11587. * @return {PIXI.Texture|null} The Texture that was removed
  11588. */
  11589. Texture.removeFromCache = function removeFromCache (texture)
  11590. {
  11591. if (typeof texture === 'string')
  11592. {
  11593. var textureFromCache = TextureCache[texture];
  11594. if (textureFromCache)
  11595. {
  11596. var index = textureFromCache.textureCacheIds.indexOf(texture);
  11597. if (index > -1)
  11598. {
  11599. textureFromCache.textureCacheIds.splice(index, 1);
  11600. }
  11601. delete TextureCache[texture];
  11602. return textureFromCache;
  11603. }
  11604. }
  11605. else if (texture && texture.textureCacheIds)
  11606. {
  11607. for (var i = 0; i < texture.textureCacheIds.length; ++i)
  11608. {
  11609. // Check that texture matches the one being passed in before deleting it from the cache.
  11610. if (TextureCache[texture.textureCacheIds[i]] === texture)
  11611. {
  11612. delete TextureCache[texture.textureCacheIds[i]];
  11613. }
  11614. }
  11615. texture.textureCacheIds.length = 0;
  11616. return texture;
  11617. }
  11618. return null;
  11619. };
  11620. /**
  11621. * The frame specifies the region of the base texture that this texture uses.
  11622. * Please call `updateUvs()` after you change coordinates of `frame` manually.
  11623. *
  11624. * @member {PIXI.Rectangle}
  11625. */
  11626. prototypeAccessors.frame.get = function ()
  11627. {
  11628. return this._frame;
  11629. };
  11630. prototypeAccessors.frame.set = function (frame) // eslint-disable-line require-jsdoc
  11631. {
  11632. this._frame = frame;
  11633. this.noFrame = false;
  11634. var x = frame.x;
  11635. var y = frame.y;
  11636. var width = frame.width;
  11637. var height = frame.height;
  11638. var xNotFit = x + width > this.baseTexture.width;
  11639. var yNotFit = y + height > this.baseTexture.height;
  11640. if (xNotFit || yNotFit)
  11641. {
  11642. var relationship = xNotFit && yNotFit ? 'and' : 'or';
  11643. var errorX = "X: " + x + " + " + width + " = " + (x + width) + " > " + (this.baseTexture.width);
  11644. var errorY = "Y: " + y + " + " + height + " = " + (y + height) + " > " + (this.baseTexture.height);
  11645. throw new Error('Texture Error: frame does not fit inside the base Texture dimensions: '
  11646. + errorX + " " + relationship + " " + errorY);
  11647. }
  11648. this.valid = width && height && this.baseTexture.valid;
  11649. if (!this.trim && !this.rotate)
  11650. {
  11651. this.orig = frame;
  11652. }
  11653. if (this.valid)
  11654. {
  11655. this.updateUvs();
  11656. }
  11657. };
  11658. /**
  11659. * Indicates whether the texture is rotated inside the atlas
  11660. * set to 2 to compensate for texture packer rotation
  11661. * set to 6 to compensate for spine packer rotation
  11662. * can be used to rotate or mirror sprites
  11663. * See {@link PIXI.GroupD8} for explanation
  11664. *
  11665. * @member {number}
  11666. */
  11667. prototypeAccessors.rotate.get = function ()
  11668. {
  11669. return this._rotate;
  11670. };
  11671. prototypeAccessors.rotate.set = function (rotate) // eslint-disable-line require-jsdoc
  11672. {
  11673. this._rotate = rotate;
  11674. if (this.valid)
  11675. {
  11676. this.updateUvs();
  11677. }
  11678. };
  11679. /**
  11680. * The width of the Texture in pixels.
  11681. *
  11682. * @member {number}
  11683. */
  11684. prototypeAccessors.width.get = function ()
  11685. {
  11686. return this.orig.width;
  11687. };
  11688. /**
  11689. * The height of the Texture in pixels.
  11690. *
  11691. * @member {number}
  11692. */
  11693. prototypeAccessors.height.get = function ()
  11694. {
  11695. return this.orig.height;
  11696. };
  11697. Object.defineProperties( Texture.prototype, prototypeAccessors );
  11698. return Texture;
  11699. }(eventemitter3));
  11700. function createWhiteTexture()
  11701. {
  11702. var canvas = document.createElement('canvas');
  11703. canvas.width = 16;
  11704. canvas.height = 16;
  11705. var context = canvas.getContext('2d');
  11706. context.fillStyle = 'white';
  11707. context.fillRect(0, 0, 16, 16);
  11708. return new Texture(new BaseTexture(new CanvasResource(canvas)));
  11709. }
  11710. function removeAllHandlers(tex)
  11711. {
  11712. tex.destroy = function _emptyDestroy() { /* empty */ };
  11713. tex.on = function _emptyOn() { /* empty */ };
  11714. tex.once = function _emptyOnce() { /* empty */ };
  11715. tex.emit = function _emptyEmit() { /* empty */ };
  11716. }
  11717. /**
  11718. * An empty texture, used often to not have to create multiple empty textures.
  11719. * Can not be destroyed.
  11720. *
  11721. * @static
  11722. * @constant
  11723. * @member {PIXI.Texture}
  11724. */
  11725. Texture.EMPTY = new Texture(new BaseTexture());
  11726. removeAllHandlers(Texture.EMPTY);
  11727. removeAllHandlers(Texture.EMPTY.baseTexture);
  11728. /**
  11729. * A white texture of 10x10 size, used for graphics and other things
  11730. * Can not be destroyed.
  11731. *
  11732. * @static
  11733. * @constant
  11734. * @member {PIXI.Texture}
  11735. */
  11736. Texture.WHITE = createWhiteTexture();
  11737. removeAllHandlers(Texture.WHITE);
  11738. removeAllHandlers(Texture.WHITE.baseTexture);
  11739. /**
  11740. * A RenderTexture is a special texture that allows any PixiJS display object to be rendered to it.
  11741. *
  11742. * __Hint__: All DisplayObjects (i.e. Sprites) that render to a RenderTexture should be preloaded
  11743. * otherwise black rectangles will be drawn instead.
  11744. *
  11745. * __Hint-2__: The actual memory allocation will happen on first render.
  11746. * You shouldn't create renderTextures each frame just to delete them after, try to reuse them.
  11747. *
  11748. * A RenderTexture takes a snapshot of any Display Object given to its render method. For example:
  11749. *
  11750. * ```js
  11751. * let renderer = PIXI.autoDetectRenderer();
  11752. * let renderTexture = PIXI.RenderTexture.create(800, 600);
  11753. * let sprite = PIXI.Sprite.from("spinObj_01.png");
  11754. *
  11755. * sprite.position.x = 800/2;
  11756. * sprite.position.y = 600/2;
  11757. * sprite.anchor.x = 0.5;
  11758. * sprite.anchor.y = 0.5;
  11759. *
  11760. * renderer.render(sprite, renderTexture);
  11761. * ```
  11762. *
  11763. * The Sprite in this case will be rendered using its local transform. To render this sprite at 0,0
  11764. * you can clear the transform
  11765. *
  11766. * ```js
  11767. *
  11768. * sprite.setTransform()
  11769. *
  11770. * let renderTexture = new PIXI.RenderTexture.create(100, 100);
  11771. *
  11772. * renderer.render(sprite, renderTexture); // Renders to center of RenderTexture
  11773. * ```
  11774. *
  11775. * @class
  11776. * @extends PIXI.Texture
  11777. * @memberof PIXI
  11778. */
  11779. var RenderTexture = /*@__PURE__*/(function (Texture) {
  11780. function RenderTexture(baseRenderTexture, frame)
  11781. {
  11782. // support for legacy..
  11783. var _legacyRenderer = null;
  11784. if (!(baseRenderTexture instanceof BaseRenderTexture))
  11785. {
  11786. /* eslint-disable prefer-rest-params, no-console */
  11787. var width = arguments[1];
  11788. var height = arguments[2];
  11789. var scaleMode = arguments[3];
  11790. var resolution = arguments[4];
  11791. // we have an old render texture..
  11792. console.warn(("Please use RenderTexture.create(" + width + ", " + height + ") instead of the ctor directly."));
  11793. _legacyRenderer = arguments[0];
  11794. /* eslint-enable prefer-rest-params, no-console */
  11795. frame = null;
  11796. baseRenderTexture = new BaseRenderTexture({
  11797. width: width,
  11798. height: height,
  11799. scaleMode: scaleMode,
  11800. resolution: resolution,
  11801. });
  11802. }
  11803. /**
  11804. * The base texture object that this texture uses
  11805. *
  11806. * @member {PIXI.BaseTexture}
  11807. */
  11808. Texture.call(this, baseRenderTexture, frame);
  11809. this.legacyRenderer = _legacyRenderer;
  11810. /**
  11811. * This will let the renderer know if the texture is valid. If it's not then it cannot be rendered.
  11812. *
  11813. * @member {boolean}
  11814. */
  11815. this.valid = true;
  11816. /**
  11817. * FilterSystem temporary storage
  11818. * @protected
  11819. * @member {PIXI.Rectangle}
  11820. */
  11821. this.filterFrame = null;
  11822. /**
  11823. * The key for pooled texture of FilterSystem
  11824. * @protected
  11825. * @member {string}
  11826. */
  11827. this.filterPoolKey = null;
  11828. this.updateUvs();
  11829. }
  11830. if ( Texture ) { RenderTexture.__proto__ = Texture; }
  11831. RenderTexture.prototype = Object.create( Texture && Texture.prototype );
  11832. RenderTexture.prototype.constructor = RenderTexture;
  11833. /**
  11834. * Resizes the RenderTexture.
  11835. *
  11836. * @param {number} width - The width to resize to.
  11837. * @param {number} height - The height to resize to.
  11838. * @param {boolean} [resizeBaseTexture=true] - Should the baseTexture.width and height values be resized as well?
  11839. */
  11840. RenderTexture.prototype.resize = function resize (width, height, resizeBaseTexture)
  11841. {
  11842. if ( resizeBaseTexture === void 0 ) { resizeBaseTexture = true; }
  11843. width = Math.ceil(width);
  11844. height = Math.ceil(height);
  11845. // TODO - could be not required..
  11846. this.valid = (width > 0 && height > 0);
  11847. this._frame.width = this.orig.width = width;
  11848. this._frame.height = this.orig.height = height;
  11849. if (resizeBaseTexture)
  11850. {
  11851. this.baseTexture.resize(width, height);
  11852. }
  11853. this.updateUvs();
  11854. };
  11855. /**
  11856. * Changes the resolution of baseTexture, but does not change framebuffer size.
  11857. *
  11858. * @param {number} resolution - The new resolution to apply to RenderTexture
  11859. */
  11860. RenderTexture.prototype.setResolution = function setResolution (resolution)
  11861. {
  11862. var ref = this;
  11863. var baseTexture = ref.baseTexture;
  11864. if (baseTexture.resolution === resolution)
  11865. {
  11866. return;
  11867. }
  11868. baseTexture.setResolution(resolution);
  11869. this.resize(baseTexture.width, baseTexture.height, false);
  11870. };
  11871. /**
  11872. * A short hand way of creating a render texture.
  11873. *
  11874. * @param {object} [options] - Options
  11875. * @param {number} [options.width=100] - The width of the render texture
  11876. * @param {number} [options.height=100] - The height of the render texture
  11877. * @param {number} [options.scaleMode=PIXI.settings.SCALE_MODE] - See {@link PIXI.SCALE_MODES} for possible values
  11878. * @param {number} [options.resolution=1] - The resolution / device pixel ratio of the texture being generated
  11879. * @return {PIXI.RenderTexture} The new render texture
  11880. */
  11881. RenderTexture.create = function create (options)
  11882. {
  11883. // fallback, old-style: create(width, height, scaleMode, resolution)
  11884. if (typeof options === 'number')
  11885. {
  11886. /* eslint-disable prefer-rest-params */
  11887. options = {
  11888. width: options,
  11889. height: arguments[1],
  11890. scaleMode: arguments[2],
  11891. resolution: arguments[3],
  11892. };
  11893. /* eslint-enable prefer-rest-params */
  11894. }
  11895. return new RenderTexture(new BaseRenderTexture(options));
  11896. };
  11897. return RenderTexture;
  11898. }(Texture));
  11899. /* eslint-disable max-len */
  11900. /**
  11901. * Holds the information for a single attribute structure required to render geometry.
  11902. *
  11903. * This does not contain the actual data, but instead has a buffer id that maps to a {@link PIXI.Buffer}
  11904. * This can include anything from positions, uvs, normals, colors etc.
  11905. *
  11906. * @class
  11907. * @memberof PIXI
  11908. */
  11909. var Attribute = function Attribute(buffer, size, normalized, type, stride, start, instance)
  11910. {
  11911. if ( normalized === void 0 ) { normalized = false; }
  11912. if ( type === void 0 ) { type = 5126; }
  11913. this.buffer = buffer;
  11914. this.size = size;
  11915. this.normalized = normalized;
  11916. this.type = type;
  11917. this.stride = stride;
  11918. this.start = start;
  11919. this.instance = instance;
  11920. };
  11921. /**
  11922. * Destroys the Attribute.
  11923. */
  11924. Attribute.prototype.destroy = function destroy ()
  11925. {
  11926. this.buffer = null;
  11927. };
  11928. /**
  11929. * Helper function that creates an Attribute based on the information provided
  11930. *
  11931. * @static
  11932. * @param {string} buffer the id of the buffer that this attribute will look for
  11933. * @param {Number} [size=2] the size of the attribute. If you have 2 floats per vertex (eg position x and y) this would be 2
  11934. * @param {Number} [stride=0] How far apart (in floats) the start of each value is. (used for interleaving data)
  11935. * @param {Number} [start=0] How far into the array to start reading values (used for interleaving data)
  11936. * @param {Boolean} [normalized=false] should the data be normalized.
  11937. *
  11938. * @returns {PIXI.Attribute} A new {@link PIXI.Attribute} based on the information provided
  11939. */
  11940. Attribute.from = function from (buffer, size, normalized, type, stride)
  11941. {
  11942. return new Attribute(buffer, size, normalized, type, stride);
  11943. };
  11944. var UID = 0;
  11945. /* eslint-disable max-len */
  11946. /**
  11947. * A wrapper for data so that it can be used and uploaded by WebGL
  11948. *
  11949. * @class
  11950. * @memberof PIXI
  11951. */
  11952. var Buffer = function Buffer(data, _static, index)
  11953. {
  11954. if ( _static === void 0 ) { _static = true; }
  11955. if ( index === void 0 ) { index = false; }
  11956. /**
  11957. * The data in the buffer, as a typed array
  11958. *
  11959. * @member {ArrayBuffer| SharedArrayBuffer|ArrayBufferView}
  11960. */
  11961. this.data = data || new Float32Array(1);
  11962. /**
  11963. * A map of renderer IDs to webgl buffer
  11964. *
  11965. * @private
  11966. * @member {object<number, GLBuffer>}
  11967. */
  11968. this._glBuffers = {};
  11969. this._updateID = 0;
  11970. this.index = index;
  11971. this.static = _static;
  11972. this.id = UID++;
  11973. this.disposeRunner = new Runner('disposeBuffer', 2);
  11974. };
  11975. // TODO could explore flagging only a partial upload?
  11976. /**
  11977. * flags this buffer as requiring an upload to the GPU
  11978. * @param {ArrayBuffer|SharedArrayBuffer|ArrayBufferView} [data] the data to update in the buffer.
  11979. */
  11980. Buffer.prototype.update = function update (data)
  11981. {
  11982. this.data = data || this.data;
  11983. this._updateID++;
  11984. };
  11985. /**
  11986. * disposes WebGL resources that are connected to this geometry
  11987. */
  11988. Buffer.prototype.dispose = function dispose ()
  11989. {
  11990. this.disposeRunner.run(this, false);
  11991. };
  11992. /**
  11993. * Destroys the buffer
  11994. */
  11995. Buffer.prototype.destroy = function destroy ()
  11996. {
  11997. this.dispose();
  11998. this.data = null;
  11999. };
  12000. /**
  12001. * Helper function that creates a buffer based on an array or TypedArray
  12002. *
  12003. * @static
  12004. * @param {ArrayBufferView | number[]} data the TypedArray that the buffer will store. If this is a regular Array it will be converted to a Float32Array.
  12005. * @return {PIXI.Buffer} A new Buffer based on the data provided.
  12006. */
  12007. Buffer.from = function from (data)
  12008. {
  12009. if (data instanceof Array)
  12010. {
  12011. data = new Float32Array(data);
  12012. }
  12013. return new Buffer(data);
  12014. };
  12015. function getBufferType(array)
  12016. {
  12017. if (array.BYTES_PER_ELEMENT === 4)
  12018. {
  12019. if (array instanceof Float32Array)
  12020. {
  12021. return 'Float32Array';
  12022. }
  12023. else if (array instanceof Uint32Array)
  12024. {
  12025. return 'Uint32Array';
  12026. }
  12027. return 'Int32Array';
  12028. }
  12029. else if (array.BYTES_PER_ELEMENT === 2)
  12030. {
  12031. if (array instanceof Uint16Array)
  12032. {
  12033. return 'Uint16Array';
  12034. }
  12035. }
  12036. else if (array.BYTES_PER_ELEMENT === 1)
  12037. {
  12038. if (array instanceof Uint8Array)
  12039. {
  12040. return 'Uint8Array';
  12041. }
  12042. }
  12043. // TODO map out the rest of the array elements!
  12044. return null;
  12045. }
  12046. /* eslint-disable object-shorthand */
  12047. var map = {
  12048. Float32Array: Float32Array,
  12049. Uint32Array: Uint32Array,
  12050. Int32Array: Int32Array,
  12051. Uint8Array: Uint8Array,
  12052. };
  12053. function interleaveTypedArrays(arrays, sizes)
  12054. {
  12055. var outSize = 0;
  12056. var stride = 0;
  12057. var views = {};
  12058. for (var i = 0; i < arrays.length; i++)
  12059. {
  12060. stride += sizes[i];
  12061. outSize += arrays[i].length;
  12062. }
  12063. var buffer = new ArrayBuffer(outSize * 4);
  12064. var out = null;
  12065. var littleOffset = 0;
  12066. for (var i$1 = 0; i$1 < arrays.length; i$1++)
  12067. {
  12068. var size = sizes[i$1];
  12069. var array = arrays[i$1];
  12070. var type = getBufferType(array);
  12071. if (!views[type])
  12072. {
  12073. views[type] = new map[type](buffer);
  12074. }
  12075. out = views[type];
  12076. for (var j = 0; j < array.length; j++)
  12077. {
  12078. var indexStart = ((j / size | 0) * stride) + littleOffset;
  12079. var index = j % size;
  12080. out[indexStart + index] = array[j];
  12081. }
  12082. littleOffset += size;
  12083. }
  12084. return new Float32Array(buffer);
  12085. }
  12086. var byteSizeMap = { 5126: 4, 5123: 2, 5121: 1 };
  12087. var UID$1 = 0;
  12088. /* eslint-disable object-shorthand */
  12089. var map$1 = {
  12090. Float32Array: Float32Array,
  12091. Uint32Array: Uint32Array,
  12092. Int32Array: Int32Array,
  12093. Uint8Array: Uint8Array,
  12094. Uint16Array: Uint16Array,
  12095. };
  12096. /* eslint-disable max-len */
  12097. /**
  12098. * The Geometry represents a model. It consists of two components:
  12099. * - GeometryStyle - The structure of the model such as the attributes layout
  12100. * - GeometryData - the data of the model - this consists of buffers.
  12101. * This can include anything from positions, uvs, normals, colors etc.
  12102. *
  12103. * Geometry can be defined without passing in a style or data if required (thats how I prefer!)
  12104. *
  12105. * ```js
  12106. * let geometry = new PIXI.Geometry();
  12107. *
  12108. * geometry.addAttribute('positions', [0, 0, 100, 0, 100, 100, 0, 100], 2);
  12109. * geometry.addAttribute('uvs', [0,0,1,0,1,1,0,1],2)
  12110. * geometry.addIndex([0,1,2,1,3,2])
  12111. *
  12112. * ```
  12113. * @class
  12114. * @memberof PIXI
  12115. */
  12116. var Geometry = function Geometry(buffers, attributes)
  12117. {
  12118. if ( buffers === void 0 ) { buffers = []; }
  12119. if ( attributes === void 0 ) { attributes = {}; }
  12120. this.buffers = buffers;
  12121. this.indexBuffer = null;
  12122. this.attributes = attributes;
  12123. /**
  12124. * A map of renderer IDs to webgl VAOs
  12125. *
  12126. * @protected
  12127. * @type {object}
  12128. */
  12129. this.glVertexArrayObjects = {};
  12130. this.id = UID$1++;
  12131. this.instanced = false;
  12132. this.instanceCount = 1;
  12133. this._size = null;
  12134. this.disposeRunner = new Runner('disposeGeometry', 2);
  12135. /**
  12136. * Count of existing (not destroyed) meshes that reference this geometry
  12137. * @member {boolean}
  12138. */
  12139. this.refCount = 0;
  12140. };
  12141. /**
  12142. *
  12143. * Adds an attribute to the geometry
  12144. *
  12145. * @param {String} id - the name of the attribute (matching up to a shader)
  12146. * @param {PIXI.Buffer} [buffer] the buffer that holds the data of the attribute . You can also provide an Array and a buffer will be created from it.
  12147. * @param {Number} [size=0] the size of the attribute. If you have 2 floats per vertex (eg position x and y) this would be 2
  12148. * @param {Boolean} [normalized=false] should the data be normalized.
  12149. * @param {Number} [type=PIXI.TYPES.FLOAT] what type of number is the attribute. Check {PIXI.TYPES} to see the ones available
  12150. * @param {Number} [stride=0] How far apart (in floats) the start of each value is. (used for interleaving data)
  12151. * @param {Number} [start=0] How far into the array to start reading values (used for interleaving data)
  12152. *
  12153. * @return {PIXI.Geometry} returns self, useful for chaining.
  12154. */
  12155. Geometry.prototype.addAttribute = function addAttribute (id, buffer, size, normalized, type, stride, start, instance)
  12156. {
  12157. if ( normalized === void 0 ) { normalized = false; }
  12158. if ( instance === void 0 ) { instance = false; }
  12159. if (!buffer)
  12160. {
  12161. throw new Error('You must pass a buffer when creating an attribute');
  12162. }
  12163. // check if this is a buffer!
  12164. if (!buffer.data)
  12165. {
  12166. // its an array!
  12167. if (buffer instanceof Array)
  12168. {
  12169. buffer = new Float32Array(buffer);
  12170. }
  12171. buffer = new Buffer(buffer);
  12172. }
  12173. var ids = id.split('|');
  12174. if (ids.length > 1)
  12175. {
  12176. for (var i = 0; i < ids.length; i++)
  12177. {
  12178. this.addAttribute(ids[i], buffer, size, normalized, type);
  12179. }
  12180. return this;
  12181. }
  12182. var bufferIndex = this.buffers.indexOf(buffer);
  12183. if (bufferIndex === -1)
  12184. {
  12185. this.buffers.push(buffer);
  12186. bufferIndex = this.buffers.length - 1;
  12187. }
  12188. this.attributes[id] = new Attribute(bufferIndex, size, normalized, type, stride, start, instance);
  12189. // assuming that if there is instanced data then this will be drawn with instancing!
  12190. this.instanced = this.instanced || instance;
  12191. return this;
  12192. };
  12193. /**
  12194. * returns the requested attribute
  12195. *
  12196. * @param {String} id the name of the attribute required
  12197. * @return {PIXI.Attribute} the attribute requested.
  12198. */
  12199. Geometry.prototype.getAttribute = function getAttribute (id)
  12200. {
  12201. return this.attributes[id];
  12202. };
  12203. /**
  12204. * returns the requested buffer
  12205. *
  12206. * @param {String} id the name of the buffer required
  12207. * @return {PIXI.Buffer} the buffer requested.
  12208. */
  12209. Geometry.prototype.getBuffer = function getBuffer (id)
  12210. {
  12211. return this.buffers[this.getAttribute(id).buffer];
  12212. };
  12213. /**
  12214. *
  12215. * Adds an index buffer to the geometry
  12216. * 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.
  12217. *
  12218. * @param {PIXI.Buffer} [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.
  12219. * @return {PIXI.Geometry} returns self, useful for chaining.
  12220. */
  12221. Geometry.prototype.addIndex = function addIndex (buffer)
  12222. {
  12223. if (!buffer.data)
  12224. {
  12225. // its an array!
  12226. if (buffer instanceof Array)
  12227. {
  12228. buffer = new Uint16Array(buffer);
  12229. }
  12230. buffer = new Buffer(buffer);
  12231. }
  12232. buffer.index = true;
  12233. this.indexBuffer = buffer;
  12234. if (this.buffers.indexOf(buffer) === -1)
  12235. {
  12236. this.buffers.push(buffer);
  12237. }
  12238. return this;
  12239. };
  12240. /**
  12241. * returns the index buffer
  12242. *
  12243. * @return {PIXI.Buffer} the index buffer.
  12244. */
  12245. Geometry.prototype.getIndex = function getIndex ()
  12246. {
  12247. return this.indexBuffer;
  12248. };
  12249. /**
  12250. * this function modifies the structure so that all current attributes become interleaved into a single buffer
  12251. * This can be useful if your model remains static as it offers a little performance boost
  12252. *
  12253. * @return {PIXI.Geometry} returns self, useful for chaining.
  12254. */
  12255. Geometry.prototype.interleave = function interleave ()
  12256. {
  12257. // a simple check to see if buffers are already interleaved..
  12258. if (this.buffers.length === 1 || (this.buffers.length === 2 && this.indexBuffer)) { return this; }
  12259. // assume already that no buffers are interleaved
  12260. var arrays = [];
  12261. var sizes = [];
  12262. var interleavedBuffer = new Buffer();
  12263. var i;
  12264. for (i in this.attributes)
  12265. {
  12266. var attribute = this.attributes[i];
  12267. var buffer = this.buffers[attribute.buffer];
  12268. arrays.push(buffer.data);
  12269. sizes.push((attribute.size * byteSizeMap[attribute.type]) / 4);
  12270. attribute.buffer = 0;
  12271. }
  12272. interleavedBuffer.data = interleaveTypedArrays(arrays, sizes);
  12273. for (i = 0; i < this.buffers.length; i++)
  12274. {
  12275. if (this.buffers[i] !== this.indexBuffer)
  12276. {
  12277. this.buffers[i].destroy();
  12278. }
  12279. }
  12280. this.buffers = [interleavedBuffer];
  12281. if (this.indexBuffer)
  12282. {
  12283. this.buffers.push(this.indexBuffer);
  12284. }
  12285. return this;
  12286. };
  12287. Geometry.prototype.getSize = function getSize ()
  12288. {
  12289. for (var i in this.attributes)
  12290. {
  12291. var attribute = this.attributes[i];
  12292. var buffer = this.buffers[attribute.buffer];
  12293. return buffer.data.length / ((attribute.stride / 4) || attribute.size);
  12294. }
  12295. return 0;
  12296. };
  12297. /**
  12298. * disposes WebGL resources that are connected to this geometry
  12299. */
  12300. Geometry.prototype.dispose = function dispose ()
  12301. {
  12302. this.disposeRunner.run(this, false);
  12303. };
  12304. /**
  12305. * Destroys the geometry.
  12306. */
  12307. Geometry.prototype.destroy = function destroy ()
  12308. {
  12309. this.dispose();
  12310. this.buffers = null;
  12311. this.indexBuffer.destroy();
  12312. this.attributes = null;
  12313. };
  12314. /**
  12315. * returns a clone of the geometry
  12316. *
  12317. * @returns {PIXI.Geometry} a new clone of this geometry
  12318. */
  12319. Geometry.prototype.clone = function clone ()
  12320. {
  12321. var geometry = new Geometry();
  12322. for (var i = 0; i < this.buffers.length; i++)
  12323. {
  12324. geometry.buffers[i] = new Buffer(this.buffers[i].data.slice());
  12325. }
  12326. for (var i$1 in this.attributes)
  12327. {
  12328. var attrib = this.attributes[i$1];
  12329. geometry.attributes[i$1] = new Attribute(
  12330. attrib.buffer,
  12331. attrib.size,
  12332. attrib.normalized,
  12333. attrib.type,
  12334. attrib.stride,
  12335. attrib.start,
  12336. attrib.instance
  12337. );
  12338. }
  12339. if (this.indexBuffer)
  12340. {
  12341. geometry.indexBuffer = geometry.buffers[this.buffers.indexOf(this.indexBuffer)];
  12342. geometry.indexBuffer.index = true;
  12343. }
  12344. return geometry;
  12345. };
  12346. /**
  12347. * merges an array of geometries into a new single one
  12348. * geometry attribute styles must match for this operation to work
  12349. *
  12350. * @param {PIXI.Geometry[]} geometries array of geometries to merge
  12351. * @returns {PIXI.Geometry} shiny new geometry!
  12352. */
  12353. Geometry.merge = function merge (geometries)
  12354. {
  12355. // todo add a geometry check!
  12356. // also a size check.. cant be too big!]
  12357. var geometryOut = new Geometry();
  12358. var arrays = [];
  12359. var sizes = [];
  12360. var offsets = [];
  12361. var geometry;
  12362. // pass one.. get sizes..
  12363. for (var i = 0; i < geometries.length; i++)
  12364. {
  12365. geometry = geometries[i];
  12366. for (var j = 0; j < geometry.buffers.length; j++)
  12367. {
  12368. sizes[j] = sizes[j] || 0;
  12369. sizes[j] += geometry.buffers[j].data.length;
  12370. offsets[j] = 0;
  12371. }
  12372. }
  12373. // build the correct size arrays..
  12374. for (var i$1 = 0; i$1 < geometry.buffers.length; i$1++)
  12375. {
  12376. // TODO types!
  12377. arrays[i$1] = new map$1[getBufferType(geometry.buffers[i$1].data)](sizes[i$1]);
  12378. geometryOut.buffers[i$1] = new Buffer(arrays[i$1]);
  12379. }
  12380. // pass to set data..
  12381. for (var i$2 = 0; i$2 < geometries.length; i$2++)
  12382. {
  12383. geometry = geometries[i$2];
  12384. for (var j$1 = 0; j$1 < geometry.buffers.length; j$1++)
  12385. {
  12386. arrays[j$1].set(geometry.buffers[j$1].data, offsets[j$1]);
  12387. offsets[j$1] += geometry.buffers[j$1].data.length;
  12388. }
  12389. }
  12390. geometryOut.attributes = geometry.attributes;
  12391. if (geometry.indexBuffer)
  12392. {
  12393. geometryOut.indexBuffer = geometryOut.buffers[geometry.buffers.indexOf(geometry.indexBuffer)];
  12394. geometryOut.indexBuffer.index = true;
  12395. var offset = 0;
  12396. var stride = 0;
  12397. var offset2 = 0;
  12398. var bufferIndexToCount = 0;
  12399. // get a buffer
  12400. for (var i$3 = 0; i$3 < geometry.buffers.length; i$3++)
  12401. {
  12402. if (geometry.buffers[i$3] !== geometry.indexBuffer)
  12403. {
  12404. bufferIndexToCount = i$3;
  12405. break;
  12406. }
  12407. }
  12408. // figure out the stride of one buffer..
  12409. for (var i$4 in geometry.attributes)
  12410. {
  12411. var attribute = geometry.attributes[i$4];
  12412. if ((attribute.buffer | 0) === bufferIndexToCount)
  12413. {
  12414. stride += ((attribute.size * byteSizeMap[attribute.type]) / 4);
  12415. }
  12416. }
  12417. // time to off set all indexes..
  12418. for (var i$5 = 0; i$5 < geometries.length; i$5++)
  12419. {
  12420. var indexBufferData = geometries[i$5].indexBuffer.data;
  12421. for (var j$2 = 0; j$2 < indexBufferData.length; j$2++)
  12422. {
  12423. geometryOut.indexBuffer.data[j$2 + offset2] += offset;
  12424. }
  12425. offset += geometry.buffers[bufferIndexToCount].data.length / (stride);
  12426. offset2 += indexBufferData.length;
  12427. }
  12428. }
  12429. return geometryOut;
  12430. };
  12431. /**
  12432. * Helper class to create a quad
  12433. *
  12434. * @class
  12435. * @memberof PIXI
  12436. */
  12437. var Quad = /*@__PURE__*/(function (Geometry) {
  12438. function Quad()
  12439. {
  12440. Geometry.call(this);
  12441. this.addAttribute('aVertexPosition', [
  12442. 0, 0,
  12443. 1, 0,
  12444. 1, 1,
  12445. 0, 1 ])
  12446. .addIndex([0, 1, 3, 2]);
  12447. }
  12448. if ( Geometry ) { Quad.__proto__ = Geometry; }
  12449. Quad.prototype = Object.create( Geometry && Geometry.prototype );
  12450. Quad.prototype.constructor = Quad;
  12451. return Quad;
  12452. }(Geometry));
  12453. /**
  12454. * Helper class to create a quad with uvs like in v4
  12455. *
  12456. * @class
  12457. * @memberof PIXI
  12458. */
  12459. var QuadUv = /*@__PURE__*/(function (Geometry) {
  12460. function QuadUv()
  12461. {
  12462. Geometry.call(this);
  12463. /**
  12464. * An array of vertices
  12465. *
  12466. * @member {Float32Array}
  12467. */
  12468. this.vertices = new Float32Array([
  12469. -1, -1,
  12470. 1, -1,
  12471. 1, 1,
  12472. -1, 1 ]);
  12473. /**
  12474. * The Uvs of the quad
  12475. *
  12476. * @member {Float32Array}
  12477. */
  12478. this.uvs = new Float32Array([
  12479. 0, 0,
  12480. 1, 0,
  12481. 1, 1,
  12482. 0, 1 ]);
  12483. this.vertexBuffer = new Buffer(this.vertices);
  12484. this.uvBuffer = new Buffer(this.uvs);
  12485. this.addAttribute('aVertexPosition', this.vertexBuffer)
  12486. .addAttribute('aTextureCoord', this.uvBuffer)
  12487. .addIndex([0, 1, 2, 0, 2, 3]);
  12488. }
  12489. if ( Geometry ) { QuadUv.__proto__ = Geometry; }
  12490. QuadUv.prototype = Object.create( Geometry && Geometry.prototype );
  12491. QuadUv.prototype.constructor = QuadUv;
  12492. /**
  12493. * Maps two Rectangle to the quad.
  12494. *
  12495. * @param {PIXI.Rectangle} targetTextureFrame - the first rectangle
  12496. * @param {PIXI.Rectangle} destinationFrame - the second rectangle
  12497. * @return {PIXI.Quad} Returns itself.
  12498. */
  12499. QuadUv.prototype.map = function map (targetTextureFrame, destinationFrame)
  12500. {
  12501. var x = 0; // destinationFrame.x / targetTextureFrame.width;
  12502. var y = 0; // destinationFrame.y / targetTextureFrame.height;
  12503. this.uvs[0] = x;
  12504. this.uvs[1] = y;
  12505. this.uvs[2] = x + (destinationFrame.width / targetTextureFrame.width);
  12506. this.uvs[3] = y;
  12507. this.uvs[4] = x + (destinationFrame.width / targetTextureFrame.width);
  12508. this.uvs[5] = y + (destinationFrame.height / targetTextureFrame.height);
  12509. this.uvs[6] = x;
  12510. this.uvs[7] = y + (destinationFrame.height / targetTextureFrame.height);
  12511. x = destinationFrame.x;
  12512. y = destinationFrame.y;
  12513. this.vertices[0] = x;
  12514. this.vertices[1] = y;
  12515. this.vertices[2] = x + destinationFrame.width;
  12516. this.vertices[3] = y;
  12517. this.vertices[4] = x + destinationFrame.width;
  12518. this.vertices[5] = y + destinationFrame.height;
  12519. this.vertices[6] = x;
  12520. this.vertices[7] = y + destinationFrame.height;
  12521. this.invalidate();
  12522. return this;
  12523. };
  12524. /**
  12525. * legacy upload method, just marks buffers dirty
  12526. * @returns {PIXI.QuadUv} Returns itself.
  12527. */
  12528. QuadUv.prototype.invalidate = function invalidate ()
  12529. {
  12530. this.vertexBuffer._updateID++;
  12531. this.uvBuffer._updateID++;
  12532. return this;
  12533. };
  12534. return QuadUv;
  12535. }(Geometry));
  12536. var UID$2 = 0;
  12537. /**
  12538. * Uniform group holds uniform map and some ID's for work
  12539. *
  12540. * @class
  12541. * @memberof PIXI
  12542. */
  12543. var UniformGroup = function UniformGroup(uniforms, _static)
  12544. {
  12545. /**
  12546. * uniform values
  12547. * @member {object}
  12548. * @readonly
  12549. */
  12550. this.uniforms = uniforms;
  12551. /**
  12552. * Its a group and not a single uniforms
  12553. * @member {boolean}
  12554. * @readonly
  12555. * @default true
  12556. */
  12557. this.group = true;
  12558. // lets generate this when the shader ?
  12559. this.syncUniforms = {};
  12560. /**
  12561. * dirty version
  12562. * @protected
  12563. * @member {number}
  12564. */
  12565. this.dirtyId = 0;
  12566. /**
  12567. * unique id
  12568. * @protected
  12569. * @member {number}
  12570. */
  12571. this.id = UID$2++;
  12572. /**
  12573. * Uniforms wont be changed after creation
  12574. * @member {boolean}
  12575. */
  12576. this.static = !!_static;
  12577. };
  12578. UniformGroup.prototype.update = function update ()
  12579. {
  12580. this.dirtyId++;
  12581. };
  12582. UniformGroup.prototype.add = function add (name, uniforms, _static)
  12583. {
  12584. this.uniforms[name] = new UniformGroup(uniforms, _static);
  12585. };
  12586. UniformGroup.from = function from (uniforms, _static)
  12587. {
  12588. return new UniformGroup(uniforms, _static);
  12589. };
  12590. /**
  12591. * System plugin to the renderer to manage filter states.
  12592. *
  12593. * @class
  12594. * @private
  12595. */
  12596. var FilterState = function FilterState()
  12597. {
  12598. this.renderTexture = null;
  12599. /**
  12600. * Target of the filters
  12601. * We store for case when custom filter wants to know the element it was applied on
  12602. * @member {PIXI.DisplayObject}
  12603. * @private
  12604. */
  12605. this.target = null;
  12606. /**
  12607. * Compatibility with PixiJS v4 filters
  12608. * @member {boolean}
  12609. * @default false
  12610. * @private
  12611. */
  12612. this.legacy = false;
  12613. /**
  12614. * Resolution of filters
  12615. * @member {number}
  12616. * @default 1
  12617. * @private
  12618. */
  12619. this.resolution = 1;
  12620. // next three fields are created only for root
  12621. // re-assigned for everything else
  12622. /**
  12623. * Source frame
  12624. * @member {PIXI.Rectangle}
  12625. * @private
  12626. */
  12627. this.sourceFrame = new Rectangle();
  12628. /**
  12629. * Destination frame
  12630. * @member {PIXI.Rectangle}
  12631. * @private
  12632. */
  12633. this.destinationFrame = new Rectangle();
  12634. /**
  12635. * Collection of filters
  12636. * @member {PIXI.Filter[]}
  12637. * @private
  12638. */
  12639. this.filters = [];
  12640. };
  12641. /**
  12642. * clears the state
  12643. * @private
  12644. */
  12645. FilterState.prototype.clear = function clear ()
  12646. {
  12647. this.target = null;
  12648. this.filters = null;
  12649. this.renderTexture = null;
  12650. };
  12651. var screenKey = 'screen';
  12652. /**
  12653. * System plugin to the renderer to manage the filters.
  12654. *
  12655. * @class
  12656. * @memberof PIXI.systems
  12657. * @extends PIXI.System
  12658. */
  12659. var FilterSystem = /*@__PURE__*/(function (System) {
  12660. function FilterSystem(renderer)
  12661. {
  12662. System.call(this, renderer);
  12663. /**
  12664. * List of filters for the FilterSystem
  12665. * @member {Object[]}
  12666. * @readonly
  12667. */
  12668. this.defaultFilterStack = [{}];
  12669. /**
  12670. * stores a bunch of PO2 textures used for filtering
  12671. * @member {Object}
  12672. */
  12673. this.texturePool = {};
  12674. /**
  12675. * a pool for storing filter states, save us creating new ones each tick
  12676. * @member {Object[]}
  12677. */
  12678. this.statePool = [];
  12679. /**
  12680. * A very simple geometry used when drawing a filter effect to the screen
  12681. * @member {PIXI.Quad}
  12682. */
  12683. this.quad = new Quad();
  12684. /**
  12685. * Quad UVs
  12686. * @member {PIXI.QuadUv}
  12687. */
  12688. this.quadUv = new QuadUv();
  12689. /**
  12690. * Temporary rect for maths
  12691. * @type {PIXI.Rectangle}
  12692. */
  12693. this.tempRect = new Rectangle();
  12694. /**
  12695. * Active state
  12696. * @member {object}
  12697. */
  12698. this.activeState = {};
  12699. /**
  12700. * This uniform group is attached to filter uniforms when used
  12701. * @member {PIXI.UniformGroup}
  12702. * @property {PIXI.Rectangle} outputFrame
  12703. * @property {Float32Array} inputSize
  12704. * @property {Float32Array} inputPixel
  12705. * @property {Float32Array} inputClamp
  12706. * @property {Number} resolution
  12707. * @property {Float32Array} filterArea
  12708. * @property {Fload32Array} filterClamp
  12709. */
  12710. this.globalUniforms = new UniformGroup({
  12711. outputFrame: this.tempRect,
  12712. inputSize: new Float32Array(4),
  12713. inputPixel: new Float32Array(4),
  12714. inputClamp: new Float32Array(4),
  12715. resolution: 1,
  12716. // legacy variables
  12717. filterArea: new Float32Array(4),
  12718. filterClamp: new Float32Array(4),
  12719. }, true);
  12720. this._pixelsWidth = renderer.view.width;
  12721. this._pixelsHeight = renderer.view.height;
  12722. }
  12723. if ( System ) { FilterSystem.__proto__ = System; }
  12724. FilterSystem.prototype = Object.create( System && System.prototype );
  12725. FilterSystem.prototype.constructor = FilterSystem;
  12726. /**
  12727. * Adds a new filter to the System.
  12728. *
  12729. * @param {PIXI.DisplayObject} target - The target of the filter to render.
  12730. * @param {PIXI.Filter[]} filters - The filters to apply.
  12731. */
  12732. FilterSystem.prototype.push = function push (target, filters)
  12733. {
  12734. var renderer = this.renderer;
  12735. var filterStack = this.defaultFilterStack;
  12736. var state = this.statePool.pop() || new FilterState();
  12737. var resolution = filters[0].resolution;
  12738. var padding = filters[0].padding;
  12739. var autoFit = filters[0].autoFit;
  12740. var legacy = filters[0].legacy;
  12741. for (var i = 1; i < filters.length; i++)
  12742. {
  12743. var filter = filters[i];
  12744. // lets use the lowest resolution..
  12745. resolution = Math.min(resolution, filter.resolution);
  12746. // and the largest amount of padding!
  12747. padding = Math.max(padding, filter.padding);
  12748. // only auto fit if all filters are autofit
  12749. autoFit = autoFit || filter.autoFit;
  12750. legacy = legacy || filter.legacy;
  12751. }
  12752. if (filterStack.length === 1)
  12753. {
  12754. this.defaultFilterStack[0].renderTexture = renderer.renderTexture.current;
  12755. }
  12756. filterStack.push(state);
  12757. state.resolution = resolution;
  12758. state.legacy = legacy;
  12759. state.target = target;
  12760. state.sourceFrame.copyFrom(target.filterArea || target.getBounds(true));
  12761. state.sourceFrame.pad(padding);
  12762. if (autoFit)
  12763. {
  12764. state.sourceFrame.fit(this.renderer.renderTexture.sourceFrame);
  12765. }
  12766. // round to whole number based on resolution
  12767. state.sourceFrame.ceil(resolution);
  12768. state.renderTexture = this.getOptimalFilterTexture(state.sourceFrame.width, state.sourceFrame.height, resolution);
  12769. state.filters = filters;
  12770. state.destinationFrame.width = state.renderTexture.width;
  12771. state.destinationFrame.height = state.renderTexture.height;
  12772. state.renderTexture.filterFrame = state.sourceFrame;
  12773. renderer.renderTexture.bind(state.renderTexture, state.sourceFrame);// /, state.destinationFrame);
  12774. renderer.renderTexture.clear();
  12775. };
  12776. /**
  12777. * Pops off the filter and applies it.
  12778. *
  12779. */
  12780. FilterSystem.prototype.pop = function pop ()
  12781. {
  12782. var filterStack = this.defaultFilterStack;
  12783. var state = filterStack.pop();
  12784. var filters = state.filters;
  12785. this.activeState = state;
  12786. var globalUniforms = this.globalUniforms.uniforms;
  12787. globalUniforms.outputFrame = state.sourceFrame;
  12788. globalUniforms.resolution = state.resolution;
  12789. var inputSize = globalUniforms.inputSize;
  12790. var inputPixel = globalUniforms.inputPixel;
  12791. var inputClamp = globalUniforms.inputClamp;
  12792. inputSize[0] = state.destinationFrame.width;
  12793. inputSize[1] = state.destinationFrame.height;
  12794. inputSize[2] = 1.0 / inputSize[0];
  12795. inputSize[3] = 1.0 / inputSize[1];
  12796. inputPixel[0] = inputSize[0] * state.resolution;
  12797. inputPixel[1] = inputSize[1] * state.resolution;
  12798. inputPixel[2] = 1.0 / inputPixel[0];
  12799. inputPixel[3] = 1.0 / inputPixel[1];
  12800. inputClamp[0] = 0.5 * inputPixel[2];
  12801. inputClamp[1] = 0.5 * inputPixel[3];
  12802. inputClamp[2] = (state.sourceFrame.width * inputSize[2]) - (0.5 * inputPixel[2]);
  12803. inputClamp[3] = (state.sourceFrame.height * inputSize[3]) - (0.5 * inputPixel[3]);
  12804. // only update the rect if its legacy..
  12805. if (state.legacy)
  12806. {
  12807. var filterArea = globalUniforms.filterArea;
  12808. filterArea[0] = state.destinationFrame.width;
  12809. filterArea[1] = state.destinationFrame.height;
  12810. filterArea[2] = state.sourceFrame.x;
  12811. filterArea[3] = state.sourceFrame.y;
  12812. globalUniforms.filterClamp = globalUniforms.inputClamp;
  12813. }
  12814. this.globalUniforms.update();
  12815. var lastState = filterStack[filterStack.length - 1];
  12816. if (filters.length === 1)
  12817. {
  12818. filters[0].apply(this, state.renderTexture, lastState.renderTexture, false, state);
  12819. this.returnFilterTexture(state.renderTexture);
  12820. }
  12821. else
  12822. {
  12823. var flip = state.renderTexture;
  12824. var flop = this.getOptimalFilterTexture(
  12825. flip.width,
  12826. flip.height,
  12827. state.resolution
  12828. );
  12829. flop.filterFrame = flip.filterFrame;
  12830. var i = 0;
  12831. for (i = 0; i < filters.length - 1; ++i)
  12832. {
  12833. filters[i].apply(this, flip, flop, true, state);
  12834. var t = flip;
  12835. flip = flop;
  12836. flop = t;
  12837. }
  12838. filters[i].apply(this, flip, lastState.renderTexture, false, state);
  12839. this.returnFilterTexture(flip);
  12840. this.returnFilterTexture(flop);
  12841. }
  12842. state.clear();
  12843. this.statePool.push(state);
  12844. };
  12845. /**
  12846. * Draws a filter.
  12847. *
  12848. * @param {PIXI.Filter} filter - The filter to draw.
  12849. * @param {PIXI.RenderTexture} input - The input render target.
  12850. * @param {PIXI.RenderTexture} output - The target to output to.
  12851. * @param {boolean} clear - Should the output be cleared before rendering to it
  12852. */
  12853. FilterSystem.prototype.applyFilter = function applyFilter (filter, input, output, clear)
  12854. {
  12855. var renderer = this.renderer;
  12856. renderer.renderTexture.bind(output, output ? output.filterFrame : null);
  12857. if (clear)
  12858. {
  12859. // gl.disable(gl.SCISSOR_TEST);
  12860. renderer.renderTexture.clear();
  12861. // gl.enable(gl.SCISSOR_TEST);
  12862. }
  12863. // set the uniforms..
  12864. filter.uniforms.uSampler = input;
  12865. filter.uniforms.filterGlobals = this.globalUniforms;
  12866. // TODO make it so that the order of this does not matter..
  12867. // because it does at the moment cos of global uniforms.
  12868. // they need to get resynced
  12869. renderer.state.setState(filter.state);
  12870. renderer.shader.bind(filter);
  12871. if (filter.legacy)
  12872. {
  12873. this.quadUv.map(input._frame, input.filterFrame);
  12874. renderer.geometry.bind(this.quadUv);
  12875. renderer.geometry.draw(DRAW_MODES.TRIANGLES);
  12876. }
  12877. else
  12878. {
  12879. renderer.geometry.bind(this.quad);
  12880. renderer.geometry.draw(DRAW_MODES.TRIANGLE_STRIP);
  12881. }
  12882. };
  12883. /**
  12884. * Multiply _input normalized coordinates_ to this matrix to get _sprite texture normalized coordinates_.
  12885. *
  12886. * Use `outputMatrix * vTextureCoord` in the shader.
  12887. *
  12888. * @param {PIXI.Matrix} outputMatrix - The matrix to output to.
  12889. * @param {PIXI.Sprite} sprite - The sprite to map to.
  12890. * @return {PIXI.Matrix} The mapped matrix.
  12891. */
  12892. FilterSystem.prototype.calculateSpriteMatrix = function calculateSpriteMatrix (outputMatrix, sprite)
  12893. {
  12894. var ref = this.activeState;
  12895. var sourceFrame = ref.sourceFrame;
  12896. var destinationFrame = ref.destinationFrame;
  12897. var ref$1 = sprite._texture;
  12898. var orig = ref$1.orig;
  12899. var mappedMatrix = outputMatrix.set(destinationFrame.width, 0, 0,
  12900. destinationFrame.height, sourceFrame.x, sourceFrame.y);
  12901. var worldTransform = sprite.worldTransform.copyTo(Matrix.TEMP_MATRIX);
  12902. worldTransform.invert();
  12903. mappedMatrix.prepend(worldTransform);
  12904. mappedMatrix.scale(1.0 / orig.width, 1.0 / orig.height);
  12905. mappedMatrix.translate(sprite.anchor.x, sprite.anchor.y);
  12906. return mappedMatrix;
  12907. };
  12908. /**
  12909. * Destroys this Filter System.
  12910. *
  12911. * @param {boolean} [contextLost=false] context was lost, do not free shaders
  12912. *
  12913. */
  12914. FilterSystem.prototype.destroy = function destroy (contextLost)
  12915. {
  12916. if ( contextLost === void 0 ) { contextLost = false; }
  12917. if (!contextLost)
  12918. {
  12919. this.emptyPool();
  12920. }
  12921. else
  12922. {
  12923. this.texturePool = {};
  12924. }
  12925. };
  12926. /**
  12927. * Gets a Power-of-Two render texture or fullScreen texture
  12928. *
  12929. * TODO move to a separate class could be on renderer?
  12930. *
  12931. * @protected
  12932. * @param {number} minWidth - The minimum width of the render texture in real pixels.
  12933. * @param {number} minHeight - The minimum height of the render texture in real pixels.
  12934. * @param {number} [resolution=1] - The resolution of the render texture.
  12935. * @return {PIXI.RenderTexture} The new render texture.
  12936. */
  12937. FilterSystem.prototype.getOptimalFilterTexture = function getOptimalFilterTexture (minWidth, minHeight, resolution)
  12938. {
  12939. if ( resolution === void 0 ) { resolution = 1; }
  12940. var key = screenKey;
  12941. minWidth *= resolution;
  12942. minHeight *= resolution;
  12943. if (minWidth !== this._pixelsWidth || minHeight !== this._pixelsHeight)
  12944. {
  12945. minWidth = nextPow2(minWidth);
  12946. minHeight = nextPow2(minHeight);
  12947. key = ((minWidth & 0xFFFF) << 16) | (minHeight & 0xFFFF);
  12948. }
  12949. if (!this.texturePool[key])
  12950. {
  12951. this.texturePool[key] = [];
  12952. }
  12953. var renderTexture = this.texturePool[key].pop();
  12954. if (!renderTexture)
  12955. {
  12956. renderTexture = RenderTexture.create({
  12957. width: minWidth,
  12958. height: minHeight,
  12959. });
  12960. }
  12961. renderTexture.filterPoolKey = key;
  12962. renderTexture.setResolution(resolution);
  12963. return renderTexture;
  12964. };
  12965. /**
  12966. * Gets extra render texture to use inside current filter
  12967. *
  12968. * @param {number} resolution resolution of the renderTexture
  12969. * @returns {PIXI.RenderTexture}
  12970. */
  12971. FilterSystem.prototype.getFilterTexture = function getFilterTexture (resolution)
  12972. {
  12973. var rt = this.activeState.renderTexture;
  12974. var filterTexture = this.getOptimalFilterTexture(rt.width, rt.height, resolution || rt.baseTexture.resolution);
  12975. filterTexture.filterFrame = rt.filterFrame;
  12976. return filterTexture;
  12977. };
  12978. /**
  12979. * Frees a render texture back into the pool.
  12980. *
  12981. * @param {PIXI.RenderTexture} renderTexture - The renderTarget to free
  12982. */
  12983. FilterSystem.prototype.returnFilterTexture = function returnFilterTexture (renderTexture)
  12984. {
  12985. var key = renderTexture.filterPoolKey;
  12986. renderTexture.filterFrame = null;
  12987. this.texturePool[key].push(renderTexture);
  12988. };
  12989. /**
  12990. * Empties the texture pool.
  12991. *
  12992. */
  12993. FilterSystem.prototype.emptyPool = function emptyPool ()
  12994. {
  12995. for (var i in this.texturePool)
  12996. {
  12997. var textures = this.texturePool[i];
  12998. if (textures)
  12999. {
  13000. for (var j = 0; j < textures.length; j++)
  13001. {
  13002. textures[j].destroy(true);
  13003. }
  13004. }
  13005. }
  13006. this.texturePool = {};
  13007. };
  13008. FilterSystem.prototype.resize = function resize ()
  13009. {
  13010. var textures = this.texturePool[screenKey];
  13011. if (textures)
  13012. {
  13013. for (var j = 0; j < textures.length; j++)
  13014. {
  13015. textures[j].destroy(true);
  13016. }
  13017. }
  13018. this.texturePool[screenKey] = [];
  13019. this._pixelsWidth = this.renderer.view.width;
  13020. this._pixelsHeight = this.renderer.view.height;
  13021. };
  13022. return FilterSystem;
  13023. }(System));
  13024. /**
  13025. * Base for a common object renderer that can be used as a system renderer plugin.
  13026. *
  13027. * @class
  13028. * @extends PIXI.System
  13029. * @memberof PIXI
  13030. */
  13031. var ObjectRenderer = /*@__PURE__*/(function (System) {
  13032. function ObjectRenderer () {
  13033. System.apply(this, arguments);
  13034. }
  13035. if ( System ) { ObjectRenderer.__proto__ = System; }
  13036. ObjectRenderer.prototype = Object.create( System && System.prototype );
  13037. ObjectRenderer.prototype.constructor = ObjectRenderer;
  13038. ObjectRenderer.prototype.start = function start ()
  13039. {
  13040. // set the shader..
  13041. };
  13042. /**
  13043. * Stops the renderer
  13044. *
  13045. */
  13046. ObjectRenderer.prototype.stop = function stop ()
  13047. {
  13048. this.flush();
  13049. };
  13050. /**
  13051. * Stub method for rendering content and emptying the current batch.
  13052. *
  13053. */
  13054. ObjectRenderer.prototype.flush = function flush ()
  13055. {
  13056. // flush!
  13057. };
  13058. /**
  13059. * Renders an object
  13060. *
  13061. * @param {PIXI.DisplayObject} object - The object to render.
  13062. */
  13063. ObjectRenderer.prototype.render = function render (object) // eslint-disable-line no-unused-vars
  13064. {
  13065. // render the object
  13066. };
  13067. return ObjectRenderer;
  13068. }(System));
  13069. /**
  13070. * System plugin to the renderer to manage batching.
  13071. *
  13072. * @class
  13073. * @extends PIXI.System
  13074. * @memberof PIXI.systems
  13075. */
  13076. var BatchSystem = /*@__PURE__*/(function (System) {
  13077. function BatchSystem(renderer)
  13078. {
  13079. System.call(this, renderer);
  13080. /**
  13081. * An empty renderer.
  13082. *
  13083. * @member {PIXI.ObjectRenderer}
  13084. */
  13085. this.emptyRenderer = new ObjectRenderer(renderer);
  13086. /**
  13087. * The currently active ObjectRenderer.
  13088. *
  13089. * @member {PIXI.ObjectRenderer}
  13090. */
  13091. this.currentRenderer = this.emptyRenderer;
  13092. }
  13093. if ( System ) { BatchSystem.__proto__ = System; }
  13094. BatchSystem.prototype = Object.create( System && System.prototype );
  13095. BatchSystem.prototype.constructor = BatchSystem;
  13096. /**
  13097. * Changes the current renderer to the one given in parameter
  13098. *
  13099. * @param {PIXI.ObjectRenderer} objectRenderer - The object renderer to use.
  13100. */
  13101. BatchSystem.prototype.setObjectRenderer = function setObjectRenderer (objectRenderer)
  13102. {
  13103. if (this.currentRenderer === objectRenderer)
  13104. {
  13105. return;
  13106. }
  13107. this.currentRenderer.stop();
  13108. this.currentRenderer = objectRenderer;
  13109. this.currentRenderer.start();
  13110. };
  13111. /**
  13112. * This should be called if you wish to do some custom rendering
  13113. * It will basically render anything that may be batched up such as sprites
  13114. */
  13115. BatchSystem.prototype.flush = function flush ()
  13116. {
  13117. this.setObjectRenderer(this.emptyRenderer);
  13118. };
  13119. /**
  13120. * Reset the system to an empty renderer
  13121. */
  13122. BatchSystem.prototype.reset = function reset ()
  13123. {
  13124. this.setObjectRenderer(this.emptyRenderer);
  13125. };
  13126. return BatchSystem;
  13127. }(System));
  13128. /**
  13129. * The maximum support for using WebGL. If a device does not
  13130. * support WebGL version, for instance WebGL 2, it will still
  13131. * attempt to fallback support to WebGL 1. If you want to
  13132. * explicitly remove feature support to target a more stable
  13133. * baseline, prefer a lower environment.
  13134. *
  13135. * Due to {@link https://bugs.chromium.org/p/chromium/issues/detail?id=934823|bug in chromium}
  13136. * we disable webgl2 by default for all non-apple mobile devices.
  13137. *
  13138. * @static
  13139. * @name PREFER_ENV
  13140. * @memberof PIXI.settings
  13141. * @type {number}
  13142. * @default PIXI.ENV.WEBGL2
  13143. */
  13144. settings.PREFER_ENV = isMobile_min.any ? ENV.WEBGL : ENV.WEBGL2;
  13145. var CONTEXT_UID = 0;
  13146. /**
  13147. * System plugin to the renderer to manage the context.
  13148. *
  13149. * @class
  13150. * @extends PIXI.System
  13151. * @memberof PIXI.systems
  13152. */
  13153. var ContextSystem = /*@__PURE__*/(function (System) {
  13154. function ContextSystem(renderer)
  13155. {
  13156. System.call(this, renderer);
  13157. /**
  13158. * Either 1 or 2 to reflect the WebGL version being used
  13159. * @member {number}
  13160. * @readonly
  13161. */
  13162. this.webGLVersion = 1;
  13163. /**
  13164. * Extensions being used
  13165. * @member {object}
  13166. * @readonly
  13167. * @property {WEBGL_draw_buffers} drawBuffers - WebGL v1 extension
  13168. * @property {WEBGL_depth_texture} depthTexture - WebGL v1 extension
  13169. * @property {OES_texture_float} floatTexture - WebGL v1 extension
  13170. * @property {WEBGL_lose_context} loseContext - WebGL v1 extension
  13171. * @property {OES_vertex_array_object} vertexArrayObject - WebGL v1 extension
  13172. */
  13173. this.extensions = {};
  13174. // Bind functions
  13175. this.handleContextLost = this.handleContextLost.bind(this);
  13176. this.handleContextRestored = this.handleContextRestored.bind(this);
  13177. renderer.view.addEventListener('webglcontextlost', this.handleContextLost, false);
  13178. renderer.view.addEventListener('webglcontextrestored', this.handleContextRestored, false);
  13179. }
  13180. if ( System ) { ContextSystem.__proto__ = System; }
  13181. ContextSystem.prototype = Object.create( System && System.prototype );
  13182. ContextSystem.prototype.constructor = ContextSystem;
  13183. var prototypeAccessors = { isLost: { configurable: true } };
  13184. /**
  13185. * `true` if the context is lost
  13186. * @member {boolean}
  13187. * @readonly
  13188. */
  13189. prototypeAccessors.isLost.get = function ()
  13190. {
  13191. return (!this.gl || this.gl.isContextLost());
  13192. };
  13193. /**
  13194. * Handle the context change event
  13195. * @param {WebGLRenderingContext} gl new webgl context
  13196. */
  13197. ContextSystem.prototype.contextChange = function contextChange (gl)
  13198. {
  13199. this.gl = gl;
  13200. // restore a context if it was previously lost
  13201. if (gl.isContextLost() && gl.getExtension('WEBGL_lose_context'))
  13202. {
  13203. gl.getExtension('WEBGL_lose_context').restoreContext();
  13204. }
  13205. };
  13206. /**
  13207. * Initialize the context
  13208. *
  13209. * @protected
  13210. * @param {WebGLRenderingContext} gl - WebGL context
  13211. */
  13212. ContextSystem.prototype.initFromContext = function initFromContext (gl)
  13213. {
  13214. this.gl = gl;
  13215. this.validateContext(gl);
  13216. this.renderer.gl = gl;
  13217. this.renderer.CONTEXT_UID = CONTEXT_UID++;
  13218. this.renderer.runners.contextChange.run(gl);
  13219. };
  13220. /**
  13221. * Initialize from context options
  13222. *
  13223. * @protected
  13224. * @see https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/getContext
  13225. * @param {object} options - context attributes
  13226. */
  13227. ContextSystem.prototype.initFromOptions = function initFromOptions (options)
  13228. {
  13229. var gl = this.createContext(this.renderer.view, options);
  13230. this.initFromContext(gl);
  13231. };
  13232. /**
  13233. * Helper class to create a WebGL Context
  13234. *
  13235. * @param canvas {HTMLCanvasElement} the canvas element that we will get the context from
  13236. * @param options {object} An options object that gets passed in to the canvas element containing the context attributes
  13237. * @see https://developer.mozilla.org/en/docs/Web/API/HTMLCanvasElement/getContext
  13238. * @return {WebGLRenderingContext} the WebGL context
  13239. */
  13240. ContextSystem.prototype.createContext = function createContext (canvas, options)
  13241. {
  13242. var gl;
  13243. if (settings.PREFER_ENV >= ENV.WEBGL2)
  13244. {
  13245. gl = canvas.getContext('webgl2', options);
  13246. }
  13247. if (gl)
  13248. {
  13249. this.webGLVersion = 2;
  13250. }
  13251. else
  13252. {
  13253. this.webGLVersion = 1;
  13254. gl = canvas.getContext('webgl', options)
  13255. || canvas.getContext('experimental-webgl', options);
  13256. if (!gl)
  13257. {
  13258. // fail, not able to get a context
  13259. throw new Error('This browser does not support WebGL. Try using the canvas renderer');
  13260. }
  13261. }
  13262. this.gl = gl;
  13263. this.getExtensions();
  13264. return gl;
  13265. };
  13266. /**
  13267. * Auto-populate the extensions
  13268. *
  13269. * @protected
  13270. */
  13271. ContextSystem.prototype.getExtensions = function getExtensions ()
  13272. {
  13273. // time to set up default extensions that Pixi uses.
  13274. var ref = this;
  13275. var gl = ref.gl;
  13276. if (this.webGLVersion === 1)
  13277. {
  13278. Object.assign(this.extensions, {
  13279. drawBuffers: gl.getExtension('WEBGL_draw_buffers'),
  13280. depthTexture: gl.getExtension('WEBKIT_WEBGL_depth_texture'),
  13281. floatTexture: gl.getExtension('OES_texture_float'),
  13282. loseContext: gl.getExtension('WEBGL_lose_context'),
  13283. vertexArrayObject: gl.getExtension('OES_vertex_array_object')
  13284. || gl.getExtension('MOZ_OES_vertex_array_object')
  13285. || gl.getExtension('WEBKIT_OES_vertex_array_object'),
  13286. uint32ElementIndex: gl.getExtension('OES_element_index_uint'),
  13287. });
  13288. }
  13289. // we don't use any specific WebGL 2 ones yet!
  13290. };
  13291. /**
  13292. * Handles a lost webgl context
  13293. *
  13294. * @protected
  13295. * @param {WebGLContextEvent} event - The context lost event.
  13296. */
  13297. ContextSystem.prototype.handleContextLost = function handleContextLost (event)
  13298. {
  13299. event.preventDefault();
  13300. };
  13301. /**
  13302. * Handles a restored webgl context
  13303. *
  13304. * @protected
  13305. */
  13306. ContextSystem.prototype.handleContextRestored = function handleContextRestored ()
  13307. {
  13308. this.renderer.runners.contextChange.run(this.gl);
  13309. };
  13310. ContextSystem.prototype.destroy = function destroy ()
  13311. {
  13312. var view = this.renderer.view;
  13313. // remove listeners
  13314. view.removeEventListener('webglcontextlost', this.handleContextLost);
  13315. view.removeEventListener('webglcontextrestored', this.handleContextRestored);
  13316. this.gl.useProgram(null);
  13317. if (this.extensions.loseContext)
  13318. {
  13319. this.extensions.loseContext.loseContext();
  13320. }
  13321. };
  13322. /**
  13323. * Handle the post-render runner event
  13324. *
  13325. * @protected
  13326. */
  13327. ContextSystem.prototype.postrender = function postrender ()
  13328. {
  13329. this.gl.flush();
  13330. };
  13331. /**
  13332. * Validate context
  13333. *
  13334. * @protected
  13335. * @param {WebGLRenderingContext} gl - Render context
  13336. */
  13337. ContextSystem.prototype.validateContext = function validateContext (gl)
  13338. {
  13339. var attributes = gl.getContextAttributes();
  13340. // this is going to be fairly simple for now.. but at least we have room to grow!
  13341. if (!attributes.stencil)
  13342. {
  13343. /* eslint-disable max-len */
  13344. /* eslint-disable no-console */
  13345. console.warn('Provided WebGL context does not have a stencil buffer, masks may not render correctly');
  13346. /* eslint-enable no-console */
  13347. /* eslint-enable max-len */
  13348. }
  13349. };
  13350. Object.defineProperties( ContextSystem.prototype, prototypeAccessors );
  13351. return ContextSystem;
  13352. }(System));
  13353. /**
  13354. * System plugin to the renderer to manage framebuffers.
  13355. *
  13356. * @class
  13357. * @extends PIXI.System
  13358. * @memberof PIXI.systems
  13359. */
  13360. var FramebufferSystem = /*@__PURE__*/(function (System) {
  13361. function FramebufferSystem(renderer)
  13362. {
  13363. System.call(this, renderer);
  13364. /**
  13365. * A list of managed framebuffers
  13366. * @member {PIXI.Framebuffer[]}
  13367. * @readonly
  13368. */
  13369. this.managedFramebuffers = [];
  13370. /**
  13371. * Framebuffer value that shows that we don't know what is bound
  13372. * @member {Framebuffer}
  13373. * @readonly
  13374. */
  13375. this.unknownFramebuffer = new Framebuffer(10, 10);
  13376. }
  13377. if ( System ) { FramebufferSystem.__proto__ = System; }
  13378. FramebufferSystem.prototype = Object.create( System && System.prototype );
  13379. FramebufferSystem.prototype.constructor = FramebufferSystem;
  13380. var prototypeAccessors = { size: { configurable: true } };
  13381. /**
  13382. * Sets up the renderer context and necessary buffers.
  13383. */
  13384. FramebufferSystem.prototype.contextChange = function contextChange ()
  13385. {
  13386. var gl = this.gl = this.renderer.gl;
  13387. this.CONTEXT_UID = this.renderer.CONTEXT_UID;
  13388. this.current = this.unknownFramebuffer;
  13389. this.viewport = new Rectangle();
  13390. this.hasMRT = true;
  13391. this.writeDepthTexture = true;
  13392. this.disposeAll(true);
  13393. // webgl2
  13394. if (this.renderer.context.webGLVersion === 1)
  13395. {
  13396. // webgl 1!
  13397. var nativeDrawBuffersExtension = this.renderer.context.extensions.drawBuffers;
  13398. var nativeDepthTextureExtension = this.renderer.context.extensions.depthTexture;
  13399. if (settings.PREFER_ENV === ENV.WEBGL_LEGACY)
  13400. {
  13401. nativeDrawBuffersExtension = null;
  13402. nativeDepthTextureExtension = null;
  13403. }
  13404. if (nativeDrawBuffersExtension)
  13405. {
  13406. gl.drawBuffers = function (activeTextures) { return nativeDrawBuffersExtension.drawBuffersWEBGL(activeTextures); };
  13407. }
  13408. else
  13409. {
  13410. this.hasMRT = false;
  13411. gl.drawBuffers = function () {
  13412. // empty
  13413. };
  13414. }
  13415. if (!nativeDepthTextureExtension)
  13416. {
  13417. this.writeDepthTexture = false;
  13418. }
  13419. }
  13420. };
  13421. /**
  13422. * Bind a framebuffer
  13423. *
  13424. * @param {PIXI.Framebuffer} framebuffer
  13425. * @param {PIXI.Rectangle} [frame] frame, default is framebuffer size
  13426. */
  13427. FramebufferSystem.prototype.bind = function bind (framebuffer, frame)
  13428. {
  13429. var ref = this;
  13430. var gl = ref.gl;
  13431. if (framebuffer)
  13432. {
  13433. // TODO caching layer!
  13434. var fbo = framebuffer.glFramebuffers[this.CONTEXT_UID] || this.initFramebuffer(framebuffer);
  13435. if (this.current !== framebuffer)
  13436. {
  13437. this.current = framebuffer;
  13438. gl.bindFramebuffer(gl.FRAMEBUFFER, fbo.framebuffer);
  13439. }
  13440. // make sure all textures are unbound..
  13441. // now check for updates...
  13442. if (fbo.dirtyId !== framebuffer.dirtyId)
  13443. {
  13444. fbo.dirtyId = framebuffer.dirtyId;
  13445. if (fbo.dirtyFormat !== framebuffer.dirtyFormat)
  13446. {
  13447. fbo.dirtyFormat = framebuffer.dirtyFormat;
  13448. this.updateFramebuffer(framebuffer);
  13449. }
  13450. else if (fbo.dirtySize !== framebuffer.dirtySize)
  13451. {
  13452. fbo.dirtySize = framebuffer.dirtySize;
  13453. this.resizeFramebuffer(framebuffer);
  13454. }
  13455. }
  13456. for (var i = 0; i < framebuffer.colorTextures.length; i++)
  13457. {
  13458. if (framebuffer.colorTextures[i].texturePart)
  13459. {
  13460. this.renderer.texture.unbind(framebuffer.colorTextures[i].texture);
  13461. }
  13462. else
  13463. {
  13464. this.renderer.texture.unbind(framebuffer.colorTextures[i]);
  13465. }
  13466. }
  13467. if (framebuffer.depthTexture)
  13468. {
  13469. this.renderer.texture.unbind(framebuffer.depthTexture);
  13470. }
  13471. if (frame)
  13472. {
  13473. this.setViewport(frame.x, frame.y, frame.width, frame.height);
  13474. }
  13475. else
  13476. {
  13477. this.setViewport(0, 0, framebuffer.width, framebuffer.height);
  13478. }
  13479. }
  13480. else
  13481. {
  13482. if (this.current)
  13483. {
  13484. this.current = null;
  13485. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  13486. }
  13487. if (frame)
  13488. {
  13489. this.setViewport(frame.x, frame.y, frame.width, frame.height);
  13490. }
  13491. else
  13492. {
  13493. this.setViewport(0, 0, this.renderer.width, this.renderer.height);
  13494. }
  13495. }
  13496. };
  13497. /**
  13498. * Set the WebGLRenderingContext's viewport.
  13499. *
  13500. * @param {Number} x - X position of viewport
  13501. * @param {Number} y - Y position of viewport
  13502. * @param {Number} width - Width of viewport
  13503. * @param {Number} height - Height of viewport
  13504. */
  13505. FramebufferSystem.prototype.setViewport = function setViewport (x, y, width, height)
  13506. {
  13507. var v = this.viewport;
  13508. if (v.width !== width || v.height !== height || v.x !== x || v.y !== y)
  13509. {
  13510. v.x = x;
  13511. v.y = y;
  13512. v.width = width;
  13513. v.height = height;
  13514. this.gl.viewport(x, y, width, height);
  13515. }
  13516. };
  13517. /**
  13518. * Get the size of the current width and height. Returns object with `width` and `height` values.
  13519. *
  13520. * @member {object}
  13521. * @readonly
  13522. */
  13523. prototypeAccessors.size.get = function ()
  13524. {
  13525. if (this.current)
  13526. {
  13527. // TODO store temp
  13528. return { x: 0, y: 0, width: this.current.width, height: this.current.height };
  13529. }
  13530. return { x: 0, y: 0, width: this.renderer.width, height: this.renderer.height };
  13531. };
  13532. /**
  13533. * Clear the color of the context
  13534. *
  13535. * @param {Number} r - Red value from 0 to 1
  13536. * @param {Number} g - Green value from 0 to 1
  13537. * @param {Number} b - Blue value from 0 to 1
  13538. * @param {Number} a - Alpha value from 0 to 1
  13539. */
  13540. FramebufferSystem.prototype.clear = function clear (r, g, b, a)
  13541. {
  13542. var ref = this;
  13543. var gl = ref.gl;
  13544. // TODO clear color can be set only one right?
  13545. gl.clearColor(r, g, b, a);
  13546. gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
  13547. };
  13548. /**
  13549. * Initialize framebuffer
  13550. *
  13551. * @protected
  13552. * @param {PIXI.Framebuffer} framebuffer
  13553. */
  13554. FramebufferSystem.prototype.initFramebuffer = function initFramebuffer (framebuffer)
  13555. {
  13556. var ref = this;
  13557. var gl = ref.gl;
  13558. // TODO - make this a class?
  13559. var fbo = {
  13560. framebuffer: gl.createFramebuffer(),
  13561. stencil: null,
  13562. dirtyId: 0,
  13563. dirtyFormat: 0,
  13564. dirtySize: 0,
  13565. };
  13566. framebuffer.glFramebuffers[this.CONTEXT_UID] = fbo;
  13567. this.managedFramebuffers.push(framebuffer);
  13568. framebuffer.disposeRunner.add(this);
  13569. return fbo;
  13570. };
  13571. /**
  13572. * Resize the framebuffer
  13573. *
  13574. * @protected
  13575. * @param {PIXI.Framebuffer} framebuffer
  13576. */
  13577. FramebufferSystem.prototype.resizeFramebuffer = function resizeFramebuffer (framebuffer)
  13578. {
  13579. var ref = this;
  13580. var gl = ref.gl;
  13581. var fbo = framebuffer.glFramebuffers[this.CONTEXT_UID];
  13582. if (fbo.stencil)
  13583. {
  13584. gl.bindRenderbuffer(gl.RENDERBUFFER, fbo.stencil);
  13585. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width, framebuffer.height);
  13586. }
  13587. var colorTextures = framebuffer.colorTextures;
  13588. for (var i = 0; i < colorTextures.length; i++)
  13589. {
  13590. this.renderer.texture.bind(colorTextures[i], 0);
  13591. }
  13592. if (framebuffer.depthTexture)
  13593. {
  13594. this.renderer.texture.bind(framebuffer.depthTexture, 0);
  13595. }
  13596. };
  13597. /**
  13598. * Update the framebuffer
  13599. *
  13600. * @protected
  13601. * @param {PIXI.Framebuffer} framebuffer
  13602. */
  13603. FramebufferSystem.prototype.updateFramebuffer = function updateFramebuffer (framebuffer)
  13604. {
  13605. var ref = this;
  13606. var gl = ref.gl;
  13607. var fbo = framebuffer.glFramebuffers[this.CONTEXT_UID];
  13608. // bind the color texture
  13609. var colorTextures = framebuffer.colorTextures;
  13610. var count = colorTextures.length;
  13611. if (!gl.drawBuffers)
  13612. {
  13613. count = Math.min(count, 1);
  13614. }
  13615. var activeTextures = [];
  13616. for (var i = 0; i < count; i++)
  13617. {
  13618. var texture = framebuffer.colorTextures[i];
  13619. if (texture.texturePart)
  13620. {
  13621. this.renderer.texture.bind(texture.texture, 0);
  13622. gl.framebufferTexture2D(gl.FRAMEBUFFER,
  13623. gl.COLOR_ATTACHMENT0 + i,
  13624. gl.TEXTURE_CUBE_MAP_NEGATIVE_X + texture.side,
  13625. texture.texture._glTextures[this.CONTEXT_UID].texture,
  13626. 0);
  13627. }
  13628. else
  13629. {
  13630. this.renderer.texture.bind(texture, 0);
  13631. gl.framebufferTexture2D(gl.FRAMEBUFFER,
  13632. gl.COLOR_ATTACHMENT0 + i,
  13633. gl.TEXTURE_2D,
  13634. texture._glTextures[this.CONTEXT_UID].texture,
  13635. 0);
  13636. }
  13637. activeTextures.push(gl.COLOR_ATTACHMENT0 + i);
  13638. }
  13639. if (activeTextures.length > 1)
  13640. {
  13641. gl.drawBuffers(activeTextures);
  13642. }
  13643. if (framebuffer.depthTexture)
  13644. {
  13645. var writeDepthTexture = this.writeDepthTexture;
  13646. if (writeDepthTexture)
  13647. {
  13648. var depthTexture = framebuffer.depthTexture;
  13649. this.renderer.texture.bind(depthTexture, 0);
  13650. gl.framebufferTexture2D(gl.FRAMEBUFFER,
  13651. gl.DEPTH_ATTACHMENT,
  13652. gl.TEXTURE_2D,
  13653. depthTexture._glTextures[this.CONTEXT_UID].texture,
  13654. 0);
  13655. }
  13656. }
  13657. if (!fbo.stencil && (framebuffer.stencil || framebuffer.depth))
  13658. {
  13659. fbo.stencil = gl.createRenderbuffer();
  13660. gl.bindRenderbuffer(gl.RENDERBUFFER, fbo.stencil);
  13661. // TODO.. this is depth AND stencil?
  13662. if (!framebuffer.depthTexture)
  13663. { // you can't have both, so one should take priority if enabled
  13664. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, fbo.stencil);
  13665. }
  13666. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, framebuffer.width, framebuffer.height);
  13667. // fbo.enableStencil();
  13668. }
  13669. };
  13670. /**
  13671. * Disposes framebuffer
  13672. * @param {PIXI.Framebuffer} framebuffer framebuffer that has to be disposed of
  13673. * @param {boolean} [contextLost=false] If context was lost, we suppress all delete function calls
  13674. */
  13675. FramebufferSystem.prototype.disposeFramebuffer = function disposeFramebuffer (framebuffer, contextLost)
  13676. {
  13677. var fbo = framebuffer.glFramebuffers[this.CONTEXT_UID];
  13678. var gl = this.gl;
  13679. if (!fbo)
  13680. {
  13681. return;
  13682. }
  13683. delete framebuffer.glFramebuffers[this.CONTEXT_UID];
  13684. var index = this.managedFramebuffers.indexOf(framebuffer);
  13685. if (index >= 0)
  13686. {
  13687. this.managedFramebuffers.splice(index, 1);
  13688. }
  13689. framebuffer.disposeRunner.remove(this);
  13690. if (!contextLost)
  13691. {
  13692. gl.deleteFramebuffer(fbo.framebuffer);
  13693. if (fbo.stencil)
  13694. {
  13695. gl.deleteRenderbuffer(fbo.stencil);
  13696. }
  13697. }
  13698. };
  13699. /**
  13700. * Disposes all framebuffers, but not textures bound to them
  13701. * @param {boolean} [contextLost=false] If context was lost, we suppress all delete function calls
  13702. */
  13703. FramebufferSystem.prototype.disposeAll = function disposeAll (contextLost)
  13704. {
  13705. var list = this.managedFramebuffers;
  13706. this.managedFramebuffers = [];
  13707. for (var i = 0; i < list.count; i++)
  13708. {
  13709. this.disposeFramebuffer(list[i], contextLost);
  13710. }
  13711. };
  13712. /**
  13713. * resets framebuffer stored state, binds screen framebuffer
  13714. *
  13715. * should be called before renderTexture reset()
  13716. */
  13717. FramebufferSystem.prototype.reset = function reset ()
  13718. {
  13719. this.current = this.unknownFramebuffer;
  13720. this.viewport = new Rectangle();
  13721. };
  13722. Object.defineProperties( FramebufferSystem.prototype, prototypeAccessors );
  13723. return FramebufferSystem;
  13724. }(System));
  13725. var GLBuffer = function GLBuffer(buffer)
  13726. {
  13727. this.buffer = buffer;
  13728. this.updateID = -1;
  13729. this.byteLength = -1;
  13730. this.refCount = 0;
  13731. };
  13732. var byteSizeMap$1 = { 5126: 4, 5123: 2, 5121: 1 };
  13733. /**
  13734. * System plugin to the renderer to manage geometry.
  13735. *
  13736. * @class
  13737. * @extends PIXI.System
  13738. * @memberof PIXI.systems
  13739. */
  13740. var GeometrySystem = /*@__PURE__*/(function (System) {
  13741. function GeometrySystem(renderer)
  13742. {
  13743. System.call(this, renderer);
  13744. this._activeGeometry = null;
  13745. this._activeVao = null;
  13746. /**
  13747. * `true` if we has `*_vertex_array_object` extension
  13748. * @member {boolean}
  13749. * @readonly
  13750. */
  13751. this.hasVao = true;
  13752. /**
  13753. * `true` if has `ANGLE_instanced_arrays` extension
  13754. * @member {boolean}
  13755. * @readonly
  13756. */
  13757. this.hasInstance = true;
  13758. /**
  13759. * `true` if support `gl.UNSIGNED_INT` in `gl.drawElements` or `gl.drawElementsInstanced`
  13760. * @member {boolean}
  13761. * @readonly
  13762. */
  13763. this.canUseUInt32ElementIndex = false;
  13764. /**
  13765. * A cache of currently bound buffer,
  13766. * contains only two members with keys ARRAY_BUFFER and ELEMENT_ARRAY_BUFFER
  13767. * @member {Object.<number, PIXI.Buffer>}
  13768. * @readonly
  13769. */
  13770. this.boundBuffers = {};
  13771. /**
  13772. * Cache for all geometries by id, used in case renderer gets destroyed or for profiling
  13773. * @member {object}
  13774. * @readonly
  13775. */
  13776. this.managedGeometries = {};
  13777. /**
  13778. * Cache for all buffers by id, used in case renderer gets destroyed or for profiling
  13779. * @member {object}
  13780. * @readonly
  13781. */
  13782. this.managedBuffers = {};
  13783. }
  13784. if ( System ) { GeometrySystem.__proto__ = System; }
  13785. GeometrySystem.prototype = Object.create( System && System.prototype );
  13786. GeometrySystem.prototype.constructor = GeometrySystem;
  13787. /**
  13788. * Sets up the renderer context and necessary buffers.
  13789. */
  13790. GeometrySystem.prototype.contextChange = function contextChange ()
  13791. {
  13792. this.disposeAll(true);
  13793. var gl = this.gl = this.renderer.gl;
  13794. var context = this.renderer.context;
  13795. this.CONTEXT_UID = this.renderer.CONTEXT_UID;
  13796. // webgl2
  13797. if (!gl.createVertexArray)
  13798. {
  13799. // webgl 1!
  13800. var nativeVaoExtension = this.renderer.context.extensions.vertexArrayObject;
  13801. if (settings.PREFER_ENV === ENV.WEBGL_LEGACY)
  13802. {
  13803. nativeVaoExtension = null;
  13804. }
  13805. if (nativeVaoExtension)
  13806. {
  13807. gl.createVertexArray = function () { return nativeVaoExtension.createVertexArrayOES(); };
  13808. gl.bindVertexArray = function (vao) { return nativeVaoExtension.bindVertexArrayOES(vao); };
  13809. gl.deleteVertexArray = function (vao) { return nativeVaoExtension.deleteVertexArrayOES(vao); };
  13810. }
  13811. else
  13812. {
  13813. this.hasVao = false;
  13814. gl.createVertexArray = function () {
  13815. // empty
  13816. };
  13817. gl.bindVertexArray = function () {
  13818. // empty
  13819. };
  13820. gl.deleteVertexArray = function () {
  13821. // empty
  13822. };
  13823. }
  13824. }
  13825. if (!gl.vertexAttribDivisor)
  13826. {
  13827. var instanceExt = gl.getExtension('ANGLE_instanced_arrays');
  13828. if (instanceExt)
  13829. {
  13830. gl.vertexAttribDivisor = function (a, b) { return instanceExt.vertexAttribDivisorANGLE(a, b); };
  13831. gl.drawElementsInstanced = function (a, b, c, d, e) { return instanceExt.drawElementsInstancedANGLE(a, b, c, d, e); };
  13832. gl.drawArraysInstanced = function (a, b, c, d) { return instanceExt.drawArraysInstancedANGLE(a, b, c, d); };
  13833. }
  13834. else
  13835. {
  13836. this.hasInstance = false;
  13837. }
  13838. }
  13839. this.canUseUInt32ElementIndex = context.webGLVersion === 2 || !!context.extensions.uint32ElementIndex;
  13840. };
  13841. /**
  13842. * Binds geometry so that is can be drawn. Creating a Vao if required
  13843. * @protected
  13844. * @param {PIXI.Geometry} geometry instance of geometry to bind
  13845. * @param {PIXI.Shader} shader instance of shader to bind
  13846. */
  13847. GeometrySystem.prototype.bind = function bind (geometry, shader)
  13848. {
  13849. shader = shader || this.renderer.shader.shader;
  13850. var ref = this;
  13851. var gl = ref.gl;
  13852. // not sure the best way to address this..
  13853. // currently different shaders require different VAOs for the same geometry
  13854. // Still mulling over the best way to solve this one..
  13855. // will likely need to modify the shader attribute locations at run time!
  13856. var vaos = geometry.glVertexArrayObjects[this.CONTEXT_UID];
  13857. if (!vaos)
  13858. {
  13859. this.managedGeometries[geometry.id] = geometry;
  13860. geometry.disposeRunner.add(this);
  13861. geometry.glVertexArrayObjects[this.CONTEXT_UID] = vaos = {};
  13862. }
  13863. var vao = vaos[shader.program.id] || this.initGeometryVao(geometry, shader.program);
  13864. this._activeGeometry = geometry;
  13865. if (this._activeVao !== vao)
  13866. {
  13867. this._activeVao = vao;
  13868. if (this.hasVao)
  13869. {
  13870. gl.bindVertexArray(vao);
  13871. }
  13872. else
  13873. {
  13874. this.activateVao(geometry, shader.program);
  13875. }
  13876. }
  13877. // TODO - optimise later!
  13878. // don't need to loop through if nothing changed!
  13879. // maybe look to add an 'autoupdate' to geometry?
  13880. this.updateBuffers();
  13881. };
  13882. /**
  13883. * Reset and unbind any active VAO and geometry
  13884. */
  13885. GeometrySystem.prototype.reset = function reset ()
  13886. {
  13887. this.unbind();
  13888. };
  13889. /**
  13890. * Update buffers
  13891. * @protected
  13892. */
  13893. GeometrySystem.prototype.updateBuffers = function updateBuffers ()
  13894. {
  13895. var geometry = this._activeGeometry;
  13896. var ref = this;
  13897. var gl = ref.gl;
  13898. for (var i = 0; i < geometry.buffers.length; i++)
  13899. {
  13900. var buffer = geometry.buffers[i];
  13901. var glBuffer = buffer._glBuffers[this.CONTEXT_UID];
  13902. if (buffer._updateID !== glBuffer.updateID)
  13903. {
  13904. glBuffer.updateID = buffer._updateID;
  13905. // TODO can cache this on buffer! maybe added a getter / setter?
  13906. var type = buffer.index ? gl.ELEMENT_ARRAY_BUFFER : gl.ARRAY_BUFFER;
  13907. // TODO this could change if the VAO changes...
  13908. // need to come up with a better way to cache..
  13909. // if (this.boundBuffers[type] !== glBuffer)
  13910. // {
  13911. // this.boundBuffers[type] = glBuffer;
  13912. gl.bindBuffer(type, glBuffer.buffer);
  13913. // }
  13914. this._boundBuffer = glBuffer;
  13915. if (glBuffer.byteLength >= buffer.data.byteLength)
  13916. {
  13917. // offset is always zero for now!
  13918. gl.bufferSubData(type, 0, buffer.data);
  13919. }
  13920. else
  13921. {
  13922. var drawType = buffer.static ? gl.STATIC_DRAW : gl.DYNAMIC_DRAW;
  13923. glBuffer.byteLength = buffer.data.byteLength;
  13924. gl.bufferData(type, buffer.data, drawType);
  13925. }
  13926. }
  13927. }
  13928. };
  13929. /**
  13930. * Check compability between a geometry and a program
  13931. * @protected
  13932. * @param {PIXI.Geometry} geometry - Geometry instance
  13933. * @param {PIXI.Program} program - Program instance
  13934. */
  13935. GeometrySystem.prototype.checkCompatibility = function checkCompatibility (geometry, program)
  13936. {
  13937. // geometry must have at least all the attributes that the shader requires.
  13938. var geometryAttributes = geometry.attributes;
  13939. var shaderAttributes = program.attributeData;
  13940. for (var j in shaderAttributes)
  13941. {
  13942. if (!geometryAttributes[j])
  13943. {
  13944. throw new Error(("shader and geometry incompatible, geometry missing the \"" + j + "\" attribute"));
  13945. }
  13946. }
  13947. };
  13948. /**
  13949. * Takes a geometry and program and generates a unique signature for them.
  13950. *
  13951. * @param {PIXI.Geometry} geometry to get signature from
  13952. * @param {PIXI.Program} program to test geometry against
  13953. * @returns {String} Unique signature of the geometry and program
  13954. * @protected
  13955. */
  13956. GeometrySystem.prototype.getSignature = function getSignature (geometry, program)
  13957. {
  13958. var attribs = geometry.attributes;
  13959. var shaderAttributes = program.attributeData;
  13960. var strings = ['g', geometry.id];
  13961. for (var i in attribs)
  13962. {
  13963. if (shaderAttributes[i])
  13964. {
  13965. strings.push(i);
  13966. }
  13967. }
  13968. return strings.join('-');
  13969. };
  13970. /**
  13971. * Creates or gets Vao with the same structure as the geometry and stores it on the geometry.
  13972. * If vao is created, it is bound automatically.
  13973. *
  13974. * @protected
  13975. * @param {PIXI.Geometry} geometry - Instance of geometry to to generate Vao for
  13976. * @param {PIXI.Program} program - Instance of program
  13977. */
  13978. GeometrySystem.prototype.initGeometryVao = function initGeometryVao (geometry, program)
  13979. {
  13980. this.checkCompatibility(geometry, program);
  13981. var gl = this.gl;
  13982. var CONTEXT_UID = this.CONTEXT_UID;
  13983. var signature = this.getSignature(geometry, program);
  13984. var vaoObjectHash = geometry.glVertexArrayObjects[this.CONTEXT_UID];
  13985. var vao = vaoObjectHash[signature];
  13986. if (vao)
  13987. {
  13988. // this will give us easy access to the vao
  13989. vaoObjectHash[program.id] = vao;
  13990. return vao;
  13991. }
  13992. var buffers = geometry.buffers;
  13993. var attributes = geometry.attributes;
  13994. var tempStride = {};
  13995. var tempStart = {};
  13996. for (var j in buffers)
  13997. {
  13998. tempStride[j] = 0;
  13999. tempStart[j] = 0;
  14000. }
  14001. for (var j$1 in attributes)
  14002. {
  14003. if (!attributes[j$1].size && program.attributeData[j$1])
  14004. {
  14005. attributes[j$1].size = program.attributeData[j$1].size;
  14006. }
  14007. else if (!attributes[j$1].size)
  14008. {
  14009. console.warn(("PIXI Geometry attribute '" + j$1 + "' size cannot be determined (likely the bound shader does not have the attribute)")); // eslint-disable-line
  14010. }
  14011. tempStride[attributes[j$1].buffer] += attributes[j$1].size * byteSizeMap$1[attributes[j$1].type];
  14012. }
  14013. for (var j$2 in attributes)
  14014. {
  14015. var attribute = attributes[j$2];
  14016. var attribSize = attribute.size;
  14017. if (attribute.stride === undefined)
  14018. {
  14019. if (tempStride[attribute.buffer] === attribSize * byteSizeMap$1[attribute.type])
  14020. {
  14021. attribute.stride = 0;
  14022. }
  14023. else
  14024. {
  14025. attribute.stride = tempStride[attribute.buffer];
  14026. }
  14027. }
  14028. if (attribute.start === undefined)
  14029. {
  14030. attribute.start = tempStart[attribute.buffer];
  14031. tempStart[attribute.buffer] += attribSize * byteSizeMap$1[attribute.type];
  14032. }
  14033. }
  14034. vao = gl.createVertexArray();
  14035. gl.bindVertexArray(vao);
  14036. // first update - and create the buffers!
  14037. // only create a gl buffer if it actually gets
  14038. for (var i = 0; i < buffers.length; i++)
  14039. {
  14040. var buffer = buffers[i];
  14041. if (!buffer._glBuffers[CONTEXT_UID])
  14042. {
  14043. buffer._glBuffers[CONTEXT_UID] = new GLBuffer(gl.createBuffer());
  14044. this.managedBuffers[buffer.id] = buffer;
  14045. buffer.disposeRunner.add(this);
  14046. }
  14047. buffer._glBuffers[CONTEXT_UID].refCount++;
  14048. }
  14049. // TODO - maybe make this a data object?
  14050. // lets wait to see if we need to first!
  14051. this.activateVao(geometry, program);
  14052. this._activeVao = vao;
  14053. // add it to the cache!
  14054. vaoObjectHash[program.id] = vao;
  14055. vaoObjectHash[signature] = vao;
  14056. return vao;
  14057. };
  14058. /**
  14059. * Disposes buffer
  14060. * @param {PIXI.Buffer} buffer buffer with data
  14061. * @param {boolean} [contextLost=false] If context was lost, we suppress deleteVertexArray
  14062. */
  14063. GeometrySystem.prototype.disposeBuffer = function disposeBuffer (buffer, contextLost)
  14064. {
  14065. if (!this.managedBuffers[buffer.id])
  14066. {
  14067. return;
  14068. }
  14069. delete this.managedBuffers[buffer.id];
  14070. var glBuffer = buffer._glBuffers[this.CONTEXT_UID];
  14071. var gl = this.gl;
  14072. buffer.disposeRunner.remove(this);
  14073. if (!glBuffer)
  14074. {
  14075. return;
  14076. }
  14077. if (!contextLost)
  14078. {
  14079. gl.deleteBuffer(glBuffer.buffer);
  14080. }
  14081. delete buffer._glBuffers[this.CONTEXT_UID];
  14082. };
  14083. /**
  14084. * Disposes geometry
  14085. * @param {PIXI.Geometry} geometry Geometry with buffers. Only VAO will be disposed
  14086. * @param {boolean} [contextLost=false] If context was lost, we suppress deleteVertexArray
  14087. */
  14088. GeometrySystem.prototype.disposeGeometry = function disposeGeometry (geometry, contextLost)
  14089. {
  14090. if (!this.managedGeometries[geometry.id])
  14091. {
  14092. return;
  14093. }
  14094. delete this.managedGeometries[geometry.id];
  14095. var vaos = geometry.glVertexArrayObjects[this.CONTEXT_UID];
  14096. var gl = this.gl;
  14097. var buffers = geometry.buffers;
  14098. geometry.disposeRunner.remove(this);
  14099. if (!vaos)
  14100. {
  14101. return;
  14102. }
  14103. for (var i = 0; i < buffers.length; i++)
  14104. {
  14105. var buf = buffers[i]._glBuffers[this.CONTEXT_UID];
  14106. buf.refCount--;
  14107. if (buf.refCount === 0 && !contextLost)
  14108. {
  14109. this.disposeBuffer(buffers[i], contextLost);
  14110. }
  14111. }
  14112. if (!contextLost)
  14113. {
  14114. for (var vaoId in vaos)
  14115. {
  14116. // delete only signatures, everything else are copies
  14117. if (vaoId[0] === 'g')
  14118. {
  14119. var vao = vaos[vaoId];
  14120. if (this._activeVao === vao)
  14121. {
  14122. this.unbind();
  14123. }
  14124. gl.deleteVertexArray(vao);
  14125. }
  14126. }
  14127. }
  14128. delete geometry.glVertexArrayObjects[this.CONTEXT_UID];
  14129. };
  14130. /**
  14131. * dispose all WebGL resources of all managed geometries and buffers
  14132. * @param {boolean} [contextLost=false] If context was lost, we suppress `gl.delete` calls
  14133. */
  14134. GeometrySystem.prototype.disposeAll = function disposeAll (contextLost)
  14135. {
  14136. var all = Object.keys(this.managedGeometries);
  14137. for (var i = 0; i < all.length; i++)
  14138. {
  14139. this.disposeGeometry(this.managedGeometries[all[i]], contextLost);
  14140. }
  14141. all = Object.keys(this.managedBuffers);
  14142. for (var i$1 = 0; i$1 < all.length; i$1++)
  14143. {
  14144. this.disposeBuffer(this.managedBuffers[all[i$1]], contextLost);
  14145. }
  14146. };
  14147. /**
  14148. * Activate vertex array object
  14149. *
  14150. * @protected
  14151. * @param {PIXI.Geometry} geometry - Geometry instance
  14152. * @param {PIXI.Program} program - Shader program instance
  14153. */
  14154. GeometrySystem.prototype.activateVao = function activateVao (geometry, program)
  14155. {
  14156. var gl = this.gl;
  14157. var CONTEXT_UID = this.CONTEXT_UID;
  14158. var buffers = geometry.buffers;
  14159. var attributes = geometry.attributes;
  14160. if (geometry.indexBuffer)
  14161. {
  14162. // first update the index buffer if we have one..
  14163. gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, geometry.indexBuffer._glBuffers[CONTEXT_UID].buffer);
  14164. }
  14165. var lastBuffer = null;
  14166. // add a new one!
  14167. for (var j in attributes)
  14168. {
  14169. var attribute = attributes[j];
  14170. var buffer = buffers[attribute.buffer];
  14171. var glBuffer = buffer._glBuffers[CONTEXT_UID];
  14172. if (program.attributeData[j])
  14173. {
  14174. if (lastBuffer !== glBuffer)
  14175. {
  14176. gl.bindBuffer(gl.ARRAY_BUFFER, glBuffer.buffer);
  14177. lastBuffer = glBuffer;
  14178. }
  14179. var location = program.attributeData[j].location;
  14180. // TODO introduce state again
  14181. // we can optimise this for older devices that have no VAOs
  14182. gl.enableVertexAttribArray(location);
  14183. gl.vertexAttribPointer(location,
  14184. attribute.size,
  14185. attribute.type || gl.FLOAT,
  14186. attribute.normalized,
  14187. attribute.stride,
  14188. attribute.start);
  14189. if (attribute.instance)
  14190. {
  14191. // TODO calculate instance count based of this...
  14192. if (this.hasInstance)
  14193. {
  14194. gl.vertexAttribDivisor(location, 1);
  14195. }
  14196. else
  14197. {
  14198. throw new Error('geometry error, GPU Instancing is not supported on this device');
  14199. }
  14200. }
  14201. }
  14202. }
  14203. };
  14204. /**
  14205. * Draw the geometry
  14206. *
  14207. * @param {Number} type - the type primitive to render
  14208. * @param {Number} [size] - the number of elements to be rendered
  14209. * @param {Number} [start] - Starting index
  14210. * @param {Number} [instanceCount] - the number of instances of the set of elements to execute
  14211. */
  14212. GeometrySystem.prototype.draw = function draw (type, size, start, instanceCount)
  14213. {
  14214. var ref = this;
  14215. var gl = ref.gl;
  14216. var geometry = this._activeGeometry;
  14217. // TODO.. this should not change so maybe cache the function?
  14218. if (geometry.indexBuffer)
  14219. {
  14220. var byteSize = geometry.indexBuffer.data.BYTES_PER_ELEMENT;
  14221. var glType = byteSize === 2 ? gl.UNSIGNED_SHORT : gl.UNSIGNED_INT;
  14222. if (byteSize === 2 || (byteSize === 4 && this.canUseUInt32ElementIndex))
  14223. {
  14224. if (geometry.instanced)
  14225. {
  14226. /* eslint-disable max-len */
  14227. gl.drawElementsInstanced(type, size || geometry.indexBuffer.data.length, glType, (start || 0) * byteSize, instanceCount || 1);
  14228. /* eslint-enable max-len */
  14229. }
  14230. else
  14231. {
  14232. /* eslint-disable max-len */
  14233. gl.drawElements(type, size || geometry.indexBuffer.data.length, glType, (start || 0) * byteSize);
  14234. /* eslint-enable max-len */
  14235. }
  14236. }
  14237. else
  14238. {
  14239. console.warn('unsupported index buffer type: uint32');
  14240. }
  14241. }
  14242. else if (geometry.instanced)
  14243. {
  14244. // TODO need a better way to calculate size..
  14245. gl.drawArraysInstanced(type, start, size || geometry.getSize(), instanceCount || 1);
  14246. }
  14247. else
  14248. {
  14249. gl.drawArrays(type, start, size || geometry.getSize());
  14250. }
  14251. return this;
  14252. };
  14253. /**
  14254. * Unbind/reset everything
  14255. * @protected
  14256. */
  14257. GeometrySystem.prototype.unbind = function unbind ()
  14258. {
  14259. this.gl.bindVertexArray(null);
  14260. this._activeVao = null;
  14261. this._activeGeometry = null;
  14262. };
  14263. return GeometrySystem;
  14264. }(System));
  14265. /**
  14266. * @method compileProgram
  14267. * @private
  14268. * @memberof PIXI.glCore.shader
  14269. * @param gl {WebGLRenderingContext} The current WebGL context {WebGLProgram}
  14270. * @param vertexSrc {string|string[]} The vertex shader source as an array of strings.
  14271. * @param fragmentSrc {string|string[]} The fragment shader source as an array of strings.
  14272. * @param attributeLocations {Object} An attribute location map that lets you manually set the attribute locations
  14273. * @return {WebGLProgram} the shader program
  14274. */
  14275. function compileProgram(gl, vertexSrc, fragmentSrc, attributeLocations)
  14276. {
  14277. var glVertShader = compileShader(gl, gl.VERTEX_SHADER, vertexSrc);
  14278. var glFragShader = compileShader(gl, gl.FRAGMENT_SHADER, fragmentSrc);
  14279. var program = gl.createProgram();
  14280. gl.attachShader(program, glVertShader);
  14281. gl.attachShader(program, glFragShader);
  14282. // optionally, set the attributes manually for the program rather than letting WebGL decide..
  14283. if (attributeLocations)
  14284. {
  14285. for (var i in attributeLocations)
  14286. {
  14287. gl.bindAttribLocation(program, attributeLocations[i], i);
  14288. }
  14289. }
  14290. gl.linkProgram(program);
  14291. // if linking fails, then log and cleanup
  14292. if (!gl.getProgramParameter(program, gl.LINK_STATUS))
  14293. {
  14294. console.error('Pixi.js Error: Could not initialize shader.');
  14295. console.error('gl.VALIDATE_STATUS', gl.getProgramParameter(program, gl.VALIDATE_STATUS));
  14296. console.error('gl.getError()', gl.getError());
  14297. // if there is a program info log, log it
  14298. if (gl.getProgramInfoLog(program) !== '')
  14299. {
  14300. console.warn('Pixi.js Warning: gl.getProgramInfoLog()', gl.getProgramInfoLog(program));
  14301. }
  14302. gl.deleteProgram(program);
  14303. program = null;
  14304. }
  14305. // clean up some shaders
  14306. gl.deleteShader(glVertShader);
  14307. gl.deleteShader(glFragShader);
  14308. return program;
  14309. }
  14310. /**
  14311. * @private
  14312. * @param gl {WebGLRenderingContext} The current WebGL context {WebGLProgram}
  14313. * @param type {Number} the type, can be either VERTEX_SHADER or FRAGMENT_SHADER
  14314. * @param vertexSrc {string|string[]} The vertex shader source as an array of strings.
  14315. * @return {WebGLShader} the shader
  14316. */
  14317. function compileShader(gl, type, src)
  14318. {
  14319. var shader = gl.createShader(type);
  14320. gl.shaderSource(shader, src);
  14321. gl.compileShader(shader);
  14322. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS))
  14323. {
  14324. console.warn(src);
  14325. console.error(gl.getShaderInfoLog(shader));
  14326. return null;
  14327. }
  14328. return shader;
  14329. }
  14330. /**
  14331. * @method defaultValue
  14332. * @memberof PIXI.glCore.shader
  14333. * @param type {String} Type of value
  14334. * @param size {Number}
  14335. * @private
  14336. */
  14337. function defaultValue(type, size)
  14338. {
  14339. switch (type)
  14340. {
  14341. case 'float':
  14342. return 0;
  14343. case 'vec2':
  14344. return new Float32Array(2 * size);
  14345. case 'vec3':
  14346. return new Float32Array(3 * size);
  14347. case 'vec4':
  14348. return new Float32Array(4 * size);
  14349. case 'int':
  14350. case 'sampler2D':
  14351. case 'sampler2DArray':
  14352. return 0;
  14353. case 'ivec2':
  14354. return new Int32Array(2 * size);
  14355. case 'ivec3':
  14356. return new Int32Array(3 * size);
  14357. case 'ivec4':
  14358. return new Int32Array(4 * size);
  14359. case 'bool':
  14360. return false;
  14361. case 'bvec2':
  14362. return booleanArray(2 * size);
  14363. case 'bvec3':
  14364. return booleanArray(3 * size);
  14365. case 'bvec4':
  14366. return booleanArray(4 * size);
  14367. case 'mat2':
  14368. return new Float32Array([1, 0,
  14369. 0, 1]);
  14370. case 'mat3':
  14371. return new Float32Array([1, 0, 0,
  14372. 0, 1, 0,
  14373. 0, 0, 1]);
  14374. case 'mat4':
  14375. return new Float32Array([1, 0, 0, 0,
  14376. 0, 1, 0, 0,
  14377. 0, 0, 1, 0,
  14378. 0, 0, 0, 1]);
  14379. }
  14380. return null;
  14381. }
  14382. function booleanArray(size)
  14383. {
  14384. var array = new Array(size);
  14385. for (var i = 0; i < array.length; i++)
  14386. {
  14387. array[i] = false;
  14388. }
  14389. return array;
  14390. }
  14391. var context = null;
  14392. /**
  14393. * returns a little WebGL context to use for program inspection.
  14394. *
  14395. * @static
  14396. * @private
  14397. * @returns {webGL-context} a gl context to test with
  14398. */
  14399. function getTestContext()
  14400. {
  14401. if (!context)
  14402. {
  14403. var canvas = document.createElement('canvas');
  14404. var gl;
  14405. if (settings.PREFER_ENV >= ENV.WEBGL2)
  14406. {
  14407. gl = canvas.getContext('webgl2', {});
  14408. }
  14409. if (!gl)
  14410. {
  14411. gl = canvas.getContext('webgl', {})
  14412. || canvas.getContext('experimental-webgl', {});
  14413. if (!gl)
  14414. {
  14415. // fail, not able to get a context
  14416. throw new Error('This browser does not support WebGL. Try using the canvas renderer');
  14417. }
  14418. else
  14419. {
  14420. // for shader testing..
  14421. gl.getExtension('WEBGL_draw_buffers');
  14422. }
  14423. }
  14424. context = gl;
  14425. return gl;
  14426. }
  14427. return context;
  14428. }
  14429. var maxFragmentPrecision;
  14430. function getMaxFragmentPrecision()
  14431. {
  14432. if (!maxFragmentPrecision)
  14433. {
  14434. maxFragmentPrecision = PRECISION.MEDIUM;
  14435. var gl = getTestContext();
  14436. if (gl)
  14437. {
  14438. if (gl.getShaderPrecisionFormat)
  14439. {
  14440. var shaderFragment = gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.HIGH_FLOAT);
  14441. maxFragmentPrecision = shaderFragment.precision ? PRECISION.HIGH : PRECISION.MEDIUM;
  14442. }
  14443. }
  14444. }
  14445. return maxFragmentPrecision;
  14446. }
  14447. /**
  14448. * Sets the float precision on the shader, ensuring the device supports the request precision.
  14449. * If the precision is already present, it just ensures that the device is able to handle it.
  14450. *
  14451. * @private
  14452. * @param {string} src - The shader source
  14453. * @param {string} requestedPrecision - The request float precision of the shader. Options are 'lowp', 'mediump' or 'highp'.
  14454. * @param {string} maxSupportedPrecision - The maximum precision the shader supports.
  14455. *
  14456. * @return {string} modified shader source
  14457. */
  14458. function setPrecision(src, requestedPrecision, maxSupportedPrecision)
  14459. {
  14460. if (src.substring(0, 9) !== 'precision')
  14461. {
  14462. // no precision supplied, so PixiJS will add the requested level.
  14463. var precision = requestedPrecision;
  14464. // If highp is requested but not supported, downgrade precision to a level all devices support.
  14465. if (requestedPrecision === PRECISION.HIGH && maxSupportedPrecision !== PRECISION.HIGH)
  14466. {
  14467. precision = PRECISION.MEDIUM;
  14468. }
  14469. return ("precision " + precision + " float;\n" + src);
  14470. }
  14471. else if (maxSupportedPrecision !== PRECISION.HIGH && src.substring(0, 15) === 'precision highp')
  14472. {
  14473. // precision was supplied, but at a level this device does not support, so downgrading to mediump.
  14474. return src.replace('precision highp', 'precision mediump');
  14475. }
  14476. return src;
  14477. }
  14478. var GLSL_TO_SIZE = {
  14479. float: 1,
  14480. vec2: 2,
  14481. vec3: 3,
  14482. vec4: 4,
  14483. int: 1,
  14484. ivec2: 2,
  14485. ivec3: 3,
  14486. ivec4: 4,
  14487. bool: 1,
  14488. bvec2: 2,
  14489. bvec3: 3,
  14490. bvec4: 4,
  14491. mat2: 4,
  14492. mat3: 9,
  14493. mat4: 16,
  14494. sampler2D: 1,
  14495. };
  14496. /**
  14497. * @private
  14498. * @method mapSize
  14499. * @memberof PIXI.glCore.shader
  14500. * @param type {String}
  14501. * @return {Number}
  14502. */
  14503. function mapSize(type)
  14504. {
  14505. return GLSL_TO_SIZE[type];
  14506. }
  14507. var GL_TABLE = null;
  14508. var GL_TO_GLSL_TYPES = {
  14509. FLOAT: 'float',
  14510. FLOAT_VEC2: 'vec2',
  14511. FLOAT_VEC3: 'vec3',
  14512. FLOAT_VEC4: 'vec4',
  14513. INT: 'int',
  14514. INT_VEC2: 'ivec2',
  14515. INT_VEC3: 'ivec3',
  14516. INT_VEC4: 'ivec4',
  14517. BOOL: 'bool',
  14518. BOOL_VEC2: 'bvec2',
  14519. BOOL_VEC3: 'bvec3',
  14520. BOOL_VEC4: 'bvec4',
  14521. FLOAT_MAT2: 'mat2',
  14522. FLOAT_MAT3: 'mat3',
  14523. FLOAT_MAT4: 'mat4',
  14524. SAMPLER_2D: 'sampler2D',
  14525. SAMPLER_CUBE: 'samplerCube',
  14526. SAMPLER_2D_ARRAY: 'sampler2DArray',
  14527. };
  14528. function mapType(gl, type)
  14529. {
  14530. if (!GL_TABLE)
  14531. {
  14532. var typeNames = Object.keys(GL_TO_GLSL_TYPES);
  14533. GL_TABLE = {};
  14534. for (var i = 0; i < typeNames.length; ++i)
  14535. {
  14536. var tn = typeNames[i];
  14537. GL_TABLE[gl[tn]] = GL_TO_GLSL_TYPES[tn];
  14538. }
  14539. }
  14540. return GL_TABLE[type];
  14541. }
  14542. // cv = CachedValue
  14543. // v = value
  14544. // ud = uniformData
  14545. // uv = uniformValue
  14546. // l = location
  14547. var GLSL_TO_SINGLE_SETTERS_CACHED = {
  14548. float: "\n if(cv !== v)\n {\n cv.v = v;\n gl.uniform1f(location, v)\n }",
  14549. vec2: "\n if(cv[0] !== v[0] || cv[1] !== v[1])\n {\n cv[0] = v[0];\n cv[1] = v[1];\n gl.uniform2f(location, v[0], v[1])\n }",
  14550. 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 }",
  14551. vec4: 'gl.uniform4f(location, v[0], v[1], v[2], v[3])',
  14552. int: 'gl.uniform1i(location, v)',
  14553. ivec2: 'gl.uniform2i(location, v[0], v[1])',
  14554. ivec3: 'gl.uniform3i(location, v[0], v[1], v[2])',
  14555. ivec4: 'gl.uniform4i(location, v[0], v[1], v[2], v[3])',
  14556. bool: 'gl.uniform1i(location, v)',
  14557. bvec2: 'gl.uniform2i(location, v[0], v[1])',
  14558. bvec3: 'gl.uniform3i(location, v[0], v[1], v[2])',
  14559. bvec4: 'gl.uniform4i(location, v[0], v[1], v[2], v[3])',
  14560. mat2: 'gl.uniformMatrix2fv(location, false, v)',
  14561. mat3: 'gl.uniformMatrix3fv(location, false, v)',
  14562. mat4: 'gl.uniformMatrix4fv(location, false, v)',
  14563. sampler2D: 'gl.uniform1i(location, v)',
  14564. samplerCube: 'gl.uniform1i(location, v)',
  14565. sampler2DArray: 'gl.uniform1i(location, v)',
  14566. };
  14567. var GLSL_TO_ARRAY_SETTERS = {
  14568. float: "gl.uniform1fv(location, v)",
  14569. vec2: "gl.uniform2fv(location, v)",
  14570. vec3: "gl.uniform3fv(location, v)",
  14571. vec4: 'gl.uniform4fv(location, v)',
  14572. mat4: 'gl.uniformMatrix4fv(location, false, v)',
  14573. mat3: 'gl.uniformMatrix3fv(location, false, v)',
  14574. mat2: 'gl.uniformMatrix2fv(location, false, v)',
  14575. int: 'gl.uniform1iv(location, v)',
  14576. ivec2: 'gl.uniform2iv(location, v)',
  14577. ivec3: 'gl.uniform3iv(location, v)',
  14578. ivec4: 'gl.uniform4iv(location, v)',
  14579. bool: 'gl.uniform1iv(location, v)',
  14580. bvec2: 'gl.uniform2iv(location, v)',
  14581. bvec3: 'gl.uniform3iv(location, v)',
  14582. bvec4: 'gl.uniform4iv(location, v)',
  14583. sampler2D: 'gl.uniform1iv(location, v)',
  14584. samplerCube: 'gl.uniform1iv(location, v)',
  14585. sampler2DArray: 'gl.uniform1iv(location, v)',
  14586. };
  14587. function generateUniformsSync(group, uniformData)
  14588. {
  14589. var textureCount = 0;
  14590. var func = "var v = null;\n var cv = null\n var gl = renderer.gl";
  14591. for (var i in group.uniforms)
  14592. {
  14593. var data = uniformData[i];
  14594. if (!data)
  14595. {
  14596. if (group.uniforms[i].group)
  14597. {
  14598. func += "\n renderer.shader.syncUniformGroup(uv." + i + ");\n ";
  14599. }
  14600. continue;
  14601. }
  14602. // TODO && uniformData[i].value !== 0 <-- do we still need this?
  14603. if (data.type === 'float' && data.size === 1)
  14604. {
  14605. func += "\n if(uv." + i + " !== ud." + i + ".value)\n {\n ud." + i + ".value = uv." + i + "\n gl.uniform1f(ud." + i + ".location, uv." + i + ")\n }\n";
  14606. }
  14607. /* eslint-disable max-len */
  14608. else if ((data.type === 'sampler2D' || data.type === 'samplerCube' || data.type === 'sampler2DArray') && data.size === 1 && !data.isArray)
  14609. /* eslint-disable max-len */
  14610. {
  14611. func += "\n renderer.texture.bind(uv." + i + ", " + textureCount + ");\n\n if(ud." + i + ".value !== " + textureCount + ")\n {\n ud." + i + ".value = " + textureCount + ";\n gl.uniform1i(ud." + i + ".location, " + textureCount + ");\n; // eslint-disable-line max-len\n }\n";
  14612. textureCount++;
  14613. }
  14614. else if (data.type === 'mat3' && data.size === 1)
  14615. {
  14616. if (group.uniforms[i].a !== undefined)
  14617. {
  14618. // TODO and some smart caching dirty ids here!
  14619. func += "\n gl.uniformMatrix3fv(ud." + i + ".location, false, uv." + i + ".toArray(true));\n \n";
  14620. }
  14621. else
  14622. {
  14623. func += "\n gl.uniformMatrix3fv(ud." + i + ".location, false, uv." + i + ");\n \n";
  14624. }
  14625. }
  14626. else if (data.type === 'vec2' && data.size === 1)
  14627. {
  14628. // TODO - do we need both here?
  14629. // maybe we can get away with only using points?
  14630. if (group.uniforms[i].x !== undefined)
  14631. {
  14632. func += "\n cv = ud." + i + ".value;\n v = uv." + i + ";\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." + i + ".location, v.x, v.y);\n }\n";
  14633. }
  14634. else
  14635. {
  14636. func += "\n cv = ud." + i + ".value;\n v = uv." + i + ";\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." + i + ".location, v[0], v[1]);\n }\n \n";
  14637. }
  14638. }
  14639. else if (data.type === 'vec4' && data.size === 1)
  14640. {
  14641. // TODO - do we need both here?
  14642. // maybe we can get away with only using points?
  14643. if (group.uniforms[i].width !== undefined)
  14644. {
  14645. func += "\n cv = ud." + i + ".value;\n v = uv." + i + ";\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." + i + ".location, v.x, v.y, v.width, v.height)\n }\n";
  14646. }
  14647. else
  14648. {
  14649. func += "\n cv = ud." + i + ".value;\n v = uv." + i + ";\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." + i + ".location, v[0], v[1], v[2], v[3])\n }\n \n";
  14650. }
  14651. }
  14652. else
  14653. {
  14654. var templateType = (data.size === 1) ? GLSL_TO_SINGLE_SETTERS_CACHED : GLSL_TO_ARRAY_SETTERS;
  14655. var template = templateType[data.type].replace('location', ("ud." + i + ".location"));
  14656. func += "\n cv = ud." + i + ".value;\n v = uv." + i + ";\n " + template + ";\n";
  14657. }
  14658. }
  14659. return new Function('ud', 'uv', 'renderer', func); // eslint-disable-line no-new-func
  14660. }
  14661. var fragTemplate = [
  14662. 'precision mediump float;',
  14663. 'void main(void){',
  14664. 'float test = 0.1;',
  14665. '%forloop%',
  14666. 'gl_FragColor = vec4(0.0);',
  14667. '}' ].join('\n');
  14668. function checkMaxIfStatementsInShader(maxIfs, gl)
  14669. {
  14670. if (maxIfs === 0)
  14671. {
  14672. throw new Error('Invalid value of `0` passed to `checkMaxIfStatementsInShader`');
  14673. }
  14674. var shader = gl.createShader(gl.FRAGMENT_SHADER);
  14675. while (true) // eslint-disable-line no-constant-condition
  14676. {
  14677. var fragmentSrc = fragTemplate.replace(/%forloop%/gi, generateIfTestSrc(maxIfs));
  14678. gl.shaderSource(shader, fragmentSrc);
  14679. gl.compileShader(shader);
  14680. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS))
  14681. {
  14682. maxIfs = (maxIfs / 2) | 0;
  14683. }
  14684. else
  14685. {
  14686. // valid!
  14687. break;
  14688. }
  14689. }
  14690. return maxIfs;
  14691. }
  14692. function generateIfTestSrc(maxIfs)
  14693. {
  14694. var src = '';
  14695. for (var i = 0; i < maxIfs; ++i)
  14696. {
  14697. if (i > 0)
  14698. {
  14699. src += '\nelse ';
  14700. }
  14701. if (i < maxIfs - 1)
  14702. {
  14703. src += "if(test == " + i + ".0){}";
  14704. }
  14705. }
  14706. return src;
  14707. }
  14708. // Cache the result to prevent running this over and over
  14709. var unsafeEval;
  14710. /**
  14711. * Not all platforms allow to generate function code (e.g., `new Function`).
  14712. * this provides the platform-level detection.
  14713. *
  14714. * @private
  14715. * @returns {boolean}
  14716. */
  14717. function unsafeEvalSupported()
  14718. {
  14719. if (typeof unsafeEval === 'boolean')
  14720. {
  14721. return unsafeEval;
  14722. }
  14723. try
  14724. {
  14725. /* eslint-disable no-new-func */
  14726. var func = new Function('param1', 'param2', 'param3', 'return param1[param2] === param3;');
  14727. /* eslint-enable no-new-func */
  14728. unsafeEval = func({ a: 'b' }, 'a', 'b') === true;
  14729. }
  14730. catch (e)
  14731. {
  14732. unsafeEval = false;
  14733. }
  14734. return unsafeEval;
  14735. }
  14736. var defaultFragment = "varying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\n\nvoid main(void){\n gl_FragColor *= texture2D(uSampler, vTextureCoord);\n}";
  14737. var defaultVertex = "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";
  14738. // import * as from '../systems/shader/shader';
  14739. var UID$3 = 0;
  14740. var nameCache = {};
  14741. /**
  14742. * Helper class to create a shader program.
  14743. *
  14744. * @class
  14745. * @memberof PIXI
  14746. */
  14747. var Program = function Program(vertexSrc, fragmentSrc, name)
  14748. {
  14749. if ( name === void 0 ) { name = 'pixi-shader'; }
  14750. this.id = UID$3++;
  14751. /**
  14752. * The vertex shader.
  14753. *
  14754. * @member {string}
  14755. */
  14756. this.vertexSrc = vertexSrc || Program.defaultVertexSrc;
  14757. /**
  14758. * The fragment shader.
  14759. *
  14760. * @member {string}
  14761. */
  14762. this.fragmentSrc = fragmentSrc || Program.defaultFragmentSrc;
  14763. this.vertexSrc = this.vertexSrc.trim();
  14764. this.fragmentSrc = this.fragmentSrc.trim();
  14765. if (this.vertexSrc.substring(0, 8) !== '#version')
  14766. {
  14767. name = name.replace(/\s+/g, '-');
  14768. if (nameCache[name])
  14769. {
  14770. nameCache[name]++;
  14771. name += "-" + (nameCache[name]);
  14772. }
  14773. else
  14774. {
  14775. nameCache[name] = 1;
  14776. }
  14777. this.vertexSrc = "#define SHADER_NAME " + name + "\n" + (this.vertexSrc);
  14778. this.fragmentSrc = "#define SHADER_NAME " + name + "\n" + (this.fragmentSrc);
  14779. this.vertexSrc = setPrecision(this.vertexSrc, settings.PRECISION_VERTEX, PRECISION.HIGH);
  14780. this.fragmentSrc = setPrecision(this.fragmentSrc, settings.PRECISION_FRAGMENT, getMaxFragmentPrecision());
  14781. }
  14782. // currently this does not extract structs only default types
  14783. this.extractData(this.vertexSrc, this.fragmentSrc);
  14784. // this is where we store shader references..
  14785. this.glPrograms = {};
  14786. this.syncUniforms = null;
  14787. };
  14788. var staticAccessors$3 = { defaultVertexSrc: { configurable: true },defaultFragmentSrc: { configurable: true } };
  14789. /**
  14790. * Extracts the data for a buy creating a small test program
  14791. * or reading the src directly.
  14792. * @protected
  14793. *
  14794. * @param {string} [vertexSrc] - The source of the vertex shader.
  14795. * @param {string} [fragmentSrc] - The source of the fragment shader.
  14796. */
  14797. Program.prototype.extractData = function extractData (vertexSrc, fragmentSrc)
  14798. {
  14799. var gl = getTestContext();
  14800. if (gl)
  14801. {
  14802. var program = compileProgram(gl, vertexSrc, fragmentSrc);
  14803. this.attributeData = this.getAttributeData(program, gl);
  14804. this.uniformData = this.getUniformData(program, gl);
  14805. gl.deleteProgram(program);
  14806. }
  14807. else
  14808. {
  14809. this.uniformData = {};
  14810. this.attributeData = {};
  14811. }
  14812. };
  14813. /**
  14814. * returns the attribute data from the program
  14815. * @private
  14816. *
  14817. * @param {WebGLProgram} [program] - the WebGL program
  14818. * @param {WebGLRenderingContext} [gl] - the WebGL context
  14819. *
  14820. * @returns {object} the attribute data for this program
  14821. */
  14822. Program.prototype.getAttributeData = function getAttributeData (program, gl)
  14823. {
  14824. var attributes = {};
  14825. var attributesArray = [];
  14826. var totalAttributes = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES);
  14827. for (var i = 0; i < totalAttributes; i++)
  14828. {
  14829. var attribData = gl.getActiveAttrib(program, i);
  14830. var type = mapType(gl, attribData.type);
  14831. /*eslint-disable */
  14832. var data = {
  14833. type: type,
  14834. name: attribData.name,
  14835. size: mapSize(type),
  14836. location: 0,
  14837. };
  14838. /* eslint-enable */
  14839. attributes[attribData.name] = data;
  14840. attributesArray.push(data);
  14841. }
  14842. attributesArray.sort(function (a, b) { return (a.name > b.name) ? 1 : -1; }); // eslint-disable-line no-confusing-arrow
  14843. for (var i$1 = 0; i$1 < attributesArray.length; i$1++)
  14844. {
  14845. attributesArray[i$1].location = i$1;
  14846. }
  14847. return attributes;
  14848. };
  14849. /**
  14850. * returns the uniform data from the program
  14851. * @private
  14852. *
  14853. * @param {webGL-program} [program] - the webgl program
  14854. * @param {context} [gl] - the WebGL context
  14855. *
  14856. * @returns {object} the uniform data for this program
  14857. */
  14858. Program.prototype.getUniformData = function getUniformData (program, gl)
  14859. {
  14860. var uniforms = {};
  14861. var totalUniforms = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS);
  14862. // TODO expose this as a prop?
  14863. // const maskRegex = new RegExp('^(projectionMatrix|uSampler|translationMatrix)$');
  14864. // const maskRegex = new RegExp('^(projectionMatrix|uSampler|translationMatrix)$');
  14865. for (var i = 0; i < totalUniforms; i++)
  14866. {
  14867. var uniformData = gl.getActiveUniform(program, i);
  14868. var name = uniformData.name.replace(/\[.*?\]/, '');
  14869. var isArray = uniformData.name.match(/\[.*?\]/, '');
  14870. var type = mapType(gl, uniformData.type);
  14871. /*eslint-disable */
  14872. uniforms[name] = {
  14873. type: type,
  14874. size: uniformData.size,
  14875. isArray:isArray,
  14876. value: defaultValue(type, uniformData.size),
  14877. };
  14878. /* eslint-enable */
  14879. }
  14880. return uniforms;
  14881. };
  14882. /**
  14883. * The default vertex shader source
  14884. *
  14885. * @static
  14886. * @constant
  14887. * @member {string}
  14888. */
  14889. staticAccessors$3.defaultVertexSrc.get = function ()
  14890. {
  14891. return defaultVertex;
  14892. };
  14893. /**
  14894. * The default fragment shader source
  14895. *
  14896. * @static
  14897. * @constant
  14898. * @member {string}
  14899. */
  14900. staticAccessors$3.defaultFragmentSrc.get = function ()
  14901. {
  14902. return defaultFragment;
  14903. };
  14904. /**
  14905. * A short hand function to create a program based of a vertex and fragment shader
  14906. * this method will also check to see if there is a cached program.
  14907. *
  14908. * @param {string} [vertexSrc] - The source of the vertex shader.
  14909. * @param {string} [fragmentSrc] - The source of the fragment shader.
  14910. * @param {object} [uniforms] - Custom uniforms to use to augment the built-in ones.
  14911. *
  14912. * @returns {PIXI.Program} an shiny new Pixi shader!
  14913. */
  14914. Program.from = function from (vertexSrc, fragmentSrc, name)
  14915. {
  14916. var key = vertexSrc + fragmentSrc;
  14917. var program = ProgramCache[key];
  14918. if (!program)
  14919. {
  14920. ProgramCache[key] = program = new Program(vertexSrc, fragmentSrc, name);
  14921. }
  14922. return program;
  14923. };
  14924. Object.defineProperties( Program, staticAccessors$3 );
  14925. /**
  14926. * A helper class for shaders
  14927. *
  14928. * @class
  14929. * @memberof PIXI
  14930. */
  14931. var Shader = function Shader(program, uniforms)
  14932. {
  14933. this.program = program;
  14934. // lets see whats been passed in
  14935. // uniforms should be converted to a uniform group
  14936. if (uniforms)
  14937. {
  14938. if (uniforms instanceof UniformGroup)
  14939. {
  14940. this.uniformGroup = uniforms;
  14941. }
  14942. else
  14943. {
  14944. this.uniformGroup = new UniformGroup(uniforms);
  14945. }
  14946. }
  14947. else
  14948. {
  14949. this.uniformGroup = new UniformGroup({});
  14950. }
  14951. // time to build some getters and setters!
  14952. // I guess down the line this could sort of generate an instruction list rather than use dirty ids?
  14953. // does the trick for now though!
  14954. for (var i in program.uniformData)
  14955. {
  14956. if (this.uniformGroup.uniforms[i] instanceof Array)
  14957. {
  14958. this.uniformGroup.uniforms[i] = new Float32Array(this.uniformGroup.uniforms[i]);
  14959. }
  14960. }
  14961. };
  14962. var prototypeAccessors$2$1 = { uniforms: { configurable: true } };
  14963. // TODO move to shader system..
  14964. Shader.prototype.checkUniformExists = function checkUniformExists (name, group)
  14965. {
  14966. if (group.uniforms[name])
  14967. {
  14968. return true;
  14969. }
  14970. for (var i in group.uniforms)
  14971. {
  14972. var uniform = group.uniforms[i];
  14973. if (uniform.group)
  14974. {
  14975. if (this.checkUniformExists(name, uniform))
  14976. {
  14977. return true;
  14978. }
  14979. }
  14980. }
  14981. return false;
  14982. };
  14983. Shader.prototype.destroy = function destroy ()
  14984. {
  14985. // usage count on programs?
  14986. // remove if not used!
  14987. this.uniformGroup = null;
  14988. };
  14989. /**
  14990. * Shader uniform values, shortcut for `uniformGroup.uniforms`
  14991. * @readonly
  14992. * @member {object}
  14993. */
  14994. prototypeAccessors$2$1.uniforms.get = function ()
  14995. {
  14996. return this.uniformGroup.uniforms;
  14997. };
  14998. /**
  14999. * A short hand function to create a shader based of a vertex and fragment shader
  15000. *
  15001. * @param {string} [vertexSrc] - The source of the vertex shader.
  15002. * @param {string} [fragmentSrc] - The source of the fragment shader.
  15003. * @param {object} [uniforms] - Custom uniforms to use to augment the built-in ones.
  15004. *
  15005. * @returns {PIXI.Shader} an shiny new Pixi shader!
  15006. */
  15007. Shader.from = function from (vertexSrc, fragmentSrc, uniforms)
  15008. {
  15009. var program = Program.from(vertexSrc, fragmentSrc);
  15010. return new Shader(program, uniforms);
  15011. };
  15012. Object.defineProperties( Shader.prototype, prototypeAccessors$2$1 );
  15013. /* eslint-disable max-len */
  15014. var BLEND = 0;
  15015. var OFFSET = 1;
  15016. var CULLING = 2;
  15017. var DEPTH_TEST = 3;
  15018. var WINDING = 4;
  15019. /**
  15020. * This is a WebGL state, and is is passed The WebGL StateManager.
  15021. *
  15022. * Each mesh rendered may require WebGL to be in a different state.
  15023. * For example you may want different blend mode or to enable polygon offsets
  15024. *
  15025. * @class
  15026. * @memberof PIXI
  15027. */
  15028. var State = function State()
  15029. {
  15030. this.data = 0;
  15031. this.blendMode = BLEND_MODES.NORMAL;
  15032. this.polygonOffset = 0;
  15033. this.blend = true;
  15034. // this.depthTest = true;
  15035. };
  15036. var prototypeAccessors$3$1 = { blend: { configurable: true },offsets: { configurable: true },culling: { configurable: true },depthTest: { configurable: true },clockwiseFrontFace: { configurable: true },blendMode: { configurable: true },polygonOffset: { configurable: true } };
  15037. /**
  15038. * Activates blending of the computed fragment color values
  15039. *
  15040. * @member {boolean}
  15041. */
  15042. prototypeAccessors$3$1.blend.get = function ()
  15043. {
  15044. return !!(this.data & (1 << BLEND));
  15045. };
  15046. prototypeAccessors$3$1.blend.set = function (value) // eslint-disable-line require-jsdoc
  15047. {
  15048. if (!!(this.data & (1 << BLEND)) !== value)
  15049. {
  15050. this.data ^= (1 << BLEND);
  15051. }
  15052. };
  15053. /**
  15054. * Activates adding an offset to depth values of polygon's fragments
  15055. *
  15056. * @member {boolean}
  15057. * @default false
  15058. */
  15059. prototypeAccessors$3$1.offsets.get = function ()
  15060. {
  15061. return !!(this.data & (1 << OFFSET));
  15062. };
  15063. prototypeAccessors$3$1.offsets.set = function (value) // eslint-disable-line require-jsdoc
  15064. {
  15065. if (!!(this.data & (1 << OFFSET)) !== value)
  15066. {
  15067. this.data ^= (1 << OFFSET);
  15068. }
  15069. };
  15070. /**
  15071. * Activates culling of polygons.
  15072. *
  15073. * @member {boolean}
  15074. * @default false
  15075. */
  15076. prototypeAccessors$3$1.culling.get = function ()
  15077. {
  15078. return !!(this.data & (1 << CULLING));
  15079. };
  15080. prototypeAccessors$3$1.culling.set = function (value) // eslint-disable-line require-jsdoc
  15081. {
  15082. if (!!(this.data & (1 << CULLING)) !== value)
  15083. {
  15084. this.data ^= (1 << CULLING);
  15085. }
  15086. };
  15087. /**
  15088. * Activates depth comparisons and updates to the depth buffer.
  15089. *
  15090. * @member {boolean}
  15091. * @default false
  15092. */
  15093. prototypeAccessors$3$1.depthTest.get = function ()
  15094. {
  15095. return !!(this.data & (1 << DEPTH_TEST));
  15096. };
  15097. prototypeAccessors$3$1.depthTest.set = function (value) // eslint-disable-line require-jsdoc
  15098. {
  15099. if (!!(this.data & (1 << DEPTH_TEST)) !== value)
  15100. {
  15101. this.data ^= (1 << DEPTH_TEST);
  15102. }
  15103. };
  15104. /**
  15105. * Specifies whether or not front or back-facing polygons can be culled.
  15106. * @member {boolean}
  15107. * @default false
  15108. */
  15109. prototypeAccessors$3$1.clockwiseFrontFace.get = function ()
  15110. {
  15111. return !!(this.data & (1 << WINDING));
  15112. };
  15113. prototypeAccessors$3$1.clockwiseFrontFace.set = function (value) // eslint-disable-line require-jsdoc
  15114. {
  15115. if (!!(this.data & (1 << WINDING)) !== value)
  15116. {
  15117. this.data ^= (1 << WINDING);
  15118. }
  15119. };
  15120. /**
  15121. * The blend mode to be applied when this state is set. Apply a value of `PIXI.BLEND_MODES.NORMAL` to reset the blend mode.
  15122. * Setting this mode to anything other than NO_BLEND will automatically switch blending on.
  15123. *
  15124. * @member {number}
  15125. * @default PIXI.BLEND_MODES.NORMAL
  15126. * @see PIXI.BLEND_MODES
  15127. */
  15128. prototypeAccessors$3$1.blendMode.get = function ()
  15129. {
  15130. return this._blendMode;
  15131. };
  15132. prototypeAccessors$3$1.blendMode.set = function (value) // eslint-disable-line require-jsdoc
  15133. {
  15134. this.blend = (value !== BLEND_MODES.NONE);
  15135. this._blendMode = value;
  15136. };
  15137. /**
  15138. * The polygon offset. Setting this property to anything other than 0 will automatically enable polygon offset fill.
  15139. *
  15140. * @member {number}
  15141. * @default 0
  15142. */
  15143. prototypeAccessors$3$1.polygonOffset.get = function ()
  15144. {
  15145. return this._polygonOffset;
  15146. };
  15147. prototypeAccessors$3$1.polygonOffset.set = function (value) // eslint-disable-line require-jsdoc
  15148. {
  15149. this.offsets = !!value;
  15150. this._polygonOffset = value;
  15151. };
  15152. State.for2d = function for2d ()
  15153. {
  15154. var state = new State();
  15155. state.depthTest = false;
  15156. state.blend = true;
  15157. return state;
  15158. };
  15159. Object.defineProperties( State.prototype, prototypeAccessors$3$1 );
  15160. var defaultVertex$1 = "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";
  15161. var defaultFragment$1 = "varying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\n\nvoid main(void){\n gl_FragColor = texture2D(uSampler, vTextureCoord);\n}\n";
  15162. /**
  15163. * Filter is a special type of WebGL shader that is applied to the screen.
  15164. *
  15165. * {@link http://pixijs.io/examples/#/filters/blur-filter.js Example} of the
  15166. * {@link PIXI.filters.BlurFilter BlurFilter}.
  15167. *
  15168. * ### Usage
  15169. * Filters can be applied to any DisplayObject or Container.
  15170. * PixiJS' `FilterSystem` renders the container into temporary Framebuffer,
  15171. * then filter renders it to the screen.
  15172. * Multiple filters can be added to the `filters` array property and stacked on each other.
  15173. *
  15174. * ```
  15175. * const filter = new PIXI.Filter(myShaderVert, myShaderFrag, { myUniform: 0.5 });
  15176. * const container = new PIXI.Container();
  15177. * container.filters = [filter];
  15178. * ```
  15179. *
  15180. * ### Previous Version Differences
  15181. *
  15182. * In PixiJS **v3**, a filter was always applied to _whole screen_.
  15183. *
  15184. * In PixiJS **v4**, a filter can be applied _only part of the screen_.
  15185. * Developers had to create a set of uniforms to deal with coordinates.
  15186. *
  15187. * In PixiJS **v5** combines _both approaches_.
  15188. * Developers can use normal coordinates of v3 and then allow filter to use partial Framebuffers,
  15189. * bringing those extra uniforms into account.
  15190. *
  15191. * Also be aware that we have changed default vertex shader, please consult
  15192. * {@link https://github.com/pixijs/pixi.js/wiki/v5-Creating-filters Wiki}.
  15193. *
  15194. * ### Built-in Uniforms
  15195. *
  15196. * PixiJS viewport uses screen (CSS) coordinates, `(0, 0, renderer.screen.width, renderer.screen.height)`,
  15197. * and `projectionMatrix` uniform maps it to the gl viewport.
  15198. *
  15199. * **uSampler**
  15200. *
  15201. * The most important uniform is the input texture that container was rendered into.
  15202. * _Important note: as with all Framebuffers in PixiJS, both input and output are
  15203. * premultiplied by alpha._
  15204. *
  15205. * By default, input normalized coordinates are passed to fragment shader with `vTextureCoord`.
  15206. * Use it to sample the input.
  15207. *
  15208. * ```
  15209. * const fragment = `
  15210. * varying vec2 vTextureCoord;
  15211. * uniform sampler2D uSampler;
  15212. * void main(void)
  15213. * {
  15214. * gl_FragColor = texture2D(uSampler, vTextureCoord);
  15215. * }
  15216. * `;
  15217. *
  15218. * const myFilter = new PIXI.Filter(null, fragment);
  15219. * ```
  15220. *
  15221. * This filter is just one uniform less than {@link PIXI.filters.AlphaFilter AlphaFilter}.
  15222. *
  15223. * **outputFrame**
  15224. *
  15225. * The `outputFrame` holds the rectangle where filter is applied in screen (CSS) coordinates.
  15226. * It's the same as `renderer.screen` for a fullscreen filter.
  15227. * Only a part of `outputFrame.zw` size of temporary Framebuffer is used,
  15228. * `(0, 0, outputFrame.width, outputFrame.height)`,
  15229. *
  15230. * Filters uses this quad to normalized (0-1) space, its passed into `aVertexPosition` attribute.
  15231. * To calculate vertex position in screen space using normalized (0-1) space:
  15232. *
  15233. * ```
  15234. * vec4 filterVertexPosition( void )
  15235. * {
  15236. * vec2 position = aVertexPosition * max(outputFrame.zw, vec2(0.)) + outputFrame.xy;
  15237. * return vec4((projectionMatrix * vec3(position, 1.0)).xy, 0.0, 1.0);
  15238. * }
  15239. * ```
  15240. *
  15241. * **inputSize**
  15242. *
  15243. * Temporary framebuffer is different, it can be either the size of screen, either power-of-two.
  15244. * The `inputSize.xy` are size of temporary framebuffer that holds input.
  15245. * The `inputSize.zw` is inverted, it's a shortcut to evade division inside the shader.
  15246. *
  15247. * Set `inputSize.xy = outputFrame.zw` for a fullscreen filter.
  15248. *
  15249. * To calculate input normalized coordinate, you have to map it to filter normalized space.
  15250. * Multiply by `outputFrame.zw` to get input coordinate.
  15251. * Divide by `inputSize.xy` to get input normalized coordinate.
  15252. *
  15253. * ```
  15254. * vec2 filterTextureCoord( void )
  15255. * {
  15256. * return aVertexPosition * (outputFrame.zw * inputSize.zw); // same as /inputSize.xy
  15257. * }
  15258. * ```
  15259. * **resolution**
  15260. *
  15261. * The `resolution` is the ratio of screen (CSS) pixels to real pixels.
  15262. *
  15263. * **inputPixel**
  15264. *
  15265. * `inputPixel.xy` is the size of framebuffer in real pixels, same as `inputSize.xy * resolution`
  15266. * `inputPixel.zw` is inverted `inputPixel.xy`.
  15267. *
  15268. * It's handy for filters that use neighbour pixels, like {@link PIXI.filters.FXAAFilter FXAAFilter}.
  15269. *
  15270. * **inputClamp**
  15271. *
  15272. * If you try to get info from outside of used part of Framebuffer - you'll get undefined behaviour.
  15273. * For displacements, coordinates has to be clamped.
  15274. *
  15275. * The `inputClamp.xy` is left-top pixel center, you may ignore it, because we use left-top part of Framebuffer
  15276. * `inputClamp.zw` is bottom-right pixel center.
  15277. *
  15278. * ```
  15279. * vec4 color = texture2D(uSampler, clamp(modifigedTextureCoord, inputClamp.xy, inputClamp.zw))
  15280. * ```
  15281. * OR
  15282. * ```
  15283. * vec4 color = texture2D(uSampler, min(modifigedTextureCoord, inputClamp.zw))
  15284. * ```
  15285. *
  15286. * ### Additional Information
  15287. *
  15288. * Complete documentation on Filter usage is located in the
  15289. * {@link https://github.com/pixijs/pixi.js/wiki/v5-Creating-filters Wiki}.
  15290. *
  15291. * Since PixiJS only had a handful of built-in filters, additional filters can be downloaded
  15292. * {@link https://github.com/pixijs/pixi-filters here} from the PixiJS Filters repository.
  15293. *
  15294. * @class
  15295. * @memberof PIXI
  15296. * @extends PIXI.Shader
  15297. */
  15298. var Filter = /*@__PURE__*/(function (Shader) {
  15299. function Filter(vertexSrc, fragmentSrc, uniforms)
  15300. {
  15301. var program = Program.from(vertexSrc || Filter.defaultVertexSrc,
  15302. fragmentSrc || Filter.defaultFragmentSrc);
  15303. Shader.call(this, program, uniforms);
  15304. /**
  15305. * The padding of the filter. Some filters require extra space to breath such as a blur.
  15306. * Increasing this will add extra width and height to the bounds of the object that the
  15307. * filter is applied to.
  15308. *
  15309. * @member {number}
  15310. */
  15311. this.padding = 0;
  15312. /**
  15313. * The resolution of the filter. Setting this to be lower will lower the quality but
  15314. * increase the performance of the filter.
  15315. *
  15316. * @member {number}
  15317. */
  15318. this.resolution = settings.FILTER_RESOLUTION;
  15319. /**
  15320. * If enabled is true the filter is applied, if false it will not.
  15321. *
  15322. * @member {boolean}
  15323. */
  15324. this.enabled = true;
  15325. /**
  15326. * If enabled, PixiJS will fit the filter area into boundaries for better performance.
  15327. * Switch it off if it does not work for specific shader.
  15328. *
  15329. * @member {boolean}
  15330. */
  15331. this.autoFit = true;
  15332. /**
  15333. * Legacy filters use position and uvs from attributes
  15334. * @member {boolean}
  15335. * @readonly
  15336. */
  15337. this.legacy = !!this.program.attributeData.aTextureCoord;
  15338. /**
  15339. * The WebGL state the filter requires to render
  15340. * @member {PIXI.State}
  15341. */
  15342. this.state = new State();
  15343. }
  15344. if ( Shader ) { Filter.__proto__ = Shader; }
  15345. Filter.prototype = Object.create( Shader && Shader.prototype );
  15346. Filter.prototype.constructor = Filter;
  15347. var prototypeAccessors = { blendMode: { configurable: true } };
  15348. var staticAccessors = { defaultVertexSrc: { configurable: true },defaultFragmentSrc: { configurable: true } };
  15349. /**
  15350. * Applies the filter
  15351. *
  15352. * @param {PIXI.systems.FilterSystem} filterManager - The renderer to retrieve the filter from
  15353. * @param {PIXI.RenderTexture} input - The input render target.
  15354. * @param {PIXI.RenderTexture} output - The target to output to.
  15355. * @param {boolean} clear - Should the output be cleared before rendering to it
  15356. * @param {object} [currentState] - It's current state of filter.
  15357. * There are some useful properties in the currentState :
  15358. * target, filters, sourceFrame, destinationFrame, renderTarget, resolution
  15359. */
  15360. Filter.prototype.apply = function apply (filterManager, input, output, clear, currentState)
  15361. {
  15362. // do as you please!
  15363. filterManager.applyFilter(this, input, output, clear, currentState);
  15364. // or just do a regular render..
  15365. };
  15366. /**
  15367. * Sets the blendmode of the filter
  15368. *
  15369. * @member {number}
  15370. * @default PIXI.BLEND_MODES.NORMAL
  15371. */
  15372. prototypeAccessors.blendMode.get = function ()
  15373. {
  15374. return this.state.blendMode;
  15375. };
  15376. prototypeAccessors.blendMode.set = function (value) // eslint-disable-line require-jsdoc
  15377. {
  15378. this.state.blendMode = value;
  15379. };
  15380. /**
  15381. * The default vertex shader source
  15382. *
  15383. * @static
  15384. * @type {string}
  15385. * @constant
  15386. */
  15387. staticAccessors.defaultVertexSrc.get = function ()
  15388. {
  15389. return defaultVertex$1;
  15390. };
  15391. /**
  15392. * The default fragment shader source
  15393. *
  15394. * @static
  15395. * @type {string}
  15396. * @constant
  15397. */
  15398. staticAccessors.defaultFragmentSrc.get = function ()
  15399. {
  15400. return defaultFragment$1;
  15401. };
  15402. Object.defineProperties( Filter.prototype, prototypeAccessors );
  15403. Object.defineProperties( Filter, staticAccessors );
  15404. return Filter;
  15405. }(Shader));
  15406. /**
  15407. * Used for caching shader IDs
  15408. *
  15409. * @static
  15410. * @type {object}
  15411. * @protected
  15412. */
  15413. Filter.SOURCE_KEY_MAP = {};
  15414. var vertex = "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";
  15415. var fragment = "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";
  15416. var tempMat = new Matrix();
  15417. /**
  15418. * Class controls uv mapping from Texture normal space to BaseTexture normal space.
  15419. *
  15420. * Takes `trim` and `rotate` into account. May contain clamp settings for Meshes and TilingSprite.
  15421. *
  15422. * Can be used in Texture `uvMatrix` field, or separately, you can use different clamp settings on the same texture.
  15423. * If you want to add support for texture region of certain feature or filter, that's what you're looking for.
  15424. *
  15425. * Takes track of Texture changes through `_lastTextureID` private field.
  15426. * Use `update()` method call to track it from outside.
  15427. *
  15428. * @see PIXI.Texture
  15429. * @see PIXI.Mesh
  15430. * @see PIXI.TilingSprite
  15431. * @class
  15432. * @memberof PIXI
  15433. */
  15434. var TextureMatrix = function TextureMatrix(texture, clampMargin)
  15435. {
  15436. this._texture = texture;
  15437. this.mapCoord = new Matrix();
  15438. this.uClampFrame = new Float32Array(4);
  15439. this.uClampOffset = new Float32Array(2);
  15440. /**
  15441. * Tracks Texture frame changes
  15442. * @member {number}
  15443. * @protected
  15444. */
  15445. this._updateID = -1;
  15446. /**
  15447. * Changes frame clamping
  15448. * Works with TilingSprite and Mesh
  15449. * Change to 1.5 if you texture has repeated right and bottom lines, that leads to smoother borders
  15450. *
  15451. * @default 0
  15452. * @member {number}
  15453. */
  15454. this.clampOffset = 0;
  15455. /**
  15456. * Changes frame clamping
  15457. * Works with TilingSprite and Mesh
  15458. * Change to -0.5 to add a pixel to the edge, recommended for transparent trimmed textures in atlas
  15459. *
  15460. * @default 0.5
  15461. * @member {number}
  15462. */
  15463. this.clampMargin = (typeof clampMargin === 'undefined') ? 0.5 : clampMargin;
  15464. /**
  15465. * If texture size is the same as baseTexture
  15466. * @member {boolean}
  15467. * @default false
  15468. * @readonly
  15469. */
  15470. this.isSimple = false;
  15471. };
  15472. var prototypeAccessors$4$1 = { texture: { configurable: true } };
  15473. /**
  15474. * texture property
  15475. * @member {PIXI.Texture}
  15476. */
  15477. prototypeAccessors$4$1.texture.get = function ()
  15478. {
  15479. return this._texture;
  15480. };
  15481. prototypeAccessors$4$1.texture.set = function (value) // eslint-disable-line require-jsdoc
  15482. {
  15483. this._texture = value;
  15484. this._updateID = -1;
  15485. };
  15486. /**
  15487. * Multiplies uvs array to transform
  15488. * @param {Float32Array} uvs mesh uvs
  15489. * @param {Float32Array} [out=uvs] output
  15490. * @returns {Float32Array} output
  15491. */
  15492. TextureMatrix.prototype.multiplyUvs = function multiplyUvs (uvs, out)
  15493. {
  15494. if (out === undefined)
  15495. {
  15496. out = uvs;
  15497. }
  15498. var mat = this.mapCoord;
  15499. for (var i = 0; i < uvs.length; i += 2)
  15500. {
  15501. var x = uvs[i];
  15502. var y = uvs[i + 1];
  15503. out[i] = (x * mat.a) + (y * mat.c) + mat.tx;
  15504. out[i + 1] = (x * mat.b) + (y * mat.d) + mat.ty;
  15505. }
  15506. return out;
  15507. };
  15508. /**
  15509. * updates matrices if texture was changed
  15510. * @param {boolean} [forceUpdate=false] if true, matrices will be updated any case
  15511. * @returns {boolean} whether or not it was updated
  15512. */
  15513. TextureMatrix.prototype.update = function update (forceUpdate)
  15514. {
  15515. var tex = this._texture;
  15516. if (!tex || !tex.valid)
  15517. {
  15518. return false;
  15519. }
  15520. if (!forceUpdate
  15521. && this._updateID === tex._updateID)
  15522. {
  15523. return false;
  15524. }
  15525. this._updateID = tex._updateID;
  15526. var uvs = tex._uvs;
  15527. this.mapCoord.set(uvs.x1 - uvs.x0, uvs.y1 - uvs.y0, uvs.x3 - uvs.x0, uvs.y3 - uvs.y0, uvs.x0, uvs.y0);
  15528. var orig = tex.orig;
  15529. var trim = tex.trim;
  15530. if (trim)
  15531. {
  15532. tempMat.set(orig.width / trim.width, 0, 0, orig.height / trim.height,
  15533. -trim.x / trim.width, -trim.y / trim.height);
  15534. this.mapCoord.append(tempMat);
  15535. }
  15536. var texBase = tex.baseTexture;
  15537. var frame = this.uClampFrame;
  15538. var margin = this.clampMargin / texBase.resolution;
  15539. var offset = this.clampOffset;
  15540. frame[0] = (tex._frame.x + margin + offset) / texBase.width;
  15541. frame[1] = (tex._frame.y + margin + offset) / texBase.height;
  15542. frame[2] = (tex._frame.x + tex._frame.width - margin + offset) / texBase.width;
  15543. frame[3] = (tex._frame.y + tex._frame.height - margin + offset) / texBase.height;
  15544. this.uClampOffset[0] = offset / texBase.realWidth;
  15545. this.uClampOffset[1] = offset / texBase.realHeight;
  15546. this.isSimple = tex._frame.width === texBase.width
  15547. && tex._frame.height === texBase.height
  15548. && tex.rotate === 0;
  15549. return true;
  15550. };
  15551. Object.defineProperties( TextureMatrix.prototype, prototypeAccessors$4$1 );
  15552. /**
  15553. * This handles a Sprite acting as a mask, as opposed to a Graphic.
  15554. *
  15555. * WebGL only.
  15556. *
  15557. * @class
  15558. * @extends PIXI.Filter
  15559. * @memberof PIXI
  15560. */
  15561. var SpriteMaskFilter = /*@__PURE__*/(function (Filter) {
  15562. function SpriteMaskFilter(sprite)
  15563. {
  15564. var maskMatrix = new Matrix();
  15565. Filter.call(this, vertex, fragment);
  15566. sprite.renderable = false;
  15567. /**
  15568. * Sprite mask
  15569. * @member {PIXI.Sprite}
  15570. */
  15571. this.maskSprite = sprite;
  15572. /**
  15573. * Mask matrix
  15574. * @member {PIXI.Matrix}
  15575. */
  15576. this.maskMatrix = maskMatrix;
  15577. }
  15578. if ( Filter ) { SpriteMaskFilter.__proto__ = Filter; }
  15579. SpriteMaskFilter.prototype = Object.create( Filter && Filter.prototype );
  15580. SpriteMaskFilter.prototype.constructor = SpriteMaskFilter;
  15581. /**
  15582. * Applies the filter
  15583. *
  15584. * @param {PIXI.systems.FilterSystem} filterManager - The renderer to retrieve the filter from
  15585. * @param {PIXI.RenderTexture} input - The input render target.
  15586. * @param {PIXI.RenderTexture} output - The target to output to.
  15587. * @param {boolean} clear - Should the output be cleared before rendering to it.
  15588. */
  15589. SpriteMaskFilter.prototype.apply = function apply (filterManager, input, output, clear)
  15590. {
  15591. var maskSprite = this.maskSprite;
  15592. var tex = this.maskSprite.texture;
  15593. if (!tex.valid)
  15594. {
  15595. return;
  15596. }
  15597. if (!tex.transform)
  15598. {
  15599. // margin = 0.0, let it bleed a bit, shader code becomes easier
  15600. // assuming that atlas textures were made with 1-pixel padding
  15601. tex.transform = new TextureMatrix(tex, 0.0);
  15602. }
  15603. tex.transform.update();
  15604. this.uniforms.npmAlpha = tex.baseTexture.premultiplyAlpha ? 0.0 : 1.0;
  15605. this.uniforms.mask = tex;
  15606. // get _normalized sprite texture coords_ and convert them to _normalized atlas texture coords_ with `prepend`
  15607. this.uniforms.otherMatrix = filterManager.calculateSpriteMatrix(this.maskMatrix, maskSprite)
  15608. .prepend(tex.transform.mapCoord);
  15609. this.uniforms.alpha = maskSprite.worldAlpha;
  15610. this.uniforms.maskClamp = tex.transform.uClampFrame;
  15611. filterManager.applyFilter(this, input, output, clear);
  15612. };
  15613. return SpriteMaskFilter;
  15614. }(Filter));
  15615. /**
  15616. * System plugin to the renderer to manage masks.
  15617. *
  15618. * @class
  15619. * @extends PIXI.System
  15620. * @memberof PIXI.systems
  15621. */
  15622. var MaskSystem = /*@__PURE__*/(function (System) {
  15623. function MaskSystem(renderer)
  15624. {
  15625. System.call(this, renderer);
  15626. // TODO - we don't need both!
  15627. /**
  15628. * `true` if current pushed masked is scissor
  15629. * @member {boolean}
  15630. * @readonly
  15631. */
  15632. this.scissor = false;
  15633. /**
  15634. * Mask data
  15635. * @member {PIXI.Graphics}
  15636. * @readonly
  15637. */
  15638. this.scissorData = null;
  15639. /**
  15640. * Target to mask
  15641. * @member {PIXI.DisplayObject}
  15642. * @readonly
  15643. */
  15644. this.scissorRenderTarget = null;
  15645. /**
  15646. * Enable scissor
  15647. * @member {boolean}
  15648. * @readonly
  15649. */
  15650. this.enableScissor = false;
  15651. /**
  15652. * Pool of used sprite mask filters
  15653. * @member {PIXI.SpriteMaskFilter[]}
  15654. * @readonly
  15655. */
  15656. this.alphaMaskPool = [];
  15657. /**
  15658. * Current index of alpha mask pool
  15659. * @member {number}
  15660. * @default 0
  15661. * @readonly
  15662. */
  15663. this.alphaMaskIndex = 0;
  15664. }
  15665. if ( System ) { MaskSystem.__proto__ = System; }
  15666. MaskSystem.prototype = Object.create( System && System.prototype );
  15667. MaskSystem.prototype.constructor = MaskSystem;
  15668. /**
  15669. * Applies the Mask and adds it to the current filter stack.
  15670. *
  15671. * @param {PIXI.DisplayObject} target - Display Object to push the mask to
  15672. * @param {PIXI.Sprite|PIXI.Graphics} maskData - The masking data.
  15673. */
  15674. MaskSystem.prototype.push = function push (target, maskData)
  15675. {
  15676. // TODO the root check means scissor rect will not
  15677. // be used on render textures more info here:
  15678. // https://github.com/pixijs/pixi.js/pull/3545
  15679. if (maskData.isSprite)
  15680. {
  15681. this.pushSpriteMask(target, maskData);
  15682. }
  15683. else if (this.enableScissor
  15684. && !this.scissor
  15685. && this.renderer._activeRenderTarget.root
  15686. && !this.renderer.stencil.stencilMaskStack.length
  15687. && maskData.isFastRect())
  15688. {
  15689. var matrix = maskData.worldTransform;
  15690. var rot = Math.atan2(matrix.b, matrix.a);
  15691. // use the nearest degree!
  15692. rot = Math.round(rot * (180 / Math.PI));
  15693. if (rot % 90)
  15694. {
  15695. this.pushStencilMask(maskData);
  15696. }
  15697. else
  15698. {
  15699. this.pushScissorMask(target, maskData);
  15700. }
  15701. }
  15702. else
  15703. {
  15704. this.pushStencilMask(maskData);
  15705. }
  15706. };
  15707. /**
  15708. * Removes the last mask from the mask stack and doesn't return it.
  15709. *
  15710. * @param {PIXI.DisplayObject} target - Display Object to pop the mask from
  15711. * @param {PIXI.Sprite|PIXI.Graphics} maskData - The masking data.
  15712. */
  15713. MaskSystem.prototype.pop = function pop (target, maskData)
  15714. {
  15715. if (maskData.isSprite)
  15716. {
  15717. this.popSpriteMask(target, maskData);
  15718. }
  15719. else if (this.enableScissor && !this.renderer.stencil.stencilMaskStack.length)
  15720. {
  15721. this.popScissorMask(target, maskData);
  15722. }
  15723. else
  15724. {
  15725. this.popStencilMask(target, maskData);
  15726. }
  15727. };
  15728. /**
  15729. * Applies the Mask and adds it to the current filter stack.
  15730. *
  15731. * @param {PIXI.RenderTexture} target - Display Object to push the sprite mask to
  15732. * @param {PIXI.Sprite} maskData - Sprite to be used as the mask
  15733. */
  15734. MaskSystem.prototype.pushSpriteMask = function pushSpriteMask (target, maskData)
  15735. {
  15736. var alphaMaskFilter = this.alphaMaskPool[this.alphaMaskIndex];
  15737. if (!alphaMaskFilter)
  15738. {
  15739. alphaMaskFilter = this.alphaMaskPool[this.alphaMaskIndex] = [new SpriteMaskFilter(maskData)];
  15740. }
  15741. alphaMaskFilter[0].resolution = this.renderer.resolution;
  15742. alphaMaskFilter[0].maskSprite = maskData;
  15743. var stashFilterArea = target.filterArea;
  15744. target.filterArea = maskData.getBounds(true);
  15745. this.renderer.filter.push(target, alphaMaskFilter);
  15746. target.filterArea = stashFilterArea;
  15747. this.alphaMaskIndex++;
  15748. };
  15749. /**
  15750. * Removes the last filter from the filter stack and doesn't return it.
  15751. *
  15752. */
  15753. MaskSystem.prototype.popSpriteMask = function popSpriteMask ()
  15754. {
  15755. this.renderer.filter.pop();
  15756. this.alphaMaskIndex--;
  15757. };
  15758. /**
  15759. * Applies the Mask and adds it to the current filter stack.
  15760. *
  15761. * @param {PIXI.Sprite|PIXI.Graphics} maskData - The masking data.
  15762. */
  15763. MaskSystem.prototype.pushStencilMask = function pushStencilMask (maskData)
  15764. {
  15765. this.renderer.batch.flush();
  15766. this.renderer.stencil.pushStencil(maskData);
  15767. };
  15768. /**
  15769. * Removes the last filter from the filter stack and doesn't return it.
  15770. *
  15771. */
  15772. MaskSystem.prototype.popStencilMask = function popStencilMask ()
  15773. {
  15774. // this.renderer.currentRenderer.stop();
  15775. this.renderer.stencil.popStencil();
  15776. };
  15777. /**
  15778. *
  15779. * @param {PIXI.DisplayObject} target - Display Object to push the mask to
  15780. * @param {PIXI.Graphics} maskData - The masking data.
  15781. */
  15782. MaskSystem.prototype.pushScissorMask = function pushScissorMask (target, maskData)
  15783. {
  15784. maskData.renderable = true;
  15785. var renderTarget = this.renderer._activeRenderTarget;
  15786. var bounds = maskData.getBounds();
  15787. bounds.fit(renderTarget.size);
  15788. maskData.renderable = false;
  15789. this.renderer.gl.enable(this.renderer.gl.SCISSOR_TEST);
  15790. var resolution = this.renderer.resolution;
  15791. this.renderer.gl.scissor(
  15792. bounds.x * resolution,
  15793. (renderTarget.root ? renderTarget.size.height - bounds.y - bounds.height : bounds.y) * resolution,
  15794. bounds.width * resolution,
  15795. bounds.height * resolution
  15796. );
  15797. this.scissorRenderTarget = renderTarget;
  15798. this.scissorData = maskData;
  15799. this.scissor = true;
  15800. };
  15801. /**
  15802. * Pop scissor mask
  15803. *
  15804. */
  15805. MaskSystem.prototype.popScissorMask = function popScissorMask ()
  15806. {
  15807. this.scissorRenderTarget = null;
  15808. this.scissorData = null;
  15809. this.scissor = false;
  15810. // must be scissor!
  15811. var ref = this.renderer;
  15812. var gl = ref.gl;
  15813. gl.disable(gl.SCISSOR_TEST);
  15814. };
  15815. return MaskSystem;
  15816. }(System));
  15817. /**
  15818. * System plugin to the renderer to manage stencils (used for masks).
  15819. *
  15820. * @class
  15821. * @extends PIXI.System
  15822. * @memberof PIXI.systems
  15823. */
  15824. var StencilSystem = /*@__PURE__*/(function (System) {
  15825. function StencilSystem(renderer)
  15826. {
  15827. System.call(this, renderer);
  15828. /**
  15829. * The mask stack
  15830. * @member {PIXI.Graphics[]}
  15831. */
  15832. this.stencilMaskStack = [];
  15833. }
  15834. if ( System ) { StencilSystem.__proto__ = System; }
  15835. StencilSystem.prototype = Object.create( System && System.prototype );
  15836. StencilSystem.prototype.constructor = StencilSystem;
  15837. /**
  15838. * Changes the mask stack that is used by this System.
  15839. *
  15840. * @param {PIXI.Graphics[]} stencilMaskStack - The mask stack
  15841. */
  15842. StencilSystem.prototype.setMaskStack = function setMaskStack (stencilMaskStack)
  15843. {
  15844. var gl = this.renderer.gl;
  15845. if (stencilMaskStack.length !== this.stencilMaskStack.length)
  15846. {
  15847. if (stencilMaskStack.length === 0)
  15848. {
  15849. gl.disable(gl.STENCIL_TEST);
  15850. }
  15851. else
  15852. {
  15853. gl.enable(gl.STENCIL_TEST);
  15854. }
  15855. }
  15856. this.stencilMaskStack = stencilMaskStack;
  15857. };
  15858. /**
  15859. * Applies the Mask and adds it to the current stencil stack. @alvin
  15860. *
  15861. * @param {PIXI.Graphics} graphics - The mask
  15862. */
  15863. StencilSystem.prototype.pushStencil = function pushStencil (graphics)
  15864. {
  15865. var gl = this.renderer.gl;
  15866. var prevMaskCount = this.stencilMaskStack.length;
  15867. if (prevMaskCount === 0)
  15868. {
  15869. gl.enable(gl.STENCIL_TEST);
  15870. }
  15871. this.stencilMaskStack.push(graphics);
  15872. // Increment the reference stencil value where the new mask overlaps with the old ones.
  15873. gl.colorMask(false, false, false, false);
  15874. gl.stencilFunc(gl.EQUAL, prevMaskCount, this._getBitwiseMask());
  15875. gl.stencilOp(gl.KEEP, gl.KEEP, gl.INCR);
  15876. graphics.renderable = true;
  15877. graphics.render(this.renderer);
  15878. this.renderer.batch.flush();
  15879. graphics.renderable = false;
  15880. this._useCurrent();
  15881. };
  15882. /**
  15883. * Removes the last mask from the stencil stack. @alvin
  15884. */
  15885. StencilSystem.prototype.popStencil = function popStencil ()
  15886. {
  15887. var gl = this.renderer.gl;
  15888. var graphics = this.stencilMaskStack.pop();
  15889. if (this.stencilMaskStack.length === 0)
  15890. {
  15891. // the stack is empty!
  15892. gl.disable(gl.STENCIL_TEST);
  15893. gl.clear(gl.STENCIL_BUFFER_BIT);
  15894. gl.clearStencil(0);
  15895. }
  15896. else
  15897. {
  15898. // Decrement the reference stencil value where the popped mask overlaps with the other ones
  15899. gl.colorMask(false, false, false, false);
  15900. gl.stencilOp(gl.KEEP, gl.KEEP, gl.DECR);
  15901. graphics.renderable = true;
  15902. graphics.render(this.renderer);
  15903. this.renderer.batch.flush();
  15904. graphics.renderable = false;
  15905. this._useCurrent();
  15906. }
  15907. };
  15908. /**
  15909. * Setup renderer to use the current stencil data.
  15910. * @private
  15911. */
  15912. StencilSystem.prototype._useCurrent = function _useCurrent ()
  15913. {
  15914. var gl = this.renderer.gl;
  15915. gl.colorMask(true, true, true, true);
  15916. gl.stencilFunc(gl.EQUAL, this.stencilMaskStack.length, this._getBitwiseMask());
  15917. gl.stencilOp(gl.KEEP, gl.KEEP, gl.KEEP);
  15918. };
  15919. /**
  15920. * Fill 1s equal to the number of acitve stencil masks.
  15921. * @private
  15922. * @return {number} The bitwise mask.
  15923. */
  15924. StencilSystem.prototype._getBitwiseMask = function _getBitwiseMask ()
  15925. {
  15926. return (1 << this.stencilMaskStack.length) - 1;
  15927. };
  15928. /**
  15929. * Destroys the mask stack.
  15930. *
  15931. */
  15932. StencilSystem.prototype.destroy = function destroy ()
  15933. {
  15934. System.prototype.destroy.call(this, this);
  15935. this.stencilMaskStack = null;
  15936. };
  15937. return StencilSystem;
  15938. }(System));
  15939. /**
  15940. * System plugin to the renderer to manage the projection matrix.
  15941. *
  15942. * @class
  15943. * @extends PIXI.System
  15944. * @memberof PIXI.systems
  15945. */
  15946. var ProjectionSystem = /*@__PURE__*/(function (System) {
  15947. function ProjectionSystem(renderer)
  15948. {
  15949. System.call(this, renderer);
  15950. /**
  15951. * Destination frame
  15952. * @member {PIXI.Rectangle}
  15953. * @readonly
  15954. */
  15955. this.destinationFrame = null;
  15956. /**
  15957. * Source frame
  15958. * @member {PIXI.Rectangle}
  15959. * @readonly
  15960. */
  15961. this.sourceFrame = null;
  15962. /**
  15963. * Default destination frame
  15964. * @member {PIXI.Rectangle}
  15965. * @readonly
  15966. */
  15967. this.defaultFrame = null;
  15968. /**
  15969. * Project matrix
  15970. * @member {PIXI.Matrix}
  15971. * @readonly
  15972. */
  15973. this.projectionMatrix = new Matrix();
  15974. /**
  15975. * A transform that will be appended to the projection matrix
  15976. * if null, nothing will be applied
  15977. * @member {PIXI.Matrix}
  15978. */
  15979. this.transform = null;
  15980. }
  15981. if ( System ) { ProjectionSystem.__proto__ = System; }
  15982. ProjectionSystem.prototype = Object.create( System && System.prototype );
  15983. ProjectionSystem.prototype.constructor = ProjectionSystem;
  15984. /**
  15985. * Updates the projection matrix based on a projection frame (which is a rectangle)
  15986. *
  15987. * @param {PIXI.Rectangle} destinationFrame - The destination frame.
  15988. * @param {PIXI.Rectangle} sourceFrame - The source frame.
  15989. * @param {Number} resolution - Resolution
  15990. * @param {boolean} root - If is root
  15991. */
  15992. ProjectionSystem.prototype.update = function update (destinationFrame, sourceFrame, resolution, root)
  15993. {
  15994. this.destinationFrame = destinationFrame || this.destinationFrame || this.defaultFrame;
  15995. this.sourceFrame = sourceFrame || this.sourceFrame || destinationFrame;
  15996. this.calculateProjection(this.destinationFrame, this.sourceFrame, resolution, root);
  15997. if (this.transform)
  15998. {
  15999. this.projectionMatrix.append(this.transform);
  16000. }
  16001. var renderer = this.renderer;
  16002. renderer.globalUniforms.uniforms.projectionMatrix = this.projectionMatrix;
  16003. renderer.globalUniforms.update();
  16004. // this will work for now
  16005. // but would be sweet to stick and even on the global uniforms..
  16006. if (renderer.shader.shader)
  16007. {
  16008. renderer.shader.syncUniformGroup(renderer.shader.shader.uniforms.globals);
  16009. }
  16010. };
  16011. /**
  16012. * Updates the projection matrix based on a projection frame (which is a rectangle)
  16013. *
  16014. * @param {PIXI.Rectangle} destinationFrame - The destination frame.
  16015. * @param {PIXI.Rectangle} sourceFrame - The source frame.
  16016. * @param {Number} resolution - Resolution
  16017. * @param {boolean} root - If is root
  16018. */
  16019. ProjectionSystem.prototype.calculateProjection = function calculateProjection (destinationFrame, sourceFrame, resolution, root)
  16020. {
  16021. var pm = this.projectionMatrix;
  16022. // I don't think we will need this line..
  16023. // pm.identity();
  16024. if (!root)
  16025. {
  16026. pm.a = (1 / destinationFrame.width * 2) * resolution;
  16027. pm.d = (1 / destinationFrame.height * 2) * resolution;
  16028. pm.tx = -1 - (sourceFrame.x * pm.a);
  16029. pm.ty = -1 - (sourceFrame.y * pm.d);
  16030. }
  16031. else
  16032. {
  16033. pm.a = (1 / destinationFrame.width * 2) * resolution;
  16034. pm.d = (-1 / destinationFrame.height * 2) * resolution;
  16035. pm.tx = -1 - (sourceFrame.x * pm.a);
  16036. pm.ty = 1 - (sourceFrame.y * pm.d);
  16037. }
  16038. };
  16039. /**
  16040. * Sets the transform of the active render target to the given matrix
  16041. *
  16042. * @param {PIXI.Matrix} matrix - The transformation matrix
  16043. */
  16044. ProjectionSystem.prototype.setTransform = function setTransform ()// matrix)
  16045. {
  16046. // this._activeRenderTarget.transform = matrix;
  16047. };
  16048. return ProjectionSystem;
  16049. }(System));
  16050. var tempRect = new Rectangle();
  16051. /**
  16052. * System plugin to the renderer to manage render textures.
  16053. *
  16054. * Should be added after FramebufferSystem
  16055. *
  16056. * @class
  16057. * @extends PIXI.System
  16058. * @memberof PIXI.systems
  16059. */
  16060. var RenderTextureSystem = /*@__PURE__*/(function (System) {
  16061. function RenderTextureSystem(renderer)
  16062. {
  16063. System.call(this, renderer);
  16064. /**
  16065. * The clear background color as rgba
  16066. * @member {number[]}
  16067. */
  16068. this.clearColor = renderer._backgroundColorRgba;
  16069. // TODO move this property somewhere else!
  16070. /**
  16071. * List of masks for the StencilSystem
  16072. * @member {PIXI.Graphics[]}
  16073. * @readonly
  16074. */
  16075. this.defaultMaskStack = [];
  16076. // empty render texture?
  16077. /**
  16078. * Render texture
  16079. * @member {PIXI.RenderTexture}
  16080. * @readonly
  16081. */
  16082. this.current = null;
  16083. /**
  16084. * Source frame
  16085. * @member {PIXI.Rectangle}
  16086. * @readonly
  16087. */
  16088. this.sourceFrame = new Rectangle();
  16089. /**
  16090. * Destination frame
  16091. * @member {PIXI.Rectangle}
  16092. * @readonly
  16093. */
  16094. this.destinationFrame = new Rectangle();
  16095. }
  16096. if ( System ) { RenderTextureSystem.__proto__ = System; }
  16097. RenderTextureSystem.prototype = Object.create( System && System.prototype );
  16098. RenderTextureSystem.prototype.constructor = RenderTextureSystem;
  16099. /**
  16100. * Bind the current render texture
  16101. * @param {PIXI.RenderTexture} [renderTexture] - RenderTexture to bind, by default its `null`, the screen
  16102. * @param {PIXI.Rectangle} [sourceFrame] - part of screen that is mapped to the renderTexture
  16103. * @param {PIXI.Rectangle} [destinationFrame] - part of renderTexture, by default it has the same size as sourceFrame
  16104. */
  16105. RenderTextureSystem.prototype.bind = function bind (renderTexture, sourceFrame, destinationFrame)
  16106. {
  16107. if ( renderTexture === void 0 ) { renderTexture = null; }
  16108. this.current = renderTexture;
  16109. var renderer = this.renderer;
  16110. var resolution;
  16111. if (renderTexture)
  16112. {
  16113. var baseTexture = renderTexture.baseTexture;
  16114. resolution = baseTexture.resolution;
  16115. if (!destinationFrame)
  16116. {
  16117. tempRect.width = baseTexture.realWidth;
  16118. tempRect.height = baseTexture.realHeight;
  16119. destinationFrame = tempRect;
  16120. }
  16121. if (!sourceFrame)
  16122. {
  16123. sourceFrame = destinationFrame;
  16124. }
  16125. this.renderer.framebuffer.bind(baseTexture.framebuffer, destinationFrame);
  16126. this.renderer.projection.update(destinationFrame, sourceFrame, resolution, false);
  16127. this.renderer.stencil.setMaskStack(baseTexture.stencilMaskStack);
  16128. }
  16129. else
  16130. {
  16131. resolution = this.renderer.resolution;
  16132. // TODO these validation checks happen deeper down..
  16133. // thing they can be avoided..
  16134. if (!destinationFrame)
  16135. {
  16136. tempRect.width = renderer.width;
  16137. tempRect.height = renderer.height;
  16138. destinationFrame = tempRect;
  16139. }
  16140. if (!sourceFrame)
  16141. {
  16142. sourceFrame = destinationFrame;
  16143. }
  16144. renderer.framebuffer.bind(null, destinationFrame);
  16145. // TODO store this..
  16146. this.renderer.projection.update(destinationFrame, sourceFrame, resolution, true);
  16147. this.renderer.stencil.setMaskStack(this.defaultMaskStack);
  16148. }
  16149. this.sourceFrame.copyFrom(sourceFrame);
  16150. this.destinationFrame.x = destinationFrame.x / resolution;
  16151. this.destinationFrame.y = destinationFrame.y / resolution;
  16152. this.destinationFrame.width = destinationFrame.width / resolution;
  16153. this.destinationFrame.height = destinationFrame.height / resolution;
  16154. if (sourceFrame === destinationFrame)
  16155. {
  16156. this.sourceFrame.copyFrom(this.destinationFrame);
  16157. }
  16158. };
  16159. /**
  16160. * Erases the render texture and fills the drawing area with a colour
  16161. *
  16162. * @param {number[]} [clearColor] - The color as rgba, default to use the renderer backgroundColor
  16163. * @return {PIXI.Renderer} Returns itself.
  16164. */
  16165. RenderTextureSystem.prototype.clear = function clear (clearColor)
  16166. {
  16167. if (this.current)
  16168. {
  16169. clearColor = clearColor || this.current.baseTexture.clearColor;
  16170. }
  16171. else
  16172. {
  16173. clearColor = clearColor || this.clearColor;
  16174. }
  16175. this.renderer.framebuffer.clear(clearColor[0], clearColor[1], clearColor[2], clearColor[3]);
  16176. };
  16177. RenderTextureSystem.prototype.resize = function resize ()// screenWidth, screenHeight)
  16178. {
  16179. // resize the root only!
  16180. this.bind(null);
  16181. };
  16182. /**
  16183. * Resets renderTexture state
  16184. */
  16185. RenderTextureSystem.prototype.reset = function reset ()
  16186. {
  16187. this.bind(null);
  16188. };
  16189. return RenderTextureSystem;
  16190. }(System));
  16191. /**
  16192. * Helper class to create a WebGL Program
  16193. *
  16194. * @class
  16195. * @memberof PIXI
  16196. */
  16197. var GLProgram = function GLProgram(program, uniformData)
  16198. {
  16199. /**
  16200. * The shader program
  16201. *
  16202. * @member {WebGLProgram}
  16203. */
  16204. this.program = program;
  16205. /**
  16206. * holds the uniform data which contains uniform locations
  16207. * and current uniform values used for caching and preventing unneeded GPU commands
  16208. * @member {Object}
  16209. */
  16210. this.uniformData = uniformData;
  16211. /**
  16212. * uniformGroups holds the various upload functions for the shader. Each uniform group
  16213. * and program have a unique upload function generated.
  16214. * @member {Object}
  16215. */
  16216. this.uniformGroups = {};
  16217. };
  16218. /**
  16219. * Destroys this program
  16220. */
  16221. GLProgram.prototype.destroy = function destroy ()
  16222. {
  16223. this.uniformData = null;
  16224. this.uniformGroups = null;
  16225. this.program = null;
  16226. };
  16227. var UID$4 = 0;
  16228. /**
  16229. * System plugin to the renderer to manage shaders.
  16230. *
  16231. * @class
  16232. * @memberof PIXI.systems
  16233. * @extends PIXI.System
  16234. */
  16235. var ShaderSystem = /*@__PURE__*/(function (System) {
  16236. function ShaderSystem(renderer)
  16237. {
  16238. System.call(this, renderer);
  16239. // Validation check that this environment support `new Function`
  16240. this.systemCheck();
  16241. /**
  16242. * The current WebGL rendering context
  16243. *
  16244. * @member {WebGLRenderingContext}
  16245. */
  16246. this.gl = null;
  16247. this.shader = null;
  16248. this.program = null;
  16249. /**
  16250. * Cache to holds the generated functions. Stored against UniformObjects unique signature
  16251. * @type {Object}
  16252. * @private
  16253. */
  16254. this.cache = {};
  16255. this.id = UID$4++;
  16256. }
  16257. if ( System ) { ShaderSystem.__proto__ = System; }
  16258. ShaderSystem.prototype = Object.create( System && System.prototype );
  16259. ShaderSystem.prototype.constructor = ShaderSystem;
  16260. /**
  16261. * Overrideable function by `@pixi/unsafe-eval` to silence
  16262. * throwing an error if platform doesn't support unsafe-evals.
  16263. *
  16264. * @private
  16265. */
  16266. ShaderSystem.prototype.systemCheck = function systemCheck ()
  16267. {
  16268. if (!unsafeEvalSupported())
  16269. {
  16270. throw new Error('Current environment does not allow unsafe-eval, '
  16271. + 'please use @pixi/unsafe-eval module to enable support.');
  16272. }
  16273. };
  16274. ShaderSystem.prototype.contextChange = function contextChange (gl)
  16275. {
  16276. this.gl = gl;
  16277. };
  16278. /**
  16279. * Changes the current shader to the one given in parameter
  16280. *
  16281. * @param {PIXI.Shader} shader - the new shader
  16282. * @param {boolean} dontSync - false if the shader should automatically sync its uniforms.
  16283. * @returns {PIXI.GLProgram} the glProgram that belongs to the shader.
  16284. */
  16285. ShaderSystem.prototype.bind = function bind (shader, dontSync)
  16286. {
  16287. shader.uniforms.globals = this.renderer.globalUniforms;
  16288. var program = shader.program;
  16289. var glProgram = program.glPrograms[this.renderer.CONTEXT_UID] || this.generateShader(shader);
  16290. this.shader = shader;
  16291. // TODO - some current Pixi plugins bypass this.. so it not safe to use yet..
  16292. if (this.program !== program)
  16293. {
  16294. this.program = program;
  16295. this.gl.useProgram(glProgram.program);
  16296. }
  16297. if (!dontSync)
  16298. {
  16299. this.syncUniformGroup(shader.uniformGroup);
  16300. }
  16301. return glProgram;
  16302. };
  16303. /**
  16304. * Uploads the uniforms values to the currently bound shader.
  16305. *
  16306. * @param {object} uniforms - the uniforms values that be applied to the current shader
  16307. */
  16308. ShaderSystem.prototype.setUniforms = function setUniforms (uniforms)
  16309. {
  16310. var shader = this.shader.program;
  16311. var glProgram = shader.glPrograms[this.renderer.CONTEXT_UID];
  16312. shader.syncUniforms(glProgram.uniformData, uniforms, this.renderer);
  16313. };
  16314. ShaderSystem.prototype.syncUniformGroup = function syncUniformGroup (group)
  16315. {
  16316. var glProgram = this.getglProgram();
  16317. if (!group.static || group.dirtyId !== glProgram.uniformGroups[group.id])
  16318. {
  16319. glProgram.uniformGroups[group.id] = group.dirtyId;
  16320. this.syncUniforms(group, glProgram);
  16321. }
  16322. };
  16323. /**
  16324. * Overrideable by the @pixi/unsafe-eval package to use static
  16325. * syncUnforms instead.
  16326. *
  16327. * @private
  16328. */
  16329. ShaderSystem.prototype.syncUniforms = function syncUniforms (group, glProgram)
  16330. {
  16331. var syncFunc = group.syncUniforms[this.shader.program.id] || this.createSyncGroups(group);
  16332. syncFunc(glProgram.uniformData, group.uniforms, this.renderer);
  16333. };
  16334. ShaderSystem.prototype.createSyncGroups = function createSyncGroups (group)
  16335. {
  16336. var id = this.getSignature(group, this.shader.program.uniformData);
  16337. if (!this.cache[id])
  16338. {
  16339. this.cache[id] = generateUniformsSync(group, this.shader.program.uniformData);
  16340. }
  16341. group.syncUniforms[this.shader.program.id] = this.cache[id];
  16342. return group.syncUniforms[this.shader.program.id];
  16343. };
  16344. /**
  16345. * Takes a uniform group and data and generates a unique signature for them.
  16346. *
  16347. * @param {PIXI.UniformGroup} group the uniform group to get signature of
  16348. * @param {Object} uniformData uniform information generated by the shader
  16349. * @returns {String} Unique signature of the uniform group
  16350. * @private
  16351. */
  16352. ShaderSystem.prototype.getSignature = function getSignature (group, uniformData)
  16353. {
  16354. var uniforms = group.uniforms;
  16355. var strings = [];
  16356. for (var i in uniforms)
  16357. {
  16358. strings.push(i);
  16359. if (uniformData[i])
  16360. {
  16361. strings.push(uniformData[i].type);
  16362. }
  16363. }
  16364. return strings.join('-');
  16365. };
  16366. /**
  16367. * Returns the underlying GLShade rof the currently bound shader.
  16368. * This can be handy for when you to have a little more control over the setting of your uniforms.
  16369. *
  16370. * @return {PIXI.GLProgram} the glProgram for the currently bound Shader for this context
  16371. */
  16372. ShaderSystem.prototype.getglProgram = function getglProgram ()
  16373. {
  16374. if (this.shader)
  16375. {
  16376. return this.shader.program.glPrograms[this.renderer.CONTEXT_UID];
  16377. }
  16378. return null;
  16379. };
  16380. /**
  16381. * Generates a glProgram version of the Shader provided.
  16382. *
  16383. * @private
  16384. * @param {PIXI.Shader} shader the shader that the glProgram will be based on.
  16385. * @return {PIXI.GLProgram} A shiny new glProgram!
  16386. */
  16387. ShaderSystem.prototype.generateShader = function generateShader (shader)
  16388. {
  16389. var gl = this.gl;
  16390. var program = shader.program;
  16391. var attribMap = {};
  16392. for (var i in program.attributeData)
  16393. {
  16394. attribMap[i] = program.attributeData[i].location;
  16395. }
  16396. var shaderProgram = compileProgram(gl, program.vertexSrc, program.fragmentSrc, attribMap);
  16397. var uniformData = {};
  16398. for (var i$1 in program.uniformData)
  16399. {
  16400. var data = program.uniformData[i$1];
  16401. uniformData[i$1] = {
  16402. location: gl.getUniformLocation(shaderProgram, i$1),
  16403. value: defaultValue(data.type, data.size),
  16404. };
  16405. }
  16406. var glProgram = new GLProgram(shaderProgram, uniformData);
  16407. program.glPrograms[this.renderer.CONTEXT_UID] = glProgram;
  16408. return glProgram;
  16409. };
  16410. /**
  16411. * Resets ShaderSystem state, does not affect WebGL state
  16412. */
  16413. ShaderSystem.prototype.reset = function reset ()
  16414. {
  16415. this.program = null;
  16416. this.shader = null;
  16417. };
  16418. /**
  16419. * Destroys this System and removes all its textures
  16420. */
  16421. ShaderSystem.prototype.destroy = function destroy ()
  16422. {
  16423. // TODO implement destroy method for ShaderSystem
  16424. this.destroyed = true;
  16425. };
  16426. return ShaderSystem;
  16427. }(System));
  16428. /**
  16429. * Maps gl blend combinations to WebGL.
  16430. *
  16431. * @memberof PIXI
  16432. * @function mapWebGLBlendModesToPixi
  16433. * @private
  16434. * @param {WebGLRenderingContext} gl - The rendering context.
  16435. * @param {number[][]} [array=[]] - The array to output into.
  16436. * @return {number[][]} Mapped modes.
  16437. */
  16438. function mapWebGLBlendModesToPixi(gl, array)
  16439. {
  16440. if ( array === void 0 ) { array = []; }
  16441. // TODO - premultiply alpha would be different.
  16442. // add a boolean for that!
  16443. array[BLEND_MODES.NORMAL] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
  16444. array[BLEND_MODES.ADD] = [gl.ONE, gl.ONE];
  16445. array[BLEND_MODES.MULTIPLY] = [gl.DST_COLOR, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
  16446. array[BLEND_MODES.SCREEN] = [gl.ONE, gl.ONE_MINUS_SRC_COLOR, gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
  16447. array[BLEND_MODES.OVERLAY] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
  16448. array[BLEND_MODES.DARKEN] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
  16449. array[BLEND_MODES.LIGHTEN] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
  16450. array[BLEND_MODES.COLOR_DODGE] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
  16451. array[BLEND_MODES.COLOR_BURN] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
  16452. array[BLEND_MODES.HARD_LIGHT] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
  16453. array[BLEND_MODES.SOFT_LIGHT] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
  16454. array[BLEND_MODES.DIFFERENCE] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
  16455. array[BLEND_MODES.EXCLUSION] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
  16456. array[BLEND_MODES.HUE] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
  16457. array[BLEND_MODES.SATURATION] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
  16458. array[BLEND_MODES.COLOR] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
  16459. array[BLEND_MODES.LUMINOSITY] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
  16460. array[BLEND_MODES.NONE] = [0, 0];
  16461. // not-premultiplied blend modes
  16462. array[BLEND_MODES.NORMAL_NPM] = [gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
  16463. array[BLEND_MODES.ADD_NPM] = [gl.SRC_ALPHA, gl.ONE, gl.ONE, gl.ONE];
  16464. array[BLEND_MODES.SCREEN_NPM] = [gl.SRC_ALPHA, gl.ONE_MINUS_SRC_COLOR, gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
  16465. // composite operations
  16466. array[BLEND_MODES.SRC_IN] = [gl.DST_ALPHA, gl.ZERO];
  16467. array[BLEND_MODES.SRC_OUT] = [gl.ONE_MINUS_DST_ALPHA, gl.ZERO];
  16468. array[BLEND_MODES.SRC_ATOP] = [gl.DST_ALPHA, gl.ONE_MINUS_SRC_ALPHA];
  16469. array[BLEND_MODES.DST_OVER] = [gl.ONE_MINUS_DST_ALPHA, gl.ONE];
  16470. array[BLEND_MODES.DST_IN] = [gl.ZERO, gl.SRC_ALPHA];
  16471. array[BLEND_MODES.DST_OUT] = [gl.ZERO, gl.ONE_MINUS_SRC_ALPHA];
  16472. array[BLEND_MODES.DST_ATOP] = [gl.ONE_MINUS_DST_ALPHA, gl.SRC_ALPHA];
  16473. // SUBTRACT from flash
  16474. array[BLEND_MODES.SUBTRACT] = [gl.ONE, gl.ONE, gl.ONE, gl.ONE, gl.FUNC_REVERSE_SUBTRACT, gl.FUNC_ADD];
  16475. return array;
  16476. }
  16477. var BLEND$1 = 0;
  16478. var OFFSET$1 = 1;
  16479. var CULLING$1 = 2;
  16480. var DEPTH_TEST$1 = 3;
  16481. var WINDING$1 = 4;
  16482. /**
  16483. * System plugin to the renderer to manage WebGL state machines.
  16484. *
  16485. * @class
  16486. * @extends PIXI.System
  16487. * @memberof PIXI.systems
  16488. */
  16489. var StateSystem = /*@__PURE__*/(function (System) {
  16490. function StateSystem(renderer)
  16491. {
  16492. System.call(this, renderer);
  16493. /**
  16494. * GL context
  16495. * @member {WebGLRenderingContext}
  16496. * @readonly
  16497. */
  16498. this.gl = null;
  16499. /**
  16500. * State ID
  16501. * @member {number}
  16502. * @readonly
  16503. */
  16504. this.stateId = 0;
  16505. /**
  16506. * Polygon offset
  16507. * @member {number}
  16508. * @readonly
  16509. */
  16510. this.polygonOffset = 0;
  16511. /**
  16512. * Blend mode
  16513. * @member {number}
  16514. * @default PIXI.BLEND_MODES.NONE
  16515. * @readonly
  16516. */
  16517. this.blendMode = BLEND_MODES.NONE;
  16518. /**
  16519. * Whether current blend equation is different
  16520. * @member {boolean}
  16521. * @protected
  16522. */
  16523. this._blendEq = false;
  16524. /**
  16525. * Collection of calls
  16526. * @member {function[]}
  16527. * @readonly
  16528. */
  16529. this.map = [];
  16530. // map functions for when we set state..
  16531. this.map[BLEND$1] = this.setBlend;
  16532. this.map[OFFSET$1] = this.setOffset;
  16533. this.map[CULLING$1] = this.setCullFace;
  16534. this.map[DEPTH_TEST$1] = this.setDepthTest;
  16535. this.map[WINDING$1] = this.setFrontFace;
  16536. /**
  16537. * Collection of check calls
  16538. * @member {function[]}
  16539. * @readonly
  16540. */
  16541. this.checks = [];
  16542. /**
  16543. * Default WebGL State
  16544. * @member {PIXI.State}
  16545. * @readonly
  16546. */
  16547. this.defaultState = new State();
  16548. this.defaultState.blend = true;
  16549. this.defaultState.depth = true;
  16550. }
  16551. if ( System ) { StateSystem.__proto__ = System; }
  16552. StateSystem.prototype = Object.create( System && System.prototype );
  16553. StateSystem.prototype.constructor = StateSystem;
  16554. StateSystem.prototype.contextChange = function contextChange (gl)
  16555. {
  16556. this.gl = gl;
  16557. this.blendModes = mapWebGLBlendModesToPixi(gl);
  16558. this.setState(this.defaultState);
  16559. this.reset();
  16560. };
  16561. /**
  16562. * Sets the current state
  16563. *
  16564. * @param {*} state - The state to set.
  16565. */
  16566. StateSystem.prototype.setState = function setState (state)
  16567. {
  16568. state = state || this.defaultState;
  16569. // TODO maybe to an object check? ( this.state === state )?
  16570. if (this.stateId !== state.data)
  16571. {
  16572. var diff = this.stateId ^ state.data;
  16573. var i = 0;
  16574. // order from least to most common
  16575. while (diff)
  16576. {
  16577. if (diff & 1)
  16578. {
  16579. // state change!
  16580. this.map[i].call(this, !!(state.data & (1 << i)));
  16581. }
  16582. diff = diff >> 1;
  16583. i++;
  16584. }
  16585. this.stateId = state.data;
  16586. }
  16587. // based on the above settings we check for specific modes..
  16588. // for example if blend is active we check and set the blend modes
  16589. // or of polygon offset is active we check the poly depth.
  16590. for (var i$1 = 0; i$1 < this.checks.length; i$1++)
  16591. {
  16592. this.checks[i$1](this, state);
  16593. }
  16594. };
  16595. /**
  16596. * Sets the state, when previous state is unknown
  16597. *
  16598. * @param {*} state - The state to set
  16599. */
  16600. StateSystem.prototype.forceState = function forceState (state)
  16601. {
  16602. state = state || this.defaultState;
  16603. for (var i = 0; i < this.map.length; i++)
  16604. {
  16605. this.map[i].call(this, !!(state.data & (1 << i)));
  16606. }
  16607. for (var i$1 = 0; i$1 < this.checks.length; i$1++)
  16608. {
  16609. this.checks[i$1](this, state);
  16610. }
  16611. this.stateId = state.data;
  16612. };
  16613. /**
  16614. * Enables or disabled blending.
  16615. *
  16616. * @param {boolean} value - Turn on or off webgl blending.
  16617. */
  16618. StateSystem.prototype.setBlend = function setBlend (value)
  16619. {
  16620. this.updateCheck(StateSystem.checkBlendMode, value);
  16621. this.gl[value ? 'enable' : 'disable'](this.gl.BLEND);
  16622. };
  16623. /**
  16624. * Enables or disable polygon offset fill
  16625. *
  16626. * @param {boolean} value - Turn on or off webgl polygon offset testing.
  16627. */
  16628. StateSystem.prototype.setOffset = function setOffset (value)
  16629. {
  16630. this.updateCheck(StateSystem.checkPolygonOffset, value);
  16631. this.gl[value ? 'enable' : 'disable'](this.gl.POLYGON_OFFSET_FILL);
  16632. };
  16633. /**
  16634. * Sets whether to enable or disable depth test.
  16635. *
  16636. * @param {boolean} value - Turn on or off webgl depth testing.
  16637. */
  16638. StateSystem.prototype.setDepthTest = function setDepthTest (value)
  16639. {
  16640. this.gl[value ? 'enable' : 'disable'](this.gl.DEPTH_TEST);
  16641. };
  16642. /**
  16643. * Sets whether to enable or disable cull face.
  16644. *
  16645. * @param {boolean} value - Turn on or off webgl cull face.
  16646. */
  16647. StateSystem.prototype.setCullFace = function setCullFace (value)
  16648. {
  16649. this.gl[value ? 'enable' : 'disable'](this.gl.CULL_FACE);
  16650. };
  16651. /**
  16652. * Sets the gl front face.
  16653. *
  16654. * @param {boolean} value - true is clockwise and false is counter-clockwise
  16655. */
  16656. StateSystem.prototype.setFrontFace = function setFrontFace (value)
  16657. {
  16658. this.gl.frontFace(this.gl[value ? 'CW' : 'CCW']);
  16659. };
  16660. /**
  16661. * Sets the blend mode.
  16662. *
  16663. * @param {number} value - The blend mode to set to.
  16664. */
  16665. StateSystem.prototype.setBlendMode = function setBlendMode (value)
  16666. {
  16667. if (value === this.blendMode)
  16668. {
  16669. return;
  16670. }
  16671. this.blendMode = value;
  16672. var mode = this.blendModes[value];
  16673. var gl = this.gl;
  16674. if (mode.length === 2)
  16675. {
  16676. gl.blendFunc(mode[0], mode[1]);
  16677. }
  16678. else
  16679. {
  16680. gl.blendFuncSeparate(mode[0], mode[1], mode[2], mode[3]);
  16681. }
  16682. if (mode.length === 6)
  16683. {
  16684. this._blendEq = true;
  16685. gl.blendEquationSeparate(mode[4], mode[5]);
  16686. }
  16687. else if (this._blendEq)
  16688. {
  16689. this._blendEq = false;
  16690. gl.blendEquationSeparate(gl.FUNC_ADD, gl.FUNC_ADD);
  16691. }
  16692. };
  16693. /**
  16694. * Sets the polygon offset.
  16695. *
  16696. * @param {number} value - the polygon offset
  16697. * @param {number} scale - the polygon offset scale
  16698. */
  16699. StateSystem.prototype.setPolygonOffset = function setPolygonOffset (value, scale)
  16700. {
  16701. this.gl.polygonOffset(value, scale);
  16702. };
  16703. // used
  16704. /**
  16705. * Resets all the logic and disables the vaos
  16706. */
  16707. StateSystem.prototype.reset = function reset ()
  16708. {
  16709. this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL, false);
  16710. this.forceState(0);
  16711. this._blendEq = true;
  16712. this.blendMode = -1;
  16713. this.setBlendMode(0);
  16714. };
  16715. /**
  16716. * checks to see which updates should be checked based on which settings have been activated.
  16717. * For example, if blend is enabled then we should check the blend modes each time the state is changed
  16718. * or if polygon fill is activated then we need to check if the polygon offset changes.
  16719. * The idea is that we only check what we have too.
  16720. *
  16721. * @param {Function} func the checking function to add or remove
  16722. * @param {boolean} value should the check function be added or removed.
  16723. */
  16724. StateSystem.prototype.updateCheck = function updateCheck (func, value)
  16725. {
  16726. var index = this.checks.indexOf(func);
  16727. if (value && index === -1)
  16728. {
  16729. this.checks.push(func);
  16730. }
  16731. else if (!value && index !== -1)
  16732. {
  16733. this.checks.splice(index, 1);
  16734. }
  16735. };
  16736. /**
  16737. * A private little wrapper function that we call to check the blend mode.
  16738. *
  16739. * @static
  16740. * @private
  16741. * @param {PIXI.StateSystem} System the System to perform the state check on
  16742. * @param {PIXI.State} state the state that the blendMode will pulled from
  16743. */
  16744. StateSystem.checkBlendMode = function checkBlendMode (system, state)
  16745. {
  16746. system.setBlendMode(state.blendMode);
  16747. };
  16748. /**
  16749. * A private little wrapper function that we call to check the polygon offset.
  16750. *
  16751. * @static
  16752. * @private
  16753. * @param {PIXI.StateSystem} System the System to perform the state check on
  16754. * @param {PIXI.State} state the state that the blendMode will pulled from
  16755. */
  16756. StateSystem.checkPolygonOffset = function checkPolygonOffset (system, state)
  16757. {
  16758. system.setPolygonOffset(state.polygonOffset, 0);
  16759. };
  16760. return StateSystem;
  16761. }(System));
  16762. /**
  16763. * System plugin to the renderer to manage texture garbage collection on the GPU,
  16764. * ensuring that it does not get clogged up with textures that are no longer being used.
  16765. *
  16766. * @class
  16767. * @memberof PIXI.systems
  16768. * @extends PIXI.System
  16769. */
  16770. var TextureGCSystem = /*@__PURE__*/(function (System) {
  16771. function TextureGCSystem(renderer)
  16772. {
  16773. System.call(this, renderer);
  16774. /**
  16775. * Count
  16776. * @member {number}
  16777. * @readonly
  16778. */
  16779. this.count = 0;
  16780. /**
  16781. * Check count
  16782. * @member {number}
  16783. * @readonly
  16784. */
  16785. this.checkCount = 0;
  16786. /**
  16787. * Maximum idle time, in seconds
  16788. * @member {number}
  16789. * @see PIXI.settings.GC_MAX_IDLE
  16790. */
  16791. this.maxIdle = settings.GC_MAX_IDLE;
  16792. /**
  16793. * Maximum number of itesm to check
  16794. * @member {number}
  16795. * @see PIXI.settings.GC_MAX_CHECK_COUNT
  16796. */
  16797. this.checkCountMax = settings.GC_MAX_CHECK_COUNT;
  16798. /**
  16799. * Current garabage collection mode
  16800. * @member {PIXI.GC_MODES}
  16801. * @see PIXI.settings.GC_MODE
  16802. */
  16803. this.mode = settings.GC_MODE;
  16804. }
  16805. if ( System ) { TextureGCSystem.__proto__ = System; }
  16806. TextureGCSystem.prototype = Object.create( System && System.prototype );
  16807. TextureGCSystem.prototype.constructor = TextureGCSystem;
  16808. /**
  16809. * Checks to see when the last time a texture was used
  16810. * if the texture has not been used for a specified amount of time it will be removed from the GPU
  16811. */
  16812. TextureGCSystem.prototype.postrender = function postrender ()
  16813. {
  16814. this.count++;
  16815. if (this.mode === GC_MODES.MANUAL)
  16816. {
  16817. return;
  16818. }
  16819. this.checkCount++;
  16820. if (this.checkCount > this.checkCountMax)
  16821. {
  16822. this.checkCount = 0;
  16823. this.run();
  16824. }
  16825. };
  16826. /**
  16827. * Checks to see when the last time a texture was used
  16828. * if the texture has not been used for a specified amount of time it will be removed from the GPU
  16829. */
  16830. TextureGCSystem.prototype.run = function run ()
  16831. {
  16832. var tm = this.renderer.texture;
  16833. var managedTextures = tm.managedTextures;
  16834. var wasRemoved = false;
  16835. for (var i = 0; i < managedTextures.length; i++)
  16836. {
  16837. var texture = managedTextures[i];
  16838. // only supports non generated textures at the moment!
  16839. if (!texture.framebuffer && this.count - texture.touched > this.maxIdle)
  16840. {
  16841. tm.destroyTexture(texture, true);
  16842. managedTextures[i] = null;
  16843. wasRemoved = true;
  16844. }
  16845. }
  16846. if (wasRemoved)
  16847. {
  16848. var j = 0;
  16849. for (var i$1 = 0; i$1 < managedTextures.length; i$1++)
  16850. {
  16851. if (managedTextures[i$1] !== null)
  16852. {
  16853. managedTextures[j++] = managedTextures[i$1];
  16854. }
  16855. }
  16856. managedTextures.length = j;
  16857. }
  16858. };
  16859. /**
  16860. * Removes all the textures within the specified displayObject and its children from the GPU
  16861. *
  16862. * @param {PIXI.DisplayObject} displayObject - the displayObject to remove the textures from.
  16863. */
  16864. TextureGCSystem.prototype.unload = function unload (displayObject)
  16865. {
  16866. var tm = this.renderer.textureSystem;
  16867. // only destroy non generated textures
  16868. if (displayObject._texture && displayObject._texture._glRenderTargets)
  16869. {
  16870. tm.destroyTexture(displayObject._texture);
  16871. }
  16872. for (var i = displayObject.children.length - 1; i >= 0; i--)
  16873. {
  16874. this.unload(displayObject.children[i]);
  16875. }
  16876. };
  16877. return TextureGCSystem;
  16878. }(System));
  16879. /**
  16880. * Internal texture for WebGL context
  16881. * @class
  16882. * @memberof PIXI
  16883. */
  16884. var GLTexture = function GLTexture(texture)
  16885. {
  16886. /**
  16887. * The WebGL texture
  16888. * @member {WebGLTexture}
  16889. */
  16890. this.texture = texture;
  16891. this.width = -1;
  16892. this.height = -1;
  16893. /**
  16894. * Texture contents dirty flag
  16895. * @member {number}
  16896. */
  16897. this.dirtyId = -1;
  16898. /**
  16899. * Texture style dirty flag
  16900. * @member {number}
  16901. */
  16902. this.dirtyStyleId = -1;
  16903. /**
  16904. * Whether mip levels has to be generated
  16905. * @member {boolean}
  16906. */
  16907. this.mipmap = false;
  16908. /**
  16909. * WrapMode copied from baseTexture
  16910. * @member {number}
  16911. */
  16912. this.wrapMode = 33071;
  16913. };
  16914. /**
  16915. * System plugin to the renderer to manage textures.
  16916. *
  16917. * @class
  16918. * @extends PIXI.System
  16919. * @memberof PIXI.systems
  16920. */
  16921. var TextureSystem = /*@__PURE__*/(function (System) {
  16922. function TextureSystem(renderer)
  16923. {
  16924. System.call(this, renderer);
  16925. // TODO set to max textures...
  16926. /**
  16927. * Bound textures
  16928. * @member {PIXI.BaseTexture[]}
  16929. * @readonly
  16930. */
  16931. this.boundTextures = [];
  16932. /**
  16933. * Current location
  16934. * @member {number}
  16935. * @readonly
  16936. */
  16937. this.currentLocation = -1;
  16938. /**
  16939. * List of managed textures
  16940. * @member {PIXI.BaseTexture[]}
  16941. * @readonly
  16942. */
  16943. this.managedTextures = [];
  16944. /**
  16945. * Did someone temper with textures state? We'll overwrite them when we need to unbind something.
  16946. * @member {boolean}
  16947. * @private
  16948. */
  16949. this._unknownBoundTextures = false;
  16950. /**
  16951. * BaseTexture value that shows that we don't know what is bound
  16952. * @member {PIXI.BaseTexture}
  16953. * @readonly
  16954. */
  16955. this.unknownTexture = new BaseTexture();
  16956. }
  16957. if ( System ) { TextureSystem.__proto__ = System; }
  16958. TextureSystem.prototype = Object.create( System && System.prototype );
  16959. TextureSystem.prototype.constructor = TextureSystem;
  16960. /**
  16961. * Sets up the renderer context and necessary buffers.
  16962. */
  16963. TextureSystem.prototype.contextChange = function contextChange ()
  16964. {
  16965. var gl = this.gl = this.renderer.gl;
  16966. this.CONTEXT_UID = this.renderer.CONTEXT_UID;
  16967. this.webGLVersion = this.renderer.context.webGLVersion;
  16968. var maxTextures = gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS);
  16969. this.boundTextures.length = maxTextures;
  16970. for (var i = 0; i < maxTextures; i++)
  16971. {
  16972. this.boundTextures[i] = null;
  16973. }
  16974. // TODO move this.. to a nice make empty textures class..
  16975. this.emptyTextures = {};
  16976. var emptyTexture2D = new GLTexture(gl.createTexture());
  16977. gl.bindTexture(gl.TEXTURE_2D, emptyTexture2D.texture);
  16978. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, new Uint8Array(4));
  16979. this.emptyTextures[gl.TEXTURE_2D] = emptyTexture2D;
  16980. this.emptyTextures[gl.TEXTURE_CUBE_MAP] = new GLTexture(gl.createTexture());
  16981. gl.bindTexture(gl.TEXTURE_CUBE_MAP, this.emptyTextures[gl.TEXTURE_CUBE_MAP].texture);
  16982. for (var i$1 = 0; i$1 < 6; i$1++)
  16983. {
  16984. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + i$1, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  16985. }
  16986. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  16987. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  16988. for (var i$2 = 0; i$2 < this.boundTextures.length; i$2++)
  16989. {
  16990. this.bind(null, i$2);
  16991. }
  16992. };
  16993. /**
  16994. * Bind a texture to a specific location
  16995. *
  16996. * If you want to unbind something, please use `unbind(texture)` instead of `bind(null, textureLocation)`
  16997. *
  16998. * @param {PIXI.Texture|PIXI.BaseTexture} texture - Texture to bind
  16999. * @param {number} [location=0] - Location to bind at
  17000. */
  17001. TextureSystem.prototype.bind = function bind (texture, location)
  17002. {
  17003. if ( location === void 0 ) { location = 0; }
  17004. var ref = this;
  17005. var gl = ref.gl;
  17006. if (texture)
  17007. {
  17008. texture = texture.baseTexture || texture;
  17009. if (texture.valid)
  17010. {
  17011. texture.touched = this.renderer.textureGC.count;
  17012. var glTexture = texture._glTextures[this.CONTEXT_UID] || this.initTexture(texture);
  17013. if (this.currentLocation !== location)
  17014. {
  17015. this.currentLocation = location;
  17016. gl.activeTexture(gl.TEXTURE0 + location);
  17017. }
  17018. if (this.boundTextures[location] !== texture)
  17019. {
  17020. gl.bindTexture(texture.target, glTexture.texture);
  17021. }
  17022. if (glTexture.dirtyId !== texture.dirtyId)
  17023. {
  17024. this.updateTexture(texture);
  17025. }
  17026. this.boundTextures[location] = texture;
  17027. }
  17028. }
  17029. else
  17030. {
  17031. if (this.currentLocation !== location)
  17032. {
  17033. this.currentLocation = location;
  17034. gl.activeTexture(gl.TEXTURE0 + location);
  17035. }
  17036. gl.bindTexture(gl.TEXTURE_2D, this.emptyTextures[gl.TEXTURE_2D].texture);
  17037. this.boundTextures[location] = null;
  17038. }
  17039. };
  17040. /**
  17041. * Resets texture location and bound textures
  17042. *
  17043. * Actual `bind(null, i)` calls will be performed at next `unbind()` call
  17044. */
  17045. TextureSystem.prototype.reset = function reset ()
  17046. {
  17047. this._unknownBoundTextures = true;
  17048. this.currentLocation = -1;
  17049. for (var i = 0; i < this.boundTextures.length; i++)
  17050. {
  17051. this.boundTextures[i] = this.unknownTexture;
  17052. }
  17053. };
  17054. /**
  17055. * Unbind a texture
  17056. * @param {PIXI.Texture|PIXI.BaseTexture} texture - Texture to bind
  17057. */
  17058. TextureSystem.prototype.unbind = function unbind (texture)
  17059. {
  17060. var ref = this;
  17061. var gl = ref.gl;
  17062. var boundTextures = ref.boundTextures;
  17063. if (this._unknownBoundTextures)
  17064. {
  17065. this._unknownBoundTextures = false;
  17066. // someone changed webGL state,
  17067. // we have to be sure that our texture does not appear in multi-texture renderer samplers
  17068. for (var i = 0; i < boundTextures.length; i++)
  17069. {
  17070. if (boundTextures[i] === this.unknownTexture)
  17071. {
  17072. this.bind(null, i);
  17073. }
  17074. }
  17075. }
  17076. for (var i$1 = 0; i$1 < boundTextures.length; i$1++)
  17077. {
  17078. if (boundTextures[i$1] === texture)
  17079. {
  17080. if (this.currentLocation !== i$1)
  17081. {
  17082. gl.activeTexture(gl.TEXTURE0 + i$1);
  17083. this.currentLocation = i$1;
  17084. }
  17085. gl.bindTexture(gl.TEXTURE_2D, this.emptyTextures[texture.target].texture);
  17086. boundTextures[i$1] = null;
  17087. }
  17088. }
  17089. };
  17090. /**
  17091. * Initialize a texture
  17092. *
  17093. * @private
  17094. * @param {PIXI.BaseTexture} texture - Texture to initialize
  17095. */
  17096. TextureSystem.prototype.initTexture = function initTexture (texture)
  17097. {
  17098. var glTexture = new GLTexture(this.gl.createTexture());
  17099. // guarantee an update..
  17100. glTexture.dirtyId = -1;
  17101. texture._glTextures[this.CONTEXT_UID] = glTexture;
  17102. this.managedTextures.push(texture);
  17103. texture.on('dispose', this.destroyTexture, this);
  17104. return glTexture;
  17105. };
  17106. /**
  17107. * Update a texture
  17108. *
  17109. * @private
  17110. * @param {PIXI.BaseTexture} texture - Texture to initialize
  17111. */
  17112. TextureSystem.prototype.updateTexture = function updateTexture (texture)
  17113. {
  17114. var glTexture = texture._glTextures[this.CONTEXT_UID];
  17115. var renderer = this.renderer;
  17116. if (texture.resource && texture.resource.upload(renderer, texture, glTexture))
  17117. { ; }
  17118. else
  17119. {
  17120. // default, renderTexture-like logic
  17121. var width = texture.realWidth;
  17122. var height = texture.realHeight;
  17123. var gl = renderer.gl;
  17124. if (glTexture.width !== width
  17125. || glTexture.height !== height
  17126. || glTexture.dirtyId < 0)
  17127. {
  17128. glTexture.width = width;
  17129. glTexture.height = height;
  17130. gl.texImage2D(texture.target, 0,
  17131. texture.format,
  17132. width,
  17133. height,
  17134. 0,
  17135. texture.format,
  17136. texture.type,
  17137. null);
  17138. }
  17139. }
  17140. // lets only update what changes..
  17141. if (texture.dirtyStyleId !== glTexture.dirtyStyleId)
  17142. {
  17143. this.updateTextureStyle(texture);
  17144. }
  17145. glTexture.dirtyId = texture.dirtyId;
  17146. };
  17147. /**
  17148. * Deletes the texture from WebGL
  17149. *
  17150. * @private
  17151. * @param {PIXI.BaseTexture|PIXI.Texture} texture - the texture to destroy
  17152. * @param {boolean} [skipRemove=false] - Whether to skip removing the texture from the TextureManager.
  17153. */
  17154. TextureSystem.prototype.destroyTexture = function destroyTexture (texture, skipRemove)
  17155. {
  17156. var ref = this;
  17157. var gl = ref.gl;
  17158. texture = texture.baseTexture || texture;
  17159. if (texture._glTextures[this.CONTEXT_UID])
  17160. {
  17161. this.unbind(texture);
  17162. gl.deleteTexture(texture._glTextures[this.CONTEXT_UID].texture);
  17163. texture.off('dispose', this.destroyTexture, this);
  17164. delete texture._glTextures[this.CONTEXT_UID];
  17165. if (!skipRemove)
  17166. {
  17167. var i = this.managedTextures.indexOf(texture);
  17168. if (i !== -1)
  17169. {
  17170. removeItems(this.managedTextures, i, 1);
  17171. }
  17172. }
  17173. }
  17174. };
  17175. /**
  17176. * Update texture style such as mipmap flag
  17177. *
  17178. * @private
  17179. * @param {PIXI.BaseTexture} texture - Texture to update
  17180. */
  17181. TextureSystem.prototype.updateTextureStyle = function updateTextureStyle (texture)
  17182. {
  17183. var glTexture = texture._glTextures[this.CONTEXT_UID];
  17184. if (!glTexture)
  17185. {
  17186. return;
  17187. }
  17188. if ((texture.mipmap === MIPMAP_MODES.POW2 || this.webGLVersion !== 2) && !texture.isPowerOfTwo)
  17189. {
  17190. glTexture.mipmap = 0;
  17191. glTexture.wrapMode = WRAP_MODES.CLAMP;
  17192. }
  17193. else
  17194. {
  17195. glTexture.mipmap = texture.mipmap >= 1;
  17196. glTexture.wrapMode = texture.wrapMode;
  17197. }
  17198. if (texture.resource && texture.resource.style(this.renderer, texture, glTexture))
  17199. { ; }
  17200. else
  17201. {
  17202. this.setStyle(texture, glTexture);
  17203. }
  17204. glTexture.dirtyStyleId = texture.dirtyStyleId;
  17205. };
  17206. /**
  17207. * Set style for texture
  17208. *
  17209. * @private
  17210. * @param {PIXI.BaseTexture} texture - Texture to update
  17211. * @param {PIXI.GLTexture} glTexture
  17212. */
  17213. TextureSystem.prototype.setStyle = function setStyle (texture, glTexture)
  17214. {
  17215. var gl = this.gl;
  17216. if (glTexture.mipmap)
  17217. {
  17218. gl.generateMipmap(texture.target);
  17219. }
  17220. gl.texParameteri(texture.target, gl.TEXTURE_WRAP_S, glTexture.wrapMode);
  17221. gl.texParameteri(texture.target, gl.TEXTURE_WRAP_T, glTexture.wrapMode);
  17222. if (glTexture.mipmap)
  17223. {
  17224. /* eslint-disable max-len */
  17225. gl.texParameteri(texture.target, gl.TEXTURE_MIN_FILTER, texture.scaleMode ? gl.LINEAR_MIPMAP_LINEAR : gl.NEAREST_MIPMAP_NEAREST);
  17226. /* eslint-disable max-len */
  17227. }
  17228. else
  17229. {
  17230. gl.texParameteri(texture.target, gl.TEXTURE_MIN_FILTER, texture.scaleMode ? gl.LINEAR : gl.NEAREST);
  17231. }
  17232. gl.texParameteri(texture.target, gl.TEXTURE_MAG_FILTER, texture.scaleMode ? gl.LINEAR : gl.NEAREST);
  17233. };
  17234. return TextureSystem;
  17235. }(System));
  17236. /**
  17237. * Systems are individual components to the Renderer pipeline.
  17238. * @namespace PIXI.systems
  17239. */
  17240. var systems = ({
  17241. FilterSystem: FilterSystem,
  17242. BatchSystem: BatchSystem,
  17243. ContextSystem: ContextSystem,
  17244. FramebufferSystem: FramebufferSystem,
  17245. GeometrySystem: GeometrySystem,
  17246. MaskSystem: MaskSystem,
  17247. StencilSystem: StencilSystem,
  17248. ProjectionSystem: ProjectionSystem,
  17249. RenderTextureSystem: RenderTextureSystem,
  17250. ShaderSystem: ShaderSystem,
  17251. StateSystem: StateSystem,
  17252. TextureGCSystem: TextureGCSystem,
  17253. TextureSystem: TextureSystem
  17254. });
  17255. var tempMatrix = new Matrix();
  17256. /**
  17257. * The AbstractRenderer is the base for a PixiJS Renderer. It is extended by the {@link PIXI.CanvasRenderer}
  17258. * and {@link PIXI.Renderer} which can be used for rendering a PixiJS scene.
  17259. *
  17260. * @abstract
  17261. * @class
  17262. * @extends PIXI.utils.EventEmitter
  17263. * @memberof PIXI
  17264. */
  17265. var AbstractRenderer = /*@__PURE__*/(function (EventEmitter) {
  17266. function AbstractRenderer(system, options)
  17267. {
  17268. EventEmitter.call(this);
  17269. // Add the default render options
  17270. options = Object.assign({}, settings.RENDER_OPTIONS, options);
  17271. // Deprecation notice for renderer roundPixels option
  17272. if (options.roundPixels)
  17273. {
  17274. settings.ROUND_PIXELS = options.roundPixels;
  17275. deprecation('5.0.0', 'Renderer roundPixels option is deprecated, please use PIXI.settings.ROUND_PIXELS', 2);
  17276. }
  17277. /**
  17278. * The supplied constructor options.
  17279. *
  17280. * @member {Object}
  17281. * @readOnly
  17282. */
  17283. this.options = options;
  17284. /**
  17285. * The type of the renderer.
  17286. *
  17287. * @member {number}
  17288. * @default PIXI.RENDERER_TYPE.UNKNOWN
  17289. * @see PIXI.RENDERER_TYPE
  17290. */
  17291. this.type = RENDERER_TYPE.UNKNOWN;
  17292. /**
  17293. * Measurements of the screen. (0, 0, screenWidth, screenHeight).
  17294. *
  17295. * Its safe to use as filterArea or hitArea for the whole stage.
  17296. *
  17297. * @member {PIXI.Rectangle}
  17298. */
  17299. this.screen = new Rectangle(0, 0, options.width, options.height);
  17300. /**
  17301. * The canvas element that everything is drawn to.
  17302. *
  17303. * @member {HTMLCanvasElement}
  17304. */
  17305. this.view = options.view || document.createElement('canvas');
  17306. /**
  17307. * The resolution / device pixel ratio of the renderer.
  17308. *
  17309. * @member {number}
  17310. * @default 1
  17311. */
  17312. this.resolution = options.resolution || settings.RESOLUTION;
  17313. /**
  17314. * Whether the render view is transparent.
  17315. *
  17316. * @member {boolean}
  17317. */
  17318. this.transparent = options.transparent;
  17319. /**
  17320. * Whether CSS dimensions of canvas view should be resized to screen dimensions automatically.
  17321. *
  17322. * @member {boolean}
  17323. */
  17324. this.autoDensity = options.autoDensity || options.autoResize || false;
  17325. // autoResize is deprecated, provides fallback support
  17326. /**
  17327. * The value of the preserveDrawingBuffer flag affects whether or not the contents of
  17328. * the stencil buffer is retained after rendering.
  17329. *
  17330. * @member {boolean}
  17331. */
  17332. this.preserveDrawingBuffer = options.preserveDrawingBuffer;
  17333. /**
  17334. * This sets if the CanvasRenderer will clear the canvas or not before the new render pass.
  17335. * If the scene is NOT transparent PixiJS will use a canvas sized fillRect operation every
  17336. * frame to set the canvas background color. If the scene is transparent PixiJS will use clearRect
  17337. * to clear the canvas every frame. Disable this by setting this to false. For example, if
  17338. * your game has a canvas filling background image you often don't need this set.
  17339. *
  17340. * @member {boolean}
  17341. * @default
  17342. */
  17343. this.clearBeforeRender = options.clearBeforeRender;
  17344. /**
  17345. * The background color as a number.
  17346. *
  17347. * @member {number}
  17348. * @protected
  17349. */
  17350. this._backgroundColor = 0x000000;
  17351. /**
  17352. * The background color as an [R, G, B] array.
  17353. *
  17354. * @member {number[]}
  17355. * @protected
  17356. */
  17357. this._backgroundColorRgba = [0, 0, 0, 0];
  17358. /**
  17359. * The background color as a string.
  17360. *
  17361. * @member {string}
  17362. * @protected
  17363. */
  17364. this._backgroundColorString = '#000000';
  17365. this.backgroundColor = options.backgroundColor || this._backgroundColor; // run bg color setter
  17366. /**
  17367. * This temporary display object used as the parent of the currently being rendered item.
  17368. *
  17369. * @member {PIXI.DisplayObject}
  17370. * @protected
  17371. */
  17372. this._tempDisplayObjectParent = new Container();
  17373. /**
  17374. * The last root object that the renderer tried to render.
  17375. *
  17376. * @member {PIXI.DisplayObject}
  17377. * @protected
  17378. */
  17379. this._lastObjectRendered = this._tempDisplayObjectParent;
  17380. /**
  17381. * Collection of plugins.
  17382. * @readonly
  17383. * @member {object}
  17384. */
  17385. this.plugins = {};
  17386. }
  17387. if ( EventEmitter ) { AbstractRenderer.__proto__ = EventEmitter; }
  17388. AbstractRenderer.prototype = Object.create( EventEmitter && EventEmitter.prototype );
  17389. AbstractRenderer.prototype.constructor = AbstractRenderer;
  17390. var prototypeAccessors = { width: { configurable: true },height: { configurable: true },backgroundColor: { configurable: true } };
  17391. /**
  17392. * Initialize the plugins.
  17393. *
  17394. * @protected
  17395. * @param {object} staticMap - The dictionary of statically saved plugins.
  17396. */
  17397. AbstractRenderer.prototype.initPlugins = function initPlugins (staticMap)
  17398. {
  17399. for (var o in staticMap)
  17400. {
  17401. this.plugins[o] = new (staticMap[o])(this);
  17402. }
  17403. };
  17404. /**
  17405. * Same as view.width, actual number of pixels in the canvas by horizontal.
  17406. *
  17407. * @member {number}
  17408. * @readonly
  17409. * @default 800
  17410. */
  17411. prototypeAccessors.width.get = function ()
  17412. {
  17413. return this.view.width;
  17414. };
  17415. /**
  17416. * Same as view.height, actual number of pixels in the canvas by vertical.
  17417. *
  17418. * @member {number}
  17419. * @readonly
  17420. * @default 600
  17421. */
  17422. prototypeAccessors.height.get = function ()
  17423. {
  17424. return this.view.height;
  17425. };
  17426. /**
  17427. * Resizes the screen and canvas to the specified width and height.
  17428. * Canvas dimensions are multiplied by resolution.
  17429. *
  17430. * @param {number} screenWidth - The new width of the screen.
  17431. * @param {number} screenHeight - The new height of the screen.
  17432. */
  17433. AbstractRenderer.prototype.resize = function resize (screenWidth, screenHeight)
  17434. {
  17435. this.screen.width = screenWidth;
  17436. this.screen.height = screenHeight;
  17437. this.view.width = screenWidth * this.resolution;
  17438. this.view.height = screenHeight * this.resolution;
  17439. if (this.autoDensity)
  17440. {
  17441. this.view.style.width = screenWidth + "px";
  17442. this.view.style.height = screenHeight + "px";
  17443. }
  17444. };
  17445. /**
  17446. * Useful function that returns a texture of the display object that can then be used to create sprites
  17447. * This can be quite useful if your displayObject is complicated and needs to be reused multiple times.
  17448. *
  17449. * @param {PIXI.DisplayObject} displayObject - The displayObject the object will be generated from.
  17450. * @param {number} scaleMode - Should be one of the scaleMode consts.
  17451. * @param {number} resolution - The resolution / device pixel ratio of the texture being generated.
  17452. * @param {PIXI.Rectangle} [region] - The region of the displayObject, that shall be rendered,
  17453. * if no region is specified, defaults to the local bounds of the displayObject.
  17454. * @return {PIXI.Texture} A texture of the graphics object.
  17455. */
  17456. AbstractRenderer.prototype.generateTexture = function generateTexture (displayObject, scaleMode, resolution, region)
  17457. {
  17458. region = region || displayObject.getLocalBounds();
  17459. // minimum texture size is 1x1, 0x0 will throw an error
  17460. if (region.width === 0) { region.width = 1; }
  17461. if (region.height === 0) { region.height = 1; }
  17462. var renderTexture = RenderTexture.create(region.width | 0, region.height | 0, scaleMode, resolution);
  17463. tempMatrix.tx = -region.x;
  17464. tempMatrix.ty = -region.y;
  17465. this.render(displayObject, renderTexture, false, tempMatrix, !!displayObject.parent);
  17466. return renderTexture;
  17467. };
  17468. /**
  17469. * Removes everything from the renderer and optionally removes the Canvas DOM element.
  17470. *
  17471. * @param {boolean} [removeView=false] - Removes the Canvas element from the DOM.
  17472. */
  17473. AbstractRenderer.prototype.destroy = function destroy (removeView)
  17474. {
  17475. for (var o in this.plugins)
  17476. {
  17477. this.plugins[o].destroy();
  17478. this.plugins[o] = null;
  17479. }
  17480. if (removeView && this.view.parentNode)
  17481. {
  17482. this.view.parentNode.removeChild(this.view);
  17483. }
  17484. this.plugins = null;
  17485. this.type = RENDERER_TYPE.UNKNOWN;
  17486. this.view = null;
  17487. this.screen = null;
  17488. this.resolution = 0;
  17489. this.transparent = false;
  17490. this.autoDensity = false;
  17491. this.blendModes = null;
  17492. this.options = null;
  17493. this.preserveDrawingBuffer = false;
  17494. this.clearBeforeRender = false;
  17495. this._backgroundColor = 0;
  17496. this._backgroundColorRgba = null;
  17497. this._backgroundColorString = null;
  17498. this._tempDisplayObjectParent = null;
  17499. this._lastObjectRendered = null;
  17500. };
  17501. /**
  17502. * The background color to fill if not transparent
  17503. *
  17504. * @member {number}
  17505. */
  17506. prototypeAccessors.backgroundColor.get = function ()
  17507. {
  17508. return this._backgroundColor;
  17509. };
  17510. prototypeAccessors.backgroundColor.set = function (value) // eslint-disable-line require-jsdoc
  17511. {
  17512. this._backgroundColor = value;
  17513. this._backgroundColorString = hex2string(value);
  17514. hex2rgb(value, this._backgroundColorRgba);
  17515. };
  17516. Object.defineProperties( AbstractRenderer.prototype, prototypeAccessors );
  17517. return AbstractRenderer;
  17518. }(eventemitter3));
  17519. /**
  17520. * The Renderer draws the scene and all its content onto a WebGL enabled canvas.
  17521. *
  17522. * This renderer should be used for browsers that support WebGL.
  17523. *
  17524. * This renderer works by automatically managing WebGLBatchesm, so no need for Sprite Batches or Sprite Clouds.
  17525. * Don't forget to add the view to your DOM or you will not see anything!
  17526. *
  17527. * @class
  17528. * @memberof PIXI
  17529. * @extends PIXI.AbstractRenderer
  17530. */
  17531. var Renderer = /*@__PURE__*/(function (AbstractRenderer) {
  17532. function Renderer(options)
  17533. {
  17534. if ( options === void 0 ) { options = {}; }
  17535. AbstractRenderer.call(this, 'WebGL', options);
  17536. // the options will have been modified here in the super constructor with pixi's default settings..
  17537. options = this.options;
  17538. /**
  17539. * The type of this renderer as a standardized const
  17540. *
  17541. * @member {number}
  17542. * @see PIXI.RENDERER_TYPE
  17543. */
  17544. this.type = RENDERER_TYPE.WEBGL;
  17545. // this will be set by the contextSystem (this.context)
  17546. this.gl = null;
  17547. this.CONTEXT_UID = 0;
  17548. // TODO legacy!
  17549. /**
  17550. * Internal signal instances of **runner**, these
  17551. * are assigned to each system created.
  17552. * @see PIXI.Runner
  17553. * @name PIXI.Renderer#runners
  17554. * @private
  17555. * @type {object}
  17556. * @readonly
  17557. * @property {PIXI.Runner} destroy - Destroy runner
  17558. * @property {PIXI.Runner} contextChange - Context change runner
  17559. * @property {PIXI.Runner} reset - Reset runner
  17560. * @property {PIXI.Runner} update - Update runner
  17561. * @property {PIXI.Runner} postrender - Post-render runner
  17562. * @property {PIXI.Runner} prerender - Pre-render runner
  17563. * @property {PIXI.Runner} resize - Resize runner
  17564. */
  17565. this.runners = {
  17566. destroy: new Runner('destroy'),
  17567. contextChange: new Runner('contextChange', 1),
  17568. reset: new Runner('reset'),
  17569. update: new Runner('update'),
  17570. postrender: new Runner('postrender'),
  17571. prerender: new Runner('prerender'),
  17572. resize: new Runner('resize', 2),
  17573. };
  17574. /**
  17575. * Global uniforms
  17576. * @member {PIXI.UniformGroup}
  17577. */
  17578. this.globalUniforms = new UniformGroup({
  17579. projectionMatrix: new Matrix(),
  17580. }, true);
  17581. /**
  17582. * Mask system instance
  17583. * @member {PIXI.systems.MaskSystem} mask
  17584. * @memberof PIXI.Renderer#
  17585. * @readonly
  17586. */
  17587. this.addSystem(MaskSystem, 'mask')
  17588. /**
  17589. * Context system instance
  17590. * @member {PIXI.systems.ContextSystem} context
  17591. * @memberof PIXI.Renderer#
  17592. * @readonly
  17593. */
  17594. .addSystem(ContextSystem, 'context')
  17595. /**
  17596. * State system instance
  17597. * @member {PIXI.systems.StateSystem} state
  17598. * @memberof PIXI.Renderer#
  17599. * @readonly
  17600. */
  17601. .addSystem(StateSystem, 'state')
  17602. /**
  17603. * Shader system instance
  17604. * @member {PIXI.systems.ShaderSystem} shader
  17605. * @memberof PIXI.Renderer#
  17606. * @readonly
  17607. */
  17608. .addSystem(ShaderSystem, 'shader')
  17609. /**
  17610. * Texture system instance
  17611. * @member {PIXI.systems.TextureSystem} texture
  17612. * @memberof PIXI.Renderer#
  17613. * @readonly
  17614. */
  17615. .addSystem(TextureSystem, 'texture')
  17616. /**
  17617. * Geometry system instance
  17618. * @member {PIXI.systems.GeometrySystem} geometry
  17619. * @memberof PIXI.Renderer#
  17620. * @readonly
  17621. */
  17622. .addSystem(GeometrySystem, 'geometry')
  17623. /**
  17624. * Framebuffer system instance
  17625. * @member {PIXI.systems.FramebufferSystem} framebuffer
  17626. * @memberof PIXI.Renderer#
  17627. * @readonly
  17628. */
  17629. .addSystem(FramebufferSystem, 'framebuffer')
  17630. /**
  17631. * Stencil system instance
  17632. * @member {PIXI.systems.StencilSystem} stencil
  17633. * @memberof PIXI.Renderer#
  17634. * @readonly
  17635. */
  17636. .addSystem(StencilSystem, 'stencil')
  17637. /**
  17638. * Projection system instance
  17639. * @member {PIXI.systems.ProjectionSystem} projection
  17640. * @memberof PIXI.Renderer#
  17641. * @readonly
  17642. */
  17643. .addSystem(ProjectionSystem, 'projection')
  17644. /**
  17645. * Texture garbage collector system instance
  17646. * @member {PIXI.systems.TextureGCSystem} textureGC
  17647. * @memberof PIXI.Renderer#
  17648. * @readonly
  17649. */
  17650. .addSystem(TextureGCSystem, 'textureGC')
  17651. /**
  17652. * Filter system instance
  17653. * @member {PIXI.systems.FilterSystem} filter
  17654. * @memberof PIXI.Renderer#
  17655. * @readonly
  17656. */
  17657. .addSystem(FilterSystem, 'filter')
  17658. /**
  17659. * RenderTexture system instance
  17660. * @member {PIXI.systems.RenderTextureSystem} renderTexture
  17661. * @memberof PIXI.Renderer#
  17662. * @readonly
  17663. */
  17664. .addSystem(RenderTextureSystem, 'renderTexture')
  17665. /**
  17666. * Batch system instance
  17667. * @member {PIXI.systems.BatchSystem} batch
  17668. * @memberof PIXI.Renderer#
  17669. * @readonly
  17670. */
  17671. .addSystem(BatchSystem, 'batch');
  17672. this.initPlugins(Renderer.__plugins);
  17673. /**
  17674. * The options passed in to create a new WebGL context.
  17675. */
  17676. if (options.context)
  17677. {
  17678. this.context.initFromContext(options.context);
  17679. }
  17680. else
  17681. {
  17682. this.context.initFromOptions({
  17683. alpha: this.transparent,
  17684. antialias: options.antialias,
  17685. premultipliedAlpha: this.transparent && this.transparent !== 'notMultiplied',
  17686. stencil: true,
  17687. preserveDrawingBuffer: options.preserveDrawingBuffer,
  17688. powerPreference: this.options.powerPreference,
  17689. });
  17690. }
  17691. /**
  17692. * Flag if we are rendering to the screen vs renderTexture
  17693. * @member {boolean}
  17694. * @readonly
  17695. * @default true
  17696. */
  17697. this.renderingToScreen = true;
  17698. sayHello(this.context.webGLVersion === 2 ? 'WebGL 2' : 'WebGL 1');
  17699. this.resize(this.options.width, this.options.height);
  17700. }
  17701. if ( AbstractRenderer ) { Renderer.__proto__ = AbstractRenderer; }
  17702. Renderer.prototype = Object.create( AbstractRenderer && AbstractRenderer.prototype );
  17703. Renderer.prototype.constructor = Renderer;
  17704. /**
  17705. * Add a new system to the renderer.
  17706. * @param {Function} ClassRef - Class reference
  17707. * @param {string} [name] - Property name for system, if not specified
  17708. * will use a static `name` property on the class itself. This
  17709. * name will be assigned as s property on the Renderer so make
  17710. * sure it doesn't collide with properties on Renderer.
  17711. * @return {PIXI.Renderer} Return instance of renderer
  17712. */
  17713. Renderer.create = function create (options)
  17714. {
  17715. if (isWebGLSupported())
  17716. {
  17717. return new Renderer(options);
  17718. }
  17719. throw new Error('WebGL unsupported in this browser, use "pixi.js-legacy" for fallback canvas2d support.');
  17720. };
  17721. Renderer.prototype.addSystem = function addSystem (ClassRef, name)
  17722. {
  17723. if (!name)
  17724. {
  17725. name = ClassRef.name;
  17726. }
  17727. var system = new ClassRef(this);
  17728. if (this[name])
  17729. {
  17730. throw new Error(("Whoops! The name \"" + name + "\" is already in use"));
  17731. }
  17732. this[name] = system;
  17733. for (var i in this.runners)
  17734. {
  17735. this.runners[i].add(system);
  17736. }
  17737. /**
  17738. * Fired after rendering finishes.
  17739. *
  17740. * @event PIXI.Renderer#postrender
  17741. */
  17742. /**
  17743. * Fired before rendering starts.
  17744. *
  17745. * @event PIXI.Renderer#prerender
  17746. */
  17747. /**
  17748. * Fired when the WebGL context is set.
  17749. *
  17750. * @event PIXI.Renderer#context
  17751. * @param {WebGLRenderingContext} gl - WebGL context.
  17752. */
  17753. return this;
  17754. };
  17755. /**
  17756. * Renders the object to its WebGL view
  17757. *
  17758. * @param {PIXI.DisplayObject} displayObject - The object to be rendered.
  17759. * @param {PIXI.RenderTexture} [renderTexture] - The render texture to render to.
  17760. * @param {boolean} [clear=true] - Should the canvas be cleared before the new render.
  17761. * @param {PIXI.Matrix} [transform] - A transform to apply to the render texture before rendering.
  17762. * @param {boolean} [skipUpdateTransform=false] - Should we skip the update transform pass?
  17763. */
  17764. Renderer.prototype.render = function render (displayObject, renderTexture, clear, transform, skipUpdateTransform)
  17765. {
  17766. // can be handy to know!
  17767. this.renderingToScreen = !renderTexture;
  17768. this.runners.prerender.run();
  17769. this.emit('prerender');
  17770. // apply a transform at a GPU level
  17771. this.projection.transform = transform;
  17772. // no point rendering if our context has been blown up!
  17773. if (this.context.isLost)
  17774. {
  17775. return;
  17776. }
  17777. if (!renderTexture)
  17778. {
  17779. this._lastObjectRendered = displayObject;
  17780. }
  17781. if (!skipUpdateTransform)
  17782. {
  17783. // update the scene graph
  17784. var cacheParent = displayObject.parent;
  17785. displayObject.parent = this._tempDisplayObjectParent;
  17786. displayObject.updateTransform();
  17787. displayObject.parent = cacheParent;
  17788. // displayObject.hitArea = //TODO add a temp hit area
  17789. }
  17790. this.renderTexture.bind(renderTexture);
  17791. this.batch.currentRenderer.start();
  17792. if (clear !== undefined ? clear : this.clearBeforeRender)
  17793. {
  17794. this.renderTexture.clear();
  17795. }
  17796. displayObject.render(this);
  17797. // apply transform..
  17798. this.batch.currentRenderer.flush();
  17799. if (renderTexture)
  17800. {
  17801. renderTexture.baseTexture.update();
  17802. }
  17803. this.runners.postrender.run();
  17804. // reset transform after render
  17805. this.projection.transform = null;
  17806. this.emit('postrender');
  17807. };
  17808. /**
  17809. * Resizes the WebGL view to the specified width and height.
  17810. *
  17811. * @param {number} screenWidth - The new width of the screen.
  17812. * @param {number} screenHeight - The new height of the screen.
  17813. */
  17814. Renderer.prototype.resize = function resize (screenWidth, screenHeight)
  17815. {
  17816. AbstractRenderer.prototype.resize.call(this, screenWidth, screenHeight);
  17817. this.runners.resize.run(screenWidth, screenHeight);
  17818. };
  17819. /**
  17820. * Resets the WebGL state so you can render things however you fancy!
  17821. *
  17822. * @return {PIXI.Renderer} Returns itself.
  17823. */
  17824. Renderer.prototype.reset = function reset ()
  17825. {
  17826. this.runners.reset.run();
  17827. return this;
  17828. };
  17829. /**
  17830. * Clear the frame buffer
  17831. */
  17832. Renderer.prototype.clear = function clear ()
  17833. {
  17834. this.framebuffer.bind();
  17835. this.framebuffer.clear();
  17836. };
  17837. /**
  17838. * Removes everything from the renderer (event listeners, spritebatch, etc...)
  17839. *
  17840. * @param {boolean} [removeView=false] - Removes the Canvas element from the DOM.
  17841. * See: https://github.com/pixijs/pixi.js/issues/2233
  17842. */
  17843. Renderer.prototype.destroy = function destroy (removeView)
  17844. {
  17845. this.runners.destroy.run();
  17846. // call base destroy
  17847. AbstractRenderer.prototype.destroy.call(this, removeView);
  17848. // TODO nullify all the managers..
  17849. this.gl = null;
  17850. };
  17851. /**
  17852. * Collection of installed plugins. These are included by default in PIXI, but can be excluded
  17853. * by creating a custom build. Consult the README for more information about creating custom
  17854. * builds and excluding plugins.
  17855. * @name PIXI.Renderer#plugins
  17856. * @type {object}
  17857. * @readonly
  17858. * @property {PIXI.accessibility.AccessibilityManager} accessibility Support tabbing interactive elements.
  17859. * @property {PIXI.extract.Extract} extract Extract image data from renderer.
  17860. * @property {PIXI.interaction.InteractionManager} interaction Handles mouse, touch and pointer events.
  17861. * @property {PIXI.prepare.Prepare} prepare Pre-render display objects.
  17862. */
  17863. /**
  17864. * Adds a plugin to the renderer.
  17865. *
  17866. * @method
  17867. * @param {string} pluginName - The name of the plugin.
  17868. * @param {Function} ctor - The constructor function or class for the plugin.
  17869. */
  17870. Renderer.registerPlugin = function registerPlugin (pluginName, ctor)
  17871. {
  17872. Renderer.__plugins = Renderer.__plugins || {};
  17873. Renderer.__plugins[pluginName] = ctor;
  17874. };
  17875. return Renderer;
  17876. }(AbstractRenderer));
  17877. /**
  17878. * This helper function will automatically detect which renderer you should be using.
  17879. * WebGL is the preferred renderer as it is a lot faster. If WebGL is not supported by
  17880. * the browser then this function will return a canvas renderer
  17881. *
  17882. * @memberof PIXI
  17883. * @function autoDetectRenderer
  17884. * @param {object} [options] - The optional renderer parameters
  17885. * @param {number} [options.width=800] - the width of the renderers view
  17886. * @param {number} [options.height=600] - the height of the renderers view
  17887. * @param {HTMLCanvasElement} [options.view] - the canvas to use as a view, optional
  17888. * @param {boolean} [options.transparent=false] - If the render view is transparent, default false
  17889. * @param {boolean} [options.autoDensity=false] - Resizes renderer view in CSS pixels to allow for
  17890. * resolutions other than 1
  17891. * @param {boolean} [options.antialias=false] - sets antialias
  17892. * @param {boolean} [options.preserveDrawingBuffer=false] - enables drawing buffer preservation, enable this if you
  17893. * need to call toDataUrl on the webgl context
  17894. * @param {number} [options.backgroundColor=0x000000] - The background color of the rendered area
  17895. * (shown if not transparent).
  17896. * @param {boolean} [options.clearBeforeRender=true] - This sets if the renderer will clear the canvas or
  17897. * not before the new render pass.
  17898. * @param {number} [options.resolution=1] - The resolution / device pixel ratio of the renderer, retina would be 2
  17899. * @param {boolean} [options.forceCanvas=false] - prevents selection of WebGL renderer, even if such is present, this
  17900. * option only is available when using **pixi.js-legacy** or **@pixi/canvas-renderer** modules, otherwise
  17901. * it is ignored.
  17902. * @param {boolean} [options.forceFXAA=false] - forces FXAA antialiasing to be used over native.
  17903. * FXAA is faster, but may not always look as great **webgl only**
  17904. * @param {string} [options.powerPreference] - Parameter passed to webgl context, set to "high-performance"
  17905. * for devices with dual graphics card **webgl only**
  17906. * @return {PIXI.Renderer|PIXI.CanvasRenderer} Returns WebGL renderer if available, otherwise CanvasRenderer
  17907. */
  17908. function autoDetectRenderer(options)
  17909. {
  17910. return Renderer.create(options);
  17911. }
  17912. var _default = "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}";
  17913. var defaultFilter = "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";
  17914. /**
  17915. * A Texture that depends on six other resources.
  17916. *
  17917. * @class
  17918. * @extends PIXI.BaseTexture
  17919. * @memberof PIXI
  17920. */
  17921. var CubeTexture = /*@__PURE__*/(function (BaseTexture) {
  17922. function CubeTexture () {
  17923. BaseTexture.apply(this, arguments);
  17924. }
  17925. if ( BaseTexture ) { CubeTexture.__proto__ = BaseTexture; }
  17926. CubeTexture.prototype = Object.create( BaseTexture && BaseTexture.prototype );
  17927. CubeTexture.prototype.constructor = CubeTexture;
  17928. CubeTexture.from = function from (resources, options)
  17929. {
  17930. return new CubeTexture(new CubeResource(resources, options));
  17931. };
  17932. return CubeTexture;
  17933. }(BaseTexture));
  17934. /**
  17935. * Geometry used to batch standard PIXI content (e.g. Mesh, Sprite, Graphics objects).
  17936. *
  17937. * @class
  17938. * @memberof PIXI
  17939. */
  17940. var BatchGeometry = /*@__PURE__*/(function (Geometry) {
  17941. function BatchGeometry(_static)
  17942. {
  17943. if ( _static === void 0 ) { _static = false; }
  17944. Geometry.call(this);
  17945. /**
  17946. * Buffer used for position, color, texture IDs
  17947. *
  17948. * @member {PIXI.Buffer}
  17949. * @protected
  17950. */
  17951. this._buffer = new Buffer(null, _static, false);
  17952. /**
  17953. * Index buffer data
  17954. *
  17955. * @member {PIXI.Buffer}
  17956. * @protected
  17957. */
  17958. this._indexBuffer = new Buffer(null, _static, true);
  17959. this.addAttribute('aVertexPosition', this._buffer, 2, false, TYPES.FLOAT)
  17960. .addAttribute('aTextureCoord', this._buffer, 2, false, TYPES.FLOAT)
  17961. .addAttribute('aColor', this._buffer, 4, true, TYPES.UNSIGNED_BYTE)
  17962. .addAttribute('aTextureId', this._buffer, 1, true, TYPES.FLOAT)
  17963. .addIndex(this._indexBuffer);
  17964. }
  17965. if ( Geometry ) { BatchGeometry.__proto__ = Geometry; }
  17966. BatchGeometry.prototype = Object.create( Geometry && Geometry.prototype );
  17967. BatchGeometry.prototype.constructor = BatchGeometry;
  17968. return BatchGeometry;
  17969. }(Geometry));
  17970. /**
  17971. * Used by the batcher to draw batches.
  17972. * Each one of these contains all information required to draw a bound geometry.
  17973. *
  17974. * @class
  17975. * @memberof PIXI
  17976. */
  17977. var BatchDrawCall = function BatchDrawCall()
  17978. {
  17979. this.textures = [];
  17980. this.ids = [];
  17981. this.blend = 0;
  17982. this.textureCount = 0;
  17983. this.start = 0;
  17984. this.size = 0;
  17985. this.type = 4;
  17986. };
  17987. /**
  17988. * Used by the BatchRenderer
  17989. *
  17990. * @class
  17991. * @memberof PIXI
  17992. */
  17993. var BatchBuffer = function BatchBuffer(size)
  17994. {
  17995. this.vertices = new ArrayBuffer(size);
  17996. /**
  17997. * View on the vertices as a Float32Array for positions
  17998. *
  17999. * @member {Float32Array}
  18000. */
  18001. this.float32View = new Float32Array(this.vertices);
  18002. /**
  18003. * View on the vertices as a Uint32Array for uvs
  18004. *
  18005. * @member {Float32Array}
  18006. */
  18007. this.uint32View = new Uint32Array(this.vertices);
  18008. };
  18009. /**
  18010. * Destroys the buffer.
  18011. *
  18012. */
  18013. BatchBuffer.prototype.destroy = function destroy ()
  18014. {
  18015. this.vertices = null;
  18016. this.float32View = null;
  18017. this.uint32View = null;
  18018. };
  18019. var vertex$1 = "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";
  18020. var fragTemplate$1 = [
  18021. 'varying vec2 vTextureCoord;',
  18022. 'varying vec4 vColor;',
  18023. 'varying float vTextureId;',
  18024. 'uniform sampler2D uSamplers[%count%];',
  18025. 'void main(void){',
  18026. 'vec4 color;',
  18027. '%forloop%',
  18028. 'gl_FragColor = color * vColor;',
  18029. '}' ].join('\n');
  18030. var defaultGroupCache = {};
  18031. var programCache = {};
  18032. function generateMultiTextureShader(gl, maxTextures)
  18033. {
  18034. if (!programCache[maxTextures])
  18035. {
  18036. var sampleValues = new Int32Array(maxTextures);
  18037. for (var i = 0; i < maxTextures; i++)
  18038. {
  18039. sampleValues[i] = i;
  18040. }
  18041. defaultGroupCache[maxTextures] = UniformGroup.from({ uSamplers: sampleValues }, true);
  18042. var fragmentSrc = fragTemplate$1;
  18043. fragmentSrc = fragmentSrc.replace(/%count%/gi, maxTextures);
  18044. fragmentSrc = fragmentSrc.replace(/%forloop%/gi, generateSampleSrc(maxTextures));
  18045. programCache[maxTextures] = new Program(vertex$1, fragmentSrc);
  18046. }
  18047. var uniforms = {
  18048. tint: new Float32Array([1, 1, 1, 1]),
  18049. translationMatrix: new Matrix(),
  18050. default: defaultGroupCache[maxTextures],
  18051. };
  18052. var shader = new Shader(programCache[maxTextures], uniforms);
  18053. return shader;
  18054. }
  18055. function generateSampleSrc(maxTextures)
  18056. {
  18057. var src = '';
  18058. src += '\n';
  18059. src += '\n';
  18060. for (var i = 0; i < maxTextures; i++)
  18061. {
  18062. if (i > 0)
  18063. {
  18064. src += '\nelse ';
  18065. }
  18066. if (i < maxTextures - 1)
  18067. {
  18068. src += "if(vTextureId < " + i + ".5)";
  18069. }
  18070. src += '\n{';
  18071. src += "\n\tcolor = texture2D(uSamplers[" + i + "], vTextureCoord);";
  18072. src += '\n}';
  18073. }
  18074. src += '\n';
  18075. src += '\n';
  18076. return src;
  18077. }
  18078. /**
  18079. * Renderer dedicated to drawing and batching sprites.
  18080. *
  18081. * @class
  18082. * @protected
  18083. * @memberof PIXI
  18084. * @extends PIXI.ObjectRenderer
  18085. */
  18086. var BatchRenderer = /*@__PURE__*/(function (ObjectRenderer) {
  18087. function BatchRenderer(renderer)
  18088. {
  18089. ObjectRenderer.call(this, renderer);
  18090. /**
  18091. * Number of values sent in the vertex buffer.
  18092. * aVertexPosition(2), aTextureCoord(1), aColor(1), aTextureId(1) = 5
  18093. *
  18094. * @member {number}
  18095. */
  18096. this.vertSize = 6;
  18097. /**
  18098. * The size of the vertex information in bytes.
  18099. *
  18100. * @member {number}
  18101. */
  18102. this.vertByteSize = this.vertSize * 4;
  18103. /**
  18104. * The number of images in the SpriteRenderer before it flushes.
  18105. *
  18106. * @member {number}
  18107. */
  18108. this.size = 2000 * 4;// settings.SPRITE_BATCH_SIZE; // 2000 is a nice balance between mobile / desktop
  18109. this.currentSize = 0;
  18110. this.currentIndexSize = 0;
  18111. // the total number of bytes in our batch
  18112. // let numVerts = this.size * 4 * this.vertByteSize;
  18113. this.attributeBuffers = {};
  18114. this.aBuffers = {};
  18115. this.iBuffers = {};
  18116. // this.defualtSpriteIndexBuffer = new Buffer(createIndicesForQuads(this.size), true, true);
  18117. /**
  18118. * Holds the defualt indices of the geometry (quads) to draw
  18119. *
  18120. * @member {Uint16Array}
  18121. */
  18122. // const indicies = createIndicesForQuads(this.size);
  18123. // this.defaultQuadIndexBuffer = new Buffer(indicies, true, true);
  18124. this.onlySprites = false;
  18125. /**
  18126. * The default shaders that is used if a sprite doesn't have a more specific one.
  18127. * there is a shader for each number of textures that can be rendered.
  18128. * These shaders will also be generated on the fly as required.
  18129. * @member {PIXI.Shader[]}
  18130. */
  18131. this.shader = null;
  18132. this.currentIndex = 0;
  18133. this.groups = [];
  18134. for (var k = 0; k < this.size / 4; k++)
  18135. {
  18136. this.groups[k] = new BatchDrawCall();
  18137. }
  18138. this.elements = [];
  18139. this.vaos = [];
  18140. this.vaoMax = 2;
  18141. this.vertexCount = 0;
  18142. this.renderer.on('prerender', this.onPrerender, this);
  18143. this.state = State.for2d();
  18144. }
  18145. if ( ObjectRenderer ) { BatchRenderer.__proto__ = ObjectRenderer; }
  18146. BatchRenderer.prototype = Object.create( ObjectRenderer && ObjectRenderer.prototype );
  18147. BatchRenderer.prototype.constructor = BatchRenderer;
  18148. /**
  18149. * Sets up the renderer context and necessary buffers.
  18150. */
  18151. BatchRenderer.prototype.contextChange = function contextChange ()
  18152. {
  18153. var gl = this.renderer.gl;
  18154. if (settings.PREFER_ENV === ENV.WEBGL_LEGACY)
  18155. {
  18156. this.MAX_TEXTURES = 1;
  18157. }
  18158. else
  18159. {
  18160. // step 1: first check max textures the GPU can handle.
  18161. this.MAX_TEXTURES = Math.min(gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS), settings.SPRITE_MAX_TEXTURES);
  18162. // step 2: check the maximum number of if statements the shader can have too..
  18163. this.MAX_TEXTURES = checkMaxIfStatementsInShader(this.MAX_TEXTURES, gl);
  18164. }
  18165. // generate generateMultiTextureProgram, may be a better move?
  18166. this.shader = generateMultiTextureShader(gl, this.MAX_TEXTURES);
  18167. // we use the second shader as the first one depending on your browser may omit aTextureId
  18168. // as it is not used by the shader so is optimized out.
  18169. for (var i = 0; i < this.vaoMax; i++)
  18170. {
  18171. /* eslint-disable max-len */
  18172. this.vaos[i] = new BatchGeometry();
  18173. }
  18174. };
  18175. /**
  18176. * Called before the renderer starts rendering.
  18177. *
  18178. */
  18179. BatchRenderer.prototype.onPrerender = function onPrerender ()
  18180. {
  18181. this.vertexCount = 0;
  18182. };
  18183. /**
  18184. * Renders the sprite object.
  18185. *
  18186. * @param {PIXI.Sprite} sprite - the sprite to render when using this spritebatch
  18187. */
  18188. BatchRenderer.prototype.render = function render (element)
  18189. {
  18190. if (!element._texture.valid)
  18191. {
  18192. return;
  18193. }
  18194. if (this.currentSize + (element.vertexData.length / 2) > this.size)
  18195. {
  18196. this.flush();
  18197. }
  18198. this.elements[this.currentIndex++] = element;
  18199. this.currentSize += element.vertexData.length / 2;
  18200. this.currentIndexSize += element.indices.length;
  18201. };
  18202. BatchRenderer.prototype.getIndexBuffer = function getIndexBuffer (size)
  18203. {
  18204. // 12 indices is enough for 2 quads
  18205. var roundedP2 = nextPow2(Math.ceil(size / 12));
  18206. var roundedSizeIndex = log2(roundedP2);
  18207. var roundedSize = roundedP2 * 12;
  18208. if (this.iBuffers.length <= roundedSizeIndex)
  18209. {
  18210. this.iBuffers.length = roundedSizeIndex + 1;
  18211. }
  18212. var buffer = this.iBuffers[roundedSizeIndex];
  18213. if (!buffer)
  18214. {
  18215. this.iBuffers[roundedSizeIndex] = buffer = new Uint16Array(roundedSize);
  18216. }
  18217. return buffer;
  18218. };
  18219. BatchRenderer.prototype.getAttributeBuffer = function getAttributeBuffer (size)
  18220. {
  18221. // 8 vertices is enough for 2 quads
  18222. var roundedP2 = nextPow2(Math.ceil(size / 8));
  18223. var roundedSizeIndex = log2(roundedP2);
  18224. var roundedSize = roundedP2 * 8;
  18225. if (this.aBuffers.length <= roundedSizeIndex)
  18226. {
  18227. this.iBuffers.length = roundedSizeIndex + 1;
  18228. }
  18229. var buffer = this.aBuffers[roundedSize];
  18230. if (!buffer)
  18231. {
  18232. this.aBuffers[roundedSize] = buffer = new BatchBuffer(roundedSize * this.vertByteSize);
  18233. }
  18234. return buffer;
  18235. };
  18236. /**
  18237. * Renders the content and empties the current batch.
  18238. *
  18239. */
  18240. BatchRenderer.prototype.flush = function flush ()
  18241. {
  18242. if (this.currentSize === 0)
  18243. {
  18244. return;
  18245. }
  18246. var gl = this.renderer.gl;
  18247. var MAX_TEXTURES = this.MAX_TEXTURES;
  18248. var buffer = this.getAttributeBuffer(this.currentSize);
  18249. var indexBuffer = this.getIndexBuffer(this.currentIndexSize);
  18250. var elements = this.elements;
  18251. var groups = this.groups;
  18252. var float32View = buffer.float32View;
  18253. var uint32View = buffer.uint32View;
  18254. var touch = this.renderer.textureGC.count;
  18255. var index = 0;
  18256. var indexCount = 0;
  18257. var nextTexture;
  18258. var currentTexture;
  18259. var groupCount = 0;
  18260. var textureCount = 0;
  18261. var currentGroup = groups[0];
  18262. var blendMode = -1;// premultiplyBlendMode[elements[0]._texture.baseTexture.premultiplyAlpha ? 0 : ][elements[0].blendMode];
  18263. currentGroup.textureCount = 0;
  18264. currentGroup.start = 0;
  18265. currentGroup.blend = blendMode;
  18266. var TICK = ++BaseTexture._globalBatch;
  18267. var i;
  18268. for (i = 0; i < this.currentIndex; ++i)
  18269. {
  18270. // upload the sprite elements...
  18271. // they have all ready been calculated so we just need to push them into the buffer.
  18272. var sprite = elements[i];
  18273. elements[i] = null;
  18274. nextTexture = sprite._texture.baseTexture;
  18275. var spriteBlendMode = premultiplyBlendMode[nextTexture.premultiplyAlpha ? 1 : 0][sprite.blendMode];
  18276. if (blendMode !== spriteBlendMode)
  18277. {
  18278. blendMode = spriteBlendMode;
  18279. // force the batch to break!
  18280. currentTexture = null;
  18281. textureCount = MAX_TEXTURES;
  18282. TICK++;
  18283. }
  18284. if (currentTexture !== nextTexture)
  18285. {
  18286. currentTexture = nextTexture;
  18287. if (nextTexture._batchEnabled !== TICK)
  18288. {
  18289. if (textureCount === MAX_TEXTURES)
  18290. {
  18291. TICK++;
  18292. textureCount = 0;
  18293. currentGroup.size = indexCount - currentGroup.start;
  18294. currentGroup = groups[groupCount++];
  18295. currentGroup.textureCount = 0;
  18296. currentGroup.blend = blendMode;
  18297. currentGroup.start = indexCount;
  18298. }
  18299. nextTexture.touched = touch;
  18300. nextTexture._batchEnabled = TICK;
  18301. nextTexture._id = textureCount;
  18302. currentGroup.textures[currentGroup.textureCount++] = nextTexture;
  18303. textureCount++;
  18304. }
  18305. }
  18306. this.packGeometry(sprite, float32View, uint32View, indexBuffer, index, indexCount);// argb, nextTexture._id, float32View, uint32View, indexBuffer, index, indexCount);
  18307. // push a graphics..
  18308. index += (sprite.vertexData.length / 2) * this.vertSize;
  18309. indexCount += sprite.indices.length;
  18310. }
  18311. BaseTexture._globalBatch = TICK;
  18312. currentGroup.size = indexCount - currentGroup.start;
  18313. // this.indexBuffer.update();
  18314. if (!settings.CAN_UPLOAD_SAME_BUFFER)
  18315. {
  18316. // this is still needed for IOS performance..
  18317. // it really does not like uploading to the same buffer in a single frame!
  18318. if (this.vaoMax <= this.vertexCount)
  18319. {
  18320. this.vaoMax++;
  18321. /* eslint-disable max-len */
  18322. this.vaos[this.vertexCount] = new BatchGeometry();
  18323. }
  18324. this.vaos[this.vertexCount]._buffer.update(buffer.vertices, 0);
  18325. this.vaos[this.vertexCount]._indexBuffer.update(indexBuffer, 0);
  18326. // this.vertexBuffers[this.vertexCount].update(buffer.vertices, 0);
  18327. this.renderer.geometry.bind(this.vaos[this.vertexCount]);
  18328. this.renderer.geometry.updateBuffers();
  18329. this.vertexCount++;
  18330. }
  18331. else
  18332. {
  18333. // lets use the faster option, always use buffer number 0
  18334. this.vaos[this.vertexCount]._buffer.update(buffer.vertices, 0);
  18335. this.vaos[this.vertexCount]._indexBuffer.update(indexBuffer, 0);
  18336. // if (true)// this.spriteOnly)
  18337. // {
  18338. // this.vaos[this.vertexCount].indexBuffer = this.defualtSpriteIndexBuffer;
  18339. // this.vaos[this.vertexCount].buffers[1] = this.defualtSpriteIndexBuffer;
  18340. // }
  18341. this.renderer.geometry.updateBuffers();
  18342. }
  18343. // this.renderer.state.set(this.state);
  18344. var textureSystem = this.renderer.texture;
  18345. var stateSystem = this.renderer.state;
  18346. // e.log(groupCount);
  18347. // / render the groups..
  18348. for (i = 0; i < groupCount; i++)
  18349. {
  18350. var group = groups[i];
  18351. var groupTextureCount = group.textureCount;
  18352. for (var j = 0; j < groupTextureCount; j++)
  18353. {
  18354. textureSystem.bind(group.textures[j], j);
  18355. group.textures[j] = null;
  18356. }
  18357. // this.state.blendMode = group.blend;
  18358. // this.state.blend = true;
  18359. // this.renderer.state.setState(this.state);
  18360. // set the blend mode..
  18361. stateSystem.setBlendMode(group.blend);
  18362. gl.drawElements(group.type, group.size, gl.UNSIGNED_SHORT, group.start * 2);
  18363. }
  18364. // reset elements for the next flush
  18365. this.currentIndex = 0;
  18366. this.currentSize = 0;
  18367. this.currentIndexSize = 0;
  18368. };
  18369. BatchRenderer.prototype.packGeometry = function packGeometry (element, float32View, uint32View, indexBuffer, index, indexCount)
  18370. {
  18371. var p = index / this.vertSize;// float32View.length / 6 / 2;
  18372. var uvs = element.uvs;
  18373. var indicies = element.indices;// geometry.getIndex().data;// indicies;
  18374. var vertexData = element.vertexData;
  18375. var textureId = element._texture.baseTexture._id;
  18376. var alpha = Math.min(element.worldAlpha, 1.0);
  18377. var argb = alpha < 1.0 && element._texture.baseTexture.premultiplyAlpha ? premultiplyTint(element._tintRGB, alpha)
  18378. : element._tintRGB + (alpha * 255 << 24);
  18379. // lets not worry about tint! for now..
  18380. for (var i = 0; i < vertexData.length; i += 2)
  18381. {
  18382. float32View[index++] = vertexData[i];
  18383. float32View[index++] = vertexData[i + 1];
  18384. float32View[index++] = uvs[i];
  18385. float32View[index++] = uvs[i + 1];
  18386. uint32View[index++] = argb;
  18387. float32View[index++] = textureId;
  18388. }
  18389. for (var i$1 = 0; i$1 < indicies.length; i$1++)
  18390. {
  18391. indexBuffer[indexCount++] = p + indicies[i$1];
  18392. }
  18393. };
  18394. /*
  18395. renderQuad(vertexData, uvs, argb, textureId, float32View, uint32View, indexBuffer, index, indexCount)
  18396. {
  18397. const p = index / 6;
  18398. float32View[index++] = vertexData[0];
  18399. float32View[index++] = vertexData[1];
  18400. float32View[index++] = uvs.x0;
  18401. float32View[index++] = uvs.y0;
  18402. uint32View[index++] = argb;
  18403. float32View[index++] = textureId;
  18404. float32View[index++] = vertexData[2];
  18405. float32View[index++] = vertexData[3];
  18406. float32View[index++] = uvs.x1;
  18407. float32View[index++] = uvs.y1;
  18408. uint32View[index++] = argb;
  18409. float32View[index++] = textureId;
  18410. float32View[index++] = vertexData[4];
  18411. float32View[index++] = vertexData[5];
  18412. float32View[index++] = uvs.x2;
  18413. float32View[index++] = uvs.y2;
  18414. uint32View[index++] = argb;
  18415. float32View[index++] = textureId;
  18416. float32View[index++] = vertexData[6];
  18417. float32View[index++] = vertexData[7];
  18418. float32View[index++] = uvs.x3;
  18419. float32View[index++] = uvs.y3;
  18420. uint32View[index++] = argb;
  18421. float32View[index++] = textureId;
  18422. indexBuffer[indexCount++] = p + 0;
  18423. indexBuffer[indexCount++] = p + 1;
  18424. indexBuffer[indexCount++] = p + 2;
  18425. indexBuffer[indexCount++] = p + 0;
  18426. indexBuffer[indexCount++] = p + 2;
  18427. indexBuffer[indexCount++] = p + 3;
  18428. }
  18429. */
  18430. /**
  18431. * Starts a new sprite batch.
  18432. */
  18433. BatchRenderer.prototype.start = function start ()
  18434. {
  18435. this.renderer.state.setState(this.state);
  18436. this.renderer.shader.bind(this.shader);
  18437. if (settings.CAN_UPLOAD_SAME_BUFFER)
  18438. {
  18439. // bind buffer #0, we don't need others
  18440. this.renderer.geometry.bind(this.vaos[this.vertexCount]);
  18441. }
  18442. };
  18443. /**
  18444. * Stops and flushes the current batch.
  18445. *
  18446. */
  18447. BatchRenderer.prototype.stop = function stop ()
  18448. {
  18449. this.flush();
  18450. };
  18451. /**
  18452. * Destroys the SpriteRenderer.
  18453. *
  18454. */
  18455. BatchRenderer.prototype.destroy = function destroy ()
  18456. {
  18457. for (var i = 0; i < this.vaoMax; i++)
  18458. {
  18459. // if (this.vertexBuffers[i])
  18460. // {
  18461. // this.vertexBuffers[i].destroy();
  18462. // }
  18463. if (this.vaos[i])
  18464. {
  18465. this.vaos[i].destroy();
  18466. }
  18467. }
  18468. if (this.indexBuffer)
  18469. {
  18470. this.indexBuffer.destroy();
  18471. }
  18472. this.renderer.off('prerender', this.onPrerender, this);
  18473. if (this.shader)
  18474. {
  18475. this.shader.destroy();
  18476. this.shader = null;
  18477. }
  18478. // this.vertexBuffers = null;
  18479. this.vaos = null;
  18480. this.indexBuffer = null;
  18481. this.indices = null;
  18482. this.sprites = null;
  18483. // for (let i = 0; i < this.buffers.length; ++i)
  18484. // {
  18485. // this.buffers[i].destroy();
  18486. // }
  18487. ObjectRenderer.prototype.destroy.call(this);
  18488. };
  18489. return BatchRenderer;
  18490. }(ObjectRenderer));
  18491. /*!
  18492. * @pixi/extract - v5.0.4
  18493. * Compiled Fri, 07 Jun 2019 17:17:49 UTC
  18494. *
  18495. * @pixi/extract is licensed under the MIT License.
  18496. * http://www.opensource.org/licenses/mit-license
  18497. */
  18498. var TEMP_RECT = new Rectangle();
  18499. var BYTES_PER_PIXEL = 4;
  18500. /**
  18501. * The extract manager provides functionality to export content from the renderers.
  18502. *
  18503. * An instance of this class is automatically created by default, and can be found at `renderer.plugins.extract`
  18504. *
  18505. * @class
  18506. * @memberof PIXI.extract
  18507. */
  18508. var Extract = function Extract(renderer)
  18509. {
  18510. this.renderer = renderer;
  18511. /**
  18512. * Collection of methods for extracting data (image, pixels, etc.) from a display object or render texture
  18513. *
  18514. * @member {PIXI.extract.Extract} extract
  18515. * @memberof PIXI.Renderer#
  18516. * @see PIXI.extract.Extract
  18517. */
  18518. renderer.extract = this;
  18519. };
  18520. /**
  18521. * Will return a HTML Image of the target
  18522. *
  18523. * @param {PIXI.DisplayObject|PIXI.RenderTexture} target - A displayObject or renderTexture
  18524. * to convert. If left empty will use the main renderer
  18525. * @param {string} [format] - Image format, e.g. "image/jpeg" or "image/webp".
  18526. * @param {number} [quality] - JPEG or Webp compression from 0 to 1. Default is 0.92.
  18527. * @return {HTMLImageElement} HTML Image of the target
  18528. */
  18529. Extract.prototype.image = function image (target, format, quality)
  18530. {
  18531. var image = new Image();
  18532. image.src = this.base64(target, format, quality);
  18533. return image;
  18534. };
  18535. /**
  18536. * Will return a a base64 encoded string of this target. It works by calling
  18537. * `Extract.getCanvas` and then running toDataURL on that.
  18538. *
  18539. * @param {PIXI.DisplayObject|PIXI.RenderTexture} target - A displayObject or renderTexture
  18540. * to convert. If left empty will use the main renderer
  18541. * @param {string} [format] - Image format, e.g. "image/jpeg" or "image/webp".
  18542. * @param {number} [quality] - JPEG or Webp compression from 0 to 1. Default is 0.92.
  18543. * @return {string} A base64 encoded string of the texture.
  18544. */
  18545. Extract.prototype.base64 = function base64 (target, format, quality)
  18546. {
  18547. return this.canvas(target).toDataURL(format, quality);
  18548. };
  18549. /**
  18550. * Creates a Canvas element, renders this target to it and then returns it.
  18551. *
  18552. * @param {PIXI.DisplayObject|PIXI.RenderTexture} target - A displayObject or renderTexture
  18553. * to convert. If left empty will use the main renderer
  18554. * @return {HTMLCanvasElement} A Canvas element with the texture rendered on.
  18555. */
  18556. Extract.prototype.canvas = function canvas (target)
  18557. {
  18558. var renderer = this.renderer;
  18559. var resolution;
  18560. var frame;
  18561. var flipY = false;
  18562. var renderTexture;
  18563. var generated = false;
  18564. if (target)
  18565. {
  18566. if (target instanceof RenderTexture)
  18567. {
  18568. renderTexture = target;
  18569. }
  18570. else
  18571. {
  18572. renderTexture = this.renderer.generateTexture(target);
  18573. generated = true;
  18574. }
  18575. }
  18576. if (renderTexture)
  18577. {
  18578. resolution = renderTexture.baseTexture.resolution;
  18579. frame = renderTexture.frame;
  18580. flipY = false;
  18581. renderer.renderTexture.bind(renderTexture);
  18582. }
  18583. else
  18584. {
  18585. resolution = this.renderer.resolution;
  18586. flipY = true;
  18587. frame = TEMP_RECT;
  18588. frame.width = this.renderer.width;
  18589. frame.height = this.renderer.height;
  18590. renderer.renderTexture.bind(null);
  18591. }
  18592. var width = frame.width * resolution;
  18593. var height = frame.height * resolution;
  18594. var canvasBuffer = new CanvasRenderTarget(width, height, 1);
  18595. var webglPixels = new Uint8Array(BYTES_PER_PIXEL * width * height);
  18596. // read pixels to the array
  18597. var gl = renderer.gl;
  18598. gl.readPixels(
  18599. frame.x * resolution,
  18600. frame.y * resolution,
  18601. width,
  18602. height,
  18603. gl.RGBA,
  18604. gl.UNSIGNED_BYTE,
  18605. webglPixels
  18606. );
  18607. // add the pixels to the canvas
  18608. var canvasData = canvasBuffer.context.getImageData(0, 0, width, height);
  18609. canvasData.data.set(webglPixels);
  18610. canvasBuffer.context.putImageData(canvasData, 0, 0);
  18611. // pulling pixels
  18612. if (flipY)
  18613. {
  18614. canvasBuffer.context.scale(1, -1);
  18615. canvasBuffer.context.drawImage(canvasBuffer.canvas, 0, -height);
  18616. }
  18617. if (generated)
  18618. {
  18619. renderTexture.destroy(true);
  18620. }
  18621. // send the canvas back..
  18622. return canvasBuffer.canvas;
  18623. };
  18624. /**
  18625. * Will return a one-dimensional array containing the pixel data of the entire texture in RGBA
  18626. * order, with integer values between 0 and 255 (included).
  18627. *
  18628. * @param {PIXI.DisplayObject|PIXI.RenderTexture} target - A displayObject or renderTexture
  18629. * to convert. If left empty will use the main renderer
  18630. * @return {Uint8ClampedArray} One-dimensional array containing the pixel data of the entire texture
  18631. */
  18632. Extract.prototype.pixels = function pixels (target)
  18633. {
  18634. var renderer = this.renderer;
  18635. var resolution;
  18636. var frame;
  18637. var renderTexture;
  18638. var generated = false;
  18639. if (target)
  18640. {
  18641. if (target instanceof RenderTexture)
  18642. {
  18643. renderTexture = target;
  18644. }
  18645. else
  18646. {
  18647. renderTexture = this.renderer.generateTexture(target);
  18648. generated = true;
  18649. }
  18650. }
  18651. if (renderTexture)
  18652. {
  18653. resolution = renderTexture.baseTexture.resolution;
  18654. frame = renderTexture.frame;
  18655. // bind the buffer
  18656. renderer.renderTexture.bind(renderTexture);
  18657. }
  18658. else
  18659. {
  18660. resolution = renderer.resolution;
  18661. frame = TEMP_RECT;
  18662. frame.width = renderer.width;
  18663. frame.height = renderer.height;
  18664. renderer.renderTexture.bind(null);
  18665. }
  18666. var width = frame.width * resolution;
  18667. var height = frame.height * resolution;
  18668. var webglPixels = new Uint8Array(BYTES_PER_PIXEL * width * height);
  18669. // read pixels to the array
  18670. var gl = renderer.gl;
  18671. gl.readPixels(
  18672. frame.x * resolution,
  18673. frame.y * resolution,
  18674. width,
  18675. height,
  18676. gl.RGBA,
  18677. gl.UNSIGNED_BYTE,
  18678. webglPixels
  18679. );
  18680. if (generated)
  18681. {
  18682. renderTexture.destroy(true);
  18683. }
  18684. return webglPixels;
  18685. };
  18686. /**
  18687. * Destroys the extract
  18688. *
  18689. */
  18690. Extract.prototype.destroy = function destroy ()
  18691. {
  18692. this.renderer.extract = null;
  18693. this.renderer = null;
  18694. };
  18695. var extract_es = ({
  18696. Extract: Extract
  18697. });
  18698. /*!
  18699. * @pixi/interaction - v5.0.4
  18700. * Compiled Fri, 07 Jun 2019 17:17:49 UTC
  18701. *
  18702. * @pixi/interaction is licensed under the MIT License.
  18703. * http://www.opensource.org/licenses/mit-license
  18704. */
  18705. /**
  18706. * Holds all information related to an Interaction event
  18707. *
  18708. * @class
  18709. * @memberof PIXI.interaction
  18710. */
  18711. var InteractionData = function InteractionData()
  18712. {
  18713. /**
  18714. * This point stores the global coords of where the touch/mouse event happened
  18715. *
  18716. * @member {PIXI.Point}
  18717. */
  18718. this.global = new Point();
  18719. /**
  18720. * The target Sprite that was interacted with
  18721. *
  18722. * @member {PIXI.Sprite}
  18723. */
  18724. this.target = null;
  18725. /**
  18726. * When passed to an event handler, this will be the original DOM Event that was captured
  18727. *
  18728. * @see https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent
  18729. * @see https://developer.mozilla.org/en-US/docs/Web/API/TouchEvent
  18730. * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent
  18731. * @member {MouseEvent|TouchEvent|PointerEvent}
  18732. */
  18733. this.originalEvent = null;
  18734. /**
  18735. * Unique identifier for this interaction
  18736. *
  18737. * @member {number}
  18738. */
  18739. this.identifier = null;
  18740. /**
  18741. * Indicates whether or not the pointer device that created the event is the primary pointer.
  18742. * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/isPrimary
  18743. * @type {Boolean}
  18744. */
  18745. this.isPrimary = false;
  18746. /**
  18747. * Indicates which button was pressed on the mouse or pointer device to trigger the event.
  18748. * @see https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/button
  18749. * @type {number}
  18750. */
  18751. this.button = 0;
  18752. /**
  18753. * Indicates which buttons are pressed on the mouse or pointer device when the event is triggered.
  18754. * @see https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/buttons
  18755. * @type {number}
  18756. */
  18757. this.buttons = 0;
  18758. /**
  18759. * The width of the pointer's contact along the x-axis, measured in CSS pixels.
  18760. * radiusX of TouchEvents will be represented by this value.
  18761. * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/width
  18762. * @type {number}
  18763. */
  18764. this.width = 0;
  18765. /**
  18766. * The height of the pointer's contact along the y-axis, measured in CSS pixels.
  18767. * radiusY of TouchEvents will be represented by this value.
  18768. * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/height
  18769. * @type {number}
  18770. */
  18771. this.height = 0;
  18772. /**
  18773. * The angle, in degrees, between the pointer device and the screen.
  18774. * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/tiltX
  18775. * @type {number}
  18776. */
  18777. this.tiltX = 0;
  18778. /**
  18779. * The angle, in degrees, between the pointer device and the screen.
  18780. * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/tiltY
  18781. * @type {number}
  18782. */
  18783. this.tiltY = 0;
  18784. /**
  18785. * The type of pointer that triggered the event.
  18786. * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/pointerType
  18787. * @type {string}
  18788. */
  18789. this.pointerType = null;
  18790. /**
  18791. * Pressure applied by the pointing device during the event. A Touch's force property
  18792. * will be represented by this value.
  18793. * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/pressure
  18794. * @type {number}
  18795. */
  18796. this.pressure = 0;
  18797. /**
  18798. * From TouchEvents (not PointerEvents triggered by touches), the rotationAngle of the Touch.
  18799. * @see https://developer.mozilla.org/en-US/docs/Web/API/Touch/rotationAngle
  18800. * @type {number}
  18801. */
  18802. this.rotationAngle = 0;
  18803. /**
  18804. * Twist of a stylus pointer.
  18805. * @see https://w3c.github.io/pointerevents/#pointerevent-interface
  18806. * @type {number}
  18807. */
  18808. this.twist = 0;
  18809. /**
  18810. * Barrel pressure on a stylus pointer.
  18811. * @see https://w3c.github.io/pointerevents/#pointerevent-interface
  18812. * @type {number}
  18813. */
  18814. this.tangentialPressure = 0;
  18815. };
  18816. var prototypeAccessors$6 = { pointerId: { configurable: true } };
  18817. /**
  18818. * The unique identifier of the pointer. It will be the same as `identifier`.
  18819. * @readonly
  18820. * @member {number}
  18821. * @see https://developer.mozilla.org/en-US/docs/Web/API/PointerEvent/pointerId
  18822. */
  18823. prototypeAccessors$6.pointerId.get = function ()
  18824. {
  18825. return this.identifier;
  18826. };
  18827. /**
  18828. * This will return the local coordinates of the specified displayObject for this InteractionData
  18829. *
  18830. * @param {PIXI.DisplayObject} displayObject - The DisplayObject that you would like the local
  18831. * coords off
  18832. * @param {PIXI.Point} [point] - A Point object in which to store the value, optional (otherwise
  18833. * will create a new point)
  18834. * @param {PIXI.Point} [globalPos] - A Point object containing your custom global coords, optional
  18835. * (otherwise will use the current global coords)
  18836. * @return {PIXI.Point} A point containing the coordinates of the InteractionData position relative
  18837. * to the DisplayObject
  18838. */
  18839. InteractionData.prototype.getLocalPosition = function getLocalPosition (displayObject, point, globalPos)
  18840. {
  18841. return displayObject.worldTransform.applyInverse(globalPos || this.global, point);
  18842. };
  18843. /**
  18844. * Copies properties from normalized event data.
  18845. *
  18846. * @param {Touch|MouseEvent|PointerEvent} event The normalized event data
  18847. */
  18848. InteractionData.prototype.copyEvent = function copyEvent (event)
  18849. {
  18850. // isPrimary should only change on touchstart/pointerdown, so we don't want to overwrite
  18851. // it with "false" on later events when our shim for it on touch events might not be
  18852. // accurate
  18853. if (event.isPrimary)
  18854. {
  18855. this.isPrimary = true;
  18856. }
  18857. this.button = event.button;
  18858. // event.buttons is not available in all browsers (ie. Safari), but it does have a non-standard
  18859. // event.which property instead, which conveys the same information.
  18860. this.buttons = Number.isInteger(event.buttons) ? event.buttons : event.which;
  18861. this.width = event.width;
  18862. this.height = event.height;
  18863. this.tiltX = event.tiltX;
  18864. this.tiltY = event.tiltY;
  18865. this.pointerType = event.pointerType;
  18866. this.pressure = event.pressure;
  18867. this.rotationAngle = event.rotationAngle;
  18868. this.twist = event.twist || 0;
  18869. this.tangentialPressure = event.tangentialPressure || 0;
  18870. };
  18871. /**
  18872. * Resets the data for pooling.
  18873. */
  18874. InteractionData.prototype.reset = function reset ()
  18875. {
  18876. // isPrimary is the only property that we really need to reset - everything else is
  18877. // guaranteed to be overwritten
  18878. this.isPrimary = false;
  18879. };
  18880. Object.defineProperties( InteractionData.prototype, prototypeAccessors$6 );
  18881. /**
  18882. * Event class that mimics native DOM events.
  18883. *
  18884. * @class
  18885. * @memberof PIXI.interaction
  18886. */
  18887. var InteractionEvent = function InteractionEvent()
  18888. {
  18889. /**
  18890. * Whether this event will continue propagating in the tree
  18891. *
  18892. * @member {boolean}
  18893. */
  18894. this.stopped = false;
  18895. /**
  18896. * The object which caused this event to be dispatched.
  18897. * For listener callback see {@link PIXI.interaction.InteractionEvent.currentTarget}.
  18898. *
  18899. * @member {PIXI.DisplayObject}
  18900. */
  18901. this.target = null;
  18902. /**
  18903. * The object whose event listener’s callback is currently being invoked.
  18904. *
  18905. * @member {PIXI.DisplayObject}
  18906. */
  18907. this.currentTarget = null;
  18908. /**
  18909. * Type of the event
  18910. *
  18911. * @member {string}
  18912. */
  18913. this.type = null;
  18914. /**
  18915. * InteractionData related to this event
  18916. *
  18917. * @member {PIXI.interaction.InteractionData}
  18918. */
  18919. this.data = null;
  18920. };
  18921. /**
  18922. * Prevents event from reaching any objects other than the current object.
  18923. *
  18924. */
  18925. InteractionEvent.prototype.stopPropagation = function stopPropagation ()
  18926. {
  18927. this.stopped = true;
  18928. };
  18929. /**
  18930. * Resets the event.
  18931. */
  18932. InteractionEvent.prototype.reset = function reset ()
  18933. {
  18934. this.stopped = false;
  18935. this.currentTarget = null;
  18936. this.target = null;
  18937. };
  18938. /**
  18939. * DisplayObjects with the {@link PIXI.interaction.interactiveTarget} mixin use this class to track interactions
  18940. *
  18941. * @class
  18942. * @private
  18943. * @memberof PIXI.interaction
  18944. */
  18945. var InteractionTrackingData = function InteractionTrackingData(pointerId)
  18946. {
  18947. this._pointerId = pointerId;
  18948. this._flags = InteractionTrackingData.FLAGS.NONE;
  18949. };
  18950. var prototypeAccessors$1$3 = { pointerId: { configurable: true },flags: { configurable: true },none: { configurable: true },over: { configurable: true },rightDown: { configurable: true },leftDown: { configurable: true } };
  18951. /**
  18952. *
  18953. * @private
  18954. * @param {number} flag - The interaction flag to set
  18955. * @param {boolean} yn - Should the flag be set or unset
  18956. */
  18957. InteractionTrackingData.prototype._doSet = function _doSet (flag, yn)
  18958. {
  18959. if (yn)
  18960. {
  18961. this._flags = this._flags | flag;
  18962. }
  18963. else
  18964. {
  18965. this._flags = this._flags & (~flag);
  18966. }
  18967. };
  18968. /**
  18969. * Unique pointer id of the event
  18970. *
  18971. * @readonly
  18972. * @private
  18973. * @member {number}
  18974. */
  18975. prototypeAccessors$1$3.pointerId.get = function ()
  18976. {
  18977. return this._pointerId;
  18978. };
  18979. /**
  18980. * State of the tracking data, expressed as bit flags
  18981. *
  18982. * @private
  18983. * @member {number}
  18984. */
  18985. prototypeAccessors$1$3.flags.get = function ()
  18986. {
  18987. return this._flags;
  18988. };
  18989. prototypeAccessors$1$3.flags.set = function (flags) // eslint-disable-line require-jsdoc
  18990. {
  18991. this._flags = flags;
  18992. };
  18993. /**
  18994. * Is the tracked event inactive (not over or down)?
  18995. *
  18996. * @private
  18997. * @member {number}
  18998. */
  18999. prototypeAccessors$1$3.none.get = function ()
  19000. {
  19001. return this._flags === this.constructor.FLAGS.NONE;
  19002. };
  19003. /**
  19004. * Is the tracked event over the DisplayObject?
  19005. *
  19006. * @private
  19007. * @member {boolean}
  19008. */
  19009. prototypeAccessors$1$3.over.get = function ()
  19010. {
  19011. return (this._flags & this.constructor.FLAGS.OVER) !== 0;
  19012. };
  19013. prototypeAccessors$1$3.over.set = function (yn) // eslint-disable-line require-jsdoc
  19014. {
  19015. this._doSet(this.constructor.FLAGS.OVER, yn);
  19016. };
  19017. /**
  19018. * Did the right mouse button come down in the DisplayObject?
  19019. *
  19020. * @private
  19021. * @member {boolean}
  19022. */
  19023. prototypeAccessors$1$3.rightDown.get = function ()
  19024. {
  19025. return (this._flags & this.constructor.FLAGS.RIGHT_DOWN) !== 0;
  19026. };
  19027. prototypeAccessors$1$3.rightDown.set = function (yn) // eslint-disable-line require-jsdoc
  19028. {
  19029. this._doSet(this.constructor.FLAGS.RIGHT_DOWN, yn);
  19030. };
  19031. /**
  19032. * Did the left mouse button come down in the DisplayObject?
  19033. *
  19034. * @private
  19035. * @member {boolean}
  19036. */
  19037. prototypeAccessors$1$3.leftDown.get = function ()
  19038. {
  19039. return (this._flags & this.constructor.FLAGS.LEFT_DOWN) !== 0;
  19040. };
  19041. prototypeAccessors$1$3.leftDown.set = function (yn) // eslint-disable-line require-jsdoc
  19042. {
  19043. this._doSet(this.constructor.FLAGS.LEFT_DOWN, yn);
  19044. };
  19045. Object.defineProperties( InteractionTrackingData.prototype, prototypeAccessors$1$3 );
  19046. InteractionTrackingData.FLAGS = Object.freeze({
  19047. NONE: 0,
  19048. OVER: 1 << 0,
  19049. LEFT_DOWN: 1 << 1,
  19050. RIGHT_DOWN: 1 << 2,
  19051. });
  19052. /**
  19053. * Default property values of interactive objects
  19054. * Used by {@link PIXI.interaction.InteractionManager} to automatically give all DisplayObjects these properties
  19055. *
  19056. * @private
  19057. * @name interactiveTarget
  19058. * @type {Object}
  19059. * @memberof PIXI.interaction
  19060. * @example
  19061. * function MyObject() {}
  19062. *
  19063. * Object.assign(
  19064. * DisplayObject.prototype,
  19065. * PIXI.interaction.interactiveTarget
  19066. * );
  19067. */
  19068. var interactiveTarget = {
  19069. /**
  19070. * Enable interaction events for the DisplayObject. Touch, pointer and mouse
  19071. * events will not be emitted unless `interactive` is set to `true`.
  19072. *
  19073. * @example
  19074. * const sprite = new PIXI.Sprite(texture);
  19075. * sprite.interactive = true;
  19076. * sprite.on('tap', (event) => {
  19077. * //handle event
  19078. * });
  19079. * @member {boolean}
  19080. * @memberof PIXI.DisplayObject#
  19081. */
  19082. interactive: false,
  19083. /**
  19084. * Determines if the children to the displayObject can be clicked/touched
  19085. * Setting this to false allows PixiJS to bypass a recursive `hitTest` function
  19086. *
  19087. * @member {boolean}
  19088. * @memberof PIXI.Container#
  19089. */
  19090. interactiveChildren: true,
  19091. /**
  19092. * Interaction shape. Children will be hit first, then this shape will be checked.
  19093. * Setting this will cause this shape to be checked in hit tests rather than the displayObject's bounds.
  19094. *
  19095. * @example
  19096. * const sprite = new PIXI.Sprite(texture);
  19097. * sprite.interactive = true;
  19098. * sprite.hitArea = new PIXI.Rectangle(0, 0, 100, 100);
  19099. * @member {PIXI.Rectangle|PIXI.Circle|PIXI.Ellipse|PIXI.Polygon|PIXI.RoundedRectangle}
  19100. * @memberof PIXI.DisplayObject#
  19101. */
  19102. hitArea: null,
  19103. /**
  19104. * If enabled, the mouse cursor use the pointer behavior when hovered over the displayObject if it is interactive
  19105. * Setting this changes the 'cursor' property to `'pointer'`.
  19106. *
  19107. * @example
  19108. * const sprite = new PIXI.Sprite(texture);
  19109. * sprite.interactive = true;
  19110. * sprite.buttonMode = true;
  19111. * @member {boolean}
  19112. * @memberof PIXI.DisplayObject#
  19113. */
  19114. get buttonMode()
  19115. {
  19116. return this.cursor === 'pointer';
  19117. },
  19118. set buttonMode(value)
  19119. {
  19120. if (value)
  19121. {
  19122. this.cursor = 'pointer';
  19123. }
  19124. else if (this.cursor === 'pointer')
  19125. {
  19126. this.cursor = null;
  19127. }
  19128. },
  19129. /**
  19130. * This defines what cursor mode is used when the mouse cursor
  19131. * is hovered over the displayObject.
  19132. *
  19133. * @example
  19134. * const sprite = new PIXI.Sprite(texture);
  19135. * sprite.interactive = true;
  19136. * sprite.cursor = 'wait';
  19137. * @see https://developer.mozilla.org/en/docs/Web/CSS/cursor
  19138. *
  19139. * @member {string}
  19140. * @memberof PIXI.DisplayObject#
  19141. */
  19142. cursor: null,
  19143. /**
  19144. * Internal set of all active pointers, by identifier
  19145. *
  19146. * @member {Map<number, InteractionTrackingData>}
  19147. * @memberof PIXI.DisplayObject#
  19148. * @private
  19149. */
  19150. get trackedPointers()
  19151. {
  19152. if (this._trackedPointers === undefined) { this._trackedPointers = {}; }
  19153. return this._trackedPointers;
  19154. },
  19155. /**
  19156. * Map of all tracked pointers, by identifier. Use trackedPointers to access.
  19157. *
  19158. * @private
  19159. * @type {Map<number, InteractionTrackingData>}
  19160. */
  19161. _trackedPointers: undefined,
  19162. };
  19163. // Mix interactiveTarget into DisplayObject.prototype,
  19164. // after deprecation has been handled
  19165. DisplayObject.mixin(interactiveTarget);
  19166. var MOUSE_POINTER_ID = 1;
  19167. // helpers for hitTest() - only used inside hitTest()
  19168. var hitTestEvent = {
  19169. target: null,
  19170. data: {
  19171. global: null,
  19172. },
  19173. };
  19174. /**
  19175. * The interaction manager deals with mouse, touch and pointer events.
  19176. *
  19177. * Any DisplayObject can be interactive if its `interactive` property is set to true.
  19178. *
  19179. * This manager also supports multitouch.
  19180. *
  19181. * An instance of this class is automatically created by default, and can be found at `renderer.plugins.interaction`
  19182. *
  19183. * @class
  19184. * @extends PIXI.utils.EventEmitter
  19185. * @memberof PIXI.interaction
  19186. */
  19187. var InteractionManager = /*@__PURE__*/(function (EventEmitter) {
  19188. function InteractionManager(renderer, options)
  19189. {
  19190. EventEmitter.call(this);
  19191. options = options || {};
  19192. /**
  19193. * The renderer this interaction manager works for.
  19194. *
  19195. * @member {PIXI.AbstractRenderer}
  19196. */
  19197. this.renderer = renderer;
  19198. /**
  19199. * Should default browser actions automatically be prevented.
  19200. * Does not apply to pointer events for backwards compatibility
  19201. * preventDefault on pointer events stops mouse events from firing
  19202. * Thus, for every pointer event, there will always be either a mouse of touch event alongside it.
  19203. *
  19204. * @member {boolean}
  19205. * @default true
  19206. */
  19207. this.autoPreventDefault = options.autoPreventDefault !== undefined ? options.autoPreventDefault : true;
  19208. /**
  19209. * Frequency in milliseconds that the mousemove, mouseover & mouseout interaction events will be checked.
  19210. *
  19211. * @member {number}
  19212. * @default 10
  19213. */
  19214. this.interactionFrequency = options.interactionFrequency || 10;
  19215. /**
  19216. * The mouse data
  19217. *
  19218. * @member {PIXI.interaction.InteractionData}
  19219. */
  19220. this.mouse = new InteractionData();
  19221. this.mouse.identifier = MOUSE_POINTER_ID;
  19222. // setting the mouse to start off far off screen will mean that mouse over does
  19223. // not get called before we even move the mouse.
  19224. this.mouse.global.set(-999999);
  19225. /**
  19226. * Actively tracked InteractionData
  19227. *
  19228. * @private
  19229. * @member {Object.<number,PIXI.interaction.InteractionData>}
  19230. */
  19231. this.activeInteractionData = {};
  19232. this.activeInteractionData[MOUSE_POINTER_ID] = this.mouse;
  19233. /**
  19234. * Pool of unused InteractionData
  19235. *
  19236. * @private
  19237. * @member {PIXI.interaction.InteractionData[]}
  19238. */
  19239. this.interactionDataPool = [];
  19240. /**
  19241. * An event data object to handle all the event tracking/dispatching
  19242. *
  19243. * @member {object}
  19244. */
  19245. this.eventData = new InteractionEvent();
  19246. /**
  19247. * The DOM element to bind to.
  19248. *
  19249. * @protected
  19250. * @member {HTMLElement}
  19251. */
  19252. this.interactionDOMElement = null;
  19253. /**
  19254. * This property determines if mousemove and touchmove events are fired only when the cursor
  19255. * is over the object.
  19256. * Setting to true will make things work more in line with how the DOM version works.
  19257. * Setting to false can make things easier for things like dragging
  19258. * It is currently set to false as this is how PixiJS used to work. This will be set to true in
  19259. * future versions of pixi.
  19260. *
  19261. * @member {boolean}
  19262. * @default false
  19263. */
  19264. this.moveWhenInside = false;
  19265. /**
  19266. * Have events been attached to the dom element?
  19267. *
  19268. * @protected
  19269. * @member {boolean}
  19270. */
  19271. this.eventsAdded = false;
  19272. /**
  19273. * Is the mouse hovering over the renderer?
  19274. *
  19275. * @protected
  19276. * @member {boolean}
  19277. */
  19278. this.mouseOverRenderer = false;
  19279. /**
  19280. * Does the device support touch events
  19281. * https://www.w3.org/TR/touch-events/
  19282. *
  19283. * @readonly
  19284. * @member {boolean}
  19285. */
  19286. this.supportsTouchEvents = 'ontouchstart' in window;
  19287. /**
  19288. * Does the device support pointer events
  19289. * https://www.w3.org/Submission/pointer-events/
  19290. *
  19291. * @readonly
  19292. * @member {boolean}
  19293. */
  19294. this.supportsPointerEvents = !!window.PointerEvent;
  19295. // this will make it so that you don't have to call bind all the time
  19296. /**
  19297. * @private
  19298. * @member {Function}
  19299. */
  19300. this.onPointerUp = this.onPointerUp.bind(this);
  19301. this.processPointerUp = this.processPointerUp.bind(this);
  19302. /**
  19303. * @private
  19304. * @member {Function}
  19305. */
  19306. this.onPointerCancel = this.onPointerCancel.bind(this);
  19307. this.processPointerCancel = this.processPointerCancel.bind(this);
  19308. /**
  19309. * @private
  19310. * @member {Function}
  19311. */
  19312. this.onPointerDown = this.onPointerDown.bind(this);
  19313. this.processPointerDown = this.processPointerDown.bind(this);
  19314. /**
  19315. * @private
  19316. * @member {Function}
  19317. */
  19318. this.onPointerMove = this.onPointerMove.bind(this);
  19319. this.processPointerMove = this.processPointerMove.bind(this);
  19320. /**
  19321. * @private
  19322. * @member {Function}
  19323. */
  19324. this.onPointerOut = this.onPointerOut.bind(this);
  19325. this.processPointerOverOut = this.processPointerOverOut.bind(this);
  19326. /**
  19327. * @private
  19328. * @member {Function}
  19329. */
  19330. this.onPointerOver = this.onPointerOver.bind(this);
  19331. /**
  19332. * Dictionary of how different cursor modes are handled. Strings are handled as CSS cursor
  19333. * values, objects are handled as dictionaries of CSS values for interactionDOMElement,
  19334. * and functions are called instead of changing the CSS.
  19335. * Default CSS cursor values are provided for 'default' and 'pointer' modes.
  19336. * @member {Object.<string, Object>}
  19337. */
  19338. this.cursorStyles = {
  19339. default: 'inherit',
  19340. pointer: 'pointer',
  19341. };
  19342. /**
  19343. * The mode of the cursor that is being used.
  19344. * The value of this is a key from the cursorStyles dictionary.
  19345. *
  19346. * @member {string}
  19347. */
  19348. this.currentCursorMode = null;
  19349. /**
  19350. * Internal cached let.
  19351. *
  19352. * @private
  19353. * @member {string}
  19354. */
  19355. this.cursor = null;
  19356. /**
  19357. * Internal cached let.
  19358. *
  19359. * @private
  19360. * @member {PIXI.Point}
  19361. */
  19362. this._tempPoint = new Point();
  19363. /**
  19364. * The current resolution / device pixel ratio.
  19365. *
  19366. * @member {number}
  19367. * @default 1
  19368. */
  19369. this.resolution = 1;
  19370. /**
  19371. * Fired when a pointer device button (usually a mouse left-button) is pressed on the display
  19372. * object.
  19373. *
  19374. * @event PIXI.interaction.InteractionManager#mousedown
  19375. * @param {PIXI.interaction.InteractionEvent} event - Interaction event
  19376. */
  19377. /**
  19378. * Fired when a pointer device secondary button (usually a mouse right-button) is pressed
  19379. * on the display object.
  19380. *
  19381. * @event PIXI.interaction.InteractionManager#rightdown
  19382. * @param {PIXI.interaction.InteractionEvent} event - Interaction event
  19383. */
  19384. /**
  19385. * Fired when a pointer device button (usually a mouse left-button) is released over the display
  19386. * object.
  19387. *
  19388. * @event PIXI.interaction.InteractionManager#mouseup
  19389. * @param {PIXI.interaction.InteractionEvent} event - Interaction event
  19390. */
  19391. /**
  19392. * Fired when a pointer device secondary button (usually a mouse right-button) is released
  19393. * over the display object.
  19394. *
  19395. * @event PIXI.interaction.InteractionManager#rightup
  19396. * @param {PIXI.interaction.InteractionEvent} event - Interaction event
  19397. */
  19398. /**
  19399. * Fired when a pointer device button (usually a mouse left-button) is pressed and released on
  19400. * the display object.
  19401. *
  19402. * @event PIXI.interaction.InteractionManager#click
  19403. * @param {PIXI.interaction.InteractionEvent} event - Interaction event
  19404. */
  19405. /**
  19406. * Fired when a pointer device secondary button (usually a mouse right-button) is pressed
  19407. * and released on the display object.
  19408. *
  19409. * @event PIXI.interaction.InteractionManager#rightclick
  19410. * @param {PIXI.interaction.InteractionEvent} event - Interaction event
  19411. */
  19412. /**
  19413. * Fired when a pointer device button (usually a mouse left-button) is released outside the
  19414. * display object that initially registered a
  19415. * [mousedown]{@link PIXI.interaction.InteractionManager#event:mousedown}.
  19416. *
  19417. * @event PIXI.interaction.InteractionManager#mouseupoutside
  19418. * @param {PIXI.interaction.InteractionEvent} event - Interaction event
  19419. */
  19420. /**
  19421. * Fired when a pointer device secondary button (usually a mouse right-button) is released
  19422. * outside the display object that initially registered a
  19423. * [rightdown]{@link PIXI.interaction.InteractionManager#event:rightdown}.
  19424. *
  19425. * @event PIXI.interaction.InteractionManager#rightupoutside
  19426. * @param {PIXI.interaction.InteractionEvent} event - Interaction event
  19427. */
  19428. /**
  19429. * Fired when a pointer device (usually a mouse) is moved while over the display object
  19430. *
  19431. * @event PIXI.interaction.InteractionManager#mousemove
  19432. * @param {PIXI.interaction.InteractionEvent} event - Interaction event
  19433. */
  19434. /**
  19435. * Fired when a pointer device (usually a mouse) is moved onto the display object
  19436. *
  19437. * @event PIXI.interaction.InteractionManager#mouseover
  19438. * @param {PIXI.interaction.InteractionEvent} event - Interaction event
  19439. */
  19440. /**
  19441. * Fired when a pointer device (usually a mouse) is moved off the display object
  19442. *
  19443. * @event PIXI.interaction.InteractionManager#mouseout
  19444. * @param {PIXI.interaction.InteractionEvent} event - Interaction event
  19445. */
  19446. /**
  19447. * Fired when a pointer device button is pressed on the display object.
  19448. *
  19449. * @event PIXI.interaction.InteractionManager#pointerdown
  19450. * @param {PIXI.interaction.InteractionEvent} event - Interaction event
  19451. */
  19452. /**
  19453. * Fired when a pointer device button is released over the display object.
  19454. * Not always fired when some buttons are held down while others are released. In those cases,
  19455. * use [mousedown]{@link PIXI.interaction.InteractionManager#event:mousedown} and
  19456. * [mouseup]{@link PIXI.interaction.InteractionManager#event:mouseup} instead.
  19457. *
  19458. * @event PIXI.interaction.InteractionManager#pointerup
  19459. * @param {PIXI.interaction.InteractionEvent} event - Interaction event
  19460. */
  19461. /**
  19462. * Fired when the operating system cancels a pointer event
  19463. *
  19464. * @event PIXI.interaction.InteractionManager#pointercancel
  19465. * @param {PIXI.interaction.InteractionEvent} event - Interaction event
  19466. */
  19467. /**
  19468. * Fired when a pointer device button is pressed and released on the display object.
  19469. *
  19470. * @event PIXI.interaction.InteractionManager#pointertap
  19471. * @param {PIXI.interaction.InteractionEvent} event - Interaction event
  19472. */
  19473. /**
  19474. * Fired when a pointer device button is released outside the display object that initially
  19475. * registered a [pointerdown]{@link PIXI.interaction.InteractionManager#event:pointerdown}.
  19476. *
  19477. * @event PIXI.interaction.InteractionManager#pointerupoutside
  19478. * @param {PIXI.interaction.InteractionEvent} event - Interaction event
  19479. */
  19480. /**
  19481. * Fired when a pointer device is moved while over the display object
  19482. *
  19483. * @event PIXI.interaction.InteractionManager#pointermove
  19484. * @param {PIXI.interaction.InteractionEvent} event - Interaction event
  19485. */
  19486. /**
  19487. * Fired when a pointer device is moved onto the display object
  19488. *
  19489. * @event PIXI.interaction.InteractionManager#pointerover
  19490. * @param {PIXI.interaction.InteractionEvent} event - Interaction event
  19491. */
  19492. /**
  19493. * Fired when a pointer device is moved off the display object
  19494. *
  19495. * @event PIXI.interaction.InteractionManager#pointerout
  19496. * @param {PIXI.interaction.InteractionEvent} event - Interaction event
  19497. */
  19498. /**
  19499. * Fired when a touch point is placed on the display object.
  19500. *
  19501. * @event PIXI.interaction.InteractionManager#touchstart
  19502. * @param {PIXI.interaction.InteractionEvent} event - Interaction event
  19503. */
  19504. /**
  19505. * Fired when a touch point is removed from the display object.
  19506. *
  19507. * @event PIXI.interaction.InteractionManager#touchend
  19508. * @param {PIXI.interaction.InteractionEvent} event - Interaction event
  19509. */
  19510. /**
  19511. * Fired when the operating system cancels a touch
  19512. *
  19513. * @event PIXI.interaction.InteractionManager#touchcancel
  19514. * @param {PIXI.interaction.InteractionEvent} event - Interaction event
  19515. */
  19516. /**
  19517. * Fired when a touch point is placed and removed from the display object.
  19518. *
  19519. * @event PIXI.interaction.InteractionManager#tap
  19520. * @param {PIXI.interaction.InteractionEvent} event - Interaction event
  19521. */
  19522. /**
  19523. * Fired when a touch point is removed outside of the display object that initially
  19524. * registered a [touchstart]{@link PIXI.interaction.InteractionManager#event:touchstart}.
  19525. *
  19526. * @event PIXI.interaction.InteractionManager#touchendoutside
  19527. * @param {PIXI.interaction.InteractionEvent} event - Interaction event
  19528. */
  19529. /**
  19530. * Fired when a touch point is moved along the display object.
  19531. *
  19532. * @event PIXI.interaction.InteractionManager#touchmove
  19533. * @param {PIXI.interaction.InteractionEvent} event - Interaction event
  19534. */
  19535. /**
  19536. * Fired when a pointer device button (usually a mouse left-button) is pressed on the display.
  19537. * object. DisplayObject's `interactive` property must be set to `true` to fire event.
  19538. *
  19539. * @event PIXI.DisplayObject#mousedown
  19540. * @param {PIXI.interaction.InteractionEvent} event - Interaction event
  19541. */
  19542. /**
  19543. * Fired when a pointer device secondary button (usually a mouse right-button) is pressed
  19544. * on the display object. DisplayObject's `interactive` property must be set to `true` to fire event.
  19545. *
  19546. * @event PIXI.DisplayObject#rightdown
  19547. * @param {PIXI.interaction.InteractionEvent} event - Interaction event
  19548. */
  19549. /**
  19550. * Fired when a pointer device button (usually a mouse left-button) is released over the display
  19551. * object. DisplayObject's `interactive` property must be set to `true` to fire event.
  19552. *
  19553. * @event PIXI.DisplayObject#mouseup
  19554. * @param {PIXI.interaction.InteractionEvent} event - Interaction event
  19555. */
  19556. /**
  19557. * Fired when a pointer device secondary button (usually a mouse right-button) is released
  19558. * over the display object. DisplayObject's `interactive` property must be set to `true` to fire event.
  19559. *
  19560. * @event PIXI.DisplayObject#rightup
  19561. * @param {PIXI.interaction.InteractionEvent} event - Interaction event
  19562. */
  19563. /**
  19564. * Fired when a pointer device button (usually a mouse left-button) is pressed and released on
  19565. * the display object. DisplayObject's `interactive` property must be set to `true` to fire event.
  19566. *
  19567. * @event PIXI.DisplayObject#click
  19568. * @param {PIXI.interaction.InteractionEvent} event - Interaction event
  19569. */
  19570. /**
  19571. * Fired when a pointer device secondary button (usually a mouse right-button) is pressed
  19572. * and released on the display object. DisplayObject's `interactive` property must be set to `true` to fire event.
  19573. *
  19574. * @event PIXI.DisplayObject#rightclick
  19575. * @param {PIXI.interaction.InteractionEvent} event - Interaction event
  19576. */
  19577. /**
  19578. * Fired when a pointer device button (usually a mouse left-button) is released outside the
  19579. * display object that initially registered a
  19580. * [mousedown]{@link PIXI.DisplayObject#event:mousedown}.
  19581. * DisplayObject's `interactive` property must be set to `true` to fire event.
  19582. *
  19583. * @event PIXI.DisplayObject#mouseupoutside
  19584. * @param {PIXI.interaction.InteractionEvent} event - Interaction event
  19585. */
  19586. /**
  19587. * Fired when a pointer device secondary button (usually a mouse right-button) is released
  19588. * outside the display object that initially registered a
  19589. * [rightdown]{@link PIXI.DisplayObject#event:rightdown}.
  19590. * DisplayObject's `interactive` property must be set to `true` to fire event.
  19591. *
  19592. * @event PIXI.DisplayObject#rightupoutside
  19593. * @param {PIXI.interaction.InteractionEvent} event - Interaction event
  19594. */
  19595. /**
  19596. * Fired when a pointer device (usually a mouse) is moved while over the display object.
  19597. * DisplayObject's `interactive` property must be set to `true` to fire event.
  19598. *
  19599. * @event PIXI.DisplayObject#mousemove
  19600. * @param {PIXI.interaction.InteractionEvent} event - Interaction event
  19601. */
  19602. /**
  19603. * Fired when a pointer device (usually a mouse) is moved onto the display object.
  19604. * DisplayObject's `interactive` property must be set to `true` to fire event.
  19605. *
  19606. * @event PIXI.DisplayObject#mouseover
  19607. * @param {PIXI.interaction.InteractionEvent} event - Interaction event
  19608. */
  19609. /**
  19610. * Fired when a pointer device (usually a mouse) is moved off the display object.
  19611. * DisplayObject's `interactive` property must be set to `true` to fire event.
  19612. *
  19613. * @event PIXI.DisplayObject#mouseout
  19614. * @param {PIXI.interaction.InteractionEvent} event - Interaction event
  19615. */
  19616. /**
  19617. * Fired when a pointer device button is pressed on the display object.
  19618. * DisplayObject's `interactive` property must be set to `true` to fire event.
  19619. *
  19620. * @event PIXI.DisplayObject#pointerdown
  19621. * @param {PIXI.interaction.InteractionEvent} event - Interaction event
  19622. */
  19623. /**
  19624. * Fired when a pointer device button is released over the display object.
  19625. * DisplayObject's `interactive` property must be set to `true` to fire event.
  19626. *
  19627. * @event PIXI.DisplayObject#pointerup
  19628. * @param {PIXI.interaction.InteractionEvent} event - Interaction event
  19629. */
  19630. /**
  19631. * Fired when the operating system cancels a pointer event.
  19632. * DisplayObject's `interactive` property must be set to `true` to fire event.
  19633. *
  19634. * @event PIXI.DisplayObject#pointercancel
  19635. * @param {PIXI.interaction.InteractionEvent} event - Interaction event
  19636. */
  19637. /**
  19638. * Fired when a pointer device button is pressed and released on the display object.
  19639. * DisplayObject's `interactive` property must be set to `true` to fire event.
  19640. *
  19641. * @event PIXI.DisplayObject#pointertap
  19642. * @param {PIXI.interaction.InteractionEvent} event - Interaction event
  19643. */
  19644. /**
  19645. * Fired when a pointer device button is released outside the display object that initially
  19646. * registered a [pointerdown]{@link PIXI.DisplayObject#event:pointerdown}.
  19647. * DisplayObject's `interactive` property must be set to `true` to fire event.
  19648. *
  19649. * @event PIXI.DisplayObject#pointerupoutside
  19650. * @param {PIXI.interaction.InteractionEvent} event - Interaction event
  19651. */
  19652. /**
  19653. * Fired when a pointer device is moved while over the display object.
  19654. * DisplayObject's `interactive` property must be set to `true` to fire event.
  19655. *
  19656. * @event PIXI.DisplayObject#pointermove
  19657. * @param {PIXI.interaction.InteractionEvent} event - Interaction event
  19658. */
  19659. /**
  19660. * Fired when a pointer device is moved onto the display object.
  19661. * DisplayObject's `interactive` property must be set to `true` to fire event.
  19662. *
  19663. * @event PIXI.DisplayObject#pointerover
  19664. * @param {PIXI.interaction.InteractionEvent} event - Interaction event
  19665. */
  19666. /**
  19667. * Fired when a pointer device is moved off the display object.
  19668. * DisplayObject's `interactive` property must be set to `true` to fire event.
  19669. *
  19670. * @event PIXI.DisplayObject#pointerout
  19671. * @param {PIXI.interaction.InteractionEvent} event - Interaction event
  19672. */
  19673. /**
  19674. * Fired when a touch point is placed on the display object.
  19675. * DisplayObject's `interactive` property must be set to `true` to fire event.
  19676. *
  19677. * @event PIXI.DisplayObject#touchstart
  19678. * @param {PIXI.interaction.InteractionEvent} event - Interaction event
  19679. */
  19680. /**
  19681. * Fired when a touch point is removed from the display object.
  19682. * DisplayObject's `interactive` property must be set to `true` to fire event.
  19683. *
  19684. * @event PIXI.DisplayObject#touchend
  19685. * @param {PIXI.interaction.InteractionEvent} event - Interaction event
  19686. */
  19687. /**
  19688. * Fired when the operating system cancels a touch.
  19689. * DisplayObject's `interactive` property must be set to `true` to fire event.
  19690. *
  19691. * @event PIXI.DisplayObject#touchcancel
  19692. * @param {PIXI.interaction.InteractionEvent} event - Interaction event
  19693. */
  19694. /**
  19695. * Fired when a touch point is placed and removed from the display object.
  19696. * DisplayObject's `interactive` property must be set to `true` to fire event.
  19697. *
  19698. * @event PIXI.DisplayObject#tap
  19699. * @param {PIXI.interaction.InteractionEvent} event - Interaction event
  19700. */
  19701. /**
  19702. * Fired when a touch point is removed outside of the display object that initially
  19703. * registered a [touchstart]{@link PIXI.DisplayObject#event:touchstart}.
  19704. * DisplayObject's `interactive` property must be set to `true` to fire event.
  19705. *
  19706. * @event PIXI.DisplayObject#touchendoutside
  19707. * @param {PIXI.interaction.InteractionEvent} event - Interaction event
  19708. */
  19709. /**
  19710. * Fired when a touch point is moved along the display object.
  19711. * DisplayObject's `interactive` property must be set to `true` to fire event.
  19712. *
  19713. * @event PIXI.DisplayObject#touchmove
  19714. * @param {PIXI.interaction.InteractionEvent} event - Interaction event
  19715. */
  19716. this.setTargetElement(this.renderer.view, this.renderer.resolution);
  19717. }
  19718. if ( EventEmitter ) { InteractionManager.__proto__ = EventEmitter; }
  19719. InteractionManager.prototype = Object.create( EventEmitter && EventEmitter.prototype );
  19720. InteractionManager.prototype.constructor = InteractionManager;
  19721. /**
  19722. * Hit tests a point against the display tree, returning the first interactive object that is hit.
  19723. *
  19724. * @param {PIXI.Point} globalPoint - A point to hit test with, in global space.
  19725. * @param {PIXI.Container} [root] - The root display object to start from. If omitted, defaults
  19726. * to the last rendered root of the associated renderer.
  19727. * @return {PIXI.DisplayObject} The hit display object, if any.
  19728. */
  19729. InteractionManager.prototype.hitTest = function hitTest (globalPoint, root)
  19730. {
  19731. // clear the target for our hit test
  19732. hitTestEvent.target = null;
  19733. // assign the global point
  19734. hitTestEvent.data.global = globalPoint;
  19735. // ensure safety of the root
  19736. if (!root)
  19737. {
  19738. root = this.renderer._lastObjectRendered;
  19739. }
  19740. // run the hit test
  19741. this.processInteractive(hitTestEvent, root, null, true);
  19742. // return our found object - it'll be null if we didn't hit anything
  19743. return hitTestEvent.target;
  19744. };
  19745. /**
  19746. * Sets the DOM element which will receive mouse/touch events. This is useful for when you have
  19747. * other DOM elements on top of the renderers Canvas element. With this you'll be bale to delegate
  19748. * another DOM element to receive those events.
  19749. *
  19750. * @param {HTMLCanvasElement} element - the DOM element which will receive mouse and touch events.
  19751. * @param {number} [resolution=1] - The resolution / device pixel ratio of the new element (relative to the canvas).
  19752. */
  19753. InteractionManager.prototype.setTargetElement = function setTargetElement (element, resolution)
  19754. {
  19755. if ( resolution === void 0 ) { resolution = 1; }
  19756. this.removeEvents();
  19757. this.interactionDOMElement = element;
  19758. this.resolution = resolution;
  19759. this.addEvents();
  19760. };
  19761. /**
  19762. * Registers all the DOM events
  19763. *
  19764. * @private
  19765. */
  19766. InteractionManager.prototype.addEvents = function addEvents ()
  19767. {
  19768. if (!this.interactionDOMElement)
  19769. {
  19770. return;
  19771. }
  19772. Ticker.system.add(this.update, this, UPDATE_PRIORITY.INTERACTION);
  19773. if (window.navigator.msPointerEnabled)
  19774. {
  19775. this.interactionDOMElement.style['-ms-content-zooming'] = 'none';
  19776. this.interactionDOMElement.style['-ms-touch-action'] = 'none';
  19777. }
  19778. else if (this.supportsPointerEvents)
  19779. {
  19780. this.interactionDOMElement.style['touch-action'] = 'none';
  19781. }
  19782. /**
  19783. * These events are added first, so that if pointer events are normalized, they are fired
  19784. * in the same order as non-normalized events. ie. pointer event 1st, mouse / touch 2nd
  19785. */
  19786. if (this.supportsPointerEvents)
  19787. {
  19788. window.document.addEventListener('pointermove', this.onPointerMove, true);
  19789. this.interactionDOMElement.addEventListener('pointerdown', this.onPointerDown, true);
  19790. // pointerout is fired in addition to pointerup (for touch events) and pointercancel
  19791. // we already handle those, so for the purposes of what we do in onPointerOut, we only
  19792. // care about the pointerleave event
  19793. this.interactionDOMElement.addEventListener('pointerleave', this.onPointerOut, true);
  19794. this.interactionDOMElement.addEventListener('pointerover', this.onPointerOver, true);
  19795. window.addEventListener('pointercancel', this.onPointerCancel, true);
  19796. window.addEventListener('pointerup', this.onPointerUp, true);
  19797. }
  19798. else
  19799. {
  19800. window.document.addEventListener('mousemove', this.onPointerMove, true);
  19801. this.interactionDOMElement.addEventListener('mousedown', this.onPointerDown, true);
  19802. this.interactionDOMElement.addEventListener('mouseout', this.onPointerOut, true);
  19803. this.interactionDOMElement.addEventListener('mouseover', this.onPointerOver, true);
  19804. window.addEventListener('mouseup', this.onPointerUp, true);
  19805. }
  19806. // always look directly for touch events so that we can provide original data
  19807. // In a future version we should change this to being just a fallback and rely solely on
  19808. // PointerEvents whenever available
  19809. if (this.supportsTouchEvents)
  19810. {
  19811. this.interactionDOMElement.addEventListener('touchstart', this.onPointerDown, true);
  19812. this.interactionDOMElement.addEventListener('touchcancel', this.onPointerCancel, true);
  19813. this.interactionDOMElement.addEventListener('touchend', this.onPointerUp, true);
  19814. this.interactionDOMElement.addEventListener('touchmove', this.onPointerMove, true);
  19815. }
  19816. this.eventsAdded = true;
  19817. };
  19818. /**
  19819. * Removes all the DOM events that were previously registered
  19820. *
  19821. * @private
  19822. */
  19823. InteractionManager.prototype.removeEvents = function removeEvents ()
  19824. {
  19825. if (!this.interactionDOMElement)
  19826. {
  19827. return;
  19828. }
  19829. Ticker.system.remove(this.update, this);
  19830. if (window.navigator.msPointerEnabled)
  19831. {
  19832. this.interactionDOMElement.style['-ms-content-zooming'] = '';
  19833. this.interactionDOMElement.style['-ms-touch-action'] = '';
  19834. }
  19835. else if (this.supportsPointerEvents)
  19836. {
  19837. this.interactionDOMElement.style['touch-action'] = '';
  19838. }
  19839. if (this.supportsPointerEvents)
  19840. {
  19841. window.document.removeEventListener('pointermove', this.onPointerMove, true);
  19842. this.interactionDOMElement.removeEventListener('pointerdown', this.onPointerDown, true);
  19843. this.interactionDOMElement.removeEventListener('pointerleave', this.onPointerOut, true);
  19844. this.interactionDOMElement.removeEventListener('pointerover', this.onPointerOver, true);
  19845. window.removeEventListener('pointercancel', this.onPointerCancel, true);
  19846. window.removeEventListener('pointerup', this.onPointerUp, true);
  19847. }
  19848. else
  19849. {
  19850. window.document.removeEventListener('mousemove', this.onPointerMove, true);
  19851. this.interactionDOMElement.removeEventListener('mousedown', this.onPointerDown, true);
  19852. this.interactionDOMElement.removeEventListener('mouseout', this.onPointerOut, true);
  19853. this.interactionDOMElement.removeEventListener('mouseover', this.onPointerOver, true);
  19854. window.removeEventListener('mouseup', this.onPointerUp, true);
  19855. }
  19856. if (this.supportsTouchEvents)
  19857. {
  19858. this.interactionDOMElement.removeEventListener('touchstart', this.onPointerDown, true);
  19859. this.interactionDOMElement.removeEventListener('touchcancel', this.onPointerCancel, true);
  19860. this.interactionDOMElement.removeEventListener('touchend', this.onPointerUp, true);
  19861. this.interactionDOMElement.removeEventListener('touchmove', this.onPointerMove, true);
  19862. }
  19863. this.interactionDOMElement = null;
  19864. this.eventsAdded = false;
  19865. };
  19866. /**
  19867. * Updates the state of interactive objects.
  19868. * Invoked by a throttled ticker update from {@link PIXI.Ticker.system}.
  19869. *
  19870. * @param {number} deltaTime - time delta since last tick
  19871. */
  19872. InteractionManager.prototype.update = function update (deltaTime)
  19873. {
  19874. this._deltaTime += deltaTime;
  19875. if (this._deltaTime < this.interactionFrequency)
  19876. {
  19877. return;
  19878. }
  19879. this._deltaTime = 0;
  19880. if (!this.interactionDOMElement)
  19881. {
  19882. return;
  19883. }
  19884. // if the user move the mouse this check has already been done using the mouse move!
  19885. if (this.didMove)
  19886. {
  19887. this.didMove = false;
  19888. return;
  19889. }
  19890. this.cursor = null;
  19891. // Resets the flag as set by a stopPropagation call. This flag is usually reset by a user interaction of any kind,
  19892. // but there was a scenario of a display object moving under a static mouse cursor.
  19893. // In this case, mouseover and mouseevents would not pass the flag test in dispatchEvent function
  19894. for (var k in this.activeInteractionData)
  19895. {
  19896. // eslint-disable-next-line no-prototype-builtins
  19897. if (this.activeInteractionData.hasOwnProperty(k))
  19898. {
  19899. var interactionData = this.activeInteractionData[k];
  19900. if (interactionData.originalEvent && interactionData.pointerType !== 'touch')
  19901. {
  19902. var interactionEvent = this.configureInteractionEventForDOMEvent(
  19903. this.eventData,
  19904. interactionData.originalEvent,
  19905. interactionData
  19906. );
  19907. this.processInteractive(
  19908. interactionEvent,
  19909. this.renderer._lastObjectRendered,
  19910. this.processPointerOverOut,
  19911. true
  19912. );
  19913. }
  19914. }
  19915. }
  19916. this.setCursorMode(this.cursor);
  19917. // TODO
  19918. };
  19919. /**
  19920. * Sets the current cursor mode, handling any callbacks or CSS style changes.
  19921. *
  19922. * @param {string} mode - cursor mode, a key from the cursorStyles dictionary
  19923. */
  19924. InteractionManager.prototype.setCursorMode = function setCursorMode (mode)
  19925. {
  19926. mode = mode || 'default';
  19927. // if the mode didn't actually change, bail early
  19928. if (this.currentCursorMode === mode)
  19929. {
  19930. return;
  19931. }
  19932. this.currentCursorMode = mode;
  19933. var style = this.cursorStyles[mode];
  19934. // only do things if there is a cursor style for it
  19935. if (style)
  19936. {
  19937. switch (typeof style)
  19938. {
  19939. case 'string':
  19940. // string styles are handled as cursor CSS
  19941. this.interactionDOMElement.style.cursor = style;
  19942. break;
  19943. case 'function':
  19944. // functions are just called, and passed the cursor mode
  19945. style(mode);
  19946. break;
  19947. case 'object':
  19948. // if it is an object, assume that it is a dictionary of CSS styles,
  19949. // apply it to the interactionDOMElement
  19950. Object.assign(this.interactionDOMElement.style, style);
  19951. break;
  19952. }
  19953. }
  19954. else if (typeof mode === 'string' && !Object.prototype.hasOwnProperty.call(this.cursorStyles, mode))
  19955. {
  19956. // if it mode is a string (not a Symbol) and cursorStyles doesn't have any entry
  19957. // for the mode, then assume that the dev wants it to be CSS for the cursor.
  19958. this.interactionDOMElement.style.cursor = mode;
  19959. }
  19960. };
  19961. /**
  19962. * Dispatches an event on the display object that was interacted with
  19963. *
  19964. * @param {PIXI.Container|PIXI.Sprite|PIXI.TilingSprite} displayObject - the display object in question
  19965. * @param {string} eventString - the name of the event (e.g, mousedown)
  19966. * @param {object} eventData - the event data object
  19967. * @private
  19968. */
  19969. InteractionManager.prototype.dispatchEvent = function dispatchEvent (displayObject, eventString, eventData)
  19970. {
  19971. if (!eventData.stopped)
  19972. {
  19973. eventData.currentTarget = displayObject;
  19974. eventData.type = eventString;
  19975. displayObject.emit(eventString, eventData);
  19976. if (displayObject[eventString])
  19977. {
  19978. displayObject[eventString](eventData);
  19979. }
  19980. }
  19981. };
  19982. /**
  19983. * Maps x and y coords from a DOM object and maps them correctly to the PixiJS view. The
  19984. * resulting value is stored in the point. This takes into account the fact that the DOM
  19985. * element could be scaled and positioned anywhere on the screen.
  19986. *
  19987. * @param {PIXI.Point} point - the point that the result will be stored in
  19988. * @param {number} x - the x coord of the position to map
  19989. * @param {number} y - the y coord of the position to map
  19990. */
  19991. InteractionManager.prototype.mapPositionToPoint = function mapPositionToPoint (point, x, y)
  19992. {
  19993. var rect;
  19994. // IE 11 fix
  19995. if (!this.interactionDOMElement.parentElement)
  19996. {
  19997. rect = { x: 0, y: 0, width: 0, height: 0 };
  19998. }
  19999. else
  20000. {
  20001. rect = this.interactionDOMElement.getBoundingClientRect();
  20002. }
  20003. var resolutionMultiplier = 1.0 / this.resolution;
  20004. point.x = ((x - rect.left) * (this.interactionDOMElement.width / rect.width)) * resolutionMultiplier;
  20005. point.y = ((y - rect.top) * (this.interactionDOMElement.height / rect.height)) * resolutionMultiplier;
  20006. };
  20007. /**
  20008. * This function is provides a neat way of crawling through the scene graph and running a
  20009. * specified function on all interactive objects it finds. It will also take care of hit
  20010. * testing the interactive objects and passes the hit across in the function.
  20011. *
  20012. * @protected
  20013. * @param {PIXI.interaction.InteractionEvent} interactionEvent - event containing the point that
  20014. * is tested for collision
  20015. * @param {PIXI.Container|PIXI.Sprite|PIXI.TilingSprite} displayObject - the displayObject
  20016. * that will be hit test (recursively crawls its children)
  20017. * @param {Function} [func] - the function that will be called on each interactive object. The
  20018. * interactionEvent, displayObject and hit will be passed to the function
  20019. * @param {boolean} [hitTest] - this indicates if the objects inside should be hit test against the point
  20020. * @param {boolean} [interactive] - Whether the displayObject is interactive
  20021. * @return {boolean} returns true if the displayObject hit the point
  20022. */
  20023. InteractionManager.prototype.processInteractive = function processInteractive (interactionEvent, displayObject, func, hitTest, interactive)
  20024. {
  20025. if (!displayObject || !displayObject.visible)
  20026. {
  20027. return false;
  20028. }
  20029. var point = interactionEvent.data.global;
  20030. // Took a little while to rework this function correctly! But now it is done and nice and optimized! ^_^
  20031. //
  20032. // This function will now loop through all objects and then only hit test the objects it HAS
  20033. // to, not all of them. MUCH faster..
  20034. // An object will be hit test if the following is true:
  20035. //
  20036. // 1: It is interactive.
  20037. // 2: It belongs to a parent that is interactive AND one of the parents children have not already been hit.
  20038. //
  20039. // As another little optimization once an interactive object has been hit we can carry on
  20040. // through the scenegraph, but we know that there will be no more hits! So we can avoid extra hit tests
  20041. // A final optimization is that an object is not hit test directly if a child has already been hit.
  20042. interactive = displayObject.interactive || interactive;
  20043. var hit = false;
  20044. var interactiveParent = interactive;
  20045. // Flag here can set to false if the event is outside the parents hitArea or mask
  20046. var hitTestChildren = true;
  20047. // If there is a hitArea, no need to test against anything else if the pointer is not within the hitArea
  20048. // There is also no longer a need to hitTest children.
  20049. if (displayObject.hitArea)
  20050. {
  20051. if (hitTest)
  20052. {
  20053. displayObject.worldTransform.applyInverse(point, this._tempPoint);
  20054. if (!displayObject.hitArea.contains(this._tempPoint.x, this._tempPoint.y))
  20055. {
  20056. hitTest = false;
  20057. hitTestChildren = false;
  20058. }
  20059. else
  20060. {
  20061. hit = true;
  20062. }
  20063. }
  20064. interactiveParent = false;
  20065. }
  20066. // If there is a mask, no need to hitTest against anything else if the pointer is not within the mask.
  20067. // We still want to hitTestChildren, however, to ensure a mouseout can still be generated.
  20068. // https://github.com/pixijs/pixi.js/issues/5135
  20069. else if (displayObject._mask)
  20070. {
  20071. if (hitTest)
  20072. {
  20073. if (!(displayObject._mask.containsPoint && displayObject._mask.containsPoint(point)))
  20074. {
  20075. hitTest = false;
  20076. }
  20077. }
  20078. }
  20079. // ** FREE TIP **! If an object is not interactive or has no buttons in it
  20080. // (such as a game scene!) set interactiveChildren to false for that displayObject.
  20081. // This will allow PixiJS to completely ignore and bypass checking the displayObjects children.
  20082. if (hitTestChildren && displayObject.interactiveChildren && displayObject.children)
  20083. {
  20084. var children = displayObject.children;
  20085. for (var i = children.length - 1; i >= 0; i--)
  20086. {
  20087. var child = children[i];
  20088. // time to get recursive.. if this function will return if something is hit..
  20089. var childHit = this.processInteractive(interactionEvent, child, func, hitTest, interactiveParent);
  20090. if (childHit)
  20091. {
  20092. // its a good idea to check if a child has lost its parent.
  20093. // this means it has been removed whilst looping so its best
  20094. if (!child.parent)
  20095. {
  20096. continue;
  20097. }
  20098. // we no longer need to hit test any more objects in this container as we we
  20099. // now know the parent has been hit
  20100. interactiveParent = false;
  20101. // If the child is interactive , that means that the object hit was actually
  20102. // interactive and not just the child of an interactive object.
  20103. // This means we no longer need to hit test anything else. We still need to run
  20104. // through all objects, but we don't need to perform any hit tests.
  20105. if (childHit)
  20106. {
  20107. if (interactionEvent.target)
  20108. {
  20109. hitTest = false;
  20110. }
  20111. hit = true;
  20112. }
  20113. }
  20114. }
  20115. }
  20116. // no point running this if the item is not interactive or does not have an interactive parent.
  20117. if (interactive)
  20118. {
  20119. // if we are hit testing (as in we have no hit any objects yet)
  20120. // We also don't need to worry about hit testing if once of the displayObjects children
  20121. // has already been hit - but only if it was interactive, otherwise we need to keep
  20122. // looking for an interactive child, just in case we hit one
  20123. if (hitTest && !interactionEvent.target)
  20124. {
  20125. // already tested against hitArea if it is defined
  20126. if (!displayObject.hitArea && displayObject.containsPoint)
  20127. {
  20128. if (displayObject.containsPoint(point))
  20129. {
  20130. hit = true;
  20131. }
  20132. }
  20133. }
  20134. if (displayObject.interactive)
  20135. {
  20136. if (hit && !interactionEvent.target)
  20137. {
  20138. interactionEvent.target = displayObject;
  20139. }
  20140. if (func)
  20141. {
  20142. func(interactionEvent, displayObject, !!hit);
  20143. }
  20144. }
  20145. }
  20146. return hit;
  20147. };
  20148. /**
  20149. * Is called when the pointer button is pressed down on the renderer element
  20150. *
  20151. * @private
  20152. * @param {PointerEvent} originalEvent - The DOM event of a pointer button being pressed down
  20153. */
  20154. InteractionManager.prototype.onPointerDown = function onPointerDown (originalEvent)
  20155. {
  20156. // if we support touch events, then only use those for touch events, not pointer events
  20157. if (this.supportsTouchEvents && originalEvent.pointerType === 'touch') { return; }
  20158. var events = this.normalizeToPointerData(originalEvent);
  20159. /**
  20160. * No need to prevent default on natural pointer events, as there are no side effects
  20161. * Normalized events, however, may have the double mousedown/touchstart issue on the native android browser,
  20162. * so still need to be prevented.
  20163. */
  20164. // Guaranteed that there will be at least one event in events, and all events must have the same pointer type
  20165. if (this.autoPreventDefault && events[0].isNormalized)
  20166. {
  20167. var cancelable = originalEvent.cancelable || !('cancelable' in originalEvent);
  20168. if (cancelable)
  20169. {
  20170. originalEvent.preventDefault();
  20171. }
  20172. }
  20173. var eventLen = events.length;
  20174. for (var i = 0; i < eventLen; i++)
  20175. {
  20176. var event = events[i];
  20177. var interactionData = this.getInteractionDataForPointerId(event);
  20178. var interactionEvent = this.configureInteractionEventForDOMEvent(this.eventData, event, interactionData);
  20179. interactionEvent.data.originalEvent = originalEvent;
  20180. this.processInteractive(interactionEvent, this.renderer._lastObjectRendered, this.processPointerDown, true);
  20181. this.emit('pointerdown', interactionEvent);
  20182. if (event.pointerType === 'touch')
  20183. {
  20184. this.emit('touchstart', interactionEvent);
  20185. }
  20186. // emit a mouse event for "pen" pointers, the way a browser would emit a fallback event
  20187. else if (event.pointerType === 'mouse' || event.pointerType === 'pen')
  20188. {
  20189. var isRightButton = event.button === 2;
  20190. this.emit(isRightButton ? 'rightdown' : 'mousedown', this.eventData);
  20191. }
  20192. }
  20193. };
  20194. /**
  20195. * Processes the result of the pointer down check and dispatches the event if need be
  20196. *
  20197. * @private
  20198. * @param {PIXI.interaction.InteractionEvent} interactionEvent - The interaction event wrapping the DOM event
  20199. * @param {PIXI.Container|PIXI.Sprite|PIXI.TilingSprite} displayObject - The display object that was tested
  20200. * @param {boolean} hit - the result of the hit test on the display object
  20201. */
  20202. InteractionManager.prototype.processPointerDown = function processPointerDown (interactionEvent, displayObject, hit)
  20203. {
  20204. var data = interactionEvent.data;
  20205. var id = interactionEvent.data.identifier;
  20206. if (hit)
  20207. {
  20208. if (!displayObject.trackedPointers[id])
  20209. {
  20210. displayObject.trackedPointers[id] = new InteractionTrackingData(id);
  20211. }
  20212. this.dispatchEvent(displayObject, 'pointerdown', interactionEvent);
  20213. if (data.pointerType === 'touch')
  20214. {
  20215. this.dispatchEvent(displayObject, 'touchstart', interactionEvent);
  20216. }
  20217. else if (data.pointerType === 'mouse' || data.pointerType === 'pen')
  20218. {
  20219. var isRightButton = data.button === 2;
  20220. if (isRightButton)
  20221. {
  20222. displayObject.trackedPointers[id].rightDown = true;
  20223. }
  20224. else
  20225. {
  20226. displayObject.trackedPointers[id].leftDown = true;
  20227. }
  20228. this.dispatchEvent(displayObject, isRightButton ? 'rightdown' : 'mousedown', interactionEvent);
  20229. }
  20230. }
  20231. };
  20232. /**
  20233. * Is called when the pointer button is released on the renderer element
  20234. *
  20235. * @private
  20236. * @param {PointerEvent} originalEvent - The DOM event of a pointer button being released
  20237. * @param {boolean} cancelled - true if the pointer is cancelled
  20238. * @param {Function} func - Function passed to {@link processInteractive}
  20239. */
  20240. InteractionManager.prototype.onPointerComplete = function onPointerComplete (originalEvent, cancelled, func)
  20241. {
  20242. var events = this.normalizeToPointerData(originalEvent);
  20243. var eventLen = events.length;
  20244. // if the event wasn't targeting our canvas, then consider it to be pointerupoutside
  20245. // in all cases (unless it was a pointercancel)
  20246. var eventAppend = originalEvent.target !== this.interactionDOMElement ? 'outside' : '';
  20247. for (var i = 0; i < eventLen; i++)
  20248. {
  20249. var event = events[i];
  20250. var interactionData = this.getInteractionDataForPointerId(event);
  20251. var interactionEvent = this.configureInteractionEventForDOMEvent(this.eventData, event, interactionData);
  20252. interactionEvent.data.originalEvent = originalEvent;
  20253. // perform hit testing for events targeting our canvas or cancel events
  20254. this.processInteractive(interactionEvent, this.renderer._lastObjectRendered, func, cancelled || !eventAppend);
  20255. this.emit(cancelled ? 'pointercancel' : ("pointerup" + eventAppend), interactionEvent);
  20256. if (event.pointerType === 'mouse' || event.pointerType === 'pen')
  20257. {
  20258. var isRightButton = event.button === 2;
  20259. this.emit(isRightButton ? ("rightup" + eventAppend) : ("mouseup" + eventAppend), interactionEvent);
  20260. }
  20261. else if (event.pointerType === 'touch')
  20262. {
  20263. this.emit(cancelled ? 'touchcancel' : ("touchend" + eventAppend), interactionEvent);
  20264. this.releaseInteractionDataForPointerId(event.pointerId, interactionData);
  20265. }
  20266. }
  20267. };
  20268. /**
  20269. * Is called when the pointer button is cancelled
  20270. *
  20271. * @private
  20272. * @param {PointerEvent} event - The DOM event of a pointer button being released
  20273. */
  20274. InteractionManager.prototype.onPointerCancel = function onPointerCancel (event)
  20275. {
  20276. // if we support touch events, then only use those for touch events, not pointer events
  20277. if (this.supportsTouchEvents && event.pointerType === 'touch') { return; }
  20278. this.onPointerComplete(event, true, this.processPointerCancel);
  20279. };
  20280. /**
  20281. * Processes the result of the pointer cancel check and dispatches the event if need be
  20282. *
  20283. * @private
  20284. * @param {PIXI.interaction.InteractionEvent} interactionEvent - The interaction event wrapping the DOM event
  20285. * @param {PIXI.Container|PIXI.Sprite|PIXI.TilingSprite} displayObject - The display object that was tested
  20286. */
  20287. InteractionManager.prototype.processPointerCancel = function processPointerCancel (interactionEvent, displayObject)
  20288. {
  20289. var data = interactionEvent.data;
  20290. var id = interactionEvent.data.identifier;
  20291. if (displayObject.trackedPointers[id] !== undefined)
  20292. {
  20293. delete displayObject.trackedPointers[id];
  20294. this.dispatchEvent(displayObject, 'pointercancel', interactionEvent);
  20295. if (data.pointerType === 'touch')
  20296. {
  20297. this.dispatchEvent(displayObject, 'touchcancel', interactionEvent);
  20298. }
  20299. }
  20300. };
  20301. /**
  20302. * Is called when the pointer button is released on the renderer element
  20303. *
  20304. * @private
  20305. * @param {PointerEvent} event - The DOM event of a pointer button being released
  20306. */
  20307. InteractionManager.prototype.onPointerUp = function onPointerUp (event)
  20308. {
  20309. // if we support touch events, then only use those for touch events, not pointer events
  20310. if (this.supportsTouchEvents && event.pointerType === 'touch') { return; }
  20311. this.onPointerComplete(event, false, this.processPointerUp);
  20312. };
  20313. /**
  20314. * Processes the result of the pointer up check and dispatches the event if need be
  20315. *
  20316. * @private
  20317. * @param {PIXI.interaction.InteractionEvent} interactionEvent - The interaction event wrapping the DOM event
  20318. * @param {PIXI.Container|PIXI.Sprite|PIXI.TilingSprite} displayObject - The display object that was tested
  20319. * @param {boolean} hit - the result of the hit test on the display object
  20320. */
  20321. InteractionManager.prototype.processPointerUp = function processPointerUp (interactionEvent, displayObject, hit)
  20322. {
  20323. var data = interactionEvent.data;
  20324. var id = interactionEvent.data.identifier;
  20325. var trackingData = displayObject.trackedPointers[id];
  20326. var isTouch = data.pointerType === 'touch';
  20327. var isMouse = (data.pointerType === 'mouse' || data.pointerType === 'pen');
  20328. // need to track mouse down status in the mouse block so that we can emit
  20329. // event in a later block
  20330. var isMouseTap = false;
  20331. // Mouse only
  20332. if (isMouse)
  20333. {
  20334. var isRightButton = data.button === 2;
  20335. var flags = InteractionTrackingData.FLAGS;
  20336. var test = isRightButton ? flags.RIGHT_DOWN : flags.LEFT_DOWN;
  20337. var isDown = trackingData !== undefined && (trackingData.flags & test);
  20338. if (hit)
  20339. {
  20340. this.dispatchEvent(displayObject, isRightButton ? 'rightup' : 'mouseup', interactionEvent);
  20341. if (isDown)
  20342. {
  20343. this.dispatchEvent(displayObject, isRightButton ? 'rightclick' : 'click', interactionEvent);
  20344. // because we can confirm that the mousedown happened on this object, flag for later emit of pointertap
  20345. isMouseTap = true;
  20346. }
  20347. }
  20348. else if (isDown)
  20349. {
  20350. this.dispatchEvent(displayObject, isRightButton ? 'rightupoutside' : 'mouseupoutside', interactionEvent);
  20351. }
  20352. // update the down state of the tracking data
  20353. if (trackingData)
  20354. {
  20355. if (isRightButton)
  20356. {
  20357. trackingData.rightDown = false;
  20358. }
  20359. else
  20360. {
  20361. trackingData.leftDown = false;
  20362. }
  20363. }
  20364. }
  20365. // Pointers and Touches, and Mouse
  20366. if (hit)
  20367. {
  20368. this.dispatchEvent(displayObject, 'pointerup', interactionEvent);
  20369. if (isTouch) { this.dispatchEvent(displayObject, 'touchend', interactionEvent); }
  20370. if (trackingData)
  20371. {
  20372. // emit pointertap if not a mouse, or if the mouse block decided it was a tap
  20373. if (!isMouse || isMouseTap)
  20374. {
  20375. this.dispatchEvent(displayObject, 'pointertap', interactionEvent);
  20376. }
  20377. if (isTouch)
  20378. {
  20379. this.dispatchEvent(displayObject, 'tap', interactionEvent);
  20380. // touches are no longer over (if they ever were) when we get the touchend
  20381. // so we should ensure that we don't keep pretending that they are
  20382. trackingData.over = false;
  20383. }
  20384. }
  20385. }
  20386. else if (trackingData)
  20387. {
  20388. this.dispatchEvent(displayObject, 'pointerupoutside', interactionEvent);
  20389. if (isTouch) { this.dispatchEvent(displayObject, 'touchendoutside', interactionEvent); }
  20390. }
  20391. // Only remove the tracking data if there is no over/down state still associated with it
  20392. if (trackingData && trackingData.none)
  20393. {
  20394. delete displayObject.trackedPointers[id];
  20395. }
  20396. };
  20397. /**
  20398. * Is called when the pointer moves across the renderer element
  20399. *
  20400. * @private
  20401. * @param {PointerEvent} originalEvent - The DOM event of a pointer moving
  20402. */
  20403. InteractionManager.prototype.onPointerMove = function onPointerMove (originalEvent)
  20404. {
  20405. // if we support touch events, then only use those for touch events, not pointer events
  20406. if (this.supportsTouchEvents && originalEvent.pointerType === 'touch') { return; }
  20407. var events = this.normalizeToPointerData(originalEvent);
  20408. if (events[0].pointerType === 'mouse' || events[0].pointerType === 'pen')
  20409. {
  20410. this.didMove = true;
  20411. this.cursor = null;
  20412. }
  20413. var eventLen = events.length;
  20414. for (var i = 0; i < eventLen; i++)
  20415. {
  20416. var event = events[i];
  20417. var interactionData = this.getInteractionDataForPointerId(event);
  20418. var interactionEvent = this.configureInteractionEventForDOMEvent(this.eventData, event, interactionData);
  20419. interactionEvent.data.originalEvent = originalEvent;
  20420. var interactive = event.pointerType === 'touch' ? this.moveWhenInside : true;
  20421. this.processInteractive(
  20422. interactionEvent,
  20423. this.renderer._lastObjectRendered,
  20424. this.processPointerMove,
  20425. interactive
  20426. );
  20427. this.emit('pointermove', interactionEvent);
  20428. if (event.pointerType === 'touch') { this.emit('touchmove', interactionEvent); }
  20429. if (event.pointerType === 'mouse' || event.pointerType === 'pen') { this.emit('mousemove', interactionEvent); }
  20430. }
  20431. if (events[0].pointerType === 'mouse')
  20432. {
  20433. this.setCursorMode(this.cursor);
  20434. // TODO BUG for parents interactive object (border order issue)
  20435. }
  20436. };
  20437. /**
  20438. * Processes the result of the pointer move check and dispatches the event if need be
  20439. *
  20440. * @private
  20441. * @param {PIXI.interaction.InteractionEvent} interactionEvent - The interaction event wrapping the DOM event
  20442. * @param {PIXI.Container|PIXI.Sprite|PIXI.TilingSprite} displayObject - The display object that was tested
  20443. * @param {boolean} hit - the result of the hit test on the display object
  20444. */
  20445. InteractionManager.prototype.processPointerMove = function processPointerMove (interactionEvent, displayObject, hit)
  20446. {
  20447. var data = interactionEvent.data;
  20448. var isTouch = data.pointerType === 'touch';
  20449. var isMouse = (data.pointerType === 'mouse' || data.pointerType === 'pen');
  20450. if (isMouse)
  20451. {
  20452. this.processPointerOverOut(interactionEvent, displayObject, hit);
  20453. }
  20454. if (!this.moveWhenInside || hit)
  20455. {
  20456. this.dispatchEvent(displayObject, 'pointermove', interactionEvent);
  20457. if (isTouch) { this.dispatchEvent(displayObject, 'touchmove', interactionEvent); }
  20458. if (isMouse) { this.dispatchEvent(displayObject, 'mousemove', interactionEvent); }
  20459. }
  20460. };
  20461. /**
  20462. * Is called when the pointer is moved out of the renderer element
  20463. *
  20464. * @private
  20465. * @param {PointerEvent} originalEvent - The DOM event of a pointer being moved out
  20466. */
  20467. InteractionManager.prototype.onPointerOut = function onPointerOut (originalEvent)
  20468. {
  20469. // if we support touch events, then only use those for touch events, not pointer events
  20470. if (this.supportsTouchEvents && originalEvent.pointerType === 'touch') { return; }
  20471. var events = this.normalizeToPointerData(originalEvent);
  20472. // Only mouse and pointer can call onPointerOut, so events will always be length 1
  20473. var event = events[0];
  20474. if (event.pointerType === 'mouse')
  20475. {
  20476. this.mouseOverRenderer = false;
  20477. this.setCursorMode(null);
  20478. }
  20479. var interactionData = this.getInteractionDataForPointerId(event);
  20480. var interactionEvent = this.configureInteractionEventForDOMEvent(this.eventData, event, interactionData);
  20481. interactionEvent.data.originalEvent = event;
  20482. this.processInteractive(interactionEvent, this.renderer._lastObjectRendered, this.processPointerOverOut, false);
  20483. this.emit('pointerout', interactionEvent);
  20484. if (event.pointerType === 'mouse' || event.pointerType === 'pen')
  20485. {
  20486. this.emit('mouseout', interactionEvent);
  20487. }
  20488. else
  20489. {
  20490. // we can get touchleave events after touchend, so we want to make sure we don't
  20491. // introduce memory leaks
  20492. this.releaseInteractionDataForPointerId(interactionData.identifier);
  20493. }
  20494. };
  20495. /**
  20496. * Processes the result of the pointer over/out check and dispatches the event if need be
  20497. *
  20498. * @private
  20499. * @param {PIXI.interaction.InteractionEvent} interactionEvent - The interaction event wrapping the DOM event
  20500. * @param {PIXI.Container|PIXI.Sprite|PIXI.TilingSprite} displayObject - The display object that was tested
  20501. * @param {boolean} hit - the result of the hit test on the display object
  20502. */
  20503. InteractionManager.prototype.processPointerOverOut = function processPointerOverOut (interactionEvent, displayObject, hit)
  20504. {
  20505. var data = interactionEvent.data;
  20506. var id = interactionEvent.data.identifier;
  20507. var isMouse = (data.pointerType === 'mouse' || data.pointerType === 'pen');
  20508. var trackingData = displayObject.trackedPointers[id];
  20509. // if we just moused over the display object, then we need to track that state
  20510. if (hit && !trackingData)
  20511. {
  20512. trackingData = displayObject.trackedPointers[id] = new InteractionTrackingData(id);
  20513. }
  20514. if (trackingData === undefined) { return; }
  20515. if (hit && this.mouseOverRenderer)
  20516. {
  20517. if (!trackingData.over)
  20518. {
  20519. trackingData.over = true;
  20520. this.dispatchEvent(displayObject, 'pointerover', interactionEvent);
  20521. if (isMouse)
  20522. {
  20523. this.dispatchEvent(displayObject, 'mouseover', interactionEvent);
  20524. }
  20525. }
  20526. // only change the cursor if it has not already been changed (by something deeper in the
  20527. // display tree)
  20528. if (isMouse && this.cursor === null)
  20529. {
  20530. this.cursor = displayObject.cursor;
  20531. }
  20532. }
  20533. else if (trackingData.over)
  20534. {
  20535. trackingData.over = false;
  20536. this.dispatchEvent(displayObject, 'pointerout', this.eventData);
  20537. if (isMouse)
  20538. {
  20539. this.dispatchEvent(displayObject, 'mouseout', interactionEvent);
  20540. }
  20541. // if there is no mouse down information for the pointer, then it is safe to delete
  20542. if (trackingData.none)
  20543. {
  20544. delete displayObject.trackedPointers[id];
  20545. }
  20546. }
  20547. };
  20548. /**
  20549. * Is called when the pointer is moved into the renderer element
  20550. *
  20551. * @private
  20552. * @param {PointerEvent} originalEvent - The DOM event of a pointer button being moved into the renderer view
  20553. */
  20554. InteractionManager.prototype.onPointerOver = function onPointerOver (originalEvent)
  20555. {
  20556. var events = this.normalizeToPointerData(originalEvent);
  20557. // Only mouse and pointer can call onPointerOver, so events will always be length 1
  20558. var event = events[0];
  20559. var interactionData = this.getInteractionDataForPointerId(event);
  20560. var interactionEvent = this.configureInteractionEventForDOMEvent(this.eventData, event, interactionData);
  20561. interactionEvent.data.originalEvent = event;
  20562. if (event.pointerType === 'mouse')
  20563. {
  20564. this.mouseOverRenderer = true;
  20565. }
  20566. this.emit('pointerover', interactionEvent);
  20567. if (event.pointerType === 'mouse' || event.pointerType === 'pen')
  20568. {
  20569. this.emit('mouseover', interactionEvent);
  20570. }
  20571. };
  20572. /**
  20573. * Get InteractionData for a given pointerId. Store that data as well
  20574. *
  20575. * @private
  20576. * @param {PointerEvent} event - Normalized pointer event, output from normalizeToPointerData
  20577. * @return {PIXI.interaction.InteractionData} - Interaction data for the given pointer identifier
  20578. */
  20579. InteractionManager.prototype.getInteractionDataForPointerId = function getInteractionDataForPointerId (event)
  20580. {
  20581. var pointerId = event.pointerId;
  20582. var interactionData;
  20583. if (pointerId === MOUSE_POINTER_ID || event.pointerType === 'mouse')
  20584. {
  20585. interactionData = this.mouse;
  20586. }
  20587. else if (this.activeInteractionData[pointerId])
  20588. {
  20589. interactionData = this.activeInteractionData[pointerId];
  20590. }
  20591. else
  20592. {
  20593. interactionData = this.interactionDataPool.pop() || new InteractionData();
  20594. interactionData.identifier = pointerId;
  20595. this.activeInteractionData[pointerId] = interactionData;
  20596. }
  20597. // copy properties from the event, so that we can make sure that touch/pointer specific
  20598. // data is available
  20599. interactionData.copyEvent(event);
  20600. return interactionData;
  20601. };
  20602. /**
  20603. * Return unused InteractionData to the pool, for a given pointerId
  20604. *
  20605. * @private
  20606. * @param {number} pointerId - Identifier from a pointer event
  20607. */
  20608. InteractionManager.prototype.releaseInteractionDataForPointerId = function releaseInteractionDataForPointerId (pointerId)
  20609. {
  20610. var interactionData = this.activeInteractionData[pointerId];
  20611. if (interactionData)
  20612. {
  20613. delete this.activeInteractionData[pointerId];
  20614. interactionData.reset();
  20615. this.interactionDataPool.push(interactionData);
  20616. }
  20617. };
  20618. /**
  20619. * Configure an InteractionEvent to wrap a DOM PointerEvent and InteractionData
  20620. *
  20621. * @private
  20622. * @param {PIXI.interaction.InteractionEvent} interactionEvent - The event to be configured
  20623. * @param {PointerEvent} pointerEvent - The DOM event that will be paired with the InteractionEvent
  20624. * @param {PIXI.interaction.InteractionData} interactionData - The InteractionData that will be paired
  20625. * with the InteractionEvent
  20626. * @return {PIXI.interaction.InteractionEvent} the interaction event that was passed in
  20627. */
  20628. InteractionManager.prototype.configureInteractionEventForDOMEvent = function configureInteractionEventForDOMEvent (interactionEvent, pointerEvent, interactionData)
  20629. {
  20630. interactionEvent.data = interactionData;
  20631. this.mapPositionToPoint(interactionData.global, pointerEvent.clientX, pointerEvent.clientY);
  20632. // Not really sure why this is happening, but it's how a previous version handled things
  20633. if (pointerEvent.pointerType === 'touch')
  20634. {
  20635. pointerEvent.globalX = interactionData.global.x;
  20636. pointerEvent.globalY = interactionData.global.y;
  20637. }
  20638. interactionData.originalEvent = pointerEvent;
  20639. interactionEvent.reset();
  20640. return interactionEvent;
  20641. };
  20642. /**
  20643. * Ensures that the original event object contains all data that a regular pointer event would have
  20644. *
  20645. * @private
  20646. * @param {TouchEvent|MouseEvent|PointerEvent} event - The original event data from a touch or mouse event
  20647. * @return {PointerEvent[]} An array containing a single normalized pointer event, in the case of a pointer
  20648. * or mouse event, or a multiple normalized pointer events if there are multiple changed touches
  20649. */
  20650. InteractionManager.prototype.normalizeToPointerData = function normalizeToPointerData (event)
  20651. {
  20652. var normalizedEvents = [];
  20653. if (this.supportsTouchEvents && event instanceof TouchEvent)
  20654. {
  20655. for (var i = 0, li = event.changedTouches.length; i < li; i++)
  20656. {
  20657. var touch = event.changedTouches[i];
  20658. if (typeof touch.button === 'undefined') { touch.button = event.touches.length ? 1 : 0; }
  20659. if (typeof touch.buttons === 'undefined') { touch.buttons = event.touches.length ? 1 : 0; }
  20660. if (typeof touch.isPrimary === 'undefined')
  20661. {
  20662. touch.isPrimary = event.touches.length === 1 && event.type === 'touchstart';
  20663. }
  20664. if (typeof touch.width === 'undefined') { touch.width = touch.radiusX || 1; }
  20665. if (typeof touch.height === 'undefined') { touch.height = touch.radiusY || 1; }
  20666. if (typeof touch.tiltX === 'undefined') { touch.tiltX = 0; }
  20667. if (typeof touch.tiltY === 'undefined') { touch.tiltY = 0; }
  20668. if (typeof touch.pointerType === 'undefined') { touch.pointerType = 'touch'; }
  20669. if (typeof touch.pointerId === 'undefined') { touch.pointerId = touch.identifier || 0; }
  20670. if (typeof touch.pressure === 'undefined') { touch.pressure = touch.force || 0.5; }
  20671. if (typeof touch.twist === 'undefined') { touch.twist = 0; }
  20672. if (typeof touch.tangentialPressure === 'undefined') { touch.tangentialPressure = 0; }
  20673. // TODO: Remove these, as layerX/Y is not a standard, is deprecated, has uneven
  20674. // support, and the fill ins are not quite the same
  20675. // offsetX/Y might be okay, but is not the same as clientX/Y when the canvas's top
  20676. // left is not 0,0 on the page
  20677. if (typeof touch.layerX === 'undefined') { touch.layerX = touch.offsetX = touch.clientX; }
  20678. if (typeof touch.layerY === 'undefined') { touch.layerY = touch.offsetY = touch.clientY; }
  20679. // mark the touch as normalized, just so that we know we did it
  20680. touch.isNormalized = true;
  20681. normalizedEvents.push(touch);
  20682. }
  20683. }
  20684. // apparently PointerEvent subclasses MouseEvent, so yay
  20685. else if (event instanceof MouseEvent && (!this.supportsPointerEvents || !(event instanceof window.PointerEvent)))
  20686. {
  20687. if (typeof event.isPrimary === 'undefined') { event.isPrimary = true; }
  20688. if (typeof event.width === 'undefined') { event.width = 1; }
  20689. if (typeof event.height === 'undefined') { event.height = 1; }
  20690. if (typeof event.tiltX === 'undefined') { event.tiltX = 0; }
  20691. if (typeof event.tiltY === 'undefined') { event.tiltY = 0; }
  20692. if (typeof event.pointerType === 'undefined') { event.pointerType = 'mouse'; }
  20693. if (typeof event.pointerId === 'undefined') { event.pointerId = MOUSE_POINTER_ID; }
  20694. if (typeof event.pressure === 'undefined') { event.pressure = 0.5; }
  20695. if (typeof event.twist === 'undefined') { event.twist = 0; }
  20696. if (typeof event.tangentialPressure === 'undefined') { event.tangentialPressure = 0; }
  20697. // mark the mouse event as normalized, just so that we know we did it
  20698. event.isNormalized = true;
  20699. normalizedEvents.push(event);
  20700. }
  20701. else
  20702. {
  20703. normalizedEvents.push(event);
  20704. }
  20705. return normalizedEvents;
  20706. };
  20707. /**
  20708. * Destroys the interaction manager
  20709. *
  20710. */
  20711. InteractionManager.prototype.destroy = function destroy ()
  20712. {
  20713. this.removeEvents();
  20714. this.removeAllListeners();
  20715. this.renderer = null;
  20716. this.mouse = null;
  20717. this.eventData = null;
  20718. this.interactionDOMElement = null;
  20719. this.onPointerDown = null;
  20720. this.processPointerDown = null;
  20721. this.onPointerUp = null;
  20722. this.processPointerUp = null;
  20723. this.onPointerCancel = null;
  20724. this.processPointerCancel = null;
  20725. this.onPointerMove = null;
  20726. this.processPointerMove = null;
  20727. this.onPointerOut = null;
  20728. this.processPointerOverOut = null;
  20729. this.onPointerOver = null;
  20730. this._tempPoint = null;
  20731. };
  20732. return InteractionManager;
  20733. }(eventemitter3));
  20734. var interaction_es = ({
  20735. InteractionData: InteractionData,
  20736. InteractionEvent: InteractionEvent,
  20737. InteractionManager: InteractionManager,
  20738. InteractionTrackingData: InteractionTrackingData,
  20739. interactiveTarget: interactiveTarget
  20740. });
  20741. /*!
  20742. * @pixi/graphics - v5.0.4
  20743. * Compiled Fri, 07 Jun 2019 17:17:49 UTC
  20744. *
  20745. * @pixi/graphics is licensed under the MIT License.
  20746. * http://www.opensource.org/licenses/mit-license
  20747. */
  20748. /**
  20749. * Graphics curves resolution settings. If `adaptive` flag is set to `true`,
  20750. * the resolution is calculated based on the curve's length to ensure better visual quality.
  20751. * Adaptive draw works with `bezierCurveTo` and `quadraticCurveTo`.
  20752. *
  20753. * @static
  20754. * @constant
  20755. * @memberof PIXI
  20756. * @name GRAPHICS_CURVES
  20757. * @type {object}
  20758. * @property {boolean} adaptive=false - flag indicating if the resolution should be adaptive
  20759. * @property {number} maxLength=10 - maximal length of a single segment of the curve (if adaptive = false, ignored)
  20760. * @property {number} minSegments=8 - minimal number of segments in the curve (if adaptive = false, ignored)
  20761. * @property {number} maxSegments=2048 - maximal number of segments in the curve (if adaptive = false, ignored)
  20762. */
  20763. var GRAPHICS_CURVES = {
  20764. adaptive: true,
  20765. maxLength: 10,
  20766. minSegments: 8,
  20767. maxSegments: 2048,
  20768. _segmentsCount: function _segmentsCount(length, defaultSegments)
  20769. {
  20770. if ( defaultSegments === void 0 ) { defaultSegments = 20; }
  20771. if (!this.adaptive)
  20772. {
  20773. return defaultSegments;
  20774. }
  20775. var result = Math.ceil(length / this.maxLength);
  20776. if (result < this.minSegments)
  20777. {
  20778. result = this.minSegments;
  20779. }
  20780. else if (result > this.maxSegments)
  20781. {
  20782. result = this.maxSegments;
  20783. }
  20784. return result;
  20785. },
  20786. };
  20787. /**
  20788. * Fill style object for Graphics.
  20789. *
  20790. * @class
  20791. * @memberof PIXI
  20792. */
  20793. var FillStyle = function FillStyle()
  20794. {
  20795. this.reset();
  20796. };
  20797. /**
  20798. * Clones the object
  20799. *
  20800. * @return {PIXI.FillStyle}
  20801. */
  20802. FillStyle.prototype.clone = function clone ()
  20803. {
  20804. var obj = new FillStyle();
  20805. obj.color = this.color;
  20806. obj.alpha = this.alpha;
  20807. obj.texture = this.texture;
  20808. obj.matrix = this.matrix;
  20809. obj.visible = this.visible;
  20810. return obj;
  20811. };
  20812. /**
  20813. * Reset
  20814. */
  20815. FillStyle.prototype.reset = function reset ()
  20816. {
  20817. /**
  20818. * The hex color value used when coloring the Graphics object.
  20819. *
  20820. * @member {number}
  20821. * @default 1
  20822. */
  20823. this.color = 0xFFFFFF;
  20824. /**
  20825. * The alpha value used when filling the Graphics object.
  20826. *
  20827. * @member {number}
  20828. * @default 1
  20829. */
  20830. this.alpha = 1;
  20831. /**
  20832. * The texture to be used for the fill.
  20833. *
  20834. * @member {string}
  20835. * @default 0
  20836. */
  20837. this.texture = Texture.WHITE;
  20838. /**
  20839. * The transform aplpied to the texture.
  20840. *
  20841. * @member {string}
  20842. * @default 0
  20843. */
  20844. this.matrix = null;
  20845. /**
  20846. * If the current fill is visible.
  20847. *
  20848. * @member {boolean}
  20849. * @default false
  20850. */
  20851. this.visible = false;
  20852. };
  20853. /**
  20854. * Destroy and don't use after this
  20855. */
  20856. FillStyle.prototype.destroy = function destroy ()
  20857. {
  20858. this.texture = null;
  20859. this.matrix = null;
  20860. };
  20861. /**
  20862. * A class to contain data useful for Graphics objects
  20863. *
  20864. * @class
  20865. * @memberof PIXI
  20866. */
  20867. var GraphicsData = function GraphicsData(shape, fillStyle, lineStyle, matrix)
  20868. {
  20869. if ( fillStyle === void 0 ) { fillStyle = null; }
  20870. if ( lineStyle === void 0 ) { lineStyle = null; }
  20871. if ( matrix === void 0 ) { matrix = null; }
  20872. /**
  20873. * The shape object to draw.
  20874. * @member {PIXI.Circle|PIXI.Ellipse|PIXI.Polygon|PIXI.Rectangle|PIXI.RoundedRectangle}
  20875. */
  20876. this.shape = shape;
  20877. /**
  20878. * The style of the line.
  20879. * @member {PIXI.LineStyle}
  20880. */
  20881. this.lineStyle = lineStyle;
  20882. /**
  20883. * The style of the fill.
  20884. * @member {PIXI.FillStyle}
  20885. */
  20886. this.fillStyle = fillStyle;
  20887. /**
  20888. * The transform matrix.
  20889. * @member {PIXI.Matrix}
  20890. */
  20891. this.matrix = matrix;
  20892. /**
  20893. * The type of the shape, see the Const.Shapes file for all the existing types,
  20894. * @member {number}
  20895. */
  20896. this.type = shape.type;
  20897. /**
  20898. * The collection of points.
  20899. * @member {number[]}
  20900. */
  20901. this.points = [];
  20902. /**
  20903. * The collection of holes.
  20904. * @member {PIXI.GraphicsData[]}
  20905. */
  20906. this.holes = [];
  20907. };
  20908. /**
  20909. * Creates a new GraphicsData object with the same values as this one.
  20910. *
  20911. * @return {PIXI.GraphicsData} Cloned GraphicsData object
  20912. */
  20913. GraphicsData.prototype.clone = function clone ()
  20914. {
  20915. return new GraphicsData(
  20916. this.shape,
  20917. this.fillStyle,
  20918. this.lineStyle,
  20919. this.matrix
  20920. );
  20921. };
  20922. /**
  20923. * Destroys the Graphics data.
  20924. */
  20925. GraphicsData.prototype.destroy = function destroy ()
  20926. {
  20927. this.shape = null;
  20928. this.holes.length = 0;
  20929. this.holes = null;
  20930. this.points.length = 0;
  20931. this.points = null;
  20932. this.lineStyle = null;
  20933. this.fillStyle = null;
  20934. };
  20935. /**
  20936. * Builds a circle to draw
  20937. *
  20938. * Ignored from docs since it is not directly exposed.
  20939. *
  20940. * @ignore
  20941. * @private
  20942. * @param {PIXI.WebGLGraphicsData} graphicsData - The graphics object to draw
  20943. * @param {object} webGLData - an object containing all the WebGL-specific information to create this shape
  20944. * @param {object} webGLDataNativeLines - an object containing all the WebGL-specific information to create nativeLines
  20945. */
  20946. var buildCircle = {
  20947. build: function build(graphicsData)
  20948. {
  20949. // need to convert points to a nice regular data
  20950. var circleData = graphicsData.shape;
  20951. var points = graphicsData.points;
  20952. var x = circleData.x;
  20953. var y = circleData.y;
  20954. var width;
  20955. var height;
  20956. points.length = 0;
  20957. // TODO - bit hacky??
  20958. if (graphicsData.type === SHAPES.CIRC)
  20959. {
  20960. width = circleData.radius;
  20961. height = circleData.radius;
  20962. }
  20963. else
  20964. {
  20965. width = circleData.width;
  20966. height = circleData.height;
  20967. }
  20968. if (width === 0 || height === 0)
  20969. {
  20970. return;
  20971. }
  20972. var totalSegs = Math.floor(30 * Math.sqrt(circleData.radius))
  20973. || Math.floor(15 * Math.sqrt(circleData.width + circleData.height));
  20974. totalSegs /= 2.3;
  20975. var seg = (Math.PI * 2) / totalSegs;
  20976. for (var i = 0; i < totalSegs; i++)
  20977. {
  20978. points.push(
  20979. x + (Math.sin(-seg * i) * width),
  20980. y + (Math.cos(-seg * i) * height)
  20981. );
  20982. }
  20983. points.push(
  20984. points[0],
  20985. points[1]
  20986. );
  20987. },
  20988. triangulate: function triangulate(graphicsData, graphicsGeometry)
  20989. {
  20990. var points = graphicsData.points;
  20991. var verts = graphicsGeometry.points;
  20992. var indices = graphicsGeometry.indices;
  20993. var vertPos = verts.length / 2;
  20994. var center = vertPos;
  20995. verts.push(graphicsData.shape.x, graphicsData.shape.y);
  20996. for (var i = 0; i < points.length; i += 2)
  20997. {
  20998. verts.push(points[i], points[i + 1]);
  20999. // add some uvs
  21000. indices.push(vertPos++, center, vertPos);
  21001. }
  21002. },
  21003. };
  21004. /**
  21005. * Builds a line to draw
  21006. *
  21007. * Ignored from docs since it is not directly exposed.
  21008. *
  21009. * @ignore
  21010. * @private
  21011. * @param {PIXI.GraphicsData} graphicsData - The graphics object containing all the necessary properties
  21012. * @param {PIXI.GraphicsGeometry} graphicsGeometry - Geometry where to append output
  21013. */
  21014. function buildLine (graphicsData, graphicsGeometry)
  21015. {
  21016. if (graphicsData.lineStyle.native)
  21017. {
  21018. buildNativeLine(graphicsData, graphicsGeometry);
  21019. }
  21020. else
  21021. {
  21022. buildLine$1(graphicsData, graphicsGeometry);
  21023. }
  21024. }
  21025. /**
  21026. * Builds a line to draw using the polygon method.
  21027. *
  21028. * Ignored from docs since it is not directly exposed.
  21029. *
  21030. * @ignore
  21031. * @private
  21032. * @param {PIXI.GraphicsData} graphicsData - The graphics object containing all the necessary properties
  21033. * @param {PIXI.GraphicsGeometry} graphicsGeometry - Geometry where to append output
  21034. */
  21035. function buildLine$1(graphicsData, graphicsGeometry)
  21036. {
  21037. var shape = graphicsData.shape;
  21038. var points = graphicsData.points || shape.points.slice();
  21039. if (points.length === 0)
  21040. {
  21041. return;
  21042. }
  21043. // if the line width is an odd number add 0.5 to align to a whole pixel
  21044. // commenting this out fixes #711 and #1620
  21045. // if (graphicsData.lineWidth%2)
  21046. // {
  21047. // for (i = 0; i < points.length; i++)
  21048. // {
  21049. // points[i] += 0.5;
  21050. // }
  21051. // }
  21052. var style = graphicsData.lineStyle;
  21053. // get first and last point.. figure out the middle!
  21054. var firstPoint = new Point(points[0], points[1]);
  21055. var lastPoint = new Point(points[points.length - 2], points[points.length - 1]);
  21056. var closedShape = shape.type !== SHAPES.POLY || shape.closeStroke;
  21057. var closedPath = firstPoint.x === lastPoint.x && firstPoint.y === lastPoint.y;
  21058. // if the first point is the last point - gonna have issues :)
  21059. if (closedShape)
  21060. {
  21061. // need to clone as we are going to slightly modify the shape..
  21062. points = points.slice();
  21063. if (closedPath)
  21064. {
  21065. points.pop();
  21066. points.pop();
  21067. lastPoint.set(points[points.length - 2], points[points.length - 1]);
  21068. }
  21069. var midPointX = lastPoint.x + ((firstPoint.x - lastPoint.x) * 0.5);
  21070. var midPointY = lastPoint.y + ((firstPoint.y - lastPoint.y) * 0.5);
  21071. points.unshift(midPointX, midPointY);
  21072. points.push(midPointX, midPointY);
  21073. }
  21074. var verts = graphicsGeometry.points;
  21075. var length = points.length / 2;
  21076. var indexCount = points.length;
  21077. var indexStart = verts.length / 2;
  21078. // DRAW the Line
  21079. var width = style.width / 2;
  21080. // sort color
  21081. var p1x = points[0];
  21082. var p1y = points[1];
  21083. var p2x = points[2];
  21084. var p2y = points[3];
  21085. var p3x = 0;
  21086. var p3y = 0;
  21087. var perpx = -(p1y - p2y);
  21088. var perpy = p1x - p2x;
  21089. var perp2x = 0;
  21090. var perp2y = 0;
  21091. var perp3x = 0;
  21092. var perp3y = 0;
  21093. var dist = Math.sqrt((perpx * perpx) + (perpy * perpy));
  21094. perpx /= dist;
  21095. perpy /= dist;
  21096. perpx *= width;
  21097. perpy *= width;
  21098. var ratio = style.alignment;// 0.5;
  21099. var r1 = (1 - ratio) * 2;
  21100. var r2 = ratio * 2;
  21101. // start
  21102. verts.push(
  21103. p1x - (perpx * r1),
  21104. p1y - (perpy * r1));
  21105. verts.push(
  21106. p1x + (perpx * r2),
  21107. p1y + (perpy * r2));
  21108. for (var i = 1; i < length - 1; ++i)
  21109. {
  21110. p1x = points[(i - 1) * 2];
  21111. p1y = points[((i - 1) * 2) + 1];
  21112. p2x = points[i * 2];
  21113. p2y = points[(i * 2) + 1];
  21114. p3x = points[(i + 1) * 2];
  21115. p3y = points[((i + 1) * 2) + 1];
  21116. perpx = -(p1y - p2y);
  21117. perpy = p1x - p2x;
  21118. dist = Math.sqrt((perpx * perpx) + (perpy * perpy));
  21119. perpx /= dist;
  21120. perpy /= dist;
  21121. perpx *= width;
  21122. perpy *= width;
  21123. perp2x = -(p2y - p3y);
  21124. perp2y = p2x - p3x;
  21125. dist = Math.sqrt((perp2x * perp2x) + (perp2y * perp2y));
  21126. perp2x /= dist;
  21127. perp2y /= dist;
  21128. perp2x *= width;
  21129. perp2y *= width;
  21130. var a1 = (-perpy + p1y) - (-perpy + p2y);
  21131. var b1 = (-perpx + p2x) - (-perpx + p1x);
  21132. var c1 = ((-perpx + p1x) * (-perpy + p2y)) - ((-perpx + p2x) * (-perpy + p1y));
  21133. var a2 = (-perp2y + p3y) - (-perp2y + p2y);
  21134. var b2 = (-perp2x + p2x) - (-perp2x + p3x);
  21135. var c2 = ((-perp2x + p3x) * (-perp2y + p2y)) - ((-perp2x + p2x) * (-perp2y + p3y));
  21136. var denom = (a1 * b2) - (a2 * b1);
  21137. if (Math.abs(denom) < 0.1)
  21138. {
  21139. denom += 10.1;
  21140. verts.push(
  21141. p2x - (perpx * r1),
  21142. p2y - (perpy * r1));
  21143. verts.push(
  21144. p2x + (perpx * r2),
  21145. p2y + (perpy * r2));
  21146. continue;
  21147. }
  21148. var px = ((b1 * c2) - (b2 * c1)) / denom;
  21149. var py = ((a2 * c1) - (a1 * c2)) / denom;
  21150. var pdist = ((px - p2x) * (px - p2x)) + ((py - p2y) * (py - p2y));
  21151. if (pdist > (196 * width * width))
  21152. {
  21153. perp3x = perpx - perp2x;
  21154. perp3y = perpy - perp2y;
  21155. dist = Math.sqrt((perp3x * perp3x) + (perp3y * perp3y));
  21156. perp3x /= dist;
  21157. perp3y /= dist;
  21158. perp3x *= width;
  21159. perp3y *= width;
  21160. verts.push(p2x - (perp3x * r1), p2y - (perp3y * r1));
  21161. verts.push(p2x + (perp3x * r2), p2y + (perp3y * r2));
  21162. verts.push(p2x - (perp3x * r2 * r1), p2y - (perp3y * r1));
  21163. indexCount++;
  21164. }
  21165. else
  21166. {
  21167. verts.push(p2x + ((px - p2x) * r1), p2y + ((py - p2y) * r1));
  21168. verts.push(p2x - ((px - p2x) * r2), p2y - ((py - p2y) * r2));
  21169. }
  21170. }
  21171. p1x = points[(length - 2) * 2];
  21172. p1y = points[((length - 2) * 2) + 1];
  21173. p2x = points[(length - 1) * 2];
  21174. p2y = points[((length - 1) * 2) + 1];
  21175. perpx = -(p1y - p2y);
  21176. perpy = p1x - p2x;
  21177. dist = Math.sqrt((perpx * perpx) + (perpy * perpy));
  21178. perpx /= dist;
  21179. perpy /= dist;
  21180. perpx *= width;
  21181. perpy *= width;
  21182. verts.push(p2x - (perpx * r1), p2y - (perpy * r1));
  21183. verts.push(p2x + (perpx * r2), p2y + (perpy * r2));
  21184. var indices = graphicsGeometry.indices;
  21185. // indices.push(indexStart);
  21186. for (var i$1 = 0; i$1 < indexCount - 2; ++i$1)
  21187. {
  21188. indices.push(indexStart, indexStart + 1, indexStart + 2);
  21189. indexStart++;
  21190. }
  21191. }
  21192. /**
  21193. * Builds a line to draw using the gl.drawArrays(gl.LINES) method
  21194. *
  21195. * Ignored from docs since it is not directly exposed.
  21196. *
  21197. * @ignore
  21198. * @private
  21199. * @param {PIXI.GraphicsData} graphicsData - The graphics object containing all the necessary properties
  21200. * @param {PIXI.GraphicsGeometry} graphicsGeometry - Geometry where to append output
  21201. */
  21202. function buildNativeLine(graphicsData, graphicsGeometry)
  21203. {
  21204. var i = 0;
  21205. var points = graphicsData.points || graphicsData.shape.points;
  21206. if (points.length === 0) { return; }
  21207. var verts = graphicsGeometry.points;
  21208. var indices = graphicsGeometry.indices;
  21209. var length = points.length / 2;
  21210. var indexStart = verts.length / 2;
  21211. // sort color
  21212. for (i = 1; i < length; i++)
  21213. {
  21214. var p1x = points[(i - 1) * 2];
  21215. var p1y = points[((i - 1) * 2) + 1];
  21216. var p2x = points[i * 2];
  21217. var p2y = points[(i * 2) + 1];
  21218. verts.push(p1x, p1y);
  21219. verts.push(p2x, p2y);
  21220. indices.push(indexStart++, indexStart++);
  21221. }
  21222. }
  21223. /**
  21224. * Builds a polygon to draw
  21225. *
  21226. * Ignored from docs since it is not directly exposed.
  21227. *
  21228. * @ignore
  21229. * @private
  21230. * @param {PIXI.WebGLGraphicsData} graphicsData - The graphics object containing all the necessary properties
  21231. * @param {object} webGLData - an object containing all the WebGL-specific information to create this shape
  21232. * @param {object} webGLDataNativeLines - an object containing all the WebGL-specific information to create nativeLines
  21233. */
  21234. var buildPoly = {
  21235. build: function build(graphicsData)
  21236. {
  21237. graphicsData.points = graphicsData.shape.points.slice();
  21238. },
  21239. triangulate: function triangulate(graphicsData, graphicsGeometry)
  21240. {
  21241. var points = graphicsData.points;
  21242. var holes = graphicsData.holes;
  21243. var verts = graphicsGeometry.points;
  21244. var indices = graphicsGeometry.indices;
  21245. if (points.length >= 6)
  21246. {
  21247. var holeArray = [];
  21248. // Process holes..
  21249. for (var i = 0; i < holes.length; i++)
  21250. {
  21251. var hole = holes[i];
  21252. holeArray.push(points.length / 2);
  21253. points = points.concat(hole.points);
  21254. }
  21255. // sort color
  21256. var triangles = earcut_1(points, holeArray, 2);
  21257. if (!triangles)
  21258. {
  21259. return;
  21260. }
  21261. var vertPos = verts.length / 2;
  21262. for (var i$1 = 0; i$1 < triangles.length; i$1 += 3)
  21263. {
  21264. indices.push(triangles[i$1] + vertPos);
  21265. indices.push(triangles[i$1 + 1] + vertPos);
  21266. indices.push(triangles[i$1 + 2] + vertPos);
  21267. }
  21268. for (var i$2 = 0; i$2 < points.length; i$2++)
  21269. {
  21270. verts.push(points[i$2]);
  21271. }
  21272. }
  21273. },
  21274. };
  21275. /**
  21276. * Builds a rectangle to draw
  21277. *
  21278. * Ignored from docs since it is not directly exposed.
  21279. *
  21280. * @ignore
  21281. * @private
  21282. * @param {PIXI.WebGLGraphicsData} graphicsData - The graphics object containing all the necessary properties
  21283. * @param {object} webGLData - an object containing all the WebGL-specific information to create this shape
  21284. * @param {object} webGLDataNativeLines - an object containing all the WebGL-specific information to create nativeLines
  21285. */
  21286. var buildRectangle = {
  21287. build: function build(graphicsData)
  21288. {
  21289. // --- //
  21290. // need to convert points to a nice regular data
  21291. //
  21292. var rectData = graphicsData.shape;
  21293. var x = rectData.x;
  21294. var y = rectData.y;
  21295. var width = rectData.width;
  21296. var height = rectData.height;
  21297. var points = graphicsData.points;
  21298. points.length = 0;
  21299. points.push(x, y,
  21300. x + width, y,
  21301. x + width, y + height,
  21302. x, y + height);
  21303. },
  21304. triangulate: function triangulate(graphicsData, graphicsGeometry)
  21305. {
  21306. var points = graphicsData.points;
  21307. var verts = graphicsGeometry.points;
  21308. var vertPos = verts.length / 2;
  21309. verts.push(points[0], points[1],
  21310. points[2], points[3],
  21311. points[6], points[7],
  21312. points[4], points[5]);
  21313. graphicsGeometry.indices.push(vertPos, vertPos + 1, vertPos + 2,
  21314. vertPos + 1, vertPos + 2, vertPos + 3);
  21315. },
  21316. };
  21317. /**
  21318. * Builds a rounded rectangle to draw
  21319. *
  21320. * Ignored from docs since it is not directly exposed.
  21321. *
  21322. * @ignore
  21323. * @private
  21324. * @param {PIXI.WebGLGraphicsData} graphicsData - The graphics object containing all the necessary properties
  21325. * @param {object} webGLData - an object containing all the WebGL-specific information to create this shape
  21326. * @param {object} webGLDataNativeLines - an object containing all the WebGL-specific information to create nativeLines
  21327. */
  21328. var buildRoundedRectangle = {
  21329. build: function build(graphicsData)
  21330. {
  21331. var rrectData = graphicsData.shape;
  21332. var points = graphicsData.points;
  21333. var x = rrectData.x;
  21334. var y = rrectData.y;
  21335. var width = rrectData.width;
  21336. var height = rrectData.height;
  21337. var radius = rrectData.radius;
  21338. points.length = 0;
  21339. quadraticBezierCurve(x, y + radius,
  21340. x, y,
  21341. x + radius, y,
  21342. points);
  21343. quadraticBezierCurve(x + width - radius,
  21344. y, x + width, y,
  21345. x + width, y + radius,
  21346. points);
  21347. quadraticBezierCurve(x + width, y + height - radius,
  21348. x + width, y + height,
  21349. x + width - radius, y + height,
  21350. points);
  21351. quadraticBezierCurve(x + radius, y + height,
  21352. x, y + height,
  21353. x, y + height - radius,
  21354. points);
  21355. // this tiny number deals with the issue that occurs when points overlap and earcut fails to triangulate the item.
  21356. // TODO - fix this properly, this is not very elegant.. but it works for now.
  21357. },
  21358. triangulate: function triangulate(graphicsData, graphicsGeometry)
  21359. {
  21360. var points = graphicsData.points;
  21361. var verts = graphicsGeometry.points;
  21362. var indices = graphicsGeometry.indices;
  21363. var vecPos = verts.length / 2;
  21364. var triangles = earcut_1(points, null, 2);
  21365. for (var i = 0, j = triangles.length; i < j; i += 3)
  21366. {
  21367. indices.push(triangles[i] + vecPos);
  21368. // indices.push(triangles[i] + vecPos);
  21369. indices.push(triangles[i + 1] + vecPos);
  21370. // indices.push(triangles[i + 2] + vecPos);
  21371. indices.push(triangles[i + 2] + vecPos);
  21372. }
  21373. for (var i$1 = 0, j$1 = points.length; i$1 < j$1; i$1++)
  21374. {
  21375. verts.push(points[i$1], points[++i$1]);
  21376. }
  21377. },
  21378. };
  21379. /**
  21380. * Calculate a single point for a quadratic bezier curve.
  21381. * Utility function used by quadraticBezierCurve.
  21382. * Ignored from docs since it is not directly exposed.
  21383. *
  21384. * @ignore
  21385. * @private
  21386. * @param {number} n1 - first number
  21387. * @param {number} n2 - second number
  21388. * @param {number} perc - percentage
  21389. * @return {number} the result
  21390. *
  21391. */
  21392. function getPt(n1, n2, perc)
  21393. {
  21394. var diff = n2 - n1;
  21395. return n1 + (diff * perc);
  21396. }
  21397. /**
  21398. * Calculate the points for a quadratic bezier curve. (helper function..)
  21399. * Based on: https://stackoverflow.com/questions/785097/how-do-i-implement-a-bezier-curve-in-c
  21400. *
  21401. * Ignored from docs since it is not directly exposed.
  21402. *
  21403. * @ignore
  21404. * @private
  21405. * @param {number} fromX - Origin point x
  21406. * @param {number} fromY - Origin point x
  21407. * @param {number} cpX - Control point x
  21408. * @param {number} cpY - Control point y
  21409. * @param {number} toX - Destination point x
  21410. * @param {number} toY - Destination point y
  21411. * @param {number[]} [out=[]] - The output array to add points into. If not passed, a new array is created.
  21412. * @return {number[]} an array of points
  21413. */
  21414. function quadraticBezierCurve(fromX, fromY, cpX, cpY, toX, toY, out)
  21415. {
  21416. if ( out === void 0 ) { out = []; }
  21417. var n = 20;
  21418. var points = out;
  21419. var xa = 0;
  21420. var ya = 0;
  21421. var xb = 0;
  21422. var yb = 0;
  21423. var x = 0;
  21424. var y = 0;
  21425. for (var i = 0, j = 0; i <= n; ++i)
  21426. {
  21427. j = i / n;
  21428. // The Green Line
  21429. xa = getPt(fromX, cpX, j);
  21430. ya = getPt(fromY, cpY, j);
  21431. xb = getPt(cpX, toX, j);
  21432. yb = getPt(cpY, toY, j);
  21433. // The Black Dot
  21434. x = getPt(xa, xb, j);
  21435. y = getPt(ya, yb, j);
  21436. points.push(x, y);
  21437. }
  21438. return points;
  21439. }
  21440. var BATCH_POOL = [];
  21441. var DRAW_CALL_POOL = [];
  21442. /**
  21443. * Map of fill commands for each shape type.
  21444. *
  21445. * @member {Object}
  21446. * @private
  21447. */
  21448. var fillCommands = {};
  21449. fillCommands[SHAPES.POLY] = buildPoly;
  21450. fillCommands[SHAPES.CIRC] = buildCircle;
  21451. fillCommands[SHAPES.ELIP] = buildCircle;
  21452. fillCommands[SHAPES.RECT] = buildRectangle;
  21453. fillCommands[SHAPES.RREC] = buildRoundedRectangle;
  21454. /**
  21455. * A little internal structure to hold interim batch objects.
  21456. *
  21457. * @private
  21458. */
  21459. var BatchPart = function BatchPart()
  21460. {
  21461. this.style = null;
  21462. this.size = 0;
  21463. this.start = 0;
  21464. this.attribStart = 0;
  21465. this.attribSize = 0;
  21466. };
  21467. /**
  21468. * The Graphics class contains methods used to draw primitive shapes such as lines, circles and
  21469. * rectangles to the display, and to color and fill them.
  21470. *
  21471. * GraphicsGeometry is designed to not be continually updating the geometry since it's expensive
  21472. * to re-tesselate using **earcut**. Consider using {@link PIXI.Mesh} for this use-case, it's much faster.
  21473. *
  21474. * @class
  21475. * @extends PIXI.BatchGeometry
  21476. * @memberof PIXI
  21477. */
  21478. var GraphicsGeometry = /*@__PURE__*/(function (BatchGeometry) {
  21479. function GraphicsGeometry()
  21480. {
  21481. BatchGeometry.call(this);
  21482. /**
  21483. * An array of points to draw
  21484. *
  21485. * @member {PIXI.Point[]}
  21486. * @protected
  21487. */
  21488. this.points = [];
  21489. /**
  21490. * The collection of colors
  21491. *
  21492. * @member {number[]}
  21493. * @protected
  21494. */
  21495. this.colors = [];
  21496. /**
  21497. * The UVs collection
  21498. *
  21499. * @member {number[]}
  21500. * @protected
  21501. */
  21502. this.uvs = [];
  21503. /**
  21504. * The indices of the vertices
  21505. *
  21506. * @member {number[]}
  21507. * @protected
  21508. */
  21509. this.indices = [];
  21510. /**
  21511. * Reference to the texture IDs.
  21512. *
  21513. * @member {number[]}
  21514. * @protected
  21515. */
  21516. this.textureIds = [];
  21517. /**
  21518. * The collection of drawn shapes.
  21519. *
  21520. * @member {PIXI.GraphicsData[]}
  21521. * @protected
  21522. */
  21523. this.graphicsData = [];
  21524. /**
  21525. * Used to detect if the graphics object has changed. If this is set to true then the graphics
  21526. * object will be recalculated.
  21527. *
  21528. * @member {number}
  21529. * @protected
  21530. */
  21531. this.dirty = 0;
  21532. /**
  21533. * Batches need to regenerated if the geometry is updated.
  21534. *
  21535. * @member {number}
  21536. * @protected
  21537. */
  21538. this.batchDirty = -1;
  21539. /**
  21540. * Used to check if the cache is dirty.
  21541. *
  21542. * @member {number}
  21543. * @protected
  21544. */
  21545. this.cacheDirty = -1;
  21546. /**
  21547. * Used to detect if we clear the graphics WebGL data.
  21548. *
  21549. * @member {number}
  21550. * @default 0
  21551. * @protected
  21552. */
  21553. this.clearDirty = 0;
  21554. /**
  21555. * List of current draw calls drived from the batches.
  21556. *
  21557. * @member {object[]}
  21558. * @protected
  21559. */
  21560. this.drawCalls = [];
  21561. /**
  21562. * Intermediate abstract format sent to batch system.
  21563. * Can be converted to drawCalls or to batchable objects.
  21564. *
  21565. * @member {object[]}
  21566. * @protected
  21567. */
  21568. this.batches = [];
  21569. /**
  21570. * Index of the current last shape in the stack of calls.
  21571. *
  21572. * @member {number}
  21573. * @protected
  21574. */
  21575. this.shapeIndex = 0;
  21576. /**
  21577. * Cached bounds.
  21578. *
  21579. * @member {PIXI.Bounds}
  21580. * @protected
  21581. */
  21582. this._bounds = new Bounds();
  21583. /**
  21584. * The bounds dirty flag.
  21585. *
  21586. * @member {number}
  21587. * @protected
  21588. */
  21589. this.boundsDirty = -1;
  21590. /**
  21591. * Padding to add to the bounds.
  21592. *
  21593. * @member {number}
  21594. * @default 0
  21595. */
  21596. this.boundsPadding = 0;
  21597. this.batchable = false;
  21598. this.indicesUint16 = null;
  21599. this.uvsFloat32 = null;
  21600. }
  21601. if ( BatchGeometry ) { GraphicsGeometry.__proto__ = BatchGeometry; }
  21602. GraphicsGeometry.prototype = Object.create( BatchGeometry && BatchGeometry.prototype );
  21603. GraphicsGeometry.prototype.constructor = GraphicsGeometry;
  21604. var prototypeAccessors = { bounds: { configurable: true } };
  21605. /**
  21606. * Get the current bounds of the graphic geometry.
  21607. *
  21608. * @member {PIXI.Bounds}
  21609. * @readonly
  21610. */
  21611. prototypeAccessors.bounds.get = function ()
  21612. {
  21613. if (this.boundsDirty !== this.dirty)
  21614. {
  21615. this.boundsDirty = this.dirty;
  21616. this.calculateBounds();
  21617. }
  21618. return this._bounds;
  21619. };
  21620. /**
  21621. * Clears the graphics that were drawn to this Graphics object, and resets fill and line style settings.
  21622. *
  21623. * @return {PIXI.GraphicsGeometry} This GraphicsGeometry object. Good for chaining method calls
  21624. */
  21625. GraphicsGeometry.prototype.clear = function clear ()
  21626. {
  21627. if (this.graphicsData.length > 0)
  21628. {
  21629. this.boundsDirty = -1;
  21630. this.dirty++;
  21631. this.clearDirty++;
  21632. this.batchDirty++;
  21633. this.graphicsData.length = 0;
  21634. this.shapeIndex = 0;
  21635. this.points.length = 0;
  21636. this.colors.length = 0;
  21637. this.uvs.length = 0;
  21638. this.indices.length = 0;
  21639. this.textureIds.length = 0;
  21640. for (var i = 0; i < this.drawCalls.length; i++)
  21641. {
  21642. this.drawCalls[i].textures.length = 0;
  21643. DRAW_CALL_POOL.push(this.drawCalls[i]);
  21644. }
  21645. this.drawCalls.length = 0;
  21646. for (var i$1 = 0; i$1 < this.batches.length; i$1++)
  21647. {
  21648. var batch = this.batches[i$1];
  21649. batch.start = 0;
  21650. batch.attribStart = 0;
  21651. batch.style = null;
  21652. BATCH_POOL.push(batch);
  21653. }
  21654. this.batches.length = 0;
  21655. }
  21656. return this;
  21657. };
  21658. /**
  21659. * Draws the given shape to this Graphics object. Can be any of Circle, Rectangle, Ellipse, Line or Polygon.
  21660. *
  21661. * @param {PIXI.Circle|PIXI.Ellipse|PIXI.Polygon|PIXI.Rectangle|PIXI.RoundedRectangle} shape - The shape object to draw.
  21662. * @param {PIXI.FillStyle} fillStyle - Defines style of the fill.
  21663. * @param {PIXI.LineStyle} lineStyle - Defines style of the lines.
  21664. * @param {PIXI.Matrix} matrix - Transform applied to the points of the shape.
  21665. * @return {PIXI.GraphicsGeometry} Returns geometry for chaining.
  21666. */
  21667. GraphicsGeometry.prototype.drawShape = function drawShape (shape, fillStyle, lineStyle, matrix)
  21668. {
  21669. var data = new GraphicsData(shape, fillStyle, lineStyle, matrix);
  21670. this.graphicsData.push(data);
  21671. this.dirty++;
  21672. return this;
  21673. };
  21674. /**
  21675. * Draws the given shape to this Graphics object. Can be any of Circle, Rectangle, Ellipse, Line or Polygon.
  21676. *
  21677. * @param {PIXI.Circle|PIXI.Ellipse|PIXI.Polygon|PIXI.Rectangle|PIXI.RoundedRectangle} shape - The shape object to draw.
  21678. * @param {PIXI.Matrix} matrix - Transform applied to the points of the shape.
  21679. * @return {PIXI.GraphicsGeometry} Returns geometry for chaining.
  21680. */
  21681. GraphicsGeometry.prototype.drawHole = function drawHole (shape, matrix)
  21682. {
  21683. if (!this.graphicsData.length)
  21684. {
  21685. return null;
  21686. }
  21687. var data = new GraphicsData(shape, null, null, matrix);
  21688. var lastShape = this.graphicsData[this.graphicsData.length - 1];
  21689. data.lineStyle = lastShape.lineStyle;
  21690. lastShape.holes.push(data);
  21691. this.dirty++;
  21692. return data;
  21693. };
  21694. /**
  21695. * Destroys the Graphics object.
  21696. *
  21697. * @param {object|boolean} [options] - Options parameter. A boolean will act as if all
  21698. * options have been set to that value
  21699. * @param {boolean} [options.children=false] - if set to true, all the children will have
  21700. * their destroy method called as well. 'options' will be passed on to those calls.
  21701. * @param {boolean} [options.texture=false] - Only used for child Sprites if options.children is set to true
  21702. * Should it destroy the texture of the child sprite
  21703. * @param {boolean} [options.baseTexture=false] - Only used for child Sprites if options.children is set to true
  21704. * Should it destroy the base texture of the child sprite
  21705. */
  21706. GraphicsGeometry.prototype.destroy = function destroy (options)
  21707. {
  21708. BatchGeometry.prototype.destroy.call(this, options);
  21709. // destroy each of the GraphicsData objects
  21710. for (var i = 0; i < this.graphicsData.length; ++i)
  21711. {
  21712. this.graphicsData[i].destroy();
  21713. }
  21714. this.points.length = 0;
  21715. this.points = null;
  21716. this.colors.length = 0;
  21717. this.colors = null;
  21718. this.uvs.length = 0;
  21719. this.uvs = null;
  21720. this.indices.length = 0;
  21721. this.indices = null;
  21722. this.indexBuffer.destroy();
  21723. this.indexBuffer = null;
  21724. this.graphicsData.length = 0;
  21725. this.graphicsData = null;
  21726. this.drawCalls.length = 0;
  21727. this.drawCalls = null;
  21728. this.batches.length = 0;
  21729. this.batches = null;
  21730. this._bounds = null;
  21731. };
  21732. /**
  21733. * Check to see if a point is contained within this geometry.
  21734. *
  21735. * @param {PIXI.Point} point - Point to check if it's contained.
  21736. * @return {Boolean} `true` if the point is contained within geometry.
  21737. */
  21738. GraphicsGeometry.prototype.containsPoint = function containsPoint (point)
  21739. {
  21740. var graphicsData = this.graphicsData;
  21741. for (var i = 0; i < graphicsData.length; ++i)
  21742. {
  21743. var data = graphicsData[i];
  21744. if (!data.fillStyle.visible)
  21745. {
  21746. continue;
  21747. }
  21748. // only deal with fills..
  21749. if (data.shape)
  21750. {
  21751. if (data.shape.contains(point.x, point.y))
  21752. {
  21753. if (data.holes)
  21754. {
  21755. for (var i$1 = 0; i$1 < data.holes.length; i$1++)
  21756. {
  21757. var hole = data.holes[i$1];
  21758. if (hole.shape.contains(point.x, point.y))
  21759. {
  21760. return false;
  21761. }
  21762. }
  21763. }
  21764. return true;
  21765. }
  21766. }
  21767. }
  21768. return false;
  21769. };
  21770. /**
  21771. * Generates intermediate batch data. Either gets converted to drawCalls
  21772. * or used to convert to batch objects directly by the Graphics object.
  21773. * @protected
  21774. */
  21775. GraphicsGeometry.prototype.updateBatches = function updateBatches ()
  21776. {
  21777. if (this.dirty === this.cacheDirty) { return; }
  21778. if (this.graphicsData.length === 0) { return; }
  21779. if (this.dirty !== this.cacheDirty)
  21780. {
  21781. for (var i = 0; i < this.graphicsData.length; i++)
  21782. {
  21783. var data = this.graphicsData[i];
  21784. if (data.fillStyle && !data.fillStyle.texture.baseTexture.valid) { return; }
  21785. if (data.lineStyle && !data.lineStyle.texture.baseTexture.valid) { return; }
  21786. }
  21787. }
  21788. this.cacheDirty = this.dirty;
  21789. var uvs = this.uvs;
  21790. var batchPart = this.batches.pop()
  21791. || BATCH_POOL.pop()
  21792. || new BatchPart();
  21793. batchPart.style = batchPart.style
  21794. || this.graphicsData[0].fillStyle
  21795. || this.graphicsData[0].lineStyle;
  21796. var currentTexture = batchPart.style.texture.baseTexture;
  21797. var currentColor = batchPart.style.color + batchPart.style.alpha;
  21798. this.batches.push(batchPart);
  21799. // TODO - this can be simplified
  21800. for (var i$1 = this.shapeIndex; i$1 < this.graphicsData.length; i$1++)
  21801. {
  21802. this.shapeIndex++;
  21803. var data$1 = this.graphicsData[i$1];
  21804. var command = fillCommands[data$1.type];
  21805. var fillStyle = data$1.fillStyle;
  21806. var lineStyle = data$1.lineStyle;
  21807. // build out the shapes points..
  21808. command.build(data$1);
  21809. if (data$1.matrix)
  21810. {
  21811. this.transformPoints(data$1.points, data$1.matrix);
  21812. }
  21813. for (var j = 0; j < 2; j++)
  21814. {
  21815. var style = (j === 0) ? fillStyle : lineStyle;
  21816. if (!style.visible) { continue; }
  21817. var nextTexture = style.texture.baseTexture;
  21818. if (currentTexture !== nextTexture || (style.color + style.alpha) !== currentColor)
  21819. {
  21820. // TODO use a const
  21821. nextTexture.wrapMode = 10497;
  21822. currentTexture = nextTexture;
  21823. currentColor = style.color + style.alpha;
  21824. var index$1 = this.indices.length;
  21825. var attribIndex = this.points.length / 2;
  21826. batchPart.size = index$1 - batchPart.start;
  21827. batchPart.attribSize = attribIndex - batchPart.attribStart;
  21828. if (batchPart.size > 0)
  21829. {
  21830. batchPart = BATCH_POOL.pop() || new BatchPart();
  21831. this.batches.push(batchPart);
  21832. }
  21833. batchPart.style = style;
  21834. batchPart.start = index$1;
  21835. batchPart.attribStart = attribIndex;
  21836. // TODO add this to the render part..
  21837. }
  21838. var start = this.points.length / 2;
  21839. if (j === 0)
  21840. {
  21841. if (data$1.holes.length)
  21842. {
  21843. this.processHoles(data$1.holes);
  21844. buildPoly.triangulate(data$1, this);
  21845. }
  21846. else
  21847. {
  21848. command.triangulate(data$1, this);
  21849. }
  21850. }
  21851. else
  21852. {
  21853. buildLine(data$1, this);
  21854. for (var i$2 = 0; i$2 < data$1.holes.length; i$2++)
  21855. {
  21856. buildLine(data$1.holes[i$2], this);
  21857. }
  21858. }
  21859. var size = (this.points.length / 2) - start;
  21860. this.addUvs(this.points, uvs, style.texture, start, size, style.matrix);
  21861. }
  21862. }
  21863. var index = this.indices.length;
  21864. var attrib = this.points.length / 2;
  21865. batchPart.size = index - batchPart.start;
  21866. batchPart.attribSize = attrib - batchPart.attribStart;
  21867. this.indicesUint16 = new Uint16Array(this.indices);
  21868. // TODO make this a const..
  21869. this.batchable = this.isBatchable();
  21870. if (this.batchable)
  21871. {
  21872. this.batchDirty++;
  21873. this.uvsFloat32 = new Float32Array(this.uvs);
  21874. // offset the indices so that it works with the batcher...
  21875. for (var i$3 = 0; i$3 < this.batches.length; i$3++)
  21876. {
  21877. var batch = this.batches[i$3];
  21878. for (var j$1 = 0; j$1 < batch.size; j$1++)
  21879. {
  21880. var index$2 = batch.start + j$1;
  21881. this.indicesUint16[index$2] = this.indicesUint16[index$2] - batch.attribStart;
  21882. }
  21883. }
  21884. }
  21885. else
  21886. {
  21887. this.buildDrawCalls();
  21888. }
  21889. };
  21890. /**
  21891. * Checks to see if this graphics geometry can be batched.
  21892. * Currently it needs to be small enough and not contain any native lines.
  21893. * @protected
  21894. */
  21895. GraphicsGeometry.prototype.isBatchable = function isBatchable ()
  21896. {
  21897. var batches = this.batches;
  21898. for (var i = 0; i < batches.length; i++)
  21899. {
  21900. if (batches[i].style.native)
  21901. {
  21902. return false;
  21903. }
  21904. }
  21905. return (this.points.length < GraphicsGeometry.BATCHABLE_SIZE * 2);
  21906. };
  21907. /**
  21908. * Converts intermediate batches data to drawCalls.
  21909. * @protected
  21910. */
  21911. GraphicsGeometry.prototype.buildDrawCalls = function buildDrawCalls ()
  21912. {
  21913. var TICK = ++BaseTexture._globalBatch;
  21914. for (var i = 0; i < this.drawCalls.length; i++)
  21915. {
  21916. this.drawCalls[i].textures.length = 0;
  21917. DRAW_CALL_POOL.push(this.drawCalls[i]);
  21918. }
  21919. this.drawCalls.length = 0;
  21920. var uvs = this.uvs;
  21921. var colors = this.colors;
  21922. var textureIds = this.textureIds;
  21923. var currentGroup = DRAW_CALL_POOL.pop() || new BatchDrawCall();
  21924. currentGroup.textureCount = 0;
  21925. currentGroup.start = 0;
  21926. currentGroup.size = 0;
  21927. currentGroup.type = DRAW_MODES.TRIANGLES;
  21928. var textureCount = 0;
  21929. var currentTexture = null;
  21930. var textureId = 0;
  21931. var native = false;
  21932. var drawMode = DRAW_MODES.TRIANGLES;
  21933. var index = 0;
  21934. this.drawCalls.push(currentGroup);
  21935. // TODO - this can be simplified
  21936. for (var i$1 = 0; i$1 < this.batches.length; i$1++)
  21937. {
  21938. var data = this.batches[i$1];
  21939. // TODO add some full on MAX_TEXTURE CODE..
  21940. var MAX_TEXTURES = 8;
  21941. var style = data.style;
  21942. var nextTexture = style.texture.baseTexture;
  21943. if (native !== style.native)
  21944. {
  21945. native = style.native;
  21946. drawMode = native ? DRAW_MODES.LINES : DRAW_MODES.TRIANGLES;
  21947. // force the batch to break!
  21948. currentTexture = null;
  21949. textureCount = MAX_TEXTURES;
  21950. TICK++;
  21951. }
  21952. if (currentTexture !== nextTexture)
  21953. {
  21954. currentTexture = nextTexture;
  21955. if (nextTexture._batchEnabled !== TICK)
  21956. {
  21957. if (textureCount === MAX_TEXTURES)
  21958. {
  21959. TICK++;
  21960. textureCount = 0;
  21961. if (currentGroup.size > 0)
  21962. {
  21963. currentGroup = DRAW_CALL_POOL.pop() || new BatchDrawCall();
  21964. this.drawCalls.push(currentGroup);
  21965. }
  21966. currentGroup.start = index;
  21967. currentGroup.size = 0;
  21968. currentGroup.textureCount = 0;
  21969. currentGroup.type = drawMode;
  21970. }
  21971. // TODO add this to the render part..
  21972. nextTexture.touched = 1;// touch;
  21973. nextTexture._batchEnabled = TICK;
  21974. nextTexture._id = textureCount;
  21975. nextTexture.wrapMode = 10497;
  21976. currentGroup.textures[currentGroup.textureCount++] = nextTexture;
  21977. textureCount++;
  21978. }
  21979. }
  21980. currentGroup.size += data.size;
  21981. index += data.size;
  21982. textureId = nextTexture._id;
  21983. this.addColors(colors, style.color, style.alpha, data.attribSize);
  21984. this.addTextureIds(textureIds, textureId, data.attribSize);
  21985. }
  21986. BaseTexture._globalBatch = TICK;
  21987. // upload..
  21988. // merge for now!
  21989. var verts = this.points;
  21990. // verts are 2 positions.. so we * by 3 as there are 6 properties.. then 4 cos its bytes
  21991. var glPoints = new ArrayBuffer(verts.length * 3 * 4);
  21992. var f32 = new Float32Array(glPoints);
  21993. var u32 = new Uint32Array(glPoints);
  21994. var p = 0;
  21995. for (var i$2 = 0; i$2 < verts.length / 2; i$2++)
  21996. {
  21997. f32[p++] = verts[i$2 * 2];
  21998. f32[p++] = verts[(i$2 * 2) + 1];
  21999. f32[p++] = uvs[i$2 * 2];
  22000. f32[p++] = uvs[(i$2 * 2) + 1];
  22001. u32[p++] = colors[i$2];
  22002. f32[p++] = textureIds[i$2];
  22003. }
  22004. this._buffer.update(glPoints);
  22005. this._indexBuffer.update(this.indicesUint16);
  22006. };
  22007. /**
  22008. * Process the holes data.
  22009. *
  22010. * @param {PIXI.GraphicsData[]} holes - Holes to render
  22011. * @protected
  22012. */
  22013. GraphicsGeometry.prototype.processHoles = function processHoles (holes)
  22014. {
  22015. for (var i = 0; i < holes.length; i++)
  22016. {
  22017. var hole = holes[i];
  22018. var command = fillCommands[hole.type];
  22019. command.build(hole);
  22020. if (hole.matrix)
  22021. {
  22022. this.transformPoints(hole.points, hole.matrix);
  22023. }
  22024. }
  22025. };
  22026. /**
  22027. * Update the local bounds of the object. Expensive to use performance-wise.
  22028. * @protected
  22029. */
  22030. GraphicsGeometry.prototype.calculateBounds = function calculateBounds ()
  22031. {
  22032. var minX = Infinity;
  22033. var maxX = -Infinity;
  22034. var minY = Infinity;
  22035. var maxY = -Infinity;
  22036. if (this.graphicsData.length)
  22037. {
  22038. var shape = null;
  22039. var x = 0;
  22040. var y = 0;
  22041. var w = 0;
  22042. var h = 0;
  22043. for (var i = 0; i < this.graphicsData.length; i++)
  22044. {
  22045. var data = this.graphicsData[i];
  22046. var type = data.type;
  22047. var lineWidth = data.lineStyle ? data.lineStyle.width : 0;
  22048. shape = data.shape;
  22049. if (type === SHAPES.RECT || type === SHAPES.RREC)
  22050. {
  22051. x = shape.x - (lineWidth / 2);
  22052. y = shape.y - (lineWidth / 2);
  22053. w = shape.width + lineWidth;
  22054. h = shape.height + lineWidth;
  22055. minX = x < minX ? x : minX;
  22056. maxX = x + w > maxX ? x + w : maxX;
  22057. minY = y < minY ? y : minY;
  22058. maxY = y + h > maxY ? y + h : maxY;
  22059. }
  22060. else if (type === SHAPES.CIRC)
  22061. {
  22062. x = shape.x;
  22063. y = shape.y;
  22064. w = shape.radius + (lineWidth / 2);
  22065. h = shape.radius + (lineWidth / 2);
  22066. minX = x - w < minX ? x - w : minX;
  22067. maxX = x + w > maxX ? x + w : maxX;
  22068. minY = y - h < minY ? y - h : minY;
  22069. maxY = y + h > maxY ? y + h : maxY;
  22070. }
  22071. else if (type === SHAPES.ELIP)
  22072. {
  22073. x = shape.x;
  22074. y = shape.y;
  22075. w = shape.width + (lineWidth / 2);
  22076. h = shape.height + (lineWidth / 2);
  22077. minX = x - w < minX ? x - w : minX;
  22078. maxX = x + w > maxX ? x + w : maxX;
  22079. minY = y - h < minY ? y - h : minY;
  22080. maxY = y + h > maxY ? y + h : maxY;
  22081. }
  22082. else
  22083. {
  22084. // POLY
  22085. var points = shape.points;
  22086. var x2 = 0;
  22087. var y2 = 0;
  22088. var dx = 0;
  22089. var dy = 0;
  22090. var rw = 0;
  22091. var rh = 0;
  22092. var cx = 0;
  22093. var cy = 0;
  22094. for (var j = 0; j + 2 < points.length; j += 2)
  22095. {
  22096. x = points[j];
  22097. y = points[j + 1];
  22098. x2 = points[j + 2];
  22099. y2 = points[j + 3];
  22100. dx = Math.abs(x2 - x);
  22101. dy = Math.abs(y2 - y);
  22102. h = lineWidth;
  22103. w = Math.sqrt((dx * dx) + (dy * dy));
  22104. if (w < 1e-9)
  22105. {
  22106. continue;
  22107. }
  22108. rw = ((h / w * dy) + dx) / 2;
  22109. rh = ((h / w * dx) + dy) / 2;
  22110. cx = (x2 + x) / 2;
  22111. cy = (y2 + y) / 2;
  22112. minX = cx - rw < minX ? cx - rw : minX;
  22113. maxX = cx + rw > maxX ? cx + rw : maxX;
  22114. minY = cy - rh < minY ? cy - rh : minY;
  22115. maxY = cy + rh > maxY ? cy + rh : maxY;
  22116. }
  22117. }
  22118. }
  22119. }
  22120. else
  22121. {
  22122. minX = 0;
  22123. maxX = 0;
  22124. minY = 0;
  22125. maxY = 0;
  22126. }
  22127. var padding = this.boundsPadding;
  22128. this._bounds.minX = minX - padding;
  22129. this._bounds.maxX = maxX + padding;
  22130. this._bounds.minY = minY - padding;
  22131. this._bounds.maxY = maxY + padding;
  22132. };
  22133. /**
  22134. * Transform points using matrix.
  22135. *
  22136. * @protected
  22137. * @param {number[]} points - Points to transform
  22138. * @param {PIXI.Matrix} matrix - Transform matrix
  22139. */
  22140. GraphicsGeometry.prototype.transformPoints = function transformPoints (points, matrix)
  22141. {
  22142. for (var i = 0; i < points.length / 2; i++)
  22143. {
  22144. var x = points[(i * 2)];
  22145. var y = points[(i * 2) + 1];
  22146. points[(i * 2)] = (matrix.a * x) + (matrix.c * y) + matrix.tx;
  22147. points[(i * 2) + 1] = (matrix.b * x) + (matrix.d * y) + matrix.ty;
  22148. }
  22149. };
  22150. /**
  22151. * Add colors.
  22152. *
  22153. * @protected
  22154. * @param {number[]} colors - List of colors to add to
  22155. * @param {number} color - Color to add
  22156. * @param {number} alpha - Alpha to use
  22157. * @param {number} size - Number of colors to add
  22158. */
  22159. GraphicsGeometry.prototype.addColors = function addColors (colors, color, alpha, size)
  22160. {
  22161. // TODO use the premultiply bits Ivan added
  22162. var rgb = (color >> 16) + (color & 0xff00) + ((color & 0xff) << 16);
  22163. var rgba = premultiplyTint(rgb, alpha);
  22164. while (size-- > 0)
  22165. {
  22166. colors.push(rgba);
  22167. }
  22168. };
  22169. /**
  22170. * Add texture id that the shader/fragment wants to use.
  22171. *
  22172. * @protected
  22173. * @param {number[]} textureIds
  22174. * @param {number} id
  22175. * @param {number} size
  22176. */
  22177. GraphicsGeometry.prototype.addTextureIds = function addTextureIds (textureIds, id, size)
  22178. {
  22179. while (size-- > 0)
  22180. {
  22181. textureIds.push(id);
  22182. }
  22183. };
  22184. /**
  22185. * Generates the UVs for a shape.
  22186. *
  22187. * @protected
  22188. * @param {number[]} verts - Vertices
  22189. * @param {number[]} uvs - UVs
  22190. * @param {PIXI.Texture} texture - Reference to Texture
  22191. * @param {number} start - Index buffer start index.
  22192. * @param {number} size - The size/length for index buffer.
  22193. * @param {PIXI.Matrix} [matrix] - Optional transform for all points.
  22194. */
  22195. GraphicsGeometry.prototype.addUvs = function addUvs (verts, uvs, texture, start, size, matrix)
  22196. {
  22197. var index = 0;
  22198. var uvsStart = uvs.length;
  22199. var frame = texture.frame;
  22200. while (index < size)
  22201. {
  22202. var x = verts[(start + index) * 2];
  22203. var y = verts[((start + index) * 2) + 1];
  22204. if (matrix)
  22205. {
  22206. var nx = (matrix.a * x) + (matrix.c * y) + matrix.tx;
  22207. y = (matrix.b * x) + (matrix.d * y) + matrix.ty;
  22208. x = nx;
  22209. }
  22210. index++;
  22211. uvs.push(x / frame.width, y / frame.height);
  22212. }
  22213. var baseTexture = texture.baseTexture;
  22214. if (frame.width < baseTexture.width
  22215. || frame.height < baseTexture.height)
  22216. {
  22217. this.adjustUvs(uvs, texture, uvsStart, size);
  22218. }
  22219. };
  22220. /**
  22221. * Modify uvs array according to position of texture region
  22222. * Does not work with rotated or trimmed textures
  22223. * @param {number} uvs array
  22224. * @param {PIXI.Texture} texture region
  22225. * @param {number} start starting index for uvs
  22226. * @param {number} size how many points to adjust
  22227. */
  22228. GraphicsGeometry.prototype.adjustUvs = function adjustUvs (uvs, texture, start, size)
  22229. {
  22230. var baseTexture = texture.baseTexture;
  22231. var eps = 1e-6;
  22232. var finish = start + (size * 2);
  22233. var frame = texture.frame;
  22234. var scaleX = frame.width / baseTexture.width;
  22235. var scaleY = frame.height / baseTexture.height;
  22236. var offsetX = frame.x / frame.width;
  22237. var offsetY = frame.y / frame.height;
  22238. var minX = Math.floor(uvs[start] + eps);
  22239. var minY = Math.floor(uvs[start + 1] + eps);
  22240. for (var i = start + 2; i < finish; i += 2)
  22241. {
  22242. minX = Math.min(minX, Math.floor(uvs[i] + eps));
  22243. minY = Math.min(minY, Math.floor(uvs[i + 1] + eps));
  22244. }
  22245. offsetX -= minX;
  22246. offsetY -= minY;
  22247. for (var i$1 = start; i$1 < finish; i$1 += 2)
  22248. {
  22249. uvs[i$1] = (uvs[i$1] + offsetX) * scaleX;
  22250. uvs[i$1 + 1] = (uvs[i$1 + 1] + offsetY) * scaleY;
  22251. }
  22252. };
  22253. Object.defineProperties( GraphicsGeometry.prototype, prototypeAccessors );
  22254. return GraphicsGeometry;
  22255. }(BatchGeometry));
  22256. /**
  22257. * The maximum number of points to consider an object "batchable",
  22258. * able to be batched by the renderer's batch system.
  22259. *
  22260. * @memberof PIXI.GraphicsGeometry
  22261. * @static
  22262. * @member {number} BATCHABLE_SIZE
  22263. * @default 100
  22264. */
  22265. GraphicsGeometry.BATCHABLE_SIZE = 100;
  22266. /**
  22267. * Represents the line style for Graphics.
  22268. * @memberof PIXI
  22269. * @class
  22270. * @extends PIXI.FillStyle
  22271. */
  22272. var LineStyle = /*@__PURE__*/(function (FillStyle) {
  22273. function LineStyle () {
  22274. FillStyle.apply(this, arguments);
  22275. }
  22276. if ( FillStyle ) { LineStyle.__proto__ = FillStyle; }
  22277. LineStyle.prototype = Object.create( FillStyle && FillStyle.prototype );
  22278. LineStyle.prototype.constructor = LineStyle;
  22279. LineStyle.prototype.clone = function clone ()
  22280. {
  22281. var obj = new LineStyle();
  22282. obj.color = this.color;
  22283. obj.alpha = this.alpha;
  22284. obj.texture = this.texture;
  22285. obj.matrix = this.matrix;
  22286. obj.visible = this.visible;
  22287. obj.width = this.width;
  22288. obj.alignment = this.alignment;
  22289. obj.native = this.native;
  22290. return obj;
  22291. };
  22292. /**
  22293. * Reset the line style to default.
  22294. */
  22295. LineStyle.prototype.reset = function reset ()
  22296. {
  22297. FillStyle.prototype.reset.call(this);
  22298. // Override default line style color
  22299. this.color = 0x0;
  22300. /**
  22301. * The width (thickness) of any lines drawn.
  22302. *
  22303. * @member {number}
  22304. * @default 0
  22305. */
  22306. this.width = 0;
  22307. /**
  22308. * The alignment of any lines drawn (0.5 = middle, 1 = outter, 0 = inner).
  22309. *
  22310. * @member {number}
  22311. * @default 0
  22312. */
  22313. this.alignment = 0.5;
  22314. /**
  22315. * If true the lines will be draw using LINES instead of TRIANGLE_STRIP
  22316. *
  22317. * @member {boolean}
  22318. * @default false
  22319. */
  22320. this.native = false;
  22321. };
  22322. return LineStyle;
  22323. }(FillStyle));
  22324. /**
  22325. * Utilities for bezier curves
  22326. * @class
  22327. * @private
  22328. */
  22329. var BezierUtils = function BezierUtils () {};
  22330. BezierUtils.curveLength = function curveLength (fromX, fromY, cpX, cpY, cpX2, cpY2, toX, toY)
  22331. {
  22332. var n = 10;
  22333. var result = 0.0;
  22334. var t = 0.0;
  22335. var t2 = 0.0;
  22336. var t3 = 0.0;
  22337. var nt = 0.0;
  22338. var nt2 = 0.0;
  22339. var nt3 = 0.0;
  22340. var x = 0.0;
  22341. var y = 0.0;
  22342. var dx = 0.0;
  22343. var dy = 0.0;
  22344. var prevX = fromX;
  22345. var prevY = fromY;
  22346. for (var i = 1; i <= n; ++i)
  22347. {
  22348. t = i / n;
  22349. t2 = t * t;
  22350. t3 = t2 * t;
  22351. nt = (1.0 - t);
  22352. nt2 = nt * nt;
  22353. nt3 = nt2 * nt;
  22354. x = (nt3 * fromX) + (3.0 * nt2 * t * cpX) + (3.0 * nt * t2 * cpX2) + (t3 * toX);
  22355. y = (nt3 * fromY) + (3.0 * nt2 * t * cpY) + (3 * nt * t2 * cpY2) + (t3 * toY);
  22356. dx = prevX - x;
  22357. dy = prevY - y;
  22358. prevX = x;
  22359. prevY = y;
  22360. result += Math.sqrt((dx * dx) + (dy * dy));
  22361. }
  22362. return result;
  22363. };
  22364. /**
  22365. * Calculate the points for a bezier curve and then draws it.
  22366. *
  22367. * Ignored from docs since it is not directly exposed.
  22368. *
  22369. * @ignore
  22370. * @param {number} cpX - Control point x
  22371. * @param {number} cpY - Control point y
  22372. * @param {number} cpX2 - Second Control point x
  22373. * @param {number} cpY2 - Second Control point y
  22374. * @param {number} toX - Destination point x
  22375. * @param {number} toY - Destination point y
  22376. * @param {number[]} points - Path array to push points into
  22377. */
  22378. BezierUtils.curveTo = function curveTo (cpX, cpY, cpX2, cpY2, toX, toY, points)
  22379. {
  22380. var fromX = points[points.length - 2];
  22381. var fromY = points[points.length - 1];
  22382. points.length -= 2;
  22383. var n = GRAPHICS_CURVES._segmentsCount(
  22384. BezierUtils.curveLength(fromX, fromY, cpX, cpY, cpX2, cpY2, toX, toY)
  22385. );
  22386. var dt = 0;
  22387. var dt2 = 0;
  22388. var dt3 = 0;
  22389. var t2 = 0;
  22390. var t3 = 0;
  22391. points.push(fromX, fromY);
  22392. for (var i = 1, j = 0; i <= n; ++i)
  22393. {
  22394. j = i / n;
  22395. dt = (1 - j);
  22396. dt2 = dt * dt;
  22397. dt3 = dt2 * dt;
  22398. t2 = j * j;
  22399. t3 = t2 * j;
  22400. points.push(
  22401. (dt3 * fromX) + (3 * dt2 * j * cpX) + (3 * dt * t2 * cpX2) + (t3 * toX),
  22402. (dt3 * fromY) + (3 * dt2 * j * cpY) + (3 * dt * t2 * cpY2) + (t3 * toY)
  22403. );
  22404. }
  22405. };
  22406. /**
  22407. * Utilities for quadratic curves
  22408. * @class
  22409. * @private
  22410. */
  22411. var QuadraticUtils = function QuadraticUtils () {};
  22412. QuadraticUtils.curveLength = function curveLength (fromX, fromY, cpX, cpY, toX, toY)
  22413. {
  22414. var ax = fromX - (2.0 * cpX) + toX;
  22415. var ay = fromY - (2.0 * cpY) + toY;
  22416. var bx = (2.0 * cpX) - (2.0 * fromX);
  22417. var by = (2.0 * cpY) - (2.0 * fromY);
  22418. var a = 4.0 * ((ax * ax) + (ay * ay));
  22419. var b = 4.0 * ((ax * bx) + (ay * by));
  22420. var c = (bx * bx) + (by * by);
  22421. var s = 2.0 * Math.sqrt(a + b + c);
  22422. var a2 = Math.sqrt(a);
  22423. var a32 = 2.0 * a * a2;
  22424. var c2 = 2.0 * Math.sqrt(c);
  22425. var ba = b / a2;
  22426. return (
  22427. (a32 * s)
  22428. + (a2 * b * (s - c2))
  22429. + (
  22430. ((4.0 * c * a) - (b * b))
  22431. * Math.log(((2.0 * a2) + ba + s) / (ba + c2))
  22432. )
  22433. ) / (4.0 * a32);
  22434. };
  22435. /**
  22436. * Calculate the points for a quadratic bezier curve and then draws it.
  22437. * Based on: https://stackoverflow.com/questions/785097/how-do-i-implement-a-bezier-curve-in-c
  22438. *
  22439. * @private
  22440. * @param {number} cpX - Control point x
  22441. * @param {number} cpY - Control point y
  22442. * @param {number} toX - Destination point x
  22443. * @param {number} toY - Destination point y
  22444. * @param {number[]} points - Points to add segments to.
  22445. */
  22446. QuadraticUtils.curveTo = function curveTo (cpX, cpY, toX, toY, points)
  22447. {
  22448. var fromX = points[points.length - 2];
  22449. var fromY = points[points.length - 1];
  22450. var n = GRAPHICS_CURVES._segmentsCount(
  22451. QuadraticUtils.curveLength(fromX, fromY, cpX, cpY, toX, toY)
  22452. );
  22453. var xa = 0;
  22454. var ya = 0;
  22455. for (var i = 1; i <= n; ++i)
  22456. {
  22457. var j = i / n;
  22458. xa = fromX + ((cpX - fromX) * j);
  22459. ya = fromY + ((cpY - fromY) * j);
  22460. points.push(xa + (((cpX + ((toX - cpX) * j)) - xa) * j),
  22461. ya + (((cpY + ((toY - cpY) * j)) - ya) * j));
  22462. }
  22463. };
  22464. /**
  22465. * Utilities for arc curves
  22466. * @class
  22467. * @private
  22468. */
  22469. var ArcUtils = function ArcUtils () {};
  22470. ArcUtils.curveTo = function curveTo (x1, y1, x2, y2, radius, points)
  22471. {
  22472. var fromX = points[points.length - 2];
  22473. var fromY = points[points.length - 1];
  22474. var a1 = fromY - y1;
  22475. var b1 = fromX - x1;
  22476. var a2 = y2 - y1;
  22477. var b2 = x2 - x1;
  22478. var mm = Math.abs((a1 * b2) - (b1 * a2));
  22479. if (mm < 1.0e-8 || radius === 0)
  22480. {
  22481. if (points[points.length - 2] !== x1 || points[points.length - 1] !== y1)
  22482. {
  22483. points.push(x1, y1);
  22484. }
  22485. return null;
  22486. }
  22487. var dd = (a1 * a1) + (b1 * b1);
  22488. var cc = (a2 * a2) + (b2 * b2);
  22489. var tt = (a1 * a2) + (b1 * b2);
  22490. var k1 = radius * Math.sqrt(dd) / mm;
  22491. var k2 = radius * Math.sqrt(cc) / mm;
  22492. var j1 = k1 * tt / dd;
  22493. var j2 = k2 * tt / cc;
  22494. var cx = (k1 * b2) + (k2 * b1);
  22495. var cy = (k1 * a2) + (k2 * a1);
  22496. var px = b1 * (k2 + j1);
  22497. var py = a1 * (k2 + j1);
  22498. var qx = b2 * (k1 + j2);
  22499. var qy = a2 * (k1 + j2);
  22500. var startAngle = Math.atan2(py - cy, px - cx);
  22501. var endAngle = Math.atan2(qy - cy, qx - cx);
  22502. return {
  22503. cx: (cx + x1),
  22504. cy: (cy + y1),
  22505. radius: radius,
  22506. startAngle: startAngle,
  22507. endAngle: endAngle,
  22508. anticlockwise: (b1 * a2 > b2 * a1),
  22509. };
  22510. };
  22511. /**
  22512. * The arc method creates an arc/curve (used to create circles, or parts of circles).
  22513. *
  22514. * @private
  22515. * @param {number} startX - Start x location of arc
  22516. * @param {number} startY - Start y location of arc
  22517. * @param {number} cx - The x-coordinate of the center of the circle
  22518. * @param {number} cy - The y-coordinate of the center of the circle
  22519. * @param {number} radius - The radius of the circle
  22520. * @param {number} startAngle - The starting angle, in radians (0 is at the 3 o'clock position
  22521. * of the arc's circle)
  22522. * @param {number} endAngle - The ending angle, in radians
  22523. * @param {boolean} anticlockwise - Specifies whether the drawing should be
  22524. * counter-clockwise or clockwise. False is default, and indicates clockwise, while true
  22525. * indicates counter-clockwise.
  22526. * @param {number} n - Number of segments
  22527. * @param {number[]} points - Collection of points to add to
  22528. */
  22529. ArcUtils.arc = function arc (startX, startY, cx, cy, radius, startAngle, endAngle, anticlockwise, points)
  22530. {
  22531. var sweep = endAngle - startAngle;
  22532. var n = GRAPHICS_CURVES._segmentsCount(
  22533. Math.abs(sweep) * radius,
  22534. Math.ceil(Math.abs(sweep) / PI_2) * 40
  22535. );
  22536. var theta = (sweep) / (n * 2);
  22537. var theta2 = theta * 2;
  22538. var cTheta = Math.cos(theta);
  22539. var sTheta = Math.sin(theta);
  22540. var segMinus = n - 1;
  22541. var remainder = (segMinus % 1) / segMinus;
  22542. for (var i = 0; i <= segMinus; ++i)
  22543. {
  22544. var real = i + (remainder * i);
  22545. var angle = ((theta) + startAngle + (theta2 * real));
  22546. var c = Math.cos(angle);
  22547. var s = -Math.sin(angle);
  22548. points.push(
  22549. (((cTheta * c) + (sTheta * s)) * radius) + cx,
  22550. (((cTheta * -s) + (sTheta * c)) * radius) + cy
  22551. );
  22552. }
  22553. };
  22554. /**
  22555. * Draw a star shape with an arbitrary number of points.
  22556. *
  22557. * @class
  22558. * @extends PIXI.Polygon
  22559. * @memberof PIXI
  22560. * @param {number} x - Center X position of the star
  22561. * @param {number} y - Center Y position of the star
  22562. * @param {number} points - The number of points of the star, must be > 1
  22563. * @param {number} radius - The outer radius of the star
  22564. * @param {number} [innerRadius] - The inner radius between points, default half `radius`
  22565. * @param {number} [rotation=0] - The rotation of the star in radians, where 0 is vertical
  22566. * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls
  22567. */
  22568. var Star = /*@__PURE__*/(function (Polygon) {
  22569. function Star(x, y, points, radius, innerRadius, rotation)
  22570. {
  22571. innerRadius = innerRadius || radius / 2;
  22572. var startAngle = (-1 * Math.PI / 2) + rotation;
  22573. var len = points * 2;
  22574. var delta = PI_2 / len;
  22575. var polygon = [];
  22576. for (var i = 0; i < len; i++)
  22577. {
  22578. var r = i % 2 ? innerRadius : radius;
  22579. var angle = (i * delta) + startAngle;
  22580. polygon.push(
  22581. x + (r * Math.cos(angle)),
  22582. y + (r * Math.sin(angle))
  22583. );
  22584. }
  22585. Polygon.call(this, polygon);
  22586. }
  22587. if ( Polygon ) { Star.__proto__ = Polygon; }
  22588. Star.prototype = Object.create( Polygon && Polygon.prototype );
  22589. Star.prototype.constructor = Star;
  22590. return Star;
  22591. }(Polygon));
  22592. var temp = new Float32Array(3);
  22593. // a default shader used by graphics..
  22594. var defaultShader = null;
  22595. /**
  22596. * The Graphics class contains methods used to draw primitive shapes such as lines, circles and
  22597. * rectangles to the display, and to color and fill them.
  22598. *
  22599. * Note that because Graphics can share a GraphicsGeometry with other instances,
  22600. * it is necessary to call `destroy()` to properly dereference the underlying
  22601. * GraphicsGeometry and avoid a memory leak. Alternatively, keep using the same
  22602. * Graphics instance and call `clear()` between redraws.
  22603. *
  22604. * @class
  22605. * @extends PIXI.Container
  22606. * @memberof PIXI
  22607. */
  22608. var Graphics = /*@__PURE__*/(function (Container) {
  22609. function Graphics(geometry)
  22610. {
  22611. if ( geometry === void 0 ) { geometry = null; }
  22612. Container.call(this);
  22613. /**
  22614. * Includes vertex positions, face indices, normals, colors, UVs, and
  22615. * custom attributes within buffers, reducing the cost of passing all
  22616. * this data to the GPU. Can be shared between multiple Mesh or Graphics objects.
  22617. * @member {PIXI.GraphicsGeometry}
  22618. * @readonly
  22619. */
  22620. this.geometry = geometry || new GraphicsGeometry();
  22621. this.geometry.refCount++;
  22622. /**
  22623. * Represents the vertex and fragment shaders that processes the geometry and runs on the GPU.
  22624. * Can be shared between multiple Graphics objects.
  22625. * @member {PIXI.Shader}
  22626. */
  22627. this.shader = null;
  22628. /**
  22629. * Represents the WebGL state the Graphics required to render, excludes shader and geometry. E.g.,
  22630. * blend mode, culling, depth testing, direction of rendering triangles, backface, etc.
  22631. * @member {PIXI.State}
  22632. */
  22633. this.state = State.for2d();
  22634. /**
  22635. * Current fill style
  22636. *
  22637. * @member {PIXI.FillStyle}
  22638. * @protected
  22639. */
  22640. this._fillStyle = new FillStyle();
  22641. /**
  22642. * Current line style
  22643. *
  22644. * @member {PIXI.LineStyle}
  22645. * @protected
  22646. */
  22647. this._lineStyle = new LineStyle();
  22648. /**
  22649. * Current shape transform matrix.
  22650. *
  22651. * @member {PIXI.Matrix}
  22652. * @protected
  22653. */
  22654. this._matrix = null;
  22655. /**
  22656. * Current hole mode is enabled.
  22657. *
  22658. * @member {boolean}
  22659. * @default false
  22660. * @protected
  22661. */
  22662. this._holeMode = false;
  22663. /**
  22664. * Current path
  22665. *
  22666. * @member {PIXI.Polygon}
  22667. * @protected
  22668. */
  22669. this.currentPath = null;
  22670. /**
  22671. * When cacheAsBitmap is set to true the graphics object will be rendered as if it was a sprite.
  22672. * This is useful if your graphics element does not change often, as it will speed up the rendering
  22673. * of the object in exchange for taking up texture memory. It is also useful if you need the graphics
  22674. * object to be anti-aliased, because it will be rendered using canvas. This is not recommended if
  22675. * you are constantly redrawing the graphics element.
  22676. *
  22677. * @name cacheAsBitmap
  22678. * @member {boolean}
  22679. * @memberof PIXI.Graphics#
  22680. * @default false
  22681. */
  22682. /**
  22683. * A collections of batches! These can be drawn by the renderer batch system.
  22684. *
  22685. * @protected
  22686. * @member {object[]}
  22687. */
  22688. this.batches = [];
  22689. /**
  22690. * Update dirty for limiting calculating tints for batches.
  22691. *
  22692. * @protected
  22693. * @member {number}
  22694. * @default -1
  22695. */
  22696. this.batchTint = -1;
  22697. /**
  22698. * Copy of the object vertex data.
  22699. *
  22700. * @protected
  22701. * @member {Float32Array}
  22702. */
  22703. this.vertexData = null;
  22704. this._transformID = -1;
  22705. this.batchDirty = -1;
  22706. // Set default
  22707. this.tint = 0xFFFFFF;
  22708. this.blendMode = BLEND_MODES.NORMAL;
  22709. }
  22710. if ( Container ) { Graphics.__proto__ = Container; }
  22711. Graphics.prototype = Object.create( Container && Container.prototype );
  22712. Graphics.prototype.constructor = Graphics;
  22713. var prototypeAccessors = { blendMode: { configurable: true },tint: { configurable: true },fill: { configurable: true },line: { configurable: true } };
  22714. /**
  22715. * Creates a new Graphics object with the same values as this one.
  22716. * Note that the only the properties of the object are cloned, not its transform (position,scale,etc)
  22717. *
  22718. * @return {PIXI.Graphics} A clone of the graphics object
  22719. */
  22720. Graphics.prototype.clone = function clone ()
  22721. {
  22722. this.finishPoly();
  22723. return new Graphics(this.geometry);
  22724. };
  22725. /**
  22726. * The blend mode to be applied to the graphic shape. Apply a value of
  22727. * `PIXI.BLEND_MODES.NORMAL` to reset the blend mode.
  22728. *
  22729. * @member {number}
  22730. * @default PIXI.BLEND_MODES.NORMAL;
  22731. * @see PIXI.BLEND_MODES
  22732. */
  22733. prototypeAccessors.blendMode.set = function (value)
  22734. {
  22735. this.state.blendMode = value;
  22736. };
  22737. prototypeAccessors.blendMode.get = function ()
  22738. {
  22739. return this.state.blendMode;
  22740. };
  22741. /**
  22742. * The tint applied to the graphic shape. This is a hex value. A value of
  22743. * 0xFFFFFF will remove any tint effect.
  22744. *
  22745. * @member {number}
  22746. * @default 0xFFFFFF
  22747. */
  22748. prototypeAccessors.tint.get = function ()
  22749. {
  22750. return this._tint;
  22751. };
  22752. prototypeAccessors.tint.set = function (value)
  22753. {
  22754. this._tint = value;
  22755. };
  22756. /**
  22757. * The current fill style.
  22758. *
  22759. * @member {PIXI.FillStyle}
  22760. * @readonly
  22761. */
  22762. prototypeAccessors.fill.get = function ()
  22763. {
  22764. return this._fillStyle;
  22765. };
  22766. /**
  22767. * The current line style.
  22768. *
  22769. * @member {PIXI.LineStyle}
  22770. * @readonly
  22771. */
  22772. prototypeAccessors.line.get = function ()
  22773. {
  22774. return this._lineStyle;
  22775. };
  22776. /**
  22777. * Specifies the line style used for subsequent calls to Graphics methods such as the lineTo()
  22778. * method or the drawCircle() method.
  22779. *
  22780. * @param {number} [width=0] - width of the line to draw, will update the objects stored style
  22781. * @param {number} [color=0] - color of the line to draw, will update the objects stored style
  22782. * @param {number} [alpha=1] - alpha of the line to draw, will update the objects stored style
  22783. * @param {number} [alignment=1] - alignment of the line to draw, (0 = inner, 0.5 = middle, 1 = outter)
  22784. * @param {boolean} [native=false] - If true the lines will be draw using LINES instead of TRIANGLE_STRIP
  22785. * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls
  22786. */
  22787. Graphics.prototype.lineStyle = function lineStyle (width, color, alpha, alignment, native)
  22788. {
  22789. if ( width === void 0 ) { width = 0; }
  22790. if ( color === void 0 ) { color = 0; }
  22791. if ( alpha === void 0 ) { alpha = 1; }
  22792. if ( alignment === void 0 ) { alignment = 0.5; }
  22793. if ( native === void 0 ) { native = false; }
  22794. this.lineTextureStyle(width, Texture.WHITE, color, alpha, null, alignment, native);
  22795. return this;
  22796. };
  22797. /**
  22798. * Like line style but support texture for line fill.
  22799. *
  22800. * @param {number} [width=0] - width of the line to draw, will update the objects stored style
  22801. * @param {PIXI.Texture} [texture=PIXI.Texture.WHITE] - Texture to use
  22802. * @param {number} [color=0] - color of the line to draw, will update the objects stored style
  22803. * @param {number} [alpha=1] - alpha of the line to draw, will update the objects stored style
  22804. * @param {PIXI.Matrix} [matrix=null] Texture matrix to transform texture
  22805. * @param {number} [alignment=0.5] - alignment of the line to draw, (0 = inner, 0.5 = middle, 1 = outter)
  22806. * @param {boolean} [native=false] - If true the lines will be draw using LINES instead of TRIANGLE_STRIP
  22807. * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls
  22808. */
  22809. Graphics.prototype.lineTextureStyle = function lineTextureStyle (width, texture, color, alpha,
  22810. matrix, alignment, native)
  22811. {
  22812. if ( width === void 0 ) { width = 0; }
  22813. if ( texture === void 0 ) { texture = Texture.WHITE; }
  22814. if ( color === void 0 ) { color = 0xFFFFFF; }
  22815. if ( alpha === void 0 ) { alpha = 1; }
  22816. if ( matrix === void 0 ) { matrix = null; }
  22817. if ( alignment === void 0 ) { alignment = 0.5; }
  22818. if ( native === void 0 ) { native = false; }
  22819. if (this.currentPath)
  22820. {
  22821. this.startPoly();
  22822. }
  22823. var visible = width > 0 && alpha > 0;
  22824. if (!visible)
  22825. {
  22826. this._lineStyle.reset();
  22827. }
  22828. else
  22829. {
  22830. if (matrix)
  22831. {
  22832. matrix = matrix.clone();
  22833. matrix.invert();
  22834. }
  22835. Object.assign(this._lineStyle, {
  22836. color: color,
  22837. width: width,
  22838. alpha: alpha,
  22839. matrix: matrix,
  22840. texture: texture,
  22841. alignment: alignment,
  22842. native: native,
  22843. visible: visible,
  22844. });
  22845. }
  22846. return this;
  22847. };
  22848. /**
  22849. * Start a polygon object internally
  22850. * @protected
  22851. */
  22852. Graphics.prototype.startPoly = function startPoly ()
  22853. {
  22854. if (this.currentPath)
  22855. {
  22856. var points = this.currentPath.points;
  22857. var len = this.currentPath.points.length;
  22858. if (len > 2)
  22859. {
  22860. this.drawShape(this.currentPath);
  22861. this.currentPath = new Polygon();
  22862. this.currentPath.closeStroke = false;
  22863. this.currentPath.points.push(points[len - 2], points[len - 1]);
  22864. }
  22865. }
  22866. else
  22867. {
  22868. this.currentPath = new Polygon();
  22869. this.currentPath.closeStroke = false;
  22870. }
  22871. };
  22872. /**
  22873. * Finish the polygon object.
  22874. * @protected
  22875. */
  22876. Graphics.prototype.finishPoly = function finishPoly ()
  22877. {
  22878. if (this.currentPath)
  22879. {
  22880. if (this.currentPath.points.length > 2)
  22881. {
  22882. this.drawShape(this.currentPath);
  22883. this.currentPath = null;
  22884. }
  22885. else
  22886. {
  22887. this.currentPath.points.length = 0;
  22888. }
  22889. }
  22890. };
  22891. /**
  22892. * Moves the current drawing position to x, y.
  22893. *
  22894. * @param {number} x - the X coordinate to move to
  22895. * @param {number} y - the Y coordinate to move to
  22896. * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls
  22897. */
  22898. Graphics.prototype.moveTo = function moveTo (x, y)
  22899. {
  22900. this.startPoly();
  22901. this.currentPath.points[0] = x;
  22902. this.currentPath.points[1] = y;
  22903. return this;
  22904. };
  22905. /**
  22906. * Draws a line using the current line style from the current drawing position to (x, y);
  22907. * The current drawing position is then set to (x, y).
  22908. *
  22909. * @param {number} x - the X coordinate to draw to
  22910. * @param {number} y - the Y coordinate to draw to
  22911. * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls
  22912. */
  22913. Graphics.prototype.lineTo = function lineTo (x, y)
  22914. {
  22915. if (!this.currentPath)
  22916. {
  22917. this.moveTo(0, 0);
  22918. }
  22919. // remove duplicates..
  22920. var points = this.currentPath.points;
  22921. var fromX = points[points.length - 2];
  22922. var fromY = points[points.length - 1];
  22923. if (fromX !== x || fromY !== y)
  22924. {
  22925. points.push(x, y);
  22926. }
  22927. return this;
  22928. };
  22929. /**
  22930. * Initialize the curve
  22931. *
  22932. * @protected
  22933. * @param {number} [x=0]
  22934. * @param {number} [y=0]
  22935. */
  22936. Graphics.prototype._initCurve = function _initCurve (x, y)
  22937. {
  22938. if ( x === void 0 ) { x = 0; }
  22939. if ( y === void 0 ) { y = 0; }
  22940. if (this.currentPath)
  22941. {
  22942. if (this.currentPath.points.length === 0)
  22943. {
  22944. this.currentPath.points = [x, y];
  22945. }
  22946. }
  22947. else
  22948. {
  22949. this.moveTo(x, y);
  22950. }
  22951. };
  22952. /**
  22953. * Calculate the points for a quadratic bezier curve and then draws it.
  22954. * Based on: https://stackoverflow.com/questions/785097/how-do-i-implement-a-bezier-curve-in-c
  22955. *
  22956. * @param {number} cpX - Control point x
  22957. * @param {number} cpY - Control point y
  22958. * @param {number} toX - Destination point x
  22959. * @param {number} toY - Destination point y
  22960. * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls
  22961. */
  22962. Graphics.prototype.quadraticCurveTo = function quadraticCurveTo (cpX, cpY, toX, toY)
  22963. {
  22964. this._initCurve();
  22965. var points = this.currentPath.points;
  22966. if (points.length === 0)
  22967. {
  22968. this.moveTo(0, 0);
  22969. }
  22970. QuadraticUtils.curveTo(cpX, cpY, toX, toY, points);
  22971. return this;
  22972. };
  22973. /**
  22974. * Calculate the points for a bezier curve and then draws it.
  22975. *
  22976. * @param {number} cpX - Control point x
  22977. * @param {number} cpY - Control point y
  22978. * @param {number} cpX2 - Second Control point x
  22979. * @param {number} cpY2 - Second Control point y
  22980. * @param {number} toX - Destination point x
  22981. * @param {number} toY - Destination point y
  22982. * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls
  22983. */
  22984. Graphics.prototype.bezierCurveTo = function bezierCurveTo (cpX, cpY, cpX2, cpY2, toX, toY)
  22985. {
  22986. this._initCurve();
  22987. BezierUtils.curveTo(cpX, cpY, cpX2, cpY2, toX, toY, this.currentPath.points);
  22988. return this;
  22989. };
  22990. /**
  22991. * The arcTo() method creates an arc/curve between two tangents on the canvas.
  22992. *
  22993. * "borrowed" from https://code.google.com/p/fxcanvas/ - thanks google!
  22994. *
  22995. * @param {number} x1 - The x-coordinate of the beginning of the arc
  22996. * @param {number} y1 - The y-coordinate of the beginning of the arc
  22997. * @param {number} x2 - The x-coordinate of the end of the arc
  22998. * @param {number} y2 - The y-coordinate of the end of the arc
  22999. * @param {number} radius - The radius of the arc
  23000. * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls
  23001. */
  23002. Graphics.prototype.arcTo = function arcTo (x1, y1, x2, y2, radius)
  23003. {
  23004. this._initCurve(x1, y1);
  23005. var points = this.currentPath.points;
  23006. var result = ArcUtils.curveTo(x1, y1, x2, y2, radius, points);
  23007. if (result)
  23008. {
  23009. var cx = result.cx;
  23010. var cy = result.cy;
  23011. var radius$1 = result.radius;
  23012. var startAngle = result.startAngle;
  23013. var endAngle = result.endAngle;
  23014. var anticlockwise = result.anticlockwise;
  23015. this.arc(cx, cy, radius$1, startAngle, endAngle, anticlockwise);
  23016. }
  23017. return this;
  23018. };
  23019. /**
  23020. * The arc method creates an arc/curve (used to create circles, or parts of circles).
  23021. *
  23022. * @param {number} cx - The x-coordinate of the center of the circle
  23023. * @param {number} cy - The y-coordinate of the center of the circle
  23024. * @param {number} radius - The radius of the circle
  23025. * @param {number} startAngle - The starting angle, in radians (0 is at the 3 o'clock position
  23026. * of the arc's circle)
  23027. * @param {number} endAngle - The ending angle, in radians
  23028. * @param {boolean} [anticlockwise=false] - Specifies whether the drawing should be
  23029. * counter-clockwise or clockwise. False is default, and indicates clockwise, while true
  23030. * indicates counter-clockwise.
  23031. * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls
  23032. */
  23033. Graphics.prototype.arc = function arc (cx, cy, radius, startAngle, endAngle, anticlockwise)
  23034. {
  23035. if ( anticlockwise === void 0 ) { anticlockwise = false; }
  23036. if (startAngle === endAngle)
  23037. {
  23038. return this;
  23039. }
  23040. if (!anticlockwise && endAngle <= startAngle)
  23041. {
  23042. endAngle += PI_2;
  23043. }
  23044. else if (anticlockwise && startAngle <= endAngle)
  23045. {
  23046. startAngle += PI_2;
  23047. }
  23048. var sweep = endAngle - startAngle;
  23049. if (sweep === 0)
  23050. {
  23051. return this;
  23052. }
  23053. var startX = cx + (Math.cos(startAngle) * radius);
  23054. var startY = cy + (Math.sin(startAngle) * radius);
  23055. // If the currentPath exists, take its points. Otherwise call `moveTo` to start a path.
  23056. var points = this.currentPath ? this.currentPath.points : null;
  23057. if (points)
  23058. {
  23059. // TODO: make a better fix.
  23060. // We check how far our start is from the last existing point
  23061. var xDiff = Math.abs(points[points.length - 2] - startX);
  23062. var yDiff = Math.abs(points[points.length - 1] - startY);
  23063. if (xDiff < 0.001 && yDiff < 0.001)
  23064. { ; }
  23065. else
  23066. {
  23067. points.push(startX, startY);
  23068. }
  23069. }
  23070. else
  23071. {
  23072. this.moveTo(startX, startY);
  23073. points = this.currentPath.points;
  23074. }
  23075. ArcUtils.arc(startX, startY, cx, cy, radius, startAngle, endAngle, anticlockwise, points);
  23076. return this;
  23077. };
  23078. /**
  23079. * Specifies a simple one-color fill that subsequent calls to other Graphics methods
  23080. * (such as lineTo() or drawCircle()) use when drawing.
  23081. *
  23082. * @param {number} [color=0] - the color of the fill
  23083. * @param {number} [alpha=1] - the alpha of the fill
  23084. * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls
  23085. */
  23086. Graphics.prototype.beginFill = function beginFill (color, alpha)
  23087. {
  23088. if ( color === void 0 ) { color = 0; }
  23089. if ( alpha === void 0 ) { alpha = 1; }
  23090. return this.beginTextureFill(Texture.WHITE, color, alpha);
  23091. };
  23092. /**
  23093. * Begin the texture fill
  23094. *
  23095. * @param {PIXI.Texture} [texture=PIXI.Texture.WHITE] - Texture to fill
  23096. * @param {number} [color=0xffffff] - Background to fill behind texture
  23097. * @param {number} [alpha=1] - Alpha of fill
  23098. * @param {PIXI.Matrix} [matrix=null] - Transform matrix
  23099. * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls
  23100. */
  23101. Graphics.prototype.beginTextureFill = function beginTextureFill (texture, color, alpha, matrix)
  23102. {
  23103. if ( texture === void 0 ) { texture = Texture.WHITE; }
  23104. if ( color === void 0 ) { color = 0xFFFFFF; }
  23105. if ( alpha === void 0 ) { alpha = 1; }
  23106. if ( matrix === void 0 ) { matrix = null; }
  23107. if (this.currentPath)
  23108. {
  23109. this.startPoly();
  23110. }
  23111. var visible = alpha > 0;
  23112. if (!visible)
  23113. {
  23114. this._fillStyle.reset();
  23115. }
  23116. else
  23117. {
  23118. if (matrix)
  23119. {
  23120. matrix = matrix.clone();
  23121. matrix.invert();
  23122. }
  23123. Object.assign(this._fillStyle, {
  23124. color: color,
  23125. alpha: alpha,
  23126. texture: texture,
  23127. matrix: matrix,
  23128. visible: visible,
  23129. });
  23130. }
  23131. return this;
  23132. };
  23133. /**
  23134. * Applies a fill to the lines and shapes that were added since the last call to the beginFill() method.
  23135. *
  23136. * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls
  23137. */
  23138. Graphics.prototype.endFill = function endFill ()
  23139. {
  23140. this.finishPoly();
  23141. this._fillStyle.reset();
  23142. return this;
  23143. };
  23144. /**
  23145. * Draws a rectangle shape.
  23146. *
  23147. * @param {number} x - The X coord of the top-left of the rectangle
  23148. * @param {number} y - The Y coord of the top-left of the rectangle
  23149. * @param {number} width - The width of the rectangle
  23150. * @param {number} height - The height of the rectangle
  23151. * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls
  23152. */
  23153. Graphics.prototype.drawRect = function drawRect (x, y, width, height)
  23154. {
  23155. return this.drawShape(new Rectangle(x, y, width, height));
  23156. };
  23157. /**
  23158. * Draw a rectangle shape with rounded/beveled corners.
  23159. *
  23160. * @param {number} x - The X coord of the top-left of the rectangle
  23161. * @param {number} y - The Y coord of the top-left of the rectangle
  23162. * @param {number} width - The width of the rectangle
  23163. * @param {number} height - The height of the rectangle
  23164. * @param {number} radius - Radius of the rectangle corners
  23165. * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls
  23166. */
  23167. Graphics.prototype.drawRoundedRect = function drawRoundedRect (x, y, width, height, radius)
  23168. {
  23169. return this.drawShape(new RoundedRectangle(x, y, width, height, radius));
  23170. };
  23171. /**
  23172. * Draws a circle.
  23173. *
  23174. * @param {number} x - The X coordinate of the center of the circle
  23175. * @param {number} y - The Y coordinate of the center of the circle
  23176. * @param {number} radius - The radius of the circle
  23177. * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls
  23178. */
  23179. Graphics.prototype.drawCircle = function drawCircle (x, y, radius)
  23180. {
  23181. return this.drawShape(new Circle(x, y, radius));
  23182. };
  23183. /**
  23184. * Draws an ellipse.
  23185. *
  23186. * @param {number} x - The X coordinate of the center of the ellipse
  23187. * @param {number} y - The Y coordinate of the center of the ellipse
  23188. * @param {number} width - The half width of the ellipse
  23189. * @param {number} height - The half height of the ellipse
  23190. * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls
  23191. */
  23192. Graphics.prototype.drawEllipse = function drawEllipse (x, y, width, height)
  23193. {
  23194. return this.drawShape(new Ellipse(x, y, width, height));
  23195. };
  23196. /**
  23197. * Draws a polygon using the given path.
  23198. *
  23199. * @param {number[]|PIXI.Point[]|PIXI.Polygon} path - The path data used to construct the polygon.
  23200. * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls
  23201. */
  23202. Graphics.prototype.drawPolygon = function drawPolygon (path)
  23203. {
  23204. var arguments$1 = arguments;
  23205. // prevents an argument assignment deopt
  23206. // see section 3.1: https://github.com/petkaantonov/bluebird/wiki/Optimization-killers#3-managing-arguments
  23207. var points = path;
  23208. var closeStroke = true;// !!this._fillStyle;
  23209. // check if data has points..
  23210. if (points.points)
  23211. {
  23212. closeStroke = points.closeStroke;
  23213. points = points.points;
  23214. }
  23215. if (!Array.isArray(points))
  23216. {
  23217. // prevents an argument leak deopt
  23218. // see section 3.2: https://github.com/petkaantonov/bluebird/wiki/Optimization-killers#3-managing-arguments
  23219. points = new Array(arguments.length);
  23220. for (var i = 0; i < points.length; ++i)
  23221. {
  23222. points[i] = arguments$1[i]; // eslint-disable-line prefer-rest-params
  23223. }
  23224. }
  23225. var shape = new Polygon(points);
  23226. shape.closeStroke = closeStroke;
  23227. this.drawShape(shape);
  23228. return this;
  23229. };
  23230. /**
  23231. * Draw any shape.
  23232. *
  23233. * @param {PIXI.Circle|PIXI.Ellipse|PIXI.Polygon|PIXI.Rectangle|PIXI.RoundedRectangle} shape - Shape to draw
  23234. * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls
  23235. */
  23236. Graphics.prototype.drawShape = function drawShape (shape)
  23237. {
  23238. if (!this._holeMode)
  23239. {
  23240. this.geometry.drawShape(
  23241. shape,
  23242. this._fillStyle.clone(),
  23243. this._lineStyle.clone(),
  23244. this._matrix
  23245. );
  23246. }
  23247. else
  23248. {
  23249. this.geometry.drawHole(shape, this._matrix);
  23250. }
  23251. return this;
  23252. };
  23253. /**
  23254. * Draw a star shape with an arbitrary number of points.
  23255. *
  23256. * @param {number} x - Center X position of the star
  23257. * @param {number} y - Center Y position of the star
  23258. * @param {number} points - The number of points of the star, must be > 1
  23259. * @param {number} radius - The outer radius of the star
  23260. * @param {number} [innerRadius] - The inner radius between points, default half `radius`
  23261. * @param {number} [rotation=0] - The rotation of the star in radians, where 0 is vertical
  23262. * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls
  23263. */
  23264. Graphics.prototype.drawStar = function drawStar (x, y, points, radius, innerRadius, rotation)
  23265. {
  23266. if ( rotation === void 0 ) { rotation = 0; }
  23267. return this.drawPolygon(new Star(x, y, points, radius, innerRadius, rotation));
  23268. };
  23269. /**
  23270. * Clears the graphics that were drawn to this Graphics object, and resets fill and line style settings.
  23271. *
  23272. * @return {PIXI.Graphics} This Graphics object. Good for chaining method calls
  23273. */
  23274. Graphics.prototype.clear = function clear ()
  23275. {
  23276. this.geometry.clear();
  23277. this._matrix = null;
  23278. this._holeMode = false;
  23279. this.currentPath = null;
  23280. this._spriteRect = null;
  23281. return this;
  23282. };
  23283. /**
  23284. * True if graphics consists of one rectangle, and thus, can be drawn like a Sprite and
  23285. * masked with gl.scissor.
  23286. *
  23287. * @returns {boolean} True if only 1 rect.
  23288. */
  23289. Graphics.prototype.isFastRect = function isFastRect ()
  23290. {
  23291. // will fix this!
  23292. return false;
  23293. // this.graphicsData.length === 1
  23294. // && this.graphicsData[0].shape.type === SHAPES.RECT
  23295. // && !this.graphicsData[0].lineWidth;
  23296. };
  23297. /**
  23298. * Renders the object using the WebGL renderer
  23299. *
  23300. * @protected
  23301. * @param {PIXI.Renderer} renderer - The renderer
  23302. */
  23303. Graphics.prototype._render = function _render (renderer)
  23304. {
  23305. this.finishPoly();
  23306. var geometry = this.geometry;
  23307. // batch part..
  23308. // batch it!
  23309. geometry.updateBatches();
  23310. if (geometry.batchable)
  23311. {
  23312. if (this.batchDirty !== geometry.batchDirty)
  23313. {
  23314. this.batches = [];
  23315. this.batchTint = -1;
  23316. this._transformID = -1;
  23317. this.batchDirty = geometry.batchDirty;
  23318. this.vertexData = new Float32Array(geometry.points);
  23319. var blendMode = this.blendMode;
  23320. for (var i = 0; i < geometry.batches.length; i++)
  23321. {
  23322. var gI = geometry.batches[i];
  23323. var color = gI.style.color;
  23324. // + (alpha * 255 << 24);
  23325. var vertexData = new Float32Array(this.vertexData.buffer,
  23326. gI.attribStart * 4 * 2,
  23327. gI.attribSize * 2);
  23328. var uvs = new Float32Array(geometry.uvsFloat32.buffer,
  23329. gI.attribStart * 4 * 2,
  23330. gI.attribSize * 2);
  23331. var indices = new Uint16Array(geometry.indicesUint16.buffer,
  23332. gI.start * 2,
  23333. gI.size);
  23334. var batch = {
  23335. vertexData: vertexData,
  23336. blendMode: blendMode,
  23337. indices: indices,
  23338. uvs: uvs,
  23339. _batchRGB: hex2rgb(color),
  23340. _tintRGB: color,
  23341. _texture: gI.style.texture,
  23342. alpha: gI.style.alpha,
  23343. worldAlpha: 1 };
  23344. this.batches[i] = batch;
  23345. }
  23346. }
  23347. renderer.batch.setObjectRenderer(renderer.plugins.batch);
  23348. if (this.batches.length)
  23349. {
  23350. this.calculateVertices();
  23351. this.calculateTints();
  23352. for (var i$1 = 0; i$1 < this.batches.length; i$1++)
  23353. {
  23354. var batch$1 = this.batches[i$1];
  23355. batch$1.worldAlpha = this.worldAlpha * batch$1.alpha;
  23356. renderer.plugins.batch.render(batch$1);
  23357. }
  23358. }
  23359. }
  23360. else
  23361. {
  23362. // no batching...
  23363. renderer.batch.flush();
  23364. if (!this.shader)
  23365. {
  23366. // if there is no shader here, we can use the default shader.
  23367. // and that only gets created if we actually need it..
  23368. if (!defaultShader)
  23369. {
  23370. var sampleValues = new Int32Array(16);
  23371. for (var i$2 = 0; i$2 < 16; i$2++)
  23372. {
  23373. sampleValues[i$2] = i$2;
  23374. }
  23375. var uniforms = {
  23376. tint: new Float32Array([1, 1, 1, 1]),
  23377. translationMatrix: new Matrix(),
  23378. default: UniformGroup.from({ uSamplers: sampleValues }, true),
  23379. };
  23380. // we can bbase default shader of the batch renderers program
  23381. var program = renderer.plugins.batch.shader.program;
  23382. defaultShader = new Shader(program, uniforms);
  23383. }
  23384. this.shader = defaultShader;
  23385. }
  23386. var uniforms$1 = this.shader.uniforms;
  23387. // lets set the transfomr
  23388. uniforms$1.translationMatrix = this.transform.worldTransform;
  23389. var tint = this.tint;
  23390. var wa = this.worldAlpha;
  23391. // and then lets set the tint..
  23392. uniforms$1.tint[0] = (((tint >> 16) & 0xFF) / 255) * wa;
  23393. uniforms$1.tint[1] = (((tint >> 8) & 0xFF) / 255) * wa;
  23394. uniforms$1.tint[2] = ((tint & 0xFF) / 255) * wa;
  23395. uniforms$1.tint[3] = wa;
  23396. // the first draw call, we can set the uniforms of the shader directly here.
  23397. // this means that we can tack advantage of the sync function of pixi!
  23398. // bind and sync uniforms..
  23399. // there is a way to optimise this..
  23400. renderer.shader.bind(this.shader);
  23401. // then render it
  23402. renderer.geometry.bind(geometry, this.shader);
  23403. // set state..
  23404. renderer.state.setState(this.state);
  23405. // then render the rest of them...
  23406. for (var i$3 = 0; i$3 < geometry.drawCalls.length; i$3++)
  23407. {
  23408. var drawCall = geometry.drawCalls[i$3];
  23409. var groupTextureCount = drawCall.textureCount;
  23410. for (var j = 0; j < groupTextureCount; j++)
  23411. {
  23412. renderer.texture.bind(drawCall.textures[j], j);
  23413. }
  23414. // bind the geometry...
  23415. renderer.geometry.draw(drawCall.type, drawCall.size, drawCall.start);
  23416. }
  23417. }
  23418. };
  23419. /**
  23420. * Retrieves the bounds of the graphic shape as a rectangle object
  23421. *
  23422. * @protected
  23423. */
  23424. Graphics.prototype._calculateBounds = function _calculateBounds ()
  23425. {
  23426. this.finishPoly();
  23427. var lb = this.geometry.bounds;
  23428. this._bounds.addFrame(this.transform, lb.minX, lb.minY, lb.maxX, lb.maxY);
  23429. };
  23430. /**
  23431. * Tests if a point is inside this graphics object
  23432. *
  23433. * @param {PIXI.Point} point - the point to test
  23434. * @return {boolean} the result of the test
  23435. */
  23436. Graphics.prototype.containsPoint = function containsPoint (point)
  23437. {
  23438. this.worldTransform.applyInverse(point, Graphics._TEMP_POINT);
  23439. return this.geometry.containsPoint(Graphics._TEMP_POINT);
  23440. };
  23441. /**
  23442. * Recalcuate the tint by applying tin to batches using Graphics tint.
  23443. * @protected
  23444. */
  23445. Graphics.prototype.calculateTints = function calculateTints ()
  23446. {
  23447. if (this.batchTint !== this.tint)
  23448. {
  23449. this.batchTint = this.tint;
  23450. var tintRGB = hex2rgb(this.tint, temp);
  23451. for (var i = 0; i < this.batches.length; i++)
  23452. {
  23453. var batch = this.batches[i];
  23454. var batchTint = batch._batchRGB;
  23455. var r = (tintRGB[0] * batchTint[0]) * 255;
  23456. var g = (tintRGB[1] * batchTint[1]) * 255;
  23457. var b = (tintRGB[2] * batchTint[2]) * 255;
  23458. // TODO Ivan, can this be done in one go?
  23459. var color = (r << 16) + (g << 8) + (b | 0);
  23460. batch._tintRGB = (color >> 16)
  23461. + (color & 0xff00)
  23462. + ((color & 0xff) << 16);
  23463. }
  23464. }
  23465. };
  23466. /**
  23467. * If there's a transform update or a change to the shape of the
  23468. * geometry, recaculate the vertices.
  23469. * @protected
  23470. */
  23471. Graphics.prototype.calculateVertices = function calculateVertices ()
  23472. {
  23473. if (this._transformID === this.transform._worldID)
  23474. {
  23475. return;
  23476. }
  23477. this._transformID = this.transform._worldID;
  23478. var wt = this.transform.worldTransform;
  23479. var a = wt.a;
  23480. var b = wt.b;
  23481. var c = wt.c;
  23482. var d = wt.d;
  23483. var tx = wt.tx;
  23484. var ty = wt.ty;
  23485. var data = this.geometry.points;// batch.vertexDataOriginal;
  23486. var vertexData = this.vertexData;
  23487. var count = 0;
  23488. for (var i = 0; i < data.length; i += 2)
  23489. {
  23490. var x = data[i];
  23491. var y = data[i + 1];
  23492. vertexData[count++] = (a * x) + (c * y) + tx;
  23493. vertexData[count++] = (d * y) + (b * x) + ty;
  23494. }
  23495. };
  23496. /**
  23497. * Closes the current path.
  23498. *
  23499. * @return {PIXI.Graphics} Returns itself.
  23500. */
  23501. Graphics.prototype.closePath = function closePath ()
  23502. {
  23503. var currentPath = this.currentPath;
  23504. if (currentPath)
  23505. {
  23506. // we don't need to add extra point in the end because buildLine will take care of that
  23507. currentPath.closeStroke = true;
  23508. }
  23509. return this;
  23510. };
  23511. /**
  23512. * Apply a matrix to the positional data.
  23513. *
  23514. * @param {PIXI.Matrix} matrix - Matrix to use for transform current shape.
  23515. * @return {PIXI.Graphics} Returns itself.
  23516. */
  23517. Graphics.prototype.setMatrix = function setMatrix (matrix)
  23518. {
  23519. this._matrix = matrix;
  23520. return this;
  23521. };
  23522. /**
  23523. * Begin adding holes to the last draw shape
  23524. * IMPORTANT: holes must be fully inside a shape to work
  23525. * Also weirdness ensues if holes overlap!
  23526. * Ellipses, Circles, Rectangles and Rounded Rectangles cannot be holes or host for holes in CanvasRenderer,
  23527. * please use `moveTo` `lineTo`, `quadraticCurveTo` if you rely on pixi-legacy bundle.
  23528. * @return {PIXI.Graphics} Returns itself.
  23529. */
  23530. Graphics.prototype.beginHole = function beginHole ()
  23531. {
  23532. this.finishPoly();
  23533. this._holeMode = true;
  23534. return this;
  23535. };
  23536. /**
  23537. * End adding holes to the last draw shape
  23538. * @return {PIXI.Graphics} Returns itself.
  23539. */
  23540. Graphics.prototype.endHole = function endHole ()
  23541. {
  23542. this.finishPoly();
  23543. this._holeMode = false;
  23544. return this;
  23545. };
  23546. /**
  23547. * Destroys the Graphics object.
  23548. *
  23549. * @param {object|boolean} [options] - Options parameter. A boolean will act as if all
  23550. * options have been set to that value
  23551. * @param {boolean} [options.children=false] - if set to true, all the children will have
  23552. * their destroy method called as well. 'options' will be passed on to those calls.
  23553. * @param {boolean} [options.texture=false] - Only used for child Sprites if options.children is set to true
  23554. * Should it destroy the texture of the child sprite
  23555. * @param {boolean} [options.baseTexture=false] - Only used for child Sprites if options.children is set to true
  23556. * Should it destroy the base texture of the child sprite
  23557. */
  23558. Graphics.prototype.destroy = function destroy (options)
  23559. {
  23560. Container.prototype.destroy.call(this, options);
  23561. this.geometry.refCount--;
  23562. if (this.geometry.refCount === 0)
  23563. {
  23564. this.geometry.dispose();
  23565. }
  23566. this._matrix = null;
  23567. this.currentPath = null;
  23568. this._lineStyle.destroy();
  23569. this._lineStyle = null;
  23570. this._fillStyle.destroy();
  23571. this._fillStyle = null;
  23572. this.geometry = null;
  23573. this.shader = null;
  23574. this.vertexData = null;
  23575. this.batches.length = 0;
  23576. this.batches = null;
  23577. Container.prototype.destroy.call(this, options);
  23578. };
  23579. Object.defineProperties( Graphics.prototype, prototypeAccessors );
  23580. return Graphics;
  23581. }(Container));
  23582. /**
  23583. * Temporary point to use for containsPoint
  23584. *
  23585. * @static
  23586. * @private
  23587. * @member {PIXI.Point}
  23588. */
  23589. Graphics._TEMP_POINT = new Point();
  23590. /*!
  23591. * @pixi/sprite - v5.0.4
  23592. * Compiled Fri, 07 Jun 2019 17:17:49 UTC
  23593. *
  23594. * @pixi/sprite is licensed under the MIT License.
  23595. * http://www.opensource.org/licenses/mit-license
  23596. */
  23597. var tempPoint = new Point();
  23598. var indices = new Uint16Array([0, 1, 2, 0, 2, 3]);
  23599. /**
  23600. * The Sprite object is the base for all textured objects that are rendered to the screen
  23601. *
  23602. * A sprite can be created directly from an image like this:
  23603. *
  23604. * ```js
  23605. * let sprite = PIXI.Sprite.from('assets/image.png');
  23606. * ```
  23607. *
  23608. * The more efficient way to create sprites is using a {@link PIXI.Spritesheet},
  23609. * as swapping base textures when rendering to the screen is inefficient.
  23610. *
  23611. * ```js
  23612. * PIXI.Loader.shared.add("assets/spritesheet.json").load(setup);
  23613. *
  23614. * function setup() {
  23615. * let sheet = PIXI.Loader.shared.resources["assets/spritesheet.json"].spritesheet;
  23616. * let sprite = new PIXI.Sprite(sheet.textures["image.png"]);
  23617. * ...
  23618. * }
  23619. * ```
  23620. *
  23621. * @class
  23622. * @extends PIXI.Container
  23623. * @memberof PIXI
  23624. */
  23625. var Sprite = /*@__PURE__*/(function (Container) {
  23626. function Sprite(texture)
  23627. {
  23628. Container.call(this);
  23629. /**
  23630. * The anchor sets the origin point of the texture.
  23631. * The default is 0,0 or taken from the {@link PIXI.Texture#defaultAnchor|Texture}
  23632. * passed to the constructor. A value of 0,0 means the texture's origin is the top left.
  23633. * Setting the anchor to 0.5,0.5 means the texture's origin is centered.
  23634. * Setting the anchor to 1,1 would mean the texture's origin point will be the bottom right corner.
  23635. * Note: Updating the {@link PIXI.Texture#defaultAnchor} after a Texture is
  23636. * created does _not_ update the Sprite's anchor values.
  23637. *
  23638. * @member {PIXI.ObservablePoint}
  23639. * @private
  23640. */
  23641. this._anchor = new ObservablePoint(
  23642. this._onAnchorUpdate,
  23643. this,
  23644. (texture ? texture.defaultAnchor.x : 0),
  23645. (texture ? texture.defaultAnchor.y : 0)
  23646. );
  23647. /**
  23648. * The texture that the sprite is using
  23649. *
  23650. * @private
  23651. * @member {PIXI.Texture}
  23652. */
  23653. this._texture = null;
  23654. /**
  23655. * The width of the sprite (this is initially set by the texture)
  23656. *
  23657. * @private
  23658. * @member {number}
  23659. */
  23660. this._width = 0;
  23661. /**
  23662. * The height of the sprite (this is initially set by the texture)
  23663. *
  23664. * @private
  23665. * @member {number}
  23666. */
  23667. this._height = 0;
  23668. /**
  23669. * The tint applied to the sprite. This is a hex value. A value of 0xFFFFFF will remove any tint effect.
  23670. *
  23671. * @private
  23672. * @member {number}
  23673. * @default 0xFFFFFF
  23674. */
  23675. this._tint = null;
  23676. this._tintRGB = null;
  23677. this.tint = 0xFFFFFF;
  23678. /**
  23679. * The blend mode to be applied to the sprite. Apply a value of `PIXI.BLEND_MODES.NORMAL` to reset the blend mode.
  23680. *
  23681. * @member {number}
  23682. * @default PIXI.BLEND_MODES.NORMAL
  23683. * @see PIXI.BLEND_MODES
  23684. */
  23685. this.blendMode = BLEND_MODES.NORMAL;
  23686. /**
  23687. * The shader that will be used to render the sprite. Set to null to remove a current shader.
  23688. *
  23689. * @member {PIXI.Filter|PIXI.Shader}
  23690. */
  23691. this.shader = null;
  23692. /**
  23693. * Cached tint value so we can tell when the tint is changed.
  23694. * Value is used for 2d CanvasRenderer.
  23695. *
  23696. * @protected
  23697. * @member {number}
  23698. * @default 0xFFFFFF
  23699. */
  23700. this._cachedTint = 0xFFFFFF;
  23701. this.uvs = null;
  23702. // call texture setter
  23703. this.texture = texture || Texture.EMPTY;
  23704. /**
  23705. * this is used to store the vertex data of the sprite (basically a quad)
  23706. *
  23707. * @private
  23708. * @member {Float32Array}
  23709. */
  23710. this.vertexData = new Float32Array(8);
  23711. /**
  23712. * This is used to calculate the bounds of the object IF it is a trimmed sprite
  23713. *
  23714. * @private
  23715. * @member {Float32Array}
  23716. */
  23717. this.vertexTrimmedData = null;
  23718. this._transformID = -1;
  23719. this._textureID = -1;
  23720. this._transformTrimmedID = -1;
  23721. this._textureTrimmedID = -1;
  23722. // Batchable stuff..
  23723. // TODO could make this a mixin?
  23724. this.indices = indices;
  23725. this.size = 4;
  23726. this.start = 0;
  23727. /**
  23728. * Plugin that is responsible for rendering this element.
  23729. * Allows to customize the rendering process without overriding '_render' & '_renderCanvas' methods.
  23730. *
  23731. * @member {string}
  23732. * @default 'sprite'
  23733. */
  23734. this.pluginName = 'batch';
  23735. /**
  23736. * used to fast check if a sprite is.. a sprite!
  23737. * @member {boolean}
  23738. */
  23739. this.isSprite = true;
  23740. /**
  23741. * Internal roundPixels field
  23742. *
  23743. * @member {boolean}
  23744. * @private
  23745. */
  23746. this._roundPixels = settings.ROUND_PIXELS;
  23747. }
  23748. if ( Container ) { Sprite.__proto__ = Container; }
  23749. Sprite.prototype = Object.create( Container && Container.prototype );
  23750. Sprite.prototype.constructor = Sprite;
  23751. var prototypeAccessors = { roundPixels: { configurable: true },width: { configurable: true },height: { configurable: true },anchor: { configurable: true },tint: { configurable: true },texture: { configurable: true } };
  23752. /**
  23753. * When the texture is updated, this event will fire to update the scale and frame
  23754. *
  23755. * @private
  23756. */
  23757. Sprite.prototype._onTextureUpdate = function _onTextureUpdate ()
  23758. {
  23759. this._textureID = -1;
  23760. this._textureTrimmedID = -1;
  23761. this._cachedTint = 0xFFFFFF;
  23762. this.uvs = this._texture._uvs.uvsFloat32;
  23763. // so if _width is 0 then width was not set..
  23764. if (this._width)
  23765. {
  23766. this.scale.x = sign(this.scale.x) * this._width / this._texture.orig.width;
  23767. }
  23768. if (this._height)
  23769. {
  23770. this.scale.y = sign(this.scale.y) * this._height / this._texture.orig.height;
  23771. }
  23772. };
  23773. /**
  23774. * Called when the anchor position updates.
  23775. *
  23776. * @private
  23777. */
  23778. Sprite.prototype._onAnchorUpdate = function _onAnchorUpdate ()
  23779. {
  23780. this._transformID = -1;
  23781. this._transformTrimmedID = -1;
  23782. };
  23783. /**
  23784. * calculates worldTransform * vertices, store it in vertexData
  23785. */
  23786. Sprite.prototype.calculateVertices = function calculateVertices ()
  23787. {
  23788. var texture = this._texture;
  23789. if (this._transformID === this.transform._worldID && this._textureID === texture._updateID)
  23790. {
  23791. return;
  23792. }
  23793. this._transformID = this.transform._worldID;
  23794. this._textureID = texture._updateID;
  23795. // set the vertex data
  23796. var wt = this.transform.worldTransform;
  23797. var a = wt.a;
  23798. var b = wt.b;
  23799. var c = wt.c;
  23800. var d = wt.d;
  23801. var tx = wt.tx;
  23802. var ty = wt.ty;
  23803. var vertexData = this.vertexData;
  23804. var trim = texture.trim;
  23805. var orig = texture.orig;
  23806. var anchor = this._anchor;
  23807. var w0 = 0;
  23808. var w1 = 0;
  23809. var h0 = 0;
  23810. var h1 = 0;
  23811. if (trim)
  23812. {
  23813. // if the sprite is trimmed and is not a tilingsprite then we need to add the extra
  23814. // space before transforming the sprite coords.
  23815. w1 = trim.x - (anchor._x * orig.width);
  23816. w0 = w1 + trim.width;
  23817. h1 = trim.y - (anchor._y * orig.height);
  23818. h0 = h1 + trim.height;
  23819. }
  23820. else
  23821. {
  23822. w1 = -anchor._x * orig.width;
  23823. w0 = w1 + orig.width;
  23824. h1 = -anchor._y * orig.height;
  23825. h0 = h1 + orig.height;
  23826. }
  23827. // xy
  23828. vertexData[0] = (a * w1) + (c * h1) + tx;
  23829. vertexData[1] = (d * h1) + (b * w1) + ty;
  23830. // xy
  23831. vertexData[2] = (a * w0) + (c * h1) + tx;
  23832. vertexData[3] = (d * h1) + (b * w0) + ty;
  23833. // xy
  23834. vertexData[4] = (a * w0) + (c * h0) + tx;
  23835. vertexData[5] = (d * h0) + (b * w0) + ty;
  23836. // xy
  23837. vertexData[6] = (a * w1) + (c * h0) + tx;
  23838. vertexData[7] = (d * h0) + (b * w1) + ty;
  23839. if (this._roundPixels)
  23840. {
  23841. for (var i = 0; i < 8; i++)
  23842. {
  23843. vertexData[i] = Math.round(vertexData[i]);
  23844. }
  23845. }
  23846. };
  23847. /**
  23848. * calculates worldTransform * vertices for a non texture with a trim. store it in vertexTrimmedData
  23849. * This is used to ensure that the true width and height of a trimmed texture is respected
  23850. */
  23851. Sprite.prototype.calculateTrimmedVertices = function calculateTrimmedVertices ()
  23852. {
  23853. if (!this.vertexTrimmedData)
  23854. {
  23855. this.vertexTrimmedData = new Float32Array(8);
  23856. }
  23857. else if (this._transformTrimmedID === this.transform._worldID && this._textureTrimmedID === this._texture._updateID)
  23858. {
  23859. return;
  23860. }
  23861. this._transformTrimmedID = this.transform._worldID;
  23862. this._textureTrimmedID = this._texture._updateID;
  23863. // lets do some special trim code!
  23864. var texture = this._texture;
  23865. var vertexData = this.vertexTrimmedData;
  23866. var orig = texture.orig;
  23867. var anchor = this._anchor;
  23868. // lets calculate the new untrimmed bounds..
  23869. var wt = this.transform.worldTransform;
  23870. var a = wt.a;
  23871. var b = wt.b;
  23872. var c = wt.c;
  23873. var d = wt.d;
  23874. var tx = wt.tx;
  23875. var ty = wt.ty;
  23876. var w1 = -anchor._x * orig.width;
  23877. var w0 = w1 + orig.width;
  23878. var h1 = -anchor._y * orig.height;
  23879. var h0 = h1 + orig.height;
  23880. // xy
  23881. vertexData[0] = (a * w1) + (c * h1) + tx;
  23882. vertexData[1] = (d * h1) + (b * w1) + ty;
  23883. // xy
  23884. vertexData[2] = (a * w0) + (c * h1) + tx;
  23885. vertexData[3] = (d * h1) + (b * w0) + ty;
  23886. // xy
  23887. vertexData[4] = (a * w0) + (c * h0) + tx;
  23888. vertexData[5] = (d * h0) + (b * w0) + ty;
  23889. // xy
  23890. vertexData[6] = (a * w1) + (c * h0) + tx;
  23891. vertexData[7] = (d * h0) + (b * w1) + ty;
  23892. };
  23893. /**
  23894. *
  23895. * Renders the object using the WebGL renderer
  23896. *
  23897. * @protected
  23898. * @param {PIXI.Renderer} renderer - The webgl renderer to use.
  23899. */
  23900. Sprite.prototype._render = function _render (renderer)
  23901. {
  23902. this.calculateVertices();
  23903. renderer.batch.setObjectRenderer(renderer.plugins[this.pluginName]);
  23904. renderer.plugins[this.pluginName].render(this);
  23905. };
  23906. /**
  23907. * Updates the bounds of the sprite.
  23908. *
  23909. * @protected
  23910. */
  23911. Sprite.prototype._calculateBounds = function _calculateBounds ()
  23912. {
  23913. var trim = this._texture.trim;
  23914. var orig = this._texture.orig;
  23915. // First lets check to see if the current texture has a trim..
  23916. if (!trim || (trim.width === orig.width && trim.height === orig.height))
  23917. {
  23918. // no trim! lets use the usual calculations..
  23919. this.calculateVertices();
  23920. this._bounds.addQuad(this.vertexData);
  23921. }
  23922. else
  23923. {
  23924. // lets calculate a special trimmed bounds...
  23925. this.calculateTrimmedVertices();
  23926. this._bounds.addQuad(this.vertexTrimmedData);
  23927. }
  23928. };
  23929. /**
  23930. * Gets the local bounds of the sprite object.
  23931. *
  23932. * @param {PIXI.Rectangle} [rect] - The output rectangle.
  23933. * @return {PIXI.Rectangle} The bounds.
  23934. */
  23935. Sprite.prototype.getLocalBounds = function getLocalBounds (rect)
  23936. {
  23937. // we can do a fast local bounds if the sprite has no children!
  23938. if (this.children.length === 0)
  23939. {
  23940. this._bounds.minX = this._texture.orig.width * -this._anchor._x;
  23941. this._bounds.minY = this._texture.orig.height * -this._anchor._y;
  23942. this._bounds.maxX = this._texture.orig.width * (1 - this._anchor._x);
  23943. this._bounds.maxY = this._texture.orig.height * (1 - this._anchor._y);
  23944. if (!rect)
  23945. {
  23946. if (!this._localBoundsRect)
  23947. {
  23948. this._localBoundsRect = new Rectangle();
  23949. }
  23950. rect = this._localBoundsRect;
  23951. }
  23952. return this._bounds.getRectangle(rect);
  23953. }
  23954. return Container.prototype.getLocalBounds.call(this, rect);
  23955. };
  23956. /**
  23957. * Tests if a point is inside this sprite
  23958. *
  23959. * @param {PIXI.Point} point - the point to test
  23960. * @return {boolean} the result of the test
  23961. */
  23962. Sprite.prototype.containsPoint = function containsPoint (point)
  23963. {
  23964. this.worldTransform.applyInverse(point, tempPoint);
  23965. var width = this._texture.orig.width;
  23966. var height = this._texture.orig.height;
  23967. var x1 = -width * this.anchor.x;
  23968. var y1 = 0;
  23969. if (tempPoint.x >= x1 && tempPoint.x < x1 + width)
  23970. {
  23971. y1 = -height * this.anchor.y;
  23972. if (tempPoint.y >= y1 && tempPoint.y < y1 + height)
  23973. {
  23974. return true;
  23975. }
  23976. }
  23977. return false;
  23978. };
  23979. /**
  23980. * Destroys this sprite and optionally its texture and children
  23981. *
  23982. * @param {object|boolean} [options] - Options parameter. A boolean will act as if all options
  23983. * have been set to that value
  23984. * @param {boolean} [options.children=false] - if set to true, all the children will have their destroy
  23985. * method called as well. 'options' will be passed on to those calls.
  23986. * @param {boolean} [options.texture=false] - Should it destroy the current texture of the sprite as well
  23987. * @param {boolean} [options.baseTexture=false] - Should it destroy the base texture of the sprite as well
  23988. */
  23989. Sprite.prototype.destroy = function destroy (options)
  23990. {
  23991. Container.prototype.destroy.call(this, options);
  23992. this._texture.off('update', this._onTextureUpdate, this);
  23993. this._anchor = null;
  23994. var destroyTexture = typeof options === 'boolean' ? options : options && options.texture;
  23995. if (destroyTexture)
  23996. {
  23997. var destroyBaseTexture = typeof options === 'boolean' ? options : options && options.baseTexture;
  23998. this._texture.destroy(!!destroyBaseTexture);
  23999. }
  24000. this._texture = null;
  24001. this.shader = null;
  24002. };
  24003. // some helper functions..
  24004. /**
  24005. * Helper function that creates a new sprite based on the source you provide.
  24006. * The source can be - frame id, image url, video url, canvas element, video element, base texture
  24007. *
  24008. * @static
  24009. * @param {number|string|PIXI.Texture|HTMLCanvasElement|HTMLVideoElement} source Source to create texture from
  24010. * @param {object} [options] See {@link PIXI.BaseTexture}'s constructor for options.
  24011. * @return {PIXI.Sprite} The newly created sprite
  24012. */
  24013. Sprite.from = function from (source, options)
  24014. {
  24015. var texture = (source instanceof Texture)
  24016. ? source
  24017. : Texture.from(source, options);
  24018. return new Sprite(texture);
  24019. };
  24020. /**
  24021. * If true PixiJS will Math.floor() x/y values when rendering, stopping pixel interpolation.
  24022. * Advantages can include sharper image quality (like text) and faster rendering on canvas.
  24023. * The main disadvantage is movement of objects may appear less smooth.
  24024. * To set the global default, change {@link PIXI.settings.ROUND_PIXELS}
  24025. *
  24026. * @member {boolean}
  24027. * @default false
  24028. */
  24029. prototypeAccessors.roundPixels.set = function (value)
  24030. {
  24031. if (this._roundPixels !== value)
  24032. {
  24033. this._transformID = -1;
  24034. }
  24035. this._roundPixels = value;
  24036. };
  24037. prototypeAccessors.roundPixels.get = function ()
  24038. {
  24039. return this._roundPixels;
  24040. };
  24041. /**
  24042. * The width of the sprite, setting this will actually modify the scale to achieve the value set
  24043. *
  24044. * @member {number}
  24045. */
  24046. prototypeAccessors.width.get = function ()
  24047. {
  24048. return Math.abs(this.scale.x) * this._texture.orig.width;
  24049. };
  24050. prototypeAccessors.width.set = function (value) // eslint-disable-line require-jsdoc
  24051. {
  24052. var s = sign(this.scale.x) || 1;
  24053. this.scale.x = s * value / this._texture.orig.width;
  24054. this._width = value;
  24055. };
  24056. /**
  24057. * The height of the sprite, setting this will actually modify the scale to achieve the value set
  24058. *
  24059. * @member {number}
  24060. */
  24061. prototypeAccessors.height.get = function ()
  24062. {
  24063. return Math.abs(this.scale.y) * this._texture.orig.height;
  24064. };
  24065. prototypeAccessors.height.set = function (value) // eslint-disable-line require-jsdoc
  24066. {
  24067. var s = sign(this.scale.y) || 1;
  24068. this.scale.y = s * value / this._texture.orig.height;
  24069. this._height = value;
  24070. };
  24071. /**
  24072. * The anchor sets the origin point of the text. The default value is taken from the {@link PIXI.Texture|Texture}
  24073. * and passed to the constructor.
  24074. *
  24075. * The default is `(0,0)`, this means the text's origin is the top left.
  24076. *
  24077. * Setting the anchor to `(0.5,0.5)` means the text's origin is centered.
  24078. *
  24079. * Setting the anchor to `(1,1)` would mean the text's origin point will be the bottom right corner.
  24080. *
  24081. * If you pass only single parameter, it will set both x and y to the same value as shown in the example below.
  24082. *
  24083. * @example
  24084. * const sprite = new PIXI.Sprite(texture);
  24085. * sprite.anchor.set(0.5); // This will set the origin to center. (0.5) is same as (0.5, 0.5).
  24086. *
  24087. * @member {PIXI.ObservablePoint}
  24088. */
  24089. prototypeAccessors.anchor.get = function ()
  24090. {
  24091. return this._anchor;
  24092. };
  24093. prototypeAccessors.anchor.set = function (value) // eslint-disable-line require-jsdoc
  24094. {
  24095. this._anchor.copyFrom(value);
  24096. };
  24097. /**
  24098. * The tint applied to the sprite. This is a hex value.
  24099. * A value of 0xFFFFFF will remove any tint effect.
  24100. *
  24101. * @member {number}
  24102. * @default 0xFFFFFF
  24103. */
  24104. prototypeAccessors.tint.get = function ()
  24105. {
  24106. return this._tint;
  24107. };
  24108. prototypeAccessors.tint.set = function (value) // eslint-disable-line require-jsdoc
  24109. {
  24110. this._tint = value;
  24111. this._tintRGB = (value >> 16) + (value & 0xff00) + ((value & 0xff) << 16);
  24112. };
  24113. /**
  24114. * The texture that the sprite is using
  24115. *
  24116. * @member {PIXI.Texture}
  24117. */
  24118. prototypeAccessors.texture.get = function ()
  24119. {
  24120. return this._texture;
  24121. };
  24122. prototypeAccessors.texture.set = function (value) // eslint-disable-line require-jsdoc
  24123. {
  24124. if (this._texture === value)
  24125. {
  24126. return;
  24127. }
  24128. this._texture = value || Texture.EMPTY;
  24129. this._cachedTint = 0xFFFFFF;
  24130. this._textureID = -1;
  24131. this._textureTrimmedID = -1;
  24132. if (value)
  24133. {
  24134. // wait for the texture to load
  24135. if (value.baseTexture.valid)
  24136. {
  24137. this._onTextureUpdate();
  24138. }
  24139. else
  24140. {
  24141. value.once('update', this._onTextureUpdate, this);
  24142. }
  24143. }
  24144. };
  24145. Object.defineProperties( Sprite.prototype, prototypeAccessors );
  24146. return Sprite;
  24147. }(Container));
  24148. /*!
  24149. * @pixi/text - v5.0.4
  24150. * Compiled Fri, 07 Jun 2019 17:17:49 UTC
  24151. *
  24152. * @pixi/text is licensed under the MIT License.
  24153. * http://www.opensource.org/licenses/mit-license
  24154. */
  24155. /**
  24156. * Constants that define the type of gradient on text.
  24157. *
  24158. * @static
  24159. * @constant
  24160. * @name TEXT_GRADIENT
  24161. * @memberof PIXI
  24162. * @type {object}
  24163. * @property {number} LINEAR_VERTICAL Vertical gradient
  24164. * @property {number} LINEAR_HORIZONTAL Linear gradient
  24165. */
  24166. var TEXT_GRADIENT = {
  24167. LINEAR_VERTICAL: 0,
  24168. LINEAR_HORIZONTAL: 1,
  24169. };
  24170. // disabling eslint for now, going to rewrite this in v5
  24171. var defaultStyle = {
  24172. align: 'left',
  24173. breakWords: false,
  24174. dropShadow: false,
  24175. dropShadowAlpha: 1,
  24176. dropShadowAngle: Math.PI / 6,
  24177. dropShadowBlur: 0,
  24178. dropShadowColor: 'black',
  24179. dropShadowDistance: 5,
  24180. fill: 'black',
  24181. fillGradientType: TEXT_GRADIENT.LINEAR_VERTICAL,
  24182. fillGradientStops: [],
  24183. fontFamily: 'Arial',
  24184. fontSize: 26,
  24185. fontStyle: 'normal',
  24186. fontVariant: 'normal',
  24187. fontWeight: 'normal',
  24188. letterSpacing: 0,
  24189. lineHeight: 0,
  24190. lineJoin: 'miter',
  24191. miterLimit: 10,
  24192. padding: 0,
  24193. stroke: 'black',
  24194. strokeThickness: 0,
  24195. textBaseline: 'alphabetic',
  24196. trim: false,
  24197. whiteSpace: 'pre',
  24198. wordWrap: false,
  24199. wordWrapWidth: 100,
  24200. leading: 0,
  24201. };
  24202. var genericFontFamilies = [
  24203. 'serif',
  24204. 'sans-serif',
  24205. 'monospace',
  24206. 'cursive',
  24207. 'fantasy',
  24208. 'system-ui' ];
  24209. /**
  24210. * A TextStyle Object contains information to decorate a Text objects.
  24211. *
  24212. * An instance can be shared between multiple Text objects; then changing the style will update all text objects using it.
  24213. *
  24214. * A tool can be used to generate a text style [here](https://pixijs.io/pixi-text-style).
  24215. *
  24216. * @class
  24217. * @memberof PIXI
  24218. */
  24219. var TextStyle = function TextStyle(style)
  24220. {
  24221. this.styleID = 0;
  24222. this.reset();
  24223. deepCopyProperties(this, style, style);
  24224. };
  24225. var prototypeAccessors$7 = { align: { configurable: true },breakWords: { configurable: true },dropShadow: { configurable: true },dropShadowAlpha: { configurable: true },dropShadowAngle: { configurable: true },dropShadowBlur: { configurable: true },dropShadowColor: { configurable: true },dropShadowDistance: { configurable: true },fill: { configurable: true },fillGradientType: { configurable: true },fillGradientStops: { configurable: true },fontFamily: { configurable: true },fontSize: { configurable: true },fontStyle: { configurable: true },fontVariant: { configurable: true },fontWeight: { configurable: true },letterSpacing: { configurable: true },lineHeight: { configurable: true },leading: { configurable: true },lineJoin: { configurable: true },miterLimit: { configurable: true },padding: { configurable: true },stroke: { configurable: true },strokeThickness: { configurable: true },textBaseline: { configurable: true },trim: { configurable: true },whiteSpace: { configurable: true },wordWrap: { configurable: true },wordWrapWidth: { configurable: true } };
  24226. /**
  24227. * Creates a new TextStyle object with the same values as this one.
  24228. * Note that the only the properties of the object are cloned.
  24229. *
  24230. * @return {PIXI.TextStyle} New cloned TextStyle object
  24231. */
  24232. TextStyle.prototype.clone = function clone ()
  24233. {
  24234. var clonedProperties = {};
  24235. deepCopyProperties(clonedProperties, this, defaultStyle);
  24236. return new TextStyle(clonedProperties);
  24237. };
  24238. /**
  24239. * Resets all properties to the defaults specified in TextStyle.prototype._default
  24240. */
  24241. TextStyle.prototype.reset = function reset ()
  24242. {
  24243. deepCopyProperties(this, defaultStyle, defaultStyle);
  24244. };
  24245. /**
  24246. * Alignment for multiline text ('left', 'center' or 'right'), does not affect single line text
  24247. *
  24248. * @member {string}
  24249. */
  24250. prototypeAccessors$7.align.get = function ()
  24251. {
  24252. return this._align;
  24253. };
  24254. prototypeAccessors$7.align.set = function (align) // eslint-disable-line require-jsdoc
  24255. {
  24256. if (this._align !== align)
  24257. {
  24258. this._align = align;
  24259. this.styleID++;
  24260. }
  24261. };
  24262. /**
  24263. * Indicates if lines can be wrapped within words, it needs wordWrap to be set to true
  24264. *
  24265. * @member {boolean}
  24266. */
  24267. prototypeAccessors$7.breakWords.get = function ()
  24268. {
  24269. return this._breakWords;
  24270. };
  24271. prototypeAccessors$7.breakWords.set = function (breakWords) // eslint-disable-line require-jsdoc
  24272. {
  24273. if (this._breakWords !== breakWords)
  24274. {
  24275. this._breakWords = breakWords;
  24276. this.styleID++;
  24277. }
  24278. };
  24279. /**
  24280. * Set a drop shadow for the text
  24281. *
  24282. * @member {boolean}
  24283. */
  24284. prototypeAccessors$7.dropShadow.get = function ()
  24285. {
  24286. return this._dropShadow;
  24287. };
  24288. prototypeAccessors$7.dropShadow.set = function (dropShadow) // eslint-disable-line require-jsdoc
  24289. {
  24290. if (this._dropShadow !== dropShadow)
  24291. {
  24292. this._dropShadow = dropShadow;
  24293. this.styleID++;
  24294. }
  24295. };
  24296. /**
  24297. * Set alpha for the drop shadow
  24298. *
  24299. * @member {number}
  24300. */
  24301. prototypeAccessors$7.dropShadowAlpha.get = function ()
  24302. {
  24303. return this._dropShadowAlpha;
  24304. };
  24305. prototypeAccessors$7.dropShadowAlpha.set = function (dropShadowAlpha) // eslint-disable-line require-jsdoc
  24306. {
  24307. if (this._dropShadowAlpha !== dropShadowAlpha)
  24308. {
  24309. this._dropShadowAlpha = dropShadowAlpha;
  24310. this.styleID++;
  24311. }
  24312. };
  24313. /**
  24314. * Set a angle of the drop shadow
  24315. *
  24316. * @member {number}
  24317. */
  24318. prototypeAccessors$7.dropShadowAngle.get = function ()
  24319. {
  24320. return this._dropShadowAngle;
  24321. };
  24322. prototypeAccessors$7.dropShadowAngle.set = function (dropShadowAngle) // eslint-disable-line require-jsdoc
  24323. {
  24324. if (this._dropShadowAngle !== dropShadowAngle)
  24325. {
  24326. this._dropShadowAngle = dropShadowAngle;
  24327. this.styleID++;
  24328. }
  24329. };
  24330. /**
  24331. * Set a shadow blur radius
  24332. *
  24333. * @member {number}
  24334. */
  24335. prototypeAccessors$7.dropShadowBlur.get = function ()
  24336. {
  24337. return this._dropShadowBlur;
  24338. };
  24339. prototypeAccessors$7.dropShadowBlur.set = function (dropShadowBlur) // eslint-disable-line require-jsdoc
  24340. {
  24341. if (this._dropShadowBlur !== dropShadowBlur)
  24342. {
  24343. this._dropShadowBlur = dropShadowBlur;
  24344. this.styleID++;
  24345. }
  24346. };
  24347. /**
  24348. * A fill style to be used on the dropshadow e.g 'red', '#00FF00'
  24349. *
  24350. * @member {string|number}
  24351. */
  24352. prototypeAccessors$7.dropShadowColor.get = function ()
  24353. {
  24354. return this._dropShadowColor;
  24355. };
  24356. prototypeAccessors$7.dropShadowColor.set = function (dropShadowColor) // eslint-disable-line require-jsdoc
  24357. {
  24358. var outputColor = getColor(dropShadowColor);
  24359. if (this._dropShadowColor !== outputColor)
  24360. {
  24361. this._dropShadowColor = outputColor;
  24362. this.styleID++;
  24363. }
  24364. };
  24365. /**
  24366. * Set a distance of the drop shadow
  24367. *
  24368. * @member {number}
  24369. */
  24370. prototypeAccessors$7.dropShadowDistance.get = function ()
  24371. {
  24372. return this._dropShadowDistance;
  24373. };
  24374. prototypeAccessors$7.dropShadowDistance.set = function (dropShadowDistance) // eslint-disable-line require-jsdoc
  24375. {
  24376. if (this._dropShadowDistance !== dropShadowDistance)
  24377. {
  24378. this._dropShadowDistance = dropShadowDistance;
  24379. this.styleID++;
  24380. }
  24381. };
  24382. /**
  24383. * A canvas fillstyle that will be used on the text e.g 'red', '#00FF00'.
  24384. * Can be an array to create a gradient eg ['#000000','#FFFFFF']
  24385. * {@link https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/fillStyle|MDN}
  24386. *
  24387. * @member {string|string[]|number|number[]|CanvasGradient|CanvasPattern}
  24388. */
  24389. prototypeAccessors$7.fill.get = function ()
  24390. {
  24391. return this._fill;
  24392. };
  24393. prototypeAccessors$7.fill.set = function (fill) // eslint-disable-line require-jsdoc
  24394. {
  24395. var outputColor = getColor(fill);
  24396. if (this._fill !== outputColor)
  24397. {
  24398. this._fill = outputColor;
  24399. this.styleID++;
  24400. }
  24401. };
  24402. /**
  24403. * If fill is an array of colours to create a gradient, this can change the type/direction of the gradient.
  24404. * See {@link PIXI.TEXT_GRADIENT}
  24405. *
  24406. * @member {number}
  24407. */
  24408. prototypeAccessors$7.fillGradientType.get = function ()
  24409. {
  24410. return this._fillGradientType;
  24411. };
  24412. prototypeAccessors$7.fillGradientType.set = function (fillGradientType) // eslint-disable-line require-jsdoc
  24413. {
  24414. if (this._fillGradientType !== fillGradientType)
  24415. {
  24416. this._fillGradientType = fillGradientType;
  24417. this.styleID++;
  24418. }
  24419. };
  24420. /**
  24421. * If fill is an array of colours to create a gradient, this array can set the stop points
  24422. * (numbers between 0 and 1) for the color, overriding the default behaviour of evenly spacing them.
  24423. *
  24424. * @member {number[]}
  24425. */
  24426. prototypeAccessors$7.fillGradientStops.get = function ()
  24427. {
  24428. return this._fillGradientStops;
  24429. };
  24430. prototypeAccessors$7.fillGradientStops.set = function (fillGradientStops) // eslint-disable-line require-jsdoc
  24431. {
  24432. if (!areArraysEqual(this._fillGradientStops,fillGradientStops))
  24433. {
  24434. this._fillGradientStops = fillGradientStops;
  24435. this.styleID++;
  24436. }
  24437. };
  24438. /**
  24439. * The font family
  24440. *
  24441. * @member {string|string[]}
  24442. */
  24443. prototypeAccessors$7.fontFamily.get = function ()
  24444. {
  24445. return this._fontFamily;
  24446. };
  24447. prototypeAccessors$7.fontFamily.set = function (fontFamily) // eslint-disable-line require-jsdoc
  24448. {
  24449. if (this.fontFamily !== fontFamily)
  24450. {
  24451. this._fontFamily = fontFamily;
  24452. this.styleID++;
  24453. }
  24454. };
  24455. /**
  24456. * The font size
  24457. * (as a number it converts to px, but as a string, equivalents are '26px','20pt','160%' or '1.6em')
  24458. *
  24459. * @member {number|string}
  24460. */
  24461. prototypeAccessors$7.fontSize.get = function ()
  24462. {
  24463. return this._fontSize;
  24464. };
  24465. prototypeAccessors$7.fontSize.set = function (fontSize) // eslint-disable-line require-jsdoc
  24466. {
  24467. if (this._fontSize !== fontSize)
  24468. {
  24469. this._fontSize = fontSize;
  24470. this.styleID++;
  24471. }
  24472. };
  24473. /**
  24474. * The font style
  24475. * ('normal', 'italic' or 'oblique')
  24476. *
  24477. * @member {string}
  24478. */
  24479. prototypeAccessors$7.fontStyle.get = function ()
  24480. {
  24481. return this._fontStyle;
  24482. };
  24483. prototypeAccessors$7.fontStyle.set = function (fontStyle) // eslint-disable-line require-jsdoc
  24484. {
  24485. if (this._fontStyle !== fontStyle)
  24486. {
  24487. this._fontStyle = fontStyle;
  24488. this.styleID++;
  24489. }
  24490. };
  24491. /**
  24492. * The font variant
  24493. * ('normal' or 'small-caps')
  24494. *
  24495. * @member {string}
  24496. */
  24497. prototypeAccessors$7.fontVariant.get = function ()
  24498. {
  24499. return this._fontVariant;
  24500. };
  24501. prototypeAccessors$7.fontVariant.set = function (fontVariant) // eslint-disable-line require-jsdoc
  24502. {
  24503. if (this._fontVariant !== fontVariant)
  24504. {
  24505. this._fontVariant = fontVariant;
  24506. this.styleID++;
  24507. }
  24508. };
  24509. /**
  24510. * The font weight
  24511. * ('normal', 'bold', 'bolder', 'lighter' and '100', '200', '300', '400', '500', '600', '700', 800' or '900')
  24512. *
  24513. * @member {string}
  24514. */
  24515. prototypeAccessors$7.fontWeight.get = function ()
  24516. {
  24517. return this._fontWeight;
  24518. };
  24519. prototypeAccessors$7.fontWeight.set = function (fontWeight) // eslint-disable-line require-jsdoc
  24520. {
  24521. if (this._fontWeight !== fontWeight)
  24522. {
  24523. this._fontWeight = fontWeight;
  24524. this.styleID++;
  24525. }
  24526. };
  24527. /**
  24528. * The amount of spacing between letters, default is 0
  24529. *
  24530. * @member {number}
  24531. */
  24532. prototypeAccessors$7.letterSpacing.get = function ()
  24533. {
  24534. return this._letterSpacing;
  24535. };
  24536. prototypeAccessors$7.letterSpacing.set = function (letterSpacing) // eslint-disable-line require-jsdoc
  24537. {
  24538. if (this._letterSpacing !== letterSpacing)
  24539. {
  24540. this._letterSpacing = letterSpacing;
  24541. this.styleID++;
  24542. }
  24543. };
  24544. /**
  24545. * The line height, a number that represents the vertical space that a letter uses
  24546. *
  24547. * @member {number}
  24548. */
  24549. prototypeAccessors$7.lineHeight.get = function ()
  24550. {
  24551. return this._lineHeight;
  24552. };
  24553. prototypeAccessors$7.lineHeight.set = function (lineHeight) // eslint-disable-line require-jsdoc
  24554. {
  24555. if (this._lineHeight !== lineHeight)
  24556. {
  24557. this._lineHeight = lineHeight;
  24558. this.styleID++;
  24559. }
  24560. };
  24561. /**
  24562. * The space between lines
  24563. *
  24564. * @member {number}
  24565. */
  24566. prototypeAccessors$7.leading.get = function ()
  24567. {
  24568. return this._leading;
  24569. };
  24570. prototypeAccessors$7.leading.set = function (leading) // eslint-disable-line require-jsdoc
  24571. {
  24572. if (this._leading !== leading)
  24573. {
  24574. this._leading = leading;
  24575. this.styleID++;
  24576. }
  24577. };
  24578. /**
  24579. * The lineJoin property sets the type of corner created, it can resolve spiked text issues.
  24580. * Default is 'miter' (creates a sharp corner).
  24581. *
  24582. * @member {string}
  24583. */
  24584. prototypeAccessors$7.lineJoin.get = function ()
  24585. {
  24586. return this._lineJoin;
  24587. };
  24588. prototypeAccessors$7.lineJoin.set = function (lineJoin) // eslint-disable-line require-jsdoc
  24589. {
  24590. if (this._lineJoin !== lineJoin)
  24591. {
  24592. this._lineJoin = lineJoin;
  24593. this.styleID++;
  24594. }
  24595. };
  24596. /**
  24597. * The miter limit to use when using the 'miter' lineJoin mode
  24598. * This can reduce or increase the spikiness of rendered text.
  24599. *
  24600. * @member {number}
  24601. */
  24602. prototypeAccessors$7.miterLimit.get = function ()
  24603. {
  24604. return this._miterLimit;
  24605. };
  24606. prototypeAccessors$7.miterLimit.set = function (miterLimit) // eslint-disable-line require-jsdoc
  24607. {
  24608. if (this._miterLimit !== miterLimit)
  24609. {
  24610. this._miterLimit = miterLimit;
  24611. this.styleID++;
  24612. }
  24613. };
  24614. /**
  24615. * Occasionally some fonts are cropped. Adding some padding will prevent this from happening
  24616. * by adding padding to all sides of the text.
  24617. *
  24618. * @member {number}
  24619. */
  24620. prototypeAccessors$7.padding.get = function ()
  24621. {
  24622. return this._padding;
  24623. };
  24624. prototypeAccessors$7.padding.set = function (padding) // eslint-disable-line require-jsdoc
  24625. {
  24626. if (this._padding !== padding)
  24627. {
  24628. this._padding = padding;
  24629. this.styleID++;
  24630. }
  24631. };
  24632. /**
  24633. * A canvas fillstyle that will be used on the text stroke
  24634. * e.g 'blue', '#FCFF00'
  24635. *
  24636. * @member {string|number}
  24637. */
  24638. prototypeAccessors$7.stroke.get = function ()
  24639. {
  24640. return this._stroke;
  24641. };
  24642. prototypeAccessors$7.stroke.set = function (stroke) // eslint-disable-line require-jsdoc
  24643. {
  24644. var outputColor = getColor(stroke);
  24645. if (this._stroke !== outputColor)
  24646. {
  24647. this._stroke = outputColor;
  24648. this.styleID++;
  24649. }
  24650. };
  24651. /**
  24652. * A number that represents the thickness of the stroke.
  24653. * Default is 0 (no stroke)
  24654. *
  24655. * @member {number}
  24656. */
  24657. prototypeAccessors$7.strokeThickness.get = function ()
  24658. {
  24659. return this._strokeThickness;
  24660. };
  24661. prototypeAccessors$7.strokeThickness.set = function (strokeThickness) // eslint-disable-line require-jsdoc
  24662. {
  24663. if (this._strokeThickness !== strokeThickness)
  24664. {
  24665. this._strokeThickness = strokeThickness;
  24666. this.styleID++;
  24667. }
  24668. };
  24669. /**
  24670. * The baseline of the text that is rendered.
  24671. *
  24672. * @member {string}
  24673. */
  24674. prototypeAccessors$7.textBaseline.get = function ()
  24675. {
  24676. return this._textBaseline;
  24677. };
  24678. prototypeAccessors$7.textBaseline.set = function (textBaseline) // eslint-disable-line require-jsdoc
  24679. {
  24680. if (this._textBaseline !== textBaseline)
  24681. {
  24682. this._textBaseline = textBaseline;
  24683. this.styleID++;
  24684. }
  24685. };
  24686. /**
  24687. * Trim transparent borders
  24688. *
  24689. * @member {boolean}
  24690. */
  24691. prototypeAccessors$7.trim.get = function ()
  24692. {
  24693. return this._trim;
  24694. };
  24695. prototypeAccessors$7.trim.set = function (trim) // eslint-disable-line require-jsdoc
  24696. {
  24697. if (this._trim !== trim)
  24698. {
  24699. this._trim = trim;
  24700. this.styleID++;
  24701. }
  24702. };
  24703. /**
  24704. * How newlines and spaces should be handled.
  24705. * Default is 'pre' (preserve, preserve).
  24706. *
  24707. * value | New lines | Spaces
  24708. * --- | --- | ---
  24709. * 'normal' | Collapse | Collapse
  24710. * 'pre' | Preserve | Preserve
  24711. * 'pre-line' | Preserve | Collapse
  24712. *
  24713. * @member {string}
  24714. */
  24715. prototypeAccessors$7.whiteSpace.get = function ()
  24716. {
  24717. return this._whiteSpace;
  24718. };
  24719. prototypeAccessors$7.whiteSpace.set = function (whiteSpace) // eslint-disable-line require-jsdoc
  24720. {
  24721. if (this._whiteSpace !== whiteSpace)
  24722. {
  24723. this._whiteSpace = whiteSpace;
  24724. this.styleID++;
  24725. }
  24726. };
  24727. /**
  24728. * Indicates if word wrap should be used
  24729. *
  24730. * @member {boolean}
  24731. */
  24732. prototypeAccessors$7.wordWrap.get = function ()
  24733. {
  24734. return this._wordWrap;
  24735. };
  24736. prototypeAccessors$7.wordWrap.set = function (wordWrap) // eslint-disable-line require-jsdoc
  24737. {
  24738. if (this._wordWrap !== wordWrap)
  24739. {
  24740. this._wordWrap = wordWrap;
  24741. this.styleID++;
  24742. }
  24743. };
  24744. /**
  24745. * The width at which text will wrap, it needs wordWrap to be set to true
  24746. *
  24747. * @member {number}
  24748. */
  24749. prototypeAccessors$7.wordWrapWidth.get = function ()
  24750. {
  24751. return this._wordWrapWidth;
  24752. };
  24753. prototypeAccessors$7.wordWrapWidth.set = function (wordWrapWidth) // eslint-disable-line require-jsdoc
  24754. {
  24755. if (this._wordWrapWidth !== wordWrapWidth)
  24756. {
  24757. this._wordWrapWidth = wordWrapWidth;
  24758. this.styleID++;
  24759. }
  24760. };
  24761. /**
  24762. * Generates a font style string to use for `TextMetrics.measureFont()`.
  24763. *
  24764. * @return {string} Font style string, for passing to `TextMetrics.measureFont()`
  24765. */
  24766. TextStyle.prototype.toFontString = function toFontString ()
  24767. {
  24768. // build canvas api font setting from individual components. Convert a numeric this.fontSize to px
  24769. var fontSizeString = (typeof this.fontSize === 'number') ? ((this.fontSize) + "px") : this.fontSize;
  24770. // Clean-up fontFamily property by quoting each font name
  24771. // this will support font names with spaces
  24772. var fontFamilies = this.fontFamily;
  24773. if (!Array.isArray(this.fontFamily))
  24774. {
  24775. fontFamilies = this.fontFamily.split(',');
  24776. }
  24777. for (var i = fontFamilies.length - 1; i >= 0; i--)
  24778. {
  24779. // Trim any extra white-space
  24780. var fontFamily = fontFamilies[i].trim();
  24781. // Check if font already contains strings
  24782. if (!(/([\"\'])[^\'\"]+\1/).test(fontFamily) && genericFontFamilies.indexOf(fontFamily) < 0)
  24783. {
  24784. fontFamily = "\"" + fontFamily + "\"";
  24785. }
  24786. fontFamilies[i] = fontFamily;
  24787. }
  24788. return ((this.fontStyle) + " " + (this.fontVariant) + " " + (this.fontWeight) + " " + fontSizeString + " " + (fontFamilies.join(',')));
  24789. };
  24790. Object.defineProperties( TextStyle.prototype, prototypeAccessors$7 );
  24791. /**
  24792. * Utility function to convert hexadecimal colors to strings, and simply return the color if it's a string.
  24793. * @private
  24794. * @param {number|number[]} color
  24795. * @return {string} The color as a string.
  24796. */
  24797. function getSingleColor(color)
  24798. {
  24799. if (typeof color === 'number')
  24800. {
  24801. return hex2string(color);
  24802. }
  24803. else if ( typeof color === 'string' )
  24804. {
  24805. if ( color.indexOf('0x') === 0 )
  24806. {
  24807. color = color.replace('0x', '#');
  24808. }
  24809. }
  24810. return color;
  24811. }
  24812. /**
  24813. * Utility function to convert hexadecimal colors to strings, and simply return the color if it's a string.
  24814. * This version can also convert array of colors
  24815. * @private
  24816. * @param {number|number[]} color
  24817. * @return {string} The color as a string.
  24818. */
  24819. function getColor(color)
  24820. {
  24821. if (!Array.isArray(color))
  24822. {
  24823. return getSingleColor(color);
  24824. }
  24825. else
  24826. {
  24827. for (var i = 0; i < color.length; ++i)
  24828. {
  24829. color[i] = getSingleColor(color[i]);
  24830. }
  24831. return color;
  24832. }
  24833. }
  24834. /**
  24835. * Utility function to convert hexadecimal colors to strings, and simply return the color if it's a string.
  24836. * This version can also convert array of colors
  24837. * @private
  24838. * @param {Array} array1 First array to compare
  24839. * @param {Array} array2 Second array to compare
  24840. * @return {boolean} Do the arrays contain the same values in the same order
  24841. */
  24842. function areArraysEqual(array1, array2)
  24843. {
  24844. if (!Array.isArray(array1) || !Array.isArray(array2))
  24845. {
  24846. return false;
  24847. }
  24848. if (array1.length !== array2.length)
  24849. {
  24850. return false;
  24851. }
  24852. for (var i = 0; i < array1.length; ++i)
  24853. {
  24854. if (array1[i] !== array2[i])
  24855. {
  24856. return false;
  24857. }
  24858. }
  24859. return true;
  24860. }
  24861. /**
  24862. * Utility function to ensure that object properties are copied by value, and not by reference
  24863. * @private
  24864. * @param {Object} target Target object to copy properties into
  24865. * @param {Object} source Source object for the properties to copy
  24866. * @param {string} propertyObj Object containing properties names we want to loop over
  24867. */
  24868. function deepCopyProperties(target, source, propertyObj) {
  24869. for (var prop in propertyObj) {
  24870. if (Array.isArray(source[prop])) {
  24871. target[prop] = source[prop].slice();
  24872. } else {
  24873. target[prop] = source[prop];
  24874. }
  24875. }
  24876. }
  24877. /**
  24878. * The TextMetrics object represents the measurement of a block of text with a specified style.
  24879. *
  24880. * ```js
  24881. * let style = new PIXI.TextStyle({fontFamily : 'Arial', fontSize: 24, fill : 0xff1010, align : 'center'})
  24882. * let textMetrics = PIXI.TextMetrics.measureText('Your text', style)
  24883. * ```
  24884. *
  24885. * @class
  24886. * @memberof PIXI
  24887. */
  24888. var TextMetrics = function TextMetrics(text, style, width, height, lines, lineWidths, lineHeight, maxLineWidth, fontProperties)
  24889. {
  24890. /**
  24891. * The text that was measured
  24892. *
  24893. * @member {string}
  24894. */
  24895. this.text = text;
  24896. /**
  24897. * The style that was measured
  24898. *
  24899. * @member {PIXI.TextStyle}
  24900. */
  24901. this.style = style;
  24902. /**
  24903. * The measured width of the text
  24904. *
  24905. * @member {number}
  24906. */
  24907. this.width = width;
  24908. /**
  24909. * The measured height of the text
  24910. *
  24911. * @member {number}
  24912. */
  24913. this.height = height;
  24914. /**
  24915. * An array of lines of the text broken by new lines and wrapping is specified in style
  24916. *
  24917. * @member {string[]}
  24918. */
  24919. this.lines = lines;
  24920. /**
  24921. * An array of the line widths for each line matched to `lines`
  24922. *
  24923. * @member {number[]}
  24924. */
  24925. this.lineWidths = lineWidths;
  24926. /**
  24927. * The measured line height for this style
  24928. *
  24929. * @member {number}
  24930. */
  24931. this.lineHeight = lineHeight;
  24932. /**
  24933. * The maximum line width for all measured lines
  24934. *
  24935. * @member {number}
  24936. */
  24937. this.maxLineWidth = maxLineWidth;
  24938. /**
  24939. * The font properties object from TextMetrics.measureFont
  24940. *
  24941. * @member {PIXI.IFontMetrics}
  24942. */
  24943. this.fontProperties = fontProperties;
  24944. };
  24945. /**
  24946. * Measures the supplied string of text and returns a Rectangle.
  24947. *
  24948. * @param {string} text - the text to measure.
  24949. * @param {PIXI.TextStyle} style - the text style to use for measuring
  24950. * @param {boolean} [wordWrap] - optional override for if word-wrap should be applied to the text.
  24951. * @param {HTMLCanvasElement} [canvas] - optional specification of the canvas to use for measuring.
  24952. * @return {PIXI.TextMetrics} measured width and height of the text.
  24953. */
  24954. TextMetrics.measureText = function measureText (text, style, wordWrap, canvas)
  24955. {
  24956. if ( canvas === void 0 ) { canvas = TextMetrics._canvas; }
  24957. wordWrap = (wordWrap === undefined || wordWrap === null) ? style.wordWrap : wordWrap;
  24958. var font = style.toFontString();
  24959. var fontProperties = TextMetrics.measureFont(font);
  24960. // fallback in case UA disallow canvas data extraction
  24961. // (toDataURI, getImageData functions)
  24962. if (fontProperties.fontSize === 0)
  24963. {
  24964. fontProperties.fontSize = style.fontSize;
  24965. fontProperties.ascent = style.fontSize;
  24966. }
  24967. var context = canvas.getContext('2d');
  24968. context.font = font;
  24969. var outputText = wordWrap ? TextMetrics.wordWrap(text, style, canvas) : text;
  24970. var lines = outputText.split(/(?:\r\n|\r|\n)/);
  24971. var lineWidths = new Array(lines.length);
  24972. var maxLineWidth = 0;
  24973. for (var i = 0; i < lines.length; i++)
  24974. {
  24975. var lineWidth = context.measureText(lines[i]).width + ((lines[i].length - 1) * style.letterSpacing);
  24976. lineWidths[i] = lineWidth;
  24977. maxLineWidth = Math.max(maxLineWidth, lineWidth);
  24978. }
  24979. var width = maxLineWidth + style.strokeThickness;
  24980. if (style.dropShadow)
  24981. {
  24982. width += style.dropShadowDistance;
  24983. }
  24984. var lineHeight = style.lineHeight || fontProperties.fontSize + style.strokeThickness;
  24985. var height = Math.max(lineHeight, fontProperties.fontSize + style.strokeThickness)
  24986. + ((lines.length - 1) * (lineHeight + style.leading));
  24987. if (style.dropShadow)
  24988. {
  24989. height += style.dropShadowDistance;
  24990. }
  24991. return new TextMetrics(
  24992. text,
  24993. style,
  24994. width,
  24995. height,
  24996. lines,
  24997. lineWidths,
  24998. lineHeight + style.leading,
  24999. maxLineWidth,
  25000. fontProperties
  25001. );
  25002. };
  25003. /**
  25004. * Applies newlines to a string to have it optimally fit into the horizontal
  25005. * bounds set by the Text object's wordWrapWidth property.
  25006. *
  25007. * @private
  25008. * @param {string} text - String to apply word wrapping to
  25009. * @param {PIXI.TextStyle} style - the style to use when wrapping
  25010. * @param {HTMLCanvasElement} [canvas] - optional specification of the canvas to use for measuring.
  25011. * @return {string} New string with new lines applied where required
  25012. */
  25013. TextMetrics.wordWrap = function wordWrap (text, style, canvas)
  25014. {
  25015. if ( canvas === void 0 ) { canvas = TextMetrics._canvas; }
  25016. var context = canvas.getContext('2d');
  25017. var width = 0;
  25018. var line = '';
  25019. var lines = '';
  25020. var cache = {};
  25021. var letterSpacing = style.letterSpacing;
  25022. var whiteSpace = style.whiteSpace;
  25023. // How to handle whitespaces
  25024. var collapseSpaces = TextMetrics.collapseSpaces(whiteSpace);
  25025. var collapseNewlines = TextMetrics.collapseNewlines(whiteSpace);
  25026. // whether or not spaces may be added to the beginning of lines
  25027. var canPrependSpaces = !collapseSpaces;
  25028. // There is letterSpacing after every char except the last one
  25029. // t_h_i_s_' '_i_s_' '_a_n_' '_e_x_a_m_p_l_e_' '_!
  25030. // so for convenience the above needs to be compared to width + 1 extra letterSpace
  25031. // t_h_i_s_' '_i_s_' '_a_n_' '_e_x_a_m_p_l_e_' '_!_
  25032. // ________________________________________________
  25033. // And then the final space is simply no appended to each line
  25034. var wordWrapWidth = style.wordWrapWidth + letterSpacing;
  25035. // break text into words, spaces and newline chars
  25036. var tokens = TextMetrics.tokenize(text);
  25037. for (var i = 0; i < tokens.length; i++)
  25038. {
  25039. // get the word, space or newlineChar
  25040. var token = tokens[i];
  25041. // if word is a new line
  25042. if (TextMetrics.isNewline(token))
  25043. {
  25044. // keep the new line
  25045. if (!collapseNewlines)
  25046. {
  25047. lines += TextMetrics.addLine(line);
  25048. canPrependSpaces = !collapseSpaces;
  25049. line = '';
  25050. width = 0;
  25051. continue;
  25052. }
  25053. // if we should collapse new lines
  25054. // we simply convert it into a space
  25055. token = ' ';
  25056. }
  25057. // if we should collapse repeated whitespaces
  25058. if (collapseSpaces)
  25059. {
  25060. // check both this and the last tokens for spaces
  25061. var currIsBreakingSpace = TextMetrics.isBreakingSpace(token);
  25062. var lastIsBreakingSpace = TextMetrics.isBreakingSpace(line[line.length - 1]);
  25063. if (currIsBreakingSpace && lastIsBreakingSpace)
  25064. {
  25065. continue;
  25066. }
  25067. }
  25068. // get word width from cache if possible
  25069. var tokenWidth = TextMetrics.getFromCache(token, letterSpacing, cache, context);
  25070. // word is longer than desired bounds
  25071. if (tokenWidth > wordWrapWidth)
  25072. {
  25073. // if we are not already at the beginning of a line
  25074. if (line !== '')
  25075. {
  25076. // start newlines for overflow words
  25077. lines += TextMetrics.addLine(line);
  25078. line = '';
  25079. width = 0;
  25080. }
  25081. // break large word over multiple lines
  25082. if (TextMetrics.canBreakWords(token, style.breakWords))
  25083. {
  25084. // break word into characters
  25085. var characters = token.split('');
  25086. // loop the characters
  25087. for (var j = 0; j < characters.length; j++)
  25088. {
  25089. var char = characters[j];
  25090. var k = 1;
  25091. // we are not at the end of the token
  25092. while (characters[j + k])
  25093. {
  25094. var nextChar = characters[j + k];
  25095. var lastChar = char[char.length - 1];
  25096. // should not split chars
  25097. if (!TextMetrics.canBreakChars(lastChar, nextChar, token, j, style.breakWords))
  25098. {
  25099. // combine chars & move forward one
  25100. char += nextChar;
  25101. }
  25102. else
  25103. {
  25104. break;
  25105. }
  25106. k++;
  25107. }
  25108. j += char.length - 1;
  25109. var characterWidth = TextMetrics.getFromCache(char, letterSpacing, cache, context);
  25110. if (characterWidth + width > wordWrapWidth)
  25111. {
  25112. lines += TextMetrics.addLine(line);
  25113. canPrependSpaces = false;
  25114. line = '';
  25115. width = 0;
  25116. }
  25117. line += char;
  25118. width += characterWidth;
  25119. }
  25120. }
  25121. // run word out of the bounds
  25122. else
  25123. {
  25124. // if there are words in this line already
  25125. // finish that line and start a new one
  25126. if (line.length > 0)
  25127. {
  25128. lines += TextMetrics.addLine(line);
  25129. line = '';
  25130. width = 0;
  25131. }
  25132. var isLastToken = i === tokens.length - 1;
  25133. // give it its own line if it's not the end
  25134. lines += TextMetrics.addLine(token, !isLastToken);
  25135. canPrependSpaces = false;
  25136. line = '';
  25137. width = 0;
  25138. }
  25139. }
  25140. // word could fit
  25141. else
  25142. {
  25143. // word won't fit because of existing words
  25144. // start a new line
  25145. if (tokenWidth + width > wordWrapWidth)
  25146. {
  25147. // if its a space we don't want it
  25148. canPrependSpaces = false;
  25149. // add a new line
  25150. lines += TextMetrics.addLine(line);
  25151. // start a new line
  25152. line = '';
  25153. width = 0;
  25154. }
  25155. // don't add spaces to the beginning of lines
  25156. if (line.length > 0 || !TextMetrics.isBreakingSpace(token) || canPrependSpaces)
  25157. {
  25158. // add the word to the current line
  25159. line += token;
  25160. // update width counter
  25161. width += tokenWidth;
  25162. }
  25163. }
  25164. }
  25165. lines += TextMetrics.addLine(line, false);
  25166. return lines;
  25167. };
  25168. /**
  25169. * Convienience function for logging each line added during the wordWrap
  25170. * method
  25171. *
  25172. * @private
  25173. * @param {string} line - The line of text to add
  25174. * @param {boolean} newLine - Add new line character to end
  25175. * @return {string} A formatted line
  25176. */
  25177. TextMetrics.addLine = function addLine (line, newLine)
  25178. {
  25179. if ( newLine === void 0 ) { newLine = true; }
  25180. line = TextMetrics.trimRight(line);
  25181. line = (newLine) ? (line + "\n") : line;
  25182. return line;
  25183. };
  25184. /**
  25185. * Gets & sets the widths of calculated characters in a cache object
  25186. *
  25187. * @private
  25188. * @param {string} key The key
  25189. * @param {number} letterSpacing The letter spacing
  25190. * @param {object} cache The cache
  25191. * @param {CanvasRenderingContext2D} context The canvas context
  25192. * @return {number} The from cache.
  25193. */
  25194. TextMetrics.getFromCache = function getFromCache (key, letterSpacing, cache, context)
  25195. {
  25196. var width = cache[key];
  25197. if (width === undefined)
  25198. {
  25199. var spacing = ((key.length) * letterSpacing);
  25200. width = context.measureText(key).width + spacing;
  25201. cache[key] = width;
  25202. }
  25203. return width;
  25204. };
  25205. /**
  25206. * Determines whether we should collapse breaking spaces
  25207. *
  25208. * @private
  25209. * @param {string} whiteSpace The TextStyle property whiteSpace
  25210. * @return {boolean} should collapse
  25211. */
  25212. TextMetrics.collapseSpaces = function collapseSpaces (whiteSpace)
  25213. {
  25214. return (whiteSpace === 'normal' || whiteSpace === 'pre-line');
  25215. };
  25216. /**
  25217. * Determines whether we should collapse newLine chars
  25218. *
  25219. * @private
  25220. * @param {string} whiteSpace The white space
  25221. * @return {boolean} should collapse
  25222. */
  25223. TextMetrics.collapseNewlines = function collapseNewlines (whiteSpace)
  25224. {
  25225. return (whiteSpace === 'normal');
  25226. };
  25227. /**
  25228. * trims breaking whitespaces from string
  25229. *
  25230. * @private
  25231. * @param {string} text The text
  25232. * @return {string} trimmed string
  25233. */
  25234. TextMetrics.trimRight = function trimRight (text)
  25235. {
  25236. if (typeof text !== 'string')
  25237. {
  25238. return '';
  25239. }
  25240. for (var i = text.length - 1; i >= 0; i--)
  25241. {
  25242. var char = text[i];
  25243. if (!TextMetrics.isBreakingSpace(char))
  25244. {
  25245. break;
  25246. }
  25247. text = text.slice(0, -1);
  25248. }
  25249. return text;
  25250. };
  25251. /**
  25252. * Determines if char is a newline.
  25253. *
  25254. * @private
  25255. * @param {string} char The character
  25256. * @return {boolean} True if newline, False otherwise.
  25257. */
  25258. TextMetrics.isNewline = function isNewline (char)
  25259. {
  25260. if (typeof char !== 'string')
  25261. {
  25262. return false;
  25263. }
  25264. return (TextMetrics._newlines.indexOf(char.charCodeAt(0)) >= 0);
  25265. };
  25266. /**
  25267. * Determines if char is a breaking whitespace.
  25268. *
  25269. * @private
  25270. * @param {string} char The character
  25271. * @return {boolean} True if whitespace, False otherwise.
  25272. */
  25273. TextMetrics.isBreakingSpace = function isBreakingSpace (char)
  25274. {
  25275. if (typeof char !== 'string')
  25276. {
  25277. return false;
  25278. }
  25279. return (TextMetrics._breakingSpaces.indexOf(char.charCodeAt(0)) >= 0);
  25280. };
  25281. /**
  25282. * Splits a string into words, breaking-spaces and newLine characters
  25283. *
  25284. * @private
  25285. * @param {string} text The text
  25286. * @return {string[]} A tokenized array
  25287. */
  25288. TextMetrics.tokenize = function tokenize (text)
  25289. {
  25290. var tokens = [];
  25291. var token = '';
  25292. if (typeof text !== 'string')
  25293. {
  25294. return tokens;
  25295. }
  25296. for (var i = 0; i < text.length; i++)
  25297. {
  25298. var char = text[i];
  25299. if (TextMetrics.isBreakingSpace(char) || TextMetrics.isNewline(char))
  25300. {
  25301. if (token !== '')
  25302. {
  25303. tokens.push(token);
  25304. token = '';
  25305. }
  25306. tokens.push(char);
  25307. continue;
  25308. }
  25309. token += char;
  25310. }
  25311. if (token !== '')
  25312. {
  25313. tokens.push(token);
  25314. }
  25315. return tokens;
  25316. };
  25317. /**
  25318. * This method exists to be easily overridden
  25319. * It allows one to customise which words should break
  25320. * Examples are if the token is CJK or numbers.
  25321. * It must return a boolean.
  25322. *
  25323. * @private
  25324. * @param {string} token The token
  25325. * @param {boolean} breakWords The style attr break words
  25326. * @return {boolean} whether to break word or not
  25327. */
  25328. TextMetrics.canBreakWords = function canBreakWords (token, breakWords)
  25329. {
  25330. return breakWords;
  25331. };
  25332. /**
  25333. * This method exists to be easily overridden
  25334. * It allows one to determine whether a pair of characters
  25335. * should be broken by newlines
  25336. * For example certain characters in CJK langs or numbers.
  25337. * It must return a boolean.
  25338. *
  25339. * @private
  25340. * @param {string} char The character
  25341. * @param {string} nextChar The next character
  25342. * @param {string} token The token/word the characters are from
  25343. * @param {number} index The index in the token of the char
  25344. * @param {boolean} breakWords The style attr break words
  25345. * @return {boolean} whether to break word or not
  25346. */
  25347. TextMetrics.canBreakChars = function canBreakChars (char, nextChar, token, index, breakWords) // eslint-disable-line no-unused-vars
  25348. {
  25349. return true;
  25350. };
  25351. /**
  25352. * Calculates the ascent, descent and fontSize of a given font-style
  25353. *
  25354. * @static
  25355. * @param {string} font - String representing the style of the font
  25356. * @return {PIXI.IFontMetrics} Font properties object
  25357. */
  25358. TextMetrics.measureFont = function measureFont (font)
  25359. {
  25360. // as this method is used for preparing assets, don't recalculate things if we don't need to
  25361. if (TextMetrics._fonts[font])
  25362. {
  25363. return TextMetrics._fonts[font];
  25364. }
  25365. var properties = {};
  25366. var canvas = TextMetrics._canvas;
  25367. var context = TextMetrics._context;
  25368. context.font = font;
  25369. var metricsString = TextMetrics.METRICS_STRING + TextMetrics.BASELINE_SYMBOL;
  25370. var width = Math.ceil(context.measureText(metricsString).width);
  25371. var baseline = Math.ceil(context.measureText(TextMetrics.BASELINE_SYMBOL).width);
  25372. var height = 2 * baseline;
  25373. baseline = baseline * TextMetrics.BASELINE_MULTIPLIER | 0;
  25374. canvas.width = width;
  25375. canvas.height = height;
  25376. context.fillStyle = '#f00';
  25377. context.fillRect(0, 0, width, height);
  25378. context.font = font;
  25379. context.textBaseline = 'alphabetic';
  25380. context.fillStyle = '#000';
  25381. context.fillText(metricsString, 0, baseline);
  25382. var imagedata = context.getImageData(0, 0, width, height).data;
  25383. var pixels = imagedata.length;
  25384. var line = width * 4;
  25385. var i = 0;
  25386. var idx = 0;
  25387. var stop = false;
  25388. // ascent. scan from top to bottom until we find a non red pixel
  25389. for (i = 0; i < baseline; ++i)
  25390. {
  25391. for (var j = 0; j < line; j += 4)
  25392. {
  25393. if (imagedata[idx + j] !== 255)
  25394. {
  25395. stop = true;
  25396. break;
  25397. }
  25398. }
  25399. if (!stop)
  25400. {
  25401. idx += line;
  25402. }
  25403. else
  25404. {
  25405. break;
  25406. }
  25407. }
  25408. properties.ascent = baseline - i;
  25409. idx = pixels - line;
  25410. stop = false;
  25411. // descent. scan from bottom to top until we find a non red pixel
  25412. for (i = height; i > baseline; --i)
  25413. {
  25414. for (var j$1 = 0; j$1 < line; j$1 += 4)
  25415. {
  25416. if (imagedata[idx + j$1] !== 255)
  25417. {
  25418. stop = true;
  25419. break;
  25420. }
  25421. }
  25422. if (!stop)
  25423. {
  25424. idx -= line;
  25425. }
  25426. else
  25427. {
  25428. break;
  25429. }
  25430. }
  25431. properties.descent = i - baseline;
  25432. properties.fontSize = properties.ascent + properties.descent;
  25433. TextMetrics._fonts[font] = properties;
  25434. return properties;
  25435. };
  25436. /**
  25437. * Clear font metrics in metrics cache.
  25438. *
  25439. * @static
  25440. * @param {string} [font] - font name. If font name not set then clear cache for all fonts.
  25441. */
  25442. TextMetrics.clearMetrics = function clearMetrics (font)
  25443. {
  25444. if ( font === void 0 ) { font = ''; }
  25445. if (font)
  25446. {
  25447. delete TextMetrics._fonts[font];
  25448. }
  25449. else
  25450. {
  25451. TextMetrics._fonts = {};
  25452. }
  25453. };
  25454. /**
  25455. * Internal return object for {@link PIXI.TextMetrics.measureFont `TextMetrics.measureFont`}.
  25456. *
  25457. * @typedef {object} FontMetrics
  25458. * @property {number} ascent - The ascent distance
  25459. * @property {number} descent - The descent distance
  25460. * @property {number} fontSize - Font size from ascent to descent
  25461. * @memberof PIXI.TextMetrics
  25462. * @private
  25463. */
  25464. var canvas = document.createElement('canvas');
  25465. canvas.width = canvas.height = 10;
  25466. /**
  25467. * Cached canvas element for measuring text
  25468. *
  25469. * @memberof PIXI.TextMetrics
  25470. * @type {HTMLCanvasElement}
  25471. * @private
  25472. */
  25473. TextMetrics._canvas = canvas;
  25474. /**
  25475. * Cache for context to use.
  25476. *
  25477. * @memberof PIXI.TextMetrics
  25478. * @type {CanvasRenderingContext2D}
  25479. * @private
  25480. */
  25481. TextMetrics._context = canvas.getContext('2d');
  25482. /**
  25483. * Cache of {@see PIXI.TextMetrics.FontMetrics} objects.
  25484. *
  25485. * @memberof PIXI.TextMetrics
  25486. * @type {Object}
  25487. * @private
  25488. */
  25489. TextMetrics._fonts = {};
  25490. /**
  25491. * String used for calculate font metrics.
  25492. * These characters are all tall to help calculate the height required for text.
  25493. *
  25494. * @static
  25495. * @memberof PIXI.TextMetrics
  25496. * @name METRICS_STRING
  25497. * @type {string}
  25498. * @default |ÉqÅ
  25499. */
  25500. TextMetrics.METRICS_STRING = '|ÉqÅ';
  25501. /**
  25502. * Baseline symbol for calculate font metrics.
  25503. *
  25504. * @static
  25505. * @memberof PIXI.TextMetrics
  25506. * @name BASELINE_SYMBOL
  25507. * @type {string}
  25508. * @default M
  25509. */
  25510. TextMetrics.BASELINE_SYMBOL = 'M';
  25511. /**
  25512. * Baseline multiplier for calculate font metrics.
  25513. *
  25514. * @static
  25515. * @memberof PIXI.TextMetrics
  25516. * @name BASELINE_MULTIPLIER
  25517. * @type {number}
  25518. * @default 1.4
  25519. */
  25520. TextMetrics.BASELINE_MULTIPLIER = 1.4;
  25521. /**
  25522. * Cache of new line chars.
  25523. *
  25524. * @memberof PIXI.TextMetrics
  25525. * @type {number[]}
  25526. * @private
  25527. */
  25528. TextMetrics._newlines = [
  25529. 0x000A, // line feed
  25530. 0x000D ];
  25531. /**
  25532. * Cache of breaking spaces.
  25533. *
  25534. * @memberof PIXI.TextMetrics
  25535. * @type {number[]}
  25536. * @private
  25537. */
  25538. TextMetrics._breakingSpaces = [
  25539. 0x0009, // character tabulation
  25540. 0x0020, // space
  25541. 0x2000, // en quad
  25542. 0x2001, // em quad
  25543. 0x2002, // en space
  25544. 0x2003, // em space
  25545. 0x2004, // three-per-em space
  25546. 0x2005, // four-per-em space
  25547. 0x2006, // six-per-em space
  25548. 0x2008, // punctuation space
  25549. 0x2009, // thin space
  25550. 0x200A, // hair space
  25551. 0x205F, // medium mathematical space
  25552. 0x3000 ];
  25553. /**
  25554. * A number, or a string containing a number.
  25555. *
  25556. * @memberof PIXI
  25557. * @typedef IFontMetrics
  25558. * @property {number} ascent - Font ascent
  25559. * @property {number} descent - Font descent
  25560. * @property {number} fontSize - Font size
  25561. */
  25562. /* eslint max-depth: [2, 8] */
  25563. var defaultDestroyOptions = {
  25564. texture: true,
  25565. children: false,
  25566. baseTexture: true,
  25567. };
  25568. /**
  25569. * A Text Object will create a line or multiple lines of text.
  25570. *
  25571. * The text is created using the [Canvas API](https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API).
  25572. *
  25573. * The primary advantage of this class over BitmapText is that you have great control over the style of the next,
  25574. * which you can change at runtime.
  25575. *
  25576. * The primary disadvantages is that each piece of text has it's own texture, which can use more memory.
  25577. * When text changes, this texture has to be re-generated and re-uploaded to the GPU, taking up time.
  25578. *
  25579. * To split a line you can use '\n' in your text string, or, on the `style` object,
  25580. * change its `wordWrap` property to true and and give the `wordWrapWidth` property a value.
  25581. *
  25582. * A Text can be created directly from a string and a style object,
  25583. * which can be generated [here](https://pixijs.io/pixi-text-style).
  25584. *
  25585. * ```js
  25586. * let text = new PIXI.Text('This is a PixiJS text',{fontFamily : 'Arial', fontSize: 24, fill : 0xff1010, align : 'center'});
  25587. * ```
  25588. *
  25589. * @class
  25590. * @extends PIXI.Sprite
  25591. * @memberof PIXI
  25592. */
  25593. var Text = /*@__PURE__*/(function (Sprite) {
  25594. function Text(text, style, canvas)
  25595. {
  25596. canvas = canvas || document.createElement('canvas');
  25597. canvas.width = 3;
  25598. canvas.height = 3;
  25599. var texture = Texture.from(canvas);
  25600. texture.orig = new Rectangle();
  25601. texture.trim = new Rectangle();
  25602. Sprite.call(this, texture);
  25603. /**
  25604. * The canvas element that everything is drawn to
  25605. *
  25606. * @member {HTMLCanvasElement}
  25607. */
  25608. this.canvas = canvas;
  25609. /**
  25610. * The canvas 2d context that everything is drawn with
  25611. * @member {CanvasRenderingContext2D}
  25612. */
  25613. this.context = this.canvas.getContext('2d');
  25614. /**
  25615. * The resolution / device pixel ratio of the canvas.
  25616. * This is set to automatically match the renderer resolution by default, but can be overridden by setting manually.
  25617. * @member {number}
  25618. * @default 1
  25619. */
  25620. this._resolution = settings.RESOLUTION;
  25621. this._autoResolution = true;
  25622. /**
  25623. * Private tracker for the current text.
  25624. *
  25625. * @member {string}
  25626. * @private
  25627. */
  25628. this._text = null;
  25629. /**
  25630. * Private tracker for the current style.
  25631. *
  25632. * @member {object}
  25633. * @private
  25634. */
  25635. this._style = null;
  25636. /**
  25637. * Private listener to track style changes.
  25638. *
  25639. * @member {Function}
  25640. * @private
  25641. */
  25642. this._styleListener = null;
  25643. /**
  25644. * Private tracker for the current font.
  25645. *
  25646. * @member {string}
  25647. * @private
  25648. */
  25649. this._font = '';
  25650. this.text = text;
  25651. this.style = style;
  25652. this.localStyleID = -1;
  25653. }
  25654. if ( Sprite ) { Text.__proto__ = Sprite; }
  25655. Text.prototype = Object.create( Sprite && Sprite.prototype );
  25656. Text.prototype.constructor = Text;
  25657. var prototypeAccessors = { width: { configurable: true },height: { configurable: true },style: { configurable: true },text: { configurable: true },resolution: { configurable: true } };
  25658. /**
  25659. * Renders text and updates it when needed.
  25660. *
  25661. * @private
  25662. * @param {boolean} respectDirty - Whether to abort updating the text if the Text isn't dirty and the function is called.
  25663. */
  25664. Text.prototype.updateText = function updateText (respectDirty)
  25665. {
  25666. var style = this._style;
  25667. // check if style has changed..
  25668. if (this.localStyleID !== style.styleID)
  25669. {
  25670. this.dirty = true;
  25671. this.localStyleID = style.styleID;
  25672. }
  25673. if (!this.dirty && respectDirty)
  25674. {
  25675. return;
  25676. }
  25677. this._font = this._style.toFontString();
  25678. var context = this.context;
  25679. var measured = TextMetrics.measureText(this._text || ' ', this._style, this._style.wordWrap, this.canvas);
  25680. var width = measured.width;
  25681. var height = measured.height;
  25682. var lines = measured.lines;
  25683. var lineHeight = measured.lineHeight;
  25684. var lineWidths = measured.lineWidths;
  25685. var maxLineWidth = measured.maxLineWidth;
  25686. var fontProperties = measured.fontProperties;
  25687. this.canvas.width = Math.ceil((Math.max(1, width) + (style.padding * 2)) * this._resolution);
  25688. this.canvas.height = Math.ceil((Math.max(1, height) + (style.padding * 2)) * this._resolution);
  25689. context.scale(this._resolution, this._resolution);
  25690. context.clearRect(0, 0, this.canvas.width, this.canvas.height);
  25691. context.font = this._font;
  25692. context.strokeStyle = style.stroke;
  25693. context.lineWidth = style.strokeThickness;
  25694. context.textBaseline = style.textBaseline;
  25695. context.lineJoin = style.lineJoin;
  25696. context.miterLimit = style.miterLimit;
  25697. var linePositionX;
  25698. var linePositionY;
  25699. if (style.dropShadow)
  25700. {
  25701. var dropShadowColor = style.dropShadowColor;
  25702. var rgb = hex2rgb(typeof dropShadowColor === 'number' ? dropShadowColor : string2hex(dropShadowColor));
  25703. context.shadowColor = "rgba(" + (rgb[0] * 255) + "," + (rgb[1] * 255) + "," + (rgb[2] * 255) + "," + (style.dropShadowAlpha) + ")";
  25704. context.shadowBlur = style.dropShadowBlur;
  25705. context.shadowOffsetX = Math.cos(style.dropShadowAngle) * style.dropShadowDistance;
  25706. context.shadowOffsetY = Math.sin(style.dropShadowAngle) * style.dropShadowDistance;
  25707. }
  25708. else
  25709. {
  25710. context.shadowColor = 0;
  25711. context.shadowBlur = 0;
  25712. context.shadowOffsetX = 0;
  25713. context.shadowOffsetY = 0;
  25714. }
  25715. // set canvas text styles
  25716. context.fillStyle = this._generateFillStyle(style, lines);
  25717. // draw lines line by line
  25718. for (var i = 0; i < lines.length; i++)
  25719. {
  25720. linePositionX = style.strokeThickness / 2;
  25721. linePositionY = ((style.strokeThickness / 2) + (i * lineHeight)) + fontProperties.ascent;
  25722. if (style.align === 'right')
  25723. {
  25724. linePositionX += maxLineWidth - lineWidths[i];
  25725. }
  25726. else if (style.align === 'center')
  25727. {
  25728. linePositionX += (maxLineWidth - lineWidths[i]) / 2;
  25729. }
  25730. if (style.stroke && style.strokeThickness)
  25731. {
  25732. this.drawLetterSpacing(
  25733. lines[i],
  25734. linePositionX + style.padding,
  25735. linePositionY + style.padding,
  25736. true
  25737. );
  25738. }
  25739. if (style.fill)
  25740. {
  25741. this.drawLetterSpacing(
  25742. lines[i],
  25743. linePositionX + style.padding,
  25744. linePositionY + style.padding
  25745. );
  25746. }
  25747. }
  25748. this.updateTexture();
  25749. };
  25750. /**
  25751. * Render the text with letter-spacing.
  25752. * @param {string} text - The text to draw
  25753. * @param {number} x - Horizontal position to draw the text
  25754. * @param {number} y - Vertical position to draw the text
  25755. * @param {boolean} [isStroke=false] - Is this drawing for the outside stroke of the
  25756. * text? If not, it's for the inside fill
  25757. * @private
  25758. */
  25759. Text.prototype.drawLetterSpacing = function drawLetterSpacing (text, x, y, isStroke)
  25760. {
  25761. if ( isStroke === void 0 ) { isStroke = false; }
  25762. var style = this._style;
  25763. // letterSpacing of 0 means normal
  25764. var letterSpacing = style.letterSpacing;
  25765. if (letterSpacing === 0)
  25766. {
  25767. if (isStroke)
  25768. {
  25769. this.context.strokeText(text, x, y);
  25770. }
  25771. else
  25772. {
  25773. this.context.fillText(text, x, y);
  25774. }
  25775. return;
  25776. }
  25777. var currentPosition = x;
  25778. // Using Array.from correctly splits characters whilst keeping emoji together.
  25779. // This is not supported on IE as it requires ES6, so regular text splitting occurs.
  25780. // This also doesn't account for emoji that are multiple emoji put together to make something else.
  25781. // Handling all of this would require a big library itself.
  25782. // https://medium.com/@giltayar/iterating-over-emoji-characters-the-es6-way-f06e4589516
  25783. // https://github.com/orling/grapheme-splitter
  25784. var stringArray = Array.from ? Array.from(text) : text.split('');
  25785. for (var i = 0; i < stringArray.length; ++i)
  25786. {
  25787. var currentChar = stringArray[i];
  25788. if (isStroke)
  25789. {
  25790. this.context.strokeText(currentChar, currentPosition, y);
  25791. }
  25792. else
  25793. {
  25794. this.context.fillText(currentChar, currentPosition, y);
  25795. }
  25796. currentPosition += this.context.measureText(currentChar).width + letterSpacing;
  25797. }
  25798. };
  25799. /**
  25800. * Updates texture size based on canvas size
  25801. *
  25802. * @private
  25803. */
  25804. Text.prototype.updateTexture = function updateTexture ()
  25805. {
  25806. var canvas = this.canvas;
  25807. if (this._style.trim)
  25808. {
  25809. var trimmed = trimCanvas(canvas);
  25810. if (trimmed.data)
  25811. {
  25812. canvas.width = trimmed.width;
  25813. canvas.height = trimmed.height;
  25814. this.context.putImageData(trimmed.data, 0, 0);
  25815. }
  25816. }
  25817. var texture = this._texture;
  25818. var style = this._style;
  25819. var padding = style.trim ? 0 : style.padding;
  25820. var baseTexture = texture.baseTexture;
  25821. texture.trim.width = texture._frame.width = canvas.width / this._resolution;
  25822. texture.trim.height = texture._frame.height = canvas.height / this._resolution;
  25823. texture.trim.x = -padding;
  25824. texture.trim.y = -padding;
  25825. texture.orig.width = texture._frame.width - (padding * 2);
  25826. texture.orig.height = texture._frame.height - (padding * 2);
  25827. // call sprite onTextureUpdate to update scale if _width or _height were set
  25828. this._onTextureUpdate();
  25829. baseTexture.setRealSize(canvas.width, canvas.height, this._resolution);
  25830. this.dirty = false;
  25831. };
  25832. /**
  25833. * Renders the object using the WebGL renderer
  25834. *
  25835. * @param {PIXI.Renderer} renderer - The renderer
  25836. */
  25837. Text.prototype.render = function render (renderer)
  25838. {
  25839. if (this._autoResolution && this._resolution !== renderer.resolution)
  25840. {
  25841. this._resolution = renderer.resolution;
  25842. this.dirty = true;
  25843. }
  25844. this.updateText(true);
  25845. Sprite.prototype.render.call(this, renderer);
  25846. };
  25847. /**
  25848. * Renders the object using the Canvas renderer
  25849. *
  25850. * @private
  25851. * @param {PIXI.CanvasRenderer} renderer - The renderer
  25852. */
  25853. Text.prototype._renderCanvas = function _renderCanvas (renderer)
  25854. {
  25855. if (this._autoResolution && this._resolution !== renderer.resolution)
  25856. {
  25857. this._resolution = renderer.resolution;
  25858. this.dirty = true;
  25859. }
  25860. this.updateText(true);
  25861. Sprite.prototype._renderCanvas.call(this, renderer);
  25862. };
  25863. /**
  25864. * Gets the local bounds of the text object.
  25865. *
  25866. * @param {PIXI.Rectangle} rect - The output rectangle.
  25867. * @return {PIXI.Rectangle} The bounds.
  25868. */
  25869. Text.prototype.getLocalBounds = function getLocalBounds (rect)
  25870. {
  25871. this.updateText(true);
  25872. return Sprite.prototype.getLocalBounds.call(this, rect);
  25873. };
  25874. /**
  25875. * calculates the bounds of the Text as a rectangle. The bounds calculation takes the worldTransform into account.
  25876. * @protected
  25877. */
  25878. Text.prototype._calculateBounds = function _calculateBounds ()
  25879. {
  25880. this.updateText(true);
  25881. this.calculateVertices();
  25882. // if we have already done this on THIS frame.
  25883. this._bounds.addQuad(this.vertexData);
  25884. };
  25885. /**
  25886. * Method to be called upon a TextStyle change.
  25887. * @private
  25888. */
  25889. Text.prototype._onStyleChange = function _onStyleChange ()
  25890. {
  25891. this.dirty = true;
  25892. };
  25893. /**
  25894. * Generates the fill style. Can automatically generate a gradient based on the fill style being an array
  25895. *
  25896. * @private
  25897. * @param {object} style - The style.
  25898. * @param {string[]} lines - The lines of text.
  25899. * @return {string|number|CanvasGradient} The fill style
  25900. */
  25901. Text.prototype._generateFillStyle = function _generateFillStyle (style, lines)
  25902. {
  25903. if (!Array.isArray(style.fill))
  25904. {
  25905. return style.fill;
  25906. }
  25907. // the gradient will be evenly spaced out according to how large the array is.
  25908. // ['#FF0000', '#00FF00', '#0000FF'] would created stops at 0.25, 0.5 and 0.75
  25909. var gradient;
  25910. var totalIterations;
  25911. var currentIteration;
  25912. var stop;
  25913. var width = this.canvas.width / this._resolution;
  25914. var height = this.canvas.height / this._resolution;
  25915. // make a copy of the style settings, so we can manipulate them later
  25916. var fill = style.fill.slice();
  25917. var fillGradientStops = style.fillGradientStops.slice();
  25918. // wanting to evenly distribute the fills. So an array of 4 colours should give fills of 0.25, 0.5 and 0.75
  25919. if (!fillGradientStops.length)
  25920. {
  25921. var lengthPlus1 = fill.length + 1;
  25922. for (var i = 1; i < lengthPlus1; ++i)
  25923. {
  25924. fillGradientStops.push(i / lengthPlus1);
  25925. }
  25926. }
  25927. // stop the bleeding of the last gradient on the line above to the top gradient of the this line
  25928. // by hard defining the first gradient colour at point 0, and last gradient colour at point 1
  25929. fill.unshift(style.fill[0]);
  25930. fillGradientStops.unshift(0);
  25931. fill.push(style.fill[style.fill.length - 1]);
  25932. fillGradientStops.push(1);
  25933. if (style.fillGradientType === TEXT_GRADIENT.LINEAR_VERTICAL)
  25934. {
  25935. // start the gradient at the top center of the canvas, and end at the bottom middle of the canvas
  25936. gradient = this.context.createLinearGradient(width / 2, 0, width / 2, height);
  25937. // we need to repeat the gradient so that each individual line of text has the same vertical gradient effect
  25938. // ['#FF0000', '#00FF00', '#0000FF'] over 2 lines would create stops at 0.125, 0.25, 0.375, 0.625, 0.75, 0.875
  25939. totalIterations = (fill.length + 1) * lines.length;
  25940. currentIteration = 0;
  25941. for (var i$1 = 0; i$1 < lines.length; i$1++)
  25942. {
  25943. currentIteration += 1;
  25944. for (var j = 0; j < fill.length; j++)
  25945. {
  25946. if (typeof fillGradientStops[j] === 'number')
  25947. {
  25948. stop = (fillGradientStops[j] / lines.length) + (i$1 / lines.length);
  25949. }
  25950. else
  25951. {
  25952. stop = currentIteration / totalIterations;
  25953. }
  25954. gradient.addColorStop(stop, fill[j]);
  25955. currentIteration++;
  25956. }
  25957. }
  25958. }
  25959. else
  25960. {
  25961. // start the gradient at the center left of the canvas, and end at the center right of the canvas
  25962. gradient = this.context.createLinearGradient(0, height / 2, width, height / 2);
  25963. // can just evenly space out the gradients in this case, as multiple lines makes no difference
  25964. // to an even left to right gradient
  25965. totalIterations = fill.length + 1;
  25966. currentIteration = 1;
  25967. for (var i$2 = 0; i$2 < fill.length; i$2++)
  25968. {
  25969. if (typeof fillGradientStops[i$2] === 'number')
  25970. {
  25971. stop = fillGradientStops[i$2];
  25972. }
  25973. else
  25974. {
  25975. stop = currentIteration / totalIterations;
  25976. }
  25977. gradient.addColorStop(stop, fill[i$2]);
  25978. currentIteration++;
  25979. }
  25980. }
  25981. return gradient;
  25982. };
  25983. /**
  25984. * Destroys this text object.
  25985. * Note* Unlike a Sprite, a Text object will automatically destroy its baseTexture and texture as
  25986. * the majority of the time the texture will not be shared with any other Sprites.
  25987. *
  25988. * @param {object|boolean} [options] - Options parameter. A boolean will act as if all options
  25989. * have been set to that value
  25990. * @param {boolean} [options.children=false] - if set to true, all the children will have their
  25991. * destroy method called as well. 'options' will be passed on to those calls.
  25992. * @param {boolean} [options.texture=true] - Should it destroy the current texture of the sprite as well
  25993. * @param {boolean} [options.baseTexture=true] - Should it destroy the base texture of the sprite as well
  25994. */
  25995. Text.prototype.destroy = function destroy (options)
  25996. {
  25997. if (typeof options === 'boolean')
  25998. {
  25999. options = { children: options };
  26000. }
  26001. options = Object.assign({}, defaultDestroyOptions, options);
  26002. Sprite.prototype.destroy.call(this, options);
  26003. // make sure to reset the the context and canvas.. dont want this hanging around in memory!
  26004. this.context = null;
  26005. this.canvas = null;
  26006. this._style = null;
  26007. };
  26008. /**
  26009. * The width of the Text, setting this will actually modify the scale to achieve the value set
  26010. *
  26011. * @member {number}
  26012. */
  26013. prototypeAccessors.width.get = function ()
  26014. {
  26015. this.updateText(true);
  26016. return Math.abs(this.scale.x) * this._texture.orig.width;
  26017. };
  26018. prototypeAccessors.width.set = function (value) // eslint-disable-line require-jsdoc
  26019. {
  26020. this.updateText(true);
  26021. var s = sign(this.scale.x) || 1;
  26022. this.scale.x = s * value / this._texture.orig.width;
  26023. this._width = value;
  26024. };
  26025. /**
  26026. * The height of the Text, setting this will actually modify the scale to achieve the value set
  26027. *
  26028. * @member {number}
  26029. */
  26030. prototypeAccessors.height.get = function ()
  26031. {
  26032. this.updateText(true);
  26033. return Math.abs(this.scale.y) * this._texture.orig.height;
  26034. };
  26035. prototypeAccessors.height.set = function (value) // eslint-disable-line require-jsdoc
  26036. {
  26037. this.updateText(true);
  26038. var s = sign(this.scale.y) || 1;
  26039. this.scale.y = s * value / this._texture.orig.height;
  26040. this._height = value;
  26041. };
  26042. /**
  26043. * Set the style of the text. Set up an event listener to listen for changes on the style
  26044. * object and mark the text as dirty.
  26045. *
  26046. * @member {object|PIXI.TextStyle}
  26047. */
  26048. prototypeAccessors.style.get = function ()
  26049. {
  26050. return this._style;
  26051. };
  26052. prototypeAccessors.style.set = function (style) // eslint-disable-line require-jsdoc
  26053. {
  26054. style = style || {};
  26055. if (style instanceof TextStyle)
  26056. {
  26057. this._style = style;
  26058. }
  26059. else
  26060. {
  26061. this._style = new TextStyle(style);
  26062. }
  26063. this.localStyleID = -1;
  26064. this.dirty = true;
  26065. };
  26066. /**
  26067. * Set the copy for the text object. To split a line you can use '\n'.
  26068. *
  26069. * @member {string}
  26070. */
  26071. prototypeAccessors.text.get = function ()
  26072. {
  26073. return this._text;
  26074. };
  26075. prototypeAccessors.text.set = function (text) // eslint-disable-line require-jsdoc
  26076. {
  26077. text = String(text === null || text === undefined ? '' : text);
  26078. if (this._text === text)
  26079. {
  26080. return;
  26081. }
  26082. this._text = text;
  26083. this.dirty = true;
  26084. };
  26085. /**
  26086. * The resolution / device pixel ratio of the canvas.
  26087. * This is set to automatically match the renderer resolution by default, but can be overridden by setting manually.
  26088. * @member {number}
  26089. * @default 1
  26090. */
  26091. prototypeAccessors.resolution.get = function ()
  26092. {
  26093. return this._resolution;
  26094. };
  26095. prototypeAccessors.resolution.set = function (value) // eslint-disable-line require-jsdoc
  26096. {
  26097. this._autoResolution = false;
  26098. if (this._resolution === value)
  26099. {
  26100. return;
  26101. }
  26102. this._resolution = value;
  26103. this.dirty = true;
  26104. };
  26105. Object.defineProperties( Text.prototype, prototypeAccessors );
  26106. return Text;
  26107. }(Sprite));
  26108. /*!
  26109. * @pixi/prepare - v5.0.4
  26110. * Compiled Fri, 07 Jun 2019 17:17:49 UTC
  26111. *
  26112. * @pixi/prepare is licensed under the MIT License.
  26113. * http://www.opensource.org/licenses/mit-license
  26114. */
  26115. /**
  26116. * Default number of uploads per frame using prepare plugin.
  26117. *
  26118. * @static
  26119. * @memberof PIXI.settings
  26120. * @name UPLOADS_PER_FRAME
  26121. * @type {number}
  26122. * @default 4
  26123. */
  26124. settings.UPLOADS_PER_FRAME = 4;
  26125. /**
  26126. * CountLimiter limits the number of items handled by a {@link PIXI.prepare.BasePrepare} to a specified
  26127. * number of items per frame.
  26128. *
  26129. * @class
  26130. * @memberof PIXI.prepare
  26131. */
  26132. var CountLimiter = function CountLimiter(maxItemsPerFrame)
  26133. {
  26134. /**
  26135. * The maximum number of items that can be prepared each frame.
  26136. * @type {number}
  26137. * @private
  26138. */
  26139. this.maxItemsPerFrame = maxItemsPerFrame;
  26140. /**
  26141. * The number of items that can be prepared in the current frame.
  26142. * @type {number}
  26143. * @private
  26144. */
  26145. this.itemsLeft = 0;
  26146. };
  26147. /**
  26148. * Resets any counting properties to start fresh on a new frame.
  26149. */
  26150. CountLimiter.prototype.beginFrame = function beginFrame ()
  26151. {
  26152. this.itemsLeft = this.maxItemsPerFrame;
  26153. };
  26154. /**
  26155. * Checks to see if another item can be uploaded. This should only be called once per item.
  26156. * @return {boolean} If the item is allowed to be uploaded.
  26157. */
  26158. CountLimiter.prototype.allowedToUpload = function allowedToUpload ()
  26159. {
  26160. return this.itemsLeft-- > 0;
  26161. };
  26162. /**
  26163. * The prepare manager provides functionality to upload content to the GPU.
  26164. *
  26165. * BasePrepare handles basic queuing functionality and is extended by
  26166. * {@link PIXI.prepare.Prepare} and {@link PIXI.prepare.CanvasPrepare}
  26167. * to provide preparation capabilities specific to their respective renderers.
  26168. *
  26169. * @example
  26170. * // Create a sprite
  26171. * const sprite = PIXI.Sprite.from('something.png');
  26172. *
  26173. * // Load object into GPU
  26174. * app.renderer.plugins.prepare.upload(sprite, () => {
  26175. *
  26176. * //Texture(s) has been uploaded to GPU
  26177. * app.stage.addChild(sprite);
  26178. *
  26179. * })
  26180. *
  26181. * @abstract
  26182. * @class
  26183. * @memberof PIXI.prepare
  26184. */
  26185. var BasePrepare = function BasePrepare(renderer)
  26186. {
  26187. var this$1 = this;
  26188. /**
  26189. * The limiter to be used to control how quickly items are prepared.
  26190. * @type {PIXI.prepare.CountLimiter|PIXI.prepare.TimeLimiter}
  26191. */
  26192. this.limiter = new CountLimiter(settings.UPLOADS_PER_FRAME);
  26193. /**
  26194. * Reference to the renderer.
  26195. * @type {PIXI.AbstractRenderer}
  26196. * @protected
  26197. */
  26198. this.renderer = renderer;
  26199. /**
  26200. * The only real difference between CanvasPrepare and Prepare is what they pass
  26201. * to upload hooks. That different parameter is stored here.
  26202. * @type {PIXI.prepare.CanvasPrepare|PIXI.Renderer}
  26203. * @protected
  26204. */
  26205. this.uploadHookHelper = null;
  26206. /**
  26207. * Collection of items to uploads at once.
  26208. * @type {Array<*>}
  26209. * @private
  26210. */
  26211. this.queue = [];
  26212. /**
  26213. * Collection of additional hooks for finding assets.
  26214. * @type {Array<Function>}
  26215. * @private
  26216. */
  26217. this.addHooks = [];
  26218. /**
  26219. * Collection of additional hooks for processing assets.
  26220. * @type {Array<Function>}
  26221. * @private
  26222. */
  26223. this.uploadHooks = [];
  26224. /**
  26225. * Callback to call after completed.
  26226. * @type {Array<Function>}
  26227. * @private
  26228. */
  26229. this.completes = [];
  26230. /**
  26231. * If prepare is ticking (running).
  26232. * @type {boolean}
  26233. * @private
  26234. */
  26235. this.ticking = false;
  26236. /**
  26237. * 'bound' call for prepareItems().
  26238. * @type {Function}
  26239. * @private
  26240. */
  26241. this.delayedTick = function () {
  26242. // unlikely, but in case we were destroyed between tick() and delayedTick()
  26243. if (!this$1.queue)
  26244. {
  26245. return;
  26246. }
  26247. this$1.prepareItems();
  26248. };
  26249. // hooks to find the correct texture
  26250. this.registerFindHook(findText);
  26251. this.registerFindHook(findTextStyle);
  26252. this.registerFindHook(findMultipleBaseTextures);
  26253. this.registerFindHook(findBaseTexture);
  26254. this.registerFindHook(findTexture);
  26255. // upload hooks
  26256. this.registerUploadHook(drawText);
  26257. this.registerUploadHook(calculateTextStyle);
  26258. };
  26259. /**
  26260. * Upload all the textures and graphics to the GPU.
  26261. *
  26262. * @param {Function|PIXI.DisplayObject|PIXI.Container|PIXI.BaseTexture|PIXI.Texture|PIXI.Graphics|PIXI.Text} item -
  26263. * Either the container or display object to search for items to upload, the items to upload themselves,
  26264. * or the callback function, if items have been added using `prepare.add`.
  26265. * @param {Function} [done] - Optional callback when all queued uploads have completed
  26266. */
  26267. BasePrepare.prototype.upload = function upload (item, done)
  26268. {
  26269. if (typeof item === 'function')
  26270. {
  26271. done = item;
  26272. item = null;
  26273. }
  26274. // If a display object, search for items
  26275. // that we could upload
  26276. if (item)
  26277. {
  26278. this.add(item);
  26279. }
  26280. // Get the items for upload from the display
  26281. if (this.queue.length)
  26282. {
  26283. if (done)
  26284. {
  26285. this.completes.push(done);
  26286. }
  26287. if (!this.ticking)
  26288. {
  26289. this.ticking = true;
  26290. Ticker.system.addOnce(this.tick, this, UPDATE_PRIORITY.UTILITY);
  26291. }
  26292. }
  26293. else if (done)
  26294. {
  26295. done();
  26296. }
  26297. };
  26298. /**
  26299. * Handle tick update
  26300. *
  26301. * @private
  26302. */
  26303. BasePrepare.prototype.tick = function tick ()
  26304. {
  26305. setTimeout(this.delayedTick, 0);
  26306. };
  26307. /**
  26308. * Actually prepare items. This is handled outside of the tick because it will take a while
  26309. * and we do NOT want to block the current animation frame from rendering.
  26310. *
  26311. * @private
  26312. */
  26313. BasePrepare.prototype.prepareItems = function prepareItems ()
  26314. {
  26315. this.limiter.beginFrame();
  26316. // Upload the graphics
  26317. while (this.queue.length && this.limiter.allowedToUpload())
  26318. {
  26319. var item = this.queue[0];
  26320. var uploaded = false;
  26321. if (item && !item._destroyed)
  26322. {
  26323. for (var i = 0, len = this.uploadHooks.length; i < len; i++)
  26324. {
  26325. if (this.uploadHooks[i](this.uploadHookHelper, item))
  26326. {
  26327. this.queue.shift();
  26328. uploaded = true;
  26329. break;
  26330. }
  26331. }
  26332. }
  26333. if (!uploaded)
  26334. {
  26335. this.queue.shift();
  26336. }
  26337. }
  26338. // We're finished
  26339. if (!this.queue.length)
  26340. {
  26341. this.ticking = false;
  26342. var completes = this.completes.slice(0);
  26343. this.completes.length = 0;
  26344. for (var i$1 = 0, len$1 = completes.length; i$1 < len$1; i$1++)
  26345. {
  26346. completes[i$1]();
  26347. }
  26348. }
  26349. else
  26350. {
  26351. // if we are not finished, on the next rAF do this again
  26352. Ticker.system.addOnce(this.tick, this, UPDATE_PRIORITY.UTILITY);
  26353. }
  26354. };
  26355. /**
  26356. * Adds hooks for finding items.
  26357. *
  26358. * @param {Function} addHook - Function call that takes two parameters: `item:*, queue:Array`
  26359. * function must return `true` if it was able to add item to the queue.
  26360. * @return {PIXI.prepare.BasePrepare} Instance of plugin for chaining.
  26361. */
  26362. BasePrepare.prototype.registerFindHook = function registerFindHook (addHook)
  26363. {
  26364. if (addHook)
  26365. {
  26366. this.addHooks.push(addHook);
  26367. }
  26368. return this;
  26369. };
  26370. /**
  26371. * Adds hooks for uploading items.
  26372. *
  26373. * @param {Function} uploadHook - Function call that takes two parameters: `prepare:CanvasPrepare, item:*` and
  26374. * function must return `true` if it was able to handle upload of item.
  26375. * @return {PIXI.prepare.BasePrepare} Instance of plugin for chaining.
  26376. */
  26377. BasePrepare.prototype.registerUploadHook = function registerUploadHook (uploadHook)
  26378. {
  26379. if (uploadHook)
  26380. {
  26381. this.uploadHooks.push(uploadHook);
  26382. }
  26383. return this;
  26384. };
  26385. /**
  26386. * Manually add an item to the uploading queue.
  26387. *
  26388. * @param {PIXI.DisplayObject|PIXI.Container|PIXI.BaseTexture|PIXI.Texture|PIXI.Graphics|PIXI.Text|*} item - Object to
  26389. * add to the queue
  26390. * @return {PIXI.prepare.BasePrepare} Instance of plugin for chaining.
  26391. */
  26392. BasePrepare.prototype.add = function add (item)
  26393. {
  26394. // Add additional hooks for finding elements on special
  26395. // types of objects that
  26396. for (var i = 0, len = this.addHooks.length; i < len; i++)
  26397. {
  26398. if (this.addHooks[i](item, this.queue))
  26399. {
  26400. break;
  26401. }
  26402. }
  26403. // Get children recursively
  26404. if (item instanceof Container)
  26405. {
  26406. for (var i$1 = item.children.length - 1; i$1 >= 0; i$1--)
  26407. {
  26408. this.add(item.children[i$1]);
  26409. }
  26410. }
  26411. return this;
  26412. };
  26413. /**
  26414. * Destroys the plugin, don't use after this.
  26415. *
  26416. */
  26417. BasePrepare.prototype.destroy = function destroy ()
  26418. {
  26419. if (this.ticking)
  26420. {
  26421. Ticker.system.remove(this.tick, this);
  26422. }
  26423. this.ticking = false;
  26424. this.addHooks = null;
  26425. this.uploadHooks = null;
  26426. this.renderer = null;
  26427. this.completes = null;
  26428. this.queue = null;
  26429. this.limiter = null;
  26430. this.uploadHookHelper = null;
  26431. };
  26432. /**
  26433. * Built-in hook to find multiple textures from objects like AnimatedSprites.
  26434. *
  26435. * @private
  26436. * @param {PIXI.DisplayObject} item - Display object to check
  26437. * @param {Array<*>} queue - Collection of items to upload
  26438. * @return {boolean} if a PIXI.Texture object was found.
  26439. */
  26440. function findMultipleBaseTextures(item, queue)
  26441. {
  26442. var result = false;
  26443. // Objects with multiple textures
  26444. if (item && item._textures && item._textures.length)
  26445. {
  26446. for (var i = 0; i < item._textures.length; i++)
  26447. {
  26448. if (item._textures[i] instanceof Texture)
  26449. {
  26450. var baseTexture = item._textures[i].baseTexture;
  26451. if (queue.indexOf(baseTexture) === -1)
  26452. {
  26453. queue.push(baseTexture);
  26454. result = true;
  26455. }
  26456. }
  26457. }
  26458. }
  26459. return result;
  26460. }
  26461. /**
  26462. * Built-in hook to find BaseTextures from Sprites.
  26463. *
  26464. * @private
  26465. * @param {PIXI.DisplayObject} item - Display object to check
  26466. * @param {Array<*>} queue - Collection of items to upload
  26467. * @return {boolean} if a PIXI.Texture object was found.
  26468. */
  26469. function findBaseTexture(item, queue)
  26470. {
  26471. // Objects with textures, like Sprites/Text
  26472. if (item instanceof BaseTexture)
  26473. {
  26474. if (queue.indexOf(item) === -1)
  26475. {
  26476. queue.push(item);
  26477. }
  26478. return true;
  26479. }
  26480. return false;
  26481. }
  26482. /**
  26483. * Built-in hook to find textures from objects.
  26484. *
  26485. * @private
  26486. * @param {PIXI.DisplayObject} item - Display object to check
  26487. * @param {Array<*>} queue - Collection of items to upload
  26488. * @return {boolean} if a PIXI.Texture object was found.
  26489. */
  26490. function findTexture(item, queue)
  26491. {
  26492. if (item._texture && item._texture instanceof Texture)
  26493. {
  26494. var texture = item._texture.baseTexture;
  26495. if (queue.indexOf(texture) === -1)
  26496. {
  26497. queue.push(texture);
  26498. }
  26499. return true;
  26500. }
  26501. return false;
  26502. }
  26503. /**
  26504. * Built-in hook to draw PIXI.Text to its texture.
  26505. *
  26506. * @private
  26507. * @param {PIXI.Renderer|PIXI.CanvasPrepare} helper - Not used by this upload handler
  26508. * @param {PIXI.DisplayObject} item - Item to check
  26509. * @return {boolean} If item was uploaded.
  26510. */
  26511. function drawText(helper, item)
  26512. {
  26513. if (item instanceof Text)
  26514. {
  26515. // updating text will return early if it is not dirty
  26516. item.updateText(true);
  26517. return true;
  26518. }
  26519. return false;
  26520. }
  26521. /**
  26522. * Built-in hook to calculate a text style for a PIXI.Text object.
  26523. *
  26524. * @private
  26525. * @param {PIXI.Renderer|PIXI.CanvasPrepare} helper - Not used by this upload handler
  26526. * @param {PIXI.DisplayObject} item - Item to check
  26527. * @return {boolean} If item was uploaded.
  26528. */
  26529. function calculateTextStyle(helper, item)
  26530. {
  26531. if (item instanceof TextStyle)
  26532. {
  26533. var font = item.toFontString();
  26534. TextMetrics.measureFont(font);
  26535. return true;
  26536. }
  26537. return false;
  26538. }
  26539. /**
  26540. * Built-in hook to find Text objects.
  26541. *
  26542. * @private
  26543. * @param {PIXI.DisplayObject} item - Display object to check
  26544. * @param {Array<*>} queue - Collection of items to upload
  26545. * @return {boolean} if a PIXI.Text object was found.
  26546. */
  26547. function findText(item, queue)
  26548. {
  26549. if (item instanceof Text)
  26550. {
  26551. // push the text style to prepare it - this can be really expensive
  26552. if (queue.indexOf(item.style) === -1)
  26553. {
  26554. queue.push(item.style);
  26555. }
  26556. // also push the text object so that we can render it (to canvas/texture) if needed
  26557. if (queue.indexOf(item) === -1)
  26558. {
  26559. queue.push(item);
  26560. }
  26561. // also push the Text's texture for upload to GPU
  26562. var texture = item._texture.baseTexture;
  26563. if (queue.indexOf(texture) === -1)
  26564. {
  26565. queue.push(texture);
  26566. }
  26567. return true;
  26568. }
  26569. return false;
  26570. }
  26571. /**
  26572. * Built-in hook to find TextStyle objects.
  26573. *
  26574. * @private
  26575. * @param {PIXI.TextStyle} item - Display object to check
  26576. * @param {Array<*>} queue - Collection of items to upload
  26577. * @return {boolean} if a PIXI.TextStyle object was found.
  26578. */
  26579. function findTextStyle(item, queue)
  26580. {
  26581. if (item instanceof TextStyle)
  26582. {
  26583. if (queue.indexOf(item) === -1)
  26584. {
  26585. queue.push(item);
  26586. }
  26587. return true;
  26588. }
  26589. return false;
  26590. }
  26591. /**
  26592. * The prepare manager provides functionality to upload content to the GPU.
  26593. *
  26594. * An instance of this class is automatically created by default, and can be found at `renderer.plugins.prepare`
  26595. *
  26596. * @class
  26597. * @extends PIXI.prepare.BasePrepare
  26598. * @memberof PIXI.prepare
  26599. */
  26600. var Prepare = /*@__PURE__*/(function (BasePrepare) {
  26601. function Prepare(renderer)
  26602. {
  26603. BasePrepare.call(this, renderer);
  26604. this.uploadHookHelper = this.renderer;
  26605. // Add textures and graphics to upload
  26606. this.registerFindHook(findGraphics);
  26607. this.registerUploadHook(uploadBaseTextures);
  26608. this.registerUploadHook(uploadGraphics);
  26609. }
  26610. if ( BasePrepare ) { Prepare.__proto__ = BasePrepare; }
  26611. Prepare.prototype = Object.create( BasePrepare && BasePrepare.prototype );
  26612. Prepare.prototype.constructor = Prepare;
  26613. return Prepare;
  26614. }(BasePrepare));
  26615. /**
  26616. * Built-in hook to upload PIXI.Texture objects to the GPU.
  26617. *
  26618. * @private
  26619. * @param {PIXI.Renderer} renderer - instance of the webgl renderer
  26620. * @param {PIXI.DisplayObject} item - Item to check
  26621. * @return {boolean} If item was uploaded.
  26622. */
  26623. function uploadBaseTextures(renderer, item)
  26624. {
  26625. if (item instanceof BaseTexture)
  26626. {
  26627. // if the texture already has a GL texture, then the texture has been prepared or rendered
  26628. // before now. If the texture changed, then the changer should be calling texture.update() which
  26629. // reuploads the texture without need for preparing it again
  26630. if (!item._glTextures[renderer.CONTEXT_UID])
  26631. {
  26632. renderer.textureManager.updateTexture(item);
  26633. }
  26634. return true;
  26635. }
  26636. return false;
  26637. }
  26638. /**
  26639. * Built-in hook to upload PIXI.Graphics to the GPU.
  26640. *
  26641. * @private
  26642. * @param {PIXI.Renderer} renderer - instance of the webgl renderer
  26643. * @param {PIXI.DisplayObject} item - Item to check
  26644. * @return {boolean} If item was uploaded.
  26645. */
  26646. function uploadGraphics(renderer, item)
  26647. {
  26648. if (item instanceof Graphics)
  26649. {
  26650. // if the item is not dirty and already has webgl data, then it got prepared or rendered
  26651. // before now and we shouldn't waste time updating it again
  26652. if (item.dirty || item.clearDirty || !item._webGL[renderer.plugins.graphics.CONTEXT_UID])
  26653. {
  26654. renderer.plugins.graphics.updateGraphics(item);
  26655. }
  26656. return true;
  26657. }
  26658. return false;
  26659. }
  26660. /**
  26661. * Built-in hook to find graphics.
  26662. *
  26663. * @private
  26664. * @param {PIXI.DisplayObject} item - Display object to check
  26665. * @param {Array<*>} queue - Collection of items to upload
  26666. * @return {boolean} if a PIXI.Graphics object was found.
  26667. */
  26668. function findGraphics(item, queue)
  26669. {
  26670. if (item instanceof Graphics)
  26671. {
  26672. queue.push(item);
  26673. return true;
  26674. }
  26675. return false;
  26676. }
  26677. /**
  26678. * TimeLimiter limits the number of items handled by a {@link PIXI.BasePrepare} to a specified
  26679. * number of milliseconds per frame.
  26680. *
  26681. * @class
  26682. * @memberof PIXI.prepare
  26683. */
  26684. var TimeLimiter = function TimeLimiter(maxMilliseconds)
  26685. {
  26686. /**
  26687. * The maximum milliseconds that can be spent preparing items each frame.
  26688. * @type {number}
  26689. * @private
  26690. */
  26691. this.maxMilliseconds = maxMilliseconds;
  26692. /**
  26693. * The start time of the current frame.
  26694. * @type {number}
  26695. * @private
  26696. */
  26697. this.frameStart = 0;
  26698. };
  26699. /**
  26700. * Resets any counting properties to start fresh on a new frame.
  26701. */
  26702. TimeLimiter.prototype.beginFrame = function beginFrame ()
  26703. {
  26704. this.frameStart = Date.now();
  26705. };
  26706. /**
  26707. * Checks to see if another item can be uploaded. This should only be called once per item.
  26708. * @return {boolean} If the item is allowed to be uploaded.
  26709. */
  26710. TimeLimiter.prototype.allowedToUpload = function allowedToUpload ()
  26711. {
  26712. return Date.now() - this.frameStart < this.maxMilliseconds;
  26713. };
  26714. var prepare_es = ({
  26715. BasePrepare: BasePrepare,
  26716. CountLimiter: CountLimiter,
  26717. Prepare: Prepare,
  26718. TimeLimiter: TimeLimiter
  26719. });
  26720. /*!
  26721. * @pixi/app - v5.0.4
  26722. * Compiled Fri, 07 Jun 2019 17:17:49 UTC
  26723. *
  26724. * @pixi/app is licensed under the MIT License.
  26725. * http://www.opensource.org/licenses/mit-license
  26726. */
  26727. /**
  26728. * Convenience class to create a new PIXI application.
  26729. *
  26730. * This class automatically creates the renderer, ticker and root container.
  26731. *
  26732. * @example
  26733. * // Create the application
  26734. * const app = new PIXI.Application();
  26735. *
  26736. * // Add the view to the DOM
  26737. * document.body.appendChild(app.view);
  26738. *
  26739. * // ex, add display objects
  26740. * app.stage.addChild(PIXI.Sprite.from('something.png'));
  26741. *
  26742. * @class
  26743. * @memberof PIXI
  26744. */
  26745. var Application = function Application(options)
  26746. {
  26747. var this$1 = this;
  26748. // The default options
  26749. options = Object.assign({
  26750. forceCanvas: false,
  26751. }, options);
  26752. /**
  26753. * WebGL renderer if available, otherwise CanvasRenderer.
  26754. * @member {PIXI.Renderer|PIXI.CanvasRenderer}
  26755. */
  26756. this.renderer = autoDetectRenderer(options);
  26757. /**
  26758. * The root display container that's rendered.
  26759. * @member {PIXI.Container}
  26760. */
  26761. this.stage = new Container();
  26762. // install plugins here
  26763. Application._plugins.forEach(function (plugin) {
  26764. plugin.init.call(this$1, options);
  26765. });
  26766. };
  26767. var prototypeAccessors$8 = { view: { configurable: true },screen: { configurable: true } };
  26768. /**
  26769. * Register a middleware plugin for the application
  26770. * @static
  26771. * @param {PIXI.Application.Plugin} plugin - Plugin being installed
  26772. */
  26773. Application.registerPlugin = function registerPlugin (plugin)
  26774. {
  26775. Application._plugins.push(plugin);
  26776. };
  26777. /**
  26778. * Render the current stage.
  26779. */
  26780. Application.prototype.render = function render ()
  26781. {
  26782. this.renderer.render(this.stage);
  26783. };
  26784. /**
  26785. * Reference to the renderer's canvas element.
  26786. * @member {HTMLCanvasElement}
  26787. * @readonly
  26788. */
  26789. prototypeAccessors$8.view.get = function ()
  26790. {
  26791. return this.renderer.view;
  26792. };
  26793. /**
  26794. * Reference to the renderer's screen rectangle. Its safe to use as `filterArea` or `hitArea` for the whole screen.
  26795. * @member {PIXI.Rectangle}
  26796. * @readonly
  26797. */
  26798. prototypeAccessors$8.screen.get = function ()
  26799. {
  26800. return this.renderer.screen;
  26801. };
  26802. /**
  26803. * Destroy and don't use after this.
  26804. * @param {Boolean} [removeView=false] Automatically remove canvas from DOM.
  26805. * @param {object|boolean} [stageOptions] - Options parameter. A boolean will act as if all options
  26806. * have been set to that value
  26807. * @param {boolean} [stageOptions.children=false] - if set to true, all the children will have their destroy
  26808. * method called as well. 'stageOptions' will be passed on to those calls.
  26809. * @param {boolean} [stageOptions.texture=false] - Only used for child Sprites if stageOptions.children is set
  26810. * to true. Should it destroy the texture of the child sprite
  26811. * @param {boolean} [stageOptions.baseTexture=false] - Only used for child Sprites if stageOptions.children is set
  26812. * to true. Should it destroy the base texture of the child sprite
  26813. */
  26814. Application.prototype.destroy = function destroy (removeView)
  26815. {
  26816. var this$1 = this;
  26817. // Destroy plugins in the opposite order
  26818. // which they were constructed
  26819. var plugins = Application._plugins.slice(0);
  26820. plugins.reverse();
  26821. plugins.forEach(function (plugin) {
  26822. plugin.destroy.call(this$1);
  26823. });
  26824. this.stage.destroy();
  26825. this.stage = null;
  26826. this.renderer.destroy(removeView);
  26827. this.renderer = null;
  26828. this._options = null;
  26829. };
  26830. Object.defineProperties( Application.prototype, prototypeAccessors$8 );
  26831. /**
  26832. * @memberof PIXI.Application
  26833. * @typedef {object} Plugin
  26834. * @property {function} init - Called when Application is constructed, scoped to Application instance.
  26835. * Passes in `options` as the only argument, which are Application constructor options.
  26836. * @property {function} destroy - Called when destroying Application, scoped to Application instance
  26837. */
  26838. /**
  26839. * Collection of installed plugins.
  26840. * @static
  26841. * @private
  26842. * @type {PIXI.Application.Plugin[]}
  26843. */
  26844. Application._plugins = [];
  26845. /**
  26846. * Middleware for for Application's resize functionality
  26847. * @private
  26848. * @class
  26849. */
  26850. var ResizePlugin = function ResizePlugin () {};
  26851. ResizePlugin.init = function init (options)
  26852. {
  26853. var this$1 = this;
  26854. /**
  26855. * The element or window to resize the application to.
  26856. * @type {Window|HTMLElement}
  26857. * @name resizeTo
  26858. * @memberof PIXI.Application#
  26859. */
  26860. Object.defineProperty(this, 'resizeTo',
  26861. {
  26862. set: function set(dom)
  26863. {
  26864. window.removeEventListener('resize', this.resize);
  26865. this._resizeTo = dom;
  26866. if (dom)
  26867. {
  26868. window.addEventListener('resize', this.resize);
  26869. this.resize();
  26870. }
  26871. },
  26872. get: function get()
  26873. {
  26874. return this._resizeTo;
  26875. },
  26876. });
  26877. /**
  26878. * If `resizeTo` is set, calling this function
  26879. * will resize to the width and height of that element.
  26880. * @method PIXI.Application#resize
  26881. */
  26882. this.resize = function () {
  26883. if (this$1._resizeTo)
  26884. {
  26885. // Resize to the window
  26886. if (this$1._resizeTo === window)
  26887. {
  26888. this$1.renderer.resize(
  26889. window.innerWidth,
  26890. window.innerHeight
  26891. );
  26892. }
  26893. // Resize to other HTML entities
  26894. else
  26895. {
  26896. this$1.renderer.resize(
  26897. this$1._resizeTo.clientWidth,
  26898. this$1._resizeTo.clientHeight
  26899. );
  26900. }
  26901. }
  26902. };
  26903. // On resize
  26904. this._resizeTo = null;
  26905. this.resizeTo = options.resizeTo || null;
  26906. };
  26907. /**
  26908. * Clean up the ticker, scoped to application
  26909. * @static
  26910. * @private
  26911. */
  26912. ResizePlugin.destroy = function destroy ()
  26913. {
  26914. this.resizeTo = null;
  26915. this.resize = null;
  26916. };
  26917. Application.registerPlugin(ResizePlugin);
  26918. var miniSignals = createCommonjsModule(function (module, exports) {
  26919. 'use strict';
  26920. Object.defineProperty(exports, '__esModule', {
  26921. value: true
  26922. });
  26923. var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) { descriptor.writable = true; } Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) { defineProperties(Constructor.prototype, protoProps); } if (staticProps) { defineProperties(Constructor, staticProps); } return Constructor; }; })();
  26924. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
  26925. var MiniSignalBinding = (function () {
  26926. function MiniSignalBinding(fn, once, thisArg) {
  26927. if (once === undefined) { once = false; }
  26928. _classCallCheck(this, MiniSignalBinding);
  26929. this._fn = fn;
  26930. this._once = once;
  26931. this._thisArg = thisArg;
  26932. this._next = this._prev = this._owner = null;
  26933. }
  26934. _createClass(MiniSignalBinding, [{
  26935. key: 'detach',
  26936. value: function detach() {
  26937. if (this._owner === null) { return false; }
  26938. this._owner.detach(this);
  26939. return true;
  26940. }
  26941. }]);
  26942. return MiniSignalBinding;
  26943. })();
  26944. function _addMiniSignalBinding(self, node) {
  26945. if (!self._head) {
  26946. self._head = node;
  26947. self._tail = node;
  26948. } else {
  26949. self._tail._next = node;
  26950. node._prev = self._tail;
  26951. self._tail = node;
  26952. }
  26953. node._owner = self;
  26954. return node;
  26955. }
  26956. var MiniSignal = (function () {
  26957. function MiniSignal() {
  26958. _classCallCheck(this, MiniSignal);
  26959. this._head = this._tail = undefined;
  26960. }
  26961. _createClass(MiniSignal, [{
  26962. key: 'handlers',
  26963. value: function handlers() {
  26964. var exists = arguments.length <= 0 || arguments[0] === undefined ? false : arguments[0];
  26965. var node = this._head;
  26966. if (exists) { return !!node; }
  26967. var ee = [];
  26968. while (node) {
  26969. ee.push(node);
  26970. node = node._next;
  26971. }
  26972. return ee;
  26973. }
  26974. }, {
  26975. key: 'has',
  26976. value: function has(node) {
  26977. if (!(node instanceof MiniSignalBinding)) {
  26978. throw new Error('MiniSignal#has(): First arg must be a MiniSignalBinding object.');
  26979. }
  26980. return node._owner === this;
  26981. }
  26982. }, {
  26983. key: 'dispatch',
  26984. value: function dispatch() {
  26985. var arguments$1 = arguments;
  26986. var node = this._head;
  26987. if (!node) { return false; }
  26988. while (node) {
  26989. if (node._once) { this.detach(node); }
  26990. node._fn.apply(node._thisArg, arguments$1);
  26991. node = node._next;
  26992. }
  26993. return true;
  26994. }
  26995. }, {
  26996. key: 'add',
  26997. value: function add(fn) {
  26998. var thisArg = arguments.length <= 1 || arguments[1] === undefined ? null : arguments[1];
  26999. if (typeof fn !== 'function') {
  27000. throw new Error('MiniSignal#add(): First arg must be a Function.');
  27001. }
  27002. return _addMiniSignalBinding(this, new MiniSignalBinding(fn, false, thisArg));
  27003. }
  27004. }, {
  27005. key: 'once',
  27006. value: function once(fn) {
  27007. var thisArg = arguments.length <= 1 || arguments[1] === undefined ? null : arguments[1];
  27008. if (typeof fn !== 'function') {
  27009. throw new Error('MiniSignal#once(): First arg must be a Function.');
  27010. }
  27011. return _addMiniSignalBinding(this, new MiniSignalBinding(fn, true, thisArg));
  27012. }
  27013. }, {
  27014. key: 'detach',
  27015. value: function detach(node) {
  27016. if (!(node instanceof MiniSignalBinding)) {
  27017. throw new Error('MiniSignal#detach(): First arg must be a MiniSignalBinding object.');
  27018. }
  27019. if (node._owner !== this) { return this; }
  27020. if (node._prev) { node._prev._next = node._next; }
  27021. if (node._next) { node._next._prev = node._prev; }
  27022. if (node === this._head) {
  27023. this._head = node._next;
  27024. if (node._next === null) {
  27025. this._tail = null;
  27026. }
  27027. } else if (node === this._tail) {
  27028. this._tail = node._prev;
  27029. this._tail._next = null;
  27030. }
  27031. node._owner = null;
  27032. return this;
  27033. }
  27034. }, {
  27035. key: 'detachAll',
  27036. value: function detachAll() {
  27037. var node = this._head;
  27038. if (!node) { return this; }
  27039. this._head = this._tail = null;
  27040. while (node) {
  27041. node._owner = null;
  27042. node = node._next;
  27043. }
  27044. return this;
  27045. }
  27046. }]);
  27047. return MiniSignal;
  27048. })();
  27049. MiniSignal.MiniSignalBinding = MiniSignalBinding;
  27050. exports['default'] = MiniSignal;
  27051. module.exports = exports['default'];
  27052. });
  27053. var miniSignals$1 = unwrapExports(miniSignals);
  27054. 'use strict';
  27055. var parseUri = function parseURI (str, opts) {
  27056. opts = opts || {};
  27057. var o = {
  27058. key: ['source', 'protocol', 'authority', 'userInfo', 'user', 'password', 'host', 'port', 'relative', 'path', 'directory', 'file', 'query', 'anchor'],
  27059. q: {
  27060. name: 'queryKey',
  27061. parser: /(?:^|&)([^&=]*)=?([^&]*)/g
  27062. },
  27063. parser: {
  27064. strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,
  27065. loose: /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/
  27066. }
  27067. };
  27068. var m = o.parser[opts.strictMode ? 'strict' : 'loose'].exec(str);
  27069. var uri = {};
  27070. var i = 14;
  27071. while (i--) { uri[o.key[i]] = m[i] || ''; }
  27072. uri[o.q.name] = {};
  27073. uri[o.key[12]].replace(o.q.parser, function ($0, $1, $2) {
  27074. if ($1) { uri[o.q.name][$1] = $2; }
  27075. });
  27076. return uri
  27077. };
  27078. var async = createCommonjsModule(function (module, exports) {
  27079. 'use strict';
  27080. exports.__esModule = true;
  27081. exports.eachSeries = eachSeries;
  27082. exports.queue = queue;
  27083. /**
  27084. * Smaller version of the async library constructs.
  27085. *
  27086. * @namespace async
  27087. */
  27088. /**
  27089. * Noop function
  27090. *
  27091. * @ignore
  27092. * @function
  27093. * @memberof async
  27094. */
  27095. function _noop() {} /* empty */
  27096. /**
  27097. * Iterates an array in series.
  27098. *
  27099. * @memberof async
  27100. * @param {Array.<*>} array - Array to iterate.
  27101. * @param {function} iterator - Function to call for each element.
  27102. * @param {function} callback - Function to call when done, or on error.
  27103. * @param {boolean} [deferNext=false] - Break synchronous each loop by calling next with a setTimeout of 1.
  27104. */
  27105. function eachSeries(array, iterator, callback, deferNext) {
  27106. var i = 0;
  27107. var len = array.length;
  27108. (function next(err) {
  27109. if (err || i === len) {
  27110. if (callback) {
  27111. callback(err);
  27112. }
  27113. return;
  27114. }
  27115. if (deferNext) {
  27116. setTimeout(function () {
  27117. iterator(array[i++], next);
  27118. }, 1);
  27119. } else {
  27120. iterator(array[i++], next);
  27121. }
  27122. })();
  27123. }
  27124. /**
  27125. * Ensures a function is only called once.
  27126. *
  27127. * @ignore
  27128. * @memberof async
  27129. * @param {function} fn - The function to wrap.
  27130. * @return {function} The wrapping function.
  27131. */
  27132. function onlyOnce(fn) {
  27133. return function onceWrapper() {
  27134. if (fn === null) {
  27135. throw new Error('Callback was already called.');
  27136. }
  27137. var callFn = fn;
  27138. fn = null;
  27139. callFn.apply(this, arguments);
  27140. };
  27141. }
  27142. /**
  27143. * Async queue implementation,
  27144. *
  27145. * @memberof async
  27146. * @param {function} worker - The worker function to call for each task.
  27147. * @param {number} concurrency - How many workers to run in parrallel.
  27148. * @return {*} The async queue object.
  27149. */
  27150. function queue(worker, concurrency) {
  27151. if (concurrency == null) {
  27152. // eslint-disable-line no-eq-null,eqeqeq
  27153. concurrency = 1;
  27154. } else if (concurrency === 0) {
  27155. throw new Error('Concurrency must not be zero');
  27156. }
  27157. var workers = 0;
  27158. var q = {
  27159. _tasks: [],
  27160. concurrency: concurrency,
  27161. saturated: _noop,
  27162. unsaturated: _noop,
  27163. buffer: concurrency / 4,
  27164. empty: _noop,
  27165. drain: _noop,
  27166. error: _noop,
  27167. started: false,
  27168. paused: false,
  27169. push: function push(data, callback) {
  27170. _insert(data, false, callback);
  27171. },
  27172. kill: function kill() {
  27173. workers = 0;
  27174. q.drain = _noop;
  27175. q.started = false;
  27176. q._tasks = [];
  27177. },
  27178. unshift: function unshift(data, callback) {
  27179. _insert(data, true, callback);
  27180. },
  27181. process: function process() {
  27182. while (!q.paused && workers < q.concurrency && q._tasks.length) {
  27183. var task = q._tasks.shift();
  27184. if (q._tasks.length === 0) {
  27185. q.empty();
  27186. }
  27187. workers += 1;
  27188. if (workers === q.concurrency) {
  27189. q.saturated();
  27190. }
  27191. worker(task.data, onlyOnce(_next(task)));
  27192. }
  27193. },
  27194. length: function length() {
  27195. return q._tasks.length;
  27196. },
  27197. running: function running() {
  27198. return workers;
  27199. },
  27200. idle: function idle() {
  27201. return q._tasks.length + workers === 0;
  27202. },
  27203. pause: function pause() {
  27204. if (q.paused === true) {
  27205. return;
  27206. }
  27207. q.paused = true;
  27208. },
  27209. resume: function resume() {
  27210. if (q.paused === false) {
  27211. return;
  27212. }
  27213. q.paused = false;
  27214. // Need to call q.process once per concurrent
  27215. // worker to preserve full concurrency after pause
  27216. for (var w = 1; w <= q.concurrency; w++) {
  27217. q.process();
  27218. }
  27219. }
  27220. };
  27221. function _insert(data, insertAtFront, callback) {
  27222. if (callback != null && typeof callback !== 'function') {
  27223. // eslint-disable-line no-eq-null,eqeqeq
  27224. throw new Error('task callback must be a function');
  27225. }
  27226. q.started = true;
  27227. if (data == null && q.idle()) {
  27228. // eslint-disable-line no-eq-null,eqeqeq
  27229. // call drain immediately if there are no tasks
  27230. setTimeout(function () {
  27231. return q.drain();
  27232. }, 1);
  27233. return;
  27234. }
  27235. var item = {
  27236. data: data,
  27237. callback: typeof callback === 'function' ? callback : _noop
  27238. };
  27239. if (insertAtFront) {
  27240. q._tasks.unshift(item);
  27241. } else {
  27242. q._tasks.push(item);
  27243. }
  27244. setTimeout(function () {
  27245. return q.process();
  27246. }, 1);
  27247. }
  27248. function _next(task) {
  27249. return function next() {
  27250. workers -= 1;
  27251. task.callback.apply(task, arguments);
  27252. if (arguments[0] != null) {
  27253. // eslint-disable-line no-eq-null,eqeqeq
  27254. q.error(arguments[0], task.data);
  27255. }
  27256. if (workers <= q.concurrency - q.buffer) {
  27257. q.unsaturated();
  27258. }
  27259. if (q.idle()) {
  27260. q.drain();
  27261. }
  27262. q.process();
  27263. };
  27264. }
  27265. return q;
  27266. }
  27267. });
  27268. var async$1 = unwrapExports(async);
  27269. var async_1 = async.eachSeries;
  27270. var async_2 = async.queue;
  27271. var Resource_1 = createCommonjsModule(function (module, exports) {
  27272. 'use strict';
  27273. exports.__esModule = true;
  27274. exports.Resource = undefined;
  27275. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) { descriptor.writable = true; } Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) { defineProperties(Constructor.prototype, protoProps); } if (staticProps) { defineProperties(Constructor, staticProps); } return Constructor; }; }();
  27276. var _parseUri2 = _interopRequireDefault(parseUri);
  27277. var _miniSignals2 = _interopRequireDefault(miniSignals);
  27278. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  27279. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  27280. // tests if CORS is supported in XHR, if not we need to use XDR
  27281. var useXdr = !!(window.XDomainRequest && !('withCredentials' in new XMLHttpRequest()));
  27282. var tempAnchor = null;
  27283. // some status constants
  27284. var STATUS_NONE = 0;
  27285. var STATUS_OK = 200;
  27286. var STATUS_EMPTY = 204;
  27287. var STATUS_IE_BUG_EMPTY = 1223;
  27288. var STATUS_TYPE_OK = 2;
  27289. // noop
  27290. function _noop() {} /* empty */
  27291. /**
  27292. * Manages the state and loading of a resource and all child resources.
  27293. *
  27294. * @class
  27295. */
  27296. var Resource = exports.Resource = function () {
  27297. /**
  27298. * Sets the load type to be used for a specific extension.
  27299. *
  27300. * @static
  27301. * @param {string} extname - The extension to set the type for, e.g. "png" or "fnt"
  27302. * @param {Resource.LOAD_TYPE} loadType - The load type to set it to.
  27303. */
  27304. Resource.setExtensionLoadType = function setExtensionLoadType(extname, loadType) {
  27305. setExtMap(Resource._loadTypeMap, extname, loadType);
  27306. };
  27307. /**
  27308. * Sets the load type to be used for a specific extension.
  27309. *
  27310. * @static
  27311. * @param {string} extname - The extension to set the type for, e.g. "png" or "fnt"
  27312. * @param {Resource.XHR_RESPONSE_TYPE} xhrType - The xhr type to set it to.
  27313. */
  27314. Resource.setExtensionXhrType = function setExtensionXhrType(extname, xhrType) {
  27315. setExtMap(Resource._xhrTypeMap, extname, xhrType);
  27316. };
  27317. /**
  27318. * @param {string} name - The name of the resource to load.
  27319. * @param {string|string[]} url - The url for this resource, for audio/video loads you can pass
  27320. * an array of sources.
  27321. * @param {object} [options] - The options for the load.
  27322. * @param {string|boolean} [options.crossOrigin] - Is this request cross-origin? Default is to
  27323. * determine automatically.
  27324. * @param {number} [options.timeout=0] - A timeout in milliseconds for the load. If the load takes
  27325. * longer than this time it is cancelled and the load is considered a failure. If this value is
  27326. * set to `0` then there is no explicit timeout.
  27327. * @param {Resource.LOAD_TYPE} [options.loadType=Resource.LOAD_TYPE.XHR] - How should this resource
  27328. * be loaded?
  27329. * @param {Resource.XHR_RESPONSE_TYPE} [options.xhrType=Resource.XHR_RESPONSE_TYPE.DEFAULT] - How
  27330. * should the data being loaded be interpreted when using XHR?
  27331. * @param {Resource.IMetadata} [options.metadata] - Extra configuration for middleware and the Resource object.
  27332. */
  27333. function Resource(name, url, options) {
  27334. _classCallCheck(this, Resource);
  27335. if (typeof name !== 'string' || typeof url !== 'string') {
  27336. throw new Error('Both name and url are required for constructing a resource.');
  27337. }
  27338. options = options || {};
  27339. /**
  27340. * The state flags of this resource.
  27341. *
  27342. * @private
  27343. * @member {number}
  27344. */
  27345. this._flags = 0;
  27346. // set data url flag, needs to be set early for some _determineX checks to work.
  27347. this._setFlag(Resource.STATUS_FLAGS.DATA_URL, url.indexOf('data:') === 0);
  27348. /**
  27349. * The name of this resource.
  27350. *
  27351. * @readonly
  27352. * @member {string}
  27353. */
  27354. this.name = name;
  27355. /**
  27356. * The url used to load this resource.
  27357. *
  27358. * @readonly
  27359. * @member {string}
  27360. */
  27361. this.url = url;
  27362. /**
  27363. * The extension used to load this resource.
  27364. *
  27365. * @readonly
  27366. * @member {string}
  27367. */
  27368. this.extension = this._getExtension();
  27369. /**
  27370. * The data that was loaded by the resource.
  27371. *
  27372. * @member {any}
  27373. */
  27374. this.data = null;
  27375. /**
  27376. * Is this request cross-origin? If unset, determined automatically.
  27377. *
  27378. * @member {string}
  27379. */
  27380. this.crossOrigin = options.crossOrigin === true ? 'anonymous' : options.crossOrigin;
  27381. /**
  27382. * A timeout in milliseconds for the load. If the load takes longer than this time
  27383. * it is cancelled and the load is considered a failure. If this value is set to `0`
  27384. * then there is no explicit timeout.
  27385. *
  27386. * @member {number}
  27387. */
  27388. this.timeout = options.timeout || 0;
  27389. /**
  27390. * The method of loading to use for this resource.
  27391. *
  27392. * @member {Resource.LOAD_TYPE}
  27393. */
  27394. this.loadType = options.loadType || this._determineLoadType();
  27395. /**
  27396. * The type used to load the resource via XHR. If unset, determined automatically.
  27397. *
  27398. * @member {string}
  27399. */
  27400. this.xhrType = options.xhrType;
  27401. /**
  27402. * Extra info for middleware, and controlling specifics about how the resource loads.
  27403. *
  27404. * Note that if you pass in a `loadElement`, the Resource class takes ownership of it.
  27405. * Meaning it will modify it as it sees fit.
  27406. *
  27407. * @member {Resource.IMetadata}
  27408. */
  27409. this.metadata = options.metadata || {};
  27410. /**
  27411. * The error that occurred while loading (if any).
  27412. *
  27413. * @readonly
  27414. * @member {Error}
  27415. */
  27416. this.error = null;
  27417. /**
  27418. * The XHR object that was used to load this resource. This is only set
  27419. * when `loadType` is `Resource.LOAD_TYPE.XHR`.
  27420. *
  27421. * @readonly
  27422. * @member {XMLHttpRequest}
  27423. */
  27424. this.xhr = null;
  27425. /**
  27426. * The child resources this resource owns.
  27427. *
  27428. * @readonly
  27429. * @member {Resource[]}
  27430. */
  27431. this.children = [];
  27432. /**
  27433. * The resource type.
  27434. *
  27435. * @readonly
  27436. * @member {Resource.TYPE}
  27437. */
  27438. this.type = Resource.TYPE.UNKNOWN;
  27439. /**
  27440. * The progress chunk owned by this resource.
  27441. *
  27442. * @readonly
  27443. * @member {number}
  27444. */
  27445. this.progressChunk = 0;
  27446. /**
  27447. * The `dequeue` method that will be used a storage place for the async queue dequeue method
  27448. * used privately by the loader.
  27449. *
  27450. * @private
  27451. * @member {function}
  27452. */
  27453. this._dequeue = _noop;
  27454. /**
  27455. * Used a storage place for the on load binding used privately by the loader.
  27456. *
  27457. * @private
  27458. * @member {function}
  27459. */
  27460. this._onLoadBinding = null;
  27461. /**
  27462. * The timer for element loads to check if they timeout.
  27463. *
  27464. * @private
  27465. * @member {number}
  27466. */
  27467. this._elementTimer = 0;
  27468. /**
  27469. * The `complete` function bound to this resource's context.
  27470. *
  27471. * @private
  27472. * @member {function}
  27473. */
  27474. this._boundComplete = this.complete.bind(this);
  27475. /**
  27476. * The `_onError` function bound to this resource's context.
  27477. *
  27478. * @private
  27479. * @member {function}
  27480. */
  27481. this._boundOnError = this._onError.bind(this);
  27482. /**
  27483. * The `_onProgress` function bound to this resource's context.
  27484. *
  27485. * @private
  27486. * @member {function}
  27487. */
  27488. this._boundOnProgress = this._onProgress.bind(this);
  27489. /**
  27490. * The `_onTimeout` function bound to this resource's context.
  27491. *
  27492. * @private
  27493. * @member {function}
  27494. */
  27495. this._boundOnTimeout = this._onTimeout.bind(this);
  27496. // xhr callbacks
  27497. this._boundXhrOnError = this._xhrOnError.bind(this);
  27498. this._boundXhrOnTimeout = this._xhrOnTimeout.bind(this);
  27499. this._boundXhrOnAbort = this._xhrOnAbort.bind(this);
  27500. this._boundXhrOnLoad = this._xhrOnLoad.bind(this);
  27501. /**
  27502. * Dispatched when the resource beings to load.
  27503. *
  27504. * The callback looks like {@link Resource.OnStartSignal}.
  27505. *
  27506. * @member {Signal<Resource.OnStartSignal>}
  27507. */
  27508. this.onStart = new _miniSignals2.default();
  27509. /**
  27510. * Dispatched each time progress of this resource load updates.
  27511. * Not all resources types and loader systems can support this event
  27512. * so sometimes it may not be available. If the resource
  27513. * is being loaded on a modern browser, using XHR, and the remote server
  27514. * properly sets Content-Length headers, then this will be available.
  27515. *
  27516. * The callback looks like {@link Resource.OnProgressSignal}.
  27517. *
  27518. * @member {Signal<Resource.OnProgressSignal>}
  27519. */
  27520. this.onProgress = new _miniSignals2.default();
  27521. /**
  27522. * Dispatched once this resource has loaded, if there was an error it will
  27523. * be in the `error` property.
  27524. *
  27525. * The callback looks like {@link Resource.OnCompleteSignal}.
  27526. *
  27527. * @member {Signal<Resource.OnCompleteSignal>}
  27528. */
  27529. this.onComplete = new _miniSignals2.default();
  27530. /**
  27531. * Dispatched after this resource has had all the *after* middleware run on it.
  27532. *
  27533. * The callback looks like {@link Resource.OnCompleteSignal}.
  27534. *
  27535. * @member {Signal<Resource.OnCompleteSignal>}
  27536. */
  27537. this.onAfterMiddleware = new _miniSignals2.default();
  27538. }
  27539. /**
  27540. * When the resource starts to load.
  27541. *
  27542. * @memberof Resource
  27543. * @callback OnStartSignal
  27544. * @param {Resource} resource - The resource that the event happened on.
  27545. */
  27546. /**
  27547. * When the resource reports loading progress.
  27548. *
  27549. * @memberof Resource
  27550. * @callback OnProgressSignal
  27551. * @param {Resource} resource - The resource that the event happened on.
  27552. * @param {number} percentage - The progress of the load in the range [0, 1].
  27553. */
  27554. /**
  27555. * When the resource finishes loading.
  27556. *
  27557. * @memberof Resource
  27558. * @callback OnCompleteSignal
  27559. * @param {Resource} resource - The resource that the event happened on.
  27560. */
  27561. /**
  27562. * @memberof Resource
  27563. * @typedef {object} IMetadata
  27564. * @property {HTMLImageElement|HTMLAudioElement|HTMLVideoElement} [loadElement=null] - The
  27565. * element to use for loading, instead of creating one.
  27566. * @property {boolean} [skipSource=false] - Skips adding source(s) to the load element. This
  27567. * is useful if you want to pass in a `loadElement` that you already added load sources to.
  27568. * @property {string|string[]} [mimeType] - The mime type to use for the source element
  27569. * of a video/audio elment. If the urls are an array, you can pass this as an array as well
  27570. * where each index is the mime type to use for the corresponding url index.
  27571. */
  27572. /**
  27573. * Stores whether or not this url is a data url.
  27574. *
  27575. * @readonly
  27576. * @member {boolean}
  27577. */
  27578. /**
  27579. * Marks the resource as complete.
  27580. *
  27581. */
  27582. Resource.prototype.complete = function complete() {
  27583. this._clearEvents();
  27584. this._finish();
  27585. };
  27586. /**
  27587. * Aborts the loading of this resource, with an optional message.
  27588. *
  27589. * @param {string} message - The message to use for the error
  27590. */
  27591. Resource.prototype.abort = function abort(message) {
  27592. // abort can be called multiple times, ignore subsequent calls.
  27593. if (this.error) {
  27594. return;
  27595. }
  27596. // store error
  27597. this.error = new Error(message);
  27598. // clear events before calling aborts
  27599. this._clearEvents();
  27600. // abort the actual loading
  27601. if (this.xhr) {
  27602. this.xhr.abort();
  27603. } else if (this.xdr) {
  27604. this.xdr.abort();
  27605. } else if (this.data) {
  27606. // single source
  27607. if (this.data.src) {
  27608. this.data.src = Resource.EMPTY_GIF;
  27609. }
  27610. // multi-source
  27611. else {
  27612. while (this.data.firstChild) {
  27613. this.data.removeChild(this.data.firstChild);
  27614. }
  27615. }
  27616. }
  27617. // done now.
  27618. this._finish();
  27619. };
  27620. /**
  27621. * Kicks off loading of this resource. This method is asynchronous.
  27622. *
  27623. * @param {Resource.OnCompleteSignal} [cb] - Optional callback to call once the resource is loaded.
  27624. */
  27625. Resource.prototype.load = function load(cb) {
  27626. var _this = this;
  27627. if (this.isLoading) {
  27628. return;
  27629. }
  27630. if (this.isComplete) {
  27631. if (cb) {
  27632. setTimeout(function () {
  27633. return cb(_this);
  27634. }, 1);
  27635. }
  27636. return;
  27637. } else if (cb) {
  27638. this.onComplete.once(cb);
  27639. }
  27640. this._setFlag(Resource.STATUS_FLAGS.LOADING, true);
  27641. this.onStart.dispatch(this);
  27642. // if unset, determine the value
  27643. if (this.crossOrigin === false || typeof this.crossOrigin !== 'string') {
  27644. this.crossOrigin = this._determineCrossOrigin(this.url);
  27645. }
  27646. switch (this.loadType) {
  27647. case Resource.LOAD_TYPE.IMAGE:
  27648. this.type = Resource.TYPE.IMAGE;
  27649. this._loadElement('image');
  27650. break;
  27651. case Resource.LOAD_TYPE.AUDIO:
  27652. this.type = Resource.TYPE.AUDIO;
  27653. this._loadSourceElement('audio');
  27654. break;
  27655. case Resource.LOAD_TYPE.VIDEO:
  27656. this.type = Resource.TYPE.VIDEO;
  27657. this._loadSourceElement('video');
  27658. break;
  27659. case Resource.LOAD_TYPE.XHR:
  27660. /* falls through */
  27661. default:
  27662. if (useXdr && this.crossOrigin) {
  27663. this._loadXdr();
  27664. } else {
  27665. this._loadXhr();
  27666. }
  27667. break;
  27668. }
  27669. };
  27670. /**
  27671. * Checks if the flag is set.
  27672. *
  27673. * @private
  27674. * @param {number} flag - The flag to check.
  27675. * @return {boolean} True if the flag is set.
  27676. */
  27677. Resource.prototype._hasFlag = function _hasFlag(flag) {
  27678. return (this._flags & flag) !== 0;
  27679. };
  27680. /**
  27681. * (Un)Sets the flag.
  27682. *
  27683. * @private
  27684. * @param {number} flag - The flag to (un)set.
  27685. * @param {boolean} value - Whether to set or (un)set the flag.
  27686. */
  27687. Resource.prototype._setFlag = function _setFlag(flag, value) {
  27688. this._flags = value ? this._flags | flag : this._flags & ~flag;
  27689. };
  27690. /**
  27691. * Clears all the events from the underlying loading source.
  27692. *
  27693. * @private
  27694. */
  27695. Resource.prototype._clearEvents = function _clearEvents() {
  27696. clearTimeout(this._elementTimer);
  27697. if (this.data && this.data.removeEventListener) {
  27698. this.data.removeEventListener('error', this._boundOnError, false);
  27699. this.data.removeEventListener('load', this._boundComplete, false);
  27700. this.data.removeEventListener('progress', this._boundOnProgress, false);
  27701. this.data.removeEventListener('canplaythrough', this._boundComplete, false);
  27702. }
  27703. if (this.xhr) {
  27704. if (this.xhr.removeEventListener) {
  27705. this.xhr.removeEventListener('error', this._boundXhrOnError, false);
  27706. this.xhr.removeEventListener('timeout', this._boundXhrOnTimeout, false);
  27707. this.xhr.removeEventListener('abort', this._boundXhrOnAbort, false);
  27708. this.xhr.removeEventListener('progress', this._boundOnProgress, false);
  27709. this.xhr.removeEventListener('load', this._boundXhrOnLoad, false);
  27710. } else {
  27711. this.xhr.onerror = null;
  27712. this.xhr.ontimeout = null;
  27713. this.xhr.onprogress = null;
  27714. this.xhr.onload = null;
  27715. }
  27716. }
  27717. };
  27718. /**
  27719. * Finalizes the load.
  27720. *
  27721. * @private
  27722. */
  27723. Resource.prototype._finish = function _finish() {
  27724. if (this.isComplete) {
  27725. throw new Error('Complete called again for an already completed resource.');
  27726. }
  27727. this._setFlag(Resource.STATUS_FLAGS.COMPLETE, true);
  27728. this._setFlag(Resource.STATUS_FLAGS.LOADING, false);
  27729. this.onComplete.dispatch(this);
  27730. };
  27731. /**
  27732. * Loads this resources using an element that has a single source,
  27733. * like an HTMLImageElement.
  27734. *
  27735. * @private
  27736. * @param {string} type - The type of element to use.
  27737. */
  27738. Resource.prototype._loadElement = function _loadElement(type) {
  27739. if (this.metadata.loadElement) {
  27740. this.data = this.metadata.loadElement;
  27741. } else if (type === 'image' && typeof window.Image !== 'undefined') {
  27742. this.data = new Image();
  27743. } else {
  27744. this.data = document.createElement(type);
  27745. }
  27746. if (this.crossOrigin) {
  27747. this.data.crossOrigin = this.crossOrigin;
  27748. }
  27749. if (!this.metadata.skipSource) {
  27750. this.data.src = this.url;
  27751. }
  27752. this.data.addEventListener('error', this._boundOnError, false);
  27753. this.data.addEventListener('load', this._boundComplete, false);
  27754. this.data.addEventListener('progress', this._boundOnProgress, false);
  27755. if (this.timeout) {
  27756. this._elementTimer = setTimeout(this._boundOnTimeout, this.timeout);
  27757. }
  27758. };
  27759. /**
  27760. * Loads this resources using an element that has multiple sources,
  27761. * like an HTMLAudioElement or HTMLVideoElement.
  27762. *
  27763. * @private
  27764. * @param {string} type - The type of element to use.
  27765. */
  27766. Resource.prototype._loadSourceElement = function _loadSourceElement(type) {
  27767. if (this.metadata.loadElement) {
  27768. this.data = this.metadata.loadElement;
  27769. } else if (type === 'audio' && typeof window.Audio !== 'undefined') {
  27770. this.data = new Audio();
  27771. } else {
  27772. this.data = document.createElement(type);
  27773. }
  27774. if (this.data === null) {
  27775. this.abort('Unsupported element: ' + type);
  27776. return;
  27777. }
  27778. if (this.crossOrigin) {
  27779. this.data.crossOrigin = this.crossOrigin;
  27780. }
  27781. if (!this.metadata.skipSource) {
  27782. // support for CocoonJS Canvas+ runtime, lacks document.createElement('source')
  27783. if (navigator.isCocoonJS) {
  27784. this.data.src = Array.isArray(this.url) ? this.url[0] : this.url;
  27785. } else if (Array.isArray(this.url)) {
  27786. var mimeTypes = this.metadata.mimeType;
  27787. for (var i = 0; i < this.url.length; ++i) {
  27788. this.data.appendChild(this._createSource(type, this.url[i], Array.isArray(mimeTypes) ? mimeTypes[i] : mimeTypes));
  27789. }
  27790. } else {
  27791. var _mimeTypes = this.metadata.mimeType;
  27792. this.data.appendChild(this._createSource(type, this.url, Array.isArray(_mimeTypes) ? _mimeTypes[0] : _mimeTypes));
  27793. }
  27794. }
  27795. this.data.addEventListener('error', this._boundOnError, false);
  27796. this.data.addEventListener('load', this._boundComplete, false);
  27797. this.data.addEventListener('progress', this._boundOnProgress, false);
  27798. this.data.addEventListener('canplaythrough', this._boundComplete, false);
  27799. this.data.load();
  27800. if (this.timeout) {
  27801. this._elementTimer = setTimeout(this._boundOnTimeout, this.timeout);
  27802. }
  27803. };
  27804. /**
  27805. * Loads this resources using an XMLHttpRequest.
  27806. *
  27807. * @private
  27808. */
  27809. Resource.prototype._loadXhr = function _loadXhr() {
  27810. // if unset, determine the value
  27811. if (typeof this.xhrType !== 'string') {
  27812. this.xhrType = this._determineXhrType();
  27813. }
  27814. var xhr = this.xhr = new XMLHttpRequest();
  27815. // set the request type and url
  27816. xhr.open('GET', this.url, true);
  27817. xhr.timeout = this.timeout;
  27818. // load json as text and parse it ourselves. We do this because some browsers
  27819. // *cough* safari *cough* can't deal with it.
  27820. if (this.xhrType === Resource.XHR_RESPONSE_TYPE.JSON || this.xhrType === Resource.XHR_RESPONSE_TYPE.DOCUMENT) {
  27821. xhr.responseType = Resource.XHR_RESPONSE_TYPE.TEXT;
  27822. } else {
  27823. xhr.responseType = this.xhrType;
  27824. }
  27825. xhr.addEventListener('error', this._boundXhrOnError, false);
  27826. xhr.addEventListener('timeout', this._boundXhrOnTimeout, false);
  27827. xhr.addEventListener('abort', this._boundXhrOnAbort, false);
  27828. xhr.addEventListener('progress', this._boundOnProgress, false);
  27829. xhr.addEventListener('load', this._boundXhrOnLoad, false);
  27830. xhr.send();
  27831. };
  27832. /**
  27833. * Loads this resources using an XDomainRequest. This is here because we need to support IE9 (gross).
  27834. *
  27835. * @private
  27836. */
  27837. Resource.prototype._loadXdr = function _loadXdr() {
  27838. // if unset, determine the value
  27839. if (typeof this.xhrType !== 'string') {
  27840. this.xhrType = this._determineXhrType();
  27841. }
  27842. var xdr = this.xhr = new XDomainRequest(); // eslint-disable-line no-undef
  27843. // XDomainRequest has a few quirks. Occasionally it will abort requests
  27844. // A way to avoid this is to make sure ALL callbacks are set even if not used
  27845. // More info here: http://stackoverflow.com/questions/15786966/xdomainrequest-aborts-post-on-ie-9
  27846. xdr.timeout = this.timeout || 5000; // XDR needs a timeout value or it breaks in IE9
  27847. xdr.onerror = this._boundXhrOnError;
  27848. xdr.ontimeout = this._boundXhrOnTimeout;
  27849. xdr.onprogress = this._boundOnProgress;
  27850. xdr.onload = this._boundXhrOnLoad;
  27851. xdr.open('GET', this.url, true);
  27852. // Note: The xdr.send() call is wrapped in a timeout to prevent an
  27853. // issue with the interface where some requests are lost if multiple
  27854. // XDomainRequests are being sent at the same time.
  27855. // Some info here: https://github.com/photonstorm/phaser/issues/1248
  27856. setTimeout(function () {
  27857. return xdr.send();
  27858. }, 1);
  27859. };
  27860. /**
  27861. * Creates a source used in loading via an element.
  27862. *
  27863. * @private
  27864. * @param {string} type - The element type (video or audio).
  27865. * @param {string} url - The source URL to load from.
  27866. * @param {string} [mime] - The mime type of the video
  27867. * @return {HTMLSourceElement} The source element.
  27868. */
  27869. Resource.prototype._createSource = function _createSource(type, url, mime) {
  27870. if (!mime) {
  27871. mime = type + '/' + this._getExtension(url);
  27872. }
  27873. var source = document.createElement('source');
  27874. source.src = url;
  27875. source.type = mime;
  27876. return source;
  27877. };
  27878. /**
  27879. * Called if a load errors out.
  27880. *
  27881. * @param {Event} event - The error event from the element that emits it.
  27882. * @private
  27883. */
  27884. Resource.prototype._onError = function _onError(event) {
  27885. this.abort('Failed to load element using: ' + event.target.nodeName);
  27886. };
  27887. /**
  27888. * Called if a load progress event fires for an element or xhr/xdr.
  27889. *
  27890. * @private
  27891. * @param {XMLHttpRequestProgressEvent|Event} event - Progress event.
  27892. */
  27893. Resource.prototype._onProgress = function _onProgress(event) {
  27894. if (event && event.lengthComputable) {
  27895. this.onProgress.dispatch(this, event.loaded / event.total);
  27896. }
  27897. };
  27898. /**
  27899. * Called if a timeout event fires for an element.
  27900. *
  27901. * @private
  27902. */
  27903. Resource.prototype._onTimeout = function _onTimeout() {
  27904. this.abort('Load timed out.');
  27905. };
  27906. /**
  27907. * Called if an error event fires for xhr/xdr.
  27908. *
  27909. * @private
  27910. */
  27911. Resource.prototype._xhrOnError = function _xhrOnError() {
  27912. var xhr = this.xhr;
  27913. this.abort(reqType(xhr) + ' Request failed. Status: ' + xhr.status + ', text: "' + xhr.statusText + '"');
  27914. };
  27915. /**
  27916. * Called if an error event fires for xhr/xdr.
  27917. *
  27918. * @private
  27919. */
  27920. Resource.prototype._xhrOnTimeout = function _xhrOnTimeout() {
  27921. var xhr = this.xhr;
  27922. this.abort(reqType(xhr) + ' Request timed out.');
  27923. };
  27924. /**
  27925. * Called if an abort event fires for xhr/xdr.
  27926. *
  27927. * @private
  27928. */
  27929. Resource.prototype._xhrOnAbort = function _xhrOnAbort() {
  27930. var xhr = this.xhr;
  27931. this.abort(reqType(xhr) + ' Request was aborted by the user.');
  27932. };
  27933. /**
  27934. * Called when data successfully loads from an xhr/xdr request.
  27935. *
  27936. * @private
  27937. * @param {XMLHttpRequestLoadEvent|Event} event - Load event
  27938. */
  27939. Resource.prototype._xhrOnLoad = function _xhrOnLoad() {
  27940. var xhr = this.xhr;
  27941. var text = '';
  27942. var status = typeof xhr.status === 'undefined' ? STATUS_OK : xhr.status; // XDR has no `.status`, assume 200.
  27943. // responseText is accessible only if responseType is '' or 'text' and on older browsers
  27944. if (xhr.responseType === '' || xhr.responseType === 'text' || typeof xhr.responseType === 'undefined') {
  27945. text = xhr.responseText;
  27946. }
  27947. // status can be 0 when using the `file://` protocol so we also check if a response is set.
  27948. // If it has a response, we assume 200; otherwise a 0 status code with no contents is an aborted request.
  27949. if (status === STATUS_NONE && (text.length > 0 || xhr.responseType === Resource.XHR_RESPONSE_TYPE.BUFFER)) {
  27950. status = STATUS_OK;
  27951. }
  27952. // handle IE9 bug: http://stackoverflow.com/questions/10046972/msie-returns-status-code-of-1223-for-ajax-request
  27953. else if (status === STATUS_IE_BUG_EMPTY) {
  27954. status = STATUS_EMPTY;
  27955. }
  27956. var statusType = status / 100 | 0;
  27957. if (statusType === STATUS_TYPE_OK) {
  27958. // if text, just return it
  27959. if (this.xhrType === Resource.XHR_RESPONSE_TYPE.TEXT) {
  27960. this.data = text;
  27961. this.type = Resource.TYPE.TEXT;
  27962. }
  27963. // if json, parse into json object
  27964. else if (this.xhrType === Resource.XHR_RESPONSE_TYPE.JSON) {
  27965. try {
  27966. this.data = JSON.parse(text);
  27967. this.type = Resource.TYPE.JSON;
  27968. } catch (e) {
  27969. this.abort('Error trying to parse loaded json: ' + e);
  27970. return;
  27971. }
  27972. }
  27973. // if xml, parse into an xml document or div element
  27974. else if (this.xhrType === Resource.XHR_RESPONSE_TYPE.DOCUMENT) {
  27975. try {
  27976. if (window.DOMParser) {
  27977. var domparser = new DOMParser();
  27978. this.data = domparser.parseFromString(text, 'text/xml');
  27979. } else {
  27980. var div = document.createElement('div');
  27981. div.innerHTML = text;
  27982. this.data = div;
  27983. }
  27984. this.type = Resource.TYPE.XML;
  27985. } catch (e) {
  27986. this.abort('Error trying to parse loaded xml: ' + e);
  27987. return;
  27988. }
  27989. }
  27990. // other types just return the response
  27991. else {
  27992. this.data = xhr.response || text;
  27993. }
  27994. } else {
  27995. this.abort('[' + xhr.status + '] ' + xhr.statusText + ': ' + xhr.responseURL);
  27996. return;
  27997. }
  27998. this.complete();
  27999. };
  28000. /**
  28001. * Sets the `crossOrigin` property for this resource based on if the url
  28002. * for this resource is cross-origin. If crossOrigin was manually set, this
  28003. * function does nothing.
  28004. *
  28005. * @private
  28006. * @param {string} url - The url to test.
  28007. * @param {object} [loc=window.location] - The location object to test against.
  28008. * @return {string} The crossOrigin value to use (or empty string for none).
  28009. */
  28010. Resource.prototype._determineCrossOrigin = function _determineCrossOrigin(url, loc) {
  28011. // data: and javascript: urls are considered same-origin
  28012. if (url.indexOf('data:') === 0) {
  28013. return '';
  28014. }
  28015. // A sandboxed iframe without the 'allow-same-origin' attribute will have a special
  28016. // origin designed not to match window.location.origin, and will always require
  28017. // crossOrigin requests regardless of whether the location matches.
  28018. if (window.origin !== window.location.origin) {
  28019. return 'anonymous';
  28020. }
  28021. // default is window.location
  28022. loc = loc || window.location;
  28023. if (!tempAnchor) {
  28024. tempAnchor = document.createElement('a');
  28025. }
  28026. // let the browser determine the full href for the url of this resource and then
  28027. // parse with the node url lib, we can't use the properties of the anchor element
  28028. // because they don't work in IE9 :(
  28029. tempAnchor.href = url;
  28030. url = (0, _parseUri2.default)(tempAnchor.href, { strictMode: true });
  28031. var samePort = !url.port && loc.port === '' || url.port === loc.port;
  28032. var protocol = url.protocol ? url.protocol + ':' : '';
  28033. // if cross origin
  28034. if (url.host !== loc.hostname || !samePort || protocol !== loc.protocol) {
  28035. return 'anonymous';
  28036. }
  28037. return '';
  28038. };
  28039. /**
  28040. * Determines the responseType of an XHR request based on the extension of the
  28041. * resource being loaded.
  28042. *
  28043. * @private
  28044. * @return {Resource.XHR_RESPONSE_TYPE} The responseType to use.
  28045. */
  28046. Resource.prototype._determineXhrType = function _determineXhrType() {
  28047. return Resource._xhrTypeMap[this.extension] || Resource.XHR_RESPONSE_TYPE.TEXT;
  28048. };
  28049. /**
  28050. * Determines the loadType of a resource based on the extension of the
  28051. * resource being loaded.
  28052. *
  28053. * @private
  28054. * @return {Resource.LOAD_TYPE} The loadType to use.
  28055. */
  28056. Resource.prototype._determineLoadType = function _determineLoadType() {
  28057. return Resource._loadTypeMap[this.extension] || Resource.LOAD_TYPE.XHR;
  28058. };
  28059. /**
  28060. * Extracts the extension (sans '.') of the file being loaded by the resource.
  28061. *
  28062. * @private
  28063. * @return {string} The extension.
  28064. */
  28065. Resource.prototype._getExtension = function _getExtension() {
  28066. var url = this.url;
  28067. var ext = '';
  28068. if (this.isDataUrl) {
  28069. var slashIndex = url.indexOf('/');
  28070. ext = url.substring(slashIndex + 1, url.indexOf(';', slashIndex));
  28071. } else {
  28072. var queryStart = url.indexOf('?');
  28073. var hashStart = url.indexOf('#');
  28074. var index = Math.min(queryStart > -1 ? queryStart : url.length, hashStart > -1 ? hashStart : url.length);
  28075. url = url.substring(0, index);
  28076. ext = url.substring(url.lastIndexOf('.') + 1);
  28077. }
  28078. return ext.toLowerCase();
  28079. };
  28080. /**
  28081. * Determines the mime type of an XHR request based on the responseType of
  28082. * resource being loaded.
  28083. *
  28084. * @private
  28085. * @param {Resource.XHR_RESPONSE_TYPE} type - The type to get a mime type for.
  28086. * @return {string} The mime type to use.
  28087. */
  28088. Resource.prototype._getMimeFromXhrType = function _getMimeFromXhrType(type) {
  28089. switch (type) {
  28090. case Resource.XHR_RESPONSE_TYPE.BUFFER:
  28091. return 'application/octet-binary';
  28092. case Resource.XHR_RESPONSE_TYPE.BLOB:
  28093. return 'application/blob';
  28094. case Resource.XHR_RESPONSE_TYPE.DOCUMENT:
  28095. return 'application/xml';
  28096. case Resource.XHR_RESPONSE_TYPE.JSON:
  28097. return 'application/json';
  28098. case Resource.XHR_RESPONSE_TYPE.DEFAULT:
  28099. case Resource.XHR_RESPONSE_TYPE.TEXT:
  28100. /* falls through */
  28101. default:
  28102. return 'text/plain';
  28103. }
  28104. };
  28105. _createClass(Resource, [{
  28106. key: 'isDataUrl',
  28107. get: function get() {
  28108. return this._hasFlag(Resource.STATUS_FLAGS.DATA_URL);
  28109. }
  28110. /**
  28111. * Describes if this resource has finished loading. Is true when the resource has completely
  28112. * loaded.
  28113. *
  28114. * @readonly
  28115. * @member {boolean}
  28116. */
  28117. }, {
  28118. key: 'isComplete',
  28119. get: function get() {
  28120. return this._hasFlag(Resource.STATUS_FLAGS.COMPLETE);
  28121. }
  28122. /**
  28123. * Describes if this resource is currently loading. Is true when the resource starts loading,
  28124. * and is false again when complete.
  28125. *
  28126. * @readonly
  28127. * @member {boolean}
  28128. */
  28129. }, {
  28130. key: 'isLoading',
  28131. get: function get() {
  28132. return this._hasFlag(Resource.STATUS_FLAGS.LOADING);
  28133. }
  28134. }]);
  28135. return Resource;
  28136. }();
  28137. /**
  28138. * The types of resources a resource could represent.
  28139. *
  28140. * @static
  28141. * @readonly
  28142. * @enum {number}
  28143. */
  28144. Resource.STATUS_FLAGS = {
  28145. NONE: 0,
  28146. DATA_URL: 1 << 0,
  28147. COMPLETE: 1 << 1,
  28148. LOADING: 1 << 2
  28149. };
  28150. /**
  28151. * The types of resources a resource could represent.
  28152. *
  28153. * @static
  28154. * @readonly
  28155. * @enum {number}
  28156. */
  28157. Resource.TYPE = {
  28158. UNKNOWN: 0,
  28159. JSON: 1,
  28160. XML: 2,
  28161. IMAGE: 3,
  28162. AUDIO: 4,
  28163. VIDEO: 5,
  28164. TEXT: 6
  28165. };
  28166. /**
  28167. * The types of loading a resource can use.
  28168. *
  28169. * @static
  28170. * @readonly
  28171. * @enum {number}
  28172. */
  28173. Resource.LOAD_TYPE = {
  28174. /** Uses XMLHttpRequest to load the resource. */
  28175. XHR: 1,
  28176. /** Uses an `Image` object to load the resource. */
  28177. IMAGE: 2,
  28178. /** Uses an `Audio` object to load the resource. */
  28179. AUDIO: 3,
  28180. /** Uses a `Video` object to load the resource. */
  28181. VIDEO: 4
  28182. };
  28183. /**
  28184. * The XHR ready states, used internally.
  28185. *
  28186. * @static
  28187. * @readonly
  28188. * @enum {string}
  28189. */
  28190. Resource.XHR_RESPONSE_TYPE = {
  28191. /** string */
  28192. DEFAULT: 'text',
  28193. /** ArrayBuffer */
  28194. BUFFER: 'arraybuffer',
  28195. /** Blob */
  28196. BLOB: 'blob',
  28197. /** Document */
  28198. DOCUMENT: 'document',
  28199. /** Object */
  28200. JSON: 'json',
  28201. /** String */
  28202. TEXT: 'text'
  28203. };
  28204. Resource._loadTypeMap = {
  28205. // images
  28206. gif: Resource.LOAD_TYPE.IMAGE,
  28207. png: Resource.LOAD_TYPE.IMAGE,
  28208. bmp: Resource.LOAD_TYPE.IMAGE,
  28209. jpg: Resource.LOAD_TYPE.IMAGE,
  28210. jpeg: Resource.LOAD_TYPE.IMAGE,
  28211. tif: Resource.LOAD_TYPE.IMAGE,
  28212. tiff: Resource.LOAD_TYPE.IMAGE,
  28213. webp: Resource.LOAD_TYPE.IMAGE,
  28214. tga: Resource.LOAD_TYPE.IMAGE,
  28215. svg: Resource.LOAD_TYPE.IMAGE,
  28216. 'svg+xml': Resource.LOAD_TYPE.IMAGE, // for SVG data urls
  28217. // audio
  28218. mp3: Resource.LOAD_TYPE.AUDIO,
  28219. ogg: Resource.LOAD_TYPE.AUDIO,
  28220. wav: Resource.LOAD_TYPE.AUDIO,
  28221. // videos
  28222. mp4: Resource.LOAD_TYPE.VIDEO,
  28223. webm: Resource.LOAD_TYPE.VIDEO
  28224. };
  28225. Resource._xhrTypeMap = {
  28226. // xml
  28227. xhtml: Resource.XHR_RESPONSE_TYPE.DOCUMENT,
  28228. html: Resource.XHR_RESPONSE_TYPE.DOCUMENT,
  28229. htm: Resource.XHR_RESPONSE_TYPE.DOCUMENT,
  28230. xml: Resource.XHR_RESPONSE_TYPE.DOCUMENT,
  28231. tmx: Resource.XHR_RESPONSE_TYPE.DOCUMENT,
  28232. svg: Resource.XHR_RESPONSE_TYPE.DOCUMENT,
  28233. // This was added to handle Tiled Tileset XML, but .tsx is also a TypeScript React Component.
  28234. // Since it is way less likely for people to be loading TypeScript files instead of Tiled files,
  28235. // this should probably be fine.
  28236. tsx: Resource.XHR_RESPONSE_TYPE.DOCUMENT,
  28237. // images
  28238. gif: Resource.XHR_RESPONSE_TYPE.BLOB,
  28239. png: Resource.XHR_RESPONSE_TYPE.BLOB,
  28240. bmp: Resource.XHR_RESPONSE_TYPE.BLOB,
  28241. jpg: Resource.XHR_RESPONSE_TYPE.BLOB,
  28242. jpeg: Resource.XHR_RESPONSE_TYPE.BLOB,
  28243. tif: Resource.XHR_RESPONSE_TYPE.BLOB,
  28244. tiff: Resource.XHR_RESPONSE_TYPE.BLOB,
  28245. webp: Resource.XHR_RESPONSE_TYPE.BLOB,
  28246. tga: Resource.XHR_RESPONSE_TYPE.BLOB,
  28247. // json
  28248. json: Resource.XHR_RESPONSE_TYPE.JSON,
  28249. // text
  28250. text: Resource.XHR_RESPONSE_TYPE.TEXT,
  28251. txt: Resource.XHR_RESPONSE_TYPE.TEXT,
  28252. // fonts
  28253. ttf: Resource.XHR_RESPONSE_TYPE.BUFFER,
  28254. otf: Resource.XHR_RESPONSE_TYPE.BUFFER
  28255. };
  28256. // We can't set the `src` attribute to empty string, so on abort we set it to this 1px transparent gif
  28257. Resource.EMPTY_GIF = 'data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==';
  28258. /**
  28259. * Quick helper to set a value on one of the extension maps. Ensures there is no
  28260. * dot at the start of the extension.
  28261. *
  28262. * @ignore
  28263. * @param {object} map - The map to set on.
  28264. * @param {string} extname - The extension (or key) to set.
  28265. * @param {number} val - The value to set.
  28266. */
  28267. function setExtMap(map, extname, val) {
  28268. if (extname && extname.indexOf('.') === 0) {
  28269. extname = extname.substring(1);
  28270. }
  28271. if (!extname) {
  28272. return;
  28273. }
  28274. map[extname] = val;
  28275. }
  28276. /**
  28277. * Quick helper to get string xhr type.
  28278. *
  28279. * @ignore
  28280. * @param {XMLHttpRequest|XDomainRequest} xhr - The request to check.
  28281. * @return {string} The type.
  28282. */
  28283. function reqType(xhr) {
  28284. return xhr.toString().replace('object ', '');
  28285. }
  28286. // Backwards compat
  28287. if ('object' !== 'undefined') {
  28288. module.exports.default = Resource; // eslint-disable-line no-undef
  28289. }
  28290. });
  28291. var Resource$1 = unwrapExports(Resource_1);
  28292. var Resource_2 = Resource_1.Resource;
  28293. var Loader_1 = createCommonjsModule(function (module, exports) {
  28294. 'use strict';
  28295. exports.__esModule = true;
  28296. exports.Loader = undefined;
  28297. var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
  28298. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) { descriptor.writable = true; } Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) { defineProperties(Constructor.prototype, protoProps); } if (staticProps) { defineProperties(Constructor, staticProps); } return Constructor; }; }();
  28299. var _miniSignals2 = _interopRequireDefault(miniSignals);
  28300. var _parseUri2 = _interopRequireDefault(parseUri);
  28301. var async$1 = _interopRequireWildcard(async);
  28302. function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } }
  28303. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  28304. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  28305. // some constants
  28306. var MAX_PROGRESS = 100;
  28307. var rgxExtractUrlHash = /(#[\w-]+)?$/;
  28308. /**
  28309. * Manages the state and loading of multiple resources to load.
  28310. *
  28311. * @class
  28312. */
  28313. var Loader = exports.Loader = function () {
  28314. /**
  28315. * @param {string} [baseUrl=''] - The base url for all resources loaded by this loader.
  28316. * @param {number} [concurrency=10] - The number of resources to load concurrently.
  28317. */
  28318. function Loader() {
  28319. var _this = this;
  28320. var baseUrl = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
  28321. var concurrency = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 10;
  28322. _classCallCheck(this, Loader);
  28323. /**
  28324. * The base url for all resources loaded by this loader.
  28325. *
  28326. * @member {string}
  28327. */
  28328. this.baseUrl = baseUrl;
  28329. /**
  28330. * The progress percent of the loader going through the queue.
  28331. *
  28332. * @member {number}
  28333. */
  28334. this.progress = 0;
  28335. /**
  28336. * Loading state of the loader, true if it is currently loading resources.
  28337. *
  28338. * @member {boolean}
  28339. */
  28340. this.loading = false;
  28341. /**
  28342. * A querystring to append to every URL added to the loader.
  28343. *
  28344. * This should be a valid query string *without* the question-mark (`?`). The loader will
  28345. * also *not* escape values for you. Make sure to escape your parameters with
  28346. * [`encodeURIComponent`](https://mdn.io/encodeURIComponent) before assigning this property.
  28347. *
  28348. * @example
  28349. * const loader = new Loader();
  28350. *
  28351. * loader.defaultQueryString = 'user=me&password=secret';
  28352. *
  28353. * // This will request 'image.png?user=me&password=secret'
  28354. * loader.add('image.png').load();
  28355. *
  28356. * loader.reset();
  28357. *
  28358. * // This will request 'image.png?v=1&user=me&password=secret'
  28359. * loader.add('iamge.png?v=1').load();
  28360. *
  28361. * @member {string}
  28362. */
  28363. this.defaultQueryString = '';
  28364. /**
  28365. * The middleware to run before loading each resource.
  28366. *
  28367. * @private
  28368. * @member {function[]}
  28369. */
  28370. this._beforeMiddleware = [];
  28371. /**
  28372. * The middleware to run after loading each resource.
  28373. *
  28374. * @private
  28375. * @member {function[]}
  28376. */
  28377. this._afterMiddleware = [];
  28378. /**
  28379. * The tracks the resources we are currently completing parsing for.
  28380. *
  28381. * @private
  28382. * @member {Resource[]}
  28383. */
  28384. this._resourcesParsing = [];
  28385. /**
  28386. * The `_loadResource` function bound with this object context.
  28387. *
  28388. * @private
  28389. * @member {function}
  28390. * @param {Resource} r - The resource to load
  28391. * @param {Function} d - The dequeue function
  28392. * @return {undefined}
  28393. */
  28394. this._boundLoadResource = function (r, d) {
  28395. return _this._loadResource(r, d);
  28396. };
  28397. /**
  28398. * The resources waiting to be loaded.
  28399. *
  28400. * @private
  28401. * @member {Resource[]}
  28402. */
  28403. this._queue = async$1.queue(this._boundLoadResource, concurrency);
  28404. this._queue.pause();
  28405. /**
  28406. * All the resources for this loader keyed by name.
  28407. *
  28408. * @member {object<string, Resource>}
  28409. */
  28410. this.resources = {};
  28411. /**
  28412. * Dispatched once per loaded or errored resource.
  28413. *
  28414. * The callback looks like {@link Loader.OnProgressSignal}.
  28415. *
  28416. * @member {Signal<Loader.OnProgressSignal>}
  28417. */
  28418. this.onProgress = new _miniSignals2.default();
  28419. /**
  28420. * Dispatched once per errored resource.
  28421. *
  28422. * The callback looks like {@link Loader.OnErrorSignal}.
  28423. *
  28424. * @member {Signal<Loader.OnErrorSignal>}
  28425. */
  28426. this.onError = new _miniSignals2.default();
  28427. /**
  28428. * Dispatched once per loaded resource.
  28429. *
  28430. * The callback looks like {@link Loader.OnLoadSignal}.
  28431. *
  28432. * @member {Signal<Loader.OnLoadSignal>}
  28433. */
  28434. this.onLoad = new _miniSignals2.default();
  28435. /**
  28436. * Dispatched when the loader begins to process the queue.
  28437. *
  28438. * The callback looks like {@link Loader.OnStartSignal}.
  28439. *
  28440. * @member {Signal<Loader.OnStartSignal>}
  28441. */
  28442. this.onStart = new _miniSignals2.default();
  28443. /**
  28444. * Dispatched when the queued resources all load.
  28445. *
  28446. * The callback looks like {@link Loader.OnCompleteSignal}.
  28447. *
  28448. * @member {Signal<Loader.OnCompleteSignal>}
  28449. */
  28450. this.onComplete = new _miniSignals2.default();
  28451. // Add default before middleware
  28452. for (var i = 0; i < Loader._defaultBeforeMiddleware.length; ++i) {
  28453. this.pre(Loader._defaultBeforeMiddleware[i]);
  28454. }
  28455. // Add default after middleware
  28456. for (var _i = 0; _i < Loader._defaultAfterMiddleware.length; ++_i) {
  28457. this.use(Loader._defaultAfterMiddleware[_i]);
  28458. }
  28459. }
  28460. /**
  28461. * When the progress changes the loader and resource are disaptched.
  28462. *
  28463. * @memberof Loader
  28464. * @callback OnProgressSignal
  28465. * @param {Loader} loader - The loader the progress is advancing on.
  28466. * @param {Resource} resource - The resource that has completed or failed to cause the progress to advance.
  28467. */
  28468. /**
  28469. * When an error occurrs the loader and resource are disaptched.
  28470. *
  28471. * @memberof Loader
  28472. * @callback OnErrorSignal
  28473. * @param {Loader} loader - The loader the error happened in.
  28474. * @param {Resource} resource - The resource that caused the error.
  28475. */
  28476. /**
  28477. * When a load completes the loader and resource are disaptched.
  28478. *
  28479. * @memberof Loader
  28480. * @callback OnLoadSignal
  28481. * @param {Loader} loader - The loader that laoded the resource.
  28482. * @param {Resource} resource - The resource that has completed loading.
  28483. */
  28484. /**
  28485. * When the loader starts loading resources it dispatches this callback.
  28486. *
  28487. * @memberof Loader
  28488. * @callback OnStartSignal
  28489. * @param {Loader} loader - The loader that has started loading resources.
  28490. */
  28491. /**
  28492. * When the loader completes loading resources it dispatches this callback.
  28493. *
  28494. * @memberof Loader
  28495. * @callback OnCompleteSignal
  28496. * @param {Loader} loader - The loader that has finished loading resources.
  28497. */
  28498. /**
  28499. * Options for a call to `.add()`.
  28500. *
  28501. * @see Loader#add
  28502. *
  28503. * @typedef {object} IAddOptions
  28504. * @property {string} [name] - The name of the resource to load, if not passed the url is used.
  28505. * @property {string} [key] - Alias for `name`.
  28506. * @property {string} [url] - The url for this resource, relative to the baseUrl of this loader.
  28507. * @property {string|boolean} [crossOrigin] - Is this request cross-origin? Default is to
  28508. * determine automatically.
  28509. * @property {number} [timeout=0] - A timeout in milliseconds for the load. If the load takes
  28510. * longer than this time it is cancelled and the load is considered a failure. If this value is
  28511. * set to `0` then there is no explicit timeout.
  28512. * @property {Resource.LOAD_TYPE} [loadType=Resource.LOAD_TYPE.XHR] - How should this resource
  28513. * be loaded?
  28514. * @property {Resource.XHR_RESPONSE_TYPE} [xhrType=Resource.XHR_RESPONSE_TYPE.DEFAULT] - How
  28515. * should the data being loaded be interpreted when using XHR?
  28516. * @property {Resource.OnCompleteSignal} [onComplete] - Callback to add an an onComplete signal istener.
  28517. * @property {Resource.OnCompleteSignal} [callback] - Alias for `onComplete`.
  28518. * @property {Resource.IMetadata} [metadata] - Extra configuration for middleware and the Resource object.
  28519. */
  28520. /* eslint-disable require-jsdoc,valid-jsdoc */
  28521. /**
  28522. * Adds a resource (or multiple resources) to the loader queue.
  28523. *
  28524. * This function can take a wide variety of different parameters. The only thing that is always
  28525. * required the url to load. All the following will work:
  28526. *
  28527. * ```js
  28528. * loader
  28529. * // normal param syntax
  28530. * .add('key', 'http://...', function () {})
  28531. * .add('http://...', function () {})
  28532. * .add('http://...')
  28533. *
  28534. * // object syntax
  28535. * .add({
  28536. * name: 'key2',
  28537. * url: 'http://...'
  28538. * }, function () {})
  28539. * .add({
  28540. * url: 'http://...'
  28541. * }, function () {})
  28542. * .add({
  28543. * name: 'key3',
  28544. * url: 'http://...'
  28545. * onComplete: function () {}
  28546. * })
  28547. * .add({
  28548. * url: 'https://...',
  28549. * onComplete: function () {},
  28550. * crossOrigin: true
  28551. * })
  28552. *
  28553. * // you can also pass an array of objects or urls or both
  28554. * .add([
  28555. * { name: 'key4', url: 'http://...', onComplete: function () {} },
  28556. * { url: 'http://...', onComplete: function () {} },
  28557. * 'http://...'
  28558. * ])
  28559. *
  28560. * // and you can use both params and options
  28561. * .add('key', 'http://...', { crossOrigin: true }, function () {})
  28562. * .add('http://...', { crossOrigin: true }, function () {});
  28563. * ```
  28564. *
  28565. * @function
  28566. * @variation 1
  28567. * @param {string} name - The name of the resource to load.
  28568. * @param {string} url - The url for this resource, relative to the baseUrl of this loader.
  28569. * @param {Resource.OnCompleteSignal} [callback] - Function to call when this specific resource completes loading.
  28570. * @return {this} Returns itself.
  28571. */ /**
  28572. * @function
  28573. * @variation 2
  28574. * @param {string} name - The name of the resource to load.
  28575. * @param {string} url - The url for this resource, relative to the baseUrl of this loader.
  28576. * @param {IAddOptions} [options] - The options for the load.
  28577. * @param {Resource.OnCompleteSignal} [callback] - Function to call when this specific resource completes loading.
  28578. * @return {this} Returns itself.
  28579. */ /**
  28580. * @function
  28581. * @variation 3
  28582. * @param {string} url - The url for this resource, relative to the baseUrl of this loader.
  28583. * @param {Resource.OnCompleteSignal} [callback] - Function to call when this specific resource completes loading.
  28584. * @return {this} Returns itself.
  28585. */ /**
  28586. * @function
  28587. * @variation 4
  28588. * @param {string} url - The url for this resource, relative to the baseUrl of this loader.
  28589. * @param {IAddOptions} [options] - The options for the load.
  28590. * @param {Resource.OnCompleteSignal} [callback] - Function to call when this specific resource completes loading.
  28591. * @return {this} Returns itself.
  28592. */ /**
  28593. * @function
  28594. * @variation 5
  28595. * @param {IAddOptions} options - The options for the load. This object must contain a `url` property.
  28596. * @param {Resource.OnCompleteSignal} [callback] - Function to call when this specific resource completes loading.
  28597. * @return {this} Returns itself.
  28598. */ /**
  28599. * @function
  28600. * @variation 6
  28601. * @param {Array<IAddOptions|string>} resources - An array of resources to load, where each is
  28602. * either an object with the options or a string url. If you pass an object, it must contain a `url` property.
  28603. * @param {Resource.OnCompleteSignal} [callback] - Function to call when this specific resource completes loading.
  28604. * @return {this} Returns itself.
  28605. */
  28606. Loader.prototype.add = function add(name, url, options, cb) {
  28607. // special case of an array of objects or urls
  28608. if (Array.isArray(name)) {
  28609. for (var i = 0; i < name.length; ++i) {
  28610. this.add(name[i]);
  28611. }
  28612. return this;
  28613. }
  28614. // if an object is passed instead of params
  28615. if ((typeof name === 'undefined' ? 'undefined' : _typeof(name)) === 'object') {
  28616. cb = url || name.callback || name.onComplete;
  28617. options = name;
  28618. url = name.url;
  28619. name = name.name || name.key || name.url;
  28620. }
  28621. // case where no name is passed shift all args over by one.
  28622. if (typeof url !== 'string') {
  28623. cb = options;
  28624. options = url;
  28625. url = name;
  28626. }
  28627. // now that we shifted make sure we have a proper url.
  28628. if (typeof url !== 'string') {
  28629. throw new Error('No url passed to add resource to loader.');
  28630. }
  28631. // options are optional so people might pass a function and no options
  28632. if (typeof options === 'function') {
  28633. cb = options;
  28634. options = null;
  28635. }
  28636. // if loading already you can only add resources that have a parent.
  28637. if (this.loading && (!options || !options.parentResource)) {
  28638. throw new Error('Cannot add resources while the loader is running.');
  28639. }
  28640. // check if resource already exists.
  28641. if (this.resources[name]) {
  28642. throw new Error('Resource named "' + name + '" already exists.');
  28643. }
  28644. // add base url if this isn't an absolute url
  28645. url = this._prepareUrl(url);
  28646. // create the store the resource
  28647. this.resources[name] = new Resource_1.Resource(name, url, options);
  28648. if (typeof cb === 'function') {
  28649. this.resources[name].onAfterMiddleware.once(cb);
  28650. }
  28651. // if actively loading, make sure to adjust progress chunks for that parent and its children
  28652. if (this.loading) {
  28653. var parent = options.parentResource;
  28654. var incompleteChildren = [];
  28655. for (var _i2 = 0; _i2 < parent.children.length; ++_i2) {
  28656. if (!parent.children[_i2].isComplete) {
  28657. incompleteChildren.push(parent.children[_i2]);
  28658. }
  28659. }
  28660. var fullChunk = parent.progressChunk * (incompleteChildren.length + 1); // +1 for parent
  28661. var eachChunk = fullChunk / (incompleteChildren.length + 2); // +2 for parent & new child
  28662. parent.children.push(this.resources[name]);
  28663. parent.progressChunk = eachChunk;
  28664. for (var _i3 = 0; _i3 < incompleteChildren.length; ++_i3) {
  28665. incompleteChildren[_i3].progressChunk = eachChunk;
  28666. }
  28667. this.resources[name].progressChunk = eachChunk;
  28668. }
  28669. // add the resource to the queue
  28670. this._queue.push(this.resources[name]);
  28671. return this;
  28672. };
  28673. /* eslint-enable require-jsdoc,valid-jsdoc */
  28674. /**
  28675. * Sets up a middleware function that will run *before* the
  28676. * resource is loaded.
  28677. *
  28678. * @param {function} fn - The middleware function to register.
  28679. * @return {this} Returns itself.
  28680. */
  28681. Loader.prototype.pre = function pre(fn) {
  28682. this._beforeMiddleware.push(fn);
  28683. return this;
  28684. };
  28685. /**
  28686. * Sets up a middleware function that will run *after* the
  28687. * resource is loaded.
  28688. *
  28689. * @param {function} fn - The middleware function to register.
  28690. * @return {this} Returns itself.
  28691. */
  28692. Loader.prototype.use = function use(fn) {
  28693. this._afterMiddleware.push(fn);
  28694. return this;
  28695. };
  28696. /**
  28697. * Resets the queue of the loader to prepare for a new load.
  28698. *
  28699. * @return {this} Returns itself.
  28700. */
  28701. Loader.prototype.reset = function reset() {
  28702. this.progress = 0;
  28703. this.loading = false;
  28704. this._queue.kill();
  28705. this._queue.pause();
  28706. // abort all resource loads
  28707. for (var k in this.resources) {
  28708. var res = this.resources[k];
  28709. if (res._onLoadBinding) {
  28710. res._onLoadBinding.detach();
  28711. }
  28712. if (res.isLoading) {
  28713. res.abort();
  28714. }
  28715. }
  28716. this.resources = {};
  28717. return this;
  28718. };
  28719. /**
  28720. * Starts loading the queued resources.
  28721. *
  28722. * @param {function} [cb] - Optional callback that will be bound to the `complete` event.
  28723. * @return {this} Returns itself.
  28724. */
  28725. Loader.prototype.load = function load(cb) {
  28726. // register complete callback if they pass one
  28727. if (typeof cb === 'function') {
  28728. this.onComplete.once(cb);
  28729. }
  28730. // if the queue has already started we are done here
  28731. if (this.loading) {
  28732. return this;
  28733. }
  28734. if (this._queue.idle()) {
  28735. this._onStart();
  28736. this._onComplete();
  28737. } else {
  28738. // distribute progress chunks
  28739. var numTasks = this._queue._tasks.length;
  28740. var chunk = MAX_PROGRESS / numTasks;
  28741. for (var i = 0; i < this._queue._tasks.length; ++i) {
  28742. this._queue._tasks[i].data.progressChunk = chunk;
  28743. }
  28744. // notify we are starting
  28745. this._onStart();
  28746. // start loading
  28747. this._queue.resume();
  28748. }
  28749. return this;
  28750. };
  28751. /**
  28752. * The number of resources to load concurrently.
  28753. *
  28754. * @member {number}
  28755. * @default 10
  28756. */
  28757. /**
  28758. * Prepares a url for usage based on the configuration of this object
  28759. *
  28760. * @private
  28761. * @param {string} url - The url to prepare.
  28762. * @return {string} The prepared url.
  28763. */
  28764. Loader.prototype._prepareUrl = function _prepareUrl(url) {
  28765. var parsedUrl = (0, _parseUri2.default)(url, { strictMode: true });
  28766. var result = void 0;
  28767. // absolute url, just use it as is.
  28768. if (parsedUrl.protocol || !parsedUrl.path || url.indexOf('//') === 0) {
  28769. result = url;
  28770. }
  28771. // if baseUrl doesn't end in slash and url doesn't start with slash, then add a slash inbetween
  28772. else if (this.baseUrl.length && this.baseUrl.lastIndexOf('/') !== this.baseUrl.length - 1 && url.charAt(0) !== '/') {
  28773. result = this.baseUrl + '/' + url;
  28774. } else {
  28775. result = this.baseUrl + url;
  28776. }
  28777. // if we need to add a default querystring, there is a bit more work
  28778. if (this.defaultQueryString) {
  28779. var hash = rgxExtractUrlHash.exec(result)[0];
  28780. result = result.substr(0, result.length - hash.length);
  28781. if (result.indexOf('?') !== -1) {
  28782. result += '&' + this.defaultQueryString;
  28783. } else {
  28784. result += '?' + this.defaultQueryString;
  28785. }
  28786. result += hash;
  28787. }
  28788. return result;
  28789. };
  28790. /**
  28791. * Loads a single resource.
  28792. *
  28793. * @private
  28794. * @param {Resource} resource - The resource to load.
  28795. * @param {function} dequeue - The function to call when we need to dequeue this item.
  28796. */
  28797. Loader.prototype._loadResource = function _loadResource(resource, dequeue) {
  28798. var _this2 = this;
  28799. resource._dequeue = dequeue;
  28800. // run before middleware
  28801. async$1.eachSeries(this._beforeMiddleware, function (fn, next) {
  28802. fn.call(_this2, resource, function () {
  28803. // if the before middleware marks the resource as complete,
  28804. // break and don't process any more before middleware
  28805. next(resource.isComplete ? {} : null);
  28806. });
  28807. }, function () {
  28808. if (resource.isComplete) {
  28809. _this2._onLoad(resource);
  28810. } else {
  28811. resource._onLoadBinding = resource.onComplete.once(_this2._onLoad, _this2);
  28812. resource.load();
  28813. }
  28814. }, true);
  28815. };
  28816. /**
  28817. * Called once loading has started.
  28818. *
  28819. * @private
  28820. */
  28821. Loader.prototype._onStart = function _onStart() {
  28822. this.progress = 0;
  28823. this.loading = true;
  28824. this.onStart.dispatch(this);
  28825. };
  28826. /**
  28827. * Called once each resource has loaded.
  28828. *
  28829. * @private
  28830. */
  28831. Loader.prototype._onComplete = function _onComplete() {
  28832. this.progress = MAX_PROGRESS;
  28833. this.loading = false;
  28834. this.onComplete.dispatch(this, this.resources);
  28835. };
  28836. /**
  28837. * Called each time a resources is loaded.
  28838. *
  28839. * @private
  28840. * @param {Resource} resource - The resource that was loaded
  28841. */
  28842. Loader.prototype._onLoad = function _onLoad(resource) {
  28843. var _this3 = this;
  28844. resource._onLoadBinding = null;
  28845. // remove this resource from the async queue, and add it to our list of resources that are being parsed
  28846. this._resourcesParsing.push(resource);
  28847. resource._dequeue();
  28848. // run all the after middleware for this resource
  28849. async$1.eachSeries(this._afterMiddleware, function (fn, next) {
  28850. fn.call(_this3, resource, next);
  28851. }, function () {
  28852. resource.onAfterMiddleware.dispatch(resource);
  28853. _this3.progress = Math.min(MAX_PROGRESS, _this3.progress + resource.progressChunk);
  28854. _this3.onProgress.dispatch(_this3, resource);
  28855. if (resource.error) {
  28856. _this3.onError.dispatch(resource.error, _this3, resource);
  28857. } else {
  28858. _this3.onLoad.dispatch(_this3, resource);
  28859. }
  28860. _this3._resourcesParsing.splice(_this3._resourcesParsing.indexOf(resource), 1);
  28861. // do completion check
  28862. if (_this3._queue.idle() && _this3._resourcesParsing.length === 0) {
  28863. _this3._onComplete();
  28864. }
  28865. }, true);
  28866. };
  28867. _createClass(Loader, [{
  28868. key: 'concurrency',
  28869. get: function get() {
  28870. return this._queue.concurrency;
  28871. }
  28872. // eslint-disable-next-line require-jsdoc
  28873. ,
  28874. set: function set(concurrency) {
  28875. this._queue.concurrency = concurrency;
  28876. }
  28877. }]);
  28878. return Loader;
  28879. }();
  28880. /**
  28881. * A default array of middleware to run before loading each resource.
  28882. * Each of these middlewares are added to any new Loader instances when they are created.
  28883. *
  28884. * @private
  28885. * @member {function[]}
  28886. */
  28887. Loader._defaultBeforeMiddleware = [];
  28888. /**
  28889. * A default array of middleware to run after loading each resource.
  28890. * Each of these middlewares are added to any new Loader instances when they are created.
  28891. *
  28892. * @private
  28893. * @member {function[]}
  28894. */
  28895. Loader._defaultAfterMiddleware = [];
  28896. /**
  28897. * Sets up a middleware function that will run *before* the
  28898. * resource is loaded.
  28899. *
  28900. * @static
  28901. * @param {function} fn - The middleware function to register.
  28902. * @return {Loader} Returns itself.
  28903. */
  28904. Loader.pre = function LoaderPreStatic(fn) {
  28905. Loader._defaultBeforeMiddleware.push(fn);
  28906. return Loader;
  28907. };
  28908. /**
  28909. * Sets up a middleware function that will run *after* the
  28910. * resource is loaded.
  28911. *
  28912. * @static
  28913. * @param {function} fn - The middleware function to register.
  28914. * @return {Loader} Returns itself.
  28915. */
  28916. Loader.use = function LoaderUseStatic(fn) {
  28917. Loader._defaultAfterMiddleware.push(fn);
  28918. return Loader;
  28919. };
  28920. });
  28921. var Loader = unwrapExports(Loader_1);
  28922. var Loader_2 = Loader_1.Loader;
  28923. var b64 = createCommonjsModule(function (module, exports) {
  28924. 'use strict';
  28925. exports.__esModule = true;
  28926. exports.encodeBinary = encodeBinary;
  28927. var _keyStr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
  28928. /**
  28929. * Encodes binary into base64.
  28930. *
  28931. * @param {string} input The input data to encode.
  28932. * @returns {string} The encoded base64 string
  28933. */
  28934. function encodeBinary(input) {
  28935. var output = '';
  28936. var inx = 0;
  28937. while (inx < input.length) {
  28938. // Fill byte buffer array
  28939. var bytebuffer = [0, 0, 0];
  28940. var encodedCharIndexes = [0, 0, 0, 0];
  28941. for (var jnx = 0; jnx < bytebuffer.length; ++jnx) {
  28942. if (inx < input.length) {
  28943. // throw away high-order byte, as documented at:
  28944. // https://developer.mozilla.org/En/Using_XMLHttpRequest#Handling_binary_data
  28945. bytebuffer[jnx] = input.charCodeAt(inx++) & 0xff;
  28946. } else {
  28947. bytebuffer[jnx] = 0;
  28948. }
  28949. }
  28950. // Get each encoded character, 6 bits at a time
  28951. // index 1: first 6 bits
  28952. encodedCharIndexes[0] = bytebuffer[0] >> 2;
  28953. // index 2: second 6 bits (2 least significant bits from input byte 1 + 4 most significant bits from byte 2)
  28954. encodedCharIndexes[1] = (bytebuffer[0] & 0x3) << 4 | bytebuffer[1] >> 4;
  28955. // index 3: third 6 bits (4 least significant bits from input byte 2 + 2 most significant bits from byte 3)
  28956. encodedCharIndexes[2] = (bytebuffer[1] & 0x0f) << 2 | bytebuffer[2] >> 6;
  28957. // index 3: forth 6 bits (6 least significant bits from input byte 3)
  28958. encodedCharIndexes[3] = bytebuffer[2] & 0x3f;
  28959. // Determine whether padding happened, and adjust accordingly
  28960. var paddingBytes = inx - (input.length - 1);
  28961. switch (paddingBytes) {
  28962. case 2:
  28963. // Set last 2 characters to padding char
  28964. encodedCharIndexes[3] = 64;
  28965. encodedCharIndexes[2] = 64;
  28966. break;
  28967. case 1:
  28968. // Set last character to padding char
  28969. encodedCharIndexes[3] = 64;
  28970. break;
  28971. default:
  28972. break; // No padding - proceed
  28973. }
  28974. // Now we will grab each appropriate character out of our keystring
  28975. // based on our index array and append it to the output string
  28976. for (var _jnx = 0; _jnx < encodedCharIndexes.length; ++_jnx) {
  28977. output += _keyStr.charAt(encodedCharIndexes[_jnx]);
  28978. }
  28979. }
  28980. return output;
  28981. }
  28982. // Backwards compat
  28983. if ('object' !== 'undefined') {
  28984. module.exports.default = encodeBinary; // eslint-disable-line no-undef
  28985. }
  28986. });
  28987. var b64$1 = unwrapExports(b64);
  28988. var b64_1 = b64.encodeBinary;
  28989. 'use strict';
  28990. // import Loader from './Loader';
  28991. // import Resource from './Resource';
  28992. // import * as async from './async';
  28993. // import * as b64 from './b64';
  28994. /* eslint-disable no-undef */
  28995. var Loader$1 = Loader_1.Loader;
  28996. var Resource$2 = Resource_1.Resource;
  28997. /**
  28998. *
  28999. * @static
  29000. * @memberof Loader
  29001. * @member {Class<Resource>}
  29002. */
  29003. Loader$1.Resource = Resource$2;
  29004. /**
  29005. *
  29006. * @static
  29007. * @memberof Loader
  29008. * @member {Class<async>}
  29009. */
  29010. Loader$1.async = async;
  29011. /**
  29012. *
  29013. * @static
  29014. * @memberof Loader
  29015. * @member {Class<encodeBinary>}
  29016. */
  29017. Loader$1.encodeBinary = b64;
  29018. /**
  29019. *
  29020. * @deprecated
  29021. * @see Loader.encodeBinary
  29022. *
  29023. * @static
  29024. * @memberof Loader
  29025. * @member {Class<encodeBinary>}
  29026. */
  29027. Loader$1.base64 = b64;
  29028. // export manually, and also as default
  29029. var lib = Loader$1;
  29030. // default & named export
  29031. var Loader_1$1 = Loader$1;
  29032. var default_1$1 = Loader$1;
  29033. var lib_1 = lib.Resource;
  29034. lib.Loader = Loader_1$1;
  29035. lib.default = default_1$1;
  29036. /*!
  29037. * @pixi/loaders - v5.0.4
  29038. * Compiled Fri, 07 Jun 2019 17:17:49 UTC
  29039. *
  29040. * @pixi/loaders is licensed under the MIT License.
  29041. * http://www.opensource.org/licenses/mit-license
  29042. */
  29043. function unwrapExports$1 (x) {
  29044. return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
  29045. }
  29046. function createCommonjsModule$1(fn, module) {
  29047. return module = { exports: {} }, fn(module, module.exports), module.exports;
  29048. }
  29049. var parseUri$1 = function parseURI (str, opts) {
  29050. opts = opts || {};
  29051. var o = {
  29052. key: ['source', 'protocol', 'authority', 'userInfo', 'user', 'password', 'host', 'port', 'relative', 'path', 'directory', 'file', 'query', 'anchor'],
  29053. q: {
  29054. name: 'queryKey',
  29055. parser: /(?:^|&)([^&=]*)=?([^&]*)/g
  29056. },
  29057. parser: {
  29058. strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,
  29059. loose: /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/
  29060. }
  29061. };
  29062. var m = o.parser[opts.strictMode ? 'strict' : 'loose'].exec(str);
  29063. var uri = {};
  29064. var i = 14;
  29065. while (i--) { uri[o.key[i]] = m[i] || ''; }
  29066. uri[o.q.name] = {};
  29067. uri[o.key[12]].replace(o.q.parser, function ($0, $1, $2) {
  29068. if ($1) { uri[o.q.name][$1] = $2; }
  29069. });
  29070. return uri
  29071. };
  29072. var miniSignals$2 = createCommonjsModule$1(function (module, exports) {
  29073. Object.defineProperty(exports, '__esModule', {
  29074. value: true
  29075. });
  29076. var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) { descriptor.writable = true; } Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) { defineProperties(Constructor.prototype, protoProps); } if (staticProps) { defineProperties(Constructor, staticProps); } return Constructor; }; })();
  29077. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
  29078. var MiniSignalBinding = (function () {
  29079. function MiniSignalBinding(fn, once, thisArg) {
  29080. if (once === undefined) { once = false; }
  29081. _classCallCheck(this, MiniSignalBinding);
  29082. this._fn = fn;
  29083. this._once = once;
  29084. this._thisArg = thisArg;
  29085. this._next = this._prev = this._owner = null;
  29086. }
  29087. _createClass(MiniSignalBinding, [{
  29088. key: 'detach',
  29089. value: function detach() {
  29090. if (this._owner === null) { return false; }
  29091. this._owner.detach(this);
  29092. return true;
  29093. }
  29094. }]);
  29095. return MiniSignalBinding;
  29096. })();
  29097. function _addMiniSignalBinding(self, node) {
  29098. if (!self._head) {
  29099. self._head = node;
  29100. self._tail = node;
  29101. } else {
  29102. self._tail._next = node;
  29103. node._prev = self._tail;
  29104. self._tail = node;
  29105. }
  29106. node._owner = self;
  29107. return node;
  29108. }
  29109. var MiniSignal = (function () {
  29110. function MiniSignal() {
  29111. _classCallCheck(this, MiniSignal);
  29112. this._head = this._tail = undefined;
  29113. }
  29114. _createClass(MiniSignal, [{
  29115. key: 'handlers',
  29116. value: function handlers() {
  29117. var exists = arguments.length <= 0 || arguments[0] === undefined ? false : arguments[0];
  29118. var node = this._head;
  29119. if (exists) { return !!node; }
  29120. var ee = [];
  29121. while (node) {
  29122. ee.push(node);
  29123. node = node._next;
  29124. }
  29125. return ee;
  29126. }
  29127. }, {
  29128. key: 'has',
  29129. value: function has(node) {
  29130. if (!(node instanceof MiniSignalBinding)) {
  29131. throw new Error('MiniSignal#has(): First arg must be a MiniSignalBinding object.');
  29132. }
  29133. return node._owner === this;
  29134. }
  29135. }, {
  29136. key: 'dispatch',
  29137. value: function dispatch() {
  29138. var arguments$1 = arguments;
  29139. var node = this._head;
  29140. if (!node) { return false; }
  29141. while (node) {
  29142. if (node._once) { this.detach(node); }
  29143. node._fn.apply(node._thisArg, arguments$1);
  29144. node = node._next;
  29145. }
  29146. return true;
  29147. }
  29148. }, {
  29149. key: 'add',
  29150. value: function add(fn) {
  29151. var thisArg = arguments.length <= 1 || arguments[1] === undefined ? null : arguments[1];
  29152. if (typeof fn !== 'function') {
  29153. throw new Error('MiniSignal#add(): First arg must be a Function.');
  29154. }
  29155. return _addMiniSignalBinding(this, new MiniSignalBinding(fn, false, thisArg));
  29156. }
  29157. }, {
  29158. key: 'once',
  29159. value: function once(fn) {
  29160. var thisArg = arguments.length <= 1 || arguments[1] === undefined ? null : arguments[1];
  29161. if (typeof fn !== 'function') {
  29162. throw new Error('MiniSignal#once(): First arg must be a Function.');
  29163. }
  29164. return _addMiniSignalBinding(this, new MiniSignalBinding(fn, true, thisArg));
  29165. }
  29166. }, {
  29167. key: 'detach',
  29168. value: function detach(node) {
  29169. if (!(node instanceof MiniSignalBinding)) {
  29170. throw new Error('MiniSignal#detach(): First arg must be a MiniSignalBinding object.');
  29171. }
  29172. if (node._owner !== this) { return this; }
  29173. if (node._prev) { node._prev._next = node._next; }
  29174. if (node._next) { node._next._prev = node._prev; }
  29175. if (node === this._head) {
  29176. this._head = node._next;
  29177. if (node._next === null) {
  29178. this._tail = null;
  29179. }
  29180. } else if (node === this._tail) {
  29181. this._tail = node._prev;
  29182. this._tail._next = null;
  29183. }
  29184. node._owner = null;
  29185. return this;
  29186. }
  29187. }, {
  29188. key: 'detachAll',
  29189. value: function detachAll() {
  29190. var node = this._head;
  29191. if (!node) { return this; }
  29192. this._head = this._tail = null;
  29193. while (node) {
  29194. node._owner = null;
  29195. node = node._next;
  29196. }
  29197. return this;
  29198. }
  29199. }]);
  29200. return MiniSignal;
  29201. })();
  29202. MiniSignal.MiniSignalBinding = MiniSignalBinding;
  29203. exports['default'] = MiniSignal;
  29204. module.exports = exports['default'];
  29205. });
  29206. unwrapExports$1(miniSignals$2);
  29207. var Resource_1$1 = createCommonjsModule$1(function (module, exports) {
  29208. exports.__esModule = true;
  29209. exports.Resource = undefined;
  29210. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) { descriptor.writable = true; } Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) { defineProperties(Constructor.prototype, protoProps); } if (staticProps) { defineProperties(Constructor, staticProps); } return Constructor; }; }();
  29211. var _parseUri2 = _interopRequireDefault(parseUri$1);
  29212. var _miniSignals2 = _interopRequireDefault(miniSignals$2);
  29213. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  29214. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  29215. // tests if CORS is supported in XHR, if not we need to use XDR
  29216. var useXdr = !!(window.XDomainRequest && !('withCredentials' in new XMLHttpRequest()));
  29217. var tempAnchor = null;
  29218. // some status constants
  29219. var STATUS_NONE = 0;
  29220. var STATUS_OK = 200;
  29221. var STATUS_EMPTY = 204;
  29222. var STATUS_IE_BUG_EMPTY = 1223;
  29223. var STATUS_TYPE_OK = 2;
  29224. // noop
  29225. function _noop() {} /* empty */
  29226. /**
  29227. * Manages the state and loading of a resource and all child resources.
  29228. *
  29229. * @class
  29230. */
  29231. var Resource = exports.Resource = function () {
  29232. /**
  29233. * Sets the load type to be used for a specific extension.
  29234. *
  29235. * @static
  29236. * @param {string} extname - The extension to set the type for, e.g. "png" or "fnt"
  29237. * @param {Resource.LOAD_TYPE} loadType - The load type to set it to.
  29238. */
  29239. Resource.setExtensionLoadType = function setExtensionLoadType(extname, loadType) {
  29240. setExtMap(Resource._loadTypeMap, extname, loadType);
  29241. };
  29242. /**
  29243. * Sets the load type to be used for a specific extension.
  29244. *
  29245. * @static
  29246. * @param {string} extname - The extension to set the type for, e.g. "png" or "fnt"
  29247. * @param {Resource.XHR_RESPONSE_TYPE} xhrType - The xhr type to set it to.
  29248. */
  29249. Resource.setExtensionXhrType = function setExtensionXhrType(extname, xhrType) {
  29250. setExtMap(Resource._xhrTypeMap, extname, xhrType);
  29251. };
  29252. /**
  29253. * @param {string} name - The name of the resource to load.
  29254. * @param {string|string[]} url - The url for this resource, for audio/video loads you can pass
  29255. * an array of sources.
  29256. * @param {object} [options] - The options for the load.
  29257. * @param {string|boolean} [options.crossOrigin] - Is this request cross-origin? Default is to
  29258. * determine automatically.
  29259. * @param {number} [options.timeout=0] - A timeout in milliseconds for the load. If the load takes
  29260. * longer than this time it is cancelled and the load is considered a failure. If this value is
  29261. * set to `0` then there is no explicit timeout.
  29262. * @param {Resource.LOAD_TYPE} [options.loadType=Resource.LOAD_TYPE.XHR] - How should this resource
  29263. * be loaded?
  29264. * @param {Resource.XHR_RESPONSE_TYPE} [options.xhrType=Resource.XHR_RESPONSE_TYPE.DEFAULT] - How
  29265. * should the data being loaded be interpreted when using XHR?
  29266. * @param {Resource.IMetadata} [options.metadata] - Extra configuration for middleware and the Resource object.
  29267. */
  29268. function Resource(name, url, options) {
  29269. _classCallCheck(this, Resource);
  29270. if (typeof name !== 'string' || typeof url !== 'string') {
  29271. throw new Error('Both name and url are required for constructing a resource.');
  29272. }
  29273. options = options || {};
  29274. /**
  29275. * The state flags of this resource.
  29276. *
  29277. * @private
  29278. * @member {number}
  29279. */
  29280. this._flags = 0;
  29281. // set data url flag, needs to be set early for some _determineX checks to work.
  29282. this._setFlag(Resource.STATUS_FLAGS.DATA_URL, url.indexOf('data:') === 0);
  29283. /**
  29284. * The name of this resource.
  29285. *
  29286. * @readonly
  29287. * @member {string}
  29288. */
  29289. this.name = name;
  29290. /**
  29291. * The url used to load this resource.
  29292. *
  29293. * @readonly
  29294. * @member {string}
  29295. */
  29296. this.url = url;
  29297. /**
  29298. * The extension used to load this resource.
  29299. *
  29300. * @readonly
  29301. * @member {string}
  29302. */
  29303. this.extension = this._getExtension();
  29304. /**
  29305. * The data that was loaded by the resource.
  29306. *
  29307. * @member {any}
  29308. */
  29309. this.data = null;
  29310. /**
  29311. * Is this request cross-origin? If unset, determined automatically.
  29312. *
  29313. * @member {string}
  29314. */
  29315. this.crossOrigin = options.crossOrigin === true ? 'anonymous' : options.crossOrigin;
  29316. /**
  29317. * A timeout in milliseconds for the load. If the load takes longer than this time
  29318. * it is cancelled and the load is considered a failure. If this value is set to `0`
  29319. * then there is no explicit timeout.
  29320. *
  29321. * @member {number}
  29322. */
  29323. this.timeout = options.timeout || 0;
  29324. /**
  29325. * The method of loading to use for this resource.
  29326. *
  29327. * @member {Resource.LOAD_TYPE}
  29328. */
  29329. this.loadType = options.loadType || this._determineLoadType();
  29330. /**
  29331. * The type used to load the resource via XHR. If unset, determined automatically.
  29332. *
  29333. * @member {string}
  29334. */
  29335. this.xhrType = options.xhrType;
  29336. /**
  29337. * Extra info for middleware, and controlling specifics about how the resource loads.
  29338. *
  29339. * Note that if you pass in a `loadElement`, the Resource class takes ownership of it.
  29340. * Meaning it will modify it as it sees fit.
  29341. *
  29342. * @member {Resource.IMetadata}
  29343. */
  29344. this.metadata = options.metadata || {};
  29345. /**
  29346. * The error that occurred while loading (if any).
  29347. *
  29348. * @readonly
  29349. * @member {Error}
  29350. */
  29351. this.error = null;
  29352. /**
  29353. * The XHR object that was used to load this resource. This is only set
  29354. * when `loadType` is `Resource.LOAD_TYPE.XHR`.
  29355. *
  29356. * @readonly
  29357. * @member {XMLHttpRequest}
  29358. */
  29359. this.xhr = null;
  29360. /**
  29361. * The child resources this resource owns.
  29362. *
  29363. * @readonly
  29364. * @member {Resource[]}
  29365. */
  29366. this.children = [];
  29367. /**
  29368. * The resource type.
  29369. *
  29370. * @readonly
  29371. * @member {Resource.TYPE}
  29372. */
  29373. this.type = Resource.TYPE.UNKNOWN;
  29374. /**
  29375. * The progress chunk owned by this resource.
  29376. *
  29377. * @readonly
  29378. * @member {number}
  29379. */
  29380. this.progressChunk = 0;
  29381. /**
  29382. * The `dequeue` method that will be used a storage place for the async queue dequeue method
  29383. * used privately by the loader.
  29384. *
  29385. * @private
  29386. * @member {function}
  29387. */
  29388. this._dequeue = _noop;
  29389. /**
  29390. * Used a storage place for the on load binding used privately by the loader.
  29391. *
  29392. * @private
  29393. * @member {function}
  29394. */
  29395. this._onLoadBinding = null;
  29396. /**
  29397. * The timer for element loads to check if they timeout.
  29398. *
  29399. * @private
  29400. * @member {number}
  29401. */
  29402. this._elementTimer = 0;
  29403. /**
  29404. * The `complete` function bound to this resource's context.
  29405. *
  29406. * @private
  29407. * @member {function}
  29408. */
  29409. this._boundComplete = this.complete.bind(this);
  29410. /**
  29411. * The `_onError` function bound to this resource's context.
  29412. *
  29413. * @private
  29414. * @member {function}
  29415. */
  29416. this._boundOnError = this._onError.bind(this);
  29417. /**
  29418. * The `_onProgress` function bound to this resource's context.
  29419. *
  29420. * @private
  29421. * @member {function}
  29422. */
  29423. this._boundOnProgress = this._onProgress.bind(this);
  29424. /**
  29425. * The `_onTimeout` function bound to this resource's context.
  29426. *
  29427. * @private
  29428. * @member {function}
  29429. */
  29430. this._boundOnTimeout = this._onTimeout.bind(this);
  29431. // xhr callbacks
  29432. this._boundXhrOnError = this._xhrOnError.bind(this);
  29433. this._boundXhrOnTimeout = this._xhrOnTimeout.bind(this);
  29434. this._boundXhrOnAbort = this._xhrOnAbort.bind(this);
  29435. this._boundXhrOnLoad = this._xhrOnLoad.bind(this);
  29436. /**
  29437. * Dispatched when the resource beings to load.
  29438. *
  29439. * The callback looks like {@link Resource.OnStartSignal}.
  29440. *
  29441. * @member {Signal<Resource.OnStartSignal>}
  29442. */
  29443. this.onStart = new _miniSignals2.default();
  29444. /**
  29445. * Dispatched each time progress of this resource load updates.
  29446. * Not all resources types and loader systems can support this event
  29447. * so sometimes it may not be available. If the resource
  29448. * is being loaded on a modern browser, using XHR, and the remote server
  29449. * properly sets Content-Length headers, then this will be available.
  29450. *
  29451. * The callback looks like {@link Resource.OnProgressSignal}.
  29452. *
  29453. * @member {Signal<Resource.OnProgressSignal>}
  29454. */
  29455. this.onProgress = new _miniSignals2.default();
  29456. /**
  29457. * Dispatched once this resource has loaded, if there was an error it will
  29458. * be in the `error` property.
  29459. *
  29460. * The callback looks like {@link Resource.OnCompleteSignal}.
  29461. *
  29462. * @member {Signal<Resource.OnCompleteSignal>}
  29463. */
  29464. this.onComplete = new _miniSignals2.default();
  29465. /**
  29466. * Dispatched after this resource has had all the *after* middleware run on it.
  29467. *
  29468. * The callback looks like {@link Resource.OnCompleteSignal}.
  29469. *
  29470. * @member {Signal<Resource.OnCompleteSignal>}
  29471. */
  29472. this.onAfterMiddleware = new _miniSignals2.default();
  29473. }
  29474. /**
  29475. * When the resource starts to load.
  29476. *
  29477. * @memberof Resource
  29478. * @callback OnStartSignal
  29479. * @param {Resource} resource - The resource that the event happened on.
  29480. */
  29481. /**
  29482. * When the resource reports loading progress.
  29483. *
  29484. * @memberof Resource
  29485. * @callback OnProgressSignal
  29486. * @param {Resource} resource - The resource that the event happened on.
  29487. * @param {number} percentage - The progress of the load in the range [0, 1].
  29488. */
  29489. /**
  29490. * When the resource finishes loading.
  29491. *
  29492. * @memberof Resource
  29493. * @callback OnCompleteSignal
  29494. * @param {Resource} resource - The resource that the event happened on.
  29495. */
  29496. /**
  29497. * @memberof Resource
  29498. * @typedef {object} IMetadata
  29499. * @property {HTMLImageElement|HTMLAudioElement|HTMLVideoElement} [loadElement=null] - The
  29500. * element to use for loading, instead of creating one.
  29501. * @property {boolean} [skipSource=false] - Skips adding source(s) to the load element. This
  29502. * is useful if you want to pass in a `loadElement` that you already added load sources to.
  29503. * @property {string|string[]} [mimeType] - The mime type to use for the source element
  29504. * of a video/audio elment. If the urls are an array, you can pass this as an array as well
  29505. * where each index is the mime type to use for the corresponding url index.
  29506. */
  29507. /**
  29508. * Stores whether or not this url is a data url.
  29509. *
  29510. * @readonly
  29511. * @member {boolean}
  29512. */
  29513. /**
  29514. * Marks the resource as complete.
  29515. *
  29516. */
  29517. Resource.prototype.complete = function complete() {
  29518. this._clearEvents();
  29519. this._finish();
  29520. };
  29521. /**
  29522. * Aborts the loading of this resource, with an optional message.
  29523. *
  29524. * @param {string} message - The message to use for the error
  29525. */
  29526. Resource.prototype.abort = function abort(message) {
  29527. // abort can be called multiple times, ignore subsequent calls.
  29528. if (this.error) {
  29529. return;
  29530. }
  29531. // store error
  29532. this.error = new Error(message);
  29533. // clear events before calling aborts
  29534. this._clearEvents();
  29535. // abort the actual loading
  29536. if (this.xhr) {
  29537. this.xhr.abort();
  29538. } else if (this.xdr) {
  29539. this.xdr.abort();
  29540. } else if (this.data) {
  29541. // single source
  29542. if (this.data.src) {
  29543. this.data.src = Resource.EMPTY_GIF;
  29544. }
  29545. // multi-source
  29546. else {
  29547. while (this.data.firstChild) {
  29548. this.data.removeChild(this.data.firstChild);
  29549. }
  29550. }
  29551. }
  29552. // done now.
  29553. this._finish();
  29554. };
  29555. /**
  29556. * Kicks off loading of this resource. This method is asynchronous.
  29557. *
  29558. * @param {Resource.OnCompleteSignal} [cb] - Optional callback to call once the resource is loaded.
  29559. */
  29560. Resource.prototype.load = function load(cb) {
  29561. var _this = this;
  29562. if (this.isLoading) {
  29563. return;
  29564. }
  29565. if (this.isComplete) {
  29566. if (cb) {
  29567. setTimeout(function () {
  29568. return cb(_this);
  29569. }, 1);
  29570. }
  29571. return;
  29572. } else if (cb) {
  29573. this.onComplete.once(cb);
  29574. }
  29575. this._setFlag(Resource.STATUS_FLAGS.LOADING, true);
  29576. this.onStart.dispatch(this);
  29577. // if unset, determine the value
  29578. if (this.crossOrigin === false || typeof this.crossOrigin !== 'string') {
  29579. this.crossOrigin = this._determineCrossOrigin(this.url);
  29580. }
  29581. switch (this.loadType) {
  29582. case Resource.LOAD_TYPE.IMAGE:
  29583. this.type = Resource.TYPE.IMAGE;
  29584. this._loadElement('image');
  29585. break;
  29586. case Resource.LOAD_TYPE.AUDIO:
  29587. this.type = Resource.TYPE.AUDIO;
  29588. this._loadSourceElement('audio');
  29589. break;
  29590. case Resource.LOAD_TYPE.VIDEO:
  29591. this.type = Resource.TYPE.VIDEO;
  29592. this._loadSourceElement('video');
  29593. break;
  29594. case Resource.LOAD_TYPE.XHR:
  29595. /* falls through */
  29596. default:
  29597. if (useXdr && this.crossOrigin) {
  29598. this._loadXdr();
  29599. } else {
  29600. this._loadXhr();
  29601. }
  29602. break;
  29603. }
  29604. };
  29605. /**
  29606. * Checks if the flag is set.
  29607. *
  29608. * @private
  29609. * @param {number} flag - The flag to check.
  29610. * @return {boolean} True if the flag is set.
  29611. */
  29612. Resource.prototype._hasFlag = function _hasFlag(flag) {
  29613. return (this._flags & flag) !== 0;
  29614. };
  29615. /**
  29616. * (Un)Sets the flag.
  29617. *
  29618. * @private
  29619. * @param {number} flag - The flag to (un)set.
  29620. * @param {boolean} value - Whether to set or (un)set the flag.
  29621. */
  29622. Resource.prototype._setFlag = function _setFlag(flag, value) {
  29623. this._flags = value ? this._flags | flag : this._flags & ~flag;
  29624. };
  29625. /**
  29626. * Clears all the events from the underlying loading source.
  29627. *
  29628. * @private
  29629. */
  29630. Resource.prototype._clearEvents = function _clearEvents() {
  29631. clearTimeout(this._elementTimer);
  29632. if (this.data && this.data.removeEventListener) {
  29633. this.data.removeEventListener('error', this._boundOnError, false);
  29634. this.data.removeEventListener('load', this._boundComplete, false);
  29635. this.data.removeEventListener('progress', this._boundOnProgress, false);
  29636. this.data.removeEventListener('canplaythrough', this._boundComplete, false);
  29637. }
  29638. if (this.xhr) {
  29639. if (this.xhr.removeEventListener) {
  29640. this.xhr.removeEventListener('error', this._boundXhrOnError, false);
  29641. this.xhr.removeEventListener('timeout', this._boundXhrOnTimeout, false);
  29642. this.xhr.removeEventListener('abort', this._boundXhrOnAbort, false);
  29643. this.xhr.removeEventListener('progress', this._boundOnProgress, false);
  29644. this.xhr.removeEventListener('load', this._boundXhrOnLoad, false);
  29645. } else {
  29646. this.xhr.onerror = null;
  29647. this.xhr.ontimeout = null;
  29648. this.xhr.onprogress = null;
  29649. this.xhr.onload = null;
  29650. }
  29651. }
  29652. };
  29653. /**
  29654. * Finalizes the load.
  29655. *
  29656. * @private
  29657. */
  29658. Resource.prototype._finish = function _finish() {
  29659. if (this.isComplete) {
  29660. throw new Error('Complete called again for an already completed resource.');
  29661. }
  29662. this._setFlag(Resource.STATUS_FLAGS.COMPLETE, true);
  29663. this._setFlag(Resource.STATUS_FLAGS.LOADING, false);
  29664. this.onComplete.dispatch(this);
  29665. };
  29666. /**
  29667. * Loads this resources using an element that has a single source,
  29668. * like an HTMLImageElement.
  29669. *
  29670. * @private
  29671. * @param {string} type - The type of element to use.
  29672. */
  29673. Resource.prototype._loadElement = function _loadElement(type) {
  29674. if (this.metadata.loadElement) {
  29675. this.data = this.metadata.loadElement;
  29676. } else if (type === 'image' && typeof window.Image !== 'undefined') {
  29677. this.data = new Image();
  29678. } else {
  29679. this.data = document.createElement(type);
  29680. }
  29681. if (this.crossOrigin) {
  29682. this.data.crossOrigin = this.crossOrigin;
  29683. }
  29684. if (!this.metadata.skipSource) {
  29685. this.data.src = this.url;
  29686. }
  29687. this.data.addEventListener('error', this._boundOnError, false);
  29688. this.data.addEventListener('load', this._boundComplete, false);
  29689. this.data.addEventListener('progress', this._boundOnProgress, false);
  29690. if (this.timeout) {
  29691. this._elementTimer = setTimeout(this._boundOnTimeout, this.timeout);
  29692. }
  29693. };
  29694. /**
  29695. * Loads this resources using an element that has multiple sources,
  29696. * like an HTMLAudioElement or HTMLVideoElement.
  29697. *
  29698. * @private
  29699. * @param {string} type - The type of element to use.
  29700. */
  29701. Resource.prototype._loadSourceElement = function _loadSourceElement(type) {
  29702. if (this.metadata.loadElement) {
  29703. this.data = this.metadata.loadElement;
  29704. } else if (type === 'audio' && typeof window.Audio !== 'undefined') {
  29705. this.data = new Audio();
  29706. } else {
  29707. this.data = document.createElement(type);
  29708. }
  29709. if (this.data === null) {
  29710. this.abort('Unsupported element: ' + type);
  29711. return;
  29712. }
  29713. if (this.crossOrigin) {
  29714. this.data.crossOrigin = this.crossOrigin;
  29715. }
  29716. if (!this.metadata.skipSource) {
  29717. // support for CocoonJS Canvas+ runtime, lacks document.createElement('source')
  29718. if (navigator.isCocoonJS) {
  29719. this.data.src = Array.isArray(this.url) ? this.url[0] : this.url;
  29720. } else if (Array.isArray(this.url)) {
  29721. var mimeTypes = this.metadata.mimeType;
  29722. for (var i = 0; i < this.url.length; ++i) {
  29723. this.data.appendChild(this._createSource(type, this.url[i], Array.isArray(mimeTypes) ? mimeTypes[i] : mimeTypes));
  29724. }
  29725. } else {
  29726. var _mimeTypes = this.metadata.mimeType;
  29727. this.data.appendChild(this._createSource(type, this.url, Array.isArray(_mimeTypes) ? _mimeTypes[0] : _mimeTypes));
  29728. }
  29729. }
  29730. this.data.addEventListener('error', this._boundOnError, false);
  29731. this.data.addEventListener('load', this._boundComplete, false);
  29732. this.data.addEventListener('progress', this._boundOnProgress, false);
  29733. this.data.addEventListener('canplaythrough', this._boundComplete, false);
  29734. this.data.load();
  29735. if (this.timeout) {
  29736. this._elementTimer = setTimeout(this._boundOnTimeout, this.timeout);
  29737. }
  29738. };
  29739. /**
  29740. * Loads this resources using an XMLHttpRequest.
  29741. *
  29742. * @private
  29743. */
  29744. Resource.prototype._loadXhr = function _loadXhr() {
  29745. // if unset, determine the value
  29746. if (typeof this.xhrType !== 'string') {
  29747. this.xhrType = this._determineXhrType();
  29748. }
  29749. var xhr = this.xhr = new XMLHttpRequest();
  29750. // set the request type and url
  29751. xhr.open('GET', this.url, true);
  29752. xhr.timeout = this.timeout;
  29753. // load json as text and parse it ourselves. We do this because some browsers
  29754. // *cough* safari *cough* can't deal with it.
  29755. if (this.xhrType === Resource.XHR_RESPONSE_TYPE.JSON || this.xhrType === Resource.XHR_RESPONSE_TYPE.DOCUMENT) {
  29756. xhr.responseType = Resource.XHR_RESPONSE_TYPE.TEXT;
  29757. } else {
  29758. xhr.responseType = this.xhrType;
  29759. }
  29760. xhr.addEventListener('error', this._boundXhrOnError, false);
  29761. xhr.addEventListener('timeout', this._boundXhrOnTimeout, false);
  29762. xhr.addEventListener('abort', this._boundXhrOnAbort, false);
  29763. xhr.addEventListener('progress', this._boundOnProgress, false);
  29764. xhr.addEventListener('load', this._boundXhrOnLoad, false);
  29765. xhr.send();
  29766. };
  29767. /**
  29768. * Loads this resources using an XDomainRequest. This is here because we need to support IE9 (gross).
  29769. *
  29770. * @private
  29771. */
  29772. Resource.prototype._loadXdr = function _loadXdr() {
  29773. // if unset, determine the value
  29774. if (typeof this.xhrType !== 'string') {
  29775. this.xhrType = this._determineXhrType();
  29776. }
  29777. var xdr = this.xhr = new XDomainRequest(); // eslint-disable-line no-undef
  29778. // XDomainRequest has a few quirks. Occasionally it will abort requests
  29779. // A way to avoid this is to make sure ALL callbacks are set even if not used
  29780. // More info here: http://stackoverflow.com/questions/15786966/xdomainrequest-aborts-post-on-ie-9
  29781. xdr.timeout = this.timeout || 5000; // XDR needs a timeout value or it breaks in IE9
  29782. xdr.onerror = this._boundXhrOnError;
  29783. xdr.ontimeout = this._boundXhrOnTimeout;
  29784. xdr.onprogress = this._boundOnProgress;
  29785. xdr.onload = this._boundXhrOnLoad;
  29786. xdr.open('GET', this.url, true);
  29787. // Note: The xdr.send() call is wrapped in a timeout to prevent an
  29788. // issue with the interface where some requests are lost if multiple
  29789. // XDomainRequests are being sent at the same time.
  29790. // Some info here: https://github.com/photonstorm/phaser/issues/1248
  29791. setTimeout(function () {
  29792. return xdr.send();
  29793. }, 1);
  29794. };
  29795. /**
  29796. * Creates a source used in loading via an element.
  29797. *
  29798. * @private
  29799. * @param {string} type - The element type (video or audio).
  29800. * @param {string} url - The source URL to load from.
  29801. * @param {string} [mime] - The mime type of the video
  29802. * @return {HTMLSourceElement} The source element.
  29803. */
  29804. Resource.prototype._createSource = function _createSource(type, url, mime) {
  29805. if (!mime) {
  29806. mime = type + '/' + this._getExtension(url);
  29807. }
  29808. var source = document.createElement('source');
  29809. source.src = url;
  29810. source.type = mime;
  29811. return source;
  29812. };
  29813. /**
  29814. * Called if a load errors out.
  29815. *
  29816. * @param {Event} event - The error event from the element that emits it.
  29817. * @private
  29818. */
  29819. Resource.prototype._onError = function _onError(event) {
  29820. this.abort('Failed to load element using: ' + event.target.nodeName);
  29821. };
  29822. /**
  29823. * Called if a load progress event fires for an element or xhr/xdr.
  29824. *
  29825. * @private
  29826. * @param {XMLHttpRequestProgressEvent|Event} event - Progress event.
  29827. */
  29828. Resource.prototype._onProgress = function _onProgress(event) {
  29829. if (event && event.lengthComputable) {
  29830. this.onProgress.dispatch(this, event.loaded / event.total);
  29831. }
  29832. };
  29833. /**
  29834. * Called if a timeout event fires for an element.
  29835. *
  29836. * @private
  29837. */
  29838. Resource.prototype._onTimeout = function _onTimeout() {
  29839. this.abort('Load timed out.');
  29840. };
  29841. /**
  29842. * Called if an error event fires for xhr/xdr.
  29843. *
  29844. * @private
  29845. */
  29846. Resource.prototype._xhrOnError = function _xhrOnError() {
  29847. var xhr = this.xhr;
  29848. this.abort(reqType(xhr) + ' Request failed. Status: ' + xhr.status + ', text: "' + xhr.statusText + '"');
  29849. };
  29850. /**
  29851. * Called if an error event fires for xhr/xdr.
  29852. *
  29853. * @private
  29854. */
  29855. Resource.prototype._xhrOnTimeout = function _xhrOnTimeout() {
  29856. var xhr = this.xhr;
  29857. this.abort(reqType(xhr) + ' Request timed out.');
  29858. };
  29859. /**
  29860. * Called if an abort event fires for xhr/xdr.
  29861. *
  29862. * @private
  29863. */
  29864. Resource.prototype._xhrOnAbort = function _xhrOnAbort() {
  29865. var xhr = this.xhr;
  29866. this.abort(reqType(xhr) + ' Request was aborted by the user.');
  29867. };
  29868. /**
  29869. * Called when data successfully loads from an xhr/xdr request.
  29870. *
  29871. * @private
  29872. * @param {XMLHttpRequestLoadEvent|Event} event - Load event
  29873. */
  29874. Resource.prototype._xhrOnLoad = function _xhrOnLoad() {
  29875. var xhr = this.xhr;
  29876. var text = '';
  29877. var status = typeof xhr.status === 'undefined' ? STATUS_OK : xhr.status; // XDR has no `.status`, assume 200.
  29878. // responseText is accessible only if responseType is '' or 'text' and on older browsers
  29879. if (xhr.responseType === '' || xhr.responseType === 'text' || typeof xhr.responseType === 'undefined') {
  29880. text = xhr.responseText;
  29881. }
  29882. // status can be 0 when using the `file://` protocol so we also check if a response is set.
  29883. // If it has a response, we assume 200; otherwise a 0 status code with no contents is an aborted request.
  29884. if (status === STATUS_NONE && (text.length > 0 || xhr.responseType === Resource.XHR_RESPONSE_TYPE.BUFFER)) {
  29885. status = STATUS_OK;
  29886. }
  29887. // handle IE9 bug: http://stackoverflow.com/questions/10046972/msie-returns-status-code-of-1223-for-ajax-request
  29888. else if (status === STATUS_IE_BUG_EMPTY) {
  29889. status = STATUS_EMPTY;
  29890. }
  29891. var statusType = status / 100 | 0;
  29892. if (statusType === STATUS_TYPE_OK) {
  29893. // if text, just return it
  29894. if (this.xhrType === Resource.XHR_RESPONSE_TYPE.TEXT) {
  29895. this.data = text;
  29896. this.type = Resource.TYPE.TEXT;
  29897. }
  29898. // if json, parse into json object
  29899. else if (this.xhrType === Resource.XHR_RESPONSE_TYPE.JSON) {
  29900. try {
  29901. this.data = JSON.parse(text);
  29902. this.type = Resource.TYPE.JSON;
  29903. } catch (e) {
  29904. this.abort('Error trying to parse loaded json: ' + e);
  29905. return;
  29906. }
  29907. }
  29908. // if xml, parse into an xml document or div element
  29909. else if (this.xhrType === Resource.XHR_RESPONSE_TYPE.DOCUMENT) {
  29910. try {
  29911. if (window.DOMParser) {
  29912. var domparser = new DOMParser();
  29913. this.data = domparser.parseFromString(text, 'text/xml');
  29914. } else {
  29915. var div = document.createElement('div');
  29916. div.innerHTML = text;
  29917. this.data = div;
  29918. }
  29919. this.type = Resource.TYPE.XML;
  29920. } catch (e) {
  29921. this.abort('Error trying to parse loaded xml: ' + e);
  29922. return;
  29923. }
  29924. }
  29925. // other types just return the response
  29926. else {
  29927. this.data = xhr.response || text;
  29928. }
  29929. } else {
  29930. this.abort('[' + xhr.status + '] ' + xhr.statusText + ': ' + xhr.responseURL);
  29931. return;
  29932. }
  29933. this.complete();
  29934. };
  29935. /**
  29936. * Sets the `crossOrigin` property for this resource based on if the url
  29937. * for this resource is cross-origin. If crossOrigin was manually set, this
  29938. * function does nothing.
  29939. *
  29940. * @private
  29941. * @param {string} url - The url to test.
  29942. * @param {object} [loc=window.location] - The location object to test against.
  29943. * @return {string} The crossOrigin value to use (or empty string for none).
  29944. */
  29945. Resource.prototype._determineCrossOrigin = function _determineCrossOrigin(url, loc) {
  29946. // data: and javascript: urls are considered same-origin
  29947. if (url.indexOf('data:') === 0) {
  29948. return '';
  29949. }
  29950. // A sandboxed iframe without the 'allow-same-origin' attribute will have a special
  29951. // origin designed not to match window.location.origin, and will always require
  29952. // crossOrigin requests regardless of whether the location matches.
  29953. if (window.origin !== window.location.origin) {
  29954. return 'anonymous';
  29955. }
  29956. // default is window.location
  29957. loc = loc || window.location;
  29958. if (!tempAnchor) {
  29959. tempAnchor = document.createElement('a');
  29960. }
  29961. // let the browser determine the full href for the url of this resource and then
  29962. // parse with the node url lib, we can't use the properties of the anchor element
  29963. // because they don't work in IE9 :(
  29964. tempAnchor.href = url;
  29965. url = (0, _parseUri2.default)(tempAnchor.href, { strictMode: true });
  29966. var samePort = !url.port && loc.port === '' || url.port === loc.port;
  29967. var protocol = url.protocol ? url.protocol + ':' : '';
  29968. // if cross origin
  29969. if (url.host !== loc.hostname || !samePort || protocol !== loc.protocol) {
  29970. return 'anonymous';
  29971. }
  29972. return '';
  29973. };
  29974. /**
  29975. * Determines the responseType of an XHR request based on the extension of the
  29976. * resource being loaded.
  29977. *
  29978. * @private
  29979. * @return {Resource.XHR_RESPONSE_TYPE} The responseType to use.
  29980. */
  29981. Resource.prototype._determineXhrType = function _determineXhrType() {
  29982. return Resource._xhrTypeMap[this.extension] || Resource.XHR_RESPONSE_TYPE.TEXT;
  29983. };
  29984. /**
  29985. * Determines the loadType of a resource based on the extension of the
  29986. * resource being loaded.
  29987. *
  29988. * @private
  29989. * @return {Resource.LOAD_TYPE} The loadType to use.
  29990. */
  29991. Resource.prototype._determineLoadType = function _determineLoadType() {
  29992. return Resource._loadTypeMap[this.extension] || Resource.LOAD_TYPE.XHR;
  29993. };
  29994. /**
  29995. * Extracts the extension (sans '.') of the file being loaded by the resource.
  29996. *
  29997. * @private
  29998. * @return {string} The extension.
  29999. */
  30000. Resource.prototype._getExtension = function _getExtension() {
  30001. var url = this.url;
  30002. var ext = '';
  30003. if (this.isDataUrl) {
  30004. var slashIndex = url.indexOf('/');
  30005. ext = url.substring(slashIndex + 1, url.indexOf(';', slashIndex));
  30006. } else {
  30007. var queryStart = url.indexOf('?');
  30008. var hashStart = url.indexOf('#');
  30009. var index = Math.min(queryStart > -1 ? queryStart : url.length, hashStart > -1 ? hashStart : url.length);
  30010. url = url.substring(0, index);
  30011. ext = url.substring(url.lastIndexOf('.') + 1);
  30012. }
  30013. return ext.toLowerCase();
  30014. };
  30015. /**
  30016. * Determines the mime type of an XHR request based on the responseType of
  30017. * resource being loaded.
  30018. *
  30019. * @private
  30020. * @param {Resource.XHR_RESPONSE_TYPE} type - The type to get a mime type for.
  30021. * @return {string} The mime type to use.
  30022. */
  30023. Resource.prototype._getMimeFromXhrType = function _getMimeFromXhrType(type) {
  30024. switch (type) {
  30025. case Resource.XHR_RESPONSE_TYPE.BUFFER:
  30026. return 'application/octet-binary';
  30027. case Resource.XHR_RESPONSE_TYPE.BLOB:
  30028. return 'application/blob';
  30029. case Resource.XHR_RESPONSE_TYPE.DOCUMENT:
  30030. return 'application/xml';
  30031. case Resource.XHR_RESPONSE_TYPE.JSON:
  30032. return 'application/json';
  30033. case Resource.XHR_RESPONSE_TYPE.DEFAULT:
  30034. case Resource.XHR_RESPONSE_TYPE.TEXT:
  30035. /* falls through */
  30036. default:
  30037. return 'text/plain';
  30038. }
  30039. };
  30040. _createClass(Resource, [{
  30041. key: 'isDataUrl',
  30042. get: function get() {
  30043. return this._hasFlag(Resource.STATUS_FLAGS.DATA_URL);
  30044. }
  30045. /**
  30046. * Describes if this resource has finished loading. Is true when the resource has completely
  30047. * loaded.
  30048. *
  30049. * @readonly
  30050. * @member {boolean}
  30051. */
  30052. }, {
  30053. key: 'isComplete',
  30054. get: function get() {
  30055. return this._hasFlag(Resource.STATUS_FLAGS.COMPLETE);
  30056. }
  30057. /**
  30058. * Describes if this resource is currently loading. Is true when the resource starts loading,
  30059. * and is false again when complete.
  30060. *
  30061. * @readonly
  30062. * @member {boolean}
  30063. */
  30064. }, {
  30065. key: 'isLoading',
  30066. get: function get() {
  30067. return this._hasFlag(Resource.STATUS_FLAGS.LOADING);
  30068. }
  30069. }]);
  30070. return Resource;
  30071. }();
  30072. /**
  30073. * The types of resources a resource could represent.
  30074. *
  30075. * @static
  30076. * @readonly
  30077. * @enum {number}
  30078. */
  30079. Resource.STATUS_FLAGS = {
  30080. NONE: 0,
  30081. DATA_URL: 1 << 0,
  30082. COMPLETE: 1 << 1,
  30083. LOADING: 1 << 2
  30084. };
  30085. /**
  30086. * The types of resources a resource could represent.
  30087. *
  30088. * @static
  30089. * @readonly
  30090. * @enum {number}
  30091. */
  30092. Resource.TYPE = {
  30093. UNKNOWN: 0,
  30094. JSON: 1,
  30095. XML: 2,
  30096. IMAGE: 3,
  30097. AUDIO: 4,
  30098. VIDEO: 5,
  30099. TEXT: 6
  30100. };
  30101. /**
  30102. * The types of loading a resource can use.
  30103. *
  30104. * @static
  30105. * @readonly
  30106. * @enum {number}
  30107. */
  30108. Resource.LOAD_TYPE = {
  30109. /** Uses XMLHttpRequest to load the resource. */
  30110. XHR: 1,
  30111. /** Uses an `Image` object to load the resource. */
  30112. IMAGE: 2,
  30113. /** Uses an `Audio` object to load the resource. */
  30114. AUDIO: 3,
  30115. /** Uses a `Video` object to load the resource. */
  30116. VIDEO: 4
  30117. };
  30118. /**
  30119. * The XHR ready states, used internally.
  30120. *
  30121. * @static
  30122. * @readonly
  30123. * @enum {string}
  30124. */
  30125. Resource.XHR_RESPONSE_TYPE = {
  30126. /** string */
  30127. DEFAULT: 'text',
  30128. /** ArrayBuffer */
  30129. BUFFER: 'arraybuffer',
  30130. /** Blob */
  30131. BLOB: 'blob',
  30132. /** Document */
  30133. DOCUMENT: 'document',
  30134. /** Object */
  30135. JSON: 'json',
  30136. /** String */
  30137. TEXT: 'text'
  30138. };
  30139. Resource._loadTypeMap = {
  30140. // images
  30141. gif: Resource.LOAD_TYPE.IMAGE,
  30142. png: Resource.LOAD_TYPE.IMAGE,
  30143. bmp: Resource.LOAD_TYPE.IMAGE,
  30144. jpg: Resource.LOAD_TYPE.IMAGE,
  30145. jpeg: Resource.LOAD_TYPE.IMAGE,
  30146. tif: Resource.LOAD_TYPE.IMAGE,
  30147. tiff: Resource.LOAD_TYPE.IMAGE,
  30148. webp: Resource.LOAD_TYPE.IMAGE,
  30149. tga: Resource.LOAD_TYPE.IMAGE,
  30150. svg: Resource.LOAD_TYPE.IMAGE,
  30151. 'svg+xml': Resource.LOAD_TYPE.IMAGE, // for SVG data urls
  30152. // audio
  30153. mp3: Resource.LOAD_TYPE.AUDIO,
  30154. ogg: Resource.LOAD_TYPE.AUDIO,
  30155. wav: Resource.LOAD_TYPE.AUDIO,
  30156. // videos
  30157. mp4: Resource.LOAD_TYPE.VIDEO,
  30158. webm: Resource.LOAD_TYPE.VIDEO
  30159. };
  30160. Resource._xhrTypeMap = {
  30161. // xml
  30162. xhtml: Resource.XHR_RESPONSE_TYPE.DOCUMENT,
  30163. html: Resource.XHR_RESPONSE_TYPE.DOCUMENT,
  30164. htm: Resource.XHR_RESPONSE_TYPE.DOCUMENT,
  30165. xml: Resource.XHR_RESPONSE_TYPE.DOCUMENT,
  30166. tmx: Resource.XHR_RESPONSE_TYPE.DOCUMENT,
  30167. svg: Resource.XHR_RESPONSE_TYPE.DOCUMENT,
  30168. // This was added to handle Tiled Tileset XML, but .tsx is also a TypeScript React Component.
  30169. // Since it is way less likely for people to be loading TypeScript files instead of Tiled files,
  30170. // this should probably be fine.
  30171. tsx: Resource.XHR_RESPONSE_TYPE.DOCUMENT,
  30172. // images
  30173. gif: Resource.XHR_RESPONSE_TYPE.BLOB,
  30174. png: Resource.XHR_RESPONSE_TYPE.BLOB,
  30175. bmp: Resource.XHR_RESPONSE_TYPE.BLOB,
  30176. jpg: Resource.XHR_RESPONSE_TYPE.BLOB,
  30177. jpeg: Resource.XHR_RESPONSE_TYPE.BLOB,
  30178. tif: Resource.XHR_RESPONSE_TYPE.BLOB,
  30179. tiff: Resource.XHR_RESPONSE_TYPE.BLOB,
  30180. webp: Resource.XHR_RESPONSE_TYPE.BLOB,
  30181. tga: Resource.XHR_RESPONSE_TYPE.BLOB,
  30182. // json
  30183. json: Resource.XHR_RESPONSE_TYPE.JSON,
  30184. // text
  30185. text: Resource.XHR_RESPONSE_TYPE.TEXT,
  30186. txt: Resource.XHR_RESPONSE_TYPE.TEXT,
  30187. // fonts
  30188. ttf: Resource.XHR_RESPONSE_TYPE.BUFFER,
  30189. otf: Resource.XHR_RESPONSE_TYPE.BUFFER
  30190. };
  30191. // We can't set the `src` attribute to empty string, so on abort we set it to this 1px transparent gif
  30192. Resource.EMPTY_GIF = 'data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==';
  30193. /**
  30194. * Quick helper to set a value on one of the extension maps. Ensures there is no
  30195. * dot at the start of the extension.
  30196. *
  30197. * @ignore
  30198. * @param {object} map - The map to set on.
  30199. * @param {string} extname - The extension (or key) to set.
  30200. * @param {number} val - The value to set.
  30201. */
  30202. function setExtMap(map, extname, val) {
  30203. if (extname && extname.indexOf('.') === 0) {
  30204. extname = extname.substring(1);
  30205. }
  30206. if (!extname) {
  30207. return;
  30208. }
  30209. map[extname] = val;
  30210. }
  30211. /**
  30212. * Quick helper to get string xhr type.
  30213. *
  30214. * @ignore
  30215. * @param {XMLHttpRequest|XDomainRequest} xhr - The request to check.
  30216. * @return {string} The type.
  30217. */
  30218. function reqType(xhr) {
  30219. return xhr.toString().replace('object ', '');
  30220. }
  30221. // Backwards compat
  30222. {
  30223. module.exports.default = Resource; // eslint-disable-line no-undef
  30224. }
  30225. });
  30226. unwrapExports$1(Resource_1$1);
  30227. var Resource_2$1 = Resource_1$1.Resource;
  30228. var b64$2 = createCommonjsModule$1(function (module, exports) {
  30229. exports.__esModule = true;
  30230. exports.encodeBinary = encodeBinary;
  30231. var _keyStr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
  30232. /**
  30233. * Encodes binary into base64.
  30234. *
  30235. * @param {string} input The input data to encode.
  30236. * @returns {string} The encoded base64 string
  30237. */
  30238. function encodeBinary(input) {
  30239. var output = '';
  30240. var inx = 0;
  30241. while (inx < input.length) {
  30242. // Fill byte buffer array
  30243. var bytebuffer = [0, 0, 0];
  30244. var encodedCharIndexes = [0, 0, 0, 0];
  30245. for (var jnx = 0; jnx < bytebuffer.length; ++jnx) {
  30246. if (inx < input.length) {
  30247. // throw away high-order byte, as documented at:
  30248. // https://developer.mozilla.org/En/Using_XMLHttpRequest#Handling_binary_data
  30249. bytebuffer[jnx] = input.charCodeAt(inx++) & 0xff;
  30250. } else {
  30251. bytebuffer[jnx] = 0;
  30252. }
  30253. }
  30254. // Get each encoded character, 6 bits at a time
  30255. // index 1: first 6 bits
  30256. encodedCharIndexes[0] = bytebuffer[0] >> 2;
  30257. // index 2: second 6 bits (2 least significant bits from input byte 1 + 4 most significant bits from byte 2)
  30258. encodedCharIndexes[1] = (bytebuffer[0] & 0x3) << 4 | bytebuffer[1] >> 4;
  30259. // index 3: third 6 bits (4 least significant bits from input byte 2 + 2 most significant bits from byte 3)
  30260. encodedCharIndexes[2] = (bytebuffer[1] & 0x0f) << 2 | bytebuffer[2] >> 6;
  30261. // index 3: forth 6 bits (6 least significant bits from input byte 3)
  30262. encodedCharIndexes[3] = bytebuffer[2] & 0x3f;
  30263. // Determine whether padding happened, and adjust accordingly
  30264. var paddingBytes = inx - (input.length - 1);
  30265. switch (paddingBytes) {
  30266. case 2:
  30267. // Set last 2 characters to padding char
  30268. encodedCharIndexes[3] = 64;
  30269. encodedCharIndexes[2] = 64;
  30270. break;
  30271. case 1:
  30272. // Set last character to padding char
  30273. encodedCharIndexes[3] = 64;
  30274. break;
  30275. default:
  30276. break; // No padding - proceed
  30277. }
  30278. // Now we will grab each appropriate character out of our keystring
  30279. // based on our index array and append it to the output string
  30280. for (var _jnx = 0; _jnx < encodedCharIndexes.length; ++_jnx) {
  30281. output += _keyStr.charAt(encodedCharIndexes[_jnx]);
  30282. }
  30283. }
  30284. return output;
  30285. }
  30286. // Backwards compat
  30287. {
  30288. module.exports.default = encodeBinary; // eslint-disable-line no-undef
  30289. }
  30290. });
  30291. unwrapExports$1(b64$2);
  30292. var b64_1$1 = b64$2.encodeBinary;
  30293. var blob = createCommonjsModule$1(function (module, exports) {
  30294. exports.__esModule = true;
  30295. exports.blobMiddlewareFactory = blobMiddlewareFactory;
  30296. var Url = window.URL || window.webkitURL;
  30297. // a middleware for transforming XHR loaded Blobs into more useful objects
  30298. function blobMiddlewareFactory() {
  30299. return function blobMiddleware(resource, next) {
  30300. if (!resource.data) {
  30301. next();
  30302. return;
  30303. }
  30304. // if this was an XHR load of a blob
  30305. if (resource.xhr && resource.xhrType === Resource_1$1.Resource.XHR_RESPONSE_TYPE.BLOB) {
  30306. // if there is no blob support we probably got a binary string back
  30307. if (!window.Blob || typeof resource.data === 'string') {
  30308. var type = resource.xhr.getResponseHeader('content-type');
  30309. // this is an image, convert the binary string into a data url
  30310. if (type && type.indexOf('image') === 0) {
  30311. resource.data = new Image();
  30312. resource.data.src = 'data:' + type + ';base64,' + (0, b64$2.encodeBinary)(resource.xhr.responseText);
  30313. resource.type = Resource_1$1.Resource.TYPE.IMAGE;
  30314. // wait until the image loads and then callback
  30315. resource.data.onload = function () {
  30316. resource.data.onload = null;
  30317. next();
  30318. };
  30319. // next will be called on load
  30320. return;
  30321. }
  30322. }
  30323. // if content type says this is an image, then we should transform the blob into an Image object
  30324. else if (resource.data.type.indexOf('image') === 0) {
  30325. var src = Url.createObjectURL(resource.data);
  30326. resource.blob = resource.data;
  30327. resource.data = new Image();
  30328. resource.data.src = src;
  30329. resource.type = Resource_1$1.Resource.TYPE.IMAGE;
  30330. // cleanup the no longer used blob after the image loads
  30331. // TODO: Is this correct? Will the image be invalid after revoking?
  30332. resource.data.onload = function () {
  30333. Url.revokeObjectURL(src);
  30334. resource.data.onload = null;
  30335. next();
  30336. };
  30337. // next will be called on load.
  30338. return;
  30339. }
  30340. }
  30341. next();
  30342. };
  30343. }
  30344. });
  30345. unwrapExports$1(blob);
  30346. var blob_1 = blob.blobMiddlewareFactory;
  30347. /**
  30348. * Loader plugin for handling Texture resources.
  30349. * @class
  30350. * @memberof PIXI
  30351. * @implements PIXI.ILoaderPlugin
  30352. */
  30353. var TextureLoader = function TextureLoader () {};
  30354. TextureLoader.use = function use (resource, next)
  30355. {
  30356. // create a new texture if the data is an Image object
  30357. if (resource.data && resource.type === lib_1.TYPE.IMAGE)
  30358. {
  30359. resource.texture = Texture.fromLoader(
  30360. resource.data,
  30361. resource.url,
  30362. resource.name
  30363. );
  30364. }
  30365. next();
  30366. };
  30367. /**
  30368. * The new loader, extends Resource Loader by Chad Engler: https://github.com/englercj/resource-loader
  30369. *
  30370. * ```js
  30371. * const loader = PIXI.Loader.shared; // PixiJS exposes a premade instance for you to use.
  30372. * //or
  30373. * const loader = new PIXI.Loader(); // you can also create your own if you want
  30374. *
  30375. * const sprites = {};
  30376. *
  30377. * // Chainable `add` to enqueue a resource
  30378. * loader.add('bunny', 'data/bunny.png')
  30379. * .add('spaceship', 'assets/spritesheet.json');
  30380. * loader.add('scoreFont', 'assets/score.fnt');
  30381. *
  30382. * // Chainable `pre` to add a middleware that runs for each resource, *before* loading that resource.
  30383. * // This is useful to implement custom caching modules (using filesystem, indexeddb, memory, etc).
  30384. * loader.pre(cachingMiddleware);
  30385. *
  30386. * // Chainable `use` to add a middleware that runs for each resource, *after* loading that resource.
  30387. * // This is useful to implement custom parsing modules (like spritesheet parsers, spine parser, etc).
  30388. * loader.use(parsingMiddleware);
  30389. *
  30390. * // The `load` method loads the queue of resources, and calls the passed in callback called once all
  30391. * // resources have loaded.
  30392. * loader.load((loader, resources) => {
  30393. * // resources is an object where the key is the name of the resource loaded and the value is the resource object.
  30394. * // They have a couple default properties:
  30395. * // - `url`: The URL that the resource was loaded from
  30396. * // - `error`: The error that happened when trying to load (if any)
  30397. * // - `data`: The raw data that was loaded
  30398. * // also may contain other properties based on the middleware that runs.
  30399. * sprites.bunny = new PIXI.TilingSprite(resources.bunny.texture);
  30400. * sprites.spaceship = new PIXI.TilingSprite(resources.spaceship.texture);
  30401. * sprites.scoreFont = new PIXI.TilingSprite(resources.scoreFont.texture);
  30402. * });
  30403. *
  30404. * // throughout the process multiple signals can be dispatched.
  30405. * loader.onProgress.add(() => {}); // called once per loaded/errored file
  30406. * loader.onError.add(() => {}); // called once per errored file
  30407. * loader.onLoad.add(() => {}); // called once per loaded file
  30408. * loader.onComplete.add(() => {}); // called once when the queued resources all load.
  30409. * ```
  30410. *
  30411. * @see https://github.com/englercj/resource-loader
  30412. *
  30413. * @class Loader
  30414. * @memberof PIXI
  30415. * @param {string} [baseUrl=''] - The base url for all resources loaded by this loader.
  30416. * @param {number} [concurrency=10] - The number of resources to load concurrently.
  30417. */
  30418. var Loader$2 = /*@__PURE__*/(function (ResourceLoader) {
  30419. function Loader(baseUrl, concurrency)
  30420. {
  30421. var this$1 = this;
  30422. ResourceLoader.call(this, baseUrl, concurrency);
  30423. eventemitter3.call(this);
  30424. for (var i = 0; i < Loader._plugins.length; ++i)
  30425. {
  30426. var plugin = Loader._plugins[i];
  30427. var pre = plugin.pre;
  30428. var use = plugin.use;
  30429. if (pre)
  30430. {
  30431. this.pre(pre);
  30432. }
  30433. if (use)
  30434. {
  30435. this.use(use);
  30436. }
  30437. }
  30438. // Compat layer, translate the new v2 signals into old v1 events.
  30439. this.onStart.add(function (l) { return this$1.emit('start', l); });
  30440. this.onProgress.add(function (l, r) { return this$1.emit('progress', l, r); });
  30441. this.onError.add(function (e, l, r) { return this$1.emit('error', e, l, r); });
  30442. this.onLoad.add(function (l, r) { return this$1.emit('load', l, r); });
  30443. this.onComplete.add(function (l, r) { return this$1.emit('complete', l, r); });
  30444. /**
  30445. * If this loader cannot be destroyed.
  30446. * @member {boolean}
  30447. * @default false
  30448. * @private
  30449. */
  30450. this._protected = false;
  30451. }
  30452. if ( ResourceLoader ) { Loader.__proto__ = ResourceLoader; }
  30453. Loader.prototype = Object.create( ResourceLoader && ResourceLoader.prototype );
  30454. Loader.prototype.constructor = Loader;
  30455. var staticAccessors = { shared: { configurable: true } };
  30456. /**
  30457. * Destroy the loader, removes references.
  30458. * @private
  30459. */
  30460. Loader.prototype.destroy = function destroy ()
  30461. {
  30462. if (!this._protected)
  30463. {
  30464. this.removeAllListeners();
  30465. this.reset();
  30466. }
  30467. };
  30468. /**
  30469. * A premade instance of the loader that can be used to load resources.
  30470. * @name shared
  30471. * @type {PIXI.Loader}
  30472. * @static
  30473. * @memberof PIXI.Loader
  30474. */
  30475. staticAccessors.shared.get = function ()
  30476. {
  30477. var shared = Loader._shared;
  30478. if (!shared)
  30479. {
  30480. shared = new Loader();
  30481. shared._protected = true;
  30482. Loader._shared = shared;
  30483. }
  30484. return shared;
  30485. };
  30486. Object.defineProperties( Loader, staticAccessors );
  30487. return Loader;
  30488. }(lib));
  30489. // Copy EE3 prototype (mixin)
  30490. Object.assign(Loader$2.prototype, eventemitter3.prototype);
  30491. /**
  30492. * Collection of all installed `use` middleware for Loader.
  30493. *
  30494. * @static
  30495. * @member {Array<PIXI.ILoaderPlugin>} _plugins
  30496. * @memberof PIXI.Loader
  30497. * @private
  30498. */
  30499. Loader$2._plugins = [];
  30500. /**
  30501. * Adds a Loader plugin for the global shared loader and all
  30502. * new Loader instances created.
  30503. *
  30504. * @static
  30505. * @method registerPlugin
  30506. * @memberof PIXI.Loader
  30507. * @param {PIXI.ILoaderPlugin} plugin - The plugin to add
  30508. * @return {PIXI.Loader} Reference to PIXI.Loader for chaining
  30509. */
  30510. Loader$2.registerPlugin = function registerPlugin(plugin)
  30511. {
  30512. Loader$2._plugins.push(plugin);
  30513. if (plugin.add)
  30514. {
  30515. plugin.add();
  30516. }
  30517. return Loader$2;
  30518. };
  30519. // parse any blob into more usable objects (e.g. Image)
  30520. Loader$2.registerPlugin({ use: blob_1() });
  30521. // parse any Image objects into textures
  30522. Loader$2.registerPlugin(TextureLoader);
  30523. /**
  30524. * Plugin to be installed for handling specific Loader resources.
  30525. *
  30526. * @memberof PIXI
  30527. * @typedef ILoaderPlugin
  30528. * @property {function} [add] - Function to call immediate after registering plugin.
  30529. * @property {PIXI.Loader.loaderMiddleware} [pre] - Middleware function to run before load, the
  30530. * arguments for this are `(resource, next)`
  30531. * @property {PIXI.Loader.loaderMiddleware} [use] - Middleware function to run after load, the
  30532. * arguments for this are `(resource, next)`
  30533. */
  30534. /**
  30535. * @memberof PIXI.Loader
  30536. * @callback loaderMiddleware
  30537. * @param {PIXI.LoaderResource} resource
  30538. * @param {function} next
  30539. */
  30540. /**
  30541. * @memberof PIXI.Loader#
  30542. * @member {object} onStart
  30543. */
  30544. /**
  30545. * @memberof PIXI.Loader#
  30546. * @member {object} onProgress
  30547. */
  30548. /**
  30549. * @memberof PIXI.Loader#
  30550. * @member {object} onError
  30551. */
  30552. /**
  30553. * @memberof PIXI.Loader#
  30554. * @member {object} onLoad
  30555. */
  30556. /**
  30557. * @memberof PIXI.Loader#
  30558. * @member {object} onComplete
  30559. */
  30560. /**
  30561. * Application plugin for supporting loader option. Installing the LoaderPlugin
  30562. * is not necessary if using **pixi.js** or **pixi.js-legacy**.
  30563. * @example
  30564. * import {AppLoaderPlugin} from '@pixi/loaders';
  30565. * import {Application} from '@pixi/app';
  30566. * Application.registerPlugin(AppLoaderPlugin);
  30567. * @class
  30568. * @memberof PIXI
  30569. */
  30570. var AppLoaderPlugin = function AppLoaderPlugin () {};
  30571. AppLoaderPlugin.init = function init (options)
  30572. {
  30573. options = Object.assign({
  30574. sharedLoader: false,
  30575. }, options);
  30576. /**
  30577. * Loader instance to help with asset loading.
  30578. * @name PIXI.Application#loader
  30579. * @type {PIXI.Loader}
  30580. * @readonly
  30581. */
  30582. this.loader = options.sharedLoader ? Loader$2.shared : new Loader$2();
  30583. };
  30584. /**
  30585. * Called when application destroyed
  30586. * @private
  30587. */
  30588. AppLoaderPlugin.destroy = function destroy ()
  30589. {
  30590. if (this.loader)
  30591. {
  30592. this.loader.destroy();
  30593. this.loader = null;
  30594. }
  30595. };
  30596. /**
  30597. * Reference to **{@link https://github.com/englercj/resource-loader
  30598. * resource-loader}**'s Resource class.
  30599. * @see http://englercj.github.io/resource-loader/Resource.html
  30600. * @class LoaderResource
  30601. * @memberof PIXI
  30602. */
  30603. var LoaderResource = lib_1;
  30604. /*!
  30605. * @pixi/particles - v5.0.4
  30606. * Compiled Fri, 07 Jun 2019 17:17:49 UTC
  30607. *
  30608. * @pixi/particles is licensed under the MIT License.
  30609. * http://www.opensource.org/licenses/mit-license
  30610. */
  30611. /**
  30612. * The ParticleContainer class is a really fast version of the Container built solely for speed,
  30613. * so use when you need a lot of sprites or particles.
  30614. *
  30615. * The tradeoff of the ParticleContainer is that most advanced functionality will not work.
  30616. * ParticleContainer implements the basic object transform (position, scale, rotation)
  30617. * and some advanced functionality like tint (as of v4.5.6).
  30618. *
  30619. * Other more advanced functionality like masking, children, filters, etc will not work on sprites in this batch.
  30620. *
  30621. * It's extremely easy to use:
  30622. * ```js
  30623. * let container = new ParticleContainer();
  30624. *
  30625. * for (let i = 0; i < 100; ++i)
  30626. * {
  30627. * let sprite = PIXI.Sprite.from("myImage.png");
  30628. * container.addChild(sprite);
  30629. * }
  30630. * ```
  30631. *
  30632. * And here you have a hundred sprites that will be rendered at the speed of light.
  30633. *
  30634. * @class
  30635. * @extends PIXI.Container
  30636. * @memberof PIXI
  30637. */
  30638. var ParticleContainer = /*@__PURE__*/(function (Container) {
  30639. function ParticleContainer(maxSize, properties, batchSize, autoResize)
  30640. {
  30641. if ( maxSize === void 0 ) { maxSize = 1500; }
  30642. if ( batchSize === void 0 ) { batchSize = 16384; }
  30643. if ( autoResize === void 0 ) { autoResize = false; }
  30644. Container.call(this);
  30645. // Making sure the batch size is valid
  30646. // 65535 is max vertex index in the index buffer (see ParticleRenderer)
  30647. // so max number of particles is 65536 / 4 = 16384
  30648. var maxBatchSize = 16384;
  30649. if (batchSize > maxBatchSize)
  30650. {
  30651. batchSize = maxBatchSize;
  30652. }
  30653. /**
  30654. * Set properties to be dynamic (true) / static (false)
  30655. *
  30656. * @member {boolean[]}
  30657. * @private
  30658. */
  30659. this._properties = [false, true, false, false, false];
  30660. /**
  30661. * @member {number}
  30662. * @private
  30663. */
  30664. this._maxSize = maxSize;
  30665. /**
  30666. * @member {number}
  30667. * @private
  30668. */
  30669. this._batchSize = batchSize;
  30670. /**
  30671. * @member {Array<PIXI.Buffer>}
  30672. * @private
  30673. */
  30674. this._buffers = null;
  30675. /**
  30676. * for every batch stores _updateID corresponding to the last change in that batch
  30677. * @member {number[]}
  30678. * @private
  30679. */
  30680. this._bufferUpdateIDs = [];
  30681. /**
  30682. * when child inserted, removed or changes position this number goes up
  30683. * @member {number[]}
  30684. * @private
  30685. */
  30686. this._updateID = 0;
  30687. /**
  30688. * @member {boolean}
  30689. *
  30690. */
  30691. this.interactiveChildren = false;
  30692. /**
  30693. * The blend mode to be applied to the sprite. Apply a value of `PIXI.BLEND_MODES.NORMAL`
  30694. * to reset the blend mode.
  30695. *
  30696. * @member {number}
  30697. * @default PIXI.BLEND_MODES.NORMAL
  30698. * @see PIXI.BLEND_MODES
  30699. */
  30700. this.blendMode = BLEND_MODES.NORMAL;
  30701. /**
  30702. * If true, container allocates more batches in case there are more than `maxSize` particles.
  30703. * @member {boolean}
  30704. * @default false
  30705. */
  30706. this.autoResize = autoResize;
  30707. /**
  30708. * If true PixiJS will Math.floor() x/y values when rendering, stopping pixel interpolation.
  30709. * Advantages can include sharper image quality (like text) and faster rendering on canvas.
  30710. * The main disadvantage is movement of objects may appear less smooth.
  30711. * Default to true here as performance is usually the priority for particles.
  30712. *
  30713. * @member {boolean}
  30714. * @default true
  30715. */
  30716. this.roundPixels = true;
  30717. /**
  30718. * The texture used to render the children.
  30719. *
  30720. * @readonly
  30721. * @member {PIXI.BaseTexture}
  30722. */
  30723. this.baseTexture = null;
  30724. this.setProperties(properties);
  30725. /**
  30726. * The tint applied to the container.
  30727. * This is a hex value. A value of 0xFFFFFF will remove any tint effect.
  30728. *
  30729. * @private
  30730. * @member {number}
  30731. * @default 0xFFFFFF
  30732. */
  30733. this._tint = 0;
  30734. this.tintRgb = new Float32Array(4);
  30735. this.tint = 0xFFFFFF;
  30736. }
  30737. if ( Container ) { ParticleContainer.__proto__ = Container; }
  30738. ParticleContainer.prototype = Object.create( Container && Container.prototype );
  30739. ParticleContainer.prototype.constructor = ParticleContainer;
  30740. var prototypeAccessors = { tint: { configurable: true } };
  30741. /**
  30742. * Sets the private properties array to dynamic / static based on the passed properties object
  30743. *
  30744. * @param {object} properties - The properties to be uploaded
  30745. */
  30746. ParticleContainer.prototype.setProperties = function setProperties (properties)
  30747. {
  30748. if (properties)
  30749. {
  30750. this._properties[0] = 'vertices' in properties || 'scale' in properties
  30751. ? !!properties.vertices || !!properties.scale : this._properties[0];
  30752. this._properties[1] = 'position' in properties ? !!properties.position : this._properties[1];
  30753. this._properties[2] = 'rotation' in properties ? !!properties.rotation : this._properties[2];
  30754. this._properties[3] = 'uvs' in properties ? !!properties.uvs : this._properties[3];
  30755. this._properties[4] = 'tint' in properties || 'alpha' in properties
  30756. ? !!properties.tint || !!properties.alpha : this._properties[4];
  30757. }
  30758. };
  30759. /**
  30760. * Updates the object transform for rendering
  30761. *
  30762. * @private
  30763. */
  30764. ParticleContainer.prototype.updateTransform = function updateTransform ()
  30765. {
  30766. // TODO don't need to!
  30767. this.displayObjectUpdateTransform();
  30768. // PIXI.Container.prototype.updateTransform.call( this );
  30769. };
  30770. /**
  30771. * The tint applied to the container. This is a hex value.
  30772. * A value of 0xFFFFFF will remove any tint effect.
  30773. ** IMPORTANT: This is a WebGL only feature and will be ignored by the canvas renderer.
  30774. * @member {number}
  30775. * @default 0xFFFFFF
  30776. */
  30777. prototypeAccessors.tint.get = function ()
  30778. {
  30779. return this._tint;
  30780. };
  30781. prototypeAccessors.tint.set = function (value) // eslint-disable-line require-jsdoc
  30782. {
  30783. this._tint = value;
  30784. hex2rgb(value, this.tintRgb);
  30785. };
  30786. /**
  30787. * Renders the container using the WebGL renderer
  30788. *
  30789. * @private
  30790. * @param {PIXI.Renderer} renderer - The webgl renderer
  30791. */
  30792. ParticleContainer.prototype.render = function render (renderer)
  30793. {
  30794. var this$1 = this;
  30795. if (!this.visible || this.worldAlpha <= 0 || !this.children.length || !this.renderable)
  30796. {
  30797. return;
  30798. }
  30799. if (!this.baseTexture)
  30800. {
  30801. this.baseTexture = this.children[0]._texture.baseTexture;
  30802. if (!this.baseTexture.valid)
  30803. {
  30804. this.baseTexture.once('update', function () { return this$1.onChildrenChange(0); });
  30805. }
  30806. }
  30807. renderer.batch.setObjectRenderer(renderer.plugins.particle);
  30808. renderer.plugins.particle.render(this);
  30809. };
  30810. /**
  30811. * Set the flag that static data should be updated to true
  30812. *
  30813. * @private
  30814. * @param {number} smallestChildIndex - The smallest child index
  30815. */
  30816. ParticleContainer.prototype.onChildrenChange = function onChildrenChange (smallestChildIndex)
  30817. {
  30818. var bufferIndex = Math.floor(smallestChildIndex / this._batchSize);
  30819. while (this._bufferUpdateIDs.length < bufferIndex)
  30820. {
  30821. this._bufferUpdateIDs.push(0);
  30822. }
  30823. this._bufferUpdateIDs[bufferIndex] = ++this._updateID;
  30824. };
  30825. ParticleContainer.prototype.dispose = function dispose ()
  30826. {
  30827. if (this._buffers)
  30828. {
  30829. for (var i = 0; i < this._buffers.length; ++i)
  30830. {
  30831. this._buffers[i].destroy();
  30832. }
  30833. this._buffers = null;
  30834. }
  30835. };
  30836. /**
  30837. * Destroys the container
  30838. *
  30839. * @param {object|boolean} [options] - Options parameter. A boolean will act as if all options
  30840. * have been set to that value
  30841. * @param {boolean} [options.children=false] - if set to true, all the children will have their
  30842. * destroy method called as well. 'options' will be passed on to those calls.
  30843. * @param {boolean} [options.texture=false] - Only used for child Sprites if options.children is set to true
  30844. * Should it destroy the texture of the child sprite
  30845. * @param {boolean} [options.baseTexture=false] - Only used for child Sprites if options.children is set to true
  30846. * Should it destroy the base texture of the child sprite
  30847. */
  30848. ParticleContainer.prototype.destroy = function destroy (options)
  30849. {
  30850. Container.prototype.destroy.call(this, options);
  30851. this.dispose();
  30852. this._properties = null;
  30853. this._buffers = null;
  30854. this._bufferUpdateIDs = null;
  30855. };
  30856. Object.defineProperties( ParticleContainer.prototype, prototypeAccessors );
  30857. return ParticleContainer;
  30858. }(Container));
  30859. /**
  30860. * @author Mat Groves
  30861. *
  30862. * Big thanks to the very clever Matt DesLauriers <mattdesl> https://github.com/mattdesl/
  30863. * for creating the original PixiJS version!
  30864. * Also a thanks to https://github.com/bchevalier for tweaking the tint and alpha so that
  30865. * they now share 4 bytes on the vertex buffer
  30866. *
  30867. * Heavily inspired by LibGDX's ParticleBuffer:
  30868. * https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/graphics/g2d/ParticleBuffer.java
  30869. */
  30870. /**
  30871. * The particle buffer manages the static and dynamic buffers for a particle container.
  30872. *
  30873. * @class
  30874. * @private
  30875. * @memberof PIXI
  30876. */
  30877. var ParticleBuffer = function ParticleBuffer(properties, dynamicPropertyFlags, size)
  30878. {
  30879. this.geometry = new Geometry();
  30880. this.indexBuffer = null;
  30881. /**
  30882. * The number of particles the buffer can hold
  30883. *
  30884. * @private
  30885. * @member {number}
  30886. */
  30887. this.size = size;
  30888. /**
  30889. * A list of the properties that are dynamic.
  30890. *
  30891. * @private
  30892. * @member {object[]}
  30893. */
  30894. this.dynamicProperties = [];
  30895. /**
  30896. * A list of the properties that are static.
  30897. *
  30898. * @private
  30899. * @member {object[]}
  30900. */
  30901. this.staticProperties = [];
  30902. for (var i = 0; i < properties.length; ++i)
  30903. {
  30904. var property = properties[i];
  30905. // Make copy of properties object so that when we edit the offset it doesn't
  30906. // change all other instances of the object literal
  30907. property = {
  30908. attributeName: property.attributeName,
  30909. size: property.size,
  30910. uploadFunction: property.uploadFunction,
  30911. type: property.type || TYPES.FLOAT,
  30912. offset: property.offset,
  30913. };
  30914. if (dynamicPropertyFlags[i])
  30915. {
  30916. this.dynamicProperties.push(property);
  30917. }
  30918. else
  30919. {
  30920. this.staticProperties.push(property);
  30921. }
  30922. }
  30923. this.staticStride = 0;
  30924. this.staticBuffer = null;
  30925. this.staticData = null;
  30926. this.staticDataUint32 = null;
  30927. this.dynamicStride = 0;
  30928. this.dynamicBuffer = null;
  30929. this.dynamicData = null;
  30930. this.dynamicDataUint32 = null;
  30931. this._updateID = 0;
  30932. this.initBuffers();
  30933. };
  30934. /**
  30935. * Sets up the renderer context and necessary buffers.
  30936. *
  30937. * @private
  30938. */
  30939. ParticleBuffer.prototype.initBuffers = function initBuffers ()
  30940. {
  30941. var geometry = this.geometry;
  30942. var dynamicOffset = 0;
  30943. /**
  30944. * Holds the indices of the geometry (quads) to draw
  30945. *
  30946. * @member {Uint16Array}
  30947. * @private
  30948. */
  30949. this.indexBuffer = new Buffer(createIndicesForQuads(this.size), true, true);
  30950. geometry.addIndex(this.indexBuffer);
  30951. this.dynamicStride = 0;
  30952. for (var i = 0; i < this.dynamicProperties.length; ++i)
  30953. {
  30954. var property = this.dynamicProperties[i];
  30955. property.offset = dynamicOffset;
  30956. dynamicOffset += property.size;
  30957. this.dynamicStride += property.size;
  30958. }
  30959. var dynBuffer = new ArrayBuffer(this.size * this.dynamicStride * 4 * 4);
  30960. this.dynamicData = new Float32Array(dynBuffer);
  30961. this.dynamicDataUint32 = new Uint32Array(dynBuffer);
  30962. this.dynamicBuffer = new Buffer(this.dynamicData, false, false);
  30963. // static //
  30964. var staticOffset = 0;
  30965. this.staticStride = 0;
  30966. for (var i$1 = 0; i$1 < this.staticProperties.length; ++i$1)
  30967. {
  30968. var property$1 = this.staticProperties[i$1];
  30969. property$1.offset = staticOffset;
  30970. staticOffset += property$1.size;
  30971. this.staticStride += property$1.size;
  30972. }
  30973. var statBuffer = new ArrayBuffer(this.size * this.staticStride * 4 * 4);
  30974. this.staticData = new Float32Array(statBuffer);
  30975. this.staticDataUint32 = new Uint32Array(statBuffer);
  30976. this.staticBuffer = new Buffer(this.staticData, true, false);
  30977. for (var i$2 = 0; i$2 < this.dynamicProperties.length; ++i$2)
  30978. {
  30979. var property$2 = this.dynamicProperties[i$2];
  30980. geometry.addAttribute(
  30981. property$2.attributeName,
  30982. this.dynamicBuffer,
  30983. 0,
  30984. property$2.type === TYPES.UNSIGNED_BYTE,
  30985. property$2.type,
  30986. this.dynamicStride * 4,
  30987. property$2.offset * 4
  30988. );
  30989. }
  30990. for (var i$3 = 0; i$3 < this.staticProperties.length; ++i$3)
  30991. {
  30992. var property$3 = this.staticProperties[i$3];
  30993. geometry.addAttribute(
  30994. property$3.attributeName,
  30995. this.staticBuffer,
  30996. 0,
  30997. property$3.type === TYPES.UNSIGNED_BYTE,
  30998. property$3.type,
  30999. this.staticStride * 4,
  31000. property$3.offset * 4
  31001. );
  31002. }
  31003. };
  31004. /**
  31005. * Uploads the dynamic properties.
  31006. *
  31007. * @private
  31008. * @param {PIXI.DisplayObject[]} children - The children to upload.
  31009. * @param {number} startIndex - The index to start at.
  31010. * @param {number} amount - The number to upload.
  31011. */
  31012. ParticleBuffer.prototype.uploadDynamic = function uploadDynamic (children, startIndex, amount)
  31013. {
  31014. for (var i = 0; i < this.dynamicProperties.length; i++)
  31015. {
  31016. var property = this.dynamicProperties[i];
  31017. property.uploadFunction(children, startIndex, amount,
  31018. property.type === TYPES.UNSIGNED_BYTE ? this.dynamicDataUint32 : this.dynamicData,
  31019. this.dynamicStride, property.offset);
  31020. }
  31021. this.dynamicBuffer._updateID++;
  31022. };
  31023. /**
  31024. * Uploads the static properties.
  31025. *
  31026. * @private
  31027. * @param {PIXI.DisplayObject[]} children - The children to upload.
  31028. * @param {number} startIndex - The index to start at.
  31029. * @param {number} amount - The number to upload.
  31030. */
  31031. ParticleBuffer.prototype.uploadStatic = function uploadStatic (children, startIndex, amount)
  31032. {
  31033. for (var i = 0; i < this.staticProperties.length; i++)
  31034. {
  31035. var property = this.staticProperties[i];
  31036. property.uploadFunction(children, startIndex, amount,
  31037. property.type === TYPES.UNSIGNED_BYTE ? this.staticDataUint32 : this.staticData,
  31038. this.staticStride, property.offset);
  31039. }
  31040. this.staticBuffer._updateID++;
  31041. };
  31042. /**
  31043. * Destroys the ParticleBuffer.
  31044. *
  31045. * @private
  31046. */
  31047. ParticleBuffer.prototype.destroy = function destroy ()
  31048. {
  31049. this.indexBuffer = null;
  31050. this.dynamicProperties = null;
  31051. // this.dynamicBuffer.destroy();
  31052. this.dynamicBuffer = null;
  31053. this.dynamicData = null;
  31054. this.dynamicDataUint32 = null;
  31055. this.staticProperties = null;
  31056. // this.staticBuffer.destroy();
  31057. this.staticBuffer = null;
  31058. this.staticData = null;
  31059. this.staticDataUint32 = null;
  31060. // all buffers are destroyed inside geometry
  31061. this.geometry.destroy();
  31062. };
  31063. var vertex$2 = "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";
  31064. var fragment$1 = "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}";
  31065. /**
  31066. * @author Mat Groves
  31067. *
  31068. * Big thanks to the very clever Matt DesLauriers <mattdesl> https://github.com/mattdesl/
  31069. * for creating the original PixiJS version!
  31070. * Also a thanks to https://github.com/bchevalier for tweaking the tint and alpha so that they now
  31071. * share 4 bytes on the vertex buffer
  31072. *
  31073. * Heavily inspired by LibGDX's ParticleRenderer:
  31074. * https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/graphics/g2d/ParticleRenderer.java
  31075. */
  31076. /**
  31077. * Renderer for Particles that is designer for speed over feature set.
  31078. *
  31079. * @class
  31080. * @memberof PIXI
  31081. */
  31082. var ParticleRenderer = /*@__PURE__*/(function (ObjectRenderer) {
  31083. function ParticleRenderer(renderer)
  31084. {
  31085. ObjectRenderer.call(this, renderer);
  31086. // 65535 is max vertex index in the index buffer (see ParticleRenderer)
  31087. // so max number of particles is 65536 / 4 = 16384
  31088. // and max number of element in the index buffer is 16384 * 6 = 98304
  31089. // Creating a full index buffer, overhead is 98304 * 2 = 196Ko
  31090. // let numIndices = 98304;
  31091. /**
  31092. * The default shader that is used if a sprite doesn't have a more specific one.
  31093. *
  31094. * @member {PIXI.Shader}
  31095. */
  31096. this.shader = null;
  31097. this.properties = null;
  31098. this.tempMatrix = new Matrix();
  31099. this.properties = [
  31100. // verticesData
  31101. {
  31102. attributeName: 'aVertexPosition',
  31103. size: 2,
  31104. uploadFunction: this.uploadVertices,
  31105. offset: 0,
  31106. },
  31107. // positionData
  31108. {
  31109. attributeName: 'aPositionCoord',
  31110. size: 2,
  31111. uploadFunction: this.uploadPosition,
  31112. offset: 0,
  31113. },
  31114. // rotationData
  31115. {
  31116. attributeName: 'aRotation',
  31117. size: 1,
  31118. uploadFunction: this.uploadRotation,
  31119. offset: 0,
  31120. },
  31121. // uvsData
  31122. {
  31123. attributeName: 'aTextureCoord',
  31124. size: 2,
  31125. uploadFunction: this.uploadUvs,
  31126. offset: 0,
  31127. },
  31128. // tintData
  31129. {
  31130. attributeName: 'aColor',
  31131. size: 1,
  31132. type: TYPES.UNSIGNED_BYTE,
  31133. uploadFunction: this.uploadTint,
  31134. offset: 0,
  31135. } ];
  31136. this.shader = Shader.from(vertex$2, fragment$1, {});
  31137. }
  31138. if ( ObjectRenderer ) { ParticleRenderer.__proto__ = ObjectRenderer; }
  31139. ParticleRenderer.prototype = Object.create( ObjectRenderer && ObjectRenderer.prototype );
  31140. ParticleRenderer.prototype.constructor = ParticleRenderer;
  31141. /**
  31142. * Renders the particle container object.
  31143. *
  31144. * @param {PIXI.ParticleContainer} container - The container to render using this ParticleRenderer
  31145. */
  31146. ParticleRenderer.prototype.render = function render (container)
  31147. {
  31148. var children = container.children;
  31149. var maxSize = container._maxSize;
  31150. var batchSize = container._batchSize;
  31151. var renderer = this.renderer;
  31152. var totalChildren = children.length;
  31153. if (totalChildren === 0)
  31154. {
  31155. return;
  31156. }
  31157. else if (totalChildren > maxSize && !container.autoResize)
  31158. {
  31159. totalChildren = maxSize;
  31160. }
  31161. var buffers = container._buffers;
  31162. if (!buffers)
  31163. {
  31164. buffers = container._buffers = this.generateBuffers(container);
  31165. }
  31166. var baseTexture = children[0]._texture.baseTexture;
  31167. // if the uvs have not updated then no point rendering just yet!
  31168. this.renderer.state.setBlendMode(correctBlendMode(container.blendMode, baseTexture.premultiplyAlpha));
  31169. var gl = renderer.gl;
  31170. var m = container.worldTransform.copyTo(this.tempMatrix);
  31171. m.prepend(renderer.globalUniforms.uniforms.projectionMatrix);
  31172. this.shader.uniforms.translationMatrix = m.toArray(true);
  31173. this.shader.uniforms.uColor = premultiplyRgba(container.tintRgb,
  31174. container.worldAlpha, this.shader.uniforms.uColor, baseTexture.premultiplyAlpha);
  31175. this.shader.uniforms.uSampler = baseTexture;
  31176. this.renderer.shader.bind(this.shader);
  31177. var updateStatic = false;
  31178. // now lets upload and render the buffers..
  31179. for (var i = 0, j = 0; i < totalChildren; i += batchSize, j += 1)
  31180. {
  31181. var amount = (totalChildren - i);
  31182. if (amount > batchSize)
  31183. {
  31184. amount = batchSize;
  31185. }
  31186. if (j >= buffers.length)
  31187. {
  31188. buffers.push(this._generateOneMoreBuffer(container));
  31189. }
  31190. var buffer = buffers[j];
  31191. // we always upload the dynamic
  31192. buffer.uploadDynamic(children, i, amount);
  31193. var bid = container._bufferUpdateIDs[j] || 0;
  31194. updateStatic = updateStatic || (buffer._updateID < bid);
  31195. // we only upload the static content when we have to!
  31196. if (updateStatic)
  31197. {
  31198. buffer._updateID = container._updateID;
  31199. buffer.uploadStatic(children, i, amount);
  31200. }
  31201. // bind the buffer
  31202. renderer.geometry.bind(buffer.geometry);
  31203. gl.drawElements(gl.TRIANGLES, amount * 6, gl.UNSIGNED_SHORT, 0);
  31204. }
  31205. };
  31206. /**
  31207. * Creates one particle buffer for each child in the container we want to render and updates internal properties
  31208. *
  31209. * @param {PIXI.ParticleContainer} container - The container to render using this ParticleRenderer
  31210. * @return {PIXI.ParticleBuffer[]} The buffers
  31211. * @private
  31212. */
  31213. ParticleRenderer.prototype.generateBuffers = function generateBuffers (container)
  31214. {
  31215. var buffers = [];
  31216. var size = container._maxSize;
  31217. var batchSize = container._batchSize;
  31218. var dynamicPropertyFlags = container._properties;
  31219. for (var i = 0; i < size; i += batchSize)
  31220. {
  31221. buffers.push(new ParticleBuffer(this.properties, dynamicPropertyFlags, batchSize));
  31222. }
  31223. return buffers;
  31224. };
  31225. /**
  31226. * Creates one more particle buffer, because container has autoResize feature
  31227. *
  31228. * @param {PIXI.ParticleContainer} container - The container to render using this ParticleRenderer
  31229. * @return {PIXI.ParticleBuffer} generated buffer
  31230. * @private
  31231. */
  31232. ParticleRenderer.prototype._generateOneMoreBuffer = function _generateOneMoreBuffer (container)
  31233. {
  31234. var batchSize = container._batchSize;
  31235. var dynamicPropertyFlags = container._properties;
  31236. return new ParticleBuffer(this.properties, dynamicPropertyFlags, batchSize);
  31237. };
  31238. /**
  31239. * Uploads the vertices.
  31240. *
  31241. * @param {PIXI.DisplayObject[]} children - the array of display objects to render
  31242. * @param {number} startIndex - the index to start from in the children array
  31243. * @param {number} amount - the amount of children that will have their vertices uploaded
  31244. * @param {number[]} array - The vertices to upload.
  31245. * @param {number} stride - Stride to use for iteration.
  31246. * @param {number} offset - Offset to start at.
  31247. */
  31248. ParticleRenderer.prototype.uploadVertices = function uploadVertices (children, startIndex, amount, array, stride, offset)
  31249. {
  31250. var w0 = 0;
  31251. var w1 = 0;
  31252. var h0 = 0;
  31253. var h1 = 0;
  31254. for (var i = 0; i < amount; ++i)
  31255. {
  31256. var sprite = children[startIndex + i];
  31257. var texture = sprite._texture;
  31258. var sx = sprite.scale.x;
  31259. var sy = sprite.scale.y;
  31260. var trim = texture.trim;
  31261. var orig = texture.orig;
  31262. if (trim)
  31263. {
  31264. // if the sprite is trimmed and is not a tilingsprite then we need to add the
  31265. // extra space before transforming the sprite coords..
  31266. w1 = trim.x - (sprite.anchor.x * orig.width);
  31267. w0 = w1 + trim.width;
  31268. h1 = trim.y - (sprite.anchor.y * orig.height);
  31269. h0 = h1 + trim.height;
  31270. }
  31271. else
  31272. {
  31273. w0 = (orig.width) * (1 - sprite.anchor.x);
  31274. w1 = (orig.width) * -sprite.anchor.x;
  31275. h0 = orig.height * (1 - sprite.anchor.y);
  31276. h1 = orig.height * -sprite.anchor.y;
  31277. }
  31278. array[offset] = w1 * sx;
  31279. array[offset + 1] = h1 * sy;
  31280. array[offset + stride] = w0 * sx;
  31281. array[offset + stride + 1] = h1 * sy;
  31282. array[offset + (stride * 2)] = w0 * sx;
  31283. array[offset + (stride * 2) + 1] = h0 * sy;
  31284. array[offset + (stride * 3)] = w1 * sx;
  31285. array[offset + (stride * 3) + 1] = h0 * sy;
  31286. offset += stride * 4;
  31287. }
  31288. };
  31289. /**
  31290. * Uploads the position.
  31291. *
  31292. * @param {PIXI.DisplayObject[]} children - the array of display objects to render
  31293. * @param {number} startIndex - the index to start from in the children array
  31294. * @param {number} amount - the amount of children that will have their positions uploaded
  31295. * @param {number[]} array - The vertices to upload.
  31296. * @param {number} stride - Stride to use for iteration.
  31297. * @param {number} offset - Offset to start at.
  31298. */
  31299. ParticleRenderer.prototype.uploadPosition = function uploadPosition (children, startIndex, amount, array, stride, offset)
  31300. {
  31301. for (var i = 0; i < amount; i++)
  31302. {
  31303. var spritePosition = children[startIndex + i].position;
  31304. array[offset] = spritePosition.x;
  31305. array[offset + 1] = spritePosition.y;
  31306. array[offset + stride] = spritePosition.x;
  31307. array[offset + stride + 1] = spritePosition.y;
  31308. array[offset + (stride * 2)] = spritePosition.x;
  31309. array[offset + (stride * 2) + 1] = spritePosition.y;
  31310. array[offset + (stride * 3)] = spritePosition.x;
  31311. array[offset + (stride * 3) + 1] = spritePosition.y;
  31312. offset += stride * 4;
  31313. }
  31314. };
  31315. /**
  31316. * Uploads the rotiation.
  31317. *
  31318. * @param {PIXI.DisplayObject[]} children - the array of display objects to render
  31319. * @param {number} startIndex - the index to start from in the children array
  31320. * @param {number} amount - the amount of children that will have their rotation uploaded
  31321. * @param {number[]} array - The vertices to upload.
  31322. * @param {number} stride - Stride to use for iteration.
  31323. * @param {number} offset - Offset to start at.
  31324. */
  31325. ParticleRenderer.prototype.uploadRotation = function uploadRotation (children, startIndex, amount, array, stride, offset)
  31326. {
  31327. for (var i = 0; i < amount; i++)
  31328. {
  31329. var spriteRotation = children[startIndex + i].rotation;
  31330. array[offset] = spriteRotation;
  31331. array[offset + stride] = spriteRotation;
  31332. array[offset + (stride * 2)] = spriteRotation;
  31333. array[offset + (stride * 3)] = spriteRotation;
  31334. offset += stride * 4;
  31335. }
  31336. };
  31337. /**
  31338. * Uploads the Uvs
  31339. *
  31340. * @param {PIXI.DisplayObject[]} children - the array of display objects to render
  31341. * @param {number} startIndex - the index to start from in the children array
  31342. * @param {number} amount - the amount of children that will have their rotation uploaded
  31343. * @param {number[]} array - The vertices to upload.
  31344. * @param {number} stride - Stride to use for iteration.
  31345. * @param {number} offset - Offset to start at.
  31346. */
  31347. ParticleRenderer.prototype.uploadUvs = function uploadUvs (children, startIndex, amount, array, stride, offset)
  31348. {
  31349. for (var i = 0; i < amount; ++i)
  31350. {
  31351. var textureUvs = children[startIndex + i]._texture._uvs;
  31352. if (textureUvs)
  31353. {
  31354. array[offset] = textureUvs.x0;
  31355. array[offset + 1] = textureUvs.y0;
  31356. array[offset + stride] = textureUvs.x1;
  31357. array[offset + stride + 1] = textureUvs.y1;
  31358. array[offset + (stride * 2)] = textureUvs.x2;
  31359. array[offset + (stride * 2) + 1] = textureUvs.y2;
  31360. array[offset + (stride * 3)] = textureUvs.x3;
  31361. array[offset + (stride * 3) + 1] = textureUvs.y3;
  31362. offset += stride * 4;
  31363. }
  31364. else
  31365. {
  31366. // TODO you know this can be easier!
  31367. array[offset] = 0;
  31368. array[offset + 1] = 0;
  31369. array[offset + stride] = 0;
  31370. array[offset + stride + 1] = 0;
  31371. array[offset + (stride * 2)] = 0;
  31372. array[offset + (stride * 2) + 1] = 0;
  31373. array[offset + (stride * 3)] = 0;
  31374. array[offset + (stride * 3) + 1] = 0;
  31375. offset += stride * 4;
  31376. }
  31377. }
  31378. };
  31379. /**
  31380. * Uploads the tint.
  31381. *
  31382. * @param {PIXI.DisplayObject[]} children - the array of display objects to render
  31383. * @param {number} startIndex - the index to start from in the children array
  31384. * @param {number} amount - the amount of children that will have their rotation uploaded
  31385. * @param {number[]} array - The vertices to upload.
  31386. * @param {number} stride - Stride to use for iteration.
  31387. * @param {number} offset - Offset to start at.
  31388. */
  31389. ParticleRenderer.prototype.uploadTint = function uploadTint (children, startIndex, amount, array, stride, offset)
  31390. {
  31391. for (var i = 0; i < amount; ++i)
  31392. {
  31393. var sprite = children[startIndex + i];
  31394. var premultiplied = sprite._texture.baseTexture.premultiplyAlpha;
  31395. var alpha = sprite.alpha;
  31396. // we dont call extra function if alpha is 1.0, that's faster
  31397. var argb = alpha < 1.0 && premultiplied ? premultiplyTint(sprite._tintRGB, alpha)
  31398. : sprite._tintRGB + (alpha * 255 << 24);
  31399. array[offset] = argb;
  31400. array[offset + stride] = argb;
  31401. array[offset + (stride * 2)] = argb;
  31402. array[offset + (stride * 3)] = argb;
  31403. offset += stride * 4;
  31404. }
  31405. };
  31406. /**
  31407. * Destroys the ParticleRenderer.
  31408. */
  31409. ParticleRenderer.prototype.destroy = function destroy ()
  31410. {
  31411. ObjectRenderer.prototype.destroy.call(this);
  31412. if (this.shader)
  31413. {
  31414. this.shader.destroy();
  31415. this.shader = null;
  31416. }
  31417. this.tempMatrix = null;
  31418. };
  31419. return ParticleRenderer;
  31420. }(ObjectRenderer));
  31421. /*!
  31422. * @pixi/spritesheet - v5.0.4
  31423. * Compiled Fri, 07 Jun 2019 17:17:49 UTC
  31424. *
  31425. * @pixi/spritesheet is licensed under the MIT License.
  31426. * http://www.opensource.org/licenses/mit-license
  31427. */
  31428. /**
  31429. * Utility class for maintaining reference to a collection
  31430. * of Textures on a single Spritesheet.
  31431. *
  31432. * To access a sprite sheet from your code pass its JSON data file to Pixi's loader:
  31433. *
  31434. * ```js
  31435. * PIXI.Loader.shared.add("images/spritesheet.json").load(setup);
  31436. *
  31437. * function setup() {
  31438. * let sheet = PIXI.Loader.shared.resources["images/spritesheet.json"].spritesheet;
  31439. * ...
  31440. * }
  31441. * ```
  31442. * With the `sheet.textures` you can create Sprite objects,`sheet.animations` can be used to create an AnimatedSprite.
  31443. *
  31444. * Sprite sheets can be packed using tools like {@link https://codeandweb.com/texturepacker|TexturePacker},
  31445. * {@link https://renderhjs.net/shoebox/|Shoebox} or {@link https://github.com/krzysztof-o/spritesheet.js|Spritesheet.js}.
  31446. * Default anchor points (see {@link PIXI.Texture#defaultAnchor}) and grouping of animation sprites are currently only
  31447. * supported by TexturePacker.
  31448. *
  31449. * @class
  31450. * @memberof PIXI
  31451. */
  31452. var Spritesheet = function Spritesheet(baseTexture, data, resolutionFilename)
  31453. {
  31454. if ( resolutionFilename === void 0 ) { resolutionFilename = null; }
  31455. /**
  31456. * Reference to ths source texture
  31457. * @type {PIXI.BaseTexture}
  31458. */
  31459. this.baseTexture = baseTexture;
  31460. /**
  31461. * A map containing all textures of the sprite sheet.
  31462. * Can be used to create a {@link PIXI.Sprite|Sprite}:
  31463. * ```js
  31464. * new PIXI.Sprite(sheet.textures["image.png"]);
  31465. * ```
  31466. * @member {Object}
  31467. */
  31468. this.textures = {};
  31469. /**
  31470. * A map containing the textures for each animation.
  31471. * Can be used to create an {@link PIXI.AnimatedSprite|AnimatedSprite}:
  31472. * ```js
  31473. * new PIXI.AnimatedSprite(sheet.animations["anim_name"])
  31474. * ```
  31475. * @member {Object}
  31476. */
  31477. this.animations = {};
  31478. /**
  31479. * Reference to the original JSON data.
  31480. * @type {Object}
  31481. */
  31482. this.data = data;
  31483. /**
  31484. * The resolution of the spritesheet.
  31485. * @type {number}
  31486. */
  31487. this.resolution = this._updateResolution(
  31488. resolutionFilename
  31489. || (this.baseTexture.resource ? this.baseTexture.resource.url : null)
  31490. );
  31491. /**
  31492. * Map of spritesheet frames.
  31493. * @type {Object}
  31494. * @private
  31495. */
  31496. this._frames = this.data.frames;
  31497. /**
  31498. * Collection of frame names.
  31499. * @type {string[]}
  31500. * @private
  31501. */
  31502. this._frameKeys = Object.keys(this._frames);
  31503. /**
  31504. * Current batch index being processed.
  31505. * @type {number}
  31506. * @private
  31507. */
  31508. this._batchIndex = 0;
  31509. /**
  31510. * Callback when parse is completed.
  31511. * @type {Function}
  31512. * @private
  31513. */
  31514. this._callback = null;
  31515. };
  31516. var staticAccessors$4 = { BATCH_SIZE: { configurable: true } };
  31517. /**
  31518. * Generate the resolution from the filename or fallback
  31519. * to the meta.scale field of the JSON data.
  31520. *
  31521. * @private
  31522. * @param {string} resolutionFilename - The filename to use for resolving
  31523. * the default resolution.
  31524. * @return {number} Resolution to use for spritesheet.
  31525. */
  31526. staticAccessors$4.BATCH_SIZE.get = function ()
  31527. {
  31528. return 1000;
  31529. };
  31530. Spritesheet.prototype._updateResolution = function _updateResolution (resolutionFilename)
  31531. {
  31532. var scale = this.data.meta.scale;
  31533. // Use a defaultValue of `null` to check if a url-based resolution is set
  31534. var resolution = getResolutionOfUrl(resolutionFilename, null);
  31535. // No resolution found via URL
  31536. if (resolution === null)
  31537. {
  31538. // Use the scale value or default to 1
  31539. resolution = scale !== undefined ? parseFloat(scale) : 1;
  31540. }
  31541. // For non-1 resolutions, update baseTexture
  31542. if (resolution !== 1)
  31543. {
  31544. this.baseTexture.setResolution(resolution);
  31545. }
  31546. return resolution;
  31547. };
  31548. /**
  31549. * Parser spritesheet from loaded data. This is done asynchronously
  31550. * to prevent creating too many Texture within a single process.
  31551. *
  31552. * @param {Function} callback - Callback when complete returns
  31553. * a map of the Textures for this spritesheet.
  31554. */
  31555. Spritesheet.prototype.parse = function parse (callback)
  31556. {
  31557. this._batchIndex = 0;
  31558. this._callback = callback;
  31559. if (this._frameKeys.length <= Spritesheet.BATCH_SIZE)
  31560. {
  31561. this._processFrames(0);
  31562. this._processAnimations();
  31563. this._parseComplete();
  31564. }
  31565. else
  31566. {
  31567. this._nextBatch();
  31568. }
  31569. };
  31570. /**
  31571. * Process a batch of frames
  31572. *
  31573. * @private
  31574. * @param {number} initialFrameIndex - The index of frame to start.
  31575. */
  31576. Spritesheet.prototype._processFrames = function _processFrames (initialFrameIndex)
  31577. {
  31578. var frameIndex = initialFrameIndex;
  31579. var maxFrames = Spritesheet.BATCH_SIZE;
  31580. while (frameIndex - initialFrameIndex < maxFrames && frameIndex < this._frameKeys.length)
  31581. {
  31582. var i = this._frameKeys[frameIndex];
  31583. var data = this._frames[i];
  31584. var rect = data.frame;
  31585. if (rect)
  31586. {
  31587. var frame = null;
  31588. var trim = null;
  31589. var sourceSize = data.trimmed !== false && data.sourceSize
  31590. ? data.sourceSize : data.frame;
  31591. var orig = new Rectangle(
  31592. 0,
  31593. 0,
  31594. Math.floor(sourceSize.w) / this.resolution,
  31595. Math.floor(sourceSize.h) / this.resolution
  31596. );
  31597. if (data.rotated)
  31598. {
  31599. frame = new Rectangle(
  31600. Math.floor(rect.x) / this.resolution,
  31601. Math.floor(rect.y) / this.resolution,
  31602. Math.floor(rect.h) / this.resolution,
  31603. Math.floor(rect.w) / this.resolution
  31604. );
  31605. }
  31606. else
  31607. {
  31608. frame = new Rectangle(
  31609. Math.floor(rect.x) / this.resolution,
  31610. Math.floor(rect.y) / this.resolution,
  31611. Math.floor(rect.w) / this.resolution,
  31612. Math.floor(rect.h) / this.resolution
  31613. );
  31614. }
  31615. // Check to see if the sprite is trimmed
  31616. if (data.trimmed !== false && data.spriteSourceSize)
  31617. {
  31618. trim = new Rectangle(
  31619. Math.floor(data.spriteSourceSize.x) / this.resolution,
  31620. Math.floor(data.spriteSourceSize.y) / this.resolution,
  31621. Math.floor(rect.w) / this.resolution,
  31622. Math.floor(rect.h) / this.resolution
  31623. );
  31624. }
  31625. this.textures[i] = new Texture(
  31626. this.baseTexture,
  31627. frame,
  31628. orig,
  31629. trim,
  31630. data.rotated ? 2 : 0,
  31631. data.anchor
  31632. );
  31633. // lets also add the frame to pixi's global cache for 'from' and 'fromLoader' functions
  31634. Texture.addToCache(this.textures[i], i);
  31635. }
  31636. frameIndex++;
  31637. }
  31638. };
  31639. /**
  31640. * Parse animations config
  31641. *
  31642. * @private
  31643. */
  31644. Spritesheet.prototype._processAnimations = function _processAnimations ()
  31645. {
  31646. var animations = this.data.animations || {};
  31647. for (var animName in animations)
  31648. {
  31649. this.animations[animName] = [];
  31650. for (var i = 0; i < animations[animName].length; i++)
  31651. {
  31652. var frameName = animations[animName][i];
  31653. this.animations[animName].push(this.textures[frameName]);
  31654. }
  31655. }
  31656. };
  31657. /**
  31658. * The parse has completed.
  31659. *
  31660. * @private
  31661. */
  31662. Spritesheet.prototype._parseComplete = function _parseComplete ()
  31663. {
  31664. var callback = this._callback;
  31665. this._callback = null;
  31666. this._batchIndex = 0;
  31667. callback.call(this, this.textures);
  31668. };
  31669. /**
  31670. * Begin the next batch of textures.
  31671. *
  31672. * @private
  31673. */
  31674. Spritesheet.prototype._nextBatch = function _nextBatch ()
  31675. {
  31676. var this$1 = this;
  31677. this._processFrames(this._batchIndex * Spritesheet.BATCH_SIZE);
  31678. this._batchIndex++;
  31679. setTimeout(function () {
  31680. if (this$1._batchIndex * Spritesheet.BATCH_SIZE < this$1._frameKeys.length)
  31681. {
  31682. this$1._nextBatch();
  31683. }
  31684. else
  31685. {
  31686. this$1._processAnimations();
  31687. this$1._parseComplete();
  31688. }
  31689. }, 0);
  31690. };
  31691. /**
  31692. * Destroy Spritesheet and don't use after this.
  31693. *
  31694. * @param {boolean} [destroyBase=false] Whether to destroy the base texture as well
  31695. */
  31696. Spritesheet.prototype.destroy = function destroy (destroyBase)
  31697. {
  31698. if ( destroyBase === void 0 ) { destroyBase = false; }
  31699. for (var i in this.textures)
  31700. {
  31701. this.textures[i].destroy();
  31702. }
  31703. this._frames = null;
  31704. this._frameKeys = null;
  31705. this.data = null;
  31706. this.textures = null;
  31707. if (destroyBase)
  31708. {
  31709. this.baseTexture.destroy();
  31710. }
  31711. this.baseTexture = null;
  31712. };
  31713. Object.defineProperties( Spritesheet, staticAccessors$4 );
  31714. /**
  31715. * {@link PIXI.Loader Loader} middleware for loading texture atlases that have been created with
  31716. * TexturePacker or similar JSON-based spritesheet.
  31717. *
  31718. * This middleware automatically generates Texture resources.
  31719. *
  31720. * @class
  31721. * @memberof PIXI
  31722. * @implements PIXI.ILoaderPlugin
  31723. */
  31724. var SpritesheetLoader = function SpritesheetLoader () {};
  31725. SpritesheetLoader.use = function use (resource, next)
  31726. {
  31727. var imageResourceName = (resource.name) + "_image";
  31728. // skip if no data, its not json, it isn't spritesheet data, or the image resource already exists
  31729. if (!resource.data
  31730. || resource.type !== LoaderResource.TYPE.JSON
  31731. || !resource.data.frames
  31732. || this.resources[imageResourceName]
  31733. )
  31734. {
  31735. next();
  31736. return;
  31737. }
  31738. var loadOptions = {
  31739. crossOrigin: resource.crossOrigin,
  31740. metadata: resource.metadata.imageMetadata,
  31741. parentResource: resource,
  31742. };
  31743. var resourcePath = SpritesheetLoader.getResourcePath(resource, this.baseUrl);
  31744. // load the image for this sheet
  31745. this.add(imageResourceName, resourcePath, loadOptions, function onImageLoad(res)
  31746. {
  31747. if (res.error)
  31748. {
  31749. next(res.error);
  31750. return;
  31751. }
  31752. var spritesheet = new Spritesheet(
  31753. res.texture.baseTexture,
  31754. resource.data,
  31755. resource.url
  31756. );
  31757. spritesheet.parse(function () {
  31758. resource.spritesheet = spritesheet;
  31759. resource.textures = spritesheet.textures;
  31760. next();
  31761. });
  31762. });
  31763. };
  31764. /**
  31765. * Get the spritesheets root path
  31766. * @param {PIXI.LoaderResource} resource - Resource to check path
  31767. * @param {string} baseUrl - Base root url
  31768. */
  31769. SpritesheetLoader.getResourcePath = function getResourcePath (resource, baseUrl)
  31770. {
  31771. // Prepend url path unless the resource image is a data url
  31772. if (resource.isDataUrl)
  31773. {
  31774. return resource.data.meta.image;
  31775. }
  31776. return url.resolve(resource.url.replace(baseUrl, ''), resource.data.meta.image);
  31777. };
  31778. /*!
  31779. * @pixi/sprite-tiling - v5.0.4
  31780. * Compiled Fri, 07 Jun 2019 17:17:49 UTC
  31781. *
  31782. * @pixi/sprite-tiling is licensed under the MIT License.
  31783. * http://www.opensource.org/licenses/mit-license
  31784. */
  31785. var tempPoint$1 = new Point();
  31786. /**
  31787. * A tiling sprite is a fast way of rendering a tiling image
  31788. *
  31789. * @class
  31790. * @extends PIXI.Sprite
  31791. * @memberof PIXI
  31792. */
  31793. var TilingSprite = /*@__PURE__*/(function (Sprite) {
  31794. function TilingSprite(texture, width, height)
  31795. {
  31796. if ( width === void 0 ) { width = 100; }
  31797. if ( height === void 0 ) { height = 100; }
  31798. Sprite.call(this, texture);
  31799. /**
  31800. * Tile transform
  31801. *
  31802. * @member {PIXI.Transform}
  31803. */
  31804. this.tileTransform = new Transform();
  31805. // /// private
  31806. /**
  31807. * The with of the tiling sprite
  31808. *
  31809. * @member {number}
  31810. * @private
  31811. */
  31812. this._width = width;
  31813. /**
  31814. * The height of the tiling sprite
  31815. *
  31816. * @member {number}
  31817. * @private
  31818. */
  31819. this._height = height;
  31820. /**
  31821. * Canvas pattern
  31822. *
  31823. * @type {CanvasPattern}
  31824. * @private
  31825. */
  31826. this._canvasPattern = null;
  31827. /**
  31828. * matrix that is applied to UV to get the coords in Texture normalized space to coords in BaseTexture space
  31829. *
  31830. * @member {PIXI.TextureMatrix}
  31831. */
  31832. this.uvMatrix = texture.uvMatrix || new TextureMatrix(texture);
  31833. /**
  31834. * Plugin that is responsible for rendering this element.
  31835. * Allows to customize the rendering process without overriding '_render' method.
  31836. *
  31837. * @member {string}
  31838. * @default 'tilingSprite'
  31839. */
  31840. this.pluginName = 'tilingSprite';
  31841. /**
  31842. * Whether or not anchor affects uvs
  31843. *
  31844. * @member {boolean}
  31845. * @default false
  31846. */
  31847. this.uvRespectAnchor = false;
  31848. }
  31849. if ( Sprite ) { TilingSprite.__proto__ = Sprite; }
  31850. TilingSprite.prototype = Object.create( Sprite && Sprite.prototype );
  31851. TilingSprite.prototype.constructor = TilingSprite;
  31852. var prototypeAccessors = { clampMargin: { configurable: true },tileScale: { configurable: true },tilePosition: { configurable: true },width: { configurable: true },height: { configurable: true } };
  31853. /**
  31854. * Changes frame clamping in corresponding textureTransform, shortcut
  31855. * Change to -0.5 to add a pixel to the edge, recommended for transparent trimmed textures in atlas
  31856. *
  31857. * @default 0.5
  31858. * @member {number}
  31859. */
  31860. prototypeAccessors.clampMargin.get = function ()
  31861. {
  31862. return this.uvMatrix.clampMargin;
  31863. };
  31864. prototypeAccessors.clampMargin.set = function (value) // eslint-disable-line require-jsdoc
  31865. {
  31866. this.uvMatrix.clampMargin = value;
  31867. this.uvMatrix.update(true);
  31868. };
  31869. /**
  31870. * The scaling of the image that is being tiled
  31871. *
  31872. * @member {PIXI.ObservablePoint}
  31873. */
  31874. prototypeAccessors.tileScale.get = function ()
  31875. {
  31876. return this.tileTransform.scale;
  31877. };
  31878. prototypeAccessors.tileScale.set = function (value) // eslint-disable-line require-jsdoc
  31879. {
  31880. this.tileTransform.scale.copyFrom(value);
  31881. };
  31882. /**
  31883. * The offset of the image that is being tiled
  31884. *
  31885. * @member {PIXI.ObservablePoint}
  31886. */
  31887. prototypeAccessors.tilePosition.get = function ()
  31888. {
  31889. return this.tileTransform.position;
  31890. };
  31891. prototypeAccessors.tilePosition.set = function (value) // eslint-disable-line require-jsdoc
  31892. {
  31893. this.tileTransform.position.copyFrom(value);
  31894. };
  31895. /**
  31896. * @private
  31897. */
  31898. TilingSprite.prototype._onTextureUpdate = function _onTextureUpdate ()
  31899. {
  31900. if (this.uvMatrix)
  31901. {
  31902. this.uvMatrix.texture = this._texture;
  31903. }
  31904. this._cachedTint = 0xFFFFFF;
  31905. };
  31906. /**
  31907. * Renders the object using the WebGL renderer
  31908. *
  31909. * @protected
  31910. * @param {PIXI.Renderer} renderer - The renderer
  31911. */
  31912. TilingSprite.prototype._render = function _render (renderer)
  31913. {
  31914. // tweak our texture temporarily..
  31915. var texture = this._texture;
  31916. if (!texture || !texture.valid)
  31917. {
  31918. return;
  31919. }
  31920. this.tileTransform.updateLocalTransform();
  31921. this.uvMatrix.update();
  31922. renderer.batch.setObjectRenderer(renderer.plugins[this.pluginName]);
  31923. renderer.plugins[this.pluginName].render(this);
  31924. };
  31925. /**
  31926. * Updates the bounds of the tiling sprite.
  31927. *
  31928. * @protected
  31929. */
  31930. TilingSprite.prototype._calculateBounds = function _calculateBounds ()
  31931. {
  31932. var minX = this._width * -this._anchor._x;
  31933. var minY = this._height * -this._anchor._y;
  31934. var maxX = this._width * (1 - this._anchor._x);
  31935. var maxY = this._height * (1 - this._anchor._y);
  31936. this._bounds.addFrame(this.transform, minX, minY, maxX, maxY);
  31937. };
  31938. /**
  31939. * Gets the local bounds of the sprite object.
  31940. *
  31941. * @param {PIXI.Rectangle} rect - The output rectangle.
  31942. * @return {PIXI.Rectangle} The bounds.
  31943. */
  31944. TilingSprite.prototype.getLocalBounds = function getLocalBounds (rect)
  31945. {
  31946. // we can do a fast local bounds if the sprite has no children!
  31947. if (this.children.length === 0)
  31948. {
  31949. this._bounds.minX = this._width * -this._anchor._x;
  31950. this._bounds.minY = this._height * -this._anchor._y;
  31951. this._bounds.maxX = this._width * (1 - this._anchor._x);
  31952. this._bounds.maxY = this._height * (1 - this._anchor._y);
  31953. if (!rect)
  31954. {
  31955. if (!this._localBoundsRect)
  31956. {
  31957. this._localBoundsRect = new Rectangle();
  31958. }
  31959. rect = this._localBoundsRect;
  31960. }
  31961. return this._bounds.getRectangle(rect);
  31962. }
  31963. return Sprite.prototype.getLocalBounds.call(this, rect);
  31964. };
  31965. /**
  31966. * Checks if a point is inside this tiling sprite.
  31967. *
  31968. * @param {PIXI.Point} point - the point to check
  31969. * @return {boolean} Whether or not the sprite contains the point.
  31970. */
  31971. TilingSprite.prototype.containsPoint = function containsPoint (point)
  31972. {
  31973. this.worldTransform.applyInverse(point, tempPoint$1);
  31974. var width = this._width;
  31975. var height = this._height;
  31976. var x1 = -width * this.anchor._x;
  31977. if (tempPoint$1.x >= x1 && tempPoint$1.x < x1 + width)
  31978. {
  31979. var y1 = -height * this.anchor._y;
  31980. if (tempPoint$1.y >= y1 && tempPoint$1.y < y1 + height)
  31981. {
  31982. return true;
  31983. }
  31984. }
  31985. return false;
  31986. };
  31987. /**
  31988. * Destroys this sprite and optionally its texture and children
  31989. *
  31990. * @param {object|boolean} [options] - Options parameter. A boolean will act as if all options
  31991. * have been set to that value
  31992. * @param {boolean} [options.children=false] - if set to true, all the children will have their destroy
  31993. * method called as well. 'options' will be passed on to those calls.
  31994. * @param {boolean} [options.texture=false] - Should it destroy the current texture of the sprite as well
  31995. * @param {boolean} [options.baseTexture=false] - Should it destroy the base texture of the sprite as well
  31996. */
  31997. TilingSprite.prototype.destroy = function destroy (options)
  31998. {
  31999. Sprite.prototype.destroy.call(this, options);
  32000. this.tileTransform = null;
  32001. this.uvMatrix = null;
  32002. };
  32003. /**
  32004. * Helper function that creates a new tiling sprite based on the source you provide.
  32005. * The source can be - frame id, image url, video url, canvas element, video element, base texture
  32006. *
  32007. * @static
  32008. * @param {number|string|PIXI.Texture|HTMLCanvasElement|HTMLVideoElement} source - Source to create texture from
  32009. * @param {number} width - the width of the tiling sprite
  32010. * @param {number} height - the height of the tiling sprite
  32011. * @return {PIXI.TilingSprite} The newly created texture
  32012. */
  32013. TilingSprite.from = function from (source, width, height)
  32014. {
  32015. return new TilingSprite(Texture.from(source), width, height);
  32016. };
  32017. /**
  32018. * Helper function that creates a tiling sprite that will use a texture from the TextureCache based on the frameId
  32019. * The frame ids are created when a Texture packer file has been loaded
  32020. *
  32021. * @static
  32022. * @param {string} frameId - The frame Id of the texture in the cache
  32023. * @param {number} width - the width of the tiling sprite
  32024. * @param {number} height - the height of the tiling sprite
  32025. * @return {PIXI.TilingSprite} A new TilingSprite using a texture from the texture cache matching the frameId
  32026. */
  32027. TilingSprite.fromFrame = function fromFrame (frameId, width, height)
  32028. {
  32029. var texture = TextureCache[frameId];
  32030. if (!texture)
  32031. {
  32032. throw new Error(("The frameId \"" + frameId + "\" does not exist in the texture cache " + (this)));
  32033. }
  32034. return new TilingSprite(texture, width, height);
  32035. };
  32036. /**
  32037. * Helper function that creates a sprite that will contain a texture based on an image url
  32038. * If the image is not in the texture cache it will be loaded
  32039. *
  32040. * @static
  32041. * @param {string} imageId - The image url of the texture
  32042. * @param {number} width - the width of the tiling sprite
  32043. * @param {number} height - the height of the tiling sprite
  32044. * @param {Object} [options] - See {@link PIXI.BaseTexture}'s constructor for options.
  32045. * @return {PIXI.TilingSprite} A new TilingSprite using a texture from the texture cache matching the image id
  32046. */
  32047. TilingSprite.fromImage = function fromImage (imageId, width, height, options)
  32048. {
  32049. // Fallback support for crossorigin, scaleMode parameters
  32050. if (options && typeof options !== 'object')
  32051. {
  32052. options = {
  32053. scaleMode: arguments[4],
  32054. resourceOptions: {
  32055. crossorigin: arguments[3],
  32056. },
  32057. };
  32058. }
  32059. return new TilingSprite(Texture.from(imageId, options), width, height);
  32060. };
  32061. /**
  32062. * The width of the sprite, setting this will actually modify the scale to achieve the value set
  32063. *
  32064. * @member {number}
  32065. */
  32066. prototypeAccessors.width.get = function ()
  32067. {
  32068. return this._width;
  32069. };
  32070. prototypeAccessors.width.set = function (value) // eslint-disable-line require-jsdoc
  32071. {
  32072. this._width = value;
  32073. };
  32074. /**
  32075. * The height of the TilingSprite, setting this will actually modify the scale to achieve the value set
  32076. *
  32077. * @member {number}
  32078. */
  32079. prototypeAccessors.height.get = function ()
  32080. {
  32081. return this._height;
  32082. };
  32083. prototypeAccessors.height.set = function (value) // eslint-disable-line require-jsdoc
  32084. {
  32085. this._height = value;
  32086. };
  32087. Object.defineProperties( TilingSprite.prototype, prototypeAccessors );
  32088. return TilingSprite;
  32089. }(Sprite));
  32090. var vertex$3 = "attribute 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";
  32091. var fragment$2 = "varying 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 = mod(vTextureCoord - uClampOffset, vec2(1.0, 1.0)) + uClampOffset;\n coord = (uMapCoord * vec3(coord, 1.0)).xy;\n coord = clamp(coord, uClampFrame.xy, uClampFrame.zw);\n\n vec4 sample = texture2D(uSampler, coord);\n gl_FragColor = sample * uColor;\n}\n";
  32092. var fragmentSimple = "varying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform vec4 uColor;\n\nvoid main(void)\n{\n vec4 sample = texture2D(uSampler, vTextureCoord);\n gl_FragColor = sample * uColor;\n}\n";
  32093. var tempMat$1 = new Matrix();
  32094. /**
  32095. * WebGL renderer plugin for tiling sprites
  32096. *
  32097. * @class
  32098. * @memberof PIXI
  32099. * @extends PIXI.ObjectRenderer
  32100. */
  32101. var TilingSpriteRenderer = /*@__PURE__*/(function (ObjectRenderer) {
  32102. function TilingSpriteRenderer(renderer)
  32103. {
  32104. ObjectRenderer.call(this, renderer);
  32105. var uniforms = { globals: this.renderer.globalUniforms };
  32106. this.shader = Shader.from(vertex$3, fragment$2, uniforms);
  32107. this.simpleShader = Shader.from(vertex$3, fragmentSimple, uniforms);
  32108. this.quad = new QuadUv();
  32109. }
  32110. if ( ObjectRenderer ) { TilingSpriteRenderer.__proto__ = ObjectRenderer; }
  32111. TilingSpriteRenderer.prototype = Object.create( ObjectRenderer && ObjectRenderer.prototype );
  32112. TilingSpriteRenderer.prototype.constructor = TilingSpriteRenderer;
  32113. /**
  32114. *
  32115. * @param {PIXI.TilingSprite} ts tilingSprite to be rendered
  32116. */
  32117. TilingSpriteRenderer.prototype.render = function render (ts)
  32118. {
  32119. var renderer = this.renderer;
  32120. var quad = this.quad;
  32121. var vertices = quad.vertices;
  32122. vertices[0] = vertices[6] = (ts._width) * -ts.anchor.x;
  32123. vertices[1] = vertices[3] = ts._height * -ts.anchor.y;
  32124. vertices[2] = vertices[4] = (ts._width) * (1.0 - ts.anchor.x);
  32125. vertices[5] = vertices[7] = ts._height * (1.0 - ts.anchor.y);
  32126. if (ts.uvRespectAnchor)
  32127. {
  32128. vertices = quad.uvs;
  32129. vertices[0] = vertices[6] = -ts.anchor.x;
  32130. vertices[1] = vertices[3] = -ts.anchor.y;
  32131. vertices[2] = vertices[4] = 1.0 - ts.anchor.x;
  32132. vertices[5] = vertices[7] = 1.0 - ts.anchor.y;
  32133. }
  32134. quad.invalidate();
  32135. var tex = ts._texture;
  32136. var baseTex = tex.baseTexture;
  32137. var lt = ts.tileTransform.localTransform;
  32138. var uv = ts.uvMatrix;
  32139. var isSimple = baseTex.isPowerOfTwo
  32140. && tex.frame.width === baseTex.width && tex.frame.height === baseTex.height;
  32141. // auto, force repeat wrapMode for big tiling textures
  32142. if (isSimple)
  32143. {
  32144. if (!baseTex._glTextures[renderer.CONTEXT_UID])
  32145. {
  32146. if (baseTex.wrapMode === WRAP_MODES.CLAMP)
  32147. {
  32148. baseTex.wrapMode = WRAP_MODES.REPEAT;
  32149. }
  32150. }
  32151. else
  32152. {
  32153. isSimple = baseTex.wrapMode !== WRAP_MODES.CLAMP;
  32154. }
  32155. }
  32156. var shader = isSimple ? this.simpleShader : this.shader;
  32157. var w = tex.width;
  32158. var h = tex.height;
  32159. var W = ts._width;
  32160. var H = ts._height;
  32161. tempMat$1.set(lt.a * w / W,
  32162. lt.b * w / H,
  32163. lt.c * h / W,
  32164. lt.d * h / H,
  32165. lt.tx / W,
  32166. lt.ty / H);
  32167. // that part is the same as above:
  32168. // tempMat.identity();
  32169. // tempMat.scale(tex.width, tex.height);
  32170. // tempMat.prepend(lt);
  32171. // tempMat.scale(1.0 / ts._width, 1.0 / ts._height);
  32172. tempMat$1.invert();
  32173. if (isSimple)
  32174. {
  32175. tempMat$1.prepend(uv.mapCoord);
  32176. }
  32177. else
  32178. {
  32179. shader.uniforms.uMapCoord = uv.mapCoord.toArray(true);
  32180. shader.uniforms.uClampFrame = uv.uClampFrame;
  32181. shader.uniforms.uClampOffset = uv.uClampOffset;
  32182. }
  32183. shader.uniforms.uTransform = tempMat$1.toArray(true);
  32184. shader.uniforms.uColor = premultiplyTintToRgba(ts.tint, ts.worldAlpha,
  32185. shader.uniforms.uColor, baseTex.premultiplyAlpha);
  32186. shader.uniforms.translationMatrix = ts.transform.worldTransform.toArray(true);
  32187. shader.uniforms.uSampler = tex;
  32188. renderer.shader.bind(shader);
  32189. renderer.geometry.bind(quad);// , renderer.shader.getGLShader());
  32190. renderer.state.setBlendMode(correctBlendMode(ts.blendMode, baseTex.premultiplyAlpha));
  32191. renderer.geometry.draw(this.renderer.gl.TRIANGLES, 6, 0);
  32192. };
  32193. return TilingSpriteRenderer;
  32194. }(ObjectRenderer));
  32195. /*!
  32196. * @pixi/text-bitmap - v5.0.4
  32197. * Compiled Fri, 07 Jun 2019 17:17:49 UTC
  32198. *
  32199. * @pixi/text-bitmap is licensed under the MIT License.
  32200. * http://www.opensource.org/licenses/mit-license
  32201. */
  32202. /**
  32203. * A BitmapText object will create a line or multiple lines of text using bitmap font.
  32204. *
  32205. * The primary advantage of this class over Text is that all of your textures are pre-generated and loading,
  32206. * meaning that rendering is fast, and changing text has no performance implications.
  32207. *
  32208. * The primary disadvantage is that you need to preload the bitmap font assets, and thus the styling is set in stone.
  32209. * Supporting character sets other than latin, such as CJK languages, may be impractical due to the number of characters.
  32210. *
  32211. * To split a line you can use '\n', '\r' or '\r\n' in your string.
  32212. *
  32213. * You can generate the fnt files using
  32214. * http://www.angelcode.com/products/bmfont/ for Windows or
  32215. * http://www.bmglyph.com/ for Mac.
  32216. *
  32217. * A BitmapText can only be created when the font is loaded.
  32218. *
  32219. * ```js
  32220. * // in this case the font is in a file called 'desyrel.fnt'
  32221. * let bitmapText = new PIXI.BitmapText("text using a fancy font!", {font: "35px Desyrel", align: "right"});
  32222. * ```
  32223. *
  32224. * @class
  32225. * @extends PIXI.Container
  32226. * @memberof PIXI
  32227. */
  32228. var BitmapText = /*@__PURE__*/(function (Container) {
  32229. function BitmapText(text, style)
  32230. {
  32231. var this$1 = this;
  32232. if ( style === void 0 ) { style = {}; }
  32233. Container.call(this);
  32234. /**
  32235. * Private tracker for the width of the overall text
  32236. *
  32237. * @member {number}
  32238. * @private
  32239. */
  32240. this._textWidth = 0;
  32241. /**
  32242. * Private tracker for the height of the overall text
  32243. *
  32244. * @member {number}
  32245. * @private
  32246. */
  32247. this._textHeight = 0;
  32248. /**
  32249. * Private tracker for the letter sprite pool.
  32250. *
  32251. * @member {PIXI.Sprite[]}
  32252. * @private
  32253. */
  32254. this._glyphs = [];
  32255. /**
  32256. * Private tracker for the current style.
  32257. *
  32258. * @member {object}
  32259. * @private
  32260. */
  32261. this._font = {
  32262. tint: style.tint !== undefined ? style.tint : 0xFFFFFF,
  32263. align: style.align || 'left',
  32264. name: null,
  32265. size: 0,
  32266. };
  32267. /**
  32268. * Private tracker for the current font.
  32269. *
  32270. * @member {object}
  32271. * @private
  32272. */
  32273. this.font = style.font; // run font setter
  32274. /**
  32275. * Private tracker for the current text.
  32276. *
  32277. * @member {string}
  32278. * @private
  32279. */
  32280. this._text = text;
  32281. /**
  32282. * The max width of this bitmap text in pixels. If the text provided is longer than the
  32283. * value provided, line breaks will be automatically inserted in the last whitespace.
  32284. * Disable by setting value to 0
  32285. *
  32286. * @member {number}
  32287. * @private
  32288. */
  32289. this._maxWidth = 0;
  32290. /**
  32291. * The max line height. This is useful when trying to use the total height of the Text,
  32292. * ie: when trying to vertically align.
  32293. *
  32294. * @member {number}
  32295. * @private
  32296. */
  32297. this._maxLineHeight = 0;
  32298. /**
  32299. * Letter spacing. This is useful for setting the space between characters.
  32300. * @member {number}
  32301. * @private
  32302. */
  32303. this._letterSpacing = 0;
  32304. /**
  32305. * Text anchor. read-only
  32306. *
  32307. * @member {PIXI.ObservablePoint}
  32308. * @private
  32309. */
  32310. this._anchor = new ObservablePoint(function () { this$1.dirty = true; }, this, 0, 0);
  32311. /**
  32312. * The dirty state of this object.
  32313. *
  32314. * @member {boolean}
  32315. */
  32316. this.dirty = false;
  32317. /**
  32318. * If true PixiJS will Math.floor() x/y values when rendering, stopping pixel interpolation.
  32319. * Advantages can include sharper image quality (like text) and faster rendering on canvas.
  32320. * The main disadvantage is movement of objects may appear less smooth.
  32321. * To set the global default, change {@link PIXI.settings.ROUND_PIXELS}
  32322. *
  32323. * @member {boolean}
  32324. * @default false
  32325. */
  32326. this.roundPixels = settings.ROUND_PIXELS;
  32327. this.updateText();
  32328. }
  32329. if ( Container ) { BitmapText.__proto__ = Container; }
  32330. BitmapText.prototype = Object.create( Container && Container.prototype );
  32331. BitmapText.prototype.constructor = BitmapText;
  32332. var prototypeAccessors = { tint: { configurable: true },align: { configurable: true },anchor: { configurable: true },font: { configurable: true },text: { configurable: true },maxWidth: { configurable: true },maxLineHeight: { configurable: true },textWidth: { configurable: true },letterSpacing: { configurable: true },textHeight: { configurable: true } };
  32333. /**
  32334. * Renders text and updates it when needed
  32335. *
  32336. * @private
  32337. */
  32338. BitmapText.prototype.updateText = function updateText ()
  32339. {
  32340. var data = BitmapText.fonts[this._font.name];
  32341. var scale = this._font.size / data.size;
  32342. var pos = new Point();
  32343. var chars = [];
  32344. var lineWidths = [];
  32345. var text = this._text.replace(/(?:\r\n|\r)/g, '\n') || ' ';
  32346. var textLength = text.length;
  32347. var maxWidth = this._maxWidth * data.size / this._font.size;
  32348. var prevCharCode = null;
  32349. var lastLineWidth = 0;
  32350. var maxLineWidth = 0;
  32351. var line = 0;
  32352. var lastBreakPos = -1;
  32353. var lastBreakWidth = 0;
  32354. var spacesRemoved = 0;
  32355. var maxLineHeight = 0;
  32356. for (var i = 0; i < textLength; i++)
  32357. {
  32358. var charCode = text.charCodeAt(i);
  32359. var char = text.charAt(i);
  32360. if ((/(?:\s)/).test(char))
  32361. {
  32362. lastBreakPos = i;
  32363. lastBreakWidth = lastLineWidth;
  32364. }
  32365. if (char === '\r' || char === '\n')
  32366. {
  32367. lineWidths.push(lastLineWidth);
  32368. maxLineWidth = Math.max(maxLineWidth, lastLineWidth);
  32369. ++line;
  32370. ++spacesRemoved;
  32371. pos.x = 0;
  32372. pos.y += data.lineHeight;
  32373. prevCharCode = null;
  32374. continue;
  32375. }
  32376. var charData = data.chars[charCode];
  32377. if (!charData)
  32378. {
  32379. continue;
  32380. }
  32381. if (prevCharCode && charData.kerning[prevCharCode])
  32382. {
  32383. pos.x += charData.kerning[prevCharCode];
  32384. }
  32385. chars.push({
  32386. texture: charData.texture,
  32387. line: line,
  32388. charCode: charCode,
  32389. position: new Point(pos.x + charData.xOffset + (this._letterSpacing / 2), pos.y + charData.yOffset),
  32390. });
  32391. pos.x += charData.xAdvance + this._letterSpacing;
  32392. lastLineWidth = pos.x;
  32393. maxLineHeight = Math.max(maxLineHeight, (charData.yOffset + charData.texture.height));
  32394. prevCharCode = charCode;
  32395. if (lastBreakPos !== -1 && maxWidth > 0 && pos.x > maxWidth)
  32396. {
  32397. ++spacesRemoved;
  32398. removeItems(chars, 1 + lastBreakPos - spacesRemoved, 1 + i - lastBreakPos);
  32399. i = lastBreakPos;
  32400. lastBreakPos = -1;
  32401. lineWidths.push(lastBreakWidth);
  32402. maxLineWidth = Math.max(maxLineWidth, lastBreakWidth);
  32403. line++;
  32404. pos.x = 0;
  32405. pos.y += data.lineHeight;
  32406. prevCharCode = null;
  32407. }
  32408. }
  32409. var lastChar = text.charAt(text.length - 1);
  32410. if (lastChar !== '\r' && lastChar !== '\n')
  32411. {
  32412. if ((/(?:\s)/).test(lastChar))
  32413. {
  32414. lastLineWidth = lastBreakWidth;
  32415. }
  32416. lineWidths.push(lastLineWidth);
  32417. maxLineWidth = Math.max(maxLineWidth, lastLineWidth);
  32418. }
  32419. var lineAlignOffsets = [];
  32420. for (var i$1 = 0; i$1 <= line; i$1++)
  32421. {
  32422. var alignOffset = 0;
  32423. if (this._font.align === 'right')
  32424. {
  32425. alignOffset = maxLineWidth - lineWidths[i$1];
  32426. }
  32427. else if (this._font.align === 'center')
  32428. {
  32429. alignOffset = (maxLineWidth - lineWidths[i$1]) / 2;
  32430. }
  32431. lineAlignOffsets.push(alignOffset);
  32432. }
  32433. var lenChars = chars.length;
  32434. var tint = this.tint;
  32435. for (var i$2 = 0; i$2 < lenChars; i$2++)
  32436. {
  32437. var c = this._glyphs[i$2]; // get the next glyph sprite
  32438. if (c)
  32439. {
  32440. c.texture = chars[i$2].texture;
  32441. }
  32442. else
  32443. {
  32444. c = new Sprite(chars[i$2].texture);
  32445. c.roundPixels = this.roundPixels;
  32446. this._glyphs.push(c);
  32447. }
  32448. c.position.x = (chars[i$2].position.x + lineAlignOffsets[chars[i$2].line]) * scale;
  32449. c.position.y = chars[i$2].position.y * scale;
  32450. c.scale.x = c.scale.y = scale;
  32451. c.tint = tint;
  32452. if (!c.parent)
  32453. {
  32454. this.addChild(c);
  32455. }
  32456. }
  32457. // remove unnecessary children.
  32458. for (var i$3 = lenChars; i$3 < this._glyphs.length; ++i$3)
  32459. {
  32460. this.removeChild(this._glyphs[i$3]);
  32461. }
  32462. this._textWidth = maxLineWidth * scale;
  32463. this._textHeight = (pos.y + data.lineHeight) * scale;
  32464. // apply anchor
  32465. if (this.anchor.x !== 0 || this.anchor.y !== 0)
  32466. {
  32467. for (var i$4 = 0; i$4 < lenChars; i$4++)
  32468. {
  32469. this._glyphs[i$4].x -= this._textWidth * this.anchor.x;
  32470. this._glyphs[i$4].y -= this._textHeight * this.anchor.y;
  32471. }
  32472. }
  32473. this._maxLineHeight = maxLineHeight * scale;
  32474. };
  32475. /**
  32476. * Updates the transform of this object
  32477. *
  32478. * @private
  32479. */
  32480. BitmapText.prototype.updateTransform = function updateTransform ()
  32481. {
  32482. this.validate();
  32483. this.containerUpdateTransform();
  32484. };
  32485. /**
  32486. * Validates text before calling parent's getLocalBounds
  32487. *
  32488. * @return {PIXI.Rectangle} The rectangular bounding area
  32489. */
  32490. BitmapText.prototype.getLocalBounds = function getLocalBounds ()
  32491. {
  32492. this.validate();
  32493. return Container.prototype.getLocalBounds.call(this);
  32494. };
  32495. /**
  32496. * Updates text when needed
  32497. *
  32498. * @private
  32499. */
  32500. BitmapText.prototype.validate = function validate ()
  32501. {
  32502. if (this.dirty)
  32503. {
  32504. this.updateText();
  32505. this.dirty = false;
  32506. }
  32507. };
  32508. /**
  32509. * The tint of the BitmapText object.
  32510. *
  32511. * @member {number}
  32512. */
  32513. prototypeAccessors.tint.get = function ()
  32514. {
  32515. return this._font.tint;
  32516. };
  32517. prototypeAccessors.tint.set = function (value) // eslint-disable-line require-jsdoc
  32518. {
  32519. this._font.tint = (typeof value === 'number' && value >= 0) ? value : 0xFFFFFF;
  32520. this.dirty = true;
  32521. };
  32522. /**
  32523. * The alignment of the BitmapText object.
  32524. *
  32525. * @member {string}
  32526. * @default 'left'
  32527. */
  32528. prototypeAccessors.align.get = function ()
  32529. {
  32530. return this._font.align;
  32531. };
  32532. prototypeAccessors.align.set = function (value) // eslint-disable-line require-jsdoc
  32533. {
  32534. this._font.align = value || 'left';
  32535. this.dirty = true;
  32536. };
  32537. /**
  32538. * The anchor sets the origin point of the text.
  32539. *
  32540. * The default is `(0,0)`, this means the text's origin is the top left.
  32541. *
  32542. * Setting the anchor to `(0.5,0.5)` means the text's origin is centered.
  32543. *
  32544. * Setting the anchor to `(1,1)` would mean the text's origin point will be the bottom right corner.
  32545. *
  32546. * @member {PIXI.Point | number}
  32547. */
  32548. prototypeAccessors.anchor.get = function ()
  32549. {
  32550. return this._anchor;
  32551. };
  32552. prototypeAccessors.anchor.set = function (value) // eslint-disable-line require-jsdoc
  32553. {
  32554. if (typeof value === 'number')
  32555. {
  32556. this._anchor.set(value);
  32557. }
  32558. else
  32559. {
  32560. this._anchor.copyFrom(value);
  32561. }
  32562. };
  32563. /**
  32564. * The font descriptor of the BitmapText object.
  32565. *
  32566. * @member {object}
  32567. */
  32568. prototypeAccessors.font.get = function ()
  32569. {
  32570. return this._font;
  32571. };
  32572. prototypeAccessors.font.set = function (value) // eslint-disable-line require-jsdoc
  32573. {
  32574. if (!value)
  32575. {
  32576. return;
  32577. }
  32578. if (typeof value === 'string')
  32579. {
  32580. value = value.split(' ');
  32581. this._font.name = value.length === 1 ? value[0] : value.slice(1).join(' ');
  32582. this._font.size = value.length >= 2 ? parseInt(value[0], 10) : BitmapText.fonts[this._font.name].size;
  32583. }
  32584. else
  32585. {
  32586. this._font.name = value.name;
  32587. this._font.size = typeof value.size === 'number' ? value.size : parseInt(value.size, 10);
  32588. }
  32589. this.dirty = true;
  32590. };
  32591. /**
  32592. * The text of the BitmapText object.
  32593. *
  32594. * @member {string}
  32595. */
  32596. prototypeAccessors.text.get = function ()
  32597. {
  32598. return this._text;
  32599. };
  32600. prototypeAccessors.text.set = function (text) // eslint-disable-line require-jsdoc
  32601. {
  32602. text = String(text === null || text === undefined ? '' : text);
  32603. if (this._text === text)
  32604. {
  32605. return;
  32606. }
  32607. this._text = text;
  32608. this.dirty = true;
  32609. };
  32610. /**
  32611. * The max width of this bitmap text in pixels. If the text provided is longer than the
  32612. * value provided, line breaks will be automatically inserted in the last whitespace.
  32613. * Disable by setting the value to 0.
  32614. *
  32615. * @member {number}
  32616. */
  32617. prototypeAccessors.maxWidth.get = function ()
  32618. {
  32619. return this._maxWidth;
  32620. };
  32621. prototypeAccessors.maxWidth.set = function (value) // eslint-disable-line require-jsdoc
  32622. {
  32623. if (this._maxWidth === value)
  32624. {
  32625. return;
  32626. }
  32627. this._maxWidth = value;
  32628. this.dirty = true;
  32629. };
  32630. /**
  32631. * The max line height. This is useful when trying to use the total height of the Text,
  32632. * i.e. when trying to vertically align.
  32633. *
  32634. * @member {number}
  32635. * @readonly
  32636. */
  32637. prototypeAccessors.maxLineHeight.get = function ()
  32638. {
  32639. this.validate();
  32640. return this._maxLineHeight;
  32641. };
  32642. /**
  32643. * The width of the overall text, different from fontSize,
  32644. * which is defined in the style object.
  32645. *
  32646. * @member {number}
  32647. * @readonly
  32648. */
  32649. prototypeAccessors.textWidth.get = function ()
  32650. {
  32651. this.validate();
  32652. return this._textWidth;
  32653. };
  32654. /**
  32655. * Additional space between characters.
  32656. *
  32657. * @member {number}
  32658. */
  32659. prototypeAccessors.letterSpacing.get = function ()
  32660. {
  32661. return this._letterSpacing;
  32662. };
  32663. prototypeAccessors.letterSpacing.set = function (value) // eslint-disable-line require-jsdoc
  32664. {
  32665. if (this._letterSpacing !== value)
  32666. {
  32667. this._letterSpacing = value;
  32668. this.dirty = true;
  32669. }
  32670. };
  32671. /**
  32672. * The height of the overall text, different from fontSize,
  32673. * which is defined in the style object.
  32674. *
  32675. * @member {number}
  32676. * @readonly
  32677. */
  32678. prototypeAccessors.textHeight.get = function ()
  32679. {
  32680. this.validate();
  32681. return this._textHeight;
  32682. };
  32683. /**
  32684. * Register a bitmap font with data and a texture.
  32685. *
  32686. * @static
  32687. * @param {XMLDocument} xml - The XML document data.
  32688. * @param {Object.<string, PIXI.Texture>|PIXI.Texture|PIXI.Texture[]} textures - List of textures for each page.
  32689. * If providing an object, the key is the `<page>` element's `file` attribute in the FNT file.
  32690. * @return {Object} Result font object with font, size, lineHeight and char fields.
  32691. */
  32692. BitmapText.registerFont = function registerFont (xml, textures)
  32693. {
  32694. var data = {};
  32695. var info = xml.getElementsByTagName('info')[0];
  32696. var common = xml.getElementsByTagName('common')[0];
  32697. var pages = xml.getElementsByTagName('page');
  32698. var res = getResolutionOfUrl(pages[0].getAttribute('file'), settings.RESOLUTION);
  32699. var pagesTextures = {};
  32700. data.font = info.getAttribute('face');
  32701. data.size = parseInt(info.getAttribute('size'), 10);
  32702. data.lineHeight = parseInt(common.getAttribute('lineHeight'), 10) / res;
  32703. data.chars = {};
  32704. // Single texture, convert to list
  32705. if (textures instanceof Texture)
  32706. {
  32707. textures = [textures];
  32708. }
  32709. // Convert the input Texture, Textures or object
  32710. // into a page Texture lookup by "id"
  32711. for (var i = 0; i < pages.length; i++)
  32712. {
  32713. var id = pages[i].getAttribute('id');
  32714. var file = pages[i].getAttribute('file');
  32715. pagesTextures[id] = textures instanceof Array ? textures[i] : textures[file];
  32716. }
  32717. // parse letters
  32718. var letters = xml.getElementsByTagName('char');
  32719. for (var i$1 = 0; i$1 < letters.length; i$1++)
  32720. {
  32721. var letter = letters[i$1];
  32722. var charCode = parseInt(letter.getAttribute('id'), 10);
  32723. var page = letter.getAttribute('page') || 0;
  32724. var textureRect = new Rectangle(
  32725. (parseInt(letter.getAttribute('x'), 10) / res) + (pagesTextures[page].frame.x / res),
  32726. (parseInt(letter.getAttribute('y'), 10) / res) + (pagesTextures[page].frame.y / res),
  32727. parseInt(letter.getAttribute('width'), 10) / res,
  32728. parseInt(letter.getAttribute('height'), 10) / res
  32729. );
  32730. data.chars[charCode] = {
  32731. xOffset: parseInt(letter.getAttribute('xoffset'), 10) / res,
  32732. yOffset: parseInt(letter.getAttribute('yoffset'), 10) / res,
  32733. xAdvance: parseInt(letter.getAttribute('xadvance'), 10) / res,
  32734. kerning: {},
  32735. texture: new Texture(pagesTextures[page].baseTexture, textureRect),
  32736. page: page,
  32737. };
  32738. }
  32739. // parse kernings
  32740. var kernings = xml.getElementsByTagName('kerning');
  32741. for (var i$2 = 0; i$2 < kernings.length; i$2++)
  32742. {
  32743. var kerning = kernings[i$2];
  32744. var first = parseInt(kerning.getAttribute('first'), 10) / res;
  32745. var second = parseInt(kerning.getAttribute('second'), 10) / res;
  32746. var amount = parseInt(kerning.getAttribute('amount'), 10) / res;
  32747. if (data.chars[second])
  32748. {
  32749. data.chars[second].kerning[first] = amount;
  32750. }
  32751. }
  32752. // I'm leaving this as a temporary fix so we can test the bitmap fonts in v3
  32753. // but it's very likely to change
  32754. BitmapText.fonts[data.font] = data;
  32755. return data;
  32756. };
  32757. Object.defineProperties( BitmapText.prototype, prototypeAccessors );
  32758. return BitmapText;
  32759. }(Container));
  32760. BitmapText.fonts = {};
  32761. /**
  32762. * {@link PIXI.Loader Loader} middleware for loading
  32763. * bitmap-based fonts suitable for using with {@link PIXI.BitmapText}.
  32764. * @class
  32765. * @memberof PIXI
  32766. * @implements PIXI.ILoaderPlugin
  32767. */
  32768. var BitmapFontLoader = function BitmapFontLoader () {};
  32769. BitmapFontLoader.parse = function parse (resource, texture)
  32770. {
  32771. resource.bitmapFont = BitmapText.registerFont(resource.data, texture);
  32772. };
  32773. /**
  32774. * Called when the plugin is installed.
  32775. *
  32776. * @see PIXI.Loader.registerPlugin
  32777. */
  32778. BitmapFontLoader.add = function add ()
  32779. {
  32780. LoaderResource.setExtensionXhrType('fnt', LoaderResource.XHR_RESPONSE_TYPE.DOCUMENT);
  32781. };
  32782. /**
  32783. * Replacement for NodeJS's path.dirname
  32784. * @private
  32785. * @param {string} url Path to get directory for
  32786. */
  32787. BitmapFontLoader.dirname = function dirname (url)
  32788. {
  32789. var dir = url
  32790. .replace(/\/$/, '') // replace trailing slash
  32791. .replace(/\/[^\/]*$/, ''); // remove everything after the last
  32792. // File request is relative, use current directory
  32793. if (dir === url)
  32794. {
  32795. return '.';
  32796. }
  32797. // Started with a slash
  32798. else if (dir === '')
  32799. {
  32800. return '/';
  32801. }
  32802. return dir;
  32803. };
  32804. /**
  32805. * Called after a resource is loaded.
  32806. * @see PIXI.Loader.loaderMiddleware
  32807. * @param {PIXI.LoaderResource} resource
  32808. * @param {function} next
  32809. */
  32810. BitmapFontLoader.use = function use (resource, next)
  32811. {
  32812. // skip if no data or not xml data
  32813. if (!resource.data || resource.type !== LoaderResource.TYPE.XML)
  32814. {
  32815. next();
  32816. return;
  32817. }
  32818. // skip if not bitmap font data, using some silly duck-typing
  32819. if (resource.data.getElementsByTagName('page').length === 0
  32820. || resource.data.getElementsByTagName('info').length === 0
  32821. || resource.data.getElementsByTagName('info')[0].getAttribute('face') === null
  32822. )
  32823. {
  32824. next();
  32825. return;
  32826. }
  32827. var xmlUrl = !resource.isDataUrl ? BitmapFontLoader.dirname(resource.url) : '';
  32828. if (resource.isDataUrl)
  32829. {
  32830. if (xmlUrl === '.')
  32831. {
  32832. xmlUrl = '';
  32833. }
  32834. if (this.baseUrl && xmlUrl)
  32835. {
  32836. // if baseurl has a trailing slash then add one to xmlUrl so the replace works below
  32837. if (this.baseUrl.charAt(this.baseUrl.length - 1) === '/')
  32838. {
  32839. xmlUrl += '/';
  32840. }
  32841. }
  32842. }
  32843. // remove baseUrl from xmlUrl
  32844. xmlUrl = xmlUrl.replace(this.baseUrl, '');
  32845. // if there is an xmlUrl now, it needs a trailing slash. Ensure that it does if the string isn't empty.
  32846. if (xmlUrl && xmlUrl.charAt(xmlUrl.length - 1) !== '/')
  32847. {
  32848. xmlUrl += '/';
  32849. }
  32850. var pages = resource.data.getElementsByTagName('page');
  32851. var textures = {};
  32852. // Handle completed, when the number of textures
  32853. // load is the same number as references in the fnt file
  32854. var completed = function (page) {
  32855. textures[page.metadata.pageFile] = page.texture;
  32856. if (Object.keys(textures).length === pages.length)
  32857. {
  32858. BitmapFontLoader.parse(resource, textures);
  32859. next();
  32860. }
  32861. };
  32862. for (var i = 0; i < pages.length; ++i)
  32863. {
  32864. var pageFile = pages[i].getAttribute('file');
  32865. var url = xmlUrl + pageFile;
  32866. var exists = false;
  32867. // incase the image is loaded outside
  32868. // using the same loader, resource will be available
  32869. for (var name in this.resources)
  32870. {
  32871. var bitmapResource = this.resources[name];
  32872. if (bitmapResource.url === url)
  32873. {
  32874. bitmapResource.metadata.pageFile = pageFile;
  32875. if (bitmapResource.texture)
  32876. {
  32877. completed(bitmapResource);
  32878. }
  32879. else
  32880. {
  32881. bitmapResource.onAfterMiddleware.add(completed);
  32882. }
  32883. exists = true;
  32884. break;
  32885. }
  32886. }
  32887. // texture is not loaded, we'll attempt to add
  32888. // it to the load and add the texture to the list
  32889. if (!exists)
  32890. {
  32891. // Standard loading options for images
  32892. var options = {
  32893. crossOrigin: resource.crossOrigin,
  32894. loadType: LoaderResource.LOAD_TYPE.IMAGE,
  32895. metadata: Object.assign(
  32896. { pageFile: pageFile },
  32897. resource.metadata.imageMetadata
  32898. ),
  32899. parentResource: resource,
  32900. };
  32901. this.add(url, options, completed);
  32902. }
  32903. }
  32904. };
  32905. /*!
  32906. * @pixi/filter-alpha - v5.0.4
  32907. * Compiled Fri, 07 Jun 2019 17:17:49 UTC
  32908. *
  32909. * @pixi/filter-alpha is licensed under the MIT License.
  32910. * http://www.opensource.org/licenses/mit-license
  32911. */
  32912. var fragment$3 = "varying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform float uAlpha;\n\nvoid main(void)\n{\n gl_FragColor = texture2D(uSampler, vTextureCoord) * uAlpha;\n}\n";
  32913. /**
  32914. * Simplest filter - applies alpha.
  32915. *
  32916. * Use this instead of Container's alpha property to avoid visual layering of individual elements.
  32917. * AlphaFilter applies alpha evenly across the entire display object and any opaque elements it contains.
  32918. * If elements are not opaque, they will blend with each other anyway.
  32919. *
  32920. * Very handy if you want to use common features of all filters:
  32921. *
  32922. * 1. Assign a blendMode to this filter, blend all elements inside display object with background.
  32923. *
  32924. * 2. To use clipping in display coordinates, assign a filterArea to the same container that has this filter.
  32925. *
  32926. * @class
  32927. * @extends PIXI.Filter
  32928. * @memberof PIXI.filters
  32929. */
  32930. var AlphaFilter = /*@__PURE__*/(function (Filter) {
  32931. function AlphaFilter(alpha)
  32932. {
  32933. if ( alpha === void 0 ) { alpha = 1.0; }
  32934. Filter.call(this, _default, fragment$3, { uAlpha: 1 });
  32935. this.alpha = alpha;
  32936. }
  32937. if ( Filter ) { AlphaFilter.__proto__ = Filter; }
  32938. AlphaFilter.prototype = Object.create( Filter && Filter.prototype );
  32939. AlphaFilter.prototype.constructor = AlphaFilter;
  32940. var prototypeAccessors = { alpha: { configurable: true } };
  32941. /**
  32942. * Coefficient for alpha multiplication
  32943. *
  32944. * @member {number}
  32945. * @default 1
  32946. */
  32947. prototypeAccessors.alpha.get = function ()
  32948. {
  32949. return this.uniforms.uAlpha;
  32950. };
  32951. prototypeAccessors.alpha.set = function (value) // eslint-disable-line require-jsdoc
  32952. {
  32953. this.uniforms.uAlpha = value;
  32954. };
  32955. Object.defineProperties( AlphaFilter.prototype, prototypeAccessors );
  32956. return AlphaFilter;
  32957. }(Filter));
  32958. /*!
  32959. * @pixi/filter-blur - v5.0.4
  32960. * Compiled Fri, 07 Jun 2019 17:17:49 UTC
  32961. *
  32962. * @pixi/filter-blur is licensed under the MIT License.
  32963. * http://www.opensource.org/licenses/mit-license
  32964. */
  32965. 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 }";
  32966. function generateBlurVertSource(kernelSize, x)
  32967. {
  32968. var halfLength = Math.ceil(kernelSize / 2);
  32969. var vertSource = vertTemplate;
  32970. var blurLoop = '';
  32971. var template;
  32972. // let value;
  32973. if (x)
  32974. {
  32975. template = 'vBlurTexCoords[%index%] = textureCoord + vec2(%sampleIndex% * strength, 0.0);';
  32976. }
  32977. else
  32978. {
  32979. template = 'vBlurTexCoords[%index%] = textureCoord + vec2(0.0, %sampleIndex% * strength);';
  32980. }
  32981. for (var i = 0; i < kernelSize; i++)
  32982. {
  32983. var blur = template.replace('%index%', i);
  32984. // value = i;
  32985. // if(i >= halfLength)
  32986. // {
  32987. // value = kernelSize - i - 1;
  32988. // }
  32989. blur = blur.replace('%sampleIndex%', ((i - (halfLength - 1)) + ".0"));
  32990. blurLoop += blur;
  32991. blurLoop += '\n';
  32992. }
  32993. vertSource = vertSource.replace('%blur%', blurLoop);
  32994. vertSource = vertSource.replace('%size%', kernelSize);
  32995. return vertSource;
  32996. }
  32997. var GAUSSIAN_VALUES = {
  32998. 5: [0.153388, 0.221461, 0.250301],
  32999. 7: [0.071303, 0.131514, 0.189879, 0.214607],
  33000. 9: [0.028532, 0.067234, 0.124009, 0.179044, 0.20236],
  33001. 11: [0.0093, 0.028002, 0.065984, 0.121703, 0.175713, 0.198596],
  33002. 13: [0.002406, 0.009255, 0.027867, 0.065666, 0.121117, 0.174868, 0.197641],
  33003. 15: [0.000489, 0.002403, 0.009246, 0.02784, 0.065602, 0.120999, 0.174697, 0.197448],
  33004. };
  33005. var fragTemplate$2 = [
  33006. 'varying vec2 vBlurTexCoords[%size%];',
  33007. 'uniform sampler2D uSampler;',
  33008. 'void main(void)',
  33009. '{',
  33010. ' gl_FragColor = vec4(0.0);',
  33011. ' %blur%',
  33012. '}' ].join('\n');
  33013. function generateBlurFragSource(kernelSize)
  33014. {
  33015. var kernel = GAUSSIAN_VALUES[kernelSize];
  33016. var halfLength = kernel.length;
  33017. var fragSource = fragTemplate$2;
  33018. var blurLoop = '';
  33019. var template = 'gl_FragColor += texture2D(uSampler, vBlurTexCoords[%index%]) * %value%;';
  33020. var value;
  33021. for (var i = 0; i < kernelSize; i++)
  33022. {
  33023. var blur = template.replace('%index%', i);
  33024. value = i;
  33025. if (i >= halfLength)
  33026. {
  33027. value = kernelSize - i - 1;
  33028. }
  33029. blur = blur.replace('%value%', kernel[value]);
  33030. blurLoop += blur;
  33031. blurLoop += '\n';
  33032. }
  33033. fragSource = fragSource.replace('%blur%', blurLoop);
  33034. fragSource = fragSource.replace('%size%', kernelSize);
  33035. return fragSource;
  33036. }
  33037. /**
  33038. * The BlurFilterPass applies a horizontal or vertical Gaussian blur to an object.
  33039. *
  33040. * @class
  33041. * @extends PIXI.Filter
  33042. * @memberof PIXI.filters
  33043. */
  33044. var BlurFilterPass = /*@__PURE__*/(function (Filter) {
  33045. function BlurFilterPass(horizontal, strength, quality, resolution, kernelSize)
  33046. {
  33047. kernelSize = kernelSize || 5;
  33048. var vertSrc = generateBlurVertSource(kernelSize, horizontal);
  33049. var fragSrc = generateBlurFragSource(kernelSize);
  33050. Filter.call(
  33051. // vertex shader
  33052. this, vertSrc,
  33053. // fragment shader
  33054. fragSrc
  33055. );
  33056. this.horizontal = horizontal;
  33057. this.resolution = resolution || settings.RESOLUTION;
  33058. this._quality = 0;
  33059. this.quality = quality || 4;
  33060. this.blur = strength || 8;
  33061. }
  33062. if ( Filter ) { BlurFilterPass.__proto__ = Filter; }
  33063. BlurFilterPass.prototype = Object.create( Filter && Filter.prototype );
  33064. BlurFilterPass.prototype.constructor = BlurFilterPass;
  33065. var prototypeAccessors = { blur: { configurable: true },quality: { configurable: true } };
  33066. BlurFilterPass.prototype.apply = function apply (filterManager, input, output, clear)
  33067. {
  33068. if (output)
  33069. {
  33070. if (this.horizontal)
  33071. {
  33072. this.uniforms.strength = (1 / output.width) * (output.width / input.width);
  33073. }
  33074. else
  33075. {
  33076. this.uniforms.strength = (1 / output.height) * (output.height / input.height);
  33077. }
  33078. }
  33079. else
  33080. {
  33081. if (this.horizontal) // eslint-disable-line
  33082. {
  33083. this.uniforms.strength = (1 / filterManager.renderer.width) * (filterManager.renderer.width / input.width);
  33084. }
  33085. else
  33086. {
  33087. this.uniforms.strength = (1 / filterManager.renderer.height) * (filterManager.renderer.height / input.height); // eslint-disable-line
  33088. }
  33089. }
  33090. // screen space!
  33091. this.uniforms.strength *= this.strength;
  33092. this.uniforms.strength /= this.passes;
  33093. if (this.passes === 1)
  33094. {
  33095. filterManager.applyFilter(this, input, output, clear);
  33096. }
  33097. else
  33098. {
  33099. var renderTarget = filterManager.getFilterTexture();
  33100. var renderer = filterManager.renderer;
  33101. var flip = input;
  33102. var flop = renderTarget;
  33103. this.state.blend = false;
  33104. filterManager.applyFilter(this, flip, flop, false);
  33105. for (var i = 1; i < this.passes - 1; i++)
  33106. {
  33107. renderer.renderTexture.bind(flip, flip.filterFrame);
  33108. this.uniforms.uSampler = flop;
  33109. var temp = flop;
  33110. flop = flip;
  33111. flip = temp;
  33112. renderer.shader.bind(this);
  33113. renderer.geometry.draw(5);
  33114. }
  33115. this.state.blend = true;
  33116. filterManager.applyFilter(this, flop, output, clear);
  33117. filterManager.returnFilterTexture(renderTarget);
  33118. }
  33119. };
  33120. /**
  33121. * Sets the strength of both the blur.
  33122. *
  33123. * @member {number}
  33124. * @default 16
  33125. */
  33126. prototypeAccessors.blur.get = function ()
  33127. {
  33128. return this.strength;
  33129. };
  33130. prototypeAccessors.blur.set = function (value) // eslint-disable-line require-jsdoc
  33131. {
  33132. this.padding = 1 + (Math.abs(value) * 2);
  33133. this.strength = value;
  33134. };
  33135. /**
  33136. * Sets the quality of the blur by modifying the number of passes. More passes means higher
  33137. * quaility bluring but the lower the performance.
  33138. *
  33139. * @member {number}
  33140. * @default 4
  33141. */
  33142. prototypeAccessors.quality.get = function ()
  33143. {
  33144. return this._quality;
  33145. };
  33146. prototypeAccessors.quality.set = function (value) // eslint-disable-line require-jsdoc
  33147. {
  33148. this._quality = value;
  33149. this.passes = value;
  33150. };
  33151. Object.defineProperties( BlurFilterPass.prototype, prototypeAccessors );
  33152. return BlurFilterPass;
  33153. }(Filter));
  33154. /**
  33155. * The BlurFilter applies a Gaussian blur to an object.
  33156. *
  33157. * The strength of the blur can be set for the x-axis and y-axis separately.
  33158. *
  33159. * @class
  33160. * @extends PIXI.Filter
  33161. * @memberof PIXI.filters
  33162. */
  33163. var BlurFilter = /*@__PURE__*/(function (Filter) {
  33164. function BlurFilter(strength, quality, resolution, kernelSize)
  33165. {
  33166. Filter.call(this);
  33167. this.blurXFilter = new BlurFilterPass(true, strength, quality, resolution, kernelSize);
  33168. this.blurYFilter = new BlurFilterPass(false, strength, quality, resolution, kernelSize);
  33169. this.resolution = resolution || settings.RESOLUTION;
  33170. this.quality = quality || 4;
  33171. this.blur = strength || 8;
  33172. this.repeatEdgePixels = false;
  33173. }
  33174. if ( Filter ) { BlurFilter.__proto__ = Filter; }
  33175. BlurFilter.prototype = Object.create( Filter && Filter.prototype );
  33176. BlurFilter.prototype.constructor = BlurFilter;
  33177. var prototypeAccessors = { blur: { configurable: true },quality: { configurable: true },blurX: { configurable: true },blurY: { configurable: true },blendMode: { configurable: true },repeatEdgePixels: { configurable: true } };
  33178. /**
  33179. * Applies the filter.
  33180. *
  33181. * @param {PIXI.systems.FilterSystem} filterManager - The manager.
  33182. * @param {PIXI.RenderTexture} input - The input target.
  33183. * @param {PIXI.RenderTexture} output - The output target.
  33184. */
  33185. BlurFilter.prototype.apply = function apply (filterManager, input, output, clear)
  33186. {
  33187. var xStrength = Math.abs(this.blurXFilter.strength);
  33188. var yStrength = Math.abs(this.blurYFilter.strength);
  33189. if (xStrength && yStrength)
  33190. {
  33191. var renderTarget = filterManager.getFilterTexture();
  33192. this.blurXFilter.apply(filterManager, input, renderTarget, true);
  33193. this.blurYFilter.apply(filterManager, renderTarget, output, clear);
  33194. filterManager.returnFilterTexture(renderTarget);
  33195. }
  33196. else if (yStrength)
  33197. {
  33198. this.blurYFilter.apply(filterManager, input, output, clear);
  33199. }
  33200. else
  33201. {
  33202. this.blurXFilter.apply(filterManager, input, output, clear);
  33203. }
  33204. };
  33205. BlurFilter.prototype.updatePadding = function updatePadding ()
  33206. {
  33207. if (this._repeatEdgePixels)
  33208. {
  33209. this.padding = 0;
  33210. }
  33211. else
  33212. {
  33213. this.padding = Math.max(Math.abs(this.blurXFilter.strength), Math.abs(this.blurYFilter.strength)) * 2;
  33214. }
  33215. };
  33216. /**
  33217. * Sets the strength of both the blurX and blurY properties simultaneously
  33218. *
  33219. * @member {number}
  33220. * @default 2
  33221. */
  33222. prototypeAccessors.blur.get = function ()
  33223. {
  33224. return this.blurXFilter.blur;
  33225. };
  33226. prototypeAccessors.blur.set = function (value) // eslint-disable-line require-jsdoc
  33227. {
  33228. this.blurXFilter.blur = this.blurYFilter.blur = value;
  33229. this.updatePadding();
  33230. };
  33231. /**
  33232. * Sets the number of passes for blur. More passes means higher quaility bluring.
  33233. *
  33234. * @member {number}
  33235. * @default 1
  33236. */
  33237. prototypeAccessors.quality.get = function ()
  33238. {
  33239. return this.blurXFilter.quality;
  33240. };
  33241. prototypeAccessors.quality.set = function (value) // eslint-disable-line require-jsdoc
  33242. {
  33243. this.blurXFilter.quality = this.blurYFilter.quality = value;
  33244. };
  33245. /**
  33246. * Sets the strength of the blurX property
  33247. *
  33248. * @member {number}
  33249. * @default 2
  33250. */
  33251. prototypeAccessors.blurX.get = function ()
  33252. {
  33253. return this.blurXFilter.blur;
  33254. };
  33255. prototypeAccessors.blurX.set = function (value) // eslint-disable-line require-jsdoc
  33256. {
  33257. this.blurXFilter.blur = value;
  33258. this.updatePadding();
  33259. };
  33260. /**
  33261. * Sets the strength of the blurY property
  33262. *
  33263. * @member {number}
  33264. * @default 2
  33265. */
  33266. prototypeAccessors.blurY.get = function ()
  33267. {
  33268. return this.blurYFilter.blur;
  33269. };
  33270. prototypeAccessors.blurY.set = function (value) // eslint-disable-line require-jsdoc
  33271. {
  33272. this.blurYFilter.blur = value;
  33273. this.updatePadding();
  33274. };
  33275. /**
  33276. * Sets the blendmode of the filter
  33277. *
  33278. * @member {number}
  33279. * @default PIXI.BLEND_MODES.NORMAL
  33280. */
  33281. prototypeAccessors.blendMode.get = function ()
  33282. {
  33283. return this.blurYFilter.blendMode;
  33284. };
  33285. prototypeAccessors.blendMode.set = function (value) // eslint-disable-line require-jsdoc
  33286. {
  33287. this.blurYFilter.blendMode = value;
  33288. };
  33289. /**
  33290. * If set to true the edge of the target will be clamped
  33291. *
  33292. * @member {bool}
  33293. * @default false
  33294. */
  33295. prototypeAccessors.repeatEdgePixels.get = function ()
  33296. {
  33297. return this._repeatEdgePixels;
  33298. };
  33299. prototypeAccessors.repeatEdgePixels.set = function (value)
  33300. {
  33301. this._repeatEdgePixels = value;
  33302. this.updatePadding();
  33303. };
  33304. Object.defineProperties( BlurFilter.prototype, prototypeAccessors );
  33305. return BlurFilter;
  33306. }(Filter));
  33307. /*!
  33308. * @pixi/filter-color-matrix - v5.0.4
  33309. * Compiled Fri, 07 Jun 2019 17:17:49 UTC
  33310. *
  33311. * @pixi/filter-color-matrix is licensed under the MIT License.
  33312. * http://www.opensource.org/licenses/mit-license
  33313. */
  33314. var fragment$4 = "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";
  33315. /**
  33316. * The ColorMatrixFilter class lets you apply a 5x4 matrix transformation on the RGBA
  33317. * color and alpha values of every pixel on your displayObject to produce a result
  33318. * with a new set of RGBA color and alpha values. It's pretty powerful!
  33319. *
  33320. * ```js
  33321. * let colorMatrix = new PIXI.filters.ColorMatrixFilter();
  33322. * container.filters = [colorMatrix];
  33323. * colorMatrix.contrast(2);
  33324. * ```
  33325. * @author Clément Chenebault <clement@goodboydigital.com>
  33326. * @class
  33327. * @extends PIXI.Filter
  33328. * @memberof PIXI.filters
  33329. */
  33330. var ColorMatrixFilter = /*@__PURE__*/(function (Filter) {
  33331. function ColorMatrixFilter()
  33332. {
  33333. var uniforms = {
  33334. m: new Float32Array([1, 0, 0, 0, 0,
  33335. 0, 1, 0, 0, 0,
  33336. 0, 0, 1, 0, 0,
  33337. 0, 0, 0, 1, 0]),
  33338. uAlpha: 1,
  33339. };
  33340. Filter.call(this, defaultFilter, fragment$4, uniforms);
  33341. this.alpha = 1;
  33342. }
  33343. if ( Filter ) { ColorMatrixFilter.__proto__ = Filter; }
  33344. ColorMatrixFilter.prototype = Object.create( Filter && Filter.prototype );
  33345. ColorMatrixFilter.prototype.constructor = ColorMatrixFilter;
  33346. var prototypeAccessors = { matrix: { configurable: true },alpha: { configurable: true } };
  33347. /**
  33348. * Transforms current matrix and set the new one
  33349. *
  33350. * @param {number[]} matrix - 5x4 matrix
  33351. * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false,
  33352. * just set the current matrix with @param matrix
  33353. */
  33354. ColorMatrixFilter.prototype._loadMatrix = function _loadMatrix (matrix, multiply)
  33355. {
  33356. if ( multiply === void 0 ) { multiply = false; }
  33357. var newMatrix = matrix;
  33358. if (multiply)
  33359. {
  33360. this._multiply(newMatrix, this.uniforms.m, matrix);
  33361. newMatrix = this._colorMatrix(newMatrix);
  33362. }
  33363. // set the new matrix
  33364. this.uniforms.m = newMatrix;
  33365. };
  33366. /**
  33367. * Multiplies two mat5's
  33368. *
  33369. * @private
  33370. * @param {number[]} out - 5x4 matrix the receiving matrix
  33371. * @param {number[]} a - 5x4 matrix the first operand
  33372. * @param {number[]} b - 5x4 matrix the second operand
  33373. * @returns {number[]} 5x4 matrix
  33374. */
  33375. ColorMatrixFilter.prototype._multiply = function _multiply (out, a, b)
  33376. {
  33377. // Red Channel
  33378. out[0] = (a[0] * b[0]) + (a[1] * b[5]) + (a[2] * b[10]) + (a[3] * b[15]);
  33379. out[1] = (a[0] * b[1]) + (a[1] * b[6]) + (a[2] * b[11]) + (a[3] * b[16]);
  33380. out[2] = (a[0] * b[2]) + (a[1] * b[7]) + (a[2] * b[12]) + (a[3] * b[17]);
  33381. out[3] = (a[0] * b[3]) + (a[1] * b[8]) + (a[2] * b[13]) + (a[3] * b[18]);
  33382. out[4] = (a[0] * b[4]) + (a[1] * b[9]) + (a[2] * b[14]) + (a[3] * b[19]) + a[4];
  33383. // Green Channel
  33384. out[5] = (a[5] * b[0]) + (a[6] * b[5]) + (a[7] * b[10]) + (a[8] * b[15]);
  33385. out[6] = (a[5] * b[1]) + (a[6] * b[6]) + (a[7] * b[11]) + (a[8] * b[16]);
  33386. out[7] = (a[5] * b[2]) + (a[6] * b[7]) + (a[7] * b[12]) + (a[8] * b[17]);
  33387. out[8] = (a[5] * b[3]) + (a[6] * b[8]) + (a[7] * b[13]) + (a[8] * b[18]);
  33388. out[9] = (a[5] * b[4]) + (a[6] * b[9]) + (a[7] * b[14]) + (a[8] * b[19]) + a[9];
  33389. // Blue Channel
  33390. out[10] = (a[10] * b[0]) + (a[11] * b[5]) + (a[12] * b[10]) + (a[13] * b[15]);
  33391. out[11] = (a[10] * b[1]) + (a[11] * b[6]) + (a[12] * b[11]) + (a[13] * b[16]);
  33392. out[12] = (a[10] * b[2]) + (a[11] * b[7]) + (a[12] * b[12]) + (a[13] * b[17]);
  33393. out[13] = (a[10] * b[3]) + (a[11] * b[8]) + (a[12] * b[13]) + (a[13] * b[18]);
  33394. out[14] = (a[10] * b[4]) + (a[11] * b[9]) + (a[12] * b[14]) + (a[13] * b[19]) + a[14];
  33395. // Alpha Channel
  33396. out[15] = (a[15] * b[0]) + (a[16] * b[5]) + (a[17] * b[10]) + (a[18] * b[15]);
  33397. out[16] = (a[15] * b[1]) + (a[16] * b[6]) + (a[17] * b[11]) + (a[18] * b[16]);
  33398. out[17] = (a[15] * b[2]) + (a[16] * b[7]) + (a[17] * b[12]) + (a[18] * b[17]);
  33399. out[18] = (a[15] * b[3]) + (a[16] * b[8]) + (a[17] * b[13]) + (a[18] * b[18]);
  33400. out[19] = (a[15] * b[4]) + (a[16] * b[9]) + (a[17] * b[14]) + (a[18] * b[19]) + a[19];
  33401. return out;
  33402. };
  33403. /**
  33404. * Create a Float32 Array and normalize the offset component to 0-1
  33405. *
  33406. * @private
  33407. * @param {number[]} matrix - 5x4 matrix
  33408. * @return {number[]} 5x4 matrix with all values between 0-1
  33409. */
  33410. ColorMatrixFilter.prototype._colorMatrix = function _colorMatrix (matrix)
  33411. {
  33412. // Create a Float32 Array and normalize the offset component to 0-1
  33413. var m = new Float32Array(matrix);
  33414. m[4] /= 255;
  33415. m[9] /= 255;
  33416. m[14] /= 255;
  33417. m[19] /= 255;
  33418. return m;
  33419. };
  33420. /**
  33421. * Adjusts brightness
  33422. *
  33423. * @param {number} b - value of the brigthness (0-1, where 0 is black)
  33424. * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false,
  33425. * just set the current matrix with @param matrix
  33426. */
  33427. ColorMatrixFilter.prototype.brightness = function brightness (b, multiply)
  33428. {
  33429. var matrix = [
  33430. b, 0, 0, 0, 0,
  33431. 0, b, 0, 0, 0,
  33432. 0, 0, b, 0, 0,
  33433. 0, 0, 0, 1, 0 ];
  33434. this._loadMatrix(matrix, multiply);
  33435. };
  33436. /**
  33437. * Set the matrices in grey scales
  33438. *
  33439. * @param {number} scale - value of the grey (0-1, where 0 is black)
  33440. * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false,
  33441. * just set the current matrix with @param matrix
  33442. */
  33443. ColorMatrixFilter.prototype.greyscale = function greyscale (scale, multiply)
  33444. {
  33445. var matrix = [
  33446. scale, scale, scale, 0, 0,
  33447. scale, scale, scale, 0, 0,
  33448. scale, scale, scale, 0, 0,
  33449. 0, 0, 0, 1, 0 ];
  33450. this._loadMatrix(matrix, multiply);
  33451. };
  33452. /**
  33453. * Set the black and white matrice.
  33454. *
  33455. * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false,
  33456. * just set the current matrix with @param matrix
  33457. */
  33458. ColorMatrixFilter.prototype.blackAndWhite = function blackAndWhite (multiply)
  33459. {
  33460. var matrix = [
  33461. 0.3, 0.6, 0.1, 0, 0,
  33462. 0.3, 0.6, 0.1, 0, 0,
  33463. 0.3, 0.6, 0.1, 0, 0,
  33464. 0, 0, 0, 1, 0 ];
  33465. this._loadMatrix(matrix, multiply);
  33466. };
  33467. /**
  33468. * Set the hue property of the color
  33469. *
  33470. * @param {number} rotation - in degrees
  33471. * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false,
  33472. * just set the current matrix with @param matrix
  33473. */
  33474. ColorMatrixFilter.prototype.hue = function hue (rotation, multiply)
  33475. {
  33476. rotation = (rotation || 0) / 180 * Math.PI;
  33477. var cosR = Math.cos(rotation);
  33478. var sinR = Math.sin(rotation);
  33479. var sqrt = Math.sqrt;
  33480. /* a good approximation for hue rotation
  33481. This matrix is far better than the versions with magic luminance constants
  33482. formerly used here, but also used in the starling framework (flash) and known from this
  33483. old part of the internet: quasimondo.com/archives/000565.php
  33484. This new matrix is based on rgb cube rotation in space. Look here for a more descriptive
  33485. implementation as a shader not a general matrix:
  33486. https://github.com/evanw/glfx.js/blob/58841c23919bd59787effc0333a4897b43835412/src/filters/adjust/huesaturation.js
  33487. This is the source for the code:
  33488. see http://stackoverflow.com/questions/8507885/shift-hue-of-an-rgb-color/8510751#8510751
  33489. */
  33490. var w = 1 / 3;
  33491. var sqrW = sqrt(w); // weight is
  33492. var a00 = cosR + ((1.0 - cosR) * w);
  33493. var a01 = (w * (1.0 - cosR)) - (sqrW * sinR);
  33494. var a02 = (w * (1.0 - cosR)) + (sqrW * sinR);
  33495. var a10 = (w * (1.0 - cosR)) + (sqrW * sinR);
  33496. var a11 = cosR + (w * (1.0 - cosR));
  33497. var a12 = (w * (1.0 - cosR)) - (sqrW * sinR);
  33498. var a20 = (w * (1.0 - cosR)) - (sqrW * sinR);
  33499. var a21 = (w * (1.0 - cosR)) + (sqrW * sinR);
  33500. var a22 = cosR + (w * (1.0 - cosR));
  33501. var matrix = [
  33502. a00, a01, a02, 0, 0,
  33503. a10, a11, a12, 0, 0,
  33504. a20, a21, a22, 0, 0,
  33505. 0, 0, 0, 1, 0 ];
  33506. this._loadMatrix(matrix, multiply);
  33507. };
  33508. /**
  33509. * Set the contrast matrix, increase the separation between dark and bright
  33510. * Increase contrast : shadows darker and highlights brighter
  33511. * Decrease contrast : bring the shadows up and the highlights down
  33512. *
  33513. * @param {number} amount - value of the contrast (0-1)
  33514. * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false,
  33515. * just set the current matrix with @param matrix
  33516. */
  33517. ColorMatrixFilter.prototype.contrast = function contrast (amount, multiply)
  33518. {
  33519. var v = (amount || 0) + 1;
  33520. var o = -0.5 * (v - 1);
  33521. var matrix = [
  33522. v, 0, 0, 0, o,
  33523. 0, v, 0, 0, o,
  33524. 0, 0, v, 0, o,
  33525. 0, 0, 0, 1, 0 ];
  33526. this._loadMatrix(matrix, multiply);
  33527. };
  33528. /**
  33529. * Set the saturation matrix, increase the separation between colors
  33530. * Increase saturation : increase contrast, brightness, and sharpness
  33531. *
  33532. * @param {number} amount - The saturation amount (0-1)
  33533. * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false,
  33534. * just set the current matrix with @param matrix
  33535. */
  33536. ColorMatrixFilter.prototype.saturate = function saturate (amount, multiply)
  33537. {
  33538. if ( amount === void 0 ) { amount = 0; }
  33539. var x = (amount * 2 / 3) + 1;
  33540. var y = ((x - 1) * -0.5);
  33541. var matrix = [
  33542. x, y, y, 0, 0,
  33543. y, x, y, 0, 0,
  33544. y, y, x, 0, 0,
  33545. 0, 0, 0, 1, 0 ];
  33546. this._loadMatrix(matrix, multiply);
  33547. };
  33548. /**
  33549. * Desaturate image (remove color)
  33550. *
  33551. * Call the saturate function
  33552. *
  33553. */
  33554. ColorMatrixFilter.prototype.desaturate = function desaturate () // eslint-disable-line no-unused-vars
  33555. {
  33556. this.saturate(-1);
  33557. };
  33558. /**
  33559. * Negative image (inverse of classic rgb matrix)
  33560. *
  33561. * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false,
  33562. * just set the current matrix with @param matrix
  33563. */
  33564. ColorMatrixFilter.prototype.negative = function negative (multiply)
  33565. {
  33566. var matrix = [
  33567. -1, 0, 0, 1, 0,
  33568. 0, -1, 0, 1, 0,
  33569. 0, 0, -1, 1, 0,
  33570. 0, 0, 0, 1, 0 ];
  33571. this._loadMatrix(matrix, multiply);
  33572. };
  33573. /**
  33574. * Sepia image
  33575. *
  33576. * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false,
  33577. * just set the current matrix with @param matrix
  33578. */
  33579. ColorMatrixFilter.prototype.sepia = function sepia (multiply)
  33580. {
  33581. var matrix = [
  33582. 0.393, 0.7689999, 0.18899999, 0, 0,
  33583. 0.349, 0.6859999, 0.16799999, 0, 0,
  33584. 0.272, 0.5339999, 0.13099999, 0, 0,
  33585. 0, 0, 0, 1, 0 ];
  33586. this._loadMatrix(matrix, multiply);
  33587. };
  33588. /**
  33589. * Color motion picture process invented in 1916 (thanks Dominic Szablewski)
  33590. *
  33591. * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false,
  33592. * just set the current matrix with @param matrix
  33593. */
  33594. ColorMatrixFilter.prototype.technicolor = function technicolor (multiply)
  33595. {
  33596. var matrix = [
  33597. 1.9125277891456083, -0.8545344976951645, -0.09155508482755585, 0, 11.793603434377337,
  33598. -0.3087833385928097, 1.7658908555458428, -0.10601743074722245, 0, -70.35205161461398,
  33599. -0.231103377548616, -0.7501899197440212, 1.847597816108189, 0, 30.950940869491138,
  33600. 0, 0, 0, 1, 0 ];
  33601. this._loadMatrix(matrix, multiply);
  33602. };
  33603. /**
  33604. * Polaroid filter
  33605. *
  33606. * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false,
  33607. * just set the current matrix with @param matrix
  33608. */
  33609. ColorMatrixFilter.prototype.polaroid = function polaroid (multiply)
  33610. {
  33611. var matrix = [
  33612. 1.438, -0.062, -0.062, 0, 0,
  33613. -0.122, 1.378, -0.122, 0, 0,
  33614. -0.016, -0.016, 1.483, 0, 0,
  33615. 0, 0, 0, 1, 0 ];
  33616. this._loadMatrix(matrix, multiply);
  33617. };
  33618. /**
  33619. * Filter who transforms : Red -> Blue and Blue -> Red
  33620. *
  33621. * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false,
  33622. * just set the current matrix with @param matrix
  33623. */
  33624. ColorMatrixFilter.prototype.toBGR = function toBGR (multiply)
  33625. {
  33626. var matrix = [
  33627. 0, 0, 1, 0, 0,
  33628. 0, 1, 0, 0, 0,
  33629. 1, 0, 0, 0, 0,
  33630. 0, 0, 0, 1, 0 ];
  33631. this._loadMatrix(matrix, multiply);
  33632. };
  33633. /**
  33634. * Color reversal film introduced by Eastman Kodak in 1935. (thanks Dominic Szablewski)
  33635. *
  33636. * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false,
  33637. * just set the current matrix with @param matrix
  33638. */
  33639. ColorMatrixFilter.prototype.kodachrome = function kodachrome (multiply)
  33640. {
  33641. var matrix = [
  33642. 1.1285582396593525, -0.3967382283601348, -0.03992559172921793, 0, 63.72958762196502,
  33643. -0.16404339962244616, 1.0835251566291304, -0.05498805115633132, 0, 24.732407896706203,
  33644. -0.16786010706155763, -0.5603416277695248, 1.6014850761964943, 0, 35.62982807460946,
  33645. 0, 0, 0, 1, 0 ];
  33646. this._loadMatrix(matrix, multiply);
  33647. };
  33648. /**
  33649. * Brown delicious browni filter (thanks Dominic Szablewski)
  33650. *
  33651. * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false,
  33652. * just set the current matrix with @param matrix
  33653. */
  33654. ColorMatrixFilter.prototype.browni = function browni (multiply)
  33655. {
  33656. var matrix = [
  33657. 0.5997023498159715, 0.34553243048391263, -0.2708298674538042, 0, 47.43192855600873,
  33658. -0.037703249837783157, 0.8609577587992641, 0.15059552388459913, 0, -36.96841498319127,
  33659. 0.24113635128153335, -0.07441037908422492, 0.44972182064877153, 0, -7.562075277591283,
  33660. 0, 0, 0, 1, 0 ];
  33661. this._loadMatrix(matrix, multiply);
  33662. };
  33663. /**
  33664. * Vintage filter (thanks Dominic Szablewski)
  33665. *
  33666. * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false,
  33667. * just set the current matrix with @param matrix
  33668. */
  33669. ColorMatrixFilter.prototype.vintage = function vintage (multiply)
  33670. {
  33671. var matrix = [
  33672. 0.6279345635605994, 0.3202183420819367, -0.03965408211312453, 0, 9.651285835294123,
  33673. 0.02578397704808868, 0.6441188644374771, 0.03259127616149294, 0, 7.462829176470591,
  33674. 0.0466055556782719, -0.0851232987247891, 0.5241648018700465, 0, 5.159190588235296,
  33675. 0, 0, 0, 1, 0 ];
  33676. this._loadMatrix(matrix, multiply);
  33677. };
  33678. /**
  33679. * We don't know exactly what it does, kind of gradient map, but funny to play with!
  33680. *
  33681. * @param {number} desaturation - Tone values.
  33682. * @param {number} toned - Tone values.
  33683. * @param {string} lightColor - Tone values, example: `0xFFE580`
  33684. * @param {string} darkColor - Tone values, example: `0xFFE580`
  33685. * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false,
  33686. * just set the current matrix with @param matrix
  33687. */
  33688. ColorMatrixFilter.prototype.colorTone = function colorTone (desaturation, toned, lightColor, darkColor, multiply)
  33689. {
  33690. desaturation = desaturation || 0.2;
  33691. toned = toned || 0.15;
  33692. lightColor = lightColor || 0xFFE580;
  33693. darkColor = darkColor || 0x338000;
  33694. var lR = ((lightColor >> 16) & 0xFF) / 255;
  33695. var lG = ((lightColor >> 8) & 0xFF) / 255;
  33696. var lB = (lightColor & 0xFF) / 255;
  33697. var dR = ((darkColor >> 16) & 0xFF) / 255;
  33698. var dG = ((darkColor >> 8) & 0xFF) / 255;
  33699. var dB = (darkColor & 0xFF) / 255;
  33700. var matrix = [
  33701. 0.3, 0.59, 0.11, 0, 0,
  33702. lR, lG, lB, desaturation, 0,
  33703. dR, dG, dB, toned, 0,
  33704. lR - dR, lG - dG, lB - dB, 0, 0 ];
  33705. this._loadMatrix(matrix, multiply);
  33706. };
  33707. /**
  33708. * Night effect
  33709. *
  33710. * @param {number} intensity - The intensity of the night effect.
  33711. * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false,
  33712. * just set the current matrix with @param matrix
  33713. */
  33714. ColorMatrixFilter.prototype.night = function night (intensity, multiply)
  33715. {
  33716. intensity = intensity || 0.1;
  33717. var matrix = [
  33718. intensity * (-2.0), -intensity, 0, 0, 0,
  33719. -intensity, 0, intensity, 0, 0,
  33720. 0, intensity, intensity * 2.0, 0, 0,
  33721. 0, 0, 0, 1, 0 ];
  33722. this._loadMatrix(matrix, multiply);
  33723. };
  33724. /**
  33725. * Predator effect
  33726. *
  33727. * Erase the current matrix by setting a new indepent one
  33728. *
  33729. * @param {number} amount - how much the predator feels his future victim
  33730. * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false,
  33731. * just set the current matrix with @param matrix
  33732. */
  33733. ColorMatrixFilter.prototype.predator = function predator (amount, multiply)
  33734. {
  33735. var matrix = [
  33736. // row 1
  33737. 11.224130630493164 * amount,
  33738. -4.794486999511719 * amount,
  33739. -2.8746118545532227 * amount,
  33740. 0 * amount,
  33741. 0.40342438220977783 * amount,
  33742. // row 2
  33743. -3.6330697536468506 * amount,
  33744. 9.193157196044922 * amount,
  33745. -2.951810836791992 * amount,
  33746. 0 * amount,
  33747. -1.316135048866272 * amount,
  33748. // row 3
  33749. -3.2184197902679443 * amount,
  33750. -4.2375030517578125 * amount,
  33751. 7.476448059082031 * amount,
  33752. 0 * amount,
  33753. 0.8044459223747253 * amount,
  33754. // row 4
  33755. 0, 0, 0, 1, 0 ];
  33756. this._loadMatrix(matrix, multiply);
  33757. };
  33758. /**
  33759. * LSD effect
  33760. *
  33761. * Multiply the current matrix
  33762. *
  33763. * @param {boolean} multiply - if true, current matrix and matrix are multiplied. If false,
  33764. * just set the current matrix with @param matrix
  33765. */
  33766. ColorMatrixFilter.prototype.lsd = function lsd (multiply)
  33767. {
  33768. var matrix = [
  33769. 2, -0.4, 0.5, 0, 0,
  33770. -0.5, 2, -0.4, 0, 0,
  33771. -0.4, -0.5, 3, 0, 0,
  33772. 0, 0, 0, 1, 0 ];
  33773. this._loadMatrix(matrix, multiply);
  33774. };
  33775. /**
  33776. * Erase the current matrix by setting the default one
  33777. *
  33778. */
  33779. ColorMatrixFilter.prototype.reset = function reset ()
  33780. {
  33781. var matrix = [
  33782. 1, 0, 0, 0, 0,
  33783. 0, 1, 0, 0, 0,
  33784. 0, 0, 1, 0, 0,
  33785. 0, 0, 0, 1, 0 ];
  33786. this._loadMatrix(matrix, false);
  33787. };
  33788. /**
  33789. * The matrix of the color matrix filter
  33790. *
  33791. * @member {number[]}
  33792. * @default [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0]
  33793. */
  33794. prototypeAccessors.matrix.get = function ()
  33795. {
  33796. return this.uniforms.m;
  33797. };
  33798. prototypeAccessors.matrix.set = function (value) // eslint-disable-line require-jsdoc
  33799. {
  33800. this.uniforms.m = value;
  33801. };
  33802. /**
  33803. * The opacity value to use when mixing the original and resultant colors.
  33804. *
  33805. * When the value is 0, the original color is used without modification.
  33806. * When the value is 1, the result color is used.
  33807. * When in the range (0, 1) the color is interpolated between the original and result by this amount.
  33808. *
  33809. * @member {number}
  33810. * @default 1
  33811. */
  33812. prototypeAccessors.alpha.get = function ()
  33813. {
  33814. return this.uniforms.uAlpha;
  33815. };
  33816. prototypeAccessors.alpha.set = function (value) // eslint-disable-line require-jsdoc
  33817. {
  33818. this.uniforms.uAlpha = value;
  33819. };
  33820. Object.defineProperties( ColorMatrixFilter.prototype, prototypeAccessors );
  33821. return ColorMatrixFilter;
  33822. }(Filter));
  33823. // Americanized alias
  33824. ColorMatrixFilter.prototype.grayscale = ColorMatrixFilter.prototype.greyscale;
  33825. /*!
  33826. * @pixi/filter-displacement - v5.0.4
  33827. * Compiled Fri, 07 Jun 2019 17:17:49 UTC
  33828. *
  33829. * @pixi/filter-displacement is licensed under the MIT License.
  33830. * http://www.opensource.org/licenses/mit-license
  33831. */
  33832. var vertex$4 = "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";
  33833. var fragment$5 = "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";
  33834. /**
  33835. * The DisplacementFilter class uses the pixel values from the specified texture
  33836. * (called the displacement map) to perform a displacement of an object.
  33837. *
  33838. * You can use this filter to apply all manor of crazy warping effects.
  33839. * Currently the `r` property of the texture is used to offset the `x`
  33840. * and the `g` property of the texture is used to offset the `y`.
  33841. *
  33842. * The way it works is it uses the values of the displacement map to look up the
  33843. * correct pixels to output. This means it's not technically moving the original.
  33844. * Instead, it's starting at the output and asking "which pixel from the original goes here".
  33845. * For example, if a displacement map pixel has `red = 1` and the filter scale is `20`,
  33846. * this filter will output the pixel approximately 20 pixels to the right of the original.
  33847. *
  33848. * @class
  33849. * @extends PIXI.Filter
  33850. * @memberof PIXI.filters
  33851. */
  33852. var DisplacementFilter = /*@__PURE__*/(function (Filter) {
  33853. function DisplacementFilter(sprite, scale)
  33854. {
  33855. var maskMatrix = new Matrix();
  33856. sprite.renderable = false;
  33857. Filter.call(this, vertex$4, fragment$5, {
  33858. mapSampler: sprite._texture,
  33859. filterMatrix: maskMatrix,
  33860. scale: { x: 1, y: 1 },
  33861. rotation: new Float32Array([1, 0, 0, 1]),
  33862. });
  33863. this.maskSprite = sprite;
  33864. this.maskMatrix = maskMatrix;
  33865. if (scale === null || scale === undefined)
  33866. {
  33867. scale = 20;
  33868. }
  33869. /**
  33870. * scaleX, scaleY for displacements
  33871. * @member {PIXI.Point}
  33872. */
  33873. this.scale = new Point(scale, scale);
  33874. }
  33875. if ( Filter ) { DisplacementFilter.__proto__ = Filter; }
  33876. DisplacementFilter.prototype = Object.create( Filter && Filter.prototype );
  33877. DisplacementFilter.prototype.constructor = DisplacementFilter;
  33878. var prototypeAccessors = { map: { configurable: true } };
  33879. /**
  33880. * Applies the filter.
  33881. *
  33882. * @param {PIXI.systems.FilterSystem} filterManager - The manager.
  33883. * @param {PIXI.RenderTexture} input - The input target.
  33884. * @param {PIXI.RenderTexture} output - The output target.
  33885. * @param {boolean} clear - Should the output be cleared before rendering to it.
  33886. */
  33887. DisplacementFilter.prototype.apply = function apply (filterManager, input, output, clear)
  33888. {
  33889. // fill maskMatrix with _normalized sprite texture coords_
  33890. this.uniforms.filterMatrix = filterManager.calculateSpriteMatrix(this.maskMatrix, this.maskSprite);
  33891. this.uniforms.scale.x = this.scale.x;
  33892. this.uniforms.scale.y = this.scale.y;
  33893. // Extract rotation from world transform
  33894. var wt = this.maskSprite.transform.worldTransform;
  33895. var lenX = Math.sqrt((wt.a * wt.a) + (wt.b * wt.b));
  33896. var lenY = Math.sqrt((wt.c * wt.c) + (wt.d * wt.d));
  33897. if (lenX !== 0 && lenY !== 0)
  33898. {
  33899. this.uniforms.rotation[0] = wt.a / lenX;
  33900. this.uniforms.rotation[1] = wt.b / lenX;
  33901. this.uniforms.rotation[2] = wt.c / lenY;
  33902. this.uniforms.rotation[3] = wt.d / lenY;
  33903. }
  33904. // draw the filter...
  33905. filterManager.applyFilter(this, input, output, clear);
  33906. };
  33907. /**
  33908. * The texture used for the displacement map. Must be power of 2 sized texture.
  33909. *
  33910. * @member {PIXI.Texture}
  33911. */
  33912. prototypeAccessors.map.get = function ()
  33913. {
  33914. return this.uniforms.mapSampler;
  33915. };
  33916. prototypeAccessors.map.set = function (value) // eslint-disable-line require-jsdoc
  33917. {
  33918. this.uniforms.mapSampler = value;
  33919. };
  33920. Object.defineProperties( DisplacementFilter.prototype, prototypeAccessors );
  33921. return DisplacementFilter;
  33922. }(Filter));
  33923. /*!
  33924. * @pixi/filter-fxaa - v5.0.4
  33925. * Compiled Fri, 07 Jun 2019 17:17:49 UTC
  33926. *
  33927. * @pixi/filter-fxaa is licensed under the MIT License.
  33928. * http://www.opensource.org/licenses/mit-license
  33929. */
  33930. var vertex$5 = "\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 inputPixel;\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, inputPixel.zw, v_rgbNW, v_rgbNE, v_rgbSW, v_rgbSE, v_rgbM);\n}\n";
  33931. var fragment$6 = "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 inputPixel;\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, inputPixel.zw, v_rgbNW, v_rgbNE, v_rgbSW, v_rgbSE, v_rgbM);\n\n gl_FragColor = color;\n}\n";
  33932. /**
  33933. * Basic FXAA (Fast Approximate Anti-Aliasing) implementation based on the code on geeks3d.com
  33934. * with the modification that the texture2DLod stuff was removed since it is unsupported by WebGL.
  33935. *
  33936. * @see https://github.com/mitsuhiko/webgl-meincraft
  33937. *
  33938. * @class
  33939. * @extends PIXI.Filter
  33940. * @memberof PIXI.filters
  33941. *
  33942. */
  33943. var FXAAFilter = /*@__PURE__*/(function (Filter) {
  33944. function FXAAFilter()
  33945. {
  33946. // TODO - needs work
  33947. Filter.call(this, vertex$5, fragment$6);
  33948. }
  33949. if ( Filter ) { FXAAFilter.__proto__ = Filter; }
  33950. FXAAFilter.prototype = Object.create( Filter && Filter.prototype );
  33951. FXAAFilter.prototype.constructor = FXAAFilter;
  33952. return FXAAFilter;
  33953. }(Filter));
  33954. /*!
  33955. * @pixi/filter-noise - v5.0.4
  33956. * Compiled Fri, 07 Jun 2019 17:17:49 UTC
  33957. *
  33958. * @pixi/filter-noise is licensed under the MIT License.
  33959. * http://www.opensource.org/licenses/mit-license
  33960. */
  33961. var fragment$7 = "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";
  33962. /**
  33963. * @author Vico @vicocotea
  33964. * original filter: https://github.com/evanw/glfx.js/blob/master/src/filters/adjust/noise.js
  33965. */
  33966. /**
  33967. * A Noise effect filter.
  33968. *
  33969. * @class
  33970. * @extends PIXI.Filter
  33971. * @memberof PIXI.filters
  33972. */
  33973. var NoiseFilter = /*@__PURE__*/(function (Filter) {
  33974. function NoiseFilter(noise, seed)
  33975. {
  33976. if ( noise === void 0 ) { noise = 0.5; }
  33977. if ( seed === void 0 ) { seed = Math.random(); }
  33978. Filter.call(this, defaultFilter, fragment$7, {
  33979. uNoise: 0,
  33980. uSeed: 0,
  33981. });
  33982. this.noise = noise;
  33983. this.seed = seed;
  33984. }
  33985. if ( Filter ) { NoiseFilter.__proto__ = Filter; }
  33986. NoiseFilter.prototype = Object.create( Filter && Filter.prototype );
  33987. NoiseFilter.prototype.constructor = NoiseFilter;
  33988. var prototypeAccessors = { noise: { configurable: true },seed: { configurable: true } };
  33989. /**
  33990. * The amount of noise to apply, this value should be in the range (0, 1].
  33991. *
  33992. * @member {number}
  33993. * @default 0.5
  33994. */
  33995. prototypeAccessors.noise.get = function ()
  33996. {
  33997. return this.uniforms.uNoise;
  33998. };
  33999. prototypeAccessors.noise.set = function (value) // eslint-disable-line require-jsdoc
  34000. {
  34001. this.uniforms.uNoise = value;
  34002. };
  34003. /**
  34004. * A seed value to apply to the random noise generation. `Math.random()` is a good value to use.
  34005. *
  34006. * @member {number}
  34007. */
  34008. prototypeAccessors.seed.get = function ()
  34009. {
  34010. return this.uniforms.uSeed;
  34011. };
  34012. prototypeAccessors.seed.set = function (value) // eslint-disable-line require-jsdoc
  34013. {
  34014. this.uniforms.uSeed = value;
  34015. };
  34016. Object.defineProperties( NoiseFilter.prototype, prototypeAccessors );
  34017. return NoiseFilter;
  34018. }(Filter));
  34019. /*!
  34020. * @pixi/mixin-cache-as-bitmap - v5.0.4
  34021. * Compiled Fri, 07 Jun 2019 17:17:49 UTC
  34022. *
  34023. * @pixi/mixin-cache-as-bitmap is licensed under the MIT License.
  34024. * http://www.opensource.org/licenses/mit-license
  34025. */
  34026. var _tempMatrix = new Matrix();
  34027. DisplayObject.prototype._cacheAsBitmap = false;
  34028. DisplayObject.prototype._cacheData = false;
  34029. // figured theres no point adding ALL the extra variables to prototype.
  34030. // this model can hold the information needed. This can also be generated on demand as
  34031. // most objects are not cached as bitmaps.
  34032. /**
  34033. * @class
  34034. * @ignore
  34035. */
  34036. var CacheData = function CacheData()
  34037. {
  34038. this.textureCacheId = null;
  34039. this.originalRender = null;
  34040. this.originalRenderCanvas = null;
  34041. this.originalCalculateBounds = null;
  34042. this.originalGetLocalBounds = null;
  34043. this.originalUpdateTransform = null;
  34044. this.originalHitTest = null;
  34045. this.originalDestroy = null;
  34046. this.originalMask = null;
  34047. this.originalFilterArea = null;
  34048. this.sprite = null;
  34049. };
  34050. Object.defineProperties(DisplayObject.prototype, {
  34051. /**
  34052. * Set this to true if you want this display object to be cached as a bitmap.
  34053. * This basically takes a snap shot of the display object as it is at that moment. It can
  34054. * provide a performance benefit for complex static displayObjects.
  34055. * To remove simply set this property to `false`
  34056. *
  34057. * IMPORTANT GOTCHA - Make sure that all your textures are preloaded BEFORE setting this property to true
  34058. * as it will take a snapshot of what is currently there. If the textures have not loaded then they will not appear.
  34059. *
  34060. * @member {boolean}
  34061. * @memberof PIXI.DisplayObject#
  34062. */
  34063. cacheAsBitmap: {
  34064. get: function get()
  34065. {
  34066. return this._cacheAsBitmap;
  34067. },
  34068. set: function set(value)
  34069. {
  34070. if (this._cacheAsBitmap === value)
  34071. {
  34072. return;
  34073. }
  34074. this._cacheAsBitmap = value;
  34075. var data;
  34076. if (value)
  34077. {
  34078. if (!this._cacheData)
  34079. {
  34080. this._cacheData = new CacheData();
  34081. }
  34082. data = this._cacheData;
  34083. data.originalRender = this.render;
  34084. data.originalRenderCanvas = this.renderCanvas;
  34085. data.originalUpdateTransform = this.updateTransform;
  34086. data.originalCalculateBounds = this.calculateBounds;
  34087. data.originalGetLocalBounds = this.getLocalBounds;
  34088. data.originalDestroy = this.destroy;
  34089. data.originalContainsPoint = this.containsPoint;
  34090. data.originalMask = this._mask;
  34091. data.originalFilterArea = this.filterArea;
  34092. this.render = this._renderCached;
  34093. this.renderCanvas = this._renderCachedCanvas;
  34094. this.destroy = this._cacheAsBitmapDestroy;
  34095. }
  34096. else
  34097. {
  34098. data = this._cacheData;
  34099. if (data.sprite)
  34100. {
  34101. this._destroyCachedDisplayObject();
  34102. }
  34103. this.render = data.originalRender;
  34104. this.renderCanvas = data.originalRenderCanvas;
  34105. this.calculateBounds = data.originalCalculateBounds;
  34106. this.getLocalBounds = data.originalGetLocalBounds;
  34107. this.destroy = data.originalDestroy;
  34108. this.updateTransform = data.originalUpdateTransform;
  34109. this.containsPoint = data.originalContainsPoint;
  34110. this._mask = data.originalMask;
  34111. this.filterArea = data.originalFilterArea;
  34112. }
  34113. },
  34114. },
  34115. });
  34116. /**
  34117. * Renders a cached version of the sprite with WebGL
  34118. *
  34119. * @private
  34120. * @function _renderCached
  34121. * @memberof PIXI.DisplayObject#
  34122. * @param {PIXI.Renderer} renderer - the WebGL renderer
  34123. */
  34124. DisplayObject.prototype._renderCached = function _renderCached(renderer)
  34125. {
  34126. if (!this.visible || this.worldAlpha <= 0 || !this.renderable)
  34127. {
  34128. return;
  34129. }
  34130. this._initCachedDisplayObject(renderer);
  34131. this._cacheData.sprite.transform._worldID = this.transform._worldID;
  34132. this._cacheData.sprite.worldAlpha = this.worldAlpha;
  34133. this._cacheData.sprite._render(renderer);
  34134. };
  34135. /**
  34136. * Prepares the WebGL renderer to cache the sprite
  34137. *
  34138. * @private
  34139. * @function _initCachedDisplayObject
  34140. * @memberof PIXI.DisplayObject#
  34141. * @param {PIXI.Renderer} renderer - the WebGL renderer
  34142. */
  34143. DisplayObject.prototype._initCachedDisplayObject = function _initCachedDisplayObject(renderer)
  34144. {
  34145. if (this._cacheData && this._cacheData.sprite)
  34146. {
  34147. return;
  34148. }
  34149. // make sure alpha is set to 1 otherwise it will get rendered as invisible!
  34150. var cacheAlpha = this.alpha;
  34151. this.alpha = 1;
  34152. // first we flush anything left in the renderer (otherwise it would get rendered to the cached texture)
  34153. renderer.batch.flush();
  34154. // this.filters= [];
  34155. // next we find the dimensions of the untransformed object
  34156. // this function also calls updatetransform on all its children as part of the measuring.
  34157. // This means we don't need to update the transform again in this function
  34158. // TODO pass an object to clone too? saves having to create a new one each time!
  34159. var bounds = this.getLocalBounds().clone();
  34160. // add some padding!
  34161. if (this.filters)
  34162. {
  34163. var padding = this.filters[0].padding;
  34164. bounds.pad(padding);
  34165. }
  34166. bounds.ceil(settings.RESOLUTION);
  34167. // for now we cache the current renderTarget that the WebGL renderer is currently using.
  34168. // this could be more elegant..
  34169. var cachedRenderTarget = renderer._activeRenderTarget;
  34170. // We also store the filter stack - I will definitely look to change how this works a little later down the line.
  34171. // const stack = renderer.filterManager.filterStack;
  34172. // this renderTexture will be used to store the cached DisplayObject
  34173. var renderTexture = RenderTexture.create(bounds.width, bounds.height);
  34174. var textureCacheId = "cacheAsBitmap_" + (uid());
  34175. this._cacheData.textureCacheId = textureCacheId;
  34176. BaseTexture.addToCache(renderTexture.baseTexture, textureCacheId);
  34177. Texture.addToCache(renderTexture, textureCacheId);
  34178. // need to set //
  34179. var m = _tempMatrix;
  34180. m.tx = -bounds.x;
  34181. m.ty = -bounds.y;
  34182. // reset
  34183. this.transform.worldTransform.identity();
  34184. // set all properties to there original so we can render to a texture
  34185. this.render = this._cacheData.originalRender;
  34186. renderer.render(this, renderTexture, true, m, true);
  34187. // now restore the state be setting the new properties
  34188. renderer.renderTexture.bind(cachedRenderTarget);
  34189. // renderer.filterManager.filterStack = stack;
  34190. this.render = this._renderCached;
  34191. // the rest is the same as for Canvas
  34192. this.updateTransform = this.displayObjectUpdateTransform;
  34193. this.calculateBounds = this._calculateCachedBounds;
  34194. this.getLocalBounds = this._getCachedLocalBounds;
  34195. this._mask = null;
  34196. this.filterArea = null;
  34197. // create our cached sprite
  34198. var cachedSprite = new Sprite(renderTexture);
  34199. cachedSprite.transform.worldTransform = this.transform.worldTransform;
  34200. cachedSprite.anchor.x = -(bounds.x / bounds.width);
  34201. cachedSprite.anchor.y = -(bounds.y / bounds.height);
  34202. cachedSprite.alpha = cacheAlpha;
  34203. cachedSprite._bounds = this._bounds;
  34204. this._cacheData.sprite = cachedSprite;
  34205. this.transform._parentID = -1;
  34206. // restore the transform of the cached sprite to avoid the nasty flicker..
  34207. if (!this.parent)
  34208. {
  34209. this.parent = renderer._tempDisplayObjectParent;
  34210. this.updateTransform();
  34211. this.parent = null;
  34212. }
  34213. else
  34214. {
  34215. this.updateTransform();
  34216. }
  34217. // map the hit test..
  34218. this.containsPoint = cachedSprite.containsPoint.bind(cachedSprite);
  34219. };
  34220. /**
  34221. * Renders a cached version of the sprite with canvas
  34222. *
  34223. * @private
  34224. * @function _renderCachedCanvas
  34225. * @memberof PIXI.DisplayObject#
  34226. * @param {PIXI.Renderer} renderer - the WebGL renderer
  34227. */
  34228. DisplayObject.prototype._renderCachedCanvas = function _renderCachedCanvas(renderer)
  34229. {
  34230. if (!this.visible || this.worldAlpha <= 0 || !this.renderable)
  34231. {
  34232. return;
  34233. }
  34234. this._initCachedDisplayObjectCanvas(renderer);
  34235. this._cacheData.sprite.worldAlpha = this.worldAlpha;
  34236. this._cacheData.sprite._renderCanvas(renderer);
  34237. };
  34238. // TODO this can be the same as the WebGL version.. will need to do a little tweaking first though..
  34239. /**
  34240. * Prepares the Canvas renderer to cache the sprite
  34241. *
  34242. * @private
  34243. * @function _initCachedDisplayObjectCanvas
  34244. * @memberof PIXI.DisplayObject#
  34245. * @param {PIXI.Renderer} renderer - the WebGL renderer
  34246. */
  34247. DisplayObject.prototype._initCachedDisplayObjectCanvas = function _initCachedDisplayObjectCanvas(renderer)
  34248. {
  34249. if (this._cacheData && this._cacheData.sprite)
  34250. {
  34251. return;
  34252. }
  34253. // get bounds actually transforms the object for us already!
  34254. var bounds = this.getLocalBounds();
  34255. var cacheAlpha = this.alpha;
  34256. this.alpha = 1;
  34257. var cachedRenderTarget = renderer.context;
  34258. bounds.ceil(settings.RESOLUTION);
  34259. var renderTexture = RenderTexture.create(bounds.width, bounds.height);
  34260. var textureCacheId = "cacheAsBitmap_" + (uid());
  34261. this._cacheData.textureCacheId = textureCacheId;
  34262. BaseTexture.addToCache(renderTexture.baseTexture, textureCacheId);
  34263. Texture.addToCache(renderTexture, textureCacheId);
  34264. // need to set //
  34265. var m = _tempMatrix;
  34266. this.transform.localTransform.copyTo(m);
  34267. m.invert();
  34268. m.tx -= bounds.x;
  34269. m.ty -= bounds.y;
  34270. // m.append(this.transform.worldTransform.)
  34271. // set all properties to there original so we can render to a texture
  34272. this.renderCanvas = this._cacheData.originalRenderCanvas;
  34273. // renderTexture.render(this, m, true);
  34274. renderer.render(this, renderTexture, true, m, false);
  34275. // now restore the state be setting the new properties
  34276. renderer.context = cachedRenderTarget;
  34277. this.renderCanvas = this._renderCachedCanvas;
  34278. // the rest is the same as for WebGL
  34279. this.updateTransform = this.displayObjectUpdateTransform;
  34280. this.calculateBounds = this._calculateCachedBounds;
  34281. this.getLocalBounds = this._getCachedLocalBounds;
  34282. this._mask = null;
  34283. this.filterArea = null;
  34284. // create our cached sprite
  34285. var cachedSprite = new Sprite(renderTexture);
  34286. cachedSprite.transform.worldTransform = this.transform.worldTransform;
  34287. cachedSprite.anchor.x = -(bounds.x / bounds.width);
  34288. cachedSprite.anchor.y = -(bounds.y / bounds.height);
  34289. cachedSprite.alpha = cacheAlpha;
  34290. cachedSprite._bounds = this._bounds;
  34291. this._cacheData.sprite = cachedSprite;
  34292. this.transform._parentID = -1;
  34293. // restore the transform of the cached sprite to avoid the nasty flicker..
  34294. if (!this.parent)
  34295. {
  34296. this.parent = renderer._tempDisplayObjectParent;
  34297. this.updateTransform();
  34298. this.parent = null;
  34299. }
  34300. else
  34301. {
  34302. this.updateTransform();
  34303. }
  34304. // map the hit test..
  34305. this.containsPoint = cachedSprite.containsPoint.bind(cachedSprite);
  34306. };
  34307. /**
  34308. * Calculates the bounds of the cached sprite
  34309. *
  34310. * @private
  34311. */
  34312. DisplayObject.prototype._calculateCachedBounds = function _calculateCachedBounds()
  34313. {
  34314. this._bounds.clear();
  34315. this._cacheData.sprite.transform._worldID = this.transform._worldID;
  34316. this._cacheData.sprite._calculateBounds();
  34317. this._lastBoundsID = this._boundsID;
  34318. };
  34319. /**
  34320. * Gets the bounds of the cached sprite.
  34321. *
  34322. * @private
  34323. * @return {Rectangle} The local bounds.
  34324. */
  34325. DisplayObject.prototype._getCachedLocalBounds = function _getCachedLocalBounds()
  34326. {
  34327. return this._cacheData.sprite.getLocalBounds();
  34328. };
  34329. /**
  34330. * Destroys the cached sprite.
  34331. *
  34332. * @private
  34333. */
  34334. DisplayObject.prototype._destroyCachedDisplayObject = function _destroyCachedDisplayObject()
  34335. {
  34336. this._cacheData.sprite._texture.destroy(true);
  34337. this._cacheData.sprite = null;
  34338. BaseTexture.removeFromCache(this._cacheData.textureCacheId);
  34339. Texture.removeFromCache(this._cacheData.textureCacheId);
  34340. this._cacheData.textureCacheId = null;
  34341. };
  34342. /**
  34343. * Destroys the cached object.
  34344. *
  34345. * @private
  34346. * @param {object|boolean} [options] - Options parameter. A boolean will act as if all options
  34347. * have been set to that value.
  34348. * Used when destroying containers, see the Container.destroy method.
  34349. */
  34350. DisplayObject.prototype._cacheAsBitmapDestroy = function _cacheAsBitmapDestroy(options)
  34351. {
  34352. this.cacheAsBitmap = false;
  34353. this.destroy(options);
  34354. };
  34355. /*!
  34356. * @pixi/mixin-get-child-by-name - v5.0.4
  34357. * Compiled Fri, 07 Jun 2019 17:17:49 UTC
  34358. *
  34359. * @pixi/mixin-get-child-by-name is licensed under the MIT License.
  34360. * http://www.opensource.org/licenses/mit-license
  34361. */
  34362. /**
  34363. * The instance name of the object.
  34364. *
  34365. * @memberof PIXI.DisplayObject#
  34366. * @member {string} name
  34367. */
  34368. DisplayObject.prototype.name = null;
  34369. /**
  34370. * Returns the display object in the container.
  34371. *
  34372. * @method getChildByName
  34373. * @memberof PIXI.Container#
  34374. * @param {string} name - Instance name.
  34375. * @return {PIXI.DisplayObject} The child with the specified name.
  34376. */
  34377. Container.prototype.getChildByName = function getChildByName(name)
  34378. {
  34379. for (var i = 0; i < this.children.length; i++)
  34380. {
  34381. if (this.children[i].name === name)
  34382. {
  34383. return this.children[i];
  34384. }
  34385. }
  34386. return null;
  34387. };
  34388. /*!
  34389. * @pixi/mixin-get-global-position - v5.0.4
  34390. * Compiled Fri, 07 Jun 2019 17:17:49 UTC
  34391. *
  34392. * @pixi/mixin-get-global-position is licensed under the MIT License.
  34393. * http://www.opensource.org/licenses/mit-license
  34394. */
  34395. /**
  34396. * Returns the global position of the displayObject. Does not depend on object scale, rotation and pivot.
  34397. *
  34398. * @method getGlobalPosition
  34399. * @memberof PIXI.DisplayObject#
  34400. * @param {PIXI.Point} [point=new PIXI.Point()] - The point to write the global value to.
  34401. * @param {boolean} [skipUpdate=false] - Setting to true will stop the transforms of the scene graph from
  34402. * being updated. This means the calculation returned MAY be out of date BUT will give you a
  34403. * nice performance boost.
  34404. * @return {PIXI.Point} The updated point.
  34405. */
  34406. DisplayObject.prototype.getGlobalPosition = function getGlobalPosition(point, skipUpdate)
  34407. {
  34408. if ( point === void 0 ) { point = new Point(); }
  34409. if ( skipUpdate === void 0 ) { skipUpdate = false; }
  34410. if (this.parent)
  34411. {
  34412. this.parent.toGlobal(this.position, point, skipUpdate);
  34413. }
  34414. else
  34415. {
  34416. point.x = this.position.x;
  34417. point.y = this.position.y;
  34418. }
  34419. return point;
  34420. };
  34421. var v5 = '5.0.0';
  34422. /**
  34423. * Deprecations (backward compatibilities) are automatically applied for browser bundles
  34424. * in the UMD module format. If using Webpack or Rollup, you'll need to apply these
  34425. * deprecations manually by doing something like this:
  34426. * @example
  34427. * import * as PIXI from 'pixi.js';
  34428. * PIXI.useDeprecated(); // MUST be bound to namespace
  34429. * @memberof PIXI
  34430. * @function useDeprecated
  34431. */
  34432. function useDeprecated()
  34433. {
  34434. var PIXI = this;
  34435. Object.defineProperties(PIXI, {
  34436. /**
  34437. * @constant {RegExp|string} SVG_SIZE
  34438. * @memberof PIXI
  34439. * @see PIXI.resources.SVGResource.SVG_SIZE
  34440. * @deprecated since 5.0.0
  34441. */
  34442. SVG_SIZE: {
  34443. get: function get()
  34444. {
  34445. deprecation(v5, 'PIXI.utils.SVG_SIZE property has moved to PIXI.resources.SVGResource.SVG_SIZE');
  34446. return PIXI.SVGResource.SVG_SIZE;
  34447. },
  34448. },
  34449. /**
  34450. * @class PIXI.TransformStatic
  34451. * @deprecated since 5.0.0
  34452. * @see PIXI.Transform
  34453. */
  34454. TransformStatic: {
  34455. get: function get()
  34456. {
  34457. deprecation(v5, 'PIXI.TransformStatic class has been removed, use PIXI.Transform');
  34458. return PIXI.Transform;
  34459. },
  34460. },
  34461. /**
  34462. * @class PIXI.TransformBase
  34463. * @deprecated since 5.0.0
  34464. * @see PIXI.Transform
  34465. */
  34466. TransformBase: {
  34467. get: function get()
  34468. {
  34469. deprecation(v5, 'PIXI.TransformBase class has been removed, use PIXI.Transform');
  34470. return PIXI.Transform;
  34471. },
  34472. },
  34473. /**
  34474. * Constants that specify the transform type.
  34475. *
  34476. * @static
  34477. * @constant
  34478. * @name TRANSFORM_MODE
  34479. * @memberof PIXI
  34480. * @enum {number}
  34481. * @deprecated since 5.0.0
  34482. * @property {number} STATIC
  34483. * @property {number} DYNAMIC
  34484. */
  34485. TRANSFORM_MODE: {
  34486. get: function get()
  34487. {
  34488. deprecation(v5, 'PIXI.TRANSFORM_MODE property has been removed');
  34489. return { STATIC: 0, DYNAMIC: 1 };
  34490. },
  34491. },
  34492. /**
  34493. * @class PIXI.WebGLRenderer
  34494. * @see PIXI.Renderer
  34495. * @deprecated since 5.0.0
  34496. */
  34497. WebGLRenderer: {
  34498. get: function get()
  34499. {
  34500. deprecation(v5, 'PIXI.WebGLRenderer class has moved to PIXI.Renderer');
  34501. return PIXI.Renderer;
  34502. },
  34503. },
  34504. /**
  34505. * @class PIXI.CanvasRenderTarget
  34506. * @see PIXI.utils.CanvasRenderTarget
  34507. * @deprecated since 5.0.0
  34508. */
  34509. CanvasRenderTarget: {
  34510. get: function get()
  34511. {
  34512. deprecation(v5, 'PIXI.CanvasRenderTarget class has moved to PIXI.utils.CanvasRenderTarget');
  34513. return PIXI.utils.CanvasRenderTarget;
  34514. },
  34515. },
  34516. /**
  34517. * @memberof PIXI
  34518. * @name loader
  34519. * @type {PIXI.Loader}
  34520. * @see PIXI.Loader.shared
  34521. * @deprecated since 5.0.0
  34522. */
  34523. loader: {
  34524. get: function get()
  34525. {
  34526. deprecation(v5, 'PIXI.loader instance has moved to PIXI.Loader.shared');
  34527. return PIXI.Loader.shared;
  34528. },
  34529. },
  34530. /**
  34531. * @class PIXI.FilterManager
  34532. * @see PIXI.systems.FilterSystem
  34533. * @deprecated since 5.0.0
  34534. */
  34535. FilterManager: {
  34536. get: function get()
  34537. {
  34538. deprecation(v5, 'PIXI.FilterManager class has moved to PIXI.systems.FilterSystem');
  34539. return PIXI.systems.FilterSystem;
  34540. },
  34541. },
  34542. });
  34543. /**
  34544. * This namespace has been removed. All classes previous nested
  34545. * under this namespace have been moved to the top-level `PIXI` object.
  34546. * @namespace PIXI.extras
  34547. * @deprecated since 5.0.0
  34548. */
  34549. PIXI.extras = {};
  34550. Object.defineProperties(PIXI.extras, {
  34551. /**
  34552. * @class PIXI.extras.TilingSprite
  34553. * @see PIXI.TilingSprite
  34554. * @deprecated since 5.0.0
  34555. */
  34556. TilingSprite: {
  34557. get: function get()
  34558. {
  34559. deprecation(v5, 'PIXI.extras.TilingSprite class has moved to PIXI.TilingSprite');
  34560. return PIXI.TilingSprite;
  34561. },
  34562. },
  34563. /**
  34564. * @class PIXI.extras.TilingSpriteRenderer
  34565. * @see PIXI.TilingSpriteRenderer
  34566. * @deprecated since 5.0.0
  34567. */
  34568. TilingSpriteRenderer: {
  34569. get: function get()
  34570. {
  34571. deprecation(v5, 'PIXI.extras.TilingSpriteRenderer class has moved to PIXI.TilingSpriteRenderer');
  34572. return PIXI.TilingSpriteRenderer;
  34573. },
  34574. },
  34575. /**
  34576. * @class PIXI.extras.AnimatedSprite
  34577. * @see PIXI.AnimatedSprite
  34578. * @deprecated since 5.0.0
  34579. */
  34580. AnimatedSprite: {
  34581. get: function get()
  34582. {
  34583. deprecation(v5, 'PIXI.extras.AnimatedSprite class has moved to PIXI.AnimatedSprite');
  34584. return PIXI.AnimatedSprite;
  34585. },
  34586. },
  34587. /**
  34588. * @class PIXI.extras.BitmapText
  34589. * @see PIXI.BitmapText
  34590. * @deprecated since 5.0.0
  34591. */
  34592. BitmapText: {
  34593. get: function get()
  34594. {
  34595. deprecation(v5, 'PIXI.extras.BitmapText class has moved to PIXI.BitmapText');
  34596. return PIXI.BitmapText;
  34597. },
  34598. },
  34599. });
  34600. Object.defineProperties(PIXI.utils, {
  34601. /**
  34602. * @function PIXI.utils.getSvgSize
  34603. * @see PIXI.resources.SVGResource.getSize
  34604. * @deprecated since 5.0.0
  34605. */
  34606. getSvgSize: {
  34607. get: function get()
  34608. {
  34609. deprecation(v5, 'PIXI.utils.getSvgSize function has moved to PIXI.resources.SVGResource.getSize');
  34610. return PIXI.SVGResource.getSize;
  34611. },
  34612. },
  34613. });
  34614. /**
  34615. * All classes on this namespace have moved to the high-level `PIXI` object.
  34616. * @namespace PIXI.mesh
  34617. * @deprecated since 5.0.0
  34618. */
  34619. PIXI.mesh = {};
  34620. Object.defineProperties(PIXI.mesh, {
  34621. /**
  34622. * @class PIXI.mesh.Mesh
  34623. * @see PIXI.SimpleMesh
  34624. * @deprecated since 5.0.0
  34625. */
  34626. Mesh: {
  34627. get: function get()
  34628. {
  34629. deprecation(v5, 'PIXI.mesh.Mesh class has moved to PIXI.SimpleMesh');
  34630. return PIXI.SimpleMesh;
  34631. },
  34632. },
  34633. /**
  34634. * @class PIXI.mesh.NineSlicePlane
  34635. * @see PIXI.NineSlicePlane
  34636. * @deprecated since 5.0.0
  34637. */
  34638. NineSlicePlane: {
  34639. get: function get()
  34640. {
  34641. deprecation(v5, 'PIXI.mesh.NineSlicePlane class has moved to PIXI.NineSlicePlane');
  34642. return PIXI.NineSlicePlane;
  34643. },
  34644. },
  34645. /**
  34646. * @class PIXI.mesh.Plane
  34647. * @see PIXI.SimplePlane
  34648. * @deprecated since 5.0.0
  34649. */
  34650. Plane: {
  34651. get: function get()
  34652. {
  34653. deprecation(v5, 'PIXI.mesh.Plane class has moved to PIXI.SimplePlane');
  34654. return PIXI.SimplePlane;
  34655. },
  34656. },
  34657. /**
  34658. * @class PIXI.mesh.Rope
  34659. * @see PIXI.SimpleRope
  34660. * @deprecated since 5.0.0
  34661. */
  34662. Rope: {
  34663. get: function get()
  34664. {
  34665. deprecation(v5, 'PIXI.mesh.Rope class has moved to PIXI.SimpleRope');
  34666. return PIXI.SimpleRope;
  34667. },
  34668. },
  34669. /**
  34670. * @class PIXI.mesh.RawMesh
  34671. * @see PIXI.Mesh
  34672. * @deprecated since 5.0.0
  34673. */
  34674. RawMesh: {
  34675. get: function get()
  34676. {
  34677. deprecation(v5, 'PIXI.mesh.RawMesh class has moved to PIXI.Mesh');
  34678. return PIXI.Mesh;
  34679. },
  34680. },
  34681. /**
  34682. * @class PIXI.mesh.CanvasMeshRenderer
  34683. * @see PIXI.CanvasMeshRenderer
  34684. * @deprecated since 5.0.0
  34685. */
  34686. CanvasMeshRenderer: {
  34687. get: function get()
  34688. {
  34689. deprecation(v5, 'PIXI.mesh.CanvasMeshRenderer class has moved to PIXI.CanvasMeshRenderer');
  34690. return PIXI.CanvasMeshRenderer;
  34691. },
  34692. },
  34693. /**
  34694. * @class PIXI.mesh.MeshRenderer
  34695. * @see PIXI.MeshRenderer
  34696. * @deprecated since 5.0.0
  34697. */
  34698. MeshRenderer: {
  34699. get: function get()
  34700. {
  34701. deprecation(v5, 'PIXI.mesh.MeshRenderer class has moved to PIXI.MeshRenderer');
  34702. return PIXI.MeshRenderer;
  34703. },
  34704. },
  34705. });
  34706. /**
  34707. * This namespace has been removed and items have been moved to
  34708. * the top-level `PIXI` object.
  34709. * @namespace PIXI.particles
  34710. * @deprecated since 5.0.0
  34711. */
  34712. PIXI.particles = {};
  34713. Object.defineProperties(PIXI.particles, {
  34714. /**
  34715. * @class PIXI.particles.ParticleContainer
  34716. * @deprecated since 5.0.0
  34717. * @see PIXI.ParticleContainer
  34718. */
  34719. ParticleContainer: {
  34720. get: function get()
  34721. {
  34722. deprecation(v5, 'PIXI.particles.ParticleContainer class has moved to PIXI.ParticleContainer');
  34723. return PIXI.ParticleContainer;
  34724. },
  34725. },
  34726. /**
  34727. * @class PIXI.particles.ParticleRenderer
  34728. * @deprecated since 5.0.0
  34729. * @see PIXI.ParticleRenderer
  34730. */
  34731. ParticleRenderer: {
  34732. get: function get()
  34733. {
  34734. deprecation(v5, 'PIXI.particles.ParticleRenderer class has moved to PIXI.ParticleRenderer');
  34735. return PIXI.ParticleRenderer;
  34736. },
  34737. },
  34738. });
  34739. /**
  34740. * This namespace has been removed and items have been moved to
  34741. * the top-level `PIXI` object.
  34742. * @namespace PIXI.ticker
  34743. * @deprecated since 5.0.0
  34744. */
  34745. PIXI.ticker = {};
  34746. Object.defineProperties(PIXI.ticker, {
  34747. /**
  34748. * @class PIXI.ticker.Ticker
  34749. * @deprecated since 5.0.0
  34750. * @see PIXI.Ticker
  34751. */
  34752. Ticker: {
  34753. get: function get()
  34754. {
  34755. deprecation(v5, 'PIXI.ticker.Ticker class has moved to PIXI.Ticker');
  34756. return PIXI.Ticker;
  34757. },
  34758. },
  34759. /**
  34760. * @name PIXI.ticker.shared
  34761. * @type {PIXI.Ticker}
  34762. * @deprecated since 5.0.0
  34763. * @see PIXI.Ticker.shared
  34764. */
  34765. shared: {
  34766. get: function get()
  34767. {
  34768. deprecation(v5, 'PIXI.ticker.shared instance has moved to PIXI.Ticker.shared');
  34769. return PIXI.Ticker.shared;
  34770. },
  34771. },
  34772. });
  34773. /**
  34774. * All classes on this namespace have moved to the high-level `PIXI` object.
  34775. * @namespace PIXI.loaders
  34776. * @deprecated since 5.0.0
  34777. */
  34778. PIXI.loaders = {};
  34779. Object.defineProperties(PIXI.loaders, {
  34780. /**
  34781. * @class PIXI.loaders.Loader
  34782. * @see PIXI.Loader
  34783. * @deprecated since 5.0.0
  34784. */
  34785. Loader: {
  34786. get: function get()
  34787. {
  34788. deprecation(v5, 'PIXI.loaders.Loader class has moved to PIXI.Loader');
  34789. return PIXI.Loader;
  34790. },
  34791. },
  34792. /**
  34793. * @class PIXI.loaders.Resource
  34794. * @see PIXI.LoaderResource
  34795. * @deprecated since 5.0.0
  34796. */
  34797. Resource: {
  34798. get: function get()
  34799. {
  34800. deprecation(v5, 'PIXI.loaders.Resource class has moved to PIXI.LoaderResource');
  34801. return PIXI.LoaderResource;
  34802. },
  34803. },
  34804. /**
  34805. * @function PIXI.loaders.bitmapFontParser
  34806. * @see PIXI.BitmapFontLoader.use
  34807. * @deprecated since 5.0.0
  34808. */
  34809. bitmapFontParser: {
  34810. get: function get()
  34811. {
  34812. deprecation(v5, 'PIXI.loaders.bitmapFontParser function has moved to PIXI.BitmapFontLoader.use');
  34813. return PIXI.BitmapFontLoader.use;
  34814. },
  34815. },
  34816. /**
  34817. * @function PIXI.loaders.parseBitmapFontData
  34818. * @see PIXI.BitmapFontLoader.parse
  34819. * @deprecated since 5.0.0
  34820. */
  34821. parseBitmapFontData: {
  34822. get: function get()
  34823. {
  34824. deprecation(v5, 'PIXI.loaders.parseBitmapFontData function has moved to PIXI.BitmapFontLoader.parse');
  34825. return PIXI.BitmapFontLoader.parse;
  34826. },
  34827. },
  34828. /**
  34829. * @function PIXI.loaders.spritesheetParser
  34830. * @see PIXI.SpritesheetLoader.use
  34831. * @deprecated since 5.0.0
  34832. */
  34833. spritesheetParser: {
  34834. get: function get()
  34835. {
  34836. deprecation(v5, 'PIXI.loaders.spritesheetParser function has moved to PIXI.SpritesheetLoader.use');
  34837. return PIXI.SpritesheetLoader.use;
  34838. },
  34839. },
  34840. /**
  34841. * @function PIXI.loaders.getResourcePath
  34842. * @see PIXI.SpritesheetLoader.getResourcePath
  34843. * @deprecated since 5.0.0
  34844. */
  34845. getResourcePath: {
  34846. get: function get()
  34847. {
  34848. deprecation(v5, 'PIXI.loaders.getResourcePath property has moved to PIXI.SpritesheetLoader.getResourcePath');
  34849. return PIXI.SpritesheetLoader.getResourcePath;
  34850. },
  34851. },
  34852. });
  34853. /**
  34854. * @function PIXI.loaders.Loader.addPixiMiddleware
  34855. * @see PIXI.Loader.registerPlugin
  34856. * @deprecated since 5.0.0
  34857. * @param {function} middleware
  34858. */
  34859. PIXI.Loader.addPixiMiddleware = function addPixiMiddleware(middleware)
  34860. {
  34861. deprecation(v5,
  34862. 'PIXI.loaders.Loader.addPixiMiddleware function is deprecated, use PIXI.loaders.Loader.registerPlugin'
  34863. );
  34864. return PIXI.loaders.Loader.registerPlugin({ use: middleware() });
  34865. };
  34866. /**
  34867. * @class PIXI.extract.WebGLExtract
  34868. * @deprecated since 5.0.0
  34869. * @see PIXI.extract.Extract
  34870. */
  34871. Object.defineProperty(PIXI.extract, 'WebGLExtract', {
  34872. get: function get()
  34873. {
  34874. deprecation(v5, 'PIXI.extract.WebGLExtract method has moved to PIXI.extract.Extract');
  34875. return PIXI.extract.Extract;
  34876. },
  34877. });
  34878. /**
  34879. * @class PIXI.prepare.WebGLPrepare
  34880. * @deprecated since 5.0.0
  34881. * @see PIXI.prepare.Prepare
  34882. */
  34883. Object.defineProperty(PIXI.prepare, 'WebGLPrepare', {
  34884. get: function get()
  34885. {
  34886. deprecation(v5, 'PIXI.prepare.WebGLPrepare class has moved to PIXI.prepare.Prepare');
  34887. return PIXI.prepare.Prepare;
  34888. },
  34889. });
  34890. /**
  34891. * @method PIXI.Container#_renderWebGL
  34892. * @private
  34893. * @deprecated since 5.0.0
  34894. * @see PIXI.Container#render
  34895. * @param {PIXI.Renderer} renderer Instance of renderer
  34896. */
  34897. PIXI.Container.prototype._renderWebGL = function _renderWebGL(renderer)
  34898. {
  34899. deprecation(v5, 'PIXI.Container._renderWebGL method has moved to PIXI.Container._render');
  34900. this._render(renderer);
  34901. };
  34902. /**
  34903. * @method PIXI.Container#renderWebGL
  34904. * @deprecated since 5.0.0
  34905. * @see PIXI.Container#render
  34906. * @param {PIXI.Renderer} renderer Instance of renderer
  34907. */
  34908. PIXI.Container.prototype.renderWebGL = function renderWebGL(renderer)
  34909. {
  34910. deprecation(v5, 'PIXI.Container.renderWebGL method has moved to PIXI.Container.render');
  34911. this.render(renderer);
  34912. };
  34913. /**
  34914. * @method PIXI.DisplayObject#renderWebGL
  34915. * @deprecated since 5.0.0
  34916. * @see PIXI.DisplayObject#render
  34917. * @param {PIXI.Renderer} renderer Instance of renderer
  34918. */
  34919. PIXI.DisplayObject.prototype.renderWebGL = function renderWebGL(renderer)
  34920. {
  34921. deprecation(v5, 'PIXI.DisplayObject.renderWebGL method has moved to PIXI.DisplayObject.render');
  34922. this.render(renderer);
  34923. };
  34924. /**
  34925. * @method PIXI.Container#renderAdvancedWebGL
  34926. * @deprecated since 5.0.0
  34927. * @see PIXI.Container#renderAdvanced
  34928. * @param {PIXI.Renderer} renderer Instance of renderer
  34929. */
  34930. PIXI.Container.prototype.renderAdvancedWebGL = function renderAdvancedWebGL(renderer)
  34931. {
  34932. deprecation(v5, 'PIXI.Container.renderAdvancedWebGL method has moved to PIXI.Container.renderAdvanced');
  34933. this.renderAdvanced(renderer);
  34934. };
  34935. Object.defineProperties(PIXI.settings, {
  34936. /**
  34937. * Default transform type.
  34938. *
  34939. * @static
  34940. * @deprecated since 5.0.0
  34941. * @memberof PIXI.settings
  34942. * @type {PIXI.TRANSFORM_MODE}
  34943. * @default PIXI.TRANSFORM_MODE.STATIC
  34944. */
  34945. TRANSFORM_MODE: {
  34946. get: function get()
  34947. {
  34948. deprecation(v5, 'PIXI.settings.TRANSFORM_MODE property has been removed');
  34949. return 0;
  34950. },
  34951. set: function set()
  34952. {
  34953. deprecation(v5, 'PIXI.settings.TRANSFORM_MODE property has been removed');
  34954. },
  34955. },
  34956. });
  34957. var BaseTexture = PIXI.BaseTexture;
  34958. /**
  34959. * @method loadSource
  34960. * @memberof PIXI.BaseTexture#
  34961. * @deprecated since 5.0.0
  34962. */
  34963. BaseTexture.prototype.loadSource = function loadSource(image)
  34964. {
  34965. deprecation(v5, 'PIXI.BaseTexture.loadSource method has been deprecated');
  34966. var resource = PIXI.resources.autoDetectResource(image);
  34967. resource.internal = true;
  34968. this.setResource(resource);
  34969. this.update();
  34970. };
  34971. Object.defineProperties(BaseTexture.prototype, {
  34972. /**
  34973. * @name PIXI.BaseTexture#hasLoaded
  34974. * @type {boolean}
  34975. * @deprecated since 5.0.0
  34976. * @readonly
  34977. * @see PIXI.BaseTexture#valid
  34978. */
  34979. hasLoaded: {
  34980. get: function get()
  34981. {
  34982. deprecation(v5, 'PIXI.BaseTexture.hasLoaded property has been removed, use PIXI.BaseTexture.valid');
  34983. return this.valid;
  34984. },
  34985. },
  34986. /**
  34987. * @name PIXI.BaseTexture#imageUrl
  34988. * @type {string}
  34989. * @deprecated since 5.0.0
  34990. * @readonly
  34991. * @see PIXI.resource.ImageResource#url
  34992. */
  34993. imageUrl: {
  34994. get: function get()
  34995. {
  34996. deprecation(v5, 'PIXI.BaseTexture.imageUrl property has been removed, use resource.url');
  34997. return this.resource && this.resource.url;
  34998. },
  34999. },
  35000. /**
  35001. * @name PIXI.BaseTexture#source
  35002. * @type {HTMLImageElement|HTMLCanvasElement|HTMLVideoElement|SVGElement}
  35003. * @deprecated since 5.0.0
  35004. * @readonly
  35005. * @see PIXI.resources.BaseImageResource#source
  35006. */
  35007. source: {
  35008. get: function get()
  35009. {
  35010. deprecation(v5, 'PIXI.BaseTexture.source property has been moved, use `resource.source`');
  35011. return this.resource && this.resource.source;
  35012. },
  35013. set: function set(source)
  35014. {
  35015. deprecation(v5, 'PIXI.BaseTexture.source property has been moved, use `resource.source` '
  35016. + 'if you want to set HTMLCanvasElement. Otherwise, create new BaseTexture.');
  35017. if (this.resource)
  35018. {
  35019. this.resource.source = source;
  35020. }
  35021. },
  35022. },
  35023. });
  35024. /**
  35025. * @method fromImage
  35026. * @static
  35027. * @memberof PIXI.BaseTexture
  35028. * @deprecated since 5.0.0
  35029. * @see PIXI.BaseTexture.from
  35030. */
  35031. BaseTexture.fromImage = function fromImage(canvas, crossorigin, scaleMode, scale)
  35032. {
  35033. deprecation(v5, 'PIXI.BaseTexture.fromImage method has been replaced with PIXI.BaseTexture.from');
  35034. var resourceOptions = { scale: scale, crossorigin: crossorigin };
  35035. return BaseTexture.from(canvas, { scaleMode: scaleMode, resourceOptions: resourceOptions });
  35036. };
  35037. /**
  35038. * @method fromCanvas
  35039. * @static
  35040. * @memberof PIXI.BaseTexture
  35041. * @deprecated since 5.0.0
  35042. * @see PIXI.BaseTexture.from
  35043. */
  35044. BaseTexture.fromCanvas = function fromCanvas(canvas, scaleMode)
  35045. {
  35046. deprecation(v5, 'PIXI.BaseTexture.fromCanvas method has been replaced with PIXI.BaseTexture.from');
  35047. return BaseTexture.from(canvas, { scaleMode: scaleMode });
  35048. };
  35049. /**
  35050. * @method fromSVG
  35051. * @static
  35052. * @memberof PIXI.BaseTexture
  35053. * @deprecated since 5.0.0
  35054. * @see PIXI.BaseTexture.from
  35055. */
  35056. BaseTexture.fromSVG = function fromSVG(canvas, crossorigin, scaleMode, scale)
  35057. {
  35058. deprecation(v5, 'PIXI.BaseTexture.fromSVG method has been replaced with PIXI.BaseTexture.from');
  35059. var resourceOptions = { scale: scale, crossorigin: crossorigin };
  35060. return BaseTexture.from(canvas, { scaleMode: scaleMode, resourceOptions: resourceOptions });
  35061. };
  35062. /**
  35063. * @method PIXI.Point#copy
  35064. * @deprecated since 5.0.0
  35065. * @see PIXI.Point#copyFrom
  35066. */
  35067. PIXI.Point.prototype.copy = function copy(p)
  35068. {
  35069. deprecation(v5, 'PIXI.Point.copy method has been replaced with PIXI.Point.copyFrom');
  35070. return this.copyFrom(p);
  35071. };
  35072. /**
  35073. * @method PIXI.ObservablePoint#copy
  35074. * @deprecated since 5.0.0
  35075. * @see PIXI.ObservablePoint#copyFrom
  35076. */
  35077. PIXI.ObservablePoint.prototype.copy = function copy(p)
  35078. {
  35079. deprecation(v5, 'PIXI.ObservablePoint.copy method has been replaced with PIXI.ObservablePoint.copyFrom');
  35080. return this.copyFrom(p);
  35081. };
  35082. /**
  35083. * @method PIXI.Rectangle#copy
  35084. * @deprecated since 5.0.0
  35085. * @see PIXI.Rectangle#copyFrom
  35086. */
  35087. PIXI.Rectangle.prototype.copy = function copy(p)
  35088. {
  35089. deprecation(v5, 'PIXI.Rectangle.copy method has been replaced with PIXI.Rectangle.copyFrom');
  35090. return this.copyFrom(p);
  35091. };
  35092. /**
  35093. * @method PIXI.Matrix#copy
  35094. * @deprecated since 5.0.0
  35095. * @see PIXI.Matrix#copyTo
  35096. */
  35097. PIXI.Matrix.prototype.copy = function copy(p)
  35098. {
  35099. deprecation(v5, 'PIXI.Matrix.copy method has been replaced with PIXI.Matrix.copyTo');
  35100. return this.copyTo(p);
  35101. };
  35102. Object.assign(PIXI.systems.FilterSystem.prototype, {
  35103. /**
  35104. * @method PIXI.FilterManager#getRenderTarget
  35105. * @deprecated since 5.0.0
  35106. * @see PIXI.systems.FilterSystem#getFilterTexture
  35107. */
  35108. getRenderTarget: function getRenderTarget(clear, resolution)
  35109. {
  35110. deprecation(v5,
  35111. 'PIXI.FilterManager.getRenderTarget method has been replaced with PIXI.systems.FilterSystem#getFilterTexture'
  35112. );
  35113. return this.getFilterTexture(resolution);
  35114. },
  35115. /**
  35116. * @method PIXI.FilterManager#returnRenderTarget
  35117. * @deprecated since 5.0.0
  35118. * @see PIXI.systems.FilterSystem#returnFilterTexture
  35119. */
  35120. returnRenderTarget: function returnRenderTarget(renderTexture)
  35121. {
  35122. deprecation(v5,
  35123. 'PIXI.FilterManager.returnRenderTarget method has been replaced with '
  35124. + 'PIXI.systems.FilterSystem.returnFilterTexture'
  35125. );
  35126. this.returnFilterTexture(renderTexture);
  35127. },
  35128. /**
  35129. * @method PIXI.systems.FilterSystem#calculateScreenSpaceMatrix
  35130. * @deprecated since 5.0.0
  35131. * @param {PIXI.Matrix} outputMatrix - the matrix to output to.
  35132. * @return {PIXI.Matrix} The mapped matrix.
  35133. */
  35134. calculateScreenSpaceMatrix: function calculateScreenSpaceMatrix(outputMatrix)
  35135. {
  35136. deprecation(v5, 'PIXI.systems.FilterSystem.calculateScreenSpaceMatrix method is removed, '
  35137. + 'use `(vTextureCoord * inputSize.xy) + outputFrame.xy` instead');
  35138. var mappedMatrix = outputMatrix.identity();
  35139. var ref = this.activeState;
  35140. var sourceFrame = ref.sourceFrame;
  35141. var destinationFrame = ref.destinationFrame;
  35142. mappedMatrix.translate(sourceFrame.x / destinationFrame.width, sourceFrame.y / destinationFrame.height);
  35143. mappedMatrix.scale(destinationFrame.width, destinationFrame.height);
  35144. return mappedMatrix;
  35145. },
  35146. /**
  35147. * @method PIXI.systems.FilterSystem#calculateNormalizedScreenSpaceMatrix
  35148. * @deprecated since 5.0.0
  35149. * @param {PIXI.Matrix} outputMatrix - The matrix to output to.
  35150. * @return {PIXI.Matrix} The mapped matrix.
  35151. */
  35152. calculateNormalizedScreenSpaceMatrix: function calculateNormalizedScreenSpaceMatrix(outputMatrix)
  35153. {
  35154. deprecation(v5, 'PIXI.systems.FilterManager.calculateNormalizedScreenSpaceMatrix method is removed, '
  35155. + 'use `((vTextureCoord * inputSize.xy) + outputFrame.xy) / outputFrame.zw` instead.');
  35156. var ref = this.activeState;
  35157. var sourceFrame = ref.sourceFrame;
  35158. var destinationFrame = ref.destinationFrame;
  35159. var mappedMatrix = outputMatrix.identity();
  35160. mappedMatrix.translate(sourceFrame.x / destinationFrame.width, sourceFrame.y / destinationFrame.height);
  35161. var translateScaleX = (destinationFrame.width / sourceFrame.width);
  35162. var translateScaleY = (destinationFrame.height / sourceFrame.height);
  35163. mappedMatrix.scale(translateScaleX, translateScaleY);
  35164. return mappedMatrix;
  35165. },
  35166. });
  35167. Object.defineProperties(PIXI.RenderTexture.prototype, {
  35168. /**
  35169. * @name PIXI.RenderTexture#sourceFrame
  35170. * @type {PIXI.Rectangle}
  35171. * @deprecated since 5.0.0
  35172. * @readonly
  35173. */
  35174. sourceFrame: {
  35175. get: function get()
  35176. {
  35177. deprecation(v5, 'PIXI.RenderTexture.sourceFrame property has been removed');
  35178. return this.filterFrame;
  35179. },
  35180. },
  35181. /**
  35182. * @name PIXI.RenderTexture#size
  35183. * @type {PIXI.Rectangle}
  35184. * @deprecated since 5.0.0
  35185. * @readonly
  35186. */
  35187. size: {
  35188. get: function get()
  35189. {
  35190. deprecation(v5, 'PIXI.RenderTexture.size property has been removed');
  35191. return this._frame;
  35192. },
  35193. },
  35194. });
  35195. /**
  35196. * @class BlurXFilter
  35197. * @memberof PIXI.filters
  35198. * @deprecated since 5.0.0
  35199. * @see PIXI.filters.BlurFilterPass
  35200. */
  35201. var BlurXFilter = /*@__PURE__*/(function (superclass) {
  35202. function BlurXFilter(strength, quality, resolution, kernelSize)
  35203. {
  35204. deprecation(v5, 'PIXI.filters.BlurXFilter class is deprecated, use PIXI.filters.BlurFilterPass');
  35205. superclass.call(this, true, strength, quality, resolution, kernelSize);
  35206. }
  35207. if ( superclass ) BlurXFilter.__proto__ = superclass;
  35208. BlurXFilter.prototype = Object.create( superclass && superclass.prototype );
  35209. BlurXFilter.prototype.constructor = BlurXFilter;
  35210. return BlurXFilter;
  35211. }(PIXI.filters.BlurFilterPass));
  35212. /**
  35213. * @class BlurYFilter
  35214. * @memberof PIXI.filters
  35215. * @deprecated since 5.0.0
  35216. * @see PIXI.filters.BlurFilterPass
  35217. */
  35218. var BlurYFilter = /*@__PURE__*/(function (superclass) {
  35219. function BlurYFilter(strength, quality, resolution, kernelSize)
  35220. {
  35221. deprecation(v5, 'PIXI.filters.BlurYFilter class is deprecated, use PIXI.filters.BlurFilterPass');
  35222. superclass.call(this, false, strength, quality, resolution, kernelSize);
  35223. }
  35224. if ( superclass ) BlurYFilter.__proto__ = superclass;
  35225. BlurYFilter.prototype = Object.create( superclass && superclass.prototype );
  35226. BlurYFilter.prototype.constructor = BlurYFilter;
  35227. return BlurYFilter;
  35228. }(PIXI.filters.BlurFilterPass));
  35229. Object.assign(PIXI.filters, {
  35230. BlurXFilter: BlurXFilter,
  35231. BlurYFilter: BlurYFilter,
  35232. });
  35233. var Sprite = PIXI.Sprite;
  35234. var Texture = PIXI.Texture;
  35235. var Graphics = PIXI.Graphics;
  35236. // Support for pixi.js-legacy bifurcation
  35237. // give users a friendly assist to use legacy
  35238. if (!Graphics.prototype.generateCanvasTexture)
  35239. {
  35240. Graphics.prototype.generateCanvasTexture = function generateCanvasTexture()
  35241. {
  35242. deprecation(v5, 'PIXI.Graphics.generateCanvasTexture method is only available in "pixi.js-legacy"');
  35243. };
  35244. }
  35245. // Use these to deprecate all the Sprite from* methods
  35246. function spriteFrom(name, source, crossorigin, scaleMode)
  35247. {
  35248. deprecation(v5, ("PIXI.Sprite." + name + " method is deprecated, use PIXI.Sprite.from"));
  35249. return Sprite.from(source, {
  35250. resourceOptions: {
  35251. scale: scaleMode,
  35252. crossorigin: crossorigin,
  35253. },
  35254. });
  35255. }
  35256. /**
  35257. * @deprecated since 5.0.0
  35258. * @see PIXI.Sprite.from
  35259. * @method PIXI.Sprite.fromImage
  35260. * @return {PIXI.Sprite}
  35261. */
  35262. Sprite.fromImage = spriteFrom.bind(null, 'fromImage');
  35263. /**
  35264. * @deprecated since 5.0.0
  35265. * @method PIXI.Sprite.fromSVG
  35266. * @see PIXI.Sprite.from
  35267. * @return {PIXI.Sprite}
  35268. */
  35269. Sprite.fromSVG = spriteFrom.bind(null, 'fromSVG');
  35270. /**
  35271. * @deprecated since 5.0.0
  35272. * @method PIXI.Sprite.fromCanvas
  35273. * @see PIXI.Sprite.from
  35274. * @return {PIXI.Sprite}
  35275. */
  35276. Sprite.fromCanvas = spriteFrom.bind(null, 'fromCanvas');
  35277. /**
  35278. * @deprecated since 5.0.0
  35279. * @method PIXI.Sprite.fromVideo
  35280. * @see PIXI.Sprite.from
  35281. * @return {PIXI.Sprite}
  35282. */
  35283. Sprite.fromVideo = spriteFrom.bind(null, 'fromVideo');
  35284. /**
  35285. * @deprecated since 5.0.0
  35286. * @method PIXI.Sprite.fromFrame
  35287. * @see PIXI.Sprite.from
  35288. * @return {PIXI.Sprite}
  35289. */
  35290. Sprite.fromFrame = spriteFrom.bind(null, 'fromFrame');
  35291. // Use these to deprecate all the Texture from* methods
  35292. function textureFrom(name, source, crossorigin, scaleMode)
  35293. {
  35294. deprecation(v5, ("PIXI.Texture." + name + " method is deprecated, use PIXI.Texture.from"));
  35295. return Texture.from(source, {
  35296. resourceOptions: {
  35297. scale: scaleMode,
  35298. crossorigin: crossorigin,
  35299. },
  35300. });
  35301. }
  35302. /**
  35303. * @deprecated since 5.0.0
  35304. * @method PIXI.Texture.fromImage
  35305. * @see PIXI.Texture.from
  35306. * @return {PIXI.Texture}
  35307. */
  35308. Texture.fromImage = textureFrom.bind(null, 'fromImage');
  35309. /**
  35310. * @deprecated since 5.0.0
  35311. * @method PIXI.Texture.fromSVG
  35312. * @see PIXI.Texture.from
  35313. * @return {PIXI.Texture}
  35314. */
  35315. Texture.fromSVG = textureFrom.bind(null, 'fromSVG');
  35316. /**
  35317. * @deprecated since 5.0.0
  35318. * @method PIXI.Texture.fromCanvas
  35319. * @see PIXI.Texture.from
  35320. * @return {PIXI.Texture}
  35321. */
  35322. Texture.fromCanvas = textureFrom.bind(null, 'fromCanvas');
  35323. /**
  35324. * @deprecated since 5.0.0
  35325. * @method PIXI.Texture.fromVideo
  35326. * @see PIXI.Texture.from
  35327. * @return {PIXI.Texture}
  35328. */
  35329. Texture.fromVideo = textureFrom.bind(null, 'fromVideo');
  35330. /**
  35331. * @deprecated since 5.0.0
  35332. * @method PIXI.Texture.fromFrame
  35333. * @see PIXI.Texture.from
  35334. * @return {PIXI.Texture}
  35335. */
  35336. Texture.fromFrame = textureFrom.bind(null, 'fromFrame');
  35337. /**
  35338. * @deprecated since 5.0.0
  35339. * @member {boolean} PIXI.AbstractRenderer#autoResize
  35340. * @see PIXI.AbstractRenderer#autoDensity
  35341. */
  35342. Object.defineProperty(PIXI.AbstractRenderer.prototype, 'autoResize', {
  35343. get: function get()
  35344. {
  35345. deprecation(v5, 'PIXI.AbstractRenderer.autoResize property is deprecated, use autoDensity');
  35346. return this.autoDensity;
  35347. },
  35348. set: function set(value)
  35349. {
  35350. deprecation(v5, 'PIXI.AbstractRenderer.autoResize property is deprecated, use autoDensity');
  35351. this.autoDensity = value;
  35352. },
  35353. });
  35354. /**
  35355. * @namespace PIXI.utils.mixins
  35356. * @deprecated since 5.0.0
  35357. */
  35358. PIXI.utils.mixins = {
  35359. /**
  35360. * @memberof PIXI.utils.mixins
  35361. * @function mixin
  35362. * @deprecated since 5.0.0
  35363. */
  35364. mixin: function mixin()
  35365. {
  35366. deprecation(v5, 'PIXI.utils.mixins.mixin function is no longer available');
  35367. },
  35368. /**
  35369. * @memberof PIXI.utils.mixins
  35370. * @function delayMixin
  35371. * @deprecated since 5.0.0
  35372. */
  35373. delayMixin: function delayMixin()
  35374. {
  35375. deprecation(v5, 'PIXI.utils.mixins.delayMixin function is no longer available');
  35376. },
  35377. /**
  35378. * @memberof PIXI.utils.mixins
  35379. * @function performMixins
  35380. * @deprecated since 5.0.0
  35381. */
  35382. performMixins: function performMixins()
  35383. {
  35384. deprecation(v5, 'PIXI.utils.mixins.performMixins function is no longer available');
  35385. },
  35386. };
  35387. }
  35388. /*!
  35389. * @pixi/mesh - v5.0.4
  35390. * Compiled Fri, 07 Jun 2019 17:17:49 UTC
  35391. *
  35392. * @pixi/mesh is licensed under the MIT License.
  35393. * http://www.opensource.org/licenses/mit-license
  35394. */
  35395. /**
  35396. * Class controls cache for UV mapping from Texture normal space to BaseTexture normal space.
  35397. *
  35398. * @class
  35399. * @memberof PIXI
  35400. */
  35401. var MeshBatchUvs = function MeshBatchUvs(uvBuffer, uvMatrix)
  35402. {
  35403. /**
  35404. * Buffer with normalized UV's
  35405. * @member {PIXI.Buffer}
  35406. */
  35407. this.uvBuffer = uvBuffer;
  35408. /**
  35409. * Material UV matrix
  35410. * @member {PIXI.TextureMatrix}
  35411. */
  35412. this.uvMatrix = uvMatrix;
  35413. /**
  35414. * UV Buffer data
  35415. * @member {Float32Array}
  35416. * @readonly
  35417. */
  35418. this.data = null;
  35419. this._bufferUpdateId = -1;
  35420. this._textureUpdateId = -1;
  35421. this._updateID = 0;
  35422. };
  35423. /**
  35424. * updates
  35425. *
  35426. * @param {boolean} forceUpdate - force the update
  35427. */
  35428. MeshBatchUvs.prototype.update = function update (forceUpdate)
  35429. {
  35430. if (!forceUpdate
  35431. && this._bufferUpdateId === this.uvBuffer._updateID
  35432. && this._textureUpdateId === this.uvMatrix._updateID)
  35433. {
  35434. return;
  35435. }
  35436. this._bufferUpdateId = this.uvBuffer._updateID;
  35437. this._textureUpdateId = this.uvMatrix._updateID;
  35438. var data = this.uvBuffer.data;
  35439. if (!this.data || this.data.length !== data.length)
  35440. {
  35441. this.data = new Float32Array(data.length);
  35442. }
  35443. this.uvMatrix.multiplyUvs(data, this.data);
  35444. this._updateID++;
  35445. };
  35446. var tempPoint$2 = new Point();
  35447. var tempPolygon = new Polygon();
  35448. /**
  35449. * Base mesh class.
  35450. *
  35451. * This class empowers you to have maximum flexibility to render any kind of WebGL visuals you can think of.
  35452. * This class assumes a certain level of WebGL knowledge.
  35453. * If you know a bit this should abstract enough away to make you life easier!
  35454. *
  35455. * Pretty much ALL WebGL can be broken down into the following:
  35456. * - Geometry - The structure and data for the mesh. This can include anything from positions, uvs, normals, colors etc..
  35457. * - Shader - This is the shader that PixiJS will render the geometry with (attributes in the shader must match the geometry)
  35458. * - State - This is the state of WebGL required to render the mesh.
  35459. *
  35460. * Through a combination of the above elements you can render anything you want, 2D or 3D!
  35461. *
  35462. * @class
  35463. * @extends PIXI.Container
  35464. * @memberof PIXI
  35465. */
  35466. var Mesh = /*@__PURE__*/(function (Container) {
  35467. function Mesh(geometry, shader, state, drawMode)// vertices, uvs, indices, drawMode)
  35468. {
  35469. if ( drawMode === void 0 ) { drawMode = DRAW_MODES.TRIANGLES; }
  35470. Container.call(this);
  35471. /**
  35472. * Includes vertex positions, face indices, normals, colors, UVs, and
  35473. * custom attributes within buffers, reducing the cost of passing all
  35474. * this data to the GPU. Can be shared between multiple Mesh objects.
  35475. * @member {PIXI.Geometry}
  35476. * @readonly
  35477. */
  35478. this.geometry = geometry;
  35479. geometry.refCount++;
  35480. /**
  35481. * Represents the vertex and fragment shaders that processes the geometry and runs on the GPU.
  35482. * Can be shared between multiple Mesh objects.
  35483. * @member {PIXI.Shader|PIXI.MeshMaterial}
  35484. */
  35485. this.shader = shader;
  35486. /**
  35487. * Represents the WebGL state the Mesh required to render, excludes shader and geometry. E.g.,
  35488. * blend mode, culling, depth testing, direction of rendering triangles, backface, etc.
  35489. * @member {PIXI.State}
  35490. */
  35491. this.state = state || State.for2d();
  35492. /**
  35493. * The way the Mesh should be drawn, can be any of the {@link PIXI.DRAW_MODES} constants.
  35494. *
  35495. * @member {number}
  35496. * @see PIXI.DRAW_MODES
  35497. */
  35498. this.drawMode = drawMode;
  35499. /**
  35500. * Typically the index of the IndexBuffer where to start drawing.
  35501. * @member {number}
  35502. * @default 0
  35503. */
  35504. this.start = 0;
  35505. /**
  35506. * How much of the geometry to draw, by default `0` renders everything.
  35507. * @member {number}
  35508. * @default 0
  35509. */
  35510. this.size = 0;
  35511. /**
  35512. * thease are used as easy access for batching
  35513. * @member {Float32Array}
  35514. * @private
  35515. */
  35516. this.uvs = null;
  35517. /**
  35518. * thease are used as easy access for batching
  35519. * @member {Uint16Array}
  35520. * @private
  35521. */
  35522. this.indices = null;
  35523. /**
  35524. * this is the caching layer used by the batcher
  35525. * @member {Float32Array}
  35526. * @private
  35527. */
  35528. this.vertexData = new Float32Array(1);
  35529. /**
  35530. * If geometry is changed used to decide to re-transform
  35531. * the vertexData.
  35532. * @member {number}
  35533. * @private
  35534. */
  35535. this.vertexDirty = 0;
  35536. this._transformID = -1;
  35537. // Inherited from DisplayMode, set defaults
  35538. this.tint = 0xFFFFFF;
  35539. this.blendMode = BLEND_MODES.NORMAL;
  35540. /**
  35541. * Internal roundPixels field
  35542. *
  35543. * @member {boolean}
  35544. * @private
  35545. */
  35546. this._roundPixels = settings.ROUND_PIXELS;
  35547. /**
  35548. * Batched UV's are cached for atlas textures
  35549. * @member {PIXI.MeshBatchUvs}
  35550. * @private
  35551. */
  35552. this.batchUvs = null;
  35553. }
  35554. if ( Container ) { Mesh.__proto__ = Container; }
  35555. Mesh.prototype = Object.create( Container && Container.prototype );
  35556. Mesh.prototype.constructor = Mesh;
  35557. var prototypeAccessors = { uvBuffer: { configurable: true },verticesBuffer: { configurable: true },material: { configurable: true },blendMode: { configurable: true },roundPixels: { configurable: true },tint: { configurable: true },texture: { configurable: true } };
  35558. /**
  35559. * To change mesh uv's, change its uvBuffer data and increment its _updateID.
  35560. * @member {PIXI.Buffer}
  35561. * @readonly
  35562. */
  35563. prototypeAccessors.uvBuffer.get = function ()
  35564. {
  35565. return this.geometry.buffers[1];
  35566. };
  35567. /**
  35568. * To change mesh vertices, change its uvBuffer data and increment its _updateID.
  35569. * Incrementing _updateID is optional because most of Mesh objects do it anyway.
  35570. * @member {PIXI.Buffer}
  35571. * @readonly
  35572. */
  35573. prototypeAccessors.verticesBuffer.get = function ()
  35574. {
  35575. return this.geometry.buffers[0];
  35576. };
  35577. /**
  35578. * Alias for {@link PIXI.Mesh#shader}.
  35579. * @member {PIXI.Shader|PIXI.MeshMaterial}
  35580. */
  35581. prototypeAccessors.material.set = function (value)
  35582. {
  35583. this.shader = value;
  35584. };
  35585. prototypeAccessors.material.get = function ()
  35586. {
  35587. return this.shader;
  35588. };
  35589. /**
  35590. * The blend mode to be applied to the Mesh. Apply a value of
  35591. * `PIXI.BLEND_MODES.NORMAL` to reset the blend mode.
  35592. *
  35593. * @member {number}
  35594. * @default PIXI.BLEND_MODES.NORMAL;
  35595. * @see PIXI.BLEND_MODES
  35596. */
  35597. prototypeAccessors.blendMode.set = function (value)
  35598. {
  35599. this.state.blendMode = value;
  35600. };
  35601. prototypeAccessors.blendMode.get = function ()
  35602. {
  35603. return this.state.blendMode;
  35604. };
  35605. /**
  35606. * If true PixiJS will Math.floor() x/y values when rendering, stopping pixel interpolation.
  35607. * Advantages can include sharper image quality (like text) and faster rendering on canvas.
  35608. * The main disadvantage is movement of objects may appear less smooth.
  35609. * To set the global default, change {@link PIXI.settings.ROUND_PIXELS}
  35610. *
  35611. * @member {boolean}
  35612. * @default false
  35613. */
  35614. prototypeAccessors.roundPixels.set = function (value)
  35615. {
  35616. if (this._roundPixels !== value)
  35617. {
  35618. this._transformID = -1;
  35619. }
  35620. this._roundPixels = value;
  35621. };
  35622. prototypeAccessors.roundPixels.get = function ()
  35623. {
  35624. return this._roundPixels;
  35625. };
  35626. /**
  35627. * The multiply tint applied to the Mesh. This is a hex value. A value of
  35628. * `0xFFFFFF` will remove any tint effect.
  35629. *
  35630. * @member {number}
  35631. * @default 0xFFFFFF
  35632. */
  35633. prototypeAccessors.tint.get = function ()
  35634. {
  35635. return this.shader.tint;
  35636. };
  35637. prototypeAccessors.tint.set = function (value)
  35638. {
  35639. this.shader.tint = value;
  35640. };
  35641. /**
  35642. * The texture that the Mesh uses.
  35643. *
  35644. * @member {PIXI.Texture}
  35645. */
  35646. prototypeAccessors.texture.get = function ()
  35647. {
  35648. return this.shader.texture;
  35649. };
  35650. prototypeAccessors.texture.set = function (value)
  35651. {
  35652. this.shader.texture = value;
  35653. };
  35654. /**
  35655. * Standard renderer draw.
  35656. * @protected
  35657. */
  35658. Mesh.prototype._render = function _render (renderer)
  35659. {
  35660. // set properties for batching..
  35661. // TODO could use a different way to grab verts?
  35662. var vertices = this.geometry.buffers[0].data;
  35663. // TODO benchmark check for attribute size..
  35664. if (this.shader.batchable && this.drawMode === DRAW_MODES.TRIANGLES && vertices.length < Mesh.BATCHABLE_SIZE * 2)
  35665. {
  35666. this._renderToBatch(renderer);
  35667. }
  35668. else
  35669. {
  35670. this._renderDefault(renderer);
  35671. }
  35672. };
  35673. /**
  35674. * Standard non-batching way of rendering.
  35675. * @protected
  35676. * @param {PIXI.Renderer} renderer - Instance to renderer.
  35677. */
  35678. Mesh.prototype._renderDefault = function _renderDefault (renderer)
  35679. {
  35680. var shader = this.shader;
  35681. shader.alpha = this.worldAlpha;
  35682. if (shader.update)
  35683. {
  35684. shader.update();
  35685. }
  35686. renderer.batch.flush();
  35687. if (shader.program.uniformData.translationMatrix)
  35688. {
  35689. shader.uniforms.translationMatrix = this.transform.worldTransform.toArray(true);
  35690. }
  35691. // bind and sync uniforms..
  35692. renderer.shader.bind(shader);
  35693. // set state..
  35694. renderer.state.setState(this.state);
  35695. // bind the geometry...
  35696. renderer.geometry.bind(this.geometry, shader);
  35697. // then render it
  35698. renderer.geometry.draw(this.drawMode, this.size, this.start, this.geometry.instanceCount);
  35699. };
  35700. /**
  35701. * Rendering by using the Batch system.
  35702. * @protected
  35703. * @param {PIXI.Renderer} renderer - Instance to renderer.
  35704. */
  35705. Mesh.prototype._renderToBatch = function _renderToBatch (renderer)
  35706. {
  35707. var geometry = this.geometry;
  35708. if (this.shader.uvMatrix)
  35709. {
  35710. this.shader.uvMatrix.update();
  35711. this.calculateUvs();
  35712. }
  35713. // set properties for batching..
  35714. this.calculateVertices();
  35715. this.indices = geometry.indexBuffer.data;
  35716. this._tintRGB = this.shader._tintRGB;
  35717. this._texture = this.shader.texture;
  35718. var pluginName = this.material.pluginName;
  35719. renderer.batch.setObjectRenderer(renderer.plugins[pluginName]);
  35720. renderer.plugins[pluginName].render(this);
  35721. };
  35722. /**
  35723. * Updates vertexData field based on transform and vertices
  35724. */
  35725. Mesh.prototype.calculateVertices = function calculateVertices ()
  35726. {
  35727. var geometry = this.geometry;
  35728. var vertices = geometry.buffers[0].data;
  35729. if (geometry.vertexDirtyId === this.vertexDirty && this._transformID === this.transform._worldID)
  35730. {
  35731. return;
  35732. }
  35733. this._transformID = this.transform._worldID;
  35734. if (this.vertexData.length !== vertices.length)
  35735. {
  35736. this.vertexData = new Float32Array(vertices.length);
  35737. }
  35738. var wt = this.transform.worldTransform;
  35739. var a = wt.a;
  35740. var b = wt.b;
  35741. var c = wt.c;
  35742. var d = wt.d;
  35743. var tx = wt.tx;
  35744. var ty = wt.ty;
  35745. var vertexData = this.vertexData;
  35746. for (var i = 0; i < vertexData.length / 2; i++)
  35747. {
  35748. var x = vertices[(i * 2)];
  35749. var y = vertices[(i * 2) + 1];
  35750. vertexData[(i * 2)] = (a * x) + (c * y) + tx;
  35751. vertexData[(i * 2) + 1] = (b * x) + (d * y) + ty;
  35752. }
  35753. if (this._roundPixels)
  35754. {
  35755. for (var i$1 = 0; i$1 < vertexData.length; i$1++)
  35756. {
  35757. vertexData[i$1] = Math.round(vertexData[i$1]);
  35758. }
  35759. }
  35760. this.vertexDirty = geometry.vertexDirtyId;
  35761. };
  35762. /**
  35763. * Updates uv field based on from geometry uv's or batchUvs
  35764. */
  35765. Mesh.prototype.calculateUvs = function calculateUvs ()
  35766. {
  35767. var geomUvs = this.geometry.buffers[1];
  35768. if (!this.shader.uvMatrix.isSimple)
  35769. {
  35770. if (!this.batchUvs)
  35771. {
  35772. this.batchUvs = new MeshBatchUvs(geomUvs, this.shader.uvMatrix);
  35773. }
  35774. this.batchUvs.update();
  35775. this.uvs = this.batchUvs.data;
  35776. }
  35777. else
  35778. {
  35779. this.uvs = geomUvs.data;
  35780. }
  35781. };
  35782. /**
  35783. * Updates the bounds of the mesh as a rectangle. The bounds calculation takes the worldTransform into account.
  35784. * there must be a aVertexPosition attribute present in the geometry for bounds to be calculated correctly.
  35785. *
  35786. * @protected
  35787. */
  35788. Mesh.prototype._calculateBounds = function _calculateBounds ()
  35789. {
  35790. this.calculateVertices();
  35791. this._bounds.addVertexData(this.vertexData, 0, this.vertexData.length);
  35792. };
  35793. /**
  35794. * Tests if a point is inside this mesh. Works only for PIXI.DRAW_MODES.TRIANGLES.
  35795. *
  35796. * @param {PIXI.Point} point the point to test
  35797. * @return {boolean} the result of the test
  35798. */
  35799. Mesh.prototype.containsPoint = function containsPoint (point)
  35800. {
  35801. if (!this.getBounds().contains(point.x, point.y))
  35802. {
  35803. return false;
  35804. }
  35805. this.worldTransform.applyInverse(point, tempPoint$2);
  35806. var vertices = this.geometry.getBuffer('aVertexPosition').data;
  35807. var points = tempPolygon.points;
  35808. var indices = this.geometry.getIndex().data;
  35809. var len = indices.length;
  35810. var step = this.drawMode === 4 ? 3 : 1;
  35811. for (var i = 0; i + 2 < len; i += step)
  35812. {
  35813. var ind0 = indices[i] * 2;
  35814. var ind1 = indices[i + 1] * 2;
  35815. var ind2 = indices[i + 2] * 2;
  35816. points[0] = vertices[ind0];
  35817. points[1] = vertices[ind0 + 1];
  35818. points[2] = vertices[ind1];
  35819. points[3] = vertices[ind1 + 1];
  35820. points[4] = vertices[ind2];
  35821. points[5] = vertices[ind2 + 1];
  35822. if (tempPolygon.contains(tempPoint$2.x, tempPoint$2.y))
  35823. {
  35824. return true;
  35825. }
  35826. }
  35827. return false;
  35828. };
  35829. /**
  35830. * Destroys the Mesh object.
  35831. *
  35832. * @param {object|boolean} [options] - Options parameter. A boolean will act as if all
  35833. * options have been set to that value
  35834. * @param {boolean} [options.children=false] - if set to true, all the children will have
  35835. * their destroy method called as well. 'options' will be passed on to those calls.
  35836. */
  35837. Mesh.prototype.destroy = function destroy (options)
  35838. {
  35839. Container.prototype.destroy.call(this, options);
  35840. this.geometry.refCount--;
  35841. if (this.geometry.refCount === 0)
  35842. {
  35843. this.geometry.dispose();
  35844. }
  35845. this.geometry = null;
  35846. this.shader = null;
  35847. this.state = null;
  35848. this.uvs = null;
  35849. this.indices = null;
  35850. this.vertexData = null;
  35851. };
  35852. Object.defineProperties( Mesh.prototype, prototypeAccessors );
  35853. return Mesh;
  35854. }(Container));
  35855. /**
  35856. * The maximum number of vertices to consider batchable. Generally, the complexity
  35857. * of the geometry.
  35858. * @memberof PIXI.Mesh
  35859. * @static
  35860. * @member {number} BATCHABLE_SIZE
  35861. */
  35862. Mesh.BATCHABLE_SIZE = 100;
  35863. var vertex$6 = "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";
  35864. var fragment$8 = "varying vec2 vTextureCoord;\nuniform vec4 uColor;\n\nuniform sampler2D uSampler;\n\nvoid main(void)\n{\n gl_FragColor = texture2D(uSampler, vTextureCoord) * uColor;\n}\n";
  35865. /**
  35866. * Slightly opinionated default shader for PixiJS 2D objects.
  35867. * @class
  35868. * @memberof PIXI
  35869. * @extends PIXI.Shader
  35870. */
  35871. var MeshMaterial = /*@__PURE__*/(function (Shader) {
  35872. function MeshMaterial(uSampler, options)
  35873. {
  35874. var uniforms = {
  35875. uSampler: uSampler,
  35876. alpha: 1,
  35877. uTextureMatrix: Matrix.IDENTITY,
  35878. uColor: new Float32Array([1, 1, 1, 1]),
  35879. };
  35880. // Set defaults
  35881. options = Object.assign({
  35882. tint: 0xFFFFFF,
  35883. alpha: 1,
  35884. pluginName: 'batch',
  35885. }, options);
  35886. if (options.uniforms)
  35887. {
  35888. Object.assign(uniforms, options.uniforms);
  35889. }
  35890. Shader.call(this, options.program || Program.from(vertex$6, fragment$8), uniforms);
  35891. /**
  35892. * Only do update if tint or alpha changes.
  35893. * @member {boolean}
  35894. * @private
  35895. * @default false
  35896. */
  35897. this._colorDirty = false;
  35898. /**
  35899. * TextureMatrix instance for this Mesh, used to track Texture changes
  35900. *
  35901. * @member {PIXI.TextureMatrix}
  35902. * @readonly
  35903. */
  35904. this.uvMatrix = new TextureMatrix(uSampler);
  35905. /**
  35906. * `true` if shader can be batch with the renderer's batch system.
  35907. * @member {boolean}
  35908. * @default true
  35909. */
  35910. this.batchable = options.program === undefined;
  35911. /**
  35912. * Renderer plugin for batching
  35913. *
  35914. * @member {string}
  35915. * @default 'batch'
  35916. */
  35917. this.pluginName = options.pluginName;
  35918. this.tint = options.tint;
  35919. this.alpha = options.alpha;
  35920. }
  35921. if ( Shader ) { MeshMaterial.__proto__ = Shader; }
  35922. MeshMaterial.prototype = Object.create( Shader && Shader.prototype );
  35923. MeshMaterial.prototype.constructor = MeshMaterial;
  35924. var prototypeAccessors = { texture: { configurable: true },alpha: { configurable: true },tint: { configurable: true } };
  35925. /**
  35926. * Reference to the texture being rendered.
  35927. * @member {PIXI.Texture}
  35928. */
  35929. prototypeAccessors.texture.get = function ()
  35930. {
  35931. return this.uniforms.uSampler;
  35932. };
  35933. prototypeAccessors.texture.set = function (value)
  35934. {
  35935. if (this.uniforms.uSampler !== value)
  35936. {
  35937. this.uniforms.uSampler = value;
  35938. this.uvMatrix.texture = value;
  35939. }
  35940. };
  35941. /**
  35942. * This gets automatically set by the object using this.
  35943. *
  35944. * @default 1
  35945. * @member {number}
  35946. */
  35947. prototypeAccessors.alpha.set = function (value)
  35948. {
  35949. if (value === this._alpha) { return; }
  35950. this._alpha = value;
  35951. this._colorDirty = true;
  35952. };
  35953. prototypeAccessors.alpha.get = function ()
  35954. {
  35955. return this._alpha;
  35956. };
  35957. /**
  35958. * Multiply tint for the material.
  35959. * @member {number}
  35960. * @default 0xFFFFFF
  35961. */
  35962. prototypeAccessors.tint.set = function (value)
  35963. {
  35964. if (value === this._tint) { return; }
  35965. this._tint = value;
  35966. this._tintRGB = (value >> 16) + (value & 0xff00) + ((value & 0xff) << 16);
  35967. this._colorDirty = true;
  35968. };
  35969. prototypeAccessors.tint.get = function ()
  35970. {
  35971. return this._tint;
  35972. };
  35973. /**
  35974. * Gets called automatically by the Mesh. Intended to be overridden for custom
  35975. * MeshMaterial objects.
  35976. */
  35977. MeshMaterial.prototype.update = function update ()
  35978. {
  35979. if (this._colorDirty)
  35980. {
  35981. this._colorDirty = false;
  35982. var baseTexture = this.texture.baseTexture;
  35983. premultiplyTintToRgba(this._tint, this._alpha, this.uniforms.uColor, baseTexture.premultiplyAlpha);
  35984. }
  35985. if (this.uvMatrix.update())
  35986. {
  35987. this.uniforms.uTextureMatrix = this.uvMatrix.mapCoord;
  35988. }
  35989. };
  35990. Object.defineProperties( MeshMaterial.prototype, prototypeAccessors );
  35991. return MeshMaterial;
  35992. }(Shader));
  35993. /**
  35994. * Standard 2D geometry used in PixiJS.
  35995. *
  35996. * Geometry can be defined without passing in a style or data if required.
  35997. *
  35998. * ```js
  35999. * const geometry = new PIXI.Geometry();
  36000. *
  36001. * geometry.addAttribute('positions', [0, 0, 100, 0, 100, 100, 0, 100], 2);
  36002. * geometry.addAttribute('uvs', [0,0,1,0,1,1,0,1], 2);
  36003. * geometry.addIndex([0,1,2,1,3,2]);
  36004. *
  36005. * ```
  36006. * @class
  36007. * @memberof PIXI
  36008. * @extends PIXI.Geometry
  36009. */
  36010. var MeshGeometry = /*@__PURE__*/(function (Geometry) {
  36011. function MeshGeometry(vertices, uvs, index)
  36012. {
  36013. Geometry.call(this);
  36014. var verticesBuffer = new Buffer(vertices);
  36015. var uvsBuffer = new Buffer(uvs, true);
  36016. var indexBuffer = new Buffer(index, true, true);
  36017. this.addAttribute('aVertexPosition', verticesBuffer, 2, false, TYPES.FLOAT)
  36018. .addAttribute('aTextureCoord', uvsBuffer, 2, false, TYPES.FLOAT)
  36019. .addIndex(indexBuffer);
  36020. /**
  36021. * Dirty flag to limit update calls on Mesh. For example,
  36022. * limiting updates on a single Mesh instance with a shared Geometry
  36023. * within the render loop.
  36024. * @private
  36025. * @member {number}
  36026. * @default -1
  36027. */
  36028. this._updateId = -1;
  36029. }
  36030. if ( Geometry ) { MeshGeometry.__proto__ = Geometry; }
  36031. MeshGeometry.prototype = Object.create( Geometry && Geometry.prototype );
  36032. MeshGeometry.prototype.constructor = MeshGeometry;
  36033. var prototypeAccessors = { vertexDirtyId: { configurable: true } };
  36034. /**
  36035. * If the vertex position is updated.
  36036. * @member {number}
  36037. * @readonly
  36038. * @private
  36039. */
  36040. prototypeAccessors.vertexDirtyId.get = function ()
  36041. {
  36042. return this.buffers[0]._updateID;
  36043. };
  36044. Object.defineProperties( MeshGeometry.prototype, prototypeAccessors );
  36045. return MeshGeometry;
  36046. }(Geometry));
  36047. /*!
  36048. * @pixi/mesh-extras - v5.0.4
  36049. * Compiled Fri, 07 Jun 2019 17:17:49 UTC
  36050. *
  36051. * @pixi/mesh-extras is licensed under the MIT License.
  36052. * http://www.opensource.org/licenses/mit-license
  36053. */
  36054. var PlaneGeometry = /*@__PURE__*/(function (MeshGeometry) {
  36055. function PlaneGeometry(width, height, segWidth, segHeight)
  36056. {
  36057. if ( width === void 0 ) { width = 100; }
  36058. if ( height === void 0 ) { height = 100; }
  36059. if ( segWidth === void 0 ) { segWidth = 10; }
  36060. if ( segHeight === void 0 ) { segHeight = 10; }
  36061. MeshGeometry.call(this);
  36062. this.segWidth = segWidth;
  36063. this.segHeight = segHeight;
  36064. this.width = width;
  36065. this.height = height;
  36066. this.build();
  36067. }
  36068. if ( MeshGeometry ) { PlaneGeometry.__proto__ = MeshGeometry; }
  36069. PlaneGeometry.prototype = Object.create( MeshGeometry && MeshGeometry.prototype );
  36070. PlaneGeometry.prototype.constructor = PlaneGeometry;
  36071. /**
  36072. * Refreshes plane coordinates
  36073. * @private
  36074. */
  36075. PlaneGeometry.prototype.build = function build ()
  36076. {
  36077. var total = this.segWidth * this.segHeight;
  36078. var verts = [];
  36079. var uvs = [];
  36080. var indices = [];
  36081. var segmentsX = this.segWidth - 1;
  36082. var segmentsY = this.segHeight - 1;
  36083. var sizeX = (this.width) / segmentsX;
  36084. var sizeY = (this.height) / segmentsY;
  36085. for (var i = 0; i < total; i++)
  36086. {
  36087. var x = (i % this.segWidth);
  36088. var y = ((i / this.segWidth) | 0);
  36089. verts.push(x * sizeX, y * sizeY);
  36090. uvs.push(x / segmentsX, y / segmentsY);
  36091. }
  36092. var totalSub = segmentsX * segmentsY;
  36093. for (var i$1 = 0; i$1 < totalSub; i$1++)
  36094. {
  36095. var xpos = i$1 % segmentsX;
  36096. var ypos = (i$1 / segmentsX) | 0;
  36097. var value = (ypos * this.segWidth) + xpos;
  36098. var value2 = (ypos * this.segWidth) + xpos + 1;
  36099. var value3 = ((ypos + 1) * this.segWidth) + xpos;
  36100. var value4 = ((ypos + 1) * this.segWidth) + xpos + 1;
  36101. indices.push(value, value2, value3,
  36102. value2, value4, value3);
  36103. }
  36104. this.buffers[0].data = new Float32Array(verts);
  36105. this.buffers[1].data = new Float32Array(uvs);
  36106. this.indexBuffer.data = new Uint16Array(indices);
  36107. // ensure that the changes are uploaded
  36108. this.buffers[0].update();
  36109. this.buffers[1].update();
  36110. this.indexBuffer.update();
  36111. };
  36112. return PlaneGeometry;
  36113. }(MeshGeometry));
  36114. /**
  36115. * RopeGeometry allows you to draw a geometry across several points and then manipulate these points.
  36116. *
  36117. * ```js
  36118. * for (let i = 0; i < 20; i++) {
  36119. * points.push(new PIXI.Point(i * 50, 0));
  36120. * };
  36121. * const rope = new PIXI.RopeGeometry(100, points);
  36122. * ```
  36123. *
  36124. * @class
  36125. * @extends PIXI.MeshGeometry
  36126. * @memberof PIXI
  36127. *
  36128. */
  36129. var RopeGeometry = /*@__PURE__*/(function (MeshGeometry) {
  36130. function RopeGeometry(width, points)
  36131. {
  36132. if ( width === void 0 ) { width = 200; }
  36133. MeshGeometry.call(this, new Float32Array(points.length * 4),
  36134. new Float32Array(points.length * 4),
  36135. new Uint16Array((points.length - 1) * 6));
  36136. /**
  36137. * An array of points that determine the rope
  36138. * @member {PIXI.Point[]}
  36139. */
  36140. this.points = points;
  36141. /**
  36142. * The width (i.e., thickness) of the rope.
  36143. * @member {number}
  36144. * @readOnly
  36145. */
  36146. this.width = width;
  36147. this.build();
  36148. }
  36149. if ( MeshGeometry ) { RopeGeometry.__proto__ = MeshGeometry; }
  36150. RopeGeometry.prototype = Object.create( MeshGeometry && MeshGeometry.prototype );
  36151. RopeGeometry.prototype.constructor = RopeGeometry;
  36152. /**
  36153. * Refreshes Rope indices and uvs
  36154. * @private
  36155. */
  36156. RopeGeometry.prototype.build = function build ()
  36157. {
  36158. var points = this.points;
  36159. if (!points) { return; }
  36160. var vertexBuffer = this.getBuffer('aVertexPosition');
  36161. var uvBuffer = this.getBuffer('aTextureCoord');
  36162. var indexBuffer = this.getIndex();
  36163. // if too little points, or texture hasn't got UVs set yet just move on.
  36164. if (points.length < 1)
  36165. {
  36166. return;
  36167. }
  36168. // if the number of points has changed we will need to recreate the arraybuffers
  36169. if (vertexBuffer.data.length / 4 !== points.length)
  36170. {
  36171. vertexBuffer.data = new Float32Array(points.length * 4);
  36172. uvBuffer.data = new Float32Array(points.length * 4);
  36173. indexBuffer.data = new Uint16Array((points.length - 1) * 6);
  36174. }
  36175. var uvs = uvBuffer.data;
  36176. var indices = indexBuffer.data;
  36177. uvs[0] = 0;
  36178. uvs[1] = 0;
  36179. uvs[2] = 0;
  36180. uvs[3] = 1;
  36181. // indices[0] = 0;
  36182. // indices[1] = 1;
  36183. var total = points.length; // - 1;
  36184. for (var i = 0; i < total; i++)
  36185. {
  36186. // time to do some smart drawing!
  36187. var index = i * 4;
  36188. var amount = i / (total - 1);
  36189. uvs[index] = amount;
  36190. uvs[index + 1] = 0;
  36191. uvs[index + 2] = amount;
  36192. uvs[index + 3] = 1;
  36193. }
  36194. var indexCount = 0;
  36195. for (var i$1 = 0; i$1 < total - 1; i$1++)
  36196. {
  36197. var index$1 = i$1 * 2;
  36198. indices[indexCount++] = index$1;
  36199. indices[indexCount++] = index$1 + 1;
  36200. indices[indexCount++] = index$1 + 2;
  36201. indices[indexCount++] = index$1 + 2;
  36202. indices[indexCount++] = index$1 + 1;
  36203. indices[indexCount++] = index$1 + 3;
  36204. }
  36205. // ensure that the changes are uploaded
  36206. uvBuffer.update();
  36207. indexBuffer.update();
  36208. this.updateVertices();
  36209. };
  36210. /**
  36211. * refreshes vertices of Rope mesh
  36212. */
  36213. RopeGeometry.prototype.updateVertices = function updateVertices ()
  36214. {
  36215. var points = this.points;
  36216. if (points.length < 1)
  36217. {
  36218. return;
  36219. }
  36220. var lastPoint = points[0];
  36221. var nextPoint;
  36222. var perpX = 0;
  36223. var perpY = 0;
  36224. // this.count -= 0.2;
  36225. var vertices = this.buffers[0].data;
  36226. var total = points.length;
  36227. for (var i = 0; i < total; i++)
  36228. {
  36229. var point = points[i];
  36230. var index = i * 4;
  36231. if (i < points.length - 1)
  36232. {
  36233. nextPoint = points[i + 1];
  36234. }
  36235. else
  36236. {
  36237. nextPoint = point;
  36238. }
  36239. perpY = -(nextPoint.x - lastPoint.x);
  36240. perpX = nextPoint.y - lastPoint.y;
  36241. var perpLength = Math.sqrt((perpX * perpX) + (perpY * perpY));
  36242. var num = this.width / 2; // (20 + Math.abs(Math.sin((i + this.count) * 0.3) * 50) )* ratio;
  36243. perpX /= perpLength;
  36244. perpY /= perpLength;
  36245. perpX *= num;
  36246. perpY *= num;
  36247. vertices[index] = point.x + perpX;
  36248. vertices[index + 1] = point.y + perpY;
  36249. vertices[index + 2] = point.x - perpX;
  36250. vertices[index + 3] = point.y - perpY;
  36251. lastPoint = point;
  36252. }
  36253. this.buffers[0].update();
  36254. };
  36255. RopeGeometry.prototype.update = function update ()
  36256. {
  36257. this.updateVertices();
  36258. };
  36259. return RopeGeometry;
  36260. }(MeshGeometry));
  36261. /**
  36262. * The rope allows you to draw a texture across several points and then manipulate these points
  36263. *
  36264. *```js
  36265. * for (let i = 0; i < 20; i++) {
  36266. * points.push(new PIXI.Point(i * 50, 0));
  36267. * };
  36268. * let rope = new PIXI.Rope(PIXI.Texture.from("snake.png"), points);
  36269. * ```
  36270. *
  36271. * @class
  36272. * @extends PIXI.Mesh
  36273. * @memberof PIXI
  36274. *
  36275. */
  36276. var SimpleRope = /*@__PURE__*/(function (Mesh) {
  36277. function SimpleRope(texture, points)
  36278. {
  36279. var ropeGeometry = new RopeGeometry(texture.height, points);
  36280. var meshMaterial = new MeshMaterial(texture);
  36281. Mesh.call(this, ropeGeometry, meshMaterial);
  36282. /**
  36283. * re-calculate vertices by rope points each frame
  36284. *
  36285. * @member {boolean}
  36286. */
  36287. this.autoUpdate = true;
  36288. }
  36289. if ( Mesh ) { SimpleRope.__proto__ = Mesh; }
  36290. SimpleRope.prototype = Object.create( Mesh && Mesh.prototype );
  36291. SimpleRope.prototype.constructor = SimpleRope;
  36292. SimpleRope.prototype._render = function _render (renderer)
  36293. {
  36294. if (this.autoUpdate
  36295. || this.geometry.width !== this.shader.texture.height)
  36296. {
  36297. this.geometry.width = this.shader.texture.height;
  36298. this.geometry.update();
  36299. }
  36300. Mesh.prototype._render.call(this, renderer);
  36301. };
  36302. return SimpleRope;
  36303. }(Mesh));
  36304. /**
  36305. * The SimplePlane allows you to draw a texture across several points and then manipulate these points
  36306. *
  36307. *```js
  36308. * for (let i = 0; i < 20; i++) {
  36309. * points.push(new PIXI.Point(i * 50, 0));
  36310. * };
  36311. * let SimplePlane = new PIXI.SimplePlane(PIXI.Texture.from("snake.png"), points);
  36312. * ```
  36313. *
  36314. * @class
  36315. * @extends PIXI.Mesh
  36316. * @memberof PIXI
  36317. *
  36318. */
  36319. var SimplePlane = /*@__PURE__*/(function (Mesh) {
  36320. function SimplePlane(texture, verticesX, verticesY)
  36321. {
  36322. var planeGeometry = new PlaneGeometry(texture.width, texture.height, verticesX, verticesY);
  36323. var meshMaterial = new MeshMaterial(Texture.WHITE);
  36324. Mesh.call(this, planeGeometry, meshMaterial);
  36325. // lets call the setter to ensure all necessary updates are performed
  36326. this.texture = texture;
  36327. }
  36328. if ( Mesh ) { SimplePlane.__proto__ = Mesh; }
  36329. SimplePlane.prototype = Object.create( Mesh && Mesh.prototype );
  36330. SimplePlane.prototype.constructor = SimplePlane;
  36331. var prototypeAccessors = { texture: { configurable: true } };
  36332. /**
  36333. * Method used for overrides, to do something in case texture frame was changed.
  36334. * Meshes based on plane can override it and change more details based on texture.
  36335. */
  36336. SimplePlane.prototype.textureUpdated = function textureUpdated ()
  36337. {
  36338. this._textureID = this.shader.texture._updateID;
  36339. this.geometry.width = this.shader.texture.width;
  36340. this.geometry.height = this.shader.texture.height;
  36341. this.geometry.build();
  36342. };
  36343. prototypeAccessors.texture.set = function (value)
  36344. {
  36345. // Track texture same way sprite does.
  36346. // For generated meshes like NineSlicePlane it can change the geometry.
  36347. // Unfortunately, this method might not work if you directly change texture in material.
  36348. if (this.shader.texture === value)
  36349. {
  36350. return;
  36351. }
  36352. this.shader.texture = value;
  36353. this._textureID = -1;
  36354. if (value.baseTexture.valid)
  36355. {
  36356. this.textureUpdated();
  36357. }
  36358. else
  36359. {
  36360. value.once('update', this.textureUpdated, this);
  36361. }
  36362. };
  36363. prototypeAccessors.texture.get = function ()
  36364. {
  36365. return this.shader.texture;
  36366. };
  36367. SimplePlane.prototype._render = function _render (renderer)
  36368. {
  36369. if (this._textureID !== this.shader.texture._updateID)
  36370. {
  36371. this.textureUpdated();
  36372. }
  36373. Mesh.prototype._render.call(this, renderer);
  36374. };
  36375. Object.defineProperties( SimplePlane.prototype, prototypeAccessors );
  36376. return SimplePlane;
  36377. }(Mesh));
  36378. /**
  36379. * The Simple Mesh class mimics Mesh in PixiJS v4, providing easy-to-use constructor arguments.
  36380. * For more robust customization, use {@link PIXI.Mesh}.
  36381. *
  36382. * @class
  36383. * @extends PIXI.Mesh
  36384. * @memberof PIXI
  36385. */
  36386. var SimpleMesh = /*@__PURE__*/(function (Mesh) {
  36387. function SimpleMesh(texture, vertices, uvs, indices, drawMode)
  36388. {
  36389. if ( texture === void 0 ) { texture = Texture.EMPTY; }
  36390. var geometry = new MeshGeometry(vertices, uvs, indices);
  36391. geometry.getBuffer('aVertexPosition').static = false;
  36392. var meshMaterial = new MeshMaterial(texture);
  36393. Mesh.call(this, geometry, meshMaterial, null, drawMode);
  36394. /**
  36395. * upload vertices buffer each frame
  36396. * @member {boolean}
  36397. */
  36398. this.autoUpdate = true;
  36399. }
  36400. if ( Mesh ) { SimpleMesh.__proto__ = Mesh; }
  36401. SimpleMesh.prototype = Object.create( Mesh && Mesh.prototype );
  36402. SimpleMesh.prototype.constructor = SimpleMesh;
  36403. var prototypeAccessors = { vertices: { configurable: true } };
  36404. /**
  36405. * Collection of vertices data.
  36406. * @member {Float32Array}
  36407. */
  36408. prototypeAccessors.vertices.get = function ()
  36409. {
  36410. return this.geometry.getBuffer('aVertexPosition').data;
  36411. };
  36412. prototypeAccessors.vertices.set = function (value)
  36413. {
  36414. this.geometry.getBuffer('aVertexPosition').data = value;
  36415. };
  36416. SimpleMesh.prototype._render = function _render (renderer)
  36417. {
  36418. if (this.autoUpdate)
  36419. {
  36420. this.geometry.getBuffer('aVertexPosition').update();
  36421. }
  36422. Mesh.prototype._render.call(this, renderer);
  36423. };
  36424. Object.defineProperties( SimpleMesh.prototype, prototypeAccessors );
  36425. return SimpleMesh;
  36426. }(Mesh));
  36427. var DEFAULT_BORDER_SIZE = 10;
  36428. /**
  36429. * The NineSlicePlane allows you to stretch a texture using 9-slice scaling. The corners will remain unscaled (useful
  36430. * for buttons with rounded corners for example) and the other areas will be scaled horizontally and or vertically
  36431. *
  36432. *```js
  36433. * let Plane9 = new PIXI.NineSlicePlane(PIXI.Texture.from('BoxWithRoundedCorners.png'), 15, 15, 15, 15);
  36434. * ```
  36435. * <pre>
  36436. * A B
  36437. * +---+----------------------+---+
  36438. * C | 1 | 2 | 3 |
  36439. * +---+----------------------+---+
  36440. * | | | |
  36441. * | 4 | 5 | 6 |
  36442. * | | | |
  36443. * +---+----------------------+---+
  36444. * D | 7 | 8 | 9 |
  36445. * +---+----------------------+---+
  36446. * When changing this objects width and/or height:
  36447. * areas 1 3 7 and 9 will remain unscaled.
  36448. * areas 2 and 8 will be stretched horizontally
  36449. * areas 4 and 6 will be stretched vertically
  36450. * area 5 will be stretched both horizontally and vertically
  36451. * </pre>
  36452. *
  36453. * @class
  36454. * @extends PIXI.SimplePlane
  36455. * @memberof PIXI
  36456. *
  36457. */
  36458. var NineSlicePlane = /*@__PURE__*/(function (SimplePlane) {
  36459. function NineSlicePlane(texture, leftWidth, topHeight, rightWidth, bottomHeight)
  36460. {
  36461. SimplePlane.call(this, Texture.WHITE, 4, 4);
  36462. this._origWidth = texture.orig.width;
  36463. this._origHeight = texture.orig.height;
  36464. /**
  36465. * The width of the NineSlicePlane, setting this will actually modify the vertices and UV's of this plane
  36466. *
  36467. * @member {number}
  36468. * @override
  36469. */
  36470. this._width = this._origWidth;
  36471. /**
  36472. * The height of the NineSlicePlane, setting this will actually modify the vertices and UV's of this plane
  36473. *
  36474. * @member {number}
  36475. * @override
  36476. */
  36477. this._height = this._origHeight;
  36478. /**
  36479. * The width of the left column (a)
  36480. *
  36481. * @member {number}
  36482. * @private
  36483. */
  36484. this._leftWidth = typeof leftWidth !== 'undefined' ? leftWidth : DEFAULT_BORDER_SIZE;
  36485. /**
  36486. * The width of the right column (b)
  36487. *
  36488. * @member {number}
  36489. * @private
  36490. */
  36491. this._rightWidth = typeof rightWidth !== 'undefined' ? rightWidth : DEFAULT_BORDER_SIZE;
  36492. /**
  36493. * The height of the top row (c)
  36494. *
  36495. * @member {number}
  36496. * @private
  36497. */
  36498. this._topHeight = typeof topHeight !== 'undefined' ? topHeight : DEFAULT_BORDER_SIZE;
  36499. /**
  36500. * The height of the bottom row (d)
  36501. *
  36502. * @member {number}
  36503. * @private
  36504. */
  36505. this._bottomHeight = typeof bottomHeight !== 'undefined' ? bottomHeight : DEFAULT_BORDER_SIZE;
  36506. // lets call the setter to ensure all necessary updates are performed
  36507. this.texture = texture;
  36508. }
  36509. if ( SimplePlane ) { NineSlicePlane.__proto__ = SimplePlane; }
  36510. NineSlicePlane.prototype = Object.create( SimplePlane && SimplePlane.prototype );
  36511. NineSlicePlane.prototype.constructor = NineSlicePlane;
  36512. var prototypeAccessors = { vertices: { configurable: true },width: { configurable: true },height: { configurable: true },leftWidth: { configurable: true },rightWidth: { configurable: true },topHeight: { configurable: true },bottomHeight: { configurable: true } };
  36513. NineSlicePlane.prototype.textureUpdated = function textureUpdated ()
  36514. {
  36515. this._textureID = this.shader.texture._updateID;
  36516. this._refresh();
  36517. };
  36518. prototypeAccessors.vertices.get = function ()
  36519. {
  36520. return this.geometry.getBuffer('aVertexPosition').data;
  36521. };
  36522. prototypeAccessors.vertices.set = function (value)
  36523. {
  36524. this.geometry.getBuffer('aVertexPosition').data = value;
  36525. };
  36526. /**
  36527. * Updates the horizontal vertices.
  36528. *
  36529. */
  36530. NineSlicePlane.prototype.updateHorizontalVertices = function updateHorizontalVertices ()
  36531. {
  36532. var vertices = this.vertices;
  36533. var h = this._topHeight + this._bottomHeight;
  36534. var scale = this._height > h ? 1.0 : this._height / h;
  36535. vertices[9] = vertices[11] = vertices[13] = vertices[15] = this._topHeight * scale;
  36536. vertices[17] = vertices[19] = vertices[21] = vertices[23] = this._height - (this._bottomHeight * scale);
  36537. vertices[25] = vertices[27] = vertices[29] = vertices[31] = this._height;
  36538. };
  36539. /**
  36540. * Updates the vertical vertices.
  36541. *
  36542. */
  36543. NineSlicePlane.prototype.updateVerticalVertices = function updateVerticalVertices ()
  36544. {
  36545. var vertices = this.vertices;
  36546. var w = this._leftWidth + this._rightWidth;
  36547. var scale = this._width > w ? 1.0 : this._width / w;
  36548. vertices[2] = vertices[10] = vertices[18] = vertices[26] = this._leftWidth * scale;
  36549. vertices[4] = vertices[12] = vertices[20] = vertices[28] = this._width - (this._rightWidth * scale);
  36550. vertices[6] = vertices[14] = vertices[22] = vertices[30] = this._width;
  36551. };
  36552. /**
  36553. * The width of the NineSlicePlane, setting this will actually modify the vertices and UV's of this plane
  36554. *
  36555. * @member {number}
  36556. */
  36557. prototypeAccessors.width.get = function ()
  36558. {
  36559. return this._width;
  36560. };
  36561. prototypeAccessors.width.set = function (value) // eslint-disable-line require-jsdoc
  36562. {
  36563. this._width = value;
  36564. this._refresh();
  36565. };
  36566. /**
  36567. * The height of the NineSlicePlane, setting this will actually modify the vertices and UV's of this plane
  36568. *
  36569. * @member {number}
  36570. */
  36571. prototypeAccessors.height.get = function ()
  36572. {
  36573. return this._height;
  36574. };
  36575. prototypeAccessors.height.set = function (value) // eslint-disable-line require-jsdoc
  36576. {
  36577. this._height = value;
  36578. this._refresh();
  36579. };
  36580. /**
  36581. * The width of the left column
  36582. *
  36583. * @member {number}
  36584. */
  36585. prototypeAccessors.leftWidth.get = function ()
  36586. {
  36587. return this._leftWidth;
  36588. };
  36589. prototypeAccessors.leftWidth.set = function (value) // eslint-disable-line require-jsdoc
  36590. {
  36591. this._leftWidth = value;
  36592. this._refresh();
  36593. };
  36594. /**
  36595. * The width of the right column
  36596. *
  36597. * @member {number}
  36598. */
  36599. prototypeAccessors.rightWidth.get = function ()
  36600. {
  36601. return this._rightWidth;
  36602. };
  36603. prototypeAccessors.rightWidth.set = function (value) // eslint-disable-line require-jsdoc
  36604. {
  36605. this._rightWidth = value;
  36606. this._refresh();
  36607. };
  36608. /**
  36609. * The height of the top row
  36610. *
  36611. * @member {number}
  36612. */
  36613. prototypeAccessors.topHeight.get = function ()
  36614. {
  36615. return this._topHeight;
  36616. };
  36617. prototypeAccessors.topHeight.set = function (value) // eslint-disable-line require-jsdoc
  36618. {
  36619. this._topHeight = value;
  36620. this._refresh();
  36621. };
  36622. /**
  36623. * The height of the bottom row
  36624. *
  36625. * @member {number}
  36626. */
  36627. prototypeAccessors.bottomHeight.get = function ()
  36628. {
  36629. return this._bottomHeight;
  36630. };
  36631. prototypeAccessors.bottomHeight.set = function (value) // eslint-disable-line require-jsdoc
  36632. {
  36633. this._bottomHeight = value;
  36634. this._refresh();
  36635. };
  36636. /**
  36637. * Refreshes NineSlicePlane coords. All of them.
  36638. */
  36639. NineSlicePlane.prototype._refresh = function _refresh ()
  36640. {
  36641. var texture = this.texture;
  36642. var uvs = this.geometry.buffers[1].data;
  36643. this._origWidth = texture.orig.width;
  36644. this._origHeight = texture.orig.height;
  36645. var _uvw = 1.0 / this._origWidth;
  36646. var _uvh = 1.0 / this._origHeight;
  36647. uvs[0] = uvs[8] = uvs[16] = uvs[24] = 0;
  36648. uvs[1] = uvs[3] = uvs[5] = uvs[7] = 0;
  36649. uvs[6] = uvs[14] = uvs[22] = uvs[30] = 1;
  36650. uvs[25] = uvs[27] = uvs[29] = uvs[31] = 1;
  36651. uvs[2] = uvs[10] = uvs[18] = uvs[26] = _uvw * this._leftWidth;
  36652. uvs[4] = uvs[12] = uvs[20] = uvs[28] = 1 - (_uvw * this._rightWidth);
  36653. uvs[9] = uvs[11] = uvs[13] = uvs[15] = _uvh * this._topHeight;
  36654. uvs[17] = uvs[19] = uvs[21] = uvs[23] = 1 - (_uvh * this._bottomHeight);
  36655. this.updateHorizontalVertices();
  36656. this.updateVerticalVertices();
  36657. this.geometry.buffers[0].update();
  36658. this.geometry.buffers[1].update();
  36659. };
  36660. Object.defineProperties( NineSlicePlane.prototype, prototypeAccessors );
  36661. return NineSlicePlane;
  36662. }(SimplePlane));
  36663. /*!
  36664. * @pixi/sprite-animated - v5.0.4
  36665. * Compiled Fri, 07 Jun 2019 17:17:49 UTC
  36666. *
  36667. * @pixi/sprite-animated is licensed under the MIT License.
  36668. * http://www.opensource.org/licenses/mit-license
  36669. */
  36670. /**
  36671. * An AnimatedSprite is a simple way to display an animation depicted by a list of textures.
  36672. *
  36673. * ```js
  36674. * let alienImages = ["image_sequence_01.png","image_sequence_02.png","image_sequence_03.png","image_sequence_04.png"];
  36675. * let textureArray = [];
  36676. *
  36677. * for (let i=0; i < 4; i++)
  36678. * {
  36679. * let texture = PIXI.Texture.from(alienImages[i]);
  36680. * textureArray.push(texture);
  36681. * };
  36682. *
  36683. * let animatedSprite = new PIXI.AnimatedSprite(textureArray);
  36684. * ```
  36685. *
  36686. * The more efficient and simpler way to create an animated sprite is using a {@link PIXI.Spritesheet}
  36687. * containing the animation definitions:
  36688. *
  36689. * ```js
  36690. * PIXI.Loader.shared.add("assets/spritesheet.json").load(setup);
  36691. *
  36692. * function setup() {
  36693. * let sheet = PIXI.Loader.shared.resources["assets/spritesheet.json"].spritesheet;
  36694. * animatedSprite = new PIXI.AnimatedSprite(sheet.animations["image_sequence"]);
  36695. * ...
  36696. * }
  36697. * ```
  36698. *
  36699. * @class
  36700. * @extends PIXI.Sprite
  36701. * @memberof PIXI
  36702. */
  36703. var AnimatedSprite = /*@__PURE__*/(function (Sprite) {
  36704. function AnimatedSprite(textures, autoUpdate)
  36705. {
  36706. Sprite.call(this, textures[0] instanceof Texture ? textures[0] : textures[0].texture);
  36707. /**
  36708. * @type {PIXI.Texture[]}
  36709. * @private
  36710. */
  36711. this._textures = null;
  36712. /**
  36713. * @type {number[]}
  36714. * @private
  36715. */
  36716. this._durations = null;
  36717. this.textures = textures;
  36718. /**
  36719. * `true` uses PIXI.Ticker.shared to auto update animation time.
  36720. * @type {boolean}
  36721. * @default true
  36722. * @private
  36723. */
  36724. this._autoUpdate = autoUpdate !== false;
  36725. /**
  36726. * The speed that the AnimatedSprite will play at. Higher is faster, lower is slower.
  36727. *
  36728. * @member {number}
  36729. * @default 1
  36730. */
  36731. this.animationSpeed = 1;
  36732. /**
  36733. * Whether or not the animate sprite repeats after playing.
  36734. *
  36735. * @member {boolean}
  36736. * @default true
  36737. */
  36738. this.loop = true;
  36739. /**
  36740. * Update anchor to [Texture's defaultAnchor]{@link PIXI.Texture#defaultAnchor} when frame changes.
  36741. *
  36742. * Useful with [sprite sheet animations]{@link PIXI.Spritesheet#animations} created with tools.
  36743. * Changing anchor for each frame allows to pin sprite origin to certain moving feature
  36744. * of the frame (e.g. left foot).
  36745. *
  36746. * Note: Enabling this will override any previously set `anchor` on each frame change.
  36747. *
  36748. * @member {boolean}
  36749. * @default false
  36750. */
  36751. this.updateAnchor = false;
  36752. /**
  36753. * Function to call when an AnimatedSprite finishes playing.
  36754. *
  36755. * @member {Function}
  36756. */
  36757. this.onComplete = null;
  36758. /**
  36759. * Function to call when an AnimatedSprite changes which texture is being rendered.
  36760. *
  36761. * @member {Function}
  36762. */
  36763. this.onFrameChange = null;
  36764. /**
  36765. * Function to call when `loop` is true, and an AnimatedSprite is played and loops around to start again.
  36766. *
  36767. * @member {Function}
  36768. */
  36769. this.onLoop = null;
  36770. /**
  36771. * Elapsed time since animation has been started, used internally to display current texture.
  36772. *
  36773. * @member {number}
  36774. * @private
  36775. */
  36776. this._currentTime = 0;
  36777. /**
  36778. * Indicates if the AnimatedSprite is currently playing.
  36779. *
  36780. * @member {boolean}
  36781. * @readonly
  36782. */
  36783. this.playing = false;
  36784. }
  36785. if ( Sprite ) { AnimatedSprite.__proto__ = Sprite; }
  36786. AnimatedSprite.prototype = Object.create( Sprite && Sprite.prototype );
  36787. AnimatedSprite.prototype.constructor = AnimatedSprite;
  36788. var prototypeAccessors = { totalFrames: { configurable: true },textures: { configurable: true },currentFrame: { configurable: true } };
  36789. /**
  36790. * Stops the AnimatedSprite.
  36791. *
  36792. */
  36793. AnimatedSprite.prototype.stop = function stop ()
  36794. {
  36795. if (!this.playing)
  36796. {
  36797. return;
  36798. }
  36799. this.playing = false;
  36800. if (this._autoUpdate)
  36801. {
  36802. Ticker.shared.remove(this.update, this);
  36803. }
  36804. };
  36805. /**
  36806. * Plays the AnimatedSprite.
  36807. *
  36808. */
  36809. AnimatedSprite.prototype.play = function play ()
  36810. {
  36811. if (this.playing)
  36812. {
  36813. return;
  36814. }
  36815. this.playing = true;
  36816. if (this._autoUpdate)
  36817. {
  36818. Ticker.shared.add(this.update, this, UPDATE_PRIORITY.HIGH);
  36819. }
  36820. };
  36821. /**
  36822. * Stops the AnimatedSprite and goes to a specific frame.
  36823. *
  36824. * @param {number} frameNumber - Frame index to stop at.
  36825. */
  36826. AnimatedSprite.prototype.gotoAndStop = function gotoAndStop (frameNumber)
  36827. {
  36828. this.stop();
  36829. var previousFrame = this.currentFrame;
  36830. this._currentTime = frameNumber;
  36831. if (previousFrame !== this.currentFrame)
  36832. {
  36833. this.updateTexture();
  36834. }
  36835. };
  36836. /**
  36837. * Goes to a specific frame and begins playing the AnimatedSprite.
  36838. *
  36839. * @param {number} frameNumber - Frame index to start at.
  36840. */
  36841. AnimatedSprite.prototype.gotoAndPlay = function gotoAndPlay (frameNumber)
  36842. {
  36843. var previousFrame = this.currentFrame;
  36844. this._currentTime = frameNumber;
  36845. if (previousFrame !== this.currentFrame)
  36846. {
  36847. this.updateTexture();
  36848. }
  36849. this.play();
  36850. };
  36851. /**
  36852. * Updates the object transform for rendering.
  36853. *
  36854. * @private
  36855. * @param {number} deltaTime - Time since last tick.
  36856. */
  36857. AnimatedSprite.prototype.update = function update (deltaTime)
  36858. {
  36859. var elapsed = this.animationSpeed * deltaTime;
  36860. var previousFrame = this.currentFrame;
  36861. if (this._durations !== null)
  36862. {
  36863. var lag = this._currentTime % 1 * this._durations[this.currentFrame];
  36864. lag += elapsed / 60 * 1000;
  36865. while (lag < 0)
  36866. {
  36867. this._currentTime--;
  36868. lag += this._durations[this.currentFrame];
  36869. }
  36870. var sign = Math.sign(this.animationSpeed * deltaTime);
  36871. this._currentTime = Math.floor(this._currentTime);
  36872. while (lag >= this._durations[this.currentFrame])
  36873. {
  36874. lag -= this._durations[this.currentFrame] * sign;
  36875. this._currentTime += sign;
  36876. }
  36877. this._currentTime += lag / this._durations[this.currentFrame];
  36878. }
  36879. else
  36880. {
  36881. this._currentTime += elapsed;
  36882. }
  36883. if (this._currentTime < 0 && !this.loop)
  36884. {
  36885. this.gotoAndStop(0);
  36886. if (this.onComplete)
  36887. {
  36888. this.onComplete();
  36889. }
  36890. }
  36891. else if (this._currentTime >= this._textures.length && !this.loop)
  36892. {
  36893. this.gotoAndStop(this._textures.length - 1);
  36894. if (this.onComplete)
  36895. {
  36896. this.onComplete();
  36897. }
  36898. }
  36899. else if (previousFrame !== this.currentFrame)
  36900. {
  36901. if (this.loop && this.onLoop)
  36902. {
  36903. if (this.animationSpeed > 0 && this.currentFrame < previousFrame)
  36904. {
  36905. this.onLoop();
  36906. }
  36907. else if (this.animationSpeed < 0 && this.currentFrame > previousFrame)
  36908. {
  36909. this.onLoop();
  36910. }
  36911. }
  36912. this.updateTexture();
  36913. }
  36914. };
  36915. /**
  36916. * Updates the displayed texture to match the current frame index.
  36917. *
  36918. * @private
  36919. */
  36920. AnimatedSprite.prototype.updateTexture = function updateTexture ()
  36921. {
  36922. this._texture = this._textures[this.currentFrame];
  36923. this._textureID = -1;
  36924. this._textureTrimmedID = -1;
  36925. this._cachedTint = 0xFFFFFF;
  36926. this.uvs = this._texture._uvs.uvsFloat32;
  36927. if (this.updateAnchor)
  36928. {
  36929. this._anchor.copy(this._texture.defaultAnchor);
  36930. }
  36931. if (this.onFrameChange)
  36932. {
  36933. this.onFrameChange(this.currentFrame);
  36934. }
  36935. };
  36936. /**
  36937. * Stops the AnimatedSprite and destroys it.
  36938. *
  36939. * @param {object|boolean} [options] - Options parameter. A boolean will act as if all options
  36940. * have been set to that value.
  36941. * @param {boolean} [options.children=false] - If set to true, all the children will have their destroy
  36942. * method called as well. 'options' will be passed on to those calls.
  36943. * @param {boolean} [options.texture=false] - Should it destroy the current texture of the sprite as well.
  36944. * @param {boolean} [options.baseTexture=false] - Should it destroy the base texture of the sprite as well.
  36945. */
  36946. AnimatedSprite.prototype.destroy = function destroy (options)
  36947. {
  36948. this.stop();
  36949. Sprite.prototype.destroy.call(this, options);
  36950. this.onComplete = null;
  36951. this.onFrameChange = null;
  36952. this.onLoop = null;
  36953. };
  36954. /**
  36955. * A short hand way of creating an AnimatedSprite from an array of frame ids.
  36956. *
  36957. * @static
  36958. * @param {string[]} frames - The array of frames ids the AnimatedSprite will use as its texture frames.
  36959. * @return {AnimatedSprite} The new animated sprite with the specified frames.
  36960. */
  36961. AnimatedSprite.fromFrames = function fromFrames (frames)
  36962. {
  36963. var textures = [];
  36964. for (var i = 0; i < frames.length; ++i)
  36965. {
  36966. textures.push(Texture.from(frames[i]));
  36967. }
  36968. return new AnimatedSprite(textures);
  36969. };
  36970. /**
  36971. * A short hand way of creating an AnimatedSprite from an array of image ids.
  36972. *
  36973. * @static
  36974. * @param {string[]} images - The array of image urls the AnimatedSprite will use as its texture frames.
  36975. * @return {AnimatedSprite} The new animate sprite with the specified images as frames.
  36976. */
  36977. AnimatedSprite.fromImages = function fromImages (images)
  36978. {
  36979. var textures = [];
  36980. for (var i = 0; i < images.length; ++i)
  36981. {
  36982. textures.push(Texture.from(images[i]));
  36983. }
  36984. return new AnimatedSprite(textures);
  36985. };
  36986. /**
  36987. * The total number of frames in the AnimatedSprite. This is the same as number of textures
  36988. * assigned to the AnimatedSprite.
  36989. *
  36990. * @readonly
  36991. * @member {number}
  36992. * @default 0
  36993. */
  36994. prototypeAccessors.totalFrames.get = function ()
  36995. {
  36996. return this._textures.length;
  36997. };
  36998. /**
  36999. * The array of textures used for this AnimatedSprite.
  37000. *
  37001. * @member {PIXI.Texture[]}
  37002. */
  37003. prototypeAccessors.textures.get = function ()
  37004. {
  37005. return this._textures;
  37006. };
  37007. prototypeAccessors.textures.set = function (value) // eslint-disable-line require-jsdoc
  37008. {
  37009. if (value[0] instanceof Texture)
  37010. {
  37011. this._textures = value;
  37012. this._durations = null;
  37013. }
  37014. else
  37015. {
  37016. this._textures = [];
  37017. this._durations = [];
  37018. for (var i = 0; i < value.length; i++)
  37019. {
  37020. this._textures.push(value[i].texture);
  37021. this._durations.push(value[i].time);
  37022. }
  37023. }
  37024. this.gotoAndStop(0);
  37025. this.updateTexture();
  37026. };
  37027. /**
  37028. * The AnimatedSprites current frame index.
  37029. *
  37030. * @member {number}
  37031. * @readonly
  37032. */
  37033. prototypeAccessors.currentFrame.get = function ()
  37034. {
  37035. var currentFrame = Math.floor(this._currentTime) % this._textures.length;
  37036. if (currentFrame < 0)
  37037. {
  37038. currentFrame += this._textures.length;
  37039. }
  37040. return currentFrame;
  37041. };
  37042. Object.defineProperties( AnimatedSprite.prototype, prototypeAccessors );
  37043. return AnimatedSprite;
  37044. }(Sprite));
  37045. // Install renderer plugins
  37046. Renderer.registerPlugin('accessibility', AccessibilityManager);
  37047. Renderer.registerPlugin('extract', Extract);
  37048. Renderer.registerPlugin('interaction', InteractionManager);
  37049. Renderer.registerPlugin('particle', ParticleRenderer);
  37050. Renderer.registerPlugin('prepare', Prepare);
  37051. Renderer.registerPlugin('batch', BatchRenderer);
  37052. Renderer.registerPlugin('tilingSprite', TilingSpriteRenderer);
  37053. Loader$2.registerPlugin(BitmapFontLoader);
  37054. Loader$2.registerPlugin(SpritesheetLoader);
  37055. Application.registerPlugin(TickerPlugin);
  37056. Application.registerPlugin(AppLoaderPlugin);
  37057. /**
  37058. * String of the current PIXI version.
  37059. *
  37060. * @static
  37061. * @constant
  37062. * @memberof PIXI
  37063. * @name VERSION
  37064. * @type {string}
  37065. */
  37066. var VERSION$1 = '5.0.4';
  37067. /**
  37068. * @namespace PIXI
  37069. */
  37070. /**
  37071. * This namespace contains WebGL-only display filters that can be applied
  37072. * to DisplayObjects using the {@link PIXI.DisplayObject#filters filters} property.
  37073. *
  37074. * Since PixiJS only had a handful of built-in filters, additional filters
  37075. * can be downloaded {@link https://github.com/pixijs/pixi-filters here} from the
  37076. * PixiJS Filters repository.
  37077. *
  37078. * All filters must extend {@link PIXI.Filter}.
  37079. *
  37080. * @example
  37081. * // Create a new application
  37082. * const app = new PIXI.Application();
  37083. *
  37084. * // Draw a green rectangle
  37085. * const rect = new PIXI.Graphics()
  37086. * .beginFill(0x00ff00)
  37087. * .drawRect(40, 40, 200, 200);
  37088. *
  37089. * // Add a blur filter
  37090. * rect.filters = [new PIXI.filters.BlurFilter()];
  37091. *
  37092. * // Display rectangle
  37093. * app.stage.addChild(rect);
  37094. * document.body.appendChild(app.view);
  37095. * @namespace PIXI.filters
  37096. */
  37097. var filters = {
  37098. AlphaFilter: AlphaFilter,
  37099. BlurFilter: BlurFilter,
  37100. BlurFilterPass: BlurFilterPass,
  37101. ColorMatrixFilter: ColorMatrixFilter,
  37102. DisplacementFilter: DisplacementFilter,
  37103. FXAAFilter: FXAAFilter,
  37104. NoiseFilter: NoiseFilter,
  37105. };
  37106. exports.AbstractRenderer = AbstractRenderer;
  37107. exports.AnimatedSprite = AnimatedSprite;
  37108. exports.AppLoaderPlugin = AppLoaderPlugin;
  37109. exports.Application = Application;
  37110. exports.Attribute = Attribute;
  37111. exports.BLEND_MODES = BLEND_MODES;
  37112. exports.BaseRenderTexture = BaseRenderTexture;
  37113. exports.BaseTexture = BaseTexture;
  37114. exports.BatchDrawCall = BatchDrawCall;
  37115. exports.BatchGeometry = BatchGeometry;
  37116. exports.BatchRenderer = BatchRenderer;
  37117. exports.BitmapFontLoader = BitmapFontLoader;
  37118. exports.BitmapText = BitmapText;
  37119. exports.Bounds = Bounds;
  37120. exports.Buffer = Buffer;
  37121. exports.Circle = Circle;
  37122. exports.Container = Container;
  37123. exports.CubeTexture = CubeTexture;
  37124. exports.DEG_TO_RAD = DEG_TO_RAD;
  37125. exports.DRAW_MODES = DRAW_MODES;
  37126. exports.DisplayObject = DisplayObject;
  37127. exports.ENV = ENV;
  37128. exports.Ellipse = Ellipse;
  37129. exports.FORMATS = FORMATS;
  37130. exports.FillStyle = FillStyle;
  37131. exports.Filter = Filter;
  37132. exports.Framebuffer = Framebuffer;
  37133. exports.GC_MODES = GC_MODES;
  37134. exports.GLProgram = GLProgram;
  37135. exports.GLTexture = BaseTexture;
  37136. exports.GRAPHICS_CURVES = GRAPHICS_CURVES;
  37137. exports.Geometry = Geometry;
  37138. exports.Graphics = Graphics;
  37139. exports.GraphicsData = GraphicsData;
  37140. exports.GraphicsGeometry = GraphicsGeometry;
  37141. exports.GroupD8 = GroupD8;
  37142. exports.LineStyle = LineStyle;
  37143. exports.Loader = Loader$2;
  37144. exports.LoaderResource = LoaderResource;
  37145. exports.MIPMAP_MODES = MIPMAP_MODES;
  37146. exports.Matrix = Matrix;
  37147. exports.Mesh = Mesh;
  37148. exports.MeshBatchUvs = MeshBatchUvs;
  37149. exports.MeshGeometry = MeshGeometry;
  37150. exports.MeshMaterial = MeshMaterial;
  37151. exports.NineSlicePlane = NineSlicePlane;
  37152. exports.ObjectRenderer = ObjectRenderer;
  37153. exports.ObservablePoint = ObservablePoint;
  37154. exports.PI_2 = PI_2;
  37155. exports.PRECISION = PRECISION;
  37156. exports.ParticleContainer = ParticleContainer;
  37157. exports.ParticleRenderer = ParticleRenderer;
  37158. exports.PlaneGeometry = PlaneGeometry;
  37159. exports.Point = Point;
  37160. exports.Polygon = Polygon;
  37161. exports.Program = Program;
  37162. exports.Quad = Quad;
  37163. exports.QuadUv = QuadUv;
  37164. exports.RAD_TO_DEG = RAD_TO_DEG;
  37165. exports.RENDERER_TYPE = RENDERER_TYPE;
  37166. exports.Rectangle = Rectangle;
  37167. exports.RenderTexture = RenderTexture;
  37168. exports.Renderer = Renderer;
  37169. exports.RopeGeometry = RopeGeometry;
  37170. exports.RoundedRectangle = RoundedRectangle;
  37171. exports.Runner = Runner;
  37172. exports.SCALE_MODES = SCALE_MODES;
  37173. exports.SHAPES = SHAPES;
  37174. exports.Shader = Shader;
  37175. exports.SimpleMesh = SimpleMesh;
  37176. exports.SimplePlane = SimplePlane;
  37177. exports.SimpleRope = SimpleRope;
  37178. exports.Sprite = Sprite;
  37179. exports.SpriteMaskFilter = SpriteMaskFilter;
  37180. exports.Spritesheet = Spritesheet;
  37181. exports.SpritesheetLoader = SpritesheetLoader;
  37182. exports.State = State;
  37183. exports.System = System;
  37184. exports.TARGETS = TARGETS;
  37185. exports.TEXT_GRADIENT = TEXT_GRADIENT;
  37186. exports.TYPES = TYPES;
  37187. exports.Text = Text;
  37188. exports.TextMetrics = TextMetrics;
  37189. exports.TextStyle = TextStyle;
  37190. exports.Texture = Texture;
  37191. exports.TextureLoader = TextureLoader;
  37192. exports.TextureMatrix = TextureMatrix;
  37193. exports.TextureUvs = TextureUvs;
  37194. exports.Ticker = Ticker;
  37195. exports.TickerPlugin = TickerPlugin;
  37196. exports.TilingSprite = TilingSprite;
  37197. exports.TilingSpriteRenderer = TilingSpriteRenderer;
  37198. exports.Transform = Transform;
  37199. exports.UPDATE_PRIORITY = UPDATE_PRIORITY;
  37200. exports.UniformGroup = UniformGroup;
  37201. exports.VERSION = VERSION$1;
  37202. exports.WRAP_MODES = WRAP_MODES;
  37203. exports.accessibility = accessibility_es;
  37204. exports.autoDetectRenderer = autoDetectRenderer;
  37205. exports.checkMaxIfStatementsInShader = checkMaxIfStatementsInShader;
  37206. exports.defaultFilterVertex = defaultFilter;
  37207. exports.defaultVertex = _default;
  37208. exports.extract = extract_es;
  37209. exports.filters = filters;
  37210. exports.generateMultiTextureShader = generateMultiTextureShader;
  37211. exports.interaction = interaction_es;
  37212. exports.isMobile = isMobile_min;
  37213. exports.prepare = prepare_es;
  37214. exports.resources = index;
  37215. exports.settings = settings;
  37216. exports.systems = systems;
  37217. exports.useDeprecated = useDeprecated;
  37218. exports.utils = utils_es;
  37219. return exports;
  37220. }({}));
  37221. PIXI.useDeprecated();
  37222. //# sourceMappingURL=pixi.js.map