1
0

phaser.js 3.0 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328983299833098331983329833398334983359833698337983389833998340983419834298343983449834598346983479834898349983509835198352983539835498355983569835798358983599836098361983629836398364983659836698367983689836998370983719837298373983749837598376983779837898379983809838198382983839838498385983869838798388983899839098391983929839398394983959839698397983989839998400984019840298403984049840598406984079840898409984109841198412984139841498415984169841798418984199842098421984229842398424984259842698427984289842998430984319843298433984349843598436984379843898439984409844198442984439844498445984469844798448984499845098451984529845398454984559845698457984589845998460984619846298463984649846598466984679846898469984709847198472984739847498475984769847798478984799848098481984829848398484984859848698487984889848998490984919849298493984949849598496984979849898499985009850198502985039850498505985069850798508985099851098511985129851398514985159851698517985189851998520985219852298523985249852598526985279852898529985309853198532985339853498535985369853798538985399854098541985429854398544985459854698547985489854998550985519855298553985549855598556985579855898559985609856198562985639856498565985669856798568985699857098571985729857398574985759857698577985789857998580985819858298583985849858598586985879858898589985909859198592985939859498595985969859798598985999860098601986029860398604986059860698607986089860998610986119861298613986149861598616986179861898619986209862198622986239862498625986269862798628986299863098631986329863398634986359863698637986389863998640986419864298643986449864598646986479864898649986509865198652986539865498655986569865798658986599866098661986629866398664986659866698667986689866998670986719867298673986749867598676986779867898679986809868198682986839868498685986869868798688986899869098691986929869398694986959869698697986989869998700987019870298703987049870598706987079870898709987109871198712987139871498715987169871798718987199872098721987229872398724987259872698727987289872998730987319873298733987349873598736987379873898739987409874198742987439874498745987469874798748987499875098751987529875398754987559875698757987589875998760987619876298763987649876598766987679876898769987709877198772987739877498775987769877798778987799878098781987829878398784987859878698787987889878998790987919879298793987949879598796987979879898799988009880198802988039880498805988069880798808988099881098811988129881398814988159881698817988189881998820988219882298823988249882598826988279882898829988309883198832988339883498835988369883798838988399884098841988429884398844988459884698847988489884998850988519885298853988549885598856988579885898859988609886198862988639886498865988669886798868988699887098871988729887398874988759887698877988789887998880988819888298883988849888598886988879888898889988909889198892988939889498895988969889798898988999890098901989029890398904989059890698907989089890998910989119891298913989149891598916989179891898919989209892198922989239892498925989269892798928989299893098931989329893398934989359893698937989389893998940989419894298943989449894598946989479894898949989509895198952989539895498955989569895798958989599896098961989629896398964989659896698967989689896998970989719897298973989749897598976989779897898979989809898198982989839898498985989869898798988989899899098991989929899398994989959899698997989989899999000990019900299003990049900599006990079900899009990109901199012990139901499015990169901799018990199902099021990229902399024990259902699027990289902999030990319903299033990349903599036990379903899039990409904199042990439904499045990469904799048990499905099051990529905399054990559905699057990589905999060990619906299063990649906599066990679906899069990709907199072990739907499075990769907799078990799908099081990829908399084990859908699087990889908999090990919909299093990949909599096990979909899099991009910199102991039910499105991069910799108991099911099111991129911399114991159911699117991189911999120991219912299123991249912599126991279912899129991309913199132991339913499135991369913799138991399914099141991429914399144991459914699147991489914999150991519915299153991549915599156991579915899159991609916199162991639916499165991669916799168991699917099171991729917399174991759917699177991789917999180991819918299183991849918599186991879918899189991909919199192991939919499195991969919799198991999920099201992029920399204992059920699207992089920999210992119921299213992149921599216992179921899219992209922199222992239922499225992269922799228992299923099231992329923399234992359923699237992389923999240992419924299243992449924599246992479924899249992509925199252992539925499255992569925799258992599926099261992629926399264992659926699267992689926999270992719927299273992749927599276992779927899279992809928199282992839928499285992869928799288992899929099291992929929399294992959929699297992989929999300993019930299303993049930599306993079930899309993109931199312993139931499315993169931799318993199932099321993229932399324993259932699327993289932999330993319933299333993349933599336993379933899339993409934199342993439934499345993469934799348993499935099351993529935399354993559935699357993589935999360993619936299363993649936599366993679936899369993709937199372993739937499375993769937799378993799938099381993829938399384993859938699387993889938999390993919939299393993949939599396993979939899399994009940199402994039940499405994069940799408994099941099411994129941399414994159941699417994189941999420994219942299423994249942599426994279942899429994309943199432994339943499435994369943799438994399944099441994429944399444994459944699447994489944999450994519945299453994549945599456994579945899459994609946199462994639946499465994669946799468994699947099471994729947399474994759947699477994789947999480994819948299483994849948599486994879948899489994909949199492994939949499495994969949799498994999950099501995029950399504995059950699507995089950999510995119951299513995149951599516995179951899519995209952199522995239952499525995269952799528995299953099531995329953399534995359953699537995389953999540995419954299543995449954599546995479954899549995509955199552995539955499555995569955799558995599956099561995629956399564995659956699567995689956999570995719957299573995749957599576995779957899579995809958199582995839958499585995869958799588995899959099591995929959399594995959959699597995989959999600996019960299603996049960599606996079960899609996109961199612996139961499615996169961799618996199962099621996229962399624996259962699627996289962999630996319963299633996349963599636996379963899639996409964199642996439964499645996469964799648996499965099651996529965399654996559965699657996589965999660996619966299663996649966599666996679966899669996709967199672996739967499675996769967799678996799968099681996829968399684996859968699687996889968999690996919969299693996949969599696996979969899699997009970199702997039970499705997069970799708997099971099711997129971399714997159971699717997189971999720997219972299723997249972599726997279972899729997309973199732997339973499735997369973799738997399974099741997429974399744997459974699747997489974999750997519975299753997549975599756997579975899759997609976199762997639976499765997669976799768997699977099771997729977399774997759977699777997789977999780997819978299783997849978599786997879978899789997909979199792997939979499795997969979799798997999980099801998029980399804998059980699807998089980999810998119981299813998149981599816998179981899819998209982199822998239982499825998269982799828998299983099831998329983399834998359983699837998389983999840998419984299843998449984599846998479984899849998509985199852998539985499855998569985799858998599986099861998629986399864998659986699867998689986999870998719987299873998749987599876998779987899879998809988199882998839988499885998869988799888998899989099891998929989399894998959989699897998989989999900999019990299903999049990599906999079990899909999109991199912999139991499915999169991799918999199992099921999229992399924999259992699927999289992999930999319993299933999349993599936999379993899939999409994199942999439994499945999469994799948999499995099951999529995399954999559995699957999589995999960999619996299963999649996599966999679996899969999709997199972999739997499975999769997799978999799998099981999829998399984999859998699987999889998999990999919999299993999949999599996999979999899999100000100001100002100003100004100005100006100007100008100009100010100011100012100013100014100015100016100017100018100019100020100021100022100023100024100025100026100027100028100029100030100031100032100033100034100035100036100037100038100039100040100041100042100043100044100045100046100047100048100049100050100051100052100053100054100055100056100057100058100059100060100061100062100063100064100065100066100067100068100069100070100071100072100073100074100075100076100077100078100079100080100081100082100083100084100085100086100087100088100089100090100091100092100093100094100095100096100097100098100099100100100101100102100103100104100105100106100107100108100109100110100111100112100113100114100115100116100117100118100119100120100121100122100123100124100125100126100127100128100129100130100131100132100133100134100135100136100137100138100139100140100141100142100143100144100145100146100147100148100149100150100151100152100153100154100155100156100157100158100159100160100161100162100163100164100165100166100167100168100169100170100171100172100173100174100175100176100177100178100179100180100181100182100183100184100185100186100187100188100189100190100191100192100193100194100195100196100197100198100199100200100201100202100203100204100205100206100207100208100209100210100211100212100213100214100215100216100217100218100219100220100221100222100223100224100225100226100227100228100229100230100231100232100233100234100235100236100237100238100239100240100241100242100243100244100245100246100247100248100249100250100251100252100253100254100255100256100257100258100259100260100261100262100263100264100265100266100267100268100269100270100271100272100273100274100275100276100277100278100279100280100281100282100283100284100285100286100287100288100289100290100291100292100293100294100295100296100297100298100299100300100301100302100303100304100305100306100307100308100309100310100311100312100313100314100315100316100317100318100319100320100321100322100323100324100325100326100327100328100329100330100331100332100333100334100335100336100337100338100339100340100341100342100343100344100345100346100347100348100349100350100351100352100353100354100355100356100357100358100359100360100361100362100363100364100365100366100367100368100369100370100371100372100373100374100375100376100377100378100379100380100381100382100383100384100385100386100387100388100389100390100391100392100393100394100395100396100397100398100399100400100401100402100403100404100405100406100407100408100409100410100411100412100413100414100415100416100417100418100419100420100421100422100423100424100425100426100427100428100429100430100431100432100433100434100435100436100437100438100439100440100441100442100443100444100445100446100447100448100449100450100451100452100453100454100455100456100457100458100459100460100461100462100463100464100465100466100467100468100469100470100471100472100473100474100475100476100477100478100479100480100481100482100483100484100485100486100487100488100489100490100491100492100493100494100495100496100497100498100499100500100501100502100503100504100505100506100507100508100509100510100511100512100513100514100515100516100517100518100519100520100521100522100523100524100525100526100527100528100529100530100531100532100533100534100535100536100537100538100539100540100541100542100543100544100545100546100547100548100549100550100551100552100553100554100555100556100557100558100559100560100561100562100563100564100565100566100567100568100569100570100571100572100573100574100575100576100577100578100579100580100581100582100583100584100585100586100587100588100589100590100591100592100593100594100595100596100597100598100599100600100601100602100603100604100605100606100607100608100609100610100611100612100613100614100615100616100617100618100619100620100621100622100623100624100625100626100627100628100629100630100631100632100633100634100635100636100637100638100639100640100641100642100643100644100645100646100647100648100649100650100651100652100653100654100655100656100657100658100659100660100661100662100663100664100665100666100667100668100669100670100671100672100673100674100675100676100677100678100679100680100681100682100683100684100685100686100687100688100689100690100691100692100693100694100695100696100697100698100699100700100701100702100703100704100705100706100707100708100709100710100711100712100713100714100715100716100717100718100719100720100721100722100723100724100725100726100727100728100729100730100731100732100733100734100735100736100737100738100739100740100741100742100743100744100745100746100747100748100749100750100751100752100753100754100755100756100757100758100759100760100761100762100763100764100765100766100767100768100769100770100771100772100773100774100775100776100777100778100779100780100781100782100783100784100785100786100787100788100789100790100791100792100793100794100795100796100797100798100799100800100801100802100803100804100805100806100807100808100809100810100811100812100813100814100815100816100817100818100819100820100821100822100823100824100825100826100827100828100829100830100831100832100833100834100835100836100837100838100839100840100841100842100843100844100845100846100847100848100849100850100851100852100853100854100855100856100857100858100859100860100861100862100863100864100865100866100867100868100869100870100871100872100873100874100875100876100877100878100879100880100881100882100883100884100885100886100887100888100889100890100891100892100893100894100895100896100897100898100899100900100901100902100903100904100905100906100907100908100909100910100911100912100913100914100915100916100917100918100919100920100921100922100923100924100925100926100927100928100929100930100931100932100933100934100935100936100937100938100939100940100941100942100943100944100945100946100947100948100949100950100951100952100953100954100955100956100957100958100959100960100961100962100963100964100965100966100967100968100969100970100971100972100973100974100975100976100977100978100979100980100981100982100983100984100985100986100987100988100989100990100991100992100993100994100995100996100997100998100999101000101001101002101003101004101005101006101007101008101009101010101011101012101013101014101015101016101017101018101019101020101021101022101023101024101025101026101027101028101029101030101031101032101033101034101035101036101037101038101039101040101041101042101043101044101045101046101047101048101049101050101051101052101053101054101055101056101057101058101059101060101061101062101063101064101065101066101067101068101069101070101071101072101073101074101075101076101077101078101079101080101081101082101083101084101085101086101087101088101089101090101091101092101093101094101095101096101097101098101099101100101101101102101103101104101105101106101107101108101109101110101111101112101113101114101115101116101117101118101119101120101121101122101123101124101125101126101127101128101129101130101131101132101133101134101135101136101137101138101139101140101141101142101143101144101145101146101147101148101149101150101151101152101153101154101155101156101157101158101159101160101161101162101163101164101165101166101167101168101169101170101171101172101173101174101175101176101177101178101179101180101181101182101183101184101185101186101187101188101189101190101191101192101193101194101195101196101197101198101199101200101201101202101203101204101205101206101207101208101209101210101211101212101213101214101215101216101217101218101219101220101221101222101223101224101225101226101227101228101229101230101231101232101233101234101235101236101237101238101239101240101241101242101243101244101245101246101247101248101249101250101251101252101253101254101255101256101257101258101259101260101261101262101263101264101265101266101267101268101269101270101271101272101273101274101275101276101277101278101279101280101281101282101283101284101285101286101287101288101289101290101291101292101293101294101295101296101297101298101299101300101301101302101303101304101305101306101307101308101309101310101311101312101313101314101315101316101317101318101319101320101321101322101323101324101325101326101327101328101329101330101331101332101333101334101335101336101337101338101339101340101341101342101343101344101345101346101347101348101349101350101351101352101353101354101355101356101357101358101359101360101361101362101363101364101365101366101367101368101369101370101371101372101373101374101375101376101377101378101379101380101381101382101383101384101385101386101387101388101389101390101391101392101393101394101395101396101397101398101399101400101401101402101403101404101405101406101407101408101409101410101411101412101413101414101415101416101417101418101419101420101421101422101423101424101425101426101427101428101429101430101431101432101433101434101435101436101437101438101439101440101441101442101443101444101445101446101447101448101449101450101451101452101453101454101455101456101457101458101459101460101461101462101463101464101465101466101467101468101469101470101471101472101473101474101475101476101477101478101479101480101481101482101483101484101485101486101487101488101489101490101491101492101493101494101495101496101497101498101499101500101501101502101503101504101505101506101507101508101509101510101511101512101513101514101515101516101517101518101519101520101521101522101523101524101525101526101527101528101529101530101531101532101533101534101535101536101537101538101539101540101541101542101543101544101545101546101547101548101549101550101551101552101553101554101555101556101557101558101559101560101561101562101563101564101565101566101567101568101569101570101571101572101573101574101575101576101577101578101579101580101581101582101583101584101585101586101587101588101589101590101591101592101593101594101595101596101597101598101599101600101601101602101603101604101605101606101607101608101609101610101611101612101613101614101615101616101617101618101619101620101621101622101623101624101625101626101627101628101629101630101631101632101633101634101635101636101637101638101639101640101641101642101643101644101645101646101647101648101649101650101651101652101653101654101655101656101657101658101659101660101661101662101663101664101665101666101667101668101669101670101671101672101673101674101675101676101677101678101679101680101681101682101683101684101685101686101687101688101689101690101691101692101693101694101695101696101697101698101699101700101701101702101703101704101705101706101707101708101709101710101711101712101713101714101715101716101717101718101719101720101721101722101723101724101725101726101727101728101729101730101731101732101733101734101735101736101737101738101739101740101741101742101743101744101745101746101747101748101749101750101751101752101753101754101755101756101757101758101759101760101761101762101763101764101765101766101767101768101769101770101771101772101773101774101775101776101777101778101779101780101781101782101783101784101785101786101787101788101789101790101791101792101793101794101795101796101797101798101799101800101801101802101803101804101805101806101807101808101809101810101811101812101813101814101815101816101817101818101819101820101821101822101823101824101825101826101827101828101829101830101831101832101833101834101835101836101837101838101839101840101841101842101843101844101845101846101847101848101849101850101851101852101853101854101855101856101857101858101859101860101861101862101863101864101865101866101867101868101869101870101871101872101873101874101875101876101877101878101879101880101881101882101883101884101885101886101887101888101889101890101891101892101893101894101895101896101897101898101899101900101901101902101903101904101905101906101907101908101909101910101911101912101913101914101915101916101917101918101919101920101921101922101923101924101925101926101927101928101929101930101931101932101933101934101935101936101937101938101939101940101941101942101943101944101945101946101947101948101949101950101951101952101953101954101955101956101957101958101959101960101961101962101963101964101965101966101967101968101969101970101971101972101973101974101975101976101977101978101979101980101981101982101983101984101985101986101987101988101989101990101991101992101993101994101995101996101997101998101999102000102001102002102003102004102005102006102007102008102009102010102011102012102013102014102015102016102017102018102019102020102021102022102023102024102025102026102027102028102029102030102031102032102033102034102035102036102037102038102039102040102041102042102043102044102045102046102047102048102049102050102051102052102053102054102055102056102057102058102059102060102061102062102063102064102065102066102067102068102069102070102071102072102073102074102075102076102077102078102079102080102081102082102083102084102085102086102087102088102089102090102091102092102093102094102095102096102097102098102099102100102101102102102103102104102105102106102107102108102109102110102111102112102113102114102115102116102117102118102119102120102121102122102123102124102125102126102127102128102129102130102131102132102133102134102135102136102137102138102139102140102141102142102143102144102145102146102147102148102149102150102151102152102153102154102155102156102157102158102159102160102161102162102163102164102165102166102167102168102169102170102171102172102173102174102175102176102177102178102179102180102181102182102183102184102185102186102187102188102189102190102191102192102193102194102195102196102197102198102199102200102201102202102203102204102205102206102207102208102209102210102211102212102213102214102215102216102217102218102219102220102221102222102223102224102225102226102227102228102229102230102231102232102233102234102235102236102237102238102239102240102241102242102243102244102245102246102247102248102249102250102251102252102253102254102255102256102257102258102259102260102261102262102263102264102265102266102267102268102269102270102271102272102273102274102275102276102277102278102279102280102281102282102283102284102285102286102287102288102289102290102291102292102293102294102295102296102297102298102299102300102301102302102303102304102305102306102307102308102309102310102311102312102313102314102315102316102317102318102319102320102321102322102323102324102325102326102327102328102329102330102331102332102333102334102335102336102337102338102339102340102341102342102343102344102345102346102347102348102349102350102351102352102353102354102355102356102357102358102359102360102361102362102363102364102365102366102367102368102369102370102371102372102373102374102375102376102377102378102379102380102381102382102383102384102385102386102387102388102389102390102391102392102393102394102395102396102397102398102399102400102401102402102403102404102405102406102407102408102409102410102411102412102413102414102415102416102417102418102419102420102421102422102423102424102425102426102427102428102429102430102431102432102433102434102435102436102437102438102439102440102441102442102443102444102445102446102447102448102449102450102451102452102453102454102455102456102457102458102459102460102461102462102463102464102465102466102467102468102469102470102471102472102473102474102475102476102477102478102479102480102481102482102483102484102485102486102487102488102489102490102491102492102493102494102495102496102497102498102499102500102501102502102503102504102505102506102507102508102509102510102511102512102513102514102515102516102517102518102519102520102521102522102523102524102525102526102527102528102529102530102531102532102533102534102535102536102537102538102539102540102541102542102543102544102545102546102547102548102549102550102551102552102553102554102555102556102557102558102559102560102561102562102563102564102565102566102567102568102569102570102571102572102573102574102575102576102577102578102579102580102581102582102583102584102585102586102587102588102589102590102591102592102593102594102595102596102597102598102599102600102601102602102603102604102605102606102607102608102609102610102611102612102613102614102615102616102617102618102619102620102621102622102623102624102625102626102627102628102629102630102631102632102633102634102635102636102637102638102639102640102641102642102643102644102645102646102647102648102649102650102651102652102653102654102655102656102657102658102659102660102661102662102663102664102665102666102667102668102669102670102671102672102673102674102675102676102677102678102679102680102681102682102683102684102685102686102687102688102689102690102691102692102693102694102695102696102697102698102699102700102701102702102703102704102705102706102707102708102709102710102711102712102713102714102715102716102717102718102719102720102721102722102723102724102725102726102727102728102729102730102731102732102733102734102735102736102737102738102739102740102741102742102743102744102745102746102747102748102749102750102751102752102753102754102755102756102757102758102759102760102761102762102763102764102765102766102767102768102769102770102771102772102773102774102775102776102777102778102779102780102781102782102783102784102785102786102787102788102789102790102791102792102793102794102795102796102797102798102799102800102801102802102803102804102805102806102807102808102809102810102811102812102813102814102815102816102817102818102819102820102821102822102823102824102825102826102827102828102829102830102831102832102833102834102835102836102837102838102839102840102841102842102843102844102845102846102847102848102849102850102851102852102853102854102855102856102857102858102859102860102861102862102863102864102865102866102867102868102869102870102871102872102873102874102875102876102877102878102879102880102881102882102883102884102885102886102887102888102889102890102891102892102893102894102895102896102897102898102899102900102901102902102903102904102905102906102907102908102909102910102911102912102913102914102915102916102917102918102919102920102921102922102923102924102925102926102927102928102929102930102931102932102933102934102935102936102937102938102939102940102941102942102943102944102945102946102947102948102949102950102951102952102953102954102955102956102957102958102959102960102961102962102963102964102965102966102967102968102969102970102971102972102973102974102975102976102977102978102979102980102981102982102983102984102985102986102987102988102989102990102991102992102993102994102995102996102997102998102999103000103001103002103003103004103005103006103007103008103009103010103011103012103013103014103015103016103017103018103019103020103021103022103023103024103025103026103027103028103029103030103031103032103033103034103035103036103037103038103039103040103041103042103043103044103045103046103047103048103049103050103051103052103053103054103055103056103057103058103059103060103061103062103063103064103065
  1. /**
  2. * @author Richard Davey <rich@photonstorm.com>
  3. * @copyright 2016 Photon Storm Ltd.
  4. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  5. *
  6. * @overview
  7. *
  8. * Phaser - http://phaser.io
  9. *
  10. * v2.6.2 "Kore Springs" - Built: Fri Aug 26 2016 01:02:57
  11. *
  12. * By Richard Davey http://www.photonstorm.com @photonstorm
  13. *
  14. * Phaser is a fun, free and fast 2D game framework for making HTML5 games
  15. * for desktop and mobile web browsers, supporting Canvas and WebGL rendering.
  16. *
  17. * Phaser uses Pixi.js for rendering, created by Mat Groves http://matgroves.com @Doormat23
  18. * Phaser uses p2.js for full-body physics, created by Stefan Hedman https://github.com/schteppe/p2.js @schteppe
  19. * Phaser contains a port of N+ Physics, converted by Richard Davey, original by http://www.metanetsoftware.com
  20. *
  21. * Many thanks to Adam Saltsman (@ADAMATOMIC) for releasing Flixel, from which both Phaser and my love of framework development originate.
  22. *
  23. * Follow development at http://phaser.io and on our forum
  24. *
  25. * "If you want your children to be intelligent, read them fairy tales."
  26. * "If you want them to be more intelligent, read them more fairy tales."
  27. * -- Albert Einstein
  28. */
  29. /**
  30. * The MIT License (MIT)
  31. *
  32. * Copyright (c) 2015 p2.js authors
  33. *
  34. * Permission is hereby granted, free of charge, to any person obtaining a copy
  35. * of this software and associated documentation files (the "Software"), to deal
  36. * in the Software without restriction, including without limitation the rights
  37. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  38. * copies of the Software, and to permit persons to whom the Software is
  39. * furnished to do so, subject to the following conditions:
  40. *
  41. * The above copyright notice and this permission notice shall be included in
  42. * all copies or substantial portions of the Software.
  43. *
  44. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  45. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  46. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  47. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  48. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  49. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  50. * THE SOFTWARE.
  51. */
  52. !function(e){if("object"==typeof exports)module.exports=e();else if("function"==typeof define&&false)define(e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.p2=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){
  53. var Scalar = _dereq_('./Scalar');
  54. module.exports = Line;
  55. /**
  56. * Container for line-related functions
  57. * @class Line
  58. */
  59. function Line(){};
  60. /**
  61. * Compute the intersection between two lines.
  62. * @static
  63. * @method lineInt
  64. * @param {Array} l1 Line vector 1
  65. * @param {Array} l2 Line vector 2
  66. * @param {Number} precision Precision to use when checking if the lines are parallel
  67. * @return {Array} The intersection point.
  68. */
  69. Line.lineInt = function(l1,l2,precision){
  70. precision = precision || 0;
  71. var i = [0,0]; // point
  72. var a1, b1, c1, a2, b2, c2, det; // scalars
  73. a1 = l1[1][1] - l1[0][1];
  74. b1 = l1[0][0] - l1[1][0];
  75. c1 = a1 * l1[0][0] + b1 * l1[0][1];
  76. a2 = l2[1][1] - l2[0][1];
  77. b2 = l2[0][0] - l2[1][0];
  78. c2 = a2 * l2[0][0] + b2 * l2[0][1];
  79. det = a1 * b2 - a2*b1;
  80. if (!Scalar.eq(det, 0, precision)) { // lines are not parallel
  81. i[0] = (b2 * c1 - b1 * c2) / det;
  82. i[1] = (a1 * c2 - a2 * c1) / det;
  83. }
  84. return i;
  85. };
  86. /**
  87. * Checks if two line segments intersects.
  88. * @method segmentsIntersect
  89. * @param {Array} p1 The start vertex of the first line segment.
  90. * @param {Array} p2 The end vertex of the first line segment.
  91. * @param {Array} q1 The start vertex of the second line segment.
  92. * @param {Array} q2 The end vertex of the second line segment.
  93. * @return {Boolean} True if the two line segments intersect
  94. */
  95. Line.segmentsIntersect = function(p1, p2, q1, q2){
  96. var dx = p2[0] - p1[0];
  97. var dy = p2[1] - p1[1];
  98. var da = q2[0] - q1[0];
  99. var db = q2[1] - q1[1];
  100. // segments are parallel
  101. if(da*dy - db*dx == 0)
  102. return false;
  103. var s = (dx * (q1[1] - p1[1]) + dy * (p1[0] - q1[0])) / (da * dy - db * dx)
  104. var t = (da * (p1[1] - q1[1]) + db * (q1[0] - p1[0])) / (db * dx - da * dy)
  105. return (s>=0 && s<=1 && t>=0 && t<=1);
  106. };
  107. },{"./Scalar":4}],2:[function(_dereq_,module,exports){
  108. module.exports = Point;
  109. /**
  110. * Point related functions
  111. * @class Point
  112. */
  113. function Point(){};
  114. /**
  115. * Get the area of a triangle spanned by the three given points. Note that the area will be negative if the points are not given in counter-clockwise order.
  116. * @static
  117. * @method area
  118. * @param {Array} a
  119. * @param {Array} b
  120. * @param {Array} c
  121. * @return {Number}
  122. */
  123. Point.area = function(a,b,c){
  124. return (((b[0] - a[0])*(c[1] - a[1]))-((c[0] - a[0])*(b[1] - a[1])));
  125. };
  126. Point.left = function(a,b,c){
  127. return Point.area(a,b,c) > 0;
  128. };
  129. Point.leftOn = function(a,b,c) {
  130. return Point.area(a, b, c) >= 0;
  131. };
  132. Point.right = function(a,b,c) {
  133. return Point.area(a, b, c) < 0;
  134. };
  135. Point.rightOn = function(a,b,c) {
  136. return Point.area(a, b, c) <= 0;
  137. };
  138. var tmpPoint1 = [],
  139. tmpPoint2 = [];
  140. /**
  141. * Check if three points are collinear
  142. * @method collinear
  143. * @param {Array} a
  144. * @param {Array} b
  145. * @param {Array} c
  146. * @param {Number} [thresholdAngle=0] Threshold angle to use when comparing the vectors. The function will return true if the angle between the resulting vectors is less than this value. Use zero for max precision.
  147. * @return {Boolean}
  148. */
  149. Point.collinear = function(a,b,c,thresholdAngle) {
  150. if(!thresholdAngle)
  151. return Point.area(a, b, c) == 0;
  152. else {
  153. var ab = tmpPoint1,
  154. bc = tmpPoint2;
  155. ab[0] = b[0]-a[0];
  156. ab[1] = b[1]-a[1];
  157. bc[0] = c[0]-b[0];
  158. bc[1] = c[1]-b[1];
  159. var dot = ab[0]*bc[0] + ab[1]*bc[1],
  160. magA = Math.sqrt(ab[0]*ab[0] + ab[1]*ab[1]),
  161. magB = Math.sqrt(bc[0]*bc[0] + bc[1]*bc[1]),
  162. angle = Math.acos(dot/(magA*magB));
  163. return angle < thresholdAngle;
  164. }
  165. };
  166. Point.sqdist = function(a,b){
  167. var dx = b[0] - a[0];
  168. var dy = b[1] - a[1];
  169. return dx * dx + dy * dy;
  170. };
  171. },{}],3:[function(_dereq_,module,exports){
  172. var Line = _dereq_("./Line")
  173. , Point = _dereq_("./Point")
  174. , Scalar = _dereq_("./Scalar")
  175. module.exports = Polygon;
  176. /**
  177. * Polygon class.
  178. * @class Polygon
  179. * @constructor
  180. */
  181. function Polygon(){
  182. /**
  183. * Vertices that this polygon consists of. An array of array of numbers, example: [[0,0],[1,0],..]
  184. * @property vertices
  185. * @type {Array}
  186. */
  187. this.vertices = [];
  188. }
  189. /**
  190. * Get a vertex at position i. It does not matter if i is out of bounds, this function will just cycle.
  191. * @method at
  192. * @param {Number} i
  193. * @return {Array}
  194. */
  195. Polygon.prototype.at = function(i){
  196. var v = this.vertices,
  197. s = v.length;
  198. return v[i < 0 ? i % s + s : i % s];
  199. };
  200. /**
  201. * Get first vertex
  202. * @method first
  203. * @return {Array}
  204. */
  205. Polygon.prototype.first = function(){
  206. return this.vertices[0];
  207. };
  208. /**
  209. * Get last vertex
  210. * @method last
  211. * @return {Array}
  212. */
  213. Polygon.prototype.last = function(){
  214. return this.vertices[this.vertices.length-1];
  215. };
  216. /**
  217. * Clear the polygon data
  218. * @method clear
  219. * @return {Array}
  220. */
  221. Polygon.prototype.clear = function(){
  222. this.vertices.length = 0;
  223. };
  224. /**
  225. * Append points "from" to "to"-1 from an other polygon "poly" onto this one.
  226. * @method append
  227. * @param {Polygon} poly The polygon to get points from.
  228. * @param {Number} from The vertex index in "poly".
  229. * @param {Number} to The end vertex index in "poly". Note that this vertex is NOT included when appending.
  230. * @return {Array}
  231. */
  232. Polygon.prototype.append = function(poly,from,to){
  233. if(typeof(from) == "undefined") throw new Error("From is not given!");
  234. if(typeof(to) == "undefined") throw new Error("To is not given!");
  235. if(to-1 < from) throw new Error("lol1");
  236. if(to > poly.vertices.length) throw new Error("lol2");
  237. if(from < 0) throw new Error("lol3");
  238. for(var i=from; i<to; i++){
  239. this.vertices.push(poly.vertices[i]);
  240. }
  241. };
  242. /**
  243. * Make sure that the polygon vertices are ordered counter-clockwise.
  244. * @method makeCCW
  245. */
  246. Polygon.prototype.makeCCW = function(){
  247. var br = 0,
  248. v = this.vertices;
  249. // find bottom right point
  250. for (var i = 1; i < this.vertices.length; ++i) {
  251. if (v[i][1] < v[br][1] || (v[i][1] == v[br][1] && v[i][0] > v[br][0])) {
  252. br = i;
  253. }
  254. }
  255. // reverse poly if clockwise
  256. if (!Point.left(this.at(br - 1), this.at(br), this.at(br + 1))) {
  257. this.reverse();
  258. }
  259. };
  260. /**
  261. * Reverse the vertices in the polygon
  262. * @method reverse
  263. */
  264. Polygon.prototype.reverse = function(){
  265. var tmp = [];
  266. for(var i=0, N=this.vertices.length; i!==N; i++){
  267. tmp.push(this.vertices.pop());
  268. }
  269. this.vertices = tmp;
  270. };
  271. /**
  272. * Check if a point in the polygon is a reflex point
  273. * @method isReflex
  274. * @param {Number} i
  275. * @return {Boolean}
  276. */
  277. Polygon.prototype.isReflex = function(i){
  278. return Point.right(this.at(i - 1), this.at(i), this.at(i + 1));
  279. };
  280. var tmpLine1=[],
  281. tmpLine2=[];
  282. /**
  283. * Check if two vertices in the polygon can see each other
  284. * @method canSee
  285. * @param {Number} a Vertex index 1
  286. * @param {Number} b Vertex index 2
  287. * @return {Boolean}
  288. */
  289. Polygon.prototype.canSee = function(a,b) {
  290. var p, dist, l1=tmpLine1, l2=tmpLine2;
  291. if (Point.leftOn(this.at(a + 1), this.at(a), this.at(b)) && Point.rightOn(this.at(a - 1), this.at(a), this.at(b))) {
  292. return false;
  293. }
  294. dist = Point.sqdist(this.at(a), this.at(b));
  295. for (var i = 0; i !== this.vertices.length; ++i) { // for each edge
  296. if ((i + 1) % this.vertices.length === a || i === a) // ignore incident edges
  297. continue;
  298. if (Point.leftOn(this.at(a), this.at(b), this.at(i + 1)) && Point.rightOn(this.at(a), this.at(b), this.at(i))) { // if diag intersects an edge
  299. l1[0] = this.at(a);
  300. l1[1] = this.at(b);
  301. l2[0] = this.at(i);
  302. l2[1] = this.at(i + 1);
  303. p = Line.lineInt(l1,l2);
  304. if (Point.sqdist(this.at(a), p) < dist) { // if edge is blocking visibility to b
  305. return false;
  306. }
  307. }
  308. }
  309. return true;
  310. };
  311. /**
  312. * Copy the polygon from vertex i to vertex j.
  313. * @method copy
  314. * @param {Number} i
  315. * @param {Number} j
  316. * @param {Polygon} [targetPoly] Optional target polygon to save in.
  317. * @return {Polygon} The resulting copy.
  318. */
  319. Polygon.prototype.copy = function(i,j,targetPoly){
  320. var p = targetPoly || new Polygon();
  321. p.clear();
  322. if (i < j) {
  323. // Insert all vertices from i to j
  324. for(var k=i; k<=j; k++)
  325. p.vertices.push(this.vertices[k]);
  326. } else {
  327. // Insert vertices 0 to j
  328. for(var k=0; k<=j; k++)
  329. p.vertices.push(this.vertices[k]);
  330. // Insert vertices i to end
  331. for(var k=i; k<this.vertices.length; k++)
  332. p.vertices.push(this.vertices[k]);
  333. }
  334. return p;
  335. };
  336. /**
  337. * Decomposes the polygon into convex pieces. Returns a list of edges [[p1,p2],[p2,p3],...] that cuts the polygon.
  338. * Note that this algorithm has complexity O(N^4) and will be very slow for polygons with many vertices.
  339. * @method getCutEdges
  340. * @return {Array}
  341. */
  342. Polygon.prototype.getCutEdges = function() {
  343. var min=[], tmp1=[], tmp2=[], tmpPoly = new Polygon();
  344. var nDiags = Number.MAX_VALUE;
  345. for (var i = 0; i < this.vertices.length; ++i) {
  346. if (this.isReflex(i)) {
  347. for (var j = 0; j < this.vertices.length; ++j) {
  348. if (this.canSee(i, j)) {
  349. tmp1 = this.copy(i, j, tmpPoly).getCutEdges();
  350. tmp2 = this.copy(j, i, tmpPoly).getCutEdges();
  351. for(var k=0; k<tmp2.length; k++)
  352. tmp1.push(tmp2[k]);
  353. if (tmp1.length < nDiags) {
  354. min = tmp1;
  355. nDiags = tmp1.length;
  356. min.push([this.at(i), this.at(j)]);
  357. }
  358. }
  359. }
  360. }
  361. }
  362. return min;
  363. };
  364. /**
  365. * Decomposes the polygon into one or more convex sub-Polygons.
  366. * @method decomp
  367. * @return {Array} An array or Polygon objects.
  368. */
  369. Polygon.prototype.decomp = function(){
  370. var edges = this.getCutEdges();
  371. if(edges.length > 0)
  372. return this.slice(edges);
  373. else
  374. return [this];
  375. };
  376. /**
  377. * Slices the polygon given one or more cut edges. If given one, this function will return two polygons (false on failure). If many, an array of polygons.
  378. * @method slice
  379. * @param {Array} cutEdges A list of edges, as returned by .getCutEdges()
  380. * @return {Array}
  381. */
  382. Polygon.prototype.slice = function(cutEdges){
  383. if(cutEdges.length == 0) return [this];
  384. if(cutEdges instanceof Array && cutEdges.length && cutEdges[0] instanceof Array && cutEdges[0].length==2 && cutEdges[0][0] instanceof Array){
  385. var polys = [this];
  386. for(var i=0; i<cutEdges.length; i++){
  387. var cutEdge = cutEdges[i];
  388. // Cut all polys
  389. for(var j=0; j<polys.length; j++){
  390. var poly = polys[j];
  391. var result = poly.slice(cutEdge);
  392. if(result){
  393. // Found poly! Cut and quit
  394. polys.splice(j,1);
  395. polys.push(result[0],result[1]);
  396. break;
  397. }
  398. }
  399. }
  400. return polys;
  401. } else {
  402. // Was given one edge
  403. var cutEdge = cutEdges;
  404. var i = this.vertices.indexOf(cutEdge[0]);
  405. var j = this.vertices.indexOf(cutEdge[1]);
  406. if(i != -1 && j != -1){
  407. return [this.copy(i,j),
  408. this.copy(j,i)];
  409. } else {
  410. return false;
  411. }
  412. }
  413. };
  414. /**
  415. * Checks that the line segments of this polygon do not intersect each other.
  416. * @method isSimple
  417. * @param {Array} path An array of vertices e.g. [[0,0],[0,1],...]
  418. * @return {Boolean}
  419. * @todo Should it check all segments with all others?
  420. */
  421. Polygon.prototype.isSimple = function(){
  422. var path = this.vertices;
  423. // Check
  424. for(var i=0; i<path.length-1; i++){
  425. for(var j=0; j<i-1; j++){
  426. if(Line.segmentsIntersect(path[i], path[i+1], path[j], path[j+1] )){
  427. return false;
  428. }
  429. }
  430. }
  431. // Check the segment between the last and the first point to all others
  432. for(var i=1; i<path.length-2; i++){
  433. if(Line.segmentsIntersect(path[0], path[path.length-1], path[i], path[i+1] )){
  434. return false;
  435. }
  436. }
  437. return true;
  438. };
  439. function getIntersectionPoint(p1, p2, q1, q2, delta){
  440. delta = delta || 0;
  441. var a1 = p2[1] - p1[1];
  442. var b1 = p1[0] - p2[0];
  443. var c1 = (a1 * p1[0]) + (b1 * p1[1]);
  444. var a2 = q2[1] - q1[1];
  445. var b2 = q1[0] - q2[0];
  446. var c2 = (a2 * q1[0]) + (b2 * q1[1]);
  447. var det = (a1 * b2) - (a2 * b1);
  448. if(!Scalar.eq(det,0,delta))
  449. return [((b2 * c1) - (b1 * c2)) / det, ((a1 * c2) - (a2 * c1)) / det]
  450. else
  451. return [0,0]
  452. }
  453. /**
  454. * Quickly decompose the Polygon into convex sub-polygons.
  455. * @method quickDecomp
  456. * @param {Array} result
  457. * @param {Array} [reflexVertices]
  458. * @param {Array} [steinerPoints]
  459. * @param {Number} [delta]
  460. * @param {Number} [maxlevel]
  461. * @param {Number} [level]
  462. * @return {Array}
  463. */
  464. Polygon.prototype.quickDecomp = function(result,reflexVertices,steinerPoints,delta,maxlevel,level){
  465. maxlevel = maxlevel || 100;
  466. level = level || 0;
  467. delta = delta || 25;
  468. result = typeof(result)!="undefined" ? result : [];
  469. reflexVertices = reflexVertices || [];
  470. steinerPoints = steinerPoints || [];
  471. var upperInt=[0,0], lowerInt=[0,0], p=[0,0]; // Points
  472. var upperDist=0, lowerDist=0, d=0, closestDist=0; // scalars
  473. var upperIndex=0, lowerIndex=0, closestIndex=0; // Integers
  474. var lowerPoly=new Polygon(), upperPoly=new Polygon(); // polygons
  475. var poly = this,
  476. v = this.vertices;
  477. if(v.length < 3) return result;
  478. level++;
  479. if(level > maxlevel){
  480. console.warn("quickDecomp: max level ("+maxlevel+") reached.");
  481. return result;
  482. }
  483. for (var i = 0; i < this.vertices.length; ++i) {
  484. if (poly.isReflex(i)) {
  485. reflexVertices.push(poly.vertices[i]);
  486. upperDist = lowerDist = Number.MAX_VALUE;
  487. for (var j = 0; j < this.vertices.length; ++j) {
  488. if (Point.left(poly.at(i - 1), poly.at(i), poly.at(j))
  489. && Point.rightOn(poly.at(i - 1), poly.at(i), poly.at(j - 1))) { // if line intersects with an edge
  490. p = getIntersectionPoint(poly.at(i - 1), poly.at(i), poly.at(j), poly.at(j - 1)); // find the point of intersection
  491. if (Point.right(poly.at(i + 1), poly.at(i), p)) { // make sure it's inside the poly
  492. d = Point.sqdist(poly.vertices[i], p);
  493. if (d < lowerDist) { // keep only the closest intersection
  494. lowerDist = d;
  495. lowerInt = p;
  496. lowerIndex = j;
  497. }
  498. }
  499. }
  500. if (Point.left(poly.at(i + 1), poly.at(i), poly.at(j + 1))
  501. && Point.rightOn(poly.at(i + 1), poly.at(i), poly.at(j))) {
  502. p = getIntersectionPoint(poly.at(i + 1), poly.at(i), poly.at(j), poly.at(j + 1));
  503. if (Point.left(poly.at(i - 1), poly.at(i), p)) {
  504. d = Point.sqdist(poly.vertices[i], p);
  505. if (d < upperDist) {
  506. upperDist = d;
  507. upperInt = p;
  508. upperIndex = j;
  509. }
  510. }
  511. }
  512. }
  513. // if there are no vertices to connect to, choose a point in the middle
  514. if (lowerIndex == (upperIndex + 1) % this.vertices.length) {
  515. //console.log("Case 1: Vertex("+i+"), lowerIndex("+lowerIndex+"), upperIndex("+upperIndex+"), poly.size("+this.vertices.length+")");
  516. p[0] = (lowerInt[0] + upperInt[0]) / 2;
  517. p[1] = (lowerInt[1] + upperInt[1]) / 2;
  518. steinerPoints.push(p);
  519. if (i < upperIndex) {
  520. //lowerPoly.insert(lowerPoly.end(), poly.begin() + i, poly.begin() + upperIndex + 1);
  521. lowerPoly.append(poly, i, upperIndex+1);
  522. lowerPoly.vertices.push(p);
  523. upperPoly.vertices.push(p);
  524. if (lowerIndex != 0){
  525. //upperPoly.insert(upperPoly.end(), poly.begin() + lowerIndex, poly.end());
  526. upperPoly.append(poly,lowerIndex,poly.vertices.length);
  527. }
  528. //upperPoly.insert(upperPoly.end(), poly.begin(), poly.begin() + i + 1);
  529. upperPoly.append(poly,0,i+1);
  530. } else {
  531. if (i != 0){
  532. //lowerPoly.insert(lowerPoly.end(), poly.begin() + i, poly.end());
  533. lowerPoly.append(poly,i,poly.vertices.length);
  534. }
  535. //lowerPoly.insert(lowerPoly.end(), poly.begin(), poly.begin() + upperIndex + 1);
  536. lowerPoly.append(poly,0,upperIndex+1);
  537. lowerPoly.vertices.push(p);
  538. upperPoly.vertices.push(p);
  539. //upperPoly.insert(upperPoly.end(), poly.begin() + lowerIndex, poly.begin() + i + 1);
  540. upperPoly.append(poly,lowerIndex,i+1);
  541. }
  542. } else {
  543. // connect to the closest point within the triangle
  544. //console.log("Case 2: Vertex("+i+"), closestIndex("+closestIndex+"), poly.size("+this.vertices.length+")\n");
  545. if (lowerIndex > upperIndex) {
  546. upperIndex += this.vertices.length;
  547. }
  548. closestDist = Number.MAX_VALUE;
  549. if(upperIndex < lowerIndex){
  550. return result;
  551. }
  552. for (var j = lowerIndex; j <= upperIndex; ++j) {
  553. if (Point.leftOn(poly.at(i - 1), poly.at(i), poly.at(j))
  554. && Point.rightOn(poly.at(i + 1), poly.at(i), poly.at(j))) {
  555. d = Point.sqdist(poly.at(i), poly.at(j));
  556. if (d < closestDist) {
  557. closestDist = d;
  558. closestIndex = j % this.vertices.length;
  559. }
  560. }
  561. }
  562. if (i < closestIndex) {
  563. lowerPoly.append(poly,i,closestIndex+1);
  564. if (closestIndex != 0){
  565. upperPoly.append(poly,closestIndex,v.length);
  566. }
  567. upperPoly.append(poly,0,i+1);
  568. } else {
  569. if (i != 0){
  570. lowerPoly.append(poly,i,v.length);
  571. }
  572. lowerPoly.append(poly,0,closestIndex+1);
  573. upperPoly.append(poly,closestIndex,i+1);
  574. }
  575. }
  576. // solve smallest poly first
  577. if (lowerPoly.vertices.length < upperPoly.vertices.length) {
  578. lowerPoly.quickDecomp(result,reflexVertices,steinerPoints,delta,maxlevel,level);
  579. upperPoly.quickDecomp(result,reflexVertices,steinerPoints,delta,maxlevel,level);
  580. } else {
  581. upperPoly.quickDecomp(result,reflexVertices,steinerPoints,delta,maxlevel,level);
  582. lowerPoly.quickDecomp(result,reflexVertices,steinerPoints,delta,maxlevel,level);
  583. }
  584. return result;
  585. }
  586. }
  587. result.push(this);
  588. return result;
  589. };
  590. /**
  591. * Remove collinear points in the polygon.
  592. * @method removeCollinearPoints
  593. * @param {Number} [precision] The threshold angle to use when determining whether two edges are collinear. Use zero for finest precision.
  594. * @return {Number} The number of points removed
  595. */
  596. Polygon.prototype.removeCollinearPoints = function(precision){
  597. var num = 0;
  598. for(var i=this.vertices.length-1; this.vertices.length>3 && i>=0; --i){
  599. if(Point.collinear(this.at(i-1),this.at(i),this.at(i+1),precision)){
  600. // Remove the middle point
  601. this.vertices.splice(i%this.vertices.length,1);
  602. i--; // Jump one point forward. Otherwise we may get a chain removal
  603. num++;
  604. }
  605. }
  606. return num;
  607. };
  608. },{"./Line":1,"./Point":2,"./Scalar":4}],4:[function(_dereq_,module,exports){
  609. module.exports = Scalar;
  610. /**
  611. * Scalar functions
  612. * @class Scalar
  613. */
  614. function Scalar(){}
  615. /**
  616. * Check if two scalars are equal
  617. * @static
  618. * @method eq
  619. * @param {Number} a
  620. * @param {Number} b
  621. * @param {Number} [precision]
  622. * @return {Boolean}
  623. */
  624. Scalar.eq = function(a,b,precision){
  625. precision = precision || 0;
  626. return Math.abs(a-b) < precision;
  627. };
  628. },{}],5:[function(_dereq_,module,exports){
  629. module.exports = {
  630. Polygon : _dereq_("./Polygon"),
  631. Point : _dereq_("./Point"),
  632. };
  633. },{"./Point":2,"./Polygon":3}],6:[function(_dereq_,module,exports){
  634. module.exports={
  635. "name": "p2",
  636. "version": "0.7.0",
  637. "description": "A JavaScript 2D physics engine.",
  638. "author": "Stefan Hedman <schteppe@gmail.com> (http://steffe.se)",
  639. "keywords": [
  640. "p2.js",
  641. "p2",
  642. "physics",
  643. "engine",
  644. "2d"
  645. ],
  646. "main": "./src/p2.js",
  647. "engines": {
  648. "node": "*"
  649. },
  650. "repository": {
  651. "type": "git",
  652. "url": "https://github.com/schteppe/p2.js.git"
  653. },
  654. "bugs": {
  655. "url": "https://github.com/schteppe/p2.js/issues"
  656. },
  657. "licenses": [
  658. {
  659. "type": "MIT"
  660. }
  661. ],
  662. "devDependencies": {
  663. "grunt": "^0.4.5",
  664. "grunt-contrib-jshint": "^0.11.2",
  665. "grunt-contrib-nodeunit": "^0.4.1",
  666. "grunt-contrib-uglify": "~0.4.0",
  667. "grunt-contrib-watch": "~0.5.0",
  668. "grunt-browserify": "~2.0.1",
  669. "grunt-contrib-concat": "^0.4.0"
  670. },
  671. "dependencies": {
  672. "poly-decomp": "0.1.0"
  673. }
  674. }
  675. },{}],7:[function(_dereq_,module,exports){
  676. var vec2 = _dereq_('../math/vec2')
  677. , Utils = _dereq_('../utils/Utils');
  678. module.exports = AABB;
  679. /**
  680. * Axis aligned bounding box class.
  681. * @class AABB
  682. * @constructor
  683. * @param {Object} [options]
  684. * @param {Array} [options.upperBound]
  685. * @param {Array} [options.lowerBound]
  686. */
  687. function AABB(options){
  688. /**
  689. * The lower bound of the bounding box.
  690. * @property lowerBound
  691. * @type {Array}
  692. */
  693. this.lowerBound = vec2.create();
  694. if(options && options.lowerBound){
  695. vec2.copy(this.lowerBound, options.lowerBound);
  696. }
  697. /**
  698. * The upper bound of the bounding box.
  699. * @property upperBound
  700. * @type {Array}
  701. */
  702. this.upperBound = vec2.create();
  703. if(options && options.upperBound){
  704. vec2.copy(this.upperBound, options.upperBound);
  705. }
  706. }
  707. var tmp = vec2.create();
  708. /**
  709. * Set the AABB bounds from a set of points, transformed by the given position and angle.
  710. * @method setFromPoints
  711. * @param {Array} points An array of vec2's.
  712. * @param {Array} position
  713. * @param {number} angle
  714. * @param {number} skinSize Some margin to be added to the AABB.
  715. */
  716. AABB.prototype.setFromPoints = function(points, position, angle, skinSize){
  717. var l = this.lowerBound,
  718. u = this.upperBound;
  719. if(typeof(angle) !== "number"){
  720. angle = 0;
  721. }
  722. // Set to the first point
  723. if(angle !== 0){
  724. vec2.rotate(l, points[0], angle);
  725. } else {
  726. vec2.copy(l, points[0]);
  727. }
  728. vec2.copy(u, l);
  729. // Compute cosines and sines just once
  730. var cosAngle = Math.cos(angle),
  731. sinAngle = Math.sin(angle);
  732. for(var i = 1; i<points.length; i++){
  733. var p = points[i];
  734. if(angle !== 0){
  735. var x = p[0],
  736. y = p[1];
  737. tmp[0] = cosAngle * x -sinAngle * y;
  738. tmp[1] = sinAngle * x +cosAngle * y;
  739. p = tmp;
  740. }
  741. for(var j=0; j<2; j++){
  742. if(p[j] > u[j]){
  743. u[j] = p[j];
  744. }
  745. if(p[j] < l[j]){
  746. l[j] = p[j];
  747. }
  748. }
  749. }
  750. // Add offset
  751. if(position){
  752. vec2.add(this.lowerBound, this.lowerBound, position);
  753. vec2.add(this.upperBound, this.upperBound, position);
  754. }
  755. if(skinSize){
  756. this.lowerBound[0] -= skinSize;
  757. this.lowerBound[1] -= skinSize;
  758. this.upperBound[0] += skinSize;
  759. this.upperBound[1] += skinSize;
  760. }
  761. };
  762. /**
  763. * Copy bounds from an AABB to this AABB
  764. * @method copy
  765. * @param {AABB} aabb
  766. */
  767. AABB.prototype.copy = function(aabb){
  768. vec2.copy(this.lowerBound, aabb.lowerBound);
  769. vec2.copy(this.upperBound, aabb.upperBound);
  770. };
  771. /**
  772. * Extend this AABB so that it covers the given AABB too.
  773. * @method extend
  774. * @param {AABB} aabb
  775. */
  776. AABB.prototype.extend = function(aabb){
  777. // Loop over x and y
  778. var i = 2;
  779. while(i--){
  780. // Extend lower bound
  781. var l = aabb.lowerBound[i];
  782. if(this.lowerBound[i] > l){
  783. this.lowerBound[i] = l;
  784. }
  785. // Upper
  786. var u = aabb.upperBound[i];
  787. if(this.upperBound[i] < u){
  788. this.upperBound[i] = u;
  789. }
  790. }
  791. };
  792. /**
  793. * Returns true if the given AABB overlaps this AABB.
  794. * @method overlaps
  795. * @param {AABB} aabb
  796. * @return {Boolean}
  797. */
  798. AABB.prototype.overlaps = function(aabb){
  799. var l1 = this.lowerBound,
  800. u1 = this.upperBound,
  801. l2 = aabb.lowerBound,
  802. u2 = aabb.upperBound;
  803. // l2 u2
  804. // |---------|
  805. // |--------|
  806. // l1 u1
  807. return ((l2[0] <= u1[0] && u1[0] <= u2[0]) || (l1[0] <= u2[0] && u2[0] <= u1[0])) &&
  808. ((l2[1] <= u1[1] && u1[1] <= u2[1]) || (l1[1] <= u2[1] && u2[1] <= u1[1]));
  809. };
  810. /**
  811. * @method containsPoint
  812. * @param {Array} point
  813. * @return {boolean}
  814. */
  815. AABB.prototype.containsPoint = function(point){
  816. var l = this.lowerBound,
  817. u = this.upperBound;
  818. return l[0] <= point[0] && point[0] <= u[0] && l[1] <= point[1] && point[1] <= u[1];
  819. };
  820. /**
  821. * Check if the AABB is hit by a ray.
  822. * @method overlapsRay
  823. * @param {Ray} ray
  824. * @return {number} -1 if no hit, a number between 0 and 1 if hit.
  825. */
  826. AABB.prototype.overlapsRay = function(ray){
  827. var t = 0;
  828. // ray.direction is unit direction vector of ray
  829. var dirFracX = 1 / ray.direction[0];
  830. var dirFracY = 1 / ray.direction[1];
  831. // this.lowerBound is the corner of AABB with minimal coordinates - left bottom, rt is maximal corner
  832. var t1 = (this.lowerBound[0] - ray.from[0]) * dirFracX;
  833. var t2 = (this.upperBound[0] - ray.from[0]) * dirFracX;
  834. var t3 = (this.lowerBound[1] - ray.from[1]) * dirFracY;
  835. var t4 = (this.upperBound[1] - ray.from[1]) * dirFracY;
  836. var tmin = Math.max(Math.max(Math.min(t1, t2), Math.min(t3, t4)));
  837. var tmax = Math.min(Math.min(Math.max(t1, t2), Math.max(t3, t4)));
  838. // if tmax < 0, ray (line) is intersecting AABB, but whole AABB is behing us
  839. if (tmax < 0){
  840. //t = tmax;
  841. return -1;
  842. }
  843. // if tmin > tmax, ray doesn't intersect AABB
  844. if (tmin > tmax){
  845. //t = tmax;
  846. return -1;
  847. }
  848. return tmin;
  849. };
  850. },{"../math/vec2":30,"../utils/Utils":57}],8:[function(_dereq_,module,exports){
  851. var vec2 = _dereq_('../math/vec2');
  852. var Body = _dereq_('../objects/Body');
  853. module.exports = Broadphase;
  854. /**
  855. * Base class for broadphase implementations.
  856. * @class Broadphase
  857. * @constructor
  858. */
  859. function Broadphase(type){
  860. this.type = type;
  861. /**
  862. * The resulting overlapping pairs. Will be filled with results during .getCollisionPairs().
  863. * @property result
  864. * @type {Array}
  865. */
  866. this.result = [];
  867. /**
  868. * The world to search for collision pairs in. To change it, use .setWorld()
  869. * @property world
  870. * @type {World}
  871. * @readOnly
  872. */
  873. this.world = null;
  874. /**
  875. * The bounding volume type to use in the broadphase algorithms. Should be set to Broadphase.AABB or Broadphase.BOUNDING_CIRCLE.
  876. * @property {Number} boundingVolumeType
  877. */
  878. this.boundingVolumeType = Broadphase.AABB;
  879. }
  880. /**
  881. * Axis aligned bounding box type.
  882. * @static
  883. * @property {Number} AABB
  884. */
  885. Broadphase.AABB = 1;
  886. /**
  887. * Bounding circle type.
  888. * @static
  889. * @property {Number} BOUNDING_CIRCLE
  890. */
  891. Broadphase.BOUNDING_CIRCLE = 2;
  892. /**
  893. * Set the world that we are searching for collision pairs in.
  894. * @method setWorld
  895. * @param {World} world
  896. */
  897. Broadphase.prototype.setWorld = function(world){
  898. this.world = world;
  899. };
  900. /**
  901. * Get all potential intersecting body pairs.
  902. * @method getCollisionPairs
  903. * @param {World} world The world to search in.
  904. * @return {Array} An array of the bodies, ordered in pairs. Example: A result of [a,b,c,d] means that the potential pairs are: (a,b), (c,d).
  905. */
  906. Broadphase.prototype.getCollisionPairs = function(world){};
  907. var dist = vec2.create();
  908. /**
  909. * Check whether the bounding radius of two bodies overlap.
  910. * @method boundingRadiusCheck
  911. * @param {Body} bodyA
  912. * @param {Body} bodyB
  913. * @return {Boolean}
  914. */
  915. Broadphase.boundingRadiusCheck = function(bodyA, bodyB){
  916. vec2.sub(dist, bodyA.position, bodyB.position);
  917. var d2 = vec2.squaredLength(dist),
  918. r = bodyA.boundingRadius + bodyB.boundingRadius;
  919. return d2 <= r*r;
  920. };
  921. /**
  922. * Check whether the bounding radius of two bodies overlap.
  923. * @method boundingRadiusCheck
  924. * @param {Body} bodyA
  925. * @param {Body} bodyB
  926. * @return {Boolean}
  927. */
  928. Broadphase.aabbCheck = function(bodyA, bodyB){
  929. return bodyA.getAABB().overlaps(bodyB.getAABB());
  930. };
  931. /**
  932. * Check whether the bounding radius of two bodies overlap.
  933. * @method boundingRadiusCheck
  934. * @param {Body} bodyA
  935. * @param {Body} bodyB
  936. * @return {Boolean}
  937. */
  938. Broadphase.prototype.boundingVolumeCheck = function(bodyA, bodyB){
  939. var result;
  940. switch(this.boundingVolumeType){
  941. case Broadphase.BOUNDING_CIRCLE:
  942. result = Broadphase.boundingRadiusCheck(bodyA,bodyB);
  943. break;
  944. case Broadphase.AABB:
  945. result = Broadphase.aabbCheck(bodyA,bodyB);
  946. break;
  947. default:
  948. throw new Error('Bounding volume type not recognized: '+this.boundingVolumeType);
  949. }
  950. return result;
  951. };
  952. /**
  953. * Check whether two bodies are allowed to collide at all.
  954. * @method canCollide
  955. * @param {Body} bodyA
  956. * @param {Body} bodyB
  957. * @return {Boolean}
  958. */
  959. Broadphase.canCollide = function(bodyA, bodyB){
  960. var KINEMATIC = Body.KINEMATIC;
  961. var STATIC = Body.STATIC;
  962. // Cannot collide static bodies
  963. if(bodyA.type === STATIC && bodyB.type === STATIC){
  964. return false;
  965. }
  966. // Cannot collide static vs kinematic bodies
  967. if( (bodyA.type === KINEMATIC && bodyB.type === STATIC) ||
  968. (bodyA.type === STATIC && bodyB.type === KINEMATIC)){
  969. return false;
  970. }
  971. // Cannot collide kinematic vs kinematic
  972. if(bodyA.type === KINEMATIC && bodyB.type === KINEMATIC){
  973. return false;
  974. }
  975. // Cannot collide both sleeping bodies
  976. if(bodyA.sleepState === Body.SLEEPING && bodyB.sleepState === Body.SLEEPING){
  977. return false;
  978. }
  979. // Cannot collide if one is static and the other is sleeping
  980. if( (bodyA.sleepState === Body.SLEEPING && bodyB.type === STATIC) ||
  981. (bodyB.sleepState === Body.SLEEPING && bodyA.type === STATIC)){
  982. return false;
  983. }
  984. return true;
  985. };
  986. Broadphase.NAIVE = 1;
  987. Broadphase.SAP = 2;
  988. },{"../math/vec2":30,"../objects/Body":31}],9:[function(_dereq_,module,exports){
  989. var Circle = _dereq_('../shapes/Circle'),
  990. Plane = _dereq_('../shapes/Plane'),
  991. Shape = _dereq_('../shapes/Shape'),
  992. Particle = _dereq_('../shapes/Particle'),
  993. Broadphase = _dereq_('../collision/Broadphase'),
  994. vec2 = _dereq_('../math/vec2');
  995. module.exports = NaiveBroadphase;
  996. /**
  997. * Naive broadphase implementation. Does N^2 tests.
  998. *
  999. * @class NaiveBroadphase
  1000. * @constructor
  1001. * @extends Broadphase
  1002. */
  1003. function NaiveBroadphase(){
  1004. Broadphase.call(this, Broadphase.NAIVE);
  1005. }
  1006. NaiveBroadphase.prototype = new Broadphase();
  1007. NaiveBroadphase.prototype.constructor = NaiveBroadphase;
  1008. /**
  1009. * Get the colliding pairs
  1010. * @method getCollisionPairs
  1011. * @param {World} world
  1012. * @return {Array}
  1013. */
  1014. NaiveBroadphase.prototype.getCollisionPairs = function(world){
  1015. var bodies = world.bodies,
  1016. result = this.result;
  1017. result.length = 0;
  1018. for(var i=0, Ncolliding=bodies.length; i!==Ncolliding; i++){
  1019. var bi = bodies[i];
  1020. for(var j=0; j<i; j++){
  1021. var bj = bodies[j];
  1022. if(Broadphase.canCollide(bi,bj) && this.boundingVolumeCheck(bi,bj)){
  1023. result.push(bi,bj);
  1024. }
  1025. }
  1026. }
  1027. return result;
  1028. };
  1029. /**
  1030. * Returns all the bodies within an AABB.
  1031. * @method aabbQuery
  1032. * @param {World} world
  1033. * @param {AABB} aabb
  1034. * @param {array} result An array to store resulting bodies in.
  1035. * @return {array}
  1036. */
  1037. NaiveBroadphase.prototype.aabbQuery = function(world, aabb, result){
  1038. result = result || [];
  1039. var bodies = world.bodies;
  1040. for(var i = 0; i < bodies.length; i++){
  1041. var b = bodies[i];
  1042. if(b.aabbNeedsUpdate){
  1043. b.updateAABB();
  1044. }
  1045. if(b.aabb.overlaps(aabb)){
  1046. result.push(b);
  1047. }
  1048. }
  1049. return result;
  1050. };
  1051. },{"../collision/Broadphase":8,"../math/vec2":30,"../shapes/Circle":39,"../shapes/Particle":43,"../shapes/Plane":44,"../shapes/Shape":45}],10:[function(_dereq_,module,exports){
  1052. var vec2 = _dereq_('../math/vec2')
  1053. , sub = vec2.sub
  1054. , add = vec2.add
  1055. , dot = vec2.dot
  1056. , Utils = _dereq_('../utils/Utils')
  1057. , ContactEquationPool = _dereq_('../utils/ContactEquationPool')
  1058. , FrictionEquationPool = _dereq_('../utils/FrictionEquationPool')
  1059. , TupleDictionary = _dereq_('../utils/TupleDictionary')
  1060. , Equation = _dereq_('../equations/Equation')
  1061. , ContactEquation = _dereq_('../equations/ContactEquation')
  1062. , FrictionEquation = _dereq_('../equations/FrictionEquation')
  1063. , Circle = _dereq_('../shapes/Circle')
  1064. , Convex = _dereq_('../shapes/Convex')
  1065. , Shape = _dereq_('../shapes/Shape')
  1066. , Body = _dereq_('../objects/Body')
  1067. , Box = _dereq_('../shapes/Box');
  1068. module.exports = Narrowphase;
  1069. // Temp things
  1070. var yAxis = vec2.fromValues(0,1);
  1071. var tmp1 = vec2.fromValues(0,0)
  1072. , tmp2 = vec2.fromValues(0,0)
  1073. , tmp3 = vec2.fromValues(0,0)
  1074. , tmp4 = vec2.fromValues(0,0)
  1075. , tmp5 = vec2.fromValues(0,0)
  1076. , tmp6 = vec2.fromValues(0,0)
  1077. , tmp7 = vec2.fromValues(0,0)
  1078. , tmp8 = vec2.fromValues(0,0)
  1079. , tmp9 = vec2.fromValues(0,0)
  1080. , tmp10 = vec2.fromValues(0,0)
  1081. , tmp11 = vec2.fromValues(0,0)
  1082. , tmp12 = vec2.fromValues(0,0)
  1083. , tmp13 = vec2.fromValues(0,0)
  1084. , tmp14 = vec2.fromValues(0,0)
  1085. , tmp15 = vec2.fromValues(0,0)
  1086. , tmp16 = vec2.fromValues(0,0)
  1087. , tmp17 = vec2.fromValues(0,0)
  1088. , tmp18 = vec2.fromValues(0,0)
  1089. , tmpArray = [];
  1090. /**
  1091. * Narrowphase. Creates contacts and friction given shapes and transforms.
  1092. * @class Narrowphase
  1093. * @constructor
  1094. */
  1095. function Narrowphase(){
  1096. /**
  1097. * @property contactEquations
  1098. * @type {Array}
  1099. */
  1100. this.contactEquations = [];
  1101. /**
  1102. * @property frictionEquations
  1103. * @type {Array}
  1104. */
  1105. this.frictionEquations = [];
  1106. /**
  1107. * Whether to make friction equations in the upcoming contacts.
  1108. * @property enableFriction
  1109. * @type {Boolean}
  1110. */
  1111. this.enableFriction = true;
  1112. /**
  1113. * Whether to make equations enabled in upcoming contacts.
  1114. * @property enabledEquations
  1115. * @type {Boolean}
  1116. */
  1117. this.enabledEquations = true;
  1118. /**
  1119. * The friction slip force to use when creating friction equations.
  1120. * @property slipForce
  1121. * @type {Number}
  1122. */
  1123. this.slipForce = 10.0;
  1124. /**
  1125. * The friction value to use in the upcoming friction equations.
  1126. * @property frictionCoefficient
  1127. * @type {Number}
  1128. */
  1129. this.frictionCoefficient = 0.3;
  1130. /**
  1131. * Will be the .relativeVelocity in each produced FrictionEquation.
  1132. * @property {Number} surfaceVelocity
  1133. */
  1134. this.surfaceVelocity = 0;
  1135. /**
  1136. * Keeps track of the allocated ContactEquations.
  1137. * @property {ContactEquationPool} contactEquationPool
  1138. *
  1139. * @example
  1140. *
  1141. * // Allocate a few equations before starting the simulation.
  1142. * // This way, no contact objects need to be created on the fly in the game loop.
  1143. * world.narrowphase.contactEquationPool.resize(1024);
  1144. * world.narrowphase.frictionEquationPool.resize(1024);
  1145. */
  1146. this.contactEquationPool = new ContactEquationPool({ size: 32 });
  1147. /**
  1148. * Keeps track of the allocated ContactEquations.
  1149. * @property {FrictionEquationPool} frictionEquationPool
  1150. */
  1151. this.frictionEquationPool = new FrictionEquationPool({ size: 64 });
  1152. /**
  1153. * The restitution value to use in the next contact equations.
  1154. * @property restitution
  1155. * @type {Number}
  1156. */
  1157. this.restitution = 0;
  1158. /**
  1159. * The stiffness value to use in the next contact equations.
  1160. * @property {Number} stiffness
  1161. */
  1162. this.stiffness = Equation.DEFAULT_STIFFNESS;
  1163. /**
  1164. * The stiffness value to use in the next contact equations.
  1165. * @property {Number} stiffness
  1166. */
  1167. this.relaxation = Equation.DEFAULT_RELAXATION;
  1168. /**
  1169. * The stiffness value to use in the next friction equations.
  1170. * @property frictionStiffness
  1171. * @type {Number}
  1172. */
  1173. this.frictionStiffness = Equation.DEFAULT_STIFFNESS;
  1174. /**
  1175. * The relaxation value to use in the next friction equations.
  1176. * @property frictionRelaxation
  1177. * @type {Number}
  1178. */
  1179. this.frictionRelaxation = Equation.DEFAULT_RELAXATION;
  1180. /**
  1181. * Enable reduction of friction equations. If disabled, a box on a plane will generate 2 contact equations and 2 friction equations. If enabled, there will be only one friction equation. Same kind of simplifications are made for all collision types.
  1182. * @property enableFrictionReduction
  1183. * @type {Boolean}
  1184. * @deprecated This flag will be removed when the feature is stable enough.
  1185. * @default true
  1186. */
  1187. this.enableFrictionReduction = true;
  1188. /**
  1189. * Keeps track of the colliding bodies last step.
  1190. * @private
  1191. * @property collidingBodiesLastStep
  1192. * @type {TupleDictionary}
  1193. */
  1194. this.collidingBodiesLastStep = new TupleDictionary();
  1195. /**
  1196. * Contact skin size value to use in the next contact equations.
  1197. * @property {Number} contactSkinSize
  1198. * @default 0.01
  1199. */
  1200. this.contactSkinSize = 0.01;
  1201. }
  1202. var bodiesOverlap_shapePositionA = vec2.create();
  1203. var bodiesOverlap_shapePositionB = vec2.create();
  1204. /**
  1205. * @method bodiesOverlap
  1206. * @param {Body} bodyA
  1207. * @param {Body} bodyB
  1208. * @return {Boolean}
  1209. * @todo shape world transforms are wrong
  1210. */
  1211. Narrowphase.prototype.bodiesOverlap = function(bodyA, bodyB){
  1212. var shapePositionA = bodiesOverlap_shapePositionA;
  1213. var shapePositionB = bodiesOverlap_shapePositionB;
  1214. // Loop over all shapes of bodyA
  1215. for(var k=0, Nshapesi=bodyA.shapes.length; k!==Nshapesi; k++){
  1216. var shapeA = bodyA.shapes[k];
  1217. bodyA.toWorldFrame(shapePositionA, shapeA.position);
  1218. // All shapes of body j
  1219. for(var l=0, Nshapesj=bodyB.shapes.length; l!==Nshapesj; l++){
  1220. var shapeB = bodyB.shapes[l];
  1221. bodyB.toWorldFrame(shapePositionB, shapeB.position);
  1222. if(this[shapeA.type | shapeB.type](
  1223. bodyA,
  1224. shapeA,
  1225. shapePositionA,
  1226. shapeA.angle + bodyA.angle,
  1227. bodyB,
  1228. shapeB,
  1229. shapePositionB,
  1230. shapeB.angle + bodyB.angle,
  1231. true
  1232. )){
  1233. return true;
  1234. }
  1235. }
  1236. }
  1237. return false;
  1238. };
  1239. /**
  1240. * Check if the bodies were in contact since the last reset().
  1241. * @method collidedLastStep
  1242. * @param {Body} bodyA
  1243. * @param {Body} bodyB
  1244. * @return {Boolean}
  1245. */
  1246. Narrowphase.prototype.collidedLastStep = function(bodyA, bodyB){
  1247. var id1 = bodyA.id|0,
  1248. id2 = bodyB.id|0;
  1249. return !!this.collidingBodiesLastStep.get(id1, id2);
  1250. };
  1251. /**
  1252. * Throws away the old equations and gets ready to create new
  1253. * @method reset
  1254. */
  1255. Narrowphase.prototype.reset = function(){
  1256. this.collidingBodiesLastStep.reset();
  1257. var eqs = this.contactEquations;
  1258. var l = eqs.length;
  1259. while(l--){
  1260. var eq = eqs[l],
  1261. id1 = eq.bodyA.id,
  1262. id2 = eq.bodyB.id;
  1263. this.collidingBodiesLastStep.set(id1, id2, true);
  1264. }
  1265. var ce = this.contactEquations,
  1266. fe = this.frictionEquations;
  1267. for(var i=0; i<ce.length; i++){
  1268. this.contactEquationPool.release(ce[i]);
  1269. }
  1270. for(var i=0; i<fe.length; i++){
  1271. this.frictionEquationPool.release(fe[i]);
  1272. }
  1273. // Reset
  1274. this.contactEquations.length = this.frictionEquations.length = 0;
  1275. };
  1276. /**
  1277. * Creates a ContactEquation, either by reusing an existing object or creating a new one.
  1278. * @method createContactEquation
  1279. * @param {Body} bodyA
  1280. * @param {Body} bodyB
  1281. * @return {ContactEquation}
  1282. */
  1283. Narrowphase.prototype.createContactEquation = function(bodyA, bodyB, shapeA, shapeB){
  1284. var c = this.contactEquationPool.get();
  1285. c.bodyA = bodyA;
  1286. c.bodyB = bodyB;
  1287. c.shapeA = shapeA;
  1288. c.shapeB = shapeB;
  1289. c.restitution = this.restitution;
  1290. c.firstImpact = !this.collidedLastStep(bodyA,bodyB);
  1291. c.stiffness = this.stiffness;
  1292. c.relaxation = this.relaxation;
  1293. c.needsUpdate = true;
  1294. c.enabled = this.enabledEquations;
  1295. c.offset = this.contactSkinSize;
  1296. return c;
  1297. };
  1298. /**
  1299. * Creates a FrictionEquation, either by reusing an existing object or creating a new one.
  1300. * @method createFrictionEquation
  1301. * @param {Body} bodyA
  1302. * @param {Body} bodyB
  1303. * @return {FrictionEquation}
  1304. */
  1305. Narrowphase.prototype.createFrictionEquation = function(bodyA, bodyB, shapeA, shapeB){
  1306. var c = this.frictionEquationPool.get();
  1307. c.bodyA = bodyA;
  1308. c.bodyB = bodyB;
  1309. c.shapeA = shapeA;
  1310. c.shapeB = shapeB;
  1311. c.setSlipForce(this.slipForce);
  1312. c.frictionCoefficient = this.frictionCoefficient;
  1313. c.relativeVelocity = this.surfaceVelocity;
  1314. c.enabled = this.enabledEquations;
  1315. c.needsUpdate = true;
  1316. c.stiffness = this.frictionStiffness;
  1317. c.relaxation = this.frictionRelaxation;
  1318. c.contactEquations.length = 0;
  1319. return c;
  1320. };
  1321. /**
  1322. * Creates a FrictionEquation given the data in the ContactEquation. Uses same offset vectors ri and rj, but the tangent vector will be constructed from the collision normal.
  1323. * @method createFrictionFromContact
  1324. * @param {ContactEquation} contactEquation
  1325. * @return {FrictionEquation}
  1326. */
  1327. Narrowphase.prototype.createFrictionFromContact = function(c){
  1328. var eq = this.createFrictionEquation(c.bodyA, c.bodyB, c.shapeA, c.shapeB);
  1329. vec2.copy(eq.contactPointA, c.contactPointA);
  1330. vec2.copy(eq.contactPointB, c.contactPointB);
  1331. vec2.rotate90cw(eq.t, c.normalA);
  1332. eq.contactEquations.push(c);
  1333. return eq;
  1334. };
  1335. // Take the average N latest contact point on the plane.
  1336. Narrowphase.prototype.createFrictionFromAverage = function(numContacts){
  1337. var c = this.contactEquations[this.contactEquations.length - 1];
  1338. var eq = this.createFrictionEquation(c.bodyA, c.bodyB, c.shapeA, c.shapeB);
  1339. var bodyA = c.bodyA;
  1340. var bodyB = c.bodyB;
  1341. vec2.set(eq.contactPointA, 0, 0);
  1342. vec2.set(eq.contactPointB, 0, 0);
  1343. vec2.set(eq.t, 0, 0);
  1344. for(var i=0; i!==numContacts; i++){
  1345. c = this.contactEquations[this.contactEquations.length - 1 - i];
  1346. if(c.bodyA === bodyA){
  1347. vec2.add(eq.t, eq.t, c.normalA);
  1348. vec2.add(eq.contactPointA, eq.contactPointA, c.contactPointA);
  1349. vec2.add(eq.contactPointB, eq.contactPointB, c.contactPointB);
  1350. } else {
  1351. vec2.sub(eq.t, eq.t, c.normalA);
  1352. vec2.add(eq.contactPointA, eq.contactPointA, c.contactPointB);
  1353. vec2.add(eq.contactPointB, eq.contactPointB, c.contactPointA);
  1354. }
  1355. eq.contactEquations.push(c);
  1356. }
  1357. var invNumContacts = 1/numContacts;
  1358. vec2.scale(eq.contactPointA, eq.contactPointA, invNumContacts);
  1359. vec2.scale(eq.contactPointB, eq.contactPointB, invNumContacts);
  1360. vec2.normalize(eq.t, eq.t);
  1361. vec2.rotate90cw(eq.t, eq.t);
  1362. return eq;
  1363. };
  1364. /**
  1365. * Convex/line narrowphase
  1366. * @method convexLine
  1367. * @param {Body} convexBody
  1368. * @param {Convex} convexShape
  1369. * @param {Array} convexOffset
  1370. * @param {Number} convexAngle
  1371. * @param {Body} lineBody
  1372. * @param {Line} lineShape
  1373. * @param {Array} lineOffset
  1374. * @param {Number} lineAngle
  1375. * @param {boolean} justTest
  1376. * @todo Implement me!
  1377. */
  1378. Narrowphase.prototype[Shape.LINE | Shape.CONVEX] =
  1379. Narrowphase.prototype.convexLine = function(
  1380. convexBody,
  1381. convexShape,
  1382. convexOffset,
  1383. convexAngle,
  1384. lineBody,
  1385. lineShape,
  1386. lineOffset,
  1387. lineAngle,
  1388. justTest
  1389. ){
  1390. // TODO
  1391. if(justTest){
  1392. return false;
  1393. } else {
  1394. return 0;
  1395. }
  1396. };
  1397. /**
  1398. * Line/box narrowphase
  1399. * @method lineBox
  1400. * @param {Body} lineBody
  1401. * @param {Line} lineShape
  1402. * @param {Array} lineOffset
  1403. * @param {Number} lineAngle
  1404. * @param {Body} boxBody
  1405. * @param {Box} boxShape
  1406. * @param {Array} boxOffset
  1407. * @param {Number} boxAngle
  1408. * @param {Boolean} justTest
  1409. * @todo Implement me!
  1410. */
  1411. Narrowphase.prototype[Shape.LINE | Shape.BOX] =
  1412. Narrowphase.prototype.lineBox = function(
  1413. lineBody,
  1414. lineShape,
  1415. lineOffset,
  1416. lineAngle,
  1417. boxBody,
  1418. boxShape,
  1419. boxOffset,
  1420. boxAngle,
  1421. justTest
  1422. ){
  1423. // TODO
  1424. if(justTest){
  1425. return false;
  1426. } else {
  1427. return 0;
  1428. }
  1429. };
  1430. function setConvexToCapsuleShapeMiddle(convexShape, capsuleShape){
  1431. vec2.set(convexShape.vertices[0], -capsuleShape.length * 0.5, -capsuleShape.radius);
  1432. vec2.set(convexShape.vertices[1], capsuleShape.length * 0.5, -capsuleShape.radius);
  1433. vec2.set(convexShape.vertices[2], capsuleShape.length * 0.5, capsuleShape.radius);
  1434. vec2.set(convexShape.vertices[3], -capsuleShape.length * 0.5, capsuleShape.radius);
  1435. }
  1436. var convexCapsule_tempRect = new Box({ width: 1, height: 1 }),
  1437. convexCapsule_tempVec = vec2.create();
  1438. /**
  1439. * Convex/capsule narrowphase
  1440. * @method convexCapsule
  1441. * @param {Body} convexBody
  1442. * @param {Convex} convexShape
  1443. * @param {Array} convexPosition
  1444. * @param {Number} convexAngle
  1445. * @param {Body} capsuleBody
  1446. * @param {Capsule} capsuleShape
  1447. * @param {Array} capsulePosition
  1448. * @param {Number} capsuleAngle
  1449. */
  1450. Narrowphase.prototype[Shape.CAPSULE | Shape.CONVEX] =
  1451. Narrowphase.prototype[Shape.CAPSULE | Shape.BOX] =
  1452. Narrowphase.prototype.convexCapsule = function(
  1453. convexBody,
  1454. convexShape,
  1455. convexPosition,
  1456. convexAngle,
  1457. capsuleBody,
  1458. capsuleShape,
  1459. capsulePosition,
  1460. capsuleAngle,
  1461. justTest
  1462. ){
  1463. // Check the circles
  1464. // Add offsets!
  1465. var circlePos = convexCapsule_tempVec;
  1466. vec2.set(circlePos, capsuleShape.length/2,0);
  1467. vec2.rotate(circlePos,circlePos,capsuleAngle);
  1468. vec2.add(circlePos,circlePos,capsulePosition);
  1469. var result1 = this.circleConvex(capsuleBody,capsuleShape,circlePos,capsuleAngle, convexBody,convexShape,convexPosition,convexAngle, justTest, capsuleShape.radius);
  1470. vec2.set(circlePos,-capsuleShape.length/2, 0);
  1471. vec2.rotate(circlePos,circlePos,capsuleAngle);
  1472. vec2.add(circlePos,circlePos,capsulePosition);
  1473. var result2 = this.circleConvex(capsuleBody,capsuleShape,circlePos,capsuleAngle, convexBody,convexShape,convexPosition,convexAngle, justTest, capsuleShape.radius);
  1474. if(justTest && (result1 || result2)){
  1475. return true;
  1476. }
  1477. // Check center rect
  1478. var r = convexCapsule_tempRect;
  1479. setConvexToCapsuleShapeMiddle(r,capsuleShape);
  1480. var result = this.convexConvex(convexBody,convexShape,convexPosition,convexAngle, capsuleBody,r,capsulePosition,capsuleAngle, justTest);
  1481. return result + result1 + result2;
  1482. };
  1483. /**
  1484. * Capsule/line narrowphase
  1485. * @method lineCapsule
  1486. * @param {Body} lineBody
  1487. * @param {Line} lineShape
  1488. * @param {Array} linePosition
  1489. * @param {Number} lineAngle
  1490. * @param {Body} capsuleBody
  1491. * @param {Capsule} capsuleShape
  1492. * @param {Array} capsulePosition
  1493. * @param {Number} capsuleAngle
  1494. * @todo Implement me!
  1495. */
  1496. Narrowphase.prototype[Shape.CAPSULE | Shape.LINE] =
  1497. Narrowphase.prototype.lineCapsule = function(
  1498. lineBody,
  1499. lineShape,
  1500. linePosition,
  1501. lineAngle,
  1502. capsuleBody,
  1503. capsuleShape,
  1504. capsulePosition,
  1505. capsuleAngle,
  1506. justTest
  1507. ){
  1508. // TODO
  1509. if(justTest){
  1510. return false;
  1511. } else {
  1512. return 0;
  1513. }
  1514. };
  1515. var capsuleCapsule_tempVec1 = vec2.create();
  1516. var capsuleCapsule_tempVec2 = vec2.create();
  1517. var capsuleCapsule_tempRect1 = new Box({ width: 1, height: 1 });
  1518. /**
  1519. * Capsule/capsule narrowphase
  1520. * @method capsuleCapsule
  1521. * @param {Body} bi
  1522. * @param {Capsule} si
  1523. * @param {Array} xi
  1524. * @param {Number} ai
  1525. * @param {Body} bj
  1526. * @param {Capsule} sj
  1527. * @param {Array} xj
  1528. * @param {Number} aj
  1529. */
  1530. Narrowphase.prototype[Shape.CAPSULE | Shape.CAPSULE] =
  1531. Narrowphase.prototype.capsuleCapsule = function(bi,si,xi,ai, bj,sj,xj,aj, justTest){
  1532. var enableFrictionBefore;
  1533. // Check the circles
  1534. // Add offsets!
  1535. var circlePosi = capsuleCapsule_tempVec1,
  1536. circlePosj = capsuleCapsule_tempVec2;
  1537. var numContacts = 0;
  1538. // Need 4 circle checks, between all
  1539. for(var i=0; i<2; i++){
  1540. vec2.set(circlePosi,(i===0?-1:1)*si.length/2,0);
  1541. vec2.rotate(circlePosi,circlePosi,ai);
  1542. vec2.add(circlePosi,circlePosi,xi);
  1543. for(var j=0; j<2; j++){
  1544. vec2.set(circlePosj,(j===0?-1:1)*sj.length/2, 0);
  1545. vec2.rotate(circlePosj,circlePosj,aj);
  1546. vec2.add(circlePosj,circlePosj,xj);
  1547. // Temporarily turn off friction
  1548. if(this.enableFrictionReduction){
  1549. enableFrictionBefore = this.enableFriction;
  1550. this.enableFriction = false;
  1551. }
  1552. var result = this.circleCircle(bi,si,circlePosi,ai, bj,sj,circlePosj,aj, justTest, si.radius, sj.radius);
  1553. if(this.enableFrictionReduction){
  1554. this.enableFriction = enableFrictionBefore;
  1555. }
  1556. if(justTest && result){
  1557. return true;
  1558. }
  1559. numContacts += result;
  1560. }
  1561. }
  1562. if(this.enableFrictionReduction){
  1563. // Temporarily turn off friction
  1564. enableFrictionBefore = this.enableFriction;
  1565. this.enableFriction = false;
  1566. }
  1567. // Check circles against the center boxs
  1568. var rect = capsuleCapsule_tempRect1;
  1569. setConvexToCapsuleShapeMiddle(rect,si);
  1570. var result1 = this.convexCapsule(bi,rect,xi,ai, bj,sj,xj,aj, justTest);
  1571. if(this.enableFrictionReduction){
  1572. this.enableFriction = enableFrictionBefore;
  1573. }
  1574. if(justTest && result1){
  1575. return true;
  1576. }
  1577. numContacts += result1;
  1578. if(this.enableFrictionReduction){
  1579. // Temporarily turn off friction
  1580. var enableFrictionBefore = this.enableFriction;
  1581. this.enableFriction = false;
  1582. }
  1583. setConvexToCapsuleShapeMiddle(rect,sj);
  1584. var result2 = this.convexCapsule(bj,rect,xj,aj, bi,si,xi,ai, justTest);
  1585. if(this.enableFrictionReduction){
  1586. this.enableFriction = enableFrictionBefore;
  1587. }
  1588. if(justTest && result2){
  1589. return true;
  1590. }
  1591. numContacts += result2;
  1592. if(this.enableFrictionReduction){
  1593. if(numContacts && this.enableFriction){
  1594. this.frictionEquations.push(this.createFrictionFromAverage(numContacts));
  1595. }
  1596. }
  1597. return numContacts;
  1598. };
  1599. /**
  1600. * Line/line narrowphase
  1601. * @method lineLine
  1602. * @param {Body} bodyA
  1603. * @param {Line} shapeA
  1604. * @param {Array} positionA
  1605. * @param {Number} angleA
  1606. * @param {Body} bodyB
  1607. * @param {Line} shapeB
  1608. * @param {Array} positionB
  1609. * @param {Number} angleB
  1610. * @todo Implement me!
  1611. */
  1612. Narrowphase.prototype[Shape.LINE | Shape.LINE] =
  1613. Narrowphase.prototype.lineLine = function(
  1614. bodyA,
  1615. shapeA,
  1616. positionA,
  1617. angleA,
  1618. bodyB,
  1619. shapeB,
  1620. positionB,
  1621. angleB,
  1622. justTest
  1623. ){
  1624. // TODO
  1625. if(justTest){
  1626. return false;
  1627. } else {
  1628. return 0;
  1629. }
  1630. };
  1631. /**
  1632. * Plane/line Narrowphase
  1633. * @method planeLine
  1634. * @param {Body} planeBody
  1635. * @param {Plane} planeShape
  1636. * @param {Array} planeOffset
  1637. * @param {Number} planeAngle
  1638. * @param {Body} lineBody
  1639. * @param {Line} lineShape
  1640. * @param {Array} lineOffset
  1641. * @param {Number} lineAngle
  1642. */
  1643. Narrowphase.prototype[Shape.PLANE | Shape.LINE] =
  1644. Narrowphase.prototype.planeLine = function(planeBody, planeShape, planeOffset, planeAngle,
  1645. lineBody, lineShape, lineOffset, lineAngle, justTest){
  1646. var worldVertex0 = tmp1,
  1647. worldVertex1 = tmp2,
  1648. worldVertex01 = tmp3,
  1649. worldVertex11 = tmp4,
  1650. worldEdge = tmp5,
  1651. worldEdgeUnit = tmp6,
  1652. dist = tmp7,
  1653. worldNormal = tmp8,
  1654. worldTangent = tmp9,
  1655. verts = tmpArray,
  1656. numContacts = 0;
  1657. // Get start and end points
  1658. vec2.set(worldVertex0, -lineShape.length/2, 0);
  1659. vec2.set(worldVertex1, lineShape.length/2, 0);
  1660. // Not sure why we have to use worldVertex*1 here, but it won't work otherwise. Tired.
  1661. vec2.rotate(worldVertex01, worldVertex0, lineAngle);
  1662. vec2.rotate(worldVertex11, worldVertex1, lineAngle);
  1663. add(worldVertex01, worldVertex01, lineOffset);
  1664. add(worldVertex11, worldVertex11, lineOffset);
  1665. vec2.copy(worldVertex0,worldVertex01);
  1666. vec2.copy(worldVertex1,worldVertex11);
  1667. // Get vector along the line
  1668. sub(worldEdge, worldVertex1, worldVertex0);
  1669. vec2.normalize(worldEdgeUnit, worldEdge);
  1670. // Get tangent to the edge.
  1671. vec2.rotate90cw(worldTangent, worldEdgeUnit);
  1672. vec2.rotate(worldNormal, yAxis, planeAngle);
  1673. // Check line ends
  1674. verts[0] = worldVertex0;
  1675. verts[1] = worldVertex1;
  1676. for(var i=0; i<verts.length; i++){
  1677. var v = verts[i];
  1678. sub(dist, v, planeOffset);
  1679. var d = dot(dist,worldNormal);
  1680. if(d < 0){
  1681. if(justTest){
  1682. return true;
  1683. }
  1684. var c = this.createContactEquation(planeBody,lineBody,planeShape,lineShape);
  1685. numContacts++;
  1686. vec2.copy(c.normalA, worldNormal);
  1687. vec2.normalize(c.normalA,c.normalA);
  1688. // distance vector along plane normal
  1689. vec2.scale(dist, worldNormal, d);
  1690. // Vector from plane center to contact
  1691. sub(c.contactPointA, v, dist);
  1692. sub(c.contactPointA, c.contactPointA, planeBody.position);
  1693. // From line center to contact
  1694. sub(c.contactPointB, v, lineOffset);
  1695. add(c.contactPointB, c.contactPointB, lineOffset);
  1696. sub(c.contactPointB, c.contactPointB, lineBody.position);
  1697. this.contactEquations.push(c);
  1698. if(!this.enableFrictionReduction){
  1699. if(this.enableFriction){
  1700. this.frictionEquations.push(this.createFrictionFromContact(c));
  1701. }
  1702. }
  1703. }
  1704. }
  1705. if(justTest){
  1706. return false;
  1707. }
  1708. if(!this.enableFrictionReduction){
  1709. if(numContacts && this.enableFriction){
  1710. this.frictionEquations.push(this.createFrictionFromAverage(numContacts));
  1711. }
  1712. }
  1713. return numContacts;
  1714. };
  1715. Narrowphase.prototype[Shape.PARTICLE | Shape.CAPSULE] =
  1716. Narrowphase.prototype.particleCapsule = function(
  1717. particleBody,
  1718. particleShape,
  1719. particlePosition,
  1720. particleAngle,
  1721. capsuleBody,
  1722. capsuleShape,
  1723. capsulePosition,
  1724. capsuleAngle,
  1725. justTest
  1726. ){
  1727. return this.circleLine(particleBody,particleShape,particlePosition,particleAngle, capsuleBody,capsuleShape,capsulePosition,capsuleAngle, justTest, capsuleShape.radius, 0);
  1728. };
  1729. /**
  1730. * Circle/line Narrowphase
  1731. * @method circleLine
  1732. * @param {Body} circleBody
  1733. * @param {Circle} circleShape
  1734. * @param {Array} circleOffset
  1735. * @param {Number} circleAngle
  1736. * @param {Body} lineBody
  1737. * @param {Line} lineShape
  1738. * @param {Array} lineOffset
  1739. * @param {Number} lineAngle
  1740. * @param {Boolean} justTest If set to true, this function will return the result (intersection or not) without adding equations.
  1741. * @param {Number} lineRadius Radius to add to the line. Can be used to test Capsules.
  1742. * @param {Number} circleRadius If set, this value overrides the circle shape radius.
  1743. */
  1744. Narrowphase.prototype[Shape.CIRCLE | Shape.LINE] =
  1745. Narrowphase.prototype.circleLine = function(
  1746. circleBody,
  1747. circleShape,
  1748. circleOffset,
  1749. circleAngle,
  1750. lineBody,
  1751. lineShape,
  1752. lineOffset,
  1753. lineAngle,
  1754. justTest,
  1755. lineRadius,
  1756. circleRadius
  1757. ){
  1758. var lineRadius = lineRadius || 0,
  1759. circleRadius = typeof(circleRadius)!=="undefined" ? circleRadius : circleShape.radius,
  1760. orthoDist = tmp1,
  1761. lineToCircleOrthoUnit = tmp2,
  1762. projectedPoint = tmp3,
  1763. centerDist = tmp4,
  1764. worldTangent = tmp5,
  1765. worldEdge = tmp6,
  1766. worldEdgeUnit = tmp7,
  1767. worldVertex0 = tmp8,
  1768. worldVertex1 = tmp9,
  1769. worldVertex01 = tmp10,
  1770. worldVertex11 = tmp11,
  1771. dist = tmp12,
  1772. lineToCircle = tmp13,
  1773. lineEndToLineRadius = tmp14,
  1774. verts = tmpArray;
  1775. // Get start and end points
  1776. vec2.set(worldVertex0, -lineShape.length/2, 0);
  1777. vec2.set(worldVertex1, lineShape.length/2, 0);
  1778. // Not sure why we have to use worldVertex*1 here, but it won't work otherwise. Tired.
  1779. vec2.rotate(worldVertex01, worldVertex0, lineAngle);
  1780. vec2.rotate(worldVertex11, worldVertex1, lineAngle);
  1781. add(worldVertex01, worldVertex01, lineOffset);
  1782. add(worldVertex11, worldVertex11, lineOffset);
  1783. vec2.copy(worldVertex0,worldVertex01);
  1784. vec2.copy(worldVertex1,worldVertex11);
  1785. // Get vector along the line
  1786. sub(worldEdge, worldVertex1, worldVertex0);
  1787. vec2.normalize(worldEdgeUnit, worldEdge);
  1788. // Get tangent to the edge.
  1789. vec2.rotate90cw(worldTangent, worldEdgeUnit);
  1790. // Check distance from the plane spanned by the edge vs the circle
  1791. sub(dist, circleOffset, worldVertex0);
  1792. var d = dot(dist, worldTangent); // Distance from center of line to circle center
  1793. sub(centerDist, worldVertex0, lineOffset);
  1794. sub(lineToCircle, circleOffset, lineOffset);
  1795. var radiusSum = circleRadius + lineRadius;
  1796. if(Math.abs(d) < radiusSum){
  1797. // Now project the circle onto the edge
  1798. vec2.scale(orthoDist, worldTangent, d);
  1799. sub(projectedPoint, circleOffset, orthoDist);
  1800. // Add the missing line radius
  1801. vec2.scale(lineToCircleOrthoUnit, worldTangent, dot(worldTangent, lineToCircle));
  1802. vec2.normalize(lineToCircleOrthoUnit,lineToCircleOrthoUnit);
  1803. vec2.scale(lineToCircleOrthoUnit, lineToCircleOrthoUnit, lineRadius);
  1804. add(projectedPoint,projectedPoint,lineToCircleOrthoUnit);
  1805. // Check if the point is within the edge span
  1806. var pos = dot(worldEdgeUnit, projectedPoint);
  1807. var pos0 = dot(worldEdgeUnit, worldVertex0);
  1808. var pos1 = dot(worldEdgeUnit, worldVertex1);
  1809. if(pos > pos0 && pos < pos1){
  1810. // We got contact!
  1811. if(justTest){
  1812. return true;
  1813. }
  1814. var c = this.createContactEquation(circleBody,lineBody,circleShape,lineShape);
  1815. vec2.scale(c.normalA, orthoDist, -1);
  1816. vec2.normalize(c.normalA, c.normalA);
  1817. vec2.scale( c.contactPointA, c.normalA, circleRadius);
  1818. add(c.contactPointA, c.contactPointA, circleOffset);
  1819. sub(c.contactPointA, c.contactPointA, circleBody.position);
  1820. sub(c.contactPointB, projectedPoint, lineOffset);
  1821. add(c.contactPointB, c.contactPointB, lineOffset);
  1822. sub(c.contactPointB, c.contactPointB, lineBody.position);
  1823. this.contactEquations.push(c);
  1824. if(this.enableFriction){
  1825. this.frictionEquations.push(this.createFrictionFromContact(c));
  1826. }
  1827. return 1;
  1828. }
  1829. }
  1830. // Add corner
  1831. verts[0] = worldVertex0;
  1832. verts[1] = worldVertex1;
  1833. for(var i=0; i<verts.length; i++){
  1834. var v = verts[i];
  1835. sub(dist, v, circleOffset);
  1836. if(vec2.squaredLength(dist) < Math.pow(radiusSum, 2)){
  1837. if(justTest){
  1838. return true;
  1839. }
  1840. var c = this.createContactEquation(circleBody,lineBody,circleShape,lineShape);
  1841. vec2.copy(c.normalA, dist);
  1842. vec2.normalize(c.normalA,c.normalA);
  1843. // Vector from circle to contact point is the normal times the circle radius
  1844. vec2.scale(c.contactPointA, c.normalA, circleRadius);
  1845. add(c.contactPointA, c.contactPointA, circleOffset);
  1846. sub(c.contactPointA, c.contactPointA, circleBody.position);
  1847. sub(c.contactPointB, v, lineOffset);
  1848. vec2.scale(lineEndToLineRadius, c.normalA, -lineRadius);
  1849. add(c.contactPointB, c.contactPointB, lineEndToLineRadius);
  1850. add(c.contactPointB, c.contactPointB, lineOffset);
  1851. sub(c.contactPointB, c.contactPointB, lineBody.position);
  1852. this.contactEquations.push(c);
  1853. if(this.enableFriction){
  1854. this.frictionEquations.push(this.createFrictionFromContact(c));
  1855. }
  1856. return 1;
  1857. }
  1858. }
  1859. return 0;
  1860. };
  1861. /**
  1862. * Circle/capsule Narrowphase
  1863. * @method circleCapsule
  1864. * @param {Body} bi
  1865. * @param {Circle} si
  1866. * @param {Array} xi
  1867. * @param {Number} ai
  1868. * @param {Body} bj
  1869. * @param {Line} sj
  1870. * @param {Array} xj
  1871. * @param {Number} aj
  1872. */
  1873. Narrowphase.prototype[Shape.CIRCLE | Shape.CAPSULE] =
  1874. Narrowphase.prototype.circleCapsule = function(bi,si,xi,ai, bj,sj,xj,aj, justTest){
  1875. return this.circleLine(bi,si,xi,ai, bj,sj,xj,aj, justTest, sj.radius);
  1876. };
  1877. /**
  1878. * Circle/convex Narrowphase.
  1879. * @method circleConvex
  1880. * @param {Body} circleBody
  1881. * @param {Circle} circleShape
  1882. * @param {Array} circleOffset
  1883. * @param {Number} circleAngle
  1884. * @param {Body} convexBody
  1885. * @param {Convex} convexShape
  1886. * @param {Array} convexOffset
  1887. * @param {Number} convexAngle
  1888. * @param {Boolean} justTest
  1889. * @param {Number} circleRadius
  1890. */
  1891. Narrowphase.prototype[Shape.CIRCLE | Shape.CONVEX] =
  1892. Narrowphase.prototype[Shape.CIRCLE | Shape.BOX] =
  1893. Narrowphase.prototype.circleConvex = function(
  1894. circleBody,
  1895. circleShape,
  1896. circleOffset,
  1897. circleAngle,
  1898. convexBody,
  1899. convexShape,
  1900. convexOffset,
  1901. convexAngle,
  1902. justTest,
  1903. circleRadius
  1904. ){
  1905. var circleRadius = typeof(circleRadius)==="number" ? circleRadius : circleShape.radius;
  1906. var worldVertex0 = tmp1,
  1907. worldVertex1 = tmp2,
  1908. worldEdge = tmp3,
  1909. worldEdgeUnit = tmp4,
  1910. worldNormal = tmp5,
  1911. centerDist = tmp6,
  1912. convexToCircle = tmp7,
  1913. orthoDist = tmp8,
  1914. projectedPoint = tmp9,
  1915. dist = tmp10,
  1916. worldVertex = tmp11,
  1917. closestEdge = -1,
  1918. closestEdgeDistance = null,
  1919. closestEdgeOrthoDist = tmp12,
  1920. closestEdgeProjectedPoint = tmp13,
  1921. candidate = tmp14,
  1922. candidateDist = tmp15,
  1923. minCandidate = tmp16,
  1924. found = false,
  1925. minCandidateDistance = Number.MAX_VALUE;
  1926. var numReported = 0;
  1927. // New algorithm:
  1928. // 1. Check so center of circle is not inside the polygon. If it is, this wont work...
  1929. // 2. For each edge
  1930. // 2. 1. Get point on circle that is closest to the edge (scale normal with -radius)
  1931. // 2. 2. Check if point is inside.
  1932. var verts = convexShape.vertices;
  1933. // Check all edges first
  1934. for(var i=0; i!==verts.length+1; i++){
  1935. var v0 = verts[i%verts.length],
  1936. v1 = verts[(i+1)%verts.length];
  1937. vec2.rotate(worldVertex0, v0, convexAngle);
  1938. vec2.rotate(worldVertex1, v1, convexAngle);
  1939. add(worldVertex0, worldVertex0, convexOffset);
  1940. add(worldVertex1, worldVertex1, convexOffset);
  1941. sub(worldEdge, worldVertex1, worldVertex0);
  1942. vec2.normalize(worldEdgeUnit, worldEdge);
  1943. // Get tangent to the edge. Points out of the Convex
  1944. vec2.rotate90cw(worldNormal, worldEdgeUnit);
  1945. // Get point on circle, closest to the polygon
  1946. vec2.scale(candidate,worldNormal,-circleShape.radius);
  1947. add(candidate,candidate,circleOffset);
  1948. if(pointInConvex(candidate,convexShape,convexOffset,convexAngle)){
  1949. vec2.sub(candidateDist,worldVertex0,candidate);
  1950. var candidateDistance = Math.abs(vec2.dot(candidateDist,worldNormal));
  1951. if(candidateDistance < minCandidateDistance){
  1952. vec2.copy(minCandidate,candidate);
  1953. minCandidateDistance = candidateDistance;
  1954. vec2.scale(closestEdgeProjectedPoint,worldNormal,candidateDistance);
  1955. vec2.add(closestEdgeProjectedPoint,closestEdgeProjectedPoint,candidate);
  1956. found = true;
  1957. }
  1958. }
  1959. }
  1960. if(found){
  1961. if(justTest){
  1962. return true;
  1963. }
  1964. var c = this.createContactEquation(circleBody,convexBody,circleShape,convexShape);
  1965. vec2.sub(c.normalA, minCandidate, circleOffset);
  1966. vec2.normalize(c.normalA, c.normalA);
  1967. vec2.scale(c.contactPointA, c.normalA, circleRadius);
  1968. add(c.contactPointA, c.contactPointA, circleOffset);
  1969. sub(c.contactPointA, c.contactPointA, circleBody.position);
  1970. sub(c.contactPointB, closestEdgeProjectedPoint, convexOffset);
  1971. add(c.contactPointB, c.contactPointB, convexOffset);
  1972. sub(c.contactPointB, c.contactPointB, convexBody.position);
  1973. this.contactEquations.push(c);
  1974. if(this.enableFriction){
  1975. this.frictionEquations.push( this.createFrictionFromContact(c) );
  1976. }
  1977. return 1;
  1978. }
  1979. // Check all vertices
  1980. if(circleRadius > 0){
  1981. for(var i=0; i<verts.length; i++){
  1982. var localVertex = verts[i];
  1983. vec2.rotate(worldVertex, localVertex, convexAngle);
  1984. add(worldVertex, worldVertex, convexOffset);
  1985. sub(dist, worldVertex, circleOffset);
  1986. if(vec2.squaredLength(dist) < Math.pow(circleRadius, 2)){
  1987. if(justTest){
  1988. return true;
  1989. }
  1990. var c = this.createContactEquation(circleBody,convexBody,circleShape,convexShape);
  1991. vec2.copy(c.normalA, dist);
  1992. vec2.normalize(c.normalA,c.normalA);
  1993. // Vector from circle to contact point is the normal times the circle radius
  1994. vec2.scale(c.contactPointA, c.normalA, circleRadius);
  1995. add(c.contactPointA, c.contactPointA, circleOffset);
  1996. sub(c.contactPointA, c.contactPointA, circleBody.position);
  1997. sub(c.contactPointB, worldVertex, convexOffset);
  1998. add(c.contactPointB, c.contactPointB, convexOffset);
  1999. sub(c.contactPointB, c.contactPointB, convexBody.position);
  2000. this.contactEquations.push(c);
  2001. if(this.enableFriction){
  2002. this.frictionEquations.push(this.createFrictionFromContact(c));
  2003. }
  2004. return 1;
  2005. }
  2006. }
  2007. }
  2008. return 0;
  2009. };
  2010. var pic_worldVertex0 = vec2.create(),
  2011. pic_worldVertex1 = vec2.create(),
  2012. pic_r0 = vec2.create(),
  2013. pic_r1 = vec2.create();
  2014. /*
  2015. * Check if a point is in a polygon
  2016. */
  2017. function pointInConvex(worldPoint,convexShape,convexOffset,convexAngle){
  2018. var worldVertex0 = pic_worldVertex0,
  2019. worldVertex1 = pic_worldVertex1,
  2020. r0 = pic_r0,
  2021. r1 = pic_r1,
  2022. point = worldPoint,
  2023. verts = convexShape.vertices,
  2024. lastCross = null;
  2025. for(var i=0; i!==verts.length+1; i++){
  2026. var v0 = verts[i%verts.length],
  2027. v1 = verts[(i+1)%verts.length];
  2028. // Transform vertices to world
  2029. // @todo The point should be transformed to local coordinates in the convex, no need to transform each vertex
  2030. vec2.rotate(worldVertex0, v0, convexAngle);
  2031. vec2.rotate(worldVertex1, v1, convexAngle);
  2032. add(worldVertex0, worldVertex0, convexOffset);
  2033. add(worldVertex1, worldVertex1, convexOffset);
  2034. sub(r0, worldVertex0, point);
  2035. sub(r1, worldVertex1, point);
  2036. var cross = vec2.crossLength(r0,r1);
  2037. if(lastCross===null){
  2038. lastCross = cross;
  2039. }
  2040. // If we got a different sign of the distance vector, the point is out of the polygon
  2041. if(cross*lastCross <= 0){
  2042. return false;
  2043. }
  2044. lastCross = cross;
  2045. }
  2046. return true;
  2047. }
  2048. /**
  2049. * Particle/convex Narrowphase
  2050. * @method particleConvex
  2051. * @param {Body} particleBody
  2052. * @param {Particle} particleShape
  2053. * @param {Array} particleOffset
  2054. * @param {Number} particleAngle
  2055. * @param {Body} convexBody
  2056. * @param {Convex} convexShape
  2057. * @param {Array} convexOffset
  2058. * @param {Number} convexAngle
  2059. * @param {Boolean} justTest
  2060. * @todo use pointInConvex and code more similar to circleConvex
  2061. * @todo don't transform each vertex, but transform the particle position to convex-local instead
  2062. */
  2063. Narrowphase.prototype[Shape.PARTICLE | Shape.CONVEX] =
  2064. Narrowphase.prototype[Shape.PARTICLE | Shape.BOX] =
  2065. Narrowphase.prototype.particleConvex = function(
  2066. particleBody,
  2067. particleShape,
  2068. particleOffset,
  2069. particleAngle,
  2070. convexBody,
  2071. convexShape,
  2072. convexOffset,
  2073. convexAngle,
  2074. justTest
  2075. ){
  2076. var worldVertex0 = tmp1,
  2077. worldVertex1 = tmp2,
  2078. worldEdge = tmp3,
  2079. worldEdgeUnit = tmp4,
  2080. worldTangent = tmp5,
  2081. centerDist = tmp6,
  2082. convexToparticle = tmp7,
  2083. orthoDist = tmp8,
  2084. projectedPoint = tmp9,
  2085. dist = tmp10,
  2086. worldVertex = tmp11,
  2087. closestEdge = -1,
  2088. closestEdgeDistance = null,
  2089. closestEdgeOrthoDist = tmp12,
  2090. closestEdgeProjectedPoint = tmp13,
  2091. r0 = tmp14, // vector from particle to vertex0
  2092. r1 = tmp15,
  2093. localPoint = tmp16,
  2094. candidateDist = tmp17,
  2095. minEdgeNormal = tmp18,
  2096. minCandidateDistance = Number.MAX_VALUE;
  2097. var numReported = 0,
  2098. found = false,
  2099. verts = convexShape.vertices;
  2100. // Check if the particle is in the polygon at all
  2101. if(!pointInConvex(particleOffset,convexShape,convexOffset,convexAngle)){
  2102. return 0;
  2103. }
  2104. if(justTest){
  2105. return true;
  2106. }
  2107. // Check edges first
  2108. var lastCross = null;
  2109. for(var i=0; i!==verts.length+1; i++){
  2110. var v0 = verts[i%verts.length],
  2111. v1 = verts[(i+1)%verts.length];
  2112. // Transform vertices to world
  2113. vec2.rotate(worldVertex0, v0, convexAngle);
  2114. vec2.rotate(worldVertex1, v1, convexAngle);
  2115. add(worldVertex0, worldVertex0, convexOffset);
  2116. add(worldVertex1, worldVertex1, convexOffset);
  2117. // Get world edge
  2118. sub(worldEdge, worldVertex1, worldVertex0);
  2119. vec2.normalize(worldEdgeUnit, worldEdge);
  2120. // Get tangent to the edge. Points out of the Convex
  2121. vec2.rotate90cw(worldTangent, worldEdgeUnit);
  2122. // Check distance from the infinite line (spanned by the edge) to the particle
  2123. sub(dist, particleOffset, worldVertex0);
  2124. var d = dot(dist, worldTangent);
  2125. sub(centerDist, worldVertex0, convexOffset);
  2126. sub(convexToparticle, particleOffset, convexOffset);
  2127. vec2.sub(candidateDist,worldVertex0,particleOffset);
  2128. var candidateDistance = Math.abs(vec2.dot(candidateDist,worldTangent));
  2129. if(candidateDistance < minCandidateDistance){
  2130. minCandidateDistance = candidateDistance;
  2131. vec2.scale(closestEdgeProjectedPoint,worldTangent,candidateDistance);
  2132. vec2.add(closestEdgeProjectedPoint,closestEdgeProjectedPoint,particleOffset);
  2133. vec2.copy(minEdgeNormal,worldTangent);
  2134. found = true;
  2135. }
  2136. }
  2137. if(found){
  2138. var c = this.createContactEquation(particleBody,convexBody,particleShape,convexShape);
  2139. vec2.scale(c.normalA, minEdgeNormal, -1);
  2140. vec2.normalize(c.normalA, c.normalA);
  2141. // Particle has no extent to the contact point
  2142. vec2.set(c.contactPointA, 0, 0);
  2143. add(c.contactPointA, c.contactPointA, particleOffset);
  2144. sub(c.contactPointA, c.contactPointA, particleBody.position);
  2145. // From convex center to point
  2146. sub(c.contactPointB, closestEdgeProjectedPoint, convexOffset);
  2147. add(c.contactPointB, c.contactPointB, convexOffset);
  2148. sub(c.contactPointB, c.contactPointB, convexBody.position);
  2149. this.contactEquations.push(c);
  2150. if(this.enableFriction){
  2151. this.frictionEquations.push( this.createFrictionFromContact(c) );
  2152. }
  2153. return 1;
  2154. }
  2155. return 0;
  2156. };
  2157. /**
  2158. * Circle/circle Narrowphase
  2159. * @method circleCircle
  2160. * @param {Body} bodyA
  2161. * @param {Circle} shapeA
  2162. * @param {Array} offsetA
  2163. * @param {Number} angleA
  2164. * @param {Body} bodyB
  2165. * @param {Circle} shapeB
  2166. * @param {Array} offsetB
  2167. * @param {Number} angleB
  2168. * @param {Boolean} justTest
  2169. * @param {Number} [radiusA] Optional radius to use for shapeA
  2170. * @param {Number} [radiusB] Optional radius to use for shapeB
  2171. */
  2172. Narrowphase.prototype[Shape.CIRCLE] =
  2173. Narrowphase.prototype.circleCircle = function(
  2174. bodyA,
  2175. shapeA,
  2176. offsetA,
  2177. angleA,
  2178. bodyB,
  2179. shapeB,
  2180. offsetB,
  2181. angleB,
  2182. justTest,
  2183. radiusA,
  2184. radiusB
  2185. ){
  2186. var dist = tmp1,
  2187. radiusA = radiusA || shapeA.radius,
  2188. radiusB = radiusB || shapeB.radius;
  2189. sub(dist,offsetA,offsetB);
  2190. var r = radiusA + radiusB;
  2191. if(vec2.squaredLength(dist) > Math.pow(r,2)){
  2192. return 0;
  2193. }
  2194. if(justTest){
  2195. return true;
  2196. }
  2197. var c = this.createContactEquation(bodyA,bodyB,shapeA,shapeB);
  2198. sub(c.normalA, offsetB, offsetA);
  2199. vec2.normalize(c.normalA,c.normalA);
  2200. vec2.scale( c.contactPointA, c.normalA, radiusA);
  2201. vec2.scale( c.contactPointB, c.normalA, -radiusB);
  2202. add(c.contactPointA, c.contactPointA, offsetA);
  2203. sub(c.contactPointA, c.contactPointA, bodyA.position);
  2204. add(c.contactPointB, c.contactPointB, offsetB);
  2205. sub(c.contactPointB, c.contactPointB, bodyB.position);
  2206. this.contactEquations.push(c);
  2207. if(this.enableFriction){
  2208. this.frictionEquations.push(this.createFrictionFromContact(c));
  2209. }
  2210. return 1;
  2211. };
  2212. /**
  2213. * Plane/Convex Narrowphase
  2214. * @method planeConvex
  2215. * @param {Body} planeBody
  2216. * @param {Plane} planeShape
  2217. * @param {Array} planeOffset
  2218. * @param {Number} planeAngle
  2219. * @param {Body} convexBody
  2220. * @param {Convex} convexShape
  2221. * @param {Array} convexOffset
  2222. * @param {Number} convexAngle
  2223. * @param {Boolean} justTest
  2224. */
  2225. Narrowphase.prototype[Shape.PLANE | Shape.CONVEX] =
  2226. Narrowphase.prototype[Shape.PLANE | Shape.BOX] =
  2227. Narrowphase.prototype.planeConvex = function(
  2228. planeBody,
  2229. planeShape,
  2230. planeOffset,
  2231. planeAngle,
  2232. convexBody,
  2233. convexShape,
  2234. convexOffset,
  2235. convexAngle,
  2236. justTest
  2237. ){
  2238. var worldVertex = tmp1,
  2239. worldNormal = tmp2,
  2240. dist = tmp3;
  2241. var numReported = 0;
  2242. vec2.rotate(worldNormal, yAxis, planeAngle);
  2243. for(var i=0; i!==convexShape.vertices.length; i++){
  2244. var v = convexShape.vertices[i];
  2245. vec2.rotate(worldVertex, v, convexAngle);
  2246. add(worldVertex, worldVertex, convexOffset);
  2247. sub(dist, worldVertex, planeOffset);
  2248. if(dot(dist,worldNormal) <= 0){
  2249. if(justTest){
  2250. return true;
  2251. }
  2252. // Found vertex
  2253. numReported++;
  2254. var c = this.createContactEquation(planeBody,convexBody,planeShape,convexShape);
  2255. sub(dist, worldVertex, planeOffset);
  2256. vec2.copy(c.normalA, worldNormal);
  2257. var d = dot(dist, c.normalA);
  2258. vec2.scale(dist, c.normalA, d);
  2259. // rj is from convex center to contact
  2260. sub(c.contactPointB, worldVertex, convexBody.position);
  2261. // ri is from plane center to contact
  2262. sub( c.contactPointA, worldVertex, dist);
  2263. sub( c.contactPointA, c.contactPointA, planeBody.position);
  2264. this.contactEquations.push(c);
  2265. if(!this.enableFrictionReduction){
  2266. if(this.enableFriction){
  2267. this.frictionEquations.push(this.createFrictionFromContact(c));
  2268. }
  2269. }
  2270. }
  2271. }
  2272. if(this.enableFrictionReduction){
  2273. if(this.enableFriction && numReported){
  2274. this.frictionEquations.push(this.createFrictionFromAverage(numReported));
  2275. }
  2276. }
  2277. return numReported;
  2278. };
  2279. /**
  2280. * Narrowphase for particle vs plane
  2281. * @method particlePlane
  2282. * @param {Body} particleBody
  2283. * @param {Particle} particleShape
  2284. * @param {Array} particleOffset
  2285. * @param {Number} particleAngle
  2286. * @param {Body} planeBody
  2287. * @param {Plane} planeShape
  2288. * @param {Array} planeOffset
  2289. * @param {Number} planeAngle
  2290. * @param {Boolean} justTest
  2291. */
  2292. Narrowphase.prototype[Shape.PARTICLE | Shape.PLANE] =
  2293. Narrowphase.prototype.particlePlane = function(
  2294. particleBody,
  2295. particleShape,
  2296. particleOffset,
  2297. particleAngle,
  2298. planeBody,
  2299. planeShape,
  2300. planeOffset,
  2301. planeAngle,
  2302. justTest
  2303. ){
  2304. var dist = tmp1,
  2305. worldNormal = tmp2;
  2306. planeAngle = planeAngle || 0;
  2307. sub(dist, particleOffset, planeOffset);
  2308. vec2.rotate(worldNormal, yAxis, planeAngle);
  2309. var d = dot(dist, worldNormal);
  2310. if(d > 0){
  2311. return 0;
  2312. }
  2313. if(justTest){
  2314. return true;
  2315. }
  2316. var c = this.createContactEquation(planeBody,particleBody,planeShape,particleShape);
  2317. vec2.copy(c.normalA, worldNormal);
  2318. vec2.scale( dist, c.normalA, d );
  2319. // dist is now the distance vector in the normal direction
  2320. // ri is the particle position projected down onto the plane, from the plane center
  2321. sub( c.contactPointA, particleOffset, dist);
  2322. sub( c.contactPointA, c.contactPointA, planeBody.position);
  2323. // rj is from the body center to the particle center
  2324. sub( c.contactPointB, particleOffset, particleBody.position );
  2325. this.contactEquations.push(c);
  2326. if(this.enableFriction){
  2327. this.frictionEquations.push(this.createFrictionFromContact(c));
  2328. }
  2329. return 1;
  2330. };
  2331. /**
  2332. * Circle/Particle Narrowphase
  2333. * @method circleParticle
  2334. * @param {Body} circleBody
  2335. * @param {Circle} circleShape
  2336. * @param {Array} circleOffset
  2337. * @param {Number} circleAngle
  2338. * @param {Body} particleBody
  2339. * @param {Particle} particleShape
  2340. * @param {Array} particleOffset
  2341. * @param {Number} particleAngle
  2342. * @param {Boolean} justTest
  2343. */
  2344. Narrowphase.prototype[Shape.CIRCLE | Shape.PARTICLE] =
  2345. Narrowphase.prototype.circleParticle = function(
  2346. circleBody,
  2347. circleShape,
  2348. circleOffset,
  2349. circleAngle,
  2350. particleBody,
  2351. particleShape,
  2352. particleOffset,
  2353. particleAngle,
  2354. justTest
  2355. ){
  2356. var dist = tmp1;
  2357. sub(dist, particleOffset, circleOffset);
  2358. if(vec2.squaredLength(dist) > Math.pow(circleShape.radius, 2)){
  2359. return 0;
  2360. }
  2361. if(justTest){
  2362. return true;
  2363. }
  2364. var c = this.createContactEquation(circleBody,particleBody,circleShape,particleShape);
  2365. vec2.copy(c.normalA, dist);
  2366. vec2.normalize(c.normalA,c.normalA);
  2367. // Vector from circle to contact point is the normal times the circle radius
  2368. vec2.scale(c.contactPointA, c.normalA, circleShape.radius);
  2369. add(c.contactPointA, c.contactPointA, circleOffset);
  2370. sub(c.contactPointA, c.contactPointA, circleBody.position);
  2371. // Vector from particle center to contact point is zero
  2372. sub(c.contactPointB, particleOffset, particleBody.position);
  2373. this.contactEquations.push(c);
  2374. if(this.enableFriction){
  2375. this.frictionEquations.push(this.createFrictionFromContact(c));
  2376. }
  2377. return 1;
  2378. };
  2379. var planeCapsule_tmpCircle = new Circle({ radius: 1 }),
  2380. planeCapsule_tmp1 = vec2.create(),
  2381. planeCapsule_tmp2 = vec2.create(),
  2382. planeCapsule_tmp3 = vec2.create();
  2383. /**
  2384. * @method planeCapsule
  2385. * @param {Body} planeBody
  2386. * @param {Circle} planeShape
  2387. * @param {Array} planeOffset
  2388. * @param {Number} planeAngle
  2389. * @param {Body} capsuleBody
  2390. * @param {Particle} capsuleShape
  2391. * @param {Array} capsuleOffset
  2392. * @param {Number} capsuleAngle
  2393. * @param {Boolean} justTest
  2394. */
  2395. Narrowphase.prototype[Shape.PLANE | Shape.CAPSULE] =
  2396. Narrowphase.prototype.planeCapsule = function(
  2397. planeBody,
  2398. planeShape,
  2399. planeOffset,
  2400. planeAngle,
  2401. capsuleBody,
  2402. capsuleShape,
  2403. capsuleOffset,
  2404. capsuleAngle,
  2405. justTest
  2406. ){
  2407. var end1 = planeCapsule_tmp1,
  2408. end2 = planeCapsule_tmp2,
  2409. circle = planeCapsule_tmpCircle,
  2410. dst = planeCapsule_tmp3;
  2411. // Compute world end positions
  2412. vec2.set(end1, -capsuleShape.length/2, 0);
  2413. vec2.rotate(end1,end1,capsuleAngle);
  2414. add(end1,end1,capsuleOffset);
  2415. vec2.set(end2, capsuleShape.length/2, 0);
  2416. vec2.rotate(end2,end2,capsuleAngle);
  2417. add(end2,end2,capsuleOffset);
  2418. circle.radius = capsuleShape.radius;
  2419. var enableFrictionBefore;
  2420. // Temporarily turn off friction
  2421. if(this.enableFrictionReduction){
  2422. enableFrictionBefore = this.enableFriction;
  2423. this.enableFriction = false;
  2424. }
  2425. // Do Narrowphase as two circles
  2426. var numContacts1 = this.circlePlane(capsuleBody,circle,end1,0, planeBody,planeShape,planeOffset,planeAngle, justTest),
  2427. numContacts2 = this.circlePlane(capsuleBody,circle,end2,0, planeBody,planeShape,planeOffset,planeAngle, justTest);
  2428. // Restore friction
  2429. if(this.enableFrictionReduction){
  2430. this.enableFriction = enableFrictionBefore;
  2431. }
  2432. if(justTest){
  2433. return numContacts1 || numContacts2;
  2434. } else {
  2435. var numTotal = numContacts1 + numContacts2;
  2436. if(this.enableFrictionReduction){
  2437. if(numTotal){
  2438. this.frictionEquations.push(this.createFrictionFromAverage(numTotal));
  2439. }
  2440. }
  2441. return numTotal;
  2442. }
  2443. };
  2444. /**
  2445. * Creates ContactEquations and FrictionEquations for a collision.
  2446. * @method circlePlane
  2447. * @param {Body} bi The first body that should be connected to the equations.
  2448. * @param {Circle} si The circle shape participating in the collision.
  2449. * @param {Array} xi Extra offset to take into account for the Shape, in addition to the one in circleBody.position. Will *not* be rotated by circleBody.angle (maybe it should, for sake of homogenity?). Set to null if none.
  2450. * @param {Body} bj The second body that should be connected to the equations.
  2451. * @param {Plane} sj The Plane shape that is participating
  2452. * @param {Array} xj Extra offset for the plane shape.
  2453. * @param {Number} aj Extra angle to apply to the plane
  2454. */
  2455. Narrowphase.prototype[Shape.CIRCLE | Shape.PLANE] =
  2456. Narrowphase.prototype.circlePlane = function( bi,si,xi,ai, bj,sj,xj,aj, justTest ){
  2457. var circleBody = bi,
  2458. circleShape = si,
  2459. circleOffset = xi, // Offset from body center, rotated!
  2460. planeBody = bj,
  2461. shapeB = sj,
  2462. planeOffset = xj,
  2463. planeAngle = aj;
  2464. planeAngle = planeAngle || 0;
  2465. // Vector from plane to circle
  2466. var planeToCircle = tmp1,
  2467. worldNormal = tmp2,
  2468. temp = tmp3;
  2469. sub(planeToCircle, circleOffset, planeOffset);
  2470. // World plane normal
  2471. vec2.rotate(worldNormal, yAxis, planeAngle);
  2472. // Normal direction distance
  2473. var d = dot(worldNormal, planeToCircle);
  2474. if(d > circleShape.radius){
  2475. return 0; // No overlap. Abort.
  2476. }
  2477. if(justTest){
  2478. return true;
  2479. }
  2480. // Create contact
  2481. var contact = this.createContactEquation(planeBody,circleBody,sj,si);
  2482. // ni is the plane world normal
  2483. vec2.copy(contact.normalA, worldNormal);
  2484. // rj is the vector from circle center to the contact point
  2485. vec2.scale(contact.contactPointB, contact.normalA, -circleShape.radius);
  2486. add(contact.contactPointB, contact.contactPointB, circleOffset);
  2487. sub(contact.contactPointB, contact.contactPointB, circleBody.position);
  2488. // ri is the distance from plane center to contact.
  2489. vec2.scale(temp, contact.normalA, d);
  2490. sub(contact.contactPointA, planeToCircle, temp ); // Subtract normal distance vector from the distance vector
  2491. add(contact.contactPointA, contact.contactPointA, planeOffset);
  2492. sub(contact.contactPointA, contact.contactPointA, planeBody.position);
  2493. this.contactEquations.push(contact);
  2494. if(this.enableFriction){
  2495. this.frictionEquations.push( this.createFrictionFromContact(contact) );
  2496. }
  2497. return 1;
  2498. };
  2499. /**
  2500. * Convex/convex Narrowphase.See <a href="http://www.altdevblogaday.com/2011/05/13/contact-generation-between-3d-convex-meshes/">this article</a> for more info.
  2501. * @method convexConvex
  2502. * @param {Body} bi
  2503. * @param {Convex} si
  2504. * @param {Array} xi
  2505. * @param {Number} ai
  2506. * @param {Body} bj
  2507. * @param {Convex} sj
  2508. * @param {Array} xj
  2509. * @param {Number} aj
  2510. */
  2511. Narrowphase.prototype[Shape.CONVEX] =
  2512. Narrowphase.prototype[Shape.CONVEX | Shape.BOX] =
  2513. Narrowphase.prototype[Shape.BOX] =
  2514. Narrowphase.prototype.convexConvex = function( bi,si,xi,ai, bj,sj,xj,aj, justTest, precision ){
  2515. var sepAxis = tmp1,
  2516. worldPoint = tmp2,
  2517. worldPoint0 = tmp3,
  2518. worldPoint1 = tmp4,
  2519. worldEdge = tmp5,
  2520. projected = tmp6,
  2521. penetrationVec = tmp7,
  2522. dist = tmp8,
  2523. worldNormal = tmp9,
  2524. numContacts = 0,
  2525. precision = typeof(precision) === 'number' ? precision : 0;
  2526. var found = Narrowphase.findSeparatingAxis(si,xi,ai,sj,xj,aj,sepAxis);
  2527. if(!found){
  2528. return 0;
  2529. }
  2530. // Make sure the separating axis is directed from shape i to shape j
  2531. sub(dist,xj,xi);
  2532. if(dot(sepAxis,dist) > 0){
  2533. vec2.scale(sepAxis,sepAxis,-1);
  2534. }
  2535. // Find edges with normals closest to the separating axis
  2536. var closestEdge1 = Narrowphase.getClosestEdge(si,ai,sepAxis,true), // Flipped axis
  2537. closestEdge2 = Narrowphase.getClosestEdge(sj,aj,sepAxis);
  2538. if(closestEdge1 === -1 || closestEdge2 === -1){
  2539. return 0;
  2540. }
  2541. // Loop over the shapes
  2542. for(var k=0; k<2; k++){
  2543. var closestEdgeA = closestEdge1,
  2544. closestEdgeB = closestEdge2,
  2545. shapeA = si, shapeB = sj,
  2546. offsetA = xi, offsetB = xj,
  2547. angleA = ai, angleB = aj,
  2548. bodyA = bi, bodyB = bj;
  2549. if(k === 0){
  2550. // Swap!
  2551. var tmp;
  2552. tmp = closestEdgeA;
  2553. closestEdgeA = closestEdgeB;
  2554. closestEdgeB = tmp;
  2555. tmp = shapeA;
  2556. shapeA = shapeB;
  2557. shapeB = tmp;
  2558. tmp = offsetA;
  2559. offsetA = offsetB;
  2560. offsetB = tmp;
  2561. tmp = angleA;
  2562. angleA = angleB;
  2563. angleB = tmp;
  2564. tmp = bodyA;
  2565. bodyA = bodyB;
  2566. bodyB = tmp;
  2567. }
  2568. // Loop over 2 points in convex B
  2569. for(var j=closestEdgeB; j<closestEdgeB+2; j++){
  2570. // Get world point
  2571. var v = shapeB.vertices[(j+shapeB.vertices.length)%shapeB.vertices.length];
  2572. vec2.rotate(worldPoint, v, angleB);
  2573. add(worldPoint, worldPoint, offsetB);
  2574. var insideNumEdges = 0;
  2575. // Loop over the 3 closest edges in convex A
  2576. for(var i=closestEdgeA-1; i<closestEdgeA+2; i++){
  2577. var v0 = shapeA.vertices[(i +shapeA.vertices.length)%shapeA.vertices.length],
  2578. v1 = shapeA.vertices[(i+1+shapeA.vertices.length)%shapeA.vertices.length];
  2579. // Construct the edge
  2580. vec2.rotate(worldPoint0, v0, angleA);
  2581. vec2.rotate(worldPoint1, v1, angleA);
  2582. add(worldPoint0, worldPoint0, offsetA);
  2583. add(worldPoint1, worldPoint1, offsetA);
  2584. sub(worldEdge, worldPoint1, worldPoint0);
  2585. vec2.rotate90cw(worldNormal, worldEdge); // Normal points out of convex 1
  2586. vec2.normalize(worldNormal,worldNormal);
  2587. sub(dist, worldPoint, worldPoint0);
  2588. var d = dot(worldNormal,dist);
  2589. if((i === closestEdgeA && d <= precision) || (i !== closestEdgeA && d <= 0)){
  2590. insideNumEdges++;
  2591. }
  2592. }
  2593. if(insideNumEdges >= 3){
  2594. if(justTest){
  2595. return true;
  2596. }
  2597. // worldPoint was on the "inside" side of each of the 3 checked edges.
  2598. // Project it to the center edge and use the projection direction as normal
  2599. // Create contact
  2600. var c = this.createContactEquation(bodyA,bodyB,shapeA,shapeB);
  2601. numContacts++;
  2602. // Get center edge from body A
  2603. var v0 = shapeA.vertices[(closestEdgeA) % shapeA.vertices.length],
  2604. v1 = shapeA.vertices[(closestEdgeA+1) % shapeA.vertices.length];
  2605. // Construct the edge
  2606. vec2.rotate(worldPoint0, v0, angleA);
  2607. vec2.rotate(worldPoint1, v1, angleA);
  2608. add(worldPoint0, worldPoint0, offsetA);
  2609. add(worldPoint1, worldPoint1, offsetA);
  2610. sub(worldEdge, worldPoint1, worldPoint0);
  2611. vec2.rotate90cw(c.normalA, worldEdge); // Normal points out of convex A
  2612. vec2.normalize(c.normalA,c.normalA);
  2613. sub(dist, worldPoint, worldPoint0); // From edge point to the penetrating point
  2614. var d = dot(c.normalA,dist); // Penetration
  2615. vec2.scale(penetrationVec, c.normalA, d); // Vector penetration
  2616. sub(c.contactPointA, worldPoint, offsetA);
  2617. sub(c.contactPointA, c.contactPointA, penetrationVec);
  2618. add(c.contactPointA, c.contactPointA, offsetA);
  2619. sub(c.contactPointA, c.contactPointA, bodyA.position);
  2620. sub(c.contactPointB, worldPoint, offsetB);
  2621. add(c.contactPointB, c.contactPointB, offsetB);
  2622. sub(c.contactPointB, c.contactPointB, bodyB.position);
  2623. this.contactEquations.push(c);
  2624. // Todo reduce to 1 friction equation if we have 2 contact points
  2625. if(!this.enableFrictionReduction){
  2626. if(this.enableFriction){
  2627. this.frictionEquations.push(this.createFrictionFromContact(c));
  2628. }
  2629. }
  2630. }
  2631. }
  2632. }
  2633. if(this.enableFrictionReduction){
  2634. if(this.enableFriction && numContacts){
  2635. this.frictionEquations.push(this.createFrictionFromAverage(numContacts));
  2636. }
  2637. }
  2638. return numContacts;
  2639. };
  2640. // .projectConvex is called by other functions, need local tmp vectors
  2641. var pcoa_tmp1 = vec2.fromValues(0,0);
  2642. /**
  2643. * Project a Convex onto a world-oriented axis
  2644. * @method projectConvexOntoAxis
  2645. * @static
  2646. * @param {Convex} convexShape
  2647. * @param {Array} convexOffset
  2648. * @param {Number} convexAngle
  2649. * @param {Array} worldAxis
  2650. * @param {Array} result
  2651. */
  2652. Narrowphase.projectConvexOntoAxis = function(convexShape, convexOffset, convexAngle, worldAxis, result){
  2653. var max=null,
  2654. min=null,
  2655. v,
  2656. value,
  2657. localAxis = pcoa_tmp1;
  2658. // Convert the axis to local coords of the body
  2659. vec2.rotate(localAxis, worldAxis, -convexAngle);
  2660. // Get projected position of all vertices
  2661. for(var i=0; i<convexShape.vertices.length; i++){
  2662. v = convexShape.vertices[i];
  2663. value = dot(v,localAxis);
  2664. if(max === null || value > max){
  2665. max = value;
  2666. }
  2667. if(min === null || value < min){
  2668. min = value;
  2669. }
  2670. }
  2671. if(min > max){
  2672. var t = min;
  2673. min = max;
  2674. max = t;
  2675. }
  2676. // Project the position of the body onto the axis - need to add this to the result
  2677. var offset = dot(convexOffset, worldAxis);
  2678. vec2.set( result, min + offset, max + offset);
  2679. };
  2680. // .findSeparatingAxis is called by other functions, need local tmp vectors
  2681. var fsa_tmp1 = vec2.fromValues(0,0)
  2682. , fsa_tmp2 = vec2.fromValues(0,0)
  2683. , fsa_tmp3 = vec2.fromValues(0,0)
  2684. , fsa_tmp4 = vec2.fromValues(0,0)
  2685. , fsa_tmp5 = vec2.fromValues(0,0)
  2686. , fsa_tmp6 = vec2.fromValues(0,0);
  2687. /**
  2688. * Find a separating axis between the shapes, that maximizes the separating distance between them.
  2689. * @method findSeparatingAxis
  2690. * @static
  2691. * @param {Convex} c1
  2692. * @param {Array} offset1
  2693. * @param {Number} angle1
  2694. * @param {Convex} c2
  2695. * @param {Array} offset2
  2696. * @param {Number} angle2
  2697. * @param {Array} sepAxis The resulting axis
  2698. * @return {Boolean} Whether the axis could be found.
  2699. */
  2700. Narrowphase.findSeparatingAxis = function(c1,offset1,angle1,c2,offset2,angle2,sepAxis){
  2701. var maxDist = null,
  2702. overlap = false,
  2703. found = false,
  2704. edge = fsa_tmp1,
  2705. worldPoint0 = fsa_tmp2,
  2706. worldPoint1 = fsa_tmp3,
  2707. normal = fsa_tmp4,
  2708. span1 = fsa_tmp5,
  2709. span2 = fsa_tmp6;
  2710. if(c1 instanceof Box && c2 instanceof Box){
  2711. for(var j=0; j!==2; j++){
  2712. var c = c1,
  2713. angle = angle1;
  2714. if(j===1){
  2715. c = c2;
  2716. angle = angle2;
  2717. }
  2718. for(var i=0; i!==2; i++){
  2719. // Get the world edge
  2720. if(i === 0){
  2721. vec2.set(normal, 0, 1);
  2722. } else if(i === 1) {
  2723. vec2.set(normal, 1, 0);
  2724. }
  2725. if(angle !== 0){
  2726. vec2.rotate(normal, normal, angle);
  2727. }
  2728. // Project hulls onto that normal
  2729. Narrowphase.projectConvexOntoAxis(c1,offset1,angle1,normal,span1);
  2730. Narrowphase.projectConvexOntoAxis(c2,offset2,angle2,normal,span2);
  2731. // Order by span position
  2732. var a=span1,
  2733. b=span2,
  2734. swapped = false;
  2735. if(span1[0] > span2[0]){
  2736. b=span1;
  2737. a=span2;
  2738. swapped = true;
  2739. }
  2740. // Get separating distance
  2741. var dist = b[0] - a[1];
  2742. overlap = (dist <= 0);
  2743. if(maxDist===null || dist > maxDist){
  2744. vec2.copy(sepAxis, normal);
  2745. maxDist = dist;
  2746. found = overlap;
  2747. }
  2748. }
  2749. }
  2750. } else {
  2751. for(var j=0; j!==2; j++){
  2752. var c = c1,
  2753. angle = angle1;
  2754. if(j===1){
  2755. c = c2;
  2756. angle = angle2;
  2757. }
  2758. for(var i=0; i!==c.vertices.length; i++){
  2759. // Get the world edge
  2760. vec2.rotate(worldPoint0, c.vertices[i], angle);
  2761. vec2.rotate(worldPoint1, c.vertices[(i+1)%c.vertices.length], angle);
  2762. sub(edge, worldPoint1, worldPoint0);
  2763. // Get normal - just rotate 90 degrees since vertices are given in CCW
  2764. vec2.rotate90cw(normal, edge);
  2765. vec2.normalize(normal,normal);
  2766. // Project hulls onto that normal
  2767. Narrowphase.projectConvexOntoAxis(c1,offset1,angle1,normal,span1);
  2768. Narrowphase.projectConvexOntoAxis(c2,offset2,angle2,normal,span2);
  2769. // Order by span position
  2770. var a=span1,
  2771. b=span2,
  2772. swapped = false;
  2773. if(span1[0] > span2[0]){
  2774. b=span1;
  2775. a=span2;
  2776. swapped = true;
  2777. }
  2778. // Get separating distance
  2779. var dist = b[0] - a[1];
  2780. overlap = (dist <= 0);
  2781. if(maxDist===null || dist > maxDist){
  2782. vec2.copy(sepAxis, normal);
  2783. maxDist = dist;
  2784. found = overlap;
  2785. }
  2786. }
  2787. }
  2788. }
  2789. /*
  2790. // Needs to be tested some more
  2791. for(var j=0; j!==2; j++){
  2792. var c = c1,
  2793. angle = angle1;
  2794. if(j===1){
  2795. c = c2;
  2796. angle = angle2;
  2797. }
  2798. for(var i=0; i!==c.axes.length; i++){
  2799. var normal = c.axes[i];
  2800. // Project hulls onto that normal
  2801. Narrowphase.projectConvexOntoAxis(c1, offset1, angle1, normal, span1);
  2802. Narrowphase.projectConvexOntoAxis(c2, offset2, angle2, normal, span2);
  2803. // Order by span position
  2804. var a=span1,
  2805. b=span2,
  2806. swapped = false;
  2807. if(span1[0] > span2[0]){
  2808. b=span1;
  2809. a=span2;
  2810. swapped = true;
  2811. }
  2812. // Get separating distance
  2813. var dist = b[0] - a[1];
  2814. overlap = (dist <= Narrowphase.convexPrecision);
  2815. if(maxDist===null || dist > maxDist){
  2816. vec2.copy(sepAxis, normal);
  2817. maxDist = dist;
  2818. found = overlap;
  2819. }
  2820. }
  2821. }
  2822. */
  2823. return found;
  2824. };
  2825. // .getClosestEdge is called by other functions, need local tmp vectors
  2826. var gce_tmp1 = vec2.fromValues(0,0)
  2827. , gce_tmp2 = vec2.fromValues(0,0)
  2828. , gce_tmp3 = vec2.fromValues(0,0);
  2829. /**
  2830. * Get the edge that has a normal closest to an axis.
  2831. * @method getClosestEdge
  2832. * @static
  2833. * @param {Convex} c
  2834. * @param {Number} angle
  2835. * @param {Array} axis
  2836. * @param {Boolean} flip
  2837. * @return {Number} Index of the edge that is closest. This index and the next spans the resulting edge. Returns -1 if failed.
  2838. */
  2839. Narrowphase.getClosestEdge = function(c,angle,axis,flip){
  2840. var localAxis = gce_tmp1,
  2841. edge = gce_tmp2,
  2842. normal = gce_tmp3;
  2843. // Convert the axis to local coords of the body
  2844. vec2.rotate(localAxis, axis, -angle);
  2845. if(flip){
  2846. vec2.scale(localAxis,localAxis,-1);
  2847. }
  2848. var closestEdge = -1,
  2849. N = c.vertices.length,
  2850. maxDot = -1;
  2851. for(var i=0; i!==N; i++){
  2852. // Get the edge
  2853. sub(edge, c.vertices[(i+1)%N], c.vertices[i%N]);
  2854. // Get normal - just rotate 90 degrees since vertices are given in CCW
  2855. vec2.rotate90cw(normal, edge);
  2856. vec2.normalize(normal,normal);
  2857. var d = dot(normal,localAxis);
  2858. if(closestEdge === -1 || d > maxDot){
  2859. closestEdge = i % N;
  2860. maxDot = d;
  2861. }
  2862. }
  2863. return closestEdge;
  2864. };
  2865. var circleHeightfield_candidate = vec2.create(),
  2866. circleHeightfield_dist = vec2.create(),
  2867. circleHeightfield_v0 = vec2.create(),
  2868. circleHeightfield_v1 = vec2.create(),
  2869. circleHeightfield_minCandidate = vec2.create(),
  2870. circleHeightfield_worldNormal = vec2.create(),
  2871. circleHeightfield_minCandidateNormal = vec2.create();
  2872. /**
  2873. * @method circleHeightfield
  2874. * @param {Body} bi
  2875. * @param {Circle} si
  2876. * @param {Array} xi
  2877. * @param {Body} bj
  2878. * @param {Heightfield} sj
  2879. * @param {Array} xj
  2880. * @param {Number} aj
  2881. */
  2882. Narrowphase.prototype[Shape.CIRCLE | Shape.HEIGHTFIELD] =
  2883. Narrowphase.prototype.circleHeightfield = function( circleBody,circleShape,circlePos,circleAngle,
  2884. hfBody,hfShape,hfPos,hfAngle, justTest, radius ){
  2885. var data = hfShape.heights,
  2886. radius = radius || circleShape.radius,
  2887. w = hfShape.elementWidth,
  2888. dist = circleHeightfield_dist,
  2889. candidate = circleHeightfield_candidate,
  2890. minCandidate = circleHeightfield_minCandidate,
  2891. minCandidateNormal = circleHeightfield_minCandidateNormal,
  2892. worldNormal = circleHeightfield_worldNormal,
  2893. v0 = circleHeightfield_v0,
  2894. v1 = circleHeightfield_v1;
  2895. // Get the index of the points to test against
  2896. var idxA = Math.floor( (circlePos[0] - radius - hfPos[0]) / w ),
  2897. idxB = Math.ceil( (circlePos[0] + radius - hfPos[0]) / w );
  2898. /*if(idxB < 0 || idxA >= data.length)
  2899. return justTest ? false : 0;*/
  2900. if(idxA < 0){
  2901. idxA = 0;
  2902. }
  2903. if(idxB >= data.length){
  2904. idxB = data.length-1;
  2905. }
  2906. // Get max and min
  2907. var max = data[idxA],
  2908. min = data[idxB];
  2909. for(var i=idxA; i<idxB; i++){
  2910. if(data[i] < min){
  2911. min = data[i];
  2912. }
  2913. if(data[i] > max){
  2914. max = data[i];
  2915. }
  2916. }
  2917. if(circlePos[1]-radius > max){
  2918. return justTest ? false : 0;
  2919. }
  2920. /*
  2921. if(circlePos[1]+radius < min){
  2922. // Below the minimum point... We can just guess.
  2923. // TODO
  2924. }
  2925. */
  2926. // 1. Check so center of circle is not inside the field. If it is, this wont work...
  2927. // 2. For each edge
  2928. // 2. 1. Get point on circle that is closest to the edge (scale normal with -radius)
  2929. // 2. 2. Check if point is inside.
  2930. var found = false;
  2931. // Check all edges first
  2932. for(var i=idxA; i<idxB; i++){
  2933. // Get points
  2934. vec2.set(v0, i*w, data[i] );
  2935. vec2.set(v1, (i+1)*w, data[i+1]);
  2936. vec2.add(v0,v0,hfPos);
  2937. vec2.add(v1,v1,hfPos);
  2938. // Get normal
  2939. vec2.sub(worldNormal, v1, v0);
  2940. vec2.rotate(worldNormal, worldNormal, Math.PI/2);
  2941. vec2.normalize(worldNormal,worldNormal);
  2942. // Get point on circle, closest to the edge
  2943. vec2.scale(candidate,worldNormal,-radius);
  2944. vec2.add(candidate,candidate,circlePos);
  2945. // Distance from v0 to the candidate point
  2946. vec2.sub(dist,candidate,v0);
  2947. // Check if it is in the element "stick"
  2948. var d = vec2.dot(dist,worldNormal);
  2949. if(candidate[0] >= v0[0] && candidate[0] < v1[0] && d <= 0){
  2950. if(justTest){
  2951. return true;
  2952. }
  2953. found = true;
  2954. // Store the candidate point, projected to the edge
  2955. vec2.scale(dist,worldNormal,-d);
  2956. vec2.add(minCandidate,candidate,dist);
  2957. vec2.copy(minCandidateNormal,worldNormal);
  2958. var c = this.createContactEquation(hfBody,circleBody,hfShape,circleShape);
  2959. // Normal is out of the heightfield
  2960. vec2.copy(c.normalA, minCandidateNormal);
  2961. // Vector from circle to heightfield
  2962. vec2.scale(c.contactPointB, c.normalA, -radius);
  2963. add(c.contactPointB, c.contactPointB, circlePos);
  2964. sub(c.contactPointB, c.contactPointB, circleBody.position);
  2965. vec2.copy(c.contactPointA, minCandidate);
  2966. vec2.sub(c.contactPointA, c.contactPointA, hfBody.position);
  2967. this.contactEquations.push(c);
  2968. if(this.enableFriction){
  2969. this.frictionEquations.push( this.createFrictionFromContact(c) );
  2970. }
  2971. }
  2972. }
  2973. // Check all vertices
  2974. found = false;
  2975. if(radius > 0){
  2976. for(var i=idxA; i<=idxB; i++){
  2977. // Get point
  2978. vec2.set(v0, i*w, data[i]);
  2979. vec2.add(v0,v0,hfPos);
  2980. vec2.sub(dist, circlePos, v0);
  2981. if(vec2.squaredLength(dist) < Math.pow(radius, 2)){
  2982. if(justTest){
  2983. return true;
  2984. }
  2985. found = true;
  2986. var c = this.createContactEquation(hfBody,circleBody,hfShape,circleShape);
  2987. // Construct normal - out of heightfield
  2988. vec2.copy(c.normalA, dist);
  2989. vec2.normalize(c.normalA,c.normalA);
  2990. vec2.scale(c.contactPointB, c.normalA, -radius);
  2991. add(c.contactPointB, c.contactPointB, circlePos);
  2992. sub(c.contactPointB, c.contactPointB, circleBody.position);
  2993. sub(c.contactPointA, v0, hfPos);
  2994. add(c.contactPointA, c.contactPointA, hfPos);
  2995. sub(c.contactPointA, c.contactPointA, hfBody.position);
  2996. this.contactEquations.push(c);
  2997. if(this.enableFriction){
  2998. this.frictionEquations.push(this.createFrictionFromContact(c));
  2999. }
  3000. }
  3001. }
  3002. }
  3003. if(found){
  3004. return 1;
  3005. }
  3006. return 0;
  3007. };
  3008. var convexHeightfield_v0 = vec2.create(),
  3009. convexHeightfield_v1 = vec2.create(),
  3010. convexHeightfield_tilePos = vec2.create(),
  3011. convexHeightfield_tempConvexShape = new Convex({ vertices: [vec2.create(),vec2.create(),vec2.create(),vec2.create()] });
  3012. /**
  3013. * @method circleHeightfield
  3014. * @param {Body} bi
  3015. * @param {Circle} si
  3016. * @param {Array} xi
  3017. * @param {Body} bj
  3018. * @param {Heightfield} sj
  3019. * @param {Array} xj
  3020. * @param {Number} aj
  3021. */
  3022. Narrowphase.prototype[Shape.BOX | Shape.HEIGHTFIELD] =
  3023. Narrowphase.prototype[Shape.CONVEX | Shape.HEIGHTFIELD] =
  3024. Narrowphase.prototype.convexHeightfield = function( convexBody,convexShape,convexPos,convexAngle,
  3025. hfBody,hfShape,hfPos,hfAngle, justTest ){
  3026. var data = hfShape.heights,
  3027. w = hfShape.elementWidth,
  3028. v0 = convexHeightfield_v0,
  3029. v1 = convexHeightfield_v1,
  3030. tilePos = convexHeightfield_tilePos,
  3031. tileConvex = convexHeightfield_tempConvexShape;
  3032. // Get the index of the points to test against
  3033. var idxA = Math.floor( (convexBody.aabb.lowerBound[0] - hfPos[0]) / w ),
  3034. idxB = Math.ceil( (convexBody.aabb.upperBound[0] - hfPos[0]) / w );
  3035. if(idxA < 0){
  3036. idxA = 0;
  3037. }
  3038. if(idxB >= data.length){
  3039. idxB = data.length-1;
  3040. }
  3041. // Get max and min
  3042. var max = data[idxA],
  3043. min = data[idxB];
  3044. for(var i=idxA; i<idxB; i++){
  3045. if(data[i] < min){
  3046. min = data[i];
  3047. }
  3048. if(data[i] > max){
  3049. max = data[i];
  3050. }
  3051. }
  3052. if(convexBody.aabb.lowerBound[1] > max){
  3053. return justTest ? false : 0;
  3054. }
  3055. var found = false;
  3056. var numContacts = 0;
  3057. // Loop over all edges
  3058. // TODO: If possible, construct a convex from several data points (need o check if the points make a convex shape)
  3059. for(var i=idxA; i<idxB; i++){
  3060. // Get points
  3061. vec2.set(v0, i*w, data[i] );
  3062. vec2.set(v1, (i+1)*w, data[i+1]);
  3063. vec2.add(v0,v0,hfPos);
  3064. vec2.add(v1,v1,hfPos);
  3065. // Construct a convex
  3066. var tileHeight = 100; // todo
  3067. vec2.set(tilePos, (v1[0] + v0[0])*0.5, (v1[1] + v0[1] - tileHeight)*0.5);
  3068. vec2.sub(tileConvex.vertices[0], v1, tilePos);
  3069. vec2.sub(tileConvex.vertices[1], v0, tilePos);
  3070. vec2.copy(tileConvex.vertices[2], tileConvex.vertices[1]);
  3071. vec2.copy(tileConvex.vertices[3], tileConvex.vertices[0]);
  3072. tileConvex.vertices[2][1] -= tileHeight;
  3073. tileConvex.vertices[3][1] -= tileHeight;
  3074. // Do convex collision
  3075. numContacts += this.convexConvex( convexBody, convexShape, convexPos, convexAngle,
  3076. hfBody, tileConvex, tilePos, 0, justTest);
  3077. }
  3078. return numContacts;
  3079. };
  3080. },{"../equations/ContactEquation":21,"../equations/Equation":22,"../equations/FrictionEquation":23,"../math/vec2":30,"../objects/Body":31,"../shapes/Box":37,"../shapes/Circle":39,"../shapes/Convex":40,"../shapes/Shape":45,"../utils/ContactEquationPool":48,"../utils/FrictionEquationPool":49,"../utils/TupleDictionary":56,"../utils/Utils":57}],11:[function(_dereq_,module,exports){
  3081. module.exports = Ray;
  3082. var vec2 = _dereq_('../math/vec2');
  3083. var RaycastResult = _dereq_('../collision/RaycastResult');
  3084. var Shape = _dereq_('../shapes/Shape');
  3085. var AABB = _dereq_('../collision/AABB');
  3086. /**
  3087. * A line with a start and end point that is used to intersect shapes. For an example, see {{#crossLink "World/raycast:method"}}World.raycast{{/crossLink}}
  3088. * @class Ray
  3089. * @constructor
  3090. * @param {object} [options]
  3091. * @param {array} [options.from]
  3092. * @param {array} [options.to]
  3093. * @param {boolean} [options.checkCollisionResponse=true]
  3094. * @param {boolean} [options.skipBackfaces=false]
  3095. * @param {number} [options.collisionMask=-1]
  3096. * @param {number} [options.collisionGroup=-1]
  3097. * @param {number} [options.mode=Ray.ANY]
  3098. * @param {number} [options.callback]
  3099. */
  3100. function Ray(options){
  3101. options = options || {};
  3102. /**
  3103. * Ray start point.
  3104. * @property {array} from
  3105. */
  3106. this.from = options.from ? vec2.fromValues(options.from[0], options.from[1]) : vec2.create();
  3107. /**
  3108. * Ray end point
  3109. * @property {array} to
  3110. */
  3111. this.to = options.to ? vec2.fromValues(options.to[0], options.to[1]) : vec2.create();
  3112. /**
  3113. * Set to true if you want the Ray to take .collisionResponse flags into account on bodies and shapes.
  3114. * @property {Boolean} checkCollisionResponse
  3115. */
  3116. this.checkCollisionResponse = options.checkCollisionResponse !== undefined ? options.checkCollisionResponse : true;
  3117. /**
  3118. * If set to true, the ray skips any hits with normal.dot(rayDirection) < 0.
  3119. * @property {Boolean} skipBackfaces
  3120. */
  3121. this.skipBackfaces = !!options.skipBackfaces;
  3122. /**
  3123. * @property {number} collisionMask
  3124. * @default -1
  3125. */
  3126. this.collisionMask = options.collisionMask !== undefined ? options.collisionMask : -1;
  3127. /**
  3128. * @property {number} collisionGroup
  3129. * @default -1
  3130. */
  3131. this.collisionGroup = options.collisionGroup !== undefined ? options.collisionGroup : -1;
  3132. /**
  3133. * The intersection mode. Should be {{#crossLink "Ray/ANY:property"}}Ray.ANY{{/crossLink}}, {{#crossLink "Ray/ALL:property"}}Ray.ALL{{/crossLink}} or {{#crossLink "Ray/CLOSEST:property"}}Ray.CLOSEST{{/crossLink}}.
  3134. * @property {number} mode
  3135. */
  3136. this.mode = options.mode !== undefined ? options.mode : Ray.ANY;
  3137. /**
  3138. * Current, user-provided result callback. Will be used if mode is Ray.ALL.
  3139. * @property {Function} callback
  3140. */
  3141. this.callback = options.callback || function(result){};
  3142. /**
  3143. * @readOnly
  3144. * @property {array} direction
  3145. */
  3146. this.direction = vec2.create();
  3147. /**
  3148. * Length of the ray
  3149. * @readOnly
  3150. * @property {number} length
  3151. */
  3152. this.length = 1;
  3153. this.update();
  3154. }
  3155. Ray.prototype.constructor = Ray;
  3156. /**
  3157. * This raycasting mode will make the Ray traverse through all intersection points and only return the closest one.
  3158. * @static
  3159. * @property {Number} CLOSEST
  3160. */
  3161. Ray.CLOSEST = 1;
  3162. /**
  3163. * This raycasting mode will make the Ray stop when it finds the first intersection point.
  3164. * @static
  3165. * @property {Number} ANY
  3166. */
  3167. Ray.ANY = 2;
  3168. /**
  3169. * This raycasting mode will traverse all intersection points and executes a callback for each one.
  3170. * @static
  3171. * @property {Number} ALL
  3172. */
  3173. Ray.ALL = 4;
  3174. /**
  3175. * Should be called if you change the from or to point.
  3176. * @method update
  3177. */
  3178. Ray.prototype.update = function(){
  3179. // Update .direction and .length
  3180. var d = this.direction;
  3181. vec2.sub(d, this.to, this.from);
  3182. this.length = vec2.length(d);
  3183. vec2.normalize(d, d);
  3184. };
  3185. /**
  3186. * @method intersectBodies
  3187. * @param {Array} bodies An array of Body objects.
  3188. */
  3189. Ray.prototype.intersectBodies = function (result, bodies) {
  3190. for (var i = 0, l = bodies.length; !result.shouldStop(this) && i < l; i++) {
  3191. var body = bodies[i];
  3192. var aabb = body.getAABB();
  3193. if(aabb.overlapsRay(this) >= 0 || aabb.containsPoint(this.from)){
  3194. this.intersectBody(result, body);
  3195. }
  3196. }
  3197. };
  3198. var intersectBody_worldPosition = vec2.create();
  3199. /**
  3200. * Shoot a ray at a body, get back information about the hit.
  3201. * @method intersectBody
  3202. * @private
  3203. * @param {Body} body
  3204. */
  3205. Ray.prototype.intersectBody = function (result, body) {
  3206. var checkCollisionResponse = this.checkCollisionResponse;
  3207. if(checkCollisionResponse && !body.collisionResponse){
  3208. return;
  3209. }
  3210. var worldPosition = intersectBody_worldPosition;
  3211. for (var i = 0, N = body.shapes.length; i < N; i++) {
  3212. var shape = body.shapes[i];
  3213. if(checkCollisionResponse && !shape.collisionResponse){
  3214. continue; // Skip
  3215. }
  3216. if((this.collisionGroup & shape.collisionMask) === 0 || (shape.collisionGroup & this.collisionMask) === 0){
  3217. continue;
  3218. }
  3219. // Get world angle and position of the shape
  3220. vec2.rotate(worldPosition, shape.position, body.angle);
  3221. vec2.add(worldPosition, worldPosition, body.position);
  3222. var worldAngle = shape.angle + body.angle;
  3223. this.intersectShape(
  3224. result,
  3225. shape,
  3226. worldAngle,
  3227. worldPosition,
  3228. body
  3229. );
  3230. if(result.shouldStop(this)){
  3231. break;
  3232. }
  3233. }
  3234. };
  3235. /**
  3236. * @method intersectShape
  3237. * @private
  3238. * @param {Shape} shape
  3239. * @param {number} angle
  3240. * @param {array} position
  3241. * @param {Body} body
  3242. */
  3243. Ray.prototype.intersectShape = function(result, shape, angle, position, body){
  3244. var from = this.from;
  3245. // Checking radius
  3246. var distance = distanceFromIntersectionSquared(from, this.direction, position);
  3247. if (distance > shape.boundingRadius * shape.boundingRadius) {
  3248. return;
  3249. }
  3250. this._currentBody = body;
  3251. this._currentShape = shape;
  3252. shape.raycast(result, this, position, angle);
  3253. this._currentBody = this._currentShape = null;
  3254. };
  3255. /**
  3256. * Get the AABB of the ray.
  3257. * @method getAABB
  3258. * @param {AABB} aabb
  3259. */
  3260. Ray.prototype.getAABB = function(result){
  3261. var to = this.to;
  3262. var from = this.from;
  3263. vec2.set(
  3264. result.lowerBound,
  3265. Math.min(to[0], from[0]),
  3266. Math.min(to[1], from[1])
  3267. );
  3268. vec2.set(
  3269. result.upperBound,
  3270. Math.max(to[0], from[0]),
  3271. Math.max(to[1], from[1])
  3272. );
  3273. };
  3274. var hitPointWorld = vec2.create();
  3275. /**
  3276. * @method reportIntersection
  3277. * @private
  3278. * @param {number} fraction
  3279. * @param {array} normal
  3280. * @param {number} [faceIndex=-1]
  3281. * @return {boolean} True if the intersections should continue
  3282. */
  3283. Ray.prototype.reportIntersection = function(result, fraction, normal, faceIndex){
  3284. var from = this.from;
  3285. var to = this.to;
  3286. var shape = this._currentShape;
  3287. var body = this._currentBody;
  3288. // Skip back faces?
  3289. if(this.skipBackfaces && vec2.dot(normal, this.direction) > 0){
  3290. return;
  3291. }
  3292. switch(this.mode){
  3293. case Ray.ALL:
  3294. result.set(
  3295. normal,
  3296. shape,
  3297. body,
  3298. fraction,
  3299. faceIndex
  3300. );
  3301. this.callback(result);
  3302. break;
  3303. case Ray.CLOSEST:
  3304. // Store if closer than current closest
  3305. if(fraction < result.fraction || !result.hasHit()){
  3306. result.set(
  3307. normal,
  3308. shape,
  3309. body,
  3310. fraction,
  3311. faceIndex
  3312. );
  3313. }
  3314. break;
  3315. case Ray.ANY:
  3316. // Report and stop.
  3317. result.set(
  3318. normal,
  3319. shape,
  3320. body,
  3321. fraction,
  3322. faceIndex
  3323. );
  3324. break;
  3325. }
  3326. };
  3327. var v0 = vec2.create(),
  3328. intersect = vec2.create();
  3329. function distanceFromIntersectionSquared(from, direction, position) {
  3330. // v0 is vector from from to position
  3331. vec2.sub(v0, position, from);
  3332. var dot = vec2.dot(v0, direction);
  3333. // intersect = direction * dot + from
  3334. vec2.scale(intersect, direction, dot);
  3335. vec2.add(intersect, intersect, from);
  3336. return vec2.squaredDistance(position, intersect);
  3337. }
  3338. },{"../collision/AABB":7,"../collision/RaycastResult":12,"../math/vec2":30,"../shapes/Shape":45}],12:[function(_dereq_,module,exports){
  3339. var vec2 = _dereq_('../math/vec2');
  3340. var Ray = _dereq_('../collision/Ray');
  3341. module.exports = RaycastResult;
  3342. /**
  3343. * Storage for Ray casting hit data.
  3344. * @class RaycastResult
  3345. * @constructor
  3346. */
  3347. function RaycastResult(){
  3348. /**
  3349. * The normal of the hit, oriented in world space.
  3350. * @property {array} normal
  3351. */
  3352. this.normal = vec2.create();
  3353. /**
  3354. * The hit shape, or null.
  3355. * @property {Shape} shape
  3356. */
  3357. this.shape = null;
  3358. /**
  3359. * The hit body, or null.
  3360. * @property {Body} body
  3361. */
  3362. this.body = null;
  3363. /**
  3364. * The index of the hit triangle, if the hit shape was indexable.
  3365. * @property {number} faceIndex
  3366. * @default -1
  3367. */
  3368. this.faceIndex = -1;
  3369. /**
  3370. * Distance to the hit, as a fraction. 0 is at the "from" point, 1 is at the "to" point. Will be set to -1 if there was no hit yet.
  3371. * @property {number} fraction
  3372. * @default -1
  3373. */
  3374. this.fraction = -1;
  3375. /**
  3376. * If the ray should stop traversing.
  3377. * @readonly
  3378. * @property {Boolean} isStopped
  3379. */
  3380. this.isStopped = false;
  3381. }
  3382. /**
  3383. * Reset all result data. Must be done before re-using the result object.
  3384. * @method reset
  3385. */
  3386. RaycastResult.prototype.reset = function () {
  3387. vec2.set(this.normal, 0, 0);
  3388. this.shape = null;
  3389. this.body = null;
  3390. this.faceIndex = -1;
  3391. this.fraction = -1;
  3392. this.isStopped = false;
  3393. };
  3394. /**
  3395. * Get the distance to the hit point.
  3396. * @method getHitDistance
  3397. * @param {Ray} ray
  3398. */
  3399. RaycastResult.prototype.getHitDistance = function (ray) {
  3400. return vec2.distance(ray.from, ray.to) * this.fraction;
  3401. };
  3402. /**
  3403. * Returns true if the ray hit something since the last reset().
  3404. * @method hasHit
  3405. */
  3406. RaycastResult.prototype.hasHit = function () {
  3407. return this.fraction !== -1;
  3408. };
  3409. /**
  3410. * Get world hit point.
  3411. * @method getHitPoint
  3412. * @param {array} out
  3413. * @param {Ray} ray
  3414. */
  3415. RaycastResult.prototype.getHitPoint = function (out, ray) {
  3416. vec2.lerp(out, ray.from, ray.to, this.fraction);
  3417. };
  3418. /**
  3419. * Can be called while iterating over hits to stop searching for hit points.
  3420. * @method stop
  3421. */
  3422. RaycastResult.prototype.stop = function(){
  3423. this.isStopped = true;
  3424. };
  3425. /**
  3426. * @method shouldStop
  3427. * @private
  3428. * @param {Ray} ray
  3429. * @return {boolean}
  3430. */
  3431. RaycastResult.prototype.shouldStop = function(ray){
  3432. return this.isStopped || (this.fraction !== -1 && ray.mode === Ray.ANY);
  3433. };
  3434. /**
  3435. * @method set
  3436. * @private
  3437. * @param {array} normal
  3438. * @param {Shape} shape
  3439. * @param {Body} body
  3440. * @param {number} fraction
  3441. */
  3442. RaycastResult.prototype.set = function(
  3443. normal,
  3444. shape,
  3445. body,
  3446. fraction,
  3447. faceIndex
  3448. ){
  3449. vec2.copy(this.normal, normal);
  3450. this.shape = shape;
  3451. this.body = body;
  3452. this.fraction = fraction;
  3453. this.faceIndex = faceIndex;
  3454. };
  3455. },{"../collision/Ray":11,"../math/vec2":30}],13:[function(_dereq_,module,exports){
  3456. var Utils = _dereq_('../utils/Utils')
  3457. , Broadphase = _dereq_('../collision/Broadphase');
  3458. module.exports = SAPBroadphase;
  3459. /**
  3460. * Sweep and prune broadphase along one axis.
  3461. *
  3462. * @class SAPBroadphase
  3463. * @constructor
  3464. * @extends Broadphase
  3465. */
  3466. function SAPBroadphase(){
  3467. Broadphase.call(this,Broadphase.SAP);
  3468. /**
  3469. * List of bodies currently in the broadphase.
  3470. * @property axisList
  3471. * @type {Array}
  3472. */
  3473. this.axisList = [];
  3474. /**
  3475. * The axis to sort along. 0 means x-axis and 1 y-axis. If your bodies are more spread out over the X axis, set axisIndex to 0, and you will gain some performance.
  3476. * @property axisIndex
  3477. * @type {Number}
  3478. */
  3479. this.axisIndex = 0;
  3480. var that = this;
  3481. this._addBodyHandler = function(e){
  3482. that.axisList.push(e.body);
  3483. };
  3484. this._removeBodyHandler = function(e){
  3485. // Remove from list
  3486. var idx = that.axisList.indexOf(e.body);
  3487. if(idx !== -1){
  3488. that.axisList.splice(idx,1);
  3489. }
  3490. };
  3491. }
  3492. SAPBroadphase.prototype = new Broadphase();
  3493. SAPBroadphase.prototype.constructor = SAPBroadphase;
  3494. /**
  3495. * Change the world
  3496. * @method setWorld
  3497. * @param {World} world
  3498. */
  3499. SAPBroadphase.prototype.setWorld = function(world){
  3500. // Clear the old axis array
  3501. this.axisList.length = 0;
  3502. // Add all bodies from the new world
  3503. Utils.appendArray(this.axisList, world.bodies);
  3504. // Remove old handlers, if any
  3505. world
  3506. .off("addBody",this._addBodyHandler)
  3507. .off("removeBody",this._removeBodyHandler);
  3508. // Add handlers to update the list of bodies.
  3509. world.on("addBody",this._addBodyHandler).on("removeBody",this._removeBodyHandler);
  3510. this.world = world;
  3511. };
  3512. /**
  3513. * Sorts bodies along an axis.
  3514. * @method sortAxisList
  3515. * @param {Array} a
  3516. * @param {number} axisIndex
  3517. * @return {Array}
  3518. */
  3519. SAPBroadphase.sortAxisList = function(a, axisIndex){
  3520. axisIndex = axisIndex|0;
  3521. for(var i=1,l=a.length; i<l; i++) {
  3522. var v = a[i];
  3523. for(var j=i - 1;j>=0;j--) {
  3524. if(a[j].aabb.lowerBound[axisIndex] <= v.aabb.lowerBound[axisIndex]){
  3525. break;
  3526. }
  3527. a[j+1] = a[j];
  3528. }
  3529. a[j+1] = v;
  3530. }
  3531. return a;
  3532. };
  3533. SAPBroadphase.prototype.sortList = function(){
  3534. var bodies = this.axisList,
  3535. axisIndex = this.axisIndex;
  3536. // Sort the lists
  3537. SAPBroadphase.sortAxisList(bodies, axisIndex);
  3538. };
  3539. /**
  3540. * Get the colliding pairs
  3541. * @method getCollisionPairs
  3542. * @param {World} world
  3543. * @return {Array}
  3544. */
  3545. SAPBroadphase.prototype.getCollisionPairs = function(world){
  3546. var bodies = this.axisList,
  3547. result = this.result,
  3548. axisIndex = this.axisIndex;
  3549. result.length = 0;
  3550. // Update all AABBs if needed
  3551. var l = bodies.length;
  3552. while(l--){
  3553. var b = bodies[l];
  3554. if(b.aabbNeedsUpdate){
  3555. b.updateAABB();
  3556. }
  3557. }
  3558. // Sort the lists
  3559. this.sortList();
  3560. // Look through the X list
  3561. for(var i=0, N=bodies.length|0; i!==N; i++){
  3562. var bi = bodies[i];
  3563. for(var j=i+1; j<N; j++){
  3564. var bj = bodies[j];
  3565. // Bounds overlap?
  3566. var overlaps = (bj.aabb.lowerBound[axisIndex] <= bi.aabb.upperBound[axisIndex]);
  3567. if(!overlaps){
  3568. break;
  3569. }
  3570. if(Broadphase.canCollide(bi,bj) && this.boundingVolumeCheck(bi,bj)){
  3571. result.push(bi,bj);
  3572. }
  3573. }
  3574. }
  3575. return result;
  3576. };
  3577. /**
  3578. * Returns all the bodies within an AABB.
  3579. * @method aabbQuery
  3580. * @param {World} world
  3581. * @param {AABB} aabb
  3582. * @param {array} result An array to store resulting bodies in.
  3583. * @return {array}
  3584. */
  3585. SAPBroadphase.prototype.aabbQuery = function(world, aabb, result){
  3586. result = result || [];
  3587. this.sortList();
  3588. var axisIndex = this.axisIndex;
  3589. var axis = 'x';
  3590. if(axisIndex === 1){ axis = 'y'; }
  3591. if(axisIndex === 2){ axis = 'z'; }
  3592. var axisList = this.axisList;
  3593. var lower = aabb.lowerBound[axis];
  3594. var upper = aabb.upperBound[axis];
  3595. for(var i = 0; i < axisList.length; i++){
  3596. var b = axisList[i];
  3597. if(b.aabbNeedsUpdate){
  3598. b.updateAABB();
  3599. }
  3600. if(b.aabb.overlaps(aabb)){
  3601. result.push(b);
  3602. }
  3603. }
  3604. return result;
  3605. };
  3606. },{"../collision/Broadphase":8,"../utils/Utils":57}],14:[function(_dereq_,module,exports){
  3607. module.exports = Constraint;
  3608. var Utils = _dereq_('../utils/Utils');
  3609. /**
  3610. * Base constraint class.
  3611. *
  3612. * @class Constraint
  3613. * @constructor
  3614. * @author schteppe
  3615. * @param {Body} bodyA
  3616. * @param {Body} bodyB
  3617. * @param {Number} type
  3618. * @param {Object} [options]
  3619. * @param {Object} [options.collideConnected=true]
  3620. */
  3621. function Constraint(bodyA, bodyB, type, options){
  3622. /**
  3623. * The type of constraint. May be one of Constraint.DISTANCE, Constraint.GEAR, Constraint.LOCK, Constraint.PRISMATIC or Constraint.REVOLUTE.
  3624. * @property {number} type
  3625. */
  3626. this.type = type;
  3627. options = Utils.defaults(options,{
  3628. collideConnected : true,
  3629. wakeUpBodies : true,
  3630. });
  3631. /**
  3632. * Equations to be solved in this constraint
  3633. *
  3634. * @property equations
  3635. * @type {Array}
  3636. */
  3637. this.equations = [];
  3638. /**
  3639. * First body participating in the constraint.
  3640. * @property bodyA
  3641. * @type {Body}
  3642. */
  3643. this.bodyA = bodyA;
  3644. /**
  3645. * Second body participating in the constraint.
  3646. * @property bodyB
  3647. * @type {Body}
  3648. */
  3649. this.bodyB = bodyB;
  3650. /**
  3651. * Set to true if you want the connected bodies to collide.
  3652. * @property collideConnected
  3653. * @type {Boolean}
  3654. * @default true
  3655. */
  3656. this.collideConnected = options.collideConnected;
  3657. // Wake up bodies when connected
  3658. if(options.wakeUpBodies){
  3659. if(bodyA){
  3660. bodyA.wakeUp();
  3661. }
  3662. if(bodyB){
  3663. bodyB.wakeUp();
  3664. }
  3665. }
  3666. }
  3667. /**
  3668. * Updates the internal constraint parameters before solve.
  3669. * @method update
  3670. */
  3671. Constraint.prototype.update = function(){
  3672. throw new Error("method update() not implmemented in this Constraint subclass!");
  3673. };
  3674. /**
  3675. * @static
  3676. * @property {number} DISTANCE
  3677. */
  3678. Constraint.DISTANCE = 1;
  3679. /**
  3680. * @static
  3681. * @property {number} GEAR
  3682. */
  3683. Constraint.GEAR = 2;
  3684. /**
  3685. * @static
  3686. * @property {number} LOCK
  3687. */
  3688. Constraint.LOCK = 3;
  3689. /**
  3690. * @static
  3691. * @property {number} PRISMATIC
  3692. */
  3693. Constraint.PRISMATIC = 4;
  3694. /**
  3695. * @static
  3696. * @property {number} REVOLUTE
  3697. */
  3698. Constraint.REVOLUTE = 5;
  3699. /**
  3700. * Set stiffness for this constraint.
  3701. * @method setStiffness
  3702. * @param {Number} stiffness
  3703. */
  3704. Constraint.prototype.setStiffness = function(stiffness){
  3705. var eqs = this.equations;
  3706. for(var i=0; i !== eqs.length; i++){
  3707. var eq = eqs[i];
  3708. eq.stiffness = stiffness;
  3709. eq.needsUpdate = true;
  3710. }
  3711. };
  3712. /**
  3713. * Set relaxation for this constraint.
  3714. * @method setRelaxation
  3715. * @param {Number} relaxation
  3716. */
  3717. Constraint.prototype.setRelaxation = function(relaxation){
  3718. var eqs = this.equations;
  3719. for(var i=0; i !== eqs.length; i++){
  3720. var eq = eqs[i];
  3721. eq.relaxation = relaxation;
  3722. eq.needsUpdate = true;
  3723. }
  3724. };
  3725. },{"../utils/Utils":57}],15:[function(_dereq_,module,exports){
  3726. var Constraint = _dereq_('./Constraint')
  3727. , Equation = _dereq_('../equations/Equation')
  3728. , vec2 = _dereq_('../math/vec2')
  3729. , Utils = _dereq_('../utils/Utils');
  3730. module.exports = DistanceConstraint;
  3731. /**
  3732. * Constraint that tries to keep the distance between two bodies constant.
  3733. *
  3734. * @class DistanceConstraint
  3735. * @constructor
  3736. * @author schteppe
  3737. * @param {Body} bodyA
  3738. * @param {Body} bodyB
  3739. * @param {object} [options]
  3740. * @param {number} [options.distance] The distance to keep between the anchor points. Defaults to the current distance between the bodies.
  3741. * @param {Array} [options.localAnchorA] The anchor point for bodyA, defined locally in bodyA frame. Defaults to [0,0].
  3742. * @param {Array} [options.localAnchorB] The anchor point for bodyB, defined locally in bodyB frame. Defaults to [0,0].
  3743. * @param {object} [options.maxForce=Number.MAX_VALUE] Maximum force to apply.
  3744. * @extends Constraint
  3745. *
  3746. * @example
  3747. * // If distance is not given as an option, then the current distance between the bodies is used.
  3748. * // In this example, the bodies will be constrained to have a distance of 2 between their centers.
  3749. * var bodyA = new Body({ mass: 1, position: [-1, 0] });
  3750. * var bodyB = new Body({ mass: 1, position: [1, 0] });
  3751. * var constraint = new DistanceConstraint(bodyA, bodyB);
  3752. * world.addConstraint(constraint);
  3753. *
  3754. * @example
  3755. * // Manually set the distance and anchors
  3756. * var constraint = new DistanceConstraint(bodyA, bodyB, {
  3757. * distance: 1, // Distance to keep between the points
  3758. * localAnchorA: [1, 0], // Point on bodyA
  3759. * localAnchorB: [-1, 0] // Point on bodyB
  3760. * });
  3761. * world.addConstraint(constraint);
  3762. */
  3763. function DistanceConstraint(bodyA,bodyB,options){
  3764. options = Utils.defaults(options,{
  3765. localAnchorA:[0,0],
  3766. localAnchorB:[0,0]
  3767. });
  3768. Constraint.call(this,bodyA,bodyB,Constraint.DISTANCE,options);
  3769. /**
  3770. * Local anchor in body A.
  3771. * @property localAnchorA
  3772. * @type {Array}
  3773. */
  3774. this.localAnchorA = vec2.fromValues(options.localAnchorA[0], options.localAnchorA[1]);
  3775. /**
  3776. * Local anchor in body B.
  3777. * @property localAnchorB
  3778. * @type {Array}
  3779. */
  3780. this.localAnchorB = vec2.fromValues(options.localAnchorB[0], options.localAnchorB[1]);
  3781. var localAnchorA = this.localAnchorA;
  3782. var localAnchorB = this.localAnchorB;
  3783. /**
  3784. * The distance to keep.
  3785. * @property distance
  3786. * @type {Number}
  3787. */
  3788. this.distance = 0;
  3789. if(typeof(options.distance) === 'number'){
  3790. this.distance = options.distance;
  3791. } else {
  3792. // Use the current world distance between the world anchor points.
  3793. var worldAnchorA = vec2.create(),
  3794. worldAnchorB = vec2.create(),
  3795. r = vec2.create();
  3796. // Transform local anchors to world
  3797. vec2.rotate(worldAnchorA, localAnchorA, bodyA.angle);
  3798. vec2.rotate(worldAnchorB, localAnchorB, bodyB.angle);
  3799. vec2.add(r, bodyB.position, worldAnchorB);
  3800. vec2.sub(r, r, worldAnchorA);
  3801. vec2.sub(r, r, bodyA.position);
  3802. this.distance = vec2.length(r);
  3803. }
  3804. var maxForce;
  3805. if(typeof(options.maxForce)==="undefined" ){
  3806. maxForce = Number.MAX_VALUE;
  3807. } else {
  3808. maxForce = options.maxForce;
  3809. }
  3810. var normal = new Equation(bodyA,bodyB,-maxForce,maxForce); // Just in the normal direction
  3811. this.equations = [ normal ];
  3812. /**
  3813. * Max force to apply.
  3814. * @property {number} maxForce
  3815. */
  3816. this.maxForce = maxForce;
  3817. // g = (xi - xj).dot(n)
  3818. // dg/dt = (vi - vj).dot(n) = G*W = [n 0 -n 0] * [vi wi vj wj]'
  3819. // ...and if we were to include offset points:
  3820. // g =
  3821. // (xj + rj - xi - ri).dot(n) - distance
  3822. //
  3823. // dg/dt =
  3824. // (vj + wj x rj - vi - wi x ri).dot(n) =
  3825. // { term 2 is near zero } =
  3826. // [-n -ri x n n rj x n] * [vi wi vj wj]' =
  3827. // G * W
  3828. //
  3829. // => G = [-n -rixn n rjxn]
  3830. var r = vec2.create();
  3831. var ri = vec2.create(); // worldAnchorA
  3832. var rj = vec2.create(); // worldAnchorB
  3833. var that = this;
  3834. normal.computeGq = function(){
  3835. var bodyA = this.bodyA,
  3836. bodyB = this.bodyB,
  3837. xi = bodyA.position,
  3838. xj = bodyB.position;
  3839. // Transform local anchors to world
  3840. vec2.rotate(ri, localAnchorA, bodyA.angle);
  3841. vec2.rotate(rj, localAnchorB, bodyB.angle);
  3842. vec2.add(r, xj, rj);
  3843. vec2.sub(r, r, ri);
  3844. vec2.sub(r, r, xi);
  3845. //vec2.sub(r, bodyB.position, bodyA.position);
  3846. return vec2.length(r) - that.distance;
  3847. };
  3848. // Make the contact constraint bilateral
  3849. this.setMaxForce(maxForce);
  3850. /**
  3851. * If the upper limit is enabled or not.
  3852. * @property {Boolean} upperLimitEnabled
  3853. */
  3854. this.upperLimitEnabled = false;
  3855. /**
  3856. * The upper constraint limit.
  3857. * @property {number} upperLimit
  3858. */
  3859. this.upperLimit = 1;
  3860. /**
  3861. * If the lower limit is enabled or not.
  3862. * @property {Boolean} lowerLimitEnabled
  3863. */
  3864. this.lowerLimitEnabled = false;
  3865. /**
  3866. * The lower constraint limit.
  3867. * @property {number} lowerLimit
  3868. */
  3869. this.lowerLimit = 0;
  3870. /**
  3871. * Current constraint position. This is equal to the current distance between the world anchor points.
  3872. * @property {number} position
  3873. */
  3874. this.position = 0;
  3875. }
  3876. DistanceConstraint.prototype = new Constraint();
  3877. DistanceConstraint.prototype.constructor = DistanceConstraint;
  3878. /**
  3879. * Update the constraint equations. Should be done if any of the bodies changed position, before solving.
  3880. * @method update
  3881. */
  3882. var n = vec2.create();
  3883. var ri = vec2.create(); // worldAnchorA
  3884. var rj = vec2.create(); // worldAnchorB
  3885. DistanceConstraint.prototype.update = function(){
  3886. var normal = this.equations[0],
  3887. bodyA = this.bodyA,
  3888. bodyB = this.bodyB,
  3889. distance = this.distance,
  3890. xi = bodyA.position,
  3891. xj = bodyB.position,
  3892. normalEquation = this.equations[0],
  3893. G = normal.G;
  3894. // Transform local anchors to world
  3895. vec2.rotate(ri, this.localAnchorA, bodyA.angle);
  3896. vec2.rotate(rj, this.localAnchorB, bodyB.angle);
  3897. // Get world anchor points and normal
  3898. vec2.add(n, xj, rj);
  3899. vec2.sub(n, n, ri);
  3900. vec2.sub(n, n, xi);
  3901. this.position = vec2.length(n);
  3902. var violating = false;
  3903. if(this.upperLimitEnabled){
  3904. if(this.position > this.upperLimit){
  3905. normalEquation.maxForce = 0;
  3906. normalEquation.minForce = -this.maxForce;
  3907. this.distance = this.upperLimit;
  3908. violating = true;
  3909. }
  3910. }
  3911. if(this.lowerLimitEnabled){
  3912. if(this.position < this.lowerLimit){
  3913. normalEquation.maxForce = this.maxForce;
  3914. normalEquation.minForce = 0;
  3915. this.distance = this.lowerLimit;
  3916. violating = true;
  3917. }
  3918. }
  3919. if((this.lowerLimitEnabled || this.upperLimitEnabled) && !violating){
  3920. // No constraint needed.
  3921. normalEquation.enabled = false;
  3922. return;
  3923. }
  3924. normalEquation.enabled = true;
  3925. vec2.normalize(n,n);
  3926. // Caluclate cross products
  3927. var rixn = vec2.crossLength(ri, n),
  3928. rjxn = vec2.crossLength(rj, n);
  3929. // G = [-n -rixn n rjxn]
  3930. G[0] = -n[0];
  3931. G[1] = -n[1];
  3932. G[2] = -rixn;
  3933. G[3] = n[0];
  3934. G[4] = n[1];
  3935. G[5] = rjxn;
  3936. };
  3937. /**
  3938. * Set the max force to be used
  3939. * @method setMaxForce
  3940. * @param {Number} maxForce
  3941. */
  3942. DistanceConstraint.prototype.setMaxForce = function(maxForce){
  3943. var normal = this.equations[0];
  3944. normal.minForce = -maxForce;
  3945. normal.maxForce = maxForce;
  3946. };
  3947. /**
  3948. * Get the max force
  3949. * @method getMaxForce
  3950. * @return {Number}
  3951. */
  3952. DistanceConstraint.prototype.getMaxForce = function(){
  3953. var normal = this.equations[0];
  3954. return normal.maxForce;
  3955. };
  3956. },{"../equations/Equation":22,"../math/vec2":30,"../utils/Utils":57,"./Constraint":14}],16:[function(_dereq_,module,exports){
  3957. var Constraint = _dereq_('./Constraint')
  3958. , Equation = _dereq_('../equations/Equation')
  3959. , AngleLockEquation = _dereq_('../equations/AngleLockEquation')
  3960. , vec2 = _dereq_('../math/vec2');
  3961. module.exports = GearConstraint;
  3962. /**
  3963. * Constrains the angle of two bodies to each other to be equal. If a gear ratio is not one, the angle of bodyA must be a multiple of the angle of bodyB.
  3964. * @class GearConstraint
  3965. * @constructor
  3966. * @author schteppe
  3967. * @param {Body} bodyA
  3968. * @param {Body} bodyB
  3969. * @param {Object} [options]
  3970. * @param {Number} [options.angle=0] Relative angle between the bodies. Will be set to the current angle between the bodies (the gear ratio is accounted for).
  3971. * @param {Number} [options.ratio=1] Gear ratio.
  3972. * @param {Number} [options.maxTorque] Maximum torque to apply.
  3973. * @extends Constraint
  3974. *
  3975. * @example
  3976. * var constraint = new GearConstraint(bodyA, bodyB);
  3977. * world.addConstraint(constraint);
  3978. *
  3979. * @example
  3980. * var constraint = new GearConstraint(bodyA, bodyB, {
  3981. * ratio: 2,
  3982. * maxTorque: 1000
  3983. * });
  3984. * world.addConstraint(constraint);
  3985. */
  3986. function GearConstraint(bodyA, bodyB, options){
  3987. options = options || {};
  3988. Constraint.call(this, bodyA, bodyB, Constraint.GEAR, options);
  3989. /**
  3990. * The gear ratio.
  3991. * @property ratio
  3992. * @type {Number}
  3993. */
  3994. this.ratio = options.ratio !== undefined ? options.ratio : 1;
  3995. /**
  3996. * The relative angle
  3997. * @property angle
  3998. * @type {Number}
  3999. */
  4000. this.angle = options.angle !== undefined ? options.angle : bodyB.angle - this.ratio * bodyA.angle;
  4001. // Send same parameters to the equation
  4002. options.angle = this.angle;
  4003. options.ratio = this.ratio;
  4004. this.equations = [
  4005. new AngleLockEquation(bodyA,bodyB,options),
  4006. ];
  4007. // Set max torque
  4008. if(options.maxTorque !== undefined){
  4009. this.setMaxTorque(options.maxTorque);
  4010. }
  4011. }
  4012. GearConstraint.prototype = new Constraint();
  4013. GearConstraint.prototype.constructor = GearConstraint;
  4014. GearConstraint.prototype.update = function(){
  4015. var eq = this.equations[0];
  4016. if(eq.ratio !== this.ratio){
  4017. eq.setRatio(this.ratio);
  4018. }
  4019. eq.angle = this.angle;
  4020. };
  4021. /**
  4022. * Set the max torque for the constraint.
  4023. * @method setMaxTorque
  4024. * @param {Number} torque
  4025. */
  4026. GearConstraint.prototype.setMaxTorque = function(torque){
  4027. this.equations[0].setMaxTorque(torque);
  4028. };
  4029. /**
  4030. * Get the max torque for the constraint.
  4031. * @method getMaxTorque
  4032. * @return {Number}
  4033. */
  4034. GearConstraint.prototype.getMaxTorque = function(torque){
  4035. return this.equations[0].maxForce;
  4036. };
  4037. },{"../equations/AngleLockEquation":20,"../equations/Equation":22,"../math/vec2":30,"./Constraint":14}],17:[function(_dereq_,module,exports){
  4038. var Constraint = _dereq_('./Constraint')
  4039. , vec2 = _dereq_('../math/vec2')
  4040. , Equation = _dereq_('../equations/Equation');
  4041. module.exports = LockConstraint;
  4042. /**
  4043. * Locks the relative position and rotation between two bodies.
  4044. *
  4045. * @class LockConstraint
  4046. * @constructor
  4047. * @author schteppe
  4048. * @param {Body} bodyA
  4049. * @param {Body} bodyB
  4050. * @param {Object} [options]
  4051. * @param {Array} [options.localOffsetB] The offset of bodyB in bodyA's frame. If not given the offset is computed from current positions.
  4052. * @param {number} [options.localAngleB] The angle of bodyB in bodyA's frame. If not given, the angle is computed from current angles.
  4053. * @param {number} [options.maxForce]
  4054. * @extends Constraint
  4055. *
  4056. * @example
  4057. * // Locks the relative position and rotation between bodyA and bodyB
  4058. * var constraint = new LockConstraint(bodyA, bodyB);
  4059. * world.addConstraint(constraint);
  4060. */
  4061. function LockConstraint(bodyA, bodyB, options){
  4062. options = options || {};
  4063. Constraint.call(this,bodyA,bodyB,Constraint.LOCK,options);
  4064. var maxForce = ( typeof(options.maxForce)==="undefined" ? Number.MAX_VALUE : options.maxForce );
  4065. var localAngleB = options.localAngleB || 0;
  4066. // Use 3 equations:
  4067. // gx = (xj - xi - l) * xhat = 0
  4068. // gy = (xj - xi - l) * yhat = 0
  4069. // gr = (xi - xj + r) * that = 0
  4070. //
  4071. // ...where:
  4072. // l is the localOffsetB vector rotated to world in bodyA frame
  4073. // r is the same vector but reversed and rotated from bodyB frame
  4074. // xhat, yhat are world axis vectors
  4075. // that is the tangent of r
  4076. //
  4077. // For the first two constraints, we get
  4078. // G*W = (vj - vi - ldot ) * xhat
  4079. // = (vj - vi - wi x l) * xhat
  4080. //
  4081. // Since (wi x l) * xhat = (l x xhat) * wi, we get
  4082. // G*W = [ -1 0 (-l x xhat) 1 0 0] * [vi wi vj wj]
  4083. //
  4084. // The last constraint gives
  4085. // GW = (vi - vj + wj x r) * that
  4086. // = [ that 0 -that (r x t) ]
  4087. var x = new Equation(bodyA,bodyB,-maxForce,maxForce),
  4088. y = new Equation(bodyA,bodyB,-maxForce,maxForce),
  4089. rot = new Equation(bodyA,bodyB,-maxForce,maxForce);
  4090. var l = vec2.create(),
  4091. g = vec2.create(),
  4092. that = this;
  4093. x.computeGq = function(){
  4094. vec2.rotate(l, that.localOffsetB, bodyA.angle);
  4095. vec2.sub(g, bodyB.position, bodyA.position);
  4096. vec2.sub(g, g, l);
  4097. return g[0];
  4098. };
  4099. y.computeGq = function(){
  4100. vec2.rotate(l, that.localOffsetB, bodyA.angle);
  4101. vec2.sub(g, bodyB.position, bodyA.position);
  4102. vec2.sub(g, g, l);
  4103. return g[1];
  4104. };
  4105. var r = vec2.create(),
  4106. t = vec2.create();
  4107. rot.computeGq = function(){
  4108. vec2.rotate(r, that.localOffsetB, bodyB.angle - that.localAngleB);
  4109. vec2.scale(r,r,-1);
  4110. vec2.sub(g,bodyA.position,bodyB.position);
  4111. vec2.add(g,g,r);
  4112. vec2.rotate(t,r,-Math.PI/2);
  4113. vec2.normalize(t,t);
  4114. return vec2.dot(g,t);
  4115. };
  4116. /**
  4117. * The offset of bodyB in bodyA's frame.
  4118. * @property {Array} localOffsetB
  4119. */
  4120. this.localOffsetB = vec2.create();
  4121. if(options.localOffsetB){
  4122. vec2.copy(this.localOffsetB, options.localOffsetB);
  4123. } else {
  4124. // Construct from current positions
  4125. vec2.sub(this.localOffsetB, bodyB.position, bodyA.position);
  4126. vec2.rotate(this.localOffsetB, this.localOffsetB, -bodyA.angle);
  4127. }
  4128. /**
  4129. * The offset angle of bodyB in bodyA's frame.
  4130. * @property {Number} localAngleB
  4131. */
  4132. this.localAngleB = 0;
  4133. if(typeof(options.localAngleB) === 'number'){
  4134. this.localAngleB = options.localAngleB;
  4135. } else {
  4136. // Construct
  4137. this.localAngleB = bodyB.angle - bodyA.angle;
  4138. }
  4139. this.equations.push(x, y, rot);
  4140. this.setMaxForce(maxForce);
  4141. }
  4142. LockConstraint.prototype = new Constraint();
  4143. LockConstraint.prototype.constructor = LockConstraint;
  4144. /**
  4145. * Set the maximum force to be applied.
  4146. * @method setMaxForce
  4147. * @param {Number} force
  4148. */
  4149. LockConstraint.prototype.setMaxForce = function(force){
  4150. var eqs = this.equations;
  4151. for(var i=0; i<this.equations.length; i++){
  4152. eqs[i].maxForce = force;
  4153. eqs[i].minForce = -force;
  4154. }
  4155. };
  4156. /**
  4157. * Get the max force.
  4158. * @method getMaxForce
  4159. * @return {Number}
  4160. */
  4161. LockConstraint.prototype.getMaxForce = function(){
  4162. return this.equations[0].maxForce;
  4163. };
  4164. var l = vec2.create();
  4165. var r = vec2.create();
  4166. var t = vec2.create();
  4167. var xAxis = vec2.fromValues(1,0);
  4168. var yAxis = vec2.fromValues(0,1);
  4169. LockConstraint.prototype.update = function(){
  4170. var x = this.equations[0],
  4171. y = this.equations[1],
  4172. rot = this.equations[2],
  4173. bodyA = this.bodyA,
  4174. bodyB = this.bodyB;
  4175. vec2.rotate(l,this.localOffsetB,bodyA.angle);
  4176. vec2.rotate(r,this.localOffsetB,bodyB.angle - this.localAngleB);
  4177. vec2.scale(r,r,-1);
  4178. vec2.rotate(t,r,Math.PI/2);
  4179. vec2.normalize(t,t);
  4180. x.G[0] = -1;
  4181. x.G[1] = 0;
  4182. x.G[2] = -vec2.crossLength(l,xAxis);
  4183. x.G[3] = 1;
  4184. y.G[0] = 0;
  4185. y.G[1] = -1;
  4186. y.G[2] = -vec2.crossLength(l,yAxis);
  4187. y.G[4] = 1;
  4188. rot.G[0] = -t[0];
  4189. rot.G[1] = -t[1];
  4190. rot.G[3] = t[0];
  4191. rot.G[4] = t[1];
  4192. rot.G[5] = vec2.crossLength(r,t);
  4193. };
  4194. },{"../equations/Equation":22,"../math/vec2":30,"./Constraint":14}],18:[function(_dereq_,module,exports){
  4195. var Constraint = _dereq_('./Constraint')
  4196. , ContactEquation = _dereq_('../equations/ContactEquation')
  4197. , Equation = _dereq_('../equations/Equation')
  4198. , vec2 = _dereq_('../math/vec2')
  4199. , RotationalLockEquation = _dereq_('../equations/RotationalLockEquation');
  4200. module.exports = PrismaticConstraint;
  4201. /**
  4202. * Constraint that only allows bodies to move along a line, relative to each other. See <a href="http://www.iforce2d.net/b2dtut/joints-prismatic">this tutorial</a>. Also called "slider constraint".
  4203. *
  4204. * @class PrismaticConstraint
  4205. * @constructor
  4206. * @extends Constraint
  4207. * @author schteppe
  4208. * @param {Body} bodyA
  4209. * @param {Body} bodyB
  4210. * @param {Object} [options]
  4211. * @param {Number} [options.maxForce] Max force to be applied by the constraint
  4212. * @param {Array} [options.localAnchorA] Body A's anchor point, defined in its own local frame.
  4213. * @param {Array} [options.localAnchorB] Body B's anchor point, defined in its own local frame.
  4214. * @param {Array} [options.localAxisA] An axis, defined in body A frame, that body B's anchor point may slide along.
  4215. * @param {Boolean} [options.disableRotationalLock] If set to true, bodyB will be free to rotate around its anchor point.
  4216. * @param {Number} [options.upperLimit]
  4217. * @param {Number} [options.lowerLimit]
  4218. * @todo Ability to create using only a point and a worldAxis
  4219. */
  4220. function PrismaticConstraint(bodyA, bodyB, options){
  4221. options = options || {};
  4222. Constraint.call(this,bodyA,bodyB,Constraint.PRISMATIC,options);
  4223. // Get anchors
  4224. var localAnchorA = vec2.fromValues(0,0),
  4225. localAxisA = vec2.fromValues(1,0),
  4226. localAnchorB = vec2.fromValues(0,0);
  4227. if(options.localAnchorA){ vec2.copy(localAnchorA, options.localAnchorA); }
  4228. if(options.localAxisA){ vec2.copy(localAxisA, options.localAxisA); }
  4229. if(options.localAnchorB){ vec2.copy(localAnchorB, options.localAnchorB); }
  4230. /**
  4231. * @property localAnchorA
  4232. * @type {Array}
  4233. */
  4234. this.localAnchorA = localAnchorA;
  4235. /**
  4236. * @property localAnchorB
  4237. * @type {Array}
  4238. */
  4239. this.localAnchorB = localAnchorB;
  4240. /**
  4241. * @property localAxisA
  4242. * @type {Array}
  4243. */
  4244. this.localAxisA = localAxisA;
  4245. /*
  4246. The constraint violation for the common axis point is
  4247. g = ( xj + rj - xi - ri ) * t := gg*t
  4248. where r are body-local anchor points, and t is a tangent to the constraint axis defined in body i frame.
  4249. gdot = ( vj + wj x rj - vi - wi x ri ) * t + ( xj + rj - xi - ri ) * ( wi x t )
  4250. Note the use of the chain rule. Now we identify the jacobian
  4251. G*W = [ -t -ri x t + t x gg t rj x t ] * [vi wi vj wj]
  4252. The rotational part is just a rotation lock.
  4253. */
  4254. var maxForce = this.maxForce = typeof(options.maxForce)!=="undefined" ? options.maxForce : Number.MAX_VALUE;
  4255. // Translational part
  4256. var trans = new Equation(bodyA,bodyB,-maxForce,maxForce);
  4257. var ri = new vec2.create(),
  4258. rj = new vec2.create(),
  4259. gg = new vec2.create(),
  4260. t = new vec2.create();
  4261. trans.computeGq = function(){
  4262. // g = ( xj + rj - xi - ri ) * t
  4263. return vec2.dot(gg,t);
  4264. };
  4265. trans.updateJacobian = function(){
  4266. var G = this.G,
  4267. xi = bodyA.position,
  4268. xj = bodyB.position;
  4269. vec2.rotate(ri,localAnchorA,bodyA.angle);
  4270. vec2.rotate(rj,localAnchorB,bodyB.angle);
  4271. vec2.add(gg,xj,rj);
  4272. vec2.sub(gg,gg,xi);
  4273. vec2.sub(gg,gg,ri);
  4274. vec2.rotate(t,localAxisA,bodyA.angle+Math.PI/2);
  4275. G[0] = -t[0];
  4276. G[1] = -t[1];
  4277. G[2] = -vec2.crossLength(ri,t) + vec2.crossLength(t,gg);
  4278. G[3] = t[0];
  4279. G[4] = t[1];
  4280. G[5] = vec2.crossLength(rj,t);
  4281. };
  4282. this.equations.push(trans);
  4283. // Rotational part
  4284. if(!options.disableRotationalLock){
  4285. var rot = new RotationalLockEquation(bodyA,bodyB,-maxForce,maxForce);
  4286. this.equations.push(rot);
  4287. }
  4288. /**
  4289. * The position of anchor A relative to anchor B, along the constraint axis.
  4290. * @property position
  4291. * @type {Number}
  4292. */
  4293. this.position = 0;
  4294. // Is this one used at all?
  4295. this.velocity = 0;
  4296. /**
  4297. * Set to true to enable lower limit.
  4298. * @property lowerLimitEnabled
  4299. * @type {Boolean}
  4300. */
  4301. this.lowerLimitEnabled = typeof(options.lowerLimit)!=="undefined" ? true : false;
  4302. /**
  4303. * Set to true to enable upper limit.
  4304. * @property upperLimitEnabled
  4305. * @type {Boolean}
  4306. */
  4307. this.upperLimitEnabled = typeof(options.upperLimit)!=="undefined" ? true : false;
  4308. /**
  4309. * Lower constraint limit. The constraint position is forced to be larger than this value.
  4310. * @property lowerLimit
  4311. * @type {Number}
  4312. */
  4313. this.lowerLimit = typeof(options.lowerLimit)!=="undefined" ? options.lowerLimit : 0;
  4314. /**
  4315. * Upper constraint limit. The constraint position is forced to be smaller than this value.
  4316. * @property upperLimit
  4317. * @type {Number}
  4318. */
  4319. this.upperLimit = typeof(options.upperLimit)!=="undefined" ? options.upperLimit : 1;
  4320. // Equations used for limits
  4321. this.upperLimitEquation = new ContactEquation(bodyA,bodyB);
  4322. this.lowerLimitEquation = new ContactEquation(bodyA,bodyB);
  4323. // Set max/min forces
  4324. this.upperLimitEquation.minForce = this.lowerLimitEquation.minForce = 0;
  4325. this.upperLimitEquation.maxForce = this.lowerLimitEquation.maxForce = maxForce;
  4326. /**
  4327. * Equation used for the motor.
  4328. * @property motorEquation
  4329. * @type {Equation}
  4330. */
  4331. this.motorEquation = new Equation(bodyA,bodyB);
  4332. /**
  4333. * The current motor state. Enable or disable the motor using .enableMotor
  4334. * @property motorEnabled
  4335. * @type {Boolean}
  4336. */
  4337. this.motorEnabled = false;
  4338. /**
  4339. * Set the target speed for the motor.
  4340. * @property motorSpeed
  4341. * @type {Number}
  4342. */
  4343. this.motorSpeed = 0;
  4344. var that = this;
  4345. var motorEquation = this.motorEquation;
  4346. var old = motorEquation.computeGW;
  4347. motorEquation.computeGq = function(){ return 0; };
  4348. motorEquation.computeGW = function(){
  4349. var G = this.G,
  4350. bi = this.bodyA,
  4351. bj = this.bodyB,
  4352. vi = bi.velocity,
  4353. vj = bj.velocity,
  4354. wi = bi.angularVelocity,
  4355. wj = bj.angularVelocity;
  4356. return this.gmult(G,vi,wi,vj,wj) + that.motorSpeed;
  4357. };
  4358. }
  4359. PrismaticConstraint.prototype = new Constraint();
  4360. PrismaticConstraint.prototype.constructor = PrismaticConstraint;
  4361. var worldAxisA = vec2.create(),
  4362. worldAnchorA = vec2.create(),
  4363. worldAnchorB = vec2.create(),
  4364. orientedAnchorA = vec2.create(),
  4365. orientedAnchorB = vec2.create(),
  4366. tmp = vec2.create();
  4367. /**
  4368. * Update the constraint equations. Should be done if any of the bodies changed position, before solving.
  4369. * @method update
  4370. */
  4371. PrismaticConstraint.prototype.update = function(){
  4372. var eqs = this.equations,
  4373. trans = eqs[0],
  4374. upperLimit = this.upperLimit,
  4375. lowerLimit = this.lowerLimit,
  4376. upperLimitEquation = this.upperLimitEquation,
  4377. lowerLimitEquation = this.lowerLimitEquation,
  4378. bodyA = this.bodyA,
  4379. bodyB = this.bodyB,
  4380. localAxisA = this.localAxisA,
  4381. localAnchorA = this.localAnchorA,
  4382. localAnchorB = this.localAnchorB;
  4383. trans.updateJacobian();
  4384. // Transform local things to world
  4385. vec2.rotate(worldAxisA, localAxisA, bodyA.angle);
  4386. vec2.rotate(orientedAnchorA, localAnchorA, bodyA.angle);
  4387. vec2.add(worldAnchorA, orientedAnchorA, bodyA.position);
  4388. vec2.rotate(orientedAnchorB, localAnchorB, bodyB.angle);
  4389. vec2.add(worldAnchorB, orientedAnchorB, bodyB.position);
  4390. var relPosition = this.position = vec2.dot(worldAnchorB,worldAxisA) - vec2.dot(worldAnchorA,worldAxisA);
  4391. // Motor
  4392. if(this.motorEnabled){
  4393. // G = [ a a x ri -a -a x rj ]
  4394. var G = this.motorEquation.G;
  4395. G[0] = worldAxisA[0];
  4396. G[1] = worldAxisA[1];
  4397. G[2] = vec2.crossLength(worldAxisA,orientedAnchorB);
  4398. G[3] = -worldAxisA[0];
  4399. G[4] = -worldAxisA[1];
  4400. G[5] = -vec2.crossLength(worldAxisA,orientedAnchorA);
  4401. }
  4402. /*
  4403. Limits strategy:
  4404. Add contact equation, with normal along the constraint axis.
  4405. min/maxForce is set so the constraint is repulsive in the correct direction.
  4406. Some offset is added to either equation.contactPointA or .contactPointB to get the correct upper/lower limit.
  4407. ^
  4408. |
  4409. upperLimit x
  4410. | ------
  4411. anchorB x<---| B |
  4412. | | |
  4413. ------ | ------
  4414. | | |
  4415. | A |-->x anchorA
  4416. ------ |
  4417. x lowerLimit
  4418. |
  4419. axis
  4420. */
  4421. if(this.upperLimitEnabled && relPosition > upperLimit){
  4422. // Update contact constraint normal, etc
  4423. vec2.scale(upperLimitEquation.normalA, worldAxisA, -1);
  4424. vec2.sub(upperLimitEquation.contactPointA, worldAnchorA, bodyA.position);
  4425. vec2.sub(upperLimitEquation.contactPointB, worldAnchorB, bodyB.position);
  4426. vec2.scale(tmp,worldAxisA,upperLimit);
  4427. vec2.add(upperLimitEquation.contactPointA,upperLimitEquation.contactPointA,tmp);
  4428. if(eqs.indexOf(upperLimitEquation) === -1){
  4429. eqs.push(upperLimitEquation);
  4430. }
  4431. } else {
  4432. var idx = eqs.indexOf(upperLimitEquation);
  4433. if(idx !== -1){
  4434. eqs.splice(idx,1);
  4435. }
  4436. }
  4437. if(this.lowerLimitEnabled && relPosition < lowerLimit){
  4438. // Update contact constraint normal, etc
  4439. vec2.scale(lowerLimitEquation.normalA, worldAxisA, 1);
  4440. vec2.sub(lowerLimitEquation.contactPointA, worldAnchorA, bodyA.position);
  4441. vec2.sub(lowerLimitEquation.contactPointB, worldAnchorB, bodyB.position);
  4442. vec2.scale(tmp,worldAxisA,lowerLimit);
  4443. vec2.sub(lowerLimitEquation.contactPointB,lowerLimitEquation.contactPointB,tmp);
  4444. if(eqs.indexOf(lowerLimitEquation) === -1){
  4445. eqs.push(lowerLimitEquation);
  4446. }
  4447. } else {
  4448. var idx = eqs.indexOf(lowerLimitEquation);
  4449. if(idx !== -1){
  4450. eqs.splice(idx,1);
  4451. }
  4452. }
  4453. };
  4454. /**
  4455. * Enable the motor
  4456. * @method enableMotor
  4457. */
  4458. PrismaticConstraint.prototype.enableMotor = function(){
  4459. if(this.motorEnabled){
  4460. return;
  4461. }
  4462. this.equations.push(this.motorEquation);
  4463. this.motorEnabled = true;
  4464. };
  4465. /**
  4466. * Disable the rotational motor
  4467. * @method disableMotor
  4468. */
  4469. PrismaticConstraint.prototype.disableMotor = function(){
  4470. if(!this.motorEnabled){
  4471. return;
  4472. }
  4473. var i = this.equations.indexOf(this.motorEquation);
  4474. this.equations.splice(i,1);
  4475. this.motorEnabled = false;
  4476. };
  4477. /**
  4478. * Set the constraint limits.
  4479. * @method setLimits
  4480. * @param {number} lower Lower limit.
  4481. * @param {number} upper Upper limit.
  4482. */
  4483. PrismaticConstraint.prototype.setLimits = function (lower, upper) {
  4484. if(typeof(lower) === 'number'){
  4485. this.lowerLimit = lower;
  4486. this.lowerLimitEnabled = true;
  4487. } else {
  4488. this.lowerLimit = lower;
  4489. this.lowerLimitEnabled = false;
  4490. }
  4491. if(typeof(upper) === 'number'){
  4492. this.upperLimit = upper;
  4493. this.upperLimitEnabled = true;
  4494. } else {
  4495. this.upperLimit = upper;
  4496. this.upperLimitEnabled = false;
  4497. }
  4498. };
  4499. },{"../equations/ContactEquation":21,"../equations/Equation":22,"../equations/RotationalLockEquation":24,"../math/vec2":30,"./Constraint":14}],19:[function(_dereq_,module,exports){
  4500. var Constraint = _dereq_('./Constraint')
  4501. , Equation = _dereq_('../equations/Equation')
  4502. , RotationalVelocityEquation = _dereq_('../equations/RotationalVelocityEquation')
  4503. , RotationalLockEquation = _dereq_('../equations/RotationalLockEquation')
  4504. , vec2 = _dereq_('../math/vec2');
  4505. module.exports = RevoluteConstraint;
  4506. var worldPivotA = vec2.create(),
  4507. worldPivotB = vec2.create(),
  4508. xAxis = vec2.fromValues(1,0),
  4509. yAxis = vec2.fromValues(0,1),
  4510. g = vec2.create();
  4511. /**
  4512. * Connects two bodies at given offset points, letting them rotate relative to each other around this point.
  4513. * @class RevoluteConstraint
  4514. * @constructor
  4515. * @author schteppe
  4516. * @param {Body} bodyA
  4517. * @param {Body} bodyB
  4518. * @param {Object} [options]
  4519. * @param {Array} [options.worldPivot] A pivot point given in world coordinates. If specified, localPivotA and localPivotB are automatically computed from this value.
  4520. * @param {Array} [options.localPivotA] The point relative to the center of mass of bodyA which bodyA is constrained to.
  4521. * @param {Array} [options.localPivotB] See localPivotA.
  4522. * @param {Number} [options.maxForce] The maximum force that should be applied to constrain the bodies.
  4523. * @extends Constraint
  4524. *
  4525. * @example
  4526. * // This will create a revolute constraint between two bodies with pivot point in between them.
  4527. * var bodyA = new Body({ mass: 1, position: [-1, 0] });
  4528. * var bodyB = new Body({ mass: 1, position: [1, 0] });
  4529. * var constraint = new RevoluteConstraint(bodyA, bodyB, {
  4530. * worldPivot: [0, 0]
  4531. * });
  4532. * world.addConstraint(constraint);
  4533. *
  4534. * // Using body-local pivot points, the constraint could have been constructed like this:
  4535. * var constraint = new RevoluteConstraint(bodyA, bodyB, {
  4536. * localPivotA: [1, 0],
  4537. * localPivotB: [-1, 0]
  4538. * });
  4539. */
  4540. function RevoluteConstraint(bodyA, bodyB, options){
  4541. options = options || {};
  4542. Constraint.call(this,bodyA,bodyB,Constraint.REVOLUTE,options);
  4543. var maxForce = this.maxForce = typeof(options.maxForce) !== "undefined" ? options.maxForce : Number.MAX_VALUE;
  4544. /**
  4545. * @property {Array} pivotA
  4546. */
  4547. this.pivotA = vec2.create();
  4548. /**
  4549. * @property {Array} pivotB
  4550. */
  4551. this.pivotB = vec2.create();
  4552. if(options.worldPivot){
  4553. // Compute pivotA and pivotB
  4554. vec2.sub(this.pivotA, options.worldPivot, bodyA.position);
  4555. vec2.sub(this.pivotB, options.worldPivot, bodyB.position);
  4556. // Rotate to local coordinate system
  4557. vec2.rotate(this.pivotA, this.pivotA, -bodyA.angle);
  4558. vec2.rotate(this.pivotB, this.pivotB, -bodyB.angle);
  4559. } else {
  4560. // Get pivotA and pivotB
  4561. vec2.copy(this.pivotA, options.localPivotA);
  4562. vec2.copy(this.pivotB, options.localPivotB);
  4563. }
  4564. // Equations to be fed to the solver
  4565. var eqs = this.equations = [
  4566. new Equation(bodyA,bodyB,-maxForce,maxForce),
  4567. new Equation(bodyA,bodyB,-maxForce,maxForce),
  4568. ];
  4569. var x = eqs[0];
  4570. var y = eqs[1];
  4571. var that = this;
  4572. x.computeGq = function(){
  4573. vec2.rotate(worldPivotA, that.pivotA, bodyA.angle);
  4574. vec2.rotate(worldPivotB, that.pivotB, bodyB.angle);
  4575. vec2.add(g, bodyB.position, worldPivotB);
  4576. vec2.sub(g, g, bodyA.position);
  4577. vec2.sub(g, g, worldPivotA);
  4578. return vec2.dot(g,xAxis);
  4579. };
  4580. y.computeGq = function(){
  4581. vec2.rotate(worldPivotA, that.pivotA, bodyA.angle);
  4582. vec2.rotate(worldPivotB, that.pivotB, bodyB.angle);
  4583. vec2.add(g, bodyB.position, worldPivotB);
  4584. vec2.sub(g, g, bodyA.position);
  4585. vec2.sub(g, g, worldPivotA);
  4586. return vec2.dot(g,yAxis);
  4587. };
  4588. y.minForce = x.minForce = -maxForce;
  4589. y.maxForce = x.maxForce = maxForce;
  4590. this.motorEquation = new RotationalVelocityEquation(bodyA,bodyB);
  4591. /**
  4592. * Indicates whether the motor is enabled. Use .enableMotor() to enable the constraint motor.
  4593. * @property {Boolean} motorEnabled
  4594. * @readOnly
  4595. */
  4596. this.motorEnabled = false;
  4597. /**
  4598. * The constraint position.
  4599. * @property angle
  4600. * @type {Number}
  4601. * @readOnly
  4602. */
  4603. this.angle = 0;
  4604. /**
  4605. * Set to true to enable lower limit
  4606. * @property lowerLimitEnabled
  4607. * @type {Boolean}
  4608. */
  4609. this.lowerLimitEnabled = false;
  4610. /**
  4611. * Set to true to enable upper limit
  4612. * @property upperLimitEnabled
  4613. * @type {Boolean}
  4614. */
  4615. this.upperLimitEnabled = false;
  4616. /**
  4617. * The lower limit on the constraint angle.
  4618. * @property lowerLimit
  4619. * @type {Boolean}
  4620. */
  4621. this.lowerLimit = 0;
  4622. /**
  4623. * The upper limit on the constraint angle.
  4624. * @property upperLimit
  4625. * @type {Boolean}
  4626. */
  4627. this.upperLimit = 0;
  4628. this.upperLimitEquation = new RotationalLockEquation(bodyA,bodyB);
  4629. this.lowerLimitEquation = new RotationalLockEquation(bodyA,bodyB);
  4630. this.upperLimitEquation.minForce = 0;
  4631. this.lowerLimitEquation.maxForce = 0;
  4632. }
  4633. RevoluteConstraint.prototype = new Constraint();
  4634. RevoluteConstraint.prototype.constructor = RevoluteConstraint;
  4635. /**
  4636. * Set the constraint angle limits.
  4637. * @method setLimits
  4638. * @param {number} lower Lower angle limit.
  4639. * @param {number} upper Upper angle limit.
  4640. */
  4641. RevoluteConstraint.prototype.setLimits = function (lower, upper) {
  4642. if(typeof(lower) === 'number'){
  4643. this.lowerLimit = lower;
  4644. this.lowerLimitEnabled = true;
  4645. } else {
  4646. this.lowerLimit = lower;
  4647. this.lowerLimitEnabled = false;
  4648. }
  4649. if(typeof(upper) === 'number'){
  4650. this.upperLimit = upper;
  4651. this.upperLimitEnabled = true;
  4652. } else {
  4653. this.upperLimit = upper;
  4654. this.upperLimitEnabled = false;
  4655. }
  4656. };
  4657. RevoluteConstraint.prototype.update = function(){
  4658. var bodyA = this.bodyA,
  4659. bodyB = this.bodyB,
  4660. pivotA = this.pivotA,
  4661. pivotB = this.pivotB,
  4662. eqs = this.equations,
  4663. normal = eqs[0],
  4664. tangent= eqs[1],
  4665. x = eqs[0],
  4666. y = eqs[1],
  4667. upperLimit = this.upperLimit,
  4668. lowerLimit = this.lowerLimit,
  4669. upperLimitEquation = this.upperLimitEquation,
  4670. lowerLimitEquation = this.lowerLimitEquation;
  4671. var relAngle = this.angle = bodyB.angle - bodyA.angle;
  4672. if(this.upperLimitEnabled && relAngle > upperLimit){
  4673. upperLimitEquation.angle = upperLimit;
  4674. if(eqs.indexOf(upperLimitEquation) === -1){
  4675. eqs.push(upperLimitEquation);
  4676. }
  4677. } else {
  4678. var idx = eqs.indexOf(upperLimitEquation);
  4679. if(idx !== -1){
  4680. eqs.splice(idx,1);
  4681. }
  4682. }
  4683. if(this.lowerLimitEnabled && relAngle < lowerLimit){
  4684. lowerLimitEquation.angle = lowerLimit;
  4685. if(eqs.indexOf(lowerLimitEquation) === -1){
  4686. eqs.push(lowerLimitEquation);
  4687. }
  4688. } else {
  4689. var idx = eqs.indexOf(lowerLimitEquation);
  4690. if(idx !== -1){
  4691. eqs.splice(idx,1);
  4692. }
  4693. }
  4694. /*
  4695. The constraint violation is
  4696. g = xj + rj - xi - ri
  4697. ...where xi and xj are the body positions and ri and rj world-oriented offset vectors. Differentiate:
  4698. gdot = vj + wj x rj - vi - wi x ri
  4699. We split this into x and y directions. (let x and y be unit vectors along the respective axes)
  4700. gdot * x = ( vj + wj x rj - vi - wi x ri ) * x
  4701. = ( vj*x + (wj x rj)*x -vi*x -(wi x ri)*x
  4702. = ( vj*x + (rj x x)*wj -vi*x -(ri x x)*wi
  4703. = [ -x -(ri x x) x (rj x x)] * [vi wi vj wj]
  4704. = G*W
  4705. ...and similar for y. We have then identified the jacobian entries for x and y directions:
  4706. Gx = [ x (rj x x) -x -(ri x x)]
  4707. Gy = [ y (rj x y) -y -(ri x y)]
  4708. */
  4709. vec2.rotate(worldPivotA, pivotA, bodyA.angle);
  4710. vec2.rotate(worldPivotB, pivotB, bodyB.angle);
  4711. // todo: these are a bit sparse. We could save some computations on making custom eq.computeGW functions, etc
  4712. x.G[0] = -1;
  4713. x.G[1] = 0;
  4714. x.G[2] = -vec2.crossLength(worldPivotA,xAxis);
  4715. x.G[3] = 1;
  4716. x.G[4] = 0;
  4717. x.G[5] = vec2.crossLength(worldPivotB,xAxis);
  4718. y.G[0] = 0;
  4719. y.G[1] = -1;
  4720. y.G[2] = -vec2.crossLength(worldPivotA,yAxis);
  4721. y.G[3] = 0;
  4722. y.G[4] = 1;
  4723. y.G[5] = vec2.crossLength(worldPivotB,yAxis);
  4724. };
  4725. /**
  4726. * Enable the rotational motor
  4727. * @method enableMotor
  4728. */
  4729. RevoluteConstraint.prototype.enableMotor = function(){
  4730. if(this.motorEnabled){
  4731. return;
  4732. }
  4733. this.equations.push(this.motorEquation);
  4734. this.motorEnabled = true;
  4735. };
  4736. /**
  4737. * Disable the rotational motor
  4738. * @method disableMotor
  4739. */
  4740. RevoluteConstraint.prototype.disableMotor = function(){
  4741. if(!this.motorEnabled){
  4742. return;
  4743. }
  4744. var i = this.equations.indexOf(this.motorEquation);
  4745. this.equations.splice(i,1);
  4746. this.motorEnabled = false;
  4747. };
  4748. /**
  4749. * Check if the motor is enabled.
  4750. * @method motorIsEnabled
  4751. * @deprecated use property motorEnabled instead.
  4752. * @return {Boolean}
  4753. */
  4754. RevoluteConstraint.prototype.motorIsEnabled = function(){
  4755. return !!this.motorEnabled;
  4756. };
  4757. /**
  4758. * Set the speed of the rotational constraint motor
  4759. * @method setMotorSpeed
  4760. * @param {Number} speed
  4761. */
  4762. RevoluteConstraint.prototype.setMotorSpeed = function(speed){
  4763. if(!this.motorEnabled){
  4764. return;
  4765. }
  4766. var i = this.equations.indexOf(this.motorEquation);
  4767. this.equations[i].relativeVelocity = speed;
  4768. };
  4769. /**
  4770. * Get the speed of the rotational constraint motor
  4771. * @method getMotorSpeed
  4772. * @return {Number} The current speed, or false if the motor is not enabled.
  4773. */
  4774. RevoluteConstraint.prototype.getMotorSpeed = function(){
  4775. if(!this.motorEnabled){
  4776. return false;
  4777. }
  4778. return this.motorEquation.relativeVelocity;
  4779. };
  4780. },{"../equations/Equation":22,"../equations/RotationalLockEquation":24,"../equations/RotationalVelocityEquation":25,"../math/vec2":30,"./Constraint":14}],20:[function(_dereq_,module,exports){
  4781. var Equation = _dereq_("./Equation"),
  4782. vec2 = _dereq_('../math/vec2');
  4783. module.exports = AngleLockEquation;
  4784. /**
  4785. * Locks the relative angle between two bodies. The constraint tries to keep the dot product between two vectors, local in each body, to zero. The local angle in body i is a parameter.
  4786. *
  4787. * @class AngleLockEquation
  4788. * @constructor
  4789. * @extends Equation
  4790. * @param {Body} bodyA
  4791. * @param {Body} bodyB
  4792. * @param {Object} [options]
  4793. * @param {Number} [options.angle] Angle to add to the local vector in body A.
  4794. * @param {Number} [options.ratio] Gear ratio
  4795. */
  4796. function AngleLockEquation(bodyA, bodyB, options){
  4797. options = options || {};
  4798. Equation.call(this,bodyA,bodyB,-Number.MAX_VALUE,Number.MAX_VALUE);
  4799. this.angle = options.angle || 0;
  4800. /**
  4801. * The gear ratio.
  4802. * @property {Number} ratio
  4803. * @private
  4804. * @see setRatio
  4805. */
  4806. this.ratio = typeof(options.ratio)==="number" ? options.ratio : 1;
  4807. this.setRatio(this.ratio);
  4808. }
  4809. AngleLockEquation.prototype = new Equation();
  4810. AngleLockEquation.prototype.constructor = AngleLockEquation;
  4811. AngleLockEquation.prototype.computeGq = function(){
  4812. return this.ratio * this.bodyA.angle - this.bodyB.angle + this.angle;
  4813. };
  4814. /**
  4815. * Set the gear ratio for this equation
  4816. * @method setRatio
  4817. * @param {Number} ratio
  4818. */
  4819. AngleLockEquation.prototype.setRatio = function(ratio){
  4820. var G = this.G;
  4821. G[2] = ratio;
  4822. G[5] = -1;
  4823. this.ratio = ratio;
  4824. };
  4825. /**
  4826. * Set the max force for the equation.
  4827. * @method setMaxTorque
  4828. * @param {Number} torque
  4829. */
  4830. AngleLockEquation.prototype.setMaxTorque = function(torque){
  4831. this.maxForce = torque;
  4832. this.minForce = -torque;
  4833. };
  4834. },{"../math/vec2":30,"./Equation":22}],21:[function(_dereq_,module,exports){
  4835. var Equation = _dereq_("./Equation"),
  4836. vec2 = _dereq_('../math/vec2');
  4837. module.exports = ContactEquation;
  4838. /**
  4839. * Non-penetration constraint equation. Tries to make the contactPointA and contactPointB vectors coincide, while keeping the applied force repulsive.
  4840. *
  4841. * @class ContactEquation
  4842. * @constructor
  4843. * @extends Equation
  4844. * @param {Body} bodyA
  4845. * @param {Body} bodyB
  4846. */
  4847. function ContactEquation(bodyA, bodyB){
  4848. Equation.call(this, bodyA, bodyB, 0, Number.MAX_VALUE);
  4849. /**
  4850. * Vector from body i center of mass to the contact point.
  4851. * @property contactPointA
  4852. * @type {Array}
  4853. */
  4854. this.contactPointA = vec2.create();
  4855. this.penetrationVec = vec2.create();
  4856. /**
  4857. * World-oriented vector from body A center of mass to the contact point.
  4858. * @property contactPointB
  4859. * @type {Array}
  4860. */
  4861. this.contactPointB = vec2.create();
  4862. /**
  4863. * The normal vector, pointing out of body i
  4864. * @property normalA
  4865. * @type {Array}
  4866. */
  4867. this.normalA = vec2.create();
  4868. /**
  4869. * The restitution to use (0=no bounciness, 1=max bounciness).
  4870. * @property restitution
  4871. * @type {Number}
  4872. */
  4873. this.restitution = 0;
  4874. /**
  4875. * This property is set to true if this is the first impact between the bodies (not persistant contact).
  4876. * @property firstImpact
  4877. * @type {Boolean}
  4878. * @readOnly
  4879. */
  4880. this.firstImpact = false;
  4881. /**
  4882. * The shape in body i that triggered this contact.
  4883. * @property shapeA
  4884. * @type {Shape}
  4885. */
  4886. this.shapeA = null;
  4887. /**
  4888. * The shape in body j that triggered this contact.
  4889. * @property shapeB
  4890. * @type {Shape}
  4891. */
  4892. this.shapeB = null;
  4893. }
  4894. ContactEquation.prototype = new Equation();
  4895. ContactEquation.prototype.constructor = ContactEquation;
  4896. ContactEquation.prototype.computeB = function(a,b,h){
  4897. var bi = this.bodyA,
  4898. bj = this.bodyB,
  4899. ri = this.contactPointA,
  4900. rj = this.contactPointB,
  4901. xi = bi.position,
  4902. xj = bj.position;
  4903. var penetrationVec = this.penetrationVec,
  4904. n = this.normalA,
  4905. G = this.G;
  4906. // Caluclate cross products
  4907. var rixn = vec2.crossLength(ri,n),
  4908. rjxn = vec2.crossLength(rj,n);
  4909. // G = [-n -rixn n rjxn]
  4910. G[0] = -n[0];
  4911. G[1] = -n[1];
  4912. G[2] = -rixn;
  4913. G[3] = n[0];
  4914. G[4] = n[1];
  4915. G[5] = rjxn;
  4916. // Calculate q = xj+rj -(xi+ri) i.e. the penetration vector
  4917. vec2.add(penetrationVec,xj,rj);
  4918. vec2.sub(penetrationVec,penetrationVec,xi);
  4919. vec2.sub(penetrationVec,penetrationVec,ri);
  4920. // Compute iteration
  4921. var GW, Gq;
  4922. if(this.firstImpact && this.restitution !== 0){
  4923. Gq = 0;
  4924. GW = (1/b)*(1+this.restitution) * this.computeGW();
  4925. } else {
  4926. Gq = vec2.dot(n,penetrationVec) + this.offset;
  4927. GW = this.computeGW();
  4928. }
  4929. var GiMf = this.computeGiMf();
  4930. var B = - Gq * a - GW * b - h*GiMf;
  4931. return B;
  4932. };
  4933. },{"../math/vec2":30,"./Equation":22}],22:[function(_dereq_,module,exports){
  4934. module.exports = Equation;
  4935. var vec2 = _dereq_('../math/vec2'),
  4936. Utils = _dereq_('../utils/Utils'),
  4937. Body = _dereq_('../objects/Body');
  4938. /**
  4939. * Base class for constraint equations.
  4940. * @class Equation
  4941. * @constructor
  4942. * @param {Body} bodyA First body participating in the equation
  4943. * @param {Body} bodyB Second body participating in the equation
  4944. * @param {number} minForce Minimum force to apply. Default: -Number.MAX_VALUE
  4945. * @param {number} maxForce Maximum force to apply. Default: Number.MAX_VALUE
  4946. */
  4947. function Equation(bodyA, bodyB, minForce, maxForce){
  4948. /**
  4949. * Minimum force to apply when solving.
  4950. * @property minForce
  4951. * @type {Number}
  4952. */
  4953. this.minForce = typeof(minForce)==="undefined" ? -Number.MAX_VALUE : minForce;
  4954. /**
  4955. * Max force to apply when solving.
  4956. * @property maxForce
  4957. * @type {Number}
  4958. */
  4959. this.maxForce = typeof(maxForce)==="undefined" ? Number.MAX_VALUE : maxForce;
  4960. /**
  4961. * First body participating in the constraint
  4962. * @property bodyA
  4963. * @type {Body}
  4964. */
  4965. this.bodyA = bodyA;
  4966. /**
  4967. * Second body participating in the constraint
  4968. * @property bodyB
  4969. * @type {Body}
  4970. */
  4971. this.bodyB = bodyB;
  4972. /**
  4973. * The stiffness of this equation. Typically chosen to a large number (~1e7), but can be chosen somewhat freely to get a stable simulation.
  4974. * @property stiffness
  4975. * @type {Number}
  4976. */
  4977. this.stiffness = Equation.DEFAULT_STIFFNESS;
  4978. /**
  4979. * The number of time steps needed to stabilize the constraint equation. Typically between 3 and 5 time steps.
  4980. * @property relaxation
  4981. * @type {Number}
  4982. */
  4983. this.relaxation = Equation.DEFAULT_RELAXATION;
  4984. /**
  4985. * The Jacobian entry of this equation. 6 numbers, 3 per body (x,y,angle).
  4986. * @property G
  4987. * @type {Array}
  4988. */
  4989. this.G = new Utils.ARRAY_TYPE(6);
  4990. for(var i=0; i<6; i++){
  4991. this.G[i]=0;
  4992. }
  4993. this.offset = 0;
  4994. this.a = 0;
  4995. this.b = 0;
  4996. this.epsilon = 0;
  4997. this.timeStep = 1/60;
  4998. /**
  4999. * Indicates if stiffness or relaxation was changed.
  5000. * @property {Boolean} needsUpdate
  5001. */
  5002. this.needsUpdate = true;
  5003. /**
  5004. * The resulting constraint multiplier from the last solve. This is mostly equivalent to the force produced by the constraint.
  5005. * @property multiplier
  5006. * @type {Number}
  5007. */
  5008. this.multiplier = 0;
  5009. /**
  5010. * Relative velocity.
  5011. * @property {Number} relativeVelocity
  5012. */
  5013. this.relativeVelocity = 0;
  5014. /**
  5015. * Whether this equation is enabled or not. If true, it will be added to the solver.
  5016. * @property {Boolean} enabled
  5017. */
  5018. this.enabled = true;
  5019. }
  5020. Equation.prototype.constructor = Equation;
  5021. /**
  5022. * The default stiffness when creating a new Equation.
  5023. * @static
  5024. * @property {Number} DEFAULT_STIFFNESS
  5025. * @default 1e6
  5026. */
  5027. Equation.DEFAULT_STIFFNESS = 1e6;
  5028. /**
  5029. * The default relaxation when creating a new Equation.
  5030. * @static
  5031. * @property {Number} DEFAULT_RELAXATION
  5032. * @default 4
  5033. */
  5034. Equation.DEFAULT_RELAXATION = 4;
  5035. /**
  5036. * Compute SPOOK parameters .a, .b and .epsilon according to the current parameters. See equations 9, 10 and 11 in the <a href="http://www8.cs.umu.se/kurser/5DV058/VT09/lectures/spooknotes.pdf">SPOOK notes</a>.
  5037. * @method update
  5038. */
  5039. Equation.prototype.update = function(){
  5040. var k = this.stiffness,
  5041. d = this.relaxation,
  5042. h = this.timeStep;
  5043. this.a = 4.0 / (h * (1 + 4 * d));
  5044. this.b = (4.0 * d) / (1 + 4 * d);
  5045. this.epsilon = 4.0 / (h * h * k * (1 + 4 * d));
  5046. this.needsUpdate = false;
  5047. };
  5048. /**
  5049. * Multiply a jacobian entry with corresponding positions or velocities
  5050. * @method gmult
  5051. * @return {Number}
  5052. */
  5053. Equation.prototype.gmult = function(G,vi,wi,vj,wj){
  5054. return G[0] * vi[0] +
  5055. G[1] * vi[1] +
  5056. G[2] * wi +
  5057. G[3] * vj[0] +
  5058. G[4] * vj[1] +
  5059. G[5] * wj;
  5060. };
  5061. /**
  5062. * Computes the RHS of the SPOOK equation
  5063. * @method computeB
  5064. * @return {Number}
  5065. */
  5066. Equation.prototype.computeB = function(a,b,h){
  5067. var GW = this.computeGW();
  5068. var Gq = this.computeGq();
  5069. var GiMf = this.computeGiMf();
  5070. return - Gq * a - GW * b - GiMf*h;
  5071. };
  5072. /**
  5073. * Computes G\*q, where q are the generalized body coordinates
  5074. * @method computeGq
  5075. * @return {Number}
  5076. */
  5077. var qi = vec2.create(),
  5078. qj = vec2.create();
  5079. Equation.prototype.computeGq = function(){
  5080. var G = this.G,
  5081. bi = this.bodyA,
  5082. bj = this.bodyB,
  5083. xi = bi.position,
  5084. xj = bj.position,
  5085. ai = bi.angle,
  5086. aj = bj.angle;
  5087. return this.gmult(G, qi, ai, qj, aj) + this.offset;
  5088. };
  5089. /**
  5090. * Computes G\*W, where W are the body velocities
  5091. * @method computeGW
  5092. * @return {Number}
  5093. */
  5094. Equation.prototype.computeGW = function(){
  5095. var G = this.G,
  5096. bi = this.bodyA,
  5097. bj = this.bodyB,
  5098. vi = bi.velocity,
  5099. vj = bj.velocity,
  5100. wi = bi.angularVelocity,
  5101. wj = bj.angularVelocity;
  5102. return this.gmult(G,vi,wi,vj,wj) + this.relativeVelocity;
  5103. };
  5104. /**
  5105. * Computes G\*Wlambda, where W are the body velocities
  5106. * @method computeGWlambda
  5107. * @return {Number}
  5108. */
  5109. Equation.prototype.computeGWlambda = function(){
  5110. var G = this.G,
  5111. bi = this.bodyA,
  5112. bj = this.bodyB,
  5113. vi = bi.vlambda,
  5114. vj = bj.vlambda,
  5115. wi = bi.wlambda,
  5116. wj = bj.wlambda;
  5117. return this.gmult(G,vi,wi,vj,wj);
  5118. };
  5119. /**
  5120. * Computes G\*inv(M)\*f, where M is the mass matrix with diagonal blocks for each body, and f are the forces on the bodies.
  5121. * @method computeGiMf
  5122. * @return {Number}
  5123. */
  5124. var iMfi = vec2.create(),
  5125. iMfj = vec2.create();
  5126. Equation.prototype.computeGiMf = function(){
  5127. var bi = this.bodyA,
  5128. bj = this.bodyB,
  5129. fi = bi.force,
  5130. ti = bi.angularForce,
  5131. fj = bj.force,
  5132. tj = bj.angularForce,
  5133. invMassi = bi.invMassSolve,
  5134. invMassj = bj.invMassSolve,
  5135. invIi = bi.invInertiaSolve,
  5136. invIj = bj.invInertiaSolve,
  5137. G = this.G;
  5138. vec2.scale(iMfi, fi, invMassi);
  5139. vec2.multiply(iMfi, bi.massMultiplier, iMfi);
  5140. vec2.scale(iMfj, fj,invMassj);
  5141. vec2.multiply(iMfj, bj.massMultiplier, iMfj);
  5142. return this.gmult(G,iMfi,ti*invIi,iMfj,tj*invIj);
  5143. };
  5144. /**
  5145. * Computes G\*inv(M)\*G'
  5146. * @method computeGiMGt
  5147. * @return {Number}
  5148. */
  5149. Equation.prototype.computeGiMGt = function(){
  5150. var bi = this.bodyA,
  5151. bj = this.bodyB,
  5152. invMassi = bi.invMassSolve,
  5153. invMassj = bj.invMassSolve,
  5154. invIi = bi.invInertiaSolve,
  5155. invIj = bj.invInertiaSolve,
  5156. G = this.G;
  5157. return G[0] * G[0] * invMassi * bi.massMultiplier[0] +
  5158. G[1] * G[1] * invMassi * bi.massMultiplier[1] +
  5159. G[2] * G[2] * invIi +
  5160. G[3] * G[3] * invMassj * bj.massMultiplier[0] +
  5161. G[4] * G[4] * invMassj * bj.massMultiplier[1] +
  5162. G[5] * G[5] * invIj;
  5163. };
  5164. var addToWlambda_temp = vec2.create(),
  5165. addToWlambda_Gi = vec2.create(),
  5166. addToWlambda_Gj = vec2.create(),
  5167. addToWlambda_ri = vec2.create(),
  5168. addToWlambda_rj = vec2.create(),
  5169. addToWlambda_Mdiag = vec2.create();
  5170. /**
  5171. * Add constraint velocity to the bodies.
  5172. * @method addToWlambda
  5173. * @param {Number} deltalambda
  5174. */
  5175. Equation.prototype.addToWlambda = function(deltalambda){
  5176. var bi = this.bodyA,
  5177. bj = this.bodyB,
  5178. temp = addToWlambda_temp,
  5179. Gi = addToWlambda_Gi,
  5180. Gj = addToWlambda_Gj,
  5181. ri = addToWlambda_ri,
  5182. rj = addToWlambda_rj,
  5183. invMassi = bi.invMassSolve,
  5184. invMassj = bj.invMassSolve,
  5185. invIi = bi.invInertiaSolve,
  5186. invIj = bj.invInertiaSolve,
  5187. Mdiag = addToWlambda_Mdiag,
  5188. G = this.G;
  5189. Gi[0] = G[0];
  5190. Gi[1] = G[1];
  5191. Gj[0] = G[3];
  5192. Gj[1] = G[4];
  5193. // Add to linear velocity
  5194. // v_lambda += inv(M) * delta_lamba * G
  5195. vec2.scale(temp, Gi, invMassi*deltalambda);
  5196. vec2.multiply(temp, temp, bi.massMultiplier);
  5197. vec2.add( bi.vlambda, bi.vlambda, temp);
  5198. // This impulse is in the offset frame
  5199. // Also add contribution to angular
  5200. //bi.wlambda -= vec2.crossLength(temp,ri);
  5201. bi.wlambda += invIi * G[2] * deltalambda;
  5202. vec2.scale(temp, Gj, invMassj*deltalambda);
  5203. vec2.multiply(temp, temp, bj.massMultiplier);
  5204. vec2.add( bj.vlambda, bj.vlambda, temp);
  5205. //bj.wlambda -= vec2.crossLength(temp,rj);
  5206. bj.wlambda += invIj * G[5] * deltalambda;
  5207. };
  5208. /**
  5209. * Compute the denominator part of the SPOOK equation: C = G\*inv(M)\*G' + eps
  5210. * @method computeInvC
  5211. * @param {Number} eps
  5212. * @return {Number}
  5213. */
  5214. Equation.prototype.computeInvC = function(eps){
  5215. return 1.0 / (this.computeGiMGt() + eps);
  5216. };
  5217. },{"../math/vec2":30,"../objects/Body":31,"../utils/Utils":57}],23:[function(_dereq_,module,exports){
  5218. var vec2 = _dereq_('../math/vec2')
  5219. , Equation = _dereq_('./Equation')
  5220. , Utils = _dereq_('../utils/Utils');
  5221. module.exports = FrictionEquation;
  5222. /**
  5223. * Constrains the slipping in a contact along a tangent
  5224. *
  5225. * @class FrictionEquation
  5226. * @constructor
  5227. * @param {Body} bodyA
  5228. * @param {Body} bodyB
  5229. * @param {Number} slipForce
  5230. * @extends Equation
  5231. */
  5232. function FrictionEquation(bodyA, bodyB, slipForce){
  5233. Equation.call(this, bodyA, bodyB, -slipForce, slipForce);
  5234. /**
  5235. * Relative vector from center of body A to the contact point, world oriented.
  5236. * @property contactPointA
  5237. * @type {Array}
  5238. */
  5239. this.contactPointA = vec2.create();
  5240. /**
  5241. * Relative vector from center of body B to the contact point, world oriented.
  5242. * @property contactPointB
  5243. * @type {Array}
  5244. */
  5245. this.contactPointB = vec2.create();
  5246. /**
  5247. * Tangent vector that the friction force will act along. World oriented.
  5248. * @property t
  5249. * @type {Array}
  5250. */
  5251. this.t = vec2.create();
  5252. /**
  5253. * ContactEquations connected to this friction equation. The contact equations can be used to rescale the max force for the friction. If more than one contact equation is given, then the max force can be set to the average.
  5254. * @property contactEquations
  5255. * @type {ContactEquation}
  5256. */
  5257. this.contactEquations = [];
  5258. /**
  5259. * The shape in body i that triggered this friction.
  5260. * @property shapeA
  5261. * @type {Shape}
  5262. * @todo Needed? The shape can be looked up via contactEquation.shapeA...
  5263. */
  5264. this.shapeA = null;
  5265. /**
  5266. * The shape in body j that triggered this friction.
  5267. * @property shapeB
  5268. * @type {Shape}
  5269. * @todo Needed? The shape can be looked up via contactEquation.shapeB...
  5270. */
  5271. this.shapeB = null;
  5272. /**
  5273. * The friction coefficient to use.
  5274. * @property frictionCoefficient
  5275. * @type {Number}
  5276. */
  5277. this.frictionCoefficient = 0.3;
  5278. }
  5279. FrictionEquation.prototype = new Equation();
  5280. FrictionEquation.prototype.constructor = FrictionEquation;
  5281. /**
  5282. * Set the slipping condition for the constraint. The friction force cannot be
  5283. * larger than this value.
  5284. * @method setSlipForce
  5285. * @param {Number} slipForce
  5286. */
  5287. FrictionEquation.prototype.setSlipForce = function(slipForce){
  5288. this.maxForce = slipForce;
  5289. this.minForce = -slipForce;
  5290. };
  5291. /**
  5292. * Get the max force for the constraint.
  5293. * @method getSlipForce
  5294. * @return {Number}
  5295. */
  5296. FrictionEquation.prototype.getSlipForce = function(){
  5297. return this.maxForce;
  5298. };
  5299. FrictionEquation.prototype.computeB = function(a,b,h){
  5300. var bi = this.bodyA,
  5301. bj = this.bodyB,
  5302. ri = this.contactPointA,
  5303. rj = this.contactPointB,
  5304. t = this.t,
  5305. G = this.G;
  5306. // G = [-t -rixt t rjxt]
  5307. // And remember, this is a pure velocity constraint, g is always zero!
  5308. G[0] = -t[0];
  5309. G[1] = -t[1];
  5310. G[2] = -vec2.crossLength(ri,t);
  5311. G[3] = t[0];
  5312. G[4] = t[1];
  5313. G[5] = vec2.crossLength(rj,t);
  5314. var GW = this.computeGW(),
  5315. GiMf = this.computeGiMf();
  5316. var B = /* - g * a */ - GW * b - h*GiMf;
  5317. return B;
  5318. };
  5319. },{"../math/vec2":30,"../utils/Utils":57,"./Equation":22}],24:[function(_dereq_,module,exports){
  5320. var Equation = _dereq_("./Equation"),
  5321. vec2 = _dereq_('../math/vec2');
  5322. module.exports = RotationalLockEquation;
  5323. /**
  5324. * Locks the relative angle between two bodies. The constraint tries to keep the dot product between two vectors, local in each body, to zero. The local angle in body i is a parameter.
  5325. *
  5326. * @class RotationalLockEquation
  5327. * @constructor
  5328. * @extends Equation
  5329. * @param {Body} bodyA
  5330. * @param {Body} bodyB
  5331. * @param {Object} [options]
  5332. * @param {Number} [options.angle] Angle to add to the local vector in bodyA.
  5333. */
  5334. function RotationalLockEquation(bodyA, bodyB, options){
  5335. options = options || {};
  5336. Equation.call(this, bodyA, bodyB, -Number.MAX_VALUE, Number.MAX_VALUE);
  5337. /**
  5338. * @property {number} angle
  5339. */
  5340. this.angle = options.angle || 0;
  5341. var G = this.G;
  5342. G[2] = 1;
  5343. G[5] = -1;
  5344. }
  5345. RotationalLockEquation.prototype = new Equation();
  5346. RotationalLockEquation.prototype.constructor = RotationalLockEquation;
  5347. var worldVectorA = vec2.create(),
  5348. worldVectorB = vec2.create(),
  5349. xAxis = vec2.fromValues(1,0),
  5350. yAxis = vec2.fromValues(0,1);
  5351. RotationalLockEquation.prototype.computeGq = function(){
  5352. vec2.rotate(worldVectorA,xAxis,this.bodyA.angle+this.angle);
  5353. vec2.rotate(worldVectorB,yAxis,this.bodyB.angle);
  5354. return vec2.dot(worldVectorA,worldVectorB);
  5355. };
  5356. },{"../math/vec2":30,"./Equation":22}],25:[function(_dereq_,module,exports){
  5357. var Equation = _dereq_("./Equation"),
  5358. vec2 = _dereq_('../math/vec2');
  5359. module.exports = RotationalVelocityEquation;
  5360. /**
  5361. * Syncs rotational velocity of two bodies, or sets a relative velocity (motor).
  5362. *
  5363. * @class RotationalVelocityEquation
  5364. * @constructor
  5365. * @extends Equation
  5366. * @param {Body} bodyA
  5367. * @param {Body} bodyB
  5368. */
  5369. function RotationalVelocityEquation(bodyA, bodyB){
  5370. Equation.call(this, bodyA, bodyB, -Number.MAX_VALUE, Number.MAX_VALUE);
  5371. this.relativeVelocity = 1;
  5372. this.ratio = 1;
  5373. }
  5374. RotationalVelocityEquation.prototype = new Equation();
  5375. RotationalVelocityEquation.prototype.constructor = RotationalVelocityEquation;
  5376. RotationalVelocityEquation.prototype.computeB = function(a,b,h){
  5377. var G = this.G;
  5378. G[2] = -1;
  5379. G[5] = this.ratio;
  5380. var GiMf = this.computeGiMf();
  5381. var GW = this.computeGW();
  5382. var B = - GW * b - h*GiMf;
  5383. return B;
  5384. };
  5385. },{"../math/vec2":30,"./Equation":22}],26:[function(_dereq_,module,exports){
  5386. /**
  5387. * Base class for objects that dispatches events.
  5388. * @class EventEmitter
  5389. * @constructor
  5390. */
  5391. var EventEmitter = function () {};
  5392. module.exports = EventEmitter;
  5393. EventEmitter.prototype = {
  5394. constructor: EventEmitter,
  5395. /**
  5396. * Add an event listener
  5397. * @method on
  5398. * @param {String} type
  5399. * @param {Function} listener
  5400. * @return {EventEmitter} The self object, for chainability.
  5401. */
  5402. on: function ( type, listener, context ) {
  5403. listener.context = context || this;
  5404. if ( this._listeners === undefined ){
  5405. this._listeners = {};
  5406. }
  5407. var listeners = this._listeners;
  5408. if ( listeners[ type ] === undefined ) {
  5409. listeners[ type ] = [];
  5410. }
  5411. if ( listeners[ type ].indexOf( listener ) === - 1 ) {
  5412. listeners[ type ].push( listener );
  5413. }
  5414. return this;
  5415. },
  5416. /**
  5417. * Check if an event listener is added
  5418. * @method has
  5419. * @param {String} type
  5420. * @param {Function} listener
  5421. * @return {Boolean}
  5422. */
  5423. has: function ( type, listener ) {
  5424. if ( this._listeners === undefined ){
  5425. return false;
  5426. }
  5427. var listeners = this._listeners;
  5428. if(listener){
  5429. if ( listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1 ) {
  5430. return true;
  5431. }
  5432. } else {
  5433. if ( listeners[ type ] !== undefined ) {
  5434. return true;
  5435. }
  5436. }
  5437. return false;
  5438. },
  5439. /**
  5440. * Remove an event listener
  5441. * @method off
  5442. * @param {String} type
  5443. * @param {Function} listener
  5444. * @return {EventEmitter} The self object, for chainability.
  5445. */
  5446. off: function ( type, listener ) {
  5447. if ( this._listeners === undefined ){
  5448. return this;
  5449. }
  5450. var listeners = this._listeners;
  5451. var index = listeners[ type ].indexOf( listener );
  5452. if ( index !== - 1 ) {
  5453. listeners[ type ].splice( index, 1 );
  5454. }
  5455. return this;
  5456. },
  5457. /**
  5458. * Emit an event.
  5459. * @method emit
  5460. * @param {Object} event
  5461. * @param {String} event.type
  5462. * @return {EventEmitter} The self object, for chainability.
  5463. */
  5464. emit: function ( event ) {
  5465. if ( this._listeners === undefined ){
  5466. return this;
  5467. }
  5468. var listeners = this._listeners;
  5469. var listenerArray = listeners[ event.type ];
  5470. if ( listenerArray !== undefined ) {
  5471. event.target = this;
  5472. for ( var i = 0, l = listenerArray.length; i < l; i ++ ) {
  5473. var listener = listenerArray[ i ];
  5474. listener.call( listener.context, event );
  5475. }
  5476. }
  5477. return this;
  5478. }
  5479. };
  5480. },{}],27:[function(_dereq_,module,exports){
  5481. var Material = _dereq_('./Material');
  5482. var Equation = _dereq_('../equations/Equation');
  5483. module.exports = ContactMaterial;
  5484. /**
  5485. * Defines what happens when two materials meet, such as what friction coefficient to use. You can also set other things such as restitution, surface velocity and constraint parameters.
  5486. * @class ContactMaterial
  5487. * @constructor
  5488. * @param {Material} materialA
  5489. * @param {Material} materialB
  5490. * @param {Object} [options]
  5491. * @param {Number} [options.friction=0.3] Friction coefficient.
  5492. * @param {Number} [options.restitution=0] Restitution coefficient aka "bounciness".
  5493. * @param {Number} [options.stiffness] ContactEquation stiffness.
  5494. * @param {Number} [options.relaxation] ContactEquation relaxation.
  5495. * @param {Number} [options.frictionStiffness] FrictionEquation stiffness.
  5496. * @param {Number} [options.frictionRelaxation] FrictionEquation relaxation.
  5497. * @param {Number} [options.surfaceVelocity=0] Surface velocity.
  5498. * @author schteppe
  5499. */
  5500. function ContactMaterial(materialA, materialB, options){
  5501. options = options || {};
  5502. if(!(materialA instanceof Material) || !(materialB instanceof Material)){
  5503. throw new Error("First two arguments must be Material instances.");
  5504. }
  5505. /**
  5506. * The contact material identifier
  5507. * @property id
  5508. * @type {Number}
  5509. */
  5510. this.id = ContactMaterial.idCounter++;
  5511. /**
  5512. * First material participating in the contact material
  5513. * @property materialA
  5514. * @type {Material}
  5515. */
  5516. this.materialA = materialA;
  5517. /**
  5518. * Second material participating in the contact material
  5519. * @property materialB
  5520. * @type {Material}
  5521. */
  5522. this.materialB = materialB;
  5523. /**
  5524. * Friction to use in the contact of these two materials
  5525. * @property friction
  5526. * @type {Number}
  5527. */
  5528. this.friction = typeof(options.friction) !== "undefined" ? Number(options.friction) : 0.3;
  5529. /**
  5530. * Restitution to use in the contact of these two materials
  5531. * @property restitution
  5532. * @type {Number}
  5533. */
  5534. this.restitution = typeof(options.restitution) !== "undefined" ? Number(options.restitution) : 0.0;
  5535. /**
  5536. * Stiffness of the resulting ContactEquation that this ContactMaterial generate
  5537. * @property stiffness
  5538. * @type {Number}
  5539. */
  5540. this.stiffness = typeof(options.stiffness) !== "undefined" ? Number(options.stiffness) : Equation.DEFAULT_STIFFNESS;
  5541. /**
  5542. * Relaxation of the resulting ContactEquation that this ContactMaterial generate
  5543. * @property relaxation
  5544. * @type {Number}
  5545. */
  5546. this.relaxation = typeof(options.relaxation) !== "undefined" ? Number(options.relaxation) : Equation.DEFAULT_RELAXATION;
  5547. /**
  5548. * Stiffness of the resulting FrictionEquation that this ContactMaterial generate
  5549. * @property frictionStiffness
  5550. * @type {Number}
  5551. */
  5552. this.frictionStiffness = typeof(options.frictionStiffness) !== "undefined" ? Number(options.frictionStiffness) : Equation.DEFAULT_STIFFNESS;
  5553. /**
  5554. * Relaxation of the resulting FrictionEquation that this ContactMaterial generate
  5555. * @property frictionRelaxation
  5556. * @type {Number}
  5557. */
  5558. this.frictionRelaxation = typeof(options.frictionRelaxation) !== "undefined" ? Number(options.frictionRelaxation) : Equation.DEFAULT_RELAXATION;
  5559. /**
  5560. * Will add surface velocity to this material. If bodyA rests on top if bodyB, and the surface velocity is positive, bodyA will slide to the right.
  5561. * @property {Number} surfaceVelocity
  5562. */
  5563. this.surfaceVelocity = typeof(options.surfaceVelocity) !== "undefined" ? Number(options.surfaceVelocity) : 0;
  5564. /**
  5565. * Offset to be set on ContactEquations. A positive value will make the bodies penetrate more into each other. Can be useful in scenes where contacts need to be more persistent, for example when stacking. Aka "cure for nervous contacts".
  5566. * @property contactSkinSize
  5567. * @type {Number}
  5568. */
  5569. this.contactSkinSize = 0.005;
  5570. }
  5571. ContactMaterial.idCounter = 0;
  5572. },{"../equations/Equation":22,"./Material":28}],28:[function(_dereq_,module,exports){
  5573. module.exports = Material;
  5574. /**
  5575. * Defines a physics material.
  5576. * @class Material
  5577. * @constructor
  5578. * @param {number} id Material identifier
  5579. * @author schteppe
  5580. */
  5581. function Material(id){
  5582. /**
  5583. * The material identifier
  5584. * @property id
  5585. * @type {Number}
  5586. */
  5587. this.id = id || Material.idCounter++;
  5588. }
  5589. Material.idCounter = 0;
  5590. },{}],29:[function(_dereq_,module,exports){
  5591. /*
  5592. PolyK library
  5593. url: http://polyk.ivank.net
  5594. Released under MIT licence.
  5595. Copyright (c) 2012 Ivan Kuckir
  5596. Permission is hereby granted, free of charge, to any person
  5597. obtaining a copy of this software and associated documentation
  5598. files (the "Software"), to deal in the Software without
  5599. restriction, including without limitation the rights to use,
  5600. copy, modify, merge, publish, distribute, sublicense, and/or sell
  5601. copies of the Software, and to permit persons to whom the
  5602. Software is furnished to do so, subject to the following
  5603. conditions:
  5604. The above copyright notice and this permission notice shall be
  5605. included in all copies or substantial portions of the Software.
  5606. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  5607. EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
  5608. OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  5609. NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
  5610. HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
  5611. WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  5612. FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
  5613. OTHER DEALINGS IN THE SOFTWARE.
  5614. */
  5615. var PolyK = {};
  5616. /*
  5617. Is Polygon self-intersecting?
  5618. O(n^2)
  5619. */
  5620. /*
  5621. PolyK.IsSimple = function(p)
  5622. {
  5623. var n = p.length>>1;
  5624. if(n<4) return true;
  5625. var a1 = new PolyK._P(), a2 = new PolyK._P();
  5626. var b1 = new PolyK._P(), b2 = new PolyK._P();
  5627. var c = new PolyK._P();
  5628. for(var i=0; i<n; i++)
  5629. {
  5630. a1.x = p[2*i ];
  5631. a1.y = p[2*i+1];
  5632. if(i==n-1) { a2.x = p[0 ]; a2.y = p[1 ]; }
  5633. else { a2.x = p[2*i+2]; a2.y = p[2*i+3]; }
  5634. for(var j=0; j<n; j++)
  5635. {
  5636. if(Math.abs(i-j) < 2) continue;
  5637. if(j==n-1 && i==0) continue;
  5638. if(i==n-1 && j==0) continue;
  5639. b1.x = p[2*j ];
  5640. b1.y = p[2*j+1];
  5641. if(j==n-1) { b2.x = p[0 ]; b2.y = p[1 ]; }
  5642. else { b2.x = p[2*j+2]; b2.y = p[2*j+3]; }
  5643. if(PolyK._GetLineIntersection(a1,a2,b1,b2,c) != null) return false;
  5644. }
  5645. }
  5646. return true;
  5647. }
  5648. PolyK.IsConvex = function(p)
  5649. {
  5650. if(p.length<6) return true;
  5651. var l = p.length - 4;
  5652. for(var i=0; i<l; i+=2)
  5653. if(!PolyK._convex(p[i], p[i+1], p[i+2], p[i+3], p[i+4], p[i+5])) return false;
  5654. if(!PolyK._convex(p[l ], p[l+1], p[l+2], p[l+3], p[0], p[1])) return false;
  5655. if(!PolyK._convex(p[l+2], p[l+3], p[0 ], p[1 ], p[2], p[3])) return false;
  5656. return true;
  5657. }
  5658. */
  5659. PolyK.GetArea = function(p)
  5660. {
  5661. if(p.length <6) return 0;
  5662. var l = p.length - 2;
  5663. var sum = 0;
  5664. for(var i=0; i<l; i+=2)
  5665. sum += (p[i+2]-p[i]) * (p[i+1]+p[i+3]);
  5666. sum += (p[0]-p[l]) * (p[l+1]+p[1]);
  5667. return - sum * 0.5;
  5668. }
  5669. /*
  5670. PolyK.GetAABB = function(p)
  5671. {
  5672. var minx = Infinity;
  5673. var miny = Infinity;
  5674. var maxx = -minx;
  5675. var maxy = -miny;
  5676. for(var i=0; i<p.length; i+=2)
  5677. {
  5678. minx = Math.min(minx, p[i ]);
  5679. maxx = Math.max(maxx, p[i ]);
  5680. miny = Math.min(miny, p[i+1]);
  5681. maxy = Math.max(maxy, p[i+1]);
  5682. }
  5683. return {x:minx, y:miny, width:maxx-minx, height:maxy-miny};
  5684. }
  5685. */
  5686. PolyK.Triangulate = function(p)
  5687. {
  5688. var n = p.length>>1;
  5689. if(n<3) return [];
  5690. var tgs = [];
  5691. var avl = [];
  5692. for(var i=0; i<n; i++) avl.push(i);
  5693. var i = 0;
  5694. var al = n;
  5695. while(al > 3)
  5696. {
  5697. var i0 = avl[(i+0)%al];
  5698. var i1 = avl[(i+1)%al];
  5699. var i2 = avl[(i+2)%al];
  5700. var ax = p[2*i0], ay = p[2*i0+1];
  5701. var bx = p[2*i1], by = p[2*i1+1];
  5702. var cx = p[2*i2], cy = p[2*i2+1];
  5703. var earFound = false;
  5704. if(PolyK._convex(ax, ay, bx, by, cx, cy))
  5705. {
  5706. earFound = true;
  5707. for(var j=0; j<al; j++)
  5708. {
  5709. var vi = avl[j];
  5710. if(vi==i0 || vi==i1 || vi==i2) continue;
  5711. if(PolyK._PointInTriangle(p[2*vi], p[2*vi+1], ax, ay, bx, by, cx, cy)) {earFound = false; break;}
  5712. }
  5713. }
  5714. if(earFound)
  5715. {
  5716. tgs.push(i0, i1, i2);
  5717. avl.splice((i+1)%al, 1);
  5718. al--;
  5719. i= 0;
  5720. }
  5721. else if(i++ > 3*al) break; // no convex angles :(
  5722. }
  5723. tgs.push(avl[0], avl[1], avl[2]);
  5724. return tgs;
  5725. }
  5726. /*
  5727. PolyK.ContainsPoint = function(p, px, py)
  5728. {
  5729. var n = p.length>>1;
  5730. var ax, ay, bx = p[2*n-2]-px, by = p[2*n-1]-py;
  5731. var depth = 0;
  5732. for(var i=0; i<n; i++)
  5733. {
  5734. ax = bx; ay = by;
  5735. bx = p[2*i ] - px;
  5736. by = p[2*i+1] - py;
  5737. if(ay< 0 && by< 0) continue; // both "up" or both "donw"
  5738. if(ay>=0 && by>=0) continue; // both "up" or both "donw"
  5739. if(ax< 0 && bx< 0) continue;
  5740. var lx = ax + (bx-ax)*(-ay)/(by-ay);
  5741. if(lx>0) depth++;
  5742. }
  5743. return (depth & 1) == 1;
  5744. }
  5745. PolyK.Slice = function(p, ax, ay, bx, by)
  5746. {
  5747. if(PolyK.ContainsPoint(p, ax, ay) || PolyK.ContainsPoint(p, bx, by)) return [p.slice(0)];
  5748. var a = new PolyK._P(ax, ay);
  5749. var b = new PolyK._P(bx, by);
  5750. var iscs = []; // intersections
  5751. var ps = []; // points
  5752. for(var i=0; i<p.length; i+=2) ps.push(new PolyK._P(p[i], p[i+1]));
  5753. for(var i=0; i<ps.length; i++)
  5754. {
  5755. var isc = new PolyK._P(0,0);
  5756. isc = PolyK._GetLineIntersection(a, b, ps[i], ps[(i+1)%ps.length], isc);
  5757. if(isc)
  5758. {
  5759. isc.flag = true;
  5760. iscs.push(isc);
  5761. ps.splice(i+1,0,isc);
  5762. i++;
  5763. }
  5764. }
  5765. if(iscs.length == 0) return [p.slice(0)];
  5766. var comp = function(u,v) {return PolyK._P.dist(a,u) - PolyK._P.dist(a,v); }
  5767. iscs.sort(comp);
  5768. var pgs = [];
  5769. var dir = 0;
  5770. while(iscs.length > 0)
  5771. {
  5772. var n = ps.length;
  5773. var i0 = iscs[0];
  5774. var i1 = iscs[1];
  5775. var ind0 = ps.indexOf(i0);
  5776. var ind1 = ps.indexOf(i1);
  5777. var solved = false;
  5778. if(PolyK._firstWithFlag(ps, ind0) == ind1) solved = true;
  5779. else
  5780. {
  5781. i0 = iscs[1];
  5782. i1 = iscs[0];
  5783. ind0 = ps.indexOf(i0);
  5784. ind1 = ps.indexOf(i1);
  5785. if(PolyK._firstWithFlag(ps, ind0) == ind1) solved = true;
  5786. }
  5787. if(solved)
  5788. {
  5789. dir--;
  5790. var pgn = PolyK._getPoints(ps, ind0, ind1);
  5791. pgs.push(pgn);
  5792. ps = PolyK._getPoints(ps, ind1, ind0);
  5793. i0.flag = i1.flag = false;
  5794. iscs.splice(0,2);
  5795. if(iscs.length == 0) pgs.push(ps);
  5796. }
  5797. else { dir++; iscs.reverse(); }
  5798. if(dir>1) break;
  5799. }
  5800. var result = [];
  5801. for(var i=0; i<pgs.length; i++)
  5802. {
  5803. var pg = pgs[i];
  5804. var npg = [];
  5805. for(var j=0; j<pg.length; j++) npg.push(pg[j].x, pg[j].y);
  5806. result.push(npg);
  5807. }
  5808. return result;
  5809. }
  5810. PolyK.Raycast = function(p, x, y, dx, dy, isc)
  5811. {
  5812. var l = p.length - 2;
  5813. var tp = PolyK._tp;
  5814. var a1 = tp[0], a2 = tp[1],
  5815. b1 = tp[2], b2 = tp[3], c = tp[4];
  5816. a1.x = x; a1.y = y;
  5817. a2.x = x+dx; a2.y = y+dy;
  5818. if(isc==null) isc = {dist:0, edge:0, norm:{x:0, y:0}, refl:{x:0, y:0}};
  5819. isc.dist = Infinity;
  5820. for(var i=0; i<l; i+=2)
  5821. {
  5822. b1.x = p[i ]; b1.y = p[i+1];
  5823. b2.x = p[i+2]; b2.y = p[i+3];
  5824. var nisc = PolyK._RayLineIntersection(a1, a2, b1, b2, c);
  5825. if(nisc) PolyK._updateISC(dx, dy, a1, b1, b2, c, i/2, isc);
  5826. }
  5827. b1.x = b2.x; b1.y = b2.y;
  5828. b2.x = p[0]; b2.y = p[1];
  5829. var nisc = PolyK._RayLineIntersection(a1, a2, b1, b2, c);
  5830. if(nisc) PolyK._updateISC(dx, dy, a1, b1, b2, c, p.length/2, isc);
  5831. return (isc.dist != Infinity) ? isc : null;
  5832. }
  5833. PolyK.ClosestEdge = function(p, x, y, isc)
  5834. {
  5835. var l = p.length - 2;
  5836. var tp = PolyK._tp;
  5837. var a1 = tp[0],
  5838. b1 = tp[2], b2 = tp[3], c = tp[4];
  5839. a1.x = x; a1.y = y;
  5840. if(isc==null) isc = {dist:0, edge:0, point:{x:0, y:0}, norm:{x:0, y:0}};
  5841. isc.dist = Infinity;
  5842. for(var i=0; i<l; i+=2)
  5843. {
  5844. b1.x = p[i ]; b1.y = p[i+1];
  5845. b2.x = p[i+2]; b2.y = p[i+3];
  5846. PolyK._pointLineDist(a1, b1, b2, i>>1, isc);
  5847. }
  5848. b1.x = b2.x; b1.y = b2.y;
  5849. b2.x = p[0]; b2.y = p[1];
  5850. PolyK._pointLineDist(a1, b1, b2, l>>1, isc);
  5851. var idst = 1/isc.dist;
  5852. isc.norm.x = (x-isc.point.x)*idst;
  5853. isc.norm.y = (y-isc.point.y)*idst;
  5854. return isc;
  5855. }
  5856. PolyK._pointLineDist = function(p, a, b, edge, isc)
  5857. {
  5858. var x = p.x, y = p.y, x1 = a.x, y1 = a.y, x2 = b.x, y2 = b.y;
  5859. var A = x - x1;
  5860. var B = y - y1;
  5861. var C = x2 - x1;
  5862. var D = y2 - y1;
  5863. var dot = A * C + B * D;
  5864. var len_sq = C * C + D * D;
  5865. var param = dot / len_sq;
  5866. var xx, yy;
  5867. if (param < 0 || (x1 == x2 && y1 == y2)) {
  5868. xx = x1;
  5869. yy = y1;
  5870. }
  5871. else if (param > 1) {
  5872. xx = x2;
  5873. yy = y2;
  5874. }
  5875. else {
  5876. xx = x1 + param * C;
  5877. yy = y1 + param * D;
  5878. }
  5879. var dx = x - xx;
  5880. var dy = y - yy;
  5881. var dst = Math.sqrt(dx * dx + dy * dy);
  5882. if(dst<isc.dist)
  5883. {
  5884. isc.dist = dst;
  5885. isc.edge = edge;
  5886. isc.point.x = xx;
  5887. isc.point.y = yy;
  5888. }
  5889. }
  5890. PolyK._updateISC = function(dx, dy, a1, b1, b2, c, edge, isc)
  5891. {
  5892. var nrl = PolyK._P.dist(a1, c);
  5893. if(nrl<isc.dist)
  5894. {
  5895. var ibl = 1/PolyK._P.dist(b1, b2);
  5896. var nx = -(b2.y-b1.y)*ibl;
  5897. var ny = (b2.x-b1.x)*ibl;
  5898. var ddot = 2*(dx*nx+dy*ny);
  5899. isc.dist = nrl;
  5900. isc.norm.x = nx;
  5901. isc.norm.y = ny;
  5902. isc.refl.x = -ddot*nx+dx;
  5903. isc.refl.y = -ddot*ny+dy;
  5904. isc.edge = edge;
  5905. }
  5906. }
  5907. PolyK._getPoints = function(ps, ind0, ind1)
  5908. {
  5909. var n = ps.length;
  5910. var nps = [];
  5911. if(ind1<ind0) ind1 += n;
  5912. for(var i=ind0; i<= ind1; i++) nps.push(ps[i%n]);
  5913. return nps;
  5914. }
  5915. PolyK._firstWithFlag = function(ps, ind)
  5916. {
  5917. var n = ps.length;
  5918. while(true)
  5919. {
  5920. ind = (ind+1)%n;
  5921. if(ps[ind].flag) return ind;
  5922. }
  5923. }
  5924. */
  5925. PolyK._PointInTriangle = function(px, py, ax, ay, bx, by, cx, cy)
  5926. {
  5927. var v0x = cx-ax;
  5928. var v0y = cy-ay;
  5929. var v1x = bx-ax;
  5930. var v1y = by-ay;
  5931. var v2x = px-ax;
  5932. var v2y = py-ay;
  5933. var dot00 = v0x*v0x+v0y*v0y;
  5934. var dot01 = v0x*v1x+v0y*v1y;
  5935. var dot02 = v0x*v2x+v0y*v2y;
  5936. var dot11 = v1x*v1x+v1y*v1y;
  5937. var dot12 = v1x*v2x+v1y*v2y;
  5938. var invDenom = 1 / (dot00 * dot11 - dot01 * dot01);
  5939. var u = (dot11 * dot02 - dot01 * dot12) * invDenom;
  5940. var v = (dot00 * dot12 - dot01 * dot02) * invDenom;
  5941. // Check if point is in triangle
  5942. return (u >= 0) && (v >= 0) && (u + v < 1);
  5943. }
  5944. /*
  5945. PolyK._RayLineIntersection = function(a1, a2, b1, b2, c)
  5946. {
  5947. var dax = (a1.x-a2.x), dbx = (b1.x-b2.x);
  5948. var day = (a1.y-a2.y), dby = (b1.y-b2.y);
  5949. var Den = dax*dby - day*dbx;
  5950. if (Den == 0) return null; // parallel
  5951. var A = (a1.x * a2.y - a1.y * a2.x);
  5952. var B = (b1.x * b2.y - b1.y * b2.x);
  5953. var I = c;
  5954. var iDen = 1/Den;
  5955. I.x = ( A*dbx - dax*B ) * iDen;
  5956. I.y = ( A*dby - day*B ) * iDen;
  5957. if(!PolyK._InRect(I, b1, b2)) return null;
  5958. if((day>0 && I.y>a1.y) || (day<0 && I.y<a1.y)) return null;
  5959. if((dax>0 && I.x>a1.x) || (dax<0 && I.x<a1.x)) return null;
  5960. return I;
  5961. }
  5962. PolyK._GetLineIntersection = function(a1, a2, b1, b2, c)
  5963. {
  5964. var dax = (a1.x-a2.x), dbx = (b1.x-b2.x);
  5965. var day = (a1.y-a2.y), dby = (b1.y-b2.y);
  5966. var Den = dax*dby - day*dbx;
  5967. if (Den == 0) return null; // parallel
  5968. var A = (a1.x * a2.y - a1.y * a2.x);
  5969. var B = (b1.x * b2.y - b1.y * b2.x);
  5970. var I = c;
  5971. I.x = ( A*dbx - dax*B ) / Den;
  5972. I.y = ( A*dby - day*B ) / Den;
  5973. if(PolyK._InRect(I, a1, a2) && PolyK._InRect(I, b1, b2)) return I;
  5974. return null;
  5975. }
  5976. PolyK._InRect = function(a, b, c)
  5977. {
  5978. if (b.x == c.x) return (a.y>=Math.min(b.y, c.y) && a.y<=Math.max(b.y, c.y));
  5979. if (b.y == c.y) return (a.x>=Math.min(b.x, c.x) && a.x<=Math.max(b.x, c.x));
  5980. if(a.x >= Math.min(b.x, c.x) && a.x <= Math.max(b.x, c.x)
  5981. && a.y >= Math.min(b.y, c.y) && a.y <= Math.max(b.y, c.y))
  5982. return true;
  5983. return false;
  5984. }
  5985. */
  5986. PolyK._convex = function(ax, ay, bx, by, cx, cy)
  5987. {
  5988. return (ay-by)*(cx-bx) + (bx-ax)*(cy-by) >= 0;
  5989. }
  5990. /*
  5991. PolyK._P = function(x,y)
  5992. {
  5993. this.x = x;
  5994. this.y = y;
  5995. this.flag = false;
  5996. }
  5997. PolyK._P.prototype.toString = function()
  5998. {
  5999. return "Point ["+this.x+", "+this.y+"]";
  6000. }
  6001. PolyK._P.dist = function(a,b)
  6002. {
  6003. var dx = b.x-a.x;
  6004. var dy = b.y-a.y;
  6005. return Math.sqrt(dx*dx + dy*dy);
  6006. }
  6007. PolyK._tp = [];
  6008. for(var i=0; i<10; i++) PolyK._tp.push(new PolyK._P(0,0));
  6009. */
  6010. module.exports = PolyK;
  6011. },{}],30:[function(_dereq_,module,exports){
  6012. /* Copyright (c) 2013, Brandon Jones, Colin MacKenzie IV. All rights reserved.
  6013. Redistribution and use in source and binary forms, with or without modification,
  6014. are permitted provided that the following conditions are met:
  6015. * Redistributions of source code must retain the above copyright notice, this
  6016. list of conditions and the following disclaimer.
  6017. * Redistributions in binary form must reproduce the above copyright notice,
  6018. this list of conditions and the following disclaimer in the documentation
  6019. and/or other materials provided with the distribution.
  6020. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
  6021. ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  6022. WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  6023. DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
  6024. ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  6025. (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  6026. LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
  6027. ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  6028. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  6029. SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
  6030. /**
  6031. * The vec2 object from glMatrix, with some extensions and some removed methods. See http://glmatrix.net.
  6032. * @class vec2
  6033. */
  6034. var vec2 = module.exports = {};
  6035. var Utils = _dereq_('../utils/Utils');
  6036. /**
  6037. * Make a cross product and only return the z component
  6038. * @method crossLength
  6039. * @static
  6040. * @param {Array} a
  6041. * @param {Array} b
  6042. * @return {Number}
  6043. */
  6044. vec2.crossLength = function(a,b){
  6045. return a[0] * b[1] - a[1] * b[0];
  6046. };
  6047. /**
  6048. * Cross product between a vector and the Z component of a vector
  6049. * @method crossVZ
  6050. * @static
  6051. * @param {Array} out
  6052. * @param {Array} vec
  6053. * @param {Number} zcomp
  6054. * @return {Number}
  6055. */
  6056. vec2.crossVZ = function(out, vec, zcomp){
  6057. vec2.rotate(out,vec,-Math.PI/2);// Rotate according to the right hand rule
  6058. vec2.scale(out,out,zcomp); // Scale with z
  6059. return out;
  6060. };
  6061. /**
  6062. * Cross product between a vector and the Z component of a vector
  6063. * @method crossZV
  6064. * @static
  6065. * @param {Array} out
  6066. * @param {Number} zcomp
  6067. * @param {Array} vec
  6068. * @return {Number}
  6069. */
  6070. vec2.crossZV = function(out, zcomp, vec){
  6071. vec2.rotate(out,vec,Math.PI/2); // Rotate according to the right hand rule
  6072. vec2.scale(out,out,zcomp); // Scale with z
  6073. return out;
  6074. };
  6075. /**
  6076. * Rotate a vector by an angle
  6077. * @method rotate
  6078. * @static
  6079. * @param {Array} out
  6080. * @param {Array} a
  6081. * @param {Number} angle
  6082. */
  6083. vec2.rotate = function(out,a,angle){
  6084. if(angle !== 0){
  6085. var c = Math.cos(angle),
  6086. s = Math.sin(angle),
  6087. x = a[0],
  6088. y = a[1];
  6089. out[0] = c*x -s*y;
  6090. out[1] = s*x +c*y;
  6091. } else {
  6092. out[0] = a[0];
  6093. out[1] = a[1];
  6094. }
  6095. };
  6096. /**
  6097. * Rotate a vector 90 degrees clockwise
  6098. * @method rotate90cw
  6099. * @static
  6100. * @param {Array} out
  6101. * @param {Array} a
  6102. * @param {Number} angle
  6103. */
  6104. vec2.rotate90cw = function(out, a) {
  6105. var x = a[0];
  6106. var y = a[1];
  6107. out[0] = y;
  6108. out[1] = -x;
  6109. };
  6110. /**
  6111. * Transform a point position to local frame.
  6112. * @method toLocalFrame
  6113. * @param {Array} out
  6114. * @param {Array} worldPoint
  6115. * @param {Array} framePosition
  6116. * @param {Number} frameAngle
  6117. */
  6118. vec2.toLocalFrame = function(out, worldPoint, framePosition, frameAngle){
  6119. vec2.copy(out, worldPoint);
  6120. vec2.sub(out, out, framePosition);
  6121. vec2.rotate(out, out, -frameAngle);
  6122. };
  6123. /**
  6124. * Transform a point position to global frame.
  6125. * @method toGlobalFrame
  6126. * @param {Array} out
  6127. * @param {Array} localPoint
  6128. * @param {Array} framePosition
  6129. * @param {Number} frameAngle
  6130. */
  6131. vec2.toGlobalFrame = function(out, localPoint, framePosition, frameAngle){
  6132. vec2.copy(out, localPoint);
  6133. vec2.rotate(out, out, frameAngle);
  6134. vec2.add(out, out, framePosition);
  6135. };
  6136. /**
  6137. * Transform a vector to local frame.
  6138. * @method vectorToLocalFrame
  6139. * @param {Array} out
  6140. * @param {Array} worldVector
  6141. * @param {Number} frameAngle
  6142. */
  6143. vec2.vectorToLocalFrame = function(out, worldVector, frameAngle){
  6144. vec2.rotate(out, worldVector, -frameAngle);
  6145. };
  6146. /**
  6147. * Transform a point position to global frame.
  6148. * @method toGlobalFrame
  6149. * @param {Array} out
  6150. * @param {Array} localVector
  6151. * @param {Number} frameAngle
  6152. */
  6153. vec2.vectorToGlobalFrame = function(out, localVector, frameAngle){
  6154. vec2.rotate(out, localVector, frameAngle);
  6155. };
  6156. /**
  6157. * Compute centroid of a triangle spanned by vectors a,b,c. See http://easycalculation.com/analytical/learn-centroid.php
  6158. * @method centroid
  6159. * @static
  6160. * @param {Array} out
  6161. * @param {Array} a
  6162. * @param {Array} b
  6163. * @param {Array} c
  6164. * @return {Array} The out object
  6165. */
  6166. vec2.centroid = function(out, a, b, c){
  6167. vec2.add(out, a, b);
  6168. vec2.add(out, out, c);
  6169. vec2.scale(out, out, 1/3);
  6170. return out;
  6171. };
  6172. /**
  6173. * Creates a new, empty vec2
  6174. * @static
  6175. * @method create
  6176. * @return {Array} a new 2D vector
  6177. */
  6178. vec2.create = function() {
  6179. var out = new Utils.ARRAY_TYPE(2);
  6180. out[0] = 0;
  6181. out[1] = 0;
  6182. return out;
  6183. };
  6184. /**
  6185. * Creates a new vec2 initialized with values from an existing vector
  6186. * @static
  6187. * @method clone
  6188. * @param {Array} a vector to clone
  6189. * @return {Array} a new 2D vector
  6190. */
  6191. vec2.clone = function(a) {
  6192. var out = new Utils.ARRAY_TYPE(2);
  6193. out[0] = a[0];
  6194. out[1] = a[1];
  6195. return out;
  6196. };
  6197. /**
  6198. * Creates a new vec2 initialized with the given values
  6199. * @static
  6200. * @method fromValues
  6201. * @param {Number} x X component
  6202. * @param {Number} y Y component
  6203. * @return {Array} a new 2D vector
  6204. */
  6205. vec2.fromValues = function(x, y) {
  6206. var out = new Utils.ARRAY_TYPE(2);
  6207. out[0] = x;
  6208. out[1] = y;
  6209. return out;
  6210. };
  6211. /**
  6212. * Copy the values from one vec2 to another
  6213. * @static
  6214. * @method copy
  6215. * @param {Array} out the receiving vector
  6216. * @param {Array} a the source vector
  6217. * @return {Array} out
  6218. */
  6219. vec2.copy = function(out, a) {
  6220. out[0] = a[0];
  6221. out[1] = a[1];
  6222. return out;
  6223. };
  6224. /**
  6225. * Set the components of a vec2 to the given values
  6226. * @static
  6227. * @method set
  6228. * @param {Array} out the receiving vector
  6229. * @param {Number} x X component
  6230. * @param {Number} y Y component
  6231. * @return {Array} out
  6232. */
  6233. vec2.set = function(out, x, y) {
  6234. out[0] = x;
  6235. out[1] = y;
  6236. return out;
  6237. };
  6238. /**
  6239. * Adds two vec2's
  6240. * @static
  6241. * @method add
  6242. * @param {Array} out the receiving vector
  6243. * @param {Array} a the first operand
  6244. * @param {Array} b the second operand
  6245. * @return {Array} out
  6246. */
  6247. vec2.add = function(out, a, b) {
  6248. out[0] = a[0] + b[0];
  6249. out[1] = a[1] + b[1];
  6250. return out;
  6251. };
  6252. /**
  6253. * Subtracts two vec2's
  6254. * @static
  6255. * @method subtract
  6256. * @param {Array} out the receiving vector
  6257. * @param {Array} a the first operand
  6258. * @param {Array} b the second operand
  6259. * @return {Array} out
  6260. */
  6261. vec2.subtract = function(out, a, b) {
  6262. out[0] = a[0] - b[0];
  6263. out[1] = a[1] - b[1];
  6264. return out;
  6265. };
  6266. /**
  6267. * Alias for vec2.subtract
  6268. * @static
  6269. * @method sub
  6270. */
  6271. vec2.sub = vec2.subtract;
  6272. /**
  6273. * Multiplies two vec2's
  6274. * @static
  6275. * @method multiply
  6276. * @param {Array} out the receiving vector
  6277. * @param {Array} a the first operand
  6278. * @param {Array} b the second operand
  6279. * @return {Array} out
  6280. */
  6281. vec2.multiply = function(out, a, b) {
  6282. out[0] = a[0] * b[0];
  6283. out[1] = a[1] * b[1];
  6284. return out;
  6285. };
  6286. /**
  6287. * Alias for vec2.multiply
  6288. * @static
  6289. * @method mul
  6290. */
  6291. vec2.mul = vec2.multiply;
  6292. /**
  6293. * Divides two vec2's
  6294. * @static
  6295. * @method divide
  6296. * @param {Array} out the receiving vector
  6297. * @param {Array} a the first operand
  6298. * @param {Array} b the second operand
  6299. * @return {Array} out
  6300. */
  6301. vec2.divide = function(out, a, b) {
  6302. out[0] = a[0] / b[0];
  6303. out[1] = a[1] / b[1];
  6304. return out;
  6305. };
  6306. /**
  6307. * Alias for vec2.divide
  6308. * @static
  6309. * @method div
  6310. */
  6311. vec2.div = vec2.divide;
  6312. /**
  6313. * Scales a vec2 by a scalar number
  6314. * @static
  6315. * @method scale
  6316. * @param {Array} out the receiving vector
  6317. * @param {Array} a the vector to scale
  6318. * @param {Number} b amount to scale the vector by
  6319. * @return {Array} out
  6320. */
  6321. vec2.scale = function(out, a, b) {
  6322. out[0] = a[0] * b;
  6323. out[1] = a[1] * b;
  6324. return out;
  6325. };
  6326. /**
  6327. * Calculates the euclidian distance between two vec2's
  6328. * @static
  6329. * @method distance
  6330. * @param {Array} a the first operand
  6331. * @param {Array} b the second operand
  6332. * @return {Number} distance between a and b
  6333. */
  6334. vec2.distance = function(a, b) {
  6335. var x = b[0] - a[0],
  6336. y = b[1] - a[1];
  6337. return Math.sqrt(x*x + y*y);
  6338. };
  6339. /**
  6340. * Alias for vec2.distance
  6341. * @static
  6342. * @method dist
  6343. */
  6344. vec2.dist = vec2.distance;
  6345. /**
  6346. * Calculates the squared euclidian distance between two vec2's
  6347. * @static
  6348. * @method squaredDistance
  6349. * @param {Array} a the first operand
  6350. * @param {Array} b the second operand
  6351. * @return {Number} squared distance between a and b
  6352. */
  6353. vec2.squaredDistance = function(a, b) {
  6354. var x = b[0] - a[0],
  6355. y = b[1] - a[1];
  6356. return x*x + y*y;
  6357. };
  6358. /**
  6359. * Alias for vec2.squaredDistance
  6360. * @static
  6361. * @method sqrDist
  6362. */
  6363. vec2.sqrDist = vec2.squaredDistance;
  6364. /**
  6365. * Calculates the length of a vec2
  6366. * @static
  6367. * @method length
  6368. * @param {Array} a vector to calculate length of
  6369. * @return {Number} length of a
  6370. */
  6371. vec2.length = function (a) {
  6372. var x = a[0],
  6373. y = a[1];
  6374. return Math.sqrt(x*x + y*y);
  6375. };
  6376. /**
  6377. * Alias for vec2.length
  6378. * @method len
  6379. * @static
  6380. */
  6381. vec2.len = vec2.length;
  6382. /**
  6383. * Calculates the squared length of a vec2
  6384. * @static
  6385. * @method squaredLength
  6386. * @param {Array} a vector to calculate squared length of
  6387. * @return {Number} squared length of a
  6388. */
  6389. vec2.squaredLength = function (a) {
  6390. var x = a[0],
  6391. y = a[1];
  6392. return x*x + y*y;
  6393. };
  6394. /**
  6395. * Alias for vec2.squaredLength
  6396. * @static
  6397. * @method sqrLen
  6398. */
  6399. vec2.sqrLen = vec2.squaredLength;
  6400. /**
  6401. * Negates the components of a vec2
  6402. * @static
  6403. * @method negate
  6404. * @param {Array} out the receiving vector
  6405. * @param {Array} a vector to negate
  6406. * @return {Array} out
  6407. */
  6408. vec2.negate = function(out, a) {
  6409. out[0] = -a[0];
  6410. out[1] = -a[1];
  6411. return out;
  6412. };
  6413. /**
  6414. * Normalize a vec2
  6415. * @static
  6416. * @method normalize
  6417. * @param {Array} out the receiving vector
  6418. * @param {Array} a vector to normalize
  6419. * @return {Array} out
  6420. */
  6421. vec2.normalize = function(out, a) {
  6422. var x = a[0],
  6423. y = a[1];
  6424. var len = x*x + y*y;
  6425. if (len > 0) {
  6426. //TODO: evaluate use of glm_invsqrt here?
  6427. len = 1 / Math.sqrt(len);
  6428. out[0] = a[0] * len;
  6429. out[1] = a[1] * len;
  6430. }
  6431. return out;
  6432. };
  6433. /**
  6434. * Calculates the dot product of two vec2's
  6435. * @static
  6436. * @method dot
  6437. * @param {Array} a the first operand
  6438. * @param {Array} b the second operand
  6439. * @return {Number} dot product of a and b
  6440. */
  6441. vec2.dot = function (a, b) {
  6442. return a[0] * b[0] + a[1] * b[1];
  6443. };
  6444. /**
  6445. * Returns a string representation of a vector
  6446. * @static
  6447. * @method str
  6448. * @param {Array} vec vector to represent as a string
  6449. * @return {String} string representation of the vector
  6450. */
  6451. vec2.str = function (a) {
  6452. return 'vec2(' + a[0] + ', ' + a[1] + ')';
  6453. };
  6454. /**
  6455. * Linearly interpolate/mix two vectors.
  6456. * @static
  6457. * @method lerp
  6458. * @param {Array} out
  6459. * @param {Array} a First vector
  6460. * @param {Array} b Second vector
  6461. * @param {number} t Lerp factor
  6462. */
  6463. vec2.lerp = function (out, a, b, t) {
  6464. var ax = a[0],
  6465. ay = a[1];
  6466. out[0] = ax + t * (b[0] - ax);
  6467. out[1] = ay + t * (b[1] - ay);
  6468. return out;
  6469. };
  6470. /**
  6471. * Reflect a vector along a normal.
  6472. * @static
  6473. * @method reflect
  6474. * @param {Array} out
  6475. * @param {Array} vector
  6476. * @param {Array} normal
  6477. */
  6478. vec2.reflect = function(out, vector, normal){
  6479. var dot = vector[0] * normal[0] + vector[1] * normal[1];
  6480. out[0] = vector[0] - 2 * normal[0] * dot;
  6481. out[1] = vector[1] - 2 * normal[1] * dot;
  6482. };
  6483. /**
  6484. * Get the intersection point between two line segments.
  6485. * @static
  6486. * @method getLineSegmentsIntersection
  6487. * @param {Array} out
  6488. * @param {Array} p0
  6489. * @param {Array} p1
  6490. * @param {Array} p2
  6491. * @param {Array} p3
  6492. * @return {boolean} True if there was an intersection, otherwise false.
  6493. */
  6494. vec2.getLineSegmentsIntersection = function(out, p0, p1, p2, p3) {
  6495. var t = vec2.getLineSegmentsIntersectionFraction(p0, p1, p2, p3);
  6496. if(t < 0){
  6497. return false;
  6498. } else {
  6499. out[0] = p0[0] + (t * (p1[0] - p0[0]));
  6500. out[1] = p0[1] + (t * (p1[1] - p0[1]));
  6501. return true;
  6502. }
  6503. };
  6504. /**
  6505. * Get the intersection fraction between two line segments. If successful, the intersection is at p0 + t * (p1 - p0)
  6506. * @static
  6507. * @method getLineSegmentsIntersectionFraction
  6508. * @param {Array} p0
  6509. * @param {Array} p1
  6510. * @param {Array} p2
  6511. * @param {Array} p3
  6512. * @return {number} A number between 0 and 1 if there was an intersection, otherwise -1.
  6513. */
  6514. vec2.getLineSegmentsIntersectionFraction = function(p0, p1, p2, p3) {
  6515. var s1_x = p1[0] - p0[0];
  6516. var s1_y = p1[1] - p0[1];
  6517. var s2_x = p3[0] - p2[0];
  6518. var s2_y = p3[1] - p2[1];
  6519. var s, t;
  6520. s = (-s1_y * (p0[0] - p2[0]) + s1_x * (p0[1] - p2[1])) / (-s2_x * s1_y + s1_x * s2_y);
  6521. t = ( s2_x * (p0[1] - p2[1]) - s2_y * (p0[0] - p2[0])) / (-s2_x * s1_y + s1_x * s2_y);
  6522. if (s >= 0 && s <= 1 && t >= 0 && t <= 1) { // Collision detected
  6523. return t;
  6524. }
  6525. return -1; // No collision
  6526. };
  6527. },{"../utils/Utils":57}],31:[function(_dereq_,module,exports){
  6528. var vec2 = _dereq_('../math/vec2')
  6529. , decomp = _dereq_('poly-decomp')
  6530. , Convex = _dereq_('../shapes/Convex')
  6531. , RaycastResult = _dereq_('../collision/RaycastResult')
  6532. , Ray = _dereq_('../collision/Ray')
  6533. , AABB = _dereq_('../collision/AABB')
  6534. , EventEmitter = _dereq_('../events/EventEmitter');
  6535. module.exports = Body;
  6536. /**
  6537. * A rigid body. Has got a center of mass, position, velocity and a number of
  6538. * shapes that are used for collisions.
  6539. *
  6540. * @class Body
  6541. * @constructor
  6542. * @extends EventEmitter
  6543. * @param {Array} [options.force]
  6544. * @param {Array} [options.position]
  6545. * @param {Array} [options.velocity]
  6546. * @param {Boolean} [options.allowSleep]
  6547. * @param {Boolean} [options.collisionResponse]
  6548. * @param {Number} [options.angle=0]
  6549. * @param {Number} [options.angularForce=0]
  6550. * @param {Number} [options.angularVelocity=0]
  6551. * @param {Number} [options.ccdIterations=10]
  6552. * @param {Number} [options.ccdSpeedThreshold=-1]
  6553. * @param {Number} [options.fixedRotation=false]
  6554. * @param {Number} [options.gravityScale]
  6555. * @param {Number} [options.id]
  6556. * @param {Number} [options.mass=0] A number >= 0. If zero, the .type will be set to Body.STATIC.
  6557. * @param {Number} [options.sleepSpeedLimit]
  6558. * @param {Number} [options.sleepTimeLimit]
  6559. * @param {Object} [options]
  6560. *
  6561. * @example
  6562. *
  6563. * // Create a typical dynamic body
  6564. * var body = new Body({
  6565. * mass: 1,
  6566. * position: [0, 0],
  6567. * angle: 0,
  6568. * velocity: [0, 0],
  6569. * angularVelocity: 0
  6570. * });
  6571. *
  6572. * // Add a circular shape to the body
  6573. * body.addShape(new Circle({ radius: 1 }));
  6574. *
  6575. * // Add the body to the world
  6576. * world.addBody(body);
  6577. */
  6578. function Body(options){
  6579. options = options || {};
  6580. EventEmitter.call(this);
  6581. /**
  6582. * The body identifyer
  6583. * @property id
  6584. * @type {Number}
  6585. */
  6586. this.id = options.id || ++Body._idCounter;
  6587. /**
  6588. * The world that this body is added to. This property is set to NULL if the body is not added to any world.
  6589. * @property world
  6590. * @type {World}
  6591. */
  6592. this.world = null;
  6593. /**
  6594. * The shapes of the body.
  6595. *
  6596. * @property shapes
  6597. * @type {Array}
  6598. */
  6599. this.shapes = [];
  6600. /**
  6601. * The mass of the body.
  6602. * @property mass
  6603. * @type {number}
  6604. */
  6605. this.mass = options.mass || 0;
  6606. /**
  6607. * The inverse mass of the body.
  6608. * @property invMass
  6609. * @type {number}
  6610. */
  6611. this.invMass = 0;
  6612. /**
  6613. * The inertia of the body around the Z axis.
  6614. * @property inertia
  6615. * @type {number}
  6616. */
  6617. this.inertia = 0;
  6618. /**
  6619. * The inverse inertia of the body.
  6620. * @property invInertia
  6621. * @type {number}
  6622. */
  6623. this.invInertia = 0;
  6624. this.invMassSolve = 0;
  6625. this.invInertiaSolve = 0;
  6626. /**
  6627. * Set to true if you want to fix the rotation of the body.
  6628. * @property fixedRotation
  6629. * @type {Boolean}
  6630. */
  6631. this.fixedRotation = !!options.fixedRotation;
  6632. /**
  6633. * Set to true if you want to fix the body movement along the X axis. The body will still be able to move along Y.
  6634. * @property {Boolean} fixedX
  6635. */
  6636. this.fixedX = !!options.fixedX;
  6637. /**
  6638. * Set to true if you want to fix the body movement along the Y axis. The body will still be able to move along X.
  6639. * @property {Boolean} fixedY
  6640. */
  6641. this.fixedY = !!options.fixedY;
  6642. /**
  6643. * @private
  6644. * @property {array} massMultiplier
  6645. */
  6646. this.massMultiplier = vec2.create();
  6647. /**
  6648. * The position of the body
  6649. * @property position
  6650. * @type {Array}
  6651. */
  6652. this.position = vec2.fromValues(0,0);
  6653. if(options.position){
  6654. vec2.copy(this.position, options.position);
  6655. }
  6656. /**
  6657. * The interpolated position of the body. Use this for rendering.
  6658. * @property interpolatedPosition
  6659. * @type {Array}
  6660. */
  6661. this.interpolatedPosition = vec2.fromValues(0,0);
  6662. /**
  6663. * The interpolated angle of the body. Use this for rendering.
  6664. * @property interpolatedAngle
  6665. * @type {Number}
  6666. */
  6667. this.interpolatedAngle = 0;
  6668. /**
  6669. * The previous position of the body.
  6670. * @property previousPosition
  6671. * @type {Array}
  6672. */
  6673. this.previousPosition = vec2.fromValues(0,0);
  6674. /**
  6675. * The previous angle of the body.
  6676. * @property previousAngle
  6677. * @type {Number}
  6678. */
  6679. this.previousAngle = 0;
  6680. /**
  6681. * The current velocity of the body.
  6682. * @property velocity
  6683. * @type {Array}
  6684. */
  6685. this.velocity = vec2.fromValues(0,0);
  6686. if(options.velocity){
  6687. vec2.copy(this.velocity, options.velocity);
  6688. }
  6689. /**
  6690. * Constraint velocity that was added to the body during the last step.
  6691. * @property vlambda
  6692. * @type {Array}
  6693. */
  6694. this.vlambda = vec2.fromValues(0,0);
  6695. /**
  6696. * Angular constraint velocity that was added to the body during last step.
  6697. * @property wlambda
  6698. * @type {Array}
  6699. */
  6700. this.wlambda = 0;
  6701. /**
  6702. * The angle of the body, in radians.
  6703. * @property angle
  6704. * @type {number}
  6705. * @example
  6706. * // The angle property is not normalized to the interval 0 to 2*pi, it can be any value.
  6707. * // If you need a value between 0 and 2*pi, use the following function to normalize it.
  6708. * function normalizeAngle(angle){
  6709. * angle = angle % (2*Math.PI);
  6710. * if(angle < 0){
  6711. * angle += (2*Math.PI);
  6712. * }
  6713. * return angle;
  6714. * }
  6715. */
  6716. this.angle = options.angle || 0;
  6717. /**
  6718. * The angular velocity of the body, in radians per second.
  6719. * @property angularVelocity
  6720. * @type {number}
  6721. */
  6722. this.angularVelocity = options.angularVelocity || 0;
  6723. /**
  6724. * The force acting on the body. Since the body force (and {{#crossLink "Body/angularForce:property"}}{{/crossLink}}) will be zeroed after each step, so you need to set the force before each step.
  6725. * @property force
  6726. * @type {Array}
  6727. *
  6728. * @example
  6729. * // This produces a forcefield of 1 Newton in the positive x direction.
  6730. * for(var i=0; i<numSteps; i++){
  6731. * body.force[0] = 1;
  6732. * world.step(1/60);
  6733. * }
  6734. *
  6735. * @example
  6736. * // This will apply a rotational force on the body
  6737. * for(var i=0; i<numSteps; i++){
  6738. * body.angularForce = -3;
  6739. * world.step(1/60);
  6740. * }
  6741. */
  6742. this.force = vec2.create();
  6743. if(options.force){
  6744. vec2.copy(this.force, options.force);
  6745. }
  6746. /**
  6747. * The angular force acting on the body. See {{#crossLink "Body/force:property"}}{{/crossLink}}.
  6748. * @property angularForce
  6749. * @type {number}
  6750. */
  6751. this.angularForce = options.angularForce || 0;
  6752. /**
  6753. * The linear damping acting on the body in the velocity direction. Should be a value between 0 and 1.
  6754. * @property damping
  6755. * @type {Number}
  6756. * @default 0.1
  6757. */
  6758. this.damping = typeof(options.damping) === "number" ? options.damping : 0.1;
  6759. /**
  6760. * The angular force acting on the body. Should be a value between 0 and 1.
  6761. * @property angularDamping
  6762. * @type {Number}
  6763. * @default 0.1
  6764. */
  6765. this.angularDamping = typeof(options.angularDamping) === "number" ? options.angularDamping : 0.1;
  6766. /**
  6767. * The type of motion this body has. Should be one of: {{#crossLink "Body/STATIC:property"}}Body.STATIC{{/crossLink}}, {{#crossLink "Body/DYNAMIC:property"}}Body.DYNAMIC{{/crossLink}} and {{#crossLink "Body/KINEMATIC:property"}}Body.KINEMATIC{{/crossLink}}.
  6768. *
  6769. * * Static bodies do not move, and they do not respond to forces or collision.
  6770. * * Dynamic bodies body can move and respond to collisions and forces.
  6771. * * Kinematic bodies only moves according to its .velocity, and does not respond to collisions or force.
  6772. *
  6773. * @property type
  6774. * @type {number}
  6775. *
  6776. * @example
  6777. * // Bodies are static by default. Static bodies will never move.
  6778. * var body = new Body();
  6779. * console.log(body.type == Body.STATIC); // true
  6780. *
  6781. * @example
  6782. * // By setting the mass of a body to a nonzero number, the body
  6783. * // will become dynamic and will move and interact with other bodies.
  6784. * var dynamicBody = new Body({
  6785. * mass : 1
  6786. * });
  6787. * console.log(dynamicBody.type == Body.DYNAMIC); // true
  6788. *
  6789. * @example
  6790. * // Kinematic bodies will only move if you change their velocity.
  6791. * var kinematicBody = new Body({
  6792. * type: Body.KINEMATIC // Type can be set via the options object.
  6793. * });
  6794. */
  6795. this.type = Body.STATIC;
  6796. if(typeof(options.type) !== 'undefined'){
  6797. this.type = options.type;
  6798. } else if(!options.mass){
  6799. this.type = Body.STATIC;
  6800. } else {
  6801. this.type = Body.DYNAMIC;
  6802. }
  6803. /**
  6804. * Bounding circle radius.
  6805. * @property boundingRadius
  6806. * @type {Number}
  6807. */
  6808. this.boundingRadius = 0;
  6809. /**
  6810. * Bounding box of this body.
  6811. * @property aabb
  6812. * @type {AABB}
  6813. */
  6814. this.aabb = new AABB();
  6815. /**
  6816. * Indicates if the AABB needs update. Update it with {{#crossLink "Body/updateAABB:method"}}.updateAABB(){{/crossLink}}.
  6817. * @property aabbNeedsUpdate
  6818. * @type {Boolean}
  6819. * @see updateAABB
  6820. *
  6821. * @example
  6822. * // Force update the AABB
  6823. * body.aabbNeedsUpdate = true;
  6824. * body.updateAABB();
  6825. * console.log(body.aabbNeedsUpdate); // false
  6826. */
  6827. this.aabbNeedsUpdate = true;
  6828. /**
  6829. * If true, the body will automatically fall to sleep. Note that you need to enable sleeping in the {{#crossLink "World"}}{{/crossLink}} before anything will happen.
  6830. * @property allowSleep
  6831. * @type {Boolean}
  6832. * @default true
  6833. */
  6834. this.allowSleep = options.allowSleep !== undefined ? options.allowSleep : true;
  6835. this.wantsToSleep = false;
  6836. /**
  6837. * One of {{#crossLink "Body/AWAKE:property"}}Body.AWAKE{{/crossLink}}, {{#crossLink "Body/SLEEPY:property"}}Body.SLEEPY{{/crossLink}} and {{#crossLink "Body/SLEEPING:property"}}Body.SLEEPING{{/crossLink}}.
  6838. *
  6839. * The body is initially Body.AWAKE. If its velocity norm is below .sleepSpeedLimit, the sleepState will become Body.SLEEPY. If the body continues to be Body.SLEEPY for .sleepTimeLimit seconds, it will fall asleep (Body.SLEEPY).
  6840. *
  6841. * @property sleepState
  6842. * @type {Number}
  6843. * @default Body.AWAKE
  6844. */
  6845. this.sleepState = Body.AWAKE;
  6846. /**
  6847. * If the speed (the norm of the velocity) is smaller than this value, the body is considered sleepy.
  6848. * @property sleepSpeedLimit
  6849. * @type {Number}
  6850. * @default 0.2
  6851. */
  6852. this.sleepSpeedLimit = options.sleepSpeedLimit !== undefined ? options.sleepSpeedLimit : 0.2;
  6853. /**
  6854. * If the body has been sleepy for this sleepTimeLimit seconds, it is considered sleeping.
  6855. * @property sleepTimeLimit
  6856. * @type {Number}
  6857. * @default 1
  6858. */
  6859. this.sleepTimeLimit = options.sleepTimeLimit !== undefined ? options.sleepTimeLimit : 1;
  6860. /**
  6861. * Gravity scaling factor. If you want the body to ignore gravity, set this to zero. If you want to reverse gravity, set it to -1.
  6862. * @property {Number} gravityScale
  6863. * @default 1
  6864. */
  6865. this.gravityScale = options.gravityScale !== undefined ? options.gravityScale : 1;
  6866. /**
  6867. * Whether to produce contact forces when in contact with other bodies. Note that contacts will be generated, but they will be disabled. That means that this body will move through other bodies, but it will still trigger contact events, etc.
  6868. * @property {Boolean} collisionResponse
  6869. */
  6870. this.collisionResponse = options.collisionResponse !== undefined ? options.collisionResponse : true;
  6871. /**
  6872. * How long the body has been sleeping.
  6873. * @property {Number} idleTime
  6874. */
  6875. this.idleTime = 0;
  6876. /**
  6877. * The last time when the body went to SLEEPY state.
  6878. * @property {Number} timeLastSleepy
  6879. * @private
  6880. */
  6881. this.timeLastSleepy = 0;
  6882. /**
  6883. * If the body speed exceeds this threshold, CCD (continuous collision detection) will be enabled. Set it to a negative number to disable CCD completely for this body.
  6884. * @property {number} ccdSpeedThreshold
  6885. * @default -1
  6886. */
  6887. this.ccdSpeedThreshold = options.ccdSpeedThreshold !== undefined ? options.ccdSpeedThreshold : -1;
  6888. /**
  6889. * The number of iterations that should be used when searching for the time of impact during CCD. A larger number will assure that there's a small penetration on CCD collision, but a small number will give more performance.
  6890. * @property {number} ccdIterations
  6891. * @default 10
  6892. */
  6893. this.ccdIterations = options.ccdIterations !== undefined ? options.ccdIterations : 10;
  6894. this.concavePath = null;
  6895. this._wakeUpAfterNarrowphase = false;
  6896. this.updateMassProperties();
  6897. }
  6898. Body.prototype = new EventEmitter();
  6899. Body.prototype.constructor = Body;
  6900. Body._idCounter = 0;
  6901. /**
  6902. * @private
  6903. * @method updateSolveMassProperties
  6904. */
  6905. Body.prototype.updateSolveMassProperties = function(){
  6906. if(this.sleepState === Body.SLEEPING || this.type === Body.KINEMATIC){
  6907. this.invMassSolve = 0;
  6908. this.invInertiaSolve = 0;
  6909. } else {
  6910. this.invMassSolve = this.invMass;
  6911. this.invInertiaSolve = this.invInertia;
  6912. }
  6913. };
  6914. /**
  6915. * Set the total density of the body
  6916. * @method setDensity
  6917. * @param {number} density
  6918. */
  6919. Body.prototype.setDensity = function(density) {
  6920. var totalArea = this.getArea();
  6921. this.mass = totalArea * density;
  6922. this.updateMassProperties();
  6923. };
  6924. /**
  6925. * Get the total area of all shapes in the body
  6926. * @method getArea
  6927. * @return {Number}
  6928. */
  6929. Body.prototype.getArea = function() {
  6930. var totalArea = 0;
  6931. for(var i=0; i<this.shapes.length; i++){
  6932. totalArea += this.shapes[i].area;
  6933. }
  6934. return totalArea;
  6935. };
  6936. /**
  6937. * Get the AABB from the body. The AABB is updated if necessary.
  6938. * @method getAABB
  6939. * @return {AABB} The AABB instance (this.aabb)
  6940. */
  6941. Body.prototype.getAABB = function(){
  6942. if(this.aabbNeedsUpdate){
  6943. this.updateAABB();
  6944. }
  6945. return this.aabb;
  6946. };
  6947. var shapeAABB = new AABB(),
  6948. tmp = vec2.create();
  6949. /**
  6950. * Updates the AABB of the Body, and set .aabbNeedsUpdate = false.
  6951. * @method updateAABB
  6952. */
  6953. Body.prototype.updateAABB = function() {
  6954. var shapes = this.shapes,
  6955. N = shapes.length,
  6956. offset = tmp,
  6957. bodyAngle = this.angle;
  6958. for(var i=0; i!==N; i++){
  6959. var shape = shapes[i],
  6960. angle = shape.angle + bodyAngle;
  6961. // Get shape world offset
  6962. vec2.rotate(offset, shape.position, bodyAngle);
  6963. vec2.add(offset, offset, this.position);
  6964. // Get shape AABB
  6965. shape.computeAABB(shapeAABB, offset, angle);
  6966. if(i===0){
  6967. this.aabb.copy(shapeAABB);
  6968. } else {
  6969. this.aabb.extend(shapeAABB);
  6970. }
  6971. }
  6972. this.aabbNeedsUpdate = false;
  6973. };
  6974. /**
  6975. * Update the bounding radius of the body (this.boundingRadius). Should be done if any of the shape dimensions or positions are changed.
  6976. * @method updateBoundingRadius
  6977. */
  6978. Body.prototype.updateBoundingRadius = function(){
  6979. var shapes = this.shapes,
  6980. N = shapes.length,
  6981. radius = 0;
  6982. for(var i=0; i!==N; i++){
  6983. var shape = shapes[i],
  6984. offset = vec2.length(shape.position),
  6985. r = shape.boundingRadius;
  6986. if(offset + r > radius){
  6987. radius = offset + r;
  6988. }
  6989. }
  6990. this.boundingRadius = radius;
  6991. };
  6992. /**
  6993. * Add a shape to the body. You can pass a local transform when adding a shape,
  6994. * so that the shape gets an offset and angle relative to the body center of mass.
  6995. * Will automatically update the mass properties and bounding radius.
  6996. *
  6997. * @method addShape
  6998. * @param {Shape} shape
  6999. * @param {Array} [offset] Local body offset of the shape.
  7000. * @param {Number} [angle] Local body angle.
  7001. *
  7002. * @example
  7003. * var body = new Body(),
  7004. * shape = new Circle({ radius: 1 });
  7005. *
  7006. * // Add the shape to the body, positioned in the center
  7007. * body.addShape(shape);
  7008. *
  7009. * // Add another shape to the body, positioned 1 unit length from the body center of mass along the local x-axis.
  7010. * body.addShape(shape,[1,0]);
  7011. *
  7012. * // Add another shape to the body, positioned 1 unit length from the body center of mass along the local y-axis, and rotated 90 degrees CCW.
  7013. * body.addShape(shape,[0,1],Math.PI/2);
  7014. */
  7015. Body.prototype.addShape = function(shape, offset, angle){
  7016. if(shape.body){
  7017. throw new Error('A shape can only be added to one body.');
  7018. }
  7019. shape.body = this;
  7020. // Copy the offset vector
  7021. if(offset){
  7022. vec2.copy(shape.position, offset);
  7023. } else {
  7024. vec2.set(shape.position, 0, 0);
  7025. }
  7026. shape.angle = angle || 0;
  7027. this.shapes.push(shape);
  7028. this.updateMassProperties();
  7029. this.updateBoundingRadius();
  7030. this.aabbNeedsUpdate = true;
  7031. };
  7032. /**
  7033. * Remove a shape
  7034. * @method removeShape
  7035. * @param {Shape} shape
  7036. * @return {Boolean} True if the shape was found and removed, else false.
  7037. */
  7038. Body.prototype.removeShape = function(shape){
  7039. var idx = this.shapes.indexOf(shape);
  7040. if(idx !== -1){
  7041. this.shapes.splice(idx,1);
  7042. this.aabbNeedsUpdate = true;
  7043. shape.body = null;
  7044. return true;
  7045. } else {
  7046. return false;
  7047. }
  7048. };
  7049. /**
  7050. * Updates .inertia, .invMass, .invInertia for this Body. Should be called when
  7051. * changing the structure or mass of the Body.
  7052. *
  7053. * @method updateMassProperties
  7054. *
  7055. * @example
  7056. * body.mass += 1;
  7057. * body.updateMassProperties();
  7058. */
  7059. Body.prototype.updateMassProperties = function(){
  7060. if(this.type === Body.STATIC || this.type === Body.KINEMATIC){
  7061. this.mass = Number.MAX_VALUE;
  7062. this.invMass = 0;
  7063. this.inertia = Number.MAX_VALUE;
  7064. this.invInertia = 0;
  7065. } else {
  7066. var shapes = this.shapes,
  7067. N = shapes.length,
  7068. m = this.mass / N,
  7069. I = 0;
  7070. if(!this.fixedRotation){
  7071. for(var i=0; i<N; i++){
  7072. var shape = shapes[i],
  7073. r2 = vec2.squaredLength(shape.position),
  7074. Icm = shape.computeMomentOfInertia(m);
  7075. I += Icm + m*r2;
  7076. }
  7077. this.inertia = I;
  7078. this.invInertia = I>0 ? 1/I : 0;
  7079. } else {
  7080. this.inertia = Number.MAX_VALUE;
  7081. this.invInertia = 0;
  7082. }
  7083. // Inverse mass properties are easy
  7084. this.invMass = 1 / this.mass;
  7085. vec2.set(
  7086. this.massMultiplier,
  7087. this.fixedX ? 0 : 1,
  7088. this.fixedY ? 0 : 1
  7089. );
  7090. }
  7091. };
  7092. var Body_applyForce_r = vec2.create();
  7093. /**
  7094. * Apply force to a point relative to the center of mass of the body. This could for example be a point on the RigidBody surface. Applying force this way will add to Body.force and Body.angularForce. If relativePoint is zero, the force will be applied directly on the center of mass, and the torque produced will be zero.
  7095. * @method applyForce
  7096. * @param {Array} force The force to add.
  7097. * @param {Array} [relativePoint] A world point to apply the force on.
  7098. */
  7099. Body.prototype.applyForce = function(force, relativePoint){
  7100. // Add linear force
  7101. vec2.add(this.force, this.force, force);
  7102. if(relativePoint){
  7103. // Compute produced rotational force
  7104. var rotForce = vec2.crossLength(relativePoint,force);
  7105. // Add rotational force
  7106. this.angularForce += rotForce;
  7107. }
  7108. };
  7109. /**
  7110. * Apply force to a body-local point.
  7111. * @method applyForceLocal
  7112. * @param {Array} localForce The force vector to add, oriented in local body space.
  7113. * @param {Array} localPoint A point relative to the body in world space. If not given, it is set to zero and all of the impulse will be excerted on the center of mass.
  7114. */
  7115. var Body_applyForce_forceWorld = vec2.create();
  7116. var Body_applyForce_pointWorld = vec2.create();
  7117. var Body_applyForce_pointLocal = vec2.create();
  7118. Body.prototype.applyForceLocal = function(localForce, localPoint){
  7119. localPoint = localPoint || Body_applyForce_pointLocal;
  7120. var worldForce = Body_applyForce_forceWorld;
  7121. var worldPoint = Body_applyForce_pointWorld;
  7122. this.vectorToWorldFrame(worldForce, localForce);
  7123. this.vectorToWorldFrame(worldPoint, localPoint);
  7124. this.applyForce(worldForce, worldPoint);
  7125. };
  7126. /**
  7127. * Apply impulse to a point relative to the body. This could for example be a point on the Body surface. An impulse is a force added to a body during a short period of time (impulse = force * time). Impulses will be added to Body.velocity and Body.angularVelocity.
  7128. * @method applyImpulse
  7129. * @param {Array} impulse The impulse vector to add, oriented in world space.
  7130. * @param {Array} [relativePoint] A point relative to the body in world space. If not given, it is set to zero and all of the impulse will be excerted on the center of mass.
  7131. */
  7132. var Body_applyImpulse_velo = vec2.create();
  7133. Body.prototype.applyImpulse = function(impulseVector, relativePoint){
  7134. if(this.type !== Body.DYNAMIC){
  7135. return;
  7136. }
  7137. // Compute produced central impulse velocity
  7138. var velo = Body_applyImpulse_velo;
  7139. vec2.scale(velo, impulseVector, this.invMass);
  7140. vec2.multiply(velo, this.massMultiplier, velo);
  7141. // Add linear impulse
  7142. vec2.add(this.velocity, velo, this.velocity);
  7143. if(relativePoint){
  7144. // Compute produced rotational impulse velocity
  7145. var rotVelo = vec2.crossLength(relativePoint, impulseVector);
  7146. rotVelo *= this.invInertia;
  7147. // Add rotational Impulse
  7148. this.angularVelocity += rotVelo;
  7149. }
  7150. };
  7151. /**
  7152. * Apply impulse to a point relative to the body. This could for example be a point on the Body surface. An impulse is a force added to a body during a short period of time (impulse = force * time). Impulses will be added to Body.velocity and Body.angularVelocity.
  7153. * @method applyImpulseLocal
  7154. * @param {Array} impulse The impulse vector to add, oriented in world space.
  7155. * @param {Array} [relativePoint] A point relative to the body in world space. If not given, it is set to zero and all of the impulse will be excerted on the center of mass.
  7156. */
  7157. var Body_applyImpulse_impulseWorld = vec2.create();
  7158. var Body_applyImpulse_pointWorld = vec2.create();
  7159. var Body_applyImpulse_pointLocal = vec2.create();
  7160. Body.prototype.applyImpulseLocal = function(localImpulse, localPoint){
  7161. localPoint = localPoint || Body_applyImpulse_pointLocal;
  7162. var worldImpulse = Body_applyImpulse_impulseWorld;
  7163. var worldPoint = Body_applyImpulse_pointWorld;
  7164. this.vectorToWorldFrame(worldImpulse, localImpulse);
  7165. this.vectorToWorldFrame(worldPoint, localPoint);
  7166. this.applyImpulse(worldImpulse, worldPoint);
  7167. };
  7168. /**
  7169. * Transform a world point to local body frame.
  7170. * @method toLocalFrame
  7171. * @param {Array} out The vector to store the result in
  7172. * @param {Array} worldPoint The input world point
  7173. */
  7174. Body.prototype.toLocalFrame = function(out, worldPoint){
  7175. vec2.toLocalFrame(out, worldPoint, this.position, this.angle);
  7176. };
  7177. /**
  7178. * Transform a local point to world frame.
  7179. * @method toWorldFrame
  7180. * @param {Array} out The vector to store the result in
  7181. * @param {Array} localPoint The input local point
  7182. */
  7183. Body.prototype.toWorldFrame = function(out, localPoint){
  7184. vec2.toGlobalFrame(out, localPoint, this.position, this.angle);
  7185. };
  7186. /**
  7187. * Transform a world point to local body frame.
  7188. * @method vectorToLocalFrame
  7189. * @param {Array} out The vector to store the result in
  7190. * @param {Array} worldVector The input world vector
  7191. */
  7192. Body.prototype.vectorToLocalFrame = function(out, worldVector){
  7193. vec2.vectorToLocalFrame(out, worldVector, this.angle);
  7194. };
  7195. /**
  7196. * Transform a local point to world frame.
  7197. * @method vectorToWorldFrame
  7198. * @param {Array} out The vector to store the result in
  7199. * @param {Array} localVector The input local vector
  7200. */
  7201. Body.prototype.vectorToWorldFrame = function(out, localVector){
  7202. vec2.vectorToGlobalFrame(out, localVector, this.angle);
  7203. };
  7204. /**
  7205. * Reads a polygon shape path, and assembles convex shapes from that and puts them at proper offset points.
  7206. * @method fromPolygon
  7207. * @param {Array} path An array of 2d vectors, e.g. [[0,0],[0,1],...] that resembles a concave or convex polygon. The shape must be simple and without holes.
  7208. * @param {Object} [options]
  7209. * @param {Boolean} [options.optimalDecomp=false] Set to true if you need optimal decomposition. Warning: very slow for polygons with more than 10 vertices.
  7210. * @param {Boolean} [options.skipSimpleCheck=false] Set to true if you already know that the path is not intersecting itself.
  7211. * @param {Boolean|Number} [options.removeCollinearPoints=false] Set to a number (angle threshold value) to remove collinear points, or false to keep all points.
  7212. * @return {Boolean} True on success, else false.
  7213. */
  7214. Body.prototype.fromPolygon = function(path,options){
  7215. options = options || {};
  7216. // Remove all shapes
  7217. for(var i=this.shapes.length; i>=0; --i){
  7218. this.removeShape(this.shapes[i]);
  7219. }
  7220. var p = new decomp.Polygon();
  7221. p.vertices = path;
  7222. // Make it counter-clockwise
  7223. p.makeCCW();
  7224. if(typeof(options.removeCollinearPoints) === "number"){
  7225. p.removeCollinearPoints(options.removeCollinearPoints);
  7226. }
  7227. // Check if any line segment intersects the path itself
  7228. if(typeof(options.skipSimpleCheck) === "undefined"){
  7229. if(!p.isSimple()){
  7230. return false;
  7231. }
  7232. }
  7233. // Save this path for later
  7234. this.concavePath = p.vertices.slice(0);
  7235. for(var i=0; i<this.concavePath.length; i++){
  7236. var v = [0,0];
  7237. vec2.copy(v,this.concavePath[i]);
  7238. this.concavePath[i] = v;
  7239. }
  7240. // Slow or fast decomp?
  7241. var convexes;
  7242. if(options.optimalDecomp){
  7243. convexes = p.decomp();
  7244. } else {
  7245. convexes = p.quickDecomp();
  7246. }
  7247. var cm = vec2.create();
  7248. // Add convexes
  7249. for(var i=0; i!==convexes.length; i++){
  7250. // Create convex
  7251. var c = new Convex({ vertices: convexes[i].vertices });
  7252. // Move all vertices so its center of mass is in the local center of the convex
  7253. for(var j=0; j!==c.vertices.length; j++){
  7254. var v = c.vertices[j];
  7255. vec2.sub(v,v,c.centerOfMass);
  7256. }
  7257. vec2.scale(cm,c.centerOfMass,1);
  7258. c.updateTriangles();
  7259. c.updateCenterOfMass();
  7260. c.updateBoundingRadius();
  7261. // Add the shape
  7262. this.addShape(c,cm);
  7263. }
  7264. this.adjustCenterOfMass();
  7265. this.aabbNeedsUpdate = true;
  7266. return true;
  7267. };
  7268. var adjustCenterOfMass_tmp1 = vec2.fromValues(0,0),
  7269. adjustCenterOfMass_tmp2 = vec2.fromValues(0,0),
  7270. adjustCenterOfMass_tmp3 = vec2.fromValues(0,0),
  7271. adjustCenterOfMass_tmp4 = vec2.fromValues(0,0);
  7272. /**
  7273. * Moves the shape offsets so their center of mass becomes the body center of mass.
  7274. * @method adjustCenterOfMass
  7275. */
  7276. Body.prototype.adjustCenterOfMass = function(){
  7277. var offset_times_area = adjustCenterOfMass_tmp2,
  7278. sum = adjustCenterOfMass_tmp3,
  7279. cm = adjustCenterOfMass_tmp4,
  7280. totalArea = 0;
  7281. vec2.set(sum,0,0);
  7282. for(var i=0; i!==this.shapes.length; i++){
  7283. var s = this.shapes[i];
  7284. vec2.scale(offset_times_area, s.position, s.area);
  7285. vec2.add(sum, sum, offset_times_area);
  7286. totalArea += s.area;
  7287. }
  7288. vec2.scale(cm,sum,1/totalArea);
  7289. // Now move all shapes
  7290. for(var i=0; i!==this.shapes.length; i++){
  7291. var s = this.shapes[i];
  7292. vec2.sub(s.position, s.position, cm);
  7293. }
  7294. // Move the body position too
  7295. vec2.add(this.position,this.position,cm);
  7296. // And concave path
  7297. for(var i=0; this.concavePath && i<this.concavePath.length; i++){
  7298. vec2.sub(this.concavePath[i], this.concavePath[i], cm);
  7299. }
  7300. this.updateMassProperties();
  7301. this.updateBoundingRadius();
  7302. };
  7303. /**
  7304. * Sets the force on the body to zero.
  7305. * @method setZeroForce
  7306. */
  7307. Body.prototype.setZeroForce = function(){
  7308. vec2.set(this.force,0.0,0.0);
  7309. this.angularForce = 0.0;
  7310. };
  7311. Body.prototype.resetConstraintVelocity = function(){
  7312. var b = this,
  7313. vlambda = b.vlambda;
  7314. vec2.set(vlambda,0,0);
  7315. b.wlambda = 0;
  7316. };
  7317. Body.prototype.addConstraintVelocity = function(){
  7318. var b = this,
  7319. v = b.velocity;
  7320. vec2.add( v, v, b.vlambda);
  7321. b.angularVelocity += b.wlambda;
  7322. };
  7323. /**
  7324. * Apply damping, see <a href="http://code.google.com/p/bullet/issues/detail?id=74">this</a> for details.
  7325. * @method applyDamping
  7326. * @param {number} dt Current time step
  7327. */
  7328. Body.prototype.applyDamping = function(dt){
  7329. if(this.type === Body.DYNAMIC){ // Only for dynamic bodies
  7330. var v = this.velocity;
  7331. vec2.scale(v, v, Math.pow(1.0 - this.damping,dt));
  7332. this.angularVelocity *= Math.pow(1.0 - this.angularDamping,dt);
  7333. }
  7334. };
  7335. /**
  7336. * Wake the body up. Normally you should not need this, as the body is automatically awoken at events such as collisions.
  7337. * Sets the sleepState to {{#crossLink "Body/AWAKE:property"}}Body.AWAKE{{/crossLink}} and emits the wakeUp event if the body wasn't awake before.
  7338. * @method wakeUp
  7339. */
  7340. Body.prototype.wakeUp = function(){
  7341. var s = this.sleepState;
  7342. this.sleepState = Body.AWAKE;
  7343. this.idleTime = 0;
  7344. if(s !== Body.AWAKE){
  7345. this.emit(Body.wakeUpEvent);
  7346. }
  7347. };
  7348. /**
  7349. * Force body sleep
  7350. * @method sleep
  7351. */
  7352. Body.prototype.sleep = function(){
  7353. this.sleepState = Body.SLEEPING;
  7354. this.angularVelocity = 0;
  7355. this.angularForce = 0;
  7356. vec2.set(this.velocity,0,0);
  7357. vec2.set(this.force,0,0);
  7358. this.emit(Body.sleepEvent);
  7359. };
  7360. /**
  7361. * Called every timestep to update internal sleep timer and change sleep state if needed.
  7362. * @method sleepTick
  7363. * @param {number} time The world time in seconds
  7364. * @param {boolean} dontSleep
  7365. * @param {number} dt
  7366. */
  7367. Body.prototype.sleepTick = function(time, dontSleep, dt){
  7368. if(!this.allowSleep || this.type === Body.SLEEPING){
  7369. return;
  7370. }
  7371. this.wantsToSleep = false;
  7372. var sleepState = this.sleepState,
  7373. speedSquared = vec2.squaredLength(this.velocity) + Math.pow(this.angularVelocity,2),
  7374. speedLimitSquared = Math.pow(this.sleepSpeedLimit,2);
  7375. // Add to idle time
  7376. if(speedSquared >= speedLimitSquared){
  7377. this.idleTime = 0;
  7378. this.sleepState = Body.AWAKE;
  7379. } else {
  7380. this.idleTime += dt;
  7381. this.sleepState = Body.SLEEPY;
  7382. }
  7383. if(this.idleTime > this.sleepTimeLimit){
  7384. if(!dontSleep){
  7385. this.sleep();
  7386. } else {
  7387. this.wantsToSleep = true;
  7388. }
  7389. }
  7390. };
  7391. /**
  7392. * Check if the body is overlapping another body. Note that this method only works if the body was added to a World and if at least one step was taken.
  7393. * @method overlaps
  7394. * @param {Body} body
  7395. * @return {boolean}
  7396. */
  7397. Body.prototype.overlaps = function(body){
  7398. return this.world.overlapKeeper.bodiesAreOverlapping(this, body);
  7399. };
  7400. var integrate_fhMinv = vec2.create();
  7401. var integrate_velodt = vec2.create();
  7402. /**
  7403. * Move the body forward in time given its current velocity.
  7404. * @method integrate
  7405. * @param {Number} dt
  7406. */
  7407. Body.prototype.integrate = function(dt){
  7408. var minv = this.invMass,
  7409. f = this.force,
  7410. pos = this.position,
  7411. velo = this.velocity;
  7412. // Save old position
  7413. vec2.copy(this.previousPosition, this.position);
  7414. this.previousAngle = this.angle;
  7415. // Velocity update
  7416. if(!this.fixedRotation){
  7417. this.angularVelocity += this.angularForce * this.invInertia * dt;
  7418. }
  7419. vec2.scale(integrate_fhMinv, f, dt * minv);
  7420. vec2.multiply(integrate_fhMinv, this.massMultiplier, integrate_fhMinv);
  7421. vec2.add(velo, integrate_fhMinv, velo);
  7422. // CCD
  7423. if(!this.integrateToTimeOfImpact(dt)){
  7424. // Regular position update
  7425. vec2.scale(integrate_velodt, velo, dt);
  7426. vec2.add(pos, pos, integrate_velodt);
  7427. if(!this.fixedRotation){
  7428. this.angle += this.angularVelocity * dt;
  7429. }
  7430. }
  7431. this.aabbNeedsUpdate = true;
  7432. };
  7433. var result = new RaycastResult();
  7434. var ray = new Ray({
  7435. mode: Ray.ALL
  7436. });
  7437. var direction = vec2.create();
  7438. var end = vec2.create();
  7439. var startToEnd = vec2.create();
  7440. var rememberPosition = vec2.create();
  7441. Body.prototype.integrateToTimeOfImpact = function(dt){
  7442. if(this.ccdSpeedThreshold < 0 || vec2.squaredLength(this.velocity) < Math.pow(this.ccdSpeedThreshold, 2)){
  7443. return false;
  7444. }
  7445. vec2.normalize(direction, this.velocity);
  7446. vec2.scale(end, this.velocity, dt);
  7447. vec2.add(end, end, this.position);
  7448. vec2.sub(startToEnd, end, this.position);
  7449. var startToEndAngle = this.angularVelocity * dt;
  7450. var len = vec2.length(startToEnd);
  7451. var timeOfImpact = 1;
  7452. var hit;
  7453. var that = this;
  7454. result.reset();
  7455. ray.callback = function (result) {
  7456. if(result.body === that){
  7457. return;
  7458. }
  7459. hit = result.body;
  7460. result.getHitPoint(end, ray);
  7461. vec2.sub(startToEnd, end, that.position);
  7462. timeOfImpact = vec2.length(startToEnd) / len;
  7463. result.stop();
  7464. };
  7465. vec2.copy(ray.from, this.position);
  7466. vec2.copy(ray.to, end);
  7467. ray.update();
  7468. this.world.raycast(result, ray);
  7469. if(!hit){
  7470. return false;
  7471. }
  7472. var rememberAngle = this.angle;
  7473. vec2.copy(rememberPosition, this.position);
  7474. // Got a start and end point. Approximate time of impact using binary search
  7475. var iter = 0;
  7476. var tmin = 0;
  7477. var tmid = 0;
  7478. var tmax = timeOfImpact;
  7479. while (tmax >= tmin && iter < this.ccdIterations) {
  7480. iter++;
  7481. // calculate the midpoint
  7482. tmid = (tmax - tmin) / 2;
  7483. // Move the body to that point
  7484. vec2.scale(integrate_velodt, startToEnd, timeOfImpact);
  7485. vec2.add(this.position, rememberPosition, integrate_velodt);
  7486. this.angle = rememberAngle + startToEndAngle * timeOfImpact;
  7487. this.updateAABB();
  7488. // check overlap
  7489. var overlaps = this.aabb.overlaps(hit.aabb) && this.world.narrowphase.bodiesOverlap(this, hit);
  7490. if (overlaps) {
  7491. // change min to search upper interval
  7492. tmin = tmid;
  7493. } else {
  7494. // change max to search lower interval
  7495. tmax = tmid;
  7496. }
  7497. }
  7498. timeOfImpact = tmid;
  7499. vec2.copy(this.position, rememberPosition);
  7500. this.angle = rememberAngle;
  7501. // move to TOI
  7502. vec2.scale(integrate_velodt, startToEnd, timeOfImpact);
  7503. vec2.add(this.position, this.position, integrate_velodt);
  7504. if(!this.fixedRotation){
  7505. this.angle += startToEndAngle * timeOfImpact;
  7506. }
  7507. return true;
  7508. };
  7509. /**
  7510. * Get velocity of a point in the body.
  7511. * @method getVelocityAtPoint
  7512. * @param {Array} result A vector to store the result in
  7513. * @param {Array} relativePoint A world oriented vector, indicating the position of the point to get the velocity from
  7514. * @return {Array} The result vector
  7515. */
  7516. Body.prototype.getVelocityAtPoint = function(result, relativePoint){
  7517. vec2.crossVZ(result, relativePoint, this.angularVelocity);
  7518. vec2.subtract(result, this.velocity, result);
  7519. return result;
  7520. };
  7521. /**
  7522. * @event sleepy
  7523. */
  7524. Body.sleepyEvent = {
  7525. type: "sleepy"
  7526. };
  7527. /**
  7528. * @event sleep
  7529. */
  7530. Body.sleepEvent = {
  7531. type: "sleep"
  7532. };
  7533. /**
  7534. * @event wakeup
  7535. */
  7536. Body.wakeUpEvent = {
  7537. type: "wakeup"
  7538. };
  7539. /**
  7540. * Dynamic body.
  7541. * @property DYNAMIC
  7542. * @type {Number}
  7543. * @static
  7544. */
  7545. Body.DYNAMIC = 1;
  7546. /**
  7547. * Static body.
  7548. * @property STATIC
  7549. * @type {Number}
  7550. * @static
  7551. */
  7552. Body.STATIC = 2;
  7553. /**
  7554. * Kinematic body.
  7555. * @property KINEMATIC
  7556. * @type {Number}
  7557. * @static
  7558. */
  7559. Body.KINEMATIC = 4;
  7560. /**
  7561. * @property AWAKE
  7562. * @type {Number}
  7563. * @static
  7564. */
  7565. Body.AWAKE = 0;
  7566. /**
  7567. * @property SLEEPY
  7568. * @type {Number}
  7569. * @static
  7570. */
  7571. Body.SLEEPY = 1;
  7572. /**
  7573. * @property SLEEPING
  7574. * @type {Number}
  7575. * @static
  7576. */
  7577. Body.SLEEPING = 2;
  7578. },{"../collision/AABB":7,"../collision/Ray":11,"../collision/RaycastResult":12,"../events/EventEmitter":26,"../math/vec2":30,"../shapes/Convex":40,"poly-decomp":5}],32:[function(_dereq_,module,exports){
  7579. var vec2 = _dereq_('../math/vec2');
  7580. var Spring = _dereq_('./Spring');
  7581. var Utils = _dereq_('../utils/Utils');
  7582. module.exports = LinearSpring;
  7583. /**
  7584. * A spring, connecting two bodies.
  7585. *
  7586. * The Spring explicitly adds force and angularForce to the bodies.
  7587. *
  7588. * @class LinearSpring
  7589. * @extends Spring
  7590. * @constructor
  7591. * @param {Body} bodyA
  7592. * @param {Body} bodyB
  7593. * @param {Object} [options]
  7594. * @param {number} [options.restLength] A number > 0. Default is the current distance between the world anchor points.
  7595. * @param {number} [options.stiffness=100] Spring constant (see Hookes Law). A number >= 0.
  7596. * @param {number} [options.damping=1] A number >= 0. Default: 1
  7597. * @param {Array} [options.worldAnchorA] Where to hook the spring to body A, in world coordinates. Overrides the option "localAnchorA" if given.
  7598. * @param {Array} [options.worldAnchorB]
  7599. * @param {Array} [options.localAnchorA] Where to hook the spring to body A, in local body coordinates. Defaults to the body center.
  7600. * @param {Array} [options.localAnchorB]
  7601. */
  7602. function LinearSpring(bodyA,bodyB,options){
  7603. options = options || {};
  7604. Spring.call(this, bodyA, bodyB, options);
  7605. /**
  7606. * Anchor for bodyA in local bodyA coordinates.
  7607. * @property localAnchorA
  7608. * @type {Array}
  7609. */
  7610. this.localAnchorA = vec2.fromValues(0,0);
  7611. /**
  7612. * Anchor for bodyB in local bodyB coordinates.
  7613. * @property localAnchorB
  7614. * @type {Array}
  7615. */
  7616. this.localAnchorB = vec2.fromValues(0,0);
  7617. if(options.localAnchorA){ vec2.copy(this.localAnchorA, options.localAnchorA); }
  7618. if(options.localAnchorB){ vec2.copy(this.localAnchorB, options.localAnchorB); }
  7619. if(options.worldAnchorA){ this.setWorldAnchorA(options.worldAnchorA); }
  7620. if(options.worldAnchorB){ this.setWorldAnchorB(options.worldAnchorB); }
  7621. var worldAnchorA = vec2.create();
  7622. var worldAnchorB = vec2.create();
  7623. this.getWorldAnchorA(worldAnchorA);
  7624. this.getWorldAnchorB(worldAnchorB);
  7625. var worldDistance = vec2.distance(worldAnchorA, worldAnchorB);
  7626. /**
  7627. * Rest length of the spring.
  7628. * @property restLength
  7629. * @type {number}
  7630. */
  7631. this.restLength = typeof(options.restLength) === "number" ? options.restLength : worldDistance;
  7632. }
  7633. LinearSpring.prototype = new Spring();
  7634. LinearSpring.prototype.constructor = LinearSpring;
  7635. /**
  7636. * Set the anchor point on body A, using world coordinates.
  7637. * @method setWorldAnchorA
  7638. * @param {Array} worldAnchorA
  7639. */
  7640. LinearSpring.prototype.setWorldAnchorA = function(worldAnchorA){
  7641. this.bodyA.toLocalFrame(this.localAnchorA, worldAnchorA);
  7642. };
  7643. /**
  7644. * Set the anchor point on body B, using world coordinates.
  7645. * @method setWorldAnchorB
  7646. * @param {Array} worldAnchorB
  7647. */
  7648. LinearSpring.prototype.setWorldAnchorB = function(worldAnchorB){
  7649. this.bodyB.toLocalFrame(this.localAnchorB, worldAnchorB);
  7650. };
  7651. /**
  7652. * Get the anchor point on body A, in world coordinates.
  7653. * @method getWorldAnchorA
  7654. * @param {Array} result The vector to store the result in.
  7655. */
  7656. LinearSpring.prototype.getWorldAnchorA = function(result){
  7657. this.bodyA.toWorldFrame(result, this.localAnchorA);
  7658. };
  7659. /**
  7660. * Get the anchor point on body B, in world coordinates.
  7661. * @method getWorldAnchorB
  7662. * @param {Array} result The vector to store the result in.
  7663. */
  7664. LinearSpring.prototype.getWorldAnchorB = function(result){
  7665. this.bodyB.toWorldFrame(result, this.localAnchorB);
  7666. };
  7667. var applyForce_r = vec2.create(),
  7668. applyForce_r_unit = vec2.create(),
  7669. applyForce_u = vec2.create(),
  7670. applyForce_f = vec2.create(),
  7671. applyForce_worldAnchorA = vec2.create(),
  7672. applyForce_worldAnchorB = vec2.create(),
  7673. applyForce_ri = vec2.create(),
  7674. applyForce_rj = vec2.create(),
  7675. applyForce_tmp = vec2.create();
  7676. /**
  7677. * Apply the spring force to the connected bodies.
  7678. * @method applyForce
  7679. */
  7680. LinearSpring.prototype.applyForce = function(){
  7681. var k = this.stiffness,
  7682. d = this.damping,
  7683. l = this.restLength,
  7684. bodyA = this.bodyA,
  7685. bodyB = this.bodyB,
  7686. r = applyForce_r,
  7687. r_unit = applyForce_r_unit,
  7688. u = applyForce_u,
  7689. f = applyForce_f,
  7690. tmp = applyForce_tmp;
  7691. var worldAnchorA = applyForce_worldAnchorA,
  7692. worldAnchorB = applyForce_worldAnchorB,
  7693. ri = applyForce_ri,
  7694. rj = applyForce_rj;
  7695. // Get world anchors
  7696. this.getWorldAnchorA(worldAnchorA);
  7697. this.getWorldAnchorB(worldAnchorB);
  7698. // Get offset points
  7699. vec2.sub(ri, worldAnchorA, bodyA.position);
  7700. vec2.sub(rj, worldAnchorB, bodyB.position);
  7701. // Compute distance vector between world anchor points
  7702. vec2.sub(r, worldAnchorB, worldAnchorA);
  7703. var rlen = vec2.len(r);
  7704. vec2.normalize(r_unit,r);
  7705. //console.log(rlen)
  7706. //console.log("A",vec2.str(worldAnchorA),"B",vec2.str(worldAnchorB))
  7707. // Compute relative velocity of the anchor points, u
  7708. vec2.sub(u, bodyB.velocity, bodyA.velocity);
  7709. vec2.crossZV(tmp, bodyB.angularVelocity, rj);
  7710. vec2.add(u, u, tmp);
  7711. vec2.crossZV(tmp, bodyA.angularVelocity, ri);
  7712. vec2.sub(u, u, tmp);
  7713. // F = - k * ( x - L ) - D * ( u )
  7714. vec2.scale(f, r_unit, -k*(rlen-l) - d*vec2.dot(u,r_unit));
  7715. // Add forces to bodies
  7716. vec2.sub( bodyA.force, bodyA.force, f);
  7717. vec2.add( bodyB.force, bodyB.force, f);
  7718. // Angular force
  7719. var ri_x_f = vec2.crossLength(ri, f);
  7720. var rj_x_f = vec2.crossLength(rj, f);
  7721. bodyA.angularForce -= ri_x_f;
  7722. bodyB.angularForce += rj_x_f;
  7723. };
  7724. },{"../math/vec2":30,"../utils/Utils":57,"./Spring":34}],33:[function(_dereq_,module,exports){
  7725. var vec2 = _dereq_('../math/vec2');
  7726. var Spring = _dereq_('./Spring');
  7727. module.exports = RotationalSpring;
  7728. /**
  7729. * A rotational spring, connecting two bodies rotation. This spring explicitly adds angularForce (torque) to the bodies.
  7730. *
  7731. * The spring can be combined with a {{#crossLink "RevoluteConstraint"}}{{/crossLink}} to make, for example, a mouse trap.
  7732. *
  7733. * @class RotationalSpring
  7734. * @extends Spring
  7735. * @constructor
  7736. * @param {Body} bodyA
  7737. * @param {Body} bodyB
  7738. * @param {Object} [options]
  7739. * @param {number} [options.restAngle] The relative angle of bodies at which the spring is at rest. If not given, it's set to the current relative angle between the bodies.
  7740. * @param {number} [options.stiffness=100] Spring constant (see Hookes Law). A number >= 0.
  7741. * @param {number} [options.damping=1] A number >= 0.
  7742. */
  7743. function RotationalSpring(bodyA, bodyB, options){
  7744. options = options || {};
  7745. Spring.call(this, bodyA, bodyB, options);
  7746. /**
  7747. * Rest angle of the spring.
  7748. * @property restAngle
  7749. * @type {number}
  7750. */
  7751. this.restAngle = typeof(options.restAngle) === "number" ? options.restAngle : bodyB.angle - bodyA.angle;
  7752. }
  7753. RotationalSpring.prototype = new Spring();
  7754. RotationalSpring.prototype.constructor = RotationalSpring;
  7755. /**
  7756. * Apply the spring force to the connected bodies.
  7757. * @method applyForce
  7758. */
  7759. RotationalSpring.prototype.applyForce = function(){
  7760. var k = this.stiffness,
  7761. d = this.damping,
  7762. l = this.restAngle,
  7763. bodyA = this.bodyA,
  7764. bodyB = this.bodyB,
  7765. x = bodyB.angle - bodyA.angle,
  7766. u = bodyB.angularVelocity - bodyA.angularVelocity;
  7767. var torque = - k * (x - l) - d * u * 0;
  7768. bodyA.angularForce -= torque;
  7769. bodyB.angularForce += torque;
  7770. };
  7771. },{"../math/vec2":30,"./Spring":34}],34:[function(_dereq_,module,exports){
  7772. var vec2 = _dereq_('../math/vec2');
  7773. var Utils = _dereq_('../utils/Utils');
  7774. module.exports = Spring;
  7775. /**
  7776. * A spring, connecting two bodies. The Spring explicitly adds force and angularForce to the bodies and does therefore not put load on the constraint solver.
  7777. *
  7778. * @class Spring
  7779. * @constructor
  7780. * @param {Body} bodyA
  7781. * @param {Body} bodyB
  7782. * @param {Object} [options]
  7783. * @param {number} [options.stiffness=100] Spring constant (see Hookes Law). A number >= 0.
  7784. * @param {number} [options.damping=1] A number >= 0. Default: 1
  7785. * @param {Array} [options.localAnchorA] Where to hook the spring to body A, in local body coordinates. Defaults to the body center.
  7786. * @param {Array} [options.localAnchorB]
  7787. * @param {Array} [options.worldAnchorA] Where to hook the spring to body A, in world coordinates. Overrides the option "localAnchorA" if given.
  7788. * @param {Array} [options.worldAnchorB]
  7789. */
  7790. function Spring(bodyA, bodyB, options){
  7791. options = Utils.defaults(options,{
  7792. stiffness: 100,
  7793. damping: 1,
  7794. });
  7795. /**
  7796. * Stiffness of the spring.
  7797. * @property stiffness
  7798. * @type {number}
  7799. */
  7800. this.stiffness = options.stiffness;
  7801. /**
  7802. * Damping of the spring.
  7803. * @property damping
  7804. * @type {number}
  7805. */
  7806. this.damping = options.damping;
  7807. /**
  7808. * First connected body.
  7809. * @property bodyA
  7810. * @type {Body}
  7811. */
  7812. this.bodyA = bodyA;
  7813. /**
  7814. * Second connected body.
  7815. * @property bodyB
  7816. * @type {Body}
  7817. */
  7818. this.bodyB = bodyB;
  7819. }
  7820. /**
  7821. * Apply the spring force to the connected bodies.
  7822. * @method applyForce
  7823. */
  7824. Spring.prototype.applyForce = function(){
  7825. // To be implemented by subclasses
  7826. };
  7827. },{"../math/vec2":30,"../utils/Utils":57}],35:[function(_dereq_,module,exports){
  7828. var vec2 = _dereq_('../math/vec2');
  7829. var Utils = _dereq_('../utils/Utils');
  7830. var Constraint = _dereq_('../constraints/Constraint');
  7831. var FrictionEquation = _dereq_('../equations/FrictionEquation');
  7832. var Body = _dereq_('../objects/Body');
  7833. module.exports = TopDownVehicle;
  7834. /**
  7835. * @class TopDownVehicle
  7836. * @constructor
  7837. * @param {Body} chassisBody A dynamic body, already added to the world.
  7838. * @param {Object} [options]
  7839. *
  7840. * @example
  7841. *
  7842. * // Create a dynamic body for the chassis
  7843. * var chassisBody = new Body({
  7844. * mass: 1
  7845. * });
  7846. * var boxShape = new Box({ width: 0.5, height: 1 });
  7847. * chassisBody.addShape(boxShape);
  7848. * world.addBody(chassisBody);
  7849. *
  7850. * // Create the vehicle
  7851. * var vehicle = new TopDownVehicle(chassisBody);
  7852. *
  7853. * // Add one front wheel and one back wheel - we don't actually need four :)
  7854. * var frontWheel = vehicle.addWheel({
  7855. * localPosition: [0, 0.5] // front
  7856. * });
  7857. * frontWheel.setSideFriction(4);
  7858. *
  7859. * // Back wheel
  7860. * var backWheel = vehicle.addWheel({
  7861. * localPosition: [0, -0.5] // back
  7862. * });
  7863. * backWheel.setSideFriction(3); // Less side friction on back wheel makes it easier to drift
  7864. * vehicle.addToWorld(world);
  7865. *
  7866. * // Steer value zero means straight forward. Positive is left and negative right.
  7867. * frontWheel.steerValue = Math.PI / 16;
  7868. *
  7869. * // Engine force forward
  7870. * backWheel.engineForce = 10;
  7871. * backWheel.setBrakeForce(0);
  7872. */
  7873. function TopDownVehicle(chassisBody, options){
  7874. options = options || {};
  7875. /**
  7876. * @property {Body} chassisBody
  7877. */
  7878. this.chassisBody = chassisBody;
  7879. /**
  7880. * @property {Array} wheels
  7881. */
  7882. this.wheels = [];
  7883. // A dummy body to constrain the chassis to
  7884. this.groundBody = new Body({ mass: 0 });
  7885. this.world = null;
  7886. var that = this;
  7887. this.preStepCallback = function(){
  7888. that.update();
  7889. };
  7890. }
  7891. /**
  7892. * @method addToWorld
  7893. * @param {World} world
  7894. */
  7895. TopDownVehicle.prototype.addToWorld = function(world){
  7896. this.world = world;
  7897. world.addBody(this.groundBody);
  7898. world.on('preStep', this.preStepCallback);
  7899. for (var i = 0; i < this.wheels.length; i++) {
  7900. var wheel = this.wheels[i];
  7901. world.addConstraint(wheel);
  7902. }
  7903. };
  7904. /**
  7905. * @method removeFromWorld
  7906. * @param {World} world
  7907. */
  7908. TopDownVehicle.prototype.removeFromWorld = function(){
  7909. var world = this.world;
  7910. world.removeBody(this.groundBody);
  7911. world.off('preStep', this.preStepCallback);
  7912. for (var i = 0; i < this.wheels.length; i++) {
  7913. var wheel = this.wheels[i];
  7914. world.removeConstraint(wheel);
  7915. }
  7916. this.world = null;
  7917. };
  7918. /**
  7919. * @method addWheel
  7920. * @param {object} [wheelOptions]
  7921. * @return {WheelConstraint}
  7922. */
  7923. TopDownVehicle.prototype.addWheel = function(wheelOptions){
  7924. var wheel = new WheelConstraint(this,wheelOptions);
  7925. this.wheels.push(wheel);
  7926. return wheel;
  7927. };
  7928. /**
  7929. * @method update
  7930. */
  7931. TopDownVehicle.prototype.update = function(){
  7932. for (var i = 0; i < this.wheels.length; i++) {
  7933. this.wheels[i].update();
  7934. }
  7935. };
  7936. /**
  7937. * @class WheelConstraint
  7938. * @constructor
  7939. * @extends {Constraint}
  7940. * @param {Vehicle} vehicle
  7941. * @param {object} [options]
  7942. * @param {Array} [options.localForwardVector]The local wheel forward vector in local body space. Default is zero.
  7943. * @param {Array} [options.localPosition] The local position of the wheen in the chassis body. Default is zero - the center of the body.
  7944. * @param {Array} [options.sideFriction=5] The max friction force in the sideways direction.
  7945. */
  7946. function WheelConstraint(vehicle, options){
  7947. options = options || {};
  7948. this.vehicle = vehicle;
  7949. this.forwardEquation = new FrictionEquation(vehicle.chassisBody, vehicle.groundBody);
  7950. this.sideEquation = new FrictionEquation(vehicle.chassisBody, vehicle.groundBody);
  7951. /**
  7952. * @property {number} steerValue
  7953. */
  7954. this.steerValue = 0;
  7955. /**
  7956. * @property {number} engineForce
  7957. */
  7958. this.engineForce = 0;
  7959. this.setSideFriction(options.sideFriction !== undefined ? options.sideFriction : 5);
  7960. /**
  7961. * @property {Array} localForwardVector
  7962. */
  7963. this.localForwardVector = vec2.fromValues(0, 1);
  7964. if(options.localForwardVector){
  7965. vec2.copy(this.localForwardVector, options.localForwardVector);
  7966. }
  7967. /**
  7968. * @property {Array} localPosition
  7969. */
  7970. this.localPosition = vec2.fromValues(0, 0);
  7971. if(options.localPosition){
  7972. vec2.copy(this.localPosition, options.localPosition);
  7973. }
  7974. Constraint.apply(this, vehicle.chassisBody, vehicle.groundBody);
  7975. this.equations.push(
  7976. this.forwardEquation,
  7977. this.sideEquation
  7978. );
  7979. this.setBrakeForce(0);
  7980. }
  7981. WheelConstraint.prototype = new Constraint();
  7982. /**
  7983. * @method setForwardFriction
  7984. */
  7985. WheelConstraint.prototype.setBrakeForce = function(force){
  7986. this.forwardEquation.setSlipForce(force);
  7987. };
  7988. /**
  7989. * @method setSideFriction
  7990. */
  7991. WheelConstraint.prototype.setSideFriction = function(force){
  7992. this.sideEquation.setSlipForce(force);
  7993. };
  7994. var worldVelocity = vec2.create();
  7995. var relativePoint = vec2.create();
  7996. /**
  7997. * @method getSpeed
  7998. */
  7999. WheelConstraint.prototype.getSpeed = function(){
  8000. this.vehicle.chassisBody.vectorToWorldFrame(relativePoint, this.localForwardVector);
  8001. this.vehicle.chassisBody.getVelocityAtPoint(worldVelocity, relativePoint);
  8002. return vec2.dot(worldVelocity, relativePoint);
  8003. };
  8004. var tmpVec = vec2.create();
  8005. /**
  8006. * @method update
  8007. */
  8008. WheelConstraint.prototype.update = function(){
  8009. // Directional
  8010. this.vehicle.chassisBody.vectorToWorldFrame(this.forwardEquation.t, this.localForwardVector);
  8011. vec2.rotate(this.sideEquation.t, this.localForwardVector, Math.PI / 2);
  8012. this.vehicle.chassisBody.vectorToWorldFrame(this.sideEquation.t, this.sideEquation.t);
  8013. vec2.rotate(this.forwardEquation.t, this.forwardEquation.t, this.steerValue);
  8014. vec2.rotate(this.sideEquation.t, this.sideEquation.t, this.steerValue);
  8015. // Attachment point
  8016. this.vehicle.chassisBody.toWorldFrame(this.forwardEquation.contactPointB, this.localPosition);
  8017. vec2.copy(this.sideEquation.contactPointB, this.forwardEquation.contactPointB);
  8018. this.vehicle.chassisBody.vectorToWorldFrame(this.forwardEquation.contactPointA, this.localPosition);
  8019. vec2.copy(this.sideEquation.contactPointA, this.forwardEquation.contactPointA);
  8020. // Add engine force
  8021. vec2.normalize(tmpVec, this.forwardEquation.t);
  8022. vec2.scale(tmpVec, tmpVec, this.engineForce);
  8023. this.vehicle.chassisBody.applyForce(tmpVec, this.forwardEquation.contactPointA);
  8024. };
  8025. },{"../constraints/Constraint":14,"../equations/FrictionEquation":23,"../math/vec2":30,"../objects/Body":31,"../utils/Utils":57}],36:[function(_dereq_,module,exports){
  8026. // Export p2 classes
  8027. var p2 = module.exports = {
  8028. AABB : _dereq_('./collision/AABB'),
  8029. AngleLockEquation : _dereq_('./equations/AngleLockEquation'),
  8030. Body : _dereq_('./objects/Body'),
  8031. Broadphase : _dereq_('./collision/Broadphase'),
  8032. Capsule : _dereq_('./shapes/Capsule'),
  8033. Circle : _dereq_('./shapes/Circle'),
  8034. Constraint : _dereq_('./constraints/Constraint'),
  8035. ContactEquation : _dereq_('./equations/ContactEquation'),
  8036. ContactEquationPool : _dereq_('./utils/ContactEquationPool'),
  8037. ContactMaterial : _dereq_('./material/ContactMaterial'),
  8038. Convex : _dereq_('./shapes/Convex'),
  8039. DistanceConstraint : _dereq_('./constraints/DistanceConstraint'),
  8040. Equation : _dereq_('./equations/Equation'),
  8041. EventEmitter : _dereq_('./events/EventEmitter'),
  8042. FrictionEquation : _dereq_('./equations/FrictionEquation'),
  8043. FrictionEquationPool : _dereq_('./utils/FrictionEquationPool'),
  8044. GearConstraint : _dereq_('./constraints/GearConstraint'),
  8045. GSSolver : _dereq_('./solver/GSSolver'),
  8046. Heightfield : _dereq_('./shapes/Heightfield'),
  8047. Line : _dereq_('./shapes/Line'),
  8048. LockConstraint : _dereq_('./constraints/LockConstraint'),
  8049. Material : _dereq_('./material/Material'),
  8050. Narrowphase : _dereq_('./collision/Narrowphase'),
  8051. NaiveBroadphase : _dereq_('./collision/NaiveBroadphase'),
  8052. Particle : _dereq_('./shapes/Particle'),
  8053. Plane : _dereq_('./shapes/Plane'),
  8054. Pool : _dereq_('./utils/Pool'),
  8055. RevoluteConstraint : _dereq_('./constraints/RevoluteConstraint'),
  8056. PrismaticConstraint : _dereq_('./constraints/PrismaticConstraint'),
  8057. Ray : _dereq_('./collision/Ray'),
  8058. RaycastResult : _dereq_('./collision/RaycastResult'),
  8059. Box : _dereq_('./shapes/Box'),
  8060. RotationalVelocityEquation : _dereq_('./equations/RotationalVelocityEquation'),
  8061. SAPBroadphase : _dereq_('./collision/SAPBroadphase'),
  8062. Shape : _dereq_('./shapes/Shape'),
  8063. Solver : _dereq_('./solver/Solver'),
  8064. Spring : _dereq_('./objects/Spring'),
  8065. TopDownVehicle : _dereq_('./objects/TopDownVehicle'),
  8066. LinearSpring : _dereq_('./objects/LinearSpring'),
  8067. RotationalSpring : _dereq_('./objects/RotationalSpring'),
  8068. Utils : _dereq_('./utils/Utils'),
  8069. World : _dereq_('./world/World'),
  8070. vec2 : _dereq_('./math/vec2'),
  8071. version : _dereq_('../package.json').version,
  8072. };
  8073. Object.defineProperty(p2, 'Rectangle', {
  8074. get: function() {
  8075. console.warn('The Rectangle class has been renamed to Box.');
  8076. return this.Box;
  8077. }
  8078. });
  8079. },{"../package.json":6,"./collision/AABB":7,"./collision/Broadphase":8,"./collision/NaiveBroadphase":9,"./collision/Narrowphase":10,"./collision/Ray":11,"./collision/RaycastResult":12,"./collision/SAPBroadphase":13,"./constraints/Constraint":14,"./constraints/DistanceConstraint":15,"./constraints/GearConstraint":16,"./constraints/LockConstraint":17,"./constraints/PrismaticConstraint":18,"./constraints/RevoluteConstraint":19,"./equations/AngleLockEquation":20,"./equations/ContactEquation":21,"./equations/Equation":22,"./equations/FrictionEquation":23,"./equations/RotationalVelocityEquation":25,"./events/EventEmitter":26,"./material/ContactMaterial":27,"./material/Material":28,"./math/vec2":30,"./objects/Body":31,"./objects/LinearSpring":32,"./objects/RotationalSpring":33,"./objects/Spring":34,"./objects/TopDownVehicle":35,"./shapes/Box":37,"./shapes/Capsule":38,"./shapes/Circle":39,"./shapes/Convex":40,"./shapes/Heightfield":41,"./shapes/Line":42,"./shapes/Particle":43,"./shapes/Plane":44,"./shapes/Shape":45,"./solver/GSSolver":46,"./solver/Solver":47,"./utils/ContactEquationPool":48,"./utils/FrictionEquationPool":49,"./utils/Pool":55,"./utils/Utils":57,"./world/World":61}],37:[function(_dereq_,module,exports){
  8080. var vec2 = _dereq_('../math/vec2')
  8081. , Shape = _dereq_('./Shape')
  8082. , Convex = _dereq_('./Convex');
  8083. module.exports = Box;
  8084. /**
  8085. * Box shape class.
  8086. * @class Box
  8087. * @constructor
  8088. * @param {object} [options] (Note that this options object will be passed on to the {{#crossLink "Shape"}}{{/crossLink}} constructor.)
  8089. * @param {Number} [options.width=1] Total width of the box
  8090. * @param {Number} [options.height=1] Total height of the box
  8091. * @extends Convex
  8092. */
  8093. function Box(options){
  8094. if(typeof(arguments[0]) === 'number' && typeof(arguments[1]) === 'number'){
  8095. options = {
  8096. width: arguments[0],
  8097. height: arguments[1]
  8098. };
  8099. console.warn('The Rectangle has been renamed to Box and its constructor signature has changed. Please use the following format: new Box({ width: 1, height: 1, ... })');
  8100. }
  8101. options = options || {};
  8102. /**
  8103. * Total width of the box
  8104. * @property width
  8105. * @type {Number}
  8106. */
  8107. var width = this.width = options.width || 1;
  8108. /**
  8109. * Total height of the box
  8110. * @property height
  8111. * @type {Number}
  8112. */
  8113. var height = this.height = options.height || 1;
  8114. var verts = [
  8115. vec2.fromValues(-width/2, -height/2),
  8116. vec2.fromValues( width/2, -height/2),
  8117. vec2.fromValues( width/2, height/2),
  8118. vec2.fromValues(-width/2, height/2)
  8119. ];
  8120. var axes = [
  8121. vec2.fromValues(1, 0),
  8122. vec2.fromValues(0, 1)
  8123. ];
  8124. options.vertices = verts;
  8125. options.axes = axes;
  8126. options.type = Shape.BOX;
  8127. Convex.call(this, options);
  8128. }
  8129. Box.prototype = new Convex();
  8130. Box.prototype.constructor = Box;
  8131. /**
  8132. * Compute moment of inertia
  8133. * @method computeMomentOfInertia
  8134. * @param {Number} mass
  8135. * @return {Number}
  8136. */
  8137. Box.prototype.computeMomentOfInertia = function(mass){
  8138. var w = this.width,
  8139. h = this.height;
  8140. return mass * (h*h + w*w) / 12;
  8141. };
  8142. /**
  8143. * Update the bounding radius
  8144. * @method updateBoundingRadius
  8145. */
  8146. Box.prototype.updateBoundingRadius = function(){
  8147. var w = this.width,
  8148. h = this.height;
  8149. this.boundingRadius = Math.sqrt(w*w + h*h) / 2;
  8150. };
  8151. var corner1 = vec2.create(),
  8152. corner2 = vec2.create(),
  8153. corner3 = vec2.create(),
  8154. corner4 = vec2.create();
  8155. /**
  8156. * @method computeAABB
  8157. * @param {AABB} out The resulting AABB.
  8158. * @param {Array} position
  8159. * @param {Number} angle
  8160. */
  8161. Box.prototype.computeAABB = function(out, position, angle){
  8162. out.setFromPoints(this.vertices,position,angle,0);
  8163. };
  8164. Box.prototype.updateArea = function(){
  8165. this.area = this.width * this.height;
  8166. };
  8167. },{"../math/vec2":30,"./Convex":40,"./Shape":45}],38:[function(_dereq_,module,exports){
  8168. var Shape = _dereq_('./Shape')
  8169. , vec2 = _dereq_('../math/vec2');
  8170. module.exports = Capsule;
  8171. /**
  8172. * Capsule shape class.
  8173. * @class Capsule
  8174. * @constructor
  8175. * @extends Shape
  8176. * @param {object} [options] (Note that this options object will be passed on to the {{#crossLink "Shape"}}{{/crossLink}} constructor.)
  8177. * @param {Number} [options.length=1] The distance between the end points
  8178. * @param {Number} [options.radius=1] Radius of the capsule
  8179. * @example
  8180. * var capsuleShape = new Capsule({
  8181. * length: 1,
  8182. * radius: 2
  8183. * });
  8184. * body.addShape(capsuleShape);
  8185. */
  8186. function Capsule(options){
  8187. if(typeof(arguments[0]) === 'number' && typeof(arguments[1]) === 'number'){
  8188. options = {
  8189. length: arguments[0],
  8190. radius: arguments[1]
  8191. };
  8192. console.warn('The Capsule constructor signature has changed. Please use the following format: new Capsule({ radius: 1, length: 1 })');
  8193. }
  8194. options = options || {};
  8195. /**
  8196. * The distance between the end points.
  8197. * @property {Number} length
  8198. */
  8199. this.length = options.length || 1;
  8200. /**
  8201. * The radius of the capsule.
  8202. * @property {Number} radius
  8203. */
  8204. this.radius = options.radius || 1;
  8205. options.type = Shape.CAPSULE;
  8206. Shape.call(this, options);
  8207. }
  8208. Capsule.prototype = new Shape();
  8209. Capsule.prototype.constructor = Capsule;
  8210. /**
  8211. * Compute the mass moment of inertia of the Capsule.
  8212. * @method conputeMomentOfInertia
  8213. * @param {Number} mass
  8214. * @return {Number}
  8215. * @todo
  8216. */
  8217. Capsule.prototype.computeMomentOfInertia = function(mass){
  8218. // Approximate with rectangle
  8219. var r = this.radius,
  8220. w = this.length + r, // 2*r is too much, 0 is too little
  8221. h = r*2;
  8222. return mass * (h*h + w*w) / 12;
  8223. };
  8224. /**
  8225. * @method updateBoundingRadius
  8226. */
  8227. Capsule.prototype.updateBoundingRadius = function(){
  8228. this.boundingRadius = this.radius + this.length/2;
  8229. };
  8230. /**
  8231. * @method updateArea
  8232. */
  8233. Capsule.prototype.updateArea = function(){
  8234. this.area = Math.PI * this.radius * this.radius + this.radius * 2 * this.length;
  8235. };
  8236. var r = vec2.create();
  8237. /**
  8238. * @method computeAABB
  8239. * @param {AABB} out The resulting AABB.
  8240. * @param {Array} position
  8241. * @param {Number} angle
  8242. */
  8243. Capsule.prototype.computeAABB = function(out, position, angle){
  8244. var radius = this.radius;
  8245. // Compute center position of one of the the circles, world oriented, but with local offset
  8246. vec2.set(r,this.length / 2,0);
  8247. if(angle !== 0){
  8248. vec2.rotate(r,r,angle);
  8249. }
  8250. // Get bounds
  8251. vec2.set(out.upperBound, Math.max(r[0]+radius, -r[0]+radius),
  8252. Math.max(r[1]+radius, -r[1]+radius));
  8253. vec2.set(out.lowerBound, Math.min(r[0]-radius, -r[0]-radius),
  8254. Math.min(r[1]-radius, -r[1]-radius));
  8255. // Add offset
  8256. vec2.add(out.lowerBound, out.lowerBound, position);
  8257. vec2.add(out.upperBound, out.upperBound, position);
  8258. };
  8259. var intersectCapsule_hitPointWorld = vec2.create();
  8260. var intersectCapsule_normal = vec2.create();
  8261. var intersectCapsule_l0 = vec2.create();
  8262. var intersectCapsule_l1 = vec2.create();
  8263. var intersectCapsule_unit_y = vec2.fromValues(0,1);
  8264. /**
  8265. * @method raycast
  8266. * @param {RaycastResult} result
  8267. * @param {Ray} ray
  8268. * @param {array} position
  8269. * @param {number} angle
  8270. */
  8271. Capsule.prototype.raycast = function(result, ray, position, angle){
  8272. var from = ray.from;
  8273. var to = ray.to;
  8274. var direction = ray.direction;
  8275. var hitPointWorld = intersectCapsule_hitPointWorld;
  8276. var normal = intersectCapsule_normal;
  8277. var l0 = intersectCapsule_l0;
  8278. var l1 = intersectCapsule_l1;
  8279. // The sides
  8280. var halfLen = this.length / 2;
  8281. for(var i=0; i<2; i++){
  8282. // get start and end of the line
  8283. var y = this.radius * (i*2-1);
  8284. vec2.set(l0, -halfLen, y);
  8285. vec2.set(l1, halfLen, y);
  8286. vec2.toGlobalFrame(l0, l0, position, angle);
  8287. vec2.toGlobalFrame(l1, l1, position, angle);
  8288. var delta = vec2.getLineSegmentsIntersectionFraction(from, to, l0, l1);
  8289. if(delta >= 0){
  8290. vec2.rotate(normal, intersectCapsule_unit_y, angle);
  8291. vec2.scale(normal, normal, (i*2-1));
  8292. ray.reportIntersection(result, delta, normal, -1);
  8293. if(result.shouldStop(ray)){
  8294. return;
  8295. }
  8296. }
  8297. }
  8298. // Circles
  8299. var diagonalLengthSquared = Math.pow(this.radius, 2) + Math.pow(halfLen, 2);
  8300. for(var i=0; i<2; i++){
  8301. vec2.set(l0, halfLen * (i*2-1), 0);
  8302. vec2.toGlobalFrame(l0, l0, position, angle);
  8303. var a = Math.pow(to[0] - from[0], 2) + Math.pow(to[1] - from[1], 2);
  8304. var b = 2 * ((to[0] - from[0]) * (from[0] - l0[0]) + (to[1] - from[1]) * (from[1] - l0[1]));
  8305. var c = Math.pow(from[0] - l0[0], 2) + Math.pow(from[1] - l0[1], 2) - Math.pow(this.radius, 2);
  8306. var delta = Math.pow(b, 2) - 4 * a * c;
  8307. if(delta < 0){
  8308. // No intersection
  8309. continue;
  8310. } else if(delta === 0){
  8311. // single intersection point
  8312. vec2.lerp(hitPointWorld, from, to, delta);
  8313. if(vec2.squaredDistance(hitPointWorld, position) > diagonalLengthSquared){
  8314. vec2.sub(normal, hitPointWorld, l0);
  8315. vec2.normalize(normal,normal);
  8316. ray.reportIntersection(result, delta, normal, -1);
  8317. if(result.shouldStop(ray)){
  8318. return;
  8319. }
  8320. }
  8321. } else {
  8322. var sqrtDelta = Math.sqrt(delta);
  8323. var inv2a = 1 / (2 * a);
  8324. var d1 = (- b - sqrtDelta) * inv2a;
  8325. var d2 = (- b + sqrtDelta) * inv2a;
  8326. if(d1 >= 0 && d1 <= 1){
  8327. vec2.lerp(hitPointWorld, from, to, d1);
  8328. if(vec2.squaredDistance(hitPointWorld, position) > diagonalLengthSquared){
  8329. vec2.sub(normal, hitPointWorld, l0);
  8330. vec2.normalize(normal,normal);
  8331. ray.reportIntersection(result, d1, normal, -1);
  8332. if(result.shouldStop(ray)){
  8333. return;
  8334. }
  8335. }
  8336. }
  8337. if(d2 >= 0 && d2 <= 1){
  8338. vec2.lerp(hitPointWorld, from, to, d2);
  8339. if(vec2.squaredDistance(hitPointWorld, position) > diagonalLengthSquared){
  8340. vec2.sub(normal, hitPointWorld, l0);
  8341. vec2.normalize(normal,normal);
  8342. ray.reportIntersection(result, d2, normal, -1);
  8343. if(result.shouldStop(ray)){
  8344. return;
  8345. }
  8346. }
  8347. }
  8348. }
  8349. }
  8350. };
  8351. },{"../math/vec2":30,"./Shape":45}],39:[function(_dereq_,module,exports){
  8352. var Shape = _dereq_('./Shape')
  8353. , vec2 = _dereq_('../math/vec2');
  8354. module.exports = Circle;
  8355. /**
  8356. * Circle shape class.
  8357. * @class Circle
  8358. * @extends Shape
  8359. * @constructor
  8360. * @param {options} [options] (Note that this options object will be passed on to the {{#crossLink "Shape"}}{{/crossLink}} constructor.)
  8361. * @param {number} [options.radius=1] The radius of this circle
  8362. *
  8363. * @example
  8364. * var circleShape = new Circle({ radius: 1 });
  8365. * body.addShape(circleShape);
  8366. */
  8367. function Circle(options){
  8368. if(typeof(arguments[0]) === 'number'){
  8369. options = {
  8370. radius: arguments[0]
  8371. };
  8372. console.warn('The Circle constructor signature has changed. Please use the following format: new Circle({ radius: 1 })');
  8373. }
  8374. options = options || {};
  8375. /**
  8376. * The radius of the circle.
  8377. * @property radius
  8378. * @type {number}
  8379. */
  8380. this.radius = options.radius || 1;
  8381. options.type = Shape.CIRCLE;
  8382. Shape.call(this, options);
  8383. }
  8384. Circle.prototype = new Shape();
  8385. Circle.prototype.constructor = Circle;
  8386. /**
  8387. * @method computeMomentOfInertia
  8388. * @param {Number} mass
  8389. * @return {Number}
  8390. */
  8391. Circle.prototype.computeMomentOfInertia = function(mass){
  8392. var r = this.radius;
  8393. return mass * r * r / 2;
  8394. };
  8395. /**
  8396. * @method updateBoundingRadius
  8397. * @return {Number}
  8398. */
  8399. Circle.prototype.updateBoundingRadius = function(){
  8400. this.boundingRadius = this.radius;
  8401. };
  8402. /**
  8403. * @method updateArea
  8404. * @return {Number}
  8405. */
  8406. Circle.prototype.updateArea = function(){
  8407. this.area = Math.PI * this.radius * this.radius;
  8408. };
  8409. /**
  8410. * @method computeAABB
  8411. * @param {AABB} out The resulting AABB.
  8412. * @param {Array} position
  8413. * @param {Number} angle
  8414. */
  8415. Circle.prototype.computeAABB = function(out, position, angle){
  8416. var r = this.radius;
  8417. vec2.set(out.upperBound, r, r);
  8418. vec2.set(out.lowerBound, -r, -r);
  8419. if(position){
  8420. vec2.add(out.lowerBound, out.lowerBound, position);
  8421. vec2.add(out.upperBound, out.upperBound, position);
  8422. }
  8423. };
  8424. var Ray_intersectSphere_intersectionPoint = vec2.create();
  8425. var Ray_intersectSphere_normal = vec2.create();
  8426. /**
  8427. * @method raycast
  8428. * @param {RaycastResult} result
  8429. * @param {Ray} ray
  8430. * @param {array} position
  8431. * @param {number} angle
  8432. */
  8433. Circle.prototype.raycast = function(result, ray, position, angle){
  8434. var from = ray.from,
  8435. to = ray.to,
  8436. r = this.radius;
  8437. var a = Math.pow(to[0] - from[0], 2) + Math.pow(to[1] - from[1], 2);
  8438. var b = 2 * ((to[0] - from[0]) * (from[0] - position[0]) + (to[1] - from[1]) * (from[1] - position[1]));
  8439. var c = Math.pow(from[0] - position[0], 2) + Math.pow(from[1] - position[1], 2) - Math.pow(r, 2);
  8440. var delta = Math.pow(b, 2) - 4 * a * c;
  8441. var intersectionPoint = Ray_intersectSphere_intersectionPoint;
  8442. var normal = Ray_intersectSphere_normal;
  8443. if(delta < 0){
  8444. // No intersection
  8445. return;
  8446. } else if(delta === 0){
  8447. // single intersection point
  8448. vec2.lerp(intersectionPoint, from, to, delta);
  8449. vec2.sub(normal, intersectionPoint, position);
  8450. vec2.normalize(normal,normal);
  8451. ray.reportIntersection(result, delta, normal, -1);
  8452. } else {
  8453. var sqrtDelta = Math.sqrt(delta);
  8454. var inv2a = 1 / (2 * a);
  8455. var d1 = (- b - sqrtDelta) * inv2a;
  8456. var d2 = (- b + sqrtDelta) * inv2a;
  8457. if(d1 >= 0 && d1 <= 1){
  8458. vec2.lerp(intersectionPoint, from, to, d1);
  8459. vec2.sub(normal, intersectionPoint, position);
  8460. vec2.normalize(normal,normal);
  8461. ray.reportIntersection(result, d1, normal, -1);
  8462. if(result.shouldStop(ray)){
  8463. return;
  8464. }
  8465. }
  8466. if(d2 >= 0 && d2 <= 1){
  8467. vec2.lerp(intersectionPoint, from, to, d2);
  8468. vec2.sub(normal, intersectionPoint, position);
  8469. vec2.normalize(normal,normal);
  8470. ray.reportIntersection(result, d2, normal, -1);
  8471. }
  8472. }
  8473. };
  8474. },{"../math/vec2":30,"./Shape":45}],40:[function(_dereq_,module,exports){
  8475. var Shape = _dereq_('./Shape')
  8476. , vec2 = _dereq_('../math/vec2')
  8477. , polyk = _dereq_('../math/polyk')
  8478. , decomp = _dereq_('poly-decomp');
  8479. module.exports = Convex;
  8480. /**
  8481. * Convex shape class.
  8482. * @class Convex
  8483. * @constructor
  8484. * @extends Shape
  8485. * @param {object} [options] (Note that this options object will be passed on to the {{#crossLink "Shape"}}{{/crossLink}} constructor.)
  8486. * @param {Array} [options.vertices] An array of vertices that span this shape. Vertices are given in counter-clockwise (CCW) direction.
  8487. * @param {Array} [options.axes] An array of unit length vectors, representing the symmetry axes in the convex.
  8488. * @example
  8489. * // Create a box
  8490. * var vertices = [[-1,-1], [1,-1], [1,1], [-1,1]];
  8491. * var convexShape = new Convex({ vertices: vertices });
  8492. * body.addShape(convexShape);
  8493. */
  8494. function Convex(options){
  8495. if(Array.isArray(arguments[0])){
  8496. options = {
  8497. vertices: arguments[0],
  8498. axes: arguments[1]
  8499. };
  8500. console.warn('The Convex constructor signature has changed. Please use the following format: new Convex({ vertices: [...], ... })');
  8501. }
  8502. options = options || {};
  8503. /**
  8504. * Vertices defined in the local frame.
  8505. * @property vertices
  8506. * @type {Array}
  8507. */
  8508. this.vertices = [];
  8509. // Copy the verts
  8510. var vertices = options.vertices !== undefined ? options.vertices : [];
  8511. for(var i=0; i < vertices.length; i++){
  8512. var v = vec2.create();
  8513. vec2.copy(v, vertices[i]);
  8514. this.vertices.push(v);
  8515. }
  8516. /**
  8517. * Axes defined in the local frame.
  8518. * @property axes
  8519. * @type {Array}
  8520. */
  8521. this.axes = [];
  8522. if(options.axes){
  8523. // Copy the axes
  8524. for(var i=0; i < options.axes.length; i++){
  8525. var axis = vec2.create();
  8526. vec2.copy(axis, options.axes[i]);
  8527. this.axes.push(axis);
  8528. }
  8529. } else {
  8530. // Construct axes from the vertex data
  8531. for(var i = 0; i < this.vertices.length; i++){
  8532. // Get the world edge
  8533. var worldPoint0 = this.vertices[i];
  8534. var worldPoint1 = this.vertices[(i+1) % this.vertices.length];
  8535. var normal = vec2.create();
  8536. vec2.sub(normal, worldPoint1, worldPoint0);
  8537. // Get normal - just rotate 90 degrees since vertices are given in CCW
  8538. vec2.rotate90cw(normal, normal);
  8539. vec2.normalize(normal, normal);
  8540. this.axes.push(normal);
  8541. }
  8542. }
  8543. /**
  8544. * The center of mass of the Convex
  8545. * @property centerOfMass
  8546. * @type {Array}
  8547. */
  8548. this.centerOfMass = vec2.fromValues(0,0);
  8549. /**
  8550. * Triangulated version of this convex. The structure is Array of 3-Arrays, and each subarray contains 3 integers, referencing the vertices.
  8551. * @property triangles
  8552. * @type {Array}
  8553. */
  8554. this.triangles = [];
  8555. if(this.vertices.length){
  8556. this.updateTriangles();
  8557. this.updateCenterOfMass();
  8558. }
  8559. /**
  8560. * The bounding radius of the convex
  8561. * @property boundingRadius
  8562. * @type {Number}
  8563. */
  8564. this.boundingRadius = 0;
  8565. options.type = Shape.CONVEX;
  8566. Shape.call(this, options);
  8567. this.updateBoundingRadius();
  8568. this.updateArea();
  8569. if(this.area < 0){
  8570. throw new Error("Convex vertices must be given in conter-clockwise winding.");
  8571. }
  8572. }
  8573. Convex.prototype = new Shape();
  8574. Convex.prototype.constructor = Convex;
  8575. var tmpVec1 = vec2.create();
  8576. var tmpVec2 = vec2.create();
  8577. /**
  8578. * Project a Convex onto a world-oriented axis
  8579. * @method projectOntoAxis
  8580. * @static
  8581. * @param {Array} offset
  8582. * @param {Array} localAxis
  8583. * @param {Array} result
  8584. */
  8585. Convex.prototype.projectOntoLocalAxis = function(localAxis, result){
  8586. var max=null,
  8587. min=null,
  8588. v,
  8589. value,
  8590. localAxis = tmpVec1;
  8591. // Get projected position of all vertices
  8592. for(var i=0; i<this.vertices.length; i++){
  8593. v = this.vertices[i];
  8594. value = vec2.dot(v, localAxis);
  8595. if(max === null || value > max){
  8596. max = value;
  8597. }
  8598. if(min === null || value < min){
  8599. min = value;
  8600. }
  8601. }
  8602. if(min > max){
  8603. var t = min;
  8604. min = max;
  8605. max = t;
  8606. }
  8607. vec2.set(result, min, max);
  8608. };
  8609. Convex.prototype.projectOntoWorldAxis = function(localAxis, shapeOffset, shapeAngle, result){
  8610. var worldAxis = tmpVec2;
  8611. this.projectOntoLocalAxis(localAxis, result);
  8612. // Project the position of the body onto the axis - need to add this to the result
  8613. if(shapeAngle !== 0){
  8614. vec2.rotate(worldAxis, localAxis, shapeAngle);
  8615. } else {
  8616. worldAxis = localAxis;
  8617. }
  8618. var offset = vec2.dot(shapeOffset, worldAxis);
  8619. vec2.set(result, result[0] + offset, result[1] + offset);
  8620. };
  8621. /**
  8622. * Update the .triangles property
  8623. * @method updateTriangles
  8624. */
  8625. Convex.prototype.updateTriangles = function(){
  8626. this.triangles.length = 0;
  8627. // Rewrite on polyk notation, array of numbers
  8628. var polykVerts = [];
  8629. for(var i=0; i<this.vertices.length; i++){
  8630. var v = this.vertices[i];
  8631. polykVerts.push(v[0],v[1]);
  8632. }
  8633. // Triangulate
  8634. var triangles = polyk.Triangulate(polykVerts);
  8635. // Loop over all triangles, add their inertia contributions to I
  8636. for(var i=0; i<triangles.length; i+=3){
  8637. var id1 = triangles[i],
  8638. id2 = triangles[i+1],
  8639. id3 = triangles[i+2];
  8640. // Add to triangles
  8641. this.triangles.push([id1,id2,id3]);
  8642. }
  8643. };
  8644. var updateCenterOfMass_centroid = vec2.create(),
  8645. updateCenterOfMass_centroid_times_mass = vec2.create(),
  8646. updateCenterOfMass_a = vec2.create(),
  8647. updateCenterOfMass_b = vec2.create(),
  8648. updateCenterOfMass_c = vec2.create(),
  8649. updateCenterOfMass_ac = vec2.create(),
  8650. updateCenterOfMass_ca = vec2.create(),
  8651. updateCenterOfMass_cb = vec2.create(),
  8652. updateCenterOfMass_n = vec2.create();
  8653. /**
  8654. * Update the .centerOfMass property.
  8655. * @method updateCenterOfMass
  8656. */
  8657. Convex.prototype.updateCenterOfMass = function(){
  8658. var triangles = this.triangles,
  8659. verts = this.vertices,
  8660. cm = this.centerOfMass,
  8661. centroid = updateCenterOfMass_centroid,
  8662. n = updateCenterOfMass_n,
  8663. a = updateCenterOfMass_a,
  8664. b = updateCenterOfMass_b,
  8665. c = updateCenterOfMass_c,
  8666. ac = updateCenterOfMass_ac,
  8667. ca = updateCenterOfMass_ca,
  8668. cb = updateCenterOfMass_cb,
  8669. centroid_times_mass = updateCenterOfMass_centroid_times_mass;
  8670. vec2.set(cm,0,0);
  8671. var totalArea = 0;
  8672. for(var i=0; i!==triangles.length; i++){
  8673. var t = triangles[i],
  8674. a = verts[t[0]],
  8675. b = verts[t[1]],
  8676. c = verts[t[2]];
  8677. vec2.centroid(centroid,a,b,c);
  8678. // Get mass for the triangle (density=1 in this case)
  8679. // http://math.stackexchange.com/questions/80198/area-of-triangle-via-vectors
  8680. var m = Convex.triangleArea(a,b,c);
  8681. totalArea += m;
  8682. // Add to center of mass
  8683. vec2.scale(centroid_times_mass, centroid, m);
  8684. vec2.add(cm, cm, centroid_times_mass);
  8685. }
  8686. vec2.scale(cm,cm,1/totalArea);
  8687. };
  8688. /**
  8689. * Compute the mass moment of inertia of the Convex.
  8690. * @method computeMomentOfInertia
  8691. * @param {Number} mass
  8692. * @return {Number}
  8693. * @see http://www.gamedev.net/topic/342822-moment-of-inertia-of-a-polygon-2d/
  8694. */
  8695. Convex.prototype.computeMomentOfInertia = function(mass){
  8696. var denom = 0.0,
  8697. numer = 0.0,
  8698. N = this.vertices.length;
  8699. for(var j = N-1, i = 0; i < N; j = i, i ++){
  8700. var p0 = this.vertices[j];
  8701. var p1 = this.vertices[i];
  8702. var a = Math.abs(vec2.crossLength(p0,p1));
  8703. var b = vec2.dot(p1,p1) + vec2.dot(p1,p0) + vec2.dot(p0,p0);
  8704. denom += a * b;
  8705. numer += a;
  8706. }
  8707. return (mass / 6.0) * (denom / numer);
  8708. };
  8709. /**
  8710. * Updates the .boundingRadius property
  8711. * @method updateBoundingRadius
  8712. */
  8713. Convex.prototype.updateBoundingRadius = function(){
  8714. var verts = this.vertices,
  8715. r2 = 0;
  8716. for(var i=0; i!==verts.length; i++){
  8717. var l2 = vec2.squaredLength(verts[i]);
  8718. if(l2 > r2){
  8719. r2 = l2;
  8720. }
  8721. }
  8722. this.boundingRadius = Math.sqrt(r2);
  8723. };
  8724. /**
  8725. * Get the area of the triangle spanned by the three points a, b, c. The area is positive if the points are given in counter-clockwise order, otherwise negative.
  8726. * @static
  8727. * @method triangleArea
  8728. * @param {Array} a
  8729. * @param {Array} b
  8730. * @param {Array} c
  8731. * @return {Number}
  8732. */
  8733. Convex.triangleArea = function(a,b,c){
  8734. return (((b[0] - a[0])*(c[1] - a[1]))-((c[0] - a[0])*(b[1] - a[1]))) * 0.5;
  8735. };
  8736. /**
  8737. * Update the .area
  8738. * @method updateArea
  8739. */
  8740. Convex.prototype.updateArea = function(){
  8741. this.updateTriangles();
  8742. this.area = 0;
  8743. var triangles = this.triangles,
  8744. verts = this.vertices;
  8745. for(var i=0; i!==triangles.length; i++){
  8746. var t = triangles[i],
  8747. a = verts[t[0]],
  8748. b = verts[t[1]],
  8749. c = verts[t[2]];
  8750. // Get mass for the triangle (density=1 in this case)
  8751. var m = Convex.triangleArea(a,b,c);
  8752. this.area += m;
  8753. }
  8754. };
  8755. /**
  8756. * @method computeAABB
  8757. * @param {AABB} out
  8758. * @param {Array} position
  8759. * @param {Number} angle
  8760. */
  8761. Convex.prototype.computeAABB = function(out, position, angle){
  8762. out.setFromPoints(this.vertices, position, angle, 0);
  8763. };
  8764. var intersectConvex_rayStart = vec2.create();
  8765. var intersectConvex_rayEnd = vec2.create();
  8766. var intersectConvex_normal = vec2.create();
  8767. /**
  8768. * @method raycast
  8769. * @param {RaycastResult} result
  8770. * @param {Ray} ray
  8771. * @param {array} position
  8772. * @param {number} angle
  8773. */
  8774. Convex.prototype.raycast = function(result, ray, position, angle){
  8775. var rayStart = intersectConvex_rayStart;
  8776. var rayEnd = intersectConvex_rayEnd;
  8777. var normal = intersectConvex_normal;
  8778. var vertices = this.vertices;
  8779. // Transform to local shape space
  8780. vec2.toLocalFrame(rayStart, ray.from, position, angle);
  8781. vec2.toLocalFrame(rayEnd, ray.to, position, angle);
  8782. var n = vertices.length;
  8783. for (var i = 0; i < n && !result.shouldStop(ray); i++) {
  8784. var q1 = vertices[i];
  8785. var q2 = vertices[(i+1) % n];
  8786. var delta = vec2.getLineSegmentsIntersectionFraction(rayStart, rayEnd, q1, q2);
  8787. if(delta >= 0){
  8788. vec2.sub(normal, q2, q1);
  8789. vec2.rotate(normal, normal, -Math.PI / 2 + angle);
  8790. vec2.normalize(normal, normal);
  8791. ray.reportIntersection(result, delta, normal, i);
  8792. }
  8793. }
  8794. };
  8795. },{"../math/polyk":29,"../math/vec2":30,"./Shape":45,"poly-decomp":5}],41:[function(_dereq_,module,exports){
  8796. var Shape = _dereq_('./Shape')
  8797. , vec2 = _dereq_('../math/vec2')
  8798. , Utils = _dereq_('../utils/Utils');
  8799. module.exports = Heightfield;
  8800. /**
  8801. * Heightfield shape class. Height data is given as an array. These data points are spread out evenly with a distance "elementWidth".
  8802. * @class Heightfield
  8803. * @extends Shape
  8804. * @constructor
  8805. * @param {object} [options] (Note that this options object will be passed on to the {{#crossLink "Shape"}}{{/crossLink}} constructor.)
  8806. * @param {array} [options.heights] An array of Y values that will be used to construct the terrain.
  8807. * @param {Number} [options.minValue] Minimum value of the data points in the data array. Will be computed automatically if not given.
  8808. * @param {Number} [options.maxValue] Maximum value.
  8809. * @param {Number} [options.elementWidth=0.1] World spacing between the data points in X direction.
  8810. *
  8811. * @example
  8812. * // Generate some height data (y-values).
  8813. * var heights = [];
  8814. * for(var i = 0; i < 1000; i++){
  8815. * var y = 0.5 * Math.cos(0.2 * i);
  8816. * heights.push(y);
  8817. * }
  8818. *
  8819. * // Create the heightfield shape
  8820. * var heightfieldShape = new Heightfield({
  8821. * heights: heights,
  8822. * elementWidth: 1 // Distance between the data points in X direction
  8823. * });
  8824. * var heightfieldBody = new Body();
  8825. * heightfieldBody.addShape(heightfieldShape);
  8826. * world.addBody(heightfieldBody);
  8827. *
  8828. * @todo Should use a scale property with X and Y direction instead of just elementWidth
  8829. */
  8830. function Heightfield(options){
  8831. if(Array.isArray(arguments[0])){
  8832. options = {
  8833. heights: arguments[0]
  8834. };
  8835. if(typeof(arguments[1]) === 'object'){
  8836. for(var key in arguments[1]){
  8837. options[key] = arguments[1][key];
  8838. }
  8839. }
  8840. console.warn('The Heightfield constructor signature has changed. Please use the following format: new Heightfield({ heights: [...], ... })');
  8841. }
  8842. options = options || {};
  8843. /**
  8844. * An array of numbers, or height values, that are spread out along the x axis.
  8845. * @property {array} heights
  8846. */
  8847. this.heights = options.heights ? options.heights.slice(0) : [];
  8848. /**
  8849. * Max value of the heights
  8850. * @property {number} maxValue
  8851. */
  8852. this.maxValue = options.maxValue || null;
  8853. /**
  8854. * Max value of the heights
  8855. * @property {number} minValue
  8856. */
  8857. this.minValue = options.minValue || null;
  8858. /**
  8859. * The width of each element
  8860. * @property {number} elementWidth
  8861. */
  8862. this.elementWidth = options.elementWidth || 0.1;
  8863. if(options.maxValue === undefined || options.minValue === undefined){
  8864. this.updateMaxMinValues();
  8865. }
  8866. options.type = Shape.HEIGHTFIELD;
  8867. Shape.call(this, options);
  8868. }
  8869. Heightfield.prototype = new Shape();
  8870. Heightfield.prototype.constructor = Heightfield;
  8871. /**
  8872. * Update the .minValue and the .maxValue
  8873. * @method updateMaxMinValues
  8874. */
  8875. Heightfield.prototype.updateMaxMinValues = function(){
  8876. var data = this.heights;
  8877. var maxValue = data[0];
  8878. var minValue = data[0];
  8879. for(var i=0; i !== data.length; i++){
  8880. var v = data[i];
  8881. if(v > maxValue){
  8882. maxValue = v;
  8883. }
  8884. if(v < minValue){
  8885. minValue = v;
  8886. }
  8887. }
  8888. this.maxValue = maxValue;
  8889. this.minValue = minValue;
  8890. };
  8891. /**
  8892. * @method computeMomentOfInertia
  8893. * @param {Number} mass
  8894. * @return {Number}
  8895. */
  8896. Heightfield.prototype.computeMomentOfInertia = function(mass){
  8897. return Number.MAX_VALUE;
  8898. };
  8899. Heightfield.prototype.updateBoundingRadius = function(){
  8900. this.boundingRadius = Number.MAX_VALUE;
  8901. };
  8902. Heightfield.prototype.updateArea = function(){
  8903. var data = this.heights,
  8904. area = 0;
  8905. for(var i=0; i<data.length-1; i++){
  8906. area += (data[i]+data[i+1]) / 2 * this.elementWidth;
  8907. }
  8908. this.area = area;
  8909. };
  8910. var points = [
  8911. vec2.create(),
  8912. vec2.create(),
  8913. vec2.create(),
  8914. vec2.create()
  8915. ];
  8916. /**
  8917. * @method computeAABB
  8918. * @param {AABB} out The resulting AABB.
  8919. * @param {Array} position
  8920. * @param {Number} angle
  8921. */
  8922. Heightfield.prototype.computeAABB = function(out, position, angle){
  8923. vec2.set(points[0], 0, this.maxValue);
  8924. vec2.set(points[1], this.elementWidth * this.heights.length, this.maxValue);
  8925. vec2.set(points[2], this.elementWidth * this.heights.length, this.minValue);
  8926. vec2.set(points[3], 0, this.minValue);
  8927. out.setFromPoints(points, position, angle);
  8928. };
  8929. /**
  8930. * Get a line segment in the heightfield
  8931. * @method getLineSegment
  8932. * @param {array} start Where to store the resulting start point
  8933. * @param {array} end Where to store the resulting end point
  8934. * @param {number} i
  8935. */
  8936. Heightfield.prototype.getLineSegment = function(start, end, i){
  8937. var data = this.heights;
  8938. var width = this.elementWidth;
  8939. vec2.set(start, i * width, data[i]);
  8940. vec2.set(end, (i + 1) * width, data[i + 1]);
  8941. };
  8942. Heightfield.prototype.getSegmentIndex = function(position){
  8943. return Math.floor(position[0] / this.elementWidth);
  8944. };
  8945. Heightfield.prototype.getClampedSegmentIndex = function(position){
  8946. var i = this.getSegmentIndex(position);
  8947. i = Math.min(this.heights.length, Math.max(i, 0)); // clamp
  8948. return i;
  8949. };
  8950. var intersectHeightfield_hitPointWorld = vec2.create();
  8951. var intersectHeightfield_worldNormal = vec2.create();
  8952. var intersectHeightfield_l0 = vec2.create();
  8953. var intersectHeightfield_l1 = vec2.create();
  8954. var intersectHeightfield_localFrom = vec2.create();
  8955. var intersectHeightfield_localTo = vec2.create();
  8956. var intersectHeightfield_unit_y = vec2.fromValues(0,1);
  8957. // Returns 1 if the lines intersect, otherwise 0.
  8958. function getLineSegmentsIntersection (out, p0, p1, p2, p3) {
  8959. var s1_x, s1_y, s2_x, s2_y;
  8960. s1_x = p1[0] - p0[0];
  8961. s1_y = p1[1] - p0[1];
  8962. s2_x = p3[0] - p2[0];
  8963. s2_y = p3[1] - p2[1];
  8964. var s, t;
  8965. s = (-s1_y * (p0[0] - p2[0]) + s1_x * (p0[1] - p2[1])) / (-s2_x * s1_y + s1_x * s2_y);
  8966. t = ( s2_x * (p0[1] - p2[1]) - s2_y * (p0[0] - p2[0])) / (-s2_x * s1_y + s1_x * s2_y);
  8967. if (s >= 0 && s <= 1 && t >= 0 && t <= 1) { // Collision detected
  8968. var intX = p0[0] + (t * s1_x);
  8969. var intY = p0[1] + (t * s1_y);
  8970. out[0] = intX;
  8971. out[1] = intY;
  8972. return t;
  8973. }
  8974. return -1; // No collision
  8975. }
  8976. /**
  8977. * @method raycast
  8978. * @param {RayResult} result
  8979. * @param {Ray} ray
  8980. * @param {array} position
  8981. * @param {number} angle
  8982. */
  8983. Heightfield.prototype.raycast = function(result, ray, position, angle){
  8984. var from = ray.from;
  8985. var to = ray.to;
  8986. var direction = ray.direction;
  8987. var hitPointWorld = intersectHeightfield_hitPointWorld;
  8988. var worldNormal = intersectHeightfield_worldNormal;
  8989. var l0 = intersectHeightfield_l0;
  8990. var l1 = intersectHeightfield_l1;
  8991. var localFrom = intersectHeightfield_localFrom;
  8992. var localTo = intersectHeightfield_localTo;
  8993. // get local ray start and end
  8994. vec2.toLocalFrame(localFrom, from, position, angle);
  8995. vec2.toLocalFrame(localTo, to, position, angle);
  8996. // Get the segment range
  8997. var i0 = this.getClampedSegmentIndex(localFrom);
  8998. var i1 = this.getClampedSegmentIndex(localTo);
  8999. if(i0 > i1){
  9000. var tmp = i0;
  9001. i0 = i1;
  9002. i1 = tmp;
  9003. }
  9004. // The segments
  9005. for(var i=0; i<this.heights.length - 1; i++){
  9006. this.getLineSegment(l0, l1, i);
  9007. var t = vec2.getLineSegmentsIntersectionFraction(localFrom, localTo, l0, l1);
  9008. if(t >= 0){
  9009. vec2.sub(worldNormal, l1, l0);
  9010. vec2.rotate(worldNormal, worldNormal, angle + Math.PI / 2);
  9011. vec2.normalize(worldNormal, worldNormal);
  9012. ray.reportIntersection(result, t, worldNormal, -1);
  9013. if(result.shouldStop(ray)){
  9014. return;
  9015. }
  9016. }
  9017. }
  9018. };
  9019. },{"../math/vec2":30,"../utils/Utils":57,"./Shape":45}],42:[function(_dereq_,module,exports){
  9020. var Shape = _dereq_('./Shape')
  9021. , vec2 = _dereq_('../math/vec2');
  9022. module.exports = Line;
  9023. /**
  9024. * Line shape class. The line shape is along the x direction, and stretches from [-length/2, 0] to [length/2,0].
  9025. * @class Line
  9026. * @param {object} [options] (Note that this options object will be passed on to the {{#crossLink "Shape"}}{{/crossLink}} constructor.)
  9027. * @param {Number} [options.length=1] The total length of the line
  9028. * @extends Shape
  9029. * @constructor
  9030. */
  9031. function Line(options){
  9032. if(typeof(arguments[0]) === 'number'){
  9033. options = {
  9034. length: arguments[0]
  9035. };
  9036. console.warn('The Line constructor signature has changed. Please use the following format: new Line({ length: 1, ... })');
  9037. }
  9038. options = options || {};
  9039. /**
  9040. * Length of this line
  9041. * @property {Number} length
  9042. * @default 1
  9043. */
  9044. this.length = options.length || 1;
  9045. options.type = Shape.LINE;
  9046. Shape.call(this, options);
  9047. }
  9048. Line.prototype = new Shape();
  9049. Line.prototype.constructor = Line;
  9050. Line.prototype.computeMomentOfInertia = function(mass){
  9051. return mass * Math.pow(this.length,2) / 12;
  9052. };
  9053. Line.prototype.updateBoundingRadius = function(){
  9054. this.boundingRadius = this.length/2;
  9055. };
  9056. var points = [vec2.create(),vec2.create()];
  9057. /**
  9058. * @method computeAABB
  9059. * @param {AABB} out The resulting AABB.
  9060. * @param {Array} position
  9061. * @param {Number} angle
  9062. */
  9063. Line.prototype.computeAABB = function(out, position, angle){
  9064. var l2 = this.length / 2;
  9065. vec2.set(points[0], -l2, 0);
  9066. vec2.set(points[1], l2, 0);
  9067. out.setFromPoints(points,position,angle,0);
  9068. };
  9069. var raycast_hitPoint = vec2.create();
  9070. var raycast_normal = vec2.create();
  9071. var raycast_l0 = vec2.create();
  9072. var raycast_l1 = vec2.create();
  9073. var raycast_unit_y = vec2.fromValues(0,1);
  9074. /**
  9075. * @method raycast
  9076. * @param {RaycastResult} result
  9077. * @param {Ray} ray
  9078. * @param {number} angle
  9079. * @param {array} position
  9080. */
  9081. Line.prototype.raycast = function(result, ray, position, angle){
  9082. var from = ray.from;
  9083. var to = ray.to;
  9084. var l0 = raycast_l0;
  9085. var l1 = raycast_l1;
  9086. // get start and end of the line
  9087. var halfLen = this.length / 2;
  9088. vec2.set(l0, -halfLen, 0);
  9089. vec2.set(l1, halfLen, 0);
  9090. vec2.toGlobalFrame(l0, l0, position, angle);
  9091. vec2.toGlobalFrame(l1, l1, position, angle);
  9092. var fraction = vec2.getLineSegmentsIntersectionFraction(l0, l1, from, to);
  9093. if(fraction >= 0){
  9094. var normal = raycast_normal;
  9095. vec2.rotate(normal, raycast_unit_y, angle); // todo: this should depend on which side the ray comes from
  9096. ray.reportIntersection(result, fraction, normal, -1);
  9097. }
  9098. };
  9099. },{"../math/vec2":30,"./Shape":45}],43:[function(_dereq_,module,exports){
  9100. var Shape = _dereq_('./Shape')
  9101. , vec2 = _dereq_('../math/vec2');
  9102. module.exports = Particle;
  9103. /**
  9104. * Particle shape class.
  9105. * @class Particle
  9106. * @constructor
  9107. * @param {object} [options] (Note that this options object will be passed on to the {{#crossLink "Shape"}}{{/crossLink}} constructor.)
  9108. * @extends Shape
  9109. */
  9110. function Particle(options){
  9111. options = options || {};
  9112. options.type = Shape.PARTICLE;
  9113. Shape.call(this, options);
  9114. }
  9115. Particle.prototype = new Shape();
  9116. Particle.prototype.constructor = Particle;
  9117. Particle.prototype.computeMomentOfInertia = function(mass){
  9118. return 0; // Can't rotate a particle
  9119. };
  9120. Particle.prototype.updateBoundingRadius = function(){
  9121. this.boundingRadius = 0;
  9122. };
  9123. /**
  9124. * @method computeAABB
  9125. * @param {AABB} out
  9126. * @param {Array} position
  9127. * @param {Number} angle
  9128. */
  9129. Particle.prototype.computeAABB = function(out, position, angle){
  9130. vec2.copy(out.lowerBound, position);
  9131. vec2.copy(out.upperBound, position);
  9132. };
  9133. },{"../math/vec2":30,"./Shape":45}],44:[function(_dereq_,module,exports){
  9134. var Shape = _dereq_('./Shape')
  9135. , vec2 = _dereq_('../math/vec2')
  9136. , Utils = _dereq_('../utils/Utils');
  9137. module.exports = Plane;
  9138. /**
  9139. * Plane shape class. The plane is facing in the Y direction.
  9140. * @class Plane
  9141. * @extends Shape
  9142. * @constructor
  9143. * @param {object} [options] (Note that this options object will be passed on to the {{#crossLink "Shape"}}{{/crossLink}} constructor.)
  9144. */
  9145. function Plane(options){
  9146. options = options || {};
  9147. options.type = Shape.PLANE;
  9148. Shape.call(this, options);
  9149. }
  9150. Plane.prototype = new Shape();
  9151. Plane.prototype.constructor = Plane;
  9152. /**
  9153. * Compute moment of inertia
  9154. * @method computeMomentOfInertia
  9155. */
  9156. Plane.prototype.computeMomentOfInertia = function(mass){
  9157. return 0; // Plane is infinite. The inertia should therefore be infinty but by convention we set 0 here
  9158. };
  9159. /**
  9160. * Update the bounding radius
  9161. * @method updateBoundingRadius
  9162. */
  9163. Plane.prototype.updateBoundingRadius = function(){
  9164. this.boundingRadius = Number.MAX_VALUE;
  9165. };
  9166. /**
  9167. * @method computeAABB
  9168. * @param {AABB} out
  9169. * @param {Array} position
  9170. * @param {Number} angle
  9171. */
  9172. Plane.prototype.computeAABB = function(out, position, angle){
  9173. var a = angle % (2 * Math.PI);
  9174. var set = vec2.set;
  9175. var max = Number.MAX_VALUE;
  9176. var lowerBound = out.lowerBound;
  9177. var upperBound = out.upperBound;
  9178. if(a === 0){
  9179. // y goes from -inf to 0
  9180. set(lowerBound, -max, -max);
  9181. set(upperBound, max, 0);
  9182. } else if(a === Math.PI / 2){
  9183. // x goes from 0 to inf
  9184. set(lowerBound, 0, -max);
  9185. set(upperBound, max, max);
  9186. } else if(a === Math.PI){
  9187. // y goes from 0 to inf
  9188. set(lowerBound, -max, 0);
  9189. set(upperBound, max, max);
  9190. } else if(a === 3*Math.PI/2){
  9191. // x goes from -inf to 0
  9192. set(lowerBound, -max, -max);
  9193. set(upperBound, 0, max);
  9194. } else {
  9195. // Set max bounds
  9196. set(lowerBound, -max, -max);
  9197. set(upperBound, max, max);
  9198. }
  9199. vec2.add(lowerBound, lowerBound, position);
  9200. vec2.add(upperBound, upperBound, position);
  9201. };
  9202. Plane.prototype.updateArea = function(){
  9203. this.area = Number.MAX_VALUE;
  9204. };
  9205. var intersectPlane_planePointToFrom = vec2.create();
  9206. var intersectPlane_dir_scaled_with_t = vec2.create();
  9207. var intersectPlane_hitPoint = vec2.create();
  9208. var intersectPlane_normal = vec2.create();
  9209. var intersectPlane_len = vec2.create();
  9210. /**
  9211. * @method raycast
  9212. * @param {RayResult} result
  9213. * @param {Ray} ray
  9214. * @param {array} position
  9215. * @param {number} angle
  9216. */
  9217. Plane.prototype.raycast = function(result, ray, position, angle){
  9218. var from = ray.from;
  9219. var to = ray.to;
  9220. var direction = ray.direction;
  9221. var planePointToFrom = intersectPlane_planePointToFrom;
  9222. var dir_scaled_with_t = intersectPlane_dir_scaled_with_t;
  9223. var hitPoint = intersectPlane_hitPoint;
  9224. var normal = intersectPlane_normal;
  9225. var len = intersectPlane_len;
  9226. // Get plane normal
  9227. vec2.set(normal, 0, 1);
  9228. vec2.rotate(normal, normal, angle);
  9229. vec2.sub(len, from, position);
  9230. var planeToFrom = vec2.dot(len, normal);
  9231. vec2.sub(len, to, position);
  9232. var planeToTo = vec2.dot(len, normal);
  9233. if(planeToFrom * planeToTo > 0){
  9234. // "from" and "to" are on the same side of the plane... bail out
  9235. return;
  9236. }
  9237. if(vec2.squaredDistance(from, to) < planeToFrom * planeToFrom){
  9238. return;
  9239. }
  9240. var n_dot_dir = vec2.dot(normal, direction);
  9241. vec2.sub(planePointToFrom, from, position);
  9242. var t = -vec2.dot(normal, planePointToFrom) / n_dot_dir / ray.length;
  9243. ray.reportIntersection(result, t, normal, -1);
  9244. };
  9245. },{"../math/vec2":30,"../utils/Utils":57,"./Shape":45}],45:[function(_dereq_,module,exports){
  9246. module.exports = Shape;
  9247. var vec2 = _dereq_('../math/vec2');
  9248. /**
  9249. * Base class for shapes.
  9250. * @class Shape
  9251. * @constructor
  9252. * @param {object} [options]
  9253. * @param {array} [options.position]
  9254. * @param {number} [options.angle=0]
  9255. * @param {number} [options.collisionGroup=1]
  9256. * @param {number} [options.collisionMask=1]
  9257. * @param {boolean} [options.sensor=false]
  9258. * @param {boolean} [options.collisionResponse=true]
  9259. * @param {object} [options.type=0]
  9260. */
  9261. function Shape(options){
  9262. options = options || {};
  9263. /**
  9264. * The body this shape is attached to. A shape can only be attached to a single body.
  9265. * @property {Body} body
  9266. */
  9267. this.body = null;
  9268. /**
  9269. * Body-local position of the shape.
  9270. * @property {Array} position
  9271. */
  9272. this.position = vec2.fromValues(0,0);
  9273. if(options.position){
  9274. vec2.copy(this.position, options.position);
  9275. }
  9276. /**
  9277. * Body-local angle of the shape.
  9278. * @property {number} angle
  9279. */
  9280. this.angle = options.angle || 0;
  9281. /**
  9282. * The type of the shape. One of:
  9283. *
  9284. * * {{#crossLink "Shape/CIRCLE:property"}}Shape.CIRCLE{{/crossLink}}
  9285. * * {{#crossLink "Shape/PARTICLE:property"}}Shape.PARTICLE{{/crossLink}}
  9286. * * {{#crossLink "Shape/PLANE:property"}}Shape.PLANE{{/crossLink}}
  9287. * * {{#crossLink "Shape/CONVEX:property"}}Shape.CONVEX{{/crossLink}}
  9288. * * {{#crossLink "Shape/LINE:property"}}Shape.LINE{{/crossLink}}
  9289. * * {{#crossLink "Shape/BOX:property"}}Shape.BOX{{/crossLink}}
  9290. * * {{#crossLink "Shape/CAPSULE:property"}}Shape.CAPSULE{{/crossLink}}
  9291. * * {{#crossLink "Shape/HEIGHTFIELD:property"}}Shape.HEIGHTFIELD{{/crossLink}}
  9292. *
  9293. * @property {number} type
  9294. */
  9295. this.type = options.type || 0;
  9296. /**
  9297. * Shape object identifier.
  9298. * @type {Number}
  9299. * @property id
  9300. */
  9301. this.id = Shape.idCounter++;
  9302. /**
  9303. * Bounding circle radius of this shape
  9304. * @property boundingRadius
  9305. * @type {Number}
  9306. */
  9307. this.boundingRadius = 0;
  9308. /**
  9309. * Collision group that this shape belongs to (bit mask). See <a href="http://www.aurelienribon.com/blog/2011/07/box2d-tutorial-collision-filtering/">this tutorial</a>.
  9310. * @property collisionGroup
  9311. * @type {Number}
  9312. * @example
  9313. * // Setup bits for each available group
  9314. * var PLAYER = Math.pow(2,0),
  9315. * ENEMY = Math.pow(2,1),
  9316. * GROUND = Math.pow(2,2)
  9317. *
  9318. * // Put shapes into their groups
  9319. * player1Shape.collisionGroup = PLAYER;
  9320. * player2Shape.collisionGroup = PLAYER;
  9321. * enemyShape .collisionGroup = ENEMY;
  9322. * groundShape .collisionGroup = GROUND;
  9323. *
  9324. * // Assign groups that each shape collide with.
  9325. * // Note that the players can collide with ground and enemies, but not with other players.
  9326. * player1Shape.collisionMask = ENEMY | GROUND;
  9327. * player2Shape.collisionMask = ENEMY | GROUND;
  9328. * enemyShape .collisionMask = PLAYER | GROUND;
  9329. * groundShape .collisionMask = PLAYER | ENEMY;
  9330. *
  9331. * @example
  9332. * // How collision check is done
  9333. * if(shapeA.collisionGroup & shapeB.collisionMask)!=0 && (shapeB.collisionGroup & shapeA.collisionMask)!=0){
  9334. * // The shapes will collide
  9335. * }
  9336. */
  9337. this.collisionGroup = options.collisionGroup !== undefined ? options.collisionGroup : 1;
  9338. /**
  9339. * Whether to produce contact forces when in contact with other bodies. Note that contacts will be generated, but they will be disabled. That means that this shape will move through other body shapes, but it will still trigger contact events, etc.
  9340. * @property {Boolean} collisionResponse
  9341. */
  9342. this.collisionResponse = options.collisionResponse !== undefined ? options.collisionResponse : true;
  9343. /**
  9344. * Collision mask of this shape. See .collisionGroup.
  9345. * @property collisionMask
  9346. * @type {Number}
  9347. */
  9348. this.collisionMask = options.collisionMask !== undefined ? options.collisionMask : 1;
  9349. /**
  9350. * Material to use in collisions for this Shape. If this is set to null, the world will use default material properties instead.
  9351. * @property material
  9352. * @type {Material}
  9353. */
  9354. this.material = options.material || null;
  9355. /**
  9356. * Area of this shape.
  9357. * @property area
  9358. * @type {Number}
  9359. */
  9360. this.area = 0;
  9361. /**
  9362. * Set to true if you want this shape to be a sensor. A sensor does not generate contacts, but it still reports contact events. This is good if you want to know if a shape is overlapping another shape, without them generating contacts.
  9363. * @property {Boolean} sensor
  9364. */
  9365. this.sensor = options.sensor !== undefined ? options.sensor : false;
  9366. if(this.type){
  9367. this.updateBoundingRadius();
  9368. }
  9369. this.updateArea();
  9370. }
  9371. Shape.idCounter = 0;
  9372. /**
  9373. * @static
  9374. * @property {Number} CIRCLE
  9375. */
  9376. Shape.CIRCLE = 1;
  9377. /**
  9378. * @static
  9379. * @property {Number} PARTICLE
  9380. */
  9381. Shape.PARTICLE = 2;
  9382. /**
  9383. * @static
  9384. * @property {Number} PLANE
  9385. */
  9386. Shape.PLANE = 4;
  9387. /**
  9388. * @static
  9389. * @property {Number} CONVEX
  9390. */
  9391. Shape.CONVEX = 8;
  9392. /**
  9393. * @static
  9394. * @property {Number} LINE
  9395. */
  9396. Shape.LINE = 16;
  9397. /**
  9398. * @static
  9399. * @property {Number} BOX
  9400. */
  9401. Shape.BOX = 32;
  9402. Object.defineProperty(Shape, 'RECTANGLE', {
  9403. get: function() {
  9404. console.warn('Shape.RECTANGLE is deprecated, use Shape.BOX instead.');
  9405. return Shape.BOX;
  9406. }
  9407. });
  9408. /**
  9409. * @static
  9410. * @property {Number} CAPSULE
  9411. */
  9412. Shape.CAPSULE = 64;
  9413. /**
  9414. * @static
  9415. * @property {Number} HEIGHTFIELD
  9416. */
  9417. Shape.HEIGHTFIELD = 128;
  9418. /**
  9419. * Should return the moment of inertia around the Z axis of the body given the total mass. See <a href="http://en.wikipedia.org/wiki/List_of_moments_of_inertia">Wikipedia's list of moments of inertia</a>.
  9420. * @method computeMomentOfInertia
  9421. * @param {Number} mass
  9422. * @return {Number} If the inertia is infinity or if the object simply isn't possible to rotate, return 0.
  9423. */
  9424. Shape.prototype.computeMomentOfInertia = function(mass){};
  9425. /**
  9426. * Returns the bounding circle radius of this shape.
  9427. * @method updateBoundingRadius
  9428. * @return {Number}
  9429. */
  9430. Shape.prototype.updateBoundingRadius = function(){};
  9431. /**
  9432. * Update the .area property of the shape.
  9433. * @method updateArea
  9434. */
  9435. Shape.prototype.updateArea = function(){
  9436. // To be implemented in all subclasses
  9437. };
  9438. /**
  9439. * Compute the world axis-aligned bounding box (AABB) of this shape.
  9440. * @method computeAABB
  9441. * @param {AABB} out The resulting AABB.
  9442. * @param {Array} position World position of the shape.
  9443. * @param {Number} angle World angle of the shape.
  9444. */
  9445. Shape.prototype.computeAABB = function(out, position, angle){
  9446. // To be implemented in each subclass
  9447. };
  9448. /**
  9449. * Perform raycasting on this shape.
  9450. * @method raycast
  9451. * @param {RayResult} result Where to store the resulting data.
  9452. * @param {Ray} ray The Ray that you want to use for raycasting.
  9453. * @param {array} position World position of the shape (the .position property will be ignored).
  9454. * @param {number} angle World angle of the shape (the .angle property will be ignored).
  9455. */
  9456. Shape.prototype.raycast = function(result, ray, position, angle){
  9457. // To be implemented in each subclass
  9458. };
  9459. },{"../math/vec2":30}],46:[function(_dereq_,module,exports){
  9460. var vec2 = _dereq_('../math/vec2')
  9461. , Solver = _dereq_('./Solver')
  9462. , Utils = _dereq_('../utils/Utils')
  9463. , FrictionEquation = _dereq_('../equations/FrictionEquation');
  9464. module.exports = GSSolver;
  9465. /**
  9466. * Iterative Gauss-Seidel constraint equation solver.
  9467. *
  9468. * @class GSSolver
  9469. * @constructor
  9470. * @extends Solver
  9471. * @param {Object} [options]
  9472. * @param {Number} [options.iterations=10]
  9473. * @param {Number} [options.tolerance=0]
  9474. */
  9475. function GSSolver(options){
  9476. Solver.call(this,options,Solver.GS);
  9477. options = options || {};
  9478. /**
  9479. * The max number of iterations to do when solving. More gives better results, but is more expensive.
  9480. * @property iterations
  9481. * @type {Number}
  9482. */
  9483. this.iterations = options.iterations || 10;
  9484. /**
  9485. * The error tolerance, per constraint. If the total error is below this limit, the solver will stop iterating. Set to zero for as good solution as possible, but to something larger than zero to make computations faster.
  9486. * @property tolerance
  9487. * @type {Number}
  9488. * @default 1e-7
  9489. */
  9490. this.tolerance = options.tolerance || 1e-7;
  9491. this.arrayStep = 30;
  9492. this.lambda = new Utils.ARRAY_TYPE(this.arrayStep);
  9493. this.Bs = new Utils.ARRAY_TYPE(this.arrayStep);
  9494. this.invCs = new Utils.ARRAY_TYPE(this.arrayStep);
  9495. /**
  9496. * Set to true to set all right hand side terms to zero when solving. Can be handy for a few applications.
  9497. * @property useZeroRHS
  9498. * @type {Boolean}
  9499. */
  9500. this.useZeroRHS = false;
  9501. /**
  9502. * Number of solver iterations that are done to approximate normal forces. When these iterations are done, friction force will be computed from the contact normal forces. These friction forces will override any other friction forces set from the World for example.
  9503. * The solver will use less iterations if the solution is below the .tolerance.
  9504. * @property frictionIterations
  9505. * @type {Number}
  9506. */
  9507. this.frictionIterations = 0;
  9508. /**
  9509. * The number of iterations that were made during the last solve. If .tolerance is zero, this value will always be equal to .iterations, but if .tolerance is larger than zero, and the solver can quit early, then this number will be somewhere between 1 and .iterations.
  9510. * @property {Number} usedIterations
  9511. */
  9512. this.usedIterations = 0;
  9513. }
  9514. GSSolver.prototype = new Solver();
  9515. GSSolver.prototype.constructor = GSSolver;
  9516. function setArrayZero(array){
  9517. var l = array.length;
  9518. while(l--){
  9519. array[l] = +0.0;
  9520. }
  9521. }
  9522. /**
  9523. * Solve the system of equations
  9524. * @method solve
  9525. * @param {Number} h Time step
  9526. * @param {World} world World to solve
  9527. */
  9528. GSSolver.prototype.solve = function(h, world){
  9529. this.sortEquations();
  9530. var iter = 0,
  9531. maxIter = this.iterations,
  9532. maxFrictionIter = this.frictionIterations,
  9533. equations = this.equations,
  9534. Neq = equations.length,
  9535. tolSquared = Math.pow(this.tolerance*Neq, 2),
  9536. bodies = world.bodies,
  9537. Nbodies = world.bodies.length,
  9538. add = vec2.add,
  9539. set = vec2.set,
  9540. useZeroRHS = this.useZeroRHS,
  9541. lambda = this.lambda;
  9542. this.usedIterations = 0;
  9543. if(Neq){
  9544. for(var i=0; i!==Nbodies; i++){
  9545. var b = bodies[i];
  9546. // Update solve mass
  9547. b.updateSolveMassProperties();
  9548. }
  9549. }
  9550. // Things that does not change during iteration can be computed once
  9551. if(lambda.length < Neq){
  9552. lambda = this.lambda = new Utils.ARRAY_TYPE(Neq + this.arrayStep);
  9553. this.Bs = new Utils.ARRAY_TYPE(Neq + this.arrayStep);
  9554. this.invCs = new Utils.ARRAY_TYPE(Neq + this.arrayStep);
  9555. }
  9556. setArrayZero(lambda);
  9557. var invCs = this.invCs,
  9558. Bs = this.Bs,
  9559. lambda = this.lambda;
  9560. for(var i=0; i!==equations.length; i++){
  9561. var c = equations[i];
  9562. if(c.timeStep !== h || c.needsUpdate){
  9563. c.timeStep = h;
  9564. c.update();
  9565. }
  9566. Bs[i] = c.computeB(c.a,c.b,h);
  9567. invCs[i] = c.computeInvC(c.epsilon);
  9568. }
  9569. var q, B, c, deltalambdaTot,i,j;
  9570. if(Neq !== 0){
  9571. for(i=0; i!==Nbodies; i++){
  9572. var b = bodies[i];
  9573. // Reset vlambda
  9574. b.resetConstraintVelocity();
  9575. }
  9576. if(maxFrictionIter){
  9577. // Iterate over contact equations to get normal forces
  9578. for(iter=0; iter!==maxFrictionIter; iter++){
  9579. // Accumulate the total error for each iteration.
  9580. deltalambdaTot = 0.0;
  9581. for(j=0; j!==Neq; j++){
  9582. c = equations[j];
  9583. var deltalambda = GSSolver.iterateEquation(j,c,c.epsilon,Bs,invCs,lambda,useZeroRHS,h,iter);
  9584. deltalambdaTot += Math.abs(deltalambda);
  9585. }
  9586. this.usedIterations++;
  9587. // If the total error is small enough - stop iterate
  9588. if(deltalambdaTot*deltalambdaTot <= tolSquared){
  9589. break;
  9590. }
  9591. }
  9592. GSSolver.updateMultipliers(equations, lambda, 1/h);
  9593. // Set computed friction force
  9594. for(j=0; j!==Neq; j++){
  9595. var eq = equations[j];
  9596. if(eq instanceof FrictionEquation){
  9597. var f = 0.0;
  9598. for(var k=0; k!==eq.contactEquations.length; k++){
  9599. f += eq.contactEquations[k].multiplier;
  9600. }
  9601. f *= eq.frictionCoefficient / eq.contactEquations.length;
  9602. eq.maxForce = f;
  9603. eq.minForce = -f;
  9604. }
  9605. }
  9606. }
  9607. // Iterate over all equations
  9608. for(iter=0; iter!==maxIter; iter++){
  9609. // Accumulate the total error for each iteration.
  9610. deltalambdaTot = 0.0;
  9611. for(j=0; j!==Neq; j++){
  9612. c = equations[j];
  9613. var deltalambda = GSSolver.iterateEquation(j,c,c.epsilon,Bs,invCs,lambda,useZeroRHS,h,iter);
  9614. deltalambdaTot += Math.abs(deltalambda);
  9615. }
  9616. this.usedIterations++;
  9617. // If the total error is small enough - stop iterate
  9618. if(deltalambdaTot*deltalambdaTot <= tolSquared){
  9619. break;
  9620. }
  9621. }
  9622. // Add result to velocity
  9623. for(i=0; i!==Nbodies; i++){
  9624. bodies[i].addConstraintVelocity();
  9625. }
  9626. GSSolver.updateMultipliers(equations, lambda, 1/h);
  9627. }
  9628. };
  9629. // Sets the .multiplier property of each equation
  9630. GSSolver.updateMultipliers = function(equations, lambda, invDt){
  9631. // Set the .multiplier property of each equation
  9632. var l = equations.length;
  9633. while(l--){
  9634. equations[l].multiplier = lambda[l] * invDt;
  9635. }
  9636. };
  9637. GSSolver.iterateEquation = function(j,eq,eps,Bs,invCs,lambda,useZeroRHS,dt,iter){
  9638. // Compute iteration
  9639. var B = Bs[j],
  9640. invC = invCs[j],
  9641. lambdaj = lambda[j],
  9642. GWlambda = eq.computeGWlambda();
  9643. var maxForce = eq.maxForce,
  9644. minForce = eq.minForce;
  9645. if(useZeroRHS){
  9646. B = 0;
  9647. }
  9648. var deltalambda = invC * ( B - GWlambda - eps * lambdaj );
  9649. // Clamp if we are not within the min/max interval
  9650. var lambdaj_plus_deltalambda = lambdaj + deltalambda;
  9651. if(lambdaj_plus_deltalambda < minForce*dt){
  9652. deltalambda = minForce*dt - lambdaj;
  9653. } else if(lambdaj_plus_deltalambda > maxForce*dt){
  9654. deltalambda = maxForce*dt - lambdaj;
  9655. }
  9656. lambda[j] += deltalambda;
  9657. eq.addToWlambda(deltalambda);
  9658. return deltalambda;
  9659. };
  9660. },{"../equations/FrictionEquation":23,"../math/vec2":30,"../utils/Utils":57,"./Solver":47}],47:[function(_dereq_,module,exports){
  9661. var Utils = _dereq_('../utils/Utils')
  9662. , EventEmitter = _dereq_('../events/EventEmitter');
  9663. module.exports = Solver;
  9664. /**
  9665. * Base class for constraint solvers.
  9666. * @class Solver
  9667. * @constructor
  9668. * @extends EventEmitter
  9669. */
  9670. function Solver(options,type){
  9671. options = options || {};
  9672. EventEmitter.call(this);
  9673. this.type = type;
  9674. /**
  9675. * Current equations in the solver.
  9676. *
  9677. * @property equations
  9678. * @type {Array}
  9679. */
  9680. this.equations = [];
  9681. /**
  9682. * Function that is used to sort all equations before each solve.
  9683. * @property equationSortFunction
  9684. * @type {function|boolean}
  9685. */
  9686. this.equationSortFunction = options.equationSortFunction || false;
  9687. }
  9688. Solver.prototype = new EventEmitter();
  9689. Solver.prototype.constructor = Solver;
  9690. /**
  9691. * Method to be implemented in each subclass
  9692. * @method solve
  9693. * @param {Number} dt
  9694. * @param {World} world
  9695. */
  9696. Solver.prototype.solve = function(dt,world){
  9697. throw new Error("Solver.solve should be implemented by subclasses!");
  9698. };
  9699. var mockWorld = {bodies:[]};
  9700. /**
  9701. * Solves all constraints in an island.
  9702. * @method solveIsland
  9703. * @param {Number} dt
  9704. * @param {Island} island
  9705. */
  9706. Solver.prototype.solveIsland = function(dt,island){
  9707. this.removeAllEquations();
  9708. if(island.equations.length){
  9709. // Add equations to solver
  9710. this.addEquations(island.equations);
  9711. mockWorld.bodies.length = 0;
  9712. island.getBodies(mockWorld.bodies);
  9713. // Solve
  9714. if(mockWorld.bodies.length){
  9715. this.solve(dt,mockWorld);
  9716. }
  9717. }
  9718. };
  9719. /**
  9720. * Sort all equations using the .equationSortFunction. Should be called by subclasses before solving.
  9721. * @method sortEquations
  9722. */
  9723. Solver.prototype.sortEquations = function(){
  9724. if(this.equationSortFunction){
  9725. this.equations.sort(this.equationSortFunction);
  9726. }
  9727. };
  9728. /**
  9729. * Add an equation to be solved.
  9730. *
  9731. * @method addEquation
  9732. * @param {Equation} eq
  9733. */
  9734. Solver.prototype.addEquation = function(eq){
  9735. if(eq.enabled){
  9736. this.equations.push(eq);
  9737. }
  9738. };
  9739. /**
  9740. * Add equations. Same as .addEquation, but this time the argument is an array of Equations
  9741. *
  9742. * @method addEquations
  9743. * @param {Array} eqs
  9744. */
  9745. Solver.prototype.addEquations = function(eqs){
  9746. //Utils.appendArray(this.equations,eqs);
  9747. for(var i=0, N=eqs.length; i!==N; i++){
  9748. var eq = eqs[i];
  9749. if(eq.enabled){
  9750. this.equations.push(eq);
  9751. }
  9752. }
  9753. };
  9754. /**
  9755. * Remove an equation.
  9756. *
  9757. * @method removeEquation
  9758. * @param {Equation} eq
  9759. */
  9760. Solver.prototype.removeEquation = function(eq){
  9761. var i = this.equations.indexOf(eq);
  9762. if(i !== -1){
  9763. this.equations.splice(i,1);
  9764. }
  9765. };
  9766. /**
  9767. * Remove all currently added equations.
  9768. *
  9769. * @method removeAllEquations
  9770. */
  9771. Solver.prototype.removeAllEquations = function(){
  9772. this.equations.length=0;
  9773. };
  9774. Solver.GS = 1;
  9775. Solver.ISLAND = 2;
  9776. },{"../events/EventEmitter":26,"../utils/Utils":57}],48:[function(_dereq_,module,exports){
  9777. var ContactEquation = _dereq_('../equations/ContactEquation');
  9778. var Pool = _dereq_('./Pool');
  9779. module.exports = ContactEquationPool;
  9780. /**
  9781. * @class
  9782. */
  9783. function ContactEquationPool() {
  9784. Pool.apply(this, arguments);
  9785. }
  9786. ContactEquationPool.prototype = new Pool();
  9787. ContactEquationPool.prototype.constructor = ContactEquationPool;
  9788. /**
  9789. * @method create
  9790. * @return {ContactEquation}
  9791. */
  9792. ContactEquationPool.prototype.create = function () {
  9793. return new ContactEquation();
  9794. };
  9795. /**
  9796. * @method destroy
  9797. * @param {ContactEquation} equation
  9798. * @return {ContactEquationPool}
  9799. */
  9800. ContactEquationPool.prototype.destroy = function (equation) {
  9801. equation.bodyA = equation.bodyB = null;
  9802. return this;
  9803. };
  9804. },{"../equations/ContactEquation":21,"./Pool":55}],49:[function(_dereq_,module,exports){
  9805. var FrictionEquation = _dereq_('../equations/FrictionEquation');
  9806. var Pool = _dereq_('./Pool');
  9807. module.exports = FrictionEquationPool;
  9808. /**
  9809. * @class
  9810. */
  9811. function FrictionEquationPool() {
  9812. Pool.apply(this, arguments);
  9813. }
  9814. FrictionEquationPool.prototype = new Pool();
  9815. FrictionEquationPool.prototype.constructor = FrictionEquationPool;
  9816. /**
  9817. * @method create
  9818. * @return {FrictionEquation}
  9819. */
  9820. FrictionEquationPool.prototype.create = function () {
  9821. return new FrictionEquation();
  9822. };
  9823. /**
  9824. * @method destroy
  9825. * @param {FrictionEquation} equation
  9826. * @return {FrictionEquationPool}
  9827. */
  9828. FrictionEquationPool.prototype.destroy = function (equation) {
  9829. equation.bodyA = equation.bodyB = null;
  9830. return this;
  9831. };
  9832. },{"../equations/FrictionEquation":23,"./Pool":55}],50:[function(_dereq_,module,exports){
  9833. var IslandNode = _dereq_('../world/IslandNode');
  9834. var Pool = _dereq_('./Pool');
  9835. module.exports = IslandNodePool;
  9836. /**
  9837. * @class
  9838. */
  9839. function IslandNodePool() {
  9840. Pool.apply(this, arguments);
  9841. }
  9842. IslandNodePool.prototype = new Pool();
  9843. IslandNodePool.prototype.constructor = IslandNodePool;
  9844. /**
  9845. * @method create
  9846. * @return {IslandNode}
  9847. */
  9848. IslandNodePool.prototype.create = function () {
  9849. return new IslandNode();
  9850. };
  9851. /**
  9852. * @method destroy
  9853. * @param {IslandNode} node
  9854. * @return {IslandNodePool}
  9855. */
  9856. IslandNodePool.prototype.destroy = function (node) {
  9857. node.reset();
  9858. return this;
  9859. };
  9860. },{"../world/IslandNode":60,"./Pool":55}],51:[function(_dereq_,module,exports){
  9861. var Island = _dereq_('../world/Island');
  9862. var Pool = _dereq_('./Pool');
  9863. module.exports = IslandPool;
  9864. /**
  9865. * @class
  9866. */
  9867. function IslandPool() {
  9868. Pool.apply(this, arguments);
  9869. }
  9870. IslandPool.prototype = new Pool();
  9871. IslandPool.prototype.constructor = IslandPool;
  9872. /**
  9873. * @method create
  9874. * @return {Island}
  9875. */
  9876. IslandPool.prototype.create = function () {
  9877. return new Island();
  9878. };
  9879. /**
  9880. * @method destroy
  9881. * @param {Island} island
  9882. * @return {IslandPool}
  9883. */
  9884. IslandPool.prototype.destroy = function (island) {
  9885. island.reset();
  9886. return this;
  9887. };
  9888. },{"../world/Island":58,"./Pool":55}],52:[function(_dereq_,module,exports){
  9889. var TupleDictionary = _dereq_('./TupleDictionary');
  9890. var OverlapKeeperRecord = _dereq_('./OverlapKeeperRecord');
  9891. var OverlapKeeperRecordPool = _dereq_('./OverlapKeeperRecordPool');
  9892. var Utils = _dereq_('./Utils');
  9893. module.exports = OverlapKeeper;
  9894. /**
  9895. * Keeps track of overlaps in the current state and the last step state.
  9896. * @class OverlapKeeper
  9897. * @constructor
  9898. */
  9899. function OverlapKeeper() {
  9900. this.overlappingShapesLastState = new TupleDictionary();
  9901. this.overlappingShapesCurrentState = new TupleDictionary();
  9902. this.recordPool = new OverlapKeeperRecordPool({ size: 16 });
  9903. this.tmpDict = new TupleDictionary();
  9904. this.tmpArray1 = [];
  9905. }
  9906. /**
  9907. * Ticks one step forward in time. This will move the current overlap state to the "old" overlap state, and create a new one as current.
  9908. * @method tick
  9909. */
  9910. OverlapKeeper.prototype.tick = function() {
  9911. var last = this.overlappingShapesLastState;
  9912. var current = this.overlappingShapesCurrentState;
  9913. // Save old objects into pool
  9914. var l = last.keys.length;
  9915. while(l--){
  9916. var key = last.keys[l];
  9917. var lastObject = last.getByKey(key);
  9918. var currentObject = current.getByKey(key);
  9919. if(lastObject){
  9920. // The record is only used in the "last" dict, and will be removed. We might as well pool it.
  9921. this.recordPool.release(lastObject);
  9922. }
  9923. }
  9924. // Clear last object
  9925. last.reset();
  9926. // Transfer from new object to old
  9927. last.copy(current);
  9928. // Clear current object
  9929. current.reset();
  9930. };
  9931. /**
  9932. * @method setOverlapping
  9933. * @param {Body} bodyA
  9934. * @param {Body} shapeA
  9935. * @param {Body} bodyB
  9936. * @param {Body} shapeB
  9937. */
  9938. OverlapKeeper.prototype.setOverlapping = function(bodyA, shapeA, bodyB, shapeB) {
  9939. var last = this.overlappingShapesLastState;
  9940. var current = this.overlappingShapesCurrentState;
  9941. // Store current contact state
  9942. if(!current.get(shapeA.id, shapeB.id)){
  9943. var data = this.recordPool.get();
  9944. data.set(bodyA, shapeA, bodyB, shapeB);
  9945. current.set(shapeA.id, shapeB.id, data);
  9946. }
  9947. };
  9948. OverlapKeeper.prototype.getNewOverlaps = function(result){
  9949. return this.getDiff(this.overlappingShapesLastState, this.overlappingShapesCurrentState, result);
  9950. };
  9951. OverlapKeeper.prototype.getEndOverlaps = function(result){
  9952. return this.getDiff(this.overlappingShapesCurrentState, this.overlappingShapesLastState, result);
  9953. };
  9954. /**
  9955. * Checks if two bodies are currently overlapping.
  9956. * @method bodiesAreOverlapping
  9957. * @param {Body} bodyA
  9958. * @param {Body} bodyB
  9959. * @return {boolean}
  9960. */
  9961. OverlapKeeper.prototype.bodiesAreOverlapping = function(bodyA, bodyB){
  9962. var current = this.overlappingShapesCurrentState;
  9963. var l = current.keys.length;
  9964. while(l--){
  9965. var key = current.keys[l];
  9966. var data = current.data[key];
  9967. if((data.bodyA === bodyA && data.bodyB === bodyB) || data.bodyA === bodyB && data.bodyB === bodyA){
  9968. return true;
  9969. }
  9970. }
  9971. return false;
  9972. };
  9973. OverlapKeeper.prototype.getDiff = function(dictA, dictB, result){
  9974. var result = result || [];
  9975. var last = dictA;
  9976. var current = dictB;
  9977. result.length = 0;
  9978. var l = current.keys.length;
  9979. while(l--){
  9980. var key = current.keys[l];
  9981. var data = current.data[key];
  9982. if(!data){
  9983. throw new Error('Key '+key+' had no data!');
  9984. }
  9985. var lastData = last.data[key];
  9986. if(!lastData){
  9987. // Not overlapping in last state, but in current.
  9988. result.push(data);
  9989. }
  9990. }
  9991. return result;
  9992. };
  9993. OverlapKeeper.prototype.isNewOverlap = function(shapeA, shapeB){
  9994. var idA = shapeA.id|0,
  9995. idB = shapeB.id|0;
  9996. var last = this.overlappingShapesLastState;
  9997. var current = this.overlappingShapesCurrentState;
  9998. // Not in last but in new
  9999. return !!!last.get(idA, idB) && !!current.get(idA, idB);
  10000. };
  10001. OverlapKeeper.prototype.getNewBodyOverlaps = function(result){
  10002. this.tmpArray1.length = 0;
  10003. var overlaps = this.getNewOverlaps(this.tmpArray1);
  10004. return this.getBodyDiff(overlaps, result);
  10005. };
  10006. OverlapKeeper.prototype.getEndBodyOverlaps = function(result){
  10007. this.tmpArray1.length = 0;
  10008. var overlaps = this.getEndOverlaps(this.tmpArray1);
  10009. return this.getBodyDiff(overlaps, result);
  10010. };
  10011. OverlapKeeper.prototype.getBodyDiff = function(overlaps, result){
  10012. result = result || [];
  10013. var accumulator = this.tmpDict;
  10014. var l = overlaps.length;
  10015. while(l--){
  10016. var data = overlaps[l];
  10017. // Since we use body id's for the accumulator, these will be a subset of the original one
  10018. accumulator.set(data.bodyA.id|0, data.bodyB.id|0, data);
  10019. }
  10020. l = accumulator.keys.length;
  10021. while(l--){
  10022. var data = accumulator.getByKey(accumulator.keys[l]);
  10023. if(data){
  10024. result.push(data.bodyA, data.bodyB);
  10025. }
  10026. }
  10027. accumulator.reset();
  10028. return result;
  10029. };
  10030. },{"./OverlapKeeperRecord":53,"./OverlapKeeperRecordPool":54,"./TupleDictionary":56,"./Utils":57}],53:[function(_dereq_,module,exports){
  10031. module.exports = OverlapKeeperRecord;
  10032. /**
  10033. * Overlap data container for the OverlapKeeper
  10034. * @class OverlapKeeperRecord
  10035. * @constructor
  10036. * @param {Body} bodyA
  10037. * @param {Shape} shapeA
  10038. * @param {Body} bodyB
  10039. * @param {Shape} shapeB
  10040. */
  10041. function OverlapKeeperRecord(bodyA, shapeA, bodyB, shapeB){
  10042. /**
  10043. * @property {Shape} shapeA
  10044. */
  10045. this.shapeA = shapeA;
  10046. /**
  10047. * @property {Shape} shapeB
  10048. */
  10049. this.shapeB = shapeB;
  10050. /**
  10051. * @property {Body} bodyA
  10052. */
  10053. this.bodyA = bodyA;
  10054. /**
  10055. * @property {Body} bodyB
  10056. */
  10057. this.bodyB = bodyB;
  10058. }
  10059. /**
  10060. * Set the data for the record
  10061. * @method set
  10062. * @param {Body} bodyA
  10063. * @param {Shape} shapeA
  10064. * @param {Body} bodyB
  10065. * @param {Shape} shapeB
  10066. */
  10067. OverlapKeeperRecord.prototype.set = function(bodyA, shapeA, bodyB, shapeB){
  10068. OverlapKeeperRecord.call(this, bodyA, shapeA, bodyB, shapeB);
  10069. };
  10070. },{}],54:[function(_dereq_,module,exports){
  10071. var OverlapKeeperRecord = _dereq_('./OverlapKeeperRecord');
  10072. var Pool = _dereq_('./Pool');
  10073. module.exports = OverlapKeeperRecordPool;
  10074. /**
  10075. * @class
  10076. */
  10077. function OverlapKeeperRecordPool() {
  10078. Pool.apply(this, arguments);
  10079. }
  10080. OverlapKeeperRecordPool.prototype = new Pool();
  10081. OverlapKeeperRecordPool.prototype.constructor = OverlapKeeperRecordPool;
  10082. /**
  10083. * @method create
  10084. * @return {OverlapKeeperRecord}
  10085. */
  10086. OverlapKeeperRecordPool.prototype.create = function () {
  10087. return new OverlapKeeperRecord();
  10088. };
  10089. /**
  10090. * @method destroy
  10091. * @param {OverlapKeeperRecord} record
  10092. * @return {OverlapKeeperRecordPool}
  10093. */
  10094. OverlapKeeperRecordPool.prototype.destroy = function (record) {
  10095. record.bodyA = record.bodyB = record.shapeA = record.shapeB = null;
  10096. return this;
  10097. };
  10098. },{"./OverlapKeeperRecord":53,"./Pool":55}],55:[function(_dereq_,module,exports){
  10099. module.exports = Pool;
  10100. /**
  10101. * @class Object pooling utility.
  10102. */
  10103. function Pool(options) {
  10104. options = options || {};
  10105. /**
  10106. * @property {Array} objects
  10107. * @type {Array}
  10108. */
  10109. this.objects = [];
  10110. if(options.size !== undefined){
  10111. this.resize(options.size);
  10112. }
  10113. }
  10114. /**
  10115. * @method resize
  10116. * @param {number} size
  10117. * @return {Pool} Self, for chaining
  10118. */
  10119. Pool.prototype.resize = function (size) {
  10120. var objects = this.objects;
  10121. while (objects.length > size) {
  10122. objects.pop();
  10123. }
  10124. while (objects.length < size) {
  10125. objects.push(this.create());
  10126. }
  10127. return this;
  10128. };
  10129. /**
  10130. * Get an object from the pool or create a new instance.
  10131. * @method get
  10132. * @return {Object}
  10133. */
  10134. Pool.prototype.get = function () {
  10135. var objects = this.objects;
  10136. return objects.length ? objects.pop() : this.create();
  10137. };
  10138. /**
  10139. * Clean up and put the object back into the pool for later use.
  10140. * @method release
  10141. * @param {Object} object
  10142. * @return {Pool} Self for chaining
  10143. */
  10144. Pool.prototype.release = function (object) {
  10145. this.destroy(object);
  10146. this.objects.push(object);
  10147. return this;
  10148. };
  10149. },{}],56:[function(_dereq_,module,exports){
  10150. var Utils = _dereq_('./Utils');
  10151. module.exports = TupleDictionary;
  10152. /**
  10153. * @class TupleDictionary
  10154. * @constructor
  10155. */
  10156. function TupleDictionary() {
  10157. /**
  10158. * The data storage
  10159. * @property data
  10160. * @type {Object}
  10161. */
  10162. this.data = {};
  10163. /**
  10164. * Keys that are currently used.
  10165. * @property {Array} keys
  10166. */
  10167. this.keys = [];
  10168. }
  10169. /**
  10170. * Generate a key given two integers
  10171. * @method getKey
  10172. * @param {number} i
  10173. * @param {number} j
  10174. * @return {string}
  10175. */
  10176. TupleDictionary.prototype.getKey = function(id1, id2) {
  10177. id1 = id1|0;
  10178. id2 = id2|0;
  10179. if ( (id1|0) === (id2|0) ){
  10180. return -1;
  10181. }
  10182. // valid for values < 2^16
  10183. return ((id1|0) > (id2|0) ?
  10184. (id1 << 16) | (id2 & 0xFFFF) :
  10185. (id2 << 16) | (id1 & 0xFFFF))|0
  10186. ;
  10187. };
  10188. /**
  10189. * @method getByKey
  10190. * @param {Number} key
  10191. * @return {Object}
  10192. */
  10193. TupleDictionary.prototype.getByKey = function(key) {
  10194. key = key|0;
  10195. return this.data[key];
  10196. };
  10197. /**
  10198. * @method get
  10199. * @param {Number} i
  10200. * @param {Number} j
  10201. * @return {Number}
  10202. */
  10203. TupleDictionary.prototype.get = function(i, j) {
  10204. return this.data[this.getKey(i, j)];
  10205. };
  10206. /**
  10207. * Set a value.
  10208. * @method set
  10209. * @param {Number} i
  10210. * @param {Number} j
  10211. * @param {Number} value
  10212. */
  10213. TupleDictionary.prototype.set = function(i, j, value) {
  10214. if(!value){
  10215. throw new Error("No data!");
  10216. }
  10217. var key = this.getKey(i, j);
  10218. // Check if key already exists
  10219. if(!this.data[key]){
  10220. this.keys.push(key);
  10221. }
  10222. this.data[key] = value;
  10223. return key;
  10224. };
  10225. /**
  10226. * Remove all data.
  10227. * @method reset
  10228. */
  10229. TupleDictionary.prototype.reset = function() {
  10230. var data = this.data,
  10231. keys = this.keys;
  10232. var l = keys.length;
  10233. while(l--) {
  10234. delete data[keys[l]];
  10235. }
  10236. keys.length = 0;
  10237. };
  10238. /**
  10239. * Copy another TupleDictionary. Note that all data in this dictionary will be removed.
  10240. * @method copy
  10241. * @param {TupleDictionary} dict The TupleDictionary to copy into this one.
  10242. */
  10243. TupleDictionary.prototype.copy = function(dict) {
  10244. this.reset();
  10245. Utils.appendArray(this.keys, dict.keys);
  10246. var l = dict.keys.length;
  10247. while(l--){
  10248. var key = dict.keys[l];
  10249. this.data[key] = dict.data[key];
  10250. }
  10251. };
  10252. },{"./Utils":57}],57:[function(_dereq_,module,exports){
  10253. /* global P2_ARRAY_TYPE */
  10254. module.exports = Utils;
  10255. /**
  10256. * Misc utility functions
  10257. * @class Utils
  10258. * @constructor
  10259. */
  10260. function Utils(){}
  10261. /**
  10262. * Append the values in array b to the array a. See <a href="http://stackoverflow.com/questions/1374126/how-to-append-an-array-to-an-existing-javascript-array/1374131#1374131">this</a> for an explanation.
  10263. * @method appendArray
  10264. * @static
  10265. * @param {Array} a
  10266. * @param {Array} b
  10267. */
  10268. Utils.appendArray = function(a,b){
  10269. if (b.length < 150000) {
  10270. a.push.apply(a, b);
  10271. } else {
  10272. for (var i = 0, len = b.length; i !== len; ++i) {
  10273. a.push(b[i]);
  10274. }
  10275. }
  10276. };
  10277. /**
  10278. * Garbage free Array.splice(). Does not allocate a new array.
  10279. * @method splice
  10280. * @static
  10281. * @param {Array} array
  10282. * @param {Number} index
  10283. * @param {Number} howmany
  10284. */
  10285. Utils.splice = function(array,index,howmany){
  10286. howmany = howmany || 1;
  10287. for (var i=index, len=array.length-howmany; i < len; i++){
  10288. array[i] = array[i + howmany];
  10289. }
  10290. array.length = len;
  10291. };
  10292. /**
  10293. * The array type to use for internal numeric computations throughout the library. Float32Array is used if it is available, but falls back on Array. If you want to set array type manually, inject it via the global variable P2_ARRAY_TYPE. See example below.
  10294. * @static
  10295. * @property {function} ARRAY_TYPE
  10296. * @example
  10297. * <script>
  10298. * <!-- Inject your preferred array type before loading p2.js -->
  10299. * P2_ARRAY_TYPE = Array;
  10300. * </script>
  10301. * <script src="p2.js"></script>
  10302. */
  10303. if(typeof P2_ARRAY_TYPE !== 'undefined') {
  10304. Utils.ARRAY_TYPE = P2_ARRAY_TYPE;
  10305. } else if (typeof Float32Array !== 'undefined'){
  10306. Utils.ARRAY_TYPE = Float32Array;
  10307. } else {
  10308. Utils.ARRAY_TYPE = Array;
  10309. }
  10310. /**
  10311. * Extend an object with the properties of another
  10312. * @static
  10313. * @method extend
  10314. * @param {object} a
  10315. * @param {object} b
  10316. */
  10317. Utils.extend = function(a,b){
  10318. for(var key in b){
  10319. a[key] = b[key];
  10320. }
  10321. };
  10322. /**
  10323. * Extend an options object with default values.
  10324. * @static
  10325. * @method defaults
  10326. * @param {object} options The options object. May be falsy: in this case, a new object is created and returned.
  10327. * @param {object} defaults An object containing default values.
  10328. * @return {object} The modified options object.
  10329. */
  10330. Utils.defaults = function(options, defaults){
  10331. options = options || {};
  10332. for(var key in defaults){
  10333. if(!(key in options)){
  10334. options[key] = defaults[key];
  10335. }
  10336. }
  10337. return options;
  10338. };
  10339. },{}],58:[function(_dereq_,module,exports){
  10340. var Body = _dereq_('../objects/Body');
  10341. module.exports = Island;
  10342. /**
  10343. * An island of bodies connected with equations.
  10344. * @class Island
  10345. * @constructor
  10346. */
  10347. function Island(){
  10348. /**
  10349. * Current equations in this island.
  10350. * @property equations
  10351. * @type {Array}
  10352. */
  10353. this.equations = [];
  10354. /**
  10355. * Current bodies in this island.
  10356. * @property bodies
  10357. * @type {Array}
  10358. */
  10359. this.bodies = [];
  10360. }
  10361. /**
  10362. * Clean this island from bodies and equations.
  10363. * @method reset
  10364. */
  10365. Island.prototype.reset = function(){
  10366. this.equations.length = this.bodies.length = 0;
  10367. };
  10368. var bodyIds = [];
  10369. /**
  10370. * Get all unique bodies in this island.
  10371. * @method getBodies
  10372. * @return {Array} An array of Body
  10373. */
  10374. Island.prototype.getBodies = function(result){
  10375. var bodies = result || [],
  10376. eqs = this.equations;
  10377. bodyIds.length = 0;
  10378. for(var i=0; i!==eqs.length; i++){
  10379. var eq = eqs[i];
  10380. if(bodyIds.indexOf(eq.bodyA.id)===-1){
  10381. bodies.push(eq.bodyA);
  10382. bodyIds.push(eq.bodyA.id);
  10383. }
  10384. if(bodyIds.indexOf(eq.bodyB.id)===-1){
  10385. bodies.push(eq.bodyB);
  10386. bodyIds.push(eq.bodyB.id);
  10387. }
  10388. }
  10389. return bodies;
  10390. };
  10391. /**
  10392. * Check if the entire island wants to sleep.
  10393. * @method wantsToSleep
  10394. * @return {Boolean}
  10395. */
  10396. Island.prototype.wantsToSleep = function(){
  10397. for(var i=0; i<this.bodies.length; i++){
  10398. var b = this.bodies[i];
  10399. if(b.type === Body.DYNAMIC && !b.wantsToSleep){
  10400. return false;
  10401. }
  10402. }
  10403. return true;
  10404. };
  10405. /**
  10406. * Make all bodies in the island sleep.
  10407. * @method sleep
  10408. */
  10409. Island.prototype.sleep = function(){
  10410. for(var i=0; i<this.bodies.length; i++){
  10411. var b = this.bodies[i];
  10412. b.sleep();
  10413. }
  10414. return true;
  10415. };
  10416. },{"../objects/Body":31}],59:[function(_dereq_,module,exports){
  10417. var vec2 = _dereq_('../math/vec2')
  10418. , Island = _dereq_('./Island')
  10419. , IslandNode = _dereq_('./IslandNode')
  10420. , IslandNodePool = _dereq_('./../utils/IslandNodePool')
  10421. , IslandPool = _dereq_('./../utils/IslandPool')
  10422. , Body = _dereq_('../objects/Body');
  10423. module.exports = IslandManager;
  10424. /**
  10425. * Splits the system of bodies and equations into independent islands
  10426. *
  10427. * @class IslandManager
  10428. * @constructor
  10429. * @param {Object} [options]
  10430. * @extends Solver
  10431. */
  10432. function IslandManager(options){
  10433. /**
  10434. * @property nodePool
  10435. * @type {IslandNodePool}
  10436. */
  10437. this.nodePool = new IslandNodePool({ size: 16 });
  10438. /**
  10439. * @property islandPool
  10440. * @type {IslandPool}
  10441. */
  10442. this.islandPool = new IslandPool({ size: 8 });
  10443. /**
  10444. * The equations to split. Manually fill this array before running .split().
  10445. * @property {Array} equations
  10446. */
  10447. this.equations = [];
  10448. /**
  10449. * The resulting {{#crossLink "Island"}}{{/crossLink}}s.
  10450. * @property {Array} islands
  10451. */
  10452. this.islands = [];
  10453. /**
  10454. * The resulting graph nodes.
  10455. * @property {Array} nodes
  10456. */
  10457. this.nodes = [];
  10458. /**
  10459. * The node queue, used when traversing the graph of nodes.
  10460. * @private
  10461. * @property {Array} queue
  10462. */
  10463. this.queue = [];
  10464. }
  10465. /**
  10466. * Get an unvisited node from a list of nodes.
  10467. * @static
  10468. * @method getUnvisitedNode
  10469. * @param {Array} nodes
  10470. * @return {IslandNode|boolean} The node if found, else false.
  10471. */
  10472. IslandManager.getUnvisitedNode = function(nodes){
  10473. var Nnodes = nodes.length;
  10474. for(var i=0; i!==Nnodes; i++){
  10475. var node = nodes[i];
  10476. if(!node.visited && node.body.type === Body.DYNAMIC){
  10477. return node;
  10478. }
  10479. }
  10480. return false;
  10481. };
  10482. /**
  10483. * Visit a node.
  10484. * @method visit
  10485. * @param {IslandNode} node
  10486. * @param {Array} bds
  10487. * @param {Array} eqs
  10488. */
  10489. IslandManager.prototype.visit = function (node,bds,eqs){
  10490. bds.push(node.body);
  10491. var Neqs = node.equations.length;
  10492. for(var i=0; i!==Neqs; i++){
  10493. var eq = node.equations[i];
  10494. if(eqs.indexOf(eq) === -1){ // Already added?
  10495. eqs.push(eq);
  10496. }
  10497. }
  10498. };
  10499. /**
  10500. * Runs the search algorithm, starting at a root node. The resulting bodies and equations will be stored in the provided arrays.
  10501. * @method bfs
  10502. * @param {IslandNode} root The node to start from
  10503. * @param {Array} bds An array to append resulting Bodies to.
  10504. * @param {Array} eqs An array to append resulting Equations to.
  10505. */
  10506. IslandManager.prototype.bfs = function(root,bds,eqs){
  10507. // Reset the visit queue
  10508. var queue = this.queue;
  10509. queue.length = 0;
  10510. // Add root node to queue
  10511. queue.push(root);
  10512. root.visited = true;
  10513. this.visit(root,bds,eqs);
  10514. // Process all queued nodes
  10515. while(queue.length) {
  10516. // Get next node in the queue
  10517. var node = queue.pop();
  10518. // Visit unvisited neighboring nodes
  10519. var child;
  10520. while((child = IslandManager.getUnvisitedNode(node.neighbors))) {
  10521. child.visited = true;
  10522. this.visit(child,bds,eqs);
  10523. // Only visit the children of this node if it's dynamic
  10524. if(child.body.type === Body.DYNAMIC){
  10525. queue.push(child);
  10526. }
  10527. }
  10528. }
  10529. };
  10530. /**
  10531. * Split the world into independent islands. The result is stored in .islands.
  10532. * @method split
  10533. * @param {World} world
  10534. * @return {Array} The generated islands
  10535. */
  10536. IslandManager.prototype.split = function(world){
  10537. var bodies = world.bodies,
  10538. nodes = this.nodes,
  10539. equations = this.equations;
  10540. // Move old nodes to the node pool
  10541. while(nodes.length){
  10542. this.nodePool.release(nodes.pop());
  10543. }
  10544. // Create needed nodes, reuse if possible
  10545. for(var i=0; i!==bodies.length; i++){
  10546. var node = this.nodePool.get();
  10547. node.body = bodies[i];
  10548. nodes.push(node);
  10549. // if(this.nodePool.length){
  10550. // var node = this.nodePool.pop();
  10551. // node.reset();
  10552. // node.body = bodies[i];
  10553. // nodes.push(node);
  10554. // } else {
  10555. // nodes.push(new IslandNode(bodies[i]));
  10556. // }
  10557. }
  10558. // Add connectivity data. Each equation connects 2 bodies.
  10559. for(var k=0; k!==equations.length; k++){
  10560. var eq=equations[k],
  10561. i=bodies.indexOf(eq.bodyA),
  10562. j=bodies.indexOf(eq.bodyB),
  10563. ni=nodes[i],
  10564. nj=nodes[j];
  10565. ni.neighbors.push(nj);
  10566. nj.neighbors.push(ni);
  10567. ni.equations.push(eq);
  10568. nj.equations.push(eq);
  10569. }
  10570. // Move old islands to the island pool
  10571. var islands = this.islands;
  10572. for(var i=0; i<islands.length; i++){
  10573. this.islandPool.release(islands[i]);
  10574. }
  10575. islands.length = 0;
  10576. // Get islands
  10577. var child;
  10578. while((child = IslandManager.getUnvisitedNode(nodes))){
  10579. // Create new island
  10580. var island = this.islandPool.get();
  10581. // Get all equations and bodies in this island
  10582. this.bfs(child, island.bodies, island.equations);
  10583. islands.push(island);
  10584. }
  10585. return islands;
  10586. };
  10587. },{"../math/vec2":30,"../objects/Body":31,"./../utils/IslandNodePool":50,"./../utils/IslandPool":51,"./Island":58,"./IslandNode":60}],60:[function(_dereq_,module,exports){
  10588. module.exports = IslandNode;
  10589. /**
  10590. * Holds a body and keeps track of some additional properties needed for graph traversal.
  10591. * @class IslandNode
  10592. * @constructor
  10593. * @param {Body} body
  10594. */
  10595. function IslandNode(body){
  10596. /**
  10597. * The body that is contained in this node.
  10598. * @property {Body} body
  10599. */
  10600. this.body = body;
  10601. /**
  10602. * Neighboring IslandNodes
  10603. * @property {Array} neighbors
  10604. */
  10605. this.neighbors = [];
  10606. /**
  10607. * Equations connected to this node.
  10608. * @property {Array} equations
  10609. */
  10610. this.equations = [];
  10611. /**
  10612. * If this node was visiting during the graph traversal.
  10613. * @property visited
  10614. * @type {Boolean}
  10615. */
  10616. this.visited = false;
  10617. }
  10618. /**
  10619. * Clean this node from bodies and equations.
  10620. * @method reset
  10621. */
  10622. IslandNode.prototype.reset = function(){
  10623. this.equations.length = 0;
  10624. this.neighbors.length = 0;
  10625. this.visited = false;
  10626. this.body = null;
  10627. };
  10628. },{}],61:[function(_dereq_,module,exports){
  10629. var GSSolver = _dereq_('../solver/GSSolver')
  10630. , Solver = _dereq_('../solver/Solver')
  10631. , Ray = _dereq_('../collision/Ray')
  10632. , vec2 = _dereq_('../math/vec2')
  10633. , Circle = _dereq_('../shapes/Circle')
  10634. , Convex = _dereq_('../shapes/Convex')
  10635. , Line = _dereq_('../shapes/Line')
  10636. , Plane = _dereq_('../shapes/Plane')
  10637. , Capsule = _dereq_('../shapes/Capsule')
  10638. , Particle = _dereq_('../shapes/Particle')
  10639. , EventEmitter = _dereq_('../events/EventEmitter')
  10640. , Body = _dereq_('../objects/Body')
  10641. , Shape = _dereq_('../shapes/Shape')
  10642. , LinearSpring = _dereq_('../objects/LinearSpring')
  10643. , Material = _dereq_('../material/Material')
  10644. , ContactMaterial = _dereq_('../material/ContactMaterial')
  10645. , DistanceConstraint = _dereq_('../constraints/DistanceConstraint')
  10646. , Constraint = _dereq_('../constraints/Constraint')
  10647. , LockConstraint = _dereq_('../constraints/LockConstraint')
  10648. , RevoluteConstraint = _dereq_('../constraints/RevoluteConstraint')
  10649. , PrismaticConstraint = _dereq_('../constraints/PrismaticConstraint')
  10650. , GearConstraint = _dereq_('../constraints/GearConstraint')
  10651. , pkg = _dereq_('../../package.json')
  10652. , Broadphase = _dereq_('../collision/Broadphase')
  10653. , AABB = _dereq_('../collision/AABB')
  10654. , SAPBroadphase = _dereq_('../collision/SAPBroadphase')
  10655. , Narrowphase = _dereq_('../collision/Narrowphase')
  10656. , Utils = _dereq_('../utils/Utils')
  10657. , OverlapKeeper = _dereq_('../utils/OverlapKeeper')
  10658. , IslandManager = _dereq_('./IslandManager')
  10659. , RotationalSpring = _dereq_('../objects/RotationalSpring');
  10660. module.exports = World;
  10661. /**
  10662. * The dynamics world, where all bodies and constraints live.
  10663. *
  10664. * @class World
  10665. * @constructor
  10666. * @param {Object} [options]
  10667. * @param {Solver} [options.solver] Defaults to GSSolver.
  10668. * @param {Array} [options.gravity] Defaults to y=-9.78.
  10669. * @param {Broadphase} [options.broadphase] Defaults to SAPBroadphase
  10670. * @param {Boolean} [options.islandSplit=true]
  10671. * @extends EventEmitter
  10672. *
  10673. * @example
  10674. * var world = new World({
  10675. * gravity: [0, -10],
  10676. * broadphase: new SAPBroadphase()
  10677. * });
  10678. * world.addBody(new Body());
  10679. */
  10680. function World(options){
  10681. EventEmitter.apply(this);
  10682. options = options || {};
  10683. /**
  10684. * All springs in the world. To add a spring to the world, use {{#crossLink "World/addSpring:method"}}{{/crossLink}}.
  10685. *
  10686. * @property springs
  10687. * @type {Array}
  10688. */
  10689. this.springs = [];
  10690. /**
  10691. * All bodies in the world. To add a body to the world, use {{#crossLink "World/addBody:method"}}{{/crossLink}}.
  10692. * @property {Array} bodies
  10693. */
  10694. this.bodies = [];
  10695. /**
  10696. * Disabled body collision pairs. See {{#crossLink "World/disableBodyCollision:method"}}.
  10697. * @private
  10698. * @property {Array} disabledBodyCollisionPairs
  10699. */
  10700. this.disabledBodyCollisionPairs = [];
  10701. /**
  10702. * The solver used to satisfy constraints and contacts. Default is {{#crossLink "GSSolver"}}{{/crossLink}}.
  10703. * @property {Solver} solver
  10704. */
  10705. this.solver = options.solver || new GSSolver();
  10706. /**
  10707. * The narrowphase to use to generate contacts.
  10708. *
  10709. * @property narrowphase
  10710. * @type {Narrowphase}
  10711. */
  10712. this.narrowphase = new Narrowphase(this);
  10713. /**
  10714. * The island manager of this world.
  10715. * @property {IslandManager} islandManager
  10716. */
  10717. this.islandManager = new IslandManager();
  10718. /**
  10719. * Gravity in the world. This is applied on all bodies in the beginning of each step().
  10720. *
  10721. * @property gravity
  10722. * @type {Array}
  10723. */
  10724. this.gravity = vec2.fromValues(0, -9.78);
  10725. if(options.gravity){
  10726. vec2.copy(this.gravity, options.gravity);
  10727. }
  10728. /**
  10729. * Gravity to use when approximating the friction max force (mu*mass*gravity).
  10730. * @property {Number} frictionGravity
  10731. */
  10732. this.frictionGravity = vec2.length(this.gravity) || 10;
  10733. /**
  10734. * Set to true if you want .frictionGravity to be automatically set to the length of .gravity.
  10735. * @property {Boolean} useWorldGravityAsFrictionGravity
  10736. * @default true
  10737. */
  10738. this.useWorldGravityAsFrictionGravity = true;
  10739. /**
  10740. * If the length of .gravity is zero, and .useWorldGravityAsFrictionGravity=true, then switch to using .frictionGravity for friction instead. This fallback is useful for gravityless games.
  10741. * @property {Boolean} useFrictionGravityOnZeroGravity
  10742. * @default true
  10743. */
  10744. this.useFrictionGravityOnZeroGravity = true;
  10745. /**
  10746. * The broadphase algorithm to use.
  10747. *
  10748. * @property broadphase
  10749. * @type {Broadphase}
  10750. */
  10751. this.broadphase = options.broadphase || new SAPBroadphase();
  10752. this.broadphase.setWorld(this);
  10753. /**
  10754. * User-added constraints.
  10755. *
  10756. * @property constraints
  10757. * @type {Array}
  10758. */
  10759. this.constraints = [];
  10760. /**
  10761. * Dummy default material in the world, used in .defaultContactMaterial
  10762. * @property {Material} defaultMaterial
  10763. */
  10764. this.defaultMaterial = new Material();
  10765. /**
  10766. * The default contact material to use, if no contact material was set for the colliding materials.
  10767. * @property {ContactMaterial} defaultContactMaterial
  10768. */
  10769. this.defaultContactMaterial = new ContactMaterial(this.defaultMaterial,this.defaultMaterial);
  10770. /**
  10771. * For keeping track of what time step size we used last step
  10772. * @property lastTimeStep
  10773. * @type {Number}
  10774. */
  10775. this.lastTimeStep = 1/60;
  10776. /**
  10777. * Enable to automatically apply spring forces each step.
  10778. * @property applySpringForces
  10779. * @type {Boolean}
  10780. * @default true
  10781. */
  10782. this.applySpringForces = true;
  10783. /**
  10784. * Enable to automatically apply body damping each step.
  10785. * @property applyDamping
  10786. * @type {Boolean}
  10787. * @default true
  10788. */
  10789. this.applyDamping = true;
  10790. /**
  10791. * Enable to automatically apply gravity each step.
  10792. * @property applyGravity
  10793. * @type {Boolean}
  10794. * @default true
  10795. */
  10796. this.applyGravity = true;
  10797. /**
  10798. * Enable/disable constraint solving in each step.
  10799. * @property solveConstraints
  10800. * @type {Boolean}
  10801. * @default true
  10802. */
  10803. this.solveConstraints = true;
  10804. /**
  10805. * The ContactMaterials added to the World.
  10806. * @property contactMaterials
  10807. * @type {Array}
  10808. */
  10809. this.contactMaterials = [];
  10810. /**
  10811. * World time.
  10812. * @property time
  10813. * @type {Number}
  10814. */
  10815. this.time = 0.0;
  10816. this.accumulator = 0;
  10817. /**
  10818. * Is true during step().
  10819. * @property {Boolean} stepping
  10820. */
  10821. this.stepping = false;
  10822. /**
  10823. * Bodies that are scheduled to be removed at the end of the step.
  10824. * @property {Array} bodiesToBeRemoved
  10825. * @private
  10826. */
  10827. this.bodiesToBeRemoved = [];
  10828. /**
  10829. * Whether to enable island splitting. Island splitting can be an advantage for both precision and performance. See {{#crossLink "IslandManager"}}{{/crossLink}}.
  10830. * @property {Boolean} islandSplit
  10831. * @default true
  10832. */
  10833. this.islandSplit = typeof(options.islandSplit)!=="undefined" ? !!options.islandSplit : true;
  10834. /**
  10835. * Set to true if you want to the world to emit the "impact" event. Turning this off could improve performance.
  10836. * @property emitImpactEvent
  10837. * @type {Boolean}
  10838. * @default true
  10839. */
  10840. this.emitImpactEvent = true;
  10841. // Id counters
  10842. this._constraintIdCounter = 0;
  10843. this._bodyIdCounter = 0;
  10844. /**
  10845. * Fired after the step().
  10846. * @event postStep
  10847. */
  10848. this.postStepEvent = {
  10849. type : "postStep"
  10850. };
  10851. /**
  10852. * Fired when a body is added to the world.
  10853. * @event addBody
  10854. * @param {Body} body
  10855. */
  10856. this.addBodyEvent = {
  10857. type : "addBody",
  10858. body : null
  10859. };
  10860. /**
  10861. * Fired when a body is removed from the world.
  10862. * @event removeBody
  10863. * @param {Body} body
  10864. */
  10865. this.removeBodyEvent = {
  10866. type : "removeBody",
  10867. body : null
  10868. };
  10869. /**
  10870. * Fired when a spring is added to the world.
  10871. * @event addSpring
  10872. * @param {Spring} spring
  10873. */
  10874. this.addSpringEvent = {
  10875. type : "addSpring",
  10876. spring : null
  10877. };
  10878. /**
  10879. * Fired when a first contact is created between two bodies. This event is fired after the step has been done.
  10880. * @event impact
  10881. * @param {Body} bodyA
  10882. * @param {Body} bodyB
  10883. */
  10884. this.impactEvent = {
  10885. type: "impact",
  10886. bodyA : null,
  10887. bodyB : null,
  10888. shapeA : null,
  10889. shapeB : null,
  10890. contactEquation : null
  10891. };
  10892. /**
  10893. * Fired after the Broadphase has collected collision pairs in the world.
  10894. * Inside the event handler, you can modify the pairs array as you like, to
  10895. * prevent collisions between objects that you don't want.
  10896. * @event postBroadphase
  10897. * @param {Array} pairs An array of collision pairs. If this array is [body1,body2,body3,body4], then the body pairs 1,2 and 3,4 would advance to narrowphase.
  10898. */
  10899. this.postBroadphaseEvent = {
  10900. type: "postBroadphase",
  10901. pairs: null
  10902. };
  10903. /**
  10904. * How to deactivate bodies during simulation. Possible modes are: {{#crossLink "World/NO_SLEEPING:property"}}World.NO_SLEEPING{{/crossLink}}, {{#crossLink "World/BODY_SLEEPING:property"}}World.BODY_SLEEPING{{/crossLink}} and {{#crossLink "World/ISLAND_SLEEPING:property"}}World.ISLAND_SLEEPING{{/crossLink}}.
  10905. * If sleeping is enabled, you might need to {{#crossLink "Body/wakeUp:method"}}wake up{{/crossLink}} the bodies if they fall asleep when they shouldn't. If you want to enable sleeping in the world, but want to disable it for a particular body, see {{#crossLink "Body/allowSleep:property"}}Body.allowSleep{{/crossLink}}.
  10906. * @property sleepMode
  10907. * @type {number}
  10908. * @default World.NO_SLEEPING
  10909. */
  10910. this.sleepMode = World.NO_SLEEPING;
  10911. /**
  10912. * Fired when two shapes starts start to overlap. Fired in the narrowphase, during step.
  10913. * @event beginContact
  10914. * @param {Shape} shapeA
  10915. * @param {Shape} shapeB
  10916. * @param {Body} bodyA
  10917. * @param {Body} bodyB
  10918. * @param {Array} contactEquations
  10919. */
  10920. this.beginContactEvent = {
  10921. type: "beginContact",
  10922. shapeA: null,
  10923. shapeB: null,
  10924. bodyA: null,
  10925. bodyB: null,
  10926. contactEquations: []
  10927. };
  10928. /**
  10929. * Fired when two shapes stop overlapping, after the narrowphase (during step).
  10930. * @event endContact
  10931. * @param {Shape} shapeA
  10932. * @param {Shape} shapeB
  10933. * @param {Body} bodyA
  10934. * @param {Body} bodyB
  10935. */
  10936. this.endContactEvent = {
  10937. type: "endContact",
  10938. shapeA: null,
  10939. shapeB: null,
  10940. bodyA: null,
  10941. bodyB: null
  10942. };
  10943. /**
  10944. * Fired just before equations are added to the solver to be solved. Can be used to control what equations goes into the solver.
  10945. * @event preSolve
  10946. * @param {Array} contactEquations An array of contacts to be solved.
  10947. * @param {Array} frictionEquations An array of friction equations to be solved.
  10948. */
  10949. this.preSolveEvent = {
  10950. type: "preSolve",
  10951. contactEquations: null,
  10952. frictionEquations: null
  10953. };
  10954. // For keeping track of overlapping shapes
  10955. this.overlappingShapesLastState = { keys:[] };
  10956. this.overlappingShapesCurrentState = { keys:[] };
  10957. /**
  10958. * @property {OverlapKeeper} overlapKeeper
  10959. */
  10960. this.overlapKeeper = new OverlapKeeper();
  10961. }
  10962. World.prototype = new Object(EventEmitter.prototype);
  10963. World.prototype.constructor = World;
  10964. /**
  10965. * Never deactivate bodies.
  10966. * @static
  10967. * @property {number} NO_SLEEPING
  10968. */
  10969. World.NO_SLEEPING = 1;
  10970. /**
  10971. * Deactivate individual bodies if they are sleepy.
  10972. * @static
  10973. * @property {number} BODY_SLEEPING
  10974. */
  10975. World.BODY_SLEEPING = 2;
  10976. /**
  10977. * Deactivates bodies that are in contact, if all of them are sleepy. Note that you must enable {{#crossLink "World/islandSplit:property"}}.islandSplit{{/crossLink}} for this to work.
  10978. * @static
  10979. * @property {number} ISLAND_SLEEPING
  10980. */
  10981. World.ISLAND_SLEEPING = 4;
  10982. /**
  10983. * Add a constraint to the simulation.
  10984. *
  10985. * @method addConstraint
  10986. * @param {Constraint} constraint
  10987. * @example
  10988. * var constraint = new LockConstraint(bodyA, bodyB);
  10989. * world.addConstraint(constraint);
  10990. */
  10991. World.prototype.addConstraint = function(constraint){
  10992. this.constraints.push(constraint);
  10993. };
  10994. /**
  10995. * Add a ContactMaterial to the simulation.
  10996. * @method addContactMaterial
  10997. * @param {ContactMaterial} contactMaterial
  10998. */
  10999. World.prototype.addContactMaterial = function(contactMaterial){
  11000. this.contactMaterials.push(contactMaterial);
  11001. };
  11002. /**
  11003. * Removes a contact material
  11004. *
  11005. * @method removeContactMaterial
  11006. * @param {ContactMaterial} cm
  11007. */
  11008. World.prototype.removeContactMaterial = function(cm){
  11009. var idx = this.contactMaterials.indexOf(cm);
  11010. if(idx!==-1){
  11011. Utils.splice(this.contactMaterials,idx,1);
  11012. }
  11013. };
  11014. /**
  11015. * Get a contact material given two materials
  11016. * @method getContactMaterial
  11017. * @param {Material} materialA
  11018. * @param {Material} materialB
  11019. * @return {ContactMaterial} The matching ContactMaterial, or false on fail.
  11020. * @todo Use faster hash map to lookup from material id's
  11021. */
  11022. World.prototype.getContactMaterial = function(materialA,materialB){
  11023. var cmats = this.contactMaterials;
  11024. for(var i=0, N=cmats.length; i!==N; i++){
  11025. var cm = cmats[i];
  11026. if( (cm.materialA.id === materialA.id) && (cm.materialB.id === materialB.id) ||
  11027. (cm.materialA.id === materialB.id) && (cm.materialB.id === materialA.id) ){
  11028. return cm;
  11029. }
  11030. }
  11031. return false;
  11032. };
  11033. /**
  11034. * Removes a constraint
  11035. *
  11036. * @method removeConstraint
  11037. * @param {Constraint} constraint
  11038. */
  11039. World.prototype.removeConstraint = function(constraint){
  11040. var idx = this.constraints.indexOf(constraint);
  11041. if(idx!==-1){
  11042. Utils.splice(this.constraints,idx,1);
  11043. }
  11044. };
  11045. var step_r = vec2.create(),
  11046. step_runit = vec2.create(),
  11047. step_u = vec2.create(),
  11048. step_f = vec2.create(),
  11049. step_fhMinv = vec2.create(),
  11050. step_velodt = vec2.create(),
  11051. step_mg = vec2.create(),
  11052. xiw = vec2.fromValues(0,0),
  11053. xjw = vec2.fromValues(0,0),
  11054. zero = vec2.fromValues(0,0),
  11055. interpvelo = vec2.fromValues(0,0);
  11056. /**
  11057. * Step the physics world forward in time.
  11058. *
  11059. * There are two modes. The simple mode is fixed timestepping without interpolation. In this case you only use the first argument. The second case uses interpolation. In that you also provide the time since the function was last used, as well as the maximum fixed timesteps to take.
  11060. *
  11061. * @method step
  11062. * @param {Number} dt The fixed time step size to use.
  11063. * @param {Number} [timeSinceLastCalled=0] The time elapsed since the function was last called.
  11064. * @param {Number} [maxSubSteps=10] Maximum number of fixed steps to take per function call.
  11065. *
  11066. * @example
  11067. * // Simple fixed timestepping without interpolation
  11068. * var fixedTimeStep = 1 / 60;
  11069. * var world = new World();
  11070. * var body = new Body({ mass: 1 });
  11071. * world.addBody(body);
  11072. *
  11073. * function animate(){
  11074. * requestAnimationFrame(animate);
  11075. * world.step(fixedTimeStep);
  11076. * renderBody(body.position, body.angle);
  11077. * }
  11078. *
  11079. * // Start animation loop
  11080. * requestAnimationFrame(animate);
  11081. *
  11082. * @example
  11083. * // Fixed timestepping with interpolation
  11084. * var maxSubSteps = 10;
  11085. * var lastTimeSeconds;
  11086. *
  11087. * function animate(t){
  11088. * requestAnimationFrame(animate);
  11089. * timeSeconds = t / 1000;
  11090. * lastTimeSeconds = lastTimeSeconds || timeSeconds;
  11091. *
  11092. * deltaTime = timeSeconds - lastTimeSeconds;
  11093. * world.step(fixedTimeStep, deltaTime, maxSubSteps);
  11094. *
  11095. * renderBody(body.interpolatedPosition, body.interpolatedAngle);
  11096. * }
  11097. *
  11098. * // Start animation loop
  11099. * requestAnimationFrame(animate);
  11100. *
  11101. * @see http://bulletphysics.org/mediawiki-1.5.8/index.php/Stepping_The_World
  11102. */
  11103. World.prototype.step = function(dt,timeSinceLastCalled,maxSubSteps){
  11104. maxSubSteps = maxSubSteps || 10;
  11105. timeSinceLastCalled = timeSinceLastCalled || 0;
  11106. if(timeSinceLastCalled === 0){ // Fixed, simple stepping
  11107. this.internalStep(dt);
  11108. // Increment time
  11109. this.time += dt;
  11110. } else {
  11111. this.accumulator += timeSinceLastCalled;
  11112. var substeps = 0;
  11113. while (this.accumulator >= dt && substeps < maxSubSteps) {
  11114. // Do fixed steps to catch up
  11115. this.internalStep(dt);
  11116. this.time += dt;
  11117. this.accumulator -= dt;
  11118. substeps++;
  11119. }
  11120. var t = (this.accumulator % dt) / dt;
  11121. for(var j=0; j!==this.bodies.length; j++){
  11122. var b = this.bodies[j];
  11123. vec2.lerp(b.interpolatedPosition, b.previousPosition, b.position, t);
  11124. b.interpolatedAngle = b.previousAngle + t * (b.angle - b.previousAngle);
  11125. }
  11126. }
  11127. };
  11128. var endOverlaps = [];
  11129. /**
  11130. * Make a fixed step.
  11131. * @method internalStep
  11132. * @param {number} dt
  11133. * @private
  11134. */
  11135. World.prototype.internalStep = function(dt){
  11136. this.stepping = true;
  11137. var that = this,
  11138. Nsprings = this.springs.length,
  11139. springs = this.springs,
  11140. bodies = this.bodies,
  11141. g = this.gravity,
  11142. solver = this.solver,
  11143. Nbodies = this.bodies.length,
  11144. broadphase = this.broadphase,
  11145. np = this.narrowphase,
  11146. constraints = this.constraints,
  11147. t0, t1,
  11148. fhMinv = step_fhMinv,
  11149. velodt = step_velodt,
  11150. mg = step_mg,
  11151. scale = vec2.scale,
  11152. add = vec2.add,
  11153. rotate = vec2.rotate,
  11154. islandManager = this.islandManager;
  11155. this.overlapKeeper.tick();
  11156. this.lastTimeStep = dt;
  11157. // Update approximate friction gravity.
  11158. if(this.useWorldGravityAsFrictionGravity){
  11159. var gravityLen = vec2.length(this.gravity);
  11160. if(!(gravityLen === 0 && this.useFrictionGravityOnZeroGravity)){
  11161. // Nonzero gravity. Use it.
  11162. this.frictionGravity = gravityLen;
  11163. }
  11164. }
  11165. // Add gravity to bodies
  11166. if(this.applyGravity){
  11167. for(var i=0; i!==Nbodies; i++){
  11168. var b = bodies[i],
  11169. fi = b.force;
  11170. if(b.type !== Body.DYNAMIC || b.sleepState === Body.SLEEPING){
  11171. continue;
  11172. }
  11173. vec2.scale(mg,g,b.mass*b.gravityScale); // F=m*g
  11174. add(fi,fi,mg);
  11175. }
  11176. }
  11177. // Add spring forces
  11178. if(this.applySpringForces){
  11179. for(var i=0; i!==Nsprings; i++){
  11180. var s = springs[i];
  11181. s.applyForce();
  11182. }
  11183. }
  11184. if(this.applyDamping){
  11185. for(var i=0; i!==Nbodies; i++){
  11186. var b = bodies[i];
  11187. if(b.type === Body.DYNAMIC){
  11188. b.applyDamping(dt);
  11189. }
  11190. }
  11191. }
  11192. // Broadphase
  11193. var result = broadphase.getCollisionPairs(this);
  11194. // Remove ignored collision pairs
  11195. var ignoredPairs = this.disabledBodyCollisionPairs;
  11196. for(var i=ignoredPairs.length-2; i>=0; i-=2){
  11197. for(var j=result.length-2; j>=0; j-=2){
  11198. if( (ignoredPairs[i] === result[j] && ignoredPairs[i+1] === result[j+1]) ||
  11199. (ignoredPairs[i+1] === result[j] && ignoredPairs[i] === result[j+1])){
  11200. result.splice(j,2);
  11201. }
  11202. }
  11203. }
  11204. // Remove constrained pairs with collideConnected == false
  11205. var Nconstraints = constraints.length;
  11206. for(i=0; i!==Nconstraints; i++){
  11207. var c = constraints[i];
  11208. if(!c.collideConnected){
  11209. for(var j=result.length-2; j>=0; j-=2){
  11210. if( (c.bodyA === result[j] && c.bodyB === result[j+1]) ||
  11211. (c.bodyB === result[j] && c.bodyA === result[j+1])){
  11212. result.splice(j,2);
  11213. }
  11214. }
  11215. }
  11216. }
  11217. // postBroadphase event
  11218. this.postBroadphaseEvent.pairs = result;
  11219. this.emit(this.postBroadphaseEvent);
  11220. this.postBroadphaseEvent.pairs = null;
  11221. // Narrowphase
  11222. np.reset(this);
  11223. for(var i=0, Nresults=result.length; i!==Nresults; i+=2){
  11224. var bi = result[i],
  11225. bj = result[i+1];
  11226. // Loop over all shapes of body i
  11227. for(var k=0, Nshapesi=bi.shapes.length; k!==Nshapesi; k++){
  11228. var si = bi.shapes[k],
  11229. xi = si.position,
  11230. ai = si.angle;
  11231. // All shapes of body j
  11232. for(var l=0, Nshapesj=bj.shapes.length; l!==Nshapesj; l++){
  11233. var sj = bj.shapes[l],
  11234. xj = sj.position,
  11235. aj = sj.angle;
  11236. var cm = this.defaultContactMaterial;
  11237. if(si.material && sj.material){
  11238. var tmp = this.getContactMaterial(si.material,sj.material);
  11239. if(tmp){
  11240. cm = tmp;
  11241. }
  11242. }
  11243. this.runNarrowphase(np,bi,si,xi,ai,bj,sj,xj,aj,cm,this.frictionGravity);
  11244. }
  11245. }
  11246. }
  11247. // Wake up bodies
  11248. for(var i=0; i!==Nbodies; i++){
  11249. var body = bodies[i];
  11250. if(body._wakeUpAfterNarrowphase){
  11251. body.wakeUp();
  11252. body._wakeUpAfterNarrowphase = false;
  11253. }
  11254. }
  11255. // Emit end overlap events
  11256. if(this.has('endContact')){
  11257. this.overlapKeeper.getEndOverlaps(endOverlaps);
  11258. var e = this.endContactEvent;
  11259. var l = endOverlaps.length;
  11260. while(l--){
  11261. var data = endOverlaps[l];
  11262. e.shapeA = data.shapeA;
  11263. e.shapeB = data.shapeB;
  11264. e.bodyA = data.bodyA;
  11265. e.bodyB = data.bodyB;
  11266. this.emit(e);
  11267. }
  11268. endOverlaps.length = 0;
  11269. }
  11270. var preSolveEvent = this.preSolveEvent;
  11271. preSolveEvent.contactEquations = np.contactEquations;
  11272. preSolveEvent.frictionEquations = np.frictionEquations;
  11273. this.emit(preSolveEvent);
  11274. preSolveEvent.contactEquations = preSolveEvent.frictionEquations = null;
  11275. // update constraint equations
  11276. var Nconstraints = constraints.length;
  11277. for(i=0; i!==Nconstraints; i++){
  11278. constraints[i].update();
  11279. }
  11280. if(np.contactEquations.length || np.frictionEquations.length || Nconstraints){
  11281. if(this.islandSplit){
  11282. // Split into islands
  11283. islandManager.equations.length = 0;
  11284. Utils.appendArray(islandManager.equations, np.contactEquations);
  11285. Utils.appendArray(islandManager.equations, np.frictionEquations);
  11286. for(i=0; i!==Nconstraints; i++){
  11287. Utils.appendArray(islandManager.equations, constraints[i].equations);
  11288. }
  11289. islandManager.split(this);
  11290. for(var i=0; i!==islandManager.islands.length; i++){
  11291. var island = islandManager.islands[i];
  11292. if(island.equations.length){
  11293. solver.solveIsland(dt,island);
  11294. }
  11295. }
  11296. } else {
  11297. // Add contact equations to solver
  11298. solver.addEquations(np.contactEquations);
  11299. solver.addEquations(np.frictionEquations);
  11300. // Add user-defined constraint equations
  11301. for(i=0; i!==Nconstraints; i++){
  11302. solver.addEquations(constraints[i].equations);
  11303. }
  11304. if(this.solveConstraints){
  11305. solver.solve(dt,this);
  11306. }
  11307. solver.removeAllEquations();
  11308. }
  11309. }
  11310. // Step forward
  11311. for(var i=0; i!==Nbodies; i++){
  11312. var body = bodies[i];
  11313. // if(body.sleepState !== Body.SLEEPING && body.type !== Body.STATIC){
  11314. body.integrate(dt);
  11315. // }
  11316. }
  11317. // Reset force
  11318. for(var i=0; i!==Nbodies; i++){
  11319. bodies[i].setZeroForce();
  11320. }
  11321. // Emit impact event
  11322. if(this.emitImpactEvent && this.has('impact')){
  11323. var ev = this.impactEvent;
  11324. for(var i=0; i!==np.contactEquations.length; i++){
  11325. var eq = np.contactEquations[i];
  11326. if(eq.firstImpact){
  11327. ev.bodyA = eq.bodyA;
  11328. ev.bodyB = eq.bodyB;
  11329. ev.shapeA = eq.shapeA;
  11330. ev.shapeB = eq.shapeB;
  11331. ev.contactEquation = eq;
  11332. this.emit(ev);
  11333. }
  11334. }
  11335. }
  11336. // Sleeping update
  11337. if(this.sleepMode === World.BODY_SLEEPING){
  11338. for(i=0; i!==Nbodies; i++){
  11339. bodies[i].sleepTick(this.time, false, dt);
  11340. }
  11341. } else if(this.sleepMode === World.ISLAND_SLEEPING && this.islandSplit){
  11342. // Tell all bodies to sleep tick but dont sleep yet
  11343. for(i=0; i!==Nbodies; i++){
  11344. bodies[i].sleepTick(this.time, true, dt);
  11345. }
  11346. // Sleep islands
  11347. for(var i=0; i<this.islandManager.islands.length; i++){
  11348. var island = this.islandManager.islands[i];
  11349. if(island.wantsToSleep()){
  11350. island.sleep();
  11351. }
  11352. }
  11353. }
  11354. this.stepping = false;
  11355. // Remove bodies that are scheduled for removal
  11356. var bodiesToBeRemoved = this.bodiesToBeRemoved;
  11357. for(var i=0; i!==bodiesToBeRemoved.length; i++){
  11358. this.removeBody(bodiesToBeRemoved[i]);
  11359. }
  11360. bodiesToBeRemoved.length = 0;
  11361. this.emit(this.postStepEvent);
  11362. };
  11363. /**
  11364. * Runs narrowphase for the shape pair i and j.
  11365. * @method runNarrowphase
  11366. * @param {Narrowphase} np
  11367. * @param {Body} bi
  11368. * @param {Shape} si
  11369. * @param {Array} xi
  11370. * @param {Number} ai
  11371. * @param {Body} bj
  11372. * @param {Shape} sj
  11373. * @param {Array} xj
  11374. * @param {Number} aj
  11375. * @param {Number} mu
  11376. */
  11377. World.prototype.runNarrowphase = function(np,bi,si,xi,ai,bj,sj,xj,aj,cm,glen){
  11378. // Check collision groups and masks
  11379. if(!((si.collisionGroup & sj.collisionMask) !== 0 && (sj.collisionGroup & si.collisionMask) !== 0)){
  11380. return;
  11381. }
  11382. // Get world position and angle of each shape
  11383. vec2.rotate(xiw, xi, bi.angle);
  11384. vec2.rotate(xjw, xj, bj.angle);
  11385. vec2.add(xiw, xiw, bi.position);
  11386. vec2.add(xjw, xjw, bj.position);
  11387. var aiw = ai + bi.angle;
  11388. var ajw = aj + bj.angle;
  11389. np.enableFriction = cm.friction > 0;
  11390. np.frictionCoefficient = cm.friction;
  11391. var reducedMass;
  11392. if(bi.type === Body.STATIC || bi.type === Body.KINEMATIC){
  11393. reducedMass = bj.mass;
  11394. } else if(bj.type === Body.STATIC || bj.type === Body.KINEMATIC){
  11395. reducedMass = bi.mass;
  11396. } else {
  11397. reducedMass = (bi.mass*bj.mass)/(bi.mass+bj.mass);
  11398. }
  11399. np.slipForce = cm.friction*glen*reducedMass;
  11400. np.restitution = cm.restitution;
  11401. np.surfaceVelocity = cm.surfaceVelocity;
  11402. np.frictionStiffness = cm.frictionStiffness;
  11403. np.frictionRelaxation = cm.frictionRelaxation;
  11404. np.stiffness = cm.stiffness;
  11405. np.relaxation = cm.relaxation;
  11406. np.contactSkinSize = cm.contactSkinSize;
  11407. np.enabledEquations = bi.collisionResponse && bj.collisionResponse && si.collisionResponse && sj.collisionResponse;
  11408. var resolver = np[si.type | sj.type],
  11409. numContacts = 0;
  11410. if (resolver) {
  11411. var sensor = si.sensor || sj.sensor;
  11412. var numFrictionBefore = np.frictionEquations.length;
  11413. if (si.type < sj.type) {
  11414. numContacts = resolver.call(np, bi,si,xiw,aiw, bj,sj,xjw,ajw, sensor);
  11415. } else {
  11416. numContacts = resolver.call(np, bj,sj,xjw,ajw, bi,si,xiw,aiw, sensor);
  11417. }
  11418. var numFrictionEquations = np.frictionEquations.length - numFrictionBefore;
  11419. if(numContacts){
  11420. if( bi.allowSleep &&
  11421. bi.type === Body.DYNAMIC &&
  11422. bi.sleepState === Body.SLEEPING &&
  11423. bj.sleepState === Body.AWAKE &&
  11424. bj.type !== Body.STATIC
  11425. ){
  11426. var speedSquaredB = vec2.squaredLength(bj.velocity) + Math.pow(bj.angularVelocity,2);
  11427. var speedLimitSquaredB = Math.pow(bj.sleepSpeedLimit,2);
  11428. if(speedSquaredB >= speedLimitSquaredB*2){
  11429. bi._wakeUpAfterNarrowphase = true;
  11430. }
  11431. }
  11432. if( bj.allowSleep &&
  11433. bj.type === Body.DYNAMIC &&
  11434. bj.sleepState === Body.SLEEPING &&
  11435. bi.sleepState === Body.AWAKE &&
  11436. bi.type !== Body.STATIC
  11437. ){
  11438. var speedSquaredA = vec2.squaredLength(bi.velocity) + Math.pow(bi.angularVelocity,2);
  11439. var speedLimitSquaredA = Math.pow(bi.sleepSpeedLimit,2);
  11440. if(speedSquaredA >= speedLimitSquaredA*2){
  11441. bj._wakeUpAfterNarrowphase = true;
  11442. }
  11443. }
  11444. this.overlapKeeper.setOverlapping(bi, si, bj, sj);
  11445. if(this.has('beginContact') && this.overlapKeeper.isNewOverlap(si, sj)){
  11446. // Report new shape overlap
  11447. var e = this.beginContactEvent;
  11448. e.shapeA = si;
  11449. e.shapeB = sj;
  11450. e.bodyA = bi;
  11451. e.bodyB = bj;
  11452. // Reset contact equations
  11453. e.contactEquations.length = 0;
  11454. if(typeof(numContacts)==="number"){
  11455. for(var i=np.contactEquations.length-numContacts; i<np.contactEquations.length; i++){
  11456. e.contactEquations.push(np.contactEquations[i]);
  11457. }
  11458. }
  11459. this.emit(e);
  11460. }
  11461. // divide the max friction force by the number of contacts
  11462. if(typeof(numContacts)==="number" && numFrictionEquations > 1){ // Why divide by 1?
  11463. for(var i=np.frictionEquations.length-numFrictionEquations; i<np.frictionEquations.length; i++){
  11464. var f = np.frictionEquations[i];
  11465. f.setSlipForce(f.getSlipForce() / numFrictionEquations);
  11466. }
  11467. }
  11468. }
  11469. }
  11470. };
  11471. /**
  11472. * Add a spring to the simulation
  11473. *
  11474. * @method addSpring
  11475. * @param {Spring} spring
  11476. */
  11477. World.prototype.addSpring = function(spring){
  11478. this.springs.push(spring);
  11479. var evt = this.addSpringEvent;
  11480. evt.spring = spring;
  11481. this.emit(evt);
  11482. evt.spring = null;
  11483. };
  11484. /**
  11485. * Remove a spring
  11486. *
  11487. * @method removeSpring
  11488. * @param {Spring} spring
  11489. */
  11490. World.prototype.removeSpring = function(spring){
  11491. var idx = this.springs.indexOf(spring);
  11492. if(idx !== -1){
  11493. Utils.splice(this.springs,idx,1);
  11494. }
  11495. };
  11496. /**
  11497. * Add a body to the simulation
  11498. *
  11499. * @method addBody
  11500. * @param {Body} body
  11501. *
  11502. * @example
  11503. * var world = new World(),
  11504. * body = new Body();
  11505. * world.addBody(body);
  11506. * @todo What if this is done during step?
  11507. */
  11508. World.prototype.addBody = function(body){
  11509. if(this.bodies.indexOf(body) === -1){
  11510. this.bodies.push(body);
  11511. body.world = this;
  11512. var evt = this.addBodyEvent;
  11513. evt.body = body;
  11514. this.emit(evt);
  11515. evt.body = null;
  11516. }
  11517. };
  11518. /**
  11519. * Remove a body from the simulation. If this method is called during step(), the body removal is scheduled to after the step.
  11520. *
  11521. * @method removeBody
  11522. * @param {Body} body
  11523. */
  11524. World.prototype.removeBody = function(body){
  11525. if(this.stepping){
  11526. this.bodiesToBeRemoved.push(body);
  11527. } else {
  11528. body.world = null;
  11529. var idx = this.bodies.indexOf(body);
  11530. if(idx!==-1){
  11531. Utils.splice(this.bodies,idx,1);
  11532. this.removeBodyEvent.body = body;
  11533. body.resetConstraintVelocity();
  11534. this.emit(this.removeBodyEvent);
  11535. this.removeBodyEvent.body = null;
  11536. }
  11537. }
  11538. };
  11539. /**
  11540. * Get a body by its id.
  11541. * @method getBodyById
  11542. * @param {number} id
  11543. * @return {Body} The body, or false if it was not found.
  11544. */
  11545. World.prototype.getBodyById = function(id){
  11546. var bodies = this.bodies;
  11547. for(var i=0; i<bodies.length; i++){
  11548. var b = bodies[i];
  11549. if(b.id === id){
  11550. return b;
  11551. }
  11552. }
  11553. return false;
  11554. };
  11555. /**
  11556. * Disable collision between two bodies
  11557. * @method disableBodyCollision
  11558. * @param {Body} bodyA
  11559. * @param {Body} bodyB
  11560. */
  11561. World.prototype.disableBodyCollision = function(bodyA,bodyB){
  11562. this.disabledBodyCollisionPairs.push(bodyA,bodyB);
  11563. };
  11564. /**
  11565. * Enable collisions between the given two bodies
  11566. * @method enableBodyCollision
  11567. * @param {Body} bodyA
  11568. * @param {Body} bodyB
  11569. */
  11570. World.prototype.enableBodyCollision = function(bodyA,bodyB){
  11571. var pairs = this.disabledBodyCollisionPairs;
  11572. for(var i=0; i<pairs.length; i+=2){
  11573. if((pairs[i] === bodyA && pairs[i+1] === bodyB) || (pairs[i+1] === bodyA && pairs[i] === bodyB)){
  11574. pairs.splice(i,2);
  11575. return;
  11576. }
  11577. }
  11578. };
  11579. /**
  11580. * Resets the World, removes all bodies, constraints and springs.
  11581. *
  11582. * @method clear
  11583. */
  11584. World.prototype.clear = function(){
  11585. this.time = 0;
  11586. // Remove all solver equations
  11587. if(this.solver && this.solver.equations.length){
  11588. this.solver.removeAllEquations();
  11589. }
  11590. // Remove all constraints
  11591. var cs = this.constraints;
  11592. for(var i=cs.length-1; i>=0; i--){
  11593. this.removeConstraint(cs[i]);
  11594. }
  11595. // Remove all bodies
  11596. var bodies = this.bodies;
  11597. for(var i=bodies.length-1; i>=0; i--){
  11598. this.removeBody(bodies[i]);
  11599. }
  11600. // Remove all springs
  11601. var springs = this.springs;
  11602. for(var i=springs.length-1; i>=0; i--){
  11603. this.removeSpring(springs[i]);
  11604. }
  11605. // Remove all contact materials
  11606. var cms = this.contactMaterials;
  11607. for(var i=cms.length-1; i>=0; i--){
  11608. this.removeContactMaterial(cms[i]);
  11609. }
  11610. World.apply(this);
  11611. };
  11612. var hitTest_tmp1 = vec2.create(),
  11613. hitTest_zero = vec2.fromValues(0,0),
  11614. hitTest_tmp2 = vec2.fromValues(0,0);
  11615. /**
  11616. * Test if a world point overlaps bodies
  11617. * @method hitTest
  11618. * @param {Array} worldPoint Point to use for intersection tests
  11619. * @param {Array} bodies A list of objects to check for intersection
  11620. * @param {Number} precision Used for matching against particles and lines. Adds some margin to these infinitesimal objects.
  11621. * @return {Array} Array of bodies that overlap the point
  11622. * @todo Should use an api similar to the raycast function
  11623. * @todo Should probably implement a .containsPoint method for all shapes. Would be more efficient
  11624. */
  11625. World.prototype.hitTest = function(worldPoint,bodies,precision){
  11626. precision = precision || 0;
  11627. // Create a dummy particle body with a particle shape to test against the bodies
  11628. var pb = new Body({ position:worldPoint }),
  11629. ps = new Particle(),
  11630. px = worldPoint,
  11631. pa = 0,
  11632. x = hitTest_tmp1,
  11633. zero = hitTest_zero,
  11634. tmp = hitTest_tmp2;
  11635. pb.addShape(ps);
  11636. var n = this.narrowphase,
  11637. result = [];
  11638. // Check bodies
  11639. for(var i=0, N=bodies.length; i!==N; i++){
  11640. var b = bodies[i];
  11641. for(var j=0, NS=b.shapes.length; j!==NS; j++){
  11642. var s = b.shapes[j];
  11643. // Get shape world position + angle
  11644. vec2.rotate(x, s.position, b.angle);
  11645. vec2.add(x, x, b.position);
  11646. var a = s.angle + b.angle;
  11647. if( (s instanceof Circle && n.circleParticle (b,s,x,a, pb,ps,px,pa, true)) ||
  11648. (s instanceof Convex && n.particleConvex (pb,ps,px,pa, b,s,x,a, true)) ||
  11649. (s instanceof Plane && n.particlePlane (pb,ps,px,pa, b,s,x,a, true)) ||
  11650. (s instanceof Capsule && n.particleCapsule (pb,ps,px,pa, b,s,x,a, true)) ||
  11651. (s instanceof Particle && vec2.squaredLength(vec2.sub(tmp,x,worldPoint)) < precision*precision)
  11652. ){
  11653. result.push(b);
  11654. }
  11655. }
  11656. }
  11657. return result;
  11658. };
  11659. /**
  11660. * Set the stiffness for all equations and contact materials.
  11661. * @method setGlobalStiffness
  11662. * @param {Number} stiffness
  11663. */
  11664. World.prototype.setGlobalStiffness = function(stiffness){
  11665. // Set for all constraints
  11666. var constraints = this.constraints;
  11667. for(var i=0; i !== constraints.length; i++){
  11668. var c = constraints[i];
  11669. for(var j=0; j !== c.equations.length; j++){
  11670. var eq = c.equations[j];
  11671. eq.stiffness = stiffness;
  11672. eq.needsUpdate = true;
  11673. }
  11674. }
  11675. // Set for all contact materials
  11676. var contactMaterials = this.contactMaterials;
  11677. for(var i=0; i !== contactMaterials.length; i++){
  11678. var c = contactMaterials[i];
  11679. c.stiffness = c.frictionStiffness = stiffness;
  11680. }
  11681. // Set for default contact material
  11682. var c = this.defaultContactMaterial;
  11683. c.stiffness = c.frictionStiffness = stiffness;
  11684. };
  11685. /**
  11686. * Set the relaxation for all equations and contact materials.
  11687. * @method setGlobalRelaxation
  11688. * @param {Number} relaxation
  11689. */
  11690. World.prototype.setGlobalRelaxation = function(relaxation){
  11691. // Set for all constraints
  11692. for(var i=0; i !== this.constraints.length; i++){
  11693. var c = this.constraints[i];
  11694. for(var j=0; j !== c.equations.length; j++){
  11695. var eq = c.equations[j];
  11696. eq.relaxation = relaxation;
  11697. eq.needsUpdate = true;
  11698. }
  11699. }
  11700. // Set for all contact materials
  11701. for(var i=0; i !== this.contactMaterials.length; i++){
  11702. var c = this.contactMaterials[i];
  11703. c.relaxation = c.frictionRelaxation = relaxation;
  11704. }
  11705. // Set for default contact material
  11706. var c = this.defaultContactMaterial;
  11707. c.relaxation = c.frictionRelaxation = relaxation;
  11708. };
  11709. var tmpAABB = new AABB();
  11710. var tmpArray = [];
  11711. /**
  11712. * Ray cast against all bodies in the world.
  11713. * @method raycast
  11714. * @param {RaycastResult} result
  11715. * @param {Ray} ray
  11716. * @return {boolean} True if any body was hit.
  11717. *
  11718. * @example
  11719. * var ray = new Ray({
  11720. * mode: Ray.CLOSEST, // or ANY
  11721. * from: [0, 0],
  11722. * to: [10, 0],
  11723. * });
  11724. * var result = new RaycastResult();
  11725. * world.raycast(result, ray);
  11726. *
  11727. * // Get the hit point
  11728. * var hitPoint = vec2.create();
  11729. * result.getHitPoint(hitPoint, ray);
  11730. * console.log('Hit point: ', hitPoint[0], hitPoint[1], ' at distance ' + result.getHitDistance(ray));
  11731. *
  11732. * @example
  11733. * var ray = new Ray({
  11734. * mode: Ray.ALL,
  11735. * from: [0, 0],
  11736. * to: [10, 0],
  11737. * callback: function(result){
  11738. *
  11739. * // Print some info about the hit
  11740. * console.log('Hit body and shape: ', result.body, result.shape);
  11741. *
  11742. * // Get the hit point
  11743. * var hitPoint = vec2.create();
  11744. * result.getHitPoint(hitPoint, ray);
  11745. * console.log('Hit point: ', hitPoint[0], hitPoint[1], ' at distance ' + result.getHitDistance(ray));
  11746. *
  11747. * // If you are happy with the hits you got this far, you can stop the traversal here:
  11748. * result.stop();
  11749. * }
  11750. * });
  11751. * var result = new RaycastResult();
  11752. * world.raycast(result, ray);
  11753. */
  11754. World.prototype.raycast = function(result, ray){
  11755. // Get all bodies within the ray AABB
  11756. ray.getAABB(tmpAABB);
  11757. this.broadphase.aabbQuery(this, tmpAABB, tmpArray);
  11758. ray.intersectBodies(result, tmpArray);
  11759. tmpArray.length = 0;
  11760. return result.hasHit();
  11761. };
  11762. },{"../../package.json":6,"../collision/AABB":7,"../collision/Broadphase":8,"../collision/Narrowphase":10,"../collision/Ray":11,"../collision/SAPBroadphase":13,"../constraints/Constraint":14,"../constraints/DistanceConstraint":15,"../constraints/GearConstraint":16,"../constraints/LockConstraint":17,"../constraints/PrismaticConstraint":18,"../constraints/RevoluteConstraint":19,"../events/EventEmitter":26,"../material/ContactMaterial":27,"../material/Material":28,"../math/vec2":30,"../objects/Body":31,"../objects/LinearSpring":32,"../objects/RotationalSpring":33,"../shapes/Capsule":38,"../shapes/Circle":39,"../shapes/Convex":40,"../shapes/Line":42,"../shapes/Particle":43,"../shapes/Plane":44,"../shapes/Shape":45,"../solver/GSSolver":46,"../solver/Solver":47,"../utils/OverlapKeeper":52,"../utils/Utils":57,"./IslandManager":59}]},{},[36])
  11763. (36)
  11764. });
  11765. /**
  11766. * @author Mat Groves http://matgroves.com/ @Doormat23
  11767. */
  11768. (function(){
  11769. var root = this;
  11770. /**
  11771. * @author Mat Groves http://matgroves.com/ @Doormat23
  11772. */
  11773. /**
  11774. * The [pixi.js](http://www.pixijs.com/) module/namespace.
  11775. *
  11776. * @module PIXI
  11777. */
  11778. /**
  11779. * Namespace-class for [pixi.js](http://www.pixijs.com/).
  11780. *
  11781. * Contains assorted static properties and enumerations.
  11782. *
  11783. * @class PIXI
  11784. * @static
  11785. */
  11786. var PIXI = PIXI || {};
  11787. /**
  11788. * A reference to the Phaser Game instance that owns this Pixi renderer.
  11789. * @property {Phaser.Game} game
  11790. * @static
  11791. */
  11792. PIXI.game = null;
  11793. /**
  11794. * @property {Number} WEBGL_RENDERER
  11795. * @protected
  11796. * @static
  11797. */
  11798. PIXI.WEBGL_RENDERER = 0;
  11799. /**
  11800. * @property {Number} CANVAS_RENDERER
  11801. * @protected
  11802. * @static
  11803. */
  11804. PIXI.CANVAS_RENDERER = 1;
  11805. /**
  11806. * Version of pixi that is loaded.
  11807. * @property {String} VERSION
  11808. * @static
  11809. */
  11810. PIXI.VERSION = "v2.2.9";
  11811. // used to create uids for various pixi objects.
  11812. PIXI._UID = 0;
  11813. if (typeof(Float32Array) != 'undefined')
  11814. {
  11815. PIXI.Float32Array = Float32Array;
  11816. PIXI.Uint16Array = Uint16Array;
  11817. // Uint32Array and ArrayBuffer only used by WebGL renderer
  11818. // We can suppose that if WebGL is supported then typed arrays are supported too
  11819. // as they predate WebGL support for all browsers:
  11820. // see typed arrays support: http://caniuse.com/#search=TypedArrays
  11821. // see WebGL support: http://caniuse.com/#search=WebGL
  11822. PIXI.Uint32Array = Uint32Array;
  11823. PIXI.ArrayBuffer = ArrayBuffer;
  11824. }
  11825. else
  11826. {
  11827. PIXI.Float32Array = Array;
  11828. PIXI.Uint16Array = Array;
  11829. }
  11830. /**
  11831. * @property {Number} PI_2
  11832. * @static
  11833. */
  11834. PIXI.PI_2 = Math.PI * 2;
  11835. /**
  11836. * @property {Number} RAD_TO_DEG
  11837. * @static
  11838. */
  11839. PIXI.RAD_TO_DEG = 180 / Math.PI;
  11840. /**
  11841. * @property {Number} DEG_TO_RAD
  11842. * @static
  11843. */
  11844. PIXI.DEG_TO_RAD = Math.PI / 180;
  11845. /**
  11846. * @property {String} RETINA_PREFIX
  11847. * @protected
  11848. * @static
  11849. */
  11850. PIXI.RETINA_PREFIX = "@2x";
  11851. /**
  11852. * The default render options if none are supplied to
  11853. * {{#crossLink "WebGLRenderer"}}{{/crossLink}} or {{#crossLink "CanvasRenderer"}}{{/crossLink}}.
  11854. *
  11855. * @property {Object} defaultRenderOptions
  11856. * @property {Object} defaultRenderOptions.view=null
  11857. * @property {Boolean} defaultRenderOptions.transparent=false
  11858. * @property {Boolean} defaultRenderOptions.antialias=false
  11859. * @property {Boolean} defaultRenderOptions.preserveDrawingBuffer=false
  11860. * @property {Number} defaultRenderOptions.resolution=1
  11861. * @property {Boolean} defaultRenderOptions.clearBeforeRender=true
  11862. * @property {Boolean} defaultRenderOptions.autoResize=false
  11863. * @static
  11864. PIXI.defaultRenderOptions = {
  11865. view: null,
  11866. transparent: false,
  11867. antialias: false,
  11868. preserveDrawingBuffer: false,
  11869. resolution: 1,
  11870. clearBeforeRender: true,
  11871. autoResize: false
  11872. };
  11873. */
  11874. /**
  11875. * @author Mat Groves http://matgroves.com @Doormat23
  11876. * @author Richard Davey <rich@photonstorm.com>
  11877. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  11878. */
  11879. /**
  11880. * The base class for all objects that are rendered. Contains properties for position, scaling,
  11881. * rotation, masks and cache handling.
  11882. *
  11883. * This is an abstract class and should not be used on its own, rather it should be extended.
  11884. *
  11885. * It is used internally by the likes of PIXI.Sprite.
  11886. *
  11887. * @class PIXI.DisplayObject
  11888. * @constructor
  11889. */
  11890. PIXI.DisplayObject = function () {
  11891. /**
  11892. * The coordinates, in pixels, of this DisplayObject, relative to its parent container.
  11893. *
  11894. * The value of this property does not reflect any positioning happening further up the display list.
  11895. * To obtain that value please see the `worldPosition` property.
  11896. *
  11897. * @property {PIXI.Point} position
  11898. * @default
  11899. */
  11900. this.position = new PIXI.Point(0, 0);
  11901. /**
  11902. * The scale of this DisplayObject. A scale of 1:1 represents the DisplayObject
  11903. * at its default size. A value of 0.5 would scale this DisplayObject by half, and so on.
  11904. *
  11905. * The value of this property does not reflect any scaling happening further up the display list.
  11906. * To obtain that value please see the `worldScale` property.
  11907. *
  11908. * @property {PIXI.Point} scale
  11909. * @default
  11910. */
  11911. this.scale = new PIXI.Point(1, 1);
  11912. /**
  11913. * The pivot point of this DisplayObject that it rotates around. The values are expressed
  11914. * in pixel values.
  11915. * @property {PIXI.Point} pivot
  11916. * @default
  11917. */
  11918. this.pivot = new PIXI.Point(0, 0);
  11919. /**
  11920. * The rotation of this DisplayObject. The value is given, and expressed, in radians, and is based on
  11921. * a right-handed orientation.
  11922. *
  11923. * The value of this property does not reflect any rotation happening further up the display list.
  11924. * To obtain that value please see the `worldRotation` property.
  11925. *
  11926. * @property {number} rotation
  11927. * @default
  11928. */
  11929. this.rotation = 0;
  11930. /**
  11931. * The alpha value of this DisplayObject. A value of 1 is fully opaque. A value of 0 is transparent.
  11932. * Please note that an object with an alpha value of 0 is skipped during the render pass.
  11933. *
  11934. * The value of this property does not reflect any alpha values set further up the display list.
  11935. * To obtain that value please see the `worldAlpha` property.
  11936. *
  11937. * @property {number} alpha
  11938. * @default
  11939. */
  11940. this.alpha = 1;
  11941. /**
  11942. * The visibility of this DisplayObject. A value of `false` makes the object invisible.
  11943. * A value of `true` makes it visible. Please note that an object with a visible value of
  11944. * `false` is skipped during the render pass. Equally a DisplayObject with visible false will
  11945. * not render any of its children.
  11946. *
  11947. * The value of this property does not reflect any visible values set further up the display list.
  11948. * To obtain that value please see the `worldVisible` property.
  11949. *
  11950. * @property {boolean} visible
  11951. * @default
  11952. */
  11953. this.visible = true;
  11954. /**
  11955. * This is the defined area that will pick up mouse / touch events. It is null by default.
  11956. * Setting it is a neat way of optimising the hitTest function that the interactionManager will use (as it will not need to hit test all the children)
  11957. *
  11958. * @property hitArea
  11959. * @type Rectangle|Circle|Ellipse|Polygon
  11960. */
  11961. this.hitArea = null;
  11962. /**
  11963. * Should this DisplayObject be rendered by the renderer? An object with a renderable value of
  11964. * `false` is skipped during the render pass.
  11965. *
  11966. * @property {boolean} renderable
  11967. * @default
  11968. */
  11969. this.renderable = false;
  11970. /**
  11971. * The parent DisplayObjectContainer that this DisplayObject is a child of.
  11972. * All DisplayObjects must belong to a parent in order to be rendered.
  11973. * The root parent is the Stage object. This property is set automatically when the
  11974. * DisplayObject is added to, or removed from, a DisplayObjectContainer.
  11975. *
  11976. * @property {PIXI.DisplayObjectContainer} parent
  11977. * @default
  11978. * @readOnly
  11979. */
  11980. this.parent = null;
  11981. /**
  11982. * The multiplied alpha value of this DisplayObject. A value of 1 is fully opaque. A value of 0 is transparent.
  11983. * This value is the calculated total, based on the alpha values of all parents of this DisplayObjects
  11984. * in the display list.
  11985. *
  11986. * To obtain, and set, the local alpha value, see the `alpha` property.
  11987. *
  11988. * Note: This property is only updated at the end of the `updateTransform` call, once per render. Until
  11989. * that happens this property will contain values based on the previous frame. Be mindful of this if
  11990. * accessing this property outside of the normal game flow, i.e. from an asynchronous event callback.
  11991. *
  11992. * @property {number} worldAlpha
  11993. * @readOnly
  11994. */
  11995. this.worldAlpha = 1;
  11996. /**
  11997. * The current transform of this DisplayObject.
  11998. *
  11999. * This property contains the calculated total, based on the transforms of all parents of this
  12000. * DisplayObject in the display list.
  12001. *
  12002. * Note: This property is only updated at the end of the `updateTransform` call, once per render. Until
  12003. * that happens this property will contain values based on the previous frame. Be mindful of this if
  12004. * accessing this property outside of the normal game flow, i.e. from an asynchronous event callback.
  12005. *
  12006. * @property {PIXI.Matrix} worldTransform
  12007. * @readOnly
  12008. */
  12009. this.worldTransform = new PIXI.Matrix();
  12010. /**
  12011. * The coordinates, in pixels, of this DisplayObject within the world.
  12012. *
  12013. * This property contains the calculated total, based on the positions of all parents of this
  12014. * DisplayObject in the display list.
  12015. *
  12016. * Note: This property is only updated at the end of the `updateTransform` call, once per render. Until
  12017. * that happens this property will contain values based on the previous frame. Be mindful of this if
  12018. * accessing this property outside of the normal game flow, i.e. from an asynchronous event callback.
  12019. *
  12020. * @property {PIXI.Point} worldPosition
  12021. * @readOnly
  12022. */
  12023. this.worldPosition = new PIXI.Point(0, 0);
  12024. /**
  12025. * The global scale of this DisplayObject.
  12026. *
  12027. * This property contains the calculated total, based on the scales of all parents of this
  12028. * DisplayObject in the display list.
  12029. *
  12030. * Note: This property is only updated at the end of the `updateTransform` call, once per render. Until
  12031. * that happens this property will contain values based on the previous frame. Be mindful of this if
  12032. * accessing this property outside of the normal game flow, i.e. from an asynchronous event callback.
  12033. *
  12034. * @property {PIXI.Point} worldScale
  12035. * @readOnly
  12036. */
  12037. this.worldScale = new PIXI.Point(1, 1);
  12038. /**
  12039. * The rotation, in radians, of this DisplayObject.
  12040. *
  12041. * This property contains the calculated total, based on the rotations of all parents of this
  12042. * DisplayObject in the display list.
  12043. *
  12044. * Note: This property is only updated at the end of the `updateTransform` call, once per render. Until
  12045. * that happens this property will contain values based on the previous frame. Be mindful of this if
  12046. * accessing this property outside of the normal game flow, i.e. from an asynchronous event callback.
  12047. *
  12048. * @property {number} worldRotation
  12049. * @readOnly
  12050. */
  12051. this.worldRotation = 0;
  12052. /**
  12053. * The rectangular area used by filters when rendering a shader for this DisplayObject.
  12054. *
  12055. * @property {PIXI.Rectangle} filterArea
  12056. * @type Rectangle
  12057. * @default
  12058. */
  12059. this.filterArea = null;
  12060. /**
  12061. * @property {number} _sr - Cached rotation value.
  12062. * @private
  12063. */
  12064. this._sr = 0;
  12065. /**
  12066. * @property {number} _cr - Cached rotation value.
  12067. * @private
  12068. */
  12069. this._cr = 1;
  12070. /**
  12071. * @property {PIXI.Rectangle} _bounds - The cached bounds of this object.
  12072. * @private
  12073. */
  12074. this._bounds = new PIXI.Rectangle(0, 0, 0, 0);
  12075. /**
  12076. * @property {PIXI.Rectangle} _currentBounds - The most recently calculated bounds of this object.
  12077. * @private
  12078. */
  12079. this._currentBounds = null;
  12080. /**
  12081. * @property {PIXI.Rectangle} _mask - The cached mask of this object.
  12082. * @private
  12083. */
  12084. this._mask = null;
  12085. /**
  12086. * @property {boolean} _cacheAsBitmap - Internal cache as bitmap flag.
  12087. * @private
  12088. */
  12089. this._cacheAsBitmap = false;
  12090. /**
  12091. * @property {boolean} _cacheIsDirty - Internal dirty cache flag.
  12092. * @private
  12093. */
  12094. this._cacheIsDirty = false;
  12095. };
  12096. PIXI.DisplayObject.prototype.constructor = PIXI.DisplayObject;
  12097. PIXI.DisplayObject.prototype = {
  12098. /**
  12099. * Destroy this DisplayObject.
  12100. *
  12101. * Removes any cached sprites, sets renderable flag to false, and nulls filters, bounds and mask.
  12102. *
  12103. * Also iteratively calls `destroy` on any children.
  12104. *
  12105. * @method PIXI.DisplayObject#destroy
  12106. */
  12107. destroy: function () {
  12108. if (this.children)
  12109. {
  12110. var i = this.children.length;
  12111. while (i--)
  12112. {
  12113. this.children[i].destroy();
  12114. }
  12115. this.children = [];
  12116. }
  12117. this.hitArea = null;
  12118. this.parent = null;
  12119. this.worldTransform = null;
  12120. this.filterArea = null;
  12121. this.renderable = false;
  12122. this._bounds = null;
  12123. this._currentBounds = null;
  12124. this._mask = null;
  12125. this._destroyCachedSprite();
  12126. },
  12127. /*
  12128. * Updates the transform matrix this DisplayObject uses for rendering.
  12129. *
  12130. * If the object has no parent, and no parent parameter is provided, it will default to
  12131. * Phaser.Game.World as the parent transform to use. If that is unavailable the transform fails to take place.
  12132. *
  12133. * The `parent` parameter has priority over the actual parent. Use it as a parent override.
  12134. * Setting it does **not** change the actual parent of this DisplayObject.
  12135. *
  12136. * Calling this method updates the `worldTransform`, `worldAlpha`, `worldPosition`, `worldScale`
  12137. * and `worldRotation` properties.
  12138. *
  12139. * If a `transformCallback` has been specified, it is called at the end of this method, and is passed
  12140. * the new, updated, worldTransform property, along with the parent transform used.
  12141. *
  12142. * @method PIXI.DisplayObject#updateTransform
  12143. * @param {PIXI.DisplayObjectContainer} [parent] - Optional parent to calculate this DisplayObjects transform from.
  12144. * @return {PIXI.DisplayObject} - A reference to this DisplayObject.
  12145. */
  12146. updateTransform: function (parent) {
  12147. if (!parent && !this.parent && !this.game)
  12148. {
  12149. return this;
  12150. }
  12151. var p = this.parent;
  12152. if (parent)
  12153. {
  12154. p = parent;
  12155. }
  12156. else if (!this.parent)
  12157. {
  12158. p = this.game.world;
  12159. }
  12160. // create some matrix refs for easy access
  12161. var pt = p.worldTransform;
  12162. var wt = this.worldTransform;
  12163. // temporary matrix variables
  12164. var a, b, c, d, tx, ty;
  12165. // so if rotation is between 0 then we can simplify the multiplication process..
  12166. if (this.rotation % PIXI.PI_2)
  12167. {
  12168. // check to see if the rotation is the same as the previous render. This means we only need to use sin and cos when rotation actually changes
  12169. if (this.rotation !== this.rotationCache)
  12170. {
  12171. this.rotationCache = this.rotation;
  12172. this._sr = Math.sin(this.rotation);
  12173. this._cr = Math.cos(this.rotation);
  12174. }
  12175. // get the matrix values of the displayobject based on its transform properties..
  12176. a = this._cr * this.scale.x;
  12177. b = this._sr * this.scale.x;
  12178. c = -this._sr * this.scale.y;
  12179. d = this._cr * this.scale.y;
  12180. tx = this.position.x;
  12181. ty = this.position.y;
  12182. // check for pivot.. not often used so geared towards that fact!
  12183. if (this.pivot.x || this.pivot.y)
  12184. {
  12185. tx -= this.pivot.x * a + this.pivot.y * c;
  12186. ty -= this.pivot.x * b + this.pivot.y * d;
  12187. }
  12188. // concat the parent matrix with the objects transform.
  12189. wt.a = a * pt.a + b * pt.c;
  12190. wt.b = a * pt.b + b * pt.d;
  12191. wt.c = c * pt.a + d * pt.c;
  12192. wt.d = c * pt.b + d * pt.d;
  12193. wt.tx = tx * pt.a + ty * pt.c + pt.tx;
  12194. wt.ty = tx * pt.b + ty * pt.d + pt.ty;
  12195. }
  12196. else
  12197. {
  12198. // lets do the fast version as we know there is no rotation..
  12199. a = this.scale.x;
  12200. d = this.scale.y;
  12201. tx = this.position.x - this.pivot.x * a;
  12202. ty = this.position.y - this.pivot.y * d;
  12203. wt.a = a * pt.a;
  12204. wt.b = a * pt.b;
  12205. wt.c = d * pt.c;
  12206. wt.d = d * pt.d;
  12207. wt.tx = tx * pt.a + ty * pt.c + pt.tx;
  12208. wt.ty = tx * pt.b + ty * pt.d + pt.ty;
  12209. }
  12210. // Set the World values
  12211. this.worldAlpha = this.alpha * p.worldAlpha;
  12212. this.worldPosition.set(wt.tx, wt.ty);
  12213. this.worldScale.set(this.scale.x * Math.sqrt(wt.a * wt.a + wt.c * wt.c), this.scale.y * Math.sqrt(wt.b * wt.b + wt.d * wt.d));
  12214. this.worldRotation = Math.atan2(-wt.c, wt.d);
  12215. // reset the bounds each time this is called!
  12216. this._currentBounds = null;
  12217. // Custom callback?
  12218. if (this.transformCallback)
  12219. {
  12220. this.transformCallback.call(this.transformCallbackContext, wt, pt);
  12221. }
  12222. return this;
  12223. },
  12224. /**
  12225. * To be overridden by classes that require it.
  12226. *
  12227. * @method PIXI.DisplayObject#preUpdate
  12228. */
  12229. preUpdate: function () {
  12230. },
  12231. /**
  12232. * Generates a RenderTexture based on this DisplayObject, which can they be used to texture other Sprites.
  12233. * This can be useful if your DisplayObject is static, or complicated, and needs to be reused multiple times.
  12234. *
  12235. * Please note that no garbage collection takes place on old textures. It is up to you to destroy old textures,
  12236. * and references to them, so they don't linger in memory.
  12237. *
  12238. * @method PIXI.DisplayObject#generateTexture
  12239. * @param {number} [resolution=1] - The resolution of the texture being generated.
  12240. * @param {number} [scaleMode=PIXI.scaleModes.DEFAULT] - See {{#crossLink "PIXI/scaleModes:property"}}PIXI.scaleModes{{/crossLink}} for possible values.
  12241. * @param {PIXI.CanvasRenderer|PIXI.WebGLRenderer} renderer - The renderer used to generate the texture.
  12242. * @return {PIXI.RenderTexture} - A RenderTexture containing an image of this DisplayObject at the time it was invoked.
  12243. */
  12244. generateTexture: function (resolution, scaleMode, renderer) {
  12245. var bounds = this.getLocalBounds();
  12246. var renderTexture = new PIXI.RenderTexture(bounds.width | 0, bounds.height | 0, renderer, scaleMode, resolution);
  12247. PIXI.DisplayObject._tempMatrix.tx = -bounds.x;
  12248. PIXI.DisplayObject._tempMatrix.ty = -bounds.y;
  12249. renderTexture.render(this, PIXI.DisplayObject._tempMatrix);
  12250. return renderTexture;
  12251. },
  12252. /**
  12253. * If this DisplayObject has a cached Sprite, this method generates and updates it.
  12254. *
  12255. * @method PIXI.DisplayObject#updateCache
  12256. * @return {PIXI.DisplayObject} - A reference to this DisplayObject.
  12257. */
  12258. updateCache: function () {
  12259. this._generateCachedSprite();
  12260. return this;
  12261. },
  12262. /**
  12263. * Calculates the global position of this DisplayObject, based on the position given.
  12264. *
  12265. * @method PIXI.DisplayObject#toGlobal
  12266. * @param {PIXI.Point} position - The global position to calculate from.
  12267. * @return {PIXI.Point} - A point object representing the position of this DisplayObject based on the global position given.
  12268. */
  12269. toGlobal: function (position) {
  12270. this.updateTransform();
  12271. return this.worldTransform.apply(position);
  12272. },
  12273. /**
  12274. * Calculates the local position of this DisplayObject, relative to another point.
  12275. *
  12276. * @method PIXI.DisplayObject#toLocal
  12277. * @param {PIXI.Point} position - The world origin to calculate from.
  12278. * @param {PIXI.DisplayObject} [from] - An optional DisplayObject to calculate the global position from.
  12279. * @return {PIXI.Point} - A point object representing the position of this DisplayObject based on the global position given.
  12280. */
  12281. toLocal: function (position, from) {
  12282. if (from)
  12283. {
  12284. position = from.toGlobal(position);
  12285. }
  12286. this.updateTransform();
  12287. return this.worldTransform.applyInverse(position);
  12288. },
  12289. /**
  12290. * Internal method.
  12291. *
  12292. * @method PIXI.DisplayObject#_renderCachedSprite
  12293. * @private
  12294. * @param {Object} renderSession - The render session
  12295. */
  12296. _renderCachedSprite: function (renderSession) {
  12297. this._cachedSprite.worldAlpha = this.worldAlpha;
  12298. if (renderSession.gl)
  12299. {
  12300. PIXI.Sprite.prototype._renderWebGL.call(this._cachedSprite, renderSession);
  12301. }
  12302. else
  12303. {
  12304. PIXI.Sprite.prototype._renderCanvas.call(this._cachedSprite, renderSession);
  12305. }
  12306. },
  12307. /**
  12308. * Internal method.
  12309. *
  12310. * @method PIXI.DisplayObject#_generateCachedSprite
  12311. * @private
  12312. */
  12313. _generateCachedSprite: function () {
  12314. this._cacheAsBitmap = false;
  12315. var bounds = this.getLocalBounds();
  12316. // Round it off and force non-zero dimensions
  12317. bounds.width = Math.max(1, Math.ceil(bounds.width));
  12318. bounds.height = Math.max(1, Math.ceil(bounds.height));
  12319. this.updateTransform();
  12320. if (!this._cachedSprite)
  12321. {
  12322. var renderTexture = new PIXI.RenderTexture(bounds.width, bounds.height);
  12323. this._cachedSprite = new PIXI.Sprite(renderTexture);
  12324. this._cachedSprite.worldTransform = this.worldTransform;
  12325. }
  12326. else
  12327. {
  12328. this._cachedSprite.texture.resize(bounds.width, bounds.height);
  12329. }
  12330. // Remove filters
  12331. var tempFilters = this._filters;
  12332. this._filters = null;
  12333. this._cachedSprite.filters = tempFilters;
  12334. PIXI.DisplayObject._tempMatrix.tx = -bounds.x;
  12335. PIXI.DisplayObject._tempMatrix.ty = -bounds.y;
  12336. this._cachedSprite.texture.render(this, PIXI.DisplayObject._tempMatrix, true);
  12337. this._cachedSprite.anchor.x = -(bounds.x / bounds.width);
  12338. this._cachedSprite.anchor.y = -(bounds.y / bounds.height);
  12339. this._filters = tempFilters;
  12340. this._cacheAsBitmap = true;
  12341. },
  12342. /**
  12343. * Destroys a cached Sprite.
  12344. *
  12345. * @method PIXI.DisplayObject#_destroyCachedSprite
  12346. * @private
  12347. */
  12348. _destroyCachedSprite: function () {
  12349. if (!this._cachedSprite)
  12350. {
  12351. return;
  12352. }
  12353. this._cachedSprite.texture.destroy(true);
  12354. this._cachedSprite = null;
  12355. }
  12356. };
  12357. // Alias for updateTransform. As used in DisplayObject container, etc.
  12358. PIXI.DisplayObject.prototype.displayObjectUpdateTransform = PIXI.DisplayObject.prototype.updateTransform;
  12359. Object.defineProperties(PIXI.DisplayObject.prototype, {
  12360. /**
  12361. * The horizontal position of the DisplayObject, in pixels, relative to its parent.
  12362. * If you need the world position of the DisplayObject, use `DisplayObject.worldPosition` instead.
  12363. * @name PIXI.DisplayObject#x
  12364. * @property {number} x - The horizontal position of the DisplayObject, in pixels, relative to its parent.
  12365. */
  12366. 'x': {
  12367. get: function () {
  12368. return this.position.x;
  12369. },
  12370. set: function (value) {
  12371. this.position.x = value;
  12372. }
  12373. },
  12374. /**
  12375. * The vertical position of the DisplayObject, in pixels, relative to its parent.
  12376. * If you need the world position of the DisplayObject, use `DisplayObject.worldPosition` instead.
  12377. * @name PIXI.DisplayObject#y
  12378. * @property {number} y - The vertical position of the DisplayObject, in pixels, relative to its parent.
  12379. */
  12380. 'y': {
  12381. get: function () {
  12382. return this.position.y;
  12383. },
  12384. set: function (value) {
  12385. this.position.y = value;
  12386. }
  12387. },
  12388. /**
  12389. * Indicates if this DisplayObject is visible, based on it, and all of its parents, `visible` property values.
  12390. * @name PIXI.DisplayObject#worldVisible
  12391. * @property {boolean} worldVisible - Indicates if this DisplayObject is visible, based on it, and all of its parents, `visible` property values.
  12392. */
  12393. 'worldVisible': {
  12394. get: function () {
  12395. if (!this.visible)
  12396. {
  12397. return false;
  12398. }
  12399. else
  12400. {
  12401. var item = this.parent;
  12402. if (!item)
  12403. {
  12404. return this.visible;
  12405. }
  12406. else
  12407. {
  12408. do
  12409. {
  12410. if (!item.visible)
  12411. {
  12412. return false;
  12413. }
  12414. item = item.parent;
  12415. }
  12416. while (item);
  12417. }
  12418. return true;
  12419. }
  12420. }
  12421. },
  12422. /**
  12423. * Sets a mask for this DisplayObject. A mask is an instance of a Graphics object.
  12424. * When applied it limits the visible area of this DisplayObject to the shape of the mask.
  12425. * Under a Canvas renderer it uses shape clipping. Under a WebGL renderer it uses a Stencil Buffer.
  12426. * To remove a mask, set this property to `null`.
  12427. *
  12428. * @name PIXI.DisplayObject#mask
  12429. * @property {PIXI.Graphics} mask - The mask applied to this DisplayObject. Set to `null` to remove an existing mask.
  12430. */
  12431. 'mask': {
  12432. get: function () {
  12433. return this._mask;
  12434. },
  12435. set: function (value) {
  12436. if (this._mask)
  12437. {
  12438. this._mask.isMask = false;
  12439. }
  12440. this._mask = value;
  12441. if (value)
  12442. {
  12443. this._mask.isMask = true;
  12444. }
  12445. }
  12446. },
  12447. /**
  12448. * Sets the filters for this DisplayObject. This is a WebGL only feature, and is ignored by the Canvas
  12449. * Renderer. A filter is a shader applied to this DisplayObject. You can modify the placement of the filter
  12450. * using `DisplayObject.filterArea`.
  12451. *
  12452. * To remove filters, set this property to `null`.
  12453. *
  12454. * Note: You cannot have a filter set, and a MULTIPLY Blend Mode active, at the same time. Setting a
  12455. * filter will reset this DisplayObjects blend mode to NORMAL.
  12456. *
  12457. * @name PIXI.DisplayObject#filters
  12458. * @property {Array} filters - An Array of PIXI.AbstractFilter objects, or objects that extend them.
  12459. */
  12460. 'filters': {
  12461. get: function () {
  12462. return this._filters;
  12463. },
  12464. set: function (value) {
  12465. if (Array.isArray(value))
  12466. {
  12467. // Put all the passes in one place.
  12468. var passes = [];
  12469. for (var i = 0; i < value.length; i++)
  12470. {
  12471. var filterPasses = value[i].passes;
  12472. for (var j = 0; j < filterPasses.length; j++)
  12473. {
  12474. passes.push(filterPasses[j]);
  12475. }
  12476. }
  12477. // Needed any more?
  12478. this._filterBlock = { target: this, filterPasses: passes };
  12479. }
  12480. this._filters = value;
  12481. if (this.blendMode && this.blendMode === PIXI.blendModes.MULTIPLY)
  12482. {
  12483. this.blendMode = PIXI.blendModes.NORMAL;
  12484. }
  12485. }
  12486. },
  12487. /**
  12488. * Sets if this DisplayObject should be cached as a bitmap.
  12489. *
  12490. * When invoked it will take a snapshot of the DisplayObject, as it is at that moment, and store it
  12491. * in a RenderTexture. This is then used whenever this DisplayObject is rendered. It can provide a
  12492. * performance benefit for complex, but static, DisplayObjects. I.e. those with lots of children.
  12493. *
  12494. * Cached Bitmaps do not track their parents. If you update a property of this DisplayObject, it will not
  12495. * re-generate the cached bitmap automatically. To do that you need to call `DisplayObject.updateCache`.
  12496. *
  12497. * To remove a cached bitmap, set this property to `null`.
  12498. *
  12499. * @name PIXI.DisplayObject#cacheAsBitmap
  12500. * @property {boolean} cacheAsBitmap - Cache this DisplayObject as a Bitmap. Set to `null` to remove an existing cached bitmap.
  12501. */
  12502. 'cacheAsBitmap': {
  12503. get: function () {
  12504. return this._cacheAsBitmap;
  12505. },
  12506. set: function (value) {
  12507. if (this._cacheAsBitmap === value)
  12508. {
  12509. return;
  12510. }
  12511. if (value)
  12512. {
  12513. this._generateCachedSprite();
  12514. }
  12515. else
  12516. {
  12517. this._destroyCachedSprite();
  12518. }
  12519. this._cacheAsBitmap = value;
  12520. }
  12521. }
  12522. });
  12523. /**
  12524. * @author Mat Groves http://matgroves.com/ @Doormat23
  12525. */
  12526. /**
  12527. * A DisplayObjectContainer represents a collection of display objects.
  12528. * It is the base class of all display objects that act as a container for other objects.
  12529. *
  12530. * @class DisplayObjectContainer
  12531. * @extends DisplayObject
  12532. * @constructor
  12533. */
  12534. PIXI.DisplayObjectContainer = function () {
  12535. PIXI.DisplayObject.call(this);
  12536. /**
  12537. * [read-only] The array of children of this container.
  12538. *
  12539. * @property children
  12540. * @type Array(DisplayObject)
  12541. * @readOnly
  12542. */
  12543. this.children = [];
  12544. /**
  12545. * If `ignoreChildInput` is `false` it will allow this objects _children_ to be considered as valid for Input events.
  12546. *
  12547. * If this property is `true` then the children will _not_ be considered as valid for Input events.
  12548. *
  12549. * Note that this property isn't recursive: only immediate children are influenced, it doesn't scan further down.
  12550. * @property {boolean} ignoreChildInput
  12551. * @default
  12552. */
  12553. this.ignoreChildInput = false;
  12554. };
  12555. PIXI.DisplayObjectContainer.prototype = Object.create( PIXI.DisplayObject.prototype );
  12556. PIXI.DisplayObjectContainer.prototype.constructor = PIXI.DisplayObjectContainer;
  12557. /**
  12558. * Adds a child to the container.
  12559. *
  12560. * @method addChild
  12561. * @param child {DisplayObject} The DisplayObject to add to the container
  12562. * @return {DisplayObject} The child that was added.
  12563. */
  12564. PIXI.DisplayObjectContainer.prototype.addChild = function (child) {
  12565. return this.addChildAt(child, this.children.length);
  12566. };
  12567. /**
  12568. * Adds a child to the container at a specified index. If the index is out of bounds an error will be thrown
  12569. *
  12570. * @method addChildAt
  12571. * @param child {DisplayObject} The child to add
  12572. * @param index {Number} The index to place the child in
  12573. * @return {DisplayObject} The child that was added.
  12574. */
  12575. PIXI.DisplayObjectContainer.prototype.addChildAt = function (child, index) {
  12576. if (index >= 0 && index <= this.children.length)
  12577. {
  12578. if (child.parent)
  12579. {
  12580. child.parent.removeChild(child);
  12581. }
  12582. child.parent = this;
  12583. this.children.splice(index, 0, child);
  12584. return child;
  12585. }
  12586. else
  12587. {
  12588. throw new Error(child + 'addChildAt: The index '+ index +' supplied is out of bounds ' + this.children.length);
  12589. }
  12590. };
  12591. /**
  12592. * Swaps the position of 2 Display Objects within this container.
  12593. *
  12594. * @method swapChildren
  12595. * @param child {DisplayObject}
  12596. * @param child2 {DisplayObject}
  12597. */
  12598. PIXI.DisplayObjectContainer.prototype.swapChildren = function (child, child2) {
  12599. if (child === child2)
  12600. {
  12601. return;
  12602. }
  12603. var index1 = this.getChildIndex(child);
  12604. var index2 = this.getChildIndex(child2);
  12605. if (index1 < 0 || index2 < 0)
  12606. {
  12607. throw new Error('swapChildren: Both the supplied DisplayObjects must be a child of the caller.');
  12608. }
  12609. this.children[index1] = child2;
  12610. this.children[index2] = child;
  12611. };
  12612. /**
  12613. * Returns the index position of a child DisplayObject instance
  12614. *
  12615. * @method getChildIndex
  12616. * @param child {DisplayObject} The DisplayObject instance to identify
  12617. * @return {Number} The index position of the child display object to identify
  12618. */
  12619. PIXI.DisplayObjectContainer.prototype.getChildIndex = function (child) {
  12620. var index = this.children.indexOf(child);
  12621. if (index === -1)
  12622. {
  12623. throw new Error('The supplied DisplayObject must be a child of the caller');
  12624. }
  12625. return index;
  12626. };
  12627. /**
  12628. * Changes the position of an existing child in the display object container
  12629. *
  12630. * @method setChildIndex
  12631. * @param child {DisplayObject} The child DisplayObject instance for which you want to change the index number
  12632. * @param index {Number} The resulting index number for the child display object
  12633. */
  12634. PIXI.DisplayObjectContainer.prototype.setChildIndex = function (child, index) {
  12635. if (index < 0 || index >= this.children.length)
  12636. {
  12637. throw new Error('The supplied index is out of bounds');
  12638. }
  12639. var currentIndex = this.getChildIndex(child);
  12640. this.children.splice(currentIndex, 1); //remove from old position
  12641. this.children.splice(index, 0, child); //add at new position
  12642. };
  12643. /**
  12644. * Returns the child at the specified index
  12645. *
  12646. * @method getChildAt
  12647. * @param index {Number} The index to get the child from
  12648. * @return {DisplayObject} The child at the given index, if any.
  12649. */
  12650. PIXI.DisplayObjectContainer.prototype.getChildAt = function (index) {
  12651. if (index < 0 || index >= this.children.length)
  12652. {
  12653. throw new Error('getChildAt: Supplied index '+ index +' does not exist in the child list, or the supplied DisplayObject must be a child of the caller');
  12654. }
  12655. return this.children[index];
  12656. };
  12657. /**
  12658. * Removes a child from the container.
  12659. *
  12660. * @method removeChild
  12661. * @param child {DisplayObject} The DisplayObject to remove
  12662. * @return {DisplayObject} The child that was removed.
  12663. */
  12664. PIXI.DisplayObjectContainer.prototype.removeChild = function (child) {
  12665. var index = this.children.indexOf(child);
  12666. if (index === -1)
  12667. {
  12668. return;
  12669. }
  12670. return this.removeChildAt(index);
  12671. };
  12672. /**
  12673. * Removes a child from the specified index position.
  12674. *
  12675. * @method removeChildAt
  12676. * @param index {Number} The index to get the child from
  12677. * @return {DisplayObject} The child that was removed.
  12678. */
  12679. PIXI.DisplayObjectContainer.prototype.removeChildAt = function (index) {
  12680. var child = this.getChildAt(index);
  12681. if (child)
  12682. {
  12683. child.parent = undefined;
  12684. this.children.splice(index, 1);
  12685. }
  12686. return child;
  12687. };
  12688. /**
  12689. * Removes all children from this container that are within the begin and end indexes.
  12690. *
  12691. * @method removeChildren
  12692. * @param beginIndex {Number} The beginning position. Default value is 0.
  12693. * @param endIndex {Number} The ending position. Default value is size of the container.
  12694. */
  12695. PIXI.DisplayObjectContainer.prototype.removeChildren = function (beginIndex, endIndex) {
  12696. if (beginIndex === undefined) { beginIndex = 0; }
  12697. if (endIndex === undefined) { endIndex = this.children.length; }
  12698. var range = endIndex - beginIndex;
  12699. if (range > 0 && range <= endIndex)
  12700. {
  12701. var removed = this.children.splice(begin, range);
  12702. for (var i = 0; i < removed.length; i++)
  12703. {
  12704. var child = removed[i];
  12705. child.parent = undefined;
  12706. }
  12707. return removed;
  12708. }
  12709. else if (range === 0 && this.children.length === 0)
  12710. {
  12711. return [];
  12712. }
  12713. else
  12714. {
  12715. throw new Error( 'removeChildren: Range Error, numeric values are outside the acceptable range' );
  12716. }
  12717. };
  12718. /*
  12719. * Updates the transform on all children of this container for rendering
  12720. *
  12721. * @method updateTransform
  12722. * @private
  12723. */
  12724. PIXI.DisplayObjectContainer.prototype.updateTransform = function () {
  12725. if (!this.visible)
  12726. {
  12727. return;
  12728. }
  12729. this.displayObjectUpdateTransform();
  12730. if (this._cacheAsBitmap)
  12731. {
  12732. return;
  12733. }
  12734. for (var i = 0; i < this.children.length; i++)
  12735. {
  12736. this.children[i].updateTransform();
  12737. }
  12738. };
  12739. // performance increase to avoid using call.. (10x faster)
  12740. PIXI.DisplayObjectContainer.prototype.displayObjectContainerUpdateTransform = PIXI.DisplayObjectContainer.prototype.updateTransform;
  12741. /**
  12742. * Retrieves the global bounds of the displayObjectContainer as a rectangle. The bounds calculation takes all visible children into consideration.
  12743. *
  12744. * @method getBounds
  12745. * @param {PIXI.DisplayObject|PIXI.Matrix} [targetCoordinateSpace] Returns a rectangle that defines the area of the display object relative to the coordinate system of the targetCoordinateSpace object.
  12746. * @return {Rectangle} The rectangular bounding area
  12747. */
  12748. PIXI.DisplayObjectContainer.prototype.getBounds = function (targetCoordinateSpace) {
  12749. var isTargetCoordinateSpaceDisplayObject = (targetCoordinateSpace && targetCoordinateSpace instanceof PIXI.DisplayObject);
  12750. var isTargetCoordinateSpaceThisOrParent = true;
  12751. if (!isTargetCoordinateSpaceDisplayObject)
  12752. {
  12753. targetCoordinateSpace = this;
  12754. }
  12755. else if (targetCoordinateSpace instanceof PIXI.DisplayObjectContainer)
  12756. {
  12757. isTargetCoordinateSpaceThisOrParent = targetCoordinateSpace.contains(this);
  12758. }
  12759. else
  12760. {
  12761. isTargetCoordinateSpaceThisOrParent = false;
  12762. }
  12763. var i;
  12764. if (isTargetCoordinateSpaceDisplayObject)
  12765. {
  12766. var matrixCache = targetCoordinateSpace.worldTransform;
  12767. targetCoordinateSpace.worldTransform = PIXI.identityMatrix;
  12768. for (i = 0; i < targetCoordinateSpace.children.length; i++)
  12769. {
  12770. targetCoordinateSpace.children[i].updateTransform();
  12771. }
  12772. }
  12773. var minX = Infinity;
  12774. var minY = Infinity;
  12775. var maxX = -Infinity;
  12776. var maxY = -Infinity;
  12777. var childBounds;
  12778. var childMaxX;
  12779. var childMaxY;
  12780. var childVisible = false;
  12781. for (i = 0; i < this.children.length; i++)
  12782. {
  12783. var child = this.children[i];
  12784. if (!child.visible)
  12785. {
  12786. continue;
  12787. }
  12788. childVisible = true;
  12789. childBounds = this.children[i].getBounds();
  12790. minX = (minX < childBounds.x) ? minX : childBounds.x;
  12791. minY = (minY < childBounds.y) ? minY : childBounds.y;
  12792. childMaxX = childBounds.width + childBounds.x;
  12793. childMaxY = childBounds.height + childBounds.y;
  12794. maxX = (maxX > childMaxX) ? maxX : childMaxX;
  12795. maxY = (maxY > childMaxY) ? maxY : childMaxY;
  12796. }
  12797. var bounds = this._bounds;
  12798. if (!childVisible)
  12799. {
  12800. bounds = new PIXI.Rectangle();
  12801. var w0 = bounds.x;
  12802. var w1 = bounds.width + bounds.x;
  12803. var h0 = bounds.y;
  12804. var h1 = bounds.height + bounds.y;
  12805. var worldTransform = this.worldTransform;
  12806. var a = worldTransform.a;
  12807. var b = worldTransform.b;
  12808. var c = worldTransform.c;
  12809. var d = worldTransform.d;
  12810. var tx = worldTransform.tx;
  12811. var ty = worldTransform.ty;
  12812. var x1 = a * w1 + c * h1 + tx;
  12813. var y1 = d * h1 + b * w1 + ty;
  12814. var x2 = a * w0 + c * h1 + tx;
  12815. var y2 = d * h1 + b * w0 + ty;
  12816. var x3 = a * w0 + c * h0 + tx;
  12817. var y3 = d * h0 + b * w0 + ty;
  12818. var x4 = a * w1 + c * h0 + tx;
  12819. var y4 = d * h0 + b * w1 + ty;
  12820. maxX = x1;
  12821. maxY = y1;
  12822. minX = x1;
  12823. minY = y1;
  12824. minX = x2 < minX ? x2 : minX;
  12825. minX = x3 < minX ? x3 : minX;
  12826. minX = x4 < minX ? x4 : minX;
  12827. minY = y2 < minY ? y2 : minY;
  12828. minY = y3 < minY ? y3 : minY;
  12829. minY = y4 < minY ? y4 : minY;
  12830. maxX = x2 > maxX ? x2 : maxX;
  12831. maxX = x3 > maxX ? x3 : maxX;
  12832. maxX = x4 > maxX ? x4 : maxX;
  12833. maxY = y2 > maxY ? y2 : maxY;
  12834. maxY = y3 > maxY ? y3 : maxY;
  12835. maxY = y4 > maxY ? y4 : maxY;
  12836. }
  12837. bounds.x = minX;
  12838. bounds.y = minY;
  12839. bounds.width = maxX - minX;
  12840. bounds.height = maxY - minY;
  12841. if (isTargetCoordinateSpaceDisplayObject)
  12842. {
  12843. targetCoordinateSpace.worldTransform = matrixCache;
  12844. for (i = 0; i < targetCoordinateSpace.children.length; i++)
  12845. {
  12846. targetCoordinateSpace.children[i].updateTransform();
  12847. }
  12848. }
  12849. if (!isTargetCoordinateSpaceThisOrParent)
  12850. {
  12851. var targetCoordinateSpaceBounds = targetCoordinateSpace.getBounds();
  12852. bounds.x -= targetCoordinateSpaceBounds.x;
  12853. bounds.y -= targetCoordinateSpaceBounds.y;
  12854. }
  12855. return bounds;
  12856. };
  12857. /**
  12858. * Retrieves the non-global local bounds of the displayObjectContainer as a rectangle without any transformations. The calculation takes all visible children into consideration.
  12859. *
  12860. * @method getLocalBounds
  12861. * @return {Rectangle} The rectangular bounding area
  12862. */
  12863. PIXI.DisplayObjectContainer.prototype.getLocalBounds = function () {
  12864. return this.getBounds(this);
  12865. };
  12866. /**
  12867. * Determines whether the specified display object is a child of the DisplayObjectContainer instance or the instance itself.
  12868. *
  12869. * @method contains
  12870. * @param {DisplayObject} child
  12871. * @returns {boolean}
  12872. */
  12873. PIXI.DisplayObjectContainer.prototype.contains = function (child) {
  12874. if (!child)
  12875. {
  12876. return false;
  12877. }
  12878. else if (child === this)
  12879. {
  12880. return true;
  12881. }
  12882. else
  12883. {
  12884. return this.contains(child.parent);
  12885. }
  12886. };
  12887. /**
  12888. * Renders the object using the WebGL renderer
  12889. *
  12890. * @method _renderWebGL
  12891. * @param renderSession {RenderSession}
  12892. * @private
  12893. */
  12894. PIXI.DisplayObjectContainer.prototype._renderWebGL = function (renderSession) {
  12895. if (!this.visible || this.alpha <= 0)
  12896. {
  12897. return;
  12898. }
  12899. if (this._cacheAsBitmap)
  12900. {
  12901. this._renderCachedSprite(renderSession);
  12902. return;
  12903. }
  12904. var i;
  12905. if (this._mask || this._filters)
  12906. {
  12907. // push filter first as we need to ensure the stencil buffer is correct for any masking
  12908. if (this._filters)
  12909. {
  12910. renderSession.spriteBatch.flush();
  12911. renderSession.filterManager.pushFilter(this._filterBlock);
  12912. }
  12913. if (this._mask)
  12914. {
  12915. renderSession.spriteBatch.stop();
  12916. renderSession.maskManager.pushMask(this.mask, renderSession);
  12917. renderSession.spriteBatch.start();
  12918. }
  12919. // simple render children!
  12920. for (i = 0; i < this.children.length; i++)
  12921. {
  12922. this.children[i]._renderWebGL(renderSession);
  12923. }
  12924. renderSession.spriteBatch.stop();
  12925. if (this._mask) renderSession.maskManager.popMask(this._mask, renderSession);
  12926. if (this._filters) renderSession.filterManager.popFilter();
  12927. renderSession.spriteBatch.start();
  12928. }
  12929. else
  12930. {
  12931. // simple render children!
  12932. for (i = 0; i < this.children.length; i++)
  12933. {
  12934. this.children[i]._renderWebGL(renderSession);
  12935. }
  12936. }
  12937. };
  12938. /**
  12939. * Renders the object using the Canvas renderer
  12940. *
  12941. * @method _renderCanvas
  12942. * @param renderSession {RenderSession}
  12943. * @private
  12944. */
  12945. PIXI.DisplayObjectContainer.prototype._renderCanvas = function (renderSession) {
  12946. if (this.visible === false || this.alpha === 0)
  12947. {
  12948. return;
  12949. }
  12950. if (this._cacheAsBitmap)
  12951. {
  12952. this._renderCachedSprite(renderSession);
  12953. return;
  12954. }
  12955. if (this._mask)
  12956. {
  12957. renderSession.maskManager.pushMask(this._mask, renderSession);
  12958. }
  12959. for (var i = 0; i < this.children.length; i++)
  12960. {
  12961. this.children[i]._renderCanvas(renderSession);
  12962. }
  12963. if (this._mask)
  12964. {
  12965. renderSession.maskManager.popMask(renderSession);
  12966. }
  12967. };
  12968. /**
  12969. * The width of the displayObjectContainer, setting this will actually modify the scale to achieve the value set
  12970. *
  12971. * @property width
  12972. * @type Number
  12973. */
  12974. Object.defineProperty(PIXI.DisplayObjectContainer.prototype, 'width', {
  12975. get: function() {
  12976. return this.getLocalBounds().width * this.scale.x;
  12977. },
  12978. set: function(value) {
  12979. var width = this.getLocalBounds().width;
  12980. if (width !== 0)
  12981. {
  12982. this.scale.x = value / width;
  12983. }
  12984. else
  12985. {
  12986. this.scale.x = 1;
  12987. }
  12988. this._width = value;
  12989. }
  12990. });
  12991. /**
  12992. * The height of the displayObjectContainer, setting this will actually modify the scale to achieve the value set
  12993. *
  12994. * @property height
  12995. * @type Number
  12996. */
  12997. Object.defineProperty(PIXI.DisplayObjectContainer.prototype, 'height', {
  12998. get: function() {
  12999. return this.getLocalBounds().height * this.scale.y;
  13000. },
  13001. set: function(value) {
  13002. var height = this.getLocalBounds().height;
  13003. if (height !== 0)
  13004. {
  13005. this.scale.y = value / height;
  13006. }
  13007. else
  13008. {
  13009. this.scale.y = 1;
  13010. }
  13011. this._height = value;
  13012. }
  13013. });
  13014. /**
  13015. * @author Mat Groves http://matgroves.com/ @Doormat23
  13016. */
  13017. /**
  13018. * The Sprite object is the base for all textured objects that are rendered to the screen
  13019. *
  13020. * @class Sprite
  13021. * @extends DisplayObjectContainer
  13022. * @constructor
  13023. * @param texture {Texture} The texture for this sprite
  13024. */
  13025. PIXI.Sprite = function (texture) {
  13026. PIXI.DisplayObjectContainer.call(this);
  13027. /**
  13028. * The anchor sets the origin point of the texture.
  13029. * The default is 0,0 this means the texture's origin is the top left
  13030. * Setting than anchor to 0.5,0.5 means the textures origin is centered
  13031. * Setting the anchor to 1,1 would mean the textures origin points will be the bottom right corner
  13032. *
  13033. * @property anchor
  13034. * @type Point
  13035. */
  13036. this.anchor = new PIXI.Point();
  13037. /**
  13038. * The texture that the sprite is using
  13039. *
  13040. * @property texture
  13041. * @type Texture
  13042. */
  13043. this.texture = texture || PIXI.Texture.emptyTexture;
  13044. /**
  13045. * The width of the sprite (this is initially set by the texture)
  13046. *
  13047. * @property _width
  13048. * @type Number
  13049. * @private
  13050. */
  13051. this._width = 0;
  13052. /**
  13053. * The height of the sprite (this is initially set by the texture)
  13054. *
  13055. * @property _height
  13056. * @type Number
  13057. * @private
  13058. */
  13059. this._height = 0;
  13060. /**
  13061. * The tint applied to the sprite. This is a hex value. A value of 0xFFFFFF will remove any tint effect.
  13062. *
  13063. * @property tint
  13064. * @type Number
  13065. * @default 0xFFFFFF
  13066. */
  13067. this.tint = 0xFFFFFF;
  13068. /**
  13069. * The tint applied to the sprite. This is a hex value. A value of 0xFFFFFF will remove any tint effect.
  13070. *
  13071. * @property cachedTint
  13072. * @private
  13073. * @type Number
  13074. * @default -1
  13075. */
  13076. this.cachedTint = -1;
  13077. /**
  13078. * A canvas that contains the tinted version of the Sprite (in Canvas mode, WebGL doesn't populate this)
  13079. *
  13080. * @property tintedTexture
  13081. * @type Canvas
  13082. * @default null
  13083. */
  13084. this.tintedTexture = null;
  13085. /**
  13086. * The blend mode to be applied to the sprite. Set to PIXI.blendModes.NORMAL to remove any blend mode.
  13087. *
  13088. * Warning: You cannot have a blend mode and a filter active on the same Sprite. Doing so will render the sprite invisible.
  13089. *
  13090. * @property blendMode
  13091. * @type Number
  13092. * @default PIXI.blendModes.NORMAL;
  13093. */
  13094. this.blendMode = PIXI.blendModes.NORMAL;
  13095. /**
  13096. * The shader that will be used to render this Sprite.
  13097. * Set to null to remove a current shader.
  13098. *
  13099. * @property shader
  13100. * @type AbstractFilter
  13101. * @default null
  13102. */
  13103. this.shader = null;
  13104. /**
  13105. * Controls if this Sprite is processed by the core Phaser game loops and Group loops.
  13106. *
  13107. * @property exists
  13108. * @type Boolean
  13109. * @default true
  13110. */
  13111. this.exists = true;
  13112. if (this.texture.baseTexture.hasLoaded)
  13113. {
  13114. this.onTextureUpdate();
  13115. }
  13116. this.renderable = true;
  13117. };
  13118. // constructor
  13119. PIXI.Sprite.prototype = Object.create(PIXI.DisplayObjectContainer.prototype);
  13120. PIXI.Sprite.prototype.constructor = PIXI.Sprite;
  13121. /**
  13122. * The width of the sprite, setting this will actually modify the scale to achieve the value set
  13123. *
  13124. * @property width
  13125. * @type Number
  13126. */
  13127. Object.defineProperty(PIXI.Sprite.prototype, 'width', {
  13128. get: function() {
  13129. return this.scale.x * this.texture.frame.width;
  13130. },
  13131. set: function(value) {
  13132. this.scale.x = value / this.texture.frame.width;
  13133. this._width = value;
  13134. }
  13135. });
  13136. /**
  13137. * The height of the sprite, setting this will actually modify the scale to achieve the value set
  13138. *
  13139. * @property height
  13140. * @type Number
  13141. */
  13142. Object.defineProperty(PIXI.Sprite.prototype, 'height', {
  13143. get: function() {
  13144. return this.scale.y * this.texture.frame.height;
  13145. },
  13146. set: function(value) {
  13147. this.scale.y = value / this.texture.frame.height;
  13148. this._height = value;
  13149. }
  13150. });
  13151. /**
  13152. * Sets the texture of the sprite. Be warned that this doesn't remove or destroy the previous
  13153. * texture this Sprite was using.
  13154. *
  13155. * @method setTexture
  13156. * @param texture {Texture} The PIXI texture that is displayed by the sprite
  13157. * @param [destroy=false] {boolean} Call Texture.destroy on the current texture before replacing it with the new one?
  13158. */
  13159. PIXI.Sprite.prototype.setTexture = function(texture, destroyBase)
  13160. {
  13161. if (destroyBase !== undefined)
  13162. {
  13163. this.texture.baseTexture.destroy();
  13164. }
  13165. // Over-ridden by loadTexture as needed
  13166. this.texture.baseTexture.skipRender = false;
  13167. this.texture = texture;
  13168. this.texture.valid = true;
  13169. this.cachedTint = -1;
  13170. };
  13171. /**
  13172. * When the texture is updated, this event will fire to update the scale and frame
  13173. *
  13174. * @method onTextureUpdate
  13175. * @param event
  13176. * @private
  13177. */
  13178. PIXI.Sprite.prototype.onTextureUpdate = function()
  13179. {
  13180. // so if _width is 0 then width was not set..
  13181. if (this._width) this.scale.x = this._width / this.texture.frame.width;
  13182. if (this._height) this.scale.y = this._height / this.texture.frame.height;
  13183. };
  13184. /**
  13185. * Returns the bounds of the Sprite as a rectangle.
  13186. * The bounds calculation takes the worldTransform into account.
  13187. *
  13188. * It is important to note that the transform is not updated when you call this method.
  13189. * So if this Sprite is the child of a Display Object which has had its transform
  13190. * updated since the last render pass, those changes will not yet have been applied
  13191. * to this Sprites worldTransform. If you need to ensure that all parent transforms
  13192. * are factored into this getBounds operation then you should call `updateTransform`
  13193. * on the root most object in this Sprites display list first.
  13194. *
  13195. * @method getBounds
  13196. * @param matrix {Matrix} the transformation matrix of the sprite
  13197. * @return {Rectangle} the framing rectangle
  13198. */
  13199. PIXI.Sprite.prototype.getBounds = function(matrix)
  13200. {
  13201. var width = this.texture.frame.width;
  13202. var height = this.texture.frame.height;
  13203. var w0 = width * (1-this.anchor.x);
  13204. var w1 = width * -this.anchor.x;
  13205. var h0 = height * (1-this.anchor.y);
  13206. var h1 = height * -this.anchor.y;
  13207. var worldTransform = matrix || this.worldTransform;
  13208. var a = worldTransform.a;
  13209. var b = worldTransform.b;
  13210. var c = worldTransform.c;
  13211. var d = worldTransform.d;
  13212. var tx = worldTransform.tx;
  13213. var ty = worldTransform.ty;
  13214. var maxX = -Infinity;
  13215. var maxY = -Infinity;
  13216. var minX = Infinity;
  13217. var minY = Infinity;
  13218. if (b === 0 && c === 0)
  13219. {
  13220. // scale may be negative!
  13221. if (a < 0)
  13222. {
  13223. a *= -1;
  13224. var temp = w0;
  13225. w0 = -w1;
  13226. w1 = -temp;
  13227. }
  13228. if (d < 0)
  13229. {
  13230. d *= -1;
  13231. var temp = h0;
  13232. h0 = -h1;
  13233. h1 = -temp;
  13234. }
  13235. // this means there is no rotation going on right? RIGHT?
  13236. // if thats the case then we can avoid checking the bound values! yay
  13237. minX = a * w1 + tx;
  13238. maxX = a * w0 + tx;
  13239. minY = d * h1 + ty;
  13240. maxY = d * h0 + ty;
  13241. }
  13242. else
  13243. {
  13244. var x1 = a * w1 + c * h1 + tx;
  13245. var y1 = d * h1 + b * w1 + ty;
  13246. var x2 = a * w0 + c * h1 + tx;
  13247. var y2 = d * h1 + b * w0 + ty;
  13248. var x3 = a * w0 + c * h0 + tx;
  13249. var y3 = d * h0 + b * w0 + ty;
  13250. var x4 = a * w1 + c * h0 + tx;
  13251. var y4 = d * h0 + b * w1 + ty;
  13252. minX = x1 < minX ? x1 : minX;
  13253. minX = x2 < minX ? x2 : minX;
  13254. minX = x3 < minX ? x3 : minX;
  13255. minX = x4 < minX ? x4 : minX;
  13256. minY = y1 < minY ? y1 : minY;
  13257. minY = y2 < minY ? y2 : minY;
  13258. minY = y3 < minY ? y3 : minY;
  13259. minY = y4 < minY ? y4 : minY;
  13260. maxX = x1 > maxX ? x1 : maxX;
  13261. maxX = x2 > maxX ? x2 : maxX;
  13262. maxX = x3 > maxX ? x3 : maxX;
  13263. maxX = x4 > maxX ? x4 : maxX;
  13264. maxY = y1 > maxY ? y1 : maxY;
  13265. maxY = y2 > maxY ? y2 : maxY;
  13266. maxY = y3 > maxY ? y3 : maxY;
  13267. maxY = y4 > maxY ? y4 : maxY;
  13268. }
  13269. var bounds = this._bounds;
  13270. bounds.x = minX;
  13271. bounds.width = maxX - minX;
  13272. bounds.y = minY;
  13273. bounds.height = maxY - minY;
  13274. // store a reference so that if this function gets called again in the render cycle we do not have to recalculate
  13275. this._currentBounds = bounds;
  13276. return bounds;
  13277. };
  13278. /**
  13279. * Retrieves the non-global local bounds of the Sprite as a rectangle. The calculation takes all visible children into consideration.
  13280. *
  13281. * @method getLocalBounds
  13282. * @return {Rectangle} The rectangular bounding area
  13283. */
  13284. PIXI.Sprite.prototype.getLocalBounds = function () {
  13285. var matrixCache = this.worldTransform;
  13286. this.worldTransform = PIXI.identityMatrix;
  13287. for (var i = 0; i < this.children.length; i++)
  13288. {
  13289. this.children[i].updateTransform();
  13290. }
  13291. var bounds = this.getBounds();
  13292. this.worldTransform = matrixCache;
  13293. for (i = 0; i < this.children.length; i++)
  13294. {
  13295. this.children[i].updateTransform();
  13296. }
  13297. return bounds;
  13298. };
  13299. /**
  13300. * Renders the object using the WebGL renderer
  13301. *
  13302. * @method _renderWebGL
  13303. * @param renderSession {RenderSession}
  13304. * @param {Matrix} [matrix] - Optional matrix. If provided the Display Object will be rendered using this matrix, otherwise it will use its worldTransform.
  13305. * @private
  13306. */
  13307. PIXI.Sprite.prototype._renderWebGL = function(renderSession, matrix)
  13308. {
  13309. // if the sprite is not visible or the alpha is 0 then no need to render this element
  13310. if (!this.visible || this.alpha <= 0 || !this.renderable) return;
  13311. // They provided an alternative rendering matrix, so use it
  13312. var wt = this.worldTransform;
  13313. if (matrix)
  13314. {
  13315. wt = matrix;
  13316. }
  13317. // A quick check to see if this element has a mask or a filter.
  13318. if (this._mask || this._filters)
  13319. {
  13320. var spriteBatch = renderSession.spriteBatch;
  13321. // push filter first as we need to ensure the stencil buffer is correct for any masking
  13322. if (this._filters)
  13323. {
  13324. spriteBatch.flush();
  13325. renderSession.filterManager.pushFilter(this._filterBlock);
  13326. }
  13327. if (this._mask)
  13328. {
  13329. spriteBatch.stop();
  13330. renderSession.maskManager.pushMask(this.mask, renderSession);
  13331. spriteBatch.start();
  13332. }
  13333. // add this sprite to the batch
  13334. spriteBatch.render(this);
  13335. // now loop through the children and make sure they get rendered
  13336. for (var i = 0; i < this.children.length; i++)
  13337. {
  13338. this.children[i]._renderWebGL(renderSession);
  13339. }
  13340. // time to stop the sprite batch as either a mask element or a filter draw will happen next
  13341. spriteBatch.stop();
  13342. if (this._mask) renderSession.maskManager.popMask(this._mask, renderSession);
  13343. if (this._filters) renderSession.filterManager.popFilter();
  13344. spriteBatch.start();
  13345. }
  13346. else
  13347. {
  13348. renderSession.spriteBatch.render(this);
  13349. // Render children!
  13350. for (var i = 0; i < this.children.length; i++)
  13351. {
  13352. this.children[i]._renderWebGL(renderSession, wt);
  13353. }
  13354. }
  13355. };
  13356. /**
  13357. * Renders the object using the Canvas renderer
  13358. *
  13359. * @method _renderCanvas
  13360. * @param renderSession {RenderSession}
  13361. * @param {Matrix} [matrix] - Optional matrix. If provided the Display Object will be rendered using this matrix, otherwise it will use its worldTransform.
  13362. * @private
  13363. */
  13364. PIXI.Sprite.prototype._renderCanvas = function(renderSession, matrix)
  13365. {
  13366. // If the sprite is not visible or the alpha is 0 then no need to render this element
  13367. if (!this.visible || this.alpha === 0 || !this.renderable || this.texture.crop.width <= 0 || this.texture.crop.height <= 0)
  13368. {
  13369. return;
  13370. }
  13371. var wt = this.worldTransform;
  13372. // If they provided an alternative rendering matrix then use it
  13373. if (matrix)
  13374. {
  13375. wt = matrix;
  13376. }
  13377. if (this.blendMode !== renderSession.currentBlendMode)
  13378. {
  13379. renderSession.currentBlendMode = this.blendMode;
  13380. renderSession.context.globalCompositeOperation = PIXI.blendModesCanvas[renderSession.currentBlendMode];
  13381. }
  13382. if (this._mask)
  13383. {
  13384. renderSession.maskManager.pushMask(this._mask, renderSession);
  13385. }
  13386. // Ignore null sources
  13387. if (this.texture.valid)
  13388. {
  13389. var resolution = this.texture.baseTexture.resolution / renderSession.resolution;
  13390. renderSession.context.globalAlpha = this.worldAlpha;
  13391. // If smoothingEnabled is supported and we need to change the smoothing property for this texture
  13392. if (renderSession.smoothProperty && renderSession.scaleMode !== this.texture.baseTexture.scaleMode)
  13393. {
  13394. renderSession.scaleMode = this.texture.baseTexture.scaleMode;
  13395. renderSession.context[renderSession.smoothProperty] = (renderSession.scaleMode === PIXI.scaleModes.LINEAR);
  13396. }
  13397. // If the texture is trimmed we offset by the trim x/y, otherwise we use the frame dimensions
  13398. var dx = (this.texture.trim) ? this.texture.trim.x - this.anchor.x * this.texture.trim.width : this.anchor.x * -this.texture.frame.width;
  13399. var dy = (this.texture.trim) ? this.texture.trim.y - this.anchor.y * this.texture.trim.height : this.anchor.y * -this.texture.frame.height;
  13400. var tx = (wt.tx * renderSession.resolution) + renderSession.shakeX;
  13401. var ty = (wt.ty * renderSession.resolution) + renderSession.shakeY;
  13402. // Allow for pixel rounding
  13403. if (renderSession.roundPixels)
  13404. {
  13405. renderSession.context.setTransform(wt.a, wt.b, wt.c, wt.d, tx | 0, ty | 0);
  13406. dx |= 0;
  13407. dy |= 0;
  13408. }
  13409. else
  13410. {
  13411. renderSession.context.setTransform(wt.a, wt.b, wt.c, wt.d, tx, ty);
  13412. }
  13413. var cw = this.texture.crop.width;
  13414. var ch = this.texture.crop.height;
  13415. dx /= resolution;
  13416. dy /= resolution;
  13417. if (this.tint !== 0xFFFFFF)
  13418. {
  13419. if (this.texture.requiresReTint || this.cachedTint !== this.tint)
  13420. {
  13421. this.tintedTexture = PIXI.CanvasTinter.getTintedTexture(this, this.tint);
  13422. this.cachedTint = this.tint;
  13423. this.texture.requiresReTint = false;
  13424. }
  13425. renderSession.context.drawImage(this.tintedTexture, 0, 0, cw, ch, dx, dy, cw / resolution, ch / resolution);
  13426. }
  13427. else
  13428. {
  13429. var cx = this.texture.crop.x;
  13430. var cy = this.texture.crop.y;
  13431. renderSession.context.drawImage(this.texture.baseTexture.source, cx, cy, cw, ch, dx, dy, cw / resolution, ch / resolution);
  13432. }
  13433. }
  13434. for (var i = 0; i < this.children.length; i++)
  13435. {
  13436. this.children[i]._renderCanvas(renderSession);
  13437. }
  13438. if (this._mask)
  13439. {
  13440. renderSession.maskManager.popMask(renderSession);
  13441. }
  13442. };
  13443. /**
  13444. * @author Mat Groves http://matgroves.com/
  13445. */
  13446. /**
  13447. * The SpriteBatch class is a really fast version of the DisplayObjectContainer
  13448. * built solely for speed, so use when you need a lot of sprites or particles.
  13449. * And it's extremely easy to use :
  13450. var container = new PIXI.SpriteBatch();
  13451. for(var i = 0; i < 100; i++)
  13452. {
  13453. var sprite = new PIXI.Sprite.fromImage("myImage.png");
  13454. container.addChild(sprite);
  13455. }
  13456. * And here you have a hundred sprites that will be renderer at the speed of light
  13457. *
  13458. * @class SpriteBatch
  13459. * @constructor
  13460. * @param texture {Texture}
  13461. */
  13462. PIXI.SpriteBatch = function(texture)
  13463. {
  13464. PIXI.DisplayObjectContainer.call( this);
  13465. this.textureThing = texture;
  13466. this.ready = false;
  13467. };
  13468. PIXI.SpriteBatch.prototype = Object.create(PIXI.DisplayObjectContainer.prototype);
  13469. PIXI.SpriteBatch.prototype.constructor = PIXI.SpriteBatch;
  13470. /*
  13471. * Initialises the spriteBatch
  13472. *
  13473. * @method initWebGL
  13474. * @param gl {WebGLContext} the current WebGL drawing context
  13475. */
  13476. PIXI.SpriteBatch.prototype.initWebGL = function(gl)
  13477. {
  13478. // TODO only one needed for the whole engine really?
  13479. this.fastSpriteBatch = new PIXI.WebGLFastSpriteBatch(gl);
  13480. this.ready = true;
  13481. };
  13482. /*
  13483. * Updates the object transform for rendering
  13484. *
  13485. * @method updateTransform
  13486. * @private
  13487. */
  13488. PIXI.SpriteBatch.prototype.updateTransform = function()
  13489. {
  13490. // TODO don't need to!
  13491. this.displayObjectUpdateTransform();
  13492. // PIXI.DisplayObjectContainer.prototype.updateTransform.call( this );
  13493. };
  13494. /**
  13495. * Renders the object using the WebGL renderer
  13496. *
  13497. * @method _renderWebGL
  13498. * @param renderSession {RenderSession}
  13499. * @private
  13500. */
  13501. PIXI.SpriteBatch.prototype._renderWebGL = function(renderSession)
  13502. {
  13503. if (!this.visible || this.alpha <= 0 || !this.children.length) return;
  13504. if (!this.ready)
  13505. {
  13506. this.initWebGL(renderSession.gl);
  13507. }
  13508. if (this.fastSpriteBatch.gl !== renderSession.gl)
  13509. {
  13510. this.fastSpriteBatch.setContext(renderSession.gl);
  13511. }
  13512. renderSession.spriteBatch.stop();
  13513. renderSession.shaderManager.setShader(renderSession.shaderManager.fastShader);
  13514. this.fastSpriteBatch.begin(this, renderSession);
  13515. this.fastSpriteBatch.render(this);
  13516. renderSession.spriteBatch.start();
  13517. };
  13518. /**
  13519. * Renders the object using the Canvas renderer
  13520. *
  13521. * @method _renderCanvas
  13522. * @param renderSession {RenderSession}
  13523. * @private
  13524. */
  13525. PIXI.SpriteBatch.prototype._renderCanvas = function(renderSession)
  13526. {
  13527. if (!this.visible || this.alpha <= 0 || !this.children.length) return;
  13528. var context = renderSession.context;
  13529. context.globalAlpha = this.worldAlpha;
  13530. this.displayObjectUpdateTransform();
  13531. var transform = this.worldTransform;
  13532. var isRotated = true;
  13533. for (var i = 0; i < this.children.length; i++)
  13534. {
  13535. var child = this.children[i];
  13536. if (!child.visible) continue;
  13537. var texture = child.texture;
  13538. var frame = texture.frame;
  13539. context.globalAlpha = this.worldAlpha * child.alpha;
  13540. if (child.rotation % (Math.PI * 2) === 0)
  13541. {
  13542. if (isRotated)
  13543. {
  13544. context.setTransform(transform.a, transform.b, transform.c, transform.d, transform.tx, transform.ty);
  13545. isRotated = false;
  13546. }
  13547. // this is the fastest way to optimise! - if rotation is 0 then we can avoid any kind of setTransform call
  13548. context.drawImage(texture.baseTexture.source,
  13549. frame.x,
  13550. frame.y,
  13551. frame.width,
  13552. frame.height,
  13553. ((child.anchor.x) * (-frame.width * child.scale.x) + child.position.x + 0.5 + renderSession.shakeX) | 0,
  13554. ((child.anchor.y) * (-frame.height * child.scale.y) + child.position.y + 0.5 + renderSession.shakeY) | 0,
  13555. frame.width * child.scale.x,
  13556. frame.height * child.scale.y);
  13557. }
  13558. else
  13559. {
  13560. if (!isRotated) isRotated = true;
  13561. child.displayObjectUpdateTransform();
  13562. var childTransform = child.worldTransform;
  13563. var tx = (childTransform.tx * renderSession.resolution) + renderSession.shakeX;
  13564. var ty = (childTransform.ty * renderSession.resolution) + renderSession.shakeY;
  13565. // allow for trimming
  13566. if (renderSession.roundPixels)
  13567. {
  13568. context.setTransform(childTransform.a, childTransform.b, childTransform.c, childTransform.d, tx | 0, ty | 0);
  13569. }
  13570. else
  13571. {
  13572. context.setTransform(childTransform.a, childTransform.b, childTransform.c, childTransform.d, tx, ty);
  13573. }
  13574. context.drawImage(texture.baseTexture.source,
  13575. frame.x,
  13576. frame.y,
  13577. frame.width,
  13578. frame.height,
  13579. ((child.anchor.x) * (-frame.width) + 0.5) | 0,
  13580. ((child.anchor.y) * (-frame.height) + 0.5) | 0,
  13581. frame.width,
  13582. frame.height);
  13583. }
  13584. }
  13585. };
  13586. /**
  13587. * @author Mat Groves http://matgroves.com/ @Doormat23
  13588. */
  13589. /**
  13590. * Converts a hex color number to an [R, G, B] array
  13591. *
  13592. * @method hex2rgb
  13593. * @param hex {Number}
  13594. */
  13595. PIXI.hex2rgb = function(hex) {
  13596. return [(hex >> 16 & 0xFF) / 255, ( hex >> 8 & 0xFF) / 255, (hex & 0xFF)/ 255];
  13597. };
  13598. /**
  13599. * Converts a color as an [R, G, B] array to a hex number
  13600. *
  13601. * @method rgb2hex
  13602. * @param rgb {Array}
  13603. */
  13604. PIXI.rgb2hex = function(rgb) {
  13605. return ((rgb[0]*255 << 16) + (rgb[1]*255 << 8) + rgb[2]*255);
  13606. };
  13607. /**
  13608. * Checks whether the Canvas BlendModes are supported by the current browser for drawImage
  13609. *
  13610. * @method canUseNewCanvasBlendModes
  13611. * @return {Boolean} whether they are supported
  13612. */
  13613. PIXI.canUseNewCanvasBlendModes = function()
  13614. {
  13615. if (document === undefined) return false;
  13616. var pngHead = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAQAAAABAQMAAADD8p2OAAAAA1BMVEX/';
  13617. var pngEnd = 'AAAACklEQVQI12NgAAAAAgAB4iG8MwAAAABJRU5ErkJggg==';
  13618. var magenta = new Image();
  13619. magenta.src = pngHead + 'AP804Oa6' + pngEnd;
  13620. var yellow = new Image();
  13621. yellow.src = pngHead + '/wCKxvRF' + pngEnd;
  13622. var canvas = PIXI.CanvasPool.create(this, 6, 1);
  13623. var context = canvas.getContext('2d');
  13624. context.globalCompositeOperation = 'multiply';
  13625. context.drawImage(magenta, 0, 0);
  13626. context.drawImage(yellow, 2, 0);
  13627. if (!context.getImageData(2,0,1,1))
  13628. {
  13629. return false;
  13630. }
  13631. var data = context.getImageData(2,0,1,1).data;
  13632. PIXI.CanvasPool.remove(this);
  13633. return (data[0] === 255 && data[1] === 0 && data[2] === 0);
  13634. };
  13635. /**
  13636. * Given a number, this function returns the closest number that is a power of two
  13637. * this function is taken from Starling Framework as its pretty neat ;)
  13638. *
  13639. * @method getNextPowerOfTwo
  13640. * @param number {Number}
  13641. * @return {Number} the closest number that is a power of two
  13642. */
  13643. PIXI.getNextPowerOfTwo = function(number)
  13644. {
  13645. if (number > 0 && (number & (number - 1)) === 0) // see: http://goo.gl/D9kPj
  13646. return number;
  13647. else
  13648. {
  13649. var result = 1;
  13650. while (result < number) result <<= 1;
  13651. return result;
  13652. }
  13653. };
  13654. /**
  13655. * checks if the given width and height make a power of two texture
  13656. * @method isPowerOfTwo
  13657. * @param width {Number}
  13658. * @param height {Number}
  13659. * @return {Boolean}
  13660. */
  13661. PIXI.isPowerOfTwo = function(width, height)
  13662. {
  13663. return (width > 0 && (width & (width - 1)) === 0 && height > 0 && (height & (height - 1)) === 0);
  13664. };
  13665. /**
  13666. * @author Richard Davey <rich@photonstorm.com>
  13667. * @copyright 2016 Photon Storm Ltd.
  13668. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  13669. */
  13670. /**
  13671. * The CanvasPool is a global static object that allows Pixi and Phaser to pool canvas DOM elements.
  13672. *
  13673. * @class CanvasPool
  13674. * @static
  13675. */
  13676. PIXI.CanvasPool = {
  13677. /**
  13678. * Creates a new Canvas DOM element, or pulls one from the pool if free.
  13679. *
  13680. * @method create
  13681. * @static
  13682. * @param parent {any} The parent of the canvas element.
  13683. * @param width {number} The width of the canvas element.
  13684. * @param height {number} The height of the canvas element.
  13685. * @return {HTMLCanvasElement} The canvas element.
  13686. */
  13687. create: function (parent, width, height) {
  13688. var idx = PIXI.CanvasPool.getFirst();
  13689. var canvas;
  13690. if (idx === -1)
  13691. {
  13692. var container = {
  13693. parent: parent,
  13694. canvas: document.createElement('canvas')
  13695. }
  13696. PIXI.CanvasPool.pool.push(container);
  13697. canvas = container.canvas;
  13698. }
  13699. else
  13700. {
  13701. PIXI.CanvasPool.pool[idx].parent = parent;
  13702. canvas = PIXI.CanvasPool.pool[idx].canvas;
  13703. }
  13704. if (width !== undefined)
  13705. {
  13706. canvas.width = width;
  13707. canvas.height = height;
  13708. }
  13709. return canvas;
  13710. },
  13711. /**
  13712. * Gets the first free canvas index from the pool.
  13713. *
  13714. * @method getFirst
  13715. * @static
  13716. * @return {number}
  13717. */
  13718. getFirst: function () {
  13719. var pool = PIXI.CanvasPool.pool;
  13720. for (var i = 0; i < pool.length; i++)
  13721. {
  13722. if (!pool[i].parent)
  13723. {
  13724. return i;
  13725. }
  13726. }
  13727. return -1;
  13728. },
  13729. /**
  13730. * Removes the parent from a canvas element from the pool, freeing it up for re-use.
  13731. *
  13732. * @method remove
  13733. * @param parent {any} The parent of the canvas element.
  13734. * @static
  13735. */
  13736. remove: function (parent) {
  13737. var pool = PIXI.CanvasPool.pool;
  13738. for (var i = 0; i < pool.length; i++)
  13739. {
  13740. if (pool[i].parent === parent)
  13741. {
  13742. pool[i].parent = null;
  13743. pool[i].canvas.width = 1;
  13744. pool[i].canvas.height = 1;
  13745. }
  13746. }
  13747. },
  13748. /**
  13749. * Removes the parent from a canvas element from the pool, freeing it up for re-use.
  13750. *
  13751. * @method removeByCanvas
  13752. * @param canvas {HTMLCanvasElement} The canvas element to remove
  13753. * @static
  13754. */
  13755. removeByCanvas: function (canvas) {
  13756. var pool = PIXI.CanvasPool.pool;
  13757. for (var i = 0; i < pool.length; i++)
  13758. {
  13759. if (pool[i].canvas === canvas)
  13760. {
  13761. pool[i].parent = null;
  13762. pool[i].canvas.width = 1;
  13763. pool[i].canvas.height = 1;
  13764. }
  13765. }
  13766. },
  13767. /**
  13768. * Gets the total number of used canvas elements in the pool.
  13769. *
  13770. * @method getTotal
  13771. * @static
  13772. * @return {number} The number of in-use (parented) canvas elements in the pool.
  13773. */
  13774. getTotal: function () {
  13775. var pool = PIXI.CanvasPool.pool;
  13776. var c = 0;
  13777. for (var i = 0; i < pool.length; i++)
  13778. {
  13779. if (pool[i].parent)
  13780. {
  13781. c++;
  13782. }
  13783. }
  13784. return c;
  13785. },
  13786. /**
  13787. * Gets the total number of free canvas elements in the pool.
  13788. *
  13789. * @method getFree
  13790. * @static
  13791. * @return {number} The number of free (un-parented) canvas elements in the pool.
  13792. */
  13793. getFree: function () {
  13794. var pool = PIXI.CanvasPool.pool;
  13795. var c = 0;
  13796. for (var i = 0; i < pool.length; i++)
  13797. {
  13798. if (!pool[i].parent)
  13799. {
  13800. c++;
  13801. }
  13802. }
  13803. return c;
  13804. }
  13805. };
  13806. /**
  13807. * The pool into which the canvas dom elements are placed.
  13808. *
  13809. * @property pool
  13810. * @type Array
  13811. * @static
  13812. */
  13813. PIXI.CanvasPool.pool = [];
  13814. /**
  13815. * @author Mat Groves http://matgroves.com/ @Doormat23
  13816. */
  13817. /**
  13818. * @method initDefaultShaders
  13819. * @static
  13820. * @private
  13821. */
  13822. PIXI.initDefaultShaders = function()
  13823. {
  13824. };
  13825. /**
  13826. * @method CompileVertexShader
  13827. * @static
  13828. * @param gl {WebGLContext} the current WebGL drawing context
  13829. * @param shaderSrc {Array}
  13830. * @return {Any}
  13831. */
  13832. PIXI.CompileVertexShader = function(gl, shaderSrc)
  13833. {
  13834. return PIXI._CompileShader(gl, shaderSrc, gl.VERTEX_SHADER);
  13835. };
  13836. /**
  13837. * @method CompileFragmentShader
  13838. * @static
  13839. * @param gl {WebGLContext} the current WebGL drawing context
  13840. * @param shaderSrc {Array}
  13841. * @return {Any}
  13842. */
  13843. PIXI.CompileFragmentShader = function(gl, shaderSrc)
  13844. {
  13845. return PIXI._CompileShader(gl, shaderSrc, gl.FRAGMENT_SHADER);
  13846. };
  13847. /**
  13848. * @method _CompileShader
  13849. * @static
  13850. * @private
  13851. * @param gl {WebGLContext} the current WebGL drawing context
  13852. * @param shaderSrc {Array}
  13853. * @param shaderType {Number}
  13854. * @return {Any}
  13855. */
  13856. PIXI._CompileShader = function(gl, shaderSrc, shaderType)
  13857. {
  13858. var src = shaderSrc;
  13859. if (Array.isArray(shaderSrc))
  13860. {
  13861. src = shaderSrc.join("\n");
  13862. }
  13863. var shader = gl.createShader(shaderType);
  13864. gl.shaderSource(shader, src);
  13865. gl.compileShader(shader);
  13866. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS))
  13867. {
  13868. window.console.log(gl.getShaderInfoLog(shader));
  13869. return null;
  13870. }
  13871. return shader;
  13872. };
  13873. /**
  13874. * @method compileProgram
  13875. * @static
  13876. * @param gl {WebGLContext} the current WebGL drawing context
  13877. * @param vertexSrc {Array}
  13878. * @param fragmentSrc {Array}
  13879. * @return {Any}
  13880. */
  13881. PIXI.compileProgram = function(gl, vertexSrc, fragmentSrc)
  13882. {
  13883. var fragmentShader = PIXI.CompileFragmentShader(gl, fragmentSrc);
  13884. var vertexShader = PIXI.CompileVertexShader(gl, vertexSrc);
  13885. var shaderProgram = gl.createProgram();
  13886. gl.attachShader(shaderProgram, vertexShader);
  13887. gl.attachShader(shaderProgram, fragmentShader);
  13888. gl.linkProgram(shaderProgram);
  13889. if (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS))
  13890. {
  13891. window.console.log(gl.getProgramInfoLog(shaderProgram));
  13892. window.console.log("Could not initialise shaders");
  13893. }
  13894. return shaderProgram;
  13895. };
  13896. /**
  13897. * @author Mat Groves http://matgroves.com/ @Doormat23
  13898. * @author Richard Davey http://www.photonstorm.com @photonstorm
  13899. */
  13900. /**
  13901. * @class PixiShader
  13902. * @constructor
  13903. * @param gl {WebGLContext} the current WebGL drawing context
  13904. */
  13905. PIXI.PixiShader = function(gl)
  13906. {
  13907. /**
  13908. * @property _UID
  13909. * @type Number
  13910. * @private
  13911. */
  13912. this._UID = PIXI._UID++;
  13913. /**
  13914. * @property gl
  13915. * @type WebGLContext
  13916. */
  13917. this.gl = gl;
  13918. /**
  13919. * The WebGL program.
  13920. * @property program
  13921. * @type Any
  13922. */
  13923. this.program = null;
  13924. /**
  13925. * The fragment shader.
  13926. * @property fragmentSrc
  13927. * @type Array
  13928. */
  13929. this.fragmentSrc = [
  13930. 'precision lowp float;',
  13931. 'varying vec2 vTextureCoord;',
  13932. 'varying vec4 vColor;',
  13933. 'uniform sampler2D uSampler;',
  13934. 'void main(void) {',
  13935. ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;',
  13936. '}'
  13937. ];
  13938. /**
  13939. * A local texture counter for multi-texture shaders.
  13940. * @property textureCount
  13941. * @type Number
  13942. */
  13943. this.textureCount = 0;
  13944. /**
  13945. * A local flag
  13946. * @property firstRun
  13947. * @type Boolean
  13948. * @private
  13949. */
  13950. this.firstRun = true;
  13951. /**
  13952. * A dirty flag
  13953. * @property dirty
  13954. * @type Boolean
  13955. */
  13956. this.dirty = true;
  13957. /**
  13958. * Uniform attributes cache.
  13959. * @property attributes
  13960. * @type Array
  13961. * @private
  13962. */
  13963. this.attributes = [];
  13964. this.init();
  13965. };
  13966. PIXI.PixiShader.prototype.constructor = PIXI.PixiShader;
  13967. /**
  13968. * Initialises the shader.
  13969. *
  13970. * @method init
  13971. */
  13972. PIXI.PixiShader.prototype.init = function()
  13973. {
  13974. var gl = this.gl;
  13975. var program = PIXI.compileProgram(gl, this.vertexSrc || PIXI.PixiShader.defaultVertexSrc, this.fragmentSrc);
  13976. gl.useProgram(program);
  13977. // get and store the uniforms for the shader
  13978. this.uSampler = gl.getUniformLocation(program, 'uSampler');
  13979. this.projectionVector = gl.getUniformLocation(program, 'projectionVector');
  13980. this.offsetVector = gl.getUniformLocation(program, 'offsetVector');
  13981. this.dimensions = gl.getUniformLocation(program, 'dimensions');
  13982. // get and store the attributes
  13983. this.aVertexPosition = gl.getAttribLocation(program, 'aVertexPosition');
  13984. this.aTextureCoord = gl.getAttribLocation(program, 'aTextureCoord');
  13985. this.colorAttribute = gl.getAttribLocation(program, 'aColor');
  13986. // Begin worst hack eva //
  13987. // WHY??? ONLY on my chrome pixel the line above returns -1 when using filters?
  13988. // maybe its something to do with the current state of the gl context.
  13989. // I'm convinced this is a bug in the chrome browser as there is NO reason why this should be returning -1 especially as it only manifests on my chrome pixel
  13990. // If theres any webGL people that know why could happen please help :)
  13991. if(this.colorAttribute === -1)
  13992. {
  13993. this.colorAttribute = 2;
  13994. }
  13995. this.attributes = [this.aVertexPosition, this.aTextureCoord, this.colorAttribute];
  13996. // End worst hack eva //
  13997. // add those custom shaders!
  13998. for (var key in this.uniforms)
  13999. {
  14000. // get the uniform locations..
  14001. this.uniforms[key].uniformLocation = gl.getUniformLocation(program, key);
  14002. }
  14003. this.initUniforms();
  14004. this.program = program;
  14005. };
  14006. /**
  14007. * Initialises the shader uniform values.
  14008. *
  14009. * Uniforms are specified in the GLSL_ES Specification: http://www.khronos.org/registry/webgl/specs/latest/1.0/
  14010. * http://www.khronos.org/registry/gles/specs/2.0/GLSL_ES_Specification_1.0.17.pdf
  14011. *
  14012. * @method initUniforms
  14013. */
  14014. PIXI.PixiShader.prototype.initUniforms = function()
  14015. {
  14016. this.textureCount = 1;
  14017. var gl = this.gl;
  14018. var uniform;
  14019. for (var key in this.uniforms)
  14020. {
  14021. uniform = this.uniforms[key];
  14022. var type = uniform.type;
  14023. if (type === 'sampler2D')
  14024. {
  14025. uniform._init = false;
  14026. if (uniform.value !== null)
  14027. {
  14028. this.initSampler2D(uniform);
  14029. }
  14030. }
  14031. else if (type === 'mat2' || type === 'mat3' || type === 'mat4')
  14032. {
  14033. // These require special handling
  14034. uniform.glMatrix = true;
  14035. uniform.glValueLength = 1;
  14036. if (type === 'mat2')
  14037. {
  14038. uniform.glFunc = gl.uniformMatrix2fv;
  14039. }
  14040. else if (type === 'mat3')
  14041. {
  14042. uniform.glFunc = gl.uniformMatrix3fv;
  14043. }
  14044. else if (type === 'mat4')
  14045. {
  14046. uniform.glFunc = gl.uniformMatrix4fv;
  14047. }
  14048. }
  14049. else
  14050. {
  14051. // GL function reference
  14052. uniform.glFunc = gl['uniform' + type];
  14053. if (type === '2f' || type === '2i')
  14054. {
  14055. uniform.glValueLength = 2;
  14056. }
  14057. else if (type === '3f' || type === '3i')
  14058. {
  14059. uniform.glValueLength = 3;
  14060. }
  14061. else if (type === '4f' || type === '4i')
  14062. {
  14063. uniform.glValueLength = 4;
  14064. }
  14065. else
  14066. {
  14067. uniform.glValueLength = 1;
  14068. }
  14069. }
  14070. }
  14071. };
  14072. /**
  14073. * Initialises a Sampler2D uniform (which may only be available later on after initUniforms once the texture has loaded)
  14074. *
  14075. * @method initSampler2D
  14076. */
  14077. PIXI.PixiShader.prototype.initSampler2D = function(uniform)
  14078. {
  14079. if (!uniform.value || !uniform.value.baseTexture || !uniform.value.baseTexture.hasLoaded)
  14080. {
  14081. return;
  14082. }
  14083. var gl = this.gl;
  14084. gl.activeTexture(gl['TEXTURE' + this.textureCount]);
  14085. gl.bindTexture(gl.TEXTURE_2D, uniform.value.baseTexture._glTextures[gl.id]);
  14086. // Extended texture data
  14087. if (uniform.textureData)
  14088. {
  14089. var data = uniform.textureData;
  14090. // GLTexture = mag linear, min linear_mipmap_linear, wrap repeat + gl.generateMipmap(gl.TEXTURE_2D);
  14091. // GLTextureLinear = mag/min linear, wrap clamp
  14092. // GLTextureNearestRepeat = mag/min NEAREST, wrap repeat
  14093. // GLTextureNearest = mag/min nearest, wrap clamp
  14094. // AudioTexture = whatever + luminance + width 512, height 2, border 0
  14095. // KeyTexture = whatever + luminance + width 256, height 2, border 0
  14096. // magFilter can be: gl.LINEAR, gl.LINEAR_MIPMAP_LINEAR or gl.NEAREST
  14097. // wrapS/T can be: gl.CLAMP_TO_EDGE or gl.REPEAT
  14098. var magFilter = (data.magFilter) ? data.magFilter : gl.LINEAR;
  14099. var minFilter = (data.minFilter) ? data.minFilter : gl.LINEAR;
  14100. var wrapS = (data.wrapS) ? data.wrapS : gl.CLAMP_TO_EDGE;
  14101. var wrapT = (data.wrapT) ? data.wrapT : gl.CLAMP_TO_EDGE;
  14102. var format = (data.luminance) ? gl.LUMINANCE : gl.RGBA;
  14103. if (data.repeat)
  14104. {
  14105. wrapS = gl.REPEAT;
  14106. wrapT = gl.REPEAT;
  14107. }
  14108. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, !!data.flipY);
  14109. if (data.width)
  14110. {
  14111. var width = (data.width) ? data.width : 512;
  14112. var height = (data.height) ? data.height : 2;
  14113. var border = (data.border) ? data.border : 0;
  14114. // void texImage2D(GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, ArrayBufferView? pixels);
  14115. gl.texImage2D(gl.TEXTURE_2D, 0, format, width, height, border, format, gl.UNSIGNED_BYTE, null);
  14116. }
  14117. else
  14118. {
  14119. // void texImage2D(GLenum target, GLint level, GLenum internalformat, GLenum format, GLenum type, ImageData? pixels);
  14120. gl.texImage2D(gl.TEXTURE_2D, 0, format, gl.RGBA, gl.UNSIGNED_BYTE, uniform.value.baseTexture.source);
  14121. }
  14122. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  14123. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  14124. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, wrapS);
  14125. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, wrapT);
  14126. }
  14127. gl.uniform1i(uniform.uniformLocation, this.textureCount);
  14128. uniform._init = true;
  14129. this.textureCount++;
  14130. };
  14131. /**
  14132. * Updates the shader uniform values.
  14133. *
  14134. * @method syncUniforms
  14135. */
  14136. PIXI.PixiShader.prototype.syncUniforms = function()
  14137. {
  14138. this.textureCount = 1;
  14139. var uniform;
  14140. var gl = this.gl;
  14141. // This would probably be faster in an array and it would guarantee key order
  14142. for (var key in this.uniforms)
  14143. {
  14144. uniform = this.uniforms[key];
  14145. if (uniform.glValueLength === 1)
  14146. {
  14147. if (uniform.glMatrix === true)
  14148. {
  14149. uniform.glFunc.call(gl, uniform.uniformLocation, uniform.transpose, uniform.value);
  14150. }
  14151. else
  14152. {
  14153. uniform.glFunc.call(gl, uniform.uniformLocation, uniform.value);
  14154. }
  14155. }
  14156. else if (uniform.glValueLength === 2)
  14157. {
  14158. uniform.glFunc.call(gl, uniform.uniformLocation, uniform.value.x, uniform.value.y);
  14159. }
  14160. else if (uniform.glValueLength === 3)
  14161. {
  14162. uniform.glFunc.call(gl, uniform.uniformLocation, uniform.value.x, uniform.value.y, uniform.value.z);
  14163. }
  14164. else if (uniform.glValueLength === 4)
  14165. {
  14166. uniform.glFunc.call(gl, uniform.uniformLocation, uniform.value.x, uniform.value.y, uniform.value.z, uniform.value.w);
  14167. }
  14168. else if (uniform.type === 'sampler2D')
  14169. {
  14170. if (uniform._init)
  14171. {
  14172. gl.activeTexture(gl['TEXTURE' + this.textureCount]);
  14173. if(uniform.value.baseTexture._dirty[gl.id])
  14174. {
  14175. PIXI.instances[gl.id].updateTexture(uniform.value.baseTexture);
  14176. }
  14177. else
  14178. {
  14179. // bind the current texture
  14180. gl.bindTexture(gl.TEXTURE_2D, uniform.value.baseTexture._glTextures[gl.id]);
  14181. }
  14182. // gl.bindTexture(gl.TEXTURE_2D, uniform.value.baseTexture._glTextures[gl.id] || PIXI.createWebGLTexture( uniform.value.baseTexture, gl));
  14183. gl.uniform1i(uniform.uniformLocation, this.textureCount);
  14184. this.textureCount++;
  14185. }
  14186. else
  14187. {
  14188. this.initSampler2D(uniform);
  14189. }
  14190. }
  14191. }
  14192. };
  14193. /**
  14194. * Destroys the shader.
  14195. *
  14196. * @method destroy
  14197. */
  14198. PIXI.PixiShader.prototype.destroy = function()
  14199. {
  14200. this.gl.deleteProgram( this.program );
  14201. this.uniforms = null;
  14202. this.gl = null;
  14203. this.attributes = null;
  14204. };
  14205. /**
  14206. * The Default Vertex shader source.
  14207. *
  14208. * @property defaultVertexSrc
  14209. * @type String
  14210. */
  14211. PIXI.PixiShader.defaultVertexSrc = [
  14212. 'attribute vec2 aVertexPosition;',
  14213. 'attribute vec2 aTextureCoord;',
  14214. 'attribute vec4 aColor;',
  14215. 'uniform vec2 projectionVector;',
  14216. 'uniform vec2 offsetVector;',
  14217. 'varying vec2 vTextureCoord;',
  14218. 'varying vec4 vColor;',
  14219. 'const vec2 center = vec2(-1.0, 1.0);',
  14220. 'void main(void) {',
  14221. ' gl_Position = vec4( ((aVertexPosition + offsetVector) / projectionVector) + center , 0.0, 1.0);',
  14222. ' vTextureCoord = aTextureCoord;',
  14223. ' vColor = vec4(aColor.rgb * aColor.a, aColor.a);',
  14224. '}'
  14225. ];
  14226. /**
  14227. * @author Mat Groves http://matgroves.com/ @Doormat23
  14228. */
  14229. /**
  14230. * @class PixiFastShader
  14231. * @constructor
  14232. * @param gl {WebGLContext} the current WebGL drawing context
  14233. */
  14234. PIXI.PixiFastShader = function(gl)
  14235. {
  14236. /**
  14237. * @property _UID
  14238. * @type Number
  14239. * @private
  14240. */
  14241. this._UID = PIXI._UID++;
  14242. /**
  14243. * @property gl
  14244. * @type WebGLContext
  14245. */
  14246. this.gl = gl;
  14247. /**
  14248. * The WebGL program.
  14249. * @property program
  14250. * @type Any
  14251. */
  14252. this.program = null;
  14253. /**
  14254. * The fragment shader.
  14255. * @property fragmentSrc
  14256. * @type Array
  14257. */
  14258. this.fragmentSrc = [
  14259. 'precision lowp float;',
  14260. 'varying vec2 vTextureCoord;',
  14261. 'varying float vColor;',
  14262. 'uniform sampler2D uSampler;',
  14263. 'void main(void) {',
  14264. ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;',
  14265. '}'
  14266. ];
  14267. /**
  14268. * The vertex shader.
  14269. * @property vertexSrc
  14270. * @type Array
  14271. */
  14272. this.vertexSrc = [
  14273. 'attribute vec2 aVertexPosition;',
  14274. 'attribute vec2 aPositionCoord;',
  14275. 'attribute vec2 aScale;',
  14276. 'attribute float aRotation;',
  14277. 'attribute vec2 aTextureCoord;',
  14278. 'attribute float aColor;',
  14279. 'uniform vec2 projectionVector;',
  14280. 'uniform vec2 offsetVector;',
  14281. 'uniform mat3 uMatrix;',
  14282. 'varying vec2 vTextureCoord;',
  14283. 'varying float vColor;',
  14284. 'const vec2 center = vec2(-1.0, 1.0);',
  14285. 'void main(void) {',
  14286. ' vec2 v;',
  14287. ' vec2 sv = aVertexPosition * aScale;',
  14288. ' v.x = (sv.x) * cos(aRotation) - (sv.y) * sin(aRotation);',
  14289. ' v.y = (sv.x) * sin(aRotation) + (sv.y) * cos(aRotation);',
  14290. ' v = ( uMatrix * vec3(v + aPositionCoord , 1.0) ).xy ;',
  14291. ' gl_Position = vec4( ( v / projectionVector) + center , 0.0, 1.0);',
  14292. ' vTextureCoord = aTextureCoord;',
  14293. // ' vec3 color = mod(vec3(aColor.y/65536.0, aColor.y/256.0, aColor.y), 256.0) / 256.0;',
  14294. ' vColor = aColor;',
  14295. '}'
  14296. ];
  14297. /**
  14298. * A local texture counter for multi-texture shaders.
  14299. * @property textureCount
  14300. * @type Number
  14301. */
  14302. this.textureCount = 0;
  14303. this.init();
  14304. };
  14305. PIXI.PixiFastShader.prototype.constructor = PIXI.PixiFastShader;
  14306. /**
  14307. * Initialises the shader.
  14308. *
  14309. * @method init
  14310. */
  14311. PIXI.PixiFastShader.prototype.init = function()
  14312. {
  14313. var gl = this.gl;
  14314. var program = PIXI.compileProgram(gl, this.vertexSrc, this.fragmentSrc);
  14315. gl.useProgram(program);
  14316. // get and store the uniforms for the shader
  14317. this.uSampler = gl.getUniformLocation(program, 'uSampler');
  14318. this.projectionVector = gl.getUniformLocation(program, 'projectionVector');
  14319. this.offsetVector = gl.getUniformLocation(program, 'offsetVector');
  14320. this.dimensions = gl.getUniformLocation(program, 'dimensions');
  14321. this.uMatrix = gl.getUniformLocation(program, 'uMatrix');
  14322. // get and store the attributes
  14323. this.aVertexPosition = gl.getAttribLocation(program, 'aVertexPosition');
  14324. this.aPositionCoord = gl.getAttribLocation(program, 'aPositionCoord');
  14325. this.aScale = gl.getAttribLocation(program, 'aScale');
  14326. this.aRotation = gl.getAttribLocation(program, 'aRotation');
  14327. this.aTextureCoord = gl.getAttribLocation(program, 'aTextureCoord');
  14328. this.colorAttribute = gl.getAttribLocation(program, 'aColor');
  14329. // Begin worst hack eva //
  14330. // WHY??? ONLY on my chrome pixel the line above returns -1 when using filters?
  14331. // maybe its somthing to do with the current state of the gl context.
  14332. // Im convinced this is a bug in the chrome browser as there is NO reason why this should be returning -1 especially as it only manifests on my chrome pixel
  14333. // If theres any webGL people that know why could happen please help :)
  14334. if(this.colorAttribute === -1)
  14335. {
  14336. this.colorAttribute = 2;
  14337. }
  14338. this.attributes = [this.aVertexPosition, this.aPositionCoord, this.aScale, this.aRotation, this.aTextureCoord, this.colorAttribute];
  14339. // End worst hack eva //
  14340. this.program = program;
  14341. };
  14342. /**
  14343. * Destroys the shader.
  14344. *
  14345. * @method destroy
  14346. */
  14347. PIXI.PixiFastShader.prototype.destroy = function()
  14348. {
  14349. this.gl.deleteProgram( this.program );
  14350. this.uniforms = null;
  14351. this.gl = null;
  14352. this.attributes = null;
  14353. };
  14354. /**
  14355. * @author Mat Groves http://matgroves.com/ @Doormat23
  14356. */
  14357. /**
  14358. * @class StripShader
  14359. * @constructor
  14360. * @param gl {WebGLContext} the current WebGL drawing context
  14361. */
  14362. PIXI.StripShader = function(gl)
  14363. {
  14364. /**
  14365. * @property _UID
  14366. * @type Number
  14367. * @private
  14368. */
  14369. this._UID = PIXI._UID++;
  14370. /**
  14371. * @property gl
  14372. * @type WebGLContext
  14373. */
  14374. this.gl = gl;
  14375. /**
  14376. * The WebGL program.
  14377. * @property program
  14378. * @type Any
  14379. */
  14380. this.program = null;
  14381. /**
  14382. * The fragment shader.
  14383. * @property fragmentSrc
  14384. * @type Array
  14385. */
  14386. this.fragmentSrc = [
  14387. 'precision mediump float;',
  14388. 'varying vec2 vTextureCoord;',
  14389. // 'varying float vColor;',
  14390. 'uniform float alpha;',
  14391. 'uniform sampler2D uSampler;',
  14392. 'void main(void) {',
  14393. ' gl_FragColor = texture2D(uSampler, vec2(vTextureCoord.x, vTextureCoord.y)) * alpha;',
  14394. // ' gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);',//gl_FragColor * alpha;',
  14395. '}'
  14396. ];
  14397. /**
  14398. * The vertex shader.
  14399. * @property vertexSrc
  14400. * @type Array
  14401. */
  14402. this.vertexSrc = [
  14403. 'attribute vec2 aVertexPosition;',
  14404. 'attribute vec2 aTextureCoord;',
  14405. 'uniform mat3 translationMatrix;',
  14406. 'uniform vec2 projectionVector;',
  14407. 'uniform vec2 offsetVector;',
  14408. // 'uniform float alpha;',
  14409. // 'uniform vec3 tint;',
  14410. 'varying vec2 vTextureCoord;',
  14411. // 'varying vec4 vColor;',
  14412. 'void main(void) {',
  14413. ' vec3 v = translationMatrix * vec3(aVertexPosition , 1.0);',
  14414. ' v -= offsetVector.xyx;',
  14415. ' gl_Position = vec4( v.x / projectionVector.x -1.0, v.y / -projectionVector.y + 1.0 , 0.0, 1.0);',
  14416. ' vTextureCoord = aTextureCoord;',
  14417. // ' vColor = aColor * vec4(tint * alpha, alpha);',
  14418. '}'
  14419. ];
  14420. this.init();
  14421. };
  14422. PIXI.StripShader.prototype.constructor = PIXI.StripShader;
  14423. /**
  14424. * Initialises the shader.
  14425. *
  14426. * @method init
  14427. */
  14428. PIXI.StripShader.prototype.init = function()
  14429. {
  14430. var gl = this.gl;
  14431. var program = PIXI.compileProgram(gl, this.vertexSrc, this.fragmentSrc);
  14432. gl.useProgram(program);
  14433. // get and store the uniforms for the shader
  14434. this.uSampler = gl.getUniformLocation(program, 'uSampler');
  14435. this.projectionVector = gl.getUniformLocation(program, 'projectionVector');
  14436. this.offsetVector = gl.getUniformLocation(program, 'offsetVector');
  14437. this.colorAttribute = gl.getAttribLocation(program, 'aColor');
  14438. //this.dimensions = gl.getUniformLocation(this.program, 'dimensions');
  14439. // get and store the attributes
  14440. this.aVertexPosition = gl.getAttribLocation(program, 'aVertexPosition');
  14441. this.aTextureCoord = gl.getAttribLocation(program, 'aTextureCoord');
  14442. this.attributes = [this.aVertexPosition, this.aTextureCoord];
  14443. this.translationMatrix = gl.getUniformLocation(program, 'translationMatrix');
  14444. this.alpha = gl.getUniformLocation(program, 'alpha');
  14445. this.program = program;
  14446. };
  14447. /**
  14448. * Destroys the shader.
  14449. *
  14450. * @method destroy
  14451. */
  14452. PIXI.StripShader.prototype.destroy = function()
  14453. {
  14454. this.gl.deleteProgram( this.program );
  14455. this.uniforms = null;
  14456. this.gl = null;
  14457. this.attribute = null;
  14458. };
  14459. /**
  14460. * @author Mat Groves http://matgroves.com/ @Doormat23
  14461. */
  14462. /**
  14463. * @class PrimitiveShader
  14464. * @constructor
  14465. * @param gl {WebGLContext} the current WebGL drawing context
  14466. */
  14467. PIXI.PrimitiveShader = function(gl)
  14468. {
  14469. /**
  14470. * @property _UID
  14471. * @type Number
  14472. * @private
  14473. */
  14474. this._UID = PIXI._UID++;
  14475. /**
  14476. * @property gl
  14477. * @type WebGLContext
  14478. */
  14479. this.gl = gl;
  14480. /**
  14481. * The WebGL program.
  14482. * @property program
  14483. * @type Any
  14484. */
  14485. this.program = null;
  14486. /**
  14487. * The fragment shader.
  14488. * @property fragmentSrc
  14489. * @type Array
  14490. */
  14491. this.fragmentSrc = [
  14492. 'precision mediump float;',
  14493. 'varying vec4 vColor;',
  14494. 'void main(void) {',
  14495. ' gl_FragColor = vColor;',
  14496. '}'
  14497. ];
  14498. /**
  14499. * The vertex shader.
  14500. * @property vertexSrc
  14501. * @type Array
  14502. */
  14503. this.vertexSrc = [
  14504. 'attribute vec2 aVertexPosition;',
  14505. 'attribute vec4 aColor;',
  14506. 'uniform mat3 translationMatrix;',
  14507. 'uniform vec2 projectionVector;',
  14508. 'uniform vec2 offsetVector;',
  14509. 'uniform float alpha;',
  14510. 'uniform float flipY;',
  14511. 'uniform vec3 tint;',
  14512. 'varying vec4 vColor;',
  14513. 'void main(void) {',
  14514. ' vec3 v = translationMatrix * vec3(aVertexPosition , 1.0);',
  14515. ' v -= offsetVector.xyx;',
  14516. ' gl_Position = vec4( v.x / projectionVector.x -1.0, (v.y / projectionVector.y * -flipY) + flipY , 0.0, 1.0);',
  14517. ' vColor = aColor * vec4(tint * alpha, alpha);',
  14518. '}'
  14519. ];
  14520. this.init();
  14521. };
  14522. PIXI.PrimitiveShader.prototype.constructor = PIXI.PrimitiveShader;
  14523. /**
  14524. * Initialises the shader.
  14525. *
  14526. * @method init
  14527. */
  14528. PIXI.PrimitiveShader.prototype.init = function()
  14529. {
  14530. var gl = this.gl;
  14531. var program = PIXI.compileProgram(gl, this.vertexSrc, this.fragmentSrc);
  14532. gl.useProgram(program);
  14533. // get and store the uniforms for the shader
  14534. this.projectionVector = gl.getUniformLocation(program, 'projectionVector');
  14535. this.offsetVector = gl.getUniformLocation(program, 'offsetVector');
  14536. this.tintColor = gl.getUniformLocation(program, 'tint');
  14537. this.flipY = gl.getUniformLocation(program, 'flipY');
  14538. // get and store the attributes
  14539. this.aVertexPosition = gl.getAttribLocation(program, 'aVertexPosition');
  14540. this.colorAttribute = gl.getAttribLocation(program, 'aColor');
  14541. this.attributes = [this.aVertexPosition, this.colorAttribute];
  14542. this.translationMatrix = gl.getUniformLocation(program, 'translationMatrix');
  14543. this.alpha = gl.getUniformLocation(program, 'alpha');
  14544. this.program = program;
  14545. };
  14546. /**
  14547. * Destroys the shader.
  14548. *
  14549. * @method destroy
  14550. */
  14551. PIXI.PrimitiveShader.prototype.destroy = function()
  14552. {
  14553. this.gl.deleteProgram( this.program );
  14554. this.uniforms = null;
  14555. this.gl = null;
  14556. this.attributes = null;
  14557. };
  14558. /**
  14559. * @author Mat Groves http://matgroves.com/ @Doormat23
  14560. */
  14561. /**
  14562. * @class ComplexPrimitiveShader
  14563. * @constructor
  14564. * @param gl {WebGLContext} the current WebGL drawing context
  14565. */
  14566. PIXI.ComplexPrimitiveShader = function(gl)
  14567. {
  14568. /**
  14569. * @property _UID
  14570. * @type Number
  14571. * @private
  14572. */
  14573. this._UID = PIXI._UID++;
  14574. /**
  14575. * @property gl
  14576. * @type WebGLContext
  14577. */
  14578. this.gl = gl;
  14579. /**
  14580. * The WebGL program.
  14581. * @property program
  14582. * @type Any
  14583. */
  14584. this.program = null;
  14585. /**
  14586. * The fragment shader.
  14587. * @property fragmentSrc
  14588. * @type Array
  14589. */
  14590. this.fragmentSrc = [
  14591. 'precision mediump float;',
  14592. 'varying vec4 vColor;',
  14593. 'void main(void) {',
  14594. ' gl_FragColor = vColor;',
  14595. '}'
  14596. ];
  14597. /**
  14598. * The vertex shader.
  14599. * @property vertexSrc
  14600. * @type Array
  14601. */
  14602. this.vertexSrc = [
  14603. 'attribute vec2 aVertexPosition;',
  14604. //'attribute vec4 aColor;',
  14605. 'uniform mat3 translationMatrix;',
  14606. 'uniform vec2 projectionVector;',
  14607. 'uniform vec2 offsetVector;',
  14608. 'uniform vec3 tint;',
  14609. 'uniform float alpha;',
  14610. 'uniform vec3 color;',
  14611. 'uniform float flipY;',
  14612. 'varying vec4 vColor;',
  14613. 'void main(void) {',
  14614. ' vec3 v = translationMatrix * vec3(aVertexPosition , 1.0);',
  14615. ' v -= offsetVector.xyx;',
  14616. ' gl_Position = vec4( v.x / projectionVector.x -1.0, (v.y / projectionVector.y * -flipY) + flipY , 0.0, 1.0);',
  14617. ' vColor = vec4(color * alpha * tint, alpha);',//" * vec4(tint * alpha, alpha);',
  14618. '}'
  14619. ];
  14620. this.init();
  14621. };
  14622. PIXI.ComplexPrimitiveShader.prototype.constructor = PIXI.ComplexPrimitiveShader;
  14623. /**
  14624. * Initialises the shader.
  14625. *
  14626. * @method init
  14627. */
  14628. PIXI.ComplexPrimitiveShader.prototype.init = function()
  14629. {
  14630. var gl = this.gl;
  14631. var program = PIXI.compileProgram(gl, this.vertexSrc, this.fragmentSrc);
  14632. gl.useProgram(program);
  14633. // get and store the uniforms for the shader
  14634. this.projectionVector = gl.getUniformLocation(program, 'projectionVector');
  14635. this.offsetVector = gl.getUniformLocation(program, 'offsetVector');
  14636. this.tintColor = gl.getUniformLocation(program, 'tint');
  14637. this.color = gl.getUniformLocation(program, 'color');
  14638. this.flipY = gl.getUniformLocation(program, 'flipY');
  14639. // get and store the attributes
  14640. this.aVertexPosition = gl.getAttribLocation(program, 'aVertexPosition');
  14641. // this.colorAttribute = gl.getAttribLocation(program, 'aColor');
  14642. this.attributes = [this.aVertexPosition, this.colorAttribute];
  14643. this.translationMatrix = gl.getUniformLocation(program, 'translationMatrix');
  14644. this.alpha = gl.getUniformLocation(program, 'alpha');
  14645. this.program = program;
  14646. };
  14647. /**
  14648. * Destroys the shader.
  14649. *
  14650. * @method destroy
  14651. */
  14652. PIXI.ComplexPrimitiveShader.prototype.destroy = function()
  14653. {
  14654. this.gl.deleteProgram( this.program );
  14655. this.uniforms = null;
  14656. this.gl = null;
  14657. this.attribute = null;
  14658. };
  14659. /**
  14660. * @author Mat Groves http://matgroves.com/ @Doormat23
  14661. */
  14662. PIXI.glContexts = []; // this is where we store the webGL contexts for easy access.
  14663. PIXI.instances = [];
  14664. /**
  14665. * The WebGLRenderer draws the stage and all its content onto a webGL enabled canvas. This renderer
  14666. * should be used for browsers that support webGL. This Render works by automatically managing webGLBatchs.
  14667. * So no need for Sprite Batches or Sprite Clouds.
  14668. * Don't forget to add the view to your DOM or you will not see anything :)
  14669. *
  14670. * @class WebGLRenderer
  14671. * @constructor
  14672. * @param game {Phaser.Game} A reference to the Phaser Game instance
  14673. */
  14674. PIXI.WebGLRenderer = function(game) {
  14675. /**
  14676. * @property {Phaser.Game} game - A reference to the Phaser Game instance.
  14677. */
  14678. this.game = game;
  14679. if (!PIXI.defaultRenderer)
  14680. {
  14681. PIXI.defaultRenderer = this;
  14682. }
  14683. /**
  14684. * @property type
  14685. * @type Number
  14686. */
  14687. this.type = PIXI.WEBGL_RENDERER;
  14688. /**
  14689. * The resolution of the renderer
  14690. *
  14691. * @property resolution
  14692. * @type Number
  14693. * @default 1
  14694. */
  14695. this.resolution = game.resolution;
  14696. /**
  14697. * Whether the render view is transparent
  14698. *
  14699. * @property transparent
  14700. * @type Boolean
  14701. */
  14702. this.transparent = game.transparent;
  14703. /**
  14704. * Whether the render view should be resized automatically
  14705. *
  14706. * @property autoResize
  14707. * @type Boolean
  14708. */
  14709. this.autoResize = false;
  14710. /**
  14711. * The value of the preserveDrawingBuffer flag affects whether or not the contents of the stencil buffer is retained after rendering.
  14712. *
  14713. * @property preserveDrawingBuffer
  14714. * @type Boolean
  14715. */
  14716. this.preserveDrawingBuffer = game.preserveDrawingBuffer;
  14717. /**
  14718. * This sets if the WebGLRenderer will clear the context texture or not before the new render pass. If true:
  14719. * If the Stage is NOT transparent, Pixi will clear to alpha (0, 0, 0, 0).
  14720. * If the Stage is transparent, Pixi will clear to the target Stage's background color.
  14721. * Disable this by setting this to false. For example: if your game has a canvas filling background image, you often don't need this set.
  14722. *
  14723. * @property clearBeforeRender
  14724. * @type Boolean
  14725. * @default
  14726. */
  14727. this.clearBeforeRender = game.clearBeforeRender;
  14728. /**
  14729. * The width of the canvas view
  14730. *
  14731. * @property width
  14732. * @type Number
  14733. */
  14734. this.width = game.width;
  14735. /**
  14736. * The height of the canvas view
  14737. *
  14738. * @property height
  14739. * @type Number
  14740. */
  14741. this.height = game.height;
  14742. /**
  14743. * The canvas element that everything is drawn to
  14744. *
  14745. * @property view
  14746. * @type HTMLCanvasElement
  14747. */
  14748. this.view = game.canvas;
  14749. /**
  14750. * @property _contextOptions
  14751. * @type Object
  14752. * @private
  14753. */
  14754. this._contextOptions = {
  14755. alpha: this.transparent,
  14756. antialias: game.antialias,
  14757. premultipliedAlpha: this.transparent && this.transparent !== 'notMultiplied',
  14758. stencil: true,
  14759. preserveDrawingBuffer: this.preserveDrawingBuffer
  14760. };
  14761. /**
  14762. * @property projection
  14763. * @type Point
  14764. */
  14765. this.projection = new PIXI.Point();
  14766. /**
  14767. * @property offset
  14768. * @type Point
  14769. */
  14770. this.offset = new PIXI.Point();
  14771. // time to create the render managers! each one focuses on managing a state in webGL
  14772. /**
  14773. * Deals with managing the shader programs and their attribs
  14774. * @property shaderManager
  14775. * @type WebGLShaderManager
  14776. */
  14777. this.shaderManager = new PIXI.WebGLShaderManager();
  14778. /**
  14779. * Manages the rendering of sprites
  14780. * @property spriteBatch
  14781. * @type WebGLSpriteBatch
  14782. */
  14783. this.spriteBatch = new PIXI.WebGLSpriteBatch();
  14784. /**
  14785. * Manages the masks using the stencil buffer
  14786. * @property maskManager
  14787. * @type WebGLMaskManager
  14788. */
  14789. this.maskManager = new PIXI.WebGLMaskManager();
  14790. /**
  14791. * Manages the filters
  14792. * @property filterManager
  14793. * @type WebGLFilterManager
  14794. */
  14795. this.filterManager = new PIXI.WebGLFilterManager();
  14796. /**
  14797. * Manages the stencil buffer
  14798. * @property stencilManager
  14799. * @type WebGLStencilManager
  14800. */
  14801. this.stencilManager = new PIXI.WebGLStencilManager();
  14802. /**
  14803. * Manages the blendModes
  14804. * @property blendModeManager
  14805. * @type WebGLBlendModeManager
  14806. */
  14807. this.blendModeManager = new PIXI.WebGLBlendModeManager();
  14808. /**
  14809. * @property renderSession
  14810. * @type Object
  14811. */
  14812. this.renderSession = {};
  14813. // Needed?
  14814. this.renderSession.game = this.game;
  14815. this.renderSession.gl = this.gl;
  14816. this.renderSession.drawCount = 0;
  14817. this.renderSession.shaderManager = this.shaderManager;
  14818. this.renderSession.maskManager = this.maskManager;
  14819. this.renderSession.filterManager = this.filterManager;
  14820. this.renderSession.blendModeManager = this.blendModeManager;
  14821. this.renderSession.spriteBatch = this.spriteBatch;
  14822. this.renderSession.stencilManager = this.stencilManager;
  14823. this.renderSession.renderer = this;
  14824. this.renderSession.resolution = this.resolution;
  14825. // time init the context..
  14826. this.initContext();
  14827. // map some webGL blend modes..
  14828. this.mapBlendModes();
  14829. };
  14830. // constructor
  14831. PIXI.WebGLRenderer.prototype.constructor = PIXI.WebGLRenderer;
  14832. /**
  14833. * @method initContext
  14834. */
  14835. PIXI.WebGLRenderer.prototype.initContext = function()
  14836. {
  14837. var gl = this.view.getContext('webgl', this._contextOptions) || this.view.getContext('experimental-webgl', this._contextOptions);
  14838. this.gl = gl;
  14839. if (!gl) {
  14840. // fail, not able to get a context
  14841. throw new Error('This browser does not support webGL. Try using the canvas renderer');
  14842. }
  14843. this.glContextId = gl.id = PIXI.WebGLRenderer.glContextId++;
  14844. PIXI.glContexts[this.glContextId] = gl;
  14845. PIXI.instances[this.glContextId] = this;
  14846. // set up the default pixi settings..
  14847. gl.disable(gl.DEPTH_TEST);
  14848. gl.disable(gl.CULL_FACE);
  14849. gl.enable(gl.BLEND);
  14850. // need to set the context for all the managers...
  14851. this.shaderManager.setContext(gl);
  14852. this.spriteBatch.setContext(gl);
  14853. this.maskManager.setContext(gl);
  14854. this.filterManager.setContext(gl);
  14855. this.blendModeManager.setContext(gl);
  14856. this.stencilManager.setContext(gl);
  14857. this.renderSession.gl = this.gl;
  14858. // now resize and we are good to go!
  14859. this.resize(this.width, this.height);
  14860. };
  14861. /**
  14862. * Renders the stage to its webGL view
  14863. *
  14864. * @method render
  14865. * @param stage {Stage} the Stage element to be rendered
  14866. */
  14867. PIXI.WebGLRenderer.prototype.render = function(stage)
  14868. {
  14869. // no point rendering if our context has been blown up!
  14870. if (this.contextLost)
  14871. {
  14872. return;
  14873. }
  14874. var gl = this.gl;
  14875. // -- Does this need to be set every frame? -- //
  14876. gl.viewport(0, 0, this.width, this.height);
  14877. // make sure we are bound to the main frame buffer
  14878. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  14879. if (this.game.clearBeforeRender)
  14880. {
  14881. gl.clearColor(stage._bgColor.r, stage._bgColor.g, stage._bgColor.b, stage._bgColor.a);
  14882. gl.clear(gl.COLOR_BUFFER_BIT);
  14883. }
  14884. this.offset.x = this.game.camera._shake.x;
  14885. this.offset.y = this.game.camera._shake.y;
  14886. this.renderDisplayObject(stage, this.projection);
  14887. };
  14888. /**
  14889. * Renders a Display Object.
  14890. *
  14891. * @method renderDisplayObject
  14892. * @param displayObject {DisplayObject} The DisplayObject to render
  14893. * @param projection {Point} The projection
  14894. * @param buffer {Array} a standard WebGL buffer
  14895. */
  14896. PIXI.WebGLRenderer.prototype.renderDisplayObject = function(displayObject, projection, buffer, matrix)
  14897. {
  14898. this.renderSession.blendModeManager.setBlendMode(PIXI.blendModes.NORMAL);
  14899. // reset the render session data..
  14900. this.renderSession.drawCount = 0;
  14901. // make sure to flip the Y if using a render texture..
  14902. this.renderSession.flipY = buffer ? -1 : 1;
  14903. // set the default projection
  14904. this.renderSession.projection = projection;
  14905. //set the default offset
  14906. this.renderSession.offset = this.offset;
  14907. // start the sprite batch
  14908. this.spriteBatch.begin(this.renderSession);
  14909. // start the filter manager
  14910. this.filterManager.begin(this.renderSession, buffer);
  14911. // render the scene!
  14912. displayObject._renderWebGL(this.renderSession, matrix);
  14913. // finish the sprite batch
  14914. this.spriteBatch.end();
  14915. };
  14916. /**
  14917. * Resizes the webGL view to the specified width and height.
  14918. *
  14919. * @method resize
  14920. * @param width {Number} the new width of the webGL view
  14921. * @param height {Number} the new height of the webGL view
  14922. */
  14923. PIXI.WebGLRenderer.prototype.resize = function(width, height)
  14924. {
  14925. this.width = width * this.resolution;
  14926. this.height = height * this.resolution;
  14927. this.view.width = this.width;
  14928. this.view.height = this.height;
  14929. if (this.autoResize) {
  14930. this.view.style.width = this.width / this.resolution + 'px';
  14931. this.view.style.height = this.height / this.resolution + 'px';
  14932. }
  14933. this.gl.viewport(0, 0, this.width, this.height);
  14934. this.projection.x = this.width / 2 / this.resolution;
  14935. this.projection.y = -this.height / 2 / this.resolution;
  14936. };
  14937. /**
  14938. * Updates and Creates a WebGL texture for the renderers context.
  14939. *
  14940. * @method updateTexture
  14941. * @param texture {Texture} the texture to update
  14942. * @return {boolean} True if the texture was successfully bound, otherwise false.
  14943. */
  14944. PIXI.WebGLRenderer.prototype.updateTexture = function(texture)
  14945. {
  14946. if (!texture.hasLoaded)
  14947. {
  14948. return false;
  14949. }
  14950. var gl = this.gl;
  14951. if (!texture._glTextures[gl.id])
  14952. {
  14953. texture._glTextures[gl.id] = gl.createTexture();
  14954. }
  14955. gl.bindTexture(gl.TEXTURE_2D, texture._glTextures[gl.id]);
  14956. gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, texture.premultipliedAlpha);
  14957. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, texture.source);
  14958. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, texture.scaleMode === PIXI.scaleModes.LINEAR ? gl.LINEAR : gl.NEAREST);
  14959. if (texture.mipmap && PIXI.isPowerOfTwo(texture.width, texture.height))
  14960. {
  14961. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, texture.scaleMode === PIXI.scaleModes.LINEAR ? gl.LINEAR_MIPMAP_LINEAR : gl.NEAREST_MIPMAP_NEAREST);
  14962. gl.generateMipmap(gl.TEXTURE_2D);
  14963. }
  14964. else
  14965. {
  14966. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, texture.scaleMode === PIXI.scaleModes.LINEAR ? gl.LINEAR : gl.NEAREST);
  14967. }
  14968. if (!texture._powerOf2)
  14969. {
  14970. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14971. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14972. }
  14973. else
  14974. {
  14975. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT);
  14976. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT);
  14977. }
  14978. texture._dirty[gl.id] = false;
  14979. // return texture._glTextures[gl.id];
  14980. return true;
  14981. };
  14982. /**
  14983. * Removes everything from the renderer (event listeners, spritebatch, etc...)
  14984. *
  14985. * @method destroy
  14986. */
  14987. PIXI.WebGLRenderer.prototype.destroy = function()
  14988. {
  14989. PIXI.glContexts[this.glContextId] = null;
  14990. this.projection = null;
  14991. this.offset = null;
  14992. this.shaderManager.destroy();
  14993. this.spriteBatch.destroy();
  14994. this.maskManager.destroy();
  14995. this.filterManager.destroy();
  14996. this.shaderManager = null;
  14997. this.spriteBatch = null;
  14998. this.maskManager = null;
  14999. this.filterManager = null;
  15000. this.gl = null;
  15001. this.renderSession = null;
  15002. PIXI.CanvasPool.remove(this);
  15003. PIXI.instances[this.glContextId] = null;
  15004. PIXI.WebGLRenderer.glContextId--;
  15005. };
  15006. /**
  15007. * Maps Pixi blend modes to WebGL blend modes.
  15008. *
  15009. * @method mapBlendModes
  15010. */
  15011. PIXI.WebGLRenderer.prototype.mapBlendModes = function()
  15012. {
  15013. var gl = this.gl;
  15014. if (!PIXI.blendModesWebGL)
  15015. {
  15016. var b = [];
  15017. var modes = PIXI.blendModes;
  15018. b[modes.NORMAL] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
  15019. b[modes.ADD] = [gl.SRC_ALPHA, gl.DST_ALPHA];
  15020. b[modes.MULTIPLY] = [gl.DST_COLOR, gl.ONE_MINUS_SRC_ALPHA];
  15021. b[modes.SCREEN] = [gl.SRC_ALPHA, gl.ONE];
  15022. b[modes.OVERLAY] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
  15023. b[modes.DARKEN] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
  15024. b[modes.LIGHTEN] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
  15025. b[modes.COLOR_DODGE] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
  15026. b[modes.COLOR_BURN] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
  15027. b[modes.HARD_LIGHT] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
  15028. b[modes.SOFT_LIGHT] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
  15029. b[modes.DIFFERENCE] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
  15030. b[modes.EXCLUSION] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
  15031. b[modes.HUE] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
  15032. b[modes.SATURATION] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
  15033. b[modes.COLOR] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
  15034. b[modes.LUMINOSITY] = [gl.ONE, gl.ONE_MINUS_SRC_ALPHA];
  15035. PIXI.blendModesWebGL = b;
  15036. }
  15037. };
  15038. PIXI.WebGLRenderer.glContextId = 0;
  15039. /**
  15040. * @author Mat Groves http://matgroves.com/ @Doormat23
  15041. */
  15042. /**
  15043. * @class WebGLBlendModeManager
  15044. * @constructor
  15045. * @param gl {WebGLContext} the current WebGL drawing context
  15046. */
  15047. PIXI.WebGLBlendModeManager = function()
  15048. {
  15049. /**
  15050. * @property currentBlendMode
  15051. * @type Number
  15052. */
  15053. this.currentBlendMode = 99999;
  15054. };
  15055. PIXI.WebGLBlendModeManager.prototype.constructor = PIXI.WebGLBlendModeManager;
  15056. /**
  15057. * Sets the WebGL Context.
  15058. *
  15059. * @method setContext
  15060. * @param gl {WebGLContext} the current WebGL drawing context
  15061. */
  15062. PIXI.WebGLBlendModeManager.prototype.setContext = function(gl)
  15063. {
  15064. this.gl = gl;
  15065. };
  15066. /**
  15067. * Sets-up the given blendMode from WebGL's point of view.
  15068. *
  15069. * @method setBlendMode
  15070. * @param blendMode {Number} the blendMode, should be a Pixi const, such as PIXI.BlendModes.ADD
  15071. */
  15072. PIXI.WebGLBlendModeManager.prototype.setBlendMode = function(blendMode)
  15073. {
  15074. if(this.currentBlendMode === blendMode)return false;
  15075. this.currentBlendMode = blendMode;
  15076. var blendModeWebGL = PIXI.blendModesWebGL[this.currentBlendMode];
  15077. if (blendModeWebGL)
  15078. {
  15079. this.gl.blendFunc(blendModeWebGL[0], blendModeWebGL[1]);
  15080. }
  15081. return true;
  15082. };
  15083. /**
  15084. * Destroys this object.
  15085. *
  15086. * @method destroy
  15087. */
  15088. PIXI.WebGLBlendModeManager.prototype.destroy = function()
  15089. {
  15090. this.gl = null;
  15091. };
  15092. /**
  15093. * @author Mat Groves http://matgroves.com/ @Doormat23
  15094. */
  15095. /**
  15096. * @class WebGLMaskManager
  15097. * @constructor
  15098. * @private
  15099. */
  15100. PIXI.WebGLMaskManager = function()
  15101. {
  15102. };
  15103. PIXI.WebGLMaskManager.prototype.constructor = PIXI.WebGLMaskManager;
  15104. /**
  15105. * Sets the drawing context to the one given in parameter.
  15106. *
  15107. * @method setContext
  15108. * @param gl {WebGLContext} the current WebGL drawing context
  15109. */
  15110. PIXI.WebGLMaskManager.prototype.setContext = function(gl)
  15111. {
  15112. this.gl = gl;
  15113. };
  15114. /**
  15115. * Applies the Mask and adds it to the current filter stack.
  15116. *
  15117. * @method pushMask
  15118. * @param maskData {Array}
  15119. * @param renderSession {Object}
  15120. */
  15121. PIXI.WebGLMaskManager.prototype.pushMask = function(maskData, renderSession)
  15122. {
  15123. var gl = renderSession.gl;
  15124. if (maskData.dirty)
  15125. {
  15126. PIXI.WebGLGraphics.updateGraphics(maskData, gl);
  15127. }
  15128. if (maskData._webGL[gl.id] === undefined || maskData._webGL[gl.id].data === undefined || maskData._webGL[gl.id].data.length === 0)
  15129. {
  15130. return;
  15131. }
  15132. renderSession.stencilManager.pushStencil(maskData, maskData._webGL[gl.id].data[0], renderSession);
  15133. };
  15134. /**
  15135. * Removes the last filter from the filter stack and doesn't return it.
  15136. *
  15137. * @method popMask
  15138. * @param maskData {Array}
  15139. * @param renderSession {Object} an object containing all the useful parameters
  15140. */
  15141. PIXI.WebGLMaskManager.prototype.popMask = function(maskData, renderSession)
  15142. {
  15143. var gl = this.gl;
  15144. if (maskData._webGL[gl.id] === undefined || maskData._webGL[gl.id].data === undefined || maskData._webGL[gl.id].data.length === 0)
  15145. {
  15146. return;
  15147. }
  15148. renderSession.stencilManager.popStencil(maskData, maskData._webGL[gl.id].data[0], renderSession);
  15149. };
  15150. /**
  15151. * Destroys the mask stack.
  15152. *
  15153. * @method destroy
  15154. */
  15155. PIXI.WebGLMaskManager.prototype.destroy = function()
  15156. {
  15157. this.gl = null;
  15158. };
  15159. /**
  15160. * @author Mat Groves http://matgroves.com/ @Doormat23
  15161. */
  15162. /**
  15163. * @class WebGLStencilManager
  15164. * @constructor
  15165. * @private
  15166. */
  15167. PIXI.WebGLStencilManager = function()
  15168. {
  15169. this.stencilStack = [];
  15170. this.reverse = true;
  15171. this.count = 0;
  15172. };
  15173. /**
  15174. * Sets the drawing context to the one given in parameter.
  15175. *
  15176. * @method setContext
  15177. * @param gl {WebGLContext} the current WebGL drawing context
  15178. */
  15179. PIXI.WebGLStencilManager.prototype.setContext = function(gl)
  15180. {
  15181. this.gl = gl;
  15182. };
  15183. /**
  15184. * Applies the Mask and adds it to the current filter stack.
  15185. *
  15186. * @method pushMask
  15187. * @param graphics {Graphics}
  15188. * @param webGLData {Array}
  15189. * @param renderSession {Object}
  15190. */
  15191. PIXI.WebGLStencilManager.prototype.pushStencil = function(graphics, webGLData, renderSession)
  15192. {
  15193. var gl = this.gl;
  15194. this.bindGraphics(graphics, webGLData, renderSession);
  15195. if(this.stencilStack.length === 0)
  15196. {
  15197. gl.enable(gl.STENCIL_TEST);
  15198. gl.clear(gl.STENCIL_BUFFER_BIT);
  15199. this.reverse = true;
  15200. this.count = 0;
  15201. }
  15202. this.stencilStack.push(webGLData);
  15203. var level = this.count;
  15204. gl.colorMask(false, false, false, false);
  15205. gl.stencilFunc(gl.ALWAYS,0,0xFF);
  15206. gl.stencilOp(gl.KEEP,gl.KEEP,gl.INVERT);
  15207. // draw the triangle strip!
  15208. if(webGLData.mode === 1)
  15209. {
  15210. gl.drawElements(gl.TRIANGLE_FAN, webGLData.indices.length - 4, gl.UNSIGNED_SHORT, 0 );
  15211. if(this.reverse)
  15212. {
  15213. gl.stencilFunc(gl.EQUAL, 0xFF - level, 0xFF);
  15214. gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR);
  15215. }
  15216. else
  15217. {
  15218. gl.stencilFunc(gl.EQUAL,level, 0xFF);
  15219. gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR);
  15220. }
  15221. // draw a quad to increment..
  15222. gl.drawElements(gl.TRIANGLE_FAN, 4, gl.UNSIGNED_SHORT, ( webGLData.indices.length - 4 ) * 2 );
  15223. if(this.reverse)
  15224. {
  15225. gl.stencilFunc(gl.EQUAL,0xFF-(level+1), 0xFF);
  15226. }
  15227. else
  15228. {
  15229. gl.stencilFunc(gl.EQUAL,level+1, 0xFF);
  15230. }
  15231. this.reverse = !this.reverse;
  15232. }
  15233. else
  15234. {
  15235. if(!this.reverse)
  15236. {
  15237. gl.stencilFunc(gl.EQUAL, 0xFF - level, 0xFF);
  15238. gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR);
  15239. }
  15240. else
  15241. {
  15242. gl.stencilFunc(gl.EQUAL,level, 0xFF);
  15243. gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR);
  15244. }
  15245. gl.drawElements(gl.TRIANGLE_STRIP, webGLData.indices.length, gl.UNSIGNED_SHORT, 0 );
  15246. if(!this.reverse)
  15247. {
  15248. gl.stencilFunc(gl.EQUAL,0xFF-(level+1), 0xFF);
  15249. }
  15250. else
  15251. {
  15252. gl.stencilFunc(gl.EQUAL,level+1, 0xFF);
  15253. }
  15254. }
  15255. gl.colorMask(true, true, true, true);
  15256. gl.stencilOp(gl.KEEP,gl.KEEP,gl.KEEP);
  15257. this.count++;
  15258. };
  15259. /**
  15260. * TODO this does not belong here!
  15261. *
  15262. * @method bindGraphics
  15263. * @param graphics {Graphics}
  15264. * @param webGLData {Array}
  15265. * @param renderSession {Object}
  15266. */
  15267. PIXI.WebGLStencilManager.prototype.bindGraphics = function(graphics, webGLData, renderSession)
  15268. {
  15269. //if(this._currentGraphics === graphics)return;
  15270. this._currentGraphics = graphics;
  15271. var gl = this.gl;
  15272. // bind the graphics object..
  15273. var projection = renderSession.projection,
  15274. offset = renderSession.offset,
  15275. shader;// = renderSession.shaderManager.primitiveShader;
  15276. if(webGLData.mode === 1)
  15277. {
  15278. shader = renderSession.shaderManager.complexPrimitiveShader;
  15279. renderSession.shaderManager.setShader( shader );
  15280. gl.uniform1f(shader.flipY, renderSession.flipY);
  15281. gl.uniformMatrix3fv(shader.translationMatrix, false, graphics.worldTransform.toArray(true));
  15282. gl.uniform2f(shader.projectionVector, projection.x, -projection.y);
  15283. gl.uniform2f(shader.offsetVector, -offset.x, -offset.y);
  15284. gl.uniform3fv(shader.tintColor, PIXI.hex2rgb(graphics.tint));
  15285. gl.uniform3fv(shader.color, webGLData.color);
  15286. gl.uniform1f(shader.alpha, graphics.worldAlpha * webGLData.alpha);
  15287. gl.bindBuffer(gl.ARRAY_BUFFER, webGLData.buffer);
  15288. gl.vertexAttribPointer(shader.aVertexPosition, 2, gl.FLOAT, false, 4 * 2, 0);
  15289. // now do the rest..
  15290. // set the index buffer!
  15291. gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, webGLData.indexBuffer);
  15292. }
  15293. else
  15294. {
  15295. //renderSession.shaderManager.activatePrimitiveShader();
  15296. shader = renderSession.shaderManager.primitiveShader;
  15297. renderSession.shaderManager.setShader( shader );
  15298. gl.uniformMatrix3fv(shader.translationMatrix, false, graphics.worldTransform.toArray(true));
  15299. gl.uniform1f(shader.flipY, renderSession.flipY);
  15300. gl.uniform2f(shader.projectionVector, projection.x, -projection.y);
  15301. gl.uniform2f(shader.offsetVector, -offset.x, -offset.y);
  15302. gl.uniform3fv(shader.tintColor, PIXI.hex2rgb(graphics.tint));
  15303. gl.uniform1f(shader.alpha, graphics.worldAlpha);
  15304. gl.bindBuffer(gl.ARRAY_BUFFER, webGLData.buffer);
  15305. gl.vertexAttribPointer(shader.aVertexPosition, 2, gl.FLOAT, false, 4 * 6, 0);
  15306. gl.vertexAttribPointer(shader.colorAttribute, 4, gl.FLOAT, false,4 * 6, 2 * 4);
  15307. // set the index buffer!
  15308. gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, webGLData.indexBuffer);
  15309. }
  15310. };
  15311. /**
  15312. * @method popStencil
  15313. * @param graphics {Graphics}
  15314. * @param webGLData {Array}
  15315. * @param renderSession {Object}
  15316. */
  15317. PIXI.WebGLStencilManager.prototype.popStencil = function(graphics, webGLData, renderSession)
  15318. {
  15319. var gl = this.gl;
  15320. this.stencilStack.pop();
  15321. this.count--;
  15322. if(this.stencilStack.length === 0)
  15323. {
  15324. // the stack is empty!
  15325. gl.disable(gl.STENCIL_TEST);
  15326. }
  15327. else
  15328. {
  15329. var level = this.count;
  15330. this.bindGraphics(graphics, webGLData, renderSession);
  15331. gl.colorMask(false, false, false, false);
  15332. if(webGLData.mode === 1)
  15333. {
  15334. this.reverse = !this.reverse;
  15335. if(this.reverse)
  15336. {
  15337. gl.stencilFunc(gl.EQUAL, 0xFF - (level+1), 0xFF);
  15338. gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR);
  15339. }
  15340. else
  15341. {
  15342. gl.stencilFunc(gl.EQUAL,level+1, 0xFF);
  15343. gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR);
  15344. }
  15345. // draw a quad to increment..
  15346. gl.drawElements(gl.TRIANGLE_FAN, 4, gl.UNSIGNED_SHORT, ( webGLData.indices.length - 4 ) * 2 );
  15347. gl.stencilFunc(gl.ALWAYS,0,0xFF);
  15348. gl.stencilOp(gl.KEEP,gl.KEEP,gl.INVERT);
  15349. // draw the triangle strip!
  15350. gl.drawElements(gl.TRIANGLE_FAN, webGLData.indices.length - 4, gl.UNSIGNED_SHORT, 0 );
  15351. if(!this.reverse)
  15352. {
  15353. gl.stencilFunc(gl.EQUAL,0xFF-(level), 0xFF);
  15354. }
  15355. else
  15356. {
  15357. gl.stencilFunc(gl.EQUAL,level, 0xFF);
  15358. }
  15359. }
  15360. else
  15361. {
  15362. // console.log("<<>>")
  15363. if(!this.reverse)
  15364. {
  15365. gl.stencilFunc(gl.EQUAL, 0xFF - (level+1), 0xFF);
  15366. gl.stencilOp(gl.KEEP,gl.KEEP,gl.INCR);
  15367. }
  15368. else
  15369. {
  15370. gl.stencilFunc(gl.EQUAL,level+1, 0xFF);
  15371. gl.stencilOp(gl.KEEP,gl.KEEP,gl.DECR);
  15372. }
  15373. gl.drawElements(gl.TRIANGLE_STRIP, webGLData.indices.length, gl.UNSIGNED_SHORT, 0 );
  15374. if(!this.reverse)
  15375. {
  15376. gl.stencilFunc(gl.EQUAL,0xFF-(level), 0xFF);
  15377. }
  15378. else
  15379. {
  15380. gl.stencilFunc(gl.EQUAL,level, 0xFF);
  15381. }
  15382. }
  15383. gl.colorMask(true, true, true, true);
  15384. gl.stencilOp(gl.KEEP,gl.KEEP,gl.KEEP);
  15385. }
  15386. };
  15387. /**
  15388. * Destroys the mask stack.
  15389. *
  15390. * @method destroy
  15391. */
  15392. PIXI.WebGLStencilManager.prototype.destroy = function()
  15393. {
  15394. this.stencilStack = null;
  15395. this.gl = null;
  15396. };
  15397. /**
  15398. * @author Mat Groves http://matgroves.com/ @Doormat23
  15399. */
  15400. /**
  15401. * @class WebGLShaderManager
  15402. * @constructor
  15403. * @private
  15404. */
  15405. PIXI.WebGLShaderManager = function()
  15406. {
  15407. /**
  15408. * @property maxAttibs
  15409. * @type Number
  15410. */
  15411. this.maxAttibs = 10;
  15412. /**
  15413. * @property attribState
  15414. * @type Array
  15415. */
  15416. this.attribState = [];
  15417. /**
  15418. * @property tempAttribState
  15419. * @type Array
  15420. */
  15421. this.tempAttribState = [];
  15422. for (var i = 0; i < this.maxAttibs; i++)
  15423. {
  15424. this.attribState[i] = false;
  15425. }
  15426. /**
  15427. * @property stack
  15428. * @type Array
  15429. */
  15430. this.stack = [];
  15431. };
  15432. PIXI.WebGLShaderManager.prototype.constructor = PIXI.WebGLShaderManager;
  15433. /**
  15434. * Initialises the context and the properties.
  15435. *
  15436. * @method setContext
  15437. * @param gl {WebGLContext} the current WebGL drawing context
  15438. */
  15439. PIXI.WebGLShaderManager.prototype.setContext = function(gl)
  15440. {
  15441. this.gl = gl;
  15442. // the next one is used for rendering primitives
  15443. this.primitiveShader = new PIXI.PrimitiveShader(gl);
  15444. // the next one is used for rendering triangle strips
  15445. this.complexPrimitiveShader = new PIXI.ComplexPrimitiveShader(gl);
  15446. // this shader is used for the default sprite rendering
  15447. this.defaultShader = new PIXI.PixiShader(gl);
  15448. // this shader is used for the fast sprite rendering
  15449. this.fastShader = new PIXI.PixiFastShader(gl);
  15450. // the next one is used for rendering triangle strips
  15451. this.stripShader = new PIXI.StripShader(gl);
  15452. this.setShader(this.defaultShader);
  15453. };
  15454. /**
  15455. * Takes the attributes given in parameters.
  15456. *
  15457. * @method setAttribs
  15458. * @param attribs {Array} attribs
  15459. */
  15460. PIXI.WebGLShaderManager.prototype.setAttribs = function(attribs)
  15461. {
  15462. // reset temp state
  15463. var i;
  15464. for (i = 0; i < this.tempAttribState.length; i++)
  15465. {
  15466. this.tempAttribState[i] = false;
  15467. }
  15468. // set the new attribs
  15469. for (i = 0; i < attribs.length; i++)
  15470. {
  15471. var attribId = attribs[i];
  15472. this.tempAttribState[attribId] = true;
  15473. }
  15474. var gl = this.gl;
  15475. for (i = 0; i < this.attribState.length; i++)
  15476. {
  15477. if(this.attribState[i] !== this.tempAttribState[i])
  15478. {
  15479. this.attribState[i] = this.tempAttribState[i];
  15480. if(this.tempAttribState[i])
  15481. {
  15482. gl.enableVertexAttribArray(i);
  15483. }
  15484. else
  15485. {
  15486. gl.disableVertexAttribArray(i);
  15487. }
  15488. }
  15489. }
  15490. };
  15491. /**
  15492. * Sets the current shader.
  15493. *
  15494. * @method setShader
  15495. * @param shader {Any}
  15496. */
  15497. PIXI.WebGLShaderManager.prototype.setShader = function(shader)
  15498. {
  15499. if(this._currentId === shader._UID)return false;
  15500. this._currentId = shader._UID;
  15501. this.currentShader = shader;
  15502. this.gl.useProgram(shader.program);
  15503. this.setAttribs(shader.attributes);
  15504. return true;
  15505. };
  15506. /**
  15507. * Destroys this object.
  15508. *
  15509. * @method destroy
  15510. */
  15511. PIXI.WebGLShaderManager.prototype.destroy = function()
  15512. {
  15513. this.attribState = null;
  15514. this.tempAttribState = null;
  15515. this.primitiveShader.destroy();
  15516. this.complexPrimitiveShader.destroy();
  15517. this.defaultShader.destroy();
  15518. this.fastShader.destroy();
  15519. this.stripShader.destroy();
  15520. this.gl = null;
  15521. };
  15522. /**
  15523. * @author Mat Groves
  15524. *
  15525. * Big thanks to the very clever Matt DesLauriers <mattdesl> https://github.com/mattdesl/
  15526. * for creating the original pixi version!
  15527. * Also a thanks to https://github.com/bchevalier for tweaking the tint and alpha so that they now share 4 bytes on the vertex buffer
  15528. *
  15529. * Heavily inspired by LibGDX's WebGLSpriteBatch:
  15530. * https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/graphics/g2d/WebGLSpriteBatch.java
  15531. */
  15532. /**
  15533. *
  15534. * @class WebGLSpriteBatch
  15535. * @private
  15536. * @constructor
  15537. */
  15538. PIXI.WebGLSpriteBatch = function()
  15539. {
  15540. /**
  15541. * @property vertSize
  15542. * @type Number
  15543. */
  15544. this.vertSize = 5;
  15545. /**
  15546. * The number of images in the SpriteBatch before it flushes
  15547. * @property size
  15548. * @type Number
  15549. */
  15550. this.size = 2000;//Math.pow(2, 16) / this.vertSize;
  15551. //the total number of bytes in our batch
  15552. var numVerts = this.size * 4 * 4 * this.vertSize;
  15553. //the total number of indices in our batch
  15554. var numIndices = this.size * 6;
  15555. /**
  15556. * Holds the vertices
  15557. *
  15558. * @property vertices
  15559. * @type ArrayBuffer
  15560. */
  15561. this.vertices = new PIXI.ArrayBuffer(numVerts);
  15562. /**
  15563. * View on the vertices as a Float32Array
  15564. *
  15565. * @property positions
  15566. * @type Float32Array
  15567. */
  15568. this.positions = new PIXI.Float32Array(this.vertices);
  15569. /**
  15570. * View on the vertices as a Uint32Array
  15571. *
  15572. * @property colors
  15573. * @type Uint32Array
  15574. */
  15575. this.colors = new PIXI.Uint32Array(this.vertices);
  15576. /**
  15577. * Holds the indices
  15578. *
  15579. * @property indices
  15580. * @type Uint16Array
  15581. */
  15582. this.indices = new PIXI.Uint16Array(numIndices);
  15583. /**
  15584. * @property lastIndexCount
  15585. * @type Number
  15586. */
  15587. this.lastIndexCount = 0;
  15588. for (var i=0, j=0; i < numIndices; i += 6, j += 4)
  15589. {
  15590. this.indices[i + 0] = j + 0;
  15591. this.indices[i + 1] = j + 1;
  15592. this.indices[i + 2] = j + 2;
  15593. this.indices[i + 3] = j + 0;
  15594. this.indices[i + 4] = j + 2;
  15595. this.indices[i + 5] = j + 3;
  15596. }
  15597. /**
  15598. * @property drawing
  15599. * @type Boolean
  15600. */
  15601. this.drawing = false;
  15602. /**
  15603. * @property currentBatchSize
  15604. * @type Number
  15605. */
  15606. this.currentBatchSize = 0;
  15607. /**
  15608. * @property currentBaseTexture
  15609. * @type BaseTexture
  15610. */
  15611. this.currentBaseTexture = null;
  15612. /**
  15613. * @property dirty
  15614. * @type Boolean
  15615. */
  15616. this.dirty = true;
  15617. /**
  15618. * @property textures
  15619. * @type Array
  15620. */
  15621. this.textures = [];
  15622. /**
  15623. * @property blendModes
  15624. * @type Array
  15625. */
  15626. this.blendModes = [];
  15627. /**
  15628. * @property shaders
  15629. * @type Array
  15630. */
  15631. this.shaders = [];
  15632. /**
  15633. * @property sprites
  15634. * @type Array
  15635. */
  15636. this.sprites = [];
  15637. /**
  15638. * @property defaultShader
  15639. * @type AbstractFilter
  15640. */
  15641. this.defaultShader = new PIXI.AbstractFilter([
  15642. 'precision lowp float;',
  15643. 'varying vec2 vTextureCoord;',
  15644. 'varying vec4 vColor;',
  15645. 'uniform sampler2D uSampler;',
  15646. 'void main(void) {',
  15647. ' gl_FragColor = texture2D(uSampler, vTextureCoord) * vColor ;',
  15648. '}'
  15649. ]);
  15650. };
  15651. /**
  15652. * @method setContext
  15653. * @param gl {WebGLContext} the current WebGL drawing context
  15654. */
  15655. PIXI.WebGLSpriteBatch.prototype.setContext = function(gl)
  15656. {
  15657. this.gl = gl;
  15658. // create a couple of buffers
  15659. this.vertexBuffer = gl.createBuffer();
  15660. this.indexBuffer = gl.createBuffer();
  15661. // 65535 is max index, so 65535 / 6 = 10922.
  15662. //upload the index data
  15663. gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.indexBuffer);
  15664. gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, this.indices, gl.STATIC_DRAW);
  15665. gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer);
  15666. gl.bufferData(gl.ARRAY_BUFFER, this.vertices, gl.DYNAMIC_DRAW);
  15667. this.currentBlendMode = 99999;
  15668. var shader = new PIXI.PixiShader(gl);
  15669. shader.fragmentSrc = this.defaultShader.fragmentSrc;
  15670. shader.uniforms = {};
  15671. shader.init();
  15672. this.defaultShader.shaders[gl.id] = shader;
  15673. };
  15674. /**
  15675. * @method begin
  15676. * @param renderSession {Object} The RenderSession object
  15677. */
  15678. PIXI.WebGLSpriteBatch.prototype.begin = function(renderSession)
  15679. {
  15680. this.renderSession = renderSession;
  15681. this.shader = this.renderSession.shaderManager.defaultShader;
  15682. this.start();
  15683. };
  15684. /**
  15685. * @method end
  15686. */
  15687. PIXI.WebGLSpriteBatch.prototype.end = function()
  15688. {
  15689. this.flush();
  15690. };
  15691. /**
  15692. * @method render
  15693. * @param sprite {Sprite} the sprite to render when using this spritebatch
  15694. * @param {Matrix} [matrix] - Optional matrix. If provided the Display Object will be rendered using this matrix, otherwise it will use its worldTransform.
  15695. */
  15696. PIXI.WebGLSpriteBatch.prototype.render = function(sprite, matrix)
  15697. {
  15698. var texture = sprite.texture;
  15699. // They provided an alternative rendering matrix, so use it
  15700. var wt = sprite.worldTransform;
  15701. if (matrix)
  15702. {
  15703. wt = matrix;
  15704. }
  15705. // check texture..
  15706. if (this.currentBatchSize >= this.size)
  15707. {
  15708. this.flush();
  15709. this.currentBaseTexture = texture.baseTexture;
  15710. }
  15711. // get the uvs for the texture
  15712. var uvs = texture._uvs;
  15713. // if the uvs have not updated then no point rendering just yet!
  15714. if (!uvs)
  15715. {
  15716. return;
  15717. }
  15718. var aX = sprite.anchor.x;
  15719. var aY = sprite.anchor.y;
  15720. var w0, w1, h0, h1;
  15721. if (texture.trim)
  15722. {
  15723. // if the sprite is trimmed then we need to add the extra space before transforming the sprite coords.
  15724. var trim = texture.trim;
  15725. w1 = trim.x - aX * trim.width;
  15726. w0 = w1 + texture.crop.width;
  15727. h1 = trim.y - aY * trim.height;
  15728. h0 = h1 + texture.crop.height;
  15729. }
  15730. else
  15731. {
  15732. w0 = (texture.frame.width) * (1-aX);
  15733. w1 = (texture.frame.width) * -aX;
  15734. h0 = texture.frame.height * (1-aY);
  15735. h1 = texture.frame.height * -aY;
  15736. }
  15737. var i = this.currentBatchSize * 4 * this.vertSize;
  15738. var resolution = texture.baseTexture.resolution;
  15739. var a = wt.a / resolution;
  15740. var b = wt.b / resolution;
  15741. var c = wt.c / resolution;
  15742. var d = wt.d / resolution;
  15743. var tx = wt.tx;
  15744. var ty = wt.ty;
  15745. var colors = this.colors;
  15746. var positions = this.positions;
  15747. if (this.renderSession.roundPixels)
  15748. {
  15749. // xy
  15750. positions[i] = a * w1 + c * h1 + tx | 0;
  15751. positions[i+1] = d * h1 + b * w1 + ty | 0;
  15752. // xy
  15753. positions[i+5] = a * w0 + c * h1 + tx | 0;
  15754. positions[i+6] = d * h1 + b * w0 + ty | 0;
  15755. // xy
  15756. positions[i+10] = a * w0 + c * h0 + tx | 0;
  15757. positions[i+11] = d * h0 + b * w0 + ty | 0;
  15758. // xy
  15759. positions[i+15] = a * w1 + c * h0 + tx | 0;
  15760. positions[i+16] = d * h0 + b * w1 + ty | 0;
  15761. }
  15762. else
  15763. {
  15764. // xy
  15765. positions[i] = a * w1 + c * h1 + tx;
  15766. positions[i+1] = d * h1 + b * w1 + ty;
  15767. // xy
  15768. positions[i+5] = a * w0 + c * h1 + tx;
  15769. positions[i+6] = d * h1 + b * w0 + ty;
  15770. // xy
  15771. positions[i+10] = a * w0 + c * h0 + tx;
  15772. positions[i+11] = d * h0 + b * w0 + ty;
  15773. // xy
  15774. positions[i+15] = a * w1 + c * h0 + tx;
  15775. positions[i+16] = d * h0 + b * w1 + ty;
  15776. }
  15777. // uv
  15778. positions[i+2] = uvs.x0;
  15779. positions[i+3] = uvs.y0;
  15780. // uv
  15781. positions[i+7] = uvs.x1;
  15782. positions[i+8] = uvs.y1;
  15783. // uv
  15784. positions[i+12] = uvs.x2;
  15785. positions[i+13] = uvs.y2;
  15786. // uv
  15787. positions[i+17] = uvs.x3;
  15788. positions[i+18] = uvs.y3;
  15789. // color and alpha
  15790. var tint = sprite.tint;
  15791. colors[i+4] = colors[i+9] = colors[i+14] = colors[i+19] = (tint >> 16) + (tint & 0xff00) + ((tint & 0xff) << 16) + (sprite.worldAlpha * 255 << 24);
  15792. // increment the batchsize
  15793. this.sprites[this.currentBatchSize++] = sprite;
  15794. };
  15795. /**
  15796. * Renders a TilingSprite using the spriteBatch.
  15797. *
  15798. * @method renderTilingSprite
  15799. * @param sprite {TilingSprite} the sprite to render
  15800. */
  15801. PIXI.WebGLSpriteBatch.prototype.renderTilingSprite = function(sprite)
  15802. {
  15803. var texture = sprite.tilingTexture;
  15804. // check texture..
  15805. if (this.currentBatchSize >= this.size)
  15806. {
  15807. this.flush();
  15808. this.currentBaseTexture = texture.baseTexture;
  15809. }
  15810. // set the textures uvs temporarily
  15811. if (!sprite._uvs)
  15812. {
  15813. sprite._uvs = new PIXI.TextureUvs();
  15814. }
  15815. var uvs = sprite._uvs;
  15816. var w = texture.baseTexture.width;
  15817. var h = texture.baseTexture.height;
  15818. // var w = sprite._frame.sourceSizeW;
  15819. // var h = sprite._frame.sourceSizeH;
  15820. // w = 16;
  15821. // h = 16;
  15822. sprite.tilePosition.x %= w * sprite.tileScaleOffset.x;
  15823. sprite.tilePosition.y %= h * sprite.tileScaleOffset.y;
  15824. var offsetX = sprite.tilePosition.x / (w * sprite.tileScaleOffset.x);
  15825. var offsetY = sprite.tilePosition.y / (h * sprite.tileScaleOffset.y);
  15826. var scaleX = (sprite.width / w) / (sprite.tileScale.x * sprite.tileScaleOffset.x);
  15827. var scaleY = (sprite.height / h) / (sprite.tileScale.y * sprite.tileScaleOffset.y);
  15828. uvs.x0 = 0 - offsetX;
  15829. uvs.y0 = 0 - offsetY;
  15830. uvs.x1 = (1 * scaleX) - offsetX;
  15831. uvs.y1 = 0 - offsetY;
  15832. uvs.x2 = (1 * scaleX) - offsetX;
  15833. uvs.y2 = (1 * scaleY) - offsetY;
  15834. uvs.x3 = 0 - offsetX;
  15835. uvs.y3 = (1 * scaleY) - offsetY;
  15836. // Get the sprites current alpha and tint and combine them into a single color
  15837. var tint = sprite.tint;
  15838. var color = (tint >> 16) + (tint & 0xff00) + ((tint & 0xff) << 16) + (sprite.worldAlpha * 255 << 24);
  15839. var positions = this.positions;
  15840. var colors = this.colors;
  15841. var width = sprite.width;
  15842. var height = sprite.height;
  15843. // TODO trim??
  15844. var aX = sprite.anchor.x;
  15845. var aY = sprite.anchor.y;
  15846. var w0 = width * (1-aX);
  15847. var w1 = width * -aX;
  15848. var h0 = height * (1-aY);
  15849. var h1 = height * -aY;
  15850. var i = this.currentBatchSize * 4 * this.vertSize;
  15851. var resolution = texture.baseTexture.resolution;
  15852. var wt = sprite.worldTransform;
  15853. var a = wt.a / resolution;
  15854. var b = wt.b / resolution;
  15855. var c = wt.c / resolution;
  15856. var d = wt.d / resolution;
  15857. var tx = wt.tx;
  15858. var ty = wt.ty;
  15859. // xy
  15860. positions[i++] = a * w1 + c * h1 + tx;
  15861. positions[i++] = d * h1 + b * w1 + ty;
  15862. // uv
  15863. positions[i++] = uvs.x0;
  15864. positions[i++] = uvs.y0;
  15865. // color
  15866. colors[i++] = color;
  15867. // xy
  15868. positions[i++] = (a * w0 + c * h1 + tx);
  15869. positions[i++] = d * h1 + b * w0 + ty;
  15870. // uv
  15871. positions[i++] = uvs.x1;
  15872. positions[i++] = uvs.y1;
  15873. // color
  15874. colors[i++] = color;
  15875. // xy
  15876. positions[i++] = a * w0 + c * h0 + tx;
  15877. positions[i++] = d * h0 + b * w0 + ty;
  15878. // uv
  15879. positions[i++] = uvs.x2;
  15880. positions[i++] = uvs.y2;
  15881. // color
  15882. colors[i++] = color;
  15883. // xy
  15884. positions[i++] = a * w1 + c * h0 + tx;
  15885. positions[i++] = d * h0 + b * w1 + ty;
  15886. // uv
  15887. positions[i++] = uvs.x3;
  15888. positions[i++] = uvs.y3;
  15889. // color
  15890. colors[i++] = color;
  15891. // increment the batchsize
  15892. this.sprites[this.currentBatchSize++] = sprite;
  15893. };
  15894. /**
  15895. * Renders the content and empties the current batch.
  15896. *
  15897. * @method flush
  15898. */
  15899. PIXI.WebGLSpriteBatch.prototype.flush = function()
  15900. {
  15901. // If the batch is length 0 then return as there is nothing to draw
  15902. if (this.currentBatchSize === 0)
  15903. {
  15904. return;
  15905. }
  15906. var gl = this.gl;
  15907. var shader;
  15908. if (this.dirty)
  15909. {
  15910. this.dirty = false;
  15911. // bind the main texture
  15912. gl.activeTexture(gl.TEXTURE0);
  15913. // bind the buffers
  15914. gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer);
  15915. gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.indexBuffer);
  15916. shader = this.defaultShader.shaders[gl.id];
  15917. // this is the same for each shader?
  15918. var stride = this.vertSize * 4;
  15919. gl.vertexAttribPointer(shader.aVertexPosition, 2, gl.FLOAT, false, stride, 0);
  15920. gl.vertexAttribPointer(shader.aTextureCoord, 2, gl.FLOAT, false, stride, 2 * 4);
  15921. // color attributes will be interpreted as unsigned bytes and normalized
  15922. gl.vertexAttribPointer(shader.colorAttribute, 4, gl.UNSIGNED_BYTE, true, stride, 4 * 4);
  15923. }
  15924. // upload the verts to the buffer
  15925. if (this.currentBatchSize > (this.size * 0.5))
  15926. {
  15927. gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices);
  15928. }
  15929. else
  15930. {
  15931. var view = this.positions.subarray(0, this.currentBatchSize * 4 * this.vertSize);
  15932. gl.bufferSubData(gl.ARRAY_BUFFER, 0, view);
  15933. }
  15934. var nextTexture, nextBlendMode, nextShader;
  15935. var batchSize = 0;
  15936. var start = 0;
  15937. var currentBaseTexture = null;
  15938. var currentBlendMode = this.renderSession.blendModeManager.currentBlendMode;
  15939. var currentShader = null;
  15940. var blendSwap = false;
  15941. var shaderSwap = false;
  15942. var sprite;
  15943. for (var i = 0, j = this.currentBatchSize; i < j; i++) {
  15944. sprite = this.sprites[i];
  15945. if (sprite.tilingTexture)
  15946. {
  15947. nextTexture = sprite.tilingTexture.baseTexture;
  15948. }
  15949. else
  15950. {
  15951. nextTexture = sprite.texture.baseTexture;
  15952. }
  15953. nextBlendMode = sprite.blendMode;
  15954. nextShader = sprite.shader || this.defaultShader;
  15955. blendSwap = currentBlendMode !== nextBlendMode;
  15956. shaderSwap = currentShader !== nextShader; // should I use _UIDS???
  15957. var skip = nextTexture.skipRender;
  15958. if (skip && sprite.children.length > 0)
  15959. {
  15960. skip = false;
  15961. }
  15962. if ((currentBaseTexture !== nextTexture && !skip) || blendSwap || shaderSwap)
  15963. {
  15964. this.renderBatch(currentBaseTexture, batchSize, start);
  15965. start = i;
  15966. batchSize = 0;
  15967. currentBaseTexture = nextTexture;
  15968. if (blendSwap)
  15969. {
  15970. currentBlendMode = nextBlendMode;
  15971. this.renderSession.blendModeManager.setBlendMode(currentBlendMode);
  15972. }
  15973. if (shaderSwap)
  15974. {
  15975. currentShader = nextShader;
  15976. shader = currentShader.shaders[gl.id];
  15977. if (!shader)
  15978. {
  15979. shader = new PIXI.PixiShader(gl);
  15980. shader.fragmentSrc = currentShader.fragmentSrc;
  15981. shader.uniforms = currentShader.uniforms;
  15982. shader.init();
  15983. currentShader.shaders[gl.id] = shader;
  15984. }
  15985. // set shader function???
  15986. this.renderSession.shaderManager.setShader(shader);
  15987. if (shader.dirty)
  15988. {
  15989. shader.syncUniforms();
  15990. }
  15991. // both these only need to be set if they are changing..
  15992. // set the projection
  15993. var projection = this.renderSession.projection;
  15994. gl.uniform2f(shader.projectionVector, projection.x, projection.y);
  15995. // TODO - this is temporary!
  15996. var offsetVector = this.renderSession.offset;
  15997. gl.uniform2f(shader.offsetVector, offsetVector.x, offsetVector.y);
  15998. // set the pointers
  15999. }
  16000. }
  16001. batchSize++;
  16002. }
  16003. this.renderBatch(currentBaseTexture, batchSize, start);
  16004. // then reset the batch!
  16005. this.currentBatchSize = 0;
  16006. };
  16007. /**
  16008. * @method renderBatch
  16009. * @param texture {Texture}
  16010. * @param size {Number}
  16011. * @param startIndex {Number}
  16012. */
  16013. PIXI.WebGLSpriteBatch.prototype.renderBatch = function(texture, size, startIndex)
  16014. {
  16015. if (size === 0)
  16016. {
  16017. return;
  16018. }
  16019. var gl = this.gl;
  16020. // check if a texture is dirty..
  16021. if (texture._dirty[gl.id])
  16022. {
  16023. if (!this.renderSession.renderer.updateTexture(texture))
  16024. {
  16025. // If updateTexture returns false then we cannot render it, so bail out now
  16026. return;
  16027. }
  16028. }
  16029. else
  16030. {
  16031. // bind the current texture
  16032. gl.bindTexture(gl.TEXTURE_2D, texture._glTextures[gl.id]);
  16033. }
  16034. // now draw those suckas!
  16035. gl.drawElements(gl.TRIANGLES, size * 6, gl.UNSIGNED_SHORT, startIndex * 6 * 2);
  16036. // increment the draw count
  16037. this.renderSession.drawCount++;
  16038. };
  16039. /**
  16040. * @method stop
  16041. */
  16042. PIXI.WebGLSpriteBatch.prototype.stop = function()
  16043. {
  16044. this.flush();
  16045. this.dirty = true;
  16046. };
  16047. /**
  16048. * @method start
  16049. */
  16050. PIXI.WebGLSpriteBatch.prototype.start = function()
  16051. {
  16052. this.dirty = true;
  16053. };
  16054. /**
  16055. * Destroys the SpriteBatch.
  16056. *
  16057. * @method destroy
  16058. */
  16059. PIXI.WebGLSpriteBatch.prototype.destroy = function()
  16060. {
  16061. this.vertices = null;
  16062. this.indices = null;
  16063. this.gl.deleteBuffer(this.vertexBuffer);
  16064. this.gl.deleteBuffer(this.indexBuffer);
  16065. this.currentBaseTexture = null;
  16066. this.gl = null;
  16067. };
  16068. /**
  16069. * @author Mat Groves
  16070. *
  16071. * Big thanks to the very clever Matt DesLauriers <mattdesl> https://github.com/mattdesl/
  16072. * for creating the original pixi version!
  16073. *
  16074. * Heavily inspired by LibGDX's WebGLSpriteBatch:
  16075. * https://github.com/libgdx/libgdx/blob/master/gdx/src/com/badlogic/gdx/graphics/g2d/WebGLSpriteBatch.java
  16076. */
  16077. /**
  16078. * @class WebGLFastSpriteBatch
  16079. * @constructor
  16080. */
  16081. PIXI.WebGLFastSpriteBatch = function(gl)
  16082. {
  16083. /**
  16084. * @property vertSize
  16085. * @type Number
  16086. */
  16087. this.vertSize = 10;
  16088. /**
  16089. * @property maxSize
  16090. * @type Number
  16091. */
  16092. this.maxSize = 6000;//Math.pow(2, 16) / this.vertSize;
  16093. /**
  16094. * @property size
  16095. * @type Number
  16096. */
  16097. this.size = this.maxSize;
  16098. //the total number of floats in our batch
  16099. var numVerts = this.size * 4 * this.vertSize;
  16100. //the total number of indices in our batch
  16101. var numIndices = this.maxSize * 6;
  16102. /**
  16103. * Vertex data
  16104. * @property vertices
  16105. * @type Float32Array
  16106. */
  16107. this.vertices = new PIXI.Float32Array(numVerts);
  16108. /**
  16109. * Index data
  16110. * @property indices
  16111. * @type Uint16Array
  16112. */
  16113. this.indices = new PIXI.Uint16Array(numIndices);
  16114. /**
  16115. * @property vertexBuffer
  16116. * @type Object
  16117. */
  16118. this.vertexBuffer = null;
  16119. /**
  16120. * @property indexBuffer
  16121. * @type Object
  16122. */
  16123. this.indexBuffer = null;
  16124. /**
  16125. * @property lastIndexCount
  16126. * @type Number
  16127. */
  16128. this.lastIndexCount = 0;
  16129. for (var i=0, j=0; i < numIndices; i += 6, j += 4)
  16130. {
  16131. this.indices[i + 0] = j + 0;
  16132. this.indices[i + 1] = j + 1;
  16133. this.indices[i + 2] = j + 2;
  16134. this.indices[i + 3] = j + 0;
  16135. this.indices[i + 4] = j + 2;
  16136. this.indices[i + 5] = j + 3;
  16137. }
  16138. /**
  16139. * @property drawing
  16140. * @type Boolean
  16141. */
  16142. this.drawing = false;
  16143. /**
  16144. * @property currentBatchSize
  16145. * @type Number
  16146. */
  16147. this.currentBatchSize = 0;
  16148. /**
  16149. * @property currentBaseTexture
  16150. * @type BaseTexture
  16151. */
  16152. this.currentBaseTexture = null;
  16153. /**
  16154. * @property currentBlendMode
  16155. * @type Number
  16156. */
  16157. this.currentBlendMode = 0;
  16158. /**
  16159. * @property renderSession
  16160. * @type Object
  16161. */
  16162. this.renderSession = null;
  16163. /**
  16164. * @property shader
  16165. * @type Object
  16166. */
  16167. this.shader = null;
  16168. /**
  16169. * @property matrix
  16170. * @type Matrix
  16171. */
  16172. this.matrix = null;
  16173. this.setContext(gl);
  16174. };
  16175. PIXI.WebGLFastSpriteBatch.prototype.constructor = PIXI.WebGLFastSpriteBatch;
  16176. /**
  16177. * Sets the WebGL Context.
  16178. *
  16179. * @method setContext
  16180. * @param gl {WebGLContext} the current WebGL drawing context
  16181. */
  16182. PIXI.WebGLFastSpriteBatch.prototype.setContext = function(gl)
  16183. {
  16184. this.gl = gl;
  16185. // create a couple of buffers
  16186. this.vertexBuffer = gl.createBuffer();
  16187. this.indexBuffer = gl.createBuffer();
  16188. // 65535 is max index, so 65535 / 6 = 10922.
  16189. //upload the index data
  16190. gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.indexBuffer);
  16191. gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, this.indices, gl.STATIC_DRAW);
  16192. gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer);
  16193. gl.bufferData(gl.ARRAY_BUFFER, this.vertices, gl.DYNAMIC_DRAW);
  16194. };
  16195. /**
  16196. * @method begin
  16197. * @param spriteBatch {WebGLSpriteBatch}
  16198. * @param renderSession {Object}
  16199. */
  16200. PIXI.WebGLFastSpriteBatch.prototype.begin = function(spriteBatch, renderSession)
  16201. {
  16202. this.renderSession = renderSession;
  16203. this.shader = this.renderSession.shaderManager.fastShader;
  16204. this.matrix = spriteBatch.worldTransform.toArray(true);
  16205. this.start();
  16206. };
  16207. /**
  16208. * @method end
  16209. */
  16210. PIXI.WebGLFastSpriteBatch.prototype.end = function()
  16211. {
  16212. this.flush();
  16213. };
  16214. /**
  16215. * @method render
  16216. * @param spriteBatch {WebGLSpriteBatch}
  16217. */
  16218. PIXI.WebGLFastSpriteBatch.prototype.render = function(spriteBatch)
  16219. {
  16220. var children = spriteBatch.children;
  16221. var sprite = children[0];
  16222. // if the uvs have not updated then no point rendering just yet!
  16223. // check texture.
  16224. if(!sprite.texture._uvs)return;
  16225. this.currentBaseTexture = sprite.texture.baseTexture;
  16226. // check blend mode
  16227. if(sprite.blendMode !== this.renderSession.blendModeManager.currentBlendMode)
  16228. {
  16229. this.flush();
  16230. this.renderSession.blendModeManager.setBlendMode(sprite.blendMode);
  16231. }
  16232. for(var i=0,j= children.length; i<j; i++)
  16233. {
  16234. this.renderSprite(children[i]);
  16235. }
  16236. this.flush();
  16237. };
  16238. /**
  16239. * @method renderSprite
  16240. * @param sprite {Sprite}
  16241. */
  16242. PIXI.WebGLFastSpriteBatch.prototype.renderSprite = function(sprite)
  16243. {
  16244. //sprite = children[i];
  16245. if(!sprite.visible)return;
  16246. // TODO trim??
  16247. if(sprite.texture.baseTexture !== this.currentBaseTexture && !sprite.texture.baseTexture.skipRender)
  16248. {
  16249. this.flush();
  16250. this.currentBaseTexture = sprite.texture.baseTexture;
  16251. if(!sprite.texture._uvs)return;
  16252. }
  16253. var uvs, vertices = this.vertices, width, height, w0, w1, h0, h1, index;
  16254. uvs = sprite.texture._uvs;
  16255. width = sprite.texture.frame.width;
  16256. height = sprite.texture.frame.height;
  16257. if (sprite.texture.trim)
  16258. {
  16259. // if the sprite is trimmed then we need to add the extra space before transforming the sprite coords..
  16260. var trim = sprite.texture.trim;
  16261. w1 = trim.x - sprite.anchor.x * trim.width;
  16262. w0 = w1 + sprite.texture.crop.width;
  16263. h1 = trim.y - sprite.anchor.y * trim.height;
  16264. h0 = h1 + sprite.texture.crop.height;
  16265. }
  16266. else
  16267. {
  16268. w0 = (sprite.texture.frame.width ) * (1-sprite.anchor.x);
  16269. w1 = (sprite.texture.frame.width ) * -sprite.anchor.x;
  16270. h0 = sprite.texture.frame.height * (1-sprite.anchor.y);
  16271. h1 = sprite.texture.frame.height * -sprite.anchor.y;
  16272. }
  16273. index = this.currentBatchSize * 4 * this.vertSize;
  16274. // xy
  16275. vertices[index++] = w1;
  16276. vertices[index++] = h1;
  16277. vertices[index++] = sprite.position.x;
  16278. vertices[index++] = sprite.position.y;
  16279. //scale
  16280. vertices[index++] = sprite.scale.x;
  16281. vertices[index++] = sprite.scale.y;
  16282. //rotation
  16283. vertices[index++] = sprite.rotation;
  16284. // uv
  16285. vertices[index++] = uvs.x0;
  16286. vertices[index++] = uvs.y1;
  16287. // color
  16288. vertices[index++] = sprite.alpha;
  16289. // xy
  16290. vertices[index++] = w0;
  16291. vertices[index++] = h1;
  16292. vertices[index++] = sprite.position.x;
  16293. vertices[index++] = sprite.position.y;
  16294. //scale
  16295. vertices[index++] = sprite.scale.x;
  16296. vertices[index++] = sprite.scale.y;
  16297. //rotation
  16298. vertices[index++] = sprite.rotation;
  16299. // uv
  16300. vertices[index++] = uvs.x1;
  16301. vertices[index++] = uvs.y1;
  16302. // color
  16303. vertices[index++] = sprite.alpha;
  16304. // xy
  16305. vertices[index++] = w0;
  16306. vertices[index++] = h0;
  16307. vertices[index++] = sprite.position.x;
  16308. vertices[index++] = sprite.position.y;
  16309. //scale
  16310. vertices[index++] = sprite.scale.x;
  16311. vertices[index++] = sprite.scale.y;
  16312. //rotation
  16313. vertices[index++] = sprite.rotation;
  16314. // uv
  16315. vertices[index++] = uvs.x2;
  16316. vertices[index++] = uvs.y2;
  16317. // color
  16318. vertices[index++] = sprite.alpha;
  16319. // xy
  16320. vertices[index++] = w1;
  16321. vertices[index++] = h0;
  16322. vertices[index++] = sprite.position.x;
  16323. vertices[index++] = sprite.position.y;
  16324. //scale
  16325. vertices[index++] = sprite.scale.x;
  16326. vertices[index++] = sprite.scale.y;
  16327. //rotation
  16328. vertices[index++] = sprite.rotation;
  16329. // uv
  16330. vertices[index++] = uvs.x3;
  16331. vertices[index++] = uvs.y3;
  16332. // color
  16333. vertices[index++] = sprite.alpha;
  16334. // increment the batchs
  16335. this.currentBatchSize++;
  16336. if(this.currentBatchSize >= this.size)
  16337. {
  16338. this.flush();
  16339. }
  16340. };
  16341. /**
  16342. * @method flush
  16343. */
  16344. PIXI.WebGLFastSpriteBatch.prototype.flush = function()
  16345. {
  16346. // If the batch is length 0 then return as there is nothing to draw
  16347. if (this.currentBatchSize===0)return;
  16348. var gl = this.gl;
  16349. // bind the current texture
  16350. if(!this.currentBaseTexture._glTextures[gl.id])this.renderSession.renderer.updateTexture(this.currentBaseTexture, gl);
  16351. gl.bindTexture(gl.TEXTURE_2D, this.currentBaseTexture._glTextures[gl.id]);
  16352. // upload the verts to the buffer
  16353. if(this.currentBatchSize > ( this.size * 0.5 ) )
  16354. {
  16355. gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices);
  16356. }
  16357. else
  16358. {
  16359. var view = this.vertices.subarray(0, this.currentBatchSize * 4 * this.vertSize);
  16360. gl.bufferSubData(gl.ARRAY_BUFFER, 0, view);
  16361. }
  16362. // now draw those suckas!
  16363. gl.drawElements(gl.TRIANGLES, this.currentBatchSize * 6, gl.UNSIGNED_SHORT, 0);
  16364. // then reset the batch!
  16365. this.currentBatchSize = 0;
  16366. // increment the draw count
  16367. this.renderSession.drawCount++;
  16368. };
  16369. /**
  16370. * @method stop
  16371. */
  16372. PIXI.WebGLFastSpriteBatch.prototype.stop = function()
  16373. {
  16374. this.flush();
  16375. };
  16376. /**
  16377. * @method start
  16378. */
  16379. PIXI.WebGLFastSpriteBatch.prototype.start = function()
  16380. {
  16381. var gl = this.gl;
  16382. // bind the main texture
  16383. gl.activeTexture(gl.TEXTURE0);
  16384. // bind the buffers
  16385. gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer);
  16386. gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.indexBuffer);
  16387. // set the projection
  16388. var projection = this.renderSession.projection;
  16389. gl.uniform2f(this.shader.projectionVector, projection.x, projection.y);
  16390. // set the matrix
  16391. gl.uniformMatrix3fv(this.shader.uMatrix, false, this.matrix);
  16392. // set the pointers
  16393. var stride = this.vertSize * 4;
  16394. gl.vertexAttribPointer(this.shader.aVertexPosition, 2, gl.FLOAT, false, stride, 0);
  16395. gl.vertexAttribPointer(this.shader.aPositionCoord, 2, gl.FLOAT, false, stride, 2 * 4);
  16396. gl.vertexAttribPointer(this.shader.aScale, 2, gl.FLOAT, false, stride, 4 * 4);
  16397. gl.vertexAttribPointer(this.shader.aRotation, 1, gl.FLOAT, false, stride, 6 * 4);
  16398. gl.vertexAttribPointer(this.shader.aTextureCoord, 2, gl.FLOAT, false, stride, 7 * 4);
  16399. gl.vertexAttribPointer(this.shader.colorAttribute, 1, gl.FLOAT, false, stride, 9 * 4);
  16400. };
  16401. /**
  16402. * @author Mat Groves http://matgroves.com/ @Doormat23
  16403. */
  16404. /**
  16405. * @class WebGLFilterManager
  16406. * @constructor
  16407. */
  16408. PIXI.WebGLFilterManager = function()
  16409. {
  16410. /**
  16411. * @property filterStack
  16412. * @type Array
  16413. */
  16414. this.filterStack = [];
  16415. /**
  16416. * @property offsetX
  16417. * @type Number
  16418. */
  16419. this.offsetX = 0;
  16420. /**
  16421. * @property offsetY
  16422. * @type Number
  16423. */
  16424. this.offsetY = 0;
  16425. };
  16426. PIXI.WebGLFilterManager.prototype.constructor = PIXI.WebGLFilterManager;
  16427. /**
  16428. * Initialises the context and the properties.
  16429. *
  16430. * @method setContext
  16431. * @param gl {WebGLContext} the current WebGL drawing context
  16432. */
  16433. PIXI.WebGLFilterManager.prototype.setContext = function(gl)
  16434. {
  16435. this.gl = gl;
  16436. this.texturePool = [];
  16437. this.initShaderBuffers();
  16438. };
  16439. /**
  16440. * @method begin
  16441. * @param renderSession {RenderSession}
  16442. * @param buffer {ArrayBuffer}
  16443. */
  16444. PIXI.WebGLFilterManager.prototype.begin = function(renderSession, buffer)
  16445. {
  16446. this.renderSession = renderSession;
  16447. this.defaultShader = renderSession.shaderManager.defaultShader;
  16448. var projection = this.renderSession.projection;
  16449. this.width = projection.x * 2;
  16450. this.height = -projection.y * 2;
  16451. this.buffer = buffer;
  16452. };
  16453. /**
  16454. * Applies the filter and adds it to the current filter stack.
  16455. *
  16456. * @method pushFilter
  16457. * @param filterBlock {Object} the filter that will be pushed to the current filter stack
  16458. */
  16459. PIXI.WebGLFilterManager.prototype.pushFilter = function(filterBlock)
  16460. {
  16461. var gl = this.gl;
  16462. var projection = this.renderSession.projection;
  16463. var offset = this.renderSession.offset;
  16464. filterBlock._filterArea = filterBlock.target.filterArea || filterBlock.target.getBounds();
  16465. // >>> modify by nextht
  16466. filterBlock._previous_stencil_mgr = this.renderSession.stencilManager;
  16467. this.renderSession.stencilManager = new PIXI.WebGLStencilManager();
  16468. this.renderSession.stencilManager.setContext(gl);
  16469. gl.disable(gl.STENCIL_TEST);
  16470. // <<< modify by nextht
  16471. // filter program
  16472. // OPTIMISATION - the first filter is free if its a simple color change?
  16473. this.filterStack.push(filterBlock);
  16474. var filter = filterBlock.filterPasses[0];
  16475. this.offsetX += filterBlock._filterArea.x;
  16476. this.offsetY += filterBlock._filterArea.y;
  16477. var texture = this.texturePool.pop();
  16478. if(!texture)
  16479. {
  16480. texture = new PIXI.FilterTexture(this.gl, this.width * this.renderSession.resolution, this.height * this.renderSession.resolution);
  16481. }
  16482. else
  16483. {
  16484. texture.resize(this.width * this.renderSession.resolution, this.height * this.renderSession.resolution);
  16485. }
  16486. gl.bindTexture(gl.TEXTURE_2D, texture.texture);
  16487. var filterArea = filterBlock._filterArea;// filterBlock.target.getBounds();///filterBlock.target.filterArea;
  16488. var padding = filter.padding;
  16489. filterArea.x -= padding;
  16490. filterArea.y -= padding;
  16491. filterArea.width += padding * 2;
  16492. filterArea.height += padding * 2;
  16493. // cap filter to screen size..
  16494. if(filterArea.x < 0)filterArea.x = 0;
  16495. if(filterArea.width > this.width)filterArea.width = this.width;
  16496. if(filterArea.y < 0)filterArea.y = 0;
  16497. if(filterArea.height > this.height)filterArea.height = this.height;
  16498. //gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, filterArea.width, filterArea.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  16499. gl.bindFramebuffer(gl.FRAMEBUFFER, texture.frameBuffer);
  16500. // set view port
  16501. gl.viewport(0, 0, filterArea.width * this.renderSession.resolution, filterArea.height * this.renderSession.resolution);
  16502. projection.x = filterArea.width/2;
  16503. projection.y = -filterArea.height/2;
  16504. offset.x = -filterArea.x;
  16505. offset.y = -filterArea.y;
  16506. // update projection
  16507. // now restore the regular shader..
  16508. // this.renderSession.shaderManager.setShader(this.defaultShader);
  16509. //gl.uniform2f(this.defaultShader.projectionVector, filterArea.width/2, -filterArea.height/2);
  16510. //gl.uniform2f(this.defaultShader.offsetVector, -filterArea.x, -filterArea.y);
  16511. gl.colorMask(true, true, true, true);
  16512. gl.clearColor(0,0,0, 0);
  16513. gl.clear(gl.COLOR_BUFFER_BIT);
  16514. filterBlock._glFilterTexture = texture;
  16515. };
  16516. /**
  16517. * Removes the last filter from the filter stack and doesn't return it.
  16518. *
  16519. * @method popFilter
  16520. */
  16521. PIXI.WebGLFilterManager.prototype.popFilter = function()
  16522. {
  16523. var gl = this.gl;
  16524. var filterBlock = this.filterStack.pop();
  16525. var filterArea = filterBlock._filterArea;
  16526. var texture = filterBlock._glFilterTexture;
  16527. var projection = this.renderSession.projection;
  16528. var offset = this.renderSession.offset;
  16529. if(filterBlock.filterPasses.length > 1)
  16530. {
  16531. gl.viewport(0, 0, filterArea.width * this.renderSession.resolution, filterArea.height * this.renderSession.resolution);
  16532. gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer);
  16533. this.vertexArray[0] = 0;
  16534. this.vertexArray[1] = filterArea.height;
  16535. this.vertexArray[2] = filterArea.width;
  16536. this.vertexArray[3] = filterArea.height;
  16537. this.vertexArray[4] = 0;
  16538. this.vertexArray[5] = 0;
  16539. this.vertexArray[6] = filterArea.width;
  16540. this.vertexArray[7] = 0;
  16541. gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertexArray);
  16542. gl.bindBuffer(gl.ARRAY_BUFFER, this.uvBuffer);
  16543. // now set the uvs..
  16544. this.uvArray[2] = filterArea.width/this.width;
  16545. this.uvArray[5] = filterArea.height/this.height;
  16546. this.uvArray[6] = filterArea.width/this.width;
  16547. this.uvArray[7] = filterArea.height/this.height;
  16548. gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.uvArray);
  16549. var inputTexture = texture;
  16550. var outputTexture = this.texturePool.pop();
  16551. if(!outputTexture)outputTexture = new PIXI.FilterTexture(this.gl, this.width * this.renderSession.resolution, this.height * this.renderSession.resolution);
  16552. outputTexture.resize(this.width * this.renderSession.resolution, this.height * this.renderSession.resolution);
  16553. // need to clear this FBO as it may have some left over elements from a previous filter.
  16554. gl.bindFramebuffer(gl.FRAMEBUFFER, outputTexture.frameBuffer );
  16555. gl.clear(gl.COLOR_BUFFER_BIT);
  16556. gl.disable(gl.BLEND);
  16557. for (var i = 0; i < filterBlock.filterPasses.length-1; i++)
  16558. {
  16559. var filterPass = filterBlock.filterPasses[i];
  16560. gl.bindFramebuffer(gl.FRAMEBUFFER, outputTexture.frameBuffer );
  16561. // set texture
  16562. gl.activeTexture(gl.TEXTURE0);
  16563. gl.bindTexture(gl.TEXTURE_2D, inputTexture.texture);
  16564. // draw texture..
  16565. //filterPass.applyFilterPass(filterArea.width, filterArea.height);
  16566. this.applyFilterPass(filterPass, filterArea, filterArea.width, filterArea.height);
  16567. // swap the textures..
  16568. var temp = inputTexture;
  16569. inputTexture = outputTexture;
  16570. outputTexture = temp;
  16571. }
  16572. gl.enable(gl.BLEND);
  16573. texture = inputTexture;
  16574. this.texturePool.push(outputTexture);
  16575. }
  16576. var filter = filterBlock.filterPasses[filterBlock.filterPasses.length-1];
  16577. this.offsetX -= filterArea.x;
  16578. this.offsetY -= filterArea.y;
  16579. var sizeX = this.width;
  16580. var sizeY = this.height;
  16581. var offsetX = 0;
  16582. var offsetY = 0;
  16583. var buffer = this.buffer;
  16584. // time to render the filters texture to the previous scene
  16585. if(this.filterStack.length === 0)
  16586. {
  16587. gl.colorMask(true, true, true, true);//this.transparent);
  16588. }
  16589. else
  16590. {
  16591. var currentFilter = this.filterStack[this.filterStack.length-1];
  16592. filterArea = currentFilter._filterArea;
  16593. sizeX = filterArea.width;
  16594. sizeY = filterArea.height;
  16595. offsetX = filterArea.x;
  16596. offsetY = filterArea.y;
  16597. buffer = currentFilter._glFilterTexture.frameBuffer;
  16598. }
  16599. // TODO need to remove these global elements..
  16600. projection.x = sizeX/2;
  16601. projection.y = -sizeY/2;
  16602. offset.x = offsetX;
  16603. offset.y = offsetY;
  16604. filterArea = filterBlock._filterArea;
  16605. var x = filterArea.x-offsetX;
  16606. var y = filterArea.y-offsetY;
  16607. // update the buffers..
  16608. // make sure to flip the y!
  16609. gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer);
  16610. this.vertexArray[0] = x;
  16611. this.vertexArray[1] = y + filterArea.height;
  16612. this.vertexArray[2] = x + filterArea.width;
  16613. this.vertexArray[3] = y + filterArea.height;
  16614. this.vertexArray[4] = x;
  16615. this.vertexArray[5] = y;
  16616. this.vertexArray[6] = x + filterArea.width;
  16617. this.vertexArray[7] = y;
  16618. gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertexArray);
  16619. gl.bindBuffer(gl.ARRAY_BUFFER, this.uvBuffer);
  16620. this.uvArray[2] = filterArea.width/this.width;
  16621. this.uvArray[5] = filterArea.height/this.height;
  16622. this.uvArray[6] = filterArea.width/this.width;
  16623. this.uvArray[7] = filterArea.height/this.height;
  16624. gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.uvArray);
  16625. gl.viewport(0, 0, sizeX * this.renderSession.resolution, sizeY * this.renderSession.resolution);
  16626. // bind the buffer
  16627. gl.bindFramebuffer(gl.FRAMEBUFFER, buffer );
  16628. // set the blend mode!
  16629. //gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA)
  16630. // set texture
  16631. gl.activeTexture(gl.TEXTURE0);
  16632. gl.bindTexture(gl.TEXTURE_2D, texture.texture);
  16633. // >>> modify by nextht
  16634. if (this.renderSession.stencilManager) {
  16635. this.renderSession.stencilManager.destroy();
  16636. }
  16637. this.renderSession.stencilManager = filterBlock._previous_stencil_mgr;
  16638. filterBlock._previous_stencil_mgr = null;
  16639. if (this.renderSession.stencilManager.count > 0) {
  16640. gl.enable(gl.STENCIL_TEST);
  16641. }
  16642. else {
  16643. gl.disable(gl.STENCIL_TEST);
  16644. }
  16645. // <<< modify by nextht
  16646. // apply!
  16647. this.applyFilterPass(filter, filterArea, sizeX, sizeY);
  16648. // now restore the regular shader.. should happen automatically now..
  16649. // this.renderSession.shaderManager.setShader(this.defaultShader);
  16650. // gl.uniform2f(this.defaultShader.projectionVector, sizeX/2, -sizeY/2);
  16651. // gl.uniform2f(this.defaultShader.offsetVector, -offsetX, -offsetY);
  16652. // return the texture to the pool
  16653. this.texturePool.push(texture);
  16654. filterBlock._glFilterTexture = null;
  16655. };
  16656. /**
  16657. * Applies the filter to the specified area.
  16658. *
  16659. * @method applyFilterPass
  16660. * @param filter {AbstractFilter} the filter that needs to be applied
  16661. * @param filterArea {Texture} TODO - might need an update
  16662. * @param width {Number} the horizontal range of the filter
  16663. * @param height {Number} the vertical range of the filter
  16664. */
  16665. PIXI.WebGLFilterManager.prototype.applyFilterPass = function(filter, filterArea, width, height)
  16666. {
  16667. // use program
  16668. var gl = this.gl;
  16669. var shader = filter.shaders[gl.id];
  16670. if(!shader)
  16671. {
  16672. shader = new PIXI.PixiShader(gl);
  16673. shader.fragmentSrc = filter.fragmentSrc;
  16674. shader.uniforms = filter.uniforms;
  16675. shader.init();
  16676. filter.shaders[gl.id] = shader;
  16677. }
  16678. // set the shader
  16679. this.renderSession.shaderManager.setShader(shader);
  16680. // gl.useProgram(shader.program);
  16681. gl.uniform2f(shader.projectionVector, width/2, -height/2);
  16682. gl.uniform2f(shader.offsetVector, 0,0);
  16683. if(filter.uniforms.dimensions)
  16684. {
  16685. filter.uniforms.dimensions.value[0] = this.width;//width;
  16686. filter.uniforms.dimensions.value[1] = this.height;//height;
  16687. filter.uniforms.dimensions.value[2] = this.vertexArray[0];
  16688. filter.uniforms.dimensions.value[3] = this.vertexArray[5];//filterArea.height;
  16689. }
  16690. shader.syncUniforms();
  16691. gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer);
  16692. gl.vertexAttribPointer(shader.aVertexPosition, 2, gl.FLOAT, false, 0, 0);
  16693. gl.bindBuffer(gl.ARRAY_BUFFER, this.uvBuffer);
  16694. gl.vertexAttribPointer(shader.aTextureCoord, 2, gl.FLOAT, false, 0, 0);
  16695. gl.bindBuffer(gl.ARRAY_BUFFER, this.colorBuffer);
  16696. gl.vertexAttribPointer(shader.colorAttribute, 2, gl.FLOAT, false, 0, 0);
  16697. gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.indexBuffer);
  16698. // draw the filter...
  16699. gl.drawElements(gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0 );
  16700. this.renderSession.drawCount++;
  16701. };
  16702. /**
  16703. * Initialises the shader buffers.
  16704. *
  16705. * @method initShaderBuffers
  16706. */
  16707. PIXI.WebGLFilterManager.prototype.initShaderBuffers = function()
  16708. {
  16709. var gl = this.gl;
  16710. // create some buffers
  16711. this.vertexBuffer = gl.createBuffer();
  16712. this.uvBuffer = gl.createBuffer();
  16713. this.colorBuffer = gl.createBuffer();
  16714. this.indexBuffer = gl.createBuffer();
  16715. // bind and upload the vertexs..
  16716. // keep a reference to the vertexFloatData..
  16717. this.vertexArray = new PIXI.Float32Array([0.0, 0.0,
  16718. 1.0, 0.0,
  16719. 0.0, 1.0,
  16720. 1.0, 1.0]);
  16721. gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer);
  16722. gl.bufferData(gl.ARRAY_BUFFER, this.vertexArray, gl.STATIC_DRAW);
  16723. // bind and upload the uv buffer
  16724. this.uvArray = new PIXI.Float32Array([0.0, 0.0,
  16725. 1.0, 0.0,
  16726. 0.0, 1.0,
  16727. 1.0, 1.0]);
  16728. gl.bindBuffer(gl.ARRAY_BUFFER, this.uvBuffer);
  16729. gl.bufferData(gl.ARRAY_BUFFER, this.uvArray, gl.STATIC_DRAW);
  16730. this.colorArray = new PIXI.Float32Array([1.0, 0xFFFFFF,
  16731. 1.0, 0xFFFFFF,
  16732. 1.0, 0xFFFFFF,
  16733. 1.0, 0xFFFFFF]);
  16734. gl.bindBuffer(gl.ARRAY_BUFFER, this.colorBuffer);
  16735. gl.bufferData(gl.ARRAY_BUFFER, this.colorArray, gl.STATIC_DRAW);
  16736. // bind and upload the index
  16737. gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.indexBuffer);
  16738. gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array([0, 1, 2, 1, 3, 2]), gl.STATIC_DRAW);
  16739. };
  16740. /**
  16741. * Destroys the filter and removes it from the filter stack.
  16742. *
  16743. * @method destroy
  16744. */
  16745. PIXI.WebGLFilterManager.prototype.destroy = function()
  16746. {
  16747. var gl = this.gl;
  16748. this.filterStack = null;
  16749. this.offsetX = 0;
  16750. this.offsetY = 0;
  16751. // destroy textures
  16752. for (var i = 0; i < this.texturePool.length; i++) {
  16753. this.texturePool[i].destroy();
  16754. }
  16755. this.texturePool = null;
  16756. //destroy buffers..
  16757. gl.deleteBuffer(this.vertexBuffer);
  16758. gl.deleteBuffer(this.uvBuffer);
  16759. gl.deleteBuffer(this.colorBuffer);
  16760. gl.deleteBuffer(this.indexBuffer);
  16761. };
  16762. /**
  16763. * @author Mat Groves http://matgroves.com/ @Doormat23
  16764. */
  16765. /**
  16766. * @class FilterTexture
  16767. * @constructor
  16768. * @param gl {WebGLContext} the current WebGL drawing context
  16769. * @param width {Number} the horizontal range of the filter
  16770. * @param height {Number} the vertical range of the filter
  16771. * @param scaleMode {Number} See {{#crossLink "PIXI/scaleModes:property"}}PIXI.scaleModes{{/crossLink}} for possible values
  16772. */
  16773. PIXI.FilterTexture = function(gl, width, height, scaleMode)
  16774. {
  16775. /**
  16776. * @property gl
  16777. * @type WebGLContext
  16778. */
  16779. this.gl = gl;
  16780. // next time to create a frame buffer and texture
  16781. /**
  16782. * @property frameBuffer
  16783. * @type Any
  16784. */
  16785. this.frameBuffer = gl.createFramebuffer();
  16786. /**
  16787. * @property texture
  16788. * @type Any
  16789. */
  16790. this.texture = gl.createTexture();
  16791. /**
  16792. * @property scaleMode
  16793. * @type Number
  16794. */
  16795. scaleMode = scaleMode || PIXI.scaleModes.DEFAULT;
  16796. gl.bindTexture(gl.TEXTURE_2D, this.texture);
  16797. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, scaleMode === PIXI.scaleModes.LINEAR ? gl.LINEAR : gl.NEAREST);
  16798. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, scaleMode === PIXI.scaleModes.LINEAR ? gl.LINEAR : gl.NEAREST);
  16799. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16800. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16801. gl.bindFramebuffer(gl.FRAMEBUFFER, this.frameBuffer );
  16802. gl.bindFramebuffer(gl.FRAMEBUFFER, this.frameBuffer );
  16803. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, this.texture, 0);
  16804. // required for masking a mask??
  16805. this.renderBuffer = gl.createRenderbuffer();
  16806. gl.bindRenderbuffer(gl.RENDERBUFFER, this.renderBuffer);
  16807. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, this.renderBuffer);
  16808. this.resize(width, height);
  16809. };
  16810. PIXI.FilterTexture.prototype.constructor = PIXI.FilterTexture;
  16811. /**
  16812. * Clears the filter texture.
  16813. *
  16814. * @method clear
  16815. */
  16816. PIXI.FilterTexture.prototype.clear = function()
  16817. {
  16818. var gl = this.gl;
  16819. gl.clearColor(0,0,0, 0);
  16820. gl.clear(gl.COLOR_BUFFER_BIT);
  16821. };
  16822. /**
  16823. * Resizes the texture to the specified width and height
  16824. *
  16825. * @method resize
  16826. * @param width {Number} the new width of the texture
  16827. * @param height {Number} the new height of the texture
  16828. */
  16829. PIXI.FilterTexture.prototype.resize = function(width, height)
  16830. {
  16831. if(this.width === width && this.height === height) return;
  16832. this.width = width;
  16833. this.height = height;
  16834. var gl = this.gl;
  16835. gl.bindTexture(gl.TEXTURE_2D, this.texture);
  16836. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width , height , 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  16837. // update the stencil buffer width and height
  16838. gl.bindRenderbuffer(gl.RENDERBUFFER, this.renderBuffer);
  16839. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width , height );
  16840. };
  16841. /**
  16842. * Destroys the filter texture.
  16843. *
  16844. * @method destroy
  16845. */
  16846. PIXI.FilterTexture.prototype.destroy = function()
  16847. {
  16848. var gl = this.gl;
  16849. gl.deleteFramebuffer( this.frameBuffer );
  16850. gl.deleteTexture( this.texture );
  16851. this.frameBuffer = null;
  16852. this.texture = null;
  16853. };
  16854. /**
  16855. * @author Mat Groves http://matgroves.com/ @Doormat23
  16856. */
  16857. /**
  16858. * Creates a Canvas element of the given size.
  16859. *
  16860. * @class CanvasBuffer
  16861. * @constructor
  16862. * @param width {Number} the width for the newly created canvas
  16863. * @param height {Number} the height for the newly created canvas
  16864. */
  16865. PIXI.CanvasBuffer = function(width, height)
  16866. {
  16867. /**
  16868. * The width of the Canvas in pixels.
  16869. *
  16870. * @property width
  16871. * @type Number
  16872. */
  16873. this.width = width;
  16874. /**
  16875. * The height of the Canvas in pixels.
  16876. *
  16877. * @property height
  16878. * @type Number
  16879. */
  16880. this.height = height;
  16881. /**
  16882. * The Canvas object that belongs to this CanvasBuffer.
  16883. *
  16884. * @property canvas
  16885. * @type HTMLCanvasElement
  16886. */
  16887. this.canvas = PIXI.CanvasPool.create(this, this.width, this.height);
  16888. /**
  16889. * A CanvasRenderingContext2D object representing a two-dimensional rendering context.
  16890. *
  16891. * @property context
  16892. * @type CanvasRenderingContext2D
  16893. */
  16894. this.context = this.canvas.getContext("2d");
  16895. this.canvas.width = width;
  16896. this.canvas.height = height;
  16897. };
  16898. PIXI.CanvasBuffer.prototype.constructor = PIXI.CanvasBuffer;
  16899. /**
  16900. * Clears the canvas that was created by the CanvasBuffer class.
  16901. *
  16902. * @method clear
  16903. * @private
  16904. */
  16905. PIXI.CanvasBuffer.prototype.clear = function()
  16906. {
  16907. this.context.setTransform(1, 0, 0, 1, 0, 0);
  16908. this.context.clearRect(0,0, this.width, this.height);
  16909. };
  16910. /**
  16911. * Resizes the canvas to the specified width and height.
  16912. *
  16913. * @method resize
  16914. * @param width {Number} the new width of the canvas
  16915. * @param height {Number} the new height of the canvas
  16916. */
  16917. PIXI.CanvasBuffer.prototype.resize = function(width, height)
  16918. {
  16919. this.width = this.canvas.width = width;
  16920. this.height = this.canvas.height = height;
  16921. };
  16922. /**
  16923. * Frees the canvas up for use again.
  16924. *
  16925. * @method destroy
  16926. */
  16927. PIXI.CanvasBuffer.prototype.destroy = function()
  16928. {
  16929. PIXI.CanvasPool.remove(this);
  16930. };
  16931. /**
  16932. * @author Mat Groves http://matgroves.com/ @Doormat23
  16933. */
  16934. /**
  16935. * A set of functions used to handle masking.
  16936. *
  16937. * @class CanvasMaskManager
  16938. * @constructor
  16939. */
  16940. PIXI.CanvasMaskManager = function()
  16941. {
  16942. };
  16943. PIXI.CanvasMaskManager.prototype.constructor = PIXI.CanvasMaskManager;
  16944. /**
  16945. * This method adds it to the current stack of masks.
  16946. *
  16947. * @method pushMask
  16948. * @param maskData {Object} the maskData that will be pushed
  16949. * @param renderSession {Object} The renderSession whose context will be used for this mask manager.
  16950. */
  16951. PIXI.CanvasMaskManager.prototype.pushMask = function(maskData, renderSession) {
  16952. var context = renderSession.context;
  16953. context.save();
  16954. var cacheAlpha = maskData.alpha;
  16955. var transform = maskData.worldTransform;
  16956. var resolution = renderSession.resolution;
  16957. context.setTransform(transform.a * resolution,
  16958. transform.b * resolution,
  16959. transform.c * resolution,
  16960. transform.d * resolution,
  16961. transform.tx * resolution,
  16962. transform.ty * resolution);
  16963. PIXI.CanvasGraphics.renderGraphicsMask(maskData, context);
  16964. context.clip();
  16965. maskData.worldAlpha = cacheAlpha;
  16966. };
  16967. /**
  16968. * Restores the current drawing context to the state it was before the mask was applied.
  16969. *
  16970. * @method popMask
  16971. * @param renderSession {Object} The renderSession whose context will be used for this mask manager.
  16972. */
  16973. PIXI.CanvasMaskManager.prototype.popMask = function(renderSession)
  16974. {
  16975. renderSession.context.restore();
  16976. };
  16977. /**
  16978. * @author Mat Groves http://matgroves.com/ @Doormat23
  16979. */
  16980. /**
  16981. * Utility methods for Sprite/Texture tinting.
  16982. *
  16983. * @class CanvasTinter
  16984. * @static
  16985. */
  16986. PIXI.CanvasTinter = function() {};
  16987. /**
  16988. * Basically this method just needs a sprite and a color and tints the sprite with the given color.
  16989. *
  16990. * @method getTintedTexture
  16991. * @static
  16992. * @param sprite {Sprite} the sprite to tint
  16993. * @param color {Number} the color to use to tint the sprite with
  16994. * @return {HTMLCanvasElement} The tinted canvas
  16995. */
  16996. PIXI.CanvasTinter.getTintedTexture = function(sprite, color)
  16997. {
  16998. var canvas = sprite.tintedTexture || PIXI.CanvasPool.create(this);
  16999. PIXI.CanvasTinter.tintMethod(sprite.texture, color, canvas);
  17000. return canvas;
  17001. };
  17002. /**
  17003. * Tint a texture using the "multiply" operation.
  17004. *
  17005. * @method tintWithMultiply
  17006. * @static
  17007. * @param texture {Texture} the texture to tint
  17008. * @param color {Number} the color to use to tint the sprite with
  17009. * @param canvas {HTMLCanvasElement} the current canvas
  17010. */
  17011. PIXI.CanvasTinter.tintWithMultiply = function(texture, color, canvas)
  17012. {
  17013. var context = canvas.getContext("2d");
  17014. var crop = texture.crop;
  17015. if (canvas.width !== crop.width || canvas.height !== crop.height)
  17016. {
  17017. canvas.width = crop.width;
  17018. canvas.height = crop.height;
  17019. }
  17020. context.clearRect(0, 0, crop.width, crop.height);
  17021. context.fillStyle = "#" + ("00000" + (color | 0).toString(16)).substr(-6);
  17022. context.fillRect(0, 0, crop.width, crop.height);
  17023. context.globalCompositeOperation = "multiply";
  17024. context.drawImage(texture.baseTexture.source, crop.x, crop.y, crop.width, crop.height, 0, 0, crop.width, crop.height);
  17025. context.globalCompositeOperation = "destination-atop";
  17026. context.drawImage(texture.baseTexture.source, crop.x, crop.y, crop.width, crop.height, 0, 0, crop.width, crop.height);
  17027. };
  17028. /**
  17029. * Tint a texture pixel per pixel.
  17030. *
  17031. * @method tintPerPixel
  17032. * @static
  17033. * @param texture {Texture} the texture to tint
  17034. * @param color {Number} the color to use to tint the sprite with
  17035. * @param canvas {HTMLCanvasElement} the current canvas
  17036. */
  17037. PIXI.CanvasTinter.tintWithPerPixel = function(texture, color, canvas)
  17038. {
  17039. var context = canvas.getContext("2d");
  17040. var crop = texture.crop;
  17041. canvas.width = crop.width;
  17042. canvas.height = crop.height;
  17043. context.globalCompositeOperation = "copy";
  17044. context.drawImage(texture.baseTexture.source, crop.x, crop.y, crop.width, crop.height, 0, 0, crop.width, crop.height);
  17045. var rgbValues = PIXI.hex2rgb(color);
  17046. var r = rgbValues[0], g = rgbValues[1], b = rgbValues[2];
  17047. var pixelData = context.getImageData(0, 0, crop.width, crop.height);
  17048. var pixels = pixelData.data;
  17049. for (var i = 0; i < pixels.length; i += 4)
  17050. {
  17051. pixels[i + 0] *= r;
  17052. pixels[i + 1] *= g;
  17053. pixels[i + 2] *= b;
  17054. if (!PIXI.CanvasTinter.canHandleAlpha)
  17055. {
  17056. var alpha = pixels[i + 3];
  17057. pixels[i + 0] /= 255 / alpha;
  17058. pixels[i + 1] /= 255 / alpha;
  17059. pixels[i + 2] /= 255 / alpha;
  17060. }
  17061. }
  17062. context.putImageData(pixelData, 0, 0);
  17063. };
  17064. /**
  17065. * Checks if the browser correctly supports putImageData alpha channels.
  17066. *
  17067. * @method checkInverseAlpha
  17068. * @static
  17069. */
  17070. PIXI.CanvasTinter.checkInverseAlpha = function()
  17071. {
  17072. var canvas = new PIXI.CanvasBuffer(2, 1);
  17073. canvas.context.fillStyle = "rgba(10, 20, 30, 0.5)";
  17074. // Draw a single pixel
  17075. canvas.context.fillRect(0, 0, 1, 1);
  17076. // Get the color values
  17077. var s1 = canvas.context.getImageData(0, 0, 1, 1);
  17078. if (s1 === null)
  17079. {
  17080. return false;
  17081. }
  17082. // Plot them to x2
  17083. canvas.context.putImageData(s1, 1, 0);
  17084. // Get those values
  17085. var s2 = canvas.context.getImageData(1, 0, 1, 1);
  17086. // Compare and return
  17087. return (s2.data[0] === s1.data[0] && s2.data[1] === s1.data[1] && s2.data[2] === s1.data[2] && s2.data[3] === s1.data[3]);
  17088. };
  17089. /**
  17090. * If the browser isn't capable of handling tinting with alpha this will be false.
  17091. * This property is only applicable if using tintWithPerPixel.
  17092. *
  17093. * @property canHandleAlpha
  17094. * @type Boolean
  17095. * @static
  17096. */
  17097. PIXI.CanvasTinter.canHandleAlpha = PIXI.CanvasTinter.checkInverseAlpha();
  17098. /**
  17099. * Whether or not the Canvas BlendModes are supported, consequently the ability to tint using the multiply method.
  17100. *
  17101. * @property canUseMultiply
  17102. * @type Boolean
  17103. * @static
  17104. */
  17105. PIXI.CanvasTinter.canUseMultiply = PIXI.canUseNewCanvasBlendModes();
  17106. /**
  17107. * The tinting method that will be used.
  17108. *
  17109. * @method tintMethod
  17110. * @static
  17111. */
  17112. PIXI.CanvasTinter.tintMethod = PIXI.CanvasTinter.canUseMultiply ? PIXI.CanvasTinter.tintWithMultiply : PIXI.CanvasTinter.tintWithPerPixel;
  17113. /**
  17114. * @author Mat Groves http://matgroves.com/ @Doormat23
  17115. */
  17116. /**
  17117. * The CanvasRenderer draws the Stage and all its content onto a 2d canvas. This renderer should be used for browsers that do not support webGL.
  17118. * Don't forget to add the CanvasRenderer.view to your DOM or you will not see anything :)
  17119. *
  17120. * @class CanvasRenderer
  17121. * @constructor
  17122. * @param game {Phaser.Game} A reference to the Phaser Game instance
  17123. */
  17124. PIXI.CanvasRenderer = function (game) {
  17125. /**
  17126. * @property {Phaser.Game} game - A reference to the Phaser Game instance.
  17127. */
  17128. this.game = game;
  17129. if (!PIXI.defaultRenderer)
  17130. {
  17131. PIXI.defaultRenderer = this;
  17132. }
  17133. /**
  17134. * The renderer type.
  17135. *
  17136. * @property type
  17137. * @type Number
  17138. */
  17139. this.type = PIXI.CANVAS_RENDERER;
  17140. /**
  17141. * The resolution of the canvas.
  17142. *
  17143. * @property resolution
  17144. * @type Number
  17145. */
  17146. this.resolution = game.resolution;
  17147. /**
  17148. * This sets if the CanvasRenderer will clear the canvas or not before the new render pass.
  17149. * If the Stage is NOT transparent Pixi will use a canvas sized fillRect operation every frame to set the canvas background color.
  17150. * If the Stage is transparent Pixi will use clearRect to clear the canvas every frame.
  17151. * Disable this by setting this to false. For example if your game has a canvas filling background image you often don't need this set.
  17152. *
  17153. * @property clearBeforeRender
  17154. * @type Boolean
  17155. * @default
  17156. */
  17157. this.clearBeforeRender = game.clearBeforeRender;
  17158. /**
  17159. * Whether the render view is transparent
  17160. *
  17161. * @property transparent
  17162. * @type Boolean
  17163. */
  17164. this.transparent = game.transparent;
  17165. /**
  17166. * Whether the render view should be resized automatically
  17167. *
  17168. * @property autoResize
  17169. * @type Boolean
  17170. */
  17171. this.autoResize = false;
  17172. /**
  17173. * The width of the canvas view
  17174. *
  17175. * @property width
  17176. * @type Number
  17177. * @default 800
  17178. */
  17179. this.width = game.width * this.resolution;
  17180. /**
  17181. * The height of the canvas view
  17182. *
  17183. * @property height
  17184. * @type Number
  17185. * @default 600
  17186. */
  17187. this.height = game.height * this.resolution;
  17188. /**
  17189. * The canvas element that everything is drawn to.
  17190. *
  17191. * @property view
  17192. * @type HTMLCanvasElement
  17193. */
  17194. this.view = game.canvas;
  17195. /**
  17196. * The canvas 2d context that everything is drawn with
  17197. * @property context
  17198. * @type CanvasRenderingContext2D
  17199. */
  17200. this.context = this.view.getContext("2d", { alpha: this.transparent } );
  17201. /**
  17202. * Boolean flag controlling canvas refresh.
  17203. *
  17204. * @property refresh
  17205. * @type Boolean
  17206. */
  17207. this.refresh = true;
  17208. /**
  17209. * Internal var.
  17210. *
  17211. * @property count
  17212. * @type Number
  17213. */
  17214. this.count = 0;
  17215. /**
  17216. * Instance of a PIXI.CanvasMaskManager, handles masking when using the canvas renderer
  17217. * @property CanvasMaskManager
  17218. * @type CanvasMaskManager
  17219. */
  17220. this.maskManager = new PIXI.CanvasMaskManager();
  17221. /**
  17222. * The render session is just a bunch of parameter used for rendering
  17223. * @property renderSession
  17224. * @type Object
  17225. */
  17226. this.renderSession = {
  17227. context: this.context,
  17228. maskManager: this.maskManager,
  17229. scaleMode: null,
  17230. smoothProperty: Phaser.Canvas.getSmoothingPrefix(this.context),
  17231. /**
  17232. * If true Pixi will Math.floor() x/y values when rendering, stopping pixel interpolation.
  17233. * Handy for crisp pixel art and speed on legacy devices.
  17234. */
  17235. roundPixels: false
  17236. };
  17237. this.mapBlendModes();
  17238. this.resize(this.width, this.height);
  17239. };
  17240. // constructor
  17241. PIXI.CanvasRenderer.prototype.constructor = PIXI.CanvasRenderer;
  17242. /**
  17243. * Renders the DisplayObjectContainer, usually the Phaser.Stage, to this canvas view.
  17244. *
  17245. * @method render
  17246. * @param root {Phaser.Stage|PIXI.DisplayObjectContainer} The root element to be rendered.
  17247. */
  17248. PIXI.CanvasRenderer.prototype.render = function (root) {
  17249. this.context.setTransform(1, 0, 0, 1, 0, 0);
  17250. this.context.globalAlpha = 1;
  17251. this.renderSession.currentBlendMode = 0;
  17252. this.renderSession.shakeX = this.game.camera._shake.x;
  17253. this.renderSession.shakeY = this.game.camera._shake.y;
  17254. this.context.globalCompositeOperation = 'source-over';
  17255. if (navigator.isCocoonJS && this.view.screencanvas)
  17256. {
  17257. this.context.fillStyle = "black";
  17258. this.context.clear();
  17259. }
  17260. if (this.clearBeforeRender)
  17261. {
  17262. if (this.transparent)
  17263. {
  17264. this.context.clearRect(0, 0, this.width, this.height);
  17265. }
  17266. else if (root._bgColor)
  17267. {
  17268. this.context.fillStyle = root._bgColor.rgba;
  17269. this.context.fillRect(0, 0, this.width , this.height);
  17270. }
  17271. }
  17272. this.renderDisplayObject(root);
  17273. };
  17274. /**
  17275. * Removes everything from the renderer and optionally removes the Canvas DOM element.
  17276. *
  17277. * @method destroy
  17278. * @param [removeView=true] {boolean} Removes the Canvas element from the DOM.
  17279. */
  17280. PIXI.CanvasRenderer.prototype.destroy = function (removeView) {
  17281. if (removeView === undefined) { removeView = true; }
  17282. if (removeView && this.view.parent)
  17283. {
  17284. this.view.parent.removeChild(this.view);
  17285. }
  17286. this.view = null;
  17287. this.context = null;
  17288. this.maskManager = null;
  17289. this.renderSession = null;
  17290. };
  17291. /**
  17292. * Resizes the canvas view to the specified width and height
  17293. *
  17294. * @method resize
  17295. * @param width {Number} the new width of the canvas view
  17296. * @param height {Number} the new height of the canvas view
  17297. */
  17298. PIXI.CanvasRenderer.prototype.resize = function (width, height) {
  17299. this.width = width * this.resolution;
  17300. this.height = height * this.resolution;
  17301. this.view.width = this.width;
  17302. this.view.height = this.height;
  17303. if (this.autoResize)
  17304. {
  17305. this.view.style.width = this.width / this.resolution + "px";
  17306. this.view.style.height = this.height / this.resolution + "px";
  17307. }
  17308. if (this.renderSession.smoothProperty)
  17309. {
  17310. this.context[this.renderSession.smoothProperty] = (this.renderSession.scaleMode === PIXI.scaleModes.LINEAR);
  17311. }
  17312. };
  17313. /**
  17314. * Renders a display object
  17315. *
  17316. * @method renderDisplayObject
  17317. * @param displayObject {DisplayObject} The displayObject to render
  17318. * @param context {CanvasRenderingContext2D} the context 2d method of the canvas
  17319. * @param [matrix] {Matrix} Optional matrix to apply to the display object before rendering.
  17320. * @private
  17321. */
  17322. PIXI.CanvasRenderer.prototype.renderDisplayObject = function (displayObject, context, matrix) {
  17323. this.renderSession.context = context || this.context;
  17324. this.renderSession.resolution = this.resolution;
  17325. displayObject._renderCanvas(this.renderSession, matrix);
  17326. };
  17327. /**
  17328. * Maps Pixi blend modes to canvas blend modes.
  17329. *
  17330. * @method mapBlendModes
  17331. * @private
  17332. */
  17333. PIXI.CanvasRenderer.prototype.mapBlendModes = function () {
  17334. if (!PIXI.blendModesCanvas)
  17335. {
  17336. var b = [];
  17337. var modes = PIXI.blendModes;
  17338. var useNew = PIXI.canUseNewCanvasBlendModes();
  17339. b[modes.NORMAL] = 'source-over';
  17340. b[modes.ADD] = 'lighter';
  17341. b[modes.MULTIPLY] = (useNew) ? 'multiply' : 'source-over';
  17342. b[modes.SCREEN] = (useNew) ? 'screen' : 'source-over';
  17343. b[modes.OVERLAY] = (useNew) ? 'overlay' : 'source-over';
  17344. b[modes.DARKEN] = (useNew) ? 'darken' : 'source-over';
  17345. b[modes.LIGHTEN] = (useNew) ? 'lighten' : 'source-over';
  17346. b[modes.COLOR_DODGE] = (useNew) ? 'color-dodge' : 'source-over';
  17347. b[modes.COLOR_BURN] = (useNew) ? 'color-burn' : 'source-over';
  17348. b[modes.HARD_LIGHT] = (useNew) ? 'hard-light' : 'source-over';
  17349. b[modes.SOFT_LIGHT] = (useNew) ? 'soft-light' : 'source-over';
  17350. b[modes.DIFFERENCE] = (useNew) ? 'difference' : 'source-over';
  17351. b[modes.EXCLUSION] = (useNew) ? 'exclusion' : 'source-over';
  17352. b[modes.HUE] = (useNew) ? 'hue' : 'source-over';
  17353. b[modes.SATURATION] = (useNew) ? 'saturation' : 'source-over';
  17354. b[modes.COLOR] = (useNew) ? 'color' : 'source-over';
  17355. b[modes.LUMINOSITY] = (useNew) ? 'luminosity' : 'source-over';
  17356. PIXI.blendModesCanvas = b;
  17357. }
  17358. };
  17359. /**
  17360. * @author Mat Groves http://matgroves.com/ @Doormat23
  17361. */
  17362. /**
  17363. * A texture stores the information that represents an image. All textures have a base texture.
  17364. *
  17365. * @class BaseTexture
  17366. * @uses EventTarget
  17367. * @constructor
  17368. * @param source {String|Canvas} the source object (image or canvas)
  17369. * @param scaleMode {Number} See {{#crossLink "PIXI/scaleModes:property"}}PIXI.scaleModes{{/crossLink}} for possible values
  17370. */
  17371. PIXI.BaseTexture = function(source, scaleMode)
  17372. {
  17373. /**
  17374. * The Resolution of the texture.
  17375. *
  17376. * @property resolution
  17377. * @type Number
  17378. */
  17379. this.resolution = 1;
  17380. /**
  17381. * [read-only] The width of the base texture set when the image has loaded
  17382. *
  17383. * @property width
  17384. * @type Number
  17385. * @readOnly
  17386. */
  17387. this.width = 100;
  17388. /**
  17389. * [read-only] The height of the base texture set when the image has loaded
  17390. *
  17391. * @property height
  17392. * @type Number
  17393. * @readOnly
  17394. */
  17395. this.height = 100;
  17396. /**
  17397. * The scale mode to apply when scaling this texture
  17398. *
  17399. * @property scaleMode
  17400. * @type {Number}
  17401. * @default PIXI.scaleModes.LINEAR
  17402. */
  17403. this.scaleMode = scaleMode || PIXI.scaleModes.DEFAULT;
  17404. /**
  17405. * [read-only] Set to true once the base texture has loaded
  17406. *
  17407. * @property hasLoaded
  17408. * @type Boolean
  17409. * @readOnly
  17410. */
  17411. this.hasLoaded = false;
  17412. /**
  17413. * The image source that is used to create the texture.
  17414. *
  17415. * @property source
  17416. * @type Image
  17417. */
  17418. this.source = source;
  17419. /**
  17420. * Controls if RGB channels should be pre-multiplied by Alpha (WebGL only)
  17421. *
  17422. * @property premultipliedAlpha
  17423. * @type Boolean
  17424. * @default true
  17425. */
  17426. this.premultipliedAlpha = true;
  17427. // used for webGL
  17428. /**
  17429. * @property _glTextures
  17430. * @type Array
  17431. * @private
  17432. */
  17433. this._glTextures = [];
  17434. /**
  17435. * Set this to true if a mipmap of this texture needs to be generated. This value needs to be set before the texture is used
  17436. * Also the texture must be a power of two size to work
  17437. *
  17438. * @property mipmap
  17439. * @type {Boolean}
  17440. */
  17441. this.mipmap = false;
  17442. /**
  17443. * @property _dirty
  17444. * @type Array
  17445. * @private
  17446. */
  17447. this._dirty = [true, true, true, true];
  17448. if (!source)
  17449. {
  17450. return;
  17451. }
  17452. if ((this.source.complete || this.source.getContext) && this.source.width && this.source.height)
  17453. {
  17454. this.hasLoaded = true;
  17455. this.width = this.source.naturalWidth || this.source.width;
  17456. this.height = this.source.naturalHeight || this.source.height;
  17457. this.dirty();
  17458. }
  17459. /**
  17460. * A BaseTexture can be set to skip the rendering phase in the WebGL Sprite Batch.
  17461. *
  17462. * You may want to do this if you have a parent Sprite with no visible texture (i.e. uses the internal `__default` texture)
  17463. * that has children that you do want to render, without causing a batch flush in the process.
  17464. *
  17465. * @property skipRender
  17466. * @type Boolean
  17467. */
  17468. this.skipRender = false;
  17469. /**
  17470. * @property _powerOf2
  17471. * @type Boolean
  17472. * @private
  17473. */
  17474. this._powerOf2 = false;
  17475. };
  17476. PIXI.BaseTexture.prototype.constructor = PIXI.BaseTexture;
  17477. /**
  17478. * Forces this BaseTexture to be set as loaded, with the given width and height.
  17479. * Then calls BaseTexture.dirty.
  17480. * Important for when you don't want to modify the source object by forcing in `complete` or dimension properties it may not have.
  17481. *
  17482. * @method forceLoaded
  17483. * @param {number} width - The new width to force the BaseTexture to be.
  17484. * @param {number} height - The new height to force the BaseTexture to be.
  17485. */
  17486. PIXI.BaseTexture.prototype.forceLoaded = function(width, height)
  17487. {
  17488. this.hasLoaded = true;
  17489. this.width = width;
  17490. this.height = height;
  17491. this.dirty();
  17492. };
  17493. /**
  17494. * Destroys this base texture
  17495. *
  17496. * @method destroy
  17497. */
  17498. PIXI.BaseTexture.prototype.destroy = function()
  17499. {
  17500. if (this.source)
  17501. {
  17502. PIXI.CanvasPool.removeByCanvas(this.source);
  17503. }
  17504. this.source = null;
  17505. this.unloadFromGPU();
  17506. };
  17507. /**
  17508. * Changes the source image of the texture
  17509. *
  17510. * @method updateSourceImage
  17511. * @param newSrc {String} the path of the image
  17512. * @deprecated This method is deprecated. Please use Phaser.Sprite.loadTexture instead.
  17513. */
  17514. PIXI.BaseTexture.prototype.updateSourceImage = function(newSrc)
  17515. {
  17516. console.warn("PIXI.BaseTexture.updateSourceImage is deprecated. Use Phaser.Sprite.loadTexture instead.");
  17517. };
  17518. /**
  17519. * Sets all glTextures to be dirty.
  17520. *
  17521. * @method dirty
  17522. */
  17523. PIXI.BaseTexture.prototype.dirty = function()
  17524. {
  17525. for (var i = 0; i < this._glTextures.length; i++)
  17526. {
  17527. this._dirty[i] = true;
  17528. }
  17529. };
  17530. /**
  17531. * Removes the base texture from the GPU, useful for managing resources on the GPU.
  17532. * Atexture is still 100% usable and will simply be reuploaded if there is a sprite on screen that is using it.
  17533. *
  17534. * @method unloadFromGPU
  17535. */
  17536. PIXI.BaseTexture.prototype.unloadFromGPU = function()
  17537. {
  17538. this.dirty();
  17539. // delete the webGL textures if any.
  17540. for (var i = this._glTextures.length - 1; i >= 0; i--)
  17541. {
  17542. var glTexture = this._glTextures[i];
  17543. var gl = PIXI.glContexts[i];
  17544. if(gl && glTexture)
  17545. {
  17546. gl.deleteTexture(glTexture);
  17547. }
  17548. }
  17549. this._glTextures.length = 0;
  17550. this.dirty();
  17551. };
  17552. /**
  17553. * Helper function that creates a base texture from the given canvas element.
  17554. *
  17555. * @static
  17556. * @method fromCanvas
  17557. * @param canvas {Canvas} The canvas element source of the texture
  17558. * @param scaleMode {Number} See {{#crossLink "PIXI/scaleModes:property"}}PIXI.scaleModes{{/crossLink}} for possible values
  17559. * @return {BaseTexture}
  17560. */
  17561. PIXI.BaseTexture.fromCanvas = function(canvas, scaleMode)
  17562. {
  17563. if (canvas.width === 0)
  17564. {
  17565. canvas.width = 1;
  17566. }
  17567. if (canvas.height === 0)
  17568. {
  17569. canvas.height = 1;
  17570. }
  17571. return new PIXI.BaseTexture(canvas, scaleMode);
  17572. };
  17573. /**
  17574. * @author Mat Groves http://matgroves.com/ @Doormat23
  17575. */
  17576. /**
  17577. * TextureSilentFail is a boolean that defaults to `false`.
  17578. * If `true` then `PIXI.Texture.setFrame` will no longer throw an error if the texture dimensions are incorrect.
  17579. * Instead `Texture.valid` will be set to `false` (#1556)
  17580. *
  17581. * @type {boolean}
  17582. */
  17583. PIXI.TextureSilentFail = false;
  17584. /**
  17585. * A texture stores the information that represents an image or part of an image. It cannot be added
  17586. * to the display list directly. Instead use it as the texture for a PIXI.Sprite. If no frame is provided then the whole image is used.
  17587. *
  17588. * @class Texture
  17589. * @uses EventTarget
  17590. * @constructor
  17591. * @param baseTexture {BaseTexture} The base texture source to create the texture from
  17592. * @param frame {Rectangle} The rectangle frame of the texture to show
  17593. * @param [crop] {Rectangle} The area of original texture
  17594. * @param [trim] {Rectangle} Trimmed texture rectangle
  17595. */
  17596. PIXI.Texture = function(baseTexture, frame, crop, trim)
  17597. {
  17598. /**
  17599. * Does this Texture have any frame data assigned to it?
  17600. *
  17601. * @property noFrame
  17602. * @type Boolean
  17603. */
  17604. this.noFrame = false;
  17605. if (!frame)
  17606. {
  17607. this.noFrame = true;
  17608. frame = new PIXI.Rectangle(0,0,1,1);
  17609. }
  17610. if (baseTexture instanceof PIXI.Texture)
  17611. {
  17612. baseTexture = baseTexture.baseTexture;
  17613. }
  17614. /**
  17615. * The base texture that this texture uses.
  17616. *
  17617. * @property baseTexture
  17618. * @type BaseTexture
  17619. */
  17620. this.baseTexture = baseTexture;
  17621. /**
  17622. * The frame specifies the region of the base texture that this texture uses
  17623. *
  17624. * @property frame
  17625. * @type Rectangle
  17626. */
  17627. this.frame = frame;
  17628. /**
  17629. * The texture trim data.
  17630. *
  17631. * @property trim
  17632. * @type Rectangle
  17633. */
  17634. this.trim = trim;
  17635. /**
  17636. * This will let the renderer know if the texture is valid. If it's not then it cannot be rendered.
  17637. *
  17638. * @property valid
  17639. * @type Boolean
  17640. */
  17641. this.valid = false;
  17642. /**
  17643. * Is this a tiling texture? As used by the likes of a TilingSprite.
  17644. *
  17645. * @property isTiling
  17646. * @type Boolean
  17647. */
  17648. this.isTiling = false;
  17649. /**
  17650. * This will let a renderer know that a texture has been updated (used mainly for webGL uv updates)
  17651. *
  17652. * @property requiresUpdate
  17653. * @type Boolean
  17654. */
  17655. this.requiresUpdate = false;
  17656. /**
  17657. * This will let a renderer know that a tinted parent has updated its texture.
  17658. *
  17659. * @property requiresReTint
  17660. * @type Boolean
  17661. */
  17662. this.requiresReTint = false;
  17663. /**
  17664. * The WebGL UV data cache.
  17665. *
  17666. * @property _uvs
  17667. * @type Object
  17668. * @private
  17669. */
  17670. this._uvs = null;
  17671. /**
  17672. * The width of the Texture in pixels.
  17673. *
  17674. * @property width
  17675. * @type Number
  17676. */
  17677. this.width = 0;
  17678. /**
  17679. * The height of the Texture in pixels.
  17680. *
  17681. * @property height
  17682. * @type Number
  17683. */
  17684. this.height = 0;
  17685. /**
  17686. * This is the area of the BaseTexture image to actually copy to the Canvas / WebGL when rendering,
  17687. * irrespective of the actual frame size or placement (which can be influenced by trimmed texture atlases)
  17688. *
  17689. * @property crop
  17690. * @type Rectangle
  17691. */
  17692. this.crop = crop || new PIXI.Rectangle(0, 0, 1, 1);
  17693. if (baseTexture.hasLoaded)
  17694. {
  17695. if (this.noFrame) frame = new PIXI.Rectangle(0, 0, baseTexture.width, baseTexture.height);
  17696. this.setFrame(frame);
  17697. }
  17698. };
  17699. PIXI.Texture.prototype.constructor = PIXI.Texture;
  17700. /**
  17701. * Called when the base texture is loaded
  17702. *
  17703. * @method onBaseTextureLoaded
  17704. * @private
  17705. */
  17706. PIXI.Texture.prototype.onBaseTextureLoaded = function()
  17707. {
  17708. var baseTexture = this.baseTexture;
  17709. if (this.noFrame)
  17710. {
  17711. this.frame = new PIXI.Rectangle(0, 0, baseTexture.width, baseTexture.height);
  17712. }
  17713. this.setFrame(this.frame);
  17714. };
  17715. /**
  17716. * Destroys this texture
  17717. *
  17718. * @method destroy
  17719. * @param destroyBase {Boolean} Whether to destroy the base texture as well
  17720. */
  17721. PIXI.Texture.prototype.destroy = function(destroyBase)
  17722. {
  17723. if (destroyBase) this.baseTexture.destroy();
  17724. this.valid = false;
  17725. };
  17726. /**
  17727. * Specifies the region of the baseTexture that this texture will use.
  17728. *
  17729. * @method setFrame
  17730. * @param frame {Rectangle} The frame of the texture to set it to
  17731. */
  17732. PIXI.Texture.prototype.setFrame = function(frame)
  17733. {
  17734. this.noFrame = false;
  17735. this.frame = frame;
  17736. this.width = frame.width;
  17737. this.height = frame.height;
  17738. this.crop.x = frame.x;
  17739. this.crop.y = frame.y;
  17740. this.crop.width = frame.width;
  17741. this.crop.height = frame.height;
  17742. if (!this.trim && (frame.x + frame.width > this.baseTexture.width || frame.y + frame.height > this.baseTexture.height))
  17743. {
  17744. if (!PIXI.TextureSilentFail)
  17745. {
  17746. throw new Error('Texture Error: frame does not fit inside the base Texture dimensions ' + this);
  17747. }
  17748. this.valid = false;
  17749. return;
  17750. }
  17751. this.valid = frame && frame.width && frame.height && this.baseTexture.source && this.baseTexture.hasLoaded;
  17752. if (this.trim)
  17753. {
  17754. this.width = this.trim.width;
  17755. this.height = this.trim.height;
  17756. this.frame.width = this.trim.width;
  17757. this.frame.height = this.trim.height;
  17758. }
  17759. if (this.valid) this._updateUvs();
  17760. };
  17761. /**
  17762. * Updates the internal WebGL UV cache.
  17763. *
  17764. * @method _updateUvs
  17765. * @private
  17766. */
  17767. PIXI.Texture.prototype._updateUvs = function()
  17768. {
  17769. if(!this._uvs)this._uvs = new PIXI.TextureUvs();
  17770. var frame = this.crop;
  17771. var tw = this.baseTexture.width;
  17772. var th = this.baseTexture.height;
  17773. this._uvs.x0 = frame.x / tw;
  17774. this._uvs.y0 = frame.y / th;
  17775. this._uvs.x1 = (frame.x + frame.width) / tw;
  17776. this._uvs.y1 = frame.y / th;
  17777. this._uvs.x2 = (frame.x + frame.width) / tw;
  17778. this._uvs.y2 = (frame.y + frame.height) / th;
  17779. this._uvs.x3 = frame.x / tw;
  17780. this._uvs.y3 = (frame.y + frame.height) / th;
  17781. };
  17782. /**
  17783. * Helper function that creates a new a Texture based on the given canvas element.
  17784. *
  17785. * @static
  17786. * @method fromCanvas
  17787. * @param canvas {Canvas} The canvas element source of the texture
  17788. * @param scaleMode {Number} See {{#crossLink "PIXI/scaleModes:property"}}PIXI.scaleModes{{/crossLink}} for possible values
  17789. * @return {Texture}
  17790. */
  17791. PIXI.Texture.fromCanvas = function(canvas, scaleMode)
  17792. {
  17793. var baseTexture = PIXI.BaseTexture.fromCanvas(canvas, scaleMode);
  17794. return new PIXI.Texture(baseTexture);
  17795. };
  17796. PIXI.TextureUvs = function()
  17797. {
  17798. this.x0 = 0;
  17799. this.y0 = 0;
  17800. this.x1 = 0;
  17801. this.y1 = 0;
  17802. this.x2 = 0;
  17803. this.y2 = 0;
  17804. this.x3 = 0;
  17805. this.y3 = 0;
  17806. };
  17807. /**
  17808. * @author Mat Groves http://matgroves.com/ @Doormat23
  17809. */
  17810. /**
  17811. * A RenderTexture is a special texture that allows any Pixi display object to be rendered to it.
  17812. *
  17813. * __Hint__: All DisplayObjects (i.e. Sprites) that render to a RenderTexture should be preloaded otherwise black rectangles will be drawn instead.
  17814. *
  17815. * A RenderTexture takes a snapshot of any Display Object given to its render method. The position and rotation of the given Display Objects is ignored. For example:
  17816. *
  17817. * var renderTexture = new PIXI.RenderTexture(800, 600);
  17818. * var sprite = PIXI.Sprite.fromImage("spinObj_01.png");
  17819. * sprite.position.x = 800/2;
  17820. * sprite.position.y = 600/2;
  17821. * sprite.anchor.x = 0.5;
  17822. * sprite.anchor.y = 0.5;
  17823. * renderTexture.render(sprite);
  17824. *
  17825. * The Sprite in this case will be rendered to a position of 0,0. To render this sprite at its actual position a DisplayObjectContainer should be used:
  17826. *
  17827. * var doc = new PIXI.DisplayObjectContainer();
  17828. * doc.addChild(sprite);
  17829. * renderTexture.render(doc); // Renders to center of renderTexture
  17830. *
  17831. * @class RenderTexture
  17832. * @extends Texture
  17833. * @constructor
  17834. * @param width {Number} The width of the render texture
  17835. * @param height {Number} The height of the render texture
  17836. * @param renderer {CanvasRenderer|WebGLRenderer} The renderer used for this RenderTexture
  17837. * @param scaleMode {Number} See {{#crossLink "PIXI/scaleModes:property"}}PIXI.scaleModes{{/crossLink}} for possible values
  17838. * @param resolution {Number} The resolution of the texture being generated
  17839. */
  17840. PIXI.RenderTexture = function(width, height, renderer, scaleMode, resolution)
  17841. {
  17842. /**
  17843. * The with of the render texture
  17844. *
  17845. * @property width
  17846. * @type Number
  17847. */
  17848. this.width = width || 100;
  17849. /**
  17850. * The height of the render texture
  17851. *
  17852. * @property height
  17853. * @type Number
  17854. */
  17855. this.height = height || 100;
  17856. /**
  17857. * The Resolution of the texture.
  17858. *
  17859. * @property resolution
  17860. * @type Number
  17861. */
  17862. this.resolution = resolution || 1;
  17863. /**
  17864. * The framing rectangle of the render texture
  17865. *
  17866. * @property frame
  17867. * @type Rectangle
  17868. */
  17869. this.frame = new PIXI.Rectangle(0, 0, this.width * this.resolution, this.height * this.resolution);
  17870. /**
  17871. * This is the area of the BaseTexture image to actually copy to the Canvas / WebGL when rendering,
  17872. * irrespective of the actual frame size or placement (which can be influenced by trimmed texture atlases)
  17873. *
  17874. * @property crop
  17875. * @type Rectangle
  17876. */
  17877. this.crop = new PIXI.Rectangle(0, 0, this.width * this.resolution, this.height * this.resolution);
  17878. /**
  17879. * The base texture object that this texture uses
  17880. *
  17881. * @property baseTexture
  17882. * @type BaseTexture
  17883. */
  17884. this.baseTexture = new PIXI.BaseTexture();
  17885. this.baseTexture.width = this.width * this.resolution;
  17886. this.baseTexture.height = this.height * this.resolution;
  17887. this.baseTexture._glTextures = [];
  17888. this.baseTexture.resolution = this.resolution;
  17889. this.baseTexture.scaleMode = scaleMode || PIXI.scaleModes.DEFAULT;
  17890. this.baseTexture.hasLoaded = true;
  17891. PIXI.Texture.call(this,
  17892. this.baseTexture,
  17893. new PIXI.Rectangle(0, 0, this.width * this.resolution, this.height * this.resolution)
  17894. );
  17895. /**
  17896. * The renderer this RenderTexture uses. A RenderTexture can only belong to one renderer at the moment if its webGL.
  17897. *
  17898. * @property renderer
  17899. * @type CanvasRenderer|WebGLRenderer
  17900. */
  17901. this.renderer = renderer || PIXI.defaultRenderer;
  17902. if (this.renderer.type === PIXI.WEBGL_RENDERER)
  17903. {
  17904. var gl = this.renderer.gl;
  17905. this.baseTexture._dirty[gl.id] = false;
  17906. this.textureBuffer = new PIXI.FilterTexture(gl, this.width, this.height, this.baseTexture.scaleMode);
  17907. this.baseTexture._glTextures[gl.id] = this.textureBuffer.texture;
  17908. this.render = this.renderWebGL;
  17909. this.projection = new PIXI.Point(this.width * 0.5, -this.height * 0.5);
  17910. }
  17911. else
  17912. {
  17913. this.render = this.renderCanvas;
  17914. this.textureBuffer = new PIXI.CanvasBuffer(this.width * this.resolution, this.height * this.resolution);
  17915. this.baseTexture.source = this.textureBuffer.canvas;
  17916. }
  17917. /**
  17918. * @property valid
  17919. * @type Boolean
  17920. */
  17921. this.valid = true;
  17922. this.tempMatrix = new Phaser.Matrix();
  17923. this._updateUvs();
  17924. };
  17925. PIXI.RenderTexture.prototype = Object.create(PIXI.Texture.prototype);
  17926. PIXI.RenderTexture.prototype.constructor = PIXI.RenderTexture;
  17927. /**
  17928. * Resizes the RenderTexture.
  17929. *
  17930. * @method resize
  17931. * @param width {Number} The width to resize to.
  17932. * @param height {Number} The height to resize to.
  17933. * @param updateBase {Boolean} Should the baseTexture.width and height values be resized as well?
  17934. */
  17935. PIXI.RenderTexture.prototype.resize = function(width, height, updateBase)
  17936. {
  17937. if (width === this.width && height === this.height)return;
  17938. this.valid = (width > 0 && height > 0);
  17939. this.width = width;
  17940. this.height = height;
  17941. this.frame.width = this.crop.width = width * this.resolution;
  17942. this.frame.height = this.crop.height = height * this.resolution;
  17943. if (updateBase)
  17944. {
  17945. this.baseTexture.width = this.width * this.resolution;
  17946. this.baseTexture.height = this.height * this.resolution;
  17947. }
  17948. if (this.renderer.type === PIXI.WEBGL_RENDERER)
  17949. {
  17950. this.projection.x = this.width / 2;
  17951. this.projection.y = -this.height / 2;
  17952. }
  17953. if(!this.valid)return;
  17954. this.textureBuffer.resize(this.width, this.height);
  17955. };
  17956. /**
  17957. * Clears the RenderTexture.
  17958. *
  17959. * @method clear
  17960. */
  17961. PIXI.RenderTexture.prototype.clear = function()
  17962. {
  17963. if (!this.valid)
  17964. {
  17965. return;
  17966. }
  17967. if (this.renderer.type === PIXI.WEBGL_RENDERER)
  17968. {
  17969. this.renderer.gl.bindFramebuffer(this.renderer.gl.FRAMEBUFFER, this.textureBuffer.frameBuffer);
  17970. }
  17971. this.textureBuffer.clear();
  17972. };
  17973. /**
  17974. * This function will draw the display object to the texture.
  17975. *
  17976. * @method renderWebGL
  17977. * @param displayObject {DisplayObject} The display object to render this texture on
  17978. * @param [matrix] {Matrix} Optional matrix to apply to the display object before rendering.
  17979. * @param [clear] {Boolean} If true the texture will be cleared before the displayObject is drawn
  17980. * @private
  17981. */
  17982. PIXI.RenderTexture.prototype.renderWebGL = function(displayObject, matrix, clear)
  17983. {
  17984. if (!this.valid || displayObject.alpha === 0)
  17985. {
  17986. return;
  17987. }
  17988. // Let's create a nice matrix to apply to our display object.
  17989. // Frame buffers come in upside down so we need to flip the matrix.
  17990. var wt = displayObject.worldTransform;
  17991. wt.identity();
  17992. wt.translate(0, this.projection.y * 2);
  17993. if (matrix)
  17994. {
  17995. wt.append(matrix);
  17996. }
  17997. wt.scale(1, -1);
  17998. // Time to update all the children of the displayObject with the new matrix.
  17999. for (var i = 0; i < displayObject.children.length; i++)
  18000. {
  18001. displayObject.children[i].updateTransform();
  18002. }
  18003. // Time for the webGL fun stuff!
  18004. var gl = this.renderer.gl;
  18005. gl.viewport(0, 0, this.width * this.resolution, this.height * this.resolution);
  18006. gl.bindFramebuffer(gl.FRAMEBUFFER, this.textureBuffer.frameBuffer );
  18007. if (clear)
  18008. {
  18009. this.textureBuffer.clear();
  18010. }
  18011. this.renderer.spriteBatch.dirty = true;
  18012. this.renderer.renderDisplayObject(displayObject, this.projection, this.textureBuffer.frameBuffer, matrix);
  18013. this.renderer.spriteBatch.dirty = true;
  18014. };
  18015. /**
  18016. * This function will draw the display object to the texture.
  18017. *
  18018. * @method renderCanvas
  18019. * @param displayObject {DisplayObject} The display object to render this texture on
  18020. * @param [matrix] {Matrix} Optional matrix to apply to the display object before rendering.
  18021. * @param [clear] {Boolean} If true the texture will be cleared before the displayObject is drawn
  18022. * @private
  18023. */
  18024. PIXI.RenderTexture.prototype.renderCanvas = function(displayObject, matrix, clear)
  18025. {
  18026. if (!this.valid || displayObject.alpha === 0)
  18027. {
  18028. return;
  18029. }
  18030. // Let's create a nice matrix to apply to our display object.
  18031. // Frame buffers come in upside down so we need to flip the matrix.
  18032. var wt = displayObject.worldTransform;
  18033. wt.identity();
  18034. if (matrix)
  18035. {
  18036. wt.append(matrix);
  18037. }
  18038. // Time to update all the children of the displayObject with the new matrix (what new matrix? there isn't one!)
  18039. for (var i = 0; i < displayObject.children.length; i++)
  18040. {
  18041. displayObject.children[i].updateTransform();
  18042. }
  18043. if (clear)
  18044. {
  18045. this.textureBuffer.clear();
  18046. }
  18047. var realResolution = this.renderer.resolution;
  18048. this.renderer.resolution = this.resolution;
  18049. this.renderer.renderDisplayObject(displayObject, this.textureBuffer.context, matrix);
  18050. this.renderer.resolution = realResolution;
  18051. };
  18052. /**
  18053. * Will return a HTML Image of the texture
  18054. *
  18055. * @method getImage
  18056. * @return {Image}
  18057. */
  18058. PIXI.RenderTexture.prototype.getImage = function()
  18059. {
  18060. var image = new Image();
  18061. image.src = this.getBase64();
  18062. return image;
  18063. };
  18064. /**
  18065. * Will return a base64 encoded string of this texture. It works by calling RenderTexture.getCanvas and then running toDataURL on that.
  18066. *
  18067. * @method getBase64
  18068. * @return {String} A base64 encoded string of the texture.
  18069. */
  18070. PIXI.RenderTexture.prototype.getBase64 = function()
  18071. {
  18072. return this.getCanvas().toDataURL();
  18073. };
  18074. /**
  18075. * Creates a Canvas element, renders this RenderTexture to it and then returns it.
  18076. *
  18077. * @method getCanvas
  18078. * @return {HTMLCanvasElement} A Canvas element with the texture rendered on.
  18079. */
  18080. PIXI.RenderTexture.prototype.getCanvas = function()
  18081. {
  18082. if (this.renderer.type === PIXI.WEBGL_RENDERER)
  18083. {
  18084. var gl = this.renderer.gl;
  18085. var width = this.textureBuffer.width;
  18086. var height = this.textureBuffer.height;
  18087. var webGLPixels = new Uint8Array(4 * width * height);
  18088. gl.bindFramebuffer(gl.FRAMEBUFFER, this.textureBuffer.frameBuffer);
  18089. gl.readPixels(0, 0, width, height, gl.RGBA, gl.UNSIGNED_BYTE, webGLPixels);
  18090. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  18091. var tempCanvas = new PIXI.CanvasBuffer(width, height);
  18092. var canvasData = tempCanvas.context.getImageData(0, 0, width, height);
  18093. canvasData.data.set(webGLPixels);
  18094. tempCanvas.context.putImageData(canvasData, 0, 0);
  18095. return tempCanvas.canvas;
  18096. }
  18097. else
  18098. {
  18099. return this.textureBuffer.canvas;
  18100. }
  18101. };
  18102. /**
  18103. * @author Mat Groves http://matgroves.com/ @Doormat23
  18104. */
  18105. /**
  18106. * This is the base class for creating a PIXI filter. Currently only webGL supports filters.
  18107. * If you want to make a custom filter this should be your base class.
  18108. *
  18109. * @class AbstractFilter
  18110. * @constructor
  18111. * @param fragmentSrc {Array} The fragment source in an array of strings.
  18112. * @param uniforms {Object} An object containing the uniforms for this filter.
  18113. */
  18114. PIXI.AbstractFilter = function(fragmentSrc, uniforms)
  18115. {
  18116. /**
  18117. * An array of passes - some filters contain a few steps this array simply stores the steps in a liniear fashion.
  18118. * For example the blur filter has two passes blurX and blurY.
  18119. * @property passes
  18120. * @type Array
  18121. * @private
  18122. */
  18123. this.passes = [this];
  18124. /**
  18125. * @property shaders
  18126. * @type Array
  18127. * @private
  18128. */
  18129. this.shaders = [];
  18130. /**
  18131. * @property dirty
  18132. * @type Boolean
  18133. */
  18134. this.dirty = true;
  18135. /**
  18136. * @property padding
  18137. * @type Number
  18138. */
  18139. this.padding = 0;
  18140. /**
  18141. * @property uniforms
  18142. * @type Object
  18143. * @private
  18144. */
  18145. this.uniforms = uniforms || {};
  18146. /**
  18147. * @property fragmentSrc
  18148. * @type Array
  18149. * @private
  18150. */
  18151. this.fragmentSrc = fragmentSrc || [];
  18152. };
  18153. PIXI.AbstractFilter.prototype.constructor = PIXI.AbstractFilter;
  18154. /**
  18155. * Syncs the uniforms between the class object and the shaders.
  18156. *
  18157. * @method syncUniforms
  18158. */
  18159. PIXI.AbstractFilter.prototype.syncUniforms = function()
  18160. {
  18161. for(var i=0,j=this.shaders.length; i<j; i++)
  18162. {
  18163. this.shaders[i].dirty = true;
  18164. }
  18165. };
  18166. /**
  18167. * @author Mat Groves http://matgroves.com/
  18168. */
  18169. /**
  18170. *
  18171. * @class Strip
  18172. * @extends DisplayObjectContainer
  18173. * @constructor
  18174. * @param texture {Texture} The texture to use
  18175. * @param width {Number} the width
  18176. * @param height {Number} the height
  18177. *
  18178. */
  18179. PIXI.Strip = function(texture)
  18180. {
  18181. PIXI.DisplayObjectContainer.call( this );
  18182. /**
  18183. * The texture of the strip
  18184. *
  18185. * @property texture
  18186. * @type Texture
  18187. */
  18188. this.texture = texture;
  18189. // set up the main bits..
  18190. this.uvs = new PIXI.Float32Array([0, 1,
  18191. 1, 1,
  18192. 1, 0,
  18193. 0, 1]);
  18194. this.vertices = new PIXI.Float32Array([0, 0,
  18195. 100, 0,
  18196. 100, 100,
  18197. 0, 100]);
  18198. this.colors = new PIXI.Float32Array([1, 1, 1, 1]);
  18199. this.indices = new PIXI.Uint16Array([0, 1, 2, 3]);
  18200. /**
  18201. * Whether the strip is dirty or not
  18202. *
  18203. * @property dirty
  18204. * @type Boolean
  18205. */
  18206. this.dirty = true;
  18207. /**
  18208. * The blend mode to be applied to the sprite. Set to PIXI.blendModes.NORMAL to remove any blend mode.
  18209. *
  18210. * @property blendMode
  18211. * @type Number
  18212. * @default PIXI.blendModes.NORMAL;
  18213. */
  18214. this.blendMode = PIXI.blendModes.NORMAL;
  18215. /**
  18216. * Triangles in canvas mode are automatically antialiased, use this value to force triangles to overlap a bit with each other.
  18217. *
  18218. * @property canvasPadding
  18219. * @type Number
  18220. */
  18221. this.canvasPadding = 0;
  18222. this.drawMode = PIXI.Strip.DrawModes.TRIANGLE_STRIP;
  18223. };
  18224. // constructor
  18225. PIXI.Strip.prototype = Object.create(PIXI.DisplayObjectContainer.prototype);
  18226. PIXI.Strip.prototype.constructor = PIXI.Strip;
  18227. PIXI.Strip.prototype._renderWebGL = function(renderSession)
  18228. {
  18229. // if the sprite is not visible or the alpha is 0 then no need to render this element
  18230. if(!this.visible || this.alpha <= 0)return;
  18231. // render triangle strip..
  18232. renderSession.spriteBatch.stop();
  18233. // init! init!
  18234. if(!this._vertexBuffer)this._initWebGL(renderSession);
  18235. renderSession.shaderManager.setShader(renderSession.shaderManager.stripShader);
  18236. this._renderStrip(renderSession);
  18237. ///renderSession.shaderManager.activateDefaultShader();
  18238. renderSession.spriteBatch.start();
  18239. //TODO check culling
  18240. };
  18241. PIXI.Strip.prototype._initWebGL = function(renderSession)
  18242. {
  18243. // build the strip!
  18244. var gl = renderSession.gl;
  18245. this._vertexBuffer = gl.createBuffer();
  18246. this._indexBuffer = gl.createBuffer();
  18247. this._uvBuffer = gl.createBuffer();
  18248. this._colorBuffer = gl.createBuffer();
  18249. gl.bindBuffer(gl.ARRAY_BUFFER, this._vertexBuffer);
  18250. gl.bufferData(gl.ARRAY_BUFFER, this.vertices, gl.DYNAMIC_DRAW);
  18251. gl.bindBuffer(gl.ARRAY_BUFFER, this._uvBuffer);
  18252. gl.bufferData(gl.ARRAY_BUFFER, this.uvs, gl.STATIC_DRAW);
  18253. gl.bindBuffer(gl.ARRAY_BUFFER, this._colorBuffer);
  18254. gl.bufferData(gl.ARRAY_BUFFER, this.colors, gl.STATIC_DRAW);
  18255. gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this._indexBuffer);
  18256. gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, this.indices, gl.STATIC_DRAW);
  18257. };
  18258. PIXI.Strip.prototype._renderStrip = function(renderSession)
  18259. {
  18260. var gl = renderSession.gl;
  18261. var projection = renderSession.projection,
  18262. offset = renderSession.offset,
  18263. shader = renderSession.shaderManager.stripShader;
  18264. var drawMode = this.drawMode === PIXI.Strip.DrawModes.TRIANGLE_STRIP ? gl.TRIANGLE_STRIP : gl.TRIANGLES;
  18265. // gl.uniformMatrix4fv(shaderProgram.mvMatrixUniform, false, mat4Real);
  18266. renderSession.blendModeManager.setBlendMode(this.blendMode);
  18267. // set uniforms
  18268. gl.uniformMatrix3fv(shader.translationMatrix, false, this.worldTransform.toArray(true));
  18269. gl.uniform2f(shader.projectionVector, projection.x, -projection.y);
  18270. gl.uniform2f(shader.offsetVector, -offset.x, -offset.y);
  18271. gl.uniform1f(shader.alpha, this.worldAlpha);
  18272. if(!this.dirty)
  18273. {
  18274. gl.bindBuffer(gl.ARRAY_BUFFER, this._vertexBuffer);
  18275. gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.vertices);
  18276. gl.vertexAttribPointer(shader.aVertexPosition, 2, gl.FLOAT, false, 0, 0);
  18277. // update the uvs
  18278. gl.bindBuffer(gl.ARRAY_BUFFER, this._uvBuffer);
  18279. gl.vertexAttribPointer(shader.aTextureCoord, 2, gl.FLOAT, false, 0, 0);
  18280. gl.activeTexture(gl.TEXTURE0);
  18281. // check if a texture is dirty..
  18282. if(this.texture.baseTexture._dirty[gl.id])
  18283. {
  18284. renderSession.renderer.updateTexture(this.texture.baseTexture);
  18285. }
  18286. else
  18287. {
  18288. // bind the current texture
  18289. gl.bindTexture(gl.TEXTURE_2D, this.texture.baseTexture._glTextures[gl.id]);
  18290. }
  18291. // dont need to upload!
  18292. gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this._indexBuffer);
  18293. }
  18294. else
  18295. {
  18296. this.dirty = false;
  18297. gl.bindBuffer(gl.ARRAY_BUFFER, this._vertexBuffer);
  18298. gl.bufferData(gl.ARRAY_BUFFER, this.vertices, gl.STATIC_DRAW);
  18299. gl.vertexAttribPointer(shader.aVertexPosition, 2, gl.FLOAT, false, 0, 0);
  18300. // update the uvs
  18301. gl.bindBuffer(gl.ARRAY_BUFFER, this._uvBuffer);
  18302. gl.bufferData(gl.ARRAY_BUFFER, this.uvs, gl.STATIC_DRAW);
  18303. gl.vertexAttribPointer(shader.aTextureCoord, 2, gl.FLOAT, false, 0, 0);
  18304. gl.activeTexture(gl.TEXTURE0);
  18305. // check if a texture is dirty..
  18306. if(this.texture.baseTexture._dirty[gl.id])
  18307. {
  18308. renderSession.renderer.updateTexture(this.texture.baseTexture);
  18309. }
  18310. else
  18311. {
  18312. gl.bindTexture(gl.TEXTURE_2D, this.texture.baseTexture._glTextures[gl.id]);
  18313. }
  18314. // dont need to upload!
  18315. gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this._indexBuffer);
  18316. gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, this.indices, gl.STATIC_DRAW);
  18317. }
  18318. //console.log(gl.TRIANGLE_STRIP)
  18319. //
  18320. //
  18321. gl.drawElements(drawMode, this.indices.length, gl.UNSIGNED_SHORT, 0);
  18322. };
  18323. PIXI.Strip.prototype._renderCanvas = function(renderSession)
  18324. {
  18325. var context = renderSession.context;
  18326. var transform = this.worldTransform;
  18327. var tx = (transform.tx * renderSession.resolution) + renderSession.shakeX;
  18328. var ty = (transform.ty * renderSession.resolution) + renderSession.shakeY;
  18329. if (renderSession.roundPixels)
  18330. {
  18331. context.setTransform(transform.a, transform.b, transform.c, transform.d, tx | 0, ty | 0);
  18332. }
  18333. else
  18334. {
  18335. context.setTransform(transform.a, transform.b, transform.c, transform.d, tx, ty);
  18336. }
  18337. if (this.drawMode === PIXI.Strip.DrawModes.TRIANGLE_STRIP)
  18338. {
  18339. this._renderCanvasTriangleStrip(context);
  18340. }
  18341. else
  18342. {
  18343. this._renderCanvasTriangles(context);
  18344. }
  18345. };
  18346. PIXI.Strip.prototype._renderCanvasTriangleStrip = function(context)
  18347. {
  18348. // draw triangles!!
  18349. var vertices = this.vertices;
  18350. var uvs = this.uvs;
  18351. var length = vertices.length / 2;
  18352. this.count++;
  18353. for (var i = 0; i < length - 2; i++) {
  18354. // draw some triangles!
  18355. var index = i * 2;
  18356. this._renderCanvasDrawTriangle(context, vertices, uvs, index, (index + 2), (index + 4));
  18357. }
  18358. };
  18359. PIXI.Strip.prototype._renderCanvasTriangles = function(context)
  18360. {
  18361. // draw triangles!!
  18362. var vertices = this.vertices;
  18363. var uvs = this.uvs;
  18364. var indices = this.indices;
  18365. var length = indices.length;
  18366. this.count++;
  18367. for (var i = 0; i < length; i += 3) {
  18368. // draw some triangles!
  18369. var index0 = indices[i] * 2, index1 = indices[i + 1] * 2, index2 = indices[i + 2] * 2;
  18370. this._renderCanvasDrawTriangle(context, vertices, uvs, index0, index1, index2);
  18371. }
  18372. };
  18373. PIXI.Strip.prototype._renderCanvasDrawTriangle = function(context, vertices, uvs, index0, index1, index2)
  18374. {
  18375. var textureSource = this.texture.baseTexture.source;
  18376. var textureWidth = this.texture.width;
  18377. var textureHeight = this.texture.height;
  18378. var x0 = vertices[index0], x1 = vertices[index1], x2 = vertices[index2];
  18379. var y0 = vertices[index0 + 1], y1 = vertices[index1 + 1], y2 = vertices[index2 + 1];
  18380. var u0 = uvs[index0] * textureWidth, u1 = uvs[index1] * textureWidth, u2 = uvs[index2] * textureWidth;
  18381. var v0 = uvs[index0 + 1] * textureHeight, v1 = uvs[index1 + 1] * textureHeight, v2 = uvs[index2 + 1] * textureHeight;
  18382. if (this.canvasPadding > 0) {
  18383. var paddingX = this.canvasPadding / this.worldTransform.a;
  18384. var paddingY = this.canvasPadding / this.worldTransform.d;
  18385. var centerX = (x0 + x1 + x2) / 3;
  18386. var centerY = (y0 + y1 + y2) / 3;
  18387. var normX = x0 - centerX;
  18388. var normY = y0 - centerY;
  18389. var dist = Math.sqrt(normX * normX + normY * normY);
  18390. x0 = centerX + (normX / dist) * (dist + paddingX);
  18391. y0 = centerY + (normY / dist) * (dist + paddingY);
  18392. //
  18393. normX = x1 - centerX;
  18394. normY = y1 - centerY;
  18395. dist = Math.sqrt(normX * normX + normY * normY);
  18396. x1 = centerX + (normX / dist) * (dist + paddingX);
  18397. y1 = centerY + (normY / dist) * (dist + paddingY);
  18398. normX = x2 - centerX;
  18399. normY = y2 - centerY;
  18400. dist = Math.sqrt(normX * normX + normY * normY);
  18401. x2 = centerX + (normX / dist) * (dist + paddingX);
  18402. y2 = centerY + (normY / dist) * (dist + paddingY);
  18403. }
  18404. context.save();
  18405. context.beginPath();
  18406. context.moveTo(x0, y0);
  18407. context.lineTo(x1, y1);
  18408. context.lineTo(x2, y2);
  18409. context.closePath();
  18410. context.clip();
  18411. // Compute matrix transform
  18412. var delta = (u0 * v1) + (v0 * u2) + (u1 * v2) - (v1 * u2) - (v0 * u1) - (u0 * v2);
  18413. var deltaA = (x0 * v1) + (v0 * x2) + (x1 * v2) - (v1 * x2) - (v0 * x1) - (x0 * v2);
  18414. var deltaB = (u0 * x1) + (x0 * u2) + (u1 * x2) - (x1 * u2) - (x0 * u1) - (u0 * x2);
  18415. var deltaC = (u0 * v1 * x2) + (v0 * x1 * u2) + (x0 * u1 * v2) - (x0 * v1 * u2) - (v0 * u1 * x2) - (u0 * x1 * v2);
  18416. var deltaD = (y0 * v1) + (v0 * y2) + (y1 * v2) - (v1 * y2) - (v0 * y1) - (y0 * v2);
  18417. var deltaE = (u0 * y1) + (y0 * u2) + (u1 * y2) - (y1 * u2) - (y0 * u1) - (u0 * y2);
  18418. var deltaF = (u0 * v1 * y2) + (v0 * y1 * u2) + (y0 * u1 * v2) - (y0 * v1 * u2) - (v0 * u1 * y2) - (u0 * y1 * v2);
  18419. context.transform(deltaA / delta, deltaD / delta,
  18420. deltaB / delta, deltaE / delta,
  18421. deltaC / delta, deltaF / delta);
  18422. context.drawImage(textureSource, 0, 0);
  18423. context.restore();
  18424. };
  18425. /**
  18426. * Renders a flat strip
  18427. *
  18428. * @method renderStripFlat
  18429. * @param strip {Strip} The Strip to render
  18430. * @private
  18431. */
  18432. PIXI.Strip.prototype.renderStripFlat = function(strip)
  18433. {
  18434. var context = this.context;
  18435. var vertices = strip.vertices;
  18436. var length = vertices.length/2;
  18437. this.count++;
  18438. context.beginPath();
  18439. for (var i=1; i < length-2; i++)
  18440. {
  18441. // draw some triangles!
  18442. var index = i*2;
  18443. var x0 = vertices[index], x1 = vertices[index+2], x2 = vertices[index+4];
  18444. var y0 = vertices[index+1], y1 = vertices[index+3], y2 = vertices[index+5];
  18445. context.moveTo(x0, y0);
  18446. context.lineTo(x1, y1);
  18447. context.lineTo(x2, y2);
  18448. }
  18449. context.fillStyle = '#FF0000';
  18450. context.fill();
  18451. context.closePath();
  18452. };
  18453. /*
  18454. PIXI.Strip.prototype.setTexture = function(texture)
  18455. {
  18456. //TODO SET THE TEXTURES
  18457. //TODO VISIBILITY
  18458. // stop current texture
  18459. this.texture = texture;
  18460. this.width = texture.frame.width;
  18461. this.height = texture.frame.height;
  18462. this.updateFrame = true;
  18463. };
  18464. */
  18465. /**
  18466. * When the texture is updated, this event will fire to update the scale and frame
  18467. *
  18468. * @method onTextureUpdate
  18469. * @param event
  18470. * @private
  18471. */
  18472. PIXI.Strip.prototype.onTextureUpdate = function()
  18473. {
  18474. this.updateFrame = true;
  18475. };
  18476. /**
  18477. * Returns the bounds of the mesh as a rectangle. The bounds calculation takes the worldTransform into account.
  18478. *
  18479. * @method getBounds
  18480. * @param matrix {Matrix} the transformation matrix of the sprite
  18481. * @return {Rectangle} the framing rectangle
  18482. */
  18483. PIXI.Strip.prototype.getBounds = function(matrix)
  18484. {
  18485. var worldTransform = matrix || this.worldTransform;
  18486. var a = worldTransform.a;
  18487. var b = worldTransform.b;
  18488. var c = worldTransform.c;
  18489. var d = worldTransform.d;
  18490. var tx = worldTransform.tx;
  18491. var ty = worldTransform.ty;
  18492. var maxX = -Infinity;
  18493. var maxY = -Infinity;
  18494. var minX = Infinity;
  18495. var minY = Infinity;
  18496. var vertices = this.vertices;
  18497. for (var i = 0, n = vertices.length; i < n; i += 2)
  18498. {
  18499. var rawX = vertices[i], rawY = vertices[i + 1];
  18500. var x = (a * rawX) + (c * rawY) + tx;
  18501. var y = (d * rawY) + (b * rawX) + ty;
  18502. minX = x < minX ? x : minX;
  18503. minY = y < minY ? y : minY;
  18504. maxX = x > maxX ? x : maxX;
  18505. maxY = y > maxY ? y : maxY;
  18506. }
  18507. if (minX === -Infinity || maxY === Infinity)
  18508. {
  18509. return PIXI.EmptyRectangle;
  18510. }
  18511. var bounds = this._bounds;
  18512. bounds.x = minX;
  18513. bounds.width = maxX - minX;
  18514. bounds.y = minY;
  18515. bounds.height = maxY - minY;
  18516. // store a reference so that if this function gets called again in the render cycle we do not have to recalculate
  18517. this._currentBounds = bounds;
  18518. return bounds;
  18519. };
  18520. /**
  18521. * Different drawing buffer modes supported
  18522. *
  18523. * @property
  18524. * @type {{TRIANGLE_STRIP: number, TRIANGLES: number}}
  18525. * @static
  18526. */
  18527. PIXI.Strip.DrawModes = {
  18528. TRIANGLE_STRIP: 0,
  18529. TRIANGLES: 1
  18530. };
  18531. /**
  18532. * @author Mat Groves http://matgroves.com/ @Doormat23
  18533. * @copyright Mat Groves, Rovanion Luckey
  18534. */
  18535. /**
  18536. *
  18537. * @class Rope
  18538. * @constructor
  18539. * @extends Strip
  18540. * @param {Texture} texture - The texture to use on the rope.
  18541. * @param {Array} points - An array of {PIXI.Point}.
  18542. *
  18543. */
  18544. PIXI.Rope = function(texture, points)
  18545. {
  18546. PIXI.Strip.call( this, texture );
  18547. this.points = points;
  18548. this.vertices = new PIXI.Float32Array(points.length * 4);
  18549. this.uvs = new PIXI.Float32Array(points.length * 4);
  18550. this.colors = new PIXI.Float32Array(points.length * 2);
  18551. this.indices = new PIXI.Uint16Array(points.length * 2);
  18552. this.refresh();
  18553. };
  18554. // constructor
  18555. PIXI.Rope.prototype = Object.create( PIXI.Strip.prototype );
  18556. PIXI.Rope.prototype.constructor = PIXI.Rope;
  18557. /*
  18558. * Refreshes
  18559. *
  18560. * @method refresh
  18561. */
  18562. PIXI.Rope.prototype.refresh = function()
  18563. {
  18564. var points = this.points;
  18565. if(points.length < 1) return;
  18566. var uvs = this.uvs;
  18567. var lastPoint = points[0];
  18568. var indices = this.indices;
  18569. var colors = this.colors;
  18570. this.count-=0.2;
  18571. uvs[0] = 0;
  18572. uvs[1] = 0;
  18573. uvs[2] = 0;
  18574. uvs[3] = 1;
  18575. colors[0] = 1;
  18576. colors[1] = 1;
  18577. indices[0] = 0;
  18578. indices[1] = 1;
  18579. var total = points.length,
  18580. point, index, amount;
  18581. for (var i = 1; i < total; i++)
  18582. {
  18583. point = points[i];
  18584. index = i * 4;
  18585. // time to do some smart drawing!
  18586. amount = i / (total-1);
  18587. if(i%2)
  18588. {
  18589. uvs[index] = amount;
  18590. uvs[index+1] = 0;
  18591. uvs[index+2] = amount;
  18592. uvs[index+3] = 1;
  18593. }
  18594. else
  18595. {
  18596. uvs[index] = amount;
  18597. uvs[index+1] = 0;
  18598. uvs[index+2] = amount;
  18599. uvs[index+3] = 1;
  18600. }
  18601. index = i * 2;
  18602. colors[index] = 1;
  18603. colors[index+1] = 1;
  18604. index = i * 2;
  18605. indices[index] = index;
  18606. indices[index + 1] = index + 1;
  18607. lastPoint = point;
  18608. }
  18609. };
  18610. /*
  18611. * Updates the object transform for rendering
  18612. *
  18613. * @method updateTransform
  18614. * @private
  18615. */
  18616. PIXI.Rope.prototype.updateTransform = function()
  18617. {
  18618. var points = this.points;
  18619. if(points.length < 1)return;
  18620. var lastPoint = points[0];
  18621. var nextPoint;
  18622. var perp = {x:0, y:0};
  18623. this.count-=0.2;
  18624. var vertices = this.vertices;
  18625. var total = points.length,
  18626. point, index, ratio, perpLength, num;
  18627. for (var i = 0; i < total; i++)
  18628. {
  18629. point = points[i];
  18630. index = i * 4;
  18631. if(i < points.length-1)
  18632. {
  18633. nextPoint = points[i+1];
  18634. }
  18635. else
  18636. {
  18637. nextPoint = point;
  18638. }
  18639. perp.y = -(nextPoint.x - lastPoint.x);
  18640. perp.x = nextPoint.y - lastPoint.y;
  18641. ratio = (1 - (i / (total-1))) * 10;
  18642. if(ratio > 1) ratio = 1;
  18643. perpLength = Math.sqrt(perp.x * perp.x + perp.y * perp.y);
  18644. num = this.texture.height / 2; //(20 + Math.abs(Math.sin((i + this.count) * 0.3) * 50) )* ratio;
  18645. perp.x /= perpLength;
  18646. perp.y /= perpLength;
  18647. perp.x *= num;
  18648. perp.y *= num;
  18649. vertices[index] = point.x + perp.x;
  18650. vertices[index+1] = point.y + perp.y;
  18651. vertices[index+2] = point.x - perp.x;
  18652. vertices[index+3] = point.y - perp.y;
  18653. lastPoint = point;
  18654. }
  18655. PIXI.DisplayObjectContainer.prototype.updateTransform.call( this );
  18656. };
  18657. /*
  18658. * Sets the texture that the Rope will use
  18659. *
  18660. * @method setTexture
  18661. * @param texture {Texture} the texture that will be used
  18662. */
  18663. PIXI.Rope.prototype.setTexture = function(texture)
  18664. {
  18665. // stop current texture
  18666. this.texture = texture;
  18667. //this.updateFrame = true;
  18668. };
  18669. /**
  18670. * @author Mat Groves http://matgroves.com/
  18671. */
  18672. /**
  18673. * A tiling sprite is a fast way of rendering a tiling image
  18674. *
  18675. * @class TilingSprite
  18676. * @extends Sprite
  18677. * @constructor
  18678. * @param texture {Texture} the texture of the tiling sprite
  18679. * @param width {Number} the width of the tiling sprite
  18680. * @param height {Number} the height of the tiling sprite
  18681. */
  18682. PIXI.TilingSprite = function(texture, width, height)
  18683. {
  18684. PIXI.Sprite.call(this, texture);
  18685. /**
  18686. * The width of the tiling sprite
  18687. *
  18688. * @property width
  18689. * @type Number
  18690. */
  18691. this._width = width || 128;
  18692. /**
  18693. * The height of the tiling sprite
  18694. *
  18695. * @property height
  18696. * @type Number
  18697. */
  18698. this._height = height || 128;
  18699. /**
  18700. * The scaling of the image that is being tiled
  18701. *
  18702. * @property tileScale
  18703. * @type Point
  18704. */
  18705. this.tileScale = new PIXI.Point(1, 1);
  18706. /**
  18707. * A point that represents the scale of the texture object
  18708. *
  18709. * @property tileScaleOffset
  18710. * @type Point
  18711. */
  18712. this.tileScaleOffset = new PIXI.Point(1, 1);
  18713. /**
  18714. * The offset position of the image that is being tiled
  18715. *
  18716. * @property tilePosition
  18717. * @type Point
  18718. */
  18719. this.tilePosition = new PIXI.Point();
  18720. /**
  18721. * Whether this sprite is renderable or not
  18722. *
  18723. * @property renderable
  18724. * @type Boolean
  18725. * @default true
  18726. */
  18727. this.renderable = true;
  18728. /**
  18729. * The tint applied to the sprite. This is a hex value
  18730. *
  18731. * @property tint
  18732. * @type Number
  18733. * @default 0xFFFFFF
  18734. */
  18735. this.tint = 0xFFFFFF;
  18736. /**
  18737. * If enabled a green rectangle will be drawn behind the generated tiling texture, allowing you to visually
  18738. * debug the texture being used.
  18739. *
  18740. * @property textureDebug
  18741. * @type Boolean
  18742. */
  18743. this.textureDebug = false;
  18744. /**
  18745. * The blend mode to be applied to the sprite
  18746. *
  18747. * @property blendMode
  18748. * @type Number
  18749. * @default PIXI.blendModes.NORMAL;
  18750. */
  18751. this.blendMode = PIXI.blendModes.NORMAL;
  18752. /**
  18753. * The CanvasBuffer object that the tiled texture is drawn to.
  18754. *
  18755. * @property canvasBuffer
  18756. * @type PIXI.CanvasBuffer
  18757. */
  18758. this.canvasBuffer = null;
  18759. /**
  18760. * An internal Texture object that holds the tiling texture that was generated from TilingSprite.texture.
  18761. *
  18762. * @property tilingTexture
  18763. * @type PIXI.Texture
  18764. */
  18765. this.tilingTexture = null;
  18766. /**
  18767. * The Context fill pattern that is used to draw the TilingSprite in Canvas mode only (will be null in WebGL).
  18768. *
  18769. * @property tilePattern
  18770. * @type PIXI.Texture
  18771. */
  18772. this.tilePattern = null;
  18773. /**
  18774. * If true the TilingSprite will run generateTexture on its **next** render pass.
  18775. * This is set by the likes of Phaser.LoadTexture.setFrame.
  18776. *
  18777. * @property refreshTexture
  18778. * @type Boolean
  18779. * @default true
  18780. */
  18781. this.refreshTexture = true;
  18782. this.frameWidth = 0;
  18783. this.frameHeight = 0;
  18784. };
  18785. PIXI.TilingSprite.prototype = Object.create(PIXI.Sprite.prototype);
  18786. PIXI.TilingSprite.prototype.constructor = PIXI.TilingSprite;
  18787. PIXI.TilingSprite.prototype.setTexture = function(texture)
  18788. {
  18789. if (this.texture !== texture)
  18790. {
  18791. this.texture = texture;
  18792. this.refreshTexture = true;
  18793. this.cachedTint = 0xFFFFFF;
  18794. }
  18795. };
  18796. /**
  18797. * Renders the object using the WebGL renderer
  18798. *
  18799. * @method _renderWebGL
  18800. * @param renderSession {RenderSession}
  18801. * @private
  18802. */
  18803. PIXI.TilingSprite.prototype._renderWebGL = function(renderSession)
  18804. {
  18805. if (!this.visible || !this.renderable || this.alpha === 0)
  18806. {
  18807. return;
  18808. }
  18809. if (this._mask)
  18810. {
  18811. renderSession.spriteBatch.stop();
  18812. renderSession.maskManager.pushMask(this.mask, renderSession);
  18813. renderSession.spriteBatch.start();
  18814. }
  18815. if (this._filters)
  18816. {
  18817. renderSession.spriteBatch.flush();
  18818. renderSession.filterManager.pushFilter(this._filterBlock);
  18819. }
  18820. if (this.refreshTexture)
  18821. {
  18822. this.generateTilingTexture(true, renderSession);
  18823. if (this.tilingTexture)
  18824. {
  18825. if (this.tilingTexture.needsUpdate)
  18826. {
  18827. renderSession.renderer.updateTexture(this.tilingTexture.baseTexture);
  18828. this.tilingTexture.needsUpdate = false;
  18829. }
  18830. }
  18831. else
  18832. {
  18833. return;
  18834. }
  18835. }
  18836. renderSession.spriteBatch.renderTilingSprite(this);
  18837. for (var i = 0; i < this.children.length; i++)
  18838. {
  18839. this.children[i]._renderWebGL(renderSession);
  18840. }
  18841. renderSession.spriteBatch.stop();
  18842. if (this._filters)
  18843. {
  18844. renderSession.filterManager.popFilter();
  18845. }
  18846. if (this._mask)
  18847. {
  18848. renderSession.maskManager.popMask(this._mask, renderSession);
  18849. }
  18850. renderSession.spriteBatch.start();
  18851. };
  18852. /**
  18853. * Renders the object using the Canvas renderer
  18854. *
  18855. * @method _renderCanvas
  18856. * @param renderSession {RenderSession}
  18857. * @private
  18858. */
  18859. PIXI.TilingSprite.prototype._renderCanvas = function(renderSession)
  18860. {
  18861. if (!this.visible || !this.renderable || this.alpha === 0)
  18862. {
  18863. return;
  18864. }
  18865. var context = renderSession.context;
  18866. if (this._mask)
  18867. {
  18868. renderSession.maskManager.pushMask(this._mask, renderSession);
  18869. }
  18870. context.globalAlpha = this.worldAlpha;
  18871. var wt = this.worldTransform;
  18872. var resolution = renderSession.resolution;
  18873. var tx = (wt.tx * resolution) + renderSession.shakeX;
  18874. var ty = (wt.ty * resolution) + renderSession.shakeY;
  18875. context.setTransform(wt.a * resolution, wt.b * resolution, wt.c * resolution, wt.d * resolution, tx, ty);
  18876. if (this.refreshTexture)
  18877. {
  18878. this.generateTilingTexture(false, renderSession);
  18879. if (this.tilingTexture)
  18880. {
  18881. this.tilePattern = context.createPattern(this.tilingTexture.baseTexture.source, 'repeat');
  18882. }
  18883. else
  18884. {
  18885. return;
  18886. }
  18887. }
  18888. var sessionBlendMode = renderSession.currentBlendMode;
  18889. // Check blend mode
  18890. if (this.blendMode !== renderSession.currentBlendMode)
  18891. {
  18892. renderSession.currentBlendMode = this.blendMode;
  18893. context.globalCompositeOperation = PIXI.blendModesCanvas[renderSession.currentBlendMode];
  18894. }
  18895. var tilePosition = this.tilePosition;
  18896. var tileScale = this.tileScale;
  18897. tilePosition.x %= this.tilingTexture.baseTexture.width;
  18898. tilePosition.y %= this.tilingTexture.baseTexture.height;
  18899. // Translate
  18900. context.scale(tileScale.x, tileScale.y);
  18901. context.translate(tilePosition.x + (this.anchor.x * -this._width), tilePosition.y + (this.anchor.y * -this._height));
  18902. context.fillStyle = this.tilePattern;
  18903. var tx = -tilePosition.x;
  18904. var ty = -tilePosition.y;
  18905. var tw = this._width / tileScale.x;
  18906. var th = this._height / tileScale.y;
  18907. // Allow for pixel rounding
  18908. if (renderSession.roundPixels)
  18909. {
  18910. tx |= 0;
  18911. ty |= 0;
  18912. tw |= 0;
  18913. th |= 0;
  18914. }
  18915. context.fillRect(tx, ty, tw, th);
  18916. // Translate back again
  18917. context.scale(1 / tileScale.x, 1 / tileScale.y);
  18918. context.translate(-tilePosition.x + (this.anchor.x * this._width), -tilePosition.y + (this.anchor.y * this._height));
  18919. if (this._mask)
  18920. {
  18921. renderSession.maskManager.popMask(renderSession);
  18922. }
  18923. for (var i = 0; i < this.children.length; i++)
  18924. {
  18925. this.children[i]._renderCanvas(renderSession);
  18926. }
  18927. // Reset blend mode
  18928. if (sessionBlendMode !== this.blendMode)
  18929. {
  18930. renderSession.currentBlendMode = sessionBlendMode;
  18931. context.globalCompositeOperation = PIXI.blendModesCanvas[sessionBlendMode];
  18932. }
  18933. };
  18934. /**
  18935. * When the texture is updated, this event will fire to update the scale and frame
  18936. *
  18937. * @method onTextureUpdate
  18938. * @param event
  18939. * @private
  18940. */
  18941. PIXI.TilingSprite.prototype.onTextureUpdate = function()
  18942. {
  18943. // overriding the sprite version of this!
  18944. };
  18945. /**
  18946. *
  18947. * @method generateTilingTexture
  18948. *
  18949. * @param forcePowerOfTwo {Boolean} Whether we want to force the texture to be a power of two
  18950. * @param renderSession {RenderSession}
  18951. */
  18952. PIXI.TilingSprite.prototype.generateTilingTexture = function(forcePowerOfTwo, renderSession)
  18953. {
  18954. if (!this.texture.baseTexture.hasLoaded)
  18955. {
  18956. return;
  18957. }
  18958. var texture = this.texture;
  18959. var frame = texture.frame;
  18960. var targetWidth = this._frame.sourceSizeW || this._frame.width;
  18961. var targetHeight = this._frame.sourceSizeH || this._frame.height;
  18962. var dx = 0;
  18963. var dy = 0;
  18964. if (this._frame.trimmed)
  18965. {
  18966. dx = this._frame.spriteSourceSizeX;
  18967. dy = this._frame.spriteSourceSizeY;
  18968. }
  18969. if (forcePowerOfTwo)
  18970. {
  18971. targetWidth = PIXI.getNextPowerOfTwo(targetWidth);
  18972. targetHeight = PIXI.getNextPowerOfTwo(targetHeight);
  18973. }
  18974. if (this.canvasBuffer)
  18975. {
  18976. this.canvasBuffer.resize(targetWidth, targetHeight);
  18977. this.tilingTexture.baseTexture.width = targetWidth;
  18978. this.tilingTexture.baseTexture.height = targetHeight;
  18979. this.tilingTexture.needsUpdate = true;
  18980. }
  18981. else
  18982. {
  18983. this.canvasBuffer = new PIXI.CanvasBuffer(targetWidth, targetHeight);
  18984. this.tilingTexture = PIXI.Texture.fromCanvas(this.canvasBuffer.canvas);
  18985. this.tilingTexture.isTiling = true;
  18986. this.tilingTexture.needsUpdate = true;
  18987. }
  18988. if (this.textureDebug)
  18989. {
  18990. this.canvasBuffer.context.strokeStyle = '#00ff00';
  18991. this.canvasBuffer.context.strokeRect(0, 0, targetWidth, targetHeight);
  18992. }
  18993. // If a sprite sheet we need this:
  18994. var w = texture.crop.width;
  18995. var h = texture.crop.height;
  18996. if (w !== targetWidth || h !== targetHeight)
  18997. {
  18998. w = targetWidth;
  18999. h = targetHeight;
  19000. }
  19001. this.canvasBuffer.context.drawImage(texture.baseTexture.source,
  19002. texture.crop.x,
  19003. texture.crop.y,
  19004. texture.crop.width,
  19005. texture.crop.height,
  19006. dx,
  19007. dy,
  19008. w,
  19009. h);
  19010. this.tileScaleOffset.x = frame.width / targetWidth;
  19011. this.tileScaleOffset.y = frame.height / targetHeight;
  19012. this.refreshTexture = false;
  19013. this.tilingTexture.baseTexture._powerOf2 = true;
  19014. };
  19015. /**
  19016. * Returns the framing rectangle of the sprite as a PIXI.Rectangle object
  19017. *
  19018. * @method getBounds
  19019. * @return {Rectangle} the framing rectangle
  19020. */
  19021. PIXI.TilingSprite.prototype.getBounds = function()
  19022. {
  19023. var width = this._width;
  19024. var height = this._height;
  19025. var w0 = width * (1-this.anchor.x);
  19026. var w1 = width * -this.anchor.x;
  19027. var h0 = height * (1-this.anchor.y);
  19028. var h1 = height * -this.anchor.y;
  19029. var worldTransform = this.worldTransform;
  19030. var a = worldTransform.a;
  19031. var b = worldTransform.b;
  19032. var c = worldTransform.c;
  19033. var d = worldTransform.d;
  19034. var tx = worldTransform.tx;
  19035. var ty = worldTransform.ty;
  19036. var x1 = a * w1 + c * h1 + tx;
  19037. var y1 = d * h1 + b * w1 + ty;
  19038. var x2 = a * w0 + c * h1 + tx;
  19039. var y2 = d * h1 + b * w0 + ty;
  19040. var x3 = a * w0 + c * h0 + tx;
  19041. var y3 = d * h0 + b * w0 + ty;
  19042. var x4 = a * w1 + c * h0 + tx;
  19043. var y4 = d * h0 + b * w1 + ty;
  19044. var maxX = -Infinity;
  19045. var maxY = -Infinity;
  19046. var minX = Infinity;
  19047. var minY = Infinity;
  19048. minX = x1 < minX ? x1 : minX;
  19049. minX = x2 < minX ? x2 : minX;
  19050. minX = x3 < minX ? x3 : minX;
  19051. minX = x4 < minX ? x4 : minX;
  19052. minY = y1 < minY ? y1 : minY;
  19053. minY = y2 < minY ? y2 : minY;
  19054. minY = y3 < minY ? y3 : minY;
  19055. minY = y4 < minY ? y4 : minY;
  19056. maxX = x1 > maxX ? x1 : maxX;
  19057. maxX = x2 > maxX ? x2 : maxX;
  19058. maxX = x3 > maxX ? x3 : maxX;
  19059. maxX = x4 > maxX ? x4 : maxX;
  19060. maxY = y1 > maxY ? y1 : maxY;
  19061. maxY = y2 > maxY ? y2 : maxY;
  19062. maxY = y3 > maxY ? y3 : maxY;
  19063. maxY = y4 > maxY ? y4 : maxY;
  19064. var bounds = this._bounds;
  19065. bounds.x = minX;
  19066. bounds.width = maxX - minX;
  19067. bounds.y = minY;
  19068. bounds.height = maxY - minY;
  19069. // store a reference so that if this function gets called again in the render cycle we do not have to recalculate
  19070. this._currentBounds = bounds;
  19071. return bounds;
  19072. };
  19073. PIXI.TilingSprite.prototype.destroy = function () {
  19074. PIXI.Sprite.prototype.destroy.call(this);
  19075. if (this.canvasBuffer)
  19076. {
  19077. this.canvasBuffer.destroy();
  19078. this.canvasBuffer = null;
  19079. }
  19080. this.tileScale = null;
  19081. this.tileScaleOffset = null;
  19082. this.tilePosition = null;
  19083. if (this.tilingTexture)
  19084. {
  19085. this.tilingTexture.destroy(true);
  19086. this.tilingTexture = null;
  19087. }
  19088. };
  19089. /**
  19090. * The width of the sprite, setting this will actually modify the scale to achieve the value set
  19091. *
  19092. * @property width
  19093. * @type Number
  19094. */
  19095. Object.defineProperty(PIXI.TilingSprite.prototype, 'width', {
  19096. get: function() {
  19097. return this._width;
  19098. },
  19099. set: function(value) {
  19100. this._width = value;
  19101. }
  19102. });
  19103. /**
  19104. * The height of the TilingSprite, setting this will actually modify the scale to achieve the value set
  19105. *
  19106. * @property height
  19107. * @type Number
  19108. */
  19109. Object.defineProperty(PIXI.TilingSprite.prototype, 'height', {
  19110. get: function() {
  19111. return this._height;
  19112. },
  19113. set: function(value) {
  19114. this._height = value;
  19115. }
  19116. });
  19117. /**
  19118. * @author Mat Groves http://matgroves.com/ @Doormat23
  19119. */
  19120. if (typeof exports !== 'undefined') {
  19121. if (typeof module !== 'undefined' && module.exports) {
  19122. exports = module.exports = PIXI;
  19123. }
  19124. exports.PIXI = PIXI;
  19125. } else if (typeof define !== 'undefined' && define.amd) {
  19126. define('PIXI', (function() { return root.PIXI = PIXI; })() );
  19127. } else {
  19128. root.PIXI = PIXI;
  19129. }
  19130. return PIXI;
  19131. }).call(this);
  19132. /**
  19133. * @author Richard Davey <rich@photonstorm.com>
  19134. * @copyright 2016 Photon Storm Ltd.
  19135. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  19136. */
  19137. (function(){
  19138. var root = this;
  19139. /**
  19140. * @author Richard Davey <rich@photonstorm.com>
  19141. * @copyright 2016 Photon Storm Ltd.
  19142. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  19143. */
  19144. /**
  19145. * @namespace Phaser
  19146. */
  19147. var Phaser = Phaser || { // jshint ignore:line
  19148. /**
  19149. * The Phaser version number.
  19150. * @constant
  19151. * @type {string}
  19152. */
  19153. VERSION: '2.6.2',
  19154. /**
  19155. * An array of Phaser game instances.
  19156. * @constant
  19157. * @type {array}
  19158. */
  19159. GAMES: [],
  19160. /**
  19161. * AUTO renderer - picks between WebGL or Canvas based on device.
  19162. * @constant
  19163. * @type {integer}
  19164. */
  19165. AUTO: 0,
  19166. /**
  19167. * Canvas Renderer.
  19168. * @constant
  19169. * @type {integer}
  19170. */
  19171. CANVAS: 1,
  19172. /**
  19173. * WebGL Renderer.
  19174. * @constant
  19175. * @type {integer}
  19176. */
  19177. WEBGL: 2,
  19178. /**
  19179. * Headless renderer (not visual output)
  19180. * @constant
  19181. * @type {integer}
  19182. */
  19183. HEADLESS: 3,
  19184. /**
  19185. * Direction constant.
  19186. * @constant
  19187. * @type {integer}
  19188. */
  19189. NONE: 0,
  19190. /**
  19191. * Direction constant.
  19192. * @constant
  19193. * @type {integer}
  19194. */
  19195. LEFT: 1,
  19196. /**
  19197. * Direction constant.
  19198. * @constant
  19199. * @type {integer}
  19200. */
  19201. RIGHT: 2,
  19202. /**
  19203. * Direction constant.
  19204. * @constant
  19205. * @type {integer}
  19206. */
  19207. UP: 3,
  19208. /**
  19209. * Direction constant.
  19210. * @constant
  19211. * @type {integer}
  19212. */
  19213. DOWN: 4,
  19214. /**
  19215. * Game Object type.
  19216. * @constant
  19217. * @type {integer}
  19218. */
  19219. SPRITE: 0,
  19220. /**
  19221. * Game Object type.
  19222. * @constant
  19223. * @type {integer}
  19224. */
  19225. BUTTON: 1,
  19226. /**
  19227. * Game Object type.
  19228. * @constant
  19229. * @type {integer}
  19230. */
  19231. IMAGE: 2,
  19232. /**
  19233. * Game Object type.
  19234. * @constant
  19235. * @type {integer}
  19236. */
  19237. GRAPHICS: 3,
  19238. /**
  19239. * Game Object type.
  19240. * @constant
  19241. * @type {integer}
  19242. */
  19243. TEXT: 4,
  19244. /**
  19245. * Game Object type.
  19246. * @constant
  19247. * @type {integer}
  19248. */
  19249. TILESPRITE: 5,
  19250. /**
  19251. * Game Object type.
  19252. * @constant
  19253. * @type {integer}
  19254. */
  19255. BITMAPTEXT: 6,
  19256. /**
  19257. * Game Object type.
  19258. * @constant
  19259. * @type {integer}
  19260. */
  19261. GROUP: 7,
  19262. /**
  19263. * Game Object type.
  19264. * @constant
  19265. * @type {integer}
  19266. */
  19267. RENDERTEXTURE: 8,
  19268. /**
  19269. * Game Object type.
  19270. * @constant
  19271. * @type {integer}
  19272. */
  19273. TILEMAP: 9,
  19274. /**
  19275. * Game Object type.
  19276. * @constant
  19277. * @type {integer}
  19278. */
  19279. TILEMAPLAYER: 10,
  19280. /**
  19281. * Game Object type.
  19282. * @constant
  19283. * @type {integer}
  19284. */
  19285. EMITTER: 11,
  19286. /**
  19287. * Game Object type.
  19288. * @constant
  19289. * @type {integer}
  19290. */
  19291. POLYGON: 12,
  19292. /**
  19293. * Game Object type.
  19294. * @constant
  19295. * @type {integer}
  19296. */
  19297. BITMAPDATA: 13,
  19298. /**
  19299. * Game Object type.
  19300. * @constant
  19301. * @type {integer}
  19302. */
  19303. CANVAS_FILTER: 14,
  19304. /**
  19305. * Game Object type.
  19306. * @constant
  19307. * @type {integer}
  19308. */
  19309. WEBGL_FILTER: 15,
  19310. /**
  19311. * Game Object type.
  19312. * @constant
  19313. * @type {integer}
  19314. */
  19315. ELLIPSE: 16,
  19316. /**
  19317. * Game Object type.
  19318. * @constant
  19319. * @type {integer}
  19320. */
  19321. SPRITEBATCH: 17,
  19322. /**
  19323. * Game Object type.
  19324. * @constant
  19325. * @type {integer}
  19326. */
  19327. RETROFONT: 18,
  19328. /**
  19329. * Game Object type.
  19330. * @constant
  19331. * @type {integer}
  19332. */
  19333. POINTER: 19,
  19334. /**
  19335. * Game Object type.
  19336. * @constant
  19337. * @type {integer}
  19338. */
  19339. ROPE: 20,
  19340. /**
  19341. * Game Object type.
  19342. * @constant
  19343. * @type {integer}
  19344. */
  19345. CIRCLE: 21,
  19346. /**
  19347. * Game Object type.
  19348. * @constant
  19349. * @type {integer}
  19350. */
  19351. RECTANGLE: 22,
  19352. /**
  19353. * Game Object type.
  19354. * @constant
  19355. * @type {integer}
  19356. */
  19357. LINE: 23,
  19358. /**
  19359. * Game Object type.
  19360. * @constant
  19361. * @type {integer}
  19362. */
  19363. MATRIX: 24,
  19364. /**
  19365. * Game Object type.
  19366. * @constant
  19367. * @type {integer}
  19368. */
  19369. POINT: 25,
  19370. /**
  19371. * Game Object type.
  19372. * @constant
  19373. * @type {integer}
  19374. */
  19375. ROUNDEDRECTANGLE: 26,
  19376. /**
  19377. * Game Object type.
  19378. * @constant
  19379. * @type {integer}
  19380. */
  19381. CREATURE: 27,
  19382. /**
  19383. * Game Object type.
  19384. * @constant
  19385. * @type {integer}
  19386. */
  19387. VIDEO: 28,
  19388. /**
  19389. * Game Object type.
  19390. * @constant
  19391. * @type {integer}
  19392. */
  19393. PENDING_ATLAS: -1,
  19394. /**
  19395. * A horizontal orientation
  19396. * @constant
  19397. * @type {integer}
  19398. */
  19399. HORIZONTAL: 0,
  19400. /**
  19401. * A vertical orientation
  19402. * @constant
  19403. * @type {integer}
  19404. */
  19405. VERTICAL: 1,
  19406. /**
  19407. * A landscape orientation
  19408. * @constant
  19409. * @type {integer}
  19410. */
  19411. LANDSCAPE: 0,
  19412. /**
  19413. * A portrait orientation
  19414. * @constant
  19415. * @type {integer}
  19416. */
  19417. PORTRAIT: 1,
  19418. /**
  19419. * The Angle (in degrees) a Game Object needs to be set to in order to face up.
  19420. * @constant
  19421. * @type {integer}
  19422. */
  19423. ANGLE_UP: 270,
  19424. /**
  19425. * The Angle (in degrees) a Game Object needs to be set to in order to face down.
  19426. * @constant
  19427. * @type {integer}
  19428. */
  19429. ANGLE_DOWN: 90,
  19430. /**
  19431. * The Angle (in degrees) a Game Object needs to be set to in order to face left.
  19432. * @constant
  19433. * @type {integer}
  19434. */
  19435. ANGLE_LEFT: 180,
  19436. /**
  19437. * The Angle (in degrees) a Game Object needs to be set to in order to face right.
  19438. * @constant
  19439. * @type {integer}
  19440. */
  19441. ANGLE_RIGHT: 0,
  19442. /**
  19443. * The Angle (in degrees) a Game Object needs to be set to in order to face north east.
  19444. * @constant
  19445. * @type {integer}
  19446. */
  19447. ANGLE_NORTH_EAST: 315,
  19448. /**
  19449. * The Angle (in degrees) a Game Object needs to be set to in order to face north west.
  19450. * @constant
  19451. * @type {integer}
  19452. */
  19453. ANGLE_NORTH_WEST: 225,
  19454. /**
  19455. * The Angle (in degrees) a Game Object needs to be set to in order to face south east.
  19456. * @constant
  19457. * @type {integer}
  19458. */
  19459. ANGLE_SOUTH_EAST: 45,
  19460. /**
  19461. * The Angle (in degrees) a Game Object needs to be set to in order to face south west.
  19462. * @constant
  19463. * @type {integer}
  19464. */
  19465. ANGLE_SOUTH_WEST: 135,
  19466. /**
  19467. * A constant representing a top-left alignment or position.
  19468. * @constant
  19469. * @type {integer}
  19470. */
  19471. TOP_LEFT: 0,
  19472. /**
  19473. * A constant representing a top-center alignment or position.
  19474. * @constant
  19475. * @type {integer}
  19476. */
  19477. TOP_CENTER: 1,
  19478. /**
  19479. * A constant representing a top-right alignment or position.
  19480. * @constant
  19481. * @type {integer}
  19482. */
  19483. TOP_RIGHT: 2,
  19484. /**
  19485. * A constant representing a left-top alignment or position.
  19486. * @constant
  19487. * @type {integer}
  19488. */
  19489. LEFT_TOP: 3,
  19490. /**
  19491. * A constant representing a left-center alignment or position.
  19492. * @constant
  19493. * @type {integer}
  19494. */
  19495. LEFT_CENTER: 4,
  19496. /**
  19497. * A constant representing a left-bottom alignment or position.
  19498. * @constant
  19499. * @type {integer}
  19500. */
  19501. LEFT_BOTTOM: 5,
  19502. /**
  19503. * A constant representing a center alignment or position.
  19504. * @constant
  19505. * @type {integer}
  19506. */
  19507. CENTER: 6,
  19508. /**
  19509. * A constant representing a right-top alignment or position.
  19510. * @constant
  19511. * @type {integer}
  19512. */
  19513. RIGHT_TOP: 7,
  19514. /**
  19515. * A constant representing a right-center alignment or position.
  19516. * @constant
  19517. * @type {integer}
  19518. */
  19519. RIGHT_CENTER: 8,
  19520. /**
  19521. * A constant representing a right-bottom alignment or position.
  19522. * @constant
  19523. * @type {integer}
  19524. */
  19525. RIGHT_BOTTOM: 9,
  19526. /**
  19527. * A constant representing a bottom-left alignment or position.
  19528. * @constant
  19529. * @type {integer}
  19530. */
  19531. BOTTOM_LEFT: 10,
  19532. /**
  19533. * A constant representing a bottom-center alignment or position.
  19534. * @constant
  19535. * @type {integer}
  19536. */
  19537. BOTTOM_CENTER: 11,
  19538. /**
  19539. * A constant representing a bottom-right alignment or position.
  19540. * @constant
  19541. * @type {integer}
  19542. */
  19543. BOTTOM_RIGHT: 12,
  19544. /**
  19545. * Various blend modes supported by Pixi.
  19546. *
  19547. * IMPORTANT: The WebGL renderer only supports the NORMAL, ADD, MULTIPLY and SCREEN blend modes.
  19548. *
  19549. * @constant
  19550. * @property {Number} blendModes.NORMAL
  19551. * @property {Number} blendModes.ADD
  19552. * @property {Number} blendModes.MULTIPLY
  19553. * @property {Number} blendModes.SCREEN
  19554. * @property {Number} blendModes.OVERLAY
  19555. * @property {Number} blendModes.DARKEN
  19556. * @property {Number} blendModes.LIGHTEN
  19557. * @property {Number} blendModes.COLOR_DODGE
  19558. * @property {Number} blendModes.COLOR_BURN
  19559. * @property {Number} blendModes.HARD_LIGHT
  19560. * @property {Number} blendModes.SOFT_LIGHT
  19561. * @property {Number} blendModes.DIFFERENCE
  19562. * @property {Number} blendModes.EXCLUSION
  19563. * @property {Number} blendModes.HUE
  19564. * @property {Number} blendModes.SATURATION
  19565. * @property {Number} blendModes.COLOR
  19566. * @property {Number} blendModes.LUMINOSITY
  19567. * @static
  19568. */
  19569. blendModes: {
  19570. NORMAL:0,
  19571. ADD:1,
  19572. MULTIPLY:2,
  19573. SCREEN:3,
  19574. OVERLAY:4,
  19575. DARKEN:5,
  19576. LIGHTEN:6,
  19577. COLOR_DODGE:7,
  19578. COLOR_BURN:8,
  19579. HARD_LIGHT:9,
  19580. SOFT_LIGHT:10,
  19581. DIFFERENCE:11,
  19582. EXCLUSION:12,
  19583. HUE:13,
  19584. SATURATION:14,
  19585. COLOR:15,
  19586. LUMINOSITY:16
  19587. },
  19588. /**
  19589. * The scale modes that are supported by Pixi.
  19590. *
  19591. * The DEFAULT scale mode affects the default scaling mode of future operations.
  19592. * It can be re-assigned to either LINEAR or NEAREST, depending upon suitability.
  19593. *
  19594. * @constant
  19595. * @property {Object} Phaser.scaleModes
  19596. * @property {Number} scaleModes.DEFAULT=LINEAR
  19597. * @property {Number} scaleModes.LINEAR Smooth scaling
  19598. * @property {Number} scaleModes.NEAREST Pixelating scaling
  19599. * @static
  19600. */
  19601. scaleModes: {
  19602. DEFAULT:0,
  19603. LINEAR:0,
  19604. NEAREST:1
  19605. },
  19606. PIXI: PIXI || {}
  19607. };
  19608. /**
  19609. * @copyright 2016 Photon Storm Ltd.
  19610. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  19611. */
  19612. // ES6 Math.trunc - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc
  19613. if (!Math.trunc) {
  19614. Math.trunc = function trunc(x) {
  19615. return x < 0 ? Math.ceil(x) : Math.floor(x);
  19616. };
  19617. }
  19618. /**
  19619. * A polyfill for Function.prototype.bind
  19620. */
  19621. if (!Function.prototype.bind) {
  19622. /* jshint freeze: false */
  19623. Function.prototype.bind = (function () {
  19624. var slice = Array.prototype.slice;
  19625. return function (thisArg) {
  19626. var target = this, boundArgs = slice.call(arguments, 1);
  19627. if (typeof target !== 'function')
  19628. {
  19629. throw new TypeError();
  19630. }
  19631. function bound() {
  19632. var args = boundArgs.concat(slice.call(arguments));
  19633. target.apply(this instanceof bound ? this : thisArg, args);
  19634. }
  19635. bound.prototype = (function F(proto) {
  19636. if (proto)
  19637. {
  19638. F.prototype = proto;
  19639. }
  19640. if (!(this instanceof F))
  19641. {
  19642. /* jshint supernew: true */
  19643. return new F;
  19644. }
  19645. })(target.prototype);
  19646. return bound;
  19647. };
  19648. })();
  19649. }
  19650. /**
  19651. * A polyfill for Array.isArray
  19652. */
  19653. if (!Array.isArray)
  19654. {
  19655. Array.isArray = function (arg)
  19656. {
  19657. return Object.prototype.toString.call(arg) === '[object Array]';
  19658. };
  19659. }
  19660. /**
  19661. * A polyfill for Array.forEach
  19662. * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach
  19663. */
  19664. if (!Array.prototype.forEach)
  19665. {
  19666. Array.prototype.forEach = function(fun /*, thisArg */)
  19667. {
  19668. "use strict";
  19669. if (this === void 0 || this === null)
  19670. {
  19671. throw new TypeError();
  19672. }
  19673. var t = Object(this);
  19674. var len = t.length >>> 0;
  19675. if (typeof fun !== "function")
  19676. {
  19677. throw new TypeError();
  19678. }
  19679. var thisArg = arguments.length >= 2 ? arguments[1] : void 0;
  19680. for (var i = 0; i < len; i++)
  19681. {
  19682. if (i in t)
  19683. {
  19684. fun.call(thisArg, t[i], i, t);
  19685. }
  19686. }
  19687. };
  19688. }
  19689. /**
  19690. * Low-budget Float32Array knock-off, suitable for use with P2.js in IE9
  19691. * Source: http://www.html5gamedevs.com/topic/5988-phaser-12-ie9/
  19692. * Cameron Foale (http://www.kibibu.com)
  19693. */
  19694. if (typeof window.Uint32Array !== "function" && typeof window.Uint32Array !== "object")
  19695. {
  19696. var CheapArray = function(type)
  19697. {
  19698. var proto = new Array(); // jshint ignore:line
  19699. window[type] = function(arg) {
  19700. if (typeof(arg) === "number")
  19701. {
  19702. Array.call(this, arg);
  19703. this.length = arg;
  19704. for (var i = 0; i < this.length; i++)
  19705. {
  19706. this[i] = 0;
  19707. }
  19708. }
  19709. else
  19710. {
  19711. Array.call(this, arg.length);
  19712. this.length = arg.length;
  19713. for (var i = 0; i < this.length; i++)
  19714. {
  19715. this[i] = arg[i];
  19716. }
  19717. }
  19718. };
  19719. window[type].prototype = proto;
  19720. window[type].constructor = window[type];
  19721. };
  19722. CheapArray('Uint32Array'); // jshint ignore:line
  19723. CheapArray('Int16Array'); // jshint ignore:line
  19724. }
  19725. /**
  19726. * Also fix for the absent console in IE9
  19727. */
  19728. if (!window.console)
  19729. {
  19730. window.console = {};
  19731. window.console.log = window.console.assert = function(){};
  19732. window.console.warn = window.console.assert = function(){};
  19733. }
  19734. /**
  19735. * @author Richard Davey <rich@photonstorm.com>
  19736. * @copyright 2016 Photon Storm Ltd.
  19737. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  19738. */
  19739. /**
  19740. * @class Phaser.Utils
  19741. * @static
  19742. */
  19743. Phaser.Utils = {
  19744. /**
  19745. * Takes the given string and reverses it, returning the reversed string.
  19746. * For example if given the string `Atari 520ST` it would return `TS025 iratA`.
  19747. *
  19748. * @method Phaser.Utils.reverseString
  19749. * @param {string} string - The string to be reversed.
  19750. * @return {string} The reversed string.
  19751. */
  19752. reverseString: function (string) {
  19753. return string.split('').reverse().join('');
  19754. },
  19755. /**
  19756. * Gets an objects property by string.
  19757. *
  19758. * @method Phaser.Utils.getProperty
  19759. * @param {object} obj - The object to traverse.
  19760. * @param {string} prop - The property whose value will be returned.
  19761. * @return {*} the value of the property or null if property isn't found .
  19762. */
  19763. getProperty: function(obj, prop) {
  19764. var parts = prop.split('.'),
  19765. last = parts.pop(),
  19766. l = parts.length,
  19767. i = 1,
  19768. current = parts[0];
  19769. while (i < l && (obj = obj[current]))
  19770. {
  19771. current = parts[i];
  19772. i++;
  19773. }
  19774. if (obj)
  19775. {
  19776. return obj[last];
  19777. }
  19778. else
  19779. {
  19780. return null;
  19781. }
  19782. },
  19783. /**
  19784. * Sets an objects property by string.
  19785. *
  19786. * @method Phaser.Utils.setProperty
  19787. * @param {object} obj - The object to traverse
  19788. * @param {string} prop - The property whose value will be changed
  19789. * @return {object} The object on which the property was set.
  19790. */
  19791. setProperty: function(obj, prop, value) {
  19792. var parts = prop.split('.'),
  19793. last = parts.pop(),
  19794. l = parts.length,
  19795. i = 1,
  19796. current = parts[0];
  19797. while (i < l && (obj = obj[current]))
  19798. {
  19799. current = parts[i];
  19800. i++;
  19801. }
  19802. if (obj)
  19803. {
  19804. obj[last] = value;
  19805. }
  19806. return obj;
  19807. },
  19808. /**
  19809. * Generate a random bool result based on the chance value.
  19810. *
  19811. * Returns true or false based on the chance value (default 50%). For example if you wanted a player to have a 30% chance
  19812. * of getting a bonus, call chanceRoll(30) - true means the chance passed, false means it failed.
  19813. *
  19814. * @method Phaser.Utils#chanceRoll
  19815. * @param {number} chance - The chance of receiving the value. A number between 0 and 100 (effectively 0% to 100%).
  19816. * @return {boolean} True if the roll passed, or false otherwise.
  19817. */
  19818. chanceRoll: function (chance) {
  19819. if (chance === undefined) { chance = 50; }
  19820. return chance > 0 && (Math.random() * 100 <= chance);
  19821. },
  19822. /**
  19823. * Choose between one of two values randomly.
  19824. *
  19825. * @method Phaser.Utils#randomChoice
  19826. * @param {any} choice1
  19827. * @param {any} choice2
  19828. * @return {any} The randomly selected choice
  19829. */
  19830. randomChoice: function (choice1, choice2) {
  19831. return (Math.random() < 0.5) ? choice1 : choice2;
  19832. },
  19833. /**
  19834. * Get a unit dimension from a string.
  19835. *
  19836. * @method Phaser.Utils.parseDimension
  19837. * @param {string|number} size - The size to parse.
  19838. * @param {number} dimension - The window dimension to check.
  19839. * @return {number} The parsed dimension.
  19840. */
  19841. parseDimension: function (size, dimension) {
  19842. var f = 0;
  19843. var px = 0;
  19844. if (typeof size === 'string')
  19845. {
  19846. // %?
  19847. if (size.substr(-1) === '%')
  19848. {
  19849. f = parseInt(size, 10) / 100;
  19850. if (dimension === 0)
  19851. {
  19852. px = window.innerWidth * f;
  19853. }
  19854. else
  19855. {
  19856. px = window.innerHeight * f;
  19857. }
  19858. }
  19859. else
  19860. {
  19861. px = parseInt(size, 10);
  19862. }
  19863. }
  19864. else
  19865. {
  19866. px = size;
  19867. }
  19868. return px;
  19869. },
  19870. /**
  19871. * Takes the given string and pads it out, to the length required, using the character
  19872. * specified. For example if you need a string to be 6 characters long, you can call:
  19873. *
  19874. * `pad('bob', 6, '-', 2)`
  19875. *
  19876. * This would return: `bob---` as it has padded it out to 6 characters, using the `-` on the right.
  19877. *
  19878. * You can also use it to pad numbers (they are always returned as strings):
  19879. *
  19880. * `pad(512, 6, '0', 1)`
  19881. *
  19882. * Would return: `000512` with the string padded to the left.
  19883. *
  19884. * If you don't specify a direction it'll pad to both sides:
  19885. *
  19886. * `pad('c64', 7, '*')`
  19887. *
  19888. * Would return: `**c64**`
  19889. *
  19890. * @method Phaser.Utils.pad
  19891. * @param {string} str - The target string. `toString()` will be called on the string, which means you can also pass in common data types like numbers.
  19892. * @param {integer} [len=0] - The number of characters to be added.
  19893. * @param {string} [pad=" "] - The string to pad it out with (defaults to a space).
  19894. * @param {integer} [dir=3] - The direction dir = 1 (left), 2 (right), 3 (both).
  19895. * @return {string} The padded string.
  19896. */
  19897. pad: function (str, len, pad, dir) {
  19898. if (len === undefined) { var len = 0; }
  19899. if (pad === undefined) { var pad = ' '; }
  19900. if (dir === undefined) { var dir = 3; }
  19901. str = str.toString();
  19902. var padlen = 0;
  19903. if (len + 1 >= str.length)
  19904. {
  19905. switch (dir)
  19906. {
  19907. case 1:
  19908. str = new Array(len + 1 - str.length).join(pad) + str;
  19909. break;
  19910. case 3:
  19911. var right = Math.ceil((padlen = len - str.length) / 2);
  19912. var left = padlen - right;
  19913. str = new Array(left+1).join(pad) + str + new Array(right+1).join(pad);
  19914. break;
  19915. default:
  19916. str = str + new Array(len + 1 - str.length).join(pad);
  19917. break;
  19918. }
  19919. }
  19920. return str;
  19921. },
  19922. /**
  19923. * This is a slightly modified version of jQuery.isPlainObject.
  19924. * A plain object is an object whose internal class property is [object Object].
  19925. * @method Phaser.Utils.isPlainObject
  19926. * @param {object} obj - The object to inspect.
  19927. * @return {boolean} - true if the object is plain, otherwise false.
  19928. */
  19929. isPlainObject: function (obj) {
  19930. // Not plain objects:
  19931. // - Any object or value whose internal [[Class]] property is not "[object Object]"
  19932. // - DOM nodes
  19933. // - window
  19934. if (typeof(obj) !== "object" || obj.nodeType || obj === obj.window)
  19935. {
  19936. return false;
  19937. }
  19938. // Support: Firefox <20
  19939. // The try/catch suppresses exceptions thrown when attempting to access
  19940. // the "constructor" property of certain host objects, ie. |window.location|
  19941. // https://bugzilla.mozilla.org/show_bug.cgi?id=814622
  19942. try {
  19943. if (obj.constructor && !({}).hasOwnProperty.call(obj.constructor.prototype, "isPrototypeOf"))
  19944. {
  19945. return false;
  19946. }
  19947. } catch (e) {
  19948. return false;
  19949. }
  19950. // If the function hasn't returned already, we're confident that
  19951. // |obj| is a plain object, created by {} or constructed with new Object
  19952. return true;
  19953. },
  19954. /**
  19955. * This is a slightly modified version of http://api.jquery.com/jQuery.extend/
  19956. *
  19957. * @method Phaser.Utils.extend
  19958. * @param {boolean} deep - Perform a deep copy?
  19959. * @param {object} target - The target object to copy to.
  19960. * @return {object} The extended object.
  19961. */
  19962. extend: function () {
  19963. var options, name, src, copy, copyIsArray, clone,
  19964. target = arguments[0] || {},
  19965. i = 1,
  19966. length = arguments.length,
  19967. deep = false;
  19968. // Handle a deep copy situation
  19969. if (typeof target === "boolean")
  19970. {
  19971. deep = target;
  19972. target = arguments[1] || {};
  19973. // skip the boolean and the target
  19974. i = 2;
  19975. }
  19976. // extend Phaser if only one argument is passed
  19977. if (length === i)
  19978. {
  19979. target = this;
  19980. --i;
  19981. }
  19982. for (; i < length; i++)
  19983. {
  19984. // Only deal with non-null/undefined values
  19985. if ((options = arguments[i]) != null)
  19986. {
  19987. // Extend the base object
  19988. for (name in options)
  19989. {
  19990. src = target[name];
  19991. copy = options[name];
  19992. // Prevent never-ending loop
  19993. if (target === copy)
  19994. {
  19995. continue;
  19996. }
  19997. // Recurse if we're merging plain objects or arrays
  19998. if (deep && copy && (Phaser.Utils.isPlainObject(copy) || (copyIsArray = Array.isArray(copy))))
  19999. {
  20000. if (copyIsArray)
  20001. {
  20002. copyIsArray = false;
  20003. clone = src && Array.isArray(src) ? src : [];
  20004. }
  20005. else
  20006. {
  20007. clone = src && Phaser.Utils.isPlainObject(src) ? src : {};
  20008. }
  20009. // Never move original objects, clone them
  20010. target[name] = Phaser.Utils.extend(deep, clone, copy);
  20011. // Don't bring in undefined values
  20012. }
  20013. else if (copy !== undefined)
  20014. {
  20015. target[name] = copy;
  20016. }
  20017. }
  20018. }
  20019. }
  20020. // Return the modified object
  20021. return target;
  20022. },
  20023. /**
  20024. * Mixes in an existing mixin object with the target.
  20025. *
  20026. * Values in the mixin that have either `get` or `set` functions are created as properties via `defineProperty`
  20027. * _except_ if they also define a `clone` method - if a clone method is defined that is called instead and
  20028. * the result is assigned directly.
  20029. *
  20030. * @method Phaser.Utils.mixinPrototype
  20031. * @param {object} target - The target object to receive the new functions.
  20032. * @param {object} mixin - The object to copy the functions from.
  20033. * @param {boolean} [replace=false] - If the target object already has a matching function should it be overwritten or not?
  20034. */
  20035. mixinPrototype: function (target, mixin, replace) {
  20036. if (replace === undefined) { replace = false; }
  20037. var mixinKeys = Object.keys(mixin);
  20038. for (var i = 0; i < mixinKeys.length; i++)
  20039. {
  20040. var key = mixinKeys[i];
  20041. var value = mixin[key];
  20042. if (!replace && (key in target))
  20043. {
  20044. // Not overwriting existing property
  20045. continue;
  20046. }
  20047. else
  20048. {
  20049. if (value &&
  20050. (typeof value.get === 'function' || typeof value.set === 'function'))
  20051. {
  20052. // Special case for classes like Phaser.Point which has a 'set' function!
  20053. if (typeof value.clone === 'function')
  20054. {
  20055. target[key] = value.clone();
  20056. }
  20057. else
  20058. {
  20059. Object.defineProperty(target, key, value);
  20060. }
  20061. }
  20062. else
  20063. {
  20064. target[key] = value;
  20065. }
  20066. }
  20067. }
  20068. },
  20069. /**
  20070. * Mixes the source object into the destination object, returning the newly modified destination object.
  20071. * Based on original code by @mudcube
  20072. *
  20073. * @method Phaser.Utils.mixin
  20074. * @param {object} from - The object to copy (the source object).
  20075. * @param {object} to - The object to copy to (the destination object).
  20076. * @return {object} The modified destination object.
  20077. */
  20078. mixin: function (from, to) {
  20079. if (!from || typeof (from) !== "object")
  20080. {
  20081. return to;
  20082. }
  20083. for (var key in from)
  20084. {
  20085. var o = from[key];
  20086. if (o.childNodes || o.cloneNode)
  20087. {
  20088. continue;
  20089. }
  20090. var type = typeof (from[key]);
  20091. if (!from[key] || type !== "object")
  20092. {
  20093. to[key] = from[key];
  20094. }
  20095. else
  20096. {
  20097. // Clone sub-object
  20098. if (typeof (to[key]) === type)
  20099. {
  20100. to[key] = Phaser.Utils.mixin(from[key], to[key]);
  20101. }
  20102. else
  20103. {
  20104. to[key] = Phaser.Utils.mixin(from[key], new o.constructor());
  20105. }
  20106. }
  20107. }
  20108. return to;
  20109. }
  20110. };
  20111. /**
  20112. * @author Richard Davey <rich@photonstorm.com>
  20113. * @copyright 2016 Photon Storm Ltd.
  20114. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  20115. */
  20116. /**
  20117. * Creates a new Circle object with the center coordinate specified by the x and y parameters and the diameter specified by the diameter parameter.
  20118. * If you call this function without parameters, a circle with x, y, diameter and radius properties set to 0 is created.
  20119. *
  20120. * @class Phaser.Circle
  20121. * @constructor
  20122. * @param {number} [x=0] - The x coordinate of the center of the circle.
  20123. * @param {number} [y=0] - The y coordinate of the center of the circle.
  20124. * @param {number} [diameter=0] - The diameter of the circle.
  20125. */
  20126. Phaser.Circle = function (x, y, diameter) {
  20127. x = x || 0;
  20128. y = y || 0;
  20129. diameter = diameter || 0;
  20130. /**
  20131. * @property {number} x - The x coordinate of the center of the circle.
  20132. */
  20133. this.x = x;
  20134. /**
  20135. * @property {number} y - The y coordinate of the center of the circle.
  20136. */
  20137. this.y = y;
  20138. /**
  20139. * @property {number} _diameter - The diameter of the circle.
  20140. * @private
  20141. */
  20142. this._diameter = diameter;
  20143. /**
  20144. * @property {number} _radius - The radius of the circle.
  20145. * @private
  20146. */
  20147. this._radius = 0;
  20148. if (diameter > 0)
  20149. {
  20150. this._radius = diameter * 0.5;
  20151. }
  20152. /**
  20153. * @property {number} type - The const type of this object.
  20154. * @readonly
  20155. */
  20156. this.type = Phaser.CIRCLE;
  20157. };
  20158. Phaser.Circle.prototype = {
  20159. /**
  20160. * The circumference of the circle.
  20161. *
  20162. * @method Phaser.Circle#circumference
  20163. * @return {number} The circumference of the circle.
  20164. */
  20165. circumference: function () {
  20166. return 2 * (Math.PI * this._radius);
  20167. },
  20168. /**
  20169. * Returns a uniformly distributed random point from anywhere within this Circle.
  20170. *
  20171. * @method Phaser.Circle#random
  20172. * @param {Phaser.Point|object} [out] - A Phaser.Point, or any object with public x/y properties, that the values will be set in.
  20173. * If no object is provided a new Phaser.Point object will be created. In high performance areas avoid this by re-using an existing object.
  20174. * @return {Phaser.Point} An object containing the random point in its `x` and `y` properties.
  20175. */
  20176. random: function (out) {
  20177. if (out === undefined) { out = new Phaser.Point(); }
  20178. var t = 2 * Math.PI * Math.random();
  20179. var u = Math.random() + Math.random();
  20180. var r = (u > 1) ? 2 - u : u;
  20181. var x = r * Math.cos(t);
  20182. var y = r * Math.sin(t);
  20183. out.x = this.x + (x * this.radius);
  20184. out.y = this.y + (y * this.radius);
  20185. return out;
  20186. },
  20187. /**
  20188. * Returns the framing rectangle of the circle as a Phaser.Rectangle object.
  20189. *
  20190. * @method Phaser.Circle#getBounds
  20191. * @return {Phaser.Rectangle} The bounds of the Circle.
  20192. */
  20193. getBounds: function () {
  20194. return new Phaser.Rectangle(this.x - this.radius, this.y - this.radius, this.diameter, this.diameter);
  20195. },
  20196. /**
  20197. * Sets the members of Circle to the specified values.
  20198. * @method Phaser.Circle#setTo
  20199. * @param {number} x - The x coordinate of the center of the circle.
  20200. * @param {number} y - The y coordinate of the center of the circle.
  20201. * @param {number} diameter - The diameter of the circle.
  20202. * @return {Circle} This circle object.
  20203. */
  20204. setTo: function (x, y, diameter) {
  20205. this.x = x;
  20206. this.y = y;
  20207. this._diameter = diameter;
  20208. this._radius = diameter * 0.5;
  20209. return this;
  20210. },
  20211. /**
  20212. * Copies the x, y and diameter properties from any given object to this Circle.
  20213. * @method Phaser.Circle#copyFrom
  20214. * @param {any} source - The object to copy from.
  20215. * @return {Circle} This Circle object.
  20216. */
  20217. copyFrom: function (source) {
  20218. return this.setTo(source.x, source.y, source.diameter);
  20219. },
  20220. /**
  20221. * Copies the x, y and diameter properties from this Circle to any given object.
  20222. * @method Phaser.Circle#copyTo
  20223. * @param {any} dest - The object to copy to.
  20224. * @return {object} This dest object.
  20225. */
  20226. copyTo: function (dest) {
  20227. dest.x = this.x;
  20228. dest.y = this.y;
  20229. dest.diameter = this._diameter;
  20230. return dest;
  20231. },
  20232. /**
  20233. * Returns the distance from the center of the Circle object to the given object
  20234. * (can be Circle, Point or anything with x/y properties)
  20235. * @method Phaser.Circle#distance
  20236. * @param {object} dest - The target object. Must have visible x and y properties that represent the center of the object.
  20237. * @param {boolean} [round=false] - Round the distance to the nearest integer.
  20238. * @return {number} The distance between this Point object and the destination Point object.
  20239. */
  20240. distance: function (dest, round) {
  20241. var distance = Phaser.Math.distance(this.x, this.y, dest.x, dest.y);
  20242. return round ? Math.round(distance) : distance;
  20243. },
  20244. /**
  20245. * Returns a new Circle object with the same values for the x, y, width, and height properties as this Circle object.
  20246. * @method Phaser.Circle#clone
  20247. * @param {Phaser.Circle} output - Optional Circle object. If given the values will be set into the object, otherwise a brand new Circle object will be created and returned.
  20248. * @return {Phaser.Circle} The cloned Circle object.
  20249. */
  20250. clone: function (output) {
  20251. if (output === undefined || output === null)
  20252. {
  20253. output = new Phaser.Circle(this.x, this.y, this.diameter);
  20254. }
  20255. else
  20256. {
  20257. output.setTo(this.x, this.y, this.diameter);
  20258. }
  20259. return output;
  20260. },
  20261. /**
  20262. * Return true if the given x/y coordinates are within this Circle object.
  20263. * @method Phaser.Circle#contains
  20264. * @param {number} x - The X value of the coordinate to test.
  20265. * @param {number} y - The Y value of the coordinate to test.
  20266. * @return {boolean} True if the coordinates are within this circle, otherwise false.
  20267. */
  20268. contains: function (x, y) {
  20269. return Phaser.Circle.contains(this, x, y);
  20270. },
  20271. /**
  20272. * Returns a Point object containing the coordinates of a point on the circumference of the Circle based on the given angle.
  20273. * @method Phaser.Circle#circumferencePoint
  20274. * @param {number} angle - The angle in radians (unless asDegrees is true) to return the point from.
  20275. * @param {boolean} [asDegrees=false] - Is the given angle in radians (false) or degrees (true)?
  20276. * @param {Phaser.Point} [out] - An optional Point object to put the result in to. If none specified a new Point object will be created.
  20277. * @return {Phaser.Point} The Point object holding the result.
  20278. */
  20279. circumferencePoint: function (angle, asDegrees, out) {
  20280. return Phaser.Circle.circumferencePoint(this, angle, asDegrees, out);
  20281. },
  20282. /**
  20283. * Adjusts the location of the Circle object, as determined by its center coordinate, by the specified amounts.
  20284. * @method Phaser.Circle#offset
  20285. * @param {number} dx - Moves the x value of the Circle object by this amount.
  20286. * @param {number} dy - Moves the y value of the Circle object by this amount.
  20287. * @return {Circle} This Circle object.
  20288. */
  20289. offset: function (dx, dy) {
  20290. this.x += dx;
  20291. this.y += dy;
  20292. return this;
  20293. },
  20294. /**
  20295. * Adjusts the location of the Circle object using a Point object as a parameter. This method is similar to the Circle.offset() method, except that it takes a Point object as a parameter.
  20296. * @method Phaser.Circle#offsetPoint
  20297. * @param {Point} point A Point object to use to offset this Circle object (or any valid object with exposed x and y properties).
  20298. * @return {Circle} This Circle object.
  20299. */
  20300. offsetPoint: function (point) {
  20301. return this.offset(point.x, point.y);
  20302. },
  20303. /**
  20304. * Returns a string representation of this object.
  20305. * @method Phaser.Circle#toString
  20306. * @return {string} a string representation of the instance.
  20307. */
  20308. toString: function () {
  20309. return "[{Phaser.Circle (x=" + this.x + " y=" + this.y + " diameter=" + this.diameter + " radius=" + this.radius + ")}]";
  20310. }
  20311. };
  20312. Phaser.Circle.prototype.constructor = Phaser.Circle;
  20313. /**
  20314. * The largest distance between any two points on the circle. The same as the radius * 2.
  20315. *
  20316. * @name Phaser.Circle#diameter
  20317. * @property {number} diameter - Gets or sets the diameter of the circle.
  20318. */
  20319. Object.defineProperty(Phaser.Circle.prototype, "diameter", {
  20320. get: function () {
  20321. return this._diameter;
  20322. },
  20323. set: function (value) {
  20324. if (value > 0)
  20325. {
  20326. this._diameter = value;
  20327. this._radius = value * 0.5;
  20328. }
  20329. }
  20330. });
  20331. /**
  20332. * The length of a line extending from the center of the circle to any point on the circle itself. The same as half the diameter.
  20333. * @name Phaser.Circle#radius
  20334. * @property {number} radius - Gets or sets the radius of the circle.
  20335. */
  20336. Object.defineProperty(Phaser.Circle.prototype, "radius", {
  20337. get: function () {
  20338. return this._radius;
  20339. },
  20340. set: function (value) {
  20341. if (value > 0)
  20342. {
  20343. this._radius = value;
  20344. this._diameter = value * 2;
  20345. }
  20346. }
  20347. });
  20348. /**
  20349. * The x coordinate of the leftmost point of the circle. Changing the left property of a Circle object has no effect on the x and y properties. However it does affect the diameter, whereas changing the x value does not affect the diameter property.
  20350. * @name Phaser.Circle#left
  20351. * @propety {number} left - Gets or sets the value of the leftmost point of the circle.
  20352. */
  20353. Object.defineProperty(Phaser.Circle.prototype, "left", {
  20354. get: function () {
  20355. return this.x - this._radius;
  20356. },
  20357. set: function (value) {
  20358. if (value > this.x)
  20359. {
  20360. this._radius = 0;
  20361. this._diameter = 0;
  20362. }
  20363. else
  20364. {
  20365. this.radius = this.x - value;
  20366. }
  20367. }
  20368. });
  20369. /**
  20370. * The x coordinate of the rightmost point of the circle. Changing the right property of a Circle object has no effect on the x and y properties. However it does affect the diameter, whereas changing the x value does not affect the diameter property.
  20371. * @name Phaser.Circle#right
  20372. * @property {number} right - Gets or sets the value of the rightmost point of the circle.
  20373. */
  20374. Object.defineProperty(Phaser.Circle.prototype, "right", {
  20375. get: function () {
  20376. return this.x + this._radius;
  20377. },
  20378. set: function (value) {
  20379. if (value < this.x)
  20380. {
  20381. this._radius = 0;
  20382. this._diameter = 0;
  20383. }
  20384. else
  20385. {
  20386. this.radius = value - this.x;
  20387. }
  20388. }
  20389. });
  20390. /**
  20391. * The sum of the y minus the radius property. Changing the top property of a Circle object has no effect on the x and y properties, but does change the diameter.
  20392. * @name Phaser.Circle#top
  20393. * @property {number} top - Gets or sets the top of the circle.
  20394. */
  20395. Object.defineProperty(Phaser.Circle.prototype, "top", {
  20396. get: function () {
  20397. return this.y - this._radius;
  20398. },
  20399. set: function (value) {
  20400. if (value > this.y)
  20401. {
  20402. this._radius = 0;
  20403. this._diameter = 0;
  20404. }
  20405. else
  20406. {
  20407. this.radius = this.y - value;
  20408. }
  20409. }
  20410. });
  20411. /**
  20412. * The sum of the y and radius properties. Changing the bottom property of a Circle object has no effect on the x and y properties, but does change the diameter.
  20413. * @name Phaser.Circle#bottom
  20414. * @property {number} bottom - Gets or sets the bottom of the circle.
  20415. */
  20416. Object.defineProperty(Phaser.Circle.prototype, "bottom", {
  20417. get: function () {
  20418. return this.y + this._radius;
  20419. },
  20420. set: function (value) {
  20421. if (value < this.y)
  20422. {
  20423. this._radius = 0;
  20424. this._diameter = 0;
  20425. }
  20426. else
  20427. {
  20428. this.radius = value - this.y;
  20429. }
  20430. }
  20431. });
  20432. /**
  20433. * The area of this Circle.
  20434. * @name Phaser.Circle#area
  20435. * @property {number} area - The area of this circle.
  20436. * @readonly
  20437. */
  20438. Object.defineProperty(Phaser.Circle.prototype, "area", {
  20439. get: function () {
  20440. if (this._radius > 0)
  20441. {
  20442. return Math.PI * this._radius * this._radius;
  20443. }
  20444. else
  20445. {
  20446. return 0;
  20447. }
  20448. }
  20449. });
  20450. /**
  20451. * Determines whether or not this Circle object is empty. Will return a value of true if the Circle objects diameter is less than or equal to 0; otherwise false.
  20452. * If set to true it will reset all of the Circle objects properties to 0. A Circle object is empty if its diameter is less than or equal to 0.
  20453. * @name Phaser.Circle#empty
  20454. * @property {boolean} empty - Gets or sets the empty state of the circle.
  20455. */
  20456. Object.defineProperty(Phaser.Circle.prototype, "empty", {
  20457. get: function () {
  20458. return (this._diameter === 0);
  20459. },
  20460. set: function (value) {
  20461. if (value === true)
  20462. {
  20463. this.setTo(0, 0, 0);
  20464. }
  20465. }
  20466. });
  20467. /**
  20468. * Return true if the given x/y coordinates are within the Circle object.
  20469. * @method Phaser.Circle.contains
  20470. * @param {Phaser.Circle} a - The Circle to be checked.
  20471. * @param {number} x - The X value of the coordinate to test.
  20472. * @param {number} y - The Y value of the coordinate to test.
  20473. * @return {boolean} True if the coordinates are within this circle, otherwise false.
  20474. */
  20475. Phaser.Circle.contains = function (a, x, y) {
  20476. // Check if x/y are within the bounds first
  20477. if (a.radius > 0 && x >= a.left && x <= a.right && y >= a.top && y <= a.bottom)
  20478. {
  20479. var dx = (a.x - x) * (a.x - x);
  20480. var dy = (a.y - y) * (a.y - y);
  20481. return (dx + dy) <= (a.radius * a.radius);
  20482. }
  20483. else
  20484. {
  20485. return false;
  20486. }
  20487. };
  20488. /**
  20489. * Determines whether the two Circle objects match. This method compares the x, y and diameter properties.
  20490. * @method Phaser.Circle.equals
  20491. * @param {Phaser.Circle} a - The first Circle object.
  20492. * @param {Phaser.Circle} b - The second Circle object.
  20493. * @return {boolean} A value of true if the object has exactly the same values for the x, y and diameter properties as this Circle object; otherwise false.
  20494. */
  20495. Phaser.Circle.equals = function (a, b) {
  20496. return (a.x === b.x && a.y === b.y && a.diameter === b.diameter);
  20497. };
  20498. /**
  20499. * Determines whether the two Circle objects intersect.
  20500. * This method checks the radius distances between the two Circle objects to see if they intersect.
  20501. * @method Phaser.Circle.intersects
  20502. * @param {Phaser.Circle} a - The first Circle object.
  20503. * @param {Phaser.Circle} b - The second Circle object.
  20504. * @return {boolean} A value of true if the specified object intersects with this Circle object; otherwise false.
  20505. */
  20506. Phaser.Circle.intersects = function (a, b) {
  20507. return (Phaser.Math.distance(a.x, a.y, b.x, b.y) <= (a.radius + b.radius));
  20508. };
  20509. /**
  20510. * Returns a Point object containing the coordinates of a point on the circumference of the Circle based on the given angle.
  20511. * @method Phaser.Circle.circumferencePoint
  20512. * @param {Phaser.Circle} a - The first Circle object.
  20513. * @param {number} angle - The angle in radians (unless asDegrees is true) to return the point from.
  20514. * @param {boolean} [asDegrees=false] - Is the given angle in radians (false) or degrees (true)?
  20515. * @param {Phaser.Point} [out] - An optional Point object to put the result in to. If none specified a new Point object will be created.
  20516. * @return {Phaser.Point} The Point object holding the result.
  20517. */
  20518. Phaser.Circle.circumferencePoint = function (a, angle, asDegrees, out) {
  20519. if (asDegrees === undefined) { asDegrees = false; }
  20520. if (out === undefined) { out = new Phaser.Point(); }
  20521. if (asDegrees === true)
  20522. {
  20523. angle = Phaser.Math.degToRad(angle);
  20524. }
  20525. out.x = a.x + a.radius * Math.cos(angle);
  20526. out.y = a.y + a.radius * Math.sin(angle);
  20527. return out;
  20528. };
  20529. /**
  20530. * Checks if the given Circle and Rectangle objects intersect.
  20531. * @method Phaser.Circle.intersectsRectangle
  20532. * @param {Phaser.Circle} c - The Circle object to test.
  20533. * @param {Phaser.Rectangle} r - The Rectangle object to test.
  20534. * @return {boolean} True if the two objects intersect, otherwise false.
  20535. */
  20536. Phaser.Circle.intersectsRectangle = function (c, r) {
  20537. var cx = Math.abs(c.x - r.x - r.halfWidth);
  20538. var xDist = r.halfWidth + c.radius;
  20539. if (cx > xDist)
  20540. {
  20541. return false;
  20542. }
  20543. var cy = Math.abs(c.y - r.y - r.halfHeight);
  20544. var yDist = r.halfHeight + c.radius;
  20545. if (cy > yDist)
  20546. {
  20547. return false;
  20548. }
  20549. if (cx <= r.halfWidth || cy <= r.halfHeight)
  20550. {
  20551. return true;
  20552. }
  20553. var xCornerDist = cx - r.halfWidth;
  20554. var yCornerDist = cy - r.halfHeight;
  20555. var xCornerDistSq = xCornerDist * xCornerDist;
  20556. var yCornerDistSq = yCornerDist * yCornerDist;
  20557. var maxCornerDistSq = c.radius * c.radius;
  20558. return xCornerDistSq + yCornerDistSq <= maxCornerDistSq;
  20559. };
  20560. // Because PIXI uses its own Circle, we'll replace it with ours to avoid duplicating code or confusion.
  20561. PIXI.Circle = Phaser.Circle;
  20562. /**
  20563. * @author Richard Davey <rich@photonstorm.com>
  20564. * @author Chad Engler <chad@pantherdev.com>
  20565. * @copyright 2016 Photon Storm Ltd.
  20566. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  20567. */
  20568. /**
  20569. * Creates a Ellipse object. A curve on a plane surrounding two focal points.
  20570. *
  20571. * @class Phaser.Ellipse
  20572. * @constructor
  20573. * @param {number} [x=0] - The X coordinate of the upper-left corner of the framing rectangle of this ellipse.
  20574. * @param {number} [y=0] - The Y coordinate of the upper-left corner of the framing rectangle of this ellipse.
  20575. * @param {number} [width=0] - The overall width of this ellipse.
  20576. * @param {number} [height=0] - The overall height of this ellipse.
  20577. */
  20578. Phaser.Ellipse = function (x, y, width, height) {
  20579. x = x || 0;
  20580. y = y || 0;
  20581. width = width || 0;
  20582. height = height || 0;
  20583. /**
  20584. * @property {number} x - The X coordinate of the upper-left corner of the framing rectangle of this ellipse.
  20585. */
  20586. this.x = x;
  20587. /**
  20588. * @property {number} y - The Y coordinate of the upper-left corner of the framing rectangle of this ellipse.
  20589. */
  20590. this.y = y;
  20591. /**
  20592. * @property {number} width - The overall width of this ellipse.
  20593. */
  20594. this.width = width;
  20595. /**
  20596. * @property {number} height - The overall height of this ellipse.
  20597. */
  20598. this.height = height;
  20599. /**
  20600. * @property {number} type - The const type of this object.
  20601. * @readonly
  20602. */
  20603. this.type = Phaser.ELLIPSE;
  20604. };
  20605. Phaser.Ellipse.prototype = {
  20606. /**
  20607. * Sets the members of the Ellipse to the specified values.
  20608. * @method Phaser.Ellipse#setTo
  20609. * @param {number} x - The X coordinate of the upper-left corner of the framing rectangle of this ellipse.
  20610. * @param {number} y - The Y coordinate of the upper-left corner of the framing rectangle of this ellipse.
  20611. * @param {number} width - The overall width of this ellipse.
  20612. * @param {number} height - The overall height of this ellipse.
  20613. * @return {Phaser.Ellipse} This Ellipse object.
  20614. */
  20615. setTo: function (x, y, width, height) {
  20616. this.x = x;
  20617. this.y = y;
  20618. this.width = width;
  20619. this.height = height;
  20620. return this;
  20621. },
  20622. /**
  20623. * Returns the framing rectangle of the ellipse as a Phaser.Rectangle object.
  20624. *
  20625. * @method Phaser.Ellipse#getBounds
  20626. * @return {Phaser.Rectangle} The bounds of the Ellipse.
  20627. */
  20628. getBounds: function () {
  20629. return new Phaser.Rectangle(this.x - this.width, this.y - this.height, this.width, this.height);
  20630. },
  20631. /**
  20632. * Copies the x, y, width and height properties from any given object to this Ellipse.
  20633. *
  20634. * @method Phaser.Ellipse#copyFrom
  20635. * @param {any} source - The object to copy from.
  20636. * @return {Phaser.Ellipse} This Ellipse object.
  20637. */
  20638. copyFrom: function (source) {
  20639. return this.setTo(source.x, source.y, source.width, source.height);
  20640. },
  20641. /**
  20642. * Copies the x, y, width and height properties from this Ellipse to any given object.
  20643. * @method Phaser.Ellipse#copyTo
  20644. * @param {any} dest - The object to copy to.
  20645. * @return {object} This dest object.
  20646. */
  20647. copyTo: function(dest) {
  20648. dest.x = this.x;
  20649. dest.y = this.y;
  20650. dest.width = this.width;
  20651. dest.height = this.height;
  20652. return dest;
  20653. },
  20654. /**
  20655. * Returns a new Ellipse object with the same values for the x, y, width, and height properties as this Ellipse object.
  20656. * @method Phaser.Ellipse#clone
  20657. * @param {Phaser.Ellipse} output - Optional Ellipse object. If given the values will be set into the object, otherwise a brand new Ellipse object will be created and returned.
  20658. * @return {Phaser.Ellipse} The cloned Ellipse object.
  20659. */
  20660. clone: function(output) {
  20661. if (output === undefined || output === null)
  20662. {
  20663. output = new Phaser.Ellipse(this.x, this.y, this.width, this.height);
  20664. }
  20665. else
  20666. {
  20667. output.setTo(this.x, this.y, this.width, this.height);
  20668. }
  20669. return output;
  20670. },
  20671. /**
  20672. * Return true if the given x/y coordinates are within this Ellipse object.
  20673. *
  20674. * @method Phaser.Ellipse#contains
  20675. * @param {number} x - The X value of the coordinate to test.
  20676. * @param {number} y - The Y value of the coordinate to test.
  20677. * @return {boolean} True if the coordinates are within this ellipse, otherwise false.
  20678. */
  20679. contains: function (x, y) {
  20680. return Phaser.Ellipse.contains(this, x, y);
  20681. },
  20682. /**
  20683. * Returns a uniformly distributed random point from anywhere within this Ellipse.
  20684. *
  20685. * @method Phaser.Ellipse#random
  20686. * @param {Phaser.Point|object} [out] - A Phaser.Point, or any object with public x/y properties, that the values will be set in.
  20687. * If no object is provided a new Phaser.Point object will be created. In high performance areas avoid this by re-using an existing object.
  20688. * @return {Phaser.Point} An object containing the random point in its `x` and `y` properties.
  20689. */
  20690. random: function (out) {
  20691. if (out === undefined) { out = new Phaser.Point(); }
  20692. var p = Math.random() * Math.PI * 2;
  20693. var r = Math.random();
  20694. out.x = Math.sqrt(r) * Math.cos(p);
  20695. out.y = Math.sqrt(r) * Math.sin(p);
  20696. out.x = this.x + (out.x * this.width / 2.0);
  20697. out.y = this.y + (out.y * this.height / 2.0);
  20698. return out;
  20699. },
  20700. /**
  20701. * Returns a string representation of this object.
  20702. * @method Phaser.Ellipse#toString
  20703. * @return {string} A string representation of the instance.
  20704. */
  20705. toString: function () {
  20706. return "[{Phaser.Ellipse (x=" + this.x + " y=" + this.y + " width=" + this.width + " height=" + this.height + ")}]";
  20707. }
  20708. };
  20709. Phaser.Ellipse.prototype.constructor = Phaser.Ellipse;
  20710. /**
  20711. * The left coordinate of the Ellipse. The same as the X coordinate.
  20712. * @name Phaser.Ellipse#left
  20713. * @propety {number} left - Gets or sets the value of the leftmost point of the ellipse.
  20714. */
  20715. Object.defineProperty(Phaser.Ellipse.prototype, "left", {
  20716. get: function () {
  20717. return this.x;
  20718. },
  20719. set: function (value) {
  20720. this.x = value;
  20721. }
  20722. });
  20723. /**
  20724. * The x coordinate of the rightmost point of the Ellipse. Changing the right property of an Ellipse object has no effect on the x property, but does adjust the width.
  20725. * @name Phaser.Ellipse#right
  20726. * @property {number} right - Gets or sets the value of the rightmost point of the ellipse.
  20727. */
  20728. Object.defineProperty(Phaser.Ellipse.prototype, "right", {
  20729. get: function () {
  20730. return this.x + this.width;
  20731. },
  20732. set: function (value) {
  20733. if (value < this.x)
  20734. {
  20735. this.width = 0;
  20736. }
  20737. else
  20738. {
  20739. this.width = value - this.x;
  20740. }
  20741. }
  20742. });
  20743. /**
  20744. * The top of the Ellipse. The same as its y property.
  20745. * @name Phaser.Ellipse#top
  20746. * @property {number} top - Gets or sets the top of the ellipse.
  20747. */
  20748. Object.defineProperty(Phaser.Ellipse.prototype, "top", {
  20749. get: function () {
  20750. return this.y;
  20751. },
  20752. set: function (value) {
  20753. this.y = value;
  20754. }
  20755. });
  20756. /**
  20757. * The sum of the y and height properties. Changing the bottom property of an Ellipse doesn't adjust the y property, but does change the height.
  20758. * @name Phaser.Ellipse#bottom
  20759. * @property {number} bottom - Gets or sets the bottom of the ellipse.
  20760. */
  20761. Object.defineProperty(Phaser.Ellipse.prototype, "bottom", {
  20762. get: function () {
  20763. return this.y + this.height;
  20764. },
  20765. set: function (value) {
  20766. if (value < this.y)
  20767. {
  20768. this.height = 0;
  20769. }
  20770. else
  20771. {
  20772. this.height = value - this.y;
  20773. }
  20774. }
  20775. });
  20776. /**
  20777. * Determines whether or not this Ellipse object is empty. Will return a value of true if the Ellipse objects dimensions are less than or equal to 0; otherwise false.
  20778. * If set to true it will reset all of the Ellipse objects properties to 0. An Ellipse object is empty if its width or height is less than or equal to 0.
  20779. * @name Phaser.Ellipse#empty
  20780. * @property {boolean} empty - Gets or sets the empty state of the ellipse.
  20781. */
  20782. Object.defineProperty(Phaser.Ellipse.prototype, "empty", {
  20783. get: function () {
  20784. return (this.width === 0 || this.height === 0);
  20785. },
  20786. set: function (value) {
  20787. if (value === true)
  20788. {
  20789. this.setTo(0, 0, 0, 0);
  20790. }
  20791. }
  20792. });
  20793. /**
  20794. * Return true if the given x/y coordinates are within the Ellipse object.
  20795. *
  20796. * @method Phaser.Ellipse.contains
  20797. * @param {Phaser.Ellipse} a - The Ellipse to be checked.
  20798. * @param {number} x - The X value of the coordinate to test.
  20799. * @param {number} y - The Y value of the coordinate to test.
  20800. * @return {boolean} True if the coordinates are within this ellipse, otherwise false.
  20801. */
  20802. Phaser.Ellipse.contains = function (a, x, y) {
  20803. if (a.width <= 0 || a.height <= 0) {
  20804. return false;
  20805. }
  20806. // Normalize the coords to an ellipse with center 0,0 and a radius of 0.5
  20807. var normx = ((x - a.x) / a.width) - 0.5;
  20808. var normy = ((y - a.y) / a.height) - 0.5;
  20809. normx *= normx;
  20810. normy *= normy;
  20811. return (normx + normy < 0.25);
  20812. };
  20813. // Because PIXI uses its own Ellipse, we'll replace it with ours to avoid duplicating code or confusion.
  20814. PIXI.Ellipse = Phaser.Ellipse;
  20815. /**
  20816. * @author Richard Davey <rich@photonstorm.com>
  20817. * @copyright 2016 Photon Storm Ltd.
  20818. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  20819. */
  20820. /**
  20821. * Creates a new Line object with a start and an end point.
  20822. *
  20823. * @class Phaser.Line
  20824. * @constructor
  20825. * @param {number} [x1=0] - The x coordinate of the start of the line.
  20826. * @param {number} [y1=0] - The y coordinate of the start of the line.
  20827. * @param {number} [x2=0] - The x coordinate of the end of the line.
  20828. * @param {number} [y2=0] - The y coordinate of the end of the line.
  20829. */
  20830. Phaser.Line = function (x1, y1, x2, y2) {
  20831. x1 = x1 || 0;
  20832. y1 = y1 || 0;
  20833. x2 = x2 || 0;
  20834. y2 = y2 || 0;
  20835. /**
  20836. * @property {Phaser.Point} start - The start point of the line.
  20837. */
  20838. this.start = new Phaser.Point(x1, y1);
  20839. /**
  20840. * @property {Phaser.Point} end - The end point of the line.
  20841. */
  20842. this.end = new Phaser.Point(x2, y2);
  20843. /**
  20844. * @property {number} type - The const type of this object.
  20845. * @readonly
  20846. */
  20847. this.type = Phaser.LINE;
  20848. };
  20849. Phaser.Line.prototype = {
  20850. /**
  20851. * Sets the components of the Line to the specified values.
  20852. *
  20853. * @method Phaser.Line#setTo
  20854. * @param {number} [x1=0] - The x coordinate of the start of the line.
  20855. * @param {number} [y1=0] - The y coordinate of the start of the line.
  20856. * @param {number} [x2=0] - The x coordinate of the end of the line.
  20857. * @param {number} [y2=0] - The y coordinate of the end of the line.
  20858. * @return {Phaser.Line} This line object
  20859. */
  20860. setTo: function (x1, y1, x2, y2) {
  20861. this.start.setTo(x1, y1);
  20862. this.end.setTo(x2, y2);
  20863. return this;
  20864. },
  20865. /**
  20866. * Sets the line to match the x/y coordinates of the two given sprites.
  20867. * Can optionally be calculated from their center coordinates.
  20868. *
  20869. * @method Phaser.Line#fromSprite
  20870. * @param {Phaser.Sprite} startSprite - The coordinates of this Sprite will be set to the Line.start point.
  20871. * @param {Phaser.Sprite} endSprite - The coordinates of this Sprite will be set to the Line.start point.
  20872. * @param {boolean} [useCenter=false] - If true it will use startSprite.center.x, if false startSprite.x. Note that Sprites don't have a center property by default, so only enable if you've over-ridden your Sprite with a custom class.
  20873. * @return {Phaser.Line} This line object
  20874. */
  20875. fromSprite: function (startSprite, endSprite, useCenter) {
  20876. if (useCenter === undefined) { useCenter = false; }
  20877. if (useCenter)
  20878. {
  20879. return this.setTo(startSprite.center.x, startSprite.center.y, endSprite.center.x, endSprite.center.y);
  20880. }
  20881. return this.setTo(startSprite.x, startSprite.y, endSprite.x, endSprite.y);
  20882. },
  20883. /**
  20884. * Sets this line to start at the given `x` and `y` coordinates and for the segment to extend at `angle` for the given `length`.
  20885. *
  20886. * @method Phaser.Line#fromAngle
  20887. * @param {number} x - The x coordinate of the start of the line.
  20888. * @param {number} y - The y coordinate of the start of the line.
  20889. * @param {number} angle - The angle of the line in radians.
  20890. * @param {number} length - The length of the line in pixels.
  20891. * @return {Phaser.Line} This line object
  20892. */
  20893. fromAngle: function (x, y, angle, length) {
  20894. this.start.setTo(x, y);
  20895. this.end.setTo(x + (Math.cos(angle) * length), y + (Math.sin(angle) * length));
  20896. return this;
  20897. },
  20898. /**
  20899. * Rotates the line by the amount specified in `angle`.
  20900. *
  20901. * Rotation takes place from the center of the line.
  20902. * If you wish to rotate around a different point see Line.rotateAround.
  20903. *
  20904. * If you wish to rotate the ends of the Line then see Line.start.rotate or Line.end.rotate.
  20905. *
  20906. * @method Phaser.Line#rotate
  20907. * @param {number} angle - The angle in radians (unless asDegrees is true) to rotate the line by.
  20908. * @param {boolean} [asDegrees=false] - Is the given angle in radians (false) or degrees (true)?
  20909. * @return {Phaser.Line} This line object
  20910. */
  20911. rotate: function (angle, asDegrees) {
  20912. var cx = (this.start.x + this.end.x) / 2;
  20913. var cy = (this.start.y + this.end.y) / 2;
  20914. this.start.rotate(cx, cy, angle, asDegrees);
  20915. this.end.rotate(cx, cy, angle, asDegrees);
  20916. return this;
  20917. },
  20918. /**
  20919. * Rotates the line by the amount specified in `angle`.
  20920. *
  20921. * Rotation takes place around the coordinates given.
  20922. *
  20923. * @method Phaser.Line#rotateAround
  20924. * @param {number} x - The x coordinate to offset the rotation from.
  20925. * @param {number} y - The y coordinate to offset the rotation from.
  20926. * @param {number} angle - The angle in radians (unless asDegrees is true) to rotate the line by.
  20927. * @param {boolean} [asDegrees=false] - Is the given angle in radians (false) or degrees (true)?
  20928. * @return {Phaser.Line} This line object
  20929. */
  20930. rotateAround: function (x, y, angle, asDegrees) {
  20931. this.start.rotate(x, y, angle, asDegrees);
  20932. this.end.rotate(x, y, angle, asDegrees);
  20933. return this;
  20934. },
  20935. /**
  20936. * Checks for intersection between this line and another Line.
  20937. * If asSegment is true it will check for segment intersection. If asSegment is false it will check for line intersection.
  20938. * Returns the intersection segment of AB and EF as a Point, or null if there is no intersection.
  20939. *
  20940. * @method Phaser.Line#intersects
  20941. * @param {Phaser.Line} line - The line to check against this one.
  20942. * @param {boolean} [asSegment=true] - If true it will check for segment intersection, otherwise full line intersection.
  20943. * @param {Phaser.Point} [result] - A Point object to store the result in, if not given a new one will be created.
  20944. * @return {Phaser.Point} The intersection segment of the two lines as a Point, or null if there is no intersection.
  20945. */
  20946. intersects: function (line, asSegment, result) {
  20947. return Phaser.Line.intersectsPoints(this.start, this.end, line.start, line.end, asSegment, result);
  20948. },
  20949. /**
  20950. * Returns the reflected angle between two lines.
  20951. * This is the outgoing angle based on the angle of this line and the normalAngle of the given line.
  20952. *
  20953. * @method Phaser.Line#reflect
  20954. * @param {Phaser.Line} line - The line to reflect off this line.
  20955. * @return {number} The reflected angle in radians.
  20956. */
  20957. reflect: function (line) {
  20958. return Phaser.Line.reflect(this, line);
  20959. },
  20960. /**
  20961. * Returns a Point object where the x and y values correspond to the center (or midpoint) of the Line segment.
  20962. *
  20963. * @method Phaser.Line#midPoint
  20964. * @param {Phaser.Point} [out] - A Phaser.Point object into which the result will be populated. If not given a new Point object is created.
  20965. * @return {Phaser.Point} A Phaser.Point object with the x and y values set to the center of the line segment.
  20966. */
  20967. midPoint: function (out) {
  20968. if (out === undefined) { out = new Phaser.Point(); }
  20969. out.x = (this.start.x + this.end.x) / 2;
  20970. out.y = (this.start.y + this.end.y) / 2;
  20971. return out;
  20972. },
  20973. /**
  20974. * Centers this Line on the given coordinates.
  20975. *
  20976. * The line is centered by positioning the start and end points so that the lines midpoint matches
  20977. * the coordinates given.
  20978. *
  20979. * @method Phaser.Line#centerOn
  20980. * @param {number} x - The x position to center the line on.
  20981. * @param {number} y - The y position to center the line on.
  20982. * @return {Phaser.Line} This line object
  20983. */
  20984. centerOn: function (x, y) {
  20985. var cx = (this.start.x + this.end.x) / 2;
  20986. var cy = (this.start.y + this.end.y) / 2;
  20987. var tx = x - cx;
  20988. var ty = y - cy;
  20989. this.start.add(tx, ty);
  20990. this.end.add(tx, ty);
  20991. },
  20992. /**
  20993. * Tests if the given coordinates fall on this line. See pointOnSegment to test against just the line segment.
  20994. *
  20995. * @method Phaser.Line#pointOnLine
  20996. * @param {number} x - The line to check against this one.
  20997. * @param {number} y - The line to check against this one.
  20998. * @return {boolean} True if the point is on the line, false if not.
  20999. */
  21000. pointOnLine: function (x, y) {
  21001. return ((x - this.start.x) * (this.end.y - this.start.y) === (this.end.x - this.start.x) * (y - this.start.y));
  21002. },
  21003. /**
  21004. * Tests if the given coordinates fall on this line and within the segment. See pointOnLine to test against just the line.
  21005. *
  21006. * @method Phaser.Line#pointOnSegment
  21007. * @param {number} x - The line to check against this one.
  21008. * @param {number} y - The line to check against this one.
  21009. * @return {boolean} True if the point is on the line and segment, false if not.
  21010. */
  21011. pointOnSegment: function (x, y) {
  21012. var xMin = Math.min(this.start.x, this.end.x);
  21013. var xMax = Math.max(this.start.x, this.end.x);
  21014. var yMin = Math.min(this.start.y, this.end.y);
  21015. var yMax = Math.max(this.start.y, this.end.y);
  21016. return (this.pointOnLine(x, y) && (x >= xMin && x <= xMax) && (y >= yMin && y <= yMax));
  21017. },
  21018. /**
  21019. * Picks a random point from anywhere on the Line segment and returns it.
  21020. *
  21021. * @method Phaser.Line#random
  21022. * @param {Phaser.Point|object} [out] - A Phaser.Point, or any object with public x/y properties, that the values will be set in.
  21023. * If no object is provided a new Phaser.Point object will be created. In high performance areas avoid this by re-using an object.
  21024. * @return {Phaser.Point} An object containing the random point in its `x` and `y` properties.
  21025. */
  21026. random: function (out) {
  21027. if (out === undefined) { out = new Phaser.Point(); }
  21028. var t = Math.random();
  21029. out.x = this.start.x + t * (this.end.x - this.start.x);
  21030. out.y = this.start.y + t * (this.end.y - this.start.y);
  21031. return out;
  21032. },
  21033. /**
  21034. * Using Bresenham's line algorithm this will return an array of all coordinates on this line.
  21035. * The start and end points are rounded before this runs as the algorithm works on integers.
  21036. *
  21037. * @method Phaser.Line#coordinatesOnLine
  21038. * @param {number} [stepRate=1] - How many steps will we return? 1 = every coordinate on the line, 2 = every other coordinate, etc.
  21039. * @param {array} [results] - The array to store the results in. If not provided a new one will be generated.
  21040. * @return {array} An array of coordinates.
  21041. */
  21042. coordinatesOnLine: function (stepRate, results) {
  21043. if (stepRate === undefined) { stepRate = 1; }
  21044. if (results === undefined) { results = []; }
  21045. var x1 = Math.round(this.start.x);
  21046. var y1 = Math.round(this.start.y);
  21047. var x2 = Math.round(this.end.x);
  21048. var y2 = Math.round(this.end.y);
  21049. var dx = Math.abs(x2 - x1);
  21050. var dy = Math.abs(y2 - y1);
  21051. var sx = (x1 < x2) ? 1 : -1;
  21052. var sy = (y1 < y2) ? 1 : -1;
  21053. var err = dx - dy;
  21054. results.push([x1, y1]);
  21055. var i = 1;
  21056. while (!((x1 === x2) && (y1 === y2)))
  21057. {
  21058. var e2 = err << 1;
  21059. if (e2 > -dy)
  21060. {
  21061. err -= dy;
  21062. x1 += sx;
  21063. }
  21064. if (e2 < dx)
  21065. {
  21066. err += dx;
  21067. y1 += sy;
  21068. }
  21069. if (i % stepRate === 0)
  21070. {
  21071. results.push([x1, y1]);
  21072. }
  21073. i++;
  21074. }
  21075. return results;
  21076. },
  21077. /**
  21078. * Returns a new Line object with the same values for the start and end properties as this Line object.
  21079. * @method Phaser.Line#clone
  21080. * @param {Phaser.Line} output - Optional Line object. If given the values will be set into the object, otherwise a brand new Line object will be created and returned.
  21081. * @return {Phaser.Line} The cloned Line object.
  21082. */
  21083. clone: function (output) {
  21084. if (output === undefined || output === null)
  21085. {
  21086. output = new Phaser.Line(this.start.x, this.start.y, this.end.x, this.end.y);
  21087. }
  21088. else
  21089. {
  21090. output.setTo(this.start.x, this.start.y, this.end.x, this.end.y);
  21091. }
  21092. return output;
  21093. }
  21094. };
  21095. /**
  21096. * @name Phaser.Line#length
  21097. * @property {number} length - Gets the length of the line segment.
  21098. * @readonly
  21099. */
  21100. Object.defineProperty(Phaser.Line.prototype, "length", {
  21101. get: function () {
  21102. return Math.sqrt((this.end.x - this.start.x) * (this.end.x - this.start.x) + (this.end.y - this.start.y) * (this.end.y - this.start.y));
  21103. }
  21104. });
  21105. /**
  21106. * @name Phaser.Line#angle
  21107. * @property {number} angle - Gets the angle of the line in radians.
  21108. * @readonly
  21109. */
  21110. Object.defineProperty(Phaser.Line.prototype, "angle", {
  21111. get: function () {
  21112. return Math.atan2(this.end.y - this.start.y, this.end.x - this.start.x);
  21113. }
  21114. });
  21115. /**
  21116. * @name Phaser.Line#slope
  21117. * @property {number} slope - Gets the slope of the line (y/x).
  21118. * @readonly
  21119. */
  21120. Object.defineProperty(Phaser.Line.prototype, "slope", {
  21121. get: function () {
  21122. return (this.end.y - this.start.y) / (this.end.x - this.start.x);
  21123. }
  21124. });
  21125. /**
  21126. * @name Phaser.Line#perpSlope
  21127. * @property {number} perpSlope - Gets the perpendicular slope of the line (x/y).
  21128. * @readonly
  21129. */
  21130. Object.defineProperty(Phaser.Line.prototype, "perpSlope", {
  21131. get: function () {
  21132. return -((this.end.x - this.start.x) / (this.end.y - this.start.y));
  21133. }
  21134. });
  21135. /**
  21136. * @name Phaser.Line#x
  21137. * @property {number} x - Gets the x coordinate of the top left of the bounds around this line.
  21138. * @readonly
  21139. */
  21140. Object.defineProperty(Phaser.Line.prototype, "x", {
  21141. get: function () {
  21142. return Math.min(this.start.x, this.end.x);
  21143. }
  21144. });
  21145. /**
  21146. * @name Phaser.Line#y
  21147. * @property {number} y - Gets the y coordinate of the top left of the bounds around this line.
  21148. * @readonly
  21149. */
  21150. Object.defineProperty(Phaser.Line.prototype, "y", {
  21151. get: function () {
  21152. return Math.min(this.start.y, this.end.y);
  21153. }
  21154. });
  21155. /**
  21156. * @name Phaser.Line#left
  21157. * @property {number} left - Gets the left-most point of this line.
  21158. * @readonly
  21159. */
  21160. Object.defineProperty(Phaser.Line.prototype, "left", {
  21161. get: function () {
  21162. return Math.min(this.start.x, this.end.x);
  21163. }
  21164. });
  21165. /**
  21166. * @name Phaser.Line#right
  21167. * @property {number} right - Gets the right-most point of this line.
  21168. * @readonly
  21169. */
  21170. Object.defineProperty(Phaser.Line.prototype, "right", {
  21171. get: function () {
  21172. return Math.max(this.start.x, this.end.x);
  21173. }
  21174. });
  21175. /**
  21176. * @name Phaser.Line#top
  21177. * @property {number} top - Gets the top-most point of this line.
  21178. * @readonly
  21179. */
  21180. Object.defineProperty(Phaser.Line.prototype, "top", {
  21181. get: function () {
  21182. return Math.min(this.start.y, this.end.y);
  21183. }
  21184. });
  21185. /**
  21186. * @name Phaser.Line#bottom
  21187. * @property {number} bottom - Gets the bottom-most point of this line.
  21188. * @readonly
  21189. */
  21190. Object.defineProperty(Phaser.Line.prototype, "bottom", {
  21191. get: function () {
  21192. return Math.max(this.start.y, this.end.y);
  21193. }
  21194. });
  21195. /**
  21196. * @name Phaser.Line#width
  21197. * @property {number} width - Gets the width of this bounds of this line.
  21198. * @readonly
  21199. */
  21200. Object.defineProperty(Phaser.Line.prototype, "width", {
  21201. get: function () {
  21202. return Math.abs(this.start.x - this.end.x);
  21203. }
  21204. });
  21205. /**
  21206. * @name Phaser.Line#height
  21207. * @property {number} height - Gets the height of this bounds of this line.
  21208. * @readonly
  21209. */
  21210. Object.defineProperty(Phaser.Line.prototype, "height", {
  21211. get: function () {
  21212. return Math.abs(this.start.y - this.end.y);
  21213. }
  21214. });
  21215. /**
  21216. * @name Phaser.Line#normalX
  21217. * @property {number} normalX - Gets the x component of the left-hand normal of this line.
  21218. * @readonly
  21219. */
  21220. Object.defineProperty(Phaser.Line.prototype, "normalX", {
  21221. get: function () {
  21222. return Math.cos(this.angle - 1.5707963267948966);
  21223. }
  21224. });
  21225. /**
  21226. * @name Phaser.Line#normalY
  21227. * @property {number} normalY - Gets the y component of the left-hand normal of this line.
  21228. * @readonly
  21229. */
  21230. Object.defineProperty(Phaser.Line.prototype, "normalY", {
  21231. get: function () {
  21232. return Math.sin(this.angle - 1.5707963267948966);
  21233. }
  21234. });
  21235. /**
  21236. * @name Phaser.Line#normalAngle
  21237. * @property {number} normalAngle - Gets the angle in radians of the normal of this line (line.angle - 90 degrees.)
  21238. * @readonly
  21239. */
  21240. Object.defineProperty(Phaser.Line.prototype, "normalAngle", {
  21241. get: function () {
  21242. return Phaser.Math.wrap(this.angle - 1.5707963267948966, -Math.PI, Math.PI);
  21243. }
  21244. });
  21245. /**
  21246. * Checks for intersection between two lines as defined by the given start and end points.
  21247. * If asSegment is true it will check for line segment intersection. If asSegment is false it will check for line intersection.
  21248. * Returns the intersection segment of AB and EF as a Point, or null if there is no intersection.
  21249. * Adapted from code by Keith Hair
  21250. *
  21251. * @method Phaser.Line.intersectsPoints
  21252. * @param {Phaser.Point} a - The start of the first Line to be checked.
  21253. * @param {Phaser.Point} b - The end of the first line to be checked.
  21254. * @param {Phaser.Point} e - The start of the second Line to be checked.
  21255. * @param {Phaser.Point} f - The end of the second line to be checked.
  21256. * @param {boolean} [asSegment=true] - If true it will check for segment intersection, otherwise full line intersection.
  21257. * @param {Phaser.Point|object} [result] - A Point object to store the result in, if not given a new one will be created.
  21258. * @return {Phaser.Point} The intersection segment of the two lines as a Point, or null if there is no intersection.
  21259. */
  21260. Phaser.Line.intersectsPoints = function (a, b, e, f, asSegment, result) {
  21261. if (asSegment === undefined) { asSegment = true; }
  21262. if (result === undefined) { result = new Phaser.Point(); }
  21263. var a1 = b.y - a.y;
  21264. var a2 = f.y - e.y;
  21265. var b1 = a.x - b.x;
  21266. var b2 = e.x - f.x;
  21267. var c1 = (b.x * a.y) - (a.x * b.y);
  21268. var c2 = (f.x * e.y) - (e.x * f.y);
  21269. var denom = (a1 * b2) - (a2 * b1);
  21270. if (denom === 0)
  21271. {
  21272. return null;
  21273. }
  21274. result.x = ((b1 * c2) - (b2 * c1)) / denom;
  21275. result.y = ((a2 * c1) - (a1 * c2)) / denom;
  21276. if (asSegment)
  21277. {
  21278. var uc = ((f.y - e.y) * (b.x - a.x) - (f.x - e.x) * (b.y - a.y));
  21279. var ua = (((f.x - e.x) * (a.y - e.y)) - (f.y - e.y) * (a.x - e.x)) / uc;
  21280. var ub = (((b.x - a.x) * (a.y - e.y)) - ((b.y - a.y) * (a.x - e.x))) / uc;
  21281. if (ua >= 0 && ua <= 1 && ub >= 0 && ub <= 1)
  21282. {
  21283. return result;
  21284. }
  21285. else
  21286. {
  21287. return null;
  21288. }
  21289. }
  21290. return result;
  21291. };
  21292. /**
  21293. * Checks for intersection between two lines.
  21294. * If asSegment is true it will check for segment intersection.
  21295. * If asSegment is false it will check for line intersection.
  21296. * Returns the intersection segment of AB and EF as a Point, or null if there is no intersection.
  21297. * Adapted from code by Keith Hair
  21298. *
  21299. * @method Phaser.Line.intersects
  21300. * @param {Phaser.Line} a - The first Line to be checked.
  21301. * @param {Phaser.Line} b - The second Line to be checked.
  21302. * @param {boolean} [asSegment=true] - If true it will check for segment intersection, otherwise full line intersection.
  21303. * @param {Phaser.Point} [result] - A Point object to store the result in, if not given a new one will be created.
  21304. * @return {Phaser.Point} The intersection segment of the two lines as a Point, or null if there is no intersection.
  21305. */
  21306. Phaser.Line.intersects = function (a, b, asSegment, result) {
  21307. return Phaser.Line.intersectsPoints(a.start, a.end, b.start, b.end, asSegment, result);
  21308. };
  21309. /**
  21310. * Checks for intersection between the Line and a Rectangle shape, or a rectangle-like
  21311. * object, with public `x`, `y`, `right` and `bottom` properties, such as a Sprite or Body.
  21312. *
  21313. * An intersection is considered valid if:
  21314. *
  21315. * The line starts within, or ends within, the Rectangle.
  21316. * The line segment intersects one of the 4 rectangle edges.
  21317. *
  21318. * The for the purposes of this function rectangles are considered 'solid'.
  21319. *
  21320. * @method Phaser.Line.intersectsRectangle
  21321. * @param {Phaser.Line} line - The line to check for intersection with.
  21322. * @param {Phaser.Rectangle|object} rect - The rectangle, or rectangle-like object, to check for intersection with.
  21323. * @return {boolean} True if the line intersects with the rectangle edges, or starts or ends within the rectangle.
  21324. */
  21325. Phaser.Line.intersectsRectangle = function (line, rect) {
  21326. // Quick bail out of the Line and Rect bounds don't intersect
  21327. if (!Phaser.Rectangle.intersects(line, rect))
  21328. {
  21329. return false;
  21330. }
  21331. var x1 = line.start.x;
  21332. var y1 = line.start.y;
  21333. var x2 = line.end.x;
  21334. var y2 = line.end.y;
  21335. var bx1 = rect.x;
  21336. var by1 = rect.y;
  21337. var bx2 = rect.right;
  21338. var by2 = rect.bottom;
  21339. var t = 0;
  21340. // If the start or end of the line is inside the rect then we assume
  21341. // collision, as rects are solid for our use-case.
  21342. if ((x1 >= bx1 && x1 <= bx2 && y1 >= by1 && y1 <= by2) ||
  21343. (x2 >= bx1 && x2 <= bx2 && y2 >= by1 && y2 <= by2))
  21344. {
  21345. return true;
  21346. }
  21347. if (x1 < bx1 && x2 >= bx1)
  21348. {
  21349. // Left edge
  21350. t = y1 + (y2 - y1) * (bx1 - x1) / (x2 - x1);
  21351. if (t > by1 && t <= by2)
  21352. {
  21353. return true;
  21354. }
  21355. }
  21356. else if (x1 > bx2 && x2 <= bx2)
  21357. {
  21358. // Right edge
  21359. t = y1 + (y2 - y1) * (bx2 - x1) / (x2 - x1);
  21360. if (t >= by1 && t <= by2)
  21361. {
  21362. return true;
  21363. }
  21364. }
  21365. if (y1 < by1 && y2 >= by1)
  21366. {
  21367. // Top edge
  21368. t = x1 + (x2 - x1) * (by1 - y1) / (y2 - y1);
  21369. if (t >= bx1 && t <= bx2)
  21370. {
  21371. return true;
  21372. }
  21373. }
  21374. else if (y1 > by2 && y2 <= by2)
  21375. {
  21376. // Bottom edge
  21377. t = x1 + (x2 - x1) * (by2 - y1) / (y2 - y1);
  21378. if (t >= bx1 && t <= bx2)
  21379. {
  21380. return true;
  21381. }
  21382. }
  21383. return false;
  21384. };
  21385. /**
  21386. * Returns the reflected angle between two lines.
  21387. * This is the outgoing angle based on the angle of Line 1 and the normalAngle of Line 2.
  21388. *
  21389. * @method Phaser.Line.reflect
  21390. * @param {Phaser.Line} a - The base line.
  21391. * @param {Phaser.Line} b - The line to be reflected from the base line.
  21392. * @return {number} The reflected angle in radians.
  21393. */
  21394. Phaser.Line.reflect = function (a, b) {
  21395. return 2 * b.normalAngle - 3.141592653589793 - a.angle;
  21396. };
  21397. /**
  21398. * @author Mat Groves http://matgroves.com/ @Doormat23
  21399. * @author Richard Davey <rich@photonstorm.com>
  21400. * @copyright 2016 Photon Storm Ltd.
  21401. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  21402. */
  21403. /**
  21404. * The Matrix is a 3x3 matrix mostly used for display transforms within the renderer.
  21405. *
  21406. * It is represented like so:
  21407. *
  21408. * | a | b | tx |
  21409. * | c | d | ty |
  21410. * | 0 | 0 | 1 |
  21411. *
  21412. * @class Phaser.Matrix
  21413. * @constructor
  21414. * @param {number} [a=1] - Horizontal scaling
  21415. * @param {number} [b=0] - Horizontal skewing
  21416. * @param {number} [c=0] - Vertical skewing
  21417. * @param {number} [d=1] - Vertical scaling
  21418. * @param {number} [tx=0] - Horizontal translation
  21419. * @param {number} [ty=0] - Vertical translation
  21420. */
  21421. Phaser.Matrix = function (a, b, c, d, tx, ty) {
  21422. if (a === undefined || a === null) { a = 1; }
  21423. if (b === undefined || b === null) { b = 0; }
  21424. if (c === undefined || c === null) { c = 0; }
  21425. if (d === undefined || d === null) { d = 1; }
  21426. if (tx === undefined || tx === null) { tx = 0; }
  21427. if (ty === undefined || ty === null) { ty = 0; }
  21428. /**
  21429. * @property {number} a
  21430. * @default 1
  21431. */
  21432. this.a = a;
  21433. /**
  21434. * @property {number} b
  21435. * @default 0
  21436. */
  21437. this.b = b;
  21438. /**
  21439. * @property {number} c
  21440. * @default 0
  21441. */
  21442. this.c = c;
  21443. /**
  21444. * @property {number} d
  21445. * @default 1
  21446. */
  21447. this.d = d;
  21448. /**
  21449. * @property {number} tx
  21450. * @default 0
  21451. */
  21452. this.tx = tx;
  21453. /**
  21454. * @property {number} ty
  21455. * @default 0
  21456. */
  21457. this.ty = ty;
  21458. /**
  21459. * @property {number} type - The const type of this object.
  21460. * @readonly
  21461. */
  21462. this.type = Phaser.MATRIX;
  21463. };
  21464. Phaser.Matrix.prototype = {
  21465. /**
  21466. * Sets the values of this Matrix to the values in the given array.
  21467. *
  21468. * The Array elements should be set as follows:
  21469. *
  21470. * a = array[0]
  21471. * b = array[1]
  21472. * c = array[3]
  21473. * d = array[4]
  21474. * tx = array[2]
  21475. * ty = array[5]
  21476. *
  21477. * @method Phaser.Matrix#fromArray
  21478. * @param {Array} array - The array to copy from.
  21479. * @return {Phaser.Matrix} This Matrix object.
  21480. */
  21481. fromArray: function (array) {
  21482. return this.setTo(array[0], array[1], array[3], array[4], array[2], array[5]);
  21483. },
  21484. /**
  21485. * Sets the values of this Matrix to the given values.
  21486. *
  21487. * @method Phaser.Matrix#setTo
  21488. * @param {number} a - Horizontal scaling
  21489. * @param {number} b - Horizontal skewing
  21490. * @param {number} c - Vertical skewing
  21491. * @param {number} d - Vertical scaling
  21492. * @param {number} tx - Horizontal translation
  21493. * @param {number} ty - Vertical translation
  21494. * @return {Phaser.Matrix} This Matrix object.
  21495. */
  21496. setTo: function (a, b, c, d, tx, ty) {
  21497. this.a = a;
  21498. this.b = b;
  21499. this.c = c;
  21500. this.d = d;
  21501. this.tx = tx;
  21502. this.ty = ty;
  21503. return this;
  21504. },
  21505. /**
  21506. * Creates a new Matrix object based on the values of this Matrix.
  21507. * If you provide the output parameter the values of this Matrix will be copied over to it.
  21508. * If the output parameter is blank a new Matrix object will be created.
  21509. *
  21510. * @method Phaser.Matrix#clone
  21511. * @param {Phaser.Matrix} [output] - If provided the values of this Matrix will be copied to it, otherwise a new Matrix object is created.
  21512. * @return {Phaser.Matrix} A clone of this Matrix.
  21513. */
  21514. clone: function (output) {
  21515. if (output === undefined || output === null)
  21516. {
  21517. output = new Phaser.Matrix(this.a, this.b, this.c, this.d, this.tx, this.ty);
  21518. }
  21519. else
  21520. {
  21521. output.a = this.a;
  21522. output.b = this.b;
  21523. output.c = this.c;
  21524. output.d = this.d;
  21525. output.tx = this.tx;
  21526. output.ty = this.ty;
  21527. }
  21528. return output;
  21529. },
  21530. /**
  21531. * Copies the properties from this Matrix to the given Matrix.
  21532. *
  21533. * @method Phaser.Matrix#copyTo
  21534. * @param {Phaser.Matrix} matrix - The Matrix to copy from.
  21535. * @return {Phaser.Matrix} The destination Matrix object.
  21536. */
  21537. copyTo: function (matrix) {
  21538. matrix.copyFrom(this);
  21539. return matrix;
  21540. },
  21541. /**
  21542. * Copies the properties from the given Matrix into this Matrix.
  21543. *
  21544. * @method Phaser.Matrix#copyFrom
  21545. * @param {Phaser.Matrix} matrix - The Matrix to copy from.
  21546. * @return {Phaser.Matrix} This Matrix object.
  21547. */
  21548. copyFrom: function (matrix) {
  21549. this.a = matrix.a;
  21550. this.b = matrix.b;
  21551. this.c = matrix.c;
  21552. this.d = matrix.d;
  21553. this.tx = matrix.tx;
  21554. this.ty = matrix.ty;
  21555. return this;
  21556. },
  21557. /**
  21558. * Creates a Float32 Array with values populated from this Matrix object.
  21559. *
  21560. * @method Phaser.Matrix#toArray
  21561. * @param {boolean} [transpose=false] - Whether the values in the array are transposed or not.
  21562. * @param {PIXI.Float32Array} [array] - If provided the values will be set into this array, otherwise a new Float32Array is created.
  21563. * @return {PIXI.Float32Array} The newly created array which contains the matrix.
  21564. */
  21565. toArray: function (transpose, array) {
  21566. if (array === undefined) { array = new PIXI.Float32Array(9); }
  21567. if (transpose)
  21568. {
  21569. array[0] = this.a;
  21570. array[1] = this.b;
  21571. array[2] = 0;
  21572. array[3] = this.c;
  21573. array[4] = this.d;
  21574. array[5] = 0;
  21575. array[6] = this.tx;
  21576. array[7] = this.ty;
  21577. array[8] = 1;
  21578. }
  21579. else
  21580. {
  21581. array[0] = this.a;
  21582. array[1] = this.c;
  21583. array[2] = this.tx;
  21584. array[3] = this.b;
  21585. array[4] = this.d;
  21586. array[5] = this.ty;
  21587. array[6] = 0;
  21588. array[7] = 0;
  21589. array[8] = 1;
  21590. }
  21591. return array;
  21592. },
  21593. /**
  21594. * Get a new position with the current transformation applied.
  21595. *
  21596. * Can be used to go from a childs coordinate space to the world coordinate space (e.g. rendering)
  21597. *
  21598. * @method Phaser.Matrix#apply
  21599. * @param {Phaser.Point} pos - The origin Point.
  21600. * @param {Phaser.Point} [newPos] - The point that the new position is assigned to. This can be same as input point.
  21601. * @return {Phaser.Point} The new point, transformed through this matrix.
  21602. */
  21603. apply: function (pos, newPos) {
  21604. if (newPos === undefined) { newPos = new Phaser.Point(); }
  21605. newPos.x = this.a * pos.x + this.c * pos.y + this.tx;
  21606. newPos.y = this.b * pos.x + this.d * pos.y + this.ty;
  21607. return newPos;
  21608. },
  21609. /**
  21610. * Get a new position with the inverse of the current transformation applied.
  21611. *
  21612. * Can be used to go from the world coordinate space to a childs coordinate space. (e.g. input)
  21613. *
  21614. * @method Phaser.Matrix#applyInverse
  21615. * @param {Phaser.Point} pos - The origin Point.
  21616. * @param {Phaser.Point} [newPos] - The point that the new position is assigned to. This can be same as input point.
  21617. * @return {Phaser.Point} The new point, inverse transformed through this matrix.
  21618. */
  21619. applyInverse: function (pos, newPos) {
  21620. if (newPos === undefined) { newPos = new Phaser.Point(); }
  21621. var id = 1 / (this.a * this.d + this.c * -this.b);
  21622. var x = pos.x;
  21623. var y = pos.y;
  21624. newPos.x = this.d * id * x + -this.c * id * y + (this.ty * this.c - this.tx * this.d) * id;
  21625. newPos.y = this.a * id * y + -this.b * id * x + (-this.ty * this.a + this.tx * this.b) * id;
  21626. return newPos;
  21627. },
  21628. /**
  21629. * Translates the matrix on the x and y.
  21630. * This is the same as Matrix.tx += x.
  21631. *
  21632. * @method Phaser.Matrix#translate
  21633. * @param {number} x - The x value to translate on.
  21634. * @param {number} y - The y value to translate on.
  21635. * @return {Phaser.Matrix} This Matrix object.
  21636. */
  21637. translate: function (x, y) {
  21638. this.tx += x;
  21639. this.ty += y;
  21640. return this;
  21641. },
  21642. /**
  21643. * Applies a scale transformation to this matrix.
  21644. *
  21645. * @method Phaser.Matrix#scale
  21646. * @param {number} x - The amount to scale horizontally.
  21647. * @param {number} y - The amount to scale vertically.
  21648. * @return {Phaser.Matrix} This Matrix object.
  21649. */
  21650. scale: function (x, y) {
  21651. this.a *= x;
  21652. this.d *= y;
  21653. this.c *= x;
  21654. this.b *= y;
  21655. this.tx *= x;
  21656. this.ty *= y;
  21657. return this;
  21658. },
  21659. /**
  21660. * Applies a rotation transformation to this matrix.
  21661. *
  21662. * @method Phaser.Matrix#rotate
  21663. * @param {number} angle - The angle to rotate by, given in radians.
  21664. * @return {Phaser.Matrix} This Matrix object.
  21665. */
  21666. rotate: function (angle) {
  21667. var cos = Math.cos(angle);
  21668. var sin = Math.sin(angle);
  21669. var a1 = this.a;
  21670. var c1 = this.c;
  21671. var tx1 = this.tx;
  21672. this.a = a1 * cos-this.b * sin;
  21673. this.b = a1 * sin+this.b * cos;
  21674. this.c = c1 * cos-this.d * sin;
  21675. this.d = c1 * sin+this.d * cos;
  21676. this.tx = tx1 * cos - this.ty * sin;
  21677. this.ty = tx1 * sin + this.ty * cos;
  21678. return this;
  21679. },
  21680. /**
  21681. * Appends the given Matrix to this Matrix.
  21682. *
  21683. * @method Phaser.Matrix#append
  21684. * @param {Phaser.Matrix} matrix - The matrix to append to this one.
  21685. * @return {Phaser.Matrix} This Matrix object.
  21686. */
  21687. append: function (matrix) {
  21688. var a1 = this.a;
  21689. var b1 = this.b;
  21690. var c1 = this.c;
  21691. var d1 = this.d;
  21692. this.a = matrix.a * a1 + matrix.b * c1;
  21693. this.b = matrix.a * b1 + matrix.b * d1;
  21694. this.c = matrix.c * a1 + matrix.d * c1;
  21695. this.d = matrix.c * b1 + matrix.d * d1;
  21696. this.tx = matrix.tx * a1 + matrix.ty * c1 + this.tx;
  21697. this.ty = matrix.tx * b1 + matrix.ty * d1 + this.ty;
  21698. return this;
  21699. },
  21700. /**
  21701. * Resets this Matrix to an identity (default) matrix.
  21702. *
  21703. * @method Phaser.Matrix#identity
  21704. * @return {Phaser.Matrix} This Matrix object.
  21705. */
  21706. identity: function () {
  21707. return this.setTo(1, 0, 0, 1, 0, 0);
  21708. }
  21709. };
  21710. Phaser.identityMatrix = new Phaser.Matrix();
  21711. // Because PIXI uses its own type, we'll replace it with ours to avoid duplicating code or confusion.
  21712. PIXI.Matrix = Phaser.Matrix;
  21713. PIXI.identityMatrix = Phaser.identityMatrix;
  21714. /**
  21715. * @author Richard Davey <rich@photonstorm.com>
  21716. * @copyright 2016 Photon Storm Ltd.
  21717. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  21718. */
  21719. /**
  21720. * A Point object represents a location in a two-dimensional coordinate system, where x represents the horizontal axis and y represents the vertical axis.
  21721. * The following code creates a point at (0,0):
  21722. * `var myPoint = new Phaser.Point();`
  21723. * You can also use them as 2D Vectors and you'll find different vector related methods in this class.
  21724. *
  21725. * @class Phaser.Point
  21726. * @constructor
  21727. * @param {number} [x=0] - The horizontal position of this Point.
  21728. * @param {number} [y=0] - The vertical position of this Point.
  21729. */
  21730. Phaser.Point = function (x, y) {
  21731. x = x || 0;
  21732. y = y || 0;
  21733. /**
  21734. * @property {number} x - The x value of the point.
  21735. */
  21736. this.x = x;
  21737. /**
  21738. * @property {number} y - The y value of the point.
  21739. */
  21740. this.y = y;
  21741. /**
  21742. * @property {number} type - The const type of this object.
  21743. * @readonly
  21744. */
  21745. this.type = Phaser.POINT;
  21746. };
  21747. Phaser.Point.prototype = {
  21748. /**
  21749. * Copies the x and y properties from any given object to this Point.
  21750. *
  21751. * @method Phaser.Point#copyFrom
  21752. * @param {any} source - The object to copy from.
  21753. * @return {Phaser.Point} This Point object.
  21754. */
  21755. copyFrom: function (source) {
  21756. return this.setTo(source.x, source.y);
  21757. },
  21758. /**
  21759. * Inverts the x and y values of this Point
  21760. *
  21761. * @method Phaser.Point#invert
  21762. * @return {Phaser.Point} This Point object.
  21763. */
  21764. invert: function () {
  21765. return this.setTo(this.y, this.x);
  21766. },
  21767. /**
  21768. * Sets the `x` and `y` values of this Point object to the given values.
  21769. * If you omit the `y` value then the `x` value will be applied to both, for example:
  21770. * `Point.setTo(2)` is the same as `Point.setTo(2, 2)`
  21771. *
  21772. * @method Phaser.Point#setTo
  21773. * @param {number} x - The horizontal value of this point.
  21774. * @param {number} [y] - The vertical value of this point. If not given the x value will be used in its place.
  21775. * @return {Phaser.Point} This Point object. Useful for chaining method calls.
  21776. */
  21777. setTo: function (x, y) {
  21778. this.x = x || 0;
  21779. this.y = y || ( (y !== 0) ? this.x : 0 );
  21780. return this;
  21781. },
  21782. /**
  21783. * Sets the `x` and `y` values of this Point object to the given values.
  21784. * If you omit the `y` value then the `x` value will be applied to both, for example:
  21785. * `Point.set(2)` is the same as `Point.set(2, 2)`
  21786. *
  21787. * @method Phaser.Point#set
  21788. * @param {number} x - The horizontal value of this point.
  21789. * @param {number} [y] - The vertical value of this point. If not given the x value will be used in its place.
  21790. * @return {Phaser.Point} This Point object. Useful for chaining method calls.
  21791. */
  21792. set: function (x, y) {
  21793. this.x = x || 0;
  21794. this.y = y || ( (y !== 0) ? this.x : 0 );
  21795. return this;
  21796. },
  21797. /**
  21798. * Adds the given x and y values to this Point.
  21799. *
  21800. * @method Phaser.Point#add
  21801. * @param {number} x - The value to add to Point.x.
  21802. * @param {number} y - The value to add to Point.y.
  21803. * @return {Phaser.Point} This Point object. Useful for chaining method calls.
  21804. */
  21805. add: function (x, y) {
  21806. this.x += x;
  21807. this.y += y;
  21808. return this;
  21809. },
  21810. /**
  21811. * Subtracts the given x and y values from this Point.
  21812. *
  21813. * @method Phaser.Point#subtract
  21814. * @param {number} x - The value to subtract from Point.x.
  21815. * @param {number} y - The value to subtract from Point.y.
  21816. * @return {Phaser.Point} This Point object. Useful for chaining method calls.
  21817. */
  21818. subtract: function (x, y) {
  21819. this.x -= x;
  21820. this.y -= y;
  21821. return this;
  21822. },
  21823. /**
  21824. * Multiplies Point.x and Point.y by the given x and y values. Sometimes known as `Scale`.
  21825. *
  21826. * @method Phaser.Point#multiply
  21827. * @param {number} x - The value to multiply Point.x by.
  21828. * @param {number} y - The value to multiply Point.x by.
  21829. * @return {Phaser.Point} This Point object. Useful for chaining method calls.
  21830. */
  21831. multiply: function (x, y) {
  21832. this.x *= x;
  21833. this.y *= y;
  21834. return this;
  21835. },
  21836. /**
  21837. * Divides Point.x and Point.y by the given x and y values.
  21838. *
  21839. * @method Phaser.Point#divide
  21840. * @param {number} x - The value to divide Point.x by.
  21841. * @param {number} y - The value to divide Point.x by.
  21842. * @return {Phaser.Point} This Point object. Useful for chaining method calls.
  21843. */
  21844. divide: function (x, y) {
  21845. this.x /= x;
  21846. this.y /= y;
  21847. return this;
  21848. },
  21849. /**
  21850. * Clamps the x value of this Point to be between the given min and max.
  21851. *
  21852. * @method Phaser.Point#clampX
  21853. * @param {number} min - The minimum value to clamp this Point to.
  21854. * @param {number} max - The maximum value to clamp this Point to.
  21855. * @return {Phaser.Point} This Point object.
  21856. */
  21857. clampX: function (min, max) {
  21858. this.x = Phaser.Math.clamp(this.x, min, max);
  21859. return this;
  21860. },
  21861. /**
  21862. * Clamps the y value of this Point to be between the given min and max
  21863. *
  21864. * @method Phaser.Point#clampY
  21865. * @param {number} min - The minimum value to clamp this Point to.
  21866. * @param {number} max - The maximum value to clamp this Point to.
  21867. * @return {Phaser.Point} This Point object.
  21868. */
  21869. clampY: function (min, max) {
  21870. this.y = Phaser.Math.clamp(this.y, min, max);
  21871. return this;
  21872. },
  21873. /**
  21874. * Clamps this Point object values to be between the given min and max.
  21875. *
  21876. * @method Phaser.Point#clamp
  21877. * @param {number} min - The minimum value to clamp this Point to.
  21878. * @param {number} max - The maximum value to clamp this Point to.
  21879. * @return {Phaser.Point} This Point object.
  21880. */
  21881. clamp: function (min, max) {
  21882. this.x = Phaser.Math.clamp(this.x, min, max);
  21883. this.y = Phaser.Math.clamp(this.y, min, max);
  21884. return this;
  21885. },
  21886. /**
  21887. * Creates a copy of the given Point.
  21888. *
  21889. * @method Phaser.Point#clone
  21890. * @param {Phaser.Point} [output] Optional Point object. If given the values will be set into this object, otherwise a brand new Point object will be created and returned.
  21891. * @return {Phaser.Point} The new Point object.
  21892. */
  21893. clone: function (output) {
  21894. if (output === undefined || output === null)
  21895. {
  21896. output = new Phaser.Point(this.x, this.y);
  21897. }
  21898. else
  21899. {
  21900. output.setTo(this.x, this.y);
  21901. }
  21902. return output;
  21903. },
  21904. /**
  21905. * Copies the x and y properties from this Point to any given object.
  21906. *
  21907. * @method Phaser.Point#copyTo
  21908. * @param {any} dest - The object to copy to.
  21909. * @return {object} The dest object.
  21910. */
  21911. copyTo: function (dest) {
  21912. dest.x = this.x;
  21913. dest.y = this.y;
  21914. return dest;
  21915. },
  21916. /**
  21917. * Returns the distance of this Point object to the given object (can be a Circle, Point or anything with x/y properties)
  21918. *
  21919. * @method Phaser.Point#distance
  21920. * @param {object} dest - The target object. Must have visible x and y properties that represent the center of the object.
  21921. * @param {boolean} [round] - Round the distance to the nearest integer (default false).
  21922. * @return {number} The distance between this Point object and the destination Point object.
  21923. */
  21924. distance: function (dest, round) {
  21925. return Phaser.Point.distance(this, dest, round);
  21926. },
  21927. /**
  21928. * Determines whether the given objects x/y values are equal to this Point object.
  21929. *
  21930. * @method Phaser.Point#equals
  21931. * @param {Phaser.Point|any} a - The object to compare with this Point.
  21932. * @return {boolean} A value of true if the x and y points are equal, otherwise false.
  21933. */
  21934. equals: function (a) {
  21935. return (a.x === this.x && a.y === this.y);
  21936. },
  21937. /**
  21938. * Returns the angle between this Point object and another object with public x and y properties.
  21939. *
  21940. * @method Phaser.Point#angle
  21941. * @param {Phaser.Point|any} a - The object to get the angle from this Point to.
  21942. * @param {boolean} [asDegrees=false] - Is the given angle in radians (false) or degrees (true)?
  21943. * @return {number} The angle between the two objects.
  21944. */
  21945. angle: function (a, asDegrees) {
  21946. if (asDegrees === undefined) { asDegrees = false; }
  21947. if (asDegrees)
  21948. {
  21949. return Phaser.Math.radToDeg(Math.atan2(a.y - this.y, a.x - this.x));
  21950. }
  21951. else
  21952. {
  21953. return Math.atan2(a.y - this.y, a.x - this.x);
  21954. }
  21955. },
  21956. /**
  21957. * Rotates this Point around the x/y coordinates given to the desired angle.
  21958. *
  21959. * @method Phaser.Point#rotate
  21960. * @param {number} x - The x coordinate of the anchor point.
  21961. * @param {number} y - The y coordinate of the anchor point.
  21962. * @param {number} angle - The angle in radians (unless asDegrees is true) to rotate the Point to.
  21963. * @param {boolean} [asDegrees=false] - Is the given angle in radians (false) or degrees (true)?
  21964. * @param {number} [distance] - An optional distance constraint between the Point and the anchor.
  21965. * @return {Phaser.Point} The modified point object.
  21966. */
  21967. rotate: function (x, y, angle, asDegrees, distance) {
  21968. return Phaser.Point.rotate(this, x, y, angle, asDegrees, distance);
  21969. },
  21970. /**
  21971. * Calculates the length of the Point object.
  21972. *
  21973. * @method Phaser.Point#getMagnitude
  21974. * @return {number} The length of the Point.
  21975. */
  21976. getMagnitude: function () {
  21977. return Math.sqrt((this.x * this.x) + (this.y * this.y));
  21978. },
  21979. /**
  21980. * Calculates the length squared of the Point object.
  21981. *
  21982. * @method Phaser.Point#getMagnitudeSq
  21983. * @return {number} The length ^ 2 of the Point.
  21984. */
  21985. getMagnitudeSq: function () {
  21986. return (this.x * this.x) + (this.y * this.y);
  21987. },
  21988. /**
  21989. * Alters the length of the Point without changing the direction.
  21990. *
  21991. * @method Phaser.Point#setMagnitude
  21992. * @param {number} magnitude - The desired magnitude of the resulting Point.
  21993. * @return {Phaser.Point} This Point object.
  21994. */
  21995. setMagnitude: function (magnitude) {
  21996. return this.normalize().multiply(magnitude, magnitude);
  21997. },
  21998. /**
  21999. * Alters the Point object so that its length is 1, but it retains the same direction.
  22000. *
  22001. * @method Phaser.Point#normalize
  22002. * @return {Phaser.Point} This Point object.
  22003. */
  22004. normalize: function () {
  22005. if (!this.isZero())
  22006. {
  22007. var m = this.getMagnitude();
  22008. this.x /= m;
  22009. this.y /= m;
  22010. }
  22011. return this;
  22012. },
  22013. /**
  22014. * Determine if this point is at 0,0.
  22015. *
  22016. * @method Phaser.Point#isZero
  22017. * @return {boolean} True if this Point is 0,0, otherwise false.
  22018. */
  22019. isZero: function () {
  22020. return (this.x === 0 && this.y === 0);
  22021. },
  22022. /**
  22023. * The dot product of this and another Point object.
  22024. *
  22025. * @method Phaser.Point#dot
  22026. * @param {Phaser.Point} a - The Point object to get the dot product combined with this Point.
  22027. * @return {number} The result.
  22028. */
  22029. dot: function (a) {
  22030. return ((this.x * a.x) + (this.y * a.y));
  22031. },
  22032. /**
  22033. * The cross product of this and another Point object.
  22034. *
  22035. * @method Phaser.Point#cross
  22036. * @param {Phaser.Point} a - The Point object to get the cross product combined with this Point.
  22037. * @return {number} The result.
  22038. */
  22039. cross: function (a) {
  22040. return ((this.x * a.y) - (this.y * a.x));
  22041. },
  22042. /**
  22043. * Make this Point perpendicular (90 degrees rotation)
  22044. *
  22045. * @method Phaser.Point#perp
  22046. * @return {Phaser.Point} This Point object.
  22047. */
  22048. perp: function () {
  22049. return this.setTo(-this.y, this.x);
  22050. },
  22051. /**
  22052. * Make this Point perpendicular (-90 degrees rotation)
  22053. *
  22054. * @method Phaser.Point#rperp
  22055. * @return {Phaser.Point} This Point object.
  22056. */
  22057. rperp: function () {
  22058. return this.setTo(this.y, -this.x);
  22059. },
  22060. /**
  22061. * Right-hand normalize (make unit length) this Point.
  22062. *
  22063. * @method Phaser.Point#normalRightHand
  22064. * @return {Phaser.Point} This Point object.
  22065. */
  22066. normalRightHand: function () {
  22067. return this.setTo(this.y * -1, this.x);
  22068. },
  22069. /**
  22070. * Math.floor() both the x and y properties of this Point.
  22071. *
  22072. * @method Phaser.Point#floor
  22073. * @return {Phaser.Point} This Point object.
  22074. */
  22075. floor: function () {
  22076. return this.setTo(Math.floor(this.x), Math.floor(this.y));
  22077. },
  22078. /**
  22079. * Math.ceil() both the x and y properties of this Point.
  22080. *
  22081. * @method Phaser.Point#ceil
  22082. * @return {Phaser.Point} This Point object.
  22083. */
  22084. ceil: function () {
  22085. return this.setTo(Math.ceil(this.x), Math.ceil(this.y));
  22086. },
  22087. /**
  22088. * Returns a string representation of this object.
  22089. *
  22090. * @method Phaser.Point#toString
  22091. * @return {string} A string representation of the instance.
  22092. */
  22093. toString: function () {
  22094. return '[{Point (x=' + this.x + ' y=' + this.y + ')}]';
  22095. }
  22096. };
  22097. Phaser.Point.prototype.constructor = Phaser.Point;
  22098. /**
  22099. * Adds the coordinates of two points together to create a new point.
  22100. *
  22101. * @method Phaser.Point.add
  22102. * @param {Phaser.Point} a - The first Point object.
  22103. * @param {Phaser.Point} b - The second Point object.
  22104. * @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created.
  22105. * @return {Phaser.Point} The new Point object.
  22106. */
  22107. Phaser.Point.add = function (a, b, out) {
  22108. if (out === undefined) { out = new Phaser.Point(); }
  22109. out.x = a.x + b.x;
  22110. out.y = a.y + b.y;
  22111. return out;
  22112. };
  22113. /**
  22114. * Subtracts the coordinates of two points to create a new point.
  22115. *
  22116. * @method Phaser.Point.subtract
  22117. * @param {Phaser.Point} a - The first Point object.
  22118. * @param {Phaser.Point} b - The second Point object.
  22119. * @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created.
  22120. * @return {Phaser.Point} The new Point object.
  22121. */
  22122. Phaser.Point.subtract = function (a, b, out) {
  22123. if (out === undefined) { out = new Phaser.Point(); }
  22124. out.x = a.x - b.x;
  22125. out.y = a.y - b.y;
  22126. return out;
  22127. };
  22128. /**
  22129. * Multiplies the coordinates of two points to create a new point.
  22130. *
  22131. * @method Phaser.Point.multiply
  22132. * @param {Phaser.Point} a - The first Point object.
  22133. * @param {Phaser.Point} b - The second Point object.
  22134. * @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created.
  22135. * @return {Phaser.Point} The new Point object.
  22136. */
  22137. Phaser.Point.multiply = function (a, b, out) {
  22138. if (out === undefined) { out = new Phaser.Point(); }
  22139. out.x = a.x * b.x;
  22140. out.y = a.y * b.y;
  22141. return out;
  22142. };
  22143. /**
  22144. * Divides the coordinates of two points to create a new point.
  22145. *
  22146. * @method Phaser.Point.divide
  22147. * @param {Phaser.Point} a - The first Point object.
  22148. * @param {Phaser.Point} b - The second Point object.
  22149. * @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created.
  22150. * @return {Phaser.Point} The new Point object.
  22151. */
  22152. Phaser.Point.divide = function (a, b, out) {
  22153. if (out === undefined) { out = new Phaser.Point(); }
  22154. out.x = a.x / b.x;
  22155. out.y = a.y / b.y;
  22156. return out;
  22157. };
  22158. /**
  22159. * Determines whether the two given Point objects are equal. They are considered equal if they have the same x and y values.
  22160. *
  22161. * @method Phaser.Point.equals
  22162. * @param {Phaser.Point} a - The first Point object.
  22163. * @param {Phaser.Point} b - The second Point object.
  22164. * @return {boolean} A value of true if the Points are equal, otherwise false.
  22165. */
  22166. Phaser.Point.equals = function (a, b) {
  22167. return (a.x === b.x && a.y === b.y);
  22168. };
  22169. /**
  22170. * Returns the angle between two Point objects.
  22171. *
  22172. * @method Phaser.Point.angle
  22173. * @param {Phaser.Point} a - The first Point object.
  22174. * @param {Phaser.Point} b - The second Point object.
  22175. * @return {number} The angle between the two Points.
  22176. */
  22177. Phaser.Point.angle = function (a, b) {
  22178. // return Math.atan2(a.x * b.y - a.y * b.x, a.x * b.x + a.y * b.y);
  22179. return Math.atan2(a.y - b.y, a.x - b.x);
  22180. };
  22181. /**
  22182. * Creates a negative Point.
  22183. *
  22184. * @method Phaser.Point.negative
  22185. * @param {Phaser.Point} a - The first Point object.
  22186. * @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created.
  22187. * @return {Phaser.Point} The new Point object.
  22188. */
  22189. Phaser.Point.negative = function (a, out) {
  22190. if (out === undefined) { out = new Phaser.Point(); }
  22191. return out.setTo(-a.x, -a.y);
  22192. };
  22193. /**
  22194. * Adds two 2D Points together and multiplies the result by the given scalar.
  22195. *
  22196. * @method Phaser.Point.multiplyAdd
  22197. * @param {Phaser.Point} a - The first Point object.
  22198. * @param {Phaser.Point} b - The second Point object.
  22199. * @param {number} s - The scaling value.
  22200. * @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created.
  22201. * @return {Phaser.Point} The new Point object.
  22202. */
  22203. Phaser.Point.multiplyAdd = function (a, b, s, out) {
  22204. if (out === undefined) { out = new Phaser.Point(); }
  22205. return out.setTo(a.x + b.x * s, a.y + b.y * s);
  22206. };
  22207. /**
  22208. * Interpolates the two given Points, based on the `f` value (between 0 and 1) and returns a new Point.
  22209. *
  22210. * @method Phaser.Point.interpolate
  22211. * @param {Phaser.Point} a - The first Point object.
  22212. * @param {Phaser.Point} b - The second Point object.
  22213. * @param {number} f - The level of interpolation between the two points. Indicates where the new point will be, along the line between pt1 and pt2. If f=1, pt1 is returned; if f=0, pt2 is returned.
  22214. * @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created.
  22215. * @return {Phaser.Point} The new Point object.
  22216. */
  22217. Phaser.Point.interpolate = function (a, b, f, out) {
  22218. if (out === undefined) { out = new Phaser.Point(); }
  22219. return out.setTo(a.x + (b.x - a.x) * f, a.y + (b.y - a.y) * f);
  22220. };
  22221. /**
  22222. * Return a perpendicular vector (90 degrees rotation)
  22223. *
  22224. * @method Phaser.Point.perp
  22225. * @param {Phaser.Point} a - The Point object.
  22226. * @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created.
  22227. * @return {Phaser.Point} The new Point object.
  22228. */
  22229. Phaser.Point.perp = function (a, out) {
  22230. if (out === undefined) { out = new Phaser.Point(); }
  22231. return out.setTo(-a.y, a.x);
  22232. };
  22233. /**
  22234. * Return a perpendicular vector (-90 degrees rotation)
  22235. *
  22236. * @method Phaser.Point.rperp
  22237. * @param {Phaser.Point} a - The Point object.
  22238. * @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created.
  22239. * @return {Phaser.Point} The new Point object.
  22240. */
  22241. Phaser.Point.rperp = function (a, out) {
  22242. if (out === undefined) { out = new Phaser.Point(); }
  22243. return out.setTo(a.y, -a.x);
  22244. };
  22245. /**
  22246. * Returns the euclidian distance of this Point object to the given object (can be a Circle, Point or anything with x/y properties).
  22247. *
  22248. * @method Phaser.Point.distance
  22249. * @param {object} a - The target object. Must have visible x and y properties that represent the center of the object.
  22250. * @param {object} b - The target object. Must have visible x and y properties that represent the center of the object.
  22251. * @param {boolean} [round=false] - Round the distance to the nearest integer.
  22252. * @return {number} The distance between this Point object and the destination Point object.
  22253. */
  22254. Phaser.Point.distance = function (a, b, round) {
  22255. var distance = Phaser.Math.distance(a.x, a.y, b.x, b.y);
  22256. return round ? Math.round(distance) : distance;
  22257. };
  22258. /**
  22259. * Project two Points onto another Point.
  22260. *
  22261. * @method Phaser.Point.project
  22262. * @param {Phaser.Point} a - The first Point object.
  22263. * @param {Phaser.Point} b - The second Point object.
  22264. * @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created.
  22265. * @return {Phaser.Point} The new Point object.
  22266. */
  22267. Phaser.Point.project = function (a, b, out) {
  22268. if (out === undefined) { out = new Phaser.Point(); }
  22269. var amt = a.dot(b) / b.getMagnitudeSq();
  22270. if (amt !== 0)
  22271. {
  22272. out.setTo(amt * b.x, amt * b.y);
  22273. }
  22274. return out;
  22275. };
  22276. /**
  22277. * Project two Points onto a Point of unit length.
  22278. *
  22279. * @method Phaser.Point.projectUnit
  22280. * @param {Phaser.Point} a - The first Point object.
  22281. * @param {Phaser.Point} b - The second Point object.
  22282. * @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created.
  22283. * @return {Phaser.Point} The new Point object.
  22284. */
  22285. Phaser.Point.projectUnit = function (a, b, out) {
  22286. if (out === undefined) { out = new Phaser.Point(); }
  22287. var amt = a.dot(b);
  22288. if (amt !== 0)
  22289. {
  22290. out.setTo(amt * b.x, amt * b.y);
  22291. }
  22292. return out;
  22293. };
  22294. /**
  22295. * Right-hand normalize (make unit length) a Point.
  22296. *
  22297. * @method Phaser.Point.normalRightHand
  22298. * @param {Phaser.Point} a - The Point object.
  22299. * @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created.
  22300. * @return {Phaser.Point} The new Point object.
  22301. */
  22302. Phaser.Point.normalRightHand = function (a, out) {
  22303. if (out === undefined) { out = new Phaser.Point(); }
  22304. return out.setTo(a.y * -1, a.x);
  22305. };
  22306. /**
  22307. * Normalize (make unit length) a Point.
  22308. *
  22309. * @method Phaser.Point.normalize
  22310. * @param {Phaser.Point} a - The Point object.
  22311. * @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created.
  22312. * @return {Phaser.Point} The new Point object.
  22313. */
  22314. Phaser.Point.normalize = function (a, out) {
  22315. if (out === undefined) { out = new Phaser.Point(); }
  22316. var m = a.getMagnitude();
  22317. if (m !== 0)
  22318. {
  22319. out.setTo(a.x / m, a.y / m);
  22320. }
  22321. return out;
  22322. };
  22323. /**
  22324. * Rotates a Point object, or any object with exposed x/y properties, around the given coordinates by
  22325. * the angle specified. If the angle between the point and coordinates was 45 deg and the angle argument
  22326. * is 45 deg then the resulting angle will be 90 deg, as the angle argument is added to the current angle.
  22327. *
  22328. * The distance allows you to specify a distance constraint for the rotation between the point and the
  22329. * coordinates. If none is given the distance between the two is calculated and used.
  22330. *
  22331. * @method Phaser.Point.rotate
  22332. * @param {Phaser.Point} a - The Point object to rotate.
  22333. * @param {number} x - The x coordinate of the anchor point
  22334. * @param {number} y - The y coordinate of the anchor point
  22335. * @param {number} angle - The angle in radians (unless asDegrees is true) to rotate the Point by.
  22336. * @param {boolean} [asDegrees=false] - Is the given angle in radians (false) or degrees (true)?
  22337. * @param {number} [distance] - An optional distance constraint between the Point and the anchor.
  22338. * @return {Phaser.Point} The modified point object.
  22339. */
  22340. Phaser.Point.rotate = function (a, x, y, angle, asDegrees, distance) {
  22341. if (asDegrees) { angle = Phaser.Math.degToRad(angle); }
  22342. if (distance === undefined)
  22343. {
  22344. a.subtract(x, y);
  22345. var s = Math.sin(angle);
  22346. var c = Math.cos(angle);
  22347. var tx = c * a.x - s * a.y;
  22348. var ty = s * a.x + c * a.y;
  22349. a.x = tx + x;
  22350. a.y = ty + y;
  22351. }
  22352. else
  22353. {
  22354. var t = angle + Math.atan2(a.y - y, a.x - x);
  22355. a.x = x + distance * Math.cos(t);
  22356. a.y = y + distance * Math.sin(t);
  22357. }
  22358. return a;
  22359. };
  22360. /**
  22361. * Calculates centroid (or midpoint) from an array of points. If only one point is provided, that point is returned.
  22362. *
  22363. * @method Phaser.Point.centroid
  22364. * @param {Phaser.Point[]} points - The array of one or more points.
  22365. * @param {Phaser.Point} [out] - Optional Point to store the value in, if not supplied a new Point object will be created.
  22366. * @return {Phaser.Point} The new Point object.
  22367. */
  22368. Phaser.Point.centroid = function (points, out) {
  22369. if (out === undefined) { out = new Phaser.Point(); }
  22370. if (Object.prototype.toString.call(points) !== '[object Array]')
  22371. {
  22372. throw new Error("Phaser.Point. Parameter 'points' must be an array");
  22373. }
  22374. var pointslength = points.length;
  22375. if (pointslength < 1)
  22376. {
  22377. throw new Error("Phaser.Point. Parameter 'points' array must not be empty");
  22378. }
  22379. if (pointslength === 1)
  22380. {
  22381. out.copyFrom(points[0]);
  22382. return out;
  22383. }
  22384. for (var i = 0; i < pointslength; i++)
  22385. {
  22386. Phaser.Point.add(out, points[i], out);
  22387. }
  22388. out.divide(pointslength, pointslength);
  22389. return out;
  22390. };
  22391. /**
  22392. * Parses an object for x and/or y properties and returns a new Phaser.Point with matching values.
  22393. * If the object doesn't contain those properties a Point with x/y of zero will be returned.
  22394. *
  22395. * @method Phaser.Point.parse
  22396. * @static
  22397. * @param {object} obj - The object to parse.
  22398. * @param {string} [xProp='x'] - The property used to set the Point.x value.
  22399. * @param {string} [yProp='y'] - The property used to set the Point.y value.
  22400. * @return {Phaser.Point} The new Point object.
  22401. */
  22402. Phaser.Point.parse = function(obj, xProp, yProp) {
  22403. xProp = xProp || 'x';
  22404. yProp = yProp || 'y';
  22405. var point = new Phaser.Point();
  22406. if (obj[xProp])
  22407. {
  22408. point.x = parseInt(obj[xProp], 10);
  22409. }
  22410. if (obj[yProp])
  22411. {
  22412. point.y = parseInt(obj[yProp], 10);
  22413. }
  22414. return point;
  22415. };
  22416. // Because PIXI uses its own Point, we'll replace it with ours to avoid duplicating code or confusion.
  22417. PIXI.Point = Phaser.Point;
  22418. /**
  22419. * @author Richard Davey <rich@photonstorm.com>
  22420. * @author Adrien Brault <adrien.brault@gmail.com>
  22421. * @copyright 2016 Photon Storm Ltd.
  22422. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  22423. */
  22424. /**
  22425. * Creates a new Polygon.
  22426. *
  22427. * The points can be set from a variety of formats:
  22428. *
  22429. * - An array of Point objects: `[new Phaser.Point(x1, y1), ...]`
  22430. * - An array of objects with public x/y properties: `[obj1, obj2, ...]`
  22431. * - An array of paired numbers that represent point coordinates: `[x1,y1, x2,y2, ...]`
  22432. * - As separate Point arguments: `setTo(new Phaser.Point(x1, y1), ...)`
  22433. * - As separate objects with public x/y properties arguments: `setTo(obj1, obj2, ...)`
  22434. * - As separate arguments representing point coordinates: `setTo(x1,y1, x2,y2, ...)`
  22435. *
  22436. * @class Phaser.Polygon
  22437. * @constructor
  22438. * @param {Phaser.Point[]|number[]|...Phaser.Point|...number} points - The points to set.
  22439. */
  22440. Phaser.Polygon = function () {
  22441. /**
  22442. * @property {number} area - The area of this Polygon.
  22443. */
  22444. this.area = 0;
  22445. /**
  22446. * @property {array} _points - An array of Points that make up this Polygon.
  22447. * @private
  22448. */
  22449. this._points = [];
  22450. if (arguments.length > 0)
  22451. {
  22452. this.setTo.apply(this, arguments);
  22453. }
  22454. /**
  22455. * @property {boolean} closed - Is the Polygon closed or not?
  22456. */
  22457. this.closed = true;
  22458. /**
  22459. * @property {boolean} flattened - Has this Polygon been flattened by a call to `Polygon.flatten` ?
  22460. */
  22461. this.flattened = false;
  22462. /**
  22463. * @property {number} type - The base object type.
  22464. */
  22465. this.type = Phaser.POLYGON;
  22466. };
  22467. Phaser.Polygon.prototype = {
  22468. /**
  22469. * Export the points as an array of flat numbers, following the sequence [ x,y, x,y, x,y ]
  22470. *
  22471. * @method Phaser.Polygon#toNumberArray
  22472. * @param {array} [output] - The array to append the points to. If not specified a new array will be created.
  22473. * @return {array} The flattened array.
  22474. */
  22475. toNumberArray: function (output) {
  22476. if (output === undefined) { output = []; }
  22477. for (var i = 0; i < this._points.length; i++)
  22478. {
  22479. if (typeof this._points[i] === 'number')
  22480. {
  22481. output.push(this._points[i]);
  22482. output.push(this._points[i + 1]);
  22483. i++;
  22484. }
  22485. else
  22486. {
  22487. output.push(this._points[i].x);
  22488. output.push(this._points[i].y);
  22489. }
  22490. }
  22491. return output;
  22492. },
  22493. /**
  22494. * Flattens this Polygon so the points are a sequence of numbers.
  22495. * Any Point objects found are removed and replaced with two numbers.
  22496. * Also sets the Polygon.flattened property to `true`.
  22497. *
  22498. * @method Phaser.Polygon#flatten
  22499. * @return {Phaser.Polygon} This Polygon object
  22500. */
  22501. flatten: function () {
  22502. this._points = this.toNumberArray();
  22503. this.flattened = true;
  22504. return this;
  22505. },
  22506. /**
  22507. * Creates a copy of the given Polygon.
  22508. * This is a deep clone, the resulting copy contains new Phaser.Point objects
  22509. *
  22510. * @method Phaser.Polygon#clone
  22511. * @param {Phaser.Polygon} [output=(new Polygon)] - The polygon to update. If not specified a new polygon will be created.
  22512. * @return {Phaser.Polygon} The cloned (`output`) polygon object.
  22513. */
  22514. clone: function (output) {
  22515. var points = this._points.slice();
  22516. if (output === undefined || output === null)
  22517. {
  22518. output = new Phaser.Polygon(points);
  22519. }
  22520. else
  22521. {
  22522. output.setTo(points);
  22523. }
  22524. return output;
  22525. },
  22526. /**
  22527. * Checks whether the x and y coordinates are contained within this polygon.
  22528. *
  22529. * @method Phaser.Polygon#contains
  22530. * @param {number} x - The X value of the coordinate to test.
  22531. * @param {number} y - The Y value of the coordinate to test.
  22532. * @return {boolean} True if the coordinates are within this polygon, otherwise false.
  22533. */
  22534. contains: function (x, y) {
  22535. // Adapted from http://www.ecse.rpi.edu/Homepages/wrf/Research/Short_Notes/pnpoly.html by Jonas Raoni Soares Silva
  22536. var inside = false;
  22537. if (this.flattened)
  22538. {
  22539. for (var i = -2, j = this._points.length - 2; (i += 2) < this._points.length; j = i)
  22540. {
  22541. var ix = this._points[i];
  22542. var iy = this._points[i + 1];
  22543. var jx = this._points[j];
  22544. var jy = this._points[j + 1];
  22545. if (((iy <= y && y < jy) || (jy <= y && y < iy)) && (x < (jx - ix) * (y - iy) / (jy - iy) + ix))
  22546. {
  22547. inside = !inside;
  22548. }
  22549. }
  22550. }
  22551. else
  22552. {
  22553. for (var i = -1, j = this._points.length - 1; ++i < this._points.length; j = i)
  22554. {
  22555. var ix = this._points[i].x;
  22556. var iy = this._points[i].y;
  22557. var jx = this._points[j].x;
  22558. var jy = this._points[j].y;
  22559. if (((iy <= y && y < jy) || (jy <= y && y < iy)) && (x < (jx - ix) * (y - iy) / (jy - iy) + ix))
  22560. {
  22561. inside = !inside;
  22562. }
  22563. }
  22564. }
  22565. return inside;
  22566. },
  22567. /**
  22568. * Sets this Polygon to the given points.
  22569. *
  22570. * The points can be set from a variety of formats:
  22571. *
  22572. * - An array of Point objects: `[new Phaser.Point(x1, y1), ...]`
  22573. * - An array of objects with public x/y properties: `[obj1, obj2, ...]`
  22574. * - An array of paired numbers that represent point coordinates: `[x1,y1, x2,y2, ...]`
  22575. * - An array of arrays with two elements representing x/y coordinates: `[[x1, y1], [x2, y2], ...]`
  22576. * - As separate Point arguments: `setTo(new Phaser.Point(x1, y1), ...)`
  22577. * - As separate objects with public x/y properties arguments: `setTo(obj1, obj2, ...)`
  22578. * - As separate arguments representing point coordinates: `setTo(x1,y1, x2,y2, ...)`
  22579. *
  22580. * `setTo` may also be called without any arguments to remove all points.
  22581. *
  22582. * @method Phaser.Polygon#setTo
  22583. * @param {Phaser.Point[]|number[]|...Phaser.Point|...number} points - The points to set.
  22584. * @return {Phaser.Polygon} This Polygon object
  22585. */
  22586. setTo: function (points) {
  22587. this.area = 0;
  22588. this._points = [];
  22589. if (arguments.length > 0)
  22590. {
  22591. // If points isn't an array, use arguments as the array
  22592. if (!Array.isArray(points))
  22593. {
  22594. points = Array.prototype.slice.call(arguments);
  22595. }
  22596. var y0 = Number.MAX_VALUE;
  22597. // Allows for mixed-type arguments
  22598. for (var i = 0, len = points.length; i < len; i++)
  22599. {
  22600. if (typeof points[i] === 'number')
  22601. {
  22602. var p = new PIXI.Point(points[i], points[i + 1]);
  22603. i++;
  22604. }
  22605. else if (Array.isArray(points[i]))
  22606. {
  22607. var p = new PIXI.Point(points[i][0], points[i][1]);
  22608. }
  22609. else
  22610. {
  22611. var p = new PIXI.Point(points[i].x, points[i].y);
  22612. }
  22613. this._points.push(p);
  22614. // Lowest boundary
  22615. if (p.y < y0)
  22616. {
  22617. y0 = p.y;
  22618. }
  22619. }
  22620. this.calculateArea(y0);
  22621. }
  22622. return this;
  22623. },
  22624. /**
  22625. * Calcuates the area of the Polygon. This is available in the property Polygon.area
  22626. *
  22627. * @method Phaser.Polygon#calculateArea
  22628. * @private
  22629. * @param {number} y0 - The lowest boundary
  22630. * @return {number} The area of the Polygon.
  22631. */
  22632. calculateArea: function (y0) {
  22633. var p1;
  22634. var p2;
  22635. var avgHeight;
  22636. var width;
  22637. for (var i = 0, len = this._points.length; i < len; i++)
  22638. {
  22639. p1 = this._points[i];
  22640. if (i === len - 1)
  22641. {
  22642. p2 = this._points[0];
  22643. }
  22644. else
  22645. {
  22646. p2 = this._points[i + 1];
  22647. }
  22648. avgHeight = ((p1.y - y0) + (p2.y - y0)) / 2;
  22649. width = p1.x - p2.x;
  22650. this.area += avgHeight * width;
  22651. }
  22652. return this.area;
  22653. }
  22654. };
  22655. Phaser.Polygon.prototype.constructor = Phaser.Polygon;
  22656. /**
  22657. * Sets and modifies the points of this polygon.
  22658. *
  22659. * See {@link Phaser.Polygon#setTo setTo} for the different kinds of arrays formats that can be assigned.
  22660. *
  22661. * @name Phaser.Polygon#points
  22662. * @property {Phaser.Point[]} points - The array of vertex points.
  22663. * @deprecated Use `setTo`.
  22664. */
  22665. Object.defineProperty(Phaser.Polygon.prototype, 'points', {
  22666. get: function() {
  22667. return this._points;
  22668. },
  22669. set: function(points) {
  22670. if (points != null)
  22671. {
  22672. this.setTo(points);
  22673. }
  22674. else
  22675. {
  22676. // Clear the points
  22677. this.setTo();
  22678. }
  22679. }
  22680. });
  22681. // Because PIXI uses its own type, we'll replace it with ours to avoid duplicating code or confusion.
  22682. PIXI.Polygon = Phaser.Polygon;
  22683. /**
  22684. * @author Richard Davey <rich@photonstorm.com>
  22685. * @copyright 2016 Photon Storm Ltd.
  22686. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  22687. */
  22688. /**
  22689. * Creates a new Rectangle object with the top-left corner specified by the x and y parameters and with the specified width and height parameters.
  22690. * If you call this function without parameters, a Rectangle with x, y, width, and height properties set to 0 is created.
  22691. *
  22692. * @class Phaser.Rectangle
  22693. * @constructor
  22694. * @param {number} x - The x coordinate of the top-left corner of the Rectangle.
  22695. * @param {number} y - The y coordinate of the top-left corner of the Rectangle.
  22696. * @param {number} width - The width of the Rectangle. Should always be either zero or a positive value.
  22697. * @param {number} height - The height of the Rectangle. Should always be either zero or a positive value.
  22698. */
  22699. Phaser.Rectangle = function (x, y, width, height) {
  22700. x = x || 0;
  22701. y = y || 0;
  22702. width = width || 0;
  22703. height = height || 0;
  22704. /**
  22705. * @property {number} x - The x coordinate of the top-left corner of the Rectangle.
  22706. */
  22707. this.x = x;
  22708. /**
  22709. * @property {number} y - The y coordinate of the top-left corner of the Rectangle.
  22710. */
  22711. this.y = y;
  22712. /**
  22713. * @property {number} width - The width of the Rectangle. This value should never be set to a negative.
  22714. */
  22715. this.width = width;
  22716. /**
  22717. * @property {number} height - The height of the Rectangle. This value should never be set to a negative.
  22718. */
  22719. this.height = height;
  22720. /**
  22721. * @property {number} type - The const type of this object.
  22722. * @readonly
  22723. */
  22724. this.type = Phaser.RECTANGLE;
  22725. };
  22726. Phaser.Rectangle.prototype = {
  22727. /**
  22728. * Adjusts the location of the Rectangle object, as determined by its top-left corner, by the specified amounts.
  22729. * @method Phaser.Rectangle#offset
  22730. * @param {number} dx - Moves the x value of the Rectangle object by this amount.
  22731. * @param {number} dy - Moves the y value of the Rectangle object by this amount.
  22732. * @return {Phaser.Rectangle} This Rectangle object.
  22733. */
  22734. offset: function (dx, dy) {
  22735. this.x += dx;
  22736. this.y += dy;
  22737. return this;
  22738. },
  22739. /**
  22740. * Adjusts the location of the Rectangle object using a Point object as a parameter. This method is similar to the Rectangle.offset() method, except that it takes a Point object as a parameter.
  22741. * @method Phaser.Rectangle#offsetPoint
  22742. * @param {Phaser.Point} point - A Point object to use to offset this Rectangle object.
  22743. * @return {Phaser.Rectangle} This Rectangle object.
  22744. */
  22745. offsetPoint: function (point) {
  22746. return this.offset(point.x, point.y);
  22747. },
  22748. /**
  22749. * Sets the members of Rectangle to the specified values.
  22750. * @method Phaser.Rectangle#setTo
  22751. * @param {number} x - The x coordinate of the top-left corner of the Rectangle.
  22752. * @param {number} y - The y coordinate of the top-left corner of the Rectangle.
  22753. * @param {number} width - The width of the Rectangle. Should always be either zero or a positive value.
  22754. * @param {number} height - The height of the Rectangle. Should always be either zero or a positive value.
  22755. * @return {Phaser.Rectangle} This Rectangle object
  22756. */
  22757. setTo: function (x, y, width, height) {
  22758. this.x = x;
  22759. this.y = y;
  22760. this.width = width;
  22761. this.height = height;
  22762. return this;
  22763. },
  22764. /**
  22765. * Scales the width and height of this Rectangle by the given amounts.
  22766. *
  22767. * @method Phaser.Rectangle#scale
  22768. * @param {number} x - The amount to scale the width of the Rectangle by. A value of 0.5 would reduce by half, a value of 2 would double the width, etc.
  22769. * @param {number} [y] - The amount to scale the height of the Rectangle by. A value of 0.5 would reduce by half, a value of 2 would double the height, etc.
  22770. * @return {Phaser.Rectangle} This Rectangle object
  22771. */
  22772. scale: function (x, y) {
  22773. if (y === undefined) { y = x; }
  22774. this.width *= x;
  22775. this.height *= y;
  22776. return this;
  22777. },
  22778. /**
  22779. * Centers this Rectangle so that the center coordinates match the given x and y values.
  22780. *
  22781. * @method Phaser.Rectangle#centerOn
  22782. * @param {number} x - The x coordinate to place the center of the Rectangle at.
  22783. * @param {number} y - The y coordinate to place the center of the Rectangle at.
  22784. * @return {Phaser.Rectangle} This Rectangle object
  22785. */
  22786. centerOn: function (x, y) {
  22787. this.centerX = x;
  22788. this.centerY = y;
  22789. return this;
  22790. },
  22791. /**
  22792. * Runs Math.floor() on both the x and y values of this Rectangle.
  22793. * @method Phaser.Rectangle#floor
  22794. */
  22795. floor: function () {
  22796. this.x = Math.floor(this.x);
  22797. this.y = Math.floor(this.y);
  22798. },
  22799. /**
  22800. * Runs Math.floor() on the x, y, width and height values of this Rectangle.
  22801. * @method Phaser.Rectangle#floorAll
  22802. */
  22803. floorAll: function () {
  22804. this.x = Math.floor(this.x);
  22805. this.y = Math.floor(this.y);
  22806. this.width = Math.floor(this.width);
  22807. this.height = Math.floor(this.height);
  22808. },
  22809. /**
  22810. * Runs Math.ceil() on both the x and y values of this Rectangle.
  22811. * @method Phaser.Rectangle#ceil
  22812. */
  22813. ceil: function () {
  22814. this.x = Math.ceil(this.x);
  22815. this.y = Math.ceil(this.y);
  22816. },
  22817. /**
  22818. * Runs Math.ceil() on the x, y, width and height values of this Rectangle.
  22819. * @method Phaser.Rectangle#ceilAll
  22820. */
  22821. ceilAll: function () {
  22822. this.x = Math.ceil(this.x);
  22823. this.y = Math.ceil(this.y);
  22824. this.width = Math.ceil(this.width);
  22825. this.height = Math.ceil(this.height);
  22826. },
  22827. /**
  22828. * Copies the x, y, width and height properties from any given object to this Rectangle.
  22829. * @method Phaser.Rectangle#copyFrom
  22830. * @param {any} source - The object to copy from.
  22831. * @return {Phaser.Rectangle} This Rectangle object.
  22832. */
  22833. copyFrom: function (source) {
  22834. return this.setTo(source.x, source.y, source.width, source.height);
  22835. },
  22836. /**
  22837. * Copies the x, y, width and height properties from this Rectangle to any given object.
  22838. * @method Phaser.Rectangle#copyTo
  22839. * @param {any} source - The object to copy to.
  22840. * @return {object} This object.
  22841. */
  22842. copyTo: function (dest) {
  22843. dest.x = this.x;
  22844. dest.y = this.y;
  22845. dest.width = this.width;
  22846. dest.height = this.height;
  22847. return dest;
  22848. },
  22849. /**
  22850. * Increases the size of the Rectangle object by the specified amounts. The center point of the Rectangle object stays the same, and its size increases to the left and right by the dx value, and to the top and the bottom by the dy value.
  22851. * @method Phaser.Rectangle#inflate
  22852. * @param {number} dx - The amount to be added to the left side of the Rectangle.
  22853. * @param {number} dy - The amount to be added to the bottom side of the Rectangle.
  22854. * @return {Phaser.Rectangle} This Rectangle object.
  22855. */
  22856. inflate: function (dx, dy) {
  22857. return Phaser.Rectangle.inflate(this, dx, dy);
  22858. },
  22859. /**
  22860. * The size of the Rectangle object, expressed as a Point object with the values of the width and height properties.
  22861. * @method Phaser.Rectangle#size
  22862. * @param {Phaser.Point} [output] - Optional Point object. If given the values will be set into the object, otherwise a brand new Point object will be created and returned.
  22863. * @return {Phaser.Point} The size of the Rectangle object.
  22864. */
  22865. size: function (output) {
  22866. return Phaser.Rectangle.size(this, output);
  22867. },
  22868. /**
  22869. * Resize the Rectangle by providing a new width and height.
  22870. * The x and y positions remain unchanged.
  22871. *
  22872. * @method Phaser.Rectangle#resize
  22873. * @param {number} width - The width of the Rectangle. Should always be either zero or a positive value.
  22874. * @param {number} height - The height of the Rectangle. Should always be either zero or a positive value.
  22875. * @return {Phaser.Rectangle} This Rectangle object
  22876. */
  22877. resize: function (width, height) {
  22878. this.width = width;
  22879. this.height = height;
  22880. return this;
  22881. },
  22882. /**
  22883. * Returns a new Rectangle object with the same values for the x, y, width, and height properties as the original Rectangle object.
  22884. * @method Phaser.Rectangle#clone
  22885. * @param {Phaser.Rectangle} [output] - Optional Rectangle object. If given the values will be set into the object, otherwise a brand new Rectangle object will be created and returned.
  22886. * @return {Phaser.Rectangle}
  22887. */
  22888. clone: function (output) {
  22889. return Phaser.Rectangle.clone(this, output);
  22890. },
  22891. /**
  22892. * Determines whether the specified coordinates are contained within the region defined by this Rectangle object.
  22893. * @method Phaser.Rectangle#contains
  22894. * @param {number} x - The x coordinate of the point to test.
  22895. * @param {number} y - The y coordinate of the point to test.
  22896. * @return {boolean} A value of true if the Rectangle object contains the specified point; otherwise false.
  22897. */
  22898. contains: function (x, y) {
  22899. return Phaser.Rectangle.contains(this, x, y);
  22900. },
  22901. /**
  22902. * Determines whether the first Rectangle object is fully contained within the second Rectangle object.
  22903. * A Rectangle object is said to contain another if the second Rectangle object falls entirely within the boundaries of the first.
  22904. * @method Phaser.Rectangle#containsRect
  22905. * @param {Phaser.Rectangle} b - The second Rectangle object.
  22906. * @return {boolean} A value of true if the Rectangle object contains the specified point; otherwise false.
  22907. */
  22908. containsRect: function (b) {
  22909. return Phaser.Rectangle.containsRect(b, this);
  22910. },
  22911. /**
  22912. * Determines whether the two Rectangles are equal.
  22913. * This method compares the x, y, width and height properties of each Rectangle.
  22914. * @method Phaser.Rectangle#equals
  22915. * @param {Phaser.Rectangle} b - The second Rectangle object.
  22916. * @return {boolean} A value of true if the two Rectangles have exactly the same values for the x, y, width and height properties; otherwise false.
  22917. */
  22918. equals: function (b) {
  22919. return Phaser.Rectangle.equals(this, b);
  22920. },
  22921. /**
  22922. * If the Rectangle object specified in the toIntersect parameter intersects with this Rectangle object, returns the area of intersection as a Rectangle object. If the Rectangles do not intersect, this method returns an empty Rectangle object with its properties set to 0.
  22923. * @method Phaser.Rectangle#intersection
  22924. * @param {Phaser.Rectangle} b - The second Rectangle object.
  22925. * @param {Phaser.Rectangle} out - Optional Rectangle object. If given the intersection values will be set into this object, otherwise a brand new Rectangle object will be created and returned.
  22926. * @return {Phaser.Rectangle} A Rectangle object that equals the area of intersection. If the Rectangles do not intersect, this method returns an empty Rectangle object; that is, a Rectangle with its x, y, width, and height properties set to 0.
  22927. */
  22928. intersection: function (b, out) {
  22929. return Phaser.Rectangle.intersection(this, b, out);
  22930. },
  22931. /**
  22932. * Determines whether this Rectangle and another given Rectangle intersect with each other.
  22933. * This method checks the x, y, width, and height properties of the two Rectangles.
  22934. *
  22935. * @method Phaser.Rectangle#intersects
  22936. * @param {Phaser.Rectangle} b - The second Rectangle object.
  22937. * @return {boolean} A value of true if the specified object intersects with this Rectangle object; otherwise false.
  22938. */
  22939. intersects: function (b) {
  22940. return Phaser.Rectangle.intersects(this, b);
  22941. },
  22942. /**
  22943. * Determines whether the coordinates given intersects (overlaps) with this Rectangle.
  22944. *
  22945. * @method Phaser.Rectangle#intersectsRaw
  22946. * @param {number} left - The x coordinate of the left of the area.
  22947. * @param {number} right - The right coordinate of the area.
  22948. * @param {number} top - The y coordinate of the area.
  22949. * @param {number} bottom - The bottom coordinate of the area.
  22950. * @param {number} tolerance - A tolerance value to allow for an intersection test with padding, default to 0
  22951. * @return {boolean} A value of true if the specified object intersects with the Rectangle; otherwise false.
  22952. */
  22953. intersectsRaw: function (left, right, top, bottom, tolerance) {
  22954. return Phaser.Rectangle.intersectsRaw(this, left, right, top, bottom, tolerance);
  22955. },
  22956. /**
  22957. * Adds two Rectangles together to create a new Rectangle object, by filling in the horizontal and vertical space between the two Rectangles.
  22958. * @method Phaser.Rectangle#union
  22959. * @param {Phaser.Rectangle} b - The second Rectangle object.
  22960. * @param {Phaser.Rectangle} [out] - Optional Rectangle object. If given the new values will be set into this object, otherwise a brand new Rectangle object will be created and returned.
  22961. * @return {Phaser.Rectangle} A Rectangle object that is the union of the two Rectangles.
  22962. */
  22963. union: function (b, out) {
  22964. return Phaser.Rectangle.union(this, b, out);
  22965. },
  22966. /**
  22967. * Returns a uniformly distributed random point from anywhere within this Rectangle.
  22968. *
  22969. * @method Phaser.Rectangle#random
  22970. * @param {Phaser.Point|object} [out] - A Phaser.Point, or any object with public x/y properties, that the values will be set in.
  22971. * If no object is provided a new Phaser.Point object will be created. In high performance areas avoid this by re-using an existing object.
  22972. * @return {Phaser.Point} An object containing the random point in its `x` and `y` properties.
  22973. */
  22974. random: function (out) {
  22975. if (out === undefined) { out = new Phaser.Point(); }
  22976. out.x = this.randomX;
  22977. out.y = this.randomY;
  22978. return out;
  22979. },
  22980. /**
  22981. * Returns a point based on the given position constant, which can be one of:
  22982. *
  22983. * `Phaser.TOP_LEFT`, `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_CENTER`,
  22984. * `Phaser.CENTER`, `Phaser.RIGHT_CENTER`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER`
  22985. * and `Phaser.BOTTOM_RIGHT`.
  22986. *
  22987. * This method returns the same values as calling Rectangle.bottomLeft, etc, but those
  22988. * calls always create a new Point object, where-as this one allows you to use your own.
  22989. *
  22990. * @method Phaser.Rectangle#getPoint
  22991. * @param {integer} [position] - One of the Phaser position constants, such as `Phaser.TOP_RIGHT`.
  22992. * @param {Phaser.Point} [out] - A Phaser.Point that the values will be set in.
  22993. * If no object is provided a new Phaser.Point object will be created. In high performance areas avoid this by re-using an existing object.
  22994. * @return {Phaser.Point} An object containing the point in its `x` and `y` properties.
  22995. */
  22996. getPoint: function (position, out) {
  22997. if (out === undefined) { out = new Phaser.Point(); }
  22998. switch (position)
  22999. {
  23000. default:
  23001. case Phaser.TOP_LEFT:
  23002. return out.set(this.x, this.y);
  23003. case Phaser.TOP_CENTER:
  23004. return out.set(this.centerX, this.y);
  23005. case Phaser.TOP_RIGHT:
  23006. return out.set(this.right, this.y);
  23007. case Phaser.LEFT_CENTER:
  23008. return out.set(this.x, this.centerY);
  23009. case Phaser.CENTER:
  23010. return out.set(this.centerX, this.centerY);
  23011. case Phaser.RIGHT_CENTER:
  23012. return out.set(this.right, this.centerY);
  23013. case Phaser.BOTTOM_LEFT:
  23014. return out.set(this.x, this.bottom);
  23015. case Phaser.BOTTOM_CENTER:
  23016. return out.set(this.centerX, this.bottom);
  23017. case Phaser.BOTTOM_RIGHT:
  23018. return out.set(this.right, this.bottom);
  23019. }
  23020. },
  23021. /**
  23022. * Returns a string representation of this object.
  23023. * @method Phaser.Rectangle#toString
  23024. * @return {string} A string representation of the instance.
  23025. */
  23026. toString: function () {
  23027. return "[{Rectangle (x=" + this.x + " y=" + this.y + " width=" + this.width + " height=" + this.height + " empty=" + this.empty + ")}]";
  23028. }
  23029. };
  23030. /**
  23031. * @name Phaser.Rectangle#halfWidth
  23032. * @property {number} halfWidth - Half of the width of the Rectangle.
  23033. * @readonly
  23034. */
  23035. Object.defineProperty(Phaser.Rectangle.prototype, "halfWidth", {
  23036. get: function () {
  23037. return Math.round(this.width / 2);
  23038. }
  23039. });
  23040. /**
  23041. * @name Phaser.Rectangle#halfHeight
  23042. * @property {number} halfHeight - Half of the height of the Rectangle.
  23043. * @readonly
  23044. */
  23045. Object.defineProperty(Phaser.Rectangle.prototype, "halfHeight", {
  23046. get: function () {
  23047. return Math.round(this.height / 2);
  23048. }
  23049. });
  23050. /**
  23051. * The sum of the y and height properties. Changing the bottom property of a Rectangle object has no effect on the x, y and width properties, but does change the height property.
  23052. * @name Phaser.Rectangle#bottom
  23053. * @property {number} bottom - The sum of the y and height properties.
  23054. */
  23055. Object.defineProperty(Phaser.Rectangle.prototype, "bottom", {
  23056. get: function () {
  23057. return this.y + this.height;
  23058. },
  23059. set: function (value) {
  23060. if (value <= this.y)
  23061. {
  23062. this.height = 0;
  23063. }
  23064. else
  23065. {
  23066. this.height = value - this.y;
  23067. }
  23068. }
  23069. });
  23070. /**
  23071. * The location of the Rectangles bottom left corner as a Point object.
  23072. * @name Phaser.Rectangle#bottomLeft
  23073. * @property {Phaser.Point} bottomLeft - Gets or sets the location of the Rectangles bottom left corner as a Point object.
  23074. */
  23075. Object.defineProperty(Phaser.Rectangle.prototype, "bottomLeft", {
  23076. get: function () {
  23077. return new Phaser.Point(this.x, this.bottom);
  23078. },
  23079. set: function (value) {
  23080. this.x = value.x;
  23081. this.bottom = value.y;
  23082. }
  23083. });
  23084. /**
  23085. * The location of the Rectangles bottom right corner as a Point object.
  23086. * @name Phaser.Rectangle#bottomRight
  23087. * @property {Phaser.Point} bottomRight - Gets or sets the location of the Rectangles bottom right corner as a Point object.
  23088. */
  23089. Object.defineProperty(Phaser.Rectangle.prototype, "bottomRight", {
  23090. get: function () {
  23091. return new Phaser.Point(this.right, this.bottom);
  23092. },
  23093. set: function (value) {
  23094. this.right = value.x;
  23095. this.bottom = value.y;
  23096. }
  23097. });
  23098. /**
  23099. * The x coordinate of the left of the Rectangle. Changing the left property of a Rectangle object has no effect on the y and height properties. However it does affect the width property, whereas changing the x value does not affect the width property.
  23100. * @name Phaser.Rectangle#left
  23101. * @property {number} left - The x coordinate of the left of the Rectangle.
  23102. */
  23103. Object.defineProperty(Phaser.Rectangle.prototype, "left", {
  23104. get: function () {
  23105. return this.x;
  23106. },
  23107. set: function (value) {
  23108. if (value >= this.right) {
  23109. this.width = 0;
  23110. } else {
  23111. this.width = this.right - value;
  23112. }
  23113. this.x = value;
  23114. }
  23115. });
  23116. /**
  23117. * The sum of the x and width properties. Changing the right property of a Rectangle object has no effect on the x, y and height properties, however it does affect the width property.
  23118. * @name Phaser.Rectangle#right
  23119. * @property {number} right - The sum of the x and width properties.
  23120. */
  23121. Object.defineProperty(Phaser.Rectangle.prototype, "right", {
  23122. get: function () {
  23123. return this.x + this.width;
  23124. },
  23125. set: function (value) {
  23126. if (value <= this.x) {
  23127. this.width = 0;
  23128. } else {
  23129. this.width = value - this.x;
  23130. }
  23131. }
  23132. });
  23133. /**
  23134. * The volume of the Rectangle derived from width * height.
  23135. * @name Phaser.Rectangle#volume
  23136. * @property {number} volume - The volume of the Rectangle derived from width * height.
  23137. * @readonly
  23138. */
  23139. Object.defineProperty(Phaser.Rectangle.prototype, "volume", {
  23140. get: function () {
  23141. return this.width * this.height;
  23142. }
  23143. });
  23144. /**
  23145. * The perimeter size of the Rectangle. This is the sum of all 4 sides.
  23146. * @name Phaser.Rectangle#perimeter
  23147. * @property {number} perimeter - The perimeter size of the Rectangle. This is the sum of all 4 sides.
  23148. * @readonly
  23149. */
  23150. Object.defineProperty(Phaser.Rectangle.prototype, "perimeter", {
  23151. get: function () {
  23152. return (this.width * 2) + (this.height * 2);
  23153. }
  23154. });
  23155. /**
  23156. * The x coordinate of the center of the Rectangle.
  23157. * @name Phaser.Rectangle#centerX
  23158. * @property {number} centerX - The x coordinate of the center of the Rectangle.
  23159. */
  23160. Object.defineProperty(Phaser.Rectangle.prototype, "centerX", {
  23161. get: function () {
  23162. return this.x + this.halfWidth;
  23163. },
  23164. set: function (value) {
  23165. this.x = value - this.halfWidth;
  23166. }
  23167. });
  23168. /**
  23169. * The y coordinate of the center of the Rectangle.
  23170. * @name Phaser.Rectangle#centerY
  23171. * @property {number} centerY - The y coordinate of the center of the Rectangle.
  23172. */
  23173. Object.defineProperty(Phaser.Rectangle.prototype, "centerY", {
  23174. get: function () {
  23175. return this.y + this.halfHeight;
  23176. },
  23177. set: function (value) {
  23178. this.y = value - this.halfHeight;
  23179. }
  23180. });
  23181. /**
  23182. * A random value between the left and right values (inclusive) of the Rectangle.
  23183. *
  23184. * @name Phaser.Rectangle#randomX
  23185. * @property {number} randomX - A random value between the left and right values (inclusive) of the Rectangle.
  23186. */
  23187. Object.defineProperty(Phaser.Rectangle.prototype, "randomX", {
  23188. get: function () {
  23189. return this.x + (Math.random() * this.width);
  23190. }
  23191. });
  23192. /**
  23193. * A random value between the top and bottom values (inclusive) of the Rectangle.
  23194. *
  23195. * @name Phaser.Rectangle#randomY
  23196. * @property {number} randomY - A random value between the top and bottom values (inclusive) of the Rectangle.
  23197. */
  23198. Object.defineProperty(Phaser.Rectangle.prototype, "randomY", {
  23199. get: function () {
  23200. return this.y + (Math.random() * this.height);
  23201. }
  23202. });
  23203. /**
  23204. * The y coordinate of the top of the Rectangle. Changing the top property of a Rectangle object has no effect on the x and width properties.
  23205. * However it does affect the height property, whereas changing the y value does not affect the height property.
  23206. * @name Phaser.Rectangle#top
  23207. * @property {number} top - The y coordinate of the top of the Rectangle.
  23208. */
  23209. Object.defineProperty(Phaser.Rectangle.prototype, "top", {
  23210. get: function () {
  23211. return this.y;
  23212. },
  23213. set: function (value) {
  23214. if (value >= this.bottom) {
  23215. this.height = 0;
  23216. this.y = value;
  23217. } else {
  23218. this.height = (this.bottom - value);
  23219. }
  23220. }
  23221. });
  23222. /**
  23223. * The location of the Rectangles top left corner as a Point object.
  23224. * @name Phaser.Rectangle#topLeft
  23225. * @property {Phaser.Point} topLeft - The location of the Rectangles top left corner as a Point object.
  23226. */
  23227. Object.defineProperty(Phaser.Rectangle.prototype, "topLeft", {
  23228. get: function () {
  23229. return new Phaser.Point(this.x, this.y);
  23230. },
  23231. set: function (value) {
  23232. this.x = value.x;
  23233. this.y = value.y;
  23234. }
  23235. });
  23236. /**
  23237. * The location of the Rectangles top right corner as a Point object.
  23238. * @name Phaser.Rectangle#topRight
  23239. * @property {Phaser.Point} topRight - The location of the Rectangles top left corner as a Point object.
  23240. */
  23241. Object.defineProperty(Phaser.Rectangle.prototype, "topRight", {
  23242. get: function () {
  23243. return new Phaser.Point(this.x + this.width, this.y);
  23244. },
  23245. set: function (value) {
  23246. this.right = value.x;
  23247. this.y = value.y;
  23248. }
  23249. });
  23250. /**
  23251. * Determines whether or not this Rectangle object is empty. A Rectangle object is empty if its width or height is less than or equal to 0.
  23252. * If set to true then all of the Rectangle properties are set to 0.
  23253. * @name Phaser.Rectangle#empty
  23254. * @property {boolean} empty - Gets or sets the Rectangles empty state.
  23255. */
  23256. Object.defineProperty(Phaser.Rectangle.prototype, "empty", {
  23257. get: function () {
  23258. return (!this.width || !this.height);
  23259. },
  23260. set: function (value) {
  23261. if (value === true)
  23262. {
  23263. this.setTo(0, 0, 0, 0);
  23264. }
  23265. }
  23266. });
  23267. Phaser.Rectangle.prototype.constructor = Phaser.Rectangle;
  23268. /**
  23269. * Increases the size of the Rectangle object by the specified amounts. The center point of the Rectangle object stays the same, and its size increases to the left and right by the dx value, and to the top and the bottom by the dy value.
  23270. * @method Phaser.Rectangle.inflate
  23271. * @param {Phaser.Rectangle} a - The Rectangle object.
  23272. * @param {number} dx - The amount to be added to the left side of the Rectangle.
  23273. * @param {number} dy - The amount to be added to the bottom side of the Rectangle.
  23274. * @return {Phaser.Rectangle} This Rectangle object.
  23275. */
  23276. Phaser.Rectangle.inflate = function (a, dx, dy) {
  23277. a.x -= dx;
  23278. a.width += 2 * dx;
  23279. a.y -= dy;
  23280. a.height += 2 * dy;
  23281. return a;
  23282. };
  23283. /**
  23284. * Increases the size of the Rectangle object. This method is similar to the Rectangle.inflate() method except it takes a Point object as a parameter.
  23285. * @method Phaser.Rectangle.inflatePoint
  23286. * @param {Phaser.Rectangle} a - The Rectangle object.
  23287. * @param {Phaser.Point} point - The x property of this Point object is used to increase the horizontal dimension of the Rectangle object. The y property is used to increase the vertical dimension of the Rectangle object.
  23288. * @return {Phaser.Rectangle} The Rectangle object.
  23289. */
  23290. Phaser.Rectangle.inflatePoint = function (a, point) {
  23291. return Phaser.Rectangle.inflate(a, point.x, point.y);
  23292. };
  23293. /**
  23294. * The size of the Rectangle object, expressed as a Point object with the values of the width and height properties.
  23295. * @method Phaser.Rectangle.size
  23296. * @param {Phaser.Rectangle} a - The Rectangle object.
  23297. * @param {Phaser.Point} [output] - Optional Point object. If given the values will be set into the object, otherwise a brand new Point object will be created and returned.
  23298. * @return {Phaser.Point} The size of the Rectangle object
  23299. */
  23300. Phaser.Rectangle.size = function (a, output) {
  23301. if (output === undefined || output === null)
  23302. {
  23303. output = new Phaser.Point(a.width, a.height);
  23304. }
  23305. else
  23306. {
  23307. output.setTo(a.width, a.height);
  23308. }
  23309. return output;
  23310. };
  23311. /**
  23312. * Returns a new Rectangle object with the same values for the x, y, width, and height properties as the original Rectangle object.
  23313. * @method Phaser.Rectangle.clone
  23314. * @param {Phaser.Rectangle} a - The Rectangle object.
  23315. * @param {Phaser.Rectangle} [output] - Optional Rectangle object. If given the values will be set into the object, otherwise a brand new Rectangle object will be created and returned.
  23316. * @return {Phaser.Rectangle}
  23317. */
  23318. Phaser.Rectangle.clone = function (a, output) {
  23319. if (output === undefined || output === null)
  23320. {
  23321. output = new Phaser.Rectangle(a.x, a.y, a.width, a.height);
  23322. }
  23323. else
  23324. {
  23325. output.setTo(a.x, a.y, a.width, a.height);
  23326. }
  23327. return output;
  23328. };
  23329. /**
  23330. * Determines whether the specified coordinates are contained within the region defined by this Rectangle object.
  23331. * @method Phaser.Rectangle.contains
  23332. * @param {Phaser.Rectangle} a - The Rectangle object.
  23333. * @param {number} x - The x coordinate of the point to test.
  23334. * @param {number} y - The y coordinate of the point to test.
  23335. * @return {boolean} A value of true if the Rectangle object contains the specified point; otherwise false.
  23336. */
  23337. Phaser.Rectangle.contains = function (a, x, y) {
  23338. if (a.width <= 0 || a.height <= 0)
  23339. {
  23340. return false;
  23341. }
  23342. return (x >= a.x && x < a.right && y >= a.y && y < a.bottom);
  23343. };
  23344. /**
  23345. * Determines whether the specified coordinates are contained within the region defined by the given raw values.
  23346. * @method Phaser.Rectangle.containsRaw
  23347. * @param {number} rx - The x coordinate of the top left of the area.
  23348. * @param {number} ry - The y coordinate of the top left of the area.
  23349. * @param {number} rw - The width of the area.
  23350. * @param {number} rh - The height of the area.
  23351. * @param {number} x - The x coordinate of the point to test.
  23352. * @param {number} y - The y coordinate of the point to test.
  23353. * @return {boolean} A value of true if the Rectangle object contains the specified point; otherwise false.
  23354. */
  23355. Phaser.Rectangle.containsRaw = function (rx, ry, rw, rh, x, y) {
  23356. return (x >= rx && x < (rx + rw) && y >= ry && y < (ry + rh));
  23357. };
  23358. /**
  23359. * Determines whether the specified point is contained within the rectangular region defined by this Rectangle object. This method is similar to the Rectangle.contains() method, except that it takes a Point object as a parameter.
  23360. * @method Phaser.Rectangle.containsPoint
  23361. * @param {Phaser.Rectangle} a - The Rectangle object.
  23362. * @param {Phaser.Point} point - The point object being checked. Can be Point or any object with .x and .y values.
  23363. * @return {boolean} A value of true if the Rectangle object contains the specified point; otherwise false.
  23364. */
  23365. Phaser.Rectangle.containsPoint = function (a, point) {
  23366. return Phaser.Rectangle.contains(a, point.x, point.y);
  23367. };
  23368. /**
  23369. * Determines whether the first Rectangle object is fully contained within the second Rectangle object.
  23370. * A Rectangle object is said to contain another if the second Rectangle object falls entirely within the boundaries of the first.
  23371. * @method Phaser.Rectangle.containsRect
  23372. * @param {Phaser.Rectangle} a - The first Rectangle object.
  23373. * @param {Phaser.Rectangle} b - The second Rectangle object.
  23374. * @return {boolean} A value of true if the Rectangle object contains the specified point; otherwise false.
  23375. */
  23376. Phaser.Rectangle.containsRect = function (a, b) {
  23377. // If the given rect has a larger volume than this one then it can never contain it
  23378. if (a.volume > b.volume)
  23379. {
  23380. return false;
  23381. }
  23382. return (a.x >= b.x && a.y >= b.y && a.right < b.right && a.bottom < b.bottom);
  23383. };
  23384. /**
  23385. * Determines whether the two Rectangles are equal.
  23386. * This method compares the x, y, width and height properties of each Rectangle.
  23387. * @method Phaser.Rectangle.equals
  23388. * @param {Phaser.Rectangle} a - The first Rectangle object.
  23389. * @param {Phaser.Rectangle} b - The second Rectangle object.
  23390. * @return {boolean} A value of true if the two Rectangles have exactly the same values for the x, y, width and height properties; otherwise false.
  23391. */
  23392. Phaser.Rectangle.equals = function (a, b) {
  23393. return (a.x === b.x && a.y === b.y && a.width === b.width && a.height === b.height);
  23394. };
  23395. /**
  23396. * Determines if the two objects (either Rectangles or Rectangle-like) have the same width and height values under strict equality.
  23397. * @method Phaser.Rectangle.sameDimensions
  23398. * @param {Rectangle-like} a - The first Rectangle object.
  23399. * @param {Rectangle-like} b - The second Rectangle object.
  23400. * @return {boolean} True if the object have equivalent values for the width and height properties.
  23401. */
  23402. Phaser.Rectangle.sameDimensions = function (a, b) {
  23403. return (a.width === b.width && a.height === b.height);
  23404. };
  23405. /**
  23406. * If the Rectangle object specified in the toIntersect parameter intersects with this Rectangle object, returns the area of intersection as a Rectangle object. If the Rectangles do not intersect, this method returns an empty Rectangle object with its properties set to 0.
  23407. * @method Phaser.Rectangle.intersection
  23408. * @param {Phaser.Rectangle} a - The first Rectangle object.
  23409. * @param {Phaser.Rectangle} b - The second Rectangle object.
  23410. * @param {Phaser.Rectangle} [output] - Optional Rectangle object. If given the intersection values will be set into this object, otherwise a brand new Rectangle object will be created and returned.
  23411. * @return {Phaser.Rectangle} A Rectangle object that equals the area of intersection. If the Rectangles do not intersect, this method returns an empty Rectangle object; that is, a Rectangle with its x, y, width, and height properties set to 0.
  23412. */
  23413. Phaser.Rectangle.intersection = function (a, b, output) {
  23414. if (output === undefined)
  23415. {
  23416. output = new Phaser.Rectangle();
  23417. }
  23418. if (Phaser.Rectangle.intersects(a, b))
  23419. {
  23420. output.x = Math.max(a.x, b.x);
  23421. output.y = Math.max(a.y, b.y);
  23422. output.width = Math.min(a.right, b.right) - output.x;
  23423. output.height = Math.min(a.bottom, b.bottom) - output.y;
  23424. }
  23425. return output;
  23426. };
  23427. /**
  23428. * Determines whether the two Rectangles intersect with each other.
  23429. * This method checks the x, y, width, and height properties of the Rectangles.
  23430. * @method Phaser.Rectangle.intersects
  23431. * @param {Phaser.Rectangle} a - The first Rectangle object.
  23432. * @param {Phaser.Rectangle} b - The second Rectangle object.
  23433. * @return {boolean} A value of true if the specified object intersects with this Rectangle object; otherwise false.
  23434. */
  23435. Phaser.Rectangle.intersects = function (a, b) {
  23436. if (a.width <= 0 || a.height <= 0 || b.width <= 0 || b.height <= 0)
  23437. {
  23438. return false;
  23439. }
  23440. return !(a.right < b.x || a.bottom < b.y || a.x > b.right || a.y > b.bottom);
  23441. };
  23442. /**
  23443. * Determines whether the object specified intersects (overlaps) with the given values.
  23444. * @method Phaser.Rectangle.intersectsRaw
  23445. * @param {number} left - The x coordinate of the left of the area.
  23446. * @param {number} right - The right coordinate of the area.
  23447. * @param {number} top - The y coordinate of the area.
  23448. * @param {number} bottom - The bottom coordinate of the area.
  23449. * @param {number} tolerance - A tolerance value to allow for an intersection test with padding, default to 0
  23450. * @return {boolean} A value of true if the specified object intersects with the Rectangle; otherwise false.
  23451. */
  23452. Phaser.Rectangle.intersectsRaw = function (a, left, right, top, bottom, tolerance) {
  23453. if (tolerance === undefined) { tolerance = 0; }
  23454. return !(left > a.right + tolerance || right < a.left - tolerance || top > a.bottom + tolerance || bottom < a.top - tolerance);
  23455. };
  23456. /**
  23457. * Adds two Rectangles together to create a new Rectangle object, by filling in the horizontal and vertical space between the two Rectangles.
  23458. * @method Phaser.Rectangle.union
  23459. * @param {Phaser.Rectangle} a - The first Rectangle object.
  23460. * @param {Phaser.Rectangle} b - The second Rectangle object.
  23461. * @param {Phaser.Rectangle} [output] - Optional Rectangle object. If given the new values will be set into this object, otherwise a brand new Rectangle object will be created and returned.
  23462. * @return {Phaser.Rectangle} A Rectangle object that is the union of the two Rectangles.
  23463. */
  23464. Phaser.Rectangle.union = function (a, b, output) {
  23465. if (output === undefined)
  23466. {
  23467. output = new Phaser.Rectangle();
  23468. }
  23469. return output.setTo(Math.min(a.x, b.x), Math.min(a.y, b.y), Math.max(a.right, b.right) - Math.min(a.left, b.left), Math.max(a.bottom, b.bottom) - Math.min(a.top, b.top));
  23470. };
  23471. /**
  23472. * Calculates the Axis Aligned Bounding Box (or aabb) from an array of points.
  23473. *
  23474. * @method Phaser.Rectangle#aabb
  23475. * @param {Phaser.Point[]} points - The array of one or more points.
  23476. * @param {Phaser.Rectangle} [out] - Optional Rectangle to store the value in, if not supplied a new Rectangle object will be created.
  23477. * @return {Phaser.Rectangle} The new Rectangle object.
  23478. * @static
  23479. */
  23480. Phaser.Rectangle.aabb = function(points, out) {
  23481. if (out === undefined) {
  23482. out = new Phaser.Rectangle();
  23483. }
  23484. var xMax = Number.NEGATIVE_INFINITY,
  23485. xMin = Number.POSITIVE_INFINITY,
  23486. yMax = Number.NEGATIVE_INFINITY,
  23487. yMin = Number.POSITIVE_INFINITY;
  23488. points.forEach(function(point) {
  23489. if (point.x > xMax) {
  23490. xMax = point.x;
  23491. }
  23492. if (point.x < xMin) {
  23493. xMin = point.x;
  23494. }
  23495. if (point.y > yMax) {
  23496. yMax = point.y;
  23497. }
  23498. if (point.y < yMin) {
  23499. yMin = point.y;
  23500. }
  23501. });
  23502. out.setTo(xMin, yMin, xMax - xMin, yMax - yMin);
  23503. return out;
  23504. };
  23505. // Because PIXI uses its own Rectangle, we'll replace it with ours to avoid duplicating code or confusion.
  23506. PIXI.Rectangle = Phaser.Rectangle;
  23507. PIXI.EmptyRectangle = new Phaser.Rectangle(0, 0, 0, 0);
  23508. /**
  23509. * @author Mat Groves http://matgroves.com/
  23510. * @author Richard Davey <rich@photonstorm.com>
  23511. * @copyright 2016 Photon Storm Ltd.
  23512. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  23513. */
  23514. /**
  23515. * The Rounded Rectangle object is an area defined by its position and has nice rounded corners,
  23516. * as indicated by its top-left corner point (x, y) and by its width and its height.
  23517. *
  23518. * @class Phaser.RoundedRectangle
  23519. * @constructor
  23520. * @param {number} [x=0] - The x coordinate of the top-left corner of the Rectangle.
  23521. * @param {number} [y=0] - The y coordinate of the top-left corner of the Rectangle.
  23522. * @param {number} [width=0] - The width of the Rectangle. Should always be either zero or a positive value.
  23523. * @param {number} [height=0] - The height of the Rectangle. Should always be either zero or a positive value.
  23524. * @param {number} [radius=20] - Controls the radius of the rounded corners.
  23525. */
  23526. Phaser.RoundedRectangle = function(x, y, width, height, radius)
  23527. {
  23528. if (x === undefined) { x = 0; }
  23529. if (y === undefined) { y = 0; }
  23530. if (width === undefined) { width = 0; }
  23531. if (height === undefined) { height = 0; }
  23532. if (radius === undefined) { radius = 20; }
  23533. /**
  23534. * @property {number} x - The x coordinate of the top-left corner of the Rectangle.
  23535. */
  23536. this.x = x;
  23537. /**
  23538. * @property {number} y - The y coordinate of the top-left corner of the Rectangle.
  23539. */
  23540. this.y = y;
  23541. /**
  23542. * @property {number} width - The width of the Rectangle. This value should never be set to a negative.
  23543. */
  23544. this.width = width;
  23545. /**
  23546. * @property {number} height - The height of the Rectangle. This value should never be set to a negative.
  23547. */
  23548. this.height = height;
  23549. /**
  23550. * @property {number} radius - The radius of the rounded corners.
  23551. */
  23552. this.radius = radius || 20;
  23553. /**
  23554. * @property {number} type - The const type of this object.
  23555. * @readonly
  23556. */
  23557. this.type = Phaser.ROUNDEDRECTANGLE;
  23558. };
  23559. Phaser.RoundedRectangle.prototype = {
  23560. /**
  23561. * Returns a new RoundedRectangle object with the same values for the x, y, width, height and
  23562. * radius properties as this RoundedRectangle object.
  23563. *
  23564. * @method Phaser.RoundedRectangle#clone
  23565. * @return {Phaser.RoundedRectangle}
  23566. */
  23567. clone: function () {
  23568. return new Phaser.RoundedRectangle(this.x, this.y, this.width, this.height, this.radius);
  23569. },
  23570. /**
  23571. * Determines whether the specified coordinates are contained within the region defined by this Rounded Rectangle object.
  23572. *
  23573. * @method Phaser.RoundedRectangle#contains
  23574. * @param {number} x - The x coordinate of the point to test.
  23575. * @param {number} y - The y coordinate of the point to test.
  23576. * @return {boolean} A value of true if the RoundedRectangle Rectangle object contains the specified point; otherwise false.
  23577. */
  23578. contains: function (x, y) {
  23579. if (this.width <= 0 || this.height <= 0)
  23580. {
  23581. return false;
  23582. }
  23583. var x1 = this.x;
  23584. if (x >= x1 && x <= x1 + this.width)
  23585. {
  23586. var y1 = this.y;
  23587. if (y >= y1 && y <= y1 + this.height)
  23588. {
  23589. return true;
  23590. }
  23591. }
  23592. return false;
  23593. }
  23594. };
  23595. Phaser.RoundedRectangle.prototype.constructor = Phaser.RoundedRectangle;
  23596. // Because PIXI uses its own type, we'll replace it with ours to avoid duplicating code or confusion.
  23597. PIXI.RoundedRectangle = Phaser.RoundedRectangle;
  23598. /**
  23599. * @author Richard Davey <rich@photonstorm.com>
  23600. * @copyright 2016 Photon Storm Ltd.
  23601. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  23602. */
  23603. /**
  23604. * A Camera is your view into the game world. It has a position and size and renders only those objects within its field of view.
  23605. * The game automatically creates a single Stage sized camera on boot. Move the camera around the world with Phaser.Camera.x/y
  23606. *
  23607. * @class Phaser.Camera
  23608. * @constructor
  23609. * @param {Phaser.Game} game - Game reference to the currently running game.
  23610. * @param {number} id - Not being used at the moment, will be when Phaser supports multiple camera
  23611. * @param {number} x - Position of the camera on the X axis
  23612. * @param {number} y - Position of the camera on the Y axis
  23613. * @param {number} width - The width of the view rectangle
  23614. * @param {number} height - The height of the view rectangle
  23615. */
  23616. Phaser.Camera = function (game, id, x, y, width, height) {
  23617. /**
  23618. * @property {Phaser.Game} game - A reference to the currently running Game.
  23619. */
  23620. this.game = game;
  23621. /**
  23622. * @property {Phaser.World} world - A reference to the game world.
  23623. */
  23624. this.world = game.world;
  23625. /**
  23626. * @property {number} id - Reserved for future multiple camera set-ups.
  23627. * @default
  23628. */
  23629. this.id = 0;
  23630. /**
  23631. * Camera view.
  23632. * The view into the world we wish to render (by default the game dimensions).
  23633. * The x/y values are in world coordinates, not screen coordinates, the width/height is how many pixels to render.
  23634. * Sprites outside of this view are not rendered if Sprite.autoCull is set to `true`. Otherwise they are always rendered.
  23635. * @property {Phaser.Rectangle} view
  23636. */
  23637. this.view = new Phaser.Rectangle(x, y, width, height);
  23638. /**
  23639. * The Camera is bound to this Rectangle and cannot move outside of it. By default it is enabled and set to the size of the World.
  23640. * The Rectangle can be located anywhere in the world and updated as often as you like. If you don't wish the Camera to be bound
  23641. * at all then set this to null. The values can be anything and are in World coordinates, with 0,0 being the top-left of the world.
  23642. *
  23643. * @property {Phaser.Rectangle} bounds - The Rectangle in which the Camera is bounded. Set to null to allow for movement anywhere.
  23644. */
  23645. this.bounds = new Phaser.Rectangle(x, y, width, height);
  23646. /**
  23647. * @property {Phaser.Rectangle} deadzone - Moving inside this Rectangle will not cause the camera to move.
  23648. */
  23649. this.deadzone = null;
  23650. /**
  23651. * @property {boolean} visible - Whether this camera is visible or not.
  23652. * @default
  23653. */
  23654. this.visible = true;
  23655. /**
  23656. * @property {boolean} roundPx - If a Camera has roundPx set to `true` it will call `view.floor` as part of its update loop, keeping its boundary to integer values. Set this to `false` to disable this from happening.
  23657. * @default
  23658. */
  23659. this.roundPx = true;
  23660. /**
  23661. * @property {boolean} atLimit - Whether this camera is flush with the World Bounds or not.
  23662. */
  23663. this.atLimit = { x: false, y: false };
  23664. /**
  23665. * @property {Phaser.Sprite} target - If the camera is tracking a Sprite, this is a reference to it, otherwise null.
  23666. * @default
  23667. */
  23668. this.target = null;
  23669. /**
  23670. * @property {PIXI.DisplayObject} displayObject - The display object to which all game objects are added. Set by World.boot.
  23671. */
  23672. this.displayObject = null;
  23673. /**
  23674. * @property {Phaser.Point} scale - The scale of the display object to which all game objects are added. Set by World.boot.
  23675. */
  23676. this.scale = null;
  23677. /**
  23678. * @property {number} totalInView - The total number of Sprites with `autoCull` set to `true` that are visible by this Camera.
  23679. * @readonly
  23680. */
  23681. this.totalInView = 0;
  23682. /**
  23683. * The linear interpolation value to use when following a target.
  23684. * The default values of 1 means the camera will instantly snap to the target coordinates.
  23685. * A lower value, such as 0.1 means the camera will more slowly track the target, giving
  23686. * a smooth transition. You can set the horizontal and vertical values independently, and also
  23687. * adjust this value in real-time during your game.
  23688. * @property {Phaser.Point} lerp
  23689. * @default
  23690. */
  23691. this.lerp = new Phaser.Point(1, 1);
  23692. /**
  23693. * @property {Phaser.Signal} onShakeComplete - This signal is dispatched when the camera shake effect completes.
  23694. */
  23695. this.onShakeComplete = new Phaser.Signal();
  23696. /**
  23697. * @property {Phaser.Signal} onFlashComplete - This signal is dispatched when the camera flash effect completes.
  23698. */
  23699. this.onFlashComplete = new Phaser.Signal();
  23700. /**
  23701. * This signal is dispatched when the camera fade effect completes.
  23702. * When the fade effect completes you will be left with the screen black (or whatever
  23703. * color you faded to). In order to reset this call `Camera.resetFX`. This is called
  23704. * automatically when you change State.
  23705. * @property {Phaser.Signal} onFadeComplete
  23706. */
  23707. this.onFadeComplete = new Phaser.Signal();
  23708. /**
  23709. * The Graphics object used to handle camera fx such as fade and flash.
  23710. * @property {Phaser.Graphics} fx
  23711. * @protected
  23712. */
  23713. this.fx = null;
  23714. /**
  23715. * @property {Phaser.Point} _targetPosition - Internal point used to calculate target position.
  23716. * @private
  23717. */
  23718. this._targetPosition = new Phaser.Point();
  23719. /**
  23720. * @property {number} edge - Edge property.
  23721. * @private
  23722. * @default
  23723. */
  23724. this._edge = 0;
  23725. /**
  23726. * @property {Phaser.Point} position - Current position of the camera in world.
  23727. * @private
  23728. * @default
  23729. */
  23730. this._position = new Phaser.Point();
  23731. /**
  23732. * @property {Object} _shake - The shake effect container.
  23733. * @private
  23734. */
  23735. this._shake = {
  23736. intensity: 0,
  23737. duration: 0,
  23738. horizontal: false,
  23739. vertical: false,
  23740. shakeBounds: true,
  23741. x: 0,
  23742. y: 0
  23743. };
  23744. /**
  23745. * @property {number} _fxDuration - FX duration timer.
  23746. * @private
  23747. */
  23748. this._fxDuration = 0;
  23749. /**
  23750. * @property {number} _fxType - The FX type running.
  23751. * @private
  23752. */
  23753. this._fxType = 0;
  23754. };
  23755. /**
  23756. * @constant
  23757. * @type {number}
  23758. */
  23759. Phaser.Camera.FOLLOW_LOCKON = 0;
  23760. /**
  23761. * @constant
  23762. * @type {number}
  23763. */
  23764. Phaser.Camera.FOLLOW_PLATFORMER = 1;
  23765. /**
  23766. * @constant
  23767. * @type {number}
  23768. */
  23769. Phaser.Camera.FOLLOW_TOPDOWN = 2;
  23770. /**
  23771. * @constant
  23772. * @type {number}
  23773. */
  23774. Phaser.Camera.FOLLOW_TOPDOWN_TIGHT = 3;
  23775. /**
  23776. * @constant
  23777. * @type {number}
  23778. */
  23779. Phaser.Camera.SHAKE_BOTH = 4;
  23780. /**
  23781. * @constant
  23782. * @type {number}
  23783. */
  23784. Phaser.Camera.SHAKE_HORIZONTAL = 5;
  23785. /**
  23786. * @constant
  23787. * @type {number}
  23788. */
  23789. Phaser.Camera.SHAKE_VERTICAL = 6;
  23790. /**
  23791. * @constant
  23792. * @type {boolean}
  23793. */
  23794. Phaser.Camera.ENABLE_FX = true;
  23795. Phaser.Camera.prototype = {
  23796. /**
  23797. * Called automatically by Phaser.World.
  23798. *
  23799. * @method Phaser.Camera#boot
  23800. * @private
  23801. */
  23802. boot: function () {
  23803. this.displayObject = this.game.world;
  23804. this.scale = this.game.world.scale;
  23805. this.game.camera = this;
  23806. if (Phaser.Graphics && Phaser.Camera.ENABLE_FX)
  23807. {
  23808. this.fx = new Phaser.Graphics(this.game);
  23809. this.game.stage.addChild(this.fx);
  23810. }
  23811. },
  23812. /**
  23813. * Camera preUpdate. Sets the total view counter to zero.
  23814. *
  23815. * @method Phaser.Camera#preUpdate
  23816. */
  23817. preUpdate: function () {
  23818. this.totalInView = 0;
  23819. },
  23820. /**
  23821. * Tell the camera which sprite to follow.
  23822. *
  23823. * You can set the follow type and a linear interpolation value.
  23824. * Use low lerp values (such as 0.1) to automatically smooth the camera motion.
  23825. *
  23826. * If you find you're getting a slight "jitter" effect when following a Sprite it's probably to do with sub-pixel rendering of the Sprite position.
  23827. * This can be disabled by setting `game.renderer.renderSession.roundPixels = true` to force full pixel rendering.
  23828. *
  23829. * @method Phaser.Camera#follow
  23830. * @param {Phaser.Sprite|Phaser.Image|Phaser.Text} target - The object you want the camera to track. Set to null to not follow anything.
  23831. * @param {number} [style] - Leverage one of the existing "deadzone" presets. If you use a custom deadzone, ignore this parameter and manually specify the deadzone after calling follow().
  23832. * @param {float} [lerpX=1] - A value between 0 and 1. This value specifies the amount of linear interpolation to use when horizontally tracking the target. The closer the value to 1, the faster the camera will track.
  23833. * @param {float} [lerpY=1] - A value between 0 and 1. This value specifies the amount of linear interpolation to use when vertically tracking the target. The closer the value to 1, the faster the camera will track.
  23834. */
  23835. follow: function (target, style, lerpX, lerpY) {
  23836. if (style === undefined) { style = Phaser.Camera.FOLLOW_LOCKON; }
  23837. if (lerpX === undefined) { lerpX = 1; }
  23838. if (lerpY === undefined) { lerpY = 1; }
  23839. this.target = target;
  23840. this.lerp.set(lerpX, lerpY);
  23841. var helper;
  23842. switch (style) {
  23843. case Phaser.Camera.FOLLOW_PLATFORMER:
  23844. var w = this.width / 8;
  23845. var h = this.height / 3;
  23846. this.deadzone = new Phaser.Rectangle((this.width - w) / 2, (this.height - h) / 2 - h * 0.25, w, h);
  23847. break;
  23848. case Phaser.Camera.FOLLOW_TOPDOWN:
  23849. helper = Math.max(this.width, this.height) / 4;
  23850. this.deadzone = new Phaser.Rectangle((this.width - helper) / 2, (this.height - helper) / 2, helper, helper);
  23851. break;
  23852. case Phaser.Camera.FOLLOW_TOPDOWN_TIGHT:
  23853. helper = Math.max(this.width, this.height) / 8;
  23854. this.deadzone = new Phaser.Rectangle((this.width - helper) / 2, (this.height - helper) / 2, helper, helper);
  23855. break;
  23856. case Phaser.Camera.FOLLOW_LOCKON:
  23857. this.deadzone = null;
  23858. break;
  23859. default:
  23860. this.deadzone = null;
  23861. break;
  23862. }
  23863. },
  23864. /**
  23865. * Sets the Camera follow target to null, stopping it from following an object if it's doing so.
  23866. *
  23867. * @method Phaser.Camera#unfollow
  23868. */
  23869. unfollow: function () {
  23870. this.target = null;
  23871. },
  23872. /**
  23873. * Move the camera focus on a display object instantly.
  23874. * @method Phaser.Camera#focusOn
  23875. * @param {any} displayObject - The display object to focus the camera on. Must have visible x/y properties.
  23876. */
  23877. focusOn: function (displayObject) {
  23878. this.setPosition(Math.round(displayObject.x - this.view.halfWidth), Math.round(displayObject.y - this.view.halfHeight));
  23879. },
  23880. /**
  23881. * Move the camera focus on a location instantly.
  23882. * @method Phaser.Camera#focusOnXY
  23883. * @param {number} x - X position.
  23884. * @param {number} y - Y position.
  23885. */
  23886. focusOnXY: function (x, y) {
  23887. this.setPosition(Math.round(x - this.view.halfWidth), Math.round(y - this.view.halfHeight));
  23888. },
  23889. /**
  23890. * This creates a camera shake effect. It works by applying a random amount of additional
  23891. * spacing on the x and y axis each frame. You can control the intensity and duration
  23892. * of the effect, and if it should effect both axis or just one.
  23893. *
  23894. * When the shake effect ends the signal Camera.onShakeComplete is dispatched.
  23895. *
  23896. * @method Phaser.Camera#shake
  23897. * @param {float} [intensity=0.05] - The intensity of the camera shake. Given as a percentage of the camera size representing the maximum distance that the camera can move while shaking.
  23898. * @param {number} [duration=500] - The duration of the shake effect in milliseconds.
  23899. * @param {boolean} [force=true] - If a camera shake effect is already running and force is true it will replace the previous effect, resetting the duration.
  23900. * @param {number} [direction=Phaser.Camera.SHAKE_BOTH] - The directions in which the camera can shake. Either Phaser.Camera.SHAKE_BOTH, Phaser.Camera.SHAKE_HORIZONTAL or Phaser.Camera.SHAKE_VERTICAL.
  23901. * @param {boolean} [shakeBounds=true] - Is the effect allowed to shake the camera beyond its bounds (if set?).
  23902. * @return {boolean} True if the shake effect was started, otherwise false.
  23903. */
  23904. shake: function (intensity, duration, force, direction, shakeBounds) {
  23905. if (intensity === undefined) { intensity = 0.05; }
  23906. if (duration === undefined) { duration = 500; }
  23907. if (force === undefined) { force = true; }
  23908. if (direction === undefined) { direction = Phaser.Camera.SHAKE_BOTH; }
  23909. if (shakeBounds === undefined) { shakeBounds = true; }
  23910. if (!force && this._shake.duration > 0)
  23911. {
  23912. // Can't reset an already running shake
  23913. return false;
  23914. }
  23915. this._shake.intensity = intensity;
  23916. this._shake.duration = duration;
  23917. this._shake.shakeBounds = shakeBounds;
  23918. this._shake.x = 0;
  23919. this._shake.y = 0;
  23920. this._shake.horizontal = (direction === Phaser.Camera.SHAKE_BOTH || direction === Phaser.Camera.SHAKE_HORIZONTAL);
  23921. this._shake.vertical = (direction === Phaser.Camera.SHAKE_BOTH || direction === Phaser.Camera.SHAKE_VERTICAL);
  23922. return true;
  23923. },
  23924. /**
  23925. * This creates a camera flash effect. It works by filling the game with the solid fill
  23926. * color specified, and then fading it away to alpha 0 over the duration given.
  23927. *
  23928. * You can use this for things such as hit feedback effects.
  23929. *
  23930. * When the effect ends the signal Camera.onFlashComplete is dispatched.
  23931. *
  23932. * @method Phaser.Camera#flash
  23933. * @param {numer} [color=0xffffff] - The color of the flash effect. I.e. 0xffffff for white, 0xff0000 for red, etc.
  23934. * @param {number} [duration=500] - The duration of the flash effect in milliseconds.
  23935. * @param {boolean} [force=false] - If a camera flash or fade effect is already running and force is true it will replace the previous effect, resetting the duration.
  23936. * @return {boolean} True if the effect was started, otherwise false.
  23937. */
  23938. flash: function (color, duration, force) {
  23939. if (color === undefined) { color = 0xffffff; }
  23940. if (duration === undefined) { duration = 500; }
  23941. if (force === undefined) { force = false; }
  23942. if (!this.fx || (!force && this._fxDuration > 0))
  23943. {
  23944. return false;
  23945. }
  23946. this.fx.clear();
  23947. this.fx.beginFill(color);
  23948. this.fx.drawRect(0, 0, this.width, this.height);
  23949. this.fx.endFill();
  23950. this.fx.alpha = 1;
  23951. this._fxDuration = duration;
  23952. this._fxType = 0;
  23953. return true;
  23954. },
  23955. /**
  23956. * This creates a camera fade effect. It works by filling the game with the
  23957. * color specified, over the duration given, ending with a solid fill.
  23958. *
  23959. * You can use this for things such as transitioning to a new scene.
  23960. *
  23961. * The game will be left 'filled' at the end of this effect, likely obscuring
  23962. * everything. In order to reset it you can call `Camera.resetFX` and it will clear the
  23963. * fade. Or you can call `Camera.flash` with the same color as the fade, and it will
  23964. * reverse the process, bringing the game back into view again.
  23965. *
  23966. * When the effect ends the signal Camera.onFadeComplete is dispatched.
  23967. *
  23968. * @method Phaser.Camera#fade
  23969. * @param {numer} [color=0x000000] - The color the game will fade to. I.e. 0x000000 for black, 0xff0000 for red, etc.
  23970. * @param {number} [duration=500] - The duration of the fade in milliseconds.
  23971. * @param {boolean} [force=false] - If a camera flash or fade effect is already running and force is true it will replace the previous effect, resetting the duration.
  23972. * @return {boolean} True if the effect was started, otherwise false.
  23973. */
  23974. fade: function (color, duration, force) {
  23975. if (color === undefined) { color = 0x000000; }
  23976. if (duration === undefined) { duration = 500; }
  23977. if (force === undefined) { force = false; }
  23978. if (!this.fx || (!force && this._fxDuration > 0))
  23979. {
  23980. return false;
  23981. }
  23982. this.fx.clear();
  23983. this.fx.beginFill(color);
  23984. this.fx.drawRect(0, 0, this.width, this.height);
  23985. this.fx.endFill();
  23986. this.fx.alpha = 0;
  23987. this._fxDuration = duration;
  23988. this._fxType = 1;
  23989. return true;
  23990. },
  23991. /**
  23992. * The camera update loop. This is called automatically by the core game loop.
  23993. *
  23994. * @method Phaser.Camera#update
  23995. * @protected
  23996. */
  23997. update: function () {
  23998. if (this._fxDuration > 0)
  23999. {
  24000. this.updateFX();
  24001. }
  24002. if (this._shake.duration > 0)
  24003. {
  24004. this.updateShake();
  24005. }
  24006. if (this.bounds)
  24007. {
  24008. this.checkBounds();
  24009. }
  24010. if (this.roundPx)
  24011. {
  24012. this.view.floor();
  24013. this._shake.x = Math.floor(this._shake.x);
  24014. this._shake.y = Math.floor(this._shake.y);
  24015. }
  24016. this.displayObject.position.x = -this.view.x;
  24017. this.displayObject.position.y = -this.view.y;
  24018. },
  24019. /**
  24020. * Update the camera flash and fade effects.
  24021. *
  24022. * @method Phaser.Camera#updateFX
  24023. * @private
  24024. */
  24025. updateFX: function () {
  24026. if (this._fxType === 0)
  24027. {
  24028. // flash
  24029. this.fx.alpha -= this.game.time.elapsedMS / this._fxDuration;
  24030. if (this.fx.alpha <= 0)
  24031. {
  24032. this._fxDuration = 0;
  24033. this.fx.alpha = 0;
  24034. this.onFlashComplete.dispatch();
  24035. }
  24036. }
  24037. else
  24038. {
  24039. // fade
  24040. this.fx.alpha += this.game.time.elapsedMS / this._fxDuration;
  24041. if (this.fx.alpha >= 1)
  24042. {
  24043. this._fxDuration = 0;
  24044. this.fx.alpha = 1;
  24045. this.onFadeComplete.dispatch();
  24046. }
  24047. }
  24048. },
  24049. /**
  24050. * Update the camera shake effect.
  24051. *
  24052. * @method Phaser.Camera#updateShake
  24053. * @private
  24054. */
  24055. updateShake: function () {
  24056. this._shake.duration -= this.game.time.elapsedMS;
  24057. if (this._shake.duration <= 0)
  24058. {
  24059. this.onShakeComplete.dispatch();
  24060. this._shake.x = 0;
  24061. this._shake.y = 0;
  24062. }
  24063. else
  24064. {
  24065. if (this._shake.horizontal)
  24066. {
  24067. this._shake.x = this.game.rnd.frac() * this._shake.intensity * this.view.width * 2 - this._shake.intensity * this.view.width;
  24068. }
  24069. if (this._shake.vertical)
  24070. {
  24071. this._shake.y = this.game.rnd.frac() * this._shake.intensity * this.view.height * 2 - this._shake.intensity * this.view.height;
  24072. }
  24073. }
  24074. },
  24075. /**
  24076. * Internal method that handles tracking a sprite.
  24077. *
  24078. * @method Phaser.Camera#updateTarget
  24079. * @private
  24080. */
  24081. updateTarget: function () {
  24082. this._targetPosition.x = this.view.x + this.target.worldPosition.x;
  24083. this._targetPosition.y = this.view.y + this.target.worldPosition.y;
  24084. if (this.deadzone)
  24085. {
  24086. this._edge = this._targetPosition.x - this.view.x;
  24087. if (this._edge < this.deadzone.left)
  24088. {
  24089. this.view.x = this.game.math.linear(this.view.x, this._targetPosition.x - this.deadzone.left, this.lerp.x);
  24090. }
  24091. else if (this._edge > this.deadzone.right)
  24092. {
  24093. this.view.x = this.game.math.linear(this.view.x, this._targetPosition.x - this.deadzone.right, this.lerp.x);
  24094. }
  24095. this._edge = this._targetPosition.y - this.view.y;
  24096. if (this._edge < this.deadzone.top)
  24097. {
  24098. this.view.y = this.game.math.linear(this.view.y, this._targetPosition.y - this.deadzone.top, this.lerp.y);
  24099. }
  24100. else if (this._edge > this.deadzone.bottom)
  24101. {
  24102. this.view.y = this.game.math.linear(this.view.y, this._targetPosition.y - this.deadzone.bottom, this.lerp.y);
  24103. }
  24104. }
  24105. else
  24106. {
  24107. this.view.x = this.game.math.linear(this.view.x, this._targetPosition.x - this.view.halfWidth, this.lerp.x);
  24108. this.view.y = this.game.math.linear(this.view.y, this._targetPosition.y - this.view.halfHeight, this.lerp.y);
  24109. }
  24110. if (this.bounds)
  24111. {
  24112. this.checkBounds();
  24113. }
  24114. if (this.roundPx)
  24115. {
  24116. this.view.floor();
  24117. }
  24118. this.displayObject.position.x = -this.view.x;
  24119. this.displayObject.position.y = -this.view.y;
  24120. },
  24121. /**
  24122. * Update the Camera bounds to match the game world.
  24123. *
  24124. * @method Phaser.Camera#setBoundsToWorld
  24125. */
  24126. setBoundsToWorld: function () {
  24127. if (this.bounds)
  24128. {
  24129. this.bounds.copyFrom(this.game.world.bounds);
  24130. }
  24131. },
  24132. /**
  24133. * Method called to ensure the camera doesn't venture outside of the game world.
  24134. * Called automatically by Camera.update.
  24135. *
  24136. * @method Phaser.Camera#checkBounds
  24137. * @protected
  24138. */
  24139. checkBounds: function () {
  24140. this.atLimit.x = false;
  24141. this.atLimit.y = false;
  24142. var vx = this.view.x + this._shake.x;
  24143. var vw = this.view.right + this._shake.x;
  24144. var vy = this.view.y + this._shake.y;
  24145. var vh = this.view.bottom + this._shake.y;
  24146. // Make sure we didn't go outside the cameras bounds
  24147. if (vx <= this.bounds.x * this.scale.x)
  24148. {
  24149. this.atLimit.x = true;
  24150. this.view.x = this.bounds.x * this.scale.x;
  24151. if (!this._shake.shakeBounds)
  24152. {
  24153. // The camera is up against the bounds, so reset the shake
  24154. this._shake.x = 0;
  24155. }
  24156. }
  24157. if (vw >= this.bounds.right * this.scale.x)
  24158. {
  24159. this.atLimit.x = true;
  24160. this.view.x = (this.bounds.right * this.scale.x) - this.width;
  24161. if (!this._shake.shakeBounds)
  24162. {
  24163. // The camera is up against the bounds, so reset the shake
  24164. this._shake.x = 0;
  24165. }
  24166. }
  24167. if (vy <= this.bounds.top * this.scale.y)
  24168. {
  24169. this.atLimit.y = true;
  24170. this.view.y = this.bounds.top * this.scale.y;
  24171. if (!this._shake.shakeBounds)
  24172. {
  24173. // The camera is up against the bounds, so reset the shake
  24174. this._shake.y = 0;
  24175. }
  24176. }
  24177. if (vh >= this.bounds.bottom * this.scale.y)
  24178. {
  24179. this.atLimit.y = true;
  24180. this.view.y = (this.bounds.bottom * this.scale.y) - this.height;
  24181. if (!this._shake.shakeBounds)
  24182. {
  24183. // The camera is up against the bounds, so reset the shake
  24184. this._shake.y = 0;
  24185. }
  24186. }
  24187. },
  24188. /**
  24189. * A helper function to set both the X and Y properties of the camera at once
  24190. * without having to use game.camera.x and game.camera.y.
  24191. *
  24192. * @method Phaser.Camera#setPosition
  24193. * @param {number} x - X position.
  24194. * @param {number} y - Y position.
  24195. */
  24196. setPosition: function (x, y) {
  24197. this.view.x = x;
  24198. this.view.y = y;
  24199. if (this.bounds)
  24200. {
  24201. this.checkBounds();
  24202. }
  24203. },
  24204. /**
  24205. * Sets the size of the view rectangle given the width and height in parameters.
  24206. *
  24207. * @method Phaser.Camera#setSize
  24208. * @param {number} width - The desired width.
  24209. * @param {number} height - The desired height.
  24210. */
  24211. setSize: function (width, height) {
  24212. this.view.width = width;
  24213. this.view.height = height;
  24214. },
  24215. /**
  24216. * Resets the camera back to 0,0 and un-follows any object it may have been tracking.
  24217. * Also immediately resets any camera effects that may have been running such as
  24218. * shake, flash or fade.
  24219. *
  24220. * @method Phaser.Camera#reset
  24221. */
  24222. reset: function () {
  24223. this.target = null;
  24224. this.view.x = 0;
  24225. this.view.y = 0;
  24226. this._shake.duration = 0;
  24227. this.resetFX();
  24228. },
  24229. /**
  24230. * Resets any active FX, such as a fade or flash and immediately clears it.
  24231. * Useful to calling after a fade in order to remove the fade from the Stage.
  24232. *
  24233. * @method Phaser.Camera#resetFX
  24234. */
  24235. resetFX: function () {
  24236. this.fx.clear();
  24237. this.fx.alpha = 0;
  24238. this._fxDuration = 0;
  24239. }
  24240. };
  24241. Phaser.Camera.prototype.constructor = Phaser.Camera;
  24242. /**
  24243. * The Cameras x coordinate. This value is automatically clamped if it falls outside of the World bounds.
  24244. * @name Phaser.Camera#x
  24245. * @property {number} x - Gets or sets the cameras x position.
  24246. */
  24247. Object.defineProperty(Phaser.Camera.prototype, "x", {
  24248. get: function () {
  24249. return this.view.x;
  24250. },
  24251. set: function (value) {
  24252. this.view.x = value;
  24253. if (this.bounds)
  24254. {
  24255. this.checkBounds();
  24256. }
  24257. }
  24258. });
  24259. /**
  24260. * The Cameras y coordinate. This value is automatically clamped if it falls outside of the World bounds.
  24261. * @name Phaser.Camera#y
  24262. * @property {number} y - Gets or sets the cameras y position.
  24263. */
  24264. Object.defineProperty(Phaser.Camera.prototype, "y", {
  24265. get: function () {
  24266. return this.view.y;
  24267. },
  24268. set: function (value) {
  24269. this.view.y = value;
  24270. if (this.bounds)
  24271. {
  24272. this.checkBounds();
  24273. }
  24274. }
  24275. });
  24276. /**
  24277. * The Cameras position. This value is automatically clamped if it falls outside of the World bounds.
  24278. * @name Phaser.Camera#position
  24279. * @property {Phaser.Point} position - Gets or sets the cameras xy position using Phaser.Point object.
  24280. */
  24281. Object.defineProperty(Phaser.Camera.prototype, "position", {
  24282. get: function () {
  24283. this._position.set(this.view.x, this.view.y);
  24284. return this._position;
  24285. },
  24286. set: function (value) {
  24287. if (typeof value.x !== "undefined") { this.view.x = value.x; }
  24288. if (typeof value.y !== "undefined") { this.view.y = value.y; }
  24289. if (this.bounds)
  24290. {
  24291. this.checkBounds();
  24292. }
  24293. }
  24294. });
  24295. /**
  24296. * The Cameras width. By default this is the same as the Game size and should not be adjusted for now.
  24297. * @name Phaser.Camera#width
  24298. * @property {number} width - Gets or sets the cameras width.
  24299. */
  24300. Object.defineProperty(Phaser.Camera.prototype, "width", {
  24301. get: function () {
  24302. return this.view.width;
  24303. },
  24304. set: function (value) {
  24305. this.view.width = value;
  24306. }
  24307. });
  24308. /**
  24309. * The Cameras height. By default this is the same as the Game size and should not be adjusted for now.
  24310. * @name Phaser.Camera#height
  24311. * @property {number} height - Gets or sets the cameras height.
  24312. */
  24313. Object.defineProperty(Phaser.Camera.prototype, "height", {
  24314. get: function () {
  24315. return this.view.height;
  24316. },
  24317. set: function (value) {
  24318. this.view.height = value;
  24319. }
  24320. });
  24321. /**
  24322. * The Cameras shake intensity.
  24323. * @name Phaser.Camera#shakeIntensity
  24324. * @property {number} shakeIntensity - Gets or sets the cameras shake intensity.
  24325. */
  24326. Object.defineProperty(Phaser.Camera.prototype, "shakeIntensity", {
  24327. get: function () {
  24328. return this._shake.intensity;
  24329. },
  24330. set: function (value) {
  24331. this._shake.intensity = value;
  24332. }
  24333. });
  24334. /**
  24335. * @author Richard Davey <rich@photonstorm.com>
  24336. * @copyright 2016 Photon Storm Ltd.
  24337. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  24338. */
  24339. /**
  24340. * This is a base State class which can be extended if you are creating your own game.
  24341. * It provides quick access to common functions such as the camera, cache, input, match, sound and more.
  24342. *
  24343. * @class Phaser.State
  24344. * @constructor
  24345. */
  24346. Phaser.State = function () {
  24347. /**
  24348. * @property {Phaser.Game} game - This is a reference to the currently running Game.
  24349. */
  24350. this.game = null;
  24351. /**
  24352. * @property {string} key - The string based identifier given to the State when added into the State Manager.
  24353. */
  24354. this.key = '';
  24355. /**
  24356. * @property {Phaser.GameObjectFactory} add - A reference to the GameObjectFactory which can be used to add new objects to the World.
  24357. */
  24358. this.add = null;
  24359. /**
  24360. * @property {Phaser.GameObjectCreator} make - A reference to the GameObjectCreator which can be used to make new objects.
  24361. */
  24362. this.make = null;
  24363. /**
  24364. * @property {Phaser.Camera} camera - A handy reference to World.camera.
  24365. */
  24366. this.camera = null;
  24367. /**
  24368. * @property {Phaser.Cache} cache - A reference to the game cache which contains any loaded or generated assets, such as images, sound and more.
  24369. */
  24370. this.cache = null;
  24371. /**
  24372. * @property {Phaser.Input} input - A reference to the Input Manager.
  24373. */
  24374. this.input = null;
  24375. /**
  24376. * @property {Phaser.Loader} load - A reference to the Loader, which you mostly use in the preload method of your state to load external assets.
  24377. */
  24378. this.load = null;
  24379. /**
  24380. * @property {Phaser.Math} math - A reference to Math class with lots of helpful functions.
  24381. */
  24382. this.math = null;
  24383. /**
  24384. * @property {Phaser.SoundManager} sound - A reference to the Sound Manager which can create, play and stop sounds, as well as adjust global volume.
  24385. */
  24386. this.sound = null;
  24387. /**
  24388. * @property {Phaser.ScaleManager} scale - A reference to the Scale Manager which controls the way the game scales on different displays.
  24389. */
  24390. this.scale = null;
  24391. /**
  24392. * @property {Phaser.Stage} stage - A reference to the Stage.
  24393. */
  24394. this.stage = null;
  24395. /**
  24396. * @property {Phaser.StateManager} stage - A reference to the State Manager, which controls state changes.
  24397. */
  24398. this.state = null;
  24399. /**
  24400. * @property {Phaser.Time} time - A reference to the game clock and timed events system.
  24401. */
  24402. this.time = null;
  24403. /**
  24404. * @property {Phaser.TweenManager} tweens - A reference to the tween manager.
  24405. */
  24406. this.tweens = null;
  24407. /**
  24408. * @property {Phaser.World} world - A reference to the game world. All objects live in the Game World and its size is not bound by the display resolution.
  24409. */
  24410. this.world = null;
  24411. /**
  24412. * @property {Phaser.Particles} particles - The Particle Manager. It is called during the core gameloop and updates any Particle Emitters it has created.
  24413. */
  24414. this.particles = null;
  24415. /**
  24416. * @property {Phaser.Physics} physics - A reference to the physics manager which looks after the different physics systems available within Phaser.
  24417. */
  24418. this.physics = null;
  24419. /**
  24420. * @property {Phaser.RandomDataGenerator} rnd - A reference to the seeded and repeatable random data generator.
  24421. */
  24422. this.rnd = null;
  24423. };
  24424. Phaser.State.prototype = {
  24425. /**
  24426. * init is the very first function called when your State starts up. It's called before preload, create or anything else.
  24427. * If you need to route the game away to another State you could do so here, or if you need to prepare a set of variables
  24428. * or objects before the preloading starts.
  24429. *
  24430. * @method Phaser.State#init
  24431. */
  24432. init: function () {
  24433. },
  24434. /**
  24435. * preload is called first. Normally you'd use this to load your game assets (or those needed for the current State)
  24436. * You shouldn't create any objects in this method that require assets that you're also loading in this method, as
  24437. * they won't yet be available.
  24438. *
  24439. * @method Phaser.State#preload
  24440. */
  24441. preload: function () {
  24442. },
  24443. /**
  24444. * loadUpdate is called during the Loader process. This only happens if you've set one or more assets to load in the preload method.
  24445. *
  24446. * @method Phaser.State#loadUpdate
  24447. */
  24448. loadUpdate: function () {
  24449. },
  24450. /**
  24451. * loadRender is called during the Loader process. This only happens if you've set one or more assets to load in the preload method.
  24452. * The difference between loadRender and render is that any objects you render in this method you must be sure their assets exist.
  24453. *
  24454. * @method Phaser.State#loadRender
  24455. */
  24456. loadRender: function () {
  24457. },
  24458. /**
  24459. * create is called once preload has completed, this includes the loading of any assets from the Loader.
  24460. * If you don't have a preload method then create is the first method called in your State.
  24461. *
  24462. * @method Phaser.State#create
  24463. */
  24464. create: function () {
  24465. },
  24466. /**
  24467. * The update method is left empty for your own use.
  24468. * It is called during the core game loop AFTER debug, physics, plugins and the Stage have had their preUpdate methods called.
  24469. * It is called BEFORE Stage, Tweens, Sounds, Input, Physics, Particles and Plugins have had their postUpdate methods called.
  24470. *
  24471. * @method Phaser.State#update
  24472. */
  24473. update: function () {
  24474. },
  24475. /**
  24476. * The preRender method is called after all Game Objects have been updated, but before any rendering takes place.
  24477. *
  24478. * @method Phaser.State#preRender
  24479. */
  24480. preRender: function () {
  24481. },
  24482. /**
  24483. * Nearly all display objects in Phaser render automatically, you don't need to tell them to render.
  24484. * However the render method is called AFTER the game renderer and plugins have rendered, so you're able to do any
  24485. * final post-processing style effects here. Note that this happens before plugins postRender takes place.
  24486. *
  24487. * @method Phaser.State#render
  24488. */
  24489. render: function () {
  24490. },
  24491. /**
  24492. * If your game is set to Scalemode RESIZE then each time the browser resizes it will call this function, passing in the new width and height.
  24493. *
  24494. * @method Phaser.State#resize
  24495. */
  24496. resize: function () {
  24497. },
  24498. /**
  24499. * This method will be called if the core game loop is paused.
  24500. *
  24501. * @method Phaser.State#paused
  24502. */
  24503. paused: function () {
  24504. },
  24505. /**
  24506. * This method will be called when the core game loop resumes from a paused state.
  24507. *
  24508. * @method Phaser.State#resumed
  24509. */
  24510. resumed: function () {
  24511. },
  24512. /**
  24513. * pauseUpdate is called while the game is paused instead of preUpdate, update and postUpdate.
  24514. *
  24515. * @method Phaser.State#pauseUpdate
  24516. */
  24517. pauseUpdate: function () {
  24518. },
  24519. /**
  24520. * This method will be called when the State is shutdown (i.e. you switch to another state from this one).
  24521. *
  24522. * @method Phaser.State#shutdown
  24523. */
  24524. shutdown: function () {
  24525. }
  24526. };
  24527. Phaser.State.prototype.constructor = Phaser.State;
  24528. /* jshint newcap: false */
  24529. /**
  24530. * @author Richard Davey <rich@photonstorm.com>
  24531. * @copyright 2016 Photon Storm Ltd.
  24532. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  24533. */
  24534. /**
  24535. * The State Manager is responsible for loading, setting up and switching game states.
  24536. *
  24537. * @class Phaser.StateManager
  24538. * @constructor
  24539. * @param {Phaser.Game} game - A reference to the currently running game.
  24540. * @param {Phaser.State|Object} [pendingState=null] - A State object to seed the manager with.
  24541. */
  24542. Phaser.StateManager = function (game, pendingState) {
  24543. /**
  24544. * @property {Phaser.Game} game - A reference to the currently running game.
  24545. */
  24546. this.game = game;
  24547. /**
  24548. * @property {object} states - The object containing Phaser.States.
  24549. */
  24550. this.states = {};
  24551. /**
  24552. * @property {Phaser.State} _pendingState - The state to be switched to in the next frame.
  24553. * @private
  24554. */
  24555. this._pendingState = null;
  24556. if (typeof pendingState !== 'undefined' && pendingState !== null)
  24557. {
  24558. this._pendingState = pendingState;
  24559. }
  24560. /**
  24561. * @property {boolean} _clearWorld - Clear the world when we switch state?
  24562. * @private
  24563. */
  24564. this._clearWorld = false;
  24565. /**
  24566. * @property {boolean} _clearCache - Clear the cache when we switch state?
  24567. * @private
  24568. */
  24569. this._clearCache = false;
  24570. /**
  24571. * @property {boolean} _created - Flag that sets if the State has been created or not.
  24572. * @private
  24573. */
  24574. this._created = false;
  24575. /**
  24576. * @property {any[]} _args - Temporary container when you pass vars from one State to another.
  24577. * @private
  24578. */
  24579. this._args = [];
  24580. /**
  24581. * @property {string} current - The current active State object.
  24582. * @default
  24583. */
  24584. this.current = '';
  24585. /**
  24586. * onStateChange is a Phaser.Signal that is dispatched whenever the game changes state.
  24587. *
  24588. * It is dispatched only when the new state is started, which isn't usually at the same time as StateManager.start
  24589. * is called because state swapping is done in sync with the game loop. It is dispatched *before* any of the new states
  24590. * methods (such as preload and create) are called, and *after* the previous states shutdown method has been run.
  24591. *
  24592. * The callback you specify is sent two parameters: the string based key of the new state,
  24593. * and the second parameter is the string based key of the old / previous state.
  24594. *
  24595. * @property {Phaser.Signal} onStateChange
  24596. */
  24597. this.onStateChange = new Phaser.Signal();
  24598. /**
  24599. * @property {function} onInitCallback - This is called when the state is set as the active state.
  24600. * @default
  24601. */
  24602. this.onInitCallback = null;
  24603. /**
  24604. * @property {function} onPreloadCallback - This is called when the state starts to load assets.
  24605. * @default
  24606. */
  24607. this.onPreloadCallback = null;
  24608. /**
  24609. * @property {function} onCreateCallback - This is called when the state preload has finished and creation begins.
  24610. * @default
  24611. */
  24612. this.onCreateCallback = null;
  24613. /**
  24614. * @property {function} onUpdateCallback - This is called when the state is updated, every game loop. It doesn't happen during preload (@see onLoadUpdateCallback).
  24615. * @default
  24616. */
  24617. this.onUpdateCallback = null;
  24618. /**
  24619. * @property {function} onRenderCallback - This is called post-render. It doesn't happen during preload (see onLoadRenderCallback).
  24620. * @default
  24621. */
  24622. this.onRenderCallback = null;
  24623. /**
  24624. * @property {function} onResizeCallback - This is called if ScaleManager.scalemode is RESIZE and a resize event occurs. It's passed the new width and height.
  24625. * @default
  24626. */
  24627. this.onResizeCallback = null;
  24628. /**
  24629. * @property {function} onPreRenderCallback - This is called before the state is rendered and before the stage is cleared but after all game objects have had their final properties adjusted.
  24630. * @default
  24631. */
  24632. this.onPreRenderCallback = null;
  24633. /**
  24634. * @property {function} onLoadUpdateCallback - This is called when the State is updated during the preload phase.
  24635. * @default
  24636. */
  24637. this.onLoadUpdateCallback = null;
  24638. /**
  24639. * @property {function} onLoadRenderCallback - This is called when the State is rendered during the preload phase.
  24640. * @default
  24641. */
  24642. this.onLoadRenderCallback = null;
  24643. /**
  24644. * @property {function} onPausedCallback - This is called when the game is paused.
  24645. * @default
  24646. */
  24647. this.onPausedCallback = null;
  24648. /**
  24649. * @property {function} onResumedCallback - This is called when the game is resumed from a paused state.
  24650. * @default
  24651. */
  24652. this.onResumedCallback = null;
  24653. /**
  24654. * @property {function} onPauseUpdateCallback - This is called every frame while the game is paused.
  24655. * @default
  24656. */
  24657. this.onPauseUpdateCallback = null;
  24658. /**
  24659. * @property {function} onShutDownCallback - This is called when the state is shut down (i.e. swapped to another state).
  24660. * @default
  24661. */
  24662. this.onShutDownCallback = null;
  24663. };
  24664. Phaser.StateManager.prototype = {
  24665. /**
  24666. * The Boot handler is called by Phaser.Game when it first starts up.
  24667. * @method Phaser.StateManager#boot
  24668. * @private
  24669. */
  24670. boot: function () {
  24671. this.game.onPause.add(this.pause, this);
  24672. this.game.onResume.add(this.resume, this);
  24673. if (this._pendingState !== null && typeof this._pendingState !== 'string')
  24674. {
  24675. this.add('default', this._pendingState, true);
  24676. }
  24677. },
  24678. /**
  24679. * Adds a new State into the StateManager. You must give each State a unique key by which you'll identify it.
  24680. * The State can be either a Phaser.State object (or an object that extends it), a plain JavaScript object or a function.
  24681. * If a function is given a new state object will be created by calling it.
  24682. *
  24683. * @method Phaser.StateManager#add
  24684. * @param {string} key - A unique key you use to reference this state, i.e. "MainMenu", "Level1".
  24685. * @param {Phaser.State|object|function} state - The state you want to switch to.
  24686. * @param {boolean} [autoStart=false] - If true the State will be started immediately after adding it.
  24687. */
  24688. add: function (key, state, autoStart) {
  24689. if (autoStart === undefined) { autoStart = false; }
  24690. var newState;
  24691. if (state instanceof Phaser.State)
  24692. {
  24693. newState = state;
  24694. }
  24695. else if (typeof state === 'object')
  24696. {
  24697. newState = state;
  24698. newState.game = this.game;
  24699. }
  24700. else if (typeof state === 'function')
  24701. {
  24702. newState = new state(this.game);
  24703. }
  24704. this.states[key] = newState;
  24705. if (autoStart)
  24706. {
  24707. if (this.game.isBooted)
  24708. {
  24709. this.start(key);
  24710. }
  24711. else
  24712. {
  24713. this._pendingState = key;
  24714. }
  24715. }
  24716. return newState;
  24717. },
  24718. /**
  24719. * Delete the given state.
  24720. * @method Phaser.StateManager#remove
  24721. * @param {string} key - A unique key you use to reference this state, i.e. "MainMenu", "Level1".
  24722. */
  24723. remove: function (key) {
  24724. if (this.current === key)
  24725. {
  24726. this.callbackContext = null;
  24727. this.onInitCallback = null;
  24728. this.onShutDownCallback = null;
  24729. this.onPreloadCallback = null;
  24730. this.onLoadRenderCallback = null;
  24731. this.onLoadUpdateCallback = null;
  24732. this.onCreateCallback = null;
  24733. this.onUpdateCallback = null;
  24734. this.onPreRenderCallback = null;
  24735. this.onRenderCallback = null;
  24736. this.onResizeCallback = null;
  24737. this.onPausedCallback = null;
  24738. this.onResumedCallback = null;
  24739. this.onPauseUpdateCallback = null;
  24740. }
  24741. delete this.states[key];
  24742. },
  24743. /**
  24744. * Start the given State. If a State is already running then State.shutDown will be called (if it exists) before switching to the new State.
  24745. *
  24746. * @method Phaser.StateManager#start
  24747. * @param {string} key - The key of the state you want to start.
  24748. * @param {boolean} [clearWorld=true] - Clear everything in the world? This clears the World display list fully (but not the Stage, so if you've added your own objects to the Stage they will need managing directly)
  24749. * @param {boolean} [clearCache=false] - Clear the Game.Cache? This purges out all loaded assets. The default is false and you must have clearWorld=true if you want to clearCache as well.
  24750. * @param {...*} parameter - Additional parameters that will be passed to the State.init function (if it has one).
  24751. */
  24752. start: function (key, clearWorld, clearCache) {
  24753. if (clearWorld === undefined) { clearWorld = true; }
  24754. if (clearCache === undefined) { clearCache = false; }
  24755. if (this.checkState(key))
  24756. {
  24757. // Place the state in the queue. It will be started the next time the game loop begins.
  24758. this._pendingState = key;
  24759. this._clearWorld = clearWorld;
  24760. this._clearCache = clearCache;
  24761. if (arguments.length > 3)
  24762. {
  24763. this._args = Array.prototype.splice.call(arguments, 3);
  24764. }
  24765. }
  24766. },
  24767. /**
  24768. * Restarts the current State. State.shutDown will be called (if it exists) before the State is restarted.
  24769. *
  24770. * @method Phaser.StateManager#restart
  24771. * @param {boolean} [clearWorld=true] - Clear everything in the world? This clears the World display list fully (but not the Stage, so if you've added your own objects to the Stage they will need managing directly)
  24772. * @param {boolean} [clearCache=false] - Clear the Game.Cache? This purges out all loaded assets. The default is false and you must have clearWorld=true if you want to clearCache as well.
  24773. * @param {...*} parameter - Additional parameters that will be passed to the State.init function if it has one.
  24774. */
  24775. restart: function (clearWorld, clearCache) {
  24776. if (clearWorld === undefined) { clearWorld = true; }
  24777. if (clearCache === undefined) { clearCache = false; }
  24778. // Place the state in the queue. It will be started the next time the game loop starts.
  24779. this._pendingState = this.current;
  24780. this._clearWorld = clearWorld;
  24781. this._clearCache = clearCache;
  24782. if (arguments.length > 2)
  24783. {
  24784. this._args = Array.prototype.slice.call(arguments, 2);
  24785. }
  24786. },
  24787. /**
  24788. * Used by onInit and onShutdown when those functions don't exist on the state
  24789. * @method Phaser.StateManager#dummy
  24790. * @private
  24791. */
  24792. dummy: function () {
  24793. },
  24794. /**
  24795. * preUpdate is called right at the start of the game loop. It is responsible for changing to a new state that was requested previously.
  24796. *
  24797. * @method Phaser.StateManager#preUpdate
  24798. */
  24799. preUpdate: function () {
  24800. if (this._pendingState && this.game.isBooted)
  24801. {
  24802. var previousStateKey = this.current;
  24803. // Already got a state running?
  24804. this.clearCurrentState();
  24805. this.setCurrentState(this._pendingState);
  24806. this.onStateChange.dispatch(this.current, previousStateKey);
  24807. if (this.current !== this._pendingState)
  24808. {
  24809. return;
  24810. }
  24811. else
  24812. {
  24813. this._pendingState = null;
  24814. }
  24815. // If StateManager.start has been called from the init of a State that ALSO has a preload, then
  24816. // onPreloadCallback will be set, but must be ignored
  24817. if (this.onPreloadCallback)
  24818. {
  24819. this.game.load.reset(true);
  24820. this.onPreloadCallback.call(this.callbackContext, this.game);
  24821. // Is the loader empty?
  24822. if (this.game.load.totalQueuedFiles() === 0 && this.game.load.totalQueuedPacks() === 0)
  24823. {
  24824. this.loadComplete();
  24825. }
  24826. else
  24827. {
  24828. // Start the loader going as we have something in the queue
  24829. this.game.load.start();
  24830. }
  24831. }
  24832. else
  24833. {
  24834. // No init? Then there was nothing to load either
  24835. this.loadComplete();
  24836. }
  24837. }
  24838. },
  24839. /**
  24840. * This method clears the current State, calling its shutdown callback. The process also removes any active tweens,
  24841. * resets the camera, resets input, clears physics, removes timers and if set clears the world and cache too.
  24842. *
  24843. * @method Phaser.StateManager#clearCurrentState
  24844. */
  24845. clearCurrentState: function () {
  24846. if (this.current)
  24847. {
  24848. if (this.onShutDownCallback)
  24849. {
  24850. this.onShutDownCallback.call(this.callbackContext, this.game);
  24851. }
  24852. this.game.tweens.removeAll();
  24853. this.game.camera.reset();
  24854. this.game.input.reset(true);
  24855. this.game.physics.clear();
  24856. this.game.time.removeAll();
  24857. this.game.scale.reset(this._clearWorld);
  24858. if (this.game.debug)
  24859. {
  24860. this.game.debug.reset();
  24861. }
  24862. if (this._clearWorld)
  24863. {
  24864. this.game.world.shutdown();
  24865. if (this._clearCache)
  24866. {
  24867. this.game.cache.destroy();
  24868. }
  24869. }
  24870. }
  24871. },
  24872. /**
  24873. * Checks if a given phaser state is valid. A State is considered valid if it has at least one of the core functions: preload, create, update or render.
  24874. *
  24875. * @method Phaser.StateManager#checkState
  24876. * @param {string} key - The key of the state you want to check.
  24877. * @return {boolean} true if the State has the required functions, otherwise false.
  24878. */
  24879. checkState: function (key) {
  24880. if (this.states[key])
  24881. {
  24882. if (this.states[key]['preload'] || this.states[key]['create'] || this.states[key]['update'] || this.states[key]['render'])
  24883. {
  24884. return true;
  24885. }
  24886. else
  24887. {
  24888. console.warn("Invalid Phaser State object given. Must contain at least a one of the required functions: preload, create, update or render");
  24889. return false;
  24890. }
  24891. }
  24892. else
  24893. {
  24894. console.warn("Phaser.StateManager - No state found with the key: " + key);
  24895. return false;
  24896. }
  24897. },
  24898. /**
  24899. * Links game properties to the State given by the key.
  24900. *
  24901. * @method Phaser.StateManager#link
  24902. * @param {string} key - State key.
  24903. * @protected
  24904. */
  24905. link: function (key) {
  24906. this.states[key].game = this.game;
  24907. this.states[key].add = this.game.add;
  24908. this.states[key].make = this.game.make;
  24909. this.states[key].camera = this.game.camera;
  24910. this.states[key].cache = this.game.cache;
  24911. this.states[key].input = this.game.input;
  24912. this.states[key].load = this.game.load;
  24913. this.states[key].math = this.game.math;
  24914. this.states[key].sound = this.game.sound;
  24915. this.states[key].scale = this.game.scale;
  24916. this.states[key].state = this;
  24917. this.states[key].stage = this.game.stage;
  24918. this.states[key].time = this.game.time;
  24919. this.states[key].tweens = this.game.tweens;
  24920. this.states[key].world = this.game.world;
  24921. this.states[key].particles = this.game.particles;
  24922. this.states[key].rnd = this.game.rnd;
  24923. this.states[key].physics = this.game.physics;
  24924. this.states[key].key = key;
  24925. },
  24926. /**
  24927. * Nulls all State level Phaser properties, including a reference to Game.
  24928. *
  24929. * @method Phaser.StateManager#unlink
  24930. * @param {string} key - State key.
  24931. * @protected
  24932. */
  24933. unlink: function (key) {
  24934. if (this.states[key])
  24935. {
  24936. this.states[key].game = null;
  24937. this.states[key].add = null;
  24938. this.states[key].make = null;
  24939. this.states[key].camera = null;
  24940. this.states[key].cache = null;
  24941. this.states[key].input = null;
  24942. this.states[key].load = null;
  24943. this.states[key].math = null;
  24944. this.states[key].sound = null;
  24945. this.states[key].scale = null;
  24946. this.states[key].state = null;
  24947. this.states[key].stage = null;
  24948. this.states[key].time = null;
  24949. this.states[key].tweens = null;
  24950. this.states[key].world = null;
  24951. this.states[key].particles = null;
  24952. this.states[key].rnd = null;
  24953. this.states[key].physics = null;
  24954. }
  24955. },
  24956. /**
  24957. * Sets the current State. Should not be called directly (use StateManager.start)
  24958. *
  24959. * @method Phaser.StateManager#setCurrentState
  24960. * @param {string} key - State key.
  24961. * @private
  24962. */
  24963. setCurrentState: function (key) {
  24964. this.callbackContext = this.states[key];
  24965. this.link(key);
  24966. // Used when the state is set as being the current active state
  24967. this.onInitCallback = this.states[key]['init'] || this.dummy;
  24968. this.onPreloadCallback = this.states[key]['preload'] || null;
  24969. this.onLoadRenderCallback = this.states[key]['loadRender'] || null;
  24970. this.onLoadUpdateCallback = this.states[key]['loadUpdate'] || null;
  24971. this.onCreateCallback = this.states[key]['create'] || null;
  24972. this.onUpdateCallback = this.states[key]['update'] || null;
  24973. this.onPreRenderCallback = this.states[key]['preRender'] || null;
  24974. this.onRenderCallback = this.states[key]['render'] || null;
  24975. this.onResizeCallback = this.states[key]['resize'] || null;
  24976. this.onPausedCallback = this.states[key]['paused'] || null;
  24977. this.onResumedCallback = this.states[key]['resumed'] || null;
  24978. this.onPauseUpdateCallback = this.states[key]['pauseUpdate'] || null;
  24979. // Used when the state is no longer the current active state
  24980. this.onShutDownCallback = this.states[key]['shutdown'] || this.dummy;
  24981. // Reset the physics system, but not on the first state start
  24982. if (this.current !== '')
  24983. {
  24984. this.game.physics.reset();
  24985. }
  24986. this.current = key;
  24987. this._created = false;
  24988. // At this point key and pendingState should equal each other
  24989. this.onInitCallback.apply(this.callbackContext, this._args);
  24990. // If they no longer do then the init callback hit StateManager.start
  24991. if (key === this._pendingState)
  24992. {
  24993. this._args = [];
  24994. }
  24995. this.game._kickstart = true;
  24996. },
  24997. /**
  24998. * Gets the current State.
  24999. *
  25000. * @method Phaser.StateManager#getCurrentState
  25001. * @return {Phaser.State}
  25002. * @public
  25003. */
  25004. getCurrentState: function() {
  25005. return this.states[this.current];
  25006. },
  25007. /**
  25008. * @method Phaser.StateManager#loadComplete
  25009. * @protected
  25010. */
  25011. loadComplete: function () {
  25012. // Make sure to do load-update one last time before state is set to _created
  25013. if (this._created === false && this.onLoadUpdateCallback)
  25014. {
  25015. this.onLoadUpdateCallback.call(this.callbackContext, this.game);
  25016. }
  25017. if (this._created === false && this.onCreateCallback)
  25018. {
  25019. this._created = true;
  25020. this.onCreateCallback.call(this.callbackContext, this.game);
  25021. }
  25022. else
  25023. {
  25024. this._created = true;
  25025. }
  25026. },
  25027. /**
  25028. * @method Phaser.StateManager#pause
  25029. * @protected
  25030. */
  25031. pause: function () {
  25032. if (this._created && this.onPausedCallback)
  25033. {
  25034. this.onPausedCallback.call(this.callbackContext, this.game);
  25035. }
  25036. },
  25037. /**
  25038. * @method Phaser.StateManager#resume
  25039. * @protected
  25040. */
  25041. resume: function () {
  25042. if (this._created && this.onResumedCallback)
  25043. {
  25044. this.onResumedCallback.call(this.callbackContext, this.game);
  25045. }
  25046. },
  25047. /**
  25048. * @method Phaser.StateManager#update
  25049. * @protected
  25050. */
  25051. update: function () {
  25052. if (this._created)
  25053. {
  25054. if (this.onUpdateCallback)
  25055. {
  25056. this.onUpdateCallback.call(this.callbackContext, this.game);
  25057. }
  25058. }
  25059. else
  25060. {
  25061. if (this.onLoadUpdateCallback)
  25062. {
  25063. this.onLoadUpdateCallback.call(this.callbackContext, this.game);
  25064. }
  25065. }
  25066. },
  25067. /**
  25068. * @method Phaser.StateManager#pauseUpdate
  25069. * @protected
  25070. */
  25071. pauseUpdate: function () {
  25072. if (this._created)
  25073. {
  25074. if (this.onPauseUpdateCallback)
  25075. {
  25076. this.onPauseUpdateCallback.call(this.callbackContext, this.game);
  25077. }
  25078. }
  25079. else
  25080. {
  25081. if (this.onLoadUpdateCallback)
  25082. {
  25083. this.onLoadUpdateCallback.call(this.callbackContext, this.game);
  25084. }
  25085. }
  25086. },
  25087. /**
  25088. * @method Phaser.StateManager#preRender
  25089. * @protected
  25090. * @param {number} elapsedTime - The time elapsed since the last update.
  25091. */
  25092. preRender: function (elapsedTime) {
  25093. if (this._created && this.onPreRenderCallback)
  25094. {
  25095. this.onPreRenderCallback.call(this.callbackContext, this.game, elapsedTime);
  25096. }
  25097. },
  25098. /**
  25099. * @method Phaser.StateManager#resize
  25100. * @protected
  25101. */
  25102. resize: function (width, height) {
  25103. if (this.onResizeCallback)
  25104. {
  25105. this.onResizeCallback.call(this.callbackContext, width, height);
  25106. }
  25107. },
  25108. /**
  25109. * @method Phaser.StateManager#render
  25110. * @protected
  25111. */
  25112. render: function () {
  25113. if (this._created)
  25114. {
  25115. if (this.onRenderCallback)
  25116. {
  25117. if (this.game.renderType === Phaser.CANVAS)
  25118. {
  25119. this.game.context.save();
  25120. this.game.context.setTransform(1, 0, 0, 1, 0, 0);
  25121. this.onRenderCallback.call(this.callbackContext, this.game);
  25122. this.game.context.restore();
  25123. }
  25124. else
  25125. {
  25126. this.onRenderCallback.call(this.callbackContext, this.game);
  25127. }
  25128. }
  25129. }
  25130. else
  25131. {
  25132. if (this.onLoadRenderCallback)
  25133. {
  25134. this.onLoadRenderCallback.call(this.callbackContext, this.game);
  25135. }
  25136. }
  25137. },
  25138. /**
  25139. * Removes all StateManager callback references to the State object, nulls the game reference and clears the States object.
  25140. * You don't recover from this without rebuilding the Phaser instance again.
  25141. * @method Phaser.StateManager#destroy
  25142. */
  25143. destroy: function () {
  25144. this._clearWorld = true;
  25145. this._clearCache = true;
  25146. this.clearCurrentState();
  25147. this.callbackContext = null;
  25148. this.onInitCallback = null;
  25149. this.onShutDownCallback = null;
  25150. this.onPreloadCallback = null;
  25151. this.onLoadRenderCallback = null;
  25152. this.onLoadUpdateCallback = null;
  25153. this.onCreateCallback = null;
  25154. this.onUpdateCallback = null;
  25155. this.onRenderCallback = null;
  25156. this.onPausedCallback = null;
  25157. this.onResumedCallback = null;
  25158. this.onPauseUpdateCallback = null;
  25159. this.game = null;
  25160. this.states = {};
  25161. this._pendingState = null;
  25162. this.current = '';
  25163. }
  25164. };
  25165. Phaser.StateManager.prototype.constructor = Phaser.StateManager;
  25166. /**
  25167. * @name Phaser.StateManager#created
  25168. * @property {boolean} created - True if the current state has had its `create` method run (if it has one, if not this is true by default).
  25169. * @readOnly
  25170. */
  25171. Object.defineProperty(Phaser.StateManager.prototype, "created", {
  25172. get: function () {
  25173. return this._created;
  25174. }
  25175. });
  25176. /**
  25177. * "It's like nailing jelly to a kitten" - Gary Penn
  25178. */
  25179. /**
  25180. * @author Miller Medeiros http://millermedeiros.github.com/js-signals/
  25181. * @author Richard Davey <rich@photonstorm.com>
  25182. * @copyright 2016 Photon Storm Ltd.
  25183. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  25184. */
  25185. /**
  25186. * Signals are what Phaser uses to handle events and event dispatching.
  25187. * You can listen for a Signal by binding a callback / function to it.
  25188. * This is done by using either `Signal.add` or `Signal.addOnce`.
  25189. *
  25190. * For example you can listen for a touch or click event from the Input Manager
  25191. * by using its `onDown` Signal:
  25192. *
  25193. * `game.input.onDown.add(function() { ... });`
  25194. *
  25195. * Rather than inline your function, you can pass a reference:
  25196. *
  25197. * `game.input.onDown.add(clicked, this);`
  25198. * `function clicked () { ... }`
  25199. *
  25200. * In this case the second argument (`this`) is the context in which your function should be called.
  25201. *
  25202. * Now every time the InputManager dispatches the `onDown` signal (or event), your function
  25203. * will be called.
  25204. *
  25205. * Very often a Signal will send arguments to your function.
  25206. * This is specific to the Signal itself.
  25207. * If you're unsure then check the documentation, or failing that simply do:
  25208. *
  25209. * `Signal.add(function() { console.log(arguments); })`
  25210. *
  25211. * and it will log all of the arguments your function received from the Signal.
  25212. *
  25213. * Sprites have lots of default signals you can listen to in their Events class, such as:
  25214. *
  25215. * `sprite.events.onKilled`
  25216. *
  25217. * Which is called automatically whenever the Sprite is killed.
  25218. * There are lots of other events, see the Events component for a list.
  25219. *
  25220. * As well as listening to pre-defined Signals you can also create your own:
  25221. *
  25222. * `var mySignal = new Phaser.Signal();`
  25223. *
  25224. * This creates a new Signal. You can bind a callback to it:
  25225. *
  25226. * `mySignal.add(myCallback, this);`
  25227. *
  25228. * and then finally when ready you can dispatch the Signal:
  25229. *
  25230. * `mySignal.dispatch(your arguments);`
  25231. *
  25232. * And your callback will be invoked. See the dispatch method for more details.
  25233. *
  25234. * @class Phaser.Signal
  25235. * @constructor
  25236. */
  25237. Phaser.Signal = function () {};
  25238. Phaser.Signal.prototype = {
  25239. /**
  25240. * @property {?Array.<Phaser.SignalBinding>} _bindings - Internal variable.
  25241. * @private
  25242. */
  25243. _bindings: null,
  25244. /**
  25245. * @property {any} _prevParams - Internal variable.
  25246. * @private
  25247. */
  25248. _prevParams: null,
  25249. /**
  25250. * Memorize the previously dispatched event?
  25251. *
  25252. * If an event has been memorized it is automatically dispatched when a new listener is added with {@link #add} or {@link #addOnce}.
  25253. * Use {@link #forget} to clear any currently memorized event.
  25254. *
  25255. * @property {boolean} memorize
  25256. */
  25257. memorize: false,
  25258. /**
  25259. * @property {boolean} _shouldPropagate
  25260. * @private
  25261. */
  25262. _shouldPropagate: true,
  25263. /**
  25264. * Is the Signal active? Only active signals will broadcast dispatched events.
  25265. *
  25266. * Setting this property during a dispatch will only affect the next dispatch. To stop the propagation of a signal from a listener use {@link #halt}.
  25267. *
  25268. * @property {boolean} active
  25269. * @default
  25270. */
  25271. active: true,
  25272. /**
  25273. * @property {function} _boundDispatch - The bound dispatch function, if any.
  25274. * @private
  25275. */
  25276. _boundDispatch: false,
  25277. /**
  25278. * @method Phaser.Signal#validateListener
  25279. * @param {function} listener - Signal handler function.
  25280. * @param {string} fnName - Function name.
  25281. * @private
  25282. */
  25283. validateListener: function (listener, fnName) {
  25284. if (typeof listener !== 'function')
  25285. {
  25286. throw new Error('Phaser.Signal: listener is a required param of {fn}() and should be a Function.'.replace('{fn}', fnName));
  25287. }
  25288. },
  25289. /**
  25290. * @method Phaser.Signal#_registerListener
  25291. * @private
  25292. * @param {function} listener - Signal handler function.
  25293. * @param {boolean} isOnce - Should the listener only be called once?
  25294. * @param {object} [listenerContext] - The context under which the listener is invoked.
  25295. * @param {number} [priority] - The priority level of the event listener. Listeners with higher priority will be executed before listeners with lower priority. Listeners with same priority level will be executed at the same order as they were added. (default = 0).
  25296. * @return {Phaser.SignalBinding} An Object representing the binding between the Signal and listener.
  25297. */
  25298. _registerListener: function (listener, isOnce, listenerContext, priority, args) {
  25299. var prevIndex = this._indexOfListener(listener, listenerContext);
  25300. var binding;
  25301. if (prevIndex !== -1)
  25302. {
  25303. binding = this._bindings[prevIndex];
  25304. if (binding.isOnce() !== isOnce)
  25305. {
  25306. throw new Error('You cannot add' + (isOnce ? '' : 'Once') + '() then add' + (!isOnce ? '' : 'Once') + '() the same listener without removing the relationship first.');
  25307. }
  25308. }
  25309. else
  25310. {
  25311. binding = new Phaser.SignalBinding(this, listener, isOnce, listenerContext, priority, args);
  25312. this._addBinding(binding);
  25313. }
  25314. if (this.memorize && this._prevParams)
  25315. {
  25316. binding.execute(this._prevParams);
  25317. }
  25318. return binding;
  25319. },
  25320. /**
  25321. * @method Phaser.Signal#_addBinding
  25322. * @private
  25323. * @param {Phaser.SignalBinding} binding - An Object representing the binding between the Signal and listener.
  25324. */
  25325. _addBinding: function (binding) {
  25326. if (!this._bindings)
  25327. {
  25328. this._bindings = [];
  25329. }
  25330. // Simplified insertion sort
  25331. var n = this._bindings.length;
  25332. do {
  25333. n--;
  25334. }
  25335. while (this._bindings[n] && binding._priority <= this._bindings[n]._priority);
  25336. this._bindings.splice(n + 1, 0, binding);
  25337. },
  25338. /**
  25339. * @method Phaser.Signal#_indexOfListener
  25340. * @private
  25341. * @param {function} listener - Signal handler function.
  25342. * @param {object} [context=null] - Signal handler function.
  25343. * @return {number} The index of the listener within the private bindings array.
  25344. */
  25345. _indexOfListener: function (listener, context) {
  25346. if (!this._bindings)
  25347. {
  25348. return -1;
  25349. }
  25350. if (context === undefined) { context = null; }
  25351. var n = this._bindings.length;
  25352. var cur;
  25353. while (n--)
  25354. {
  25355. cur = this._bindings[n];
  25356. if (cur._listener === listener && cur.context === context)
  25357. {
  25358. return n;
  25359. }
  25360. }
  25361. return -1;
  25362. },
  25363. /**
  25364. * Check if a specific listener is attached.
  25365. *
  25366. * @method Phaser.Signal#has
  25367. * @param {function} listener - Signal handler function.
  25368. * @param {object} [context] - Context on which listener will be executed (object that should represent the `this` variable inside listener function).
  25369. * @return {boolean} If Signal has the specified listener.
  25370. */
  25371. has: function (listener, context) {
  25372. return this._indexOfListener(listener, context) !== -1;
  25373. },
  25374. /**
  25375. * Add an event listener for this signal.
  25376. *
  25377. * An event listener is a callback with a related context and priority.
  25378. *
  25379. * You can optionally provide extra arguments which will be passed to the callback after any internal parameters.
  25380. *
  25381. * For example: `Phaser.Key.onDown` when dispatched will send the Phaser.Key object that caused the signal as the first parameter.
  25382. * Any arguments you've specified after `priority` will be sent as well:
  25383. *
  25384. * `fireButton.onDown.add(shoot, this, 0, 'lazer', 100);`
  25385. *
  25386. * When onDown dispatches it will call the `shoot` callback passing it: `Phaser.Key, 'lazer', 100`.
  25387. *
  25388. * Where the first parameter is the one that Key.onDown dispatches internally and 'lazer',
  25389. * and the value 100 were the custom arguments given in the call to 'add'.
  25390. *
  25391. * @method Phaser.Signal#add
  25392. * @param {function} listener - The function to call when this Signal is dispatched.
  25393. * @param {object} [listenerContext] - The context under which the listener will be executed (i.e. the object that should represent the `this` variable).
  25394. * @param {number} [priority] - The priority level of the event listener. Listeners with higher priority will be executed before listeners with lower priority. Listeners with same priority level will be executed at the same order as they were added (default = 0)
  25395. * @param {...any} [args=(none)] - Additional arguments to pass to the callback (listener) function. They will be appended after any arguments usually dispatched.
  25396. * @return {Phaser.SignalBinding} An Object representing the binding between the Signal and listener.
  25397. */
  25398. add: function (listener, listenerContext, priority) {
  25399. this.validateListener(listener, 'add');
  25400. var args = [];
  25401. if (arguments.length > 3)
  25402. {
  25403. for (var i = 3; i < arguments.length; i++)
  25404. {
  25405. args.push(arguments[i]);
  25406. }
  25407. }
  25408. return this._registerListener(listener, false, listenerContext, priority, args);
  25409. },
  25410. /**
  25411. * Add a one-time listener - the listener is automatically removed after the first execution.
  25412. *
  25413. * If there is as {@link Phaser.Signal#memorize memorized} event then it will be dispatched and
  25414. * the listener will be removed immediately.
  25415. *
  25416. * @method Phaser.Signal#addOnce
  25417. * @param {function} listener - The function to call when this Signal is dispatched.
  25418. * @param {object} [listenerContext] - The context under which the listener will be executed (i.e. the object that should represent the `this` variable).
  25419. * @param {number} [priority] - The priority level of the event listener. Listeners with higher priority will be executed before listeners with lower priority. Listeners with same priority level will be executed at the same order as they were added (default = 0)
  25420. * @param {...any} [args=(none)] - Additional arguments to pass to the callback (listener) function. They will be appended after any arguments usually dispatched.
  25421. * @return {Phaser.SignalBinding} An Object representing the binding between the Signal and listener.
  25422. */
  25423. addOnce: function (listener, listenerContext, priority) {
  25424. this.validateListener(listener, 'addOnce');
  25425. var args = [];
  25426. if (arguments.length > 3)
  25427. {
  25428. for (var i = 3; i < arguments.length; i++)
  25429. {
  25430. args.push(arguments[i]);
  25431. }
  25432. }
  25433. return this._registerListener(listener, true, listenerContext, priority, args);
  25434. },
  25435. /**
  25436. * Remove a single event listener.
  25437. *
  25438. * @method Phaser.Signal#remove
  25439. * @param {function} listener - Handler function that should be removed.
  25440. * @param {object} [context=null] - Execution context (since you can add the same handler multiple times if executing in a different context).
  25441. * @return {function} Listener handler function.
  25442. */
  25443. remove: function (listener, context) {
  25444. this.validateListener(listener, 'remove');
  25445. var i = this._indexOfListener(listener, context);
  25446. if (i !== -1)
  25447. {
  25448. this._bindings[i]._destroy(); //no reason to a Phaser.SignalBinding exist if it isn't attached to a signal
  25449. this._bindings.splice(i, 1);
  25450. }
  25451. return listener;
  25452. },
  25453. /**
  25454. * Remove all event listeners.
  25455. *
  25456. * @method Phaser.Signal#removeAll
  25457. * @param {object} [context=null] - If specified only listeners for the given context will be removed.
  25458. */
  25459. removeAll: function (context) {
  25460. if (context === undefined) { context = null; }
  25461. if (!this._bindings)
  25462. {
  25463. return;
  25464. }
  25465. var n = this._bindings.length;
  25466. while (n--)
  25467. {
  25468. if (context)
  25469. {
  25470. if (this._bindings[n].context === context)
  25471. {
  25472. this._bindings[n]._destroy();
  25473. this._bindings.splice(n, 1);
  25474. }
  25475. }
  25476. else
  25477. {
  25478. this._bindings[n]._destroy();
  25479. }
  25480. }
  25481. if (!context)
  25482. {
  25483. this._bindings.length = 0;
  25484. }
  25485. },
  25486. /**
  25487. * Gets the total number of listeners attached to this Signal.
  25488. *
  25489. * @method Phaser.Signal#getNumListeners
  25490. * @return {integer} Number of listeners attached to the Signal.
  25491. */
  25492. getNumListeners: function () {
  25493. return this._bindings ? this._bindings.length : 0;
  25494. },
  25495. /**
  25496. * Stop propagation of the event, blocking the dispatch to next listener on the queue.
  25497. *
  25498. * This should be called only during event dispatch as calling it before/after dispatch won't affect another broadcast.
  25499. * See {@link #active} to enable/disable the signal entirely.
  25500. *
  25501. * @method Phaser.Signal#halt
  25502. */
  25503. halt: function () {
  25504. this._shouldPropagate = false;
  25505. },
  25506. /**
  25507. * Dispatch / broadcast the event to all listeners.
  25508. *
  25509. * To create an instance-bound dispatch for this Signal, use {@link #boundDispatch}.
  25510. *
  25511. * @method Phaser.Signal#dispatch
  25512. * @param {any} [params] - Parameters that should be passed to each handler.
  25513. */
  25514. dispatch: function () {
  25515. if (!this.active || !this._bindings)
  25516. {
  25517. return;
  25518. }
  25519. var paramsArr = Array.prototype.slice.call(arguments);
  25520. var n = this._bindings.length;
  25521. var bindings;
  25522. if (this.memorize)
  25523. {
  25524. this._prevParams = paramsArr;
  25525. }
  25526. if (!n)
  25527. {
  25528. // Should come after memorize
  25529. return;
  25530. }
  25531. bindings = this._bindings.slice(); //clone array in case add/remove items during dispatch
  25532. this._shouldPropagate = true; //in case `halt` was called before dispatch or during the previous dispatch.
  25533. //execute all callbacks until end of the list or until a callback returns `false` or stops propagation
  25534. //reverse loop since listeners with higher priority will be added at the end of the list
  25535. do {
  25536. n--;
  25537. }
  25538. while (bindings[n] && this._shouldPropagate && bindings[n].execute(paramsArr) !== false);
  25539. },
  25540. /**
  25541. * Forget the currently {@link Phaser.Signal#memorize memorized} event, if any.
  25542. *
  25543. * @method Phaser.Signal#forget
  25544. */
  25545. forget: function() {
  25546. if (this._prevParams)
  25547. {
  25548. this._prevParams = null;
  25549. }
  25550. },
  25551. /**
  25552. * Dispose the signal - no more events can be dispatched.
  25553. *
  25554. * This removes all event listeners and clears references to external objects.
  25555. * Calling methods on a disposed objects results in undefined behavior.
  25556. *
  25557. * @method Phaser.Signal#dispose
  25558. */
  25559. dispose: function () {
  25560. this.removeAll();
  25561. this._bindings = null;
  25562. if (this._prevParams)
  25563. {
  25564. this._prevParams = null;
  25565. }
  25566. },
  25567. /**
  25568. * A string representation of the object.
  25569. *
  25570. * @method Phaser.Signal#toString
  25571. * @return {string} String representation of the object.
  25572. */
  25573. toString: function () {
  25574. return '[Phaser.Signal active:'+ this.active +' numListeners:'+ this.getNumListeners() +']';
  25575. }
  25576. };
  25577. /**
  25578. * Create a `dispatch` function that maintains a binding to the original Signal context.
  25579. *
  25580. * Use the resulting value if the dispatch function needs to be passed somewhere
  25581. * or called independently of the Signal object.
  25582. *
  25583. * @memberof Phaser.Signal
  25584. * @property {function} boundDispatch
  25585. */
  25586. Object.defineProperty(Phaser.Signal.prototype, "boundDispatch", {
  25587. get: function () {
  25588. var _this = this;
  25589. return this._boundDispatch || (this._boundDispatch = function () {
  25590. return _this.dispatch.apply(_this, arguments);
  25591. });
  25592. }
  25593. });
  25594. Phaser.Signal.prototype.constructor = Phaser.Signal;
  25595. /**
  25596. * @author Miller Medeiros http://millermedeiros.github.com/js-signals/
  25597. * @author Richard Davey <rich@photonstorm.com>
  25598. * @copyright 2016 Photon Storm Ltd.
  25599. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  25600. */
  25601. /**
  25602. * Object that represents a binding between a Signal and a listener function.
  25603. * This is an internal constructor and shouldn't be created directly.
  25604. * Inspired by Joa Ebert AS3 SignalBinding and Robert Penner's Slot classes.
  25605. *
  25606. * @class Phaser.SignalBinding
  25607. * @constructor
  25608. * @param {Phaser.Signal} signal - Reference to Signal object that listener is currently bound to.
  25609. * @param {function} listener - Handler function bound to the signal.
  25610. * @param {boolean} isOnce - If binding should be executed just once.
  25611. * @param {object} [listenerContext=null] - Context on which listener will be executed (object that should represent the `this` variable inside listener function).
  25612. * @param {number} [priority] - The priority level of the event listener. (default = 0).
  25613. * @param {...any} [args=(none)] - Additional arguments to pass to the callback (listener) function. They will be appended after any arguments usually dispatched.
  25614. */
  25615. Phaser.SignalBinding = function (signal, listener, isOnce, listenerContext, priority, args) {
  25616. /**
  25617. * @property {Phaser.Game} _listener - Handler function bound to the signal.
  25618. * @private
  25619. */
  25620. this._listener = listener;
  25621. if (isOnce)
  25622. {
  25623. this._isOnce = true;
  25624. }
  25625. if (listenerContext != null) /* not null/undefined */
  25626. {
  25627. this.context = listenerContext;
  25628. }
  25629. /**
  25630. * @property {Phaser.Signal} _signal - Reference to Signal object that listener is currently bound to.
  25631. * @private
  25632. */
  25633. this._signal = signal;
  25634. if (priority)
  25635. {
  25636. this._priority = priority;
  25637. }
  25638. if (args && args.length)
  25639. {
  25640. this._args = args;
  25641. }
  25642. };
  25643. Phaser.SignalBinding.prototype = {
  25644. /**
  25645. * @property {?object} context - Context on which listener will be executed (object that should represent the `this` variable inside listener function).
  25646. */
  25647. context: null,
  25648. /**
  25649. * @property {boolean} _isOnce - If binding should be executed just once.
  25650. * @private
  25651. */
  25652. _isOnce: false,
  25653. /**
  25654. * @property {number} _priority - Listener priority.
  25655. * @private
  25656. */
  25657. _priority: 0,
  25658. /**
  25659. * @property {array} _args - Listener arguments.
  25660. * @private
  25661. */
  25662. _args: null,
  25663. /**
  25664. * @property {number} callCount - The number of times the handler function has been called.
  25665. */
  25666. callCount: 0,
  25667. /**
  25668. * If binding is active and should be executed.
  25669. * @property {boolean} active
  25670. * @default
  25671. */
  25672. active: true,
  25673. /**
  25674. * Default parameters passed to listener during `Signal.dispatch` and `SignalBinding.execute` (curried parameters).
  25675. * @property {array|null} params
  25676. * @default
  25677. */
  25678. params: null,
  25679. /**
  25680. * Call listener passing arbitrary parameters.
  25681. * If binding was added using `Signal.addOnce()` it will be automatically removed from signal dispatch queue, this method is used internally for the signal dispatch.
  25682. * @method Phaser.SignalBinding#execute
  25683. * @param {any[]} [paramsArr] - Array of parameters that should be passed to the listener.
  25684. * @return {any} Value returned by the listener.
  25685. */
  25686. execute: function(paramsArr) {
  25687. var handlerReturn, params;
  25688. if (this.active && !!this._listener)
  25689. {
  25690. params = this.params ? this.params.concat(paramsArr) : paramsArr;
  25691. if (this._args)
  25692. {
  25693. params = params.concat(this._args);
  25694. }
  25695. handlerReturn = this._listener.apply(this.context, params);
  25696. this.callCount++;
  25697. if (this._isOnce)
  25698. {
  25699. this.detach();
  25700. }
  25701. }
  25702. return handlerReturn;
  25703. },
  25704. /**
  25705. * Detach binding from signal.
  25706. * alias to: @see mySignal.remove(myBinding.getListener());
  25707. * @method Phaser.SignalBinding#detach
  25708. * @return {function|null} Handler function bound to the signal or `null` if binding was previously detached.
  25709. */
  25710. detach: function () {
  25711. return this.isBound() ? this._signal.remove(this._listener, this.context) : null;
  25712. },
  25713. /**
  25714. * @method Phaser.SignalBinding#isBound
  25715. * @return {boolean} True if binding is still bound to the signal and has a listener.
  25716. */
  25717. isBound: function () {
  25718. return (!!this._signal && !!this._listener);
  25719. },
  25720. /**
  25721. * @method Phaser.SignalBinding#isOnce
  25722. * @return {boolean} If SignalBinding will only be executed once.
  25723. */
  25724. isOnce: function () {
  25725. return this._isOnce;
  25726. },
  25727. /**
  25728. * @method Phaser.SignalBinding#getListener
  25729. * @return {function} Handler function bound to the signal.
  25730. */
  25731. getListener: function () {
  25732. return this._listener;
  25733. },
  25734. /**
  25735. * @method Phaser.SignalBinding#getSignal
  25736. * @return {Phaser.Signal} Signal that listener is currently bound to.
  25737. */
  25738. getSignal: function () {
  25739. return this._signal;
  25740. },
  25741. /**
  25742. * Delete instance properties
  25743. * @method Phaser.SignalBinding#_destroy
  25744. * @private
  25745. */
  25746. _destroy: function () {
  25747. delete this._signal;
  25748. delete this._listener;
  25749. delete this.context;
  25750. },
  25751. /**
  25752. * @method Phaser.SignalBinding#toString
  25753. * @return {string} String representation of the object.
  25754. */
  25755. toString: function () {
  25756. return '[Phaser.SignalBinding isOnce:' + this._isOnce +', isBound:'+ this.isBound() +', active:' + this.active + ']';
  25757. }
  25758. };
  25759. Phaser.SignalBinding.prototype.constructor = Phaser.SignalBinding;
  25760. /**
  25761. * @author Richard Davey <rich@photonstorm.com>
  25762. * @copyright 2016 Photon Storm Ltd.
  25763. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  25764. */
  25765. /**
  25766. * This is a base Filter class to use for any Phaser filter development.
  25767. *
  25768. * The vast majority of filters (including all of those that ship with Phaser) use fragment shaders, and
  25769. * therefore only work in WebGL and are not supported by Canvas at all.
  25770. *
  25771. * @class Phaser.Filter
  25772. * @constructor
  25773. * @param {Phaser.Game} game - A reference to the currently running game.
  25774. * @param {object} uniforms - Uniform mappings object
  25775. * @param {Array|string} fragmentSrc - The fragment shader code. Either an array, one element per line of code, or a string.
  25776. */
  25777. Phaser.Filter = function (game, uniforms, fragmentSrc) {
  25778. /**
  25779. * @property {Phaser.Game} game - A reference to the currently running game.
  25780. */
  25781. this.game = game;
  25782. /**
  25783. * @property {number} type - The const type of this object, either Phaser.WEBGL_FILTER or Phaser.CANVAS_FILTER.
  25784. * @default
  25785. */
  25786. this.type = Phaser.WEBGL_FILTER;
  25787. /**
  25788. * An array of passes - some filters contain a few steps this array simply stores the steps in a linear fashion.
  25789. * For example the blur filter has two passes blurX and blurY.
  25790. * @property {array} passes - An array of filter objects.
  25791. * @private
  25792. */
  25793. this.passes = [this];
  25794. /**
  25795. * @property {array} shaders - Array an array of shaders.
  25796. * @private
  25797. */
  25798. this.shaders = [];
  25799. /**
  25800. * @property {boolean} dirty - Internal PIXI var.
  25801. * @default
  25802. */
  25803. this.dirty = true;
  25804. /**
  25805. * @property {number} padding - Internal PIXI var.
  25806. * @default
  25807. */
  25808. this.padding = 0;
  25809. /**
  25810. * @property {Phaser.Point} prevPoint - The previous position of the pointer (we don't update the uniform if the same)
  25811. */
  25812. this.prevPoint = new Phaser.Point();
  25813. /*
  25814. * The supported types are: 1f, 1fv, 1i, 2f, 2fv, 2i, 2iv, 3f, 3fv, 3i, 3iv, 4f, 4fv, 4i, 4iv, mat2, mat3, mat4 and sampler2D.
  25815. */
  25816. var d = new Date();
  25817. /**
  25818. * @property {object} uniforms - Default uniform mappings. Compatible with ShaderToy and GLSLSandbox.
  25819. */
  25820. this.uniforms = {
  25821. resolution: { type: '2f', value: { x: 256, y: 256 }},
  25822. time: { type: '1f', value: 0 },
  25823. mouse: { type: '2f', value: { x: 0.0, y: 0.0 } },
  25824. date: { type: '4fv', value: [ d.getFullYear(), d.getMonth(), d.getDate(), d.getHours() *60 * 60 + d.getMinutes() * 60 + d.getSeconds() ] },
  25825. sampleRate: { type: '1f', value: 44100.0 },
  25826. iChannel0: { type: 'sampler2D', value: null, textureData: { repeat: true } },
  25827. iChannel1: { type: 'sampler2D', value: null, textureData: { repeat: true } },
  25828. iChannel2: { type: 'sampler2D', value: null, textureData: { repeat: true } },
  25829. iChannel3: { type: 'sampler2D', value: null, textureData: { repeat: true } }
  25830. };
  25831. // Copy over/replace any passed in the constructor
  25832. if (uniforms)
  25833. {
  25834. for (var key in uniforms)
  25835. {
  25836. this.uniforms[key] = uniforms[key];
  25837. }
  25838. }
  25839. /**
  25840. * @property {array|string} fragmentSrc - The fragment shader code.
  25841. */
  25842. this.fragmentSrc = fragmentSrc || '';
  25843. };
  25844. Phaser.Filter.prototype = {
  25845. /**
  25846. * Should be over-ridden.
  25847. * @method Phaser.Filter#init
  25848. */
  25849. init: function () {
  25850. // This should be over-ridden. Will receive a variable number of arguments.
  25851. },
  25852. /**
  25853. * Set the resolution uniforms on the filter.
  25854. * @method Phaser.Filter#setResolution
  25855. * @param {number} width - The width of the display.
  25856. * @param {number} height - The height of the display.
  25857. */
  25858. setResolution: function (width, height) {
  25859. this.uniforms.resolution.value.x = width;
  25860. this.uniforms.resolution.value.y = height;
  25861. },
  25862. /**
  25863. * Updates the filter.
  25864. * @method Phaser.Filter#update
  25865. * @param {Phaser.Pointer} [pointer] - A Pointer object to use for the filter. The coordinates are mapped to the mouse uniform.
  25866. */
  25867. update: function (pointer) {
  25868. if (typeof pointer !== 'undefined')
  25869. {
  25870. var x = pointer.x / this.game.width;
  25871. var y = 1 - pointer.y / this.game.height;
  25872. if (x !== this.prevPoint.x || y !== this.prevPoint.y)
  25873. {
  25874. this.uniforms.mouse.value.x = x.toFixed(2);
  25875. this.uniforms.mouse.value.y = y.toFixed(2);
  25876. this.prevPoint.set(x, y);
  25877. }
  25878. }
  25879. this.uniforms.time.value = this.game.time.totalElapsedSeconds();
  25880. },
  25881. /**
  25882. * Creates a new Phaser.Image object using a blank texture and assigns
  25883. * this Filter to it. The image is then added to the world.
  25884. *
  25885. * If you don't provide width and height values then Filter.width and Filter.height are used.
  25886. *
  25887. * If you do provide width and height values then this filter will be resized to match those
  25888. * values.
  25889. *
  25890. * @method Phaser.Filter#addToWorld
  25891. * @param {number} [x=0] - The x coordinate to place the Image at.
  25892. * @param {number} [y=0] - The y coordinate to place the Image at.
  25893. * @param {number} [width] - The width of the Image. If not specified (or null) it will use Filter.width. If specified Filter.width will be set to this value.
  25894. * @param {number} [height] - The height of the Image. If not specified (or null) it will use Filter.height. If specified Filter.height will be set to this value.
  25895. * @param {number} [anchorX=0] - Set the x anchor point of the Image. A value between 0 and 1, where 0 is the top-left and 1 is bottom-right.
  25896. * @param {number} [anchorY=0] - Set the y anchor point of the Image. A value between 0 and 1, where 0 is the top-left and 1 is bottom-right.
  25897. * @return {Phaser.Image} The newly added Image object.
  25898. */
  25899. addToWorld: function (x, y, width, height, anchorX, anchorY) {
  25900. if (anchorX === undefined) { anchorX = 0; }
  25901. if (anchorY === undefined) { anchorY = 0; }
  25902. if (width !== undefined && width !== null)
  25903. {
  25904. this.width = width;
  25905. }
  25906. else
  25907. {
  25908. width = this.width;
  25909. }
  25910. if (height !== undefined && height !== null)
  25911. {
  25912. this.height = height;
  25913. }
  25914. else
  25915. {
  25916. height = this.height;
  25917. }
  25918. var image = this.game.add.image(x, y, '__default');
  25919. image.width = width;
  25920. image.height = height;
  25921. image.anchor.set(anchorX, anchorY);
  25922. image.filters = [ this ];
  25923. return image;
  25924. },
  25925. /**
  25926. * Clear down this Filter and null out references
  25927. * @method Phaser.Filter#destroy
  25928. */
  25929. destroy: function () {
  25930. this.game = null;
  25931. }
  25932. };
  25933. Phaser.Filter.prototype.constructor = Phaser.Filter;
  25934. /**
  25935. * @name Phaser.Filter#width
  25936. * @property {number} width - The width (resolution uniform)
  25937. */
  25938. Object.defineProperty(Phaser.Filter.prototype, 'width', {
  25939. get: function() {
  25940. return this.uniforms.resolution.value.x;
  25941. },
  25942. set: function(value) {
  25943. this.uniforms.resolution.value.x = value;
  25944. }
  25945. });
  25946. /**
  25947. * @name Phaser.Filter#height
  25948. * @property {number} height - The height (resolution uniform)
  25949. */
  25950. Object.defineProperty(Phaser.Filter.prototype, 'height', {
  25951. get: function() {
  25952. return this.uniforms.resolution.value.y;
  25953. },
  25954. set: function(value) {
  25955. this.uniforms.resolution.value.y = value;
  25956. }
  25957. });
  25958. /**
  25959. * @author Richard Davey <rich@photonstorm.com>
  25960. * @copyright 2016 Photon Storm Ltd.
  25961. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  25962. */
  25963. /**
  25964. * This is a base Plugin template to use for any Phaser plugin development.
  25965. *
  25966. * @class Phaser.Plugin
  25967. * @constructor
  25968. * @param {Phaser.Game} game - A reference to the currently running game.
  25969. * @param {any} parent - The object that owns this plugin, usually Phaser.PluginManager.
  25970. */
  25971. Phaser.Plugin = function (game, parent) {
  25972. if (parent === undefined) { parent = null; }
  25973. /**
  25974. * @property {Phaser.Game} game - A reference to the currently running game.
  25975. */
  25976. this.game = game;
  25977. /**
  25978. * @property {any} parent - The parent of this plugin. If added to the PluginManager the parent will be set to that, otherwise it will be null.
  25979. */
  25980. this.parent = parent;
  25981. /**
  25982. * @property {boolean} active - A Plugin with active=true has its preUpdate and update methods called by the parent, otherwise they are skipped.
  25983. * @default
  25984. */
  25985. this.active = false;
  25986. /**
  25987. * @property {boolean} visible - A Plugin with visible=true has its render and postRender methods called by the parent, otherwise they are skipped.
  25988. * @default
  25989. */
  25990. this.visible = false;
  25991. /**
  25992. * @property {boolean} hasPreUpdate - A flag to indicate if this plugin has a preUpdate method.
  25993. * @default
  25994. */
  25995. this.hasPreUpdate = false;
  25996. /**
  25997. * @property {boolean} hasUpdate - A flag to indicate if this plugin has an update method.
  25998. * @default
  25999. */
  26000. this.hasUpdate = false;
  26001. /**
  26002. * @property {boolean} hasPostUpdate - A flag to indicate if this plugin has a postUpdate method.
  26003. * @default
  26004. */
  26005. this.hasPostUpdate = false;
  26006. /**
  26007. * @property {boolean} hasRender - A flag to indicate if this plugin has a render method.
  26008. * @default
  26009. */
  26010. this.hasRender = false;
  26011. /**
  26012. * @property {boolean} hasPostRender - A flag to indicate if this plugin has a postRender method.
  26013. * @default
  26014. */
  26015. this.hasPostRender = false;
  26016. };
  26017. Phaser.Plugin.prototype = {
  26018. /**
  26019. * Pre-update is called at the very start of the update cycle, before any other subsystems have been updated (including Physics).
  26020. * It is only called if active is set to true.
  26021. * @method Phaser.Plugin#preUpdate
  26022. */
  26023. preUpdate: function () {
  26024. },
  26025. /**
  26026. * Update is called after all the core subsystems (Input, Tweens, Sound, etc) and the State have updated, but before the render.
  26027. * It is only called if active is set to true.
  26028. * @method Phaser.Plugin#update
  26029. */
  26030. update: function () {
  26031. },
  26032. /**
  26033. * Render is called right after the Game Renderer completes, but before the State.render.
  26034. * It is only called if visible is set to true.
  26035. * @method Phaser.Plugin#render
  26036. */
  26037. render: function () {
  26038. },
  26039. /**
  26040. * Post-render is called after the Game Renderer and State.render have run.
  26041. * It is only called if visible is set to true.
  26042. * @method Phaser.Plugin#postRender
  26043. */
  26044. postRender: function () {
  26045. },
  26046. /**
  26047. * Clear down this Plugin and null out references
  26048. * @method Phaser.Plugin#destroy
  26049. */
  26050. destroy: function () {
  26051. this.game = null;
  26052. this.parent = null;
  26053. this.active = false;
  26054. this.visible = false;
  26055. }
  26056. };
  26057. Phaser.Plugin.prototype.constructor = Phaser.Plugin;
  26058. /* jshint newcap: false */
  26059. /**
  26060. * @author Richard Davey <rich@photonstorm.com>
  26061. * @copyright 2016 Photon Storm Ltd.
  26062. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  26063. */
  26064. /**
  26065. * The Plugin Manager is responsible for the loading, running and unloading of Phaser Plugins.
  26066. *
  26067. * @class Phaser.PluginManager
  26068. * @constructor
  26069. * @param {Phaser.Game} game - A reference to the currently running game.
  26070. */
  26071. Phaser.PluginManager = function(game) {
  26072. /**
  26073. * @property {Phaser.Game} game - A reference to the currently running game.
  26074. */
  26075. this.game = game;
  26076. /**
  26077. * @property {Phaser.Plugin[]} plugins - An array of all the plugins being managed by this PluginManager.
  26078. */
  26079. this.plugins = [];
  26080. /**
  26081. * @property {number} _len - Internal cache var.
  26082. * @private
  26083. */
  26084. this._len = 0;
  26085. /**
  26086. * @property {number} _i - Internal cache var.
  26087. * @private
  26088. */
  26089. this._i = 0;
  26090. };
  26091. Phaser.PluginManager.prototype = {
  26092. /**
  26093. * Add a new Plugin into the PluginManager.
  26094. * The Plugin must have 2 properties: game and parent. Plugin.game is set to the game reference the PluginManager uses, and parent is set to the PluginManager.
  26095. *
  26096. * @method Phaser.PluginManager#add
  26097. * @param {object|Phaser.Plugin} plugin - The Plugin to add into the PluginManager. This can be a function or an existing object.
  26098. * @param {...*} parameter - Additional arguments that will be passed to the Plugin.init method.
  26099. * @return {Phaser.Plugin} The Plugin that was added to the manager.
  26100. */
  26101. add: function (plugin) {
  26102. var args = Array.prototype.slice.call(arguments, 1);
  26103. var result = false;
  26104. // Prototype?
  26105. if (typeof plugin === 'function')
  26106. {
  26107. plugin = new plugin(this.game, this);
  26108. }
  26109. else
  26110. {
  26111. plugin.game = this.game;
  26112. plugin.parent = this;
  26113. }
  26114. // Check for methods now to avoid having to do this every loop
  26115. if (typeof plugin['preUpdate'] === 'function')
  26116. {
  26117. plugin.hasPreUpdate = true;
  26118. result = true;
  26119. }
  26120. if (typeof plugin['update'] === 'function')
  26121. {
  26122. plugin.hasUpdate = true;
  26123. result = true;
  26124. }
  26125. if (typeof plugin['postUpdate'] === 'function')
  26126. {
  26127. plugin.hasPostUpdate = true;
  26128. result = true;
  26129. }
  26130. if (typeof plugin['render'] === 'function')
  26131. {
  26132. plugin.hasRender = true;
  26133. result = true;
  26134. }
  26135. if (typeof plugin['postRender'] === 'function')
  26136. {
  26137. plugin.hasPostRender = true;
  26138. result = true;
  26139. }
  26140. // The plugin must have at least one of the above functions to be added to the PluginManager.
  26141. if (result)
  26142. {
  26143. if (plugin.hasPreUpdate || plugin.hasUpdate || plugin.hasPostUpdate)
  26144. {
  26145. plugin.active = true;
  26146. }
  26147. if (plugin.hasRender || plugin.hasPostRender)
  26148. {
  26149. plugin.visible = true;
  26150. }
  26151. this._len = this.plugins.push(plugin);
  26152. // Allows plugins to run potentially destructive code outside of the constructor, and only if being added to the PluginManager
  26153. if (typeof plugin['init'] === 'function')
  26154. {
  26155. plugin.init.apply(plugin, args);
  26156. }
  26157. return plugin;
  26158. }
  26159. else
  26160. {
  26161. return null;
  26162. }
  26163. },
  26164. /**
  26165. * Remove a Plugin from the PluginManager. It calls Plugin.destroy on the plugin before removing it from the manager.
  26166. *
  26167. * @method Phaser.PluginManager#remove
  26168. * @param {Phaser.Plugin} plugin - The plugin to be removed.
  26169. * @param {boolean} [destroy=true] - Call destroy on the plugin that is removed?
  26170. */
  26171. remove: function (plugin, destroy) {
  26172. if (destroy === undefined) { destroy = true; }
  26173. this._i = this._len;
  26174. while (this._i--)
  26175. {
  26176. if (this.plugins[this._i] === plugin)
  26177. {
  26178. if (destroy)
  26179. {
  26180. plugin.destroy();
  26181. }
  26182. this.plugins.splice(this._i, 1);
  26183. this._len--;
  26184. return;
  26185. }
  26186. }
  26187. },
  26188. /**
  26189. * Remove all Plugins from the PluginManager. It calls Plugin.destroy on every plugin before removing it from the manager.
  26190. *
  26191. * @method Phaser.PluginManager#removeAll
  26192. */
  26193. removeAll: function() {
  26194. this._i = this._len;
  26195. while (this._i--)
  26196. {
  26197. this.plugins[this._i].destroy();
  26198. }
  26199. this.plugins.length = 0;
  26200. this._len = 0;
  26201. },
  26202. /**
  26203. * Pre-update is called at the very start of the update cycle, before any other subsystems have been updated (including Physics).
  26204. * It only calls plugins who have active=true.
  26205. *
  26206. * @method Phaser.PluginManager#preUpdate
  26207. */
  26208. preUpdate: function () {
  26209. this._i = this._len;
  26210. while (this._i--)
  26211. {
  26212. if (this.plugins[this._i].active && this.plugins[this._i].hasPreUpdate)
  26213. {
  26214. this.plugins[this._i].preUpdate();
  26215. }
  26216. }
  26217. },
  26218. /**
  26219. * Update is called after all the core subsystems (Input, Tweens, Sound, etc) and the State have updated, but before the render.
  26220. * It only calls plugins who have active=true.
  26221. *
  26222. * @method Phaser.PluginManager#update
  26223. */
  26224. update: function () {
  26225. this._i = this._len;
  26226. while (this._i--)
  26227. {
  26228. if (this.plugins[this._i].active && this.plugins[this._i].hasUpdate)
  26229. {
  26230. this.plugins[this._i].update();
  26231. }
  26232. }
  26233. },
  26234. /**
  26235. * PostUpdate is the last thing to be called before the world render.
  26236. * In particular, it is called after the world postUpdate, which means the camera has been adjusted.
  26237. * It only calls plugins who have active=true.
  26238. *
  26239. * @method Phaser.PluginManager#postUpdate
  26240. */
  26241. postUpdate: function () {
  26242. this._i = this._len;
  26243. while (this._i--)
  26244. {
  26245. if (this.plugins[this._i].active && this.plugins[this._i].hasPostUpdate)
  26246. {
  26247. this.plugins[this._i].postUpdate();
  26248. }
  26249. }
  26250. },
  26251. /**
  26252. * Render is called right after the Game Renderer completes, but before the State.render.
  26253. * It only calls plugins who have visible=true.
  26254. *
  26255. * @method Phaser.PluginManager#render
  26256. */
  26257. render: function () {
  26258. this._i = this._len;
  26259. while (this._i--)
  26260. {
  26261. if (this.plugins[this._i].visible && this.plugins[this._i].hasRender)
  26262. {
  26263. this.plugins[this._i].render();
  26264. }
  26265. }
  26266. },
  26267. /**
  26268. * Post-render is called after the Game Renderer and State.render have run.
  26269. * It only calls plugins who have visible=true.
  26270. *
  26271. * @method Phaser.PluginManager#postRender
  26272. */
  26273. postRender: function () {
  26274. this._i = this._len;
  26275. while (this._i--)
  26276. {
  26277. if (this.plugins[this._i].visible && this.plugins[this._i].hasPostRender)
  26278. {
  26279. this.plugins[this._i].postRender();
  26280. }
  26281. }
  26282. },
  26283. /**
  26284. * Clear down this PluginManager, calls destroy on every plugin and nulls out references.
  26285. *
  26286. * @method Phaser.PluginManager#destroy
  26287. */
  26288. destroy: function () {
  26289. this.removeAll();
  26290. this.game = null;
  26291. }
  26292. };
  26293. Phaser.PluginManager.prototype.constructor = Phaser.PluginManager;
  26294. /**
  26295. * @author Richard Davey <rich@photonstorm.com>
  26296. * @copyright 2016 Photon Storm Ltd.
  26297. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  26298. */
  26299. /**
  26300. * The Stage controls root level display objects upon which everything is displayed.
  26301. * It also handles browser visibility handling and the pausing due to loss of focus.
  26302. *
  26303. * @class Phaser.Stage
  26304. * @extends PIXI.DisplayObjectContainer
  26305. * @constructor
  26306. * @param {Phaser.Game} game - Game reference to the currently running game.
  26307. */
  26308. Phaser.Stage = function (game) {
  26309. /**
  26310. * @property {Phaser.Game} game - A reference to the currently running Game.
  26311. */
  26312. this.game = game;
  26313. PIXI.DisplayObjectContainer.call(this);
  26314. /**
  26315. * @property {string} name - The name of this object.
  26316. * @default
  26317. */
  26318. this.name = '_stage_root';
  26319. /**
  26320. * By default if the browser tab loses focus the game will pause.
  26321. * You can stop that behavior by setting this property to true.
  26322. * Note that the browser can still elect to pause your game if it wishes to do so,
  26323. * for example swapping to another browser tab. This will cause the RAF callback to halt,
  26324. * effectively pausing your game, even though no in-game pause event is triggered if you enable this property.
  26325. * @property {boolean} disableVisibilityChange
  26326. * @default
  26327. */
  26328. this.disableVisibilityChange = false;
  26329. /**
  26330. * @property {boolean} exists - If exists is true the Stage and all children are updated, otherwise it is skipped.
  26331. * @default
  26332. */
  26333. this.exists = true;
  26334. /**
  26335. * @property {PIXI.Matrix} worldTransform - Current transform of the object based on world (parent) factors
  26336. * @private
  26337. * @readOnly
  26338. */
  26339. this.worldTransform = new PIXI.Matrix();
  26340. /**
  26341. * @property {Phaser.Stage} stage - The stage reference (the Stage is its own stage)
  26342. * @private
  26343. * @readOnly
  26344. */
  26345. this.stage = this;
  26346. /**
  26347. * @property {number} currentRenderOrderID - Reset each frame, keeps a count of the total number of objects updated.
  26348. */
  26349. this.currentRenderOrderID = 0;
  26350. /**
  26351. * @property {string} hiddenVar - The page visibility API event name.
  26352. * @private
  26353. */
  26354. this._hiddenVar = 'hidden';
  26355. /**
  26356. * @property {function} _onChange - The blur/focus event handler.
  26357. * @private
  26358. */
  26359. this._onChange = null;
  26360. /**
  26361. * @property {number} _bgColor - Stage background color object. Populated by setBackgroundColor.
  26362. * @private
  26363. */
  26364. this._bgColor = { r: 0, g: 0, b: 0, a: 0, color: 0, rgba: '#000000' };
  26365. if (!this.game.transparent)
  26366. {
  26367. // transparent = 0,0,0,0 - otherwise r,g,b,1
  26368. this._bgColor.a = 1;
  26369. }
  26370. if (game.config)
  26371. {
  26372. this.parseConfig(game.config);
  26373. }
  26374. };
  26375. Phaser.Stage.prototype = Object.create(PIXI.DisplayObjectContainer.prototype);
  26376. Phaser.Stage.prototype.constructor = Phaser.Stage;
  26377. /**
  26378. * Parses a Game configuration object.
  26379. *
  26380. * @method Phaser.Stage#parseConfig
  26381. * @protected
  26382. * @param {object} config -The configuration object to parse.
  26383. */
  26384. Phaser.Stage.prototype.parseConfig = function (config) {
  26385. if (config['disableVisibilityChange'])
  26386. {
  26387. this.disableVisibilityChange = config['disableVisibilityChange'];
  26388. }
  26389. if (config['backgroundColor'])
  26390. {
  26391. this.setBackgroundColor(config['backgroundColor']);
  26392. }
  26393. };
  26394. /**
  26395. * Initialises the stage and adds the event listeners.
  26396. * @method Phaser.Stage#boot
  26397. * @private
  26398. */
  26399. Phaser.Stage.prototype.boot = function () {
  26400. Phaser.DOM.getOffset(this.game.canvas, this.offset);
  26401. Phaser.Canvas.setUserSelect(this.game.canvas, 'none');
  26402. Phaser.Canvas.setTouchAction(this.game.canvas, 'none');
  26403. this.checkVisibility();
  26404. };
  26405. /**
  26406. * This is called automatically after the plugins preUpdate and before the State.update.
  26407. * Most objects have preUpdate methods and it's where initial movement and positioning is done.
  26408. *
  26409. * @method Phaser.Stage#preUpdate
  26410. */
  26411. Phaser.Stage.prototype.preUpdate = function () {
  26412. this.currentRenderOrderID = 0;
  26413. // This can't loop in reverse, we need the renderOrderID to be in sequence
  26414. for (var i = 0; i < this.children.length; i++)
  26415. {
  26416. this.children[i].preUpdate();
  26417. }
  26418. };
  26419. /**
  26420. * This is called automatically after the State.update, but before particles or plugins update.
  26421. *
  26422. * @method Phaser.Stage#update
  26423. */
  26424. Phaser.Stage.prototype.update = function () {
  26425. // Goes in reverse, because it's highly likely the child will destroy itself in `update`
  26426. var i = this.children.length;
  26427. while (i--)
  26428. {
  26429. this.children[i].update();
  26430. }
  26431. };
  26432. /**
  26433. * This is called automatically before the renderer runs and after the plugins have updated.
  26434. * In postUpdate this is where all the final physics calculations and object positioning happens.
  26435. * The objects are processed in the order of the display list.
  26436. *
  26437. * @method Phaser.Stage#postUpdate
  26438. */
  26439. Phaser.Stage.prototype.postUpdate = function () {
  26440. // Apply the camera shake, fade, bounds, etc
  26441. this.game.camera.update();
  26442. // Camera target first?
  26443. if (this.game.camera.target)
  26444. {
  26445. this.game.camera.target.postUpdate();
  26446. this.updateTransform();
  26447. this.game.camera.updateTarget();
  26448. }
  26449. for (var i = 0; i < this.children.length; i++)
  26450. {
  26451. this.children[i].postUpdate();
  26452. }
  26453. this.updateTransform();
  26454. };
  26455. /**
  26456. * Updates the transforms for all objects on the display list.
  26457. * This overrides the Pixi default as we don't need the interactionManager, but do need the game property check.
  26458. *
  26459. * @method Phaser.Stage#updateTransform
  26460. */
  26461. Phaser.Stage.prototype.updateTransform = function () {
  26462. this.worldAlpha = 1;
  26463. for (var i = 0; i < this.children.length; i++)
  26464. {
  26465. this.children[i].updateTransform();
  26466. }
  26467. };
  26468. /**
  26469. * Starts a page visibility event listener running, or window.onpagehide/onpageshow if not supported by the browser.
  26470. * Also listens for window.onblur and window.onfocus.
  26471. *
  26472. * @method Phaser.Stage#checkVisibility
  26473. */
  26474. Phaser.Stage.prototype.checkVisibility = function () {
  26475. if (document.hidden !== undefined)
  26476. {
  26477. this._hiddenVar = 'visibilitychange';
  26478. }
  26479. else if (document.webkitHidden !== undefined)
  26480. {
  26481. this._hiddenVar = 'webkitvisibilitychange';
  26482. }
  26483. else if (document.mozHidden !== undefined)
  26484. {
  26485. this._hiddenVar = 'mozvisibilitychange';
  26486. }
  26487. else if (document.msHidden !== undefined)
  26488. {
  26489. this._hiddenVar = 'msvisibilitychange';
  26490. }
  26491. else
  26492. {
  26493. this._hiddenVar = null;
  26494. }
  26495. var _this = this;
  26496. this._onChange = function (event) {
  26497. return _this.visibilityChange(event);
  26498. };
  26499. // Does browser support it? If not (like in IE9 or old Android) we need to fall back to blur/focus
  26500. if (this._hiddenVar)
  26501. {
  26502. document.addEventListener(this._hiddenVar, this._onChange, false);
  26503. }
  26504. window.onblur = this._onChange;
  26505. window.onfocus = this._onChange;
  26506. window.onpagehide = this._onChange;
  26507. window.onpageshow = this._onChange;
  26508. if (this.game.device.cocoonJSApp)
  26509. {
  26510. CocoonJS.App.onSuspended.addEventListener(function () {
  26511. Phaser.Stage.prototype.visibilityChange.call(_this, { type: "pause" });
  26512. });
  26513. CocoonJS.App.onActivated.addEventListener(function () {
  26514. Phaser.Stage.prototype.visibilityChange.call(_this, { type: "resume" });
  26515. });
  26516. }
  26517. };
  26518. /**
  26519. * This method is called when the document visibility is changed.
  26520. *
  26521. * @method Phaser.Stage#visibilityChange
  26522. * @param {Event} event - Its type will be used to decide whether the game should be paused or not.
  26523. */
  26524. Phaser.Stage.prototype.visibilityChange = function (event) {
  26525. if (event.type === 'pagehide' || event.type === 'blur' || event.type === 'pageshow' || event.type === 'focus')
  26526. {
  26527. if (event.type === 'pagehide' || event.type === 'blur')
  26528. {
  26529. this.game.focusLoss(event);
  26530. }
  26531. else if (event.type === 'pageshow' || event.type === 'focus')
  26532. {
  26533. this.game.focusGain(event);
  26534. }
  26535. return;
  26536. }
  26537. if (this.disableVisibilityChange)
  26538. {
  26539. return;
  26540. }
  26541. if (document.hidden || document.mozHidden || document.msHidden || document.webkitHidden || event.type === "pause")
  26542. {
  26543. this.game.gamePaused(event);
  26544. }
  26545. else
  26546. {
  26547. this.game.gameResumed(event);
  26548. }
  26549. };
  26550. /**
  26551. * Sets the background color for the Stage.
  26552. *
  26553. * The color can be given as a hex string (`'#RRGGBB'`), a CSS color string (`'rgb(r,g,b)'`), or a numeric value (`0xRRGGBB`).
  26554. *
  26555. * An alpha channel is _not_ supported and will be ignored.
  26556. *
  26557. * If you've set your game to be transparent then calls to setBackgroundColor are ignored.
  26558. *
  26559. * @method Phaser.Stage#setBackgroundColor
  26560. * @param {number|string} color - The color of the background.
  26561. */
  26562. Phaser.Stage.prototype.setBackgroundColor = function (color) {
  26563. if (this.game.transparent) { return; }
  26564. Phaser.Color.valueToColor(color, this._bgColor);
  26565. Phaser.Color.updateColor(this._bgColor);
  26566. // For gl.clearColor (canvas uses _bgColor.rgba)
  26567. this._bgColor.r /= 255;
  26568. this._bgColor.g /= 255;
  26569. this._bgColor.b /= 255;
  26570. this._bgColor.a = 1;
  26571. };
  26572. /**
  26573. * Destroys the Stage and removes event listeners.
  26574. *
  26575. * @method Phaser.Stage#destroy
  26576. */
  26577. Phaser.Stage.prototype.destroy = function () {
  26578. if (this._hiddenVar)
  26579. {
  26580. document.removeEventListener(this._hiddenVar, this._onChange, false);
  26581. }
  26582. window.onpagehide = null;
  26583. window.onpageshow = null;
  26584. window.onblur = null;
  26585. window.onfocus = null;
  26586. };
  26587. /**
  26588. * @name Phaser.Stage#backgroundColor
  26589. * @property {number|string} backgroundColor - Gets and sets the background color of the stage. The color can be given as a number: 0xff0000 or a hex string: '#ff0000'
  26590. */
  26591. Object.defineProperty(Phaser.Stage.prototype, "backgroundColor", {
  26592. get: function () {
  26593. return this._bgColor.color;
  26594. },
  26595. set: function (color) {
  26596. this.setBackgroundColor(color);
  26597. }
  26598. });
  26599. /**
  26600. * Enable or disable texture smoothing for all objects on this Stage. Only works for bitmap/image textures. Smoothing is enabled by default.
  26601. *
  26602. * @name Phaser.Stage#smoothed
  26603. * @property {boolean} smoothed - Set to true to smooth all sprites rendered on this Stage, or false to disable smoothing (great for pixel art)
  26604. */
  26605. Object.defineProperty(Phaser.Stage.prototype, "smoothed", {
  26606. get: function () {
  26607. return PIXI.scaleModes.DEFAULT === PIXI.scaleModes.LINEAR;
  26608. },
  26609. set: function (value) {
  26610. if (value)
  26611. {
  26612. PIXI.scaleModes.DEFAULT = PIXI.scaleModes.LINEAR;
  26613. }
  26614. else
  26615. {
  26616. PIXI.scaleModes.DEFAULT = PIXI.scaleModes.NEAREST;
  26617. }
  26618. }
  26619. });
  26620. /**
  26621. * @author Richard Davey <rich@photonstorm.com>
  26622. * @copyright 2016 Photon Storm Ltd.
  26623. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  26624. */
  26625. /**
  26626. * A Group is a container for {@link DisplayObject display objects} including {@link Phaser.Sprite Sprites} and {@link Phaser.Image Images}.
  26627. *
  26628. * Groups form the logical tree structure of the display/scene graph where local transformations are applied to children.
  26629. * For instance, all children are also moved/rotated/scaled when the group is moved/rotated/scaled.
  26630. *
  26631. * In addition, Groups provides support for fast pooling and object recycling.
  26632. *
  26633. * Groups are also display objects and can be nested as children within other Groups.
  26634. *
  26635. * @class Phaser.Group
  26636. * @extends PIXI.DisplayObjectContainer
  26637. * @param {Phaser.Game} game - A reference to the currently running game.
  26638. * @param {DisplayObject|null} [parent=(game world)] - The parent Group (or other {@link DisplayObject}) that this group will be added to.
  26639. * If undefined/unspecified the Group will be added to the {@link Phaser.Game#world Game World}; if null the Group will not be added to any parent.
  26640. * @param {string} [name='group'] - A name for this group. Not used internally but useful for debugging.
  26641. * @param {boolean} [addToStage=false] - If true this group will be added directly to the Game.Stage instead of Game.World.
  26642. * @param {boolean} [enableBody=false] - If true all Sprites created with {@link #create} or {@link #createMulitple} will have a physics body created on them. Change the body type with {@link #physicsBodyType}.
  26643. * @param {integer} [physicsBodyType=0] - The physics body type to use when physics bodies are automatically added. See {@link #physicsBodyType} for values.
  26644. */
  26645. Phaser.Group = function (game, parent, name, addToStage, enableBody, physicsBodyType) {
  26646. if (addToStage === undefined) { addToStage = false; }
  26647. if (enableBody === undefined) { enableBody = false; }
  26648. if (physicsBodyType === undefined) { physicsBodyType = Phaser.Physics.ARCADE; }
  26649. /**
  26650. * A reference to the currently running Game.
  26651. * @property {Phaser.Game} game
  26652. * @protected
  26653. */
  26654. this.game = game;
  26655. if (parent === undefined)
  26656. {
  26657. parent = game.world;
  26658. }
  26659. /**
  26660. * A name for this group. Not used internally but useful for debugging.
  26661. * @property {string} name
  26662. */
  26663. this.name = name || 'group';
  26664. /**
  26665. * The z-depth value of this object within its parent container/Group - the World is a Group as well.
  26666. * This value must be unique for each child in a Group.
  26667. * @property {integer} z
  26668. * @readOnly
  26669. */
  26670. this.z = 0;
  26671. PIXI.DisplayObjectContainer.call(this);
  26672. if (addToStage)
  26673. {
  26674. this.game.stage.addChild(this);
  26675. this.z = this.game.stage.children.length;
  26676. }
  26677. else
  26678. {
  26679. if (parent)
  26680. {
  26681. parent.addChild(this);
  26682. this.z = parent.children.length;
  26683. }
  26684. }
  26685. /**
  26686. * Internal Phaser Type value.
  26687. * @property {integer} type
  26688. * @protected
  26689. */
  26690. this.type = Phaser.GROUP;
  26691. /**
  26692. * @property {number} physicsType - The const physics body type of this object.
  26693. * @readonly
  26694. */
  26695. this.physicsType = Phaser.GROUP;
  26696. /**
  26697. * The alive property is useful for Groups that are children of other Groups and need to be included/excluded in checks like forEachAlive.
  26698. * @property {boolean} alive
  26699. * @default
  26700. */
  26701. this.alive = true;
  26702. /**
  26703. * If exists is true the group is updated, otherwise it is skipped.
  26704. * @property {boolean} exists
  26705. * @default
  26706. */
  26707. this.exists = true;
  26708. /**
  26709. * A group with `ignoreDestroy` set to `true` ignores all calls to its `destroy` method.
  26710. * @property {boolean} ignoreDestroy
  26711. * @default
  26712. */
  26713. this.ignoreDestroy = false;
  26714. /**
  26715. * A Group is that has `pendingDestroy` set to `true` is flagged to have its destroy method
  26716. * called on the next logic update.
  26717. * You can set it directly to flag the Group to be destroyed on its next update.
  26718. *
  26719. * This is extremely useful if you wish to destroy a Group from within one of its own callbacks
  26720. * or a callback of one of its children.
  26721. *
  26722. * @property {boolean} pendingDestroy
  26723. */
  26724. this.pendingDestroy = false;
  26725. /**
  26726. * The type of objects that will be created when using {@link #create} or {@link #createMultiple}.
  26727. *
  26728. * Any object may be used but it should extend either Sprite or Image and accept the same constructor arguments:
  26729. * when a new object is created it is passed the following parameters to its constructor: `(game, x, y, key, frame)`.
  26730. *
  26731. * @property {object} classType
  26732. * @default {@link Phaser.Sprite}
  26733. */
  26734. this.classType = Phaser.Sprite;
  26735. /**
  26736. * The current display object that the group cursor is pointing to, if any. (Can be set manually.)
  26737. *
  26738. * The cursor is a way to iterate through the children in a Group using {@link #next} and {@link #previous}.
  26739. * @property {?DisplayObject} cursor
  26740. */
  26741. this.cursor = null;
  26742. /**
  26743. * A Group with `inputEnableChildren` set to `true` will automatically call `inputEnabled = true`
  26744. * on any children _added_ to, or _created by_, this Group.
  26745. *
  26746. * If there are children already in the Group at the time you set this property, they are not changed.
  26747. *
  26748. * @property {boolean} inputEnableChildren
  26749. * @default
  26750. */
  26751. this.inputEnableChildren = false;
  26752. /**
  26753. * This Signal is dispatched whenever a child of this Group emits an onInputDown signal as a result
  26754. * of having been interacted with by a Pointer. You can bind functions to this Signal instead of to
  26755. * every child Sprite.
  26756. *
  26757. * This Signal is sent 2 arguments: A reference to the Sprite that triggered the signal, and
  26758. * a reference to the Pointer that caused it.
  26759. *
  26760. * @property {Phaser.Signal} onChildInputDown
  26761. */
  26762. this.onChildInputDown = new Phaser.Signal();
  26763. /**
  26764. * This Signal is dispatched whenever a child of this Group emits an onInputUp signal as a result
  26765. * of having been interacted with by a Pointer. You can bind functions to this Signal instead of to
  26766. * every child Sprite.
  26767. *
  26768. * This Signal is sent 3 arguments: A reference to the Sprite that triggered the signal,
  26769. * a reference to the Pointer that caused it, and a boolean value `isOver` that tells you if the Pointer
  26770. * is still over the Sprite or not.
  26771. *
  26772. * @property {Phaser.Signal} onChildInputUp
  26773. */
  26774. this.onChildInputUp = new Phaser.Signal();
  26775. /**
  26776. * This Signal is dispatched whenever a child of this Group emits an onInputOver signal as a result
  26777. * of having been interacted with by a Pointer. You can bind functions to this Signal instead of to
  26778. * every child Sprite.
  26779. *
  26780. * This Signal is sent 2 arguments: A reference to the Sprite that triggered the signal, and
  26781. * a reference to the Pointer that caused it.
  26782. *
  26783. * @property {Phaser.Signal} onChildInputOver
  26784. */
  26785. this.onChildInputOver = new Phaser.Signal();
  26786. /**
  26787. * This Signal is dispatched whenever a child of this Group emits an onInputOut signal as a result
  26788. * of having been interacted with by a Pointer. You can bind functions to this Signal instead of to
  26789. * every child Sprite.
  26790. *
  26791. * This Signal is sent 2 arguments: A reference to the Sprite that triggered the signal, and
  26792. * a reference to the Pointer that caused it.
  26793. *
  26794. * @property {Phaser.Signal} onChildInputOut
  26795. */
  26796. this.onChildInputOut = new Phaser.Signal();
  26797. /**
  26798. * If true all Sprites created by, or added to this group, will have a physics body enabled on them.
  26799. *
  26800. * If there are children already in the Group at the time you set this property, they are not changed.
  26801. *
  26802. * The default body type is controlled with {@link #physicsBodyType}.
  26803. * @property {boolean} enableBody
  26804. */
  26805. this.enableBody = enableBody;
  26806. /**
  26807. * If true when a physics body is created (via {@link #enableBody}) it will create a physics debug object as well.
  26808. *
  26809. * This only works for P2 bodies.
  26810. * @property {boolean} enableBodyDebug
  26811. * @default
  26812. */
  26813. this.enableBodyDebug = false;
  26814. /**
  26815. * If {@link #enableBody} is true this is the type of physics body that is created on new Sprites.
  26816. *
  26817. * The valid values are {@link Phaser.Physics.ARCADE}, {@link Phaser.Physics.P2JS}, {@link Phaser.Physics.NINJA}, etc.
  26818. * @property {integer} physicsBodyType
  26819. */
  26820. this.physicsBodyType = physicsBodyType;
  26821. /**
  26822. * If this Group contains Arcade Physics Sprites you can set a custom sort direction via this property.
  26823. *
  26824. * It should be set to one of the Phaser.Physics.Arcade sort direction constants:
  26825. *
  26826. * Phaser.Physics.Arcade.SORT_NONE
  26827. * Phaser.Physics.Arcade.LEFT_RIGHT
  26828. * Phaser.Physics.Arcade.RIGHT_LEFT
  26829. * Phaser.Physics.Arcade.TOP_BOTTOM
  26830. * Phaser.Physics.Arcade.BOTTOM_TOP
  26831. *
  26832. * If set to `null` the Group will use whatever Phaser.Physics.Arcade.sortDirection is set to. This is the default behavior.
  26833. *
  26834. * @property {integer} physicsSortDirection
  26835. * @default
  26836. */
  26837. this.physicsSortDirection = null;
  26838. /**
  26839. * This signal is dispatched when the group is destroyed.
  26840. * @property {Phaser.Signal} onDestroy
  26841. */
  26842. this.onDestroy = new Phaser.Signal();
  26843. /**
  26844. * @property {integer} cursorIndex - The current index of the Group cursor. Advance it with Group.next.
  26845. * @readOnly
  26846. */
  26847. this.cursorIndex = 0;
  26848. /**
  26849. * A Group that is fixed to the camera uses its x/y coordinates as offsets from the top left of the camera. These are stored in Group.cameraOffset.
  26850. *
  26851. * Note that the cameraOffset values are in addition to any parent in the display list.
  26852. * So if this Group was in a Group that has x: 200, then this will be added to the cameraOffset.x
  26853. *
  26854. * @property {boolean} fixedToCamera
  26855. */
  26856. this.fixedToCamera = false;
  26857. /**
  26858. * If this object is {@link #fixedToCamera} then this stores the x/y position offset relative to the top-left of the camera view.
  26859. * If the parent of this Group is also `fixedToCamera` then the offset here is in addition to that and should typically be disabled.
  26860. * @property {Phaser.Point} cameraOffset
  26861. */
  26862. this.cameraOffset = new Phaser.Point();
  26863. /**
  26864. * The hash array is an array belonging to this Group into which you can add any of its children via Group.addToHash and Group.removeFromHash.
  26865. *
  26866. * Only children of this Group can be added to and removed from the hash.
  26867. *
  26868. * This hash is used automatically by Phaser Arcade Physics in order to perform non z-index based destructive sorting.
  26869. * However if you don't use Arcade Physics, or this isn't a physics enabled Group, then you can use the hash to perform your own
  26870. * sorting and filtering of Group children without touching their z-index (and therefore display draw order)
  26871. *
  26872. * @property {array} hash
  26873. */
  26874. this.hash = [];
  26875. /**
  26876. * The property on which children are sorted.
  26877. * @property {string} _sortProperty
  26878. * @private
  26879. */
  26880. this._sortProperty = 'z';
  26881. };
  26882. Phaser.Group.prototype = Object.create(PIXI.DisplayObjectContainer.prototype);
  26883. Phaser.Group.prototype.constructor = Phaser.Group;
  26884. /**
  26885. * A returnType value, as specified in {@link #iterate} eg.
  26886. * @constant
  26887. * @type {integer}
  26888. */
  26889. Phaser.Group.RETURN_NONE = 0;
  26890. /**
  26891. * A returnType value, as specified in {@link #iterate} eg.
  26892. * @constant
  26893. * @type {integer}
  26894. */
  26895. Phaser.Group.RETURN_TOTAL = 1;
  26896. /**
  26897. * A returnType value, as specified in {@link #iterate} eg.
  26898. * @constant
  26899. * @type {integer}
  26900. */
  26901. Phaser.Group.RETURN_CHILD = 2;
  26902. /**
  26903. * A returnType value, as specified in {@link #iterate} eg.
  26904. * @constant
  26905. * @type {integer}
  26906. */
  26907. Phaser.Group.RETURN_ALL = 3;
  26908. /**
  26909. * A sort ordering value, as specified in {@link #sort} eg.
  26910. * @constant
  26911. * @type {integer}
  26912. */
  26913. Phaser.Group.SORT_ASCENDING = -1;
  26914. /**
  26915. * A sort ordering value, as specified in {@link #sort} eg.
  26916. * @constant
  26917. * @type {integer}
  26918. */
  26919. Phaser.Group.SORT_DESCENDING = 1;
  26920. /**
  26921. * Adds an existing object as the top child in this group.
  26922. *
  26923. * The child is automatically added to the top of the group, and is displayed above every previous child.
  26924. *
  26925. * Or if the _optional_ index is specified, the child is added at the location specified by the index value,
  26926. * this allows you to control child ordering.
  26927. *
  26928. * If the child was already in this Group, it is simply returned, and nothing else happens to it.
  26929. *
  26930. * If `Group.enableBody` is set, then a physics body will be created on the object, so long as one does not already exist.
  26931. *
  26932. * If `Group.inputEnableChildren` is set, then an Input Handler will be created on the object, so long as one does not already exist.
  26933. *
  26934. * Use {@link #addAt} to control where a child is added. Use {@link #create} to create and add a new child.
  26935. *
  26936. * @method Phaser.Group#add
  26937. * @param {DisplayObject} child - The display object to add as a child.
  26938. * @param {boolean} [silent=false] - If true the child will not dispatch the `onAddedToGroup` event.
  26939. * @param {integer} [index] - The index within the group to insert the child to. Where 0 is the bottom of the Group.
  26940. * @return {DisplayObject} The child that was added to the group.
  26941. */
  26942. Phaser.Group.prototype.add = function (child, silent, index) {
  26943. if (silent === undefined) { silent = false; }
  26944. if (child.parent === this)
  26945. {
  26946. return child;
  26947. }
  26948. if (child.body && child.parent && child.parent.hash)
  26949. {
  26950. child.parent.removeFromHash(child);
  26951. }
  26952. if (index === undefined)
  26953. {
  26954. child.z = this.children.length;
  26955. this.addChild(child);
  26956. }
  26957. else
  26958. {
  26959. this.addChildAt(child, index);
  26960. this.updateZ();
  26961. }
  26962. if (this.enableBody && child.hasOwnProperty('body') && child.body === null)
  26963. {
  26964. this.game.physics.enable(child, this.physicsBodyType);
  26965. }
  26966. else if (child.body)
  26967. {
  26968. this.addToHash(child);
  26969. }
  26970. if (this.inputEnableChildren && (!child.input || child.inputEnabled))
  26971. {
  26972. child.inputEnabled = true;
  26973. }
  26974. if (!silent && child.events)
  26975. {
  26976. child.events.onAddedToGroup$dispatch(child, this);
  26977. }
  26978. if (this.cursor === null)
  26979. {
  26980. this.cursor = child;
  26981. }
  26982. return child;
  26983. };
  26984. /**
  26985. * Adds an existing object to this group.
  26986. *
  26987. * The child is added to the group at the location specified by the index value, this allows you to control child ordering.
  26988. *
  26989. * If `Group.enableBody` is set, then a physics body will be created on the object, so long as one does not already exist.
  26990. *
  26991. * If `Group.inputEnableChildren` is set, then an Input Handler will be created on the object, so long as one does not already exist.
  26992. *
  26993. * @method Phaser.Group#addAt
  26994. * @param {DisplayObject} child - The display object to add as a child.
  26995. * @param {integer} [index=0] - The index within the group to insert the child to.
  26996. * @param {boolean} [silent=false] - If true the child will not dispatch the `onAddedToGroup` event.
  26997. * @return {DisplayObject} The child that was added to the group.
  26998. */
  26999. Phaser.Group.prototype.addAt = function (child, index, silent) {
  27000. this.add(child, silent, index);
  27001. };
  27002. /**
  27003. * Adds a child of this Group into the hash array.
  27004. * This call will return false if the child is not a child of this Group, or is already in the hash.
  27005. *
  27006. * @method Phaser.Group#addToHash
  27007. * @param {DisplayObject} child - The display object to add to this Groups hash. Must be a member of this Group already and not present in the hash.
  27008. * @return {boolean} True if the child was successfully added to the hash, otherwise false.
  27009. */
  27010. Phaser.Group.prototype.addToHash = function (child) {
  27011. if (child.parent === this)
  27012. {
  27013. var index = this.hash.indexOf(child);
  27014. if (index === -1)
  27015. {
  27016. this.hash.push(child);
  27017. return true;
  27018. }
  27019. }
  27020. return false;
  27021. };
  27022. /**
  27023. * Removes a child of this Group from the hash array.
  27024. * This call will return false if the child is not in the hash.
  27025. *
  27026. * @method Phaser.Group#removeFromHash
  27027. * @param {DisplayObject} child - The display object to remove from this Groups hash. Must be a member of this Group and in the hash.
  27028. * @return {boolean} True if the child was successfully removed from the hash, otherwise false.
  27029. */
  27030. Phaser.Group.prototype.removeFromHash = function (child) {
  27031. if (child)
  27032. {
  27033. var index = this.hash.indexOf(child);
  27034. if (index !== -1)
  27035. {
  27036. this.hash.splice(index, 1);
  27037. return true;
  27038. }
  27039. }
  27040. return false;
  27041. };
  27042. /**
  27043. * Adds an array of existing Display Objects to this Group.
  27044. *
  27045. * The Display Objects are automatically added to the top of this Group, and will render on-top of everything already in this Group.
  27046. *
  27047. * As well as an array you can also pass another Group as the first argument. In this case all of the children from that
  27048. * Group will be removed from it and added into this Group.
  27049. *
  27050. * If `Group.enableBody` is set, then a physics body will be created on the objects, so long as one does not already exist.
  27051. *
  27052. * If `Group.inputEnableChildren` is set, then an Input Handler will be created on the objects, so long as one does not already exist.
  27053. *
  27054. * @method Phaser.Group#addMultiple
  27055. * @param {DisplayObject[]|Phaser.Group} children - An array of display objects or a Phaser.Group. If a Group is given then *all* children will be moved from it.
  27056. * @param {boolean} [silent=false] - If true the children will not dispatch the `onAddedToGroup` event.
  27057. * @return {DisplayObject[]|Phaser.Group} The array of children or Group of children that were added to this Group.
  27058. */
  27059. Phaser.Group.prototype.addMultiple = function (children, silent) {
  27060. if (children instanceof Phaser.Group)
  27061. {
  27062. children.moveAll(this, silent);
  27063. }
  27064. else if (Array.isArray(children))
  27065. {
  27066. for (var i = 0; i < children.length; i++)
  27067. {
  27068. this.add(children[i], silent);
  27069. }
  27070. }
  27071. return children;
  27072. };
  27073. /**
  27074. * Returns the child found at the given index within this group.
  27075. *
  27076. * @method Phaser.Group#getAt
  27077. * @param {integer} index - The index to return the child from.
  27078. * @return {DisplayObject|integer} The child that was found at the given index, or -1 for an invalid index.
  27079. */
  27080. Phaser.Group.prototype.getAt = function (index) {
  27081. if (index < 0 || index >= this.children.length)
  27082. {
  27083. return -1;
  27084. }
  27085. else
  27086. {
  27087. return this.getChildAt(index);
  27088. }
  27089. };
  27090. /**
  27091. * Creates a new Phaser.Sprite object and adds it to the top of this group.
  27092. *
  27093. * Use {@link #classType} to change the type of object created.
  27094. *
  27095. * The child is automatically added to the top of the group, and is displayed above every previous child.
  27096. *
  27097. * Or if the _optional_ index is specified, the child is added at the location specified by the index value,
  27098. * this allows you to control child ordering.
  27099. *
  27100. * If `Group.enableBody` is set, then a physics body will be created on the object, so long as one does not already exist.
  27101. *
  27102. * If `Group.inputEnableChildren` is set, then an Input Handler will be created on the object, so long as one does not already exist.
  27103. *
  27104. * @method Phaser.Group#create
  27105. * @param {number} x - The x coordinate to display the newly created Sprite at. The value is in relation to the group.x point.
  27106. * @param {number} y - The y coordinate to display the newly created Sprite at. The value is in relation to the group.y point.
  27107. * @param {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|PIXI.Texture} [key] - This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache Image entry, or an instance of a RenderTexture, BitmapData, Video or PIXI.Texture.
  27108. * @param {string|number} [frame] - If this Sprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index.
  27109. * @param {boolean} [exists=true] - The default exists state of the Sprite.
  27110. * @param {integer} [index] - The index within the group to insert the child to. Where 0 is the bottom of the Group.
  27111. * @return {DisplayObject} The child that was created: will be a {@link Phaser.Sprite} unless {@link #classType} has been changed.
  27112. */
  27113. Phaser.Group.prototype.create = function (x, y, key, frame, exists, index) {
  27114. if (exists === undefined) { exists = true; }
  27115. var child = new this.classType(this.game, x, y, key, frame);
  27116. child.exists = exists;
  27117. child.visible = exists;
  27118. child.alive = exists;
  27119. return this.add(child, false, index);
  27120. };
  27121. /**
  27122. * Creates multiple Phaser.Sprite objects and adds them to the top of this Group.
  27123. *
  27124. * This method is useful if you need to quickly generate a pool of sprites, such as bullets.
  27125. *
  27126. * Use {@link #classType} to change the type of object created.
  27127. *
  27128. * You can provide an array as the `key` and / or `frame` arguments. When you do this
  27129. * it will create `quantity` Sprites for every key (and frame) in the arrays.
  27130. *
  27131. * For example:
  27132. *
  27133. * `createMultiple(25, ['ball', 'carrot'])`
  27134. *
  27135. * In the above code there are 2 keys (ball and carrot) which means that 50 sprites will be
  27136. * created in total, 25 of each. You can also have the `frame` as an array:
  27137. *
  27138. * `createMultiple(5, 'bricks', [0, 1, 2, 3])`
  27139. *
  27140. * In the above there is one key (bricks), which is a sprite sheet. The frames array tells
  27141. * this method to use frames 0, 1, 2 and 3. So in total it will create 20 sprites, because
  27142. * the quantity was set to 5, so that is 5 brick sprites of frame 0, 5 brick sprites with
  27143. * frame 1, and so on.
  27144. *
  27145. * If you set both the key and frame arguments to be arrays then understand it will create
  27146. * a total quantity of sprites equal to the size of both arrays times each other. I.e.:
  27147. *
  27148. * `createMultiple(20, ['diamonds', 'balls'], [0, 1, 2])`
  27149. *
  27150. * The above will create 20 'diamonds' of frame 0, 20 with frame 1 and 20 with frame 2.
  27151. * It will then create 20 'balls' of frame 0, 20 with frame 1 and 20 with frame 2.
  27152. * In total it will have created 120 sprites.
  27153. *
  27154. * By default the Sprites will have their `exists` property set to `false`, and they will be
  27155. * positioned at 0x0, relative to the `Group.x / y` values.
  27156. *
  27157. * If `Group.enableBody` is set, then a physics body will be created on the objects, so long as one does not already exist.
  27158. *
  27159. * If `Group.inputEnableChildren` is set, then an Input Handler will be created on the objects, so long as one does not already exist.
  27160. *
  27161. * @method Phaser.Group#createMultiple
  27162. * @param {integer} quantity - The number of Sprites to create.
  27163. * @param {string|array} key - The Cache key of the image that the Sprites will use. Or an Array of keys. See the description for details on how the quantity applies when arrays are used.
  27164. * @param {integer|string|array} [frame=0] - If the Sprite image contains multiple frames you can specify which one to use here. Or an Array of frames. See the description for details on how the quantity applies when arrays are used.
  27165. * @param {boolean} [exists=false] - The default exists state of the Sprite.
  27166. * @return {array} An array containing all of the Sprites that were created.
  27167. */
  27168. Phaser.Group.prototype.createMultiple = function (quantity, key, frame, exists) {
  27169. if (frame === undefined) { frame = 0; }
  27170. if (exists === undefined) { exists = false; }
  27171. if (!Array.isArray(key))
  27172. {
  27173. key = [ key ];
  27174. }
  27175. if (!Array.isArray(frame))
  27176. {
  27177. frame = [ frame ];
  27178. }
  27179. var _this = this;
  27180. var children = [];
  27181. key.forEach(function(singleKey) {
  27182. frame.forEach(function(singleFrame) {
  27183. for (var i = 0; i < quantity; i++)
  27184. {
  27185. children.push(_this.create(0, 0, singleKey, singleFrame, exists));
  27186. }
  27187. });
  27188. });
  27189. return children;
  27190. };
  27191. /**
  27192. * Internal method that re-applies all of the children's Z values.
  27193. *
  27194. * This must be called whenever children ordering is altered so that their `z` indices are correctly updated.
  27195. *
  27196. * @method Phaser.Group#updateZ
  27197. * @protected
  27198. */
  27199. Phaser.Group.prototype.updateZ = function () {
  27200. var i = this.children.length;
  27201. while (i--)
  27202. {
  27203. this.children[i].z = i;
  27204. }
  27205. };
  27206. /**
  27207. * This method iterates through all children in the Group (regardless if they are visible or exist)
  27208. * and then changes their position so they are arranged in a Grid formation. Children must have
  27209. * the `alignTo` method in order to be positioned by this call. All default Phaser Game Objects have
  27210. * this.
  27211. *
  27212. * The grid dimensions are determined by the first four arguments. The `width` and `height` arguments
  27213. * relate to the width and height of the grid respectively.
  27214. *
  27215. * For example if the Group had 100 children in it:
  27216. *
  27217. * `Group.align(10, 10, 32, 32)`
  27218. *
  27219. * This will align all of the children into a grid formation of 10x10, using 32 pixels per
  27220. * grid cell. If you want a wider grid, you could do:
  27221. *
  27222. * `Group.align(25, 4, 32, 32)`
  27223. *
  27224. * This will align the children into a grid of 25x4, again using 32 pixels per grid cell.
  27225. *
  27226. * You can choose to set _either_ the `width` or `height` value to -1. Doing so tells the method
  27227. * to keep on aligning children until there are no children left. For example if this Group had
  27228. * 48 children in it, the following:
  27229. *
  27230. * `Group.align(-1, 8, 32, 32)`
  27231. *
  27232. * ... will align the children so that there are 8 children vertically (the second argument),
  27233. * and each row will contain 6 sprites, except the last one, which will contain 5 (totaling 48)
  27234. *
  27235. * You can also do:
  27236. *
  27237. * `Group.align(10, -1, 32, 32)`
  27238. *
  27239. * In this case it will create a grid 10 wide, and as tall as it needs to be in order to fit
  27240. * all of the children in.
  27241. *
  27242. * The `position` property allows you to control where in each grid cell the child is positioned.
  27243. * This is a constant and can be one of `Phaser.TOP_LEFT` (default), `Phaser.TOP_CENTER`,
  27244. * `Phaser.TOP_RIGHT`, `Phaser.LEFT_CENTER`, `Phaser.CENTER`, `Phaser.RIGHT_CENTER`,
  27245. * `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` or `Phaser.BOTTOM_RIGHT`.
  27246. *
  27247. * The final argument; `offset` lets you start the alignment from a specific child index.
  27248. *
  27249. * @method Phaser.Group#align
  27250. * @param {integer} width - The width of the grid in items (not pixels). Set to -1 for a dynamic width. If -1 then you must set an explicit height value.
  27251. * @param {integer} height - The height of the grid in items (not pixels). Set to -1 for a dynamic height. If -1 then you must set an explicit width value.
  27252. * @param {integer} cellWidth - The width of each grid cell, in pixels.
  27253. * @param {integer} cellHeight - The height of each grid cell, in pixels.
  27254. * @param {integer} [position] - The position constant. One of `Phaser.TOP_LEFT` (default), `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_CENTER`, `Phaser.CENTER`, `Phaser.RIGHT_CENTER`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` or `Phaser.BOTTOM_RIGHT`.
  27255. * @param {integer} [offset=0] - Optional index to start the alignment from. Defaults to zero, the first child in the Group, but can be set to any valid child index value.
  27256. * @return {boolean} True if the Group children were aligned, otherwise false.
  27257. */
  27258. Phaser.Group.prototype.align = function (width, height, cellWidth, cellHeight, position, offset) {
  27259. if (position === undefined) { position = Phaser.TOP_LEFT; }
  27260. if (offset === undefined) { offset = 0; }
  27261. if (this.children.length === 0 || offset > this.children.length || (width === -1 && height === -1))
  27262. {
  27263. return false;
  27264. }
  27265. var r = new Phaser.Rectangle(0, 0, cellWidth, cellHeight);
  27266. var w = (width * cellWidth);
  27267. var h = (height * cellHeight);
  27268. for (var i = offset; i < this.children.length; i++)
  27269. {
  27270. var child = this.children[i];
  27271. if (child['alignIn'])
  27272. {
  27273. child.alignIn(r, position);
  27274. }
  27275. else
  27276. {
  27277. continue;
  27278. }
  27279. if (width === -1)
  27280. {
  27281. // We keep laying them out horizontally until we've done them all
  27282. r.y += cellHeight;
  27283. if (r.y === h)
  27284. {
  27285. r.x += cellWidth;
  27286. r.y = 0;
  27287. }
  27288. }
  27289. else if (height === -1)
  27290. {
  27291. // We keep laying them out vertically until we've done them all
  27292. r.x += cellWidth;
  27293. if (r.x === w)
  27294. {
  27295. r.x = 0;
  27296. r.y += cellHeight;
  27297. }
  27298. }
  27299. else
  27300. {
  27301. // We keep laying them out until we hit the column limit
  27302. r.x += cellWidth;
  27303. if (r.x === w)
  27304. {
  27305. r.x = 0;
  27306. r.y += cellHeight;
  27307. if (r.y === h)
  27308. {
  27309. // We've hit the column limit, so return, even if there are children left
  27310. return true;
  27311. }
  27312. }
  27313. }
  27314. }
  27315. return true;
  27316. };
  27317. /**
  27318. * Sets the group cursor to the first child in the group.
  27319. *
  27320. * If the optional index parameter is given it sets the cursor to the object at that index instead.
  27321. *
  27322. * @method Phaser.Group#resetCursor
  27323. * @param {integer} [index=0] - Set the cursor to point to a specific index.
  27324. * @return {any} The child the cursor now points to.
  27325. */
  27326. Phaser.Group.prototype.resetCursor = function (index) {
  27327. if (index === undefined) { index = 0; }
  27328. if (index > this.children.length - 1)
  27329. {
  27330. index = 0;
  27331. }
  27332. if (this.cursor)
  27333. {
  27334. this.cursorIndex = index;
  27335. this.cursor = this.children[this.cursorIndex];
  27336. return this.cursor;
  27337. }
  27338. };
  27339. /**
  27340. * Advances the group cursor to the next (higher) object in the group.
  27341. *
  27342. * If the cursor is at the end of the group (top child) it is moved the start of the group (bottom child).
  27343. *
  27344. * @method Phaser.Group#next
  27345. * @return {any} The child the cursor now points to.
  27346. */
  27347. Phaser.Group.prototype.next = function () {
  27348. if (this.cursor)
  27349. {
  27350. // Wrap the cursor?
  27351. if (this.cursorIndex >= this.children.length - 1)
  27352. {
  27353. this.cursorIndex = 0;
  27354. }
  27355. else
  27356. {
  27357. this.cursorIndex++;
  27358. }
  27359. this.cursor = this.children[this.cursorIndex];
  27360. return this.cursor;
  27361. }
  27362. };
  27363. /**
  27364. * Moves the group cursor to the previous (lower) child in the group.
  27365. *
  27366. * If the cursor is at the start of the group (bottom child) it is moved to the end (top child).
  27367. *
  27368. * @method Phaser.Group#previous
  27369. * @return {any} The child the cursor now points to.
  27370. */
  27371. Phaser.Group.prototype.previous = function () {
  27372. if (this.cursor)
  27373. {
  27374. // Wrap the cursor?
  27375. if (this.cursorIndex === 0)
  27376. {
  27377. this.cursorIndex = this.children.length - 1;
  27378. }
  27379. else
  27380. {
  27381. this.cursorIndex--;
  27382. }
  27383. this.cursor = this.children[this.cursorIndex];
  27384. return this.cursor;
  27385. }
  27386. };
  27387. /**
  27388. * Swaps the position of two children in this group.
  27389. *
  27390. * Both children must be in this group, a child cannot be swapped with itself, and unparented children cannot be swapped.
  27391. *
  27392. * @method Phaser.Group#swap
  27393. * @param {any} child1 - The first child to swap.
  27394. * @param {any} child2 - The second child to swap.
  27395. */
  27396. Phaser.Group.prototype.swap = function (child1, child2) {
  27397. this.swapChildren(child1, child2);
  27398. this.updateZ();
  27399. };
  27400. /**
  27401. * Brings the given child to the top of this group so it renders above all other children.
  27402. *
  27403. * @method Phaser.Group#bringToTop
  27404. * @param {any} child - The child to bring to the top of this group.
  27405. * @return {any} The child that was moved.
  27406. */
  27407. Phaser.Group.prototype.bringToTop = function (child) {
  27408. if (child.parent === this && this.getIndex(child) < this.children.length)
  27409. {
  27410. this.remove(child, false, true);
  27411. this.add(child, true);
  27412. }
  27413. return child;
  27414. };
  27415. /**
  27416. * Sends the given child to the bottom of this group so it renders below all other children.
  27417. *
  27418. * @method Phaser.Group#sendToBack
  27419. * @param {any} child - The child to send to the bottom of this group.
  27420. * @return {any} The child that was moved.
  27421. */
  27422. Phaser.Group.prototype.sendToBack = function (child) {
  27423. if (child.parent === this && this.getIndex(child) > 0)
  27424. {
  27425. this.remove(child, false, true);
  27426. this.addAt(child, 0, true);
  27427. }
  27428. return child;
  27429. };
  27430. /**
  27431. * Moves the given child up one place in this group unless it's already at the top.
  27432. *
  27433. * @method Phaser.Group#moveUp
  27434. * @param {any} child - The child to move up in the group.
  27435. * @return {any} The child that was moved.
  27436. */
  27437. Phaser.Group.prototype.moveUp = function (child) {
  27438. if (child.parent === this && this.getIndex(child) < this.children.length - 1)
  27439. {
  27440. var a = this.getIndex(child);
  27441. var b = this.getAt(a + 1);
  27442. if (b)
  27443. {
  27444. this.swap(child, b);
  27445. }
  27446. }
  27447. return child;
  27448. };
  27449. /**
  27450. * Moves the given child down one place in this group unless it's already at the bottom.
  27451. *
  27452. * @method Phaser.Group#moveDown
  27453. * @param {any} child - The child to move down in the group.
  27454. * @return {any} The child that was moved.
  27455. */
  27456. Phaser.Group.prototype.moveDown = function (child) {
  27457. if (child.parent === this && this.getIndex(child) > 0)
  27458. {
  27459. var a = this.getIndex(child);
  27460. var b = this.getAt(a - 1);
  27461. if (b)
  27462. {
  27463. this.swap(child, b);
  27464. }
  27465. }
  27466. return child;
  27467. };
  27468. /**
  27469. * Positions the child found at the given index within this group to the given x and y coordinates.
  27470. *
  27471. * @method Phaser.Group#xy
  27472. * @param {integer} index - The index of the child in the group to set the position of.
  27473. * @param {number} x - The new x position of the child.
  27474. * @param {number} y - The new y position of the child.
  27475. */
  27476. Phaser.Group.prototype.xy = function (index, x, y) {
  27477. if (index < 0 || index > this.children.length)
  27478. {
  27479. return -1;
  27480. }
  27481. else
  27482. {
  27483. this.getChildAt(index).x = x;
  27484. this.getChildAt(index).y = y;
  27485. }
  27486. };
  27487. /**
  27488. * Reverses all children in this group.
  27489. *
  27490. * This operation applies only to immediate children and does not propagate to subgroups.
  27491. *
  27492. * @method Phaser.Group#reverse
  27493. */
  27494. Phaser.Group.prototype.reverse = function () {
  27495. this.children.reverse();
  27496. this.updateZ();
  27497. };
  27498. /**
  27499. * Get the index position of the given child in this group, which should match the child's `z` property.
  27500. *
  27501. * @method Phaser.Group#getIndex
  27502. * @param {any} child - The child to get the index for.
  27503. * @return {integer} The index of the child or -1 if it's not a member of this group.
  27504. */
  27505. Phaser.Group.prototype.getIndex = function (child) {
  27506. return this.children.indexOf(child);
  27507. };
  27508. /**
  27509. * Searches the Group for the first instance of a child with the `name`
  27510. * property matching the given argument. Should more than one child have
  27511. * the same name only the first instance is returned.
  27512. *
  27513. * @method Phaser.Group#getByName
  27514. * @param {string} name - The name to search for.
  27515. * @return {any} The first child with a matching name, or null if none were found.
  27516. */
  27517. Phaser.Group.prototype.getByName = function (name) {
  27518. for (var i = 0; i < this.children.length; i++)
  27519. {
  27520. if (this.children[i].name === name)
  27521. {
  27522. return this.children[i];
  27523. }
  27524. }
  27525. return null;
  27526. };
  27527. /**
  27528. * Replaces a child of this Group with the given newChild. The newChild cannot be a member of this Group.
  27529. *
  27530. * If `Group.enableBody` is set, then a physics body will be created on the object, so long as one does not already exist.
  27531. *
  27532. * If `Group.inputEnableChildren` is set, then an Input Handler will be created on the object, so long as one does not already exist.
  27533. *
  27534. * @method Phaser.Group#replace
  27535. * @param {any} oldChild - The child in this group that will be replaced.
  27536. * @param {any} newChild - The child to be inserted into this group.
  27537. * @return {any} Returns the oldChild that was replaced within this group.
  27538. */
  27539. Phaser.Group.prototype.replace = function (oldChild, newChild) {
  27540. var index = this.getIndex(oldChild);
  27541. if (index !== -1)
  27542. {
  27543. if (newChild.parent)
  27544. {
  27545. if (newChild.parent instanceof Phaser.Group)
  27546. {
  27547. newChild.parent.remove(newChild);
  27548. }
  27549. else
  27550. {
  27551. newChild.parent.removeChild(newChild);
  27552. }
  27553. }
  27554. this.remove(oldChild);
  27555. this.addAt(newChild, index);
  27556. return oldChild;
  27557. }
  27558. };
  27559. /**
  27560. * Checks if the child has the given property.
  27561. *
  27562. * Will scan up to 4 levels deep only.
  27563. *
  27564. * @method Phaser.Group#hasProperty
  27565. * @param {any} child - The child to check for the existence of the property on.
  27566. * @param {string[]} key - An array of strings that make up the property.
  27567. * @return {boolean} True if the child has the property, otherwise false.
  27568. */
  27569. Phaser.Group.prototype.hasProperty = function (child, key) {
  27570. var len = key.length;
  27571. if (len === 1 && key[0] in child)
  27572. {
  27573. return true;
  27574. }
  27575. else if (len === 2 && key[0] in child && key[1] in child[key[0]])
  27576. {
  27577. return true;
  27578. }
  27579. else if (len === 3 && key[0] in child && key[1] in child[key[0]] && key[2] in child[key[0]][key[1]])
  27580. {
  27581. return true;
  27582. }
  27583. else if (len === 4 && key[0] in child && key[1] in child[key[0]] && key[2] in child[key[0]][key[1]] && key[3] in child[key[0]][key[1]][key[2]])
  27584. {
  27585. return true;
  27586. }
  27587. return false;
  27588. };
  27589. /**
  27590. * Sets a property to the given value on the child. The operation parameter controls how the value is set.
  27591. *
  27592. * The operations are:
  27593. * - 0: set the existing value to the given value; if force is `true` a new property will be created if needed
  27594. * - 1: will add the given value to the value already present.
  27595. * - 2: will subtract the given value from the value already present.
  27596. * - 3: will multiply the value already present by the given value.
  27597. * - 4: will divide the value already present by the given value.
  27598. *
  27599. * @method Phaser.Group#setProperty
  27600. * @param {any} child - The child to set the property value on.
  27601. * @param {array} key - An array of strings that make up the property that will be set.
  27602. * @param {any} value - The value that will be set.
  27603. * @param {integer} [operation=0] - Controls how the value is assigned. A value of 0 replaces the value with the new one. A value of 1 adds it, 2 subtracts it, 3 multiplies it and 4 divides it.
  27604. * @param {boolean} [force=false] - If `force` is true then the property will be set on the child regardless if it already exists or not. If false and the property doesn't exist, nothing will be set.
  27605. * @return {boolean} True if the property was set, false if not.
  27606. */
  27607. Phaser.Group.prototype.setProperty = function (child, key, value, operation, force) {
  27608. if (force === undefined) { force = false; }
  27609. operation = operation || 0;
  27610. // As ugly as this approach looks, and although it's limited to a depth of only 4, it's much faster than a for loop or object iteration.
  27611. // 0 = Equals
  27612. // 1 = Add
  27613. // 2 = Subtract
  27614. // 3 = Multiply
  27615. // 4 = Divide
  27616. // We can't force a property in and the child doesn't have it, so abort.
  27617. // Equally we can't add, subtract, multiply or divide a property value if it doesn't exist, so abort in those cases too.
  27618. if (!this.hasProperty(child, key) && (!force || operation > 0))
  27619. {
  27620. return false;
  27621. }
  27622. var len = key.length;
  27623. if (len === 1)
  27624. {
  27625. if (operation === 0) { child[key[0]] = value; }
  27626. else if (operation === 1) { child[key[0]] += value; }
  27627. else if (operation === 2) { child[key[0]] -= value; }
  27628. else if (operation === 3) { child[key[0]] *= value; }
  27629. else if (operation === 4) { child[key[0]] /= value; }
  27630. }
  27631. else if (len === 2)
  27632. {
  27633. if (operation === 0) { child[key[0]][key[1]] = value; }
  27634. else if (operation === 1) { child[key[0]][key[1]] += value; }
  27635. else if (operation === 2) { child[key[0]][key[1]] -= value; }
  27636. else if (operation === 3) { child[key[0]][key[1]] *= value; }
  27637. else if (operation === 4) { child[key[0]][key[1]] /= value; }
  27638. }
  27639. else if (len === 3)
  27640. {
  27641. if (operation === 0) { child[key[0]][key[1]][key[2]] = value; }
  27642. else if (operation === 1) { child[key[0]][key[1]][key[2]] += value; }
  27643. else if (operation === 2) { child[key[0]][key[1]][key[2]] -= value; }
  27644. else if (operation === 3) { child[key[0]][key[1]][key[2]] *= value; }
  27645. else if (operation === 4) { child[key[0]][key[1]][key[2]] /= value; }
  27646. }
  27647. else if (len === 4)
  27648. {
  27649. if (operation === 0) { child[key[0]][key[1]][key[2]][key[3]] = value; }
  27650. else if (operation === 1) { child[key[0]][key[1]][key[2]][key[3]] += value; }
  27651. else if (operation === 2) { child[key[0]][key[1]][key[2]][key[3]] -= value; }
  27652. else if (operation === 3) { child[key[0]][key[1]][key[2]][key[3]] *= value; }
  27653. else if (operation === 4) { child[key[0]][key[1]][key[2]][key[3]] /= value; }
  27654. }
  27655. return true;
  27656. };
  27657. /**
  27658. * Checks a property for the given value on the child.
  27659. *
  27660. * @method Phaser.Group#checkProperty
  27661. * @param {any} child - The child to check the property value on.
  27662. * @param {array} key - An array of strings that make up the property that will be set.
  27663. * @param {any} value - The value that will be checked.
  27664. * @param {boolean} [force=false] - If `force` is true then the property will be checked on the child regardless if it already exists or not. If true and the property doesn't exist, false will be returned.
  27665. * @return {boolean} True if the property was was equal to value, false if not.
  27666. */
  27667. Phaser.Group.prototype.checkProperty = function (child, key, value, force) {
  27668. if (force === undefined) { force = false; }
  27669. // We can't force a property in and the child doesn't have it, so abort.
  27670. if (!Phaser.Utils.getProperty(child, key) && force)
  27671. {
  27672. return false;
  27673. }
  27674. if (Phaser.Utils.getProperty(child, key) !== value)
  27675. {
  27676. return false;
  27677. }
  27678. return true;
  27679. };
  27680. /**
  27681. * Quickly set a property on a single child of this group to a new value.
  27682. *
  27683. * The operation parameter controls how the new value is assigned to the property, from simple replacement to addition and multiplication.
  27684. *
  27685. * @method Phaser.Group#set
  27686. * @param {Phaser.Sprite} child - The child to set the property on.
  27687. * @param {string} key - The property, as a string, to be set. For example: 'body.velocity.x'
  27688. * @param {any} value - The value that will be set.
  27689. * @param {boolean} [checkAlive=false] - If set then the child will only be updated if alive=true.
  27690. * @param {boolean} [checkVisible=false] - If set then the child will only be updated if visible=true.
  27691. * @param {integer} [operation=0] - Controls how the value is assigned. A value of 0 replaces the value with the new one. A value of 1 adds it, 2 subtracts it, 3 multiplies it and 4 divides it.
  27692. * @param {boolean} [force=false] - If `force` is true then the property will be set on the child regardless if it already exists or not. If false and the property doesn't exist, nothing will be set.
  27693. * @return {boolean} True if the property was set, false if not.
  27694. */
  27695. Phaser.Group.prototype.set = function (child, key, value, checkAlive, checkVisible, operation, force) {
  27696. if (force === undefined) { force = false; }
  27697. key = key.split('.');
  27698. if (checkAlive === undefined) { checkAlive = false; }
  27699. if (checkVisible === undefined) { checkVisible = false; }
  27700. if ((checkAlive === false || (checkAlive && child.alive)) && (checkVisible === false || (checkVisible && child.visible)))
  27701. {
  27702. return this.setProperty(child, key, value, operation, force);
  27703. }
  27704. };
  27705. /**
  27706. * Quickly set the same property across all children of this group to a new value.
  27707. *
  27708. * This call doesn't descend down children, so if you have a Group inside of this group, the property will be set on the group but not its children.
  27709. * If you need that ability please see `Group.setAllChildren`.
  27710. *
  27711. * The operation parameter controls how the new value is assigned to the property, from simple replacement to addition and multiplication.
  27712. *
  27713. * @method Phaser.Group#setAll
  27714. * @param {string} key - The property, as a string, to be set. For example: 'body.velocity.x'
  27715. * @param {any} value - The value that will be set.
  27716. * @param {boolean} [checkAlive=false] - If set then only children with alive=true will be updated. This includes any Groups that are children.
  27717. * @param {boolean} [checkVisible=false] - If set then only children with visible=true will be updated. This includes any Groups that are children.
  27718. * @param {integer} [operation=0] - Controls how the value is assigned. A value of 0 replaces the value with the new one. A value of 1 adds it, 2 subtracts it, 3 multiplies it and 4 divides it.
  27719. * @param {boolean} [force=false] - If `force` is true then the property will be set on the child regardless if it already exists or not. If false and the property doesn't exist, nothing will be set.
  27720. */
  27721. Phaser.Group.prototype.setAll = function (key, value, checkAlive, checkVisible, operation, force) {
  27722. if (checkAlive === undefined) { checkAlive = false; }
  27723. if (checkVisible === undefined) { checkVisible = false; }
  27724. if (force === undefined) { force = false; }
  27725. key = key.split('.');
  27726. operation = operation || 0;
  27727. for (var i = 0; i < this.children.length; i++)
  27728. {
  27729. if ((!checkAlive || (checkAlive && this.children[i].alive)) && (!checkVisible || (checkVisible && this.children[i].visible)))
  27730. {
  27731. this.setProperty(this.children[i], key, value, operation, force);
  27732. }
  27733. }
  27734. };
  27735. /**
  27736. * Quickly set the same property across all children of this group, and any child Groups, to a new value.
  27737. *
  27738. * If this group contains other Groups then the same property is set across their children as well, iterating down until it reaches the bottom.
  27739. * Unlike with `setAll` the property is NOT set on child Groups itself.
  27740. *
  27741. * The operation parameter controls how the new value is assigned to the property, from simple replacement to addition and multiplication.
  27742. *
  27743. * @method Phaser.Group#setAllChildren
  27744. * @param {string} key - The property, as a string, to be set. For example: 'body.velocity.x'
  27745. * @param {any} value - The value that will be set.
  27746. * @param {boolean} [checkAlive=false] - If set then only children with alive=true will be updated. This includes any Groups that are children.
  27747. * @param {boolean} [checkVisible=false] - If set then only children with visible=true will be updated. This includes any Groups that are children.
  27748. * @param {integer} [operation=0] - Controls how the value is assigned. A value of 0 replaces the value with the new one. A value of 1 adds it, 2 subtracts it, 3 multiplies it and 4 divides it.
  27749. * @param {boolean} [force=false] - If `force` is true then the property will be set on the child regardless if it already exists or not. If false and the property doesn't exist, nothing will be set.
  27750. */
  27751. Phaser.Group.prototype.setAllChildren = function (key, value, checkAlive, checkVisible, operation, force) {
  27752. if (checkAlive === undefined) { checkAlive = false; }
  27753. if (checkVisible === undefined) { checkVisible = false; }
  27754. if (force === undefined) { force = false; }
  27755. operation = operation || 0;
  27756. for (var i = 0; i < this.children.length; i++)
  27757. {
  27758. if ((!checkAlive || (checkAlive && this.children[i].alive)) && (!checkVisible || (checkVisible && this.children[i].visible)))
  27759. {
  27760. if (this.children[i] instanceof Phaser.Group)
  27761. {
  27762. this.children[i].setAllChildren(key, value, checkAlive, checkVisible, operation, force);
  27763. }
  27764. else
  27765. {
  27766. this.setProperty(this.children[i], key.split('.'), value, operation, force);
  27767. }
  27768. }
  27769. }
  27770. };
  27771. /**
  27772. * Quickly check that the same property across all children of this group is equal to the given value.
  27773. *
  27774. * This call doesn't descend down children, so if you have a Group inside of this group, the property will be checked on the group but not its children.
  27775. *
  27776. * @method Phaser.Group#checkAll
  27777. * @param {string} key - The property, as a string, to be set. For example: 'body.velocity.x'
  27778. * @param {any} value - The value that will be checked.
  27779. * @param {boolean} [checkAlive=false] - If set then only children with alive=true will be checked. This includes any Groups that are children.
  27780. * @param {boolean} [checkVisible=false] - If set then only children with visible=true will be checked. This includes any Groups that are children.
  27781. * @param {boolean} [force=false] - If `force` is true then the property will be checked on the child regardless if it already exists or not. If true and the property doesn't exist, false will be returned.
  27782. */
  27783. Phaser.Group.prototype.checkAll = function (key, value, checkAlive, checkVisible, force) {
  27784. if (checkAlive === undefined) { checkAlive = false; }
  27785. if (checkVisible === undefined) { checkVisible = false; }
  27786. if (force === undefined) { force = false; }
  27787. for (var i = 0; i < this.children.length; i++)
  27788. {
  27789. if ((!checkAlive || (checkAlive && this.children[i].alive)) && (!checkVisible || (checkVisible && this.children[i].visible)))
  27790. {
  27791. if (!this.checkProperty(this.children[i], key, value, force))
  27792. {
  27793. return false;
  27794. }
  27795. }
  27796. }
  27797. return true;
  27798. };
  27799. /**
  27800. * Adds the amount to the given property on all children in this group.
  27801. *
  27802. * `Group.addAll('x', 10)` will add 10 to the child.x value for each child.
  27803. *
  27804. * @method Phaser.Group#addAll
  27805. * @param {string} property - The property to increment, for example 'body.velocity.x' or 'angle'.
  27806. * @param {number} amount - The amount to increment the property by. If child.x = 10 then addAll('x', 40) would make child.x = 50.
  27807. * @param {boolean} checkAlive - If true the property will only be changed if the child is alive.
  27808. * @param {boolean} checkVisible - If true the property will only be changed if the child is visible.
  27809. */
  27810. Phaser.Group.prototype.addAll = function (property, amount, checkAlive, checkVisible) {
  27811. this.setAll(property, amount, checkAlive, checkVisible, 1);
  27812. };
  27813. /**
  27814. * Subtracts the amount from the given property on all children in this group.
  27815. *
  27816. * `Group.subAll('x', 10)` will minus 10 from the child.x value for each child.
  27817. *
  27818. * @method Phaser.Group#subAll
  27819. * @param {string} property - The property to decrement, for example 'body.velocity.x' or 'angle'.
  27820. * @param {number} amount - The amount to subtract from the property. If child.x = 50 then subAll('x', 40) would make child.x = 10.
  27821. * @param {boolean} checkAlive - If true the property will only be changed if the child is alive.
  27822. * @param {boolean} checkVisible - If true the property will only be changed if the child is visible.
  27823. */
  27824. Phaser.Group.prototype.subAll = function (property, amount, checkAlive, checkVisible) {
  27825. this.setAll(property, amount, checkAlive, checkVisible, 2);
  27826. };
  27827. /**
  27828. * Multiplies the given property by the amount on all children in this group.
  27829. *
  27830. * `Group.multiplyAll('x', 2)` will x2 the child.x value for each child.
  27831. *
  27832. * @method Phaser.Group#multiplyAll
  27833. * @param {string} property - The property to multiply, for example 'body.velocity.x' or 'angle'.
  27834. * @param {number} amount - The amount to multiply the property by. If child.x = 10 then multiplyAll('x', 2) would make child.x = 20.
  27835. * @param {boolean} checkAlive - If true the property will only be changed if the child is alive.
  27836. * @param {boolean} checkVisible - If true the property will only be changed if the child is visible.
  27837. */
  27838. Phaser.Group.prototype.multiplyAll = function (property, amount, checkAlive, checkVisible) {
  27839. this.setAll(property, amount, checkAlive, checkVisible, 3);
  27840. };
  27841. /**
  27842. * Divides the given property by the amount on all children in this group.
  27843. *
  27844. * `Group.divideAll('x', 2)` will half the child.x value for each child.
  27845. *
  27846. * @method Phaser.Group#divideAll
  27847. * @param {string} property - The property to divide, for example 'body.velocity.x' or 'angle'.
  27848. * @param {number} amount - The amount to divide the property by. If child.x = 100 then divideAll('x', 2) would make child.x = 50.
  27849. * @param {boolean} checkAlive - If true the property will only be changed if the child is alive.
  27850. * @param {boolean} checkVisible - If true the property will only be changed if the child is visible.
  27851. */
  27852. Phaser.Group.prototype.divideAll = function (property, amount, checkAlive, checkVisible) {
  27853. this.setAll(property, amount, checkAlive, checkVisible, 4);
  27854. };
  27855. /**
  27856. * Calls a function, specified by name, on all children in the group who exist (or do not exist).
  27857. *
  27858. * After the existsValue parameter you can add as many parameters as you like, which will all be passed to the child callback.
  27859. *
  27860. * @method Phaser.Group#callAllExists
  27861. * @param {string} callback - Name of the function on the children to call.
  27862. * @param {boolean} existsValue - Only children with exists=existsValue will be called.
  27863. * @param {...any} parameter - Additional parameters that will be passed to the callback.
  27864. */
  27865. Phaser.Group.prototype.callAllExists = function (callback, existsValue) {
  27866. var args;
  27867. if (arguments.length > 2)
  27868. {
  27869. args = [];
  27870. for (var i = 2; i < arguments.length; i++)
  27871. {
  27872. args.push(arguments[i]);
  27873. }
  27874. }
  27875. for (var i = 0; i < this.children.length; i++)
  27876. {
  27877. if (this.children[i].exists === existsValue && this.children[i][callback])
  27878. {
  27879. this.children[i][callback].apply(this.children[i], args);
  27880. }
  27881. }
  27882. };
  27883. /**
  27884. * Returns a reference to a function that exists on a child of the group based on the given callback array.
  27885. *
  27886. * @method Phaser.Group#callbackFromArray
  27887. * @param {object} child - The object to inspect.
  27888. * @param {array} callback - The array of function names.
  27889. * @param {integer} length - The size of the array (pre-calculated in callAll).
  27890. * @protected
  27891. */
  27892. Phaser.Group.prototype.callbackFromArray = function (child, callback, length) {
  27893. // Kinda looks like a Christmas tree
  27894. if (length === 1)
  27895. {
  27896. if (child[callback[0]])
  27897. {
  27898. return child[callback[0]];
  27899. }
  27900. }
  27901. else if (length === 2)
  27902. {
  27903. if (child[callback[0]][callback[1]])
  27904. {
  27905. return child[callback[0]][callback[1]];
  27906. }
  27907. }
  27908. else if (length === 3)
  27909. {
  27910. if (child[callback[0]][callback[1]][callback[2]])
  27911. {
  27912. return child[callback[0]][callback[1]][callback[2]];
  27913. }
  27914. }
  27915. else if (length === 4)
  27916. {
  27917. if (child[callback[0]][callback[1]][callback[2]][callback[3]])
  27918. {
  27919. return child[callback[0]][callback[1]][callback[2]][callback[3]];
  27920. }
  27921. }
  27922. else if (child[callback])
  27923. {
  27924. return child[callback];
  27925. }
  27926. return false;
  27927. };
  27928. /**
  27929. * Calls a function, specified by name, on all on children.
  27930. *
  27931. * The function is called for all children regardless if they are dead or alive (see callAllExists for different options).
  27932. * After the method parameter and context you can add as many extra parameters as you like, which will all be passed to the child.
  27933. *
  27934. * @method Phaser.Group#callAll
  27935. * @param {string} method - Name of the function on the child to call. Deep property lookup is supported.
  27936. * @param {string} [context=null] - A string containing the context under which the method will be executed. Set to null to default to the child.
  27937. * @param {...any} args - Additional parameters that will be passed to the method.
  27938. */
  27939. Phaser.Group.prototype.callAll = function (method, context) {
  27940. if (method === undefined)
  27941. {
  27942. return;
  27943. }
  27944. // Extract the method into an array
  27945. method = method.split('.');
  27946. var methodLength = method.length;
  27947. if (context === undefined || context === null || context === '')
  27948. {
  27949. context = null;
  27950. }
  27951. else
  27952. {
  27953. // Extract the context into an array
  27954. if (typeof context === 'string')
  27955. {
  27956. context = context.split('.');
  27957. var contextLength = context.length;
  27958. }
  27959. }
  27960. var args;
  27961. if (arguments.length > 2)
  27962. {
  27963. args = [];
  27964. for (var i = 2; i < arguments.length; i++)
  27965. {
  27966. args.push(arguments[i]);
  27967. }
  27968. }
  27969. var callback = null;
  27970. var callbackContext = null;
  27971. for (var i = 0; i < this.children.length; i++)
  27972. {
  27973. callback = this.callbackFromArray(this.children[i], method, methodLength);
  27974. if (context && callback)
  27975. {
  27976. callbackContext = this.callbackFromArray(this.children[i], context, contextLength);
  27977. if (callback)
  27978. {
  27979. callback.apply(callbackContext, args);
  27980. }
  27981. }
  27982. else if (callback)
  27983. {
  27984. callback.apply(this.children[i], args);
  27985. }
  27986. }
  27987. };
  27988. /**
  27989. * The core preUpdate - as called by World.
  27990. * @method Phaser.Group#preUpdate
  27991. * @protected
  27992. */
  27993. Phaser.Group.prototype.preUpdate = function () {
  27994. if (this.pendingDestroy)
  27995. {
  27996. this.destroy();
  27997. return false;
  27998. }
  27999. if (!this.exists || !this.parent.exists)
  28000. {
  28001. this.renderOrderID = -1;
  28002. return false;
  28003. }
  28004. for (var i = 0; i < this.children.length; i++)
  28005. {
  28006. this.children[i].preUpdate();
  28007. }
  28008. return true;
  28009. };
  28010. /**
  28011. * The core update - as called by World.
  28012. * @method Phaser.Group#update
  28013. * @protected
  28014. */
  28015. Phaser.Group.prototype.update = function () {
  28016. // Goes in reverse, because it's highly likely the child will destroy itself in `update`
  28017. var i = this.children.length;
  28018. while (i--)
  28019. {
  28020. this.children[i].update();
  28021. }
  28022. };
  28023. /**
  28024. * The core postUpdate - as called by World.
  28025. * @method Phaser.Group#postUpdate
  28026. * @protected
  28027. */
  28028. Phaser.Group.prototype.postUpdate = function () {
  28029. // Fixed to Camera?
  28030. if (this.fixedToCamera)
  28031. {
  28032. this.x = this.game.camera.view.x + this.cameraOffset.x;
  28033. this.y = this.game.camera.view.y + this.cameraOffset.y;
  28034. }
  28035. for (var i = 0; i < this.children.length; i++)
  28036. {
  28037. this.children[i].postUpdate();
  28038. }
  28039. };
  28040. /**
  28041. * Find children matching a certain predicate.
  28042. *
  28043. * For example:
  28044. *
  28045. * var healthyList = Group.filter(function(child, index, children) {
  28046. * return child.health > 10 ? true : false;
  28047. * }, true);
  28048. * healthyList.callAll('attack');
  28049. *
  28050. * Note: Currently this will skip any children which are Groups themselves.
  28051. *
  28052. * @method Phaser.Group#filter
  28053. * @param {function} predicate - The function that each child will be evaluated against. Each child of the group will be passed to it as its first parameter, the index as the second, and the entire child array as the third
  28054. * @param {boolean} [checkExists=false] - If true, only existing can be selected; otherwise all children can be selected and will be passed to the predicate.
  28055. * @return {Phaser.ArraySet} Returns an array list containing all the children that the predicate returned true for
  28056. */
  28057. Phaser.Group.prototype.filter = function (predicate, checkExists) {
  28058. var index = -1;
  28059. var length = this.children.length;
  28060. var results = [];
  28061. while (++index < length)
  28062. {
  28063. var child = this.children[index];
  28064. if (!checkExists || (checkExists && child.exists))
  28065. {
  28066. if (predicate(child, index, this.children))
  28067. {
  28068. results.push(child);
  28069. }
  28070. }
  28071. }
  28072. return new Phaser.ArraySet(results);
  28073. };
  28074. /**
  28075. * Call a function on each child in this group.
  28076. *
  28077. * Additional arguments for the callback can be specified after the `checkExists` parameter. For example,
  28078. *
  28079. * Group.forEach(awardBonusGold, this, true, 100, 500)
  28080. *
  28081. * would invoke `awardBonusGold` function with the parameters `(child, 100, 500)`.
  28082. *
  28083. * Note: This check will skip any children which are Groups themselves.
  28084. *
  28085. * @method Phaser.Group#forEach
  28086. * @param {function} callback - The function that will be called for each applicable child. The child will be passed as the first argument.
  28087. * @param {object} callbackContext - The context in which the function should be called (usually 'this').
  28088. * @param {boolean} [checkExists=false] - If set only children matching for which `exists` is true will be passed to the callback, otherwise all children will be passed.
  28089. * @param {...any} [args=(none)] - Additional arguments to pass to the callback function, after the child item.
  28090. */
  28091. Phaser.Group.prototype.forEach = function (callback, callbackContext, checkExists) {
  28092. if (checkExists === undefined) { checkExists = false; }
  28093. if (arguments.length <= 3)
  28094. {
  28095. for (var i = 0; i < this.children.length; i++)
  28096. {
  28097. if (!checkExists || (checkExists && this.children[i].exists))
  28098. {
  28099. callback.call(callbackContext, this.children[i]);
  28100. }
  28101. }
  28102. }
  28103. else
  28104. {
  28105. // Assigning to arguments properties causes Extreme Deoptimization in Chrome, FF, and IE.
  28106. // Using an array and pushing each element (not a slice!) is _significantly_ faster.
  28107. var args = [null];
  28108. for (var i = 3; i < arguments.length; i++)
  28109. {
  28110. args.push(arguments[i]);
  28111. }
  28112. for (var i = 0; i < this.children.length; i++)
  28113. {
  28114. if (!checkExists || (checkExists && this.children[i].exists))
  28115. {
  28116. args[0] = this.children[i];
  28117. callback.apply(callbackContext, args);
  28118. }
  28119. }
  28120. }
  28121. };
  28122. /**
  28123. * Call a function on each existing child in this group.
  28124. *
  28125. * See {@link Phaser.Group#forEach forEach} for details.
  28126. *
  28127. * @method Phaser.Group#forEachExists
  28128. * @param {function} callback - The function that will be called for each applicable child. The child will be passed as the first argument.
  28129. * @param {object} callbackContext - The context in which the function should be called (usually 'this').
  28130. * @param {...any} [args=(none)] - Additional arguments to pass to the callback function, after the child item.
  28131. */
  28132. Phaser.Group.prototype.forEachExists = function (callback, callbackContext) {
  28133. var args;
  28134. if (arguments.length > 2)
  28135. {
  28136. args = [null];
  28137. for (var i = 2; i < arguments.length; i++)
  28138. {
  28139. args.push(arguments[i]);
  28140. }
  28141. }
  28142. this.iterate('exists', true, Phaser.Group.RETURN_TOTAL, callback, callbackContext, args);
  28143. };
  28144. /**
  28145. * Call a function on each alive child in this group.
  28146. *
  28147. * See {@link Phaser.Group#forEach forEach} for details.
  28148. *
  28149. * @method Phaser.Group#forEachAlive
  28150. * @param {function} callback - The function that will be called for each applicable child. The child will be passed as the first argument.
  28151. * @param {object} callbackContext - The context in which the function should be called (usually 'this').
  28152. * @param {...any} [args=(none)] - Additional arguments to pass to the callback function, after the child item.
  28153. */
  28154. Phaser.Group.prototype.forEachAlive = function (callback, callbackContext) {
  28155. var args;
  28156. if (arguments.length > 2)
  28157. {
  28158. args = [null];
  28159. for (var i = 2; i < arguments.length; i++)
  28160. {
  28161. args.push(arguments[i]);
  28162. }
  28163. }
  28164. this.iterate('alive', true, Phaser.Group.RETURN_TOTAL, callback, callbackContext, args);
  28165. };
  28166. /**
  28167. * Call a function on each dead child in this group.
  28168. *
  28169. * See {@link Phaser.Group#forEach forEach} for details.
  28170. *
  28171. * @method Phaser.Group#forEachDead
  28172. * @param {function} callback - The function that will be called for each applicable child. The child will be passed as the first argument.
  28173. * @param {object} callbackContext - The context in which the function should be called (usually 'this').
  28174. * @param {...any} [args=(none)] - Additional arguments to pass to the callback function, after the child item.
  28175. */
  28176. Phaser.Group.prototype.forEachDead = function (callback, callbackContext) {
  28177. var args;
  28178. if (arguments.length > 2)
  28179. {
  28180. args = [null];
  28181. for (var i = 2; i < arguments.length; i++)
  28182. {
  28183. args.push(arguments[i]);
  28184. }
  28185. }
  28186. this.iterate('alive', false, Phaser.Group.RETURN_TOTAL, callback, callbackContext, args);
  28187. };
  28188. /**
  28189. * Sort the children in the group according to a particular key and ordering.
  28190. *
  28191. * Call this function to sort the group according to a particular key value and order.
  28192. *
  28193. * For example to depth sort Sprites for Zelda-style game you might call `group.sort('y', Phaser.Group.SORT_ASCENDING)` at the bottom of your `State.update()`.
  28194. *
  28195. * Internally this uses a standard JavaScript Array sort, so everything that applies there also applies here, including
  28196. * alphabetical sorting, mixing strings and numbers, and Unicode sorting. See MDN for more details.
  28197. *
  28198. * @method Phaser.Group#sort
  28199. * @param {string} [key='z'] - The name of the property to sort on. Defaults to the objects z-depth value.
  28200. * @param {integer} [order=Phaser.Group.SORT_ASCENDING] - Order ascending ({@link Phaser.Group.SORT_ASCENDING SORT_ASCENDING}) or descending ({@link Phaser.Group.SORT_DESCENDING SORT_DESCENDING}).
  28201. */
  28202. Phaser.Group.prototype.sort = function (key, order) {
  28203. if (this.children.length < 2)
  28204. {
  28205. // Nothing to swap
  28206. return;
  28207. }
  28208. if (key === undefined) { key = 'z'; }
  28209. if (order === undefined) { order = Phaser.Group.SORT_ASCENDING; }
  28210. this._sortProperty = key;
  28211. if (order === Phaser.Group.SORT_ASCENDING)
  28212. {
  28213. this.children.sort(this.ascendingSortHandler.bind(this));
  28214. }
  28215. else
  28216. {
  28217. this.children.sort(this.descendingSortHandler.bind(this));
  28218. }
  28219. this.updateZ();
  28220. };
  28221. /**
  28222. * Sort the children in the group according to custom sort function.
  28223. *
  28224. * The `sortHandler` is provided the two parameters: the two children involved in the comparison (a and b).
  28225. * It should return -1 if `a > b`, 1 if `a < b` or 0 if `a === b`.
  28226. *
  28227. * @method Phaser.Group#customSort
  28228. * @param {function} sortHandler - The custom sort function.
  28229. * @param {object} [context=undefined] - The context in which the sortHandler is called.
  28230. */
  28231. Phaser.Group.prototype.customSort = function (sortHandler, context) {
  28232. if (this.children.length < 2)
  28233. {
  28234. // Nothing to swap
  28235. return;
  28236. }
  28237. this.children.sort(sortHandler.bind(context));
  28238. this.updateZ();
  28239. };
  28240. /**
  28241. * An internal helper function for the sort process.
  28242. *
  28243. * @method Phaser.Group#ascendingSortHandler
  28244. * @protected
  28245. * @param {object} a - The first object being sorted.
  28246. * @param {object} b - The second object being sorted.
  28247. */
  28248. Phaser.Group.prototype.ascendingSortHandler = function (a, b) {
  28249. if (a[this._sortProperty] < b[this._sortProperty])
  28250. {
  28251. return -1;
  28252. }
  28253. else if (a[this._sortProperty] > b[this._sortProperty])
  28254. {
  28255. return 1;
  28256. }
  28257. else
  28258. {
  28259. if (a.z < b.z)
  28260. {
  28261. return -1;
  28262. }
  28263. else
  28264. {
  28265. return 1;
  28266. }
  28267. }
  28268. };
  28269. /**
  28270. * An internal helper function for the sort process.
  28271. *
  28272. * @method Phaser.Group#descendingSortHandler
  28273. * @protected
  28274. * @param {object} a - The first object being sorted.
  28275. * @param {object} b - The second object being sorted.
  28276. */
  28277. Phaser.Group.prototype.descendingSortHandler = function (a, b) {
  28278. if (a[this._sortProperty] < b[this._sortProperty])
  28279. {
  28280. return 1;
  28281. }
  28282. else if (a[this._sortProperty] > b[this._sortProperty])
  28283. {
  28284. return -1;
  28285. }
  28286. else
  28287. {
  28288. return 0;
  28289. }
  28290. };
  28291. /**
  28292. * Iterates over the children of the group performing one of several actions for matched children.
  28293. *
  28294. * A child is considered a match when it has a property, named `key`, whose value is equal to `value`
  28295. * according to a strict equality comparison.
  28296. *
  28297. * The result depends on the `returnType`:
  28298. *
  28299. * - {@link Phaser.Group.RETURN_TOTAL RETURN_TOTAL}:
  28300. * The callback, if any, is applied to all matching children. The number of matched children is returned.
  28301. * - {@link Phaser.Group.RETURN_NONE RETURN_NONE}:
  28302. * The callback, if any, is applied to all matching children. No value is returned.
  28303. * - {@link Phaser.Group.RETURN_CHILD RETURN_CHILD}:
  28304. * The callback, if any, is applied to the *first* matching child and the *first* matched child is returned.
  28305. * If there is no matching child then null is returned.
  28306. *
  28307. * If `args` is specified it must be an array. The matched child will be assigned to the first
  28308. * element and the entire array will be applied to the callback function.
  28309. *
  28310. * @method Phaser.Group#iterate
  28311. * @param {string} key - The child property to check, i.e. 'exists', 'alive', 'health'
  28312. * @param {any} value - A child matches if `child[key] === value` is true.
  28313. * @param {integer} returnType - How to iterate the children and what to return.
  28314. * @param {function} [callback=null] - Optional function that will be called on each matching child. The matched child is supplied as the first argument.
  28315. * @param {object} [callbackContext] - The context in which the function should be called (usually 'this').
  28316. * @param {any[]} [args=(none)] - The arguments supplied to to the callback; the first array index (argument) will be replaced with the matched child.
  28317. * @return {any} Returns either an integer (for RETURN_TOTAL), the first matched child (for RETURN_CHILD), or null.
  28318. */
  28319. Phaser.Group.prototype.iterate = function (key, value, returnType, callback, callbackContext, args) {
  28320. if (this.children.length === 0)
  28321. {
  28322. if (returnType === Phaser.Group.RETURN_TOTAL)
  28323. {
  28324. return 0;
  28325. }
  28326. else if (returnType === Phaser.Group.RETURN_ALL)
  28327. {
  28328. return [];
  28329. }
  28330. }
  28331. var total = 0;
  28332. if (returnType === Phaser.Group.RETURN_ALL)
  28333. {
  28334. var output = [];
  28335. }
  28336. for (var i = 0; i < this.children.length; i++)
  28337. {
  28338. if (this.children[i][key] === value)
  28339. {
  28340. total++;
  28341. if (callback)
  28342. {
  28343. if (args)
  28344. {
  28345. args[0] = this.children[i];
  28346. callback.apply(callbackContext, args);
  28347. }
  28348. else
  28349. {
  28350. callback.call(callbackContext, this.children[i]);
  28351. }
  28352. }
  28353. if (returnType === Phaser.Group.RETURN_CHILD)
  28354. {
  28355. return this.children[i];
  28356. }
  28357. else if (returnType === Phaser.Group.RETURN_ALL)
  28358. {
  28359. output.push(this.children[i]);
  28360. }
  28361. }
  28362. }
  28363. if (returnType === Phaser.Group.RETURN_TOTAL)
  28364. {
  28365. return total;
  28366. }
  28367. else if (returnType === Phaser.Group.RETURN_ALL)
  28368. {
  28369. return output;
  28370. }
  28371. else
  28372. {
  28373. // RETURN_CHILD or RETURN_NONE
  28374. return null;
  28375. }
  28376. };
  28377. /**
  28378. * Get the first display object that exists, or doesn't exist.
  28379. *
  28380. * You can use the optional argument `createIfNull` to create a new Game Object if none matching your exists argument were found in this Group.
  28381. *
  28382. * It works by calling `Group.create` passing it the parameters given to this method, and returning the new child.
  28383. *
  28384. * If a child *was* found , `createIfNull` is `false` and you provided the additional arguments then the child
  28385. * will be reset and/or have a new texture loaded on it. This is handled by `Group.resetChild`.
  28386. *
  28387. * @method Phaser.Group#getFirstExists
  28388. * @param {boolean} [exists=true] - If true, find the first existing child; otherwise find the first non-existing child.
  28389. * @param {boolean} [createIfNull=false] - If `true` and no alive children are found a new one is created.
  28390. * @param {number} [x] - The x coordinate to reset the child to. The value is in relation to the group.x point.
  28391. * @param {number} [y] - The y coordinate to reset the child to. The value is in relation to the group.y point.
  28392. * @param {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|PIXI.Texture} [key] - This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache Image entry, or an instance of a RenderTexture, BitmapData, Video or PIXI.Texture.
  28393. * @param {string|number} [frame] - If this Sprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index.
  28394. * @return {DisplayObject} The first child, or `null` if none found and `createIfNull` was false.
  28395. */
  28396. Phaser.Group.prototype.getFirstExists = function (exists, createIfNull, x, y, key, frame) {
  28397. if (createIfNull === undefined) { createIfNull = false; }
  28398. if (typeof exists !== 'boolean')
  28399. {
  28400. exists = true;
  28401. }
  28402. var child = this.iterate('exists', exists, Phaser.Group.RETURN_CHILD);
  28403. return (child === null && createIfNull) ? this.create(x, y, key, frame) : this.resetChild(child, x, y, key, frame);
  28404. };
  28405. /**
  28406. * Get the first child that is alive (`child.alive === true`).
  28407. *
  28408. * This is handy for choosing a squad leader, etc.
  28409. *
  28410. * You can use the optional argument `createIfNull` to create a new Game Object if no alive ones were found in this Group.
  28411. *
  28412. * It works by calling `Group.create` passing it the parameters given to this method, and returning the new child.
  28413. *
  28414. * If a child *was* found , `createIfNull` is `false` and you provided the additional arguments then the child
  28415. * will be reset and/or have a new texture loaded on it. This is handled by `Group.resetChild`.
  28416. *
  28417. * @method Phaser.Group#getFirstAlive
  28418. * @param {boolean} [createIfNull=false] - If `true` and no alive children are found a new one is created.
  28419. * @param {number} [x] - The x coordinate to reset the child to. The value is in relation to the group.x point.
  28420. * @param {number} [y] - The y coordinate to reset the child to. The value is in relation to the group.y point.
  28421. * @param {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|PIXI.Texture} [key] - This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache Image entry, or an instance of a RenderTexture, BitmapData, Video or PIXI.Texture.
  28422. * @param {string|number} [frame] - If this Sprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index.
  28423. * @return {DisplayObject} The alive dead child, or `null` if none found and `createIfNull` was false.
  28424. */
  28425. Phaser.Group.prototype.getFirstAlive = function (createIfNull, x, y, key, frame) {
  28426. if (createIfNull === undefined) { createIfNull = false; }
  28427. var child = this.iterate('alive', true, Phaser.Group.RETURN_CHILD);
  28428. return (child === null && createIfNull) ? this.create(x, y, key, frame) : this.resetChild(child, x, y, key, frame);
  28429. };
  28430. /**
  28431. * Get the first child that is dead (`child.alive === false`).
  28432. *
  28433. * This is handy for checking if everything has been wiped out and adding to the pool as needed.
  28434. *
  28435. * You can use the optional argument `createIfNull` to create a new Game Object if no dead ones were found in this Group.
  28436. *
  28437. * It works by calling `Group.create` passing it the parameters given to this method, and returning the new child.
  28438. *
  28439. * If a child *was* found , `createIfNull` is `false` and you provided the additional arguments then the child
  28440. * will be reset and/or have a new texture loaded on it. This is handled by `Group.resetChild`.
  28441. *
  28442. * @method Phaser.Group#getFirstDead
  28443. * @param {boolean} [createIfNull=false] - If `true` and no dead children are found a new one is created.
  28444. * @param {number} [x] - The x coordinate to reset the child to. The value is in relation to the group.x point.
  28445. * @param {number} [y] - The y coordinate to reset the child to. The value is in relation to the group.y point.
  28446. * @param {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|PIXI.Texture} [key] - This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache Image entry, or an instance of a RenderTexture, BitmapData, Video or PIXI.Texture.
  28447. * @param {string|number} [frame] - If this Sprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index.
  28448. * @return {DisplayObject} The first dead child, or `null` if none found and `createIfNull` was false.
  28449. */
  28450. Phaser.Group.prototype.getFirstDead = function (createIfNull, x, y, key, frame) {
  28451. if (createIfNull === undefined) { createIfNull = false; }
  28452. var child = this.iterate('alive', false, Phaser.Group.RETURN_CHILD);
  28453. return (child === null && createIfNull) ? this.create(x, y, key, frame) : this.resetChild(child, x, y, key, frame);
  28454. };
  28455. /**
  28456. * Takes a child and if the `x` and `y` arguments are given it calls `child.reset(x, y)` on it.
  28457. *
  28458. * If the `key` and optionally the `frame` arguments are given, it calls `child.loadTexture(key, frame)` on it.
  28459. *
  28460. * The two operations are separate. For example if you just wish to load a new texture then pass `null` as the x and y values.
  28461. *
  28462. * @method Phaser.Group#resetChild
  28463. * @param {DisplayObject} child - The child to reset and/or load the texture on.
  28464. * @param {number} [x] - The x coordinate to reset the child to. The value is in relation to the group.x point.
  28465. * @param {number} [y] - The y coordinate to reset the child to. The value is in relation to the group.y point.
  28466. * @param {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|PIXI.Texture} [key] - This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache Image entry, or an instance of a RenderTexture, BitmapData, Video or PIXI.Texture.
  28467. * @param {string|number} [frame] - If this Sprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index.
  28468. * @return {DisplayObject} The child that was reset: usually a {@link Phaser.Sprite}.
  28469. */
  28470. Phaser.Group.prototype.resetChild = function (child, x, y, key, frame) {
  28471. if (child === null)
  28472. {
  28473. return null;
  28474. }
  28475. if (x === undefined) { x = null; }
  28476. if (y === undefined) { y = null; }
  28477. if (x !== null && y !== null)
  28478. {
  28479. child.reset(x, y);
  28480. }
  28481. if (key !== undefined)
  28482. {
  28483. child.loadTexture(key, frame);
  28484. }
  28485. return child;
  28486. };
  28487. /**
  28488. * Return the child at the top of this group.
  28489. *
  28490. * The top child is the child displayed (rendered) above every other child.
  28491. *
  28492. * @method Phaser.Group#getTop
  28493. * @return {any} The child at the top of the Group.
  28494. */
  28495. Phaser.Group.prototype.getTop = function () {
  28496. if (this.children.length > 0)
  28497. {
  28498. return this.children[this.children.length - 1];
  28499. }
  28500. };
  28501. /**
  28502. * Returns the child at the bottom of this group.
  28503. *
  28504. * The bottom child the child being displayed (rendered) below every other child.
  28505. *
  28506. * @method Phaser.Group#getBottom
  28507. * @return {any} The child at the bottom of the Group.
  28508. */
  28509. Phaser.Group.prototype.getBottom = function () {
  28510. if (this.children.length > 0)
  28511. {
  28512. return this.children[0];
  28513. }
  28514. };
  28515. /**
  28516. * Get the closest child to given Object, with optional callback to filter children.
  28517. *
  28518. * This can be a Sprite, Group, Image or any object with public x and y properties.
  28519. *
  28520. * 'close' is determined by the distance from the objects `x` and `y` properties compared to the childs `x` and `y` properties.
  28521. *
  28522. * You can use the optional `callback` argument to apply your own filter to the distance checks.
  28523. * If the child is closer then the previous child, it will be sent to `callback` as the first argument,
  28524. * with the distance as the second. The callback should return `true` if it passes your
  28525. * filtering criteria, otherwise it should return `false`.
  28526. *
  28527. * @method Phaser.Group#getClosestTo
  28528. * @param {any} object - The object used to determine the distance. This can be a Sprite, Group, Image or any object with public x and y properties.
  28529. * @param {function} [callback] - The function that each child will be evaluated against. Each child of the group will be passed to it as its first parameter, with the distance as the second. It should return `true` if the child passes the matching criteria.
  28530. * @param {object} [callbackContext] - The context in which the function should be called (usually 'this').
  28531. * @return {any} The child closest to given object, or `null` if no child was found.
  28532. */
  28533. Phaser.Group.prototype.getClosestTo = function (object, callback, callbackContext) {
  28534. var distance = Number.MAX_VALUE;
  28535. var tempDistance = 0;
  28536. var result = null;
  28537. for (var i = 0; i < this.children.length; i++)
  28538. {
  28539. var child = this.children[i];
  28540. if (child.exists)
  28541. {
  28542. tempDistance = Math.abs(Phaser.Point.distance(object, child));
  28543. if (tempDistance < distance && (!callback || callback.call(callbackContext, child, tempDistance)))
  28544. {
  28545. distance = tempDistance;
  28546. result = child;
  28547. }
  28548. }
  28549. }
  28550. return result;
  28551. };
  28552. /**
  28553. * Get the child furthest away from the given Object, with optional callback to filter children.
  28554. *
  28555. * This can be a Sprite, Group, Image or any object with public x and y properties.
  28556. *
  28557. * 'furthest away' is determined by the distance from the objects `x` and `y` properties compared to the childs `x` and `y` properties.
  28558. *
  28559. * You can use the optional `callback` argument to apply your own filter to the distance checks.
  28560. * If the child is closer then the previous child, it will be sent to `callback` as the first argument,
  28561. * with the distance as the second. The callback should return `true` if it passes your
  28562. * filtering criteria, otherwise it should return `false`.
  28563. *
  28564. * @method Phaser.Group#getFurthestFrom
  28565. * @param {any} object - The object used to determine the distance. This can be a Sprite, Group, Image or any object with public x and y properties.
  28566. * @param {function} [callback] - The function that each child will be evaluated against. Each child of the group will be passed to it as its first parameter, with the distance as the second. It should return `true` if the child passes the matching criteria.
  28567. * @param {object} [callbackContext] - The context in which the function should be called (usually 'this').
  28568. * @return {any} The child furthest from the given object, or `null` if no child was found.
  28569. */
  28570. Phaser.Group.prototype.getFurthestFrom = function (object, callback, callbackContext) {
  28571. var distance = 0;
  28572. var tempDistance = 0;
  28573. var result = null;
  28574. for (var i = 0; i < this.children.length; i++)
  28575. {
  28576. var child = this.children[i];
  28577. if (child.exists)
  28578. {
  28579. tempDistance = Math.abs(Phaser.Point.distance(object, child));
  28580. if (tempDistance > distance && (!callback || callback.call(callbackContext, child, tempDistance)))
  28581. {
  28582. distance = tempDistance;
  28583. result = child;
  28584. }
  28585. }
  28586. }
  28587. return result;
  28588. };
  28589. /**
  28590. * Get the number of living children in this group.
  28591. *
  28592. * @method Phaser.Group#countLiving
  28593. * @return {integer} The number of children flagged as alive.
  28594. */
  28595. Phaser.Group.prototype.countLiving = function () {
  28596. return this.iterate('alive', true, Phaser.Group.RETURN_TOTAL);
  28597. };
  28598. /**
  28599. * Get the number of dead children in this group.
  28600. *
  28601. * @method Phaser.Group#countDead
  28602. * @return {integer} The number of children flagged as dead.
  28603. */
  28604. Phaser.Group.prototype.countDead = function () {
  28605. return this.iterate('alive', false, Phaser.Group.RETURN_TOTAL);
  28606. };
  28607. /**
  28608. * Returns a random child from the group.
  28609. *
  28610. * @method Phaser.Group#getRandom
  28611. * @param {integer} [startIndex=0] - Offset from the front of the group (lowest child).
  28612. * @param {integer} [length=(to top)] - Restriction on the number of values you want to randomly select from.
  28613. * @return {any} A random child of this Group.
  28614. */
  28615. Phaser.Group.prototype.getRandom = function (startIndex, length) {
  28616. if (startIndex === undefined) { startIndex = 0; }
  28617. if (length === undefined) { length = this.children.length; }
  28618. if (length === 0)
  28619. {
  28620. return null;
  28621. }
  28622. return Phaser.ArrayUtils.getRandomItem(this.children, startIndex, length);
  28623. };
  28624. /**
  28625. * Returns a random child from the Group that has `exists` set to `true`.
  28626. *
  28627. * Optionally you can specify a start and end index. For example if this Group had 100 children,
  28628. * and you set `startIndex` to 0 and `endIndex` to 50, it would return a random child from only
  28629. * the first 50 children in the Group.
  28630. *
  28631. * @method Phaser.Group#getRandomExists
  28632. * @param {integer} [startIndex=0] - The first child index to start the search from.
  28633. * @param {integer} [endIndex] - The last child index to search up to.
  28634. * @return {any} A random child of this Group that exists.
  28635. */
  28636. Phaser.Group.prototype.getRandomExists = function (startIndex, endIndex) {
  28637. var list = this.getAll('exists', true, startIndex, endIndex);
  28638. return this.game.rnd.pick(list);
  28639. };
  28640. /**
  28641. * Returns all children in this Group.
  28642. *
  28643. * You can optionally specify a matching criteria using the `property` and `value` arguments.
  28644. *
  28645. * For example: `getAll('exists', true)` would return only children that have their exists property set.
  28646. *
  28647. * Optionally you can specify a start and end index. For example if this Group had 100 children,
  28648. * and you set `startIndex` to 0 and `endIndex` to 50, it would return a random child from only
  28649. * the first 50 children in the Group.
  28650. *
  28651. * @method Phaser.Group#getAll
  28652. * @param {string} [property] - An optional property to test against the value argument.
  28653. * @param {any} [value] - If property is set then Child.property must strictly equal this value to be included in the results.
  28654. * @param {integer} [startIndex=0] - The first child index to start the search from.
  28655. * @param {integer} [endIndex] - The last child index to search up until.
  28656. * @return {any} A random existing child of this Group.
  28657. */
  28658. Phaser.Group.prototype.getAll = function (property, value, startIndex, endIndex) {
  28659. if (startIndex === undefined) { startIndex = 0; }
  28660. if (endIndex === undefined) { endIndex = this.children.length; }
  28661. var output = [];
  28662. for (var i = startIndex; i < endIndex; i++)
  28663. {
  28664. var child = this.children[i];
  28665. if (property && child[property] === value)
  28666. {
  28667. output.push(child);
  28668. }
  28669. }
  28670. return output;
  28671. };
  28672. /**
  28673. * Removes the given child from this group.
  28674. *
  28675. * This will dispatch an `onRemovedFromGroup` event from the child (if it has one), and optionally destroy the child.
  28676. *
  28677. * If the group cursor was referring to the removed child it is updated to refer to the next child.
  28678. *
  28679. * @method Phaser.Group#remove
  28680. * @param {any} child - The child to remove.
  28681. * @param {boolean} [destroy=false] - If true `destroy` will be invoked on the removed child.
  28682. * @param {boolean} [silent=false] - If true the the child will not dispatch the `onRemovedFromGroup` event.
  28683. * @return {boolean} true if the child was removed from this group, otherwise false.
  28684. */
  28685. Phaser.Group.prototype.remove = function (child, destroy, silent) {
  28686. if (destroy === undefined) { destroy = false; }
  28687. if (silent === undefined) { silent = false; }
  28688. if (this.children.length === 0 || this.children.indexOf(child) === -1)
  28689. {
  28690. return false;
  28691. }
  28692. if (!silent && child.events && !child.destroyPhase)
  28693. {
  28694. child.events.onRemovedFromGroup$dispatch(child, this);
  28695. }
  28696. var removed = this.removeChild(child);
  28697. this.removeFromHash(child);
  28698. this.updateZ();
  28699. if (this.cursor === child)
  28700. {
  28701. this.next();
  28702. }
  28703. if (destroy && removed)
  28704. {
  28705. removed.destroy(true);
  28706. }
  28707. return true;
  28708. };
  28709. /**
  28710. * Moves all children from this Group to the Group given.
  28711. *
  28712. * @method Phaser.Group#moveAll
  28713. * @param {Phaser.Group} group - The new Group to which the children will be moved to.
  28714. * @param {boolean} [silent=false] - If true the children will not dispatch the `onAddedToGroup` event for the new Group.
  28715. * @return {Phaser.Group} The Group to which all the children were moved.
  28716. */
  28717. Phaser.Group.prototype.moveAll = function (group, silent) {
  28718. if (silent === undefined) { silent = false; }
  28719. if (this.children.length > 0 && group instanceof Phaser.Group)
  28720. {
  28721. do
  28722. {
  28723. group.add(this.children[0], silent);
  28724. }
  28725. while (this.children.length > 0);
  28726. this.hash = [];
  28727. this.cursor = null;
  28728. }
  28729. return group;
  28730. };
  28731. /**
  28732. * Removes all children from this Group, but does not remove the group from its parent.
  28733. *
  28734. * The children can be optionally destroyed as they are removed.
  28735. *
  28736. * You can also optionally also destroy the BaseTexture the Child is using. Be careful if you've
  28737. * more than one Game Object sharing the same BaseTexture.
  28738. *
  28739. * @method Phaser.Group#removeAll
  28740. * @param {boolean} [destroy=false] - If true `destroy` will be invoked on each removed child.
  28741. * @param {boolean} [silent=false] - If true the children will not dispatch their `onRemovedFromGroup` events.
  28742. * @param {boolean} [destroyTexture=false] - If true, and if the `destroy` argument is also true, the BaseTexture belonging to the Child is also destroyed. Note that if another Game Object is sharing the same BaseTexture it will invalidate it.
  28743. */
  28744. Phaser.Group.prototype.removeAll = function (destroy, silent, destroyTexture) {
  28745. if (destroy === undefined) { destroy = false; }
  28746. if (silent === undefined) { silent = false; }
  28747. if (destroyTexture === undefined) { destroyTexture = false; }
  28748. if (this.children.length === 0)
  28749. {
  28750. return;
  28751. }
  28752. do
  28753. {
  28754. if (!silent && this.children[0].events)
  28755. {
  28756. this.children[0].events.onRemovedFromGroup$dispatch(this.children[0], this);
  28757. }
  28758. var removed = this.removeChild(this.children[0]);
  28759. this.removeFromHash(removed);
  28760. if (destroy && removed)
  28761. {
  28762. removed.destroy(true, destroyTexture);
  28763. }
  28764. }
  28765. while (this.children.length > 0);
  28766. this.hash = [];
  28767. this.cursor = null;
  28768. };
  28769. /**
  28770. * Removes all children from this group whose index falls beteen the given startIndex and endIndex values.
  28771. *
  28772. * @method Phaser.Group#removeBetween
  28773. * @param {integer} startIndex - The index to start removing children from.
  28774. * @param {integer} [endIndex] - The index to stop removing children at. Must be higher than startIndex. If undefined this method will remove all children between startIndex and the end of the group.
  28775. * @param {boolean} [destroy=false] - If true `destroy` will be invoked on each removed child.
  28776. * @param {boolean} [silent=false] - If true the children will not dispatch their `onRemovedFromGroup` events.
  28777. */
  28778. Phaser.Group.prototype.removeBetween = function (startIndex, endIndex, destroy, silent) {
  28779. if (endIndex === undefined) { endIndex = this.children.length - 1; }
  28780. if (destroy === undefined) { destroy = false; }
  28781. if (silent === undefined) { silent = false; }
  28782. if (this.children.length === 0)
  28783. {
  28784. return;
  28785. }
  28786. if (startIndex > endIndex || startIndex < 0 || endIndex > this.children.length)
  28787. {
  28788. return false;
  28789. }
  28790. var i = endIndex;
  28791. while (i >= startIndex)
  28792. {
  28793. if (!silent && this.children[i].events)
  28794. {
  28795. this.children[i].events.onRemovedFromGroup$dispatch(this.children[i], this);
  28796. }
  28797. var removed = this.removeChild(this.children[i]);
  28798. this.removeFromHash(removed);
  28799. if (destroy && removed)
  28800. {
  28801. removed.destroy(true);
  28802. }
  28803. if (this.cursor === this.children[i])
  28804. {
  28805. this.cursor = null;
  28806. }
  28807. i--;
  28808. }
  28809. this.updateZ();
  28810. };
  28811. /**
  28812. * Destroys this group.
  28813. *
  28814. * Removes all children, then removes this group from its parent and nulls references.
  28815. *
  28816. * @method Phaser.Group#destroy
  28817. * @param {boolean} [destroyChildren=true] - If true `destroy` will be invoked on each removed child.
  28818. * @param {boolean} [soft=false] - A 'soft destroy' (set to true) doesn't remove this group from its parent or null the game reference. Set to false and it does.
  28819. */
  28820. Phaser.Group.prototype.destroy = function (destroyChildren, soft) {
  28821. if (this.game === null || this.ignoreDestroy) { return; }
  28822. if (destroyChildren === undefined) { destroyChildren = true; }
  28823. if (soft === undefined) { soft = false; }
  28824. this.onDestroy.dispatch(this, destroyChildren, soft);
  28825. this.removeAll(destroyChildren);
  28826. this.cursor = null;
  28827. this.filters = null;
  28828. this.pendingDestroy = false;
  28829. if (!soft)
  28830. {
  28831. if (this.parent)
  28832. {
  28833. this.parent.removeChild(this);
  28834. }
  28835. this.game = null;
  28836. this.exists = false;
  28837. }
  28838. };
  28839. /**
  28840. * Total number of existing children in the group.
  28841. *
  28842. * @name Phaser.Group#total
  28843. * @property {integer} total
  28844. * @readonly
  28845. */
  28846. Object.defineProperty(Phaser.Group.prototype, "total", {
  28847. get: function () {
  28848. return this.iterate('exists', true, Phaser.Group.RETURN_TOTAL);
  28849. }
  28850. });
  28851. /**
  28852. * Total number of children in this group, regardless of exists/alive status.
  28853. *
  28854. * @name Phaser.Group#length
  28855. * @property {integer} length
  28856. * @readonly
  28857. */
  28858. Object.defineProperty(Phaser.Group.prototype, "length", {
  28859. get: function () {
  28860. return this.children.length;
  28861. }
  28862. });
  28863. /**
  28864. * The angle of rotation of the group container, in degrees.
  28865. *
  28866. * This adjusts the group itself by modifying its local rotation transform.
  28867. *
  28868. * This has no impact on the rotation/angle properties of the children, but it will update their worldTransform
  28869. * and on-screen orientation and position.
  28870. *
  28871. * @name Phaser.Group#angle
  28872. * @property {number} angle
  28873. */
  28874. Object.defineProperty(Phaser.Group.prototype, "angle", {
  28875. get: function() {
  28876. return Phaser.Math.radToDeg(this.rotation);
  28877. },
  28878. set: function(value) {
  28879. this.rotation = Phaser.Math.degToRad(value);
  28880. }
  28881. });
  28882. /**
  28883. * The center x coordinate of this Group.
  28884. *
  28885. * It is derived by calling `getBounds`, calculating the Groups dimensions based on its
  28886. * visible children.
  28887. *
  28888. * @name Phaser.Group#centerX
  28889. * @property {number} centerX
  28890. */
  28891. Object.defineProperty(Phaser.Group.prototype, "centerX", {
  28892. get: function () {
  28893. return this.getBounds(this.parent).centerX;
  28894. },
  28895. set: function (value) {
  28896. var r = this.getBounds(this.parent);
  28897. var offset = this.x - r.x;
  28898. this.x = (value + offset) - r.halfWidth;
  28899. }
  28900. });
  28901. /**
  28902. * The center y coordinate of this Group.
  28903. *
  28904. * It is derived by calling `getBounds`, calculating the Groups dimensions based on its
  28905. * visible children.
  28906. *
  28907. * @name Phaser.Group#centerY
  28908. * @property {number} centerY
  28909. */
  28910. Object.defineProperty(Phaser.Group.prototype, "centerY", {
  28911. get: function () {
  28912. return this.getBounds(this.parent).centerY;
  28913. },
  28914. set: function (value) {
  28915. var r = this.getBounds(this.parent);
  28916. var offset = this.y - r.y;
  28917. this.y = (value + offset) - r.halfHeight;
  28918. }
  28919. });
  28920. /**
  28921. * The left coordinate of this Group.
  28922. *
  28923. * It is derived by calling `getBounds`, calculating the Groups dimensions based on its
  28924. * visible children.
  28925. *
  28926. * @name Phaser.Group#left
  28927. * @property {number} left
  28928. */
  28929. Object.defineProperty(Phaser.Group.prototype, "left", {
  28930. get: function () {
  28931. return this.getBounds(this.parent).left;
  28932. },
  28933. set: function (value) {
  28934. var r = this.getBounds(this.parent);
  28935. var offset = this.x - r.x;
  28936. this.x = value + offset;
  28937. }
  28938. });
  28939. /**
  28940. * The right coordinate of this Group.
  28941. *
  28942. * It is derived by calling `getBounds`, calculating the Groups dimensions based on its
  28943. * visible children.
  28944. *
  28945. * @name Phaser.Group#right
  28946. * @property {number} right
  28947. */
  28948. Object.defineProperty(Phaser.Group.prototype, "right", {
  28949. get: function () {
  28950. return this.getBounds(this.parent).right;
  28951. },
  28952. set: function (value) {
  28953. var r = this.getBounds(this.parent);
  28954. var offset = this.x - r.x;
  28955. this.x = (value + offset) - r.width;
  28956. }
  28957. });
  28958. /**
  28959. * The top coordinate of this Group.
  28960. *
  28961. * It is derived by calling `getBounds`, calculating the Groups dimensions based on its
  28962. * visible children.
  28963. *
  28964. * @name Phaser.Group#top
  28965. * @property {number} top
  28966. */
  28967. Object.defineProperty(Phaser.Group.prototype, "top", {
  28968. get: function () {
  28969. return this.getBounds(this.parent).top;
  28970. },
  28971. set: function (value) {
  28972. var r = this.getBounds(this.parent);
  28973. var offset = this.y - r.y;
  28974. this.y = (value + offset);
  28975. }
  28976. });
  28977. /**
  28978. * The bottom coordinate of this Group.
  28979. *
  28980. * It is derived by calling `getBounds`, calculating the Groups dimensions based on its
  28981. * visible children.
  28982. *
  28983. * @name Phaser.Group#bottom
  28984. * @property {number} bottom
  28985. */
  28986. Object.defineProperty(Phaser.Group.prototype, "bottom", {
  28987. get: function () {
  28988. return this.getBounds(this.parent).bottom;
  28989. },
  28990. set: function (value) {
  28991. var r = this.getBounds(this.parent);
  28992. var offset = this.y - r.y;
  28993. this.y = (value + offset) - r.height;
  28994. }
  28995. });
  28996. /**
  28997. * Aligns this Group within another Game Object, or Rectangle, known as the
  28998. * 'container', to one of 9 possible positions.
  28999. *
  29000. * The container must be a Game Object, or Phaser.Rectangle object. This can include properties
  29001. * such as `World.bounds` or `Camera.view`, for aligning Groups within the world
  29002. * and camera bounds. Or it can include other Sprites, Images, Text objects, BitmapText,
  29003. * TileSprites or Buttons.
  29004. *
  29005. * Please note that aligning a Group to another Game Object does **not** make it a child of
  29006. * the container. It simply modifies its position coordinates so it aligns with it.
  29007. *
  29008. * The position constants you can use are:
  29009. *
  29010. * `Phaser.TOP_LEFT`, `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_CENTER`,
  29011. * `Phaser.CENTER`, `Phaser.RIGHT_CENTER`, `Phaser.BOTTOM_LEFT`,
  29012. * `Phaser.BOTTOM_CENTER` and `Phaser.BOTTOM_RIGHT`.
  29013. *
  29014. * Groups are placed in such a way that their _bounds_ align with the
  29015. * container, taking into consideration rotation and scale of its children.
  29016. * This allows you to neatly align Groups, irrespective of their position value.
  29017. *
  29018. * The optional `offsetX` and `offsetY` arguments allow you to apply extra spacing to the final
  29019. * aligned position of the Group. For example:
  29020. *
  29021. * `group.alignIn(background, Phaser.BOTTOM_RIGHT, -20, -20)`
  29022. *
  29023. * Would align the `group` to the bottom-right, but moved 20 pixels in from the corner.
  29024. * Think of the offsets as applying an adjustment to the containers bounds before the alignment takes place.
  29025. * So providing a negative offset will 'shrink' the container bounds by that amount, and providing a positive
  29026. * one expands it.
  29027. *
  29028. * @method Phaser.Group#alignIn
  29029. * @param {Phaser.Rectangle|Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapText|Phaser.Button|Phaser.Graphics|Phaser.TileSprite} container - The Game Object or Rectangle with which to align this Group to. Can also include properties such as `World.bounds` or `Camera.view`.
  29030. * @param {integer} [position] - The position constant. One of `Phaser.TOP_LEFT` (default), `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_CENTER`, `Phaser.CENTER`, `Phaser.RIGHT_CENTER`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` or `Phaser.BOTTOM_RIGHT`.
  29031. * @param {integer} [offsetX=0] - A horizontal adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it.
  29032. * @param {integer} [offsetY=0] - A vertical adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it.
  29033. * @return {Phaser.Group} This Group.
  29034. */
  29035. // This function is set at the bottom of src/gameobjects/components/Bounds.js
  29036. /**
  29037. * Aligns this Group to the side of another Game Object, or Rectangle, known as the
  29038. * 'parent', in one of 11 possible positions.
  29039. *
  29040. * The parent must be a Game Object, or Phaser.Rectangle object. This can include properties
  29041. * such as `World.bounds` or `Camera.view`, for aligning Groups within the world
  29042. * and camera bounds. Or it can include other Sprites, Images, Text objects, BitmapText,
  29043. * TileSprites or Buttons.
  29044. *
  29045. * Please note that aligning a Group to another Game Object does **not** make it a child of
  29046. * the parent. It simply modifies its position coordinates so it aligns with it.
  29047. *
  29048. * The position constants you can use are:
  29049. *
  29050. * `Phaser.TOP_LEFT` (default), `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_TOP`,
  29051. * `Phaser.LEFT_CENTER`, `Phaser.LEFT_BOTTOM`, `Phaser.RIGHT_TOP`, `Phaser.RIGHT_CENTER`,
  29052. * `Phaser.RIGHT_BOTTOM`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER`
  29053. * and `Phaser.BOTTOM_RIGHT`.
  29054. *
  29055. * Groups are placed in such a way that their _bounds_ align with the
  29056. * parent, taking into consideration rotation and scale of the children.
  29057. * This allows you to neatly align Groups, irrespective of their position value.
  29058. *
  29059. * The optional `offsetX` and `offsetY` arguments allow you to apply extra spacing to the final
  29060. * aligned position of the Group. For example:
  29061. *
  29062. * `group.alignTo(background, Phaser.BOTTOM_RIGHT, -20, -20)`
  29063. *
  29064. * Would align the `group` to the bottom-right, but moved 20 pixels in from the corner.
  29065. * Think of the offsets as applying an adjustment to the parents bounds before the alignment takes place.
  29066. * So providing a negative offset will 'shrink' the parent bounds by that amount, and providing a positive
  29067. * one expands it.
  29068. *
  29069. * @method Phaser.Group#alignTo
  29070. * @param {Phaser.Rectangle|Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapText|Phaser.Button|Phaser.Graphics|Phaser.TileSprite} parent - The Game Object or Rectangle with which to align this Group to. Can also include properties such as `World.bounds` or `Camera.view`.
  29071. * @param {integer} [position] - The position constant. One of `Phaser.TOP_LEFT`, `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_TOP`, `Phaser.LEFT_CENTER`, `Phaser.LEFT_BOTTOM`, `Phaser.RIGHT_TOP`, `Phaser.RIGHT_CENTER`, `Phaser.RIGHT_BOTTOM`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` or `Phaser.BOTTOM_RIGHT`.
  29072. * @param {integer} [offsetX=0] - A horizontal adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it.
  29073. * @param {integer} [offsetY=0] - A vertical adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it.
  29074. * @return {Phaser.Group} This Group.
  29075. */
  29076. // This function is set at the bottom of src/gameobjects/components/Bounds.js
  29077. /**
  29078. * A display object is any object that can be rendered in the Phaser/pixi.js scene graph.
  29079. *
  29080. * This includes {@link Phaser.Group} (groups are display objects!),
  29081. * {@link Phaser.Sprite}, {@link Phaser.Button}, {@link Phaser.Text}
  29082. * as well as {@link PIXI.DisplayObject} and all derived types.
  29083. *
  29084. * @typedef {object} DisplayObject
  29085. */
  29086. // Documentation stub for linking.
  29087. /**
  29088. * The x coordinate of the group container.
  29089. *
  29090. * You can adjust the group container itself by modifying its coordinates.
  29091. * This will have no impact on the x/y coordinates of its children, but it will update their worldTransform and on-screen position.
  29092. * @name Phaser.Group#x
  29093. * @property {number} x
  29094. */
  29095. /**
  29096. * The y coordinate of the group container.
  29097. *
  29098. * You can adjust the group container itself by modifying its coordinates.
  29099. * This will have no impact on the x/y coordinates of its children, but it will update their worldTransform and on-screen position.
  29100. * @name Phaser.Group#y
  29101. * @property {number} y
  29102. */
  29103. /**
  29104. * The angle of rotation of the group container, in radians.
  29105. *
  29106. * This will adjust the group container itself by modifying its rotation.
  29107. * This will have no impact on the rotation value of its children, but it will update their worldTransform and on-screen position.
  29108. * @name Phaser.Group#rotation
  29109. * @property {number} rotation
  29110. */
  29111. /**
  29112. * The visible state of the group. Non-visible Groups and all of their children are not rendered.
  29113. *
  29114. * @name Phaser.Group#visible
  29115. * @property {boolean} visible
  29116. */
  29117. /**
  29118. * The alpha value of the group container.
  29119. *
  29120. * @name Phaser.Group#alpha
  29121. * @property {number} alpha
  29122. */
  29123. /**
  29124. * @author Richard Davey <rich@photonstorm.com>
  29125. * @copyright 2016 Photon Storm Ltd.
  29126. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  29127. */
  29128. /**
  29129. * "This world is but a canvas to our imagination." - Henry David Thoreau
  29130. *
  29131. * A game has only one world. The world is an abstract place in which all game objects live. It is not bound
  29132. * by stage limits and can be any size. You look into the world via cameras. All game objects live within
  29133. * the world at world-based coordinates. By default a world is created the same size as your Stage.
  29134. *
  29135. * @class Phaser.World
  29136. * @extends Phaser.Group
  29137. * @constructor
  29138. * @param {Phaser.Game} game - Reference to the current game instance.
  29139. */
  29140. Phaser.World = function (game) {
  29141. Phaser.Group.call(this, game, null, '__world', false);
  29142. /**
  29143. * The World has no fixed size, but it does have a bounds outside of which objects are no longer considered as being "in world" and you should use this to clean-up the display list and purge dead objects.
  29144. * By default we set the Bounds to be from 0,0 to Game.width,Game.height. I.e. it will match the size given to the game constructor with 0,0 representing the top-left of the display.
  29145. * However 0,0 is actually the center of the world, and if you rotate or scale the world all of that will happen from 0,0.
  29146. * So if you want to make a game in which the world itself will rotate you should adjust the bounds so that 0,0 is the center point, i.e. set them to -1000,-1000,2000,2000 for a 2000x2000 sized world centered around 0,0.
  29147. * @property {Phaser.Rectangle} bounds - Bound of this world that objects can not escape from.
  29148. */
  29149. this.bounds = new Phaser.Rectangle(0, 0, game.width, game.height);
  29150. /**
  29151. * @property {Phaser.Camera} camera - Camera instance.
  29152. */
  29153. this.camera = null;
  29154. /**
  29155. * @property {boolean} _definedSize - True if the World has been given a specifically defined size (i.e. from a Tilemap or direct in code) or false if it's just matched to the Game dimensions.
  29156. * @readonly
  29157. */
  29158. this._definedSize = false;
  29159. /**
  29160. * @property {number} width - The defined width of the World. Sometimes the bounds needs to grow larger than this (if you resize the game) but this retains the original requested dimension.
  29161. */
  29162. this._width = game.width;
  29163. /**
  29164. * @property {number} height - The defined height of the World. Sometimes the bounds needs to grow larger than this (if you resize the game) but this retains the original requested dimension.
  29165. */
  29166. this._height = game.height;
  29167. this.game.state.onStateChange.add(this.stateChange, this);
  29168. };
  29169. Phaser.World.prototype = Object.create(Phaser.Group.prototype);
  29170. Phaser.World.prototype.constructor = Phaser.World;
  29171. /**
  29172. * Initialises the game world.
  29173. *
  29174. * @method Phaser.World#boot
  29175. * @protected
  29176. */
  29177. Phaser.World.prototype.boot = function () {
  29178. this.camera = new Phaser.Camera(this.game, 0, 0, 0, this.game.width, this.game.height);
  29179. this.game.stage.addChild(this);
  29180. this.camera.boot();
  29181. };
  29182. /**
  29183. * Called whenever the State changes or resets.
  29184. *
  29185. * It resets the world.x and world.y coordinates back to zero,
  29186. * then resets the Camera.
  29187. *
  29188. * @method Phaser.World#stateChange
  29189. * @protected
  29190. */
  29191. Phaser.World.prototype.stateChange = function () {
  29192. this.x = 0;
  29193. this.y = 0;
  29194. this.camera.reset();
  29195. };
  29196. /**
  29197. * Updates the size of this world and sets World.x/y to the given values
  29198. * The Camera bounds and Physics bounds (if set) are also updated to match the new World bounds.
  29199. *
  29200. * @method Phaser.World#setBounds
  29201. * @param {number} x - Top left most corner of the world.
  29202. * @param {number} y - Top left most corner of the world.
  29203. * @param {number} width - New width of the game world in pixels.
  29204. * @param {number} height - New height of the game world in pixels.
  29205. */
  29206. Phaser.World.prototype.setBounds = function (x, y, width, height) {
  29207. this._definedSize = true;
  29208. this._width = width;
  29209. this._height = height;
  29210. this.bounds.setTo(x, y, width, height);
  29211. this.x = x;
  29212. this.y = y;
  29213. if (this.camera.bounds)
  29214. {
  29215. // The Camera can never be smaller than the game size
  29216. this.camera.bounds.setTo(x, y, Math.max(width, this.game.width), Math.max(height, this.game.height));
  29217. }
  29218. this.game.physics.setBoundsToWorld();
  29219. };
  29220. /**
  29221. * Updates the size of this world. Note that this doesn't modify the world x/y coordinates, just the width and height.
  29222. *
  29223. * @method Phaser.World#resize
  29224. * @param {number} width - New width of the game world in pixels.
  29225. * @param {number} height - New height of the game world in pixels.
  29226. */
  29227. Phaser.World.prototype.resize = function (width, height) {
  29228. // Don't ever scale the World bounds lower than the original requested dimensions if it's a defined world size
  29229. if (this._definedSize)
  29230. {
  29231. if (width < this._width)
  29232. {
  29233. width = this._width;
  29234. }
  29235. if (height < this._height)
  29236. {
  29237. height = this._height;
  29238. }
  29239. }
  29240. this.bounds.width = width;
  29241. this.bounds.height = height;
  29242. this.game.camera.setBoundsToWorld();
  29243. this.game.physics.setBoundsToWorld();
  29244. };
  29245. /**
  29246. * Destroyer of worlds.
  29247. *
  29248. * @method Phaser.World#shutdown
  29249. */
  29250. Phaser.World.prototype.shutdown = function () {
  29251. // World is a Group, so run a soft destruction on this and all children.
  29252. this.destroy(true, true);
  29253. };
  29254. /**
  29255. * This will take the given game object and check if its x/y coordinates fall outside of the world bounds.
  29256. * If they do it will reposition the object to the opposite side of the world, creating a wrap-around effect.
  29257. * If sprite has a P2 body then the body (sprite.body) should be passed as first parameter to the function.
  29258. *
  29259. * Please understand there are limitations to this method. For example if you have scaled the World
  29260. * then objects won't always be re-positioned correctly, and you'll need to employ your own wrapping function.
  29261. *
  29262. * @method Phaser.World#wrap
  29263. * @param {Phaser.Sprite|Phaser.Image|Phaser.TileSprite|Phaser.Text} sprite - The object you wish to wrap around the world bounds.
  29264. * @param {number} [padding=0] - Extra padding added equally to the sprite.x and y coordinates before checking if within the world bounds. Ignored if useBounds is true.
  29265. * @param {boolean} [useBounds=false] - If useBounds is false wrap checks the object.x/y coordinates. If true it does a more accurate bounds check, which is more expensive.
  29266. * @param {boolean} [horizontal=true] - If horizontal is false, wrap will not wrap the object.x coordinates horizontally.
  29267. * @param {boolean} [vertical=true] - If vertical is false, wrap will not wrap the object.y coordinates vertically.
  29268. */
  29269. Phaser.World.prototype.wrap = function (sprite, padding, useBounds, horizontal, vertical) {
  29270. if (padding === undefined) { padding = 0; }
  29271. if (useBounds === undefined) { useBounds = false; }
  29272. if (horizontal === undefined) { horizontal = true; }
  29273. if (vertical === undefined) { vertical = true; }
  29274. if (!useBounds)
  29275. {
  29276. if (horizontal && sprite.x + padding < this.bounds.x)
  29277. {
  29278. sprite.x = this.bounds.right + padding;
  29279. }
  29280. else if (horizontal && sprite.x - padding > this.bounds.right)
  29281. {
  29282. sprite.x = this.bounds.left - padding;
  29283. }
  29284. if (vertical && sprite.y + padding < this.bounds.top)
  29285. {
  29286. sprite.y = this.bounds.bottom + padding;
  29287. }
  29288. else if (vertical && sprite.y - padding > this.bounds.bottom)
  29289. {
  29290. sprite.y = this.bounds.top - padding;
  29291. }
  29292. }
  29293. else
  29294. {
  29295. sprite.getBounds();
  29296. if (horizontal)
  29297. {
  29298. if ((sprite.x + sprite._currentBounds.width) < this.bounds.x)
  29299. {
  29300. sprite.x = this.bounds.right;
  29301. }
  29302. else if (sprite.x > this.bounds.right)
  29303. {
  29304. sprite.x = this.bounds.left;
  29305. }
  29306. }
  29307. if (vertical)
  29308. {
  29309. if ((sprite.y + sprite._currentBounds.height) < this.bounds.top)
  29310. {
  29311. sprite.y = this.bounds.bottom;
  29312. }
  29313. else if (sprite.y > this.bounds.bottom)
  29314. {
  29315. sprite.y = this.bounds.top;
  29316. }
  29317. }
  29318. }
  29319. };
  29320. /**
  29321. * @name Phaser.World#width
  29322. * @property {number} width - Gets or sets the current width of the game world. The world can never be smaller than the game (canvas) dimensions.
  29323. */
  29324. Object.defineProperty(Phaser.World.prototype, "width", {
  29325. get: function () {
  29326. return this.bounds.width;
  29327. },
  29328. set: function (value) {
  29329. if (value < this.game.width)
  29330. {
  29331. value = this.game.width;
  29332. }
  29333. this.bounds.width = value;
  29334. this._width = value;
  29335. this._definedSize = true;
  29336. }
  29337. });
  29338. /**
  29339. * @name Phaser.World#height
  29340. * @property {number} height - Gets or sets the current height of the game world. The world can never be smaller than the game (canvas) dimensions.
  29341. */
  29342. Object.defineProperty(Phaser.World.prototype, "height", {
  29343. get: function () {
  29344. return this.bounds.height;
  29345. },
  29346. set: function (value) {
  29347. if (value < this.game.height)
  29348. {
  29349. value = this.game.height;
  29350. }
  29351. this.bounds.height = value;
  29352. this._height = value;
  29353. this._definedSize = true;
  29354. }
  29355. });
  29356. /**
  29357. * @name Phaser.World#centerX
  29358. * @property {number} centerX - Gets the X position corresponding to the center point of the world.
  29359. * @readonly
  29360. */
  29361. Object.defineProperty(Phaser.World.prototype, "centerX", {
  29362. get: function () {
  29363. return this.bounds.halfWidth + this.bounds.x;
  29364. }
  29365. });
  29366. /**
  29367. * @name Phaser.World#centerY
  29368. * @property {number} centerY - Gets the Y position corresponding to the center point of the world.
  29369. * @readonly
  29370. */
  29371. Object.defineProperty(Phaser.World.prototype, "centerY", {
  29372. get: function () {
  29373. return this.bounds.halfHeight + this.bounds.y;
  29374. }
  29375. });
  29376. /**
  29377. * @name Phaser.World#randomX
  29378. * @property {number} randomX - Gets a random integer which is lesser than or equal to the current width of the game world.
  29379. * @readonly
  29380. */
  29381. Object.defineProperty(Phaser.World.prototype, "randomX", {
  29382. get: function () {
  29383. if (this.bounds.x < 0)
  29384. {
  29385. return this.game.rnd.between(this.bounds.x, (this.bounds.width - Math.abs(this.bounds.x)));
  29386. }
  29387. else
  29388. {
  29389. return this.game.rnd.between(this.bounds.x, this.bounds.width);
  29390. }
  29391. }
  29392. });
  29393. /**
  29394. * @name Phaser.World#randomY
  29395. * @property {number} randomY - Gets a random integer which is lesser than or equal to the current height of the game world.
  29396. * @readonly
  29397. */
  29398. Object.defineProperty(Phaser.World.prototype, "randomY", {
  29399. get: function () {
  29400. if (this.bounds.y < 0)
  29401. {
  29402. return this.game.rnd.between(this.bounds.y, (this.bounds.height - Math.abs(this.bounds.y)));
  29403. }
  29404. else
  29405. {
  29406. return this.game.rnd.between(this.bounds.y, this.bounds.height);
  29407. }
  29408. }
  29409. });
  29410. /**
  29411. * @author Richard Davey <rich@photonstorm.com>
  29412. * @copyright 2016 Photon Storm Ltd.
  29413. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  29414. */
  29415. /**
  29416. * This is where the magic happens. The Game object is the heart of your game,
  29417. * providing quick access to common functions and handling the boot process.
  29418. *
  29419. * "Hell, there are no rules here - we're trying to accomplish something."
  29420. * Thomas A. Edison
  29421. *
  29422. * @class Phaser.Game
  29423. * @constructor
  29424. * @param {number|string} [width=800] - The width of your game in game pixels. If given as a string the value must be between 0 and 100 and will be used as the percentage width of the parent container, or the browser window if no parent is given.
  29425. * @param {number|string} [height=600] - The height of your game in game pixels. If given as a string the value must be between 0 and 100 and will be used as the percentage height of the parent container, or the browser window if no parent is given.
  29426. * @param {number} [renderer=Phaser.AUTO] - Which renderer to use: Phaser.AUTO will auto-detect, Phaser.WEBGL, Phaser.CANVAS or Phaser.HEADLESS (no rendering at all).
  29427. * @param {string|HTMLElement} [parent=''] - The DOM element into which this games canvas will be injected. Either a DOM ID (string) or the element itself.
  29428. * @param {object} [state=null] - The default state object. A object consisting of Phaser.State functions (preload, create, update, render) or null.
  29429. * @param {boolean} [transparent=false] - Use a transparent canvas background or not.
  29430. * @param {boolean} [antialias=true] - Draw all image textures anti-aliased or not. The default is for smooth textures, but disable if your game features pixel art.
  29431. * @param {object} [physicsConfig=null] - A physics configuration object to pass to the Physics world on creation.
  29432. */
  29433. Phaser.Game = function (width, height, renderer, parent, state, transparent, antialias, physicsConfig) {
  29434. /**
  29435. * @property {number} id - Phaser Game ID (for when Pixi supports multiple instances).
  29436. * @readonly
  29437. */
  29438. this.id = Phaser.GAMES.push(this) - 1;
  29439. /**
  29440. * @property {object} config - The Phaser.Game configuration object.
  29441. */
  29442. this.config = null;
  29443. /**
  29444. * @property {object} physicsConfig - The Phaser.Physics.World configuration object.
  29445. */
  29446. this.physicsConfig = physicsConfig;
  29447. /**
  29448. * @property {string|HTMLElement} parent - The Games DOM parent.
  29449. * @default
  29450. */
  29451. this.parent = '';
  29452. /**
  29453. * The current Game Width in pixels.
  29454. *
  29455. * _Do not modify this property directly:_ use {@link Phaser.ScaleManager#setGameSize} - eg. `game.scale.setGameSize(width, height)` - instead.
  29456. *
  29457. * @property {integer} width
  29458. * @readonly
  29459. * @default
  29460. */
  29461. this.width = 800;
  29462. /**
  29463. * The current Game Height in pixels.
  29464. *
  29465. * _Do not modify this property directly:_ use {@link Phaser.ScaleManager#setGameSize} - eg. `game.scale.setGameSize(width, height)` - instead.
  29466. *
  29467. * @property {integer} height
  29468. * @readonly
  29469. * @default
  29470. */
  29471. this.height = 600;
  29472. /**
  29473. * The resolution of your game. This value is read only, but can be changed at start time it via a game configuration object.
  29474. *
  29475. * @property {integer} resolution
  29476. * @readonly
  29477. * @default
  29478. */
  29479. this.resolution = 1;
  29480. /**
  29481. * @property {integer} _width - Private internal var.
  29482. * @private
  29483. */
  29484. this._width = 800;
  29485. /**
  29486. * @property {integer} _height - Private internal var.
  29487. * @private
  29488. */
  29489. this._height = 600;
  29490. /**
  29491. * @property {boolean} transparent - Use a transparent canvas background or not.
  29492. * @default
  29493. */
  29494. this.transparent = false;
  29495. /**
  29496. * @property {boolean} antialias - Anti-alias graphics. By default scaled images are smoothed in Canvas and WebGL, set anti-alias to false to disable this globally.
  29497. * @default
  29498. */
  29499. this.antialias = true;
  29500. /**
  29501. * @property {boolean} preserveDrawingBuffer - The value of the preserveDrawingBuffer flag affects whether or not the contents of the stencil buffer is retained after rendering.
  29502. * @default
  29503. */
  29504. this.preserveDrawingBuffer = false;
  29505. /**
  29506. * Clear the Canvas each frame before rendering the display list.
  29507. * You can set this to `false` to gain some performance if your game always contains a background that completely fills the display.
  29508. * @property {boolean} clearBeforeRender
  29509. * @default
  29510. */
  29511. this.clearBeforeRender = true;
  29512. /**
  29513. * @property {PIXI.CanvasRenderer|PIXI.WebGLRenderer} renderer - The Pixi Renderer.
  29514. * @protected
  29515. */
  29516. this.renderer = null;
  29517. /**
  29518. * @property {number} renderType - The Renderer this game will use. Either Phaser.AUTO, Phaser.CANVAS, Phaser.WEBGL, or Phaser.HEADLESS.
  29519. * @readonly
  29520. */
  29521. this.renderType = Phaser.AUTO;
  29522. /**
  29523. * @property {Phaser.StateManager} state - The StateManager.
  29524. */
  29525. this.state = null;
  29526. /**
  29527. * @property {boolean} isBooted - Whether the game engine is booted, aka available.
  29528. * @readonly
  29529. */
  29530. this.isBooted = false;
  29531. /**
  29532. * @property {boolean} isRunning - Is game running or paused?
  29533. * @readonly
  29534. */
  29535. this.isRunning = false;
  29536. /**
  29537. * @property {Phaser.RequestAnimationFrame} raf - Automatically handles the core game loop via requestAnimationFrame or setTimeout
  29538. * @protected
  29539. */
  29540. this.raf = null;
  29541. /**
  29542. * @property {Phaser.GameObjectFactory} add - Reference to the Phaser.GameObjectFactory.
  29543. */
  29544. this.add = null;
  29545. /**
  29546. * @property {Phaser.GameObjectCreator} make - Reference to the GameObject Creator.
  29547. */
  29548. this.make = null;
  29549. /**
  29550. * @property {Phaser.Cache} cache - Reference to the assets cache.
  29551. */
  29552. this.cache = null;
  29553. /**
  29554. * @property {Phaser.Input} input - Reference to the input manager
  29555. */
  29556. this.input = null;
  29557. /**
  29558. * @property {Phaser.Loader} load - Reference to the assets loader.
  29559. */
  29560. this.load = null;
  29561. /**
  29562. * @property {Phaser.Math} math - Reference to the math helper.
  29563. */
  29564. this.math = null;
  29565. /**
  29566. * @property {Phaser.Net} net - Reference to the network class.
  29567. */
  29568. this.net = null;
  29569. /**
  29570. * @property {Phaser.ScaleManager} scale - The game scale manager.
  29571. */
  29572. this.scale = null;
  29573. /**
  29574. * @property {Phaser.SoundManager} sound - Reference to the sound manager.
  29575. */
  29576. this.sound = null;
  29577. /**
  29578. * @property {Phaser.Stage} stage - Reference to the stage.
  29579. */
  29580. this.stage = null;
  29581. /**
  29582. * @property {Phaser.Time} time - Reference to the core game clock.
  29583. */
  29584. this.time = null;
  29585. /**
  29586. * @property {Phaser.TweenManager} tweens - Reference to the tween manager.
  29587. */
  29588. this.tweens = null;
  29589. /**
  29590. * @property {Phaser.World} world - Reference to the world.
  29591. */
  29592. this.world = null;
  29593. /**
  29594. * @property {Phaser.Physics} physics - Reference to the physics manager.
  29595. */
  29596. this.physics = null;
  29597. /**
  29598. * @property {Phaser.PluginManager} plugins - Reference to the plugin manager.
  29599. */
  29600. this.plugins = null;
  29601. /**
  29602. * @property {Phaser.RandomDataGenerator} rnd - Instance of repeatable random data generator helper.
  29603. */
  29604. this.rnd = null;
  29605. /**
  29606. * @property {Phaser.Device} device - Contains device information and capabilities.
  29607. */
  29608. this.device = Phaser.Device;
  29609. /**
  29610. * @property {Phaser.Camera} camera - A handy reference to world.camera.
  29611. */
  29612. this.camera = null;
  29613. /**
  29614. * @property {HTMLCanvasElement} canvas - A handy reference to renderer.view, the canvas that the game is being rendered in to.
  29615. */
  29616. this.canvas = null;
  29617. /**
  29618. * @property {CanvasRenderingContext2D} context - A handy reference to renderer.context (only set for CANVAS games, not WebGL)
  29619. */
  29620. this.context = null;
  29621. /**
  29622. * @property {Phaser.Utils.Debug} debug - A set of useful debug utilities.
  29623. */
  29624. this.debug = null;
  29625. /**
  29626. * @property {Phaser.Particles} particles - The Particle Manager.
  29627. */
  29628. this.particles = null;
  29629. /**
  29630. * @property {Phaser.Create} create - The Asset Generator.
  29631. */
  29632. this.create = null;
  29633. /**
  29634. * If `false` Phaser will automatically render the display list every update. If `true` the render loop will be skipped.
  29635. * You can toggle this value at run-time to gain exact control over when Phaser renders. This can be useful in certain types of game or application.
  29636. * Please note that if you don't render the display list then none of the game object transforms will be updated, so use this value carefully.
  29637. * @property {boolean} lockRender
  29638. * @default
  29639. */
  29640. this.lockRender = false;
  29641. /**
  29642. * @property {boolean} stepping - Enable core loop stepping with Game.enableStep().
  29643. * @default
  29644. * @readonly
  29645. */
  29646. this.stepping = false;
  29647. /**
  29648. * @property {boolean} pendingStep - An internal property used by enableStep, but also useful to query from your own game objects.
  29649. * @default
  29650. * @readonly
  29651. */
  29652. this.pendingStep = false;
  29653. /**
  29654. * @property {number} stepCount - When stepping is enabled this contains the current step cycle.
  29655. * @default
  29656. * @readonly
  29657. */
  29658. this.stepCount = 0;
  29659. /**
  29660. * @property {Phaser.Signal} onPause - This event is fired when the game pauses.
  29661. */
  29662. this.onPause = null;
  29663. /**
  29664. * @property {Phaser.Signal} onResume - This event is fired when the game resumes from a paused state.
  29665. */
  29666. this.onResume = null;
  29667. /**
  29668. * @property {Phaser.Signal} onBlur - This event is fired when the game no longer has focus (typically on page hide).
  29669. */
  29670. this.onBlur = null;
  29671. /**
  29672. * @property {Phaser.Signal} onFocus - This event is fired when the game has focus (typically on page show).
  29673. */
  29674. this.onFocus = null;
  29675. /**
  29676. * @property {boolean} _paused - Is game paused?
  29677. * @private
  29678. */
  29679. this._paused = false;
  29680. /**
  29681. * @property {boolean} _codePaused - Was the game paused via code or a visibility change?
  29682. * @private
  29683. */
  29684. this._codePaused = false;
  29685. /**
  29686. * The ID of the current/last logic update applied this render frame, starting from 0.
  29687. * The first update is `currentUpdateID === 0` and the last update is `currentUpdateID === updatesThisFrame.`
  29688. * @property {integer} currentUpdateID
  29689. * @protected
  29690. */
  29691. this.currentUpdateID = 0;
  29692. /**
  29693. * Number of logic updates expected to occur this render frame; will be 1 unless there are catch-ups required (and allowed).
  29694. * @property {integer} updatesThisFrame
  29695. * @protected
  29696. */
  29697. this.updatesThisFrame = 1;
  29698. /**
  29699. * @property {number} _deltaTime - Accumulate elapsed time until a logic update is due.
  29700. * @private
  29701. */
  29702. this._deltaTime = 0;
  29703. /**
  29704. * @property {number} _lastCount - Remember how many 'catch-up' iterations were used on the logicUpdate last frame.
  29705. * @private
  29706. */
  29707. this._lastCount = 0;
  29708. /**
  29709. * @property {number} _spiraling - If the 'catch-up' iterations are spiraling out of control, this counter is incremented.
  29710. * @private
  29711. */
  29712. this._spiraling = 0;
  29713. /**
  29714. * @property {boolean} _kickstart - Force a logic update + render by default (always set on Boot and State swap)
  29715. * @private
  29716. */
  29717. this._kickstart = true;
  29718. /**
  29719. * If the game is struggling to maintain the desired FPS, this signal will be dispatched.
  29720. * The desired/chosen FPS should probably be closer to the {@link Phaser.Time#suggestedFps} value.
  29721. * @property {Phaser.Signal} fpsProblemNotifier
  29722. * @public
  29723. */
  29724. this.fpsProblemNotifier = new Phaser.Signal();
  29725. /**
  29726. * @property {boolean} forceSingleUpdate - Should the game loop force a logic update, regardless of the delta timer? Set to true if you know you need this. You can toggle it on the fly.
  29727. */
  29728. this.forceSingleUpdate = true;
  29729. /**
  29730. * @property {number} _nextNotification - The soonest game.time.time value that the next fpsProblemNotifier can be dispatched.
  29731. * @private
  29732. */
  29733. this._nextFpsNotification = 0;
  29734. // Parse the configuration object (if any)
  29735. if (arguments.length === 1 && typeof arguments[0] === 'object')
  29736. {
  29737. this.parseConfig(arguments[0]);
  29738. }
  29739. else
  29740. {
  29741. this.config = { enableDebug: true };
  29742. if (typeof width !== 'undefined')
  29743. {
  29744. this._width = width;
  29745. }
  29746. if (typeof height !== 'undefined')
  29747. {
  29748. this._height = height;
  29749. }
  29750. if (typeof renderer !== 'undefined')
  29751. {
  29752. this.renderType = renderer;
  29753. }
  29754. if (typeof parent !== 'undefined')
  29755. {
  29756. this.parent = parent;
  29757. }
  29758. if (typeof transparent !== 'undefined')
  29759. {
  29760. this.transparent = transparent;
  29761. }
  29762. if (typeof antialias !== 'undefined')
  29763. {
  29764. this.antialias = antialias;
  29765. }
  29766. this.rnd = new Phaser.RandomDataGenerator([(Date.now() * Math.random()).toString()]);
  29767. this.state = new Phaser.StateManager(this, state);
  29768. }
  29769. this.device.whenReady(this.boot, this);
  29770. return this;
  29771. };
  29772. Phaser.Game.prototype = {
  29773. /**
  29774. * Parses a Game configuration object.
  29775. *
  29776. * @method Phaser.Game#parseConfig
  29777. * @protected
  29778. */
  29779. parseConfig: function (config) {
  29780. this.config = config;
  29781. if (config['enableDebug'] === undefined)
  29782. {
  29783. this.config.enableDebug = true;
  29784. }
  29785. if (config['width'])
  29786. {
  29787. this._width = config['width'];
  29788. }
  29789. if (config['height'])
  29790. {
  29791. this._height = config['height'];
  29792. }
  29793. if (config['renderer'])
  29794. {
  29795. this.renderType = config['renderer'];
  29796. }
  29797. if (config['parent'])
  29798. {
  29799. this.parent = config['parent'];
  29800. }
  29801. if (config['transparent'] !== undefined)
  29802. {
  29803. this.transparent = config['transparent'];
  29804. }
  29805. if (config['antialias'] !== undefined)
  29806. {
  29807. this.antialias = config['antialias'];
  29808. }
  29809. if (config['resolution'])
  29810. {
  29811. this.resolution = config['resolution'];
  29812. }
  29813. if (config['preserveDrawingBuffer'] !== undefined)
  29814. {
  29815. this.preserveDrawingBuffer = config['preserveDrawingBuffer'];
  29816. }
  29817. if (config['physicsConfig'])
  29818. {
  29819. this.physicsConfig = config['physicsConfig'];
  29820. }
  29821. var seed = [(Date.now() * Math.random()).toString()];
  29822. if (config['seed'])
  29823. {
  29824. seed = config['seed'];
  29825. }
  29826. this.rnd = new Phaser.RandomDataGenerator(seed);
  29827. var state = null;
  29828. if (config['state'])
  29829. {
  29830. state = config['state'];
  29831. }
  29832. this.state = new Phaser.StateManager(this, state);
  29833. },
  29834. /**
  29835. * Initialize engine sub modules and start the game.
  29836. *
  29837. * @method Phaser.Game#boot
  29838. * @protected
  29839. */
  29840. boot: function () {
  29841. if (this.isBooted)
  29842. {
  29843. return;
  29844. }
  29845. this.onPause = new Phaser.Signal();
  29846. this.onResume = new Phaser.Signal();
  29847. this.onBlur = new Phaser.Signal();
  29848. this.onFocus = new Phaser.Signal();
  29849. this.isBooted = true;
  29850. PIXI.game = this;
  29851. this.math = Phaser.Math;
  29852. this.scale = new Phaser.ScaleManager(this, this._width, this._height);
  29853. this.stage = new Phaser.Stage(this);
  29854. this.setUpRenderer();
  29855. this.world = new Phaser.World(this);
  29856. this.add = new Phaser.GameObjectFactory(this);
  29857. this.make = new Phaser.GameObjectCreator(this);
  29858. this.cache = new Phaser.Cache(this);
  29859. this.load = new Phaser.Loader(this);
  29860. this.time = new Phaser.Time(this);
  29861. this.tweens = new Phaser.TweenManager(this);
  29862. this.input = new Phaser.Input(this);
  29863. this.sound = new Phaser.SoundManager(this);
  29864. this.physics = new Phaser.Physics(this, this.physicsConfig);
  29865. this.particles = new Phaser.Particles(this);
  29866. this.create = new Phaser.Create(this);
  29867. this.plugins = new Phaser.PluginManager(this);
  29868. this.net = new Phaser.Net(this);
  29869. this.time.boot();
  29870. this.stage.boot();
  29871. this.world.boot();
  29872. this.scale.boot();
  29873. this.input.boot();
  29874. this.sound.boot();
  29875. this.state.boot();
  29876. if (this.config['enableDebug'])
  29877. {
  29878. this.debug = new Phaser.Utils.Debug(this);
  29879. this.debug.boot();
  29880. }
  29881. else
  29882. {
  29883. this.debug = { preUpdate: function () {}, update: function () {}, reset: function () {} };
  29884. }
  29885. this.showDebugHeader();
  29886. this.isRunning = true;
  29887. if (this.config && this.config['forceSetTimeOut'])
  29888. {
  29889. this.raf = new Phaser.RequestAnimationFrame(this, this.config['forceSetTimeOut']);
  29890. }
  29891. else
  29892. {
  29893. this.raf = new Phaser.RequestAnimationFrame(this, false);
  29894. }
  29895. this._kickstart = true;
  29896. if (window['focus'])
  29897. {
  29898. if (!window['PhaserGlobal'] || (window['PhaserGlobal'] && !window['PhaserGlobal'].stopFocus))
  29899. {
  29900. window.focus();
  29901. }
  29902. }
  29903. this.raf.start();
  29904. },
  29905. /**
  29906. * Displays a Phaser version debug header in the console.
  29907. *
  29908. * @method Phaser.Game#showDebugHeader
  29909. * @protected
  29910. */
  29911. showDebugHeader: function () {
  29912. if (window['PhaserGlobal'] && window['PhaserGlobal'].hideBanner)
  29913. {
  29914. return;
  29915. }
  29916. var v = Phaser.VERSION;
  29917. var r = 'Canvas';
  29918. var a = 'HTML Audio';
  29919. var c = 1;
  29920. if (this.renderType === Phaser.WEBGL)
  29921. {
  29922. r = 'WebGL';
  29923. c++;
  29924. }
  29925. else if (this.renderType === Phaser.HEADLESS)
  29926. {
  29927. r = 'Headless';
  29928. }
  29929. if (this.device.webAudio)
  29930. {
  29931. a = 'WebAudio';
  29932. c++;
  29933. }
  29934. if (this.device.chrome)
  29935. {
  29936. var args = [
  29937. '%c %c %c Phaser v' + v + ' | Pixi.js | ' + r + ' | ' + a + ' %c %c ' + '%c http://phaser.io %c\u2665%c\u2665%c\u2665',
  29938. 'background: #fb8cb3',
  29939. 'background: #d44a52',
  29940. 'color: #ffffff; background: #871905;',
  29941. 'background: #d44a52',
  29942. 'background: #fb8cb3',
  29943. 'background: #ffffff'
  29944. ];
  29945. for (var i = 0; i < 3; i++)
  29946. {
  29947. if (i < c)
  29948. {
  29949. args.push('color: #ff2424; background: #fff');
  29950. }
  29951. else
  29952. {
  29953. args.push('color: #959595; background: #fff');
  29954. }
  29955. }
  29956. console.log.apply(console, args);
  29957. }
  29958. else if (window['console'])
  29959. {
  29960. console.log('Phaser v' + v + ' | Pixi.js ' + PIXI.VERSION + ' | ' + r + ' | ' + a + ' | http://phaser.io');
  29961. }
  29962. },
  29963. /**
  29964. * Checks if the device is capable of using the requested renderer and sets it up or an alternative if not.
  29965. *
  29966. * @method Phaser.Game#setUpRenderer
  29967. * @protected
  29968. */
  29969. setUpRenderer: function () {
  29970. if (this.config['canvas'])
  29971. {
  29972. this.canvas = this.config['canvas'];
  29973. }
  29974. else
  29975. {
  29976. this.canvas = Phaser.Canvas.create(this, this.width, this.height, this.config['canvasID'], true);
  29977. }
  29978. if (this.config['canvasStyle'])
  29979. {
  29980. this.canvas.style = this.config['canvasStyle'];
  29981. }
  29982. else
  29983. {
  29984. this.canvas.style['-webkit-full-screen'] = 'width: 100%; height: 100%';
  29985. }
  29986. if (this.renderType === Phaser.HEADLESS || this.renderType === Phaser.CANVAS || (this.renderType === Phaser.AUTO && !this.device.webGL))
  29987. {
  29988. if (this.device.canvas)
  29989. {
  29990. // They requested Canvas and their browser supports it
  29991. this.renderType = Phaser.CANVAS;
  29992. this.renderer = new PIXI.CanvasRenderer(this);
  29993. this.context = this.renderer.context;
  29994. }
  29995. else
  29996. {
  29997. throw new Error('Phaser.Game - Cannot create Canvas or WebGL context, aborting.');
  29998. }
  29999. }
  30000. else
  30001. {
  30002. // They requested WebGL and their browser supports it
  30003. this.renderType = Phaser.WEBGL;
  30004. this.renderer = new PIXI.WebGLRenderer(this);
  30005. this.context = null;
  30006. this.canvas.addEventListener('webglcontextlost', this.contextLost.bind(this), false);
  30007. this.canvas.addEventListener('webglcontextrestored', this.contextRestored.bind(this), false);
  30008. }
  30009. if (this.device.cocoonJS)
  30010. {
  30011. this.canvas.screencanvas = (this.renderType === Phaser.CANVAS) ? true : false;
  30012. }
  30013. if (this.renderType !== Phaser.HEADLESS)
  30014. {
  30015. this.stage.smoothed = this.antialias;
  30016. Phaser.Canvas.addToDOM(this.canvas, this.parent, false);
  30017. Phaser.Canvas.setTouchAction(this.canvas);
  30018. }
  30019. },
  30020. /**
  30021. * Handles WebGL context loss.
  30022. *
  30023. * @method Phaser.Game#contextLost
  30024. * @private
  30025. * @param {Event} event - The webglcontextlost event.
  30026. */
  30027. contextLost: function (event) {
  30028. event.preventDefault();
  30029. this.renderer.contextLost = true;
  30030. },
  30031. /**
  30032. * Handles WebGL context restoration.
  30033. *
  30034. * @method Phaser.Game#contextRestored
  30035. * @private
  30036. */
  30037. contextRestored: function () {
  30038. this.renderer.initContext();
  30039. this.cache.clearGLTextures();
  30040. this.renderer.contextLost = false;
  30041. },
  30042. /**
  30043. * The core game loop.
  30044. *
  30045. * @method Phaser.Game#update
  30046. * @protected
  30047. * @param {number} time - The current time as provided by RequestAnimationFrame.
  30048. */
  30049. update: function (time) {
  30050. this.time.update(time);
  30051. if (this._kickstart)
  30052. {
  30053. this.updateLogic(this.time.desiredFpsMult);
  30054. // call the game render update exactly once every frame
  30055. this.updateRender(this.time.slowMotion * this.time.desiredFps);
  30056. this._kickstart = false;
  30057. return;
  30058. }
  30059. // if the logic time is spiraling upwards, skip a frame entirely
  30060. if (this._spiraling > 1 && !this.forceSingleUpdate)
  30061. {
  30062. // cause an event to warn the program that this CPU can't keep up with the current desiredFps rate
  30063. if (this.time.time > this._nextFpsNotification)
  30064. {
  30065. // only permit one fps notification per 10 seconds
  30066. this._nextFpsNotification = this.time.time + 10000;
  30067. // dispatch the notification signal
  30068. this.fpsProblemNotifier.dispatch();
  30069. }
  30070. // reset the _deltaTime accumulator which will cause all pending dropped frames to be permanently skipped
  30071. this._deltaTime = 0;
  30072. this._spiraling = 0;
  30073. // call the game render update exactly once every frame
  30074. this.updateRender(this.time.slowMotion * this.time.desiredFps);
  30075. }
  30076. else
  30077. {
  30078. // step size taking into account the slow motion speed
  30079. var slowStep = this.time.slowMotion * 1000.0 / this.time.desiredFps;
  30080. // accumulate time until the slowStep threshold is met or exceeded... up to a limit of 3 catch-up frames at slowStep intervals
  30081. this._deltaTime += Math.max(Math.min(slowStep * 3, this.time.elapsed), 0);
  30082. // call the game update logic multiple times if necessary to "catch up" with dropped frames
  30083. // unless forceSingleUpdate is true
  30084. var count = 0;
  30085. this.updatesThisFrame = Math.floor(this._deltaTime / slowStep);
  30086. if (this.forceSingleUpdate)
  30087. {
  30088. this.updatesThisFrame = Math.min(1, this.updatesThisFrame);
  30089. }
  30090. while (this._deltaTime >= slowStep)
  30091. {
  30092. this._deltaTime -= slowStep;
  30093. this.currentUpdateID = count;
  30094. this.updateLogic(this.time.desiredFpsMult);
  30095. count++;
  30096. if (this.forceSingleUpdate && count === 1)
  30097. {
  30098. break;
  30099. }
  30100. else
  30101. {
  30102. this.time.refresh();
  30103. }
  30104. }
  30105. // detect spiraling (if the catch-up loop isn't fast enough, the number of iterations will increase constantly)
  30106. if (count > this._lastCount)
  30107. {
  30108. this._spiraling++;
  30109. }
  30110. else if (count < this._lastCount)
  30111. {
  30112. // looks like it caught up successfully, reset the spiral alert counter
  30113. this._spiraling = 0;
  30114. }
  30115. this._lastCount = count;
  30116. // call the game render update exactly once every frame unless we're playing catch-up from a spiral condition
  30117. this.updateRender(this._deltaTime / slowStep);
  30118. }
  30119. },
  30120. /**
  30121. * Updates all logic subsystems in Phaser. Called automatically by Game.update.
  30122. *
  30123. * @method Phaser.Game#updateLogic
  30124. * @protected
  30125. * @param {number} timeStep - The current timeStep value as determined by Game.update.
  30126. */
  30127. updateLogic: function (timeStep) {
  30128. if (!this._paused && !this.pendingStep)
  30129. {
  30130. if (this.stepping)
  30131. {
  30132. this.pendingStep = true;
  30133. }
  30134. this.scale.preUpdate();
  30135. this.debug.preUpdate();
  30136. this.camera.preUpdate();
  30137. this.physics.preUpdate();
  30138. this.state.preUpdate(timeStep);
  30139. this.plugins.preUpdate(timeStep);
  30140. this.stage.preUpdate();
  30141. this.state.update();
  30142. this.stage.update();
  30143. this.tweens.update();
  30144. this.sound.update();
  30145. this.input.update();
  30146. this.physics.update();
  30147. this.particles.update();
  30148. this.plugins.update();
  30149. this.stage.postUpdate();
  30150. this.plugins.postUpdate();
  30151. }
  30152. else
  30153. {
  30154. // Scaling and device orientation changes are still reflected when paused.
  30155. this.scale.pauseUpdate();
  30156. this.state.pauseUpdate();
  30157. this.debug.preUpdate();
  30158. }
  30159. this.stage.updateTransform();
  30160. },
  30161. /**
  30162. * Runs the Render cycle.
  30163. * It starts by calling State.preRender. In here you can do any last minute adjustments of display objects as required.
  30164. * It then calls the renderer, which renders the entire display list, starting from the Stage object and working down.
  30165. * It then calls plugin.render on any loaded plugins, in the order in which they were enabled.
  30166. * After this State.render is called. Any rendering that happens here will take place on-top of the display list.
  30167. * Finally plugin.postRender is called on any loaded plugins, in the order in which they were enabled.
  30168. * This method is called automatically by Game.update, you don't need to call it directly.
  30169. * Should you wish to have fine-grained control over when Phaser renders then use the `Game.lockRender` boolean.
  30170. * Phaser will only render when this boolean is `false`.
  30171. *
  30172. * @method Phaser.Game#updateRender
  30173. * @protected
  30174. * @param {number} elapsedTime - The time elapsed since the last update.
  30175. */
  30176. updateRender: function (elapsedTime) {
  30177. if (this.lockRender)
  30178. {
  30179. return;
  30180. }
  30181. this.state.preRender(elapsedTime);
  30182. if (this.renderType !== Phaser.HEADLESS)
  30183. {
  30184. this.renderer.render(this.stage);
  30185. this.plugins.render(elapsedTime);
  30186. this.state.render(elapsedTime);
  30187. }
  30188. this.plugins.postRender(elapsedTime);
  30189. },
  30190. /**
  30191. * Enable core game loop stepping. When enabled you must call game.step() directly (perhaps via a DOM button?)
  30192. * Calling step will advance the game loop by one frame. This is extremely useful for hard to track down errors!
  30193. *
  30194. * @method Phaser.Game#enableStep
  30195. */
  30196. enableStep: function () {
  30197. this.stepping = true;
  30198. this.pendingStep = false;
  30199. this.stepCount = 0;
  30200. },
  30201. /**
  30202. * Disables core game loop stepping.
  30203. *
  30204. * @method Phaser.Game#disableStep
  30205. */
  30206. disableStep: function () {
  30207. this.stepping = false;
  30208. this.pendingStep = false;
  30209. },
  30210. /**
  30211. * When stepping is enabled you must call this function directly (perhaps via a DOM button?) to advance the game loop by one frame.
  30212. * This is extremely useful to hard to track down errors! Use the internal stepCount property to monitor progress.
  30213. *
  30214. * @method Phaser.Game#step
  30215. */
  30216. step: function () {
  30217. this.pendingStep = false;
  30218. this.stepCount++;
  30219. },
  30220. /**
  30221. * Nukes the entire game from orbit.
  30222. *
  30223. * Calls destroy on Game.state, Game.sound, Game.scale, Game.stage, Game.input, Game.physics and Game.plugins.
  30224. *
  30225. * Then sets all of those local handlers to null, destroys the renderer, removes the canvas from the DOM
  30226. * and resets the PIXI default renderer.
  30227. *
  30228. * @method Phaser.Game#destroy
  30229. */
  30230. destroy: function () {
  30231. this.raf.stop();
  30232. this.state.destroy();
  30233. this.sound.destroy();
  30234. this.scale.destroy();
  30235. this.stage.destroy();
  30236. this.input.destroy();
  30237. this.physics.destroy();
  30238. this.plugins.destroy();
  30239. this.state = null;
  30240. this.sound = null;
  30241. this.scale = null;
  30242. this.stage = null;
  30243. this.input = null;
  30244. this.physics = null;
  30245. this.plugins = null;
  30246. this.cache = null;
  30247. this.load = null;
  30248. this.time = null;
  30249. this.world = null;
  30250. this.isBooted = false;
  30251. this.renderer.destroy(false);
  30252. Phaser.Canvas.removeFromDOM(this.canvas);
  30253. PIXI.defaultRenderer = null;
  30254. Phaser.GAMES[this.id] = null;
  30255. },
  30256. /**
  30257. * Called by the Stage visibility handler.
  30258. *
  30259. * @method Phaser.Game#gamePaused
  30260. * @param {object} event - The DOM event that caused the game to pause, if any.
  30261. * @protected
  30262. */
  30263. gamePaused: function (event) {
  30264. // If the game is already paused it was done via game code, so don't re-pause it
  30265. if (!this._paused)
  30266. {
  30267. this._paused = true;
  30268. this.time.gamePaused();
  30269. if (this.sound.muteOnPause)
  30270. {
  30271. this.sound.setMute();
  30272. }
  30273. this.onPause.dispatch(event);
  30274. // Avoids Cordova iOS crash event: https://github.com/photonstorm/phaser/issues/1800
  30275. if (this.device.cordova && this.device.iOS)
  30276. {
  30277. this.lockRender = true;
  30278. }
  30279. }
  30280. },
  30281. /**
  30282. * Called by the Stage visibility handler.
  30283. *
  30284. * @method Phaser.Game#gameResumed
  30285. * @param {object} event - The DOM event that caused the game to pause, if any.
  30286. * @protected
  30287. */
  30288. gameResumed: function (event) {
  30289. // Game is paused, but wasn't paused via code, so resume it
  30290. if (this._paused && !this._codePaused)
  30291. {
  30292. this._paused = false;
  30293. this.time.gameResumed();
  30294. this.input.reset();
  30295. if (this.sound.muteOnPause)
  30296. {
  30297. this.sound.unsetMute();
  30298. }
  30299. this.onResume.dispatch(event);
  30300. // Avoids Cordova iOS crash event: https://github.com/photonstorm/phaser/issues/1800
  30301. if (this.device.cordova && this.device.iOS)
  30302. {
  30303. this.lockRender = false;
  30304. }
  30305. }
  30306. },
  30307. /**
  30308. * Called by the Stage visibility handler.
  30309. *
  30310. * @method Phaser.Game#focusLoss
  30311. * @param {object} event - The DOM event that caused the game to pause, if any.
  30312. * @protected
  30313. */
  30314. focusLoss: function (event) {
  30315. this.onBlur.dispatch(event);
  30316. if (!this.stage.disableVisibilityChange)
  30317. {
  30318. this.gamePaused(event);
  30319. }
  30320. },
  30321. /**
  30322. * Called by the Stage visibility handler.
  30323. *
  30324. * @method Phaser.Game#focusGain
  30325. * @param {object} event - The DOM event that caused the game to pause, if any.
  30326. * @protected
  30327. */
  30328. focusGain: function (event) {
  30329. this.onFocus.dispatch(event);
  30330. if (!this.stage.disableVisibilityChange)
  30331. {
  30332. this.gameResumed(event);
  30333. }
  30334. }
  30335. };
  30336. Phaser.Game.prototype.constructor = Phaser.Game;
  30337. /**
  30338. * The paused state of the Game. A paused game doesn't update any of its subsystems.
  30339. * When a game is paused the onPause event is dispatched. When it is resumed the onResume event is dispatched.
  30340. * @name Phaser.Game#paused
  30341. * @property {boolean} paused - Gets and sets the paused state of the Game.
  30342. */
  30343. Object.defineProperty(Phaser.Game.prototype, "paused", {
  30344. get: function () {
  30345. return this._paused;
  30346. },
  30347. set: function (value) {
  30348. if (value === true)
  30349. {
  30350. if (this._paused === false)
  30351. {
  30352. this._paused = true;
  30353. this.sound.setMute();
  30354. this.time.gamePaused();
  30355. this.onPause.dispatch(this);
  30356. }
  30357. this._codePaused = true;
  30358. }
  30359. else
  30360. {
  30361. if (this._paused)
  30362. {
  30363. this._paused = false;
  30364. this.input.reset();
  30365. this.sound.unsetMute();
  30366. this.time.gameResumed();
  30367. this.onResume.dispatch(this);
  30368. }
  30369. this._codePaused = false;
  30370. }
  30371. }
  30372. });
  30373. /**
  30374. *
  30375. * "Deleted code is debugged code." - Jeff Sickel
  30376. *
  30377. * ヽ(〃^▽^〃)ノ
  30378. *
  30379. */
  30380. /**
  30381. * @author Richard Davey <rich@photonstorm.com>
  30382. * @copyright 2016 Photon Storm Ltd.
  30383. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  30384. */
  30385. /**
  30386. * Phaser.Input is the Input Manager for all types of Input across Phaser, including mouse, keyboard, touch and MSPointer.
  30387. * The Input manager is updated automatically by the core game loop.
  30388. *
  30389. * @class Phaser.Input
  30390. * @constructor
  30391. * @param {Phaser.Game} game - Current game instance.
  30392. */
  30393. Phaser.Input = function (game) {
  30394. /**
  30395. * @property {Phaser.Game} game - A reference to the currently running game.
  30396. */
  30397. this.game = game;
  30398. /**
  30399. * @property {HTMLCanvasElement} hitCanvas - The canvas to which single pixels are drawn in order to perform pixel-perfect hit detection.
  30400. * @default
  30401. */
  30402. this.hitCanvas = null;
  30403. /**
  30404. * @property {CanvasRenderingContext2D} hitContext - The context of the pixel perfect hit canvas.
  30405. * @default
  30406. */
  30407. this.hitContext = null;
  30408. /**
  30409. * An array of callbacks that will be fired every time the activePointer receives a move event from the DOM.
  30410. * To add a callback to this array please use `Input.addMoveCallback`.
  30411. * @property {array} moveCallbacks
  30412. * @protected
  30413. */
  30414. this.moveCallbacks = [];
  30415. /**
  30416. * @property {function} customCandidateHandler - See Input.setInteractiveCandidateHandler.
  30417. * @private
  30418. */
  30419. this.customCandidateHandler = null;
  30420. /**
  30421. * @property {object} customCandidateHandlerContext - See Input.setInteractiveCandidateHandler.
  30422. * @private
  30423. */
  30424. this.customCandidateHandlerContext = null;
  30425. /**
  30426. * @property {number} pollRate - How often should the input pointers be checked for updates? A value of 0 means every single frame (60fps); a value of 1 means every other frame (30fps) and so on.
  30427. * @default
  30428. */
  30429. this.pollRate = 0;
  30430. /**
  30431. * When enabled, input (eg. Keyboard, Mouse, Touch) will be processed - as long as the individual sources are enabled themselves.
  30432. *
  30433. * When not enabled, _all_ input sources are ignored. To disable just one type of input; for example, the Mouse, use `input.mouse.enabled = false`.
  30434. * @property {boolean} enabled
  30435. * @default
  30436. */
  30437. this.enabled = true;
  30438. /**
  30439. * @property {number} multiInputOverride - Controls the expected behavior when using a mouse and touch together on a multi-input device.
  30440. * @default
  30441. */
  30442. this.multiInputOverride = Phaser.Input.MOUSE_TOUCH_COMBINE;
  30443. /**
  30444. * @property {Phaser.Point} position - A point object representing the current position of the Pointer.
  30445. * @default
  30446. */
  30447. this.position = null;
  30448. /**
  30449. * @property {Phaser.Point} speed - A point object representing the speed of the Pointer. Only really useful in single Pointer games; otherwise see the Pointer objects directly.
  30450. */
  30451. this.speed = null;
  30452. /**
  30453. * A Circle object centered on the x/y screen coordinates of the Input.
  30454. * Default size of 44px (Apples recommended "finger tip" size) but can be changed to anything.
  30455. * @property {Phaser.Circle} circle
  30456. */
  30457. this.circle = null;
  30458. /**
  30459. * @property {Phaser.Point} scale - The scale by which all input coordinates are multiplied; calculated by the ScaleManager. In an un-scaled game the values will be x = 1 and y = 1.
  30460. */
  30461. this.scale = null;
  30462. /**
  30463. * @property {integer} maxPointers - The maximum number of Pointers allowed to be active at any one time. A value of -1 is only limited by the total number of pointers. For lots of games it's useful to set this to 1.
  30464. * @default -1 (Limited by total pointers.)
  30465. */
  30466. this.maxPointers = -1;
  30467. /**
  30468. * @property {number} tapRate - The number of milliseconds that the Pointer has to be pressed down and then released to be considered a tap or click.
  30469. * @default
  30470. */
  30471. this.tapRate = 200;
  30472. /**
  30473. * @property {number} doubleTapRate - The number of milliseconds between taps of the same Pointer for it to be considered a double tap / click.
  30474. * @default
  30475. */
  30476. this.doubleTapRate = 300;
  30477. /**
  30478. * @property {number} holdRate - The number of milliseconds that the Pointer has to be pressed down for it to fire a onHold event.
  30479. * @default
  30480. */
  30481. this.holdRate = 2000;
  30482. /**
  30483. * @property {number} justPressedRate - The number of milliseconds below which the Pointer is considered justPressed.
  30484. * @default
  30485. */
  30486. this.justPressedRate = 200;
  30487. /**
  30488. * @property {number} justReleasedRate - The number of milliseconds below which the Pointer is considered justReleased .
  30489. * @default
  30490. */
  30491. this.justReleasedRate = 200;
  30492. /**
  30493. * Sets if the Pointer objects should record a history of x/y coordinates they have passed through.
  30494. * The history is cleared each time the Pointer is pressed down.
  30495. * The history is updated at the rate specified in Input.pollRate
  30496. * @property {boolean} recordPointerHistory
  30497. * @default
  30498. */
  30499. this.recordPointerHistory = false;
  30500. /**
  30501. * @property {number} recordRate - The rate in milliseconds at which the Pointer objects should update their tracking history.
  30502. * @default
  30503. */
  30504. this.recordRate = 100;
  30505. /**
  30506. * The total number of entries that can be recorded into the Pointer objects tracking history.
  30507. * If the Pointer is tracking one event every 100ms; then a trackLimit of 100 would store the last 10 seconds worth of history.
  30508. * @property {number} recordLimit
  30509. * @default
  30510. */
  30511. this.recordLimit = 100;
  30512. /**
  30513. * @property {Phaser.Pointer} pointer1 - A Pointer object.
  30514. */
  30515. this.pointer1 = null;
  30516. /**
  30517. * @property {Phaser.Pointer} pointer2 - A Pointer object.
  30518. */
  30519. this.pointer2 = null;
  30520. /**
  30521. * @property {Phaser.Pointer} pointer3 - A Pointer object.
  30522. */
  30523. this.pointer3 = null;
  30524. /**
  30525. * @property {Phaser.Pointer} pointer4 - A Pointer object.
  30526. */
  30527. this.pointer4 = null;
  30528. /**
  30529. * @property {Phaser.Pointer} pointer5 - A Pointer object.
  30530. */
  30531. this.pointer5 = null;
  30532. /**
  30533. * @property {Phaser.Pointer} pointer6 - A Pointer object.
  30534. */
  30535. this.pointer6 = null;
  30536. /**
  30537. * @property {Phaser.Pointer} pointer7 - A Pointer object.
  30538. */
  30539. this.pointer7 = null;
  30540. /**
  30541. * @property {Phaser.Pointer} pointer8 - A Pointer object.
  30542. */
  30543. this.pointer8 = null;
  30544. /**
  30545. * @property {Phaser.Pointer} pointer9 - A Pointer object.
  30546. */
  30547. this.pointer9 = null;
  30548. /**
  30549. * @property {Phaser.Pointer} pointer10 - A Pointer object.
  30550. */
  30551. this.pointer10 = null;
  30552. /**
  30553. * An array of non-mouse pointers that have been added to the game.
  30554. * The properties `pointer1..N` are aliases for `pointers[0..N-1]`.
  30555. * @property {Phaser.Pointer[]} pointers
  30556. * @public
  30557. * @readonly
  30558. */
  30559. this.pointers = [];
  30560. /**
  30561. * The most recently active Pointer object.
  30562. *
  30563. * When you've limited max pointers to 1 this will accurately be either the first finger touched or mouse.
  30564. *
  30565. * @property {Phaser.Pointer} activePointer
  30566. */
  30567. this.activePointer = null;
  30568. /**
  30569. * The mouse has its own unique Phaser.Pointer object which you can use if making a desktop specific game.
  30570. *
  30571. * @property {Pointer} mousePointer
  30572. */
  30573. this.mousePointer = null;
  30574. /**
  30575. * The Mouse Input manager.
  30576. *
  30577. * You should not usually access this manager directly, but instead use Input.mousePointer or Input.activePointer
  30578. * which normalizes all the input values for you, regardless of browser.
  30579. *
  30580. * @property {Phaser.Mouse} mouse
  30581. */
  30582. this.mouse = null;
  30583. /**
  30584. * The Keyboard Input manager.
  30585. *
  30586. * @property {Phaser.Keyboard} keyboard
  30587. */
  30588. this.keyboard = null;
  30589. /**
  30590. * The Touch Input manager.
  30591. *
  30592. * You should not usually access this manager directly, but instead use Input.activePointer
  30593. * which normalizes all the input values for you, regardless of browser.
  30594. *
  30595. * @property {Phaser.Touch} touch
  30596. */
  30597. this.touch = null;
  30598. /**
  30599. * The MSPointer Input manager.
  30600. *
  30601. * You should not usually access this manager directly, but instead use Input.activePointer
  30602. * which normalizes all the input values for you, regardless of browser.
  30603. *
  30604. * @property {Phaser.MSPointer} mspointer
  30605. */
  30606. this.mspointer = null;
  30607. /**
  30608. * The Gamepad Input manager.
  30609. *
  30610. * @property {Phaser.Gamepad} gamepad
  30611. */
  30612. this.gamepad = null;
  30613. /**
  30614. * If the Input Manager has been reset locked then all calls made to InputManager.reset,
  30615. * such as from a State change, are ignored.
  30616. * @property {boolean} resetLocked
  30617. * @default
  30618. */
  30619. this.resetLocked = false;
  30620. /**
  30621. * A Signal that is dispatched each time a pointer is pressed down.
  30622. * @property {Phaser.Signal} onDown
  30623. */
  30624. this.onDown = null;
  30625. /**
  30626. * A Signal that is dispatched each time a pointer is released.
  30627. * @property {Phaser.Signal} onUp
  30628. */
  30629. this.onUp = null;
  30630. /**
  30631. * A Signal that is dispatched each time a pointer is tapped.
  30632. * @property {Phaser.Signal} onTap
  30633. */
  30634. this.onTap = null;
  30635. /**
  30636. * A Signal that is dispatched each time a pointer is held down.
  30637. * @property {Phaser.Signal} onHold
  30638. */
  30639. this.onHold = null;
  30640. /**
  30641. * You can tell all Pointers to ignore any Game Object with a `priorityID` lower than this value.
  30642. * This is useful when stacking UI layers. Set to zero to disable.
  30643. * @property {number} minPriorityID
  30644. * @default
  30645. */
  30646. this.minPriorityID = 0;
  30647. /**
  30648. * A list of interactive objects. The InputHandler components add and remove themselves from this list.
  30649. * @property {Phaser.ArraySet} interactiveItems
  30650. */
  30651. this.interactiveItems = new Phaser.ArraySet();
  30652. /**
  30653. * @property {Phaser.Point} _localPoint - Internal cache var.
  30654. * @private
  30655. */
  30656. this._localPoint = new Phaser.Point();
  30657. /**
  30658. * @property {number} _pollCounter - Internal var holding the current poll counter.
  30659. * @private
  30660. */
  30661. this._pollCounter = 0;
  30662. /**
  30663. * @property {Phaser.Point} _oldPosition - A point object representing the previous position of the Pointer.
  30664. * @private
  30665. */
  30666. this._oldPosition = null;
  30667. /**
  30668. * @property {number} _x - x coordinate of the most recent Pointer event
  30669. * @private
  30670. */
  30671. this._x = 0;
  30672. /**
  30673. * @property {number} _y - Y coordinate of the most recent Pointer event
  30674. * @private
  30675. */
  30676. this._y = 0;
  30677. };
  30678. /**
  30679. * @constant
  30680. * @type {number}
  30681. */
  30682. Phaser.Input.MOUSE_OVERRIDES_TOUCH = 0;
  30683. /**
  30684. * @constant
  30685. * @type {number}
  30686. */
  30687. Phaser.Input.TOUCH_OVERRIDES_MOUSE = 1;
  30688. /**
  30689. * @constant
  30690. * @type {number}
  30691. */
  30692. Phaser.Input.MOUSE_TOUCH_COMBINE = 2;
  30693. /**
  30694. * The maximum number of pointers that can be added. This excludes the mouse pointer.
  30695. * @constant
  30696. * @type {integer}
  30697. */
  30698. Phaser.Input.MAX_POINTERS = 10;
  30699. Phaser.Input.prototype = {
  30700. /**
  30701. * Starts the Input Manager running.
  30702. *
  30703. * @method Phaser.Input#boot
  30704. * @protected
  30705. */
  30706. boot: function () {
  30707. this.mousePointer = new Phaser.Pointer(this.game, 0, Phaser.PointerMode.CURSOR);
  30708. this.addPointer();
  30709. this.addPointer();
  30710. this.mouse = new Phaser.Mouse(this.game);
  30711. this.touch = new Phaser.Touch(this.game);
  30712. this.mspointer = new Phaser.MSPointer(this.game);
  30713. if (Phaser.Keyboard)
  30714. {
  30715. this.keyboard = new Phaser.Keyboard(this.game);
  30716. }
  30717. if (Phaser.Gamepad)
  30718. {
  30719. this.gamepad = new Phaser.Gamepad(this.game);
  30720. }
  30721. this.onDown = new Phaser.Signal();
  30722. this.onUp = new Phaser.Signal();
  30723. this.onTap = new Phaser.Signal();
  30724. this.onHold = new Phaser.Signal();
  30725. this.scale = new Phaser.Point(1, 1);
  30726. this.speed = new Phaser.Point();
  30727. this.position = new Phaser.Point();
  30728. this._oldPosition = new Phaser.Point();
  30729. this.circle = new Phaser.Circle(0, 0, 44);
  30730. this.activePointer = this.mousePointer;
  30731. this.hitCanvas = PIXI.CanvasPool.create(this, 1, 1);
  30732. this.hitContext = this.hitCanvas.getContext('2d');
  30733. this.mouse.start();
  30734. this.touch.start();
  30735. this.mspointer.start();
  30736. this.mousePointer.active = true;
  30737. if (this.keyboard)
  30738. {
  30739. this.keyboard.start();
  30740. }
  30741. var _this = this;
  30742. this._onClickTrampoline = function (event) {
  30743. _this.onClickTrampoline(event);
  30744. };
  30745. this.game.canvas.addEventListener('click', this._onClickTrampoline, false);
  30746. },
  30747. /**
  30748. * Stops all of the Input Managers from running.
  30749. *
  30750. * @method Phaser.Input#destroy
  30751. */
  30752. destroy: function () {
  30753. this.mouse.stop();
  30754. this.touch.stop();
  30755. this.mspointer.stop();
  30756. if (this.keyboard)
  30757. {
  30758. this.keyboard.stop();
  30759. }
  30760. if (this.gamepad)
  30761. {
  30762. this.gamepad.stop();
  30763. }
  30764. this.moveCallbacks = [];
  30765. PIXI.CanvasPool.remove(this);
  30766. this.game.canvas.removeEventListener('click', this._onClickTrampoline);
  30767. },
  30768. /**
  30769. * Adds a callback that is fired every time `Pointer.processInteractiveObjects` is called.
  30770. * The purpose of `processInteractiveObjects` is to work out which Game Object the Pointer is going to
  30771. * interact with. It works by polling all of the valid game objects, and then slowly discounting those
  30772. * that don't meet the criteria (i.e. they aren't under the Pointer, are disabled, invisible, etc).
  30773. *
  30774. * Eventually a short-list of 'candidates' is created. These are all of the Game Objects which are valid
  30775. * for input and overlap with the Pointer. If you need fine-grained control over which of the items is
  30776. * selected then you can use this callback to do so.
  30777. *
  30778. * The callback will be sent 3 parameters:
  30779. *
  30780. * 1) A reference to the Phaser.Pointer object that is processing the Items.
  30781. * 2) An array containing all potential interactive candidates. This is an array of `InputHandler` objects, not Sprites.
  30782. * 3) The current 'favorite' candidate, based on its priorityID and position in the display list.
  30783. *
  30784. * Your callback MUST return one of the candidates sent to it.
  30785. *
  30786. * @method Phaser.Input#setInteractiveCandidateHandler
  30787. * @param {function} callback - The callback that will be called each time `Pointer.processInteractiveObjects` is called. Set to `null` to disable.
  30788. * @param {object} context - The context in which the callback will be called.
  30789. */
  30790. setInteractiveCandidateHandler: function (callback, context) {
  30791. this.customCandidateHandler = callback;
  30792. this.customCandidateHandlerContext = context;
  30793. },
  30794. /**
  30795. * Adds a callback that is fired every time the activePointer receives a DOM move event such as a mousemove or touchmove.
  30796. *
  30797. * The callback will be sent 4 parameters:
  30798. *
  30799. * A reference to the Phaser.Pointer object that moved,
  30800. * The x position of the pointer,
  30801. * The y position,
  30802. * A boolean indicating if the movement was the result of a 'click' event (such as a mouse click or touch down).
  30803. *
  30804. * It will be called every time the activePointer moves, which in a multi-touch game can be a lot of times, so this is best
  30805. * to only use if you've limited input to a single pointer (i.e. mouse or touch).
  30806. *
  30807. * The callback is added to the Phaser.Input.moveCallbacks array and should be removed with Phaser.Input.deleteMoveCallback.
  30808. *
  30809. * @method Phaser.Input#addMoveCallback
  30810. * @param {function} callback - The callback that will be called each time the activePointer receives a DOM move event.
  30811. * @param {object} context - The context in which the callback will be called.
  30812. */
  30813. addMoveCallback: function (callback, context) {
  30814. this.moveCallbacks.push({ callback: callback, context: context });
  30815. },
  30816. /**
  30817. * Removes the callback from the Phaser.Input.moveCallbacks array.
  30818. *
  30819. * @method Phaser.Input#deleteMoveCallback
  30820. * @param {function} callback - The callback to be removed.
  30821. * @param {object} context - The context in which the callback exists.
  30822. */
  30823. deleteMoveCallback: function (callback, context) {
  30824. var i = this.moveCallbacks.length;
  30825. while (i--)
  30826. {
  30827. if (this.moveCallbacks[i].callback === callback && this.moveCallbacks[i].context === context)
  30828. {
  30829. this.moveCallbacks.splice(i, 1);
  30830. return;
  30831. }
  30832. }
  30833. },
  30834. /**
  30835. * Add a new Pointer object to the Input Manager.
  30836. * By default Input creates 3 pointer objects: `mousePointer` (not include in part of general pointer pool), `pointer1` and `pointer2`.
  30837. * This method adds an additional pointer, up to a maximum of Phaser.Input.MAX_POINTERS (default of 10).
  30838. *
  30839. * @method Phaser.Input#addPointer
  30840. * @return {Phaser.Pointer|null} The new Pointer object that was created; null if a new pointer could not be added.
  30841. */
  30842. addPointer: function () {
  30843. if (this.pointers.length >= Phaser.Input.MAX_POINTERS)
  30844. {
  30845. console.warn("Phaser.Input.addPointer: Maximum limit of " + Phaser.Input.MAX_POINTERS + " pointers reached.");
  30846. return null;
  30847. }
  30848. var id = this.pointers.length + 1;
  30849. var pointer = new Phaser.Pointer(this.game, id, Phaser.PointerMode.TOUCH);
  30850. this.pointers.push(pointer);
  30851. this['pointer' + id] = pointer;
  30852. return pointer;
  30853. },
  30854. /**
  30855. * Updates the Input Manager. Called by the core Game loop.
  30856. *
  30857. * @method Phaser.Input#update
  30858. * @protected
  30859. */
  30860. update: function () {
  30861. if (this.keyboard)
  30862. {
  30863. this.keyboard.update();
  30864. }
  30865. if (this.pollRate > 0 && this._pollCounter < this.pollRate)
  30866. {
  30867. this._pollCounter++;
  30868. return;
  30869. }
  30870. this.speed.x = this.position.x - this._oldPosition.x;
  30871. this.speed.y = this.position.y - this._oldPosition.y;
  30872. this._oldPosition.copyFrom(this.position);
  30873. this.mousePointer.update();
  30874. if (this.gamepad && this.gamepad.active)
  30875. {
  30876. this.gamepad.update();
  30877. }
  30878. for (var i = 0; i < this.pointers.length; i++)
  30879. {
  30880. this.pointers[i].update();
  30881. }
  30882. this._pollCounter = 0;
  30883. },
  30884. /**
  30885. * Reset all of the Pointers and Input states.
  30886. *
  30887. * The optional `hard` parameter will reset any events or callbacks that may be bound.
  30888. * Input.reset is called automatically during a State change or if a game loses focus / visibility.
  30889. * To control control the reset manually set {@link Phaser.InputManager.resetLocked} to `true`.
  30890. *
  30891. * @method Phaser.Input#reset
  30892. * @public
  30893. * @param {boolean} [hard=false] - A soft reset won't reset any events or callbacks that are bound. A hard reset will.
  30894. */
  30895. reset: function (hard) {
  30896. if (!this.game.isBooted || this.resetLocked)
  30897. {
  30898. return;
  30899. }
  30900. if (hard === undefined) { hard = false; }
  30901. this.mousePointer.reset();
  30902. if (this.keyboard)
  30903. {
  30904. this.keyboard.reset(hard);
  30905. }
  30906. if (this.gamepad)
  30907. {
  30908. this.gamepad.reset();
  30909. }
  30910. for (var i = 0; i < this.pointers.length; i++)
  30911. {
  30912. this.pointers[i].reset();
  30913. }
  30914. if (this.game.canvas.style.cursor !== 'none')
  30915. {
  30916. this.game.canvas.style.cursor = 'inherit';
  30917. }
  30918. if (hard)
  30919. {
  30920. this.onDown.dispose();
  30921. this.onUp.dispose();
  30922. this.onTap.dispose();
  30923. this.onHold.dispose();
  30924. this.onDown = new Phaser.Signal();
  30925. this.onUp = new Phaser.Signal();
  30926. this.onTap = new Phaser.Signal();
  30927. this.onHold = new Phaser.Signal();
  30928. this.moveCallbacks = [];
  30929. }
  30930. this._pollCounter = 0;
  30931. },
  30932. /**
  30933. * Resets the speed and old position properties.
  30934. *
  30935. * @method Phaser.Input#resetSpeed
  30936. * @param {number} x - Sets the oldPosition.x value.
  30937. * @param {number} y - Sets the oldPosition.y value.
  30938. */
  30939. resetSpeed: function (x, y) {
  30940. this._oldPosition.setTo(x, y);
  30941. this.speed.setTo(0, 0);
  30942. },
  30943. /**
  30944. * Find the first free Pointer object and start it, passing in the event data.
  30945. * This is called automatically by Phaser.Touch and Phaser.MSPointer.
  30946. *
  30947. * @method Phaser.Input#startPointer
  30948. * @protected
  30949. * @param {any} event - The event data from the Touch event.
  30950. * @return {Phaser.Pointer} The Pointer object that was started or null if no Pointer object is available.
  30951. */
  30952. startPointer: function (event) {
  30953. if (this.maxPointers >= 0 && this.countActivePointers(this.maxPointers) >= this.maxPointers)
  30954. {
  30955. return null;
  30956. }
  30957. if (!this.pointer1.active)
  30958. {
  30959. return this.pointer1.start(event);
  30960. }
  30961. if (!this.pointer2.active)
  30962. {
  30963. return this.pointer2.start(event);
  30964. }
  30965. for (var i = 2; i < this.pointers.length; i++)
  30966. {
  30967. var pointer = this.pointers[i];
  30968. if (!pointer.active)
  30969. {
  30970. return pointer.start(event);
  30971. }
  30972. }
  30973. return null;
  30974. },
  30975. /**
  30976. * Updates the matching Pointer object, passing in the event data.
  30977. * This is called automatically and should not normally need to be invoked.
  30978. *
  30979. * @method Phaser.Input#updatePointer
  30980. * @protected
  30981. * @param {any} event - The event data from the Touch event.
  30982. * @return {Phaser.Pointer} The Pointer object that was updated; null if no pointer was updated.
  30983. */
  30984. updatePointer: function (event) {
  30985. if (this.pointer1.active && this.pointer1.identifier === event.identifier)
  30986. {
  30987. return this.pointer1.move(event);
  30988. }
  30989. if (this.pointer2.active && this.pointer2.identifier === event.identifier)
  30990. {
  30991. return this.pointer2.move(event);
  30992. }
  30993. for (var i = 2; i < this.pointers.length; i++)
  30994. {
  30995. var pointer = this.pointers[i];
  30996. if (pointer.active && pointer.identifier === event.identifier)
  30997. {
  30998. return pointer.move(event);
  30999. }
  31000. }
  31001. return null;
  31002. },
  31003. /**
  31004. * Stops the matching Pointer object, passing in the event data.
  31005. *
  31006. * @method Phaser.Input#stopPointer
  31007. * @protected
  31008. * @param {any} event - The event data from the Touch event.
  31009. * @return {Phaser.Pointer} The Pointer object that was stopped or null if no Pointer object is available.
  31010. */
  31011. stopPointer: function (event) {
  31012. if (this.pointer1.active && this.pointer1.identifier === event.identifier)
  31013. {
  31014. return this.pointer1.stop(event);
  31015. }
  31016. if (this.pointer2.active && this.pointer2.identifier === event.identifier)
  31017. {
  31018. return this.pointer2.stop(event);
  31019. }
  31020. for (var i = 2; i < this.pointers.length; i++)
  31021. {
  31022. var pointer = this.pointers[i];
  31023. if (pointer.active && pointer.identifier === event.identifier)
  31024. {
  31025. return pointer.stop(event);
  31026. }
  31027. }
  31028. return null;
  31029. },
  31030. /**
  31031. * Returns the total number of active pointers, not exceeding the specified limit
  31032. *
  31033. * @name Phaser.Input#countActivePointers
  31034. * @private
  31035. * @property {integer} [limit=(max pointers)] - Stop counting after this.
  31036. * @return {integer} The number of active pointers, or limit - whichever is less.
  31037. */
  31038. countActivePointers: function (limit) {
  31039. if (limit === undefined) { limit = this.pointers.length; }
  31040. var count = limit;
  31041. for (var i = 0; i < this.pointers.length && count > 0; i++)
  31042. {
  31043. var pointer = this.pointers[i];
  31044. if (pointer.active)
  31045. {
  31046. count--;
  31047. }
  31048. }
  31049. return (limit - count);
  31050. },
  31051. /**
  31052. * Get the first Pointer with the given active state.
  31053. *
  31054. * @method Phaser.Input#getPointer
  31055. * @param {boolean} [isActive=false] - The state the Pointer should be in - active or inactive?
  31056. * @return {Phaser.Pointer} A Pointer object or null if no Pointer object matches the requested state.
  31057. */
  31058. getPointer: function (isActive) {
  31059. if (isActive === undefined) { isActive = false; }
  31060. for (var i = 0; i < this.pointers.length; i++)
  31061. {
  31062. var pointer = this.pointers[i];
  31063. if (pointer.active === isActive)
  31064. {
  31065. return pointer;
  31066. }
  31067. }
  31068. return null;
  31069. },
  31070. /**
  31071. * Get the Pointer object whos `identifier` property matches the given identifier value.
  31072. *
  31073. * The identifier property is not set until the Pointer has been used at least once, as its populated by the DOM event.
  31074. * Also it can change every time you press the pointer down, and is not fixed once set.
  31075. * Note: Not all browsers set the identifier property and it's not part of the W3C spec, so you may need getPointerFromId instead.
  31076. *
  31077. * @method Phaser.Input#getPointerFromIdentifier
  31078. * @param {number} identifier - The Pointer.identifier value to search for.
  31079. * @return {Phaser.Pointer} A Pointer object or null if no Pointer object matches the requested identifier.
  31080. */
  31081. getPointerFromIdentifier: function (identifier) {
  31082. for (var i = 0; i < this.pointers.length; i++)
  31083. {
  31084. var pointer = this.pointers[i];
  31085. if (pointer.identifier === identifier)
  31086. {
  31087. return pointer;
  31088. }
  31089. }
  31090. return null;
  31091. },
  31092. /**
  31093. * Get the Pointer object whos `pointerId` property matches the given value.
  31094. *
  31095. * The pointerId property is not set until the Pointer has been used at least once, as its populated by the DOM event.
  31096. * Also it can change every time you press the pointer down if the browser recycles it.
  31097. *
  31098. * @method Phaser.Input#getPointerFromId
  31099. * @param {number} pointerId - The `pointerId` (not 'id') value to search for.
  31100. * @return {Phaser.Pointer} A Pointer object or null if no Pointer object matches the requested identifier.
  31101. */
  31102. getPointerFromId: function (pointerId) {
  31103. for (var i = 0; i < this.pointers.length; i++)
  31104. {
  31105. var pointer = this.pointers[i];
  31106. if (pointer.pointerId === pointerId)
  31107. {
  31108. return pointer;
  31109. }
  31110. }
  31111. return null;
  31112. },
  31113. /**
  31114. * This will return the local coordinates of the specified displayObject based on the given Pointer.
  31115. *
  31116. * @method Phaser.Input#getLocalPosition
  31117. * @param {Phaser.Sprite|Phaser.Image} displayObject - The DisplayObject to get the local coordinates for.
  31118. * @param {Phaser.Pointer} pointer - The Pointer to use in the check against the displayObject.
  31119. * @return {Phaser.Point} A point containing the coordinates of the Pointer position relative to the DisplayObject.
  31120. */
  31121. getLocalPosition: function (displayObject, pointer, output) {
  31122. if (output === undefined) { output = new Phaser.Point(); }
  31123. var wt = displayObject.worldTransform;
  31124. var id = 1 / (wt.a * wt.d + wt.c * -wt.b);
  31125. return output.setTo(
  31126. wt.d * id * pointer.x + -wt.c * id * pointer.y + (wt.ty * wt.c - wt.tx * wt.d) * id,
  31127. wt.a * id * pointer.y + -wt.b * id * pointer.x + (-wt.ty * wt.a + wt.tx * wt.b) * id
  31128. );
  31129. },
  31130. /**
  31131. * Tests if the pointer hits the given object.
  31132. *
  31133. * @method Phaser.Input#hitTest
  31134. * @param {DisplayObject} displayObject - The displayObject to test for a hit.
  31135. * @param {Phaser.Pointer} pointer - The pointer to use for the test.
  31136. * @param {Phaser.Point} localPoint - The local translated point.
  31137. */
  31138. hitTest: function (displayObject, pointer, localPoint) {
  31139. if (!displayObject.worldVisible)
  31140. {
  31141. return false;
  31142. }
  31143. this.getLocalPosition(displayObject, pointer, this._localPoint);
  31144. localPoint.copyFrom(this._localPoint);
  31145. if (displayObject.hitArea && displayObject.hitArea.contains)
  31146. {
  31147. return (displayObject.hitArea.contains(this._localPoint.x, this._localPoint.y));
  31148. }
  31149. else if (displayObject instanceof Phaser.TileSprite)
  31150. {
  31151. var width = displayObject.width;
  31152. var height = displayObject.height;
  31153. var x1 = -width * displayObject.anchor.x;
  31154. if (this._localPoint.x >= x1 && this._localPoint.x < x1 + width)
  31155. {
  31156. var y1 = -height * displayObject.anchor.y;
  31157. if (this._localPoint.y >= y1 && this._localPoint.y < y1 + height)
  31158. {
  31159. return true;
  31160. }
  31161. }
  31162. }
  31163. else if (displayObject instanceof PIXI.Sprite)
  31164. {
  31165. var width = displayObject.texture.frame.width;
  31166. var height = displayObject.texture.frame.height;
  31167. var x1 = -width * displayObject.anchor.x;
  31168. if (this._localPoint.x >= x1 && this._localPoint.x < x1 + width)
  31169. {
  31170. var y1 = -height * displayObject.anchor.y;
  31171. if (this._localPoint.y >= y1 && this._localPoint.y < y1 + height)
  31172. {
  31173. return true;
  31174. }
  31175. }
  31176. }
  31177. else if (displayObject instanceof Phaser.Graphics)
  31178. {
  31179. for (var i = 0; i < displayObject.graphicsData.length; i++)
  31180. {
  31181. var data = displayObject.graphicsData[i];
  31182. if (!data.fill)
  31183. {
  31184. continue;
  31185. }
  31186. // Only deal with fills..
  31187. if (data.shape && data.shape.contains(this._localPoint.x, this._localPoint.y))
  31188. {
  31189. return true;
  31190. }
  31191. }
  31192. }
  31193. // Didn't hit the parent, does it have any children?
  31194. for (var i = 0; i < displayObject.children.length; i++)
  31195. {
  31196. if (this.hitTest(displayObject.children[i], pointer, localPoint))
  31197. {
  31198. return true;
  31199. }
  31200. }
  31201. return false;
  31202. },
  31203. /**
  31204. * Used for click trampolines. See {@link Phaser.Pointer.addClickTrampoline}.
  31205. *
  31206. * @method Phaser.Input#onClickTrampoline
  31207. * @private
  31208. */
  31209. onClickTrampoline: function () {
  31210. // It might not always be the active pointer, but this does work on
  31211. // Desktop browsers (read: IE) with Mouse or MSPointer input.
  31212. this.activePointer.processClickTrampolines();
  31213. }
  31214. };
  31215. Phaser.Input.prototype.constructor = Phaser.Input;
  31216. /**
  31217. * The X coordinate of the most recently active pointer.
  31218. * This value takes game scaling into account automatically. See Pointer.screenX/clientX for source values.
  31219. * @name Phaser.Input#x
  31220. * @property {number} x
  31221. */
  31222. Object.defineProperty(Phaser.Input.prototype, "x", {
  31223. get: function () {
  31224. return this._x;
  31225. },
  31226. set: function (value) {
  31227. this._x = Math.floor(value);
  31228. }
  31229. });
  31230. /**
  31231. * The Y coordinate of the most recently active pointer.
  31232. * This value takes game scaling into account automatically. See Pointer.screenY/clientY for source values.
  31233. * @name Phaser.Input#y
  31234. * @property {number} y
  31235. */
  31236. Object.defineProperty(Phaser.Input.prototype, "y", {
  31237. get: function () {
  31238. return this._y;
  31239. },
  31240. set: function (value) {
  31241. this._y = Math.floor(value);
  31242. }
  31243. });
  31244. /**
  31245. * True if the Input is currently poll rate locked.
  31246. * @name Phaser.Input#pollLocked
  31247. * @property {boolean} pollLocked
  31248. * @readonly
  31249. */
  31250. Object.defineProperty(Phaser.Input.prototype, "pollLocked", {
  31251. get: function () {
  31252. return (this.pollRate > 0 && this._pollCounter < this.pollRate);
  31253. }
  31254. });
  31255. /**
  31256. * The total number of inactive Pointers.
  31257. * @name Phaser.Input#totalInactivePointers
  31258. * @property {number} totalInactivePointers
  31259. * @readonly
  31260. */
  31261. Object.defineProperty(Phaser.Input.prototype, "totalInactivePointers", {
  31262. get: function () {
  31263. return this.pointers.length - this.countActivePointers();
  31264. }
  31265. });
  31266. /**
  31267. * The total number of active Pointers, not counting the mouse pointer.
  31268. * @name Phaser.Input#totalActivePointers
  31269. * @property {integers} totalActivePointers
  31270. * @readonly
  31271. */
  31272. Object.defineProperty(Phaser.Input.prototype, "totalActivePointers", {
  31273. get: function () {
  31274. return this.countActivePointers();
  31275. }
  31276. });
  31277. /**
  31278. * The world X coordinate of the most recently active pointer.
  31279. * @name Phaser.Input#worldX
  31280. * @property {number} worldX - The world X coordinate of the most recently active pointer.
  31281. * @readonly
  31282. */
  31283. Object.defineProperty(Phaser.Input.prototype, "worldX", {
  31284. get: function () {
  31285. return this.game.camera.view.x + this.x;
  31286. }
  31287. });
  31288. /**
  31289. * The world Y coordinate of the most recently active pointer.
  31290. * @name Phaser.Input#worldY
  31291. * @property {number} worldY - The world Y coordinate of the most recently active pointer.
  31292. * @readonly
  31293. */
  31294. Object.defineProperty(Phaser.Input.prototype, "worldY", {
  31295. get: function () {
  31296. return this.game.camera.view.y + this.y;
  31297. }
  31298. });
  31299. /**
  31300. * @author Richard Davey <rich@photonstorm.com>
  31301. * @copyright 2016 Photon Storm Ltd.
  31302. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  31303. */
  31304. /**
  31305. * The Mouse class is responsible for handling all aspects of mouse interaction with the browser.
  31306. *
  31307. * It captures and processes mouse events that happen on the game canvas object.
  31308. * It also adds a single `mouseup` listener to `window` which is used to capture the mouse being released
  31309. * when not over the game.
  31310. *
  31311. * You should not normally access this class directly, but instead use a Phaser.Pointer object
  31312. * which normalises all game input for you, including accurate button handling.
  31313. *
  31314. * @class Phaser.Mouse
  31315. * @constructor
  31316. * @param {Phaser.Game} game - A reference to the currently running game.
  31317. */
  31318. Phaser.Mouse = function (game) {
  31319. /**
  31320. * @property {Phaser.Game} game - A reference to the currently running game.
  31321. */
  31322. this.game = game;
  31323. /**
  31324. * @property {Phaser.Input} input - A reference to the Phaser Input Manager.
  31325. * @protected
  31326. */
  31327. this.input = game.input;
  31328. /**
  31329. * @property {object} callbackContext - The context under which callbacks are called.
  31330. */
  31331. this.callbackContext = this.game;
  31332. /**
  31333. * @property {function} mouseDownCallback - A callback that can be fired when the mouse is pressed down.
  31334. */
  31335. this.mouseDownCallback = null;
  31336. /**
  31337. * @property {function} mouseUpCallback - A callback that can be fired when the mouse is released from a pressed down state.
  31338. */
  31339. this.mouseUpCallback = null;
  31340. /**
  31341. * @property {function} mouseOutCallback - A callback that can be fired when the mouse is no longer over the game canvas.
  31342. */
  31343. this.mouseOutCallback = null;
  31344. /**
  31345. * @property {function} mouseOverCallback - A callback that can be fired when the mouse enters the game canvas (usually after a mouseout).
  31346. */
  31347. this.mouseOverCallback = null;
  31348. /**
  31349. * @property {function} mouseWheelCallback - A callback that can be fired when the mousewheel is used.
  31350. */
  31351. this.mouseWheelCallback = null;
  31352. /**
  31353. * @property {boolean} capture - If true the DOM mouse events will have event.preventDefault applied to them, if false they will propagate fully.
  31354. */
  31355. this.capture = false;
  31356. /**
  31357. * This property was removed in Phaser 2.4 and should no longer be used.
  31358. * Instead please see the Pointer button properties such as `Pointer.leftButton`, `Pointer.rightButton` and so on.
  31359. * Or Pointer.button holds the DOM event button value if you require that.
  31360. * @property {number} button
  31361. * @default
  31362. */
  31363. this.button = -1;
  31364. /**
  31365. * The direction of the _last_ mousewheel usage 1 for up -1 for down.
  31366. * @property {number} wheelDelta
  31367. */
  31368. this.wheelDelta = 0;
  31369. /**
  31370. * Mouse input will only be processed if enabled.
  31371. * @property {boolean} enabled
  31372. * @default
  31373. */
  31374. this.enabled = true;
  31375. /**
  31376. * @property {boolean} locked - If the mouse has been Pointer Locked successfully this will be set to true.
  31377. * @default
  31378. */
  31379. this.locked = false;
  31380. /**
  31381. * @property {boolean} stopOnGameOut - If true Pointer.stop will be called if the mouse leaves the game canvas.
  31382. * @default
  31383. */
  31384. this.stopOnGameOut = false;
  31385. /**
  31386. * @property {Phaser.Signal} pointerLock - This event is dispatched when the browser enters or leaves pointer lock state.
  31387. * @default
  31388. */
  31389. this.pointerLock = new Phaser.Signal();
  31390. /**
  31391. * The browser mouse DOM event. Will be null if no mouse event has ever been received.
  31392. * Access this property only inside a Mouse event handler and do not keep references to it.
  31393. * @property {MouseEvent|null} event
  31394. * @default
  31395. */
  31396. this.event = null;
  31397. /**
  31398. * @property {function} _onMouseDown - Internal event handler reference.
  31399. * @private
  31400. */
  31401. this._onMouseDown = null;
  31402. /**
  31403. * @property {function} _onMouseMove - Internal event handler reference.
  31404. * @private
  31405. */
  31406. this._onMouseMove = null;
  31407. /**
  31408. * @property {function} _onMouseUp - Internal event handler reference.
  31409. * @private
  31410. */
  31411. this._onMouseUp = null;
  31412. /**
  31413. * @property {function} _onMouseOut - Internal event handler reference.
  31414. * @private
  31415. */
  31416. this._onMouseOut = null;
  31417. /**
  31418. * @property {function} _onMouseOver - Internal event handler reference.
  31419. * @private
  31420. */
  31421. this._onMouseOver = null;
  31422. /**
  31423. * @property {function} _onMouseWheel - Internal event handler reference.
  31424. * @private
  31425. */
  31426. this._onMouseWheel = null;
  31427. /**
  31428. * Wheel proxy event object, if required. Shared for all wheel events for this mouse.
  31429. * @property {Phaser.Mouse~WheelEventProxy} _wheelEvent
  31430. * @private
  31431. */
  31432. this._wheelEvent = null;
  31433. };
  31434. /**
  31435. * @constant
  31436. * @type {number}
  31437. */
  31438. Phaser.Mouse.NO_BUTTON = -1;
  31439. /**
  31440. * @constant
  31441. * @type {number}
  31442. */
  31443. Phaser.Mouse.LEFT_BUTTON = 0;
  31444. /**
  31445. * @constant
  31446. * @type {number}
  31447. */
  31448. Phaser.Mouse.MIDDLE_BUTTON = 1;
  31449. /**
  31450. * @constant
  31451. * @type {number}
  31452. */
  31453. Phaser.Mouse.RIGHT_BUTTON = 2;
  31454. /**
  31455. * @constant
  31456. * @type {number}
  31457. */
  31458. Phaser.Mouse.BACK_BUTTON = 3;
  31459. /**
  31460. * @constant
  31461. * @type {number}
  31462. */
  31463. Phaser.Mouse.FORWARD_BUTTON = 4;
  31464. /**
  31465. * @constant
  31466. * @type {number}
  31467. */
  31468. Phaser.Mouse.WHEEL_UP = 1;
  31469. /**
  31470. * @constant
  31471. * @type {number}
  31472. */
  31473. Phaser.Mouse.WHEEL_DOWN = -1;
  31474. Phaser.Mouse.prototype = {
  31475. /**
  31476. * Starts the event listeners running.
  31477. * @method Phaser.Mouse#start
  31478. */
  31479. start: function () {
  31480. if (this.game.device.android && this.game.device.chrome === false)
  31481. {
  31482. // Android stock browser fires mouse events even if you preventDefault on the touchStart, so ...
  31483. return;
  31484. }
  31485. if (this._onMouseDown !== null)
  31486. {
  31487. // Avoid setting multiple listeners
  31488. return;
  31489. }
  31490. var _this = this;
  31491. this._onMouseDown = function (event) {
  31492. return _this.onMouseDown(event);
  31493. };
  31494. this._onMouseMove = function (event) {
  31495. return _this.onMouseMove(event);
  31496. };
  31497. this._onMouseUp = function (event) {
  31498. return _this.onMouseUp(event);
  31499. };
  31500. this._onMouseUpGlobal = function (event) {
  31501. return _this.onMouseUpGlobal(event);
  31502. };
  31503. this._onMouseOutGlobal = function (event) {
  31504. return _this.onMouseOutGlobal(event);
  31505. };
  31506. this._onMouseOut = function (event) {
  31507. return _this.onMouseOut(event);
  31508. };
  31509. this._onMouseOver = function (event) {
  31510. return _this.onMouseOver(event);
  31511. };
  31512. this._onMouseWheel = function (event) {
  31513. return _this.onMouseWheel(event);
  31514. };
  31515. var canvas = this.game.canvas;
  31516. canvas.addEventListener('mousedown', this._onMouseDown, true);
  31517. canvas.addEventListener('mousemove', this._onMouseMove, true);
  31518. canvas.addEventListener('mouseup', this._onMouseUp, true);
  31519. if (!this.game.device.cocoonJS)
  31520. {
  31521. window.addEventListener('mouseup', this._onMouseUpGlobal, true);
  31522. window.addEventListener('mouseout', this._onMouseOutGlobal, true);
  31523. canvas.addEventListener('mouseover', this._onMouseOver, true);
  31524. canvas.addEventListener('mouseout', this._onMouseOut, true);
  31525. }
  31526. var wheelEvent = this.game.device.wheelEvent;
  31527. if (wheelEvent)
  31528. {
  31529. canvas.addEventListener(wheelEvent, this._onMouseWheel, true);
  31530. if (wheelEvent === 'mousewheel')
  31531. {
  31532. this._wheelEvent = new WheelEventProxy(-1/40, 1);
  31533. }
  31534. else if (wheelEvent === 'DOMMouseScroll')
  31535. {
  31536. this._wheelEvent = new WheelEventProxy(1, 1);
  31537. }
  31538. }
  31539. },
  31540. /**
  31541. * The internal method that handles the mouse down event from the browser.
  31542. * @method Phaser.Mouse#onMouseDown
  31543. * @param {MouseEvent} event - The native event from the browser. This gets stored in Mouse.event.
  31544. */
  31545. onMouseDown: function (event) {
  31546. this.event = event;
  31547. if (this.capture)
  31548. {
  31549. event.preventDefault();
  31550. }
  31551. if (this.mouseDownCallback)
  31552. {
  31553. this.mouseDownCallback.call(this.callbackContext, event);
  31554. }
  31555. if (!this.input.enabled || !this.enabled)
  31556. {
  31557. return;
  31558. }
  31559. event['identifier'] = 0;
  31560. this.input.mousePointer.start(event);
  31561. },
  31562. /**
  31563. * The internal method that handles the mouse move event from the browser.
  31564. * @method Phaser.Mouse#onMouseMove
  31565. * @param {MouseEvent} event - The native event from the browser. This gets stored in Mouse.event.
  31566. */
  31567. onMouseMove: function (event) {
  31568. this.event = event;
  31569. if (this.capture)
  31570. {
  31571. event.preventDefault();
  31572. }
  31573. if (this.mouseMoveCallback)
  31574. {
  31575. this.mouseMoveCallback.call(this.callbackContext, event);
  31576. }
  31577. if (!this.input.enabled || !this.enabled)
  31578. {
  31579. return;
  31580. }
  31581. event['identifier'] = 0;
  31582. this.input.mousePointer.move(event);
  31583. },
  31584. /**
  31585. * The internal method that handles the mouse up event from the browser.
  31586. * @method Phaser.Mouse#onMouseUp
  31587. * @param {MouseEvent} event - The native event from the browser. This gets stored in Mouse.event.
  31588. */
  31589. onMouseUp: function (event) {
  31590. this.event = event;
  31591. if (this.capture)
  31592. {
  31593. event.preventDefault();
  31594. }
  31595. if (this.mouseUpCallback)
  31596. {
  31597. this.mouseUpCallback.call(this.callbackContext, event);
  31598. }
  31599. if (!this.input.enabled || !this.enabled)
  31600. {
  31601. return;
  31602. }
  31603. event['identifier'] = 0;
  31604. this.input.mousePointer.stop(event);
  31605. },
  31606. /**
  31607. * The internal method that handles the mouse up event from the window.
  31608. *
  31609. * @method Phaser.Mouse#onMouseUpGlobal
  31610. * @param {MouseEvent} event - The native event from the browser. This gets stored in Mouse.event.
  31611. */
  31612. onMouseUpGlobal: function (event) {
  31613. if (!this.input.mousePointer.withinGame)
  31614. {
  31615. if (this.mouseUpCallback)
  31616. {
  31617. this.mouseUpCallback.call(this.callbackContext, event);
  31618. }
  31619. event['identifier'] = 0;
  31620. this.input.mousePointer.stop(event);
  31621. }
  31622. },
  31623. /**
  31624. * The internal method that handles the mouse out event from the window.
  31625. *
  31626. * @method Phaser.Mouse#onMouseOutGlobal
  31627. * @param {MouseEvent} event - The native event from the browser. This gets stored in Mouse.event.
  31628. */
  31629. onMouseOutGlobal: function (event) {
  31630. this.event = event;
  31631. if (this.capture)
  31632. {
  31633. event.preventDefault();
  31634. }
  31635. this.input.mousePointer.withinGame = false;
  31636. if (!this.input.enabled || !this.enabled)
  31637. {
  31638. return;
  31639. }
  31640. // If we get a mouseout event from the window then basically
  31641. // something serious has gone down, usually along the lines of
  31642. // the browser opening a context-menu or similar.
  31643. // On OS X Chrome especially this is bad news, as it blocks
  31644. // us then getting a mouseup event, so we need to force that through.
  31645. //
  31646. // No matter what, we must cancel the left and right buttons
  31647. this.input.mousePointer.stop(event);
  31648. this.input.mousePointer.leftButton.stop(event);
  31649. this.input.mousePointer.rightButton.stop(event);
  31650. },
  31651. /**
  31652. * The internal method that handles the mouse out event from the browser.
  31653. *
  31654. * @method Phaser.Mouse#onMouseOut
  31655. * @param {MouseEvent} event - The native event from the browser. This gets stored in Mouse.event.
  31656. */
  31657. onMouseOut: function (event) {
  31658. this.event = event;
  31659. if (this.capture)
  31660. {
  31661. event.preventDefault();
  31662. }
  31663. this.input.mousePointer.withinGame = false;
  31664. if (this.mouseOutCallback)
  31665. {
  31666. this.mouseOutCallback.call(this.callbackContext, event);
  31667. }
  31668. if (!this.input.enabled || !this.enabled)
  31669. {
  31670. return;
  31671. }
  31672. if (this.stopOnGameOut)
  31673. {
  31674. event['identifier'] = 0;
  31675. this.input.mousePointer.stop(event);
  31676. }
  31677. },
  31678. /**
  31679. * The internal method that handles the mouse over event from the browser.
  31680. *
  31681. * @method Phaser.Mouse#onMouseOver
  31682. * @param {MouseEvent} event - The native event from the browser. This gets stored in Mouse.event.
  31683. */
  31684. onMouseOver: function (event) {
  31685. this.event = event;
  31686. if (this.capture)
  31687. {
  31688. event.preventDefault();
  31689. }
  31690. this.input.mousePointer.withinGame = true;
  31691. if (this.mouseOverCallback)
  31692. {
  31693. this.mouseOverCallback.call(this.callbackContext, event);
  31694. }
  31695. },
  31696. /**
  31697. * The internal method that handles the mouse wheel event from the browser.
  31698. *
  31699. * @method Phaser.Mouse#onMouseWheel
  31700. * @param {MouseEvent} event - The native event from the browser.
  31701. */
  31702. onMouseWheel: function (event) {
  31703. if (this._wheelEvent) {
  31704. event = this._wheelEvent.bindEvent(event);
  31705. }
  31706. this.event = event;
  31707. if (this.capture)
  31708. {
  31709. event.preventDefault();
  31710. }
  31711. // reverse detail for firefox
  31712. this.wheelDelta = Phaser.Math.clamp(-event.deltaY, -1, 1);
  31713. if (this.mouseWheelCallback)
  31714. {
  31715. this.mouseWheelCallback.call(this.callbackContext, event);
  31716. }
  31717. },
  31718. /**
  31719. * If the browser supports it you can request that the pointer be locked to the browser window.
  31720. * This is classically known as 'FPS controls', where the pointer can't leave the browser until the user presses an exit key.
  31721. * If the browser successfully enters a locked state the event Phaser.Mouse.pointerLock will be dispatched and the first parameter will be 'true'.
  31722. * @method Phaser.Mouse#requestPointerLock
  31723. */
  31724. requestPointerLock: function () {
  31725. if (this.game.device.pointerLock)
  31726. {
  31727. var element = this.game.canvas;
  31728. element.requestPointerLock = element.requestPointerLock || element.mozRequestPointerLock || element.webkitRequestPointerLock;
  31729. element.requestPointerLock();
  31730. var _this = this;
  31731. this._pointerLockChange = function (event) {
  31732. return _this.pointerLockChange(event);
  31733. };
  31734. document.addEventListener('pointerlockchange', this._pointerLockChange, true);
  31735. document.addEventListener('mozpointerlockchange', this._pointerLockChange, true);
  31736. document.addEventListener('webkitpointerlockchange', this._pointerLockChange, true);
  31737. }
  31738. },
  31739. /**
  31740. * Internal pointerLockChange handler.
  31741. *
  31742. * @method Phaser.Mouse#pointerLockChange
  31743. * @param {Event} event - The native event from the browser. This gets stored in Mouse.event.
  31744. */
  31745. pointerLockChange: function (event) {
  31746. var element = this.game.canvas;
  31747. if (document.pointerLockElement === element || document.mozPointerLockElement === element || document.webkitPointerLockElement === element)
  31748. {
  31749. // Pointer was successfully locked
  31750. this.locked = true;
  31751. this.pointerLock.dispatch(true, event);
  31752. }
  31753. else
  31754. {
  31755. // Pointer was unlocked
  31756. this.locked = false;
  31757. this.pointerLock.dispatch(false, event);
  31758. }
  31759. },
  31760. /**
  31761. * Internal release pointer lock handler.
  31762. * @method Phaser.Mouse#releasePointerLock
  31763. */
  31764. releasePointerLock: function () {
  31765. document.exitPointerLock = document.exitPointerLock || document.mozExitPointerLock || document.webkitExitPointerLock;
  31766. document.exitPointerLock();
  31767. document.removeEventListener('pointerlockchange', this._pointerLockChange, true);
  31768. document.removeEventListener('mozpointerlockchange', this._pointerLockChange, true);
  31769. document.removeEventListener('webkitpointerlockchange', this._pointerLockChange, true);
  31770. },
  31771. /**
  31772. * Stop the event listeners.
  31773. * @method Phaser.Mouse#stop
  31774. */
  31775. stop: function () {
  31776. var canvas = this.game.canvas;
  31777. canvas.removeEventListener('mousedown', this._onMouseDown, true);
  31778. canvas.removeEventListener('mousemove', this._onMouseMove, true);
  31779. canvas.removeEventListener('mouseup', this._onMouseUp, true);
  31780. canvas.removeEventListener('mouseover', this._onMouseOver, true);
  31781. canvas.removeEventListener('mouseout', this._onMouseOut, true);
  31782. var wheelEvent = this.game.device.wheelEvent;
  31783. if (wheelEvent)
  31784. {
  31785. canvas.removeEventListener(wheelEvent, this._onMouseWheel, true);
  31786. }
  31787. window.removeEventListener('mouseup', this._onMouseUpGlobal, true);
  31788. window.removeEventListener('mouseout', this._onMouseOutGlobal, true);
  31789. document.removeEventListener('pointerlockchange', this._pointerLockChange, true);
  31790. document.removeEventListener('mozpointerlockchange', this._pointerLockChange, true);
  31791. document.removeEventListener('webkitpointerlockchange', this._pointerLockChange, true);
  31792. }
  31793. };
  31794. Phaser.Mouse.prototype.constructor = Phaser.Mouse;
  31795. /* jshint latedef:nofunc */
  31796. /**
  31797. * A purely internal event support class to proxy 'wheelscroll' and 'DOMMouseWheel'
  31798. * events to 'wheel'-like events.
  31799. *
  31800. * See https://developer.mozilla.org/en-US/docs/Web/Events/mousewheel for choosing a scale and delta mode.
  31801. *
  31802. * @method Phaser.Mouse#WheelEventProxy
  31803. * @private
  31804. * @param {number} scaleFactor - Scale factor as applied to wheelDelta/wheelDeltaX or details.
  31805. * @param {integer} deltaMode - The reported delta mode.
  31806. */
  31807. function WheelEventProxy (scaleFactor, deltaMode) {
  31808. /**
  31809. * @property {number} _scaleFactor - Scale factor as applied to wheelDelta/wheelDeltaX or details.
  31810. * @private
  31811. */
  31812. this._scaleFactor = scaleFactor;
  31813. /**
  31814. * @property {number} _deltaMode - The reported delta mode.
  31815. * @private
  31816. */
  31817. this._deltaMode = deltaMode;
  31818. /**
  31819. * @property {any} originalEvent - The original event _currently_ being proxied; the getters will follow suit.
  31820. * @private
  31821. */
  31822. this.originalEvent = null;
  31823. }
  31824. WheelEventProxy.prototype = {};
  31825. WheelEventProxy.prototype.constructor = WheelEventProxy;
  31826. WheelEventProxy.prototype.bindEvent = function (event) {
  31827. // Generate stubs automatically
  31828. if (!WheelEventProxy._stubsGenerated && event)
  31829. {
  31830. var makeBinder = function (name) {
  31831. return function () {
  31832. var v = this.originalEvent[name];
  31833. return typeof v !== 'function' ? v : v.bind(this.originalEvent);
  31834. };
  31835. };
  31836. for (var prop in event)
  31837. {
  31838. if (!(prop in WheelEventProxy.prototype))
  31839. {
  31840. Object.defineProperty(WheelEventProxy.prototype, prop, {
  31841. get: makeBinder(prop)
  31842. });
  31843. }
  31844. }
  31845. WheelEventProxy._stubsGenerated = true;
  31846. }
  31847. this.originalEvent = event;
  31848. return this;
  31849. };
  31850. Object.defineProperties(WheelEventProxy.prototype, {
  31851. "type": { value: "wheel" },
  31852. "deltaMode": { get: function () { return this._deltaMode; } },
  31853. "deltaY": {
  31854. get: function () {
  31855. return (this._scaleFactor * (this.originalEvent.wheelDelta || this.originalEvent.detail)) || 0;
  31856. }
  31857. },
  31858. "deltaX": {
  31859. get: function () {
  31860. return (this._scaleFactor * this.originalEvent.wheelDeltaX) || 0;
  31861. }
  31862. },
  31863. "deltaZ": { value: 0 }
  31864. });
  31865. /**
  31866. * @author Richard Davey <rich@photonstorm.com>
  31867. * @copyright 2016 Photon Storm Ltd.
  31868. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  31869. */
  31870. /**
  31871. * The MSPointer class handles Microsoft touch interactions with the game and the resulting Pointer objects.
  31872. *
  31873. * It will work only in Internet Explorer 10+ and Windows Store or Windows Phone 8 apps using JavaScript.
  31874. * http://msdn.microsoft.com/en-us/library/ie/hh673557(v=vs.85).aspx
  31875. *
  31876. * You should not normally access this class directly, but instead use a Phaser.Pointer object which
  31877. * normalises all game input for you including accurate button handling.
  31878. *
  31879. * Please note that at the current time of writing Phaser does not yet support chorded button interactions:
  31880. * http://www.w3.org/TR/pointerevents/#chorded-button-interactions
  31881. *
  31882. * @class Phaser.MSPointer
  31883. * @constructor
  31884. * @param {Phaser.Game} game - A reference to the currently running game.
  31885. */
  31886. Phaser.MSPointer = function (game) {
  31887. /**
  31888. * @property {Phaser.Game} game - A reference to the currently running game.
  31889. */
  31890. this.game = game;
  31891. /**
  31892. * @property {Phaser.Input} input - A reference to the Phaser Input Manager.
  31893. * @protected
  31894. */
  31895. this.input = game.input;
  31896. /**
  31897. * @property {object} callbackContext - The context under which callbacks are called (defaults to game).
  31898. */
  31899. this.callbackContext = this.game;
  31900. /**
  31901. * @property {function} pointerDownCallback - A callback that can be fired on a MSPointerDown event.
  31902. */
  31903. this.pointerDownCallback = null;
  31904. /**
  31905. * @property {function} pointerMoveCallback - A callback that can be fired on a MSPointerMove event.
  31906. */
  31907. this.pointerMoveCallback = null;
  31908. /**
  31909. * @property {function} pointerUpCallback - A callback that can be fired on a MSPointerUp event.
  31910. */
  31911. this.pointerUpCallback = null;
  31912. /**
  31913. * @property {boolean} capture - If true the Pointer events will have event.preventDefault applied to them, if false they will propagate fully.
  31914. */
  31915. this.capture = true;
  31916. /**
  31917. * This property was removed in Phaser 2.4 and should no longer be used.
  31918. * Instead please see the Pointer button properties such as `Pointer.leftButton`, `Pointer.rightButton` and so on.
  31919. * Or Pointer.button holds the DOM event button value if you require that.
  31920. * @property {number} button
  31921. */
  31922. this.button = -1;
  31923. /**
  31924. * The browser MSPointer DOM event. Will be null if no event has ever been received.
  31925. * Access this property only inside a Pointer event handler and do not keep references to it.
  31926. * @property {MSPointerEvent|null} event
  31927. * @default
  31928. */
  31929. this.event = null;
  31930. /**
  31931. * MSPointer input will only be processed if enabled.
  31932. * @property {boolean} enabled
  31933. * @default
  31934. */
  31935. this.enabled = true;
  31936. /**
  31937. * @property {function} _onMSPointerDown - Internal function to handle MSPointer events.
  31938. * @private
  31939. */
  31940. this._onMSPointerDown = null;
  31941. /**
  31942. * @property {function} _onMSPointerMove - Internal function to handle MSPointer events.
  31943. * @private
  31944. */
  31945. this._onMSPointerMove = null;
  31946. /**
  31947. * @property {function} _onMSPointerUp - Internal function to handle MSPointer events.
  31948. * @private
  31949. */
  31950. this._onMSPointerUp = null;
  31951. /**
  31952. * @property {function} _onMSPointerUpGlobal - Internal function to handle MSPointer events.
  31953. * @private
  31954. */
  31955. this._onMSPointerUpGlobal = null;
  31956. /**
  31957. * @property {function} _onMSPointerOut - Internal function to handle MSPointer events.
  31958. * @private
  31959. */
  31960. this._onMSPointerOut = null;
  31961. /**
  31962. * @property {function} _onMSPointerOver - Internal function to handle MSPointer events.
  31963. * @private
  31964. */
  31965. this._onMSPointerOver = null;
  31966. };
  31967. Phaser.MSPointer.prototype = {
  31968. /**
  31969. * Starts the event listeners running.
  31970. * @method Phaser.MSPointer#start
  31971. */
  31972. start: function () {
  31973. if (this._onMSPointerDown !== null)
  31974. {
  31975. // Avoid setting multiple listeners
  31976. return;
  31977. }
  31978. var _this = this;
  31979. if (this.game.device.mspointer)
  31980. {
  31981. this._onMSPointerDown = function (event) {
  31982. return _this.onPointerDown(event);
  31983. };
  31984. this._onMSPointerMove = function (event) {
  31985. return _this.onPointerMove(event);
  31986. };
  31987. this._onMSPointerUp = function (event) {
  31988. return _this.onPointerUp(event);
  31989. };
  31990. this._onMSPointerUpGlobal = function (event) {
  31991. return _this.onPointerUpGlobal(event);
  31992. };
  31993. this._onMSPointerOut = function (event) {
  31994. return _this.onPointerOut(event);
  31995. };
  31996. this._onMSPointerOver = function (event) {
  31997. return _this.onPointerOver(event);
  31998. };
  31999. var canvas = this.game.canvas;
  32000. canvas.addEventListener('MSPointerDown', this._onMSPointerDown, false);
  32001. canvas.addEventListener('MSPointerMove', this._onMSPointerMove, false);
  32002. canvas.addEventListener('MSPointerUp', this._onMSPointerUp, false);
  32003. // IE11+ uses non-prefix events
  32004. canvas.addEventListener('pointerdown', this._onMSPointerDown, false);
  32005. canvas.addEventListener('pointermove', this._onMSPointerMove, false);
  32006. canvas.addEventListener('pointerup', this._onMSPointerUp, false);
  32007. canvas.style['-ms-content-zooming'] = 'none';
  32008. canvas.style['-ms-touch-action'] = 'none';
  32009. if (!this.game.device.cocoonJS)
  32010. {
  32011. window.addEventListener('MSPointerUp', this._onMSPointerUpGlobal, true);
  32012. canvas.addEventListener('MSPointerOver', this._onMSPointerOver, true);
  32013. canvas.addEventListener('MSPointerOut', this._onMSPointerOut, true);
  32014. // IE11+ uses non-prefix events
  32015. window.addEventListener('pointerup', this._onMSPointerUpGlobal, true);
  32016. canvas.addEventListener('pointerover', this._onMSPointerOver, true);
  32017. canvas.addEventListener('pointerout', this._onMSPointerOut, true);
  32018. }
  32019. }
  32020. },
  32021. /**
  32022. * The function that handles the PointerDown event.
  32023. *
  32024. * @method Phaser.MSPointer#onPointerDown
  32025. * @param {PointerEvent} event - The native DOM event.
  32026. */
  32027. onPointerDown: function (event) {
  32028. this.event = event;
  32029. if (this.capture)
  32030. {
  32031. event.preventDefault();
  32032. }
  32033. if (this.pointerDownCallback)
  32034. {
  32035. this.pointerDownCallback.call(this.callbackContext, event);
  32036. }
  32037. if (!this.input.enabled || !this.enabled)
  32038. {
  32039. return;
  32040. }
  32041. event.identifier = event.pointerId;
  32042. if (event.pointerType === 'mouse' || event.pointerType === 0x00000004)
  32043. {
  32044. this.input.mousePointer.start(event);
  32045. }
  32046. else
  32047. {
  32048. this.input.startPointer(event);
  32049. }
  32050. },
  32051. /**
  32052. * The function that handles the PointerMove event.
  32053. * @method Phaser.MSPointer#onPointerMove
  32054. * @param {PointerEvent} event - The native DOM event.
  32055. */
  32056. onPointerMove: function (event) {
  32057. this.event = event;
  32058. if (this.capture)
  32059. {
  32060. event.preventDefault();
  32061. }
  32062. if (this.pointerMoveCallback)
  32063. {
  32064. this.pointerMoveCallback.call(this.callbackContext, event);
  32065. }
  32066. if (!this.input.enabled || !this.enabled)
  32067. {
  32068. return;
  32069. }
  32070. event.identifier = event.pointerId;
  32071. if (event.pointerType === 'mouse' || event.pointerType === 0x00000004)
  32072. {
  32073. this.input.mousePointer.move(event);
  32074. }
  32075. else
  32076. {
  32077. this.input.updatePointer(event);
  32078. }
  32079. },
  32080. /**
  32081. * The function that handles the PointerUp event.
  32082. * @method Phaser.MSPointer#onPointerUp
  32083. * @param {PointerEvent} event - The native DOM event.
  32084. */
  32085. onPointerUp: function (event) {
  32086. this.event = event;
  32087. if (this.capture)
  32088. {
  32089. event.preventDefault();
  32090. }
  32091. if (this.pointerUpCallback)
  32092. {
  32093. this.pointerUpCallback.call(this.callbackContext, event);
  32094. }
  32095. if (!this.input.enabled || !this.enabled)
  32096. {
  32097. return;
  32098. }
  32099. event.identifier = event.pointerId;
  32100. if (event.pointerType === 'mouse' || event.pointerType === 0x00000004)
  32101. {
  32102. this.input.mousePointer.stop(event);
  32103. }
  32104. else
  32105. {
  32106. this.input.stopPointer(event);
  32107. }
  32108. },
  32109. /**
  32110. * The internal method that handles the mouse up event from the window.
  32111. *
  32112. * @method Phaser.MSPointer#onPointerUpGlobal
  32113. * @param {PointerEvent} event - The native event from the browser. This gets stored in MSPointer.event.
  32114. */
  32115. onPointerUpGlobal: function (event) {
  32116. if ((event.pointerType === 'mouse' || event.pointerType === 0x00000004) && !this.input.mousePointer.withinGame)
  32117. {
  32118. this.onPointerUp(event);
  32119. }
  32120. else
  32121. {
  32122. var pointer = this.input.getPointerFromIdentifier(event.identifier);
  32123. if (pointer && pointer.withinGame)
  32124. {
  32125. this.onPointerUp(event);
  32126. }
  32127. }
  32128. },
  32129. /**
  32130. * The internal method that handles the pointer out event from the browser.
  32131. *
  32132. * @method Phaser.MSPointer#onPointerOut
  32133. * @param {PointerEvent} event - The native event from the browser. This gets stored in MSPointer.event.
  32134. */
  32135. onPointerOut: function (event) {
  32136. this.event = event;
  32137. if (this.capture)
  32138. {
  32139. event.preventDefault();
  32140. }
  32141. if (event.pointerType === 'mouse' || event.pointerType === 0x00000004)
  32142. {
  32143. this.input.mousePointer.withinGame = false;
  32144. }
  32145. else
  32146. {
  32147. var pointer = this.input.getPointerFromIdentifier(event.identifier);
  32148. if (pointer)
  32149. {
  32150. pointer.withinGame = false;
  32151. }
  32152. }
  32153. if (this.input.mouse.mouseOutCallback)
  32154. {
  32155. this.input.mouse.mouseOutCallback.call(this.input.mouse.callbackContext, event);
  32156. }
  32157. if (!this.input.enabled || !this.enabled)
  32158. {
  32159. return;
  32160. }
  32161. if (this.input.mouse.stopOnGameOut)
  32162. {
  32163. event['identifier'] = 0;
  32164. if (pointer)
  32165. {
  32166. pointer.stop(event);
  32167. }
  32168. else
  32169. {
  32170. this.input.mousePointer.stop(event);
  32171. }
  32172. }
  32173. },
  32174. /**
  32175. * The internal method that handles the pointer out event from the browser.
  32176. *
  32177. * @method Phaser.MSPointer#onPointerOut
  32178. * @param {PointerEvent} event - The native event from the browser. This gets stored in MSPointer.event.
  32179. */
  32180. onPointerOver: function (event) {
  32181. this.event = event;
  32182. if (this.capture)
  32183. {
  32184. event.preventDefault();
  32185. }
  32186. if (event.pointerType === 'mouse' || event.pointerType === 0x00000004)
  32187. {
  32188. this.input.mousePointer.withinGame = true;
  32189. }
  32190. else
  32191. {
  32192. var pointer = this.input.getPointerFromIdentifier(event.identifier);
  32193. if (pointer)
  32194. {
  32195. pointer.withinGame = true;
  32196. }
  32197. }
  32198. if (this.input.mouse.mouseOverCallback)
  32199. {
  32200. this.input.mouse.mouseOverCallback.call(this.input.mouse.callbackContext, event);
  32201. }
  32202. },
  32203. /**
  32204. * Stop the event listeners.
  32205. * @method Phaser.MSPointer#stop
  32206. */
  32207. stop: function () {
  32208. var canvas = this.game.canvas;
  32209. canvas.removeEventListener('MSPointerDown', this._onMSPointerDown, false);
  32210. canvas.removeEventListener('MSPointerMove', this._onMSPointerMove, false);
  32211. canvas.removeEventListener('MSPointerUp', this._onMSPointerUp, false);
  32212. // IE11+ uses non-prefix events
  32213. canvas.removeEventListener('pointerdown', this._onMSPointerDown, false);
  32214. canvas.removeEventListener('pointermove', this._onMSPointerMove, false);
  32215. canvas.removeEventListener('pointerup', this._onMSPointerUp, false);
  32216. window.removeEventListener('MSPointerUp', this._onMSPointerUpGlobal, true);
  32217. canvas.removeEventListener('MSPointerOver', this._onMSPointerOver, true);
  32218. canvas.removeEventListener('MSPointerOut', this._onMSPointerOut, true);
  32219. // IE11+ uses non-prefix events
  32220. window.removeEventListener('pointerup', this._onMSPointerUpGlobal, true);
  32221. canvas.removeEventListener('pointerover', this._onMSPointerOver, true);
  32222. canvas.removeEventListener('pointerout', this._onMSPointerOut, true);
  32223. }
  32224. };
  32225. Phaser.MSPointer.prototype.constructor = Phaser.MSPointer;
  32226. /**
  32227. * @author Richard Davey <rich@photonstorm.com>
  32228. * @author @karlmacklin <tacklemcclean@gmail.com>
  32229. * @copyright 2016 Photon Storm Ltd.
  32230. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  32231. */
  32232. /**
  32233. * DeviceButtons belong to both `Phaser.Pointer` and `Phaser.SinglePad` (Gamepad) instances.
  32234. *
  32235. * For Pointers they represent the various buttons that can exist on mice and pens, such as the left button, right button,
  32236. * middle button and advanced buttons like back and forward.
  32237. *
  32238. * Access them via `Pointer.leftbutton`, `Pointer.rightButton` and so on.
  32239. *
  32240. * On Gamepads they represent all buttons on the pad: from shoulder buttons to action buttons.
  32241. *
  32242. * At the time of writing this there are device limitations you should be aware of:
  32243. *
  32244. * - On Windows, if you install a mouse driver, and its utility software allows you to customize button actions
  32245. * (e.g., IntelliPoint and SetPoint), the middle (wheel) button, the 4th button, and the 5th button might not be set,
  32246. * even when they are pressed.
  32247. * - On Linux (GTK), the 4th button and the 5th button are not supported.
  32248. * - On Mac OS X 10.5 there is no platform API for implementing any advanced buttons.
  32249. *
  32250. * @class Phaser.DeviceButton
  32251. * @constructor
  32252. * @param {Phaser.Pointer|Phaser.SinglePad} parent - A reference to the parent of this button. Either a Pointer or a Gamepad.
  32253. * @param {number} buttonCode - The button code this DeviceButton is responsible for.
  32254. */
  32255. Phaser.DeviceButton = function (parent, buttonCode) {
  32256. /**
  32257. * @property {Phaser.Pointer|Phaser.SinglePad} parent - A reference to the Pointer or Gamepad that owns this button.
  32258. */
  32259. this.parent = parent;
  32260. /**
  32261. * @property {Phaser.Game} game - A reference to the currently running game.
  32262. */
  32263. this.game = parent.game;
  32264. /**
  32265. * @property {object} event - The DOM event that caused the change in button state.
  32266. * @default
  32267. */
  32268. this.event = null;
  32269. /**
  32270. * @property {boolean} isDown - The "down" state of the button.
  32271. * @default
  32272. */
  32273. this.isDown = false;
  32274. /**
  32275. * @property {boolean} isUp - The "up" state of the button.
  32276. * @default
  32277. */
  32278. this.isUp = true;
  32279. /**
  32280. * @property {number} timeDown - The timestamp when the button was last pressed down.
  32281. * @default
  32282. */
  32283. this.timeDown = 0;
  32284. /**
  32285. * @property {number} timeUp - The timestamp when the button was last released.
  32286. * @default
  32287. */
  32288. this.timeUp = 0;
  32289. /**
  32290. * Gamepad only.
  32291. * If a button is held down this holds down the number of times the button has 'repeated'.
  32292. * @property {number} repeats
  32293. * @default
  32294. */
  32295. this.repeats = 0;
  32296. /**
  32297. * True if the alt key was held down when this button was last pressed or released.
  32298. * Not supported on Gamepads.
  32299. * @property {boolean} altKey
  32300. * @default
  32301. */
  32302. this.altKey = false;
  32303. /**
  32304. * True if the shift key was held down when this button was last pressed or released.
  32305. * Not supported on Gamepads.
  32306. * @property {boolean} shiftKey
  32307. * @default
  32308. */
  32309. this.shiftKey = false;
  32310. /**
  32311. * True if the control key was held down when this button was last pressed or released.
  32312. * Not supported on Gamepads.
  32313. * @property {boolean} ctrlKey
  32314. * @default
  32315. */
  32316. this.ctrlKey = false;
  32317. /**
  32318. * @property {number} value - Button value. Mainly useful for checking analog buttons (like shoulder triggers) on Gamepads.
  32319. * @default
  32320. */
  32321. this.value = 0;
  32322. /**
  32323. * @property {number} buttonCode - The buttoncode of this button if a Gamepad, or the DOM button event value if a Pointer.
  32324. */
  32325. this.buttonCode = buttonCode;
  32326. /**
  32327. * This Signal is dispatched every time this DeviceButton is pressed down.
  32328. * It is only dispatched once (until the button is released again).
  32329. * When dispatched it sends 2 arguments: A reference to this DeviceButton and the value of the button.
  32330. * @property {Phaser.Signal} onDown
  32331. */
  32332. this.onDown = new Phaser.Signal();
  32333. /**
  32334. * This Signal is dispatched every time this DeviceButton is released from a down state.
  32335. * It is only dispatched once (until the button is pressed again).
  32336. * When dispatched it sends 2 arguments: A reference to this DeviceButton and the value of the button.
  32337. * @property {Phaser.Signal} onUp
  32338. */
  32339. this.onUp = new Phaser.Signal();
  32340. /**
  32341. * Gamepad only.
  32342. * This Signal is dispatched every time this DeviceButton changes floating value (between, but not exactly, 0 and 1).
  32343. * When dispatched it sends 2 arguments: A reference to this DeviceButton and the value of the button.
  32344. * @property {Phaser.Signal} onFloat
  32345. */
  32346. this.onFloat = new Phaser.Signal();
  32347. };
  32348. Phaser.DeviceButton.prototype = {
  32349. /**
  32350. * Called automatically by Phaser.Pointer and Phaser.SinglePad.
  32351. * Handles the button down state.
  32352. *
  32353. * @method Phaser.DeviceButton#start
  32354. * @protected
  32355. * @param {object} [event] - The DOM event that triggered the button change.
  32356. * @param {number} [value] - The button value. Only get for Gamepads.
  32357. */
  32358. start: function (event, value) {
  32359. if (this.isDown)
  32360. {
  32361. return;
  32362. }
  32363. this.isDown = true;
  32364. this.isUp = false;
  32365. this.timeDown = this.game.time.time;
  32366. this.repeats = 0;
  32367. this.event = event;
  32368. this.value = value;
  32369. if (event)
  32370. {
  32371. this.altKey = event.altKey;
  32372. this.shiftKey = event.shiftKey;
  32373. this.ctrlKey = event.ctrlKey;
  32374. }
  32375. this.onDown.dispatch(this, value);
  32376. },
  32377. /**
  32378. * Called automatically by Phaser.Pointer and Phaser.SinglePad.
  32379. * Handles the button up state.
  32380. *
  32381. * @method Phaser.DeviceButton#stop
  32382. * @protected
  32383. * @param {object} [event] - The DOM event that triggered the button change.
  32384. * @param {number} [value] - The button value. Only get for Gamepads.
  32385. */
  32386. stop: function (event, value) {
  32387. if (this.isUp)
  32388. {
  32389. return;
  32390. }
  32391. this.isDown = false;
  32392. this.isUp = true;
  32393. this.timeUp = this.game.time.time;
  32394. this.event = event;
  32395. this.value = value;
  32396. if (event)
  32397. {
  32398. this.altKey = event.altKey;
  32399. this.shiftKey = event.shiftKey;
  32400. this.ctrlKey = event.ctrlKey;
  32401. }
  32402. this.onUp.dispatch(this, value);
  32403. },
  32404. /**
  32405. * Called automatically by Phaser.SinglePad.
  32406. *
  32407. * @method Phaser.DeviceButton#padFloat
  32408. * @protected
  32409. * @param {number} value - Button value
  32410. */
  32411. padFloat: function (value) {
  32412. this.value = value;
  32413. this.onFloat.dispatch(this, value);
  32414. },
  32415. /**
  32416. * Returns the "just pressed" state of this button.
  32417. * Just pressed is considered true if the button was pressed down within the duration given (default 250ms).
  32418. *
  32419. * @method Phaser.DeviceButton#justPressed
  32420. * @param {number} [duration=250] - The duration in ms below which the button is considered as being just pressed.
  32421. * @return {boolean} True if the button is just pressed otherwise false.
  32422. */
  32423. justPressed: function (duration) {
  32424. duration = duration || 250;
  32425. return (this.isDown && (this.timeDown + duration) > this.game.time.time);
  32426. },
  32427. /**
  32428. * Returns the "just released" state of this button.
  32429. * Just released is considered as being true if the button was released within the duration given (default 250ms).
  32430. *
  32431. * @method Phaser.DeviceButton#justReleased
  32432. * @param {number} [duration=250] - The duration in ms below which the button is considered as being just released.
  32433. * @return {boolean} True if the button is just released otherwise false.
  32434. */
  32435. justReleased: function (duration) {
  32436. duration = duration || 250;
  32437. return (this.isUp && (this.timeUp + duration) > this.game.time.time);
  32438. },
  32439. /**
  32440. * Resets this DeviceButton, changing it to an isUp state and resetting the duration and repeats counters.
  32441. *
  32442. * @method Phaser.DeviceButton#reset
  32443. */
  32444. reset: function () {
  32445. this.isDown = false;
  32446. this.isUp = true;
  32447. this.timeDown = this.game.time.time;
  32448. this.repeats = 0;
  32449. this.altKey = false;
  32450. this.shiftKey = false;
  32451. this.ctrlKey = false;
  32452. },
  32453. /**
  32454. * Destroys this DeviceButton, this disposes of the onDown, onUp and onFloat signals
  32455. * and clears the parent and game references.
  32456. *
  32457. * @method Phaser.DeviceButton#destroy
  32458. */
  32459. destroy: function () {
  32460. this.onDown.dispose();
  32461. this.onUp.dispose();
  32462. this.onFloat.dispose();
  32463. this.parent = null;
  32464. this.game = null;
  32465. }
  32466. };
  32467. Phaser.DeviceButton.prototype.constructor = Phaser.DeviceButton;
  32468. /**
  32469. * How long the button has been held down for in milliseconds.
  32470. * If not currently down it returns -1.
  32471. *
  32472. * @name Phaser.DeviceButton#duration
  32473. * @property {number} duration
  32474. * @readonly
  32475. */
  32476. Object.defineProperty(Phaser.DeviceButton.prototype, "duration", {
  32477. get: function () {
  32478. if (this.isUp)
  32479. {
  32480. return -1;
  32481. }
  32482. return this.game.time.time - this.timeDown;
  32483. }
  32484. });
  32485. /**
  32486. * @author Richard Davey <rich@photonstorm.com>
  32487. * @copyright 2016 Photon Storm Ltd.
  32488. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  32489. */
  32490. /**
  32491. * A Pointer object is used by the Mouse, Touch and MSPoint managers and represents a single finger on the touch screen.
  32492. *
  32493. * @class Phaser.Pointer
  32494. * @constructor
  32495. * @param {Phaser.Game} game - A reference to the currently running game.
  32496. * @param {number} id - The ID of the Pointer object within the game. Each game can have up to 10 active pointers.
  32497. * @param {Phaser.PointerMode} pointerMode=(CURSOR|CONTACT) - The operational mode of this pointer, eg. CURSOR or TOUCH.
  32498. */
  32499. Phaser.Pointer = function (game, id, pointerMode) {
  32500. /**
  32501. * @property {Phaser.Game} game - A reference to the currently running game.
  32502. */
  32503. this.game = game;
  32504. /**
  32505. * @property {number} id - The ID of the Pointer object within the game. Each game can have up to 10 active pointers.
  32506. */
  32507. this.id = id;
  32508. /**
  32509. * @property {number} type - The const type of this object.
  32510. * @readonly
  32511. */
  32512. this.type = Phaser.POINTER;
  32513. /**
  32514. * @property {boolean} exists - A Pointer object that exists is allowed to be checked for physics collisions and overlaps.
  32515. * @default
  32516. */
  32517. this.exists = true;
  32518. /**
  32519. * @property {number} identifier - The identifier property of the Pointer as set by the DOM event when this Pointer is started.
  32520. * @default
  32521. */
  32522. this.identifier = 0;
  32523. /**
  32524. * @property {number} pointerId - The pointerId property of the Pointer as set by the DOM event when this Pointer is started. The browser can and will recycle this value.
  32525. * @default
  32526. */
  32527. this.pointerId = null;
  32528. /**
  32529. * @property {Phaser.PointerMode} pointerMode - The operational mode of this pointer.
  32530. */
  32531. this.pointerMode = pointerMode || (Phaser.PointerMode.CURSOR | Phaser.PointerMode.CONTACT);
  32532. /**
  32533. * @property {any} target - The target property of the Pointer as set by the DOM event when this Pointer is started.
  32534. * @default
  32535. */
  32536. this.target = null;
  32537. /**
  32538. * The button property of the most recent DOM event when this Pointer is started.
  32539. * You should not rely on this value for accurate button detection, instead use the Pointer properties
  32540. * `leftButton`, `rightButton`, `middleButton` and so on.
  32541. * @property {any} button
  32542. * @default
  32543. */
  32544. this.button = null;
  32545. /**
  32546. * If this Pointer is a Mouse or Pen / Stylus then you can access its left button directly through this property.
  32547. *
  32548. * The DeviceButton has its own properties such as `isDown`, `duration` and methods like `justReleased` for more fine-grained
  32549. * button control.
  32550. *
  32551. * @property {Phaser.DeviceButton} leftButton
  32552. * @default
  32553. */
  32554. this.leftButton = new Phaser.DeviceButton(this, Phaser.Pointer.LEFT_BUTTON);
  32555. /**
  32556. * If this Pointer is a Mouse or Pen / Stylus then you can access its middle button directly through this property.
  32557. *
  32558. * The DeviceButton has its own properties such as `isDown`, `duration` and methods like `justReleased` for more fine-grained
  32559. * button control.
  32560. *
  32561. * Please see the DeviceButton docs for details on browser button limitations.
  32562. *
  32563. * @property {Phaser.DeviceButton} middleButton
  32564. * @default
  32565. */
  32566. this.middleButton = new Phaser.DeviceButton(this, Phaser.Pointer.MIDDLE_BUTTON);
  32567. /**
  32568. * If this Pointer is a Mouse or Pen / Stylus then you can access its right button directly through this property.
  32569. *
  32570. * The DeviceButton has its own properties such as `isDown`, `duration` and methods like `justReleased` for more fine-grained
  32571. * button control.
  32572. *
  32573. * Please see the DeviceButton docs for details on browser button limitations.
  32574. *
  32575. * @property {Phaser.DeviceButton} rightButton
  32576. * @default
  32577. */
  32578. this.rightButton = new Phaser.DeviceButton(this, Phaser.Pointer.RIGHT_BUTTON);
  32579. /**
  32580. * If this Pointer is a Mouse or Pen / Stylus then you can access its X1 (back) button directly through this property.
  32581. *
  32582. * The DeviceButton has its own properties such as `isDown`, `duration` and methods like `justReleased` for more fine-grained
  32583. * button control.
  32584. *
  32585. * Please see the DeviceButton docs for details on browser button limitations.
  32586. *
  32587. * @property {Phaser.DeviceButton} backButton
  32588. * @default
  32589. */
  32590. this.backButton = new Phaser.DeviceButton(this, Phaser.Pointer.BACK_BUTTON);
  32591. /**
  32592. * If this Pointer is a Mouse or Pen / Stylus then you can access its X2 (forward) button directly through this property.
  32593. *
  32594. * The DeviceButton has its own properties such as `isDown`, `duration` and methods like `justReleased` for more fine-grained
  32595. * button control.
  32596. *
  32597. * Please see the DeviceButton docs for details on browser button limitations.
  32598. *
  32599. * @property {Phaser.DeviceButton} forwardButton
  32600. * @default
  32601. */
  32602. this.forwardButton = new Phaser.DeviceButton(this, Phaser.Pointer.FORWARD_BUTTON);
  32603. /**
  32604. * If this Pointer is a Pen / Stylus then you can access its eraser button directly through this property.
  32605. *
  32606. * The DeviceButton has its own properties such as `isDown`, `duration` and methods like `justReleased` for more fine-grained
  32607. * button control.
  32608. *
  32609. * Please see the DeviceButton docs for details on browser button limitations.
  32610. *
  32611. * @property {Phaser.DeviceButton} eraserButton
  32612. * @default
  32613. */
  32614. this.eraserButton = new Phaser.DeviceButton(this, Phaser.Pointer.ERASER_BUTTON);
  32615. /**
  32616. * @property {boolean} _holdSent - Local private variable to store the status of dispatching a hold event.
  32617. * @private
  32618. * @default
  32619. */
  32620. this._holdSent = false;
  32621. /**
  32622. * @property {array} _history - Local private variable storing the short-term history of pointer movements.
  32623. * @private
  32624. */
  32625. this._history = [];
  32626. /**
  32627. * @property {number} _nextDrop - Local private variable storing the time at which the next history drop should occur.
  32628. * @private
  32629. */
  32630. this._nextDrop = 0;
  32631. /**
  32632. * @property {boolean} _stateReset - Monitor events outside of a state reset loop.
  32633. * @private
  32634. */
  32635. this._stateReset = false;
  32636. /**
  32637. * @property {boolean} withinGame - true if the Pointer is over the game canvas, otherwise false.
  32638. */
  32639. this.withinGame = false;
  32640. /**
  32641. * @property {number} clientX - The horizontal coordinate of the Pointer within the application's client area at which the event occurred (as opposed to the coordinates within the page).
  32642. */
  32643. this.clientX = -1;
  32644. /**
  32645. * @property {number} clientY - The vertical coordinate of the Pointer within the application's client area at which the event occurred (as opposed to the coordinates within the page).
  32646. */
  32647. this.clientY = -1;
  32648. /**
  32649. * @property {number} pageX - The horizontal coordinate of the Pointer relative to whole document.
  32650. */
  32651. this.pageX = -1;
  32652. /**
  32653. * @property {number} pageY - The vertical coordinate of the Pointer relative to whole document.
  32654. */
  32655. this.pageY = -1;
  32656. /**
  32657. * @property {number} screenX - The horizontal coordinate of the Pointer relative to the screen.
  32658. */
  32659. this.screenX = -1;
  32660. /**
  32661. * @property {number} screenY - The vertical coordinate of the Pointer relative to the screen.
  32662. */
  32663. this.screenY = -1;
  32664. /**
  32665. * @property {number} rawMovementX - The horizontal raw relative movement of the Pointer in pixels since last event.
  32666. * @default
  32667. */
  32668. this.rawMovementX = 0;
  32669. /**
  32670. * @property {number} rawMovementY - The vertical raw relative movement of the Pointer in pixels since last event.
  32671. * @default
  32672. */
  32673. this.rawMovementY = 0;
  32674. /**
  32675. * @property {number} movementX - The horizontal processed relative movement of the Pointer in pixels since last event.
  32676. * @default
  32677. */
  32678. this.movementX = 0;
  32679. /**
  32680. * @property {number} movementY - The vertical processed relative movement of the Pointer in pixels since last event.
  32681. * @default
  32682. */
  32683. this.movementY = 0;
  32684. /**
  32685. * @property {number} x - The horizontal coordinate of the Pointer. This value is automatically scaled based on the game scale.
  32686. * @default
  32687. */
  32688. this.x = -1;
  32689. /**
  32690. * @property {number} y - The vertical coordinate of the Pointer. This value is automatically scaled based on the game scale.
  32691. * @default
  32692. */
  32693. this.y = -1;
  32694. /**
  32695. * @property {boolean} isMouse - If the Pointer is a mouse or pen / stylus this is true, otherwise false.
  32696. */
  32697. this.isMouse = (id === 0);
  32698. /**
  32699. * If the Pointer is touching the touchscreen, or *any* mouse or pen button is held down, isDown is set to true.
  32700. * If you need to check a specific mouse or pen button then use the button properties, i.e. Pointer.rightButton.isDown.
  32701. * @property {boolean} isDown
  32702. * @default
  32703. */
  32704. this.isDown = false;
  32705. /**
  32706. * If the Pointer is not touching the touchscreen, or *all* mouse or pen buttons are up, isUp is set to true.
  32707. * If you need to check a specific mouse or pen button then use the button properties, i.e. Pointer.rightButton.isUp.
  32708. * @property {boolean} isUp
  32709. * @default
  32710. */
  32711. this.isUp = true;
  32712. /**
  32713. * @property {number} timeDown - A timestamp representing when the Pointer first touched the touchscreen.
  32714. * @default
  32715. */
  32716. this.timeDown = 0;
  32717. /**
  32718. * @property {number} timeUp - A timestamp representing when the Pointer left the touchscreen.
  32719. * @default
  32720. */
  32721. this.timeUp = 0;
  32722. /**
  32723. * @property {number} previousTapTime - A timestamp representing when the Pointer was last tapped or clicked.
  32724. * @default
  32725. */
  32726. this.previousTapTime = 0;
  32727. /**
  32728. * @property {number} totalTouches - The total number of times this Pointer has been touched to the touchscreen.
  32729. * @default
  32730. */
  32731. this.totalTouches = 0;
  32732. /**
  32733. * @property {number} msSinceLastClick - The number of milliseconds since the last click or touch event.
  32734. * @default
  32735. */
  32736. this.msSinceLastClick = Number.MAX_VALUE;
  32737. /**
  32738. * @property {any} targetObject - The Game Object this Pointer is currently over / touching / dragging.
  32739. * @default
  32740. */
  32741. this.targetObject = null;
  32742. /**
  32743. * This array is erased and re-populated every time this Pointer is updated. It contains references to all
  32744. * of the Game Objects that were considered as being valid for processing by this Pointer, this frame. To be
  32745. * valid they must have suitable a `priorityID`, be Input enabled, visible and actually have the Pointer over
  32746. * them. You can check the contents of this array in events such as `onInputDown`, but beware it is reset
  32747. * every frame.
  32748. * @property {array} interactiveCandidates
  32749. * @default
  32750. */
  32751. this.interactiveCandidates = [];
  32752. /**
  32753. * @property {boolean} active - An active pointer is one that is currently pressed down on the display. A Mouse is always active.
  32754. * @default
  32755. */
  32756. this.active = false;
  32757. /**
  32758. * @property {boolean} dirty - A dirty pointer needs to re-poll any interactive objects it may have been over, regardless if it has moved or not.
  32759. * @default
  32760. */
  32761. this.dirty = false;
  32762. /**
  32763. * @property {Phaser.Point} position - A Phaser.Point object containing the current x/y values of the pointer on the display.
  32764. */
  32765. this.position = new Phaser.Point();
  32766. /**
  32767. * @property {Phaser.Point} positionDown - A Phaser.Point object containing the x/y values of the pointer when it was last in a down state on the display.
  32768. */
  32769. this.positionDown = new Phaser.Point();
  32770. /**
  32771. * @property {Phaser.Point} positionUp - A Phaser.Point object containing the x/y values of the pointer when it was last released.
  32772. */
  32773. this.positionUp = new Phaser.Point();
  32774. /**
  32775. * A Phaser.Circle that is centered on the x/y coordinates of this pointer, useful for hit detection.
  32776. * The Circle size is 44px (Apples recommended "finger tip" size).
  32777. * @property {Phaser.Circle} circle
  32778. */
  32779. this.circle = new Phaser.Circle(0, 0, 44);
  32780. /**
  32781. * Click trampolines associated with this pointer. See `addClickTrampoline`.
  32782. * @property {object[]|null} _clickTrampolines
  32783. * @private
  32784. */
  32785. this._clickTrampolines = null;
  32786. /**
  32787. * When the Pointer has click trampolines the last target object is stored here
  32788. * so it can be used to check for validity of the trampoline in a post-Up/'stop'.
  32789. * @property {object} _trampolineTargetObject
  32790. * @private
  32791. */
  32792. this._trampolineTargetObject = null;
  32793. };
  32794. /**
  32795. * No buttons at all.
  32796. * @constant
  32797. * @type {number}
  32798. */
  32799. Phaser.Pointer.NO_BUTTON = 0;
  32800. /**
  32801. * The Left Mouse button, or in PointerEvent devices a Touch contact or Pen contact.
  32802. * @constant
  32803. * @type {number}
  32804. */
  32805. Phaser.Pointer.LEFT_BUTTON = 1;
  32806. /**
  32807. * The Right Mouse button, or in PointerEvent devices a Pen contact with a barrel button.
  32808. * @constant
  32809. * @type {number}
  32810. */
  32811. Phaser.Pointer.RIGHT_BUTTON = 2;
  32812. /**
  32813. * The Middle Mouse button.
  32814. * @constant
  32815. * @type {number}
  32816. */
  32817. Phaser.Pointer.MIDDLE_BUTTON = 4;
  32818. /**
  32819. * The X1 button. This is typically the mouse Back button, but is often reconfigured.
  32820. * On Linux (GTK) this is unsupported. On Windows if advanced pointer software (such as IntelliPoint) is installed this doesn't register.
  32821. * @constant
  32822. * @type {number}
  32823. */
  32824. Phaser.Pointer.BACK_BUTTON = 8;
  32825. /**
  32826. * The X2 button. This is typically the mouse Forward button, but is often reconfigured.
  32827. * On Linux (GTK) this is unsupported. On Windows if advanced pointer software (such as IntelliPoint) is installed this doesn't register.
  32828. * @constant
  32829. * @type {number}
  32830. */
  32831. Phaser.Pointer.FORWARD_BUTTON = 16;
  32832. /**
  32833. * The Eraser pen button on PointerEvent supported devices only.
  32834. * @constant
  32835. * @type {number}
  32836. */
  32837. Phaser.Pointer.ERASER_BUTTON = 32;
  32838. Phaser.Pointer.prototype = {
  32839. /**
  32840. * Resets the states of all the button booleans.
  32841. *
  32842. * @method Phaser.Pointer#resetButtons
  32843. * @protected
  32844. */
  32845. resetButtons: function () {
  32846. this.isDown = false;
  32847. this.isUp = true;
  32848. if (this.isMouse)
  32849. {
  32850. this.leftButton.reset();
  32851. this.middleButton.reset();
  32852. this.rightButton.reset();
  32853. this.backButton.reset();
  32854. this.forwardButton.reset();
  32855. this.eraserButton.reset();
  32856. }
  32857. },
  32858. /**
  32859. * Called by updateButtons.
  32860. *
  32861. * @method Phaser.Pointer#processButtonsDown
  32862. * @private
  32863. * @param {integer} buttons - The DOM event.buttons property.
  32864. * @param {MouseEvent} event - The DOM event.
  32865. */
  32866. processButtonsDown: function (buttons, event) {
  32867. // Note: These are bitwise checks, not booleans
  32868. if (Phaser.Pointer.LEFT_BUTTON & buttons)
  32869. {
  32870. this.leftButton.start(event);
  32871. }
  32872. if (Phaser.Pointer.RIGHT_BUTTON & buttons)
  32873. {
  32874. this.rightButton.start(event);
  32875. }
  32876. if (Phaser.Pointer.MIDDLE_BUTTON & buttons)
  32877. {
  32878. this.middleButton.start(event);
  32879. }
  32880. if (Phaser.Pointer.BACK_BUTTON & buttons)
  32881. {
  32882. this.backButton.start(event);
  32883. }
  32884. if (Phaser.Pointer.FORWARD_BUTTON & buttons)
  32885. {
  32886. this.forwardButton.start(event);
  32887. }
  32888. if (Phaser.Pointer.ERASER_BUTTON & buttons)
  32889. {
  32890. this.eraserButton.start(event);
  32891. }
  32892. },
  32893. /**
  32894. * Called by updateButtons.
  32895. *
  32896. * @method Phaser.Pointer#processButtonsUp
  32897. * @private
  32898. * @param {integer} buttons - The DOM event.buttons property.
  32899. * @param {MouseEvent} event - The DOM event.
  32900. */
  32901. processButtonsUp: function (button, event) {
  32902. // Note: These are bitwise checks, not booleans
  32903. if (button === Phaser.Mouse.LEFT_BUTTON)
  32904. {
  32905. this.leftButton.stop(event);
  32906. }
  32907. if (button === Phaser.Mouse.RIGHT_BUTTON)
  32908. {
  32909. this.rightButton.stop(event);
  32910. }
  32911. if (button === Phaser.Mouse.MIDDLE_BUTTON)
  32912. {
  32913. this.middleButton.stop(event);
  32914. }
  32915. if (button === Phaser.Mouse.BACK_BUTTON)
  32916. {
  32917. this.backButton.stop(event);
  32918. }
  32919. if (button === Phaser.Mouse.FORWARD_BUTTON)
  32920. {
  32921. this.forwardButton.stop(event);
  32922. }
  32923. if (button === 5)
  32924. {
  32925. this.eraserButton.stop(event);
  32926. }
  32927. },
  32928. /**
  32929. * Called when the event.buttons property changes from zero.
  32930. * Contains a button bitmask.
  32931. *
  32932. * @method Phaser.Pointer#updateButtons
  32933. * @protected
  32934. * @param {MouseEvent} event - The DOM event.
  32935. */
  32936. updateButtons: function (event) {
  32937. this.button = event.button;
  32938. var down = (event.type.toLowerCase().substr(-4) === 'down');
  32939. if (event.buttons !== undefined)
  32940. {
  32941. if (down)
  32942. {
  32943. this.processButtonsDown(event.buttons, event);
  32944. }
  32945. else
  32946. {
  32947. this.processButtonsUp(event.button, event);
  32948. }
  32949. }
  32950. else
  32951. {
  32952. // No buttons property (like Safari on OSX when using a trackpad)
  32953. if (down)
  32954. {
  32955. this.leftButton.start(event);
  32956. }
  32957. else
  32958. {
  32959. this.leftButton.stop(event);
  32960. this.rightButton.stop(event);
  32961. }
  32962. }
  32963. // On OS X (and other devices with trackpads) you have to press CTRL + the pad
  32964. // to initiate a right-click event, so we'll check for that here ONLY if
  32965. // event.buttons = 1 (i.e. they only have a 1 button mouse or trackpad)
  32966. if (event.buttons === 1 && event.ctrlKey && this.leftButton.isDown)
  32967. {
  32968. this.leftButton.stop(event);
  32969. this.rightButton.start(event);
  32970. }
  32971. this.isUp = true;
  32972. this.isDown = false;
  32973. if (this.leftButton.isDown || this.rightButton.isDown || this.middleButton.isDown || this.backButton.isDown || this.forwardButton.isDown || this.eraserButton.isDown)
  32974. {
  32975. this.isUp = false;
  32976. this.isDown = true;
  32977. }
  32978. },
  32979. /**
  32980. * Called when the Pointer is pressed onto the touchscreen.
  32981. * @method Phaser.Pointer#start
  32982. * @param {any} event - The DOM event from the browser.
  32983. */
  32984. start: function (event) {
  32985. var input = this.game.input;
  32986. if (event['pointerId'])
  32987. {
  32988. this.pointerId = event.pointerId;
  32989. }
  32990. this.identifier = event.identifier;
  32991. this.target = event.target;
  32992. if (this.isMouse)
  32993. {
  32994. this.updateButtons(event);
  32995. }
  32996. else
  32997. {
  32998. this.isDown = true;
  32999. this.isUp = false;
  33000. }
  33001. this.active = true;
  33002. this.withinGame = true;
  33003. this.dirty = false;
  33004. this._history = [];
  33005. this._clickTrampolines = null;
  33006. this._trampolineTargetObject = null;
  33007. // Work out how long it has been since the last click
  33008. this.msSinceLastClick = this.game.time.time - this.timeDown;
  33009. this.timeDown = this.game.time.time;
  33010. this._holdSent = false;
  33011. // This sets the x/y and other local values
  33012. this.move(event, true);
  33013. // x and y are the old values here?
  33014. this.positionDown.setTo(this.x, this.y);
  33015. if (input.multiInputOverride === Phaser.Input.MOUSE_OVERRIDES_TOUCH ||
  33016. input.multiInputOverride === Phaser.Input.MOUSE_TOUCH_COMBINE ||
  33017. (input.multiInputOverride === Phaser.Input.TOUCH_OVERRIDES_MOUSE && input.totalActivePointers === 0))
  33018. {
  33019. input.x = this.x;
  33020. input.y = this.y;
  33021. input.position.setTo(this.x, this.y);
  33022. input.onDown.dispatch(this, event);
  33023. input.resetSpeed(this.x, this.y);
  33024. }
  33025. this._stateReset = false;
  33026. this.totalTouches++;
  33027. if (this.targetObject !== null)
  33028. {
  33029. this.targetObject._touchedHandler(this);
  33030. }
  33031. return this;
  33032. },
  33033. /**
  33034. * Called by the Input Manager.
  33035. * @method Phaser.Pointer#update
  33036. */
  33037. update: function () {
  33038. var input = this.game.input;
  33039. if (this.active)
  33040. {
  33041. // Force a check?
  33042. if (this.dirty)
  33043. {
  33044. if (input.interactiveItems.total > 0)
  33045. {
  33046. this.processInteractiveObjects(false);
  33047. }
  33048. this.dirty = false;
  33049. }
  33050. if (this._holdSent === false && this.duration >= input.holdRate)
  33051. {
  33052. if (input.multiInputOverride === Phaser.Input.MOUSE_OVERRIDES_TOUCH ||
  33053. input.multiInputOverride === Phaser.Input.MOUSE_TOUCH_COMBINE ||
  33054. (input.multiInputOverride === Phaser.Input.TOUCH_OVERRIDES_MOUSE && input.totalActivePointers === 0))
  33055. {
  33056. input.onHold.dispatch(this);
  33057. }
  33058. this._holdSent = true;
  33059. }
  33060. // Update the droppings history
  33061. if (input.recordPointerHistory && this.game.time.time >= this._nextDrop)
  33062. {
  33063. this._nextDrop = this.game.time.time + input.recordRate;
  33064. this._history.push({
  33065. x: this.position.x,
  33066. y: this.position.y
  33067. });
  33068. if (this._history.length > input.recordLimit)
  33069. {
  33070. this._history.shift();
  33071. }
  33072. }
  33073. }
  33074. },
  33075. /**
  33076. * Called when the Pointer is moved.
  33077. *
  33078. * @method Phaser.Pointer#move
  33079. * @param {MouseEvent|PointerEvent|TouchEvent} event - The event passed up from the input handler.
  33080. * @param {boolean} [fromClick=false] - Was this called from the click event?
  33081. */
  33082. move: function (event, fromClick) {
  33083. var input = this.game.input;
  33084. if (input.pollLocked)
  33085. {
  33086. return;
  33087. }
  33088. if (fromClick === undefined) { fromClick = false; }
  33089. if (event.button !== undefined)
  33090. {
  33091. this.button = event.button;
  33092. }
  33093. if (fromClick && this.isMouse)
  33094. {
  33095. this.updateButtons(event);
  33096. }
  33097. this.clientX = event.clientX;
  33098. this.clientY = event.clientY;
  33099. this.pageX = event.pageX;
  33100. this.pageY = event.pageY;
  33101. this.screenX = event.screenX;
  33102. this.screenY = event.screenY;
  33103. if (this.isMouse && input.mouse.locked && !fromClick)
  33104. {
  33105. this.rawMovementX = event.movementX || event.mozMovementX || event.webkitMovementX || 0;
  33106. this.rawMovementY = event.movementY || event.mozMovementY || event.webkitMovementY || 0;
  33107. this.movementX += this.rawMovementX;
  33108. this.movementY += this.rawMovementY;
  33109. }
  33110. this.x = (this.pageX - this.game.scale.offset.x) * input.scale.x;
  33111. this.y = (this.pageY - this.game.scale.offset.y) * input.scale.y;
  33112. this.position.setTo(this.x, this.y);
  33113. this.circle.x = this.x;
  33114. this.circle.y = this.y;
  33115. if (input.multiInputOverride === Phaser.Input.MOUSE_OVERRIDES_TOUCH ||
  33116. input.multiInputOverride === Phaser.Input.MOUSE_TOUCH_COMBINE ||
  33117. (input.multiInputOverride === Phaser.Input.TOUCH_OVERRIDES_MOUSE && input.totalActivePointers === 0))
  33118. {
  33119. input.activePointer = this;
  33120. input.x = this.x;
  33121. input.y = this.y;
  33122. input.position.setTo(input.x, input.y);
  33123. input.circle.x = input.x;
  33124. input.circle.y = input.y;
  33125. }
  33126. this.withinGame = this.game.scale.bounds.contains(this.pageX, this.pageY);
  33127. // If the game is paused we don't process any target objects or callbacks
  33128. if (this.game.paused)
  33129. {
  33130. return this;
  33131. }
  33132. var i = input.moveCallbacks.length;
  33133. while (i--)
  33134. {
  33135. input.moveCallbacks[i].callback.call(input.moveCallbacks[i].context, this, this.x, this.y, fromClick);
  33136. }
  33137. // Easy out if we're dragging something and it still exists
  33138. if (this.targetObject !== null && this.targetObject.isDragged === true)
  33139. {
  33140. if (this.targetObject.update(this) === false)
  33141. {
  33142. this.targetObject = null;
  33143. }
  33144. }
  33145. else if (input.interactiveItems.total > 0)
  33146. {
  33147. this.processInteractiveObjects(fromClick);
  33148. }
  33149. return this;
  33150. },
  33151. /**
  33152. * Process all interactive objects to find out which ones were updated in the recent Pointer move.
  33153. *
  33154. * @method Phaser.Pointer#processInteractiveObjects
  33155. * @protected
  33156. * @param {boolean} [fromClick=false] - Was this called from the click event?
  33157. * @return {boolean} True if this method processes an object (i.e. a Sprite becomes the Pointers currentTarget), otherwise false.
  33158. */
  33159. processInteractiveObjects: function (fromClick) {
  33160. // Work out which object is on the top
  33161. var highestRenderOrderID = 0;
  33162. var highestInputPriorityID = -1;
  33163. var candidateTarget = null;
  33164. // First pass gets all objects that the pointer is over that DON'T use pixelPerfect checks and get the highest ID
  33165. // We know they'll be valid for input detection but not which is the top just yet
  33166. var currentNode = this.game.input.interactiveItems.first;
  33167. this.interactiveCandidates = [];
  33168. while (currentNode)
  33169. {
  33170. // Reset checked status
  33171. currentNode.checked = false;
  33172. if (currentNode.validForInput(highestInputPriorityID, highestRenderOrderID, false))
  33173. {
  33174. // Flag it as checked so we don't re-scan it on the next phase
  33175. currentNode.checked = true;
  33176. if ((fromClick && currentNode.checkPointerDown(this, true)) ||
  33177. (!fromClick && currentNode.checkPointerOver(this, true)))
  33178. {
  33179. highestRenderOrderID = currentNode.sprite.renderOrderID;
  33180. highestInputPriorityID = currentNode.priorityID;
  33181. candidateTarget = currentNode;
  33182. this.interactiveCandidates.push(currentNode);
  33183. }
  33184. }
  33185. currentNode = this.game.input.interactiveItems.next;
  33186. }
  33187. // Then in the second sweep we process ONLY the pixel perfect ones that are checked and who have a higher ID
  33188. // because if their ID is lower anyway then we can just automatically discount them
  33189. // (A node that was previously checked did not request a pixel-perfect check.)
  33190. currentNode = this.game.input.interactiveItems.first;
  33191. while (currentNode)
  33192. {
  33193. if (!currentNode.checked &&
  33194. currentNode.validForInput(highestInputPriorityID, highestRenderOrderID, true))
  33195. {
  33196. if ((fromClick && currentNode.checkPointerDown(this, false)) ||
  33197. (!fromClick && currentNode.checkPointerOver(this, false)))
  33198. {
  33199. highestRenderOrderID = currentNode.sprite.renderOrderID;
  33200. highestInputPriorityID = currentNode.priorityID;
  33201. candidateTarget = currentNode;
  33202. this.interactiveCandidates.push(currentNode);
  33203. }
  33204. }
  33205. currentNode = this.game.input.interactiveItems.next;
  33206. }
  33207. if (this.game.input.customCandidateHandler)
  33208. {
  33209. candidateTarget = this.game.input.customCandidateHandler.call(this.game.input.customCandidateHandlerContext, this, this.interactiveCandidates, candidateTarget);
  33210. }
  33211. this.swapTarget(candidateTarget, false);
  33212. return (this.targetObject !== null);
  33213. },
  33214. /**
  33215. * This will change the `Pointer.targetObject` object to be the one provided.
  33216. *
  33217. * This allows you to have fine-grained control over which object the Pointer is targeting.
  33218. *
  33219. * Note that even if you set a new Target here, it is still able to be replaced by any other valid
  33220. * target during the next Pointer update.
  33221. *
  33222. * @method Phaser.Pointer#swapTarget
  33223. * @param {Phaser.InputHandler} newTarget - The new target for this Pointer. Note this is an `InputHandler`, so don't pass a Sprite, instead pass `sprite.input` to it.
  33224. * @param {boolean} [silent=false] - If true the new target AND the old one will NOT dispatch their `onInputOver` or `onInputOut` events.
  33225. */
  33226. swapTarget: function (newTarget, silent) {
  33227. if (silent === undefined) { silent = false; }
  33228. // Now we know the top-most item (if any) we can process it
  33229. if (newTarget === null)
  33230. {
  33231. // The pointer isn't currently over anything, check if we've got a lingering previous target
  33232. if (this.targetObject)
  33233. {
  33234. this.targetObject._pointerOutHandler(this, silent);
  33235. this.targetObject = null;
  33236. }
  33237. }
  33238. else
  33239. {
  33240. if (this.targetObject === null)
  33241. {
  33242. // And now set the new one
  33243. this.targetObject = newTarget;
  33244. newTarget._pointerOverHandler(this, silent);
  33245. }
  33246. else
  33247. {
  33248. // We've got a target from the last update
  33249. if (this.targetObject === newTarget)
  33250. {
  33251. // Same target as before, so update it
  33252. if (newTarget.update(this) === false)
  33253. {
  33254. this.targetObject = null;
  33255. }
  33256. }
  33257. else
  33258. {
  33259. // The target has changed, so tell the old one we've left it
  33260. this.targetObject._pointerOutHandler(this, silent);
  33261. // And now set the new one
  33262. this.targetObject = newTarget;
  33263. this.targetObject._pointerOverHandler(this, silent);
  33264. }
  33265. }
  33266. }
  33267. },
  33268. /**
  33269. * Called when the Pointer leaves the target area.
  33270. *
  33271. * @method Phaser.Pointer#leave
  33272. * @param {MouseEvent|PointerEvent|TouchEvent} event - The event passed up from the input handler.
  33273. */
  33274. leave: function (event) {
  33275. this.withinGame = false;
  33276. this.move(event, false);
  33277. },
  33278. /**
  33279. * Called when the Pointer leaves the touchscreen.
  33280. *
  33281. * @method Phaser.Pointer#stop
  33282. * @param {MouseEvent|PointerEvent|TouchEvent} event - The event passed up from the input handler.
  33283. */
  33284. stop: function (event) {
  33285. var input = this.game.input;
  33286. if (this._stateReset && this.withinGame)
  33287. {
  33288. event.preventDefault();
  33289. return;
  33290. }
  33291. this.timeUp = this.game.time.time;
  33292. if (input.multiInputOverride === Phaser.Input.MOUSE_OVERRIDES_TOUCH ||
  33293. input.multiInputOverride === Phaser.Input.MOUSE_TOUCH_COMBINE ||
  33294. (input.multiInputOverride === Phaser.Input.TOUCH_OVERRIDES_MOUSE && input.totalActivePointers === 0))
  33295. {
  33296. input.onUp.dispatch(this, event);
  33297. // Was it a tap?
  33298. if (this.duration >= 0 && this.duration <= input.tapRate)
  33299. {
  33300. // Was it a double-tap?
  33301. if (this.timeUp - this.previousTapTime < input.doubleTapRate)
  33302. {
  33303. // Yes, let's dispatch the signal then with the 2nd parameter set to true
  33304. input.onTap.dispatch(this, true);
  33305. }
  33306. else
  33307. {
  33308. // Wasn't a double-tap, so dispatch a single tap signal
  33309. input.onTap.dispatch(this, false);
  33310. }
  33311. this.previousTapTime = this.timeUp;
  33312. }
  33313. }
  33314. if (this.isMouse)
  33315. {
  33316. this.updateButtons(event);
  33317. }
  33318. else
  33319. {
  33320. this.isDown = false;
  33321. this.isUp = true;
  33322. }
  33323. // Mouse is always active
  33324. if (this.id > 0)
  33325. {
  33326. this.active = false;
  33327. }
  33328. this.withinGame = this.game.scale.bounds.contains(event.pageX, event.pageY);
  33329. this.pointerId = null;
  33330. this.identifier = null;
  33331. this.positionUp.setTo(this.x, this.y);
  33332. if (this.isMouse === false)
  33333. {
  33334. input.currentPointers--;
  33335. }
  33336. input.interactiveItems.callAll('_releasedHandler', this);
  33337. if (this._clickTrampolines)
  33338. {
  33339. this._trampolineTargetObject = this.targetObject;
  33340. }
  33341. this.targetObject = null;
  33342. return this;
  33343. },
  33344. /**
  33345. * The Pointer is considered justPressed if the time it was pressed onto the touchscreen or clicked is less than justPressedRate.
  33346. * Note that calling justPressed doesn't reset the pressed status of the Pointer, it will return `true` for as long as the duration is valid.
  33347. * If you wish to check if the Pointer was pressed down just once then see the Sprite.events.onInputDown event.
  33348. * @method Phaser.Pointer#justPressed
  33349. * @param {number} [duration] - The time to check against. If none given it will use InputManager.justPressedRate.
  33350. * @return {boolean} true if the Pointer was pressed down within the duration given.
  33351. */
  33352. justPressed: function (duration) {
  33353. duration = duration || this.game.input.justPressedRate;
  33354. return (this.isDown === true && (this.timeDown + duration) > this.game.time.time);
  33355. },
  33356. /**
  33357. * The Pointer is considered justReleased if the time it left the touchscreen is less than justReleasedRate.
  33358. * Note that calling justReleased doesn't reset the pressed status of the Pointer, it will return `true` for as long as the duration is valid.
  33359. * If you wish to check if the Pointer was released just once then see the Sprite.events.onInputUp event.
  33360. * @method Phaser.Pointer#justReleased
  33361. * @param {number} [duration] - The time to check against. If none given it will use InputManager.justReleasedRate.
  33362. * @return {boolean} true if the Pointer was released within the duration given.
  33363. */
  33364. justReleased: function (duration) {
  33365. duration = duration || this.game.input.justReleasedRate;
  33366. return (this.isUp && (this.timeUp + duration) > this.game.time.time);
  33367. },
  33368. /**
  33369. * Add a click trampoline to this pointer.
  33370. *
  33371. * A click trampoline is a callback that is run on the DOM 'click' event; this is primarily
  33372. * needed with certain browsers (ie. IE11) which restrict some actions like requestFullscreen
  33373. * to the DOM 'click' event and rejects it for 'pointer*' and 'mouse*' events.
  33374. *
  33375. * This is used internally by the ScaleManager; click trampoline usage is uncommon.
  33376. * Click trampolines can only be added to pointers that are currently down.
  33377. *
  33378. * @method Phaser.Pointer#addClickTrampoline
  33379. * @protected
  33380. * @param {string} name - The name of the trampoline; must be unique among active trampolines in this pointer.
  33381. * @param {function} callback - Callback to run/trampoline.
  33382. * @param {object} callbackContext - Context of the callback.
  33383. * @param {object[]|null} callbackArgs - Additional callback args, if any. Supplied as an array.
  33384. */
  33385. addClickTrampoline: function (name, callback, callbackContext, callbackArgs) {
  33386. if (!this.isDown)
  33387. {
  33388. return;
  33389. }
  33390. var trampolines = (this._clickTrampolines = this._clickTrampolines || []);
  33391. for (var i = 0; i < trampolines.length; i++)
  33392. {
  33393. if (trampolines[i].name === name)
  33394. {
  33395. trampolines.splice(i, 1);
  33396. break;
  33397. }
  33398. }
  33399. trampolines.push({
  33400. name: name,
  33401. targetObject: this.targetObject,
  33402. callback: callback,
  33403. callbackContext: callbackContext,
  33404. callbackArgs: callbackArgs
  33405. });
  33406. },
  33407. /**
  33408. * Fire all click trampolines for which the pointers are still referring to the registered object.
  33409. * @method Phaser.Pointer#processClickTrampolines
  33410. * @private
  33411. */
  33412. processClickTrampolines: function () {
  33413. var trampolines = this._clickTrampolines;
  33414. if (!trampolines)
  33415. {
  33416. return;
  33417. }
  33418. for (var i = 0; i < trampolines.length; i++)
  33419. {
  33420. var trampoline = trampolines[i];
  33421. if (trampoline.targetObject === this._trampolineTargetObject)
  33422. {
  33423. trampoline.callback.apply(trampoline.callbackContext, trampoline.callbackArgs);
  33424. }
  33425. }
  33426. this._clickTrampolines = null;
  33427. this._trampolineTargetObject = null;
  33428. },
  33429. /**
  33430. * Resets the Pointer properties. Called by InputManager.reset when you perform a State change.
  33431. * @method Phaser.Pointer#reset
  33432. */
  33433. reset: function () {
  33434. if (this.isMouse === false)
  33435. {
  33436. this.active = false;
  33437. }
  33438. this.pointerId = null;
  33439. this.identifier = null;
  33440. this.dirty = false;
  33441. this.totalTouches = 0;
  33442. this._holdSent = false;
  33443. this._history.length = 0;
  33444. this._stateReset = true;
  33445. this.resetButtons();
  33446. if (this.targetObject)
  33447. {
  33448. this.targetObject._releasedHandler(this);
  33449. }
  33450. this.targetObject = null;
  33451. },
  33452. /**
  33453. * Resets the movementX and movementY properties. Use in your update handler after retrieving the values.
  33454. * @method Phaser.Pointer#resetMovement
  33455. */
  33456. resetMovement: function() {
  33457. this.movementX = 0;
  33458. this.movementY = 0;
  33459. }
  33460. };
  33461. Phaser.Pointer.prototype.constructor = Phaser.Pointer;
  33462. /**
  33463. * How long the Pointer has been depressed on the touchscreen or *any* of the mouse buttons have been held down.
  33464. * If not currently down it returns -1.
  33465. * If you need to test a specific mouse or pen button then access the buttons directly, i.e. `Pointer.rightButton.duration`.
  33466. *
  33467. * @name Phaser.Pointer#duration
  33468. * @property {number} duration
  33469. * @readonly
  33470. */
  33471. Object.defineProperty(Phaser.Pointer.prototype, "duration", {
  33472. get: function () {
  33473. if (this.isUp)
  33474. {
  33475. return -1;
  33476. }
  33477. return this.game.time.time - this.timeDown;
  33478. }
  33479. });
  33480. /**
  33481. * Gets the X value of this Pointer in world coordinates based on the world camera.
  33482. * @name Phaser.Pointer#worldX
  33483. * @property {number} worldX - The X value of this Pointer in world coordinates based on the world camera.
  33484. * @readonly
  33485. */
  33486. Object.defineProperty(Phaser.Pointer.prototype, "worldX", {
  33487. get: function () {
  33488. return this.game.world.camera.x + this.x;
  33489. }
  33490. });
  33491. /**
  33492. * Gets the Y value of this Pointer in world coordinates based on the world camera.
  33493. * @name Phaser.Pointer#worldY
  33494. * @property {number} worldY - The Y value of this Pointer in world coordinates based on the world camera.
  33495. * @readonly
  33496. */
  33497. Object.defineProperty(Phaser.Pointer.prototype, "worldY", {
  33498. get: function () {
  33499. return this.game.world.camera.y + this.y;
  33500. }
  33501. });
  33502. /**
  33503. * Enumeration categorizing operational modes of pointers.
  33504. *
  33505. * PointerType values represent valid bitmasks.
  33506. * For example, a value representing both Mouse and Touch devices
  33507. * can be expressed as `PointerMode.CURSOR | PointerMode.CONTACT`.
  33508. *
  33509. * Values may be added for future mode categorizations.
  33510. * @class Phaser.PointerMode
  33511. */
  33512. Phaser.PointerMode = {
  33513. /**
  33514. * A 'CURSOR' is a pointer with a *passive cursor* such as a mouse, touchpad, watcom stylus, or even TV-control arrow-pad.
  33515. *
  33516. * It has the property that a cursor is passively moved without activating the input.
  33517. * This currently corresponds with {@link Phaser.Pointer#isMouse} property.
  33518. * @constant
  33519. */
  33520. CURSOR: 1 << 0,
  33521. /**
  33522. * A 'CONTACT' pointer has an *active cursor* that only tracks movement when actived; notably this is a touch-style input.
  33523. * @constant
  33524. */
  33525. CONTACT: 1 << 1
  33526. };
  33527. /**
  33528. * @author Richard Davey <rich@photonstorm.com>
  33529. * @copyright 2016 Photon Storm Ltd.
  33530. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  33531. */
  33532. /**
  33533. * Phaser.Touch handles touch events with your game. Note: Android 2.x only supports 1 touch event at once, no multi-touch.
  33534. *
  33535. * You should not normally access this class directly, but instead use a Phaser.Pointer object which normalises all game input for you.
  33536. *
  33537. * @class Phaser.Touch
  33538. * @constructor
  33539. * @param {Phaser.Game} game - A reference to the currently running game.
  33540. */
  33541. Phaser.Touch = function (game) {
  33542. /**
  33543. * @property {Phaser.Game} game - A reference to the currently running game.
  33544. */
  33545. this.game = game;
  33546. /**
  33547. * Touch events will only be processed if enabled.
  33548. * @property {boolean} enabled
  33549. * @default
  33550. */
  33551. this.enabled = true;
  33552. /**
  33553. * An array of callbacks that will be fired every time a native touch start or touch end event is received from the browser.
  33554. * This is used internally to handle audio and video unlocking on mobile devices.
  33555. * To add a callback to this array please use `Touch.addTouchLockCallback`.
  33556. * @property {array} touchLockCallbacks
  33557. * @protected
  33558. */
  33559. this.touchLockCallbacks = [];
  33560. /**
  33561. * @property {object} callbackContext - The context under which callbacks are called.
  33562. */
  33563. this.callbackContext = this.game;
  33564. /**
  33565. * @property {function} touchStartCallback - A callback that can be fired on a touchStart event.
  33566. */
  33567. this.touchStartCallback = null;
  33568. /**
  33569. * @property {function} touchMoveCallback - A callback that can be fired on a touchMove event.
  33570. */
  33571. this.touchMoveCallback = null;
  33572. /**
  33573. * @property {function} touchEndCallback - A callback that can be fired on a touchEnd event.
  33574. */
  33575. this.touchEndCallback = null;
  33576. /**
  33577. * @property {function} touchEnterCallback - A callback that can be fired on a touchEnter event.
  33578. */
  33579. this.touchEnterCallback = null;
  33580. /**
  33581. * @property {function} touchLeaveCallback - A callback that can be fired on a touchLeave event.
  33582. */
  33583. this.touchLeaveCallback = null;
  33584. /**
  33585. * @property {function} touchCancelCallback - A callback that can be fired on a touchCancel event.
  33586. */
  33587. this.touchCancelCallback = null;
  33588. /**
  33589. * @property {boolean} preventDefault - If true the TouchEvent will have prevent.default called on it.
  33590. * @default
  33591. */
  33592. this.preventDefault = true;
  33593. /**
  33594. * @property {TouchEvent} event - The browser touch DOM event. Will be set to null if no touch event has ever been received.
  33595. * @default
  33596. */
  33597. this.event = null;
  33598. /**
  33599. * @property {function} _onTouchStart - Internal event handler reference.
  33600. * @private
  33601. */
  33602. this._onTouchStart = null;
  33603. /**
  33604. * @property {function} _onTouchMove - Internal event handler reference.
  33605. * @private
  33606. */
  33607. this._onTouchMove = null;
  33608. /**
  33609. * @property {function} _onTouchEnd - Internal event handler reference.
  33610. * @private
  33611. */
  33612. this._onTouchEnd = null;
  33613. /**
  33614. * @property {function} _onTouchEnter - Internal event handler reference.
  33615. * @private
  33616. */
  33617. this._onTouchEnter = null;
  33618. /**
  33619. * @property {function} _onTouchLeave - Internal event handler reference.
  33620. * @private
  33621. */
  33622. this._onTouchLeave = null;
  33623. /**
  33624. * @property {function} _onTouchCancel - Internal event handler reference.
  33625. * @private
  33626. */
  33627. this._onTouchCancel = null;
  33628. /**
  33629. * @property {function} _onTouchMove - Internal event handler reference.
  33630. * @private
  33631. */
  33632. this._onTouchMove = null;
  33633. };
  33634. Phaser.Touch.prototype = {
  33635. /**
  33636. * Starts the event listeners running.
  33637. * @method Phaser.Touch#start
  33638. */
  33639. start: function () {
  33640. if (this._onTouchStart !== null)
  33641. {
  33642. // Avoid setting multiple listeners
  33643. return;
  33644. }
  33645. var _this = this;
  33646. if (this.game.device.touch)
  33647. {
  33648. this._onTouchStart = function (event) {
  33649. return _this.onTouchStart(event);
  33650. };
  33651. this._onTouchMove = function (event) {
  33652. return _this.onTouchMove(event);
  33653. };
  33654. this._onTouchEnd = function (event) {
  33655. return _this.onTouchEnd(event);
  33656. };
  33657. this._onTouchEnter = function (event) {
  33658. return _this.onTouchEnter(event);
  33659. };
  33660. this._onTouchLeave = function (event) {
  33661. return _this.onTouchLeave(event);
  33662. };
  33663. this._onTouchCancel = function (event) {
  33664. return _this.onTouchCancel(event);
  33665. };
  33666. this.game.canvas.addEventListener('touchstart', this._onTouchStart, false);
  33667. this.game.canvas.addEventListener('touchmove', this._onTouchMove, false);
  33668. this.game.canvas.addEventListener('touchend', this._onTouchEnd, false);
  33669. this.game.canvas.addEventListener('touchcancel', this._onTouchCancel, false);
  33670. if (!this.game.device.cocoonJS)
  33671. {
  33672. this.game.canvas.addEventListener('touchenter', this._onTouchEnter, false);
  33673. this.game.canvas.addEventListener('touchleave', this._onTouchLeave, false);
  33674. }
  33675. }
  33676. },
  33677. /**
  33678. * Consumes all touchmove events on the document (only enable this if you know you need it!).
  33679. * @method Phaser.Touch#consumeTouchMove
  33680. */
  33681. consumeDocumentTouches: function () {
  33682. this._documentTouchMove = function (event) {
  33683. event.preventDefault();
  33684. };
  33685. document.addEventListener('touchmove', this._documentTouchMove, false);
  33686. },
  33687. /**
  33688. * Adds a callback that is fired when a browser touchstart or touchend event is received.
  33689. *
  33690. * This is used internally to handle audio and video unlocking on mobile devices.
  33691. *
  33692. * If the callback returns 'true' then the callback is automatically deleted once invoked.
  33693. *
  33694. * The callback is added to the Phaser.Touch.touchLockCallbacks array and should be removed with Phaser.Touch.removeTouchLockCallback.
  33695. *
  33696. * @method Phaser.Touch#addTouchLockCallback
  33697. * @param {function} callback - The callback that will be called when a touchstart event is received.
  33698. * @param {object} context - The context in which the callback will be called.
  33699. * @param {boolean} [onEnd=false] - Will the callback fire on a touchstart (default) or touchend event?
  33700. */
  33701. addTouchLockCallback: function (callback, context, onEnd) {
  33702. if (onEnd === undefined) { onEnd = false; }
  33703. this.touchLockCallbacks.push({ callback: callback, context: context, onEnd: onEnd });
  33704. },
  33705. /**
  33706. * Removes the callback at the defined index from the Phaser.Touch.touchLockCallbacks array
  33707. *
  33708. * @method Phaser.Touch#removeTouchLockCallback
  33709. * @param {function} callback - The callback to be removed.
  33710. * @param {object} context - The context in which the callback exists.
  33711. * @return {boolean} True if the callback was deleted, otherwise false.
  33712. */
  33713. removeTouchLockCallback: function (callback, context) {
  33714. var i = this.touchLockCallbacks.length;
  33715. while (i--)
  33716. {
  33717. if (this.touchLockCallbacks[i].callback === callback && this.touchLockCallbacks[i].context === context)
  33718. {
  33719. this.touchLockCallbacks.splice(i, 1);
  33720. return true;
  33721. }
  33722. }
  33723. return false;
  33724. },
  33725. /**
  33726. * The internal method that handles the touchstart event from the browser.
  33727. * @method Phaser.Touch#onTouchStart
  33728. * @param {TouchEvent} event - The native event from the browser. This gets stored in Touch.event.
  33729. */
  33730. onTouchStart: function (event) {
  33731. var i = this.touchLockCallbacks.length;
  33732. while (i--)
  33733. {
  33734. var cb = this.touchLockCallbacks[i];
  33735. if (!cb.onEnd && cb.callback.call(cb.context, this, event))
  33736. {
  33737. this.touchLockCallbacks.splice(i, 1);
  33738. }
  33739. }
  33740. this.event = event;
  33741. if (!this.game.input.enabled || !this.enabled)
  33742. {
  33743. return;
  33744. }
  33745. if (this.touchStartCallback)
  33746. {
  33747. this.touchStartCallback.call(this.callbackContext, event);
  33748. }
  33749. if (this.preventDefault)
  33750. {
  33751. event.preventDefault();
  33752. }
  33753. // event.targetTouches = list of all touches on the TARGET ELEMENT (i.e. game dom element)
  33754. // event.touches = list of all touches on the ENTIRE DOCUMENT, not just the target element
  33755. // event.changedTouches = the touches that CHANGED in this event, not the total number of them
  33756. for (var i = 0; i < event.changedTouches.length; i++)
  33757. {
  33758. this.game.input.startPointer(event.changedTouches[i]);
  33759. }
  33760. },
  33761. /**
  33762. * Touch cancel - touches that were disrupted (perhaps by moving into a plugin or browser chrome).
  33763. * Occurs for example on iOS when you put down 4 fingers and the app selector UI appears.
  33764. * @method Phaser.Touch#onTouchCancel
  33765. * @param {TouchEvent} event - The native event from the browser. This gets stored in Touch.event.
  33766. */
  33767. onTouchCancel: function (event) {
  33768. this.event = event;
  33769. if (this.touchCancelCallback)
  33770. {
  33771. this.touchCancelCallback.call(this.callbackContext, event);
  33772. }
  33773. if (!this.game.input.enabled || !this.enabled)
  33774. {
  33775. return;
  33776. }
  33777. if (this.preventDefault)
  33778. {
  33779. event.preventDefault();
  33780. }
  33781. // Touch cancel - touches that were disrupted (perhaps by moving into a plugin or browser chrome)
  33782. // http://www.w3.org/TR/touch-events/#dfn-touchcancel
  33783. for (var i = 0; i < event.changedTouches.length; i++)
  33784. {
  33785. this.game.input.stopPointer(event.changedTouches[i]);
  33786. }
  33787. },
  33788. /**
  33789. * For touch enter and leave its a list of the touch points that have entered or left the target.
  33790. * Doesn't appear to be supported by most browsers on a canvas element yet.
  33791. * @method Phaser.Touch#onTouchEnter
  33792. * @param {TouchEvent} event - The native event from the browser. This gets stored in Touch.event.
  33793. */
  33794. onTouchEnter: function (event) {
  33795. this.event = event;
  33796. if (this.touchEnterCallback)
  33797. {
  33798. this.touchEnterCallback.call(this.callbackContext, event);
  33799. }
  33800. if (!this.game.input.enabled || !this.enabled)
  33801. {
  33802. return;
  33803. }
  33804. if (this.preventDefault)
  33805. {
  33806. event.preventDefault();
  33807. }
  33808. },
  33809. /**
  33810. * For touch enter and leave its a list of the touch points that have entered or left the target.
  33811. * Doesn't appear to be supported by most browsers on a canvas element yet.
  33812. * @method Phaser.Touch#onTouchLeave
  33813. * @param {TouchEvent} event - The native event from the browser. This gets stored in Touch.event.
  33814. */
  33815. onTouchLeave: function (event) {
  33816. this.event = event;
  33817. if (this.touchLeaveCallback)
  33818. {
  33819. this.touchLeaveCallback.call(this.callbackContext, event);
  33820. }
  33821. if (this.preventDefault)
  33822. {
  33823. event.preventDefault();
  33824. }
  33825. },
  33826. /**
  33827. * The handler for the touchmove events.
  33828. * @method Phaser.Touch#onTouchMove
  33829. * @param {TouchEvent} event - The native event from the browser. This gets stored in Touch.event.
  33830. */
  33831. onTouchMove: function (event) {
  33832. this.event = event;
  33833. if (this.touchMoveCallback)
  33834. {
  33835. this.touchMoveCallback.call(this.callbackContext, event);
  33836. }
  33837. if (this.preventDefault)
  33838. {
  33839. event.preventDefault();
  33840. }
  33841. for (var i = 0; i < event.changedTouches.length; i++)
  33842. {
  33843. this.game.input.updatePointer(event.changedTouches[i]);
  33844. }
  33845. },
  33846. /**
  33847. * The handler for the touchend events.
  33848. * @method Phaser.Touch#onTouchEnd
  33849. * @param {TouchEvent} event - The native event from the browser. This gets stored in Touch.event.
  33850. */
  33851. onTouchEnd: function (event) {
  33852. var i = this.touchLockCallbacks.length;
  33853. while (i--)
  33854. {
  33855. var cb = this.touchLockCallbacks[i];
  33856. if (cb.onEnd && cb.callback.call(cb.context, this, event))
  33857. {
  33858. this.touchLockCallbacks.splice(i, 1);
  33859. }
  33860. }
  33861. this.event = event;
  33862. if (this.touchEndCallback)
  33863. {
  33864. this.touchEndCallback.call(this.callbackContext, event);
  33865. }
  33866. if (this.preventDefault)
  33867. {
  33868. event.preventDefault();
  33869. }
  33870. // For touch end its a list of the touch points that have been removed from the surface
  33871. // https://developer.mozilla.org/en-US/docs/DOM/TouchList
  33872. // event.changedTouches = the touches that CHANGED in this event, not the total number of them
  33873. for (var i = 0; i < event.changedTouches.length; i++)
  33874. {
  33875. this.game.input.stopPointer(event.changedTouches[i]);
  33876. }
  33877. },
  33878. /**
  33879. * Stop the event listeners.
  33880. * @method Phaser.Touch#stop
  33881. */
  33882. stop: function () {
  33883. if (this.game.device.touch)
  33884. {
  33885. this.game.canvas.removeEventListener('touchstart', this._onTouchStart);
  33886. this.game.canvas.removeEventListener('touchmove', this._onTouchMove);
  33887. this.game.canvas.removeEventListener('touchend', this._onTouchEnd);
  33888. this.game.canvas.removeEventListener('touchenter', this._onTouchEnter);
  33889. this.game.canvas.removeEventListener('touchleave', this._onTouchLeave);
  33890. this.game.canvas.removeEventListener('touchcancel', this._onTouchCancel);
  33891. }
  33892. }
  33893. };
  33894. Phaser.Touch.prototype.constructor = Phaser.Touch;
  33895. /**
  33896. * @author Richard Davey <rich@photonstorm.com>
  33897. * @copyright 2016 Photon Storm Ltd.
  33898. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  33899. */
  33900. /**
  33901. * The Input Handler is bound to a specific Sprite and is responsible for managing all Input events on that Sprite.
  33902. *
  33903. * @class Phaser.InputHandler
  33904. * @constructor
  33905. * @param {Phaser.Sprite} sprite - The Sprite object to which this Input Handler belongs.
  33906. */
  33907. Phaser.InputHandler = function (sprite) {
  33908. /**
  33909. * @property {Phaser.Sprite} sprite - The Sprite object to which this Input Handler belongs.
  33910. */
  33911. this.sprite = sprite;
  33912. /**
  33913. * @property {Phaser.Game} game - A reference to the currently running game.
  33914. */
  33915. this.game = sprite.game;
  33916. /**
  33917. * @property {boolean} enabled - If enabled the Input Handler will process input requests and monitor pointer activity.
  33918. * @default
  33919. */
  33920. this.enabled = false;
  33921. /**
  33922. * @property {boolean} checked - A disposable flag used by the Pointer class when performing priority checks.
  33923. * @protected
  33924. */
  33925. this.checked = false;
  33926. /**
  33927. * The priorityID is used to determine which game objects should get priority when input events occur. For example if you have
  33928. * several Sprites that overlap, by default the one at the top of the display list is given priority for input events. You can
  33929. * stop this from happening by controlling the priorityID value. The higher the value, the more important they are considered to the Input events.
  33930. * @property {number} priorityID
  33931. * @default
  33932. */
  33933. this.priorityID = 0;
  33934. /**
  33935. * @property {boolean} useHandCursor - On a desktop browser you can set the 'hand' cursor to appear when moving over the Sprite.
  33936. * @default
  33937. */
  33938. this.useHandCursor = false;
  33939. /**
  33940. * @property {boolean} _setHandCursor - Did this Sprite trigger the hand cursor?
  33941. * @private
  33942. */
  33943. this._setHandCursor = false;
  33944. /**
  33945. * @property {boolean} isDragged - true if the Sprite is being currently dragged.
  33946. * @default
  33947. */
  33948. this.isDragged = false;
  33949. /**
  33950. * @property {boolean} allowHorizontalDrag - Controls if the Sprite is allowed to be dragged horizontally.
  33951. * @default
  33952. */
  33953. this.allowHorizontalDrag = true;
  33954. /**
  33955. * @property {boolean} allowVerticalDrag - Controls if the Sprite is allowed to be dragged vertically.
  33956. * @default
  33957. */
  33958. this.allowVerticalDrag = true;
  33959. /**
  33960. * @property {boolean} bringToTop - If true when this Sprite is clicked or dragged it will automatically be bought to the top of the Group it is within.
  33961. * @default
  33962. */
  33963. this.bringToTop = false;
  33964. /**
  33965. * @property {Phaser.Point} snapOffset - A Point object that contains by how far the Sprite snap is offset.
  33966. * @default
  33967. */
  33968. this.snapOffset = null;
  33969. /**
  33970. * @property {boolean} snapOnDrag - When the Sprite is dragged this controls if the center of the Sprite will snap to the pointer on drag or not.
  33971. * @default
  33972. */
  33973. this.snapOnDrag = false;
  33974. /**
  33975. * @property {boolean} snapOnRelease - When the Sprite is dragged this controls if the Sprite will be snapped on release.
  33976. * @default
  33977. */
  33978. this.snapOnRelease = false;
  33979. /**
  33980. * @property {number} snapX - When a Sprite has snapping enabled this holds the width of the snap grid.
  33981. * @default
  33982. */
  33983. this.snapX = 0;
  33984. /**
  33985. * @property {number} snapY - When a Sprite has snapping enabled this holds the height of the snap grid.
  33986. * @default
  33987. */
  33988. this.snapY = 0;
  33989. /**
  33990. * @property {number} snapOffsetX - This defines the top-left X coordinate of the snap grid.
  33991. * @default
  33992. */
  33993. this.snapOffsetX = 0;
  33994. /**
  33995. * @property {number} snapOffsetY - This defines the top-left Y coordinate of the snap grid..
  33996. * @default
  33997. */
  33998. this.snapOffsetY = 0;
  33999. /**
  34000. * Set to true to use pixel perfect hit detection when checking if the pointer is over this Sprite.
  34001. * The x/y coordinates of the pointer are tested against the image in combination with the InputHandler.pixelPerfectAlpha value.
  34002. * This feature only works for display objects with image based textures such as Sprites. It won't work on BitmapText or Rope.
  34003. * Warning: This is expensive, especially on mobile (where it's not even needed!) so only enable if required. Also see the less-expensive InputHandler.pixelPerfectClick.
  34004. * @property {boolean} pixelPerfectOver - Use a pixel perfect check when testing for pointer over.
  34005. * @default
  34006. */
  34007. this.pixelPerfectOver = false;
  34008. /**
  34009. * Set to true to use pixel perfect hit detection when checking if the pointer is over this Sprite when it's clicked or touched.
  34010. * The x/y coordinates of the pointer are tested against the image in combination with the InputHandler.pixelPerfectAlpha value.
  34011. * This feature only works for display objects with image based textures such as Sprites. It won't work on BitmapText or Rope.
  34012. * Warning: This is expensive so only enable if you really need it.
  34013. * @property {boolean} pixelPerfectClick - Use a pixel perfect check when testing for clicks or touches on the Sprite.
  34014. * @default
  34015. */
  34016. this.pixelPerfectClick = false;
  34017. /**
  34018. * @property {number} pixelPerfectAlpha - The alpha tolerance threshold. If the alpha value of the pixel matches or is above this value, it's considered a hit.
  34019. * @default
  34020. */
  34021. this.pixelPerfectAlpha = 255;
  34022. /**
  34023. * @property {boolean} draggable - Is this sprite allowed to be dragged by the mouse? true = yes, false = no
  34024. * @default
  34025. */
  34026. this.draggable = false;
  34027. /**
  34028. * @property {Phaser.Rectangle} boundsRect - A region of the game world within which the sprite is restricted during drag.
  34029. * @default
  34030. */
  34031. this.boundsRect = null;
  34032. /**
  34033. * @property {Phaser.Sprite} boundsSprite - A Sprite the bounds of which this sprite is restricted during drag.
  34034. * @default
  34035. */
  34036. this.boundsSprite = null;
  34037. /**
  34038. * @property {boolean} scaleLayer - EXPERIMENTAL: Please do not use this property unless you know what it does. Likely to change in the future.
  34039. */
  34040. this.scaleLayer = false;
  34041. /**
  34042. * @property {Phaser.Point} dragOffset - The offset from the Sprites position that dragging takes place from.
  34043. */
  34044. this.dragOffset = new Phaser.Point();
  34045. /**
  34046. * @property {boolean} dragFromCenter - Is the Sprite dragged from its center, or the point at which the Pointer was pressed down upon it?
  34047. */
  34048. this.dragFromCenter = false;
  34049. /**
  34050. * @property {boolean} dragStopBlocksInputUp - If enabled, when the Sprite stops being dragged, it will only dispatch the `onDragStop` event, and not the `onInputUp` event. If set to `false` it will dispatch both events.
  34051. */
  34052. this.dragStopBlocksInputUp = false;
  34053. /**
  34054. * @property {Phaser.Point} dragStartPoint - The Point from which the most recent drag started from. Useful if you need to return an object to its starting position.
  34055. */
  34056. this.dragStartPoint = new Phaser.Point();
  34057. /**
  34058. * @property {integer} dragDistanceThreshold - The distance, in pixels, the pointer has to move while being held down, before the Sprite thinks it is being dragged.
  34059. */
  34060. this.dragDistanceThreshold = 0;
  34061. /**
  34062. * @property {integer} dragTimeThreshold - The amount of time, in ms, the pointer has to be held down over the Sprite before it thinks it is being dragged.
  34063. */
  34064. this.dragTimeThreshold = 0;
  34065. /**
  34066. * @property {Phaser.Point} downPoint - A Point object containing the coordinates of the Pointer when it was first pressed down onto this Sprite.
  34067. */
  34068. this.downPoint = new Phaser.Point();
  34069. /**
  34070. * @property {Phaser.Point} snapPoint - If the sprite is set to snap while dragging this holds the point of the most recent 'snap' event.
  34071. */
  34072. this.snapPoint = new Phaser.Point();
  34073. /**
  34074. * @property {Phaser.Point} _dragPoint - Internal cache var.
  34075. * @private
  34076. */
  34077. this._dragPoint = new Phaser.Point();
  34078. /**
  34079. * @property {boolean} _dragPhase - Internal cache var.
  34080. * @private
  34081. */
  34082. this._dragPhase = false;
  34083. /**
  34084. * @property {boolean} _pendingDrag - Internal cache var.
  34085. * @private
  34086. */
  34087. this._pendingDrag = false;
  34088. /**
  34089. * @property {boolean} _dragTimePass - Internal cache var.
  34090. * @private
  34091. */
  34092. this._dragTimePass = false;
  34093. /**
  34094. * @property {boolean} _dragDistancePass - Internal cache var.
  34095. * @private
  34096. */
  34097. this._dragDistancePass = false;
  34098. /**
  34099. * @property {boolean} _wasEnabled - Internal cache var.
  34100. * @private
  34101. */
  34102. this._wasEnabled = false;
  34103. /**
  34104. * @property {Phaser.Point} _tempPoint - Internal cache var.
  34105. * @private
  34106. */
  34107. this._tempPoint = new Phaser.Point();
  34108. /**
  34109. * @property {array} _pointerData - Internal cache var.
  34110. * @private
  34111. */
  34112. this._pointerData = [];
  34113. this._pointerData.push({
  34114. id: 0,
  34115. x: 0,
  34116. y: 0,
  34117. camX: 0,
  34118. camY: 0,
  34119. isDown: false,
  34120. isUp: false,
  34121. isOver: false,
  34122. isOut: false,
  34123. timeOver: 0,
  34124. timeOut: 0,
  34125. timeDown: 0,
  34126. timeUp: 0,
  34127. downDuration: 0,
  34128. isDragged: false
  34129. });
  34130. };
  34131. Phaser.InputHandler.prototype = {
  34132. /**
  34133. * Starts the Input Handler running. This is called automatically when you enable input on a Sprite, or can be called directly if you need to set a specific priority.
  34134. *
  34135. * @method Phaser.InputHandler#start
  34136. * @param {number} [priority=0] - Higher priority sprites take click priority over low-priority sprites when they are stacked on-top of each other.
  34137. * @param {boolean} [useHandCursor=false] - If true the Sprite will show the hand cursor on mouse-over (doesn't apply to mobile browsers)
  34138. * @return {Phaser.Sprite} The Sprite object to which the Input Handler is bound.
  34139. */
  34140. start: function (priority, useHandCursor) {
  34141. priority = priority || 0;
  34142. if (useHandCursor === undefined) { useHandCursor = false; }
  34143. // Turning on
  34144. if (this.enabled === false)
  34145. {
  34146. // Register, etc
  34147. this.game.input.interactiveItems.add(this);
  34148. this.useHandCursor = useHandCursor;
  34149. this.priorityID = priority;
  34150. for (var i = 0; i < 10; i++)
  34151. {
  34152. this._pointerData[i] = {
  34153. id: i,
  34154. x: 0,
  34155. y: 0,
  34156. isDown: false,
  34157. isUp: false,
  34158. isOver: false,
  34159. isOut: false,
  34160. timeOver: 0,
  34161. timeOut: 0,
  34162. timeDown: 0,
  34163. timeUp: 0,
  34164. downDuration: 0,
  34165. isDragged: false
  34166. };
  34167. }
  34168. this.snapOffset = new Phaser.Point();
  34169. this.enabled = true;
  34170. this._wasEnabled = true;
  34171. }
  34172. this.sprite.events.onAddedToGroup.add(this.addedToGroup, this);
  34173. this.sprite.events.onRemovedFromGroup.add(this.removedFromGroup, this);
  34174. return this.sprite;
  34175. },
  34176. /**
  34177. * Handles when the parent Sprite is added to a new Group.
  34178. *
  34179. * @method Phaser.InputHandler#addedToGroup
  34180. * @private
  34181. */
  34182. addedToGroup: function () {
  34183. if (this._dragPhase)
  34184. {
  34185. return;
  34186. }
  34187. if (this._wasEnabled && !this.enabled)
  34188. {
  34189. this.start();
  34190. }
  34191. },
  34192. /**
  34193. * Handles when the parent Sprite is removed from a Group.
  34194. *
  34195. * @method Phaser.InputHandler#removedFromGroup
  34196. * @private
  34197. */
  34198. removedFromGroup: function () {
  34199. if (this._dragPhase)
  34200. {
  34201. return;
  34202. }
  34203. if (this.enabled)
  34204. {
  34205. this._wasEnabled = true;
  34206. this.stop();
  34207. }
  34208. else
  34209. {
  34210. this._wasEnabled = false;
  34211. }
  34212. },
  34213. /**
  34214. * Resets the Input Handler and disables it.
  34215. * @method Phaser.InputHandler#reset
  34216. */
  34217. reset: function () {
  34218. this.enabled = false;
  34219. for (var i = 0; i < 10; i++)
  34220. {
  34221. this._pointerData[i] = {
  34222. id: i,
  34223. x: 0,
  34224. y: 0,
  34225. isDown: false,
  34226. isUp: false,
  34227. isOver: false,
  34228. isOut: false,
  34229. timeOver: 0,
  34230. timeOut: 0,
  34231. timeDown: 0,
  34232. timeUp: 0,
  34233. downDuration: 0,
  34234. isDragged: false
  34235. };
  34236. }
  34237. },
  34238. /**
  34239. * Stops the Input Handler from running.
  34240. * @method Phaser.InputHandler#stop
  34241. */
  34242. stop: function () {
  34243. // Turning off
  34244. if (this.enabled === false)
  34245. {
  34246. return;
  34247. }
  34248. else
  34249. {
  34250. // De-register, etc
  34251. this.enabled = false;
  34252. this.game.input.interactiveItems.remove(this);
  34253. }
  34254. },
  34255. /**
  34256. * Clean up memory.
  34257. * @method Phaser.InputHandler#destroy
  34258. */
  34259. destroy: function () {
  34260. if (this.sprite)
  34261. {
  34262. if (this._setHandCursor)
  34263. {
  34264. this.game.canvas.style.cursor = "default";
  34265. this._setHandCursor = false;
  34266. }
  34267. this.enabled = false;
  34268. this.game.input.interactiveItems.remove(this);
  34269. this._pointerData.length = 0;
  34270. this.boundsRect = null;
  34271. this.boundsSprite = null;
  34272. this.sprite = null;
  34273. }
  34274. },
  34275. /**
  34276. * Checks if the object this InputHandler is bound to is valid for consideration in the Pointer move event.
  34277. * This is called by Phaser.Pointer and shouldn't typically be called directly.
  34278. *
  34279. * @method Phaser.InputHandler#validForInput
  34280. * @protected
  34281. * @param {number} highestID - The highest ID currently processed by the Pointer.
  34282. * @param {number} highestRenderID - The highest Render Order ID currently processed by the Pointer.
  34283. * @param {boolean} [includePixelPerfect=true] - If this object has `pixelPerfectClick` or `pixelPerfectOver` set should it be considered as valid?
  34284. * @return {boolean} True if the object this InputHandler is bound to should be considered as valid for input detection.
  34285. */
  34286. validForInput: function (highestID, highestRenderID, includePixelPerfect) {
  34287. if (includePixelPerfect === undefined) { includePixelPerfect = true; }
  34288. if (!this.enabled ||
  34289. this.sprite.scale.x === 0 ||
  34290. this.sprite.scale.y === 0 ||
  34291. this.priorityID < this.game.input.minPriorityID ||
  34292. (this.sprite.parent && this.sprite.parent.ignoreChildInput))
  34293. {
  34294. return false;
  34295. }
  34296. // If we're trying to specifically IGNORE pixel perfect objects, then set includePixelPerfect to false and skip it
  34297. if (!includePixelPerfect && (this.pixelPerfectClick || this.pixelPerfectOver))
  34298. {
  34299. return false;
  34300. }
  34301. if (this.priorityID > highestID || (this.priorityID === highestID && this.sprite.renderOrderID > highestRenderID))
  34302. {
  34303. return true;
  34304. }
  34305. return false;
  34306. },
  34307. /**
  34308. * Is this object using pixel perfect checking?
  34309. *
  34310. * @method Phaser.InputHandler#isPixelPerfect
  34311. * @return {boolean} True if the this InputHandler has either `pixelPerfectClick` or `pixelPerfectOver` set to `true`.
  34312. */
  34313. isPixelPerfect: function () {
  34314. return (this.pixelPerfectClick || this.pixelPerfectOver);
  34315. },
  34316. /**
  34317. * The x coordinate of the Input pointer, relative to the top-left of the parent Sprite.
  34318. * This value is only set when the pointer is over this Sprite.
  34319. *
  34320. * @method Phaser.InputHandler#pointerX
  34321. * @param {integer} [pointerId=0]
  34322. * @return {number} The x coordinate of the Input pointer.
  34323. */
  34324. pointerX: function (pointerId) {
  34325. pointerId = pointerId || 0;
  34326. return this._pointerData[pointerId].x;
  34327. },
  34328. /**
  34329. * The y coordinate of the Input pointer, relative to the top-left of the parent Sprite
  34330. * This value is only set when the pointer is over this Sprite.
  34331. *
  34332. * @method Phaser.InputHandler#pointerY
  34333. * @param {integer} [pointerId=0]
  34334. * @return {number} The y coordinate of the Input pointer.
  34335. */
  34336. pointerY: function (pointerId) {
  34337. pointerId = pointerId || 0;
  34338. return this._pointerData[pointerId].y;
  34339. },
  34340. /**
  34341. * If the Pointer is down this returns true.
  34342. * This *only* checks if the Pointer is down, not if it's down over any specific Sprite.
  34343. *
  34344. * @method Phaser.InputHandler#pointerDown
  34345. * @param {integer} [pointerId=0]
  34346. * @return {boolean} - True if the given pointer is down, otherwise false.
  34347. */
  34348. pointerDown: function (pointerId) {
  34349. pointerId = pointerId || 0;
  34350. return this._pointerData[pointerId].isDown;
  34351. },
  34352. /**
  34353. * If the Pointer is up this returns true.
  34354. * This *only* checks if the Pointer is up, not if it's up over any specific Sprite.
  34355. *
  34356. * @method Phaser.InputHandler#pointerUp
  34357. * @param {integer} [pointerId=0]
  34358. * @return {boolean} - True if the given pointer is up, otherwise false.
  34359. */
  34360. pointerUp: function (pointerId) {
  34361. pointerId = pointerId || 0;
  34362. return this._pointerData[pointerId].isUp;
  34363. },
  34364. /**
  34365. * A timestamp representing when the Pointer first touched the touchscreen.
  34366. *
  34367. * @method Phaser.InputHandler#pointerTimeDown
  34368. * @param {integer} [pointerId=(check all)]
  34369. * @return {number}
  34370. */
  34371. pointerTimeDown: function (pointerId) {
  34372. pointerId = pointerId || 0;
  34373. return this._pointerData[pointerId].timeDown;
  34374. },
  34375. /**
  34376. * A timestamp representing when the Pointer left the touchscreen.
  34377. *
  34378. * @method Phaser.InputHandler#pointerTimeUp
  34379. * @param {integer} [pointerId=0]
  34380. * @return {number}
  34381. */
  34382. pointerTimeUp: function (pointerId) {
  34383. pointerId = pointerId || 0;
  34384. return this._pointerData[pointerId].timeUp;
  34385. },
  34386. /**
  34387. * Is the Pointer over this Sprite?
  34388. *
  34389. * @method Phaser.InputHandler#pointerOver
  34390. * @param {integer} [pointerId=(check all)] The ID number of a Pointer to check. If you don't provide a number it will check all Pointers.
  34391. * @return {boolean} - True if the given pointer (if a index was given, or any pointer if not) is over this object.
  34392. */
  34393. pointerOver: function (pointerId) {
  34394. if (!this.enabled)
  34395. {
  34396. return false;
  34397. }
  34398. if (pointerId === undefined)
  34399. {
  34400. for (var i = 0; i < 10; i++)
  34401. {
  34402. if (this._pointerData[i].isOver)
  34403. {
  34404. return true;
  34405. }
  34406. }
  34407. return false;
  34408. }
  34409. else
  34410. {
  34411. return this._pointerData[pointerId].isOver;
  34412. }
  34413. },
  34414. /**
  34415. * Is the Pointer outside of this Sprite?
  34416. *
  34417. * @method Phaser.InputHandler#pointerOut
  34418. * @param {integer} [pointerId=(check all)] The ID number of a Pointer to check. If you don't provide a number it will check all Pointers.
  34419. * @return {boolean} True if the given pointer (if a index was given, or any pointer if not) is out of this object.
  34420. */
  34421. pointerOut: function (pointerId) {
  34422. if (!this.enabled)
  34423. {
  34424. return false;
  34425. }
  34426. if (pointerId === undefined)
  34427. {
  34428. for (var i = 0; i < 10; i++)
  34429. {
  34430. if (this._pointerData[i].isOut)
  34431. {
  34432. return true;
  34433. }
  34434. }
  34435. }
  34436. else
  34437. {
  34438. return this._pointerData[pointerId].isOut;
  34439. }
  34440. },
  34441. /**
  34442. * A timestamp representing when the Pointer first touched the touchscreen.
  34443. *
  34444. * @method Phaser.InputHandler#pointerTimeOver
  34445. * @param {integer} [pointerId=0]
  34446. * @return {number}
  34447. */
  34448. pointerTimeOver: function (pointerId) {
  34449. pointerId = pointerId || 0;
  34450. return this._pointerData[pointerId].timeOver;
  34451. },
  34452. /**
  34453. * A timestamp representing when the Pointer left the touchscreen.
  34454. *
  34455. * @method Phaser.InputHandler#pointerTimeOut
  34456. * @param {integer} [pointerId=0]
  34457. * @return {number}
  34458. */
  34459. pointerTimeOut: function (pointerId) {
  34460. pointerId = pointerId || 0;
  34461. return this._pointerData[pointerId].timeOut;
  34462. },
  34463. /**
  34464. * Is this sprite being dragged by the mouse or not?
  34465. *
  34466. * @method Phaser.InputHandler#pointerDragged
  34467. * @param {integer} [pointerId=0]
  34468. * @return {boolean} True if the pointer is dragging an object, otherwise false.
  34469. */
  34470. pointerDragged: function (pointerId) {
  34471. pointerId = pointerId || 0;
  34472. return this._pointerData[pointerId].isDragged;
  34473. },
  34474. /**
  34475. * Checks if the given pointer is both down and over the Sprite this InputHandler belongs to.
  34476. * Use the `fastTest` flag is to quickly check just the bounding hit area even if `InputHandler.pixelPerfectOver` is `true`.
  34477. *
  34478. * @method Phaser.InputHandler#checkPointerDown
  34479. * @param {Phaser.Pointer} pointer
  34480. * @param {boolean} [fastTest=false] - Force a simple hit area check even if `pixelPerfectOver` is true for this object?
  34481. * @return {boolean} True if the pointer is down, otherwise false.
  34482. */
  34483. checkPointerDown: function (pointer, fastTest) {
  34484. if (!pointer.isDown ||
  34485. !this.enabled ||
  34486. !this.sprite ||
  34487. !this.sprite.parent ||
  34488. !this.sprite.visible ||
  34489. !this.sprite.parent.visible ||
  34490. this.sprite.worldScale.x === 0 ||
  34491. this.sprite.worldScale.y === 0)
  34492. {
  34493. return false;
  34494. }
  34495. // Need to pass it a temp point, in case we need it again for the pixel check
  34496. if (this.game.input.hitTest(this.sprite, pointer, this._tempPoint))
  34497. {
  34498. if (fastTest === undefined)
  34499. {
  34500. fastTest = false;
  34501. }
  34502. if (!fastTest && this.pixelPerfectClick)
  34503. {
  34504. return this.checkPixel(this._tempPoint.x, this._tempPoint.y);
  34505. }
  34506. else
  34507. {
  34508. return true;
  34509. }
  34510. }
  34511. return false;
  34512. },
  34513. /**
  34514. * Checks if the given pointer is over the Sprite this InputHandler belongs to.
  34515. * Use the `fastTest` flag is to quickly check just the bounding hit area even if `InputHandler.pixelPerfectOver` is `true`.
  34516. *
  34517. * @method Phaser.InputHandler#checkPointerOver
  34518. * @param {Phaser.Pointer} pointer
  34519. * @param {boolean} [fastTest=false] - Force a simple hit area check even if `pixelPerfectOver` is true for this object?
  34520. * @return {boolean}
  34521. */
  34522. checkPointerOver: function (pointer, fastTest) {
  34523. if (!this.enabled ||
  34524. !this.sprite ||
  34525. !this.sprite.parent ||
  34526. !this.sprite.visible ||
  34527. !this.sprite.parent.visible ||
  34528. this.sprite.worldScale.x === 0 ||
  34529. this.sprite.worldScale.y === 0)
  34530. {
  34531. return false;
  34532. }
  34533. // Need to pass it a temp point, in case we need it again for the pixel check
  34534. if (this.game.input.hitTest(this.sprite, pointer, this._tempPoint))
  34535. {
  34536. if (fastTest === undefined)
  34537. {
  34538. fastTest = false;
  34539. }
  34540. if (!fastTest && this.pixelPerfectOver)
  34541. {
  34542. return this.checkPixel(this._tempPoint.x, this._tempPoint.y);
  34543. }
  34544. else
  34545. {
  34546. return true;
  34547. }
  34548. }
  34549. return false;
  34550. },
  34551. /**
  34552. * Runs a pixel perfect check against the given x/y coordinates of the Sprite this InputHandler is bound to.
  34553. * It compares the alpha value of the pixel and if >= InputHandler.pixelPerfectAlpha it returns true.
  34554. *
  34555. * @method Phaser.InputHandler#checkPixel
  34556. * @param {number} x - The x coordinate to check.
  34557. * @param {number} y - The y coordinate to check.
  34558. * @param {Phaser.Pointer} [pointer] - The pointer to get the x/y coordinate from if not passed as the first two parameters.
  34559. * @return {boolean} true if there is the alpha of the pixel is >= InputHandler.pixelPerfectAlpha
  34560. */
  34561. checkPixel: function (x, y, pointer) {
  34562. // Grab a pixel from our image into the hitCanvas and then test it
  34563. if (this.sprite.texture.baseTexture.source)
  34564. {
  34565. if (x === null && y === null)
  34566. {
  34567. // Use the pointer parameter
  34568. this.game.input.getLocalPosition(this.sprite, pointer, this._tempPoint);
  34569. var x = this._tempPoint.x;
  34570. var y = this._tempPoint.y;
  34571. }
  34572. if (this.sprite.anchor.x !== 0)
  34573. {
  34574. x -= -this.sprite.texture.frame.width * this.sprite.anchor.x;
  34575. }
  34576. if (this.sprite.anchor.y !== 0)
  34577. {
  34578. y -= -this.sprite.texture.frame.height * this.sprite.anchor.y;
  34579. }
  34580. x += this.sprite.texture.frame.x;
  34581. y += this.sprite.texture.frame.y;
  34582. if (this.sprite.texture.trim)
  34583. {
  34584. x -= this.sprite.texture.trim.x;
  34585. y -= this.sprite.texture.trim.y;
  34586. // If the coordinates are outside the trim area we return false immediately, to save doing a draw call
  34587. if (x < this.sprite.texture.crop.x || x > this.sprite.texture.crop.right || y < this.sprite.texture.crop.y || y > this.sprite.texture.crop.bottom)
  34588. {
  34589. this._dx = x;
  34590. this._dy = y;
  34591. return false;
  34592. }
  34593. }
  34594. this._dx = x;
  34595. this._dy = y;
  34596. this.game.input.hitContext.clearRect(0, 0, 1, 1);
  34597. this.game.input.hitContext.drawImage(this.sprite.texture.baseTexture.source, x, y, 1, 1, 0, 0, 1, 1);
  34598. var rgb = this.game.input.hitContext.getImageData(0, 0, 1, 1);
  34599. if (rgb.data[3] >= this.pixelPerfectAlpha)
  34600. {
  34601. return true;
  34602. }
  34603. }
  34604. return false;
  34605. },
  34606. /**
  34607. * Internal Update method. This is called automatically and handles the Pointer
  34608. * and drag update loops.
  34609. *
  34610. * @method Phaser.InputHandler#update
  34611. * @protected
  34612. * @param {Phaser.Pointer} pointer
  34613. * @return {boolean} True if the pointer is still active, otherwise false.
  34614. */
  34615. update: function (pointer) {
  34616. if (this.sprite === null || this.sprite.parent === undefined)
  34617. {
  34618. // Abort. We've been destroyed.
  34619. return;
  34620. }
  34621. if (!this.enabled || !this.sprite.visible || !this.sprite.parent.visible)
  34622. {
  34623. this._pointerOutHandler(pointer);
  34624. return false;
  34625. }
  34626. if (this._pendingDrag)
  34627. {
  34628. if (!this._dragDistancePass)
  34629. {
  34630. this._dragDistancePass = (Phaser.Math.distance(pointer.x, pointer.y, this.downPoint.x, this.downPoint.y) >= this.dragDistanceThreshold);
  34631. }
  34632. if (this._dragDistancePass && this._dragTimePass)
  34633. {
  34634. this.startDrag(pointer);
  34635. }
  34636. return true;
  34637. }
  34638. else if (this.draggable && this._draggedPointerID === pointer.id)
  34639. {
  34640. return this.updateDrag(pointer, false);
  34641. }
  34642. else if (this._pointerData[pointer.id].isOver)
  34643. {
  34644. if (this.checkPointerOver(pointer))
  34645. {
  34646. this._pointerData[pointer.id].x = pointer.x - this.sprite.x;
  34647. this._pointerData[pointer.id].y = pointer.y - this.sprite.y;
  34648. return true;
  34649. }
  34650. else
  34651. {
  34652. this._pointerOutHandler(pointer);
  34653. return false;
  34654. }
  34655. }
  34656. },
  34657. /**
  34658. * Internal method handling the pointer over event.
  34659. *
  34660. * @method Phaser.InputHandler#_pointerOverHandler
  34661. * @private
  34662. * @param {Phaser.Pointer} pointer - The pointer that triggered the event
  34663. * @param {boolean} [silent=false] - If silent is `true` then this method will not dispatch any Signals from the parent Sprite.
  34664. */
  34665. _pointerOverHandler: function (pointer, silent) {
  34666. if (this.sprite === null)
  34667. {
  34668. // Abort. We've been destroyed.
  34669. return;
  34670. }
  34671. var data = this._pointerData[pointer.id];
  34672. if (data.isOver === false || pointer.dirty)
  34673. {
  34674. var sendEvent = (data.isOver === false);
  34675. data.isOver = true;
  34676. data.isOut = false;
  34677. data.timeOver = this.game.time.time;
  34678. data.x = pointer.x - this.sprite.x;
  34679. data.y = pointer.y - this.sprite.y;
  34680. if (this.useHandCursor && data.isDragged === false)
  34681. {
  34682. this.game.canvas.style.cursor = "pointer";
  34683. this._setHandCursor = true;
  34684. }
  34685. if (!silent && sendEvent && this.sprite && this.sprite.events)
  34686. {
  34687. this.sprite.events.onInputOver$dispatch(this.sprite, pointer);
  34688. }
  34689. if (this.sprite.parent && this.sprite.parent.type === Phaser.GROUP)
  34690. {
  34691. this.sprite.parent.onChildInputOver.dispatch(this.sprite, pointer);
  34692. }
  34693. }
  34694. },
  34695. /**
  34696. * Internal method handling the pointer out event.
  34697. *
  34698. * @method Phaser.InputHandler#_pointerOutHandler
  34699. * @private
  34700. * @param {Phaser.Pointer} pointer - The pointer that triggered the event.
  34701. * @param {boolean} [silent=false] - If silent is `true` then this method will not dispatch any Signals from the parent Sprite.
  34702. */
  34703. _pointerOutHandler: function (pointer, silent) {
  34704. if (this.sprite === null)
  34705. {
  34706. // Abort. We've been destroyed.
  34707. return;
  34708. }
  34709. var data = this._pointerData[pointer.id];
  34710. data.isOver = false;
  34711. data.isOut = true;
  34712. data.timeOut = this.game.time.time;
  34713. if (this.useHandCursor && data.isDragged === false)
  34714. {
  34715. this.game.canvas.style.cursor = "default";
  34716. this._setHandCursor = false;
  34717. }
  34718. if (!silent && this.sprite && this.sprite.events)
  34719. {
  34720. this.sprite.events.onInputOut$dispatch(this.sprite, pointer);
  34721. if (this.sprite && this.sprite.parent && this.sprite.parent.type === Phaser.GROUP)
  34722. {
  34723. this.sprite.parent.onChildInputOut.dispatch(this.sprite, pointer);
  34724. }
  34725. }
  34726. },
  34727. /**
  34728. * Internal method handling the touched / clicked event.
  34729. *
  34730. * @method Phaser.InputHandler#_touchedHandler
  34731. * @private
  34732. * @param {Phaser.Pointer} pointer - The pointer that triggered the event.
  34733. */
  34734. _touchedHandler: function (pointer) {
  34735. if (this.sprite === null)
  34736. {
  34737. // Abort. We've been destroyed.
  34738. return;
  34739. }
  34740. var data = this._pointerData[pointer.id];
  34741. if (!data.isDown && data.isOver)
  34742. {
  34743. if (this.pixelPerfectClick && !this.checkPixel(null, null, pointer))
  34744. {
  34745. return;
  34746. }
  34747. data.isDown = true;
  34748. data.isUp = false;
  34749. data.timeDown = this.game.time.time;
  34750. this.downPoint.set(pointer.x, pointer.y);
  34751. // It's possible the onInputDown event creates a new Sprite that is on-top of this one, so we ought to force a Pointer update
  34752. pointer.dirty = true;
  34753. if (this.sprite && this.sprite.events)
  34754. {
  34755. this.sprite.events.onInputDown$dispatch(this.sprite, pointer);
  34756. // The event above might have destroyed this sprite.
  34757. if (this.sprite && this.sprite.parent && this.sprite.parent.type === Phaser.GROUP)
  34758. {
  34759. this.sprite.parent.onChildInputDown.dispatch(this.sprite, pointer);
  34760. }
  34761. // The events might have destroyed this sprite.
  34762. if (this.sprite === null)
  34763. {
  34764. return;
  34765. }
  34766. }
  34767. // Start drag
  34768. if (this.draggable && this.isDragged === false)
  34769. {
  34770. if (this.dragTimeThreshold === 0 && this.dragDistanceThreshold === 0)
  34771. {
  34772. this.startDrag(pointer);
  34773. }
  34774. else
  34775. {
  34776. this._pendingDrag = true;
  34777. this._dragDistancePass = (this.dragDistanceThreshold === 0);
  34778. if (this.dragTimeThreshold > 0)
  34779. {
  34780. this._dragTimePass = false;
  34781. this.game.time.events.add(this.dragTimeThreshold, this.dragTimeElapsed, this, pointer);
  34782. }
  34783. else
  34784. {
  34785. this._dragTimePass = true;
  34786. }
  34787. }
  34788. }
  34789. if (this.bringToTop)
  34790. {
  34791. this.sprite.bringToTop();
  34792. }
  34793. }
  34794. },
  34795. /**
  34796. * Internal method handling the drag threshold timer.
  34797. *
  34798. * @method Phaser.InputHandler#dragTimeElapsed
  34799. * @private
  34800. * @param {Phaser.Pointer} pointer
  34801. */
  34802. dragTimeElapsed: function (pointer) {
  34803. this._dragTimePass = true;
  34804. if (this._pendingDrag && this.sprite)
  34805. {
  34806. if (this._dragDistancePass)
  34807. {
  34808. this.startDrag(pointer);
  34809. }
  34810. }
  34811. },
  34812. /**
  34813. * Internal method handling the pointer released event.
  34814. * @method Phaser.InputHandler#_releasedHandler
  34815. * @private
  34816. * @param {Phaser.Pointer} pointer
  34817. */
  34818. _releasedHandler: function (pointer) {
  34819. if (this.sprite === null)
  34820. {
  34821. // Abort. We've been destroyed.
  34822. return;
  34823. }
  34824. var data = this._pointerData[pointer.id];
  34825. // If was previously touched by this Pointer, check if still is AND still over this item
  34826. if (data.isDown && pointer.isUp)
  34827. {
  34828. data.isDown = false;
  34829. data.isUp = true;
  34830. data.timeUp = this.game.time.time;
  34831. data.downDuration = data.timeUp - data.timeDown;
  34832. // Only release the InputUp signal if the pointer is still over this sprite
  34833. var isOver = this.checkPointerOver(pointer);
  34834. if (this.sprite && this.sprite.events)
  34835. {
  34836. if (!this.dragStopBlocksInputUp ||
  34837. this.dragStopBlocksInputUp && !(this.draggable && this.isDragged && this._draggedPointerID === pointer.id))
  34838. {
  34839. this.sprite.events.onInputUp$dispatch(this.sprite, pointer, isOver);
  34840. }
  34841. if (this.sprite && this.sprite.parent && this.sprite.parent.type === Phaser.GROUP)
  34842. {
  34843. this.sprite.parent.onChildInputUp.dispatch(this.sprite, pointer, isOver);
  34844. }
  34845. // The onInputUp event may have changed the sprite so that checkPointerOver is no longer true, so update it.
  34846. if (isOver)
  34847. {
  34848. isOver = this.checkPointerOver(pointer);
  34849. }
  34850. }
  34851. data.isOver = isOver;
  34852. if (!isOver && this.useHandCursor)
  34853. {
  34854. this.game.canvas.style.cursor = "default";
  34855. this._setHandCursor = false;
  34856. }
  34857. // It's possible the onInputUp event created a new Sprite that is on-top of this one, so force a Pointer update
  34858. pointer.dirty = true;
  34859. this._pendingDrag = false;
  34860. // Stop drag
  34861. if (this.draggable && this.isDragged && this._draggedPointerID === pointer.id)
  34862. {
  34863. this.stopDrag(pointer);
  34864. }
  34865. }
  34866. },
  34867. /**
  34868. * Called as a Pointer actively drags this Game Object.
  34869. *
  34870. * @method Phaser.InputHandler#updateDrag
  34871. * @private
  34872. * @param {Phaser.Pointer} pointer - The Pointer causing the drag update.
  34873. * @param {boolean} fromStart - True if this is the first update, immediately after the drag has started.
  34874. * @return {boolean}
  34875. */
  34876. updateDrag: function (pointer, fromStart) {
  34877. if (fromStart === undefined) { fromStart = false; }
  34878. if (pointer.isUp)
  34879. {
  34880. this.stopDrag(pointer);
  34881. return false;
  34882. }
  34883. var px = this.globalToLocalX(pointer.x) + this._dragPoint.x + this.dragOffset.x;
  34884. var py = this.globalToLocalY(pointer.y) + this._dragPoint.y + this.dragOffset.y;
  34885. if (this.sprite.fixedToCamera)
  34886. {
  34887. if (this.allowHorizontalDrag)
  34888. {
  34889. this.sprite.cameraOffset.x = px;
  34890. }
  34891. if (this.allowVerticalDrag)
  34892. {
  34893. this.sprite.cameraOffset.y = py;
  34894. }
  34895. if (this.boundsRect)
  34896. {
  34897. this.checkBoundsRect();
  34898. }
  34899. if (this.boundsSprite)
  34900. {
  34901. this.checkBoundsSprite();
  34902. }
  34903. if (this.snapOnDrag)
  34904. {
  34905. this.sprite.cameraOffset.x = Math.round((this.sprite.cameraOffset.x - (this.snapOffsetX % this.snapX)) / this.snapX) * this.snapX + (this.snapOffsetX % this.snapX);
  34906. this.sprite.cameraOffset.y = Math.round((this.sprite.cameraOffset.y - (this.snapOffsetY % this.snapY)) / this.snapY) * this.snapY + (this.snapOffsetY % this.snapY);
  34907. this.snapPoint.set(this.sprite.cameraOffset.x, this.sprite.cameraOffset.y);
  34908. }
  34909. }
  34910. else
  34911. {
  34912. var cx = this.game.camera.x - this._pointerData[pointer.id].camX;
  34913. var cy = this.game.camera.y - this._pointerData[pointer.id].camY;
  34914. if (this.allowHorizontalDrag)
  34915. {
  34916. this.sprite.x = px + cx;
  34917. }
  34918. if (this.allowVerticalDrag)
  34919. {
  34920. this.sprite.y = py + cy;
  34921. }
  34922. if (this.boundsRect)
  34923. {
  34924. this.checkBoundsRect();
  34925. }
  34926. if (this.boundsSprite)
  34927. {
  34928. this.checkBoundsSprite();
  34929. }
  34930. if (this.snapOnDrag)
  34931. {
  34932. this.sprite.x = Math.round((this.sprite.x - (this.snapOffsetX % this.snapX)) / this.snapX) * this.snapX + (this.snapOffsetX % this.snapX);
  34933. this.sprite.y = Math.round((this.sprite.y - (this.snapOffsetY % this.snapY)) / this.snapY) * this.snapY + (this.snapOffsetY % this.snapY);
  34934. this.snapPoint.set(this.sprite.x, this.sprite.y);
  34935. }
  34936. }
  34937. this.sprite.events.onDragUpdate.dispatch(this.sprite, pointer, px, py, this.snapPoint, fromStart);
  34938. return true;
  34939. },
  34940. /**
  34941. * Returns true if the pointer has entered the Sprite within the specified delay time (defaults to 500ms, half a second)
  34942. *
  34943. * @method Phaser.InputHandler#justOver
  34944. * @param {integer} [pointerId=0]
  34945. * @param {number} delay - The time below which the pointer is considered as just over.
  34946. * @return {boolean}
  34947. */
  34948. justOver: function (pointerId, delay) {
  34949. pointerId = pointerId || 0;
  34950. delay = delay || 500;
  34951. return (this._pointerData[pointerId].isOver && this.overDuration(pointerId) < delay);
  34952. },
  34953. /**
  34954. * Returns true if the pointer has left the Sprite within the specified delay time (defaults to 500ms, half a second)
  34955. *
  34956. * @method Phaser.InputHandler#justOut
  34957. * @param {integer} [pointerId=0]
  34958. * @param {number} delay - The time below which the pointer is considered as just out.
  34959. * @return {boolean}
  34960. */
  34961. justOut: function (pointerId, delay) {
  34962. pointerId = pointerId || 0;
  34963. delay = delay || 500;
  34964. return (this._pointerData[pointerId].isOut && (this.game.time.time - this._pointerData[pointerId].timeOut < delay));
  34965. },
  34966. /**
  34967. * Returns true if the pointer has touched or clicked on the Sprite within the specified delay time (defaults to 500ms, half a second)
  34968. *
  34969. * @method Phaser.InputHandler#justPressed
  34970. * @param {integer} [pointerId=0]
  34971. * @param {number} delay - The time below which the pointer is considered as just over.
  34972. * @return {boolean}
  34973. */
  34974. justPressed: function (pointerId, delay) {
  34975. pointerId = pointerId || 0;
  34976. delay = delay || 500;
  34977. return (this._pointerData[pointerId].isDown && this.downDuration(pointerId) < delay);
  34978. },
  34979. /**
  34980. * Returns true if the pointer was touching this Sprite, but has been released within the specified delay time (defaults to 500ms, half a second)
  34981. *
  34982. * @method Phaser.InputHandler#justReleased
  34983. * @param {integer} [pointerId=0]
  34984. * @param {number} delay - The time below which the pointer is considered as just out.
  34985. * @return {boolean}
  34986. */
  34987. justReleased: function (pointerId, delay) {
  34988. pointerId = pointerId || 0;
  34989. delay = delay || 500;
  34990. return (this._pointerData[pointerId].isUp && (this.game.time.time - this._pointerData[pointerId].timeUp < delay));
  34991. },
  34992. /**
  34993. * If the pointer is currently over this Sprite this returns how long it has been there for in milliseconds.
  34994. *
  34995. * @method Phaser.InputHandler#overDuration
  34996. * @param {integer} [pointerId=0]
  34997. * @return {number} The number of milliseconds the pointer has been over the Sprite, or -1 if not over.
  34998. */
  34999. overDuration: function (pointerId) {
  35000. pointerId = pointerId || 0;
  35001. if (this._pointerData[pointerId].isOver)
  35002. {
  35003. return this.game.time.time - this._pointerData[pointerId].timeOver;
  35004. }
  35005. return -1;
  35006. },
  35007. /**
  35008. * If the pointer is currently over this Sprite this returns how long it has been there for in milliseconds.
  35009. *
  35010. * @method Phaser.InputHandler#downDuration
  35011. * @param {integer} [pointerId=0]
  35012. * @return {number} The number of milliseconds the pointer has been pressed down on the Sprite, or -1 if not over.
  35013. */
  35014. downDuration: function (pointerId) {
  35015. pointerId = pointerId || 0;
  35016. if (this._pointerData[pointerId].isDown)
  35017. {
  35018. return this.game.time.time - this._pointerData[pointerId].timeDown;
  35019. }
  35020. return -1;
  35021. },
  35022. /**
  35023. * Allow this Sprite to be dragged by any valid pointer.
  35024. *
  35025. * When the drag begins the Sprite.events.onDragStart event will be dispatched.
  35026. *
  35027. * When the drag completes by way of the user letting go of the pointer that was dragging the sprite, the Sprite.events.onDragStop event is dispatched.
  35028. *
  35029. * You can control the thresholds over when a drag starts via the properties:
  35030. *
  35031. * `Pointer.dragDistanceThreshold` the distance, in pixels, that the pointer has to move
  35032. * before the drag will start.
  35033. *
  35034. * `Pointer.dragTimeThreshold` the time, in ms, that the pointer must be held down on
  35035. * the Sprite before the drag will start.
  35036. *
  35037. * You can set either (or both) of these properties after enabling a Sprite for drag.
  35038. *
  35039. * For the duration of the drag the Sprite.events.onDragUpdate event is dispatched. This event is only dispatched when the pointer actually
  35040. * changes position and moves. The event sends 5 parameters: `sprite`, `pointer`, `dragX`, `dragY` and `snapPoint`.
  35041. *
  35042. * @method Phaser.InputHandler#enableDrag
  35043. * @param {boolean} [lockCenter=false] - If false the Sprite will drag from where you click it minus the dragOffset. If true it will center itself to the tip of the mouse pointer.
  35044. * @param {boolean} [bringToTop=false] - If true the Sprite will be bought to the top of the rendering list in its current Group.
  35045. * @param {boolean} [pixelPerfect=false] - If true it will use a pixel perfect test to see if you clicked the Sprite. False uses the bounding box.
  35046. * @param {boolean} [alphaThreshold=255] - If using pixel perfect collision this specifies the alpha level from 0 to 255 above which a collision is processed.
  35047. * @param {Phaser.Rectangle} [boundsRect=null] - If you want to restrict the drag of this sprite to a specific Rectangle, pass the Phaser.Rectangle here, otherwise it's free to drag anywhere.
  35048. * @param {Phaser.Sprite} [boundsSprite=null] - If you want to restrict the drag of this sprite to within the bounding box of another sprite, pass it here.
  35049. */
  35050. enableDrag: function (lockCenter, bringToTop, pixelPerfect, alphaThreshold, boundsRect, boundsSprite) {
  35051. if (lockCenter === undefined) { lockCenter = false; }
  35052. if (bringToTop === undefined) { bringToTop = false; }
  35053. if (pixelPerfect === undefined) { pixelPerfect = false; }
  35054. if (alphaThreshold === undefined) { alphaThreshold = 255; }
  35055. if (boundsRect === undefined) { boundsRect = null; }
  35056. if (boundsSprite === undefined) { boundsSprite = null; }
  35057. this._dragPoint = new Phaser.Point();
  35058. this.draggable = true;
  35059. this.bringToTop = bringToTop;
  35060. this.dragOffset = new Phaser.Point();
  35061. this.dragFromCenter = lockCenter;
  35062. this.pixelPerfectClick = pixelPerfect;
  35063. this.pixelPerfectAlpha = alphaThreshold;
  35064. if (boundsRect)
  35065. {
  35066. this.boundsRect = boundsRect;
  35067. }
  35068. if (boundsSprite)
  35069. {
  35070. this.boundsSprite = boundsSprite;
  35071. }
  35072. },
  35073. /**
  35074. * Stops this sprite from being able to be dragged.
  35075. * If it is currently the target of an active drag it will be stopped immediately; also disables any set callbacks.
  35076. *
  35077. * @method Phaser.InputHandler#disableDrag
  35078. */
  35079. disableDrag: function () {
  35080. if (this._pointerData)
  35081. {
  35082. for (var i = 0; i < 10; i++)
  35083. {
  35084. this._pointerData[i].isDragged = false;
  35085. }
  35086. }
  35087. this.draggable = false;
  35088. this.isDragged = false;
  35089. this._draggedPointerID = -1;
  35090. this._pendingDrag = false;
  35091. },
  35092. /**
  35093. * Called by Pointer when drag starts on this Sprite. Should not usually be called directly.
  35094. *
  35095. * @method Phaser.InputHandler#startDrag
  35096. * @param {Phaser.Pointer} pointer
  35097. */
  35098. startDrag: function (pointer) {
  35099. var x = this.sprite.x;
  35100. var y = this.sprite.y;
  35101. this.isDragged = true;
  35102. this._draggedPointerID = pointer.id;
  35103. this._pointerData[pointer.id].camX = this.game.camera.x;
  35104. this._pointerData[pointer.id].camY = this.game.camera.y;
  35105. this._pointerData[pointer.id].isDragged = true;
  35106. if (this.sprite.fixedToCamera)
  35107. {
  35108. if (this.dragFromCenter)
  35109. {
  35110. var bounds = this.sprite.getBounds();
  35111. this.sprite.cameraOffset.x = this.globalToLocalX(pointer.x) + (this.sprite.cameraOffset.x - bounds.centerX);
  35112. this.sprite.cameraOffset.y = this.globalToLocalY(pointer.y) + (this.sprite.cameraOffset.y - bounds.centerY);
  35113. }
  35114. this._dragPoint.setTo(this.sprite.cameraOffset.x - pointer.x, this.sprite.cameraOffset.y - pointer.y);
  35115. }
  35116. else
  35117. {
  35118. if (this.dragFromCenter)
  35119. {
  35120. var bounds = this.sprite.getBounds();
  35121. this.sprite.x = this.globalToLocalX(pointer.x) + (this.sprite.x - bounds.centerX);
  35122. this.sprite.y = this.globalToLocalY(pointer.y) + (this.sprite.y - bounds.centerY);
  35123. }
  35124. this._dragPoint.setTo(this.sprite.x - this.globalToLocalX(pointer.x), this.sprite.y - this.globalToLocalY(pointer.y));
  35125. }
  35126. this.updateDrag(pointer, true);
  35127. if (this.bringToTop)
  35128. {
  35129. this._dragPhase = true;
  35130. this.sprite.bringToTop();
  35131. }
  35132. this.dragStartPoint.set(x, y);
  35133. this.sprite.events.onDragStart$dispatch(this.sprite, pointer, x, y);
  35134. this._pendingDrag = false;
  35135. },
  35136. /**
  35137. * Warning: EXPERIMENTAL
  35138. *
  35139. * @method Phaser.InputHandler#globalToLocalX
  35140. * @param {number} x
  35141. */
  35142. globalToLocalX: function (x) {
  35143. if (this.scaleLayer)
  35144. {
  35145. x -= this.game.scale.grid.boundsFluid.x;
  35146. x *= this.game.scale.grid.scaleFluidInversed.x;
  35147. }
  35148. return x;
  35149. },
  35150. /**
  35151. * Warning: EXPERIMENTAL
  35152. *
  35153. * @method Phaser.InputHandler#globalToLocalY
  35154. * @param {number} y
  35155. */
  35156. globalToLocalY: function (y) {
  35157. if (this.scaleLayer)
  35158. {
  35159. y -= this.game.scale.grid.boundsFluid.y;
  35160. y *= this.game.scale.grid.scaleFluidInversed.y;
  35161. }
  35162. return y;
  35163. },
  35164. /**
  35165. * Called by Pointer when drag is stopped on this Sprite. Should not usually be called directly.
  35166. *
  35167. * @method Phaser.InputHandler#stopDrag
  35168. * @param {Phaser.Pointer} pointer
  35169. */
  35170. stopDrag: function (pointer) {
  35171. this.isDragged = false;
  35172. this._draggedPointerID = -1;
  35173. this._pointerData[pointer.id].isDragged = false;
  35174. this._dragPhase = false;
  35175. this._pendingDrag = false;
  35176. if (this.snapOnRelease)
  35177. {
  35178. if (this.sprite.fixedToCamera)
  35179. {
  35180. this.sprite.cameraOffset.x = Math.round((this.sprite.cameraOffset.x - (this.snapOffsetX % this.snapX)) / this.snapX) * this.snapX + (this.snapOffsetX % this.snapX);
  35181. this.sprite.cameraOffset.y = Math.round((this.sprite.cameraOffset.y - (this.snapOffsetY % this.snapY)) / this.snapY) * this.snapY + (this.snapOffsetY % this.snapY);
  35182. }
  35183. else
  35184. {
  35185. this.sprite.x = Math.round((this.sprite.x - (this.snapOffsetX % this.snapX)) / this.snapX) * this.snapX + (this.snapOffsetX % this.snapX);
  35186. this.sprite.y = Math.round((this.sprite.y - (this.snapOffsetY % this.snapY)) / this.snapY) * this.snapY + (this.snapOffsetY % this.snapY);
  35187. }
  35188. }
  35189. this.sprite.events.onDragStop$dispatch(this.sprite, pointer);
  35190. if (this.checkPointerOver(pointer) === false)
  35191. {
  35192. this._pointerOutHandler(pointer);
  35193. }
  35194. },
  35195. /**
  35196. * Restricts this sprite to drag movement only on the given axis. Note: If both are set to false the sprite will never move!
  35197. *
  35198. * @method Phaser.InputHandler#setDragLock
  35199. * @param {boolean} [allowHorizontal=true] - To enable the sprite to be dragged horizontally set to true, otherwise false.
  35200. * @param {boolean} [allowVertical=true] - To enable the sprite to be dragged vertically set to true, otherwise false.
  35201. */
  35202. setDragLock: function (allowHorizontal, allowVertical) {
  35203. if (allowHorizontal === undefined) { allowHorizontal = true; }
  35204. if (allowVertical === undefined) { allowVertical = true; }
  35205. this.allowHorizontalDrag = allowHorizontal;
  35206. this.allowVerticalDrag = allowVertical;
  35207. },
  35208. /**
  35209. * Make this Sprite snap to the given grid either during drag or when it's released.
  35210. * For example 16x16 as the snapX and snapY would make the sprite snap to every 16 pixels.
  35211. *
  35212. * @method Phaser.InputHandler#enableSnap
  35213. * @param {number} snapX - The width of the grid cell to snap to.
  35214. * @param {number} snapY - The height of the grid cell to snap to.
  35215. * @param {boolean} [onDrag=true] - If true the sprite will snap to the grid while being dragged.
  35216. * @param {boolean} [onRelease=false] - If true the sprite will snap to the grid when released.
  35217. * @param {number} [snapOffsetX=0] - Used to offset the top-left starting point of the snap grid.
  35218. * @param {number} [snapOffsetY=0] - Used to offset the top-left starting point of the snap grid.
  35219. */
  35220. enableSnap: function (snapX, snapY, onDrag, onRelease, snapOffsetX, snapOffsetY) {
  35221. if (onDrag === undefined) { onDrag = true; }
  35222. if (onRelease === undefined) { onRelease = false; }
  35223. if (snapOffsetX === undefined) { snapOffsetX = 0; }
  35224. if (snapOffsetY === undefined) { snapOffsetY = 0; }
  35225. this.snapX = snapX;
  35226. this.snapY = snapY;
  35227. this.snapOffsetX = snapOffsetX;
  35228. this.snapOffsetY = snapOffsetY;
  35229. this.snapOnDrag = onDrag;
  35230. this.snapOnRelease = onRelease;
  35231. },
  35232. /**
  35233. * Stops the sprite from snapping to a grid during drag or release.
  35234. *
  35235. * @method Phaser.InputHandler#disableSnap
  35236. */
  35237. disableSnap: function () {
  35238. this.snapOnDrag = false;
  35239. this.snapOnRelease = false;
  35240. },
  35241. /**
  35242. * Bounds Rect check for the sprite drag
  35243. *
  35244. * @method Phaser.InputHandler#checkBoundsRect
  35245. */
  35246. checkBoundsRect: function () {
  35247. if (this.sprite.fixedToCamera)
  35248. {
  35249. if (this.sprite.cameraOffset.x < this.boundsRect.left)
  35250. {
  35251. this.sprite.cameraOffset.x = this.boundsRect.left;
  35252. }
  35253. else if ((this.sprite.cameraOffset.x + this.sprite.width) > this.boundsRect.right)
  35254. {
  35255. this.sprite.cameraOffset.x = this.boundsRect.right - this.sprite.width;
  35256. }
  35257. if (this.sprite.cameraOffset.y < this.boundsRect.top)
  35258. {
  35259. this.sprite.cameraOffset.y = this.boundsRect.top;
  35260. }
  35261. else if ((this.sprite.cameraOffset.y + this.sprite.height) > this.boundsRect.bottom)
  35262. {
  35263. this.sprite.cameraOffset.y = this.boundsRect.bottom - this.sprite.height;
  35264. }
  35265. }
  35266. else
  35267. {
  35268. if (this.sprite.left < this.boundsRect.left)
  35269. {
  35270. this.sprite.x = this.boundsRect.x + this.sprite.offsetX;
  35271. }
  35272. else if (this.sprite.right > this.boundsRect.right)
  35273. {
  35274. this.sprite.x = this.boundsRect.right - (this.sprite.width - this.sprite.offsetX);
  35275. }
  35276. if (this.sprite.top < this.boundsRect.top)
  35277. {
  35278. this.sprite.y = this.boundsRect.top + this.sprite.offsetY;
  35279. }
  35280. else if (this.sprite.bottom > this.boundsRect.bottom)
  35281. {
  35282. this.sprite.y = this.boundsRect.bottom - (this.sprite.height - this.sprite.offsetY);
  35283. }
  35284. }
  35285. },
  35286. /**
  35287. * Parent Sprite Bounds check for the sprite drag.
  35288. *
  35289. * @method Phaser.InputHandler#checkBoundsSprite
  35290. */
  35291. checkBoundsSprite: function () {
  35292. if (this.sprite.fixedToCamera && this.boundsSprite.fixedToCamera)
  35293. {
  35294. if (this.sprite.cameraOffset.x < this.boundsSprite.cameraOffset.x)
  35295. {
  35296. this.sprite.cameraOffset.x = this.boundsSprite.cameraOffset.x;
  35297. }
  35298. else if ((this.sprite.cameraOffset.x + this.sprite.width) > (this.boundsSprite.cameraOffset.x + this.boundsSprite.width))
  35299. {
  35300. this.sprite.cameraOffset.x = (this.boundsSprite.cameraOffset.x + this.boundsSprite.width) - this.sprite.width;
  35301. }
  35302. if (this.sprite.cameraOffset.y < this.boundsSprite.cameraOffset.y)
  35303. {
  35304. this.sprite.cameraOffset.y = this.boundsSprite.cameraOffset.y;
  35305. }
  35306. else if ((this.sprite.cameraOffset.y + this.sprite.height) > (this.boundsSprite.cameraOffset.y + this.boundsSprite.height))
  35307. {
  35308. this.sprite.cameraOffset.y = (this.boundsSprite.cameraOffset.y + this.boundsSprite.height) - this.sprite.height;
  35309. }
  35310. }
  35311. else
  35312. {
  35313. if (this.sprite.left < this.boundsSprite.left)
  35314. {
  35315. this.sprite.x = this.boundsSprite.left + this.sprite.offsetX;
  35316. }
  35317. else if (this.sprite.right > this.boundsSprite.right)
  35318. {
  35319. this.sprite.x = this.boundsSprite.right - (this.sprite.width - this.sprite.offsetX);
  35320. }
  35321. if (this.sprite.top < this.boundsSprite.top)
  35322. {
  35323. this.sprite.y = this.boundsSprite.top + this.sprite.offsetY;
  35324. }
  35325. else if (this.sprite.bottom > this.boundsSprite.bottom)
  35326. {
  35327. this.sprite.y = this.boundsSprite.bottom - (this.sprite.height - this.sprite.offsetY);
  35328. }
  35329. }
  35330. }
  35331. };
  35332. Phaser.InputHandler.prototype.constructor = Phaser.InputHandler;
  35333. /**
  35334. * @author @karlmacklin <tacklemcclean@gmail.com>
  35335. * @copyright 2016 Photon Storm Ltd.
  35336. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  35337. */
  35338. /**
  35339. * The Gamepad class handles gamepad input and dispatches gamepad events.
  35340. *
  35341. * Remember to call `gamepad.start()`.
  35342. *
  35343. * HTML5 GAMEPAD API SUPPORT IS AT AN EXPERIMENTAL STAGE!
  35344. * At moment of writing this (end of 2013) only Chrome supports parts of it out of the box. Firefox supports it
  35345. * via prefs flags (about:config, search gamepad). The browsers map the same controllers differently.
  35346. * This class has constants for Windows 7 Chrome mapping of XBOX 360 controller.
  35347. *
  35348. * @class Phaser.Gamepad
  35349. * @constructor
  35350. * @param {Phaser.Game} game - A reference to the currently running game.
  35351. */
  35352. Phaser.Gamepad = function (game) {
  35353. /**
  35354. * @property {Phaser.Game} game - Local reference to game.
  35355. */
  35356. this.game = game;
  35357. /**
  35358. * @property {object} _gamepadIndexMap - Maps the browsers gamepad indices to our Phaser Gamepads
  35359. * @private
  35360. */
  35361. this._gamepadIndexMap = {};
  35362. /**
  35363. * @property {Array} _rawPads - The raw state of the gamepads from the browser
  35364. * @private
  35365. */
  35366. this._rawPads = [];
  35367. /**
  35368. * @property {boolean} _active - Private flag for whether or not the API is polled
  35369. * @private
  35370. * @default
  35371. */
  35372. this._active = false;
  35373. /**
  35374. * Gamepad input will only be processed if enabled.
  35375. * @property {boolean} enabled
  35376. * @default
  35377. */
  35378. this.enabled = true;
  35379. /**
  35380. * Whether or not gamepads are supported in the current browser. Note that as of Dec. 2013 this check is actually not accurate at all due to poor implementation.
  35381. * @property {boolean} _gamepadSupportAvailable - Are gamepads supported in this browser or not?
  35382. * @private
  35383. */
  35384. this._gamepadSupportAvailable = !!navigator.webkitGetGamepads || !!navigator.webkitGamepads || (navigator.userAgent.indexOf('Firefox/') !== -1) || !!navigator.getGamepads;
  35385. /**
  35386. * Used to check for differences between earlier polls and current state of gamepads.
  35387. * @property {Array} _prevRawGamepadTypes
  35388. * @private
  35389. * @default
  35390. */
  35391. this._prevRawGamepadTypes = [];
  35392. /**
  35393. * Used to check for differences between earlier polls and current state of gamepads.
  35394. * @property {Array} _prevTimestamps
  35395. * @private
  35396. * @default
  35397. */
  35398. this._prevTimestamps = [];
  35399. /**
  35400. * @property {object} callbackContext - The context under which the callbacks are run.
  35401. */
  35402. this.callbackContext = this;
  35403. /**
  35404. * @property {function} onConnectCallback - This callback is invoked every time any gamepad is connected
  35405. */
  35406. this.onConnectCallback = null;
  35407. /**
  35408. * @property {function} onDisconnectCallback - This callback is invoked every time any gamepad is disconnected
  35409. */
  35410. this.onDisconnectCallback = null;
  35411. /**
  35412. * @property {function} onDownCallback - This callback is invoked every time any gamepad button is pressed down.
  35413. */
  35414. this.onDownCallback = null;
  35415. /**
  35416. * @property {function} onUpCallback - This callback is invoked every time any gamepad button is released.
  35417. */
  35418. this.onUpCallback = null;
  35419. /**
  35420. * @property {function} onAxisCallback - This callback is invoked every time any gamepad axis is changed.
  35421. */
  35422. this.onAxisCallback = null;
  35423. /**
  35424. * @property {function} onFloatCallback - This callback is invoked every time any gamepad button is changed to a value where value > 0 and value < 1.
  35425. */
  35426. this.onFloatCallback = null;
  35427. /**
  35428. * @property {function} _ongamepadconnected - Private callback for Firefox gamepad connection handling
  35429. * @private
  35430. */
  35431. this._ongamepadconnected = null;
  35432. /**
  35433. * @property {function} _gamepaddisconnected - Private callback for Firefox gamepad connection handling
  35434. * @private
  35435. */
  35436. this._gamepaddisconnected = null;
  35437. /**
  35438. * @property {Array<Phaser.SinglePad>} _gamepads - The four Phaser Gamepads.
  35439. * @private
  35440. */
  35441. this._gamepads = [
  35442. new Phaser.SinglePad(game, this),
  35443. new Phaser.SinglePad(game, this),
  35444. new Phaser.SinglePad(game, this),
  35445. new Phaser.SinglePad(game, this)
  35446. ];
  35447. };
  35448. Phaser.Gamepad.prototype = {
  35449. /**
  35450. * Add callbacks to the main Gamepad handler to handle connect/disconnect/button down/button up/axis change/float value buttons.
  35451. *
  35452. * @method Phaser.Gamepad#addCallbacks
  35453. * @param {object} context - The context under which the callbacks are run.
  35454. * @param {object} callbacks - Object that takes six different callback methods:
  35455. * onConnectCallback, onDisconnectCallback, onDownCallback, onUpCallback, onAxisCallback, onFloatCallback
  35456. */
  35457. addCallbacks: function (context, callbacks) {
  35458. if (typeof callbacks !== 'undefined')
  35459. {
  35460. this.onConnectCallback = (typeof callbacks.onConnect === 'function') ? callbacks.onConnect : this.onConnectCallback;
  35461. this.onDisconnectCallback = (typeof callbacks.onDisconnect === 'function') ? callbacks.onDisconnect : this.onDisconnectCallback;
  35462. this.onDownCallback = (typeof callbacks.onDown === 'function') ? callbacks.onDown : this.onDownCallback;
  35463. this.onUpCallback = (typeof callbacks.onUp === 'function') ? callbacks.onUp : this.onUpCallback;
  35464. this.onAxisCallback = (typeof callbacks.onAxis === 'function') ? callbacks.onAxis : this.onAxisCallback;
  35465. this.onFloatCallback = (typeof callbacks.onFloat === 'function') ? callbacks.onFloat : this.onFloatCallback;
  35466. this.callbackContext = context;
  35467. }
  35468. },
  35469. /**
  35470. * Starts the Gamepad event handling.
  35471. * This MUST be called manually before Phaser will start polling the Gamepad API.
  35472. *
  35473. * @method Phaser.Gamepad#start
  35474. */
  35475. start: function () {
  35476. if (this._active)
  35477. {
  35478. // Avoid setting multiple listeners
  35479. return;
  35480. }
  35481. this._active = true;
  35482. var _this = this;
  35483. this._onGamepadConnected = function (event) {
  35484. return _this.onGamepadConnected(event);
  35485. };
  35486. this._onGamepadDisconnected = function (event) {
  35487. return _this.onGamepadDisconnected(event);
  35488. };
  35489. window.addEventListener('gamepadconnected', this._onGamepadConnected, false);
  35490. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnected, false);
  35491. },
  35492. /**
  35493. * Handles the connection of a Gamepad.
  35494. *
  35495. * @method onGamepadConnected
  35496. * @private
  35497. * @param {object} event - The DOM event.
  35498. */
  35499. onGamepadConnected: function (event) {
  35500. var newPad = event.gamepad;
  35501. this._rawPads.push(newPad);
  35502. this._gamepads[newPad.index].connect(newPad);
  35503. },
  35504. /**
  35505. * Handles the disconnection of a Gamepad.
  35506. *
  35507. * @method onGamepadDisconnected
  35508. * @private
  35509. * @param {object} event - The DOM event.
  35510. */
  35511. onGamepadDisconnected: function (event) {
  35512. var removedPad = event.gamepad;
  35513. for (var i in this._rawPads)
  35514. {
  35515. if (this._rawPads[i].index === removedPad.index)
  35516. {
  35517. this._rawPads.splice(i,1);
  35518. }
  35519. }
  35520. this._gamepads[removedPad.index].disconnect();
  35521. },
  35522. /**
  35523. * Main gamepad update loop. Should not be called manually.
  35524. * @method Phaser.Gamepad#update
  35525. * @protected
  35526. */
  35527. update: function () {
  35528. this._pollGamepads();
  35529. this.pad1.pollStatus();
  35530. this.pad2.pollStatus();
  35531. this.pad3.pollStatus();
  35532. this.pad4.pollStatus();
  35533. },
  35534. /**
  35535. * Updating connected gamepads (for Google Chrome). Should not be called manually.
  35536. *
  35537. * @method Phaser.Gamepad#_pollGamepads
  35538. * @private
  35539. */
  35540. _pollGamepads: function () {
  35541. if (!this._active)
  35542. {
  35543. return;
  35544. }
  35545. if (navigator['getGamepads'])
  35546. {
  35547. var rawGamepads = navigator.getGamepads();
  35548. }
  35549. else if (navigator['webkitGetGamepads'])
  35550. {
  35551. var rawGamepads = navigator.webkitGetGamepads();
  35552. }
  35553. else if (navigator['webkitGamepads'])
  35554. {
  35555. var rawGamepads = navigator.webkitGamepads();
  35556. }
  35557. if (rawGamepads)
  35558. {
  35559. this._rawPads = [];
  35560. var gamepadsChanged = false;
  35561. for (var i = 0; i < rawGamepads.length; i++)
  35562. {
  35563. if (typeof rawGamepads[i] !== this._prevRawGamepadTypes[i])
  35564. {
  35565. gamepadsChanged = true;
  35566. this._prevRawGamepadTypes[i] = typeof rawGamepads[i];
  35567. }
  35568. if (rawGamepads[i])
  35569. {
  35570. this._rawPads.push(rawGamepads[i]);
  35571. }
  35572. // Support max 4 pads at the moment
  35573. if (i === 3)
  35574. {
  35575. break;
  35576. }
  35577. }
  35578. for (var g = 0; g < this._gamepads.length; g++)
  35579. {
  35580. this._gamepads[g]._rawPad = this._rawPads[g];
  35581. }
  35582. if (gamepadsChanged)
  35583. {
  35584. var validConnections = { rawIndices: {}, padIndices: {} };
  35585. var singlePad;
  35586. for (var j = 0; j < this._gamepads.length; j++)
  35587. {
  35588. singlePad = this._gamepads[j];
  35589. if (singlePad.connected)
  35590. {
  35591. for (var k = 0; k < this._rawPads.length; k++)
  35592. {
  35593. if (this._rawPads[k].index === singlePad.index)
  35594. {
  35595. validConnections.rawIndices[singlePad.index] = true;
  35596. validConnections.padIndices[j] = true;
  35597. }
  35598. }
  35599. }
  35600. }
  35601. for (var l = 0; l < this._gamepads.length; l++)
  35602. {
  35603. singlePad = this._gamepads[l];
  35604. if (validConnections.padIndices[l])
  35605. {
  35606. continue;
  35607. }
  35608. if (this._rawPads.length < 1)
  35609. {
  35610. singlePad.disconnect();
  35611. }
  35612. for (var m = 0; m < this._rawPads.length; m++)
  35613. {
  35614. if (validConnections.padIndices[l])
  35615. {
  35616. break;
  35617. }
  35618. var rawPad = this._rawPads[m];
  35619. if (rawPad)
  35620. {
  35621. if (validConnections.rawIndices[rawPad.index])
  35622. {
  35623. singlePad.disconnect();
  35624. continue;
  35625. }
  35626. else
  35627. {
  35628. singlePad.connect(rawPad);
  35629. validConnections.rawIndices[rawPad.index] = true;
  35630. validConnections.padIndices[l] = true;
  35631. }
  35632. }
  35633. else
  35634. {
  35635. singlePad.disconnect();
  35636. }
  35637. }
  35638. }
  35639. }
  35640. }
  35641. },
  35642. /**
  35643. * Sets the deadZone variable for all four gamepads
  35644. * @method Phaser.Gamepad#setDeadZones
  35645. */
  35646. setDeadZones: function (value) {
  35647. for (var i = 0; i < this._gamepads.length; i++)
  35648. {
  35649. this._gamepads[i].deadZone = value;
  35650. }
  35651. },
  35652. /**
  35653. * Stops the Gamepad event handling.
  35654. *
  35655. * @method Phaser.Gamepad#stop
  35656. */
  35657. stop: function () {
  35658. this._active = false;
  35659. window.removeEventListener('gamepadconnected', this._onGamepadConnected);
  35660. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnected);
  35661. },
  35662. /**
  35663. * Reset all buttons/axes of all gamepads
  35664. * @method Phaser.Gamepad#reset
  35665. */
  35666. reset: function () {
  35667. this.update();
  35668. for (var i = 0; i < this._gamepads.length; i++)
  35669. {
  35670. this._gamepads[i].reset();
  35671. }
  35672. },
  35673. /**
  35674. * Returns the "just pressed" state of a button from ANY gamepad connected. Just pressed is considered true if the button was pressed down within the duration given (default 250ms).
  35675. * @method Phaser.Gamepad#justPressed
  35676. * @param {number} buttonCode - The buttonCode of the button to check for.
  35677. * @param {number} [duration=250] - The duration below which the button is considered as being just pressed.
  35678. * @return {boolean} True if the button is just pressed otherwise false.
  35679. */
  35680. justPressed: function (buttonCode, duration) {
  35681. for (var i = 0; i < this._gamepads.length; i++)
  35682. {
  35683. if (this._gamepads[i].justPressed(buttonCode, duration) === true)
  35684. {
  35685. return true;
  35686. }
  35687. }
  35688. return false;
  35689. },
  35690. /**
  35691. * Returns the "just released" state of a button from ANY gamepad connected. Just released is considered as being true if the button was released within the duration given (default 250ms).
  35692. * @method Phaser.Gamepad#justPressed
  35693. * @param {number} buttonCode - The buttonCode of the button to check for.
  35694. * @param {number} [duration=250] - The duration below which the button is considered as being just released.
  35695. * @return {boolean} True if the button is just released otherwise false.
  35696. */
  35697. justReleased: function (buttonCode, duration) {
  35698. for (var i = 0; i < this._gamepads.length; i++)
  35699. {
  35700. if (this._gamepads[i].justReleased(buttonCode, duration) === true)
  35701. {
  35702. return true;
  35703. }
  35704. }
  35705. return false;
  35706. },
  35707. /**
  35708. * Returns true if the button is currently pressed down, on ANY gamepad.
  35709. * @method Phaser.Gamepad#isDown
  35710. * @param {number} buttonCode - The buttonCode of the button to check for.
  35711. * @return {boolean} True if a button is currently down.
  35712. */
  35713. isDown: function (buttonCode) {
  35714. for (var i = 0; i < this._gamepads.length; i++)
  35715. {
  35716. if (this._gamepads[i].isDown(buttonCode) === true)
  35717. {
  35718. return true;
  35719. }
  35720. }
  35721. return false;
  35722. },
  35723. /**
  35724. * Destroys this object and the associated event listeners.
  35725. *
  35726. * @method Phaser.Gamepad#destroy
  35727. */
  35728. destroy: function () {
  35729. this.stop();
  35730. for (var i = 0; i < this._gamepads.length; i++)
  35731. {
  35732. this._gamepads[i].destroy();
  35733. }
  35734. }
  35735. };
  35736. Phaser.Gamepad.prototype.constructor = Phaser.Gamepad;
  35737. /**
  35738. * If the gamepad input is active or not - if not active it should not be updated from Input.js
  35739. * @name Phaser.Gamepad#active
  35740. * @property {boolean} active - If the gamepad input is active or not.
  35741. * @readonly
  35742. */
  35743. Object.defineProperty(Phaser.Gamepad.prototype, "active", {
  35744. get: function () {
  35745. return this._active;
  35746. }
  35747. });
  35748. /**
  35749. * Whether or not gamepads are supported in current browser.
  35750. * @name Phaser.Gamepad#supported
  35751. * @property {boolean} supported - Whether or not gamepads are supported in current browser.
  35752. * @readonly
  35753. */
  35754. Object.defineProperty(Phaser.Gamepad.prototype, "supported", {
  35755. get: function () {
  35756. return this._gamepadSupportAvailable;
  35757. }
  35758. });
  35759. /**
  35760. * How many live gamepads are currently connected.
  35761. * @name Phaser.Gamepad#padsConnected
  35762. * @property {number} padsConnected - How many live gamepads are currently connected.
  35763. * @readonly
  35764. */
  35765. Object.defineProperty(Phaser.Gamepad.prototype, "padsConnected", {
  35766. get: function () {
  35767. return this._rawPads.length;
  35768. }
  35769. });
  35770. /**
  35771. * Gamepad #1
  35772. * @name Phaser.Gamepad#pad1
  35773. * @property {Phaser.SinglePad} pad1 - Gamepad #1;
  35774. * @readonly
  35775. */
  35776. Object.defineProperty(Phaser.Gamepad.prototype, "pad1", {
  35777. get: function () {
  35778. return this._gamepads[0];
  35779. }
  35780. });
  35781. /**
  35782. * Gamepad #2
  35783. * @name Phaser.Gamepad#pad2
  35784. * @property {Phaser.SinglePad} pad2 - Gamepad #2
  35785. * @readonly
  35786. */
  35787. Object.defineProperty(Phaser.Gamepad.prototype, "pad2", {
  35788. get: function () {
  35789. return this._gamepads[1];
  35790. }
  35791. });
  35792. /**
  35793. * Gamepad #3
  35794. * @name Phaser.Gamepad#pad3
  35795. * @property {Phaser.SinglePad} pad3 - Gamepad #3
  35796. * @readonly
  35797. */
  35798. Object.defineProperty(Phaser.Gamepad.prototype, "pad3", {
  35799. get: function () {
  35800. return this._gamepads[2];
  35801. }
  35802. });
  35803. /**
  35804. * Gamepad #4
  35805. * @name Phaser.Gamepad#pad4
  35806. * @property {Phaser.SinglePad} pad4 - Gamepad #4
  35807. * @readonly
  35808. */
  35809. Object.defineProperty(Phaser.Gamepad.prototype, "pad4", {
  35810. get: function () {
  35811. return this._gamepads[3];
  35812. }
  35813. });
  35814. Phaser.Gamepad.BUTTON_0 = 0;
  35815. Phaser.Gamepad.BUTTON_1 = 1;
  35816. Phaser.Gamepad.BUTTON_2 = 2;
  35817. Phaser.Gamepad.BUTTON_3 = 3;
  35818. Phaser.Gamepad.BUTTON_4 = 4;
  35819. Phaser.Gamepad.BUTTON_5 = 5;
  35820. Phaser.Gamepad.BUTTON_6 = 6;
  35821. Phaser.Gamepad.BUTTON_7 = 7;
  35822. Phaser.Gamepad.BUTTON_8 = 8;
  35823. Phaser.Gamepad.BUTTON_9 = 9;
  35824. Phaser.Gamepad.BUTTON_10 = 10;
  35825. Phaser.Gamepad.BUTTON_11 = 11;
  35826. Phaser.Gamepad.BUTTON_12 = 12;
  35827. Phaser.Gamepad.BUTTON_13 = 13;
  35828. Phaser.Gamepad.BUTTON_14 = 14;
  35829. Phaser.Gamepad.BUTTON_15 = 15;
  35830. Phaser.Gamepad.AXIS_0 = 0;
  35831. Phaser.Gamepad.AXIS_1 = 1;
  35832. Phaser.Gamepad.AXIS_2 = 2;
  35833. Phaser.Gamepad.AXIS_3 = 3;
  35834. Phaser.Gamepad.AXIS_4 = 4;
  35835. Phaser.Gamepad.AXIS_5 = 5;
  35836. Phaser.Gamepad.AXIS_6 = 6;
  35837. Phaser.Gamepad.AXIS_7 = 7;
  35838. Phaser.Gamepad.AXIS_8 = 8;
  35839. Phaser.Gamepad.AXIS_9 = 9;
  35840. // Below mapping applies to XBOX 360 Wired and Wireless controller on Google Chrome (tested on Windows 7).
  35841. // - Firefox uses different map! Separate amount of buttons and axes. DPAD = axis and not a button.
  35842. // In other words - discrepancies when using gamepads.
  35843. Phaser.Gamepad.XBOX360_A = 0;
  35844. Phaser.Gamepad.XBOX360_B = 1;
  35845. Phaser.Gamepad.XBOX360_X = 2;
  35846. Phaser.Gamepad.XBOX360_Y = 3;
  35847. Phaser.Gamepad.XBOX360_LEFT_BUMPER = 4;
  35848. Phaser.Gamepad.XBOX360_RIGHT_BUMPER = 5;
  35849. Phaser.Gamepad.XBOX360_LEFT_TRIGGER = 6;
  35850. Phaser.Gamepad.XBOX360_RIGHT_TRIGGER = 7;
  35851. Phaser.Gamepad.XBOX360_BACK = 8;
  35852. Phaser.Gamepad.XBOX360_START = 9;
  35853. Phaser.Gamepad.XBOX360_STICK_LEFT_BUTTON = 10;
  35854. Phaser.Gamepad.XBOX360_STICK_RIGHT_BUTTON = 11;
  35855. Phaser.Gamepad.XBOX360_DPAD_LEFT = 14;
  35856. Phaser.Gamepad.XBOX360_DPAD_RIGHT = 15;
  35857. Phaser.Gamepad.XBOX360_DPAD_UP = 12;
  35858. Phaser.Gamepad.XBOX360_DPAD_DOWN = 13;
  35859. // On FF 0 = Y, 1 = X, 2 = Y, 3 = X, 4 = left bumper, 5 = dpad left, 6 = dpad right
  35860. Phaser.Gamepad.XBOX360_STICK_LEFT_X = 0;
  35861. Phaser.Gamepad.XBOX360_STICK_LEFT_Y = 1;
  35862. Phaser.Gamepad.XBOX360_STICK_RIGHT_X = 2;
  35863. Phaser.Gamepad.XBOX360_STICK_RIGHT_Y = 3;
  35864. // PlayStation 3 controller (masquerading as xbox360 controller) button mappings
  35865. Phaser.Gamepad.PS3XC_X = 0;
  35866. Phaser.Gamepad.PS3XC_CIRCLE = 1;
  35867. Phaser.Gamepad.PS3XC_SQUARE = 2;
  35868. Phaser.Gamepad.PS3XC_TRIANGLE = 3;
  35869. Phaser.Gamepad.PS3XC_L1 = 4;
  35870. Phaser.Gamepad.PS3XC_R1 = 5;
  35871. Phaser.Gamepad.PS3XC_L2 = 6; // analog trigger, range 0..1
  35872. Phaser.Gamepad.PS3XC_R2 = 7; // analog trigger, range 0..1
  35873. Phaser.Gamepad.PS3XC_SELECT = 8;
  35874. Phaser.Gamepad.PS3XC_START = 9;
  35875. Phaser.Gamepad.PS3XC_STICK_LEFT_BUTTON = 10;
  35876. Phaser.Gamepad.PS3XC_STICK_RIGHT_BUTTON = 11;
  35877. Phaser.Gamepad.PS3XC_DPAD_UP = 12;
  35878. Phaser.Gamepad.PS3XC_DPAD_DOWN = 13;
  35879. Phaser.Gamepad.PS3XC_DPAD_LEFT = 14;
  35880. Phaser.Gamepad.PS3XC_DPAD_RIGHT = 15;
  35881. Phaser.Gamepad.PS3XC_STICK_LEFT_X = 0; // analog stick, range -1..1
  35882. Phaser.Gamepad.PS3XC_STICK_LEFT_Y = 1; // analog stick, range -1..1
  35883. Phaser.Gamepad.PS3XC_STICK_RIGHT_X = 2; // analog stick, range -1..1
  35884. Phaser.Gamepad.PS3XC_STICK_RIGHT_Y = 3; // analog stick, range -1..1
  35885. /**
  35886. * @author @karlmacklin <tacklemcclean@gmail.com>
  35887. * @author Richard Davey <rich@photonstorm.com>
  35888. * @copyright 2016 Photon Storm Ltd.
  35889. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  35890. */
  35891. /**
  35892. * A single Phaser Gamepad
  35893. *
  35894. * @class Phaser.SinglePad
  35895. * @constructor
  35896. * @param {Phaser.Game} game - Current game instance.
  35897. * @param {object} padParent - The parent Phaser.Gamepad object (all gamepads reside under this)
  35898. */
  35899. Phaser.SinglePad = function (game, padParent) {
  35900. /**
  35901. * @property {Phaser.Game} game - Local reference to game.
  35902. */
  35903. this.game = game;
  35904. /**
  35905. * @property {number} index - The gamepad index as per browsers data
  35906. * @readonly
  35907. */
  35908. this.index = null;
  35909. /**
  35910. * @property {boolean} connected - Whether or not this particular gamepad is connected or not.
  35911. * @readonly
  35912. */
  35913. this.connected = false;
  35914. /**
  35915. * @property {object} callbackContext - The context under which the callbacks are run.
  35916. */
  35917. this.callbackContext = this;
  35918. /**
  35919. * @property {function} onConnectCallback - This callback is invoked every time this gamepad is connected
  35920. */
  35921. this.onConnectCallback = null;
  35922. /**
  35923. * @property {function} onDisconnectCallback - This callback is invoked every time this gamepad is disconnected
  35924. */
  35925. this.onDisconnectCallback = null;
  35926. /**
  35927. * @property {function} onDownCallback - This callback is invoked every time a button is pressed down.
  35928. */
  35929. this.onDownCallback = null;
  35930. /**
  35931. * @property {function} onUpCallback - This callback is invoked every time a gamepad button is released.
  35932. */
  35933. this.onUpCallback = null;
  35934. /**
  35935. * @property {function} onAxisCallback - This callback is invoked every time an axis is changed.
  35936. */
  35937. this.onAxisCallback = null;
  35938. /**
  35939. * @property {function} onFloatCallback - This callback is invoked every time a button is changed to a value where value > 0 and value < 1.
  35940. */
  35941. this.onFloatCallback = null;
  35942. /**
  35943. * @property {number} deadZone - Dead zone for axis feedback - within this value you won't trigger updates.
  35944. */
  35945. this.deadZone = 0.26;
  35946. /**
  35947. * @property {Phaser.Gamepad} padParent - Main Phaser Gamepad object
  35948. * @private
  35949. */
  35950. this._padParent = padParent;
  35951. /**
  35952. * @property {object} _rawPad - The 'raw' gamepad data.
  35953. * @private
  35954. */
  35955. this._rawPad = null;
  35956. /**
  35957. * @property {number} _prevTimestamp - Used to check for differences between earlier polls and current state of gamepads.
  35958. * @private
  35959. */
  35960. this._prevTimestamp = null;
  35961. /**
  35962. * @property {Array} _buttons - Array of Phaser.DeviceButton objects. This array is populated when the gamepad is connected.
  35963. * @private
  35964. */
  35965. this._buttons = [];
  35966. /**
  35967. * @property {number} _buttonsLen - Length of the _buttons array.
  35968. * @private
  35969. */
  35970. this._buttonsLen = 0;
  35971. /**
  35972. * @property {Array} _axes - Current axes state.
  35973. * @private
  35974. */
  35975. this._axes = [];
  35976. /**
  35977. * @property {number} _axesLen - Length of the _axes array.
  35978. * @private
  35979. */
  35980. this._axesLen = 0;
  35981. };
  35982. Phaser.SinglePad.prototype = {
  35983. /**
  35984. * Add callbacks to this Gamepad to handle connect / disconnect / button down / button up / axis change / float value buttons.
  35985. *
  35986. * @method Phaser.SinglePad#addCallbacks
  35987. * @param {object} context - The context under which the callbacks are run.
  35988. * @param {object} callbacks - Object that takes six different callbak methods:
  35989. * onConnectCallback, onDisconnectCallback, onDownCallback, onUpCallback, onAxisCallback, onFloatCallback
  35990. */
  35991. addCallbacks: function (context, callbacks) {
  35992. if (typeof callbacks !== 'undefined')
  35993. {
  35994. this.onConnectCallback = (typeof callbacks.onConnect === 'function') ? callbacks.onConnect : this.onConnectCallback;
  35995. this.onDisconnectCallback = (typeof callbacks.onDisconnect === 'function') ? callbacks.onDisconnect : this.onDisconnectCallback;
  35996. this.onDownCallback = (typeof callbacks.onDown === 'function') ? callbacks.onDown : this.onDownCallback;
  35997. this.onUpCallback = (typeof callbacks.onUp === 'function') ? callbacks.onUp : this.onUpCallback;
  35998. this.onAxisCallback = (typeof callbacks.onAxis === 'function') ? callbacks.onAxis : this.onAxisCallback;
  35999. this.onFloatCallback = (typeof callbacks.onFloat === 'function') ? callbacks.onFloat : this.onFloatCallback;
  36000. this.callbackContext = context;
  36001. }
  36002. },
  36003. /**
  36004. * Gets a DeviceButton object from this controller to be stored and referenced locally.
  36005. * The DeviceButton object can then be polled, have events attached to it, etc.
  36006. *
  36007. * @method Phaser.SinglePad#getButton
  36008. * @param {number} buttonCode - The buttonCode of the button, i.e. Phaser.Gamepad.BUTTON_0, Phaser.Gamepad.XBOX360_A, etc.
  36009. * @return {Phaser.DeviceButton} The DeviceButton object which you can store locally and reference directly.
  36010. */
  36011. getButton: function (buttonCode) {
  36012. if (this._buttons[buttonCode])
  36013. {
  36014. return this._buttons[buttonCode];
  36015. }
  36016. else
  36017. {
  36018. return null;
  36019. }
  36020. },
  36021. /**
  36022. * Main update function called by Phaser.Gamepad.
  36023. *
  36024. * @method Phaser.SinglePad#pollStatus
  36025. */
  36026. pollStatus: function () {
  36027. if (!this.connected || !this.game.input.enabled || !this.game.input.gamepad.enabled || (this._rawPad.timestamp && (this._rawPad.timestamp === this._prevTimestamp)))
  36028. {
  36029. return;
  36030. }
  36031. for (var i = 0; i < this._buttonsLen; i++)
  36032. {
  36033. var rawButtonVal = isNaN(this._rawPad.buttons[i]) ? this._rawPad.buttons[i].value : this._rawPad.buttons[i];
  36034. if (rawButtonVal !== this._buttons[i].value)
  36035. {
  36036. if (rawButtonVal === 1)
  36037. {
  36038. this.processButtonDown(i, rawButtonVal);
  36039. }
  36040. else if (rawButtonVal === 0)
  36041. {
  36042. this.processButtonUp(i, rawButtonVal);
  36043. }
  36044. else
  36045. {
  36046. this.processButtonFloat(i, rawButtonVal);
  36047. }
  36048. }
  36049. }
  36050. for (var index = 0; index < this._axesLen; index++)
  36051. {
  36052. var value = this._rawPad.axes[index];
  36053. if ((value > 0 && value > this.deadZone) || (value < 0 && value < -this.deadZone))
  36054. {
  36055. this.processAxisChange(index, value);
  36056. }
  36057. else
  36058. {
  36059. this.processAxisChange(index, 0);
  36060. }
  36061. }
  36062. this._prevTimestamp = this._rawPad.timestamp;
  36063. },
  36064. /**
  36065. * Gamepad connect function, should be called by Phaser.Gamepad.
  36066. *
  36067. * @method Phaser.SinglePad#connect
  36068. * @param {object} rawPad - The raw gamepad object
  36069. */
  36070. connect: function (rawPad) {
  36071. var triggerCallback = !this.connected;
  36072. this.connected = true;
  36073. this.index = rawPad.index;
  36074. this._rawPad = rawPad;
  36075. this._buttons = [];
  36076. this._buttonsLen = rawPad.buttons.length;
  36077. this._axes = [];
  36078. this._axesLen = rawPad.axes.length;
  36079. for (var a = 0; a < this._axesLen; a++)
  36080. {
  36081. this._axes[a] = rawPad.axes[a];
  36082. }
  36083. for (var buttonCode in rawPad.buttons)
  36084. {
  36085. buttonCode = parseInt(buttonCode, 10);
  36086. this._buttons[buttonCode] = new Phaser.DeviceButton(this, buttonCode);
  36087. }
  36088. if (triggerCallback && this._padParent.onConnectCallback)
  36089. {
  36090. this._padParent.onConnectCallback.call(this._padParent.callbackContext, this.index);
  36091. }
  36092. if (triggerCallback && this.onConnectCallback)
  36093. {
  36094. this.onConnectCallback.call(this.callbackContext);
  36095. }
  36096. },
  36097. /**
  36098. * Gamepad disconnect function, should be called by Phaser.Gamepad.
  36099. *
  36100. * @method Phaser.SinglePad#disconnect
  36101. */
  36102. disconnect: function () {
  36103. var triggerCallback = this.connected;
  36104. var disconnectingIndex = this.index;
  36105. this.connected = false;
  36106. this.index = null;
  36107. this._rawPad = undefined;
  36108. for (var i = 0; i < this._buttonsLen; i++)
  36109. {
  36110. this._buttons[i].destroy();
  36111. }
  36112. this._buttons = [];
  36113. this._buttonsLen = 0;
  36114. this._axes = [];
  36115. this._axesLen = 0;
  36116. if (triggerCallback && this._padParent.onDisconnectCallback)
  36117. {
  36118. this._padParent.onDisconnectCallback.call(this._padParent.callbackContext, disconnectingIndex);
  36119. }
  36120. if (triggerCallback && this.onDisconnectCallback)
  36121. {
  36122. this.onDisconnectCallback.call(this.callbackContext);
  36123. }
  36124. },
  36125. /**
  36126. * Destroys this object and associated callback references.
  36127. *
  36128. * @method Phaser.SinglePad#destroy
  36129. */
  36130. destroy: function () {
  36131. this._rawPad = undefined;
  36132. for (var i = 0; i < this._buttonsLen; i++)
  36133. {
  36134. this._buttons[i].destroy();
  36135. }
  36136. this._buttons = [];
  36137. this._buttonsLen = 0;
  36138. this._axes = [];
  36139. this._axesLen = 0;
  36140. this.onConnectCallback = null;
  36141. this.onDisconnectCallback = null;
  36142. this.onDownCallback = null;
  36143. this.onUpCallback = null;
  36144. this.onAxisCallback = null;
  36145. this.onFloatCallback = null;
  36146. },
  36147. /**
  36148. * Handles changes in axis.
  36149. *
  36150. * @method Phaser.SinglePad#processAxisChange
  36151. * @param {object} axisState - State of the relevant axis
  36152. */
  36153. processAxisChange: function (index, value) {
  36154. if (this._axes[index] === value)
  36155. {
  36156. return;
  36157. }
  36158. this._axes[index] = value;
  36159. if (this._padParent.onAxisCallback)
  36160. {
  36161. this._padParent.onAxisCallback.call(this._padParent.callbackContext, this, index, value);
  36162. }
  36163. if (this.onAxisCallback)
  36164. {
  36165. this.onAxisCallback.call(this.callbackContext, this, index, value);
  36166. }
  36167. },
  36168. /**
  36169. * Handles button down press.
  36170. *
  36171. * @method Phaser.SinglePad#processButtonDown
  36172. * @param {number} buttonCode - Which buttonCode of this button
  36173. * @param {object} value - Button value
  36174. */
  36175. processButtonDown: function (buttonCode, value) {
  36176. if (this._buttons[buttonCode])
  36177. {
  36178. this._buttons[buttonCode].start(null, value);
  36179. }
  36180. if (this._padParent.onDownCallback)
  36181. {
  36182. this._padParent.onDownCallback.call(this._padParent.callbackContext, buttonCode, value, this.index);
  36183. }
  36184. if (this.onDownCallback)
  36185. {
  36186. this.onDownCallback.call(this.callbackContext, buttonCode, value);
  36187. }
  36188. },
  36189. /**
  36190. * Handles button release.
  36191. *
  36192. * @method Phaser.SinglePad#processButtonUp
  36193. * @param {number} buttonCode - Which buttonCode of this button
  36194. * @param {object} value - Button value
  36195. */
  36196. processButtonUp: function (buttonCode, value) {
  36197. if (this._padParent.onUpCallback)
  36198. {
  36199. this._padParent.onUpCallback.call(this._padParent.callbackContext, buttonCode, value, this.index);
  36200. }
  36201. if (this.onUpCallback)
  36202. {
  36203. this.onUpCallback.call(this.callbackContext, buttonCode, value);
  36204. }
  36205. if (this._buttons[buttonCode])
  36206. {
  36207. this._buttons[buttonCode].stop(null, value);
  36208. }
  36209. },
  36210. /**
  36211. * Handles buttons with floating values (like analog buttons that acts almost like an axis but still registers like a button)
  36212. *
  36213. * @method Phaser.SinglePad#processButtonFloat
  36214. * @param {number} buttonCode - Which buttonCode of this button
  36215. * @param {object} value - Button value (will range somewhere between 0 and 1, but not specifically 0 or 1.
  36216. */
  36217. processButtonFloat: function (buttonCode, value) {
  36218. if (this._padParent.onFloatCallback)
  36219. {
  36220. this._padParent.onFloatCallback.call(this._padParent.callbackContext, buttonCode, value, this.index);
  36221. }
  36222. if (this.onFloatCallback)
  36223. {
  36224. this.onFloatCallback.call(this.callbackContext, buttonCode, value);
  36225. }
  36226. if (this._buttons[buttonCode])
  36227. {
  36228. this._buttons[buttonCode].padFloat(value);
  36229. }
  36230. },
  36231. /**
  36232. * Returns value of requested axis.
  36233. *
  36234. * @method Phaser.SinglePad#axis
  36235. * @param {number} axisCode - The index of the axis to check
  36236. * @return {number} Axis value if available otherwise false
  36237. */
  36238. axis: function (axisCode) {
  36239. if (this._axes[axisCode])
  36240. {
  36241. return this._axes[axisCode];
  36242. }
  36243. return false;
  36244. },
  36245. /**
  36246. * Returns true if the button is pressed down.
  36247. *
  36248. * @method Phaser.SinglePad#isDown
  36249. * @param {number} buttonCode - The buttonCode of the button to check.
  36250. * @return {boolean} True if the button is pressed down.
  36251. */
  36252. isDown: function (buttonCode) {
  36253. if (this._buttons[buttonCode])
  36254. {
  36255. return this._buttons[buttonCode].isDown;
  36256. }
  36257. return false;
  36258. },
  36259. /**
  36260. * Returns true if the button is not currently pressed.
  36261. *
  36262. * @method Phaser.SinglePad#isUp
  36263. * @param {number} buttonCode - The buttonCode of the button to check.
  36264. * @return {boolean} True if the button is not currently pressed down.
  36265. */
  36266. isUp: function (buttonCode) {
  36267. if (this._buttons[buttonCode])
  36268. {
  36269. return this._buttons[buttonCode].isUp;
  36270. }
  36271. return false;
  36272. },
  36273. /**
  36274. * Returns the "just released" state of a button from this gamepad. Just released is considered as being true if the button was released within the duration given (default 250ms).
  36275. *
  36276. * @method Phaser.SinglePad#justReleased
  36277. * @param {number} buttonCode - The buttonCode of the button to check for.
  36278. * @param {number} [duration=250] - The duration below which the button is considered as being just released.
  36279. * @return {boolean} True if the button is just released otherwise false.
  36280. */
  36281. justReleased: function (buttonCode, duration) {
  36282. if (this._buttons[buttonCode])
  36283. {
  36284. return this._buttons[buttonCode].justReleased(duration);
  36285. }
  36286. },
  36287. /**
  36288. * Returns the "just pressed" state of a button from this gamepad. Just pressed is considered true if the button was pressed down within the duration given (default 250ms).
  36289. *
  36290. * @method Phaser.SinglePad#justPressed
  36291. * @param {number} buttonCode - The buttonCode of the button to check for.
  36292. * @param {number} [duration=250] - The duration below which the button is considered as being just pressed.
  36293. * @return {boolean} True if the button is just pressed otherwise false.
  36294. */
  36295. justPressed: function (buttonCode, duration) {
  36296. if (this._buttons[buttonCode])
  36297. {
  36298. return this._buttons[buttonCode].justPressed(duration);
  36299. }
  36300. },
  36301. /**
  36302. * Returns the value of a gamepad button. Intended mainly for cases when you have floating button values, for example
  36303. * analog trigger buttons on the XBOX 360 controller.
  36304. *
  36305. * @method Phaser.SinglePad#buttonValue
  36306. * @param {number} buttonCode - The buttonCode of the button to check.
  36307. * @return {number} Button value if available otherwise null. Be careful as this can incorrectly evaluate to 0.
  36308. */
  36309. buttonValue: function (buttonCode) {
  36310. if (this._buttons[buttonCode])
  36311. {
  36312. return this._buttons[buttonCode].value;
  36313. }
  36314. return null;
  36315. },
  36316. /**
  36317. * Reset all buttons/axes of this gamepad.
  36318. *
  36319. * @method Phaser.SinglePad#reset
  36320. */
  36321. reset: function () {
  36322. for (var j = 0; j < this._axes.length; j++)
  36323. {
  36324. this._axes[j] = 0;
  36325. }
  36326. }
  36327. };
  36328. Phaser.SinglePad.prototype.constructor = Phaser.SinglePad;
  36329. /**
  36330. * @author Richard Davey <rich@photonstorm.com>
  36331. * @copyright 2016 Photon Storm Ltd.
  36332. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  36333. */
  36334. /**
  36335. * If you need more fine-grained control over the handling of specific keys you can create and use Phaser.Key objects.
  36336. *
  36337. * @class Phaser.Key
  36338. * @constructor
  36339. * @param {Phaser.Game} game - Current game instance.
  36340. * @param {integer} keycode - The key code this Key is responsible for. See {@link Phaser.KeyCode}.
  36341. */
  36342. Phaser.Key = function (game, keycode) {
  36343. /**
  36344. * @property {Phaser.Game} game - A reference to the currently running game.
  36345. */
  36346. this.game = game;
  36347. /**
  36348. * The enabled state of the key - see `enabled`.
  36349. * @property {boolean} _enabled
  36350. * @private
  36351. */
  36352. this._enabled = true;
  36353. /**
  36354. * @property {object} event - Stores the most recent DOM event.
  36355. * @readonly
  36356. */
  36357. this.event = null;
  36358. /**
  36359. * @property {boolean} isDown - The "down" state of the key. This will remain `true` for as long as the keyboard thinks this key is held down.
  36360. * @default
  36361. */
  36362. this.isDown = false;
  36363. /**
  36364. * @property {boolean} isUp - The "up" state of the key. This will remain `true` for as long as the keyboard thinks this key is up.
  36365. * @default
  36366. */
  36367. this.isUp = true;
  36368. /**
  36369. * @property {boolean} altKey - The down state of the ALT key, if pressed at the same time as this key.
  36370. * @default
  36371. */
  36372. this.altKey = false;
  36373. /**
  36374. * @property {boolean} ctrlKey - The down state of the CTRL key, if pressed at the same time as this key.
  36375. * @default
  36376. */
  36377. this.ctrlKey = false;
  36378. /**
  36379. * @property {boolean} shiftKey - The down state of the SHIFT key, if pressed at the same time as this key.
  36380. * @default
  36381. */
  36382. this.shiftKey = false;
  36383. /**
  36384. * @property {number} timeDown - The timestamp when the key was last pressed down. This is based on Game.time.now.
  36385. */
  36386. this.timeDown = 0;
  36387. /**
  36388. * If the key is down this value holds the duration of that key press and is constantly updated.
  36389. * If the key is up it holds the duration of the previous down session.
  36390. * @property {number} duration - The number of milliseconds this key has been held down for.
  36391. * @default
  36392. */
  36393. this.duration = 0;
  36394. /**
  36395. * @property {number} timeUp - The timestamp when the key was last released. This is based on Game.time.now.
  36396. * @default
  36397. */
  36398. this.timeUp = -2500;
  36399. /**
  36400. * @property {number} repeats - If a key is held down this holds down the number of times the key has 'repeated'.
  36401. * @default
  36402. */
  36403. this.repeats = 0;
  36404. /**
  36405. * @property {number} keyCode - The keycode of this key.
  36406. */
  36407. this.keyCode = keycode;
  36408. /**
  36409. * @property {Phaser.Signal} onDown - This Signal is dispatched every time this Key is pressed down. It is only dispatched once (until the key is released again).
  36410. */
  36411. this.onDown = new Phaser.Signal();
  36412. /**
  36413. * @property {function} onHoldCallback - A callback that is called while this Key is held down. Warning: Depending on refresh rate that could be 60+ times per second.
  36414. */
  36415. this.onHoldCallback = null;
  36416. /**
  36417. * @property {object} onHoldContext - The context under which the onHoldCallback will be called.
  36418. */
  36419. this.onHoldContext = null;
  36420. /**
  36421. * @property {Phaser.Signal} onUp - This Signal is dispatched every time this Key is released. It is only dispatched once (until the key is pressed and released again).
  36422. */
  36423. this.onUp = new Phaser.Signal();
  36424. /**
  36425. * @property {boolean} _justDown - True if the key has just been pressed (NOTE: requires to be reset, see justDown getter)
  36426. * @private
  36427. */
  36428. this._justDown = false;
  36429. /**
  36430. * @property {boolean} _justUp - True if the key has just been pressed (NOTE: requires to be reset, see justDown getter)
  36431. * @private
  36432. */
  36433. this._justUp = false;
  36434. };
  36435. Phaser.Key.prototype = {
  36436. /**
  36437. * Called automatically by Phaser.Keyboard.
  36438. *
  36439. * @method Phaser.Key#update
  36440. * @protected
  36441. */
  36442. update: function () {
  36443. if (!this._enabled) { return; }
  36444. if (this.isDown)
  36445. {
  36446. this.duration = this.game.time.time - this.timeDown;
  36447. this.repeats++;
  36448. if (this.onHoldCallback)
  36449. {
  36450. this.onHoldCallback.call(this.onHoldContext, this);
  36451. }
  36452. }
  36453. },
  36454. /**
  36455. * Called automatically by Phaser.Keyboard.
  36456. *
  36457. * @method Phaser.Key#processKeyDown
  36458. * @param {KeyboardEvent} event - The DOM event that triggered this.
  36459. * @protected
  36460. */
  36461. processKeyDown: function (event) {
  36462. if (!this._enabled) { return; }
  36463. this.event = event;
  36464. // exit if this key down is from auto-repeat
  36465. if (this.isDown)
  36466. {
  36467. return;
  36468. }
  36469. this.altKey = event.altKey;
  36470. this.ctrlKey = event.ctrlKey;
  36471. this.shiftKey = event.shiftKey;
  36472. this.isDown = true;
  36473. this.isUp = false;
  36474. this.timeDown = this.game.time.time;
  36475. this.duration = 0;
  36476. this.repeats = 0;
  36477. // _justDown will remain true until it is read via the justDown Getter
  36478. // this enables the game to poll for past presses, or reset it at the start of a new game state
  36479. this._justDown = true;
  36480. this.onDown.dispatch(this);
  36481. },
  36482. /**
  36483. * Called automatically by Phaser.Keyboard.
  36484. *
  36485. * @method Phaser.Key#processKeyUp
  36486. * @param {KeyboardEvent} event - The DOM event that triggered this.
  36487. * @protected
  36488. */
  36489. processKeyUp: function (event) {
  36490. if (!this._enabled) { return; }
  36491. this.event = event;
  36492. if (this.isUp)
  36493. {
  36494. return;
  36495. }
  36496. this.isDown = false;
  36497. this.isUp = true;
  36498. this.timeUp = this.game.time.time;
  36499. this.duration = this.game.time.time - this.timeDown;
  36500. // _justUp will remain true until it is read via the justUp Getter
  36501. // this enables the game to poll for past presses, or reset it at the start of a new game state
  36502. this._justUp = true;
  36503. this.onUp.dispatch(this);
  36504. },
  36505. /**
  36506. * Resets the state of this Key.
  36507. *
  36508. * This sets isDown to false, isUp to true, resets the time to be the current time, and _enables_ the key.
  36509. * In addition, if it is a "hard reset", it clears clears any callbacks associated with the onDown and onUp events and removes the onHoldCallback.
  36510. *
  36511. * @method Phaser.Key#reset
  36512. * @param {boolean} [hard=true] - A soft reset won't reset any events or callbacks; a hard reset will.
  36513. */
  36514. reset: function (hard) {
  36515. if (hard === undefined) { hard = true; }
  36516. this.isDown = false;
  36517. this.isUp = true;
  36518. this.timeUp = this.game.time.time;
  36519. this.duration = 0;
  36520. this._enabled = true; // .enabled causes reset(false)
  36521. this._justDown = false;
  36522. this._justUp = false;
  36523. if (hard)
  36524. {
  36525. this.onDown.removeAll();
  36526. this.onUp.removeAll();
  36527. this.onHoldCallback = null;
  36528. this.onHoldContext = null;
  36529. }
  36530. },
  36531. /**
  36532. * Returns `true` if the Key was pressed down within the `duration` value given, or `false` if it either isn't down,
  36533. * or was pressed down longer ago than then given duration.
  36534. *
  36535. * @method Phaser.Key#downDuration
  36536. * @param {number} [duration=50] - The duration within which the key is considered as being just pressed. Given in ms.
  36537. * @return {boolean} True if the key was pressed down within the given duration.
  36538. */
  36539. downDuration: function (duration) {
  36540. if (duration === undefined) { duration = 50; }
  36541. return (this.isDown && this.duration < duration);
  36542. },
  36543. /**
  36544. * Returns `true` if the Key was pressed down within the `duration` value given, or `false` if it either isn't down,
  36545. * or was pressed down longer ago than then given duration.
  36546. *
  36547. * @method Phaser.Key#upDuration
  36548. * @param {number} [duration=50] - The duration within which the key is considered as being just released. Given in ms.
  36549. * @return {boolean} True if the key was released within the given duration.
  36550. */
  36551. upDuration: function (duration) {
  36552. if (duration === undefined) { duration = 50; }
  36553. return (!this.isDown && ((this.game.time.time - this.timeUp) < duration));
  36554. }
  36555. };
  36556. /**
  36557. * The justDown value allows you to test if this Key has just been pressed down or not.
  36558. * When you check this value it will return `true` if the Key is down, otherwise `false`.
  36559. * You can only call justDown once per key press. It will only return `true` once, until the Key is released and pressed down again.
  36560. * This allows you to use it in situations where you want to check if this key is down without using a Signal, such as in a core game loop.
  36561. *
  36562. * @property {boolean} justDown
  36563. * @memberof Phaser.Key
  36564. * @default false
  36565. */
  36566. Object.defineProperty(Phaser.Key.prototype, "justDown", {
  36567. get: function () {
  36568. var current = this._justDown;
  36569. this._justDown = false;
  36570. return current;
  36571. }
  36572. });
  36573. /**
  36574. * The justUp value allows you to test if this Key has just been released or not.
  36575. * When you check this value it will return `true` if the Key is up, otherwise `false`.
  36576. * You can only call justUp once per key release. It will only return `true` once, until the Key is pressed down and released again.
  36577. * This allows you to use it in situations where you want to check if this key is up without using a Signal, such as in a core game loop.
  36578. *
  36579. * @property {boolean} justUp
  36580. * @memberof Phaser.Key
  36581. * @default false
  36582. */
  36583. Object.defineProperty(Phaser.Key.prototype, "justUp", {
  36584. get: function () {
  36585. var current = this._justUp;
  36586. this._justUp = false;
  36587. return current;
  36588. }
  36589. });
  36590. /**
  36591. * An enabled key processes its update and dispatches events.
  36592. * A key can be disabled momentarily at runtime instead of deleting it.
  36593. *
  36594. * @property {boolean} enabled
  36595. * @memberof Phaser.Key
  36596. * @default true
  36597. */
  36598. Object.defineProperty(Phaser.Key.prototype, "enabled", {
  36599. get: function () {
  36600. return this._enabled;
  36601. },
  36602. set: function (value) {
  36603. value = !!value;
  36604. if (value !== this._enabled)
  36605. {
  36606. if (!value)
  36607. {
  36608. this.reset(false);
  36609. }
  36610. this._enabled = value;
  36611. }
  36612. }
  36613. });
  36614. Phaser.Key.prototype.constructor = Phaser.Key;
  36615. /**
  36616. * @author Richard Davey <rich@photonstorm.com>
  36617. * @copyright 2016 Photon Storm Ltd.
  36618. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  36619. */
  36620. /**
  36621. * The Keyboard class monitors keyboard input and dispatches keyboard events.
  36622. *
  36623. * _Note_: many keyboards are unable to process certain combinations of keys due to hardware limitations known as ghosting.
  36624. * See http://www.html5gamedevs.com/topic/4876-impossible-to-use-more-than-2-keyboard-input-buttons-at-the-same-time/ for more details.
  36625. *
  36626. * Also please be aware that certain browser extensions can disable or override Phaser keyboard handling.
  36627. * For example the Chrome extension vimium is known to disable Phaser from using the D key. And there are others.
  36628. * So please check your extensions before opening Phaser issues.
  36629. *
  36630. * @class Phaser.Keyboard
  36631. * @constructor
  36632. * @param {Phaser.Game} game - A reference to the currently running game.
  36633. */
  36634. Phaser.Keyboard = function (game) {
  36635. /**
  36636. * @property {Phaser.Game} game - Local reference to game.
  36637. */
  36638. this.game = game;
  36639. /**
  36640. * Keyboard input will only be processed if enabled.
  36641. * @property {boolean} enabled
  36642. * @default
  36643. */
  36644. this.enabled = true;
  36645. /**
  36646. * @property {object} event - The most recent DOM event from keydown or keyup. This is updated every time a new key is pressed or released.
  36647. */
  36648. this.event = null;
  36649. /**
  36650. * @property {object} pressEvent - The most recent DOM event from keypress.
  36651. */
  36652. this.pressEvent = null;
  36653. /**
  36654. * @property {object} callbackContext - The context under which the callbacks are run.
  36655. */
  36656. this.callbackContext = this;
  36657. /**
  36658. * @property {function} onDownCallback - This callback is invoked every time a key is pressed down, including key repeats when a key is held down.
  36659. */
  36660. this.onDownCallback = null;
  36661. /**
  36662. * @property {function} onPressCallback - This callback is invoked every time a DOM onkeypress event is raised, which is only for printable keys.
  36663. */
  36664. this.onPressCallback = null;
  36665. /**
  36666. * @property {function} onUpCallback - This callback is invoked every time a key is released.
  36667. */
  36668. this.onUpCallback = null;
  36669. /**
  36670. * @property {array<Phaser.Key>} _keys - The array the Phaser.Key objects are stored in.
  36671. * @private
  36672. */
  36673. this._keys = [];
  36674. /**
  36675. * @property {array} _capture - The array the key capture values are stored in.
  36676. * @private
  36677. */
  36678. this._capture = [];
  36679. /**
  36680. * @property {function} _onKeyDown
  36681. * @private
  36682. * @default
  36683. */
  36684. this._onKeyDown = null;
  36685. /**
  36686. * @property {function} _onKeyPress
  36687. * @private
  36688. * @default
  36689. */
  36690. this._onKeyPress = null;
  36691. /**
  36692. * @property {function} _onKeyUp
  36693. * @private
  36694. * @default
  36695. */
  36696. this._onKeyUp = null;
  36697. /**
  36698. * @property {number} _i - Internal cache var
  36699. * @private
  36700. */
  36701. this._i = 0;
  36702. /**
  36703. * @property {number} _k - Internal cache var
  36704. * @private
  36705. */
  36706. this._k = 0;
  36707. };
  36708. Phaser.Keyboard.prototype = {
  36709. /**
  36710. * Add callbacks to the Keyboard handler so that each time a key is pressed down or released the callbacks are activated.
  36711. *
  36712. * @method Phaser.Keyboard#addCallbacks
  36713. * @param {object} context - The context under which the callbacks are run.
  36714. * @param {function} [onDown=null] - This callback is invoked every time a key is pressed down.
  36715. * @param {function} [onUp=null] - This callback is invoked every time a key is released.
  36716. * @param {function} [onPress=null] - This callback is invoked every time the onkeypress event is raised.
  36717. */
  36718. addCallbacks: function (context, onDown, onUp, onPress) {
  36719. this.callbackContext = context;
  36720. if (onDown !== undefined && onDown !== null)
  36721. {
  36722. this.onDownCallback = onDown;
  36723. }
  36724. if (onUp !== undefined && onUp !== null)
  36725. {
  36726. this.onUpCallback = onUp;
  36727. }
  36728. if (onPress !== undefined && onPress !== null)
  36729. {
  36730. this.onPressCallback = onPress;
  36731. }
  36732. },
  36733. /**
  36734. * If you need more fine-grained control over a Key you can create a new Phaser.Key object via this method.
  36735. * The Key object can then be polled, have events attached to it, etc.
  36736. *
  36737. * @method Phaser.Keyboard#addKey
  36738. * @param {integer} keycode - The {@link Phaser.KeyCode keycode} of the key.
  36739. * @return {Phaser.Key} The Key object which you can store locally and reference directly.
  36740. */
  36741. addKey: function (keycode) {
  36742. if (!this._keys[keycode])
  36743. {
  36744. this._keys[keycode] = new Phaser.Key(this.game, keycode);
  36745. this.addKeyCapture(keycode);
  36746. }
  36747. return this._keys[keycode];
  36748. },
  36749. /**
  36750. * A practical way to create an object containing user selected hotkeys.
  36751. *
  36752. * For example,
  36753. *
  36754. * addKeys( { 'up': Phaser.KeyCode.W, 'down': Phaser.KeyCode.S, 'left': Phaser.KeyCode.A, 'right': Phaser.KeyCode.D } );
  36755. *
  36756. * would return an object containing properties (`up`, `down`, `left` and `right`) referring to {@link Phaser.Key} object.
  36757. *
  36758. * @method Phaser.Keyboard#addKeys
  36759. * @param {object} keys - A key mapping object, i.e. `{ 'up': Phaser.KeyCode.W, 'down': Phaser.KeyCode.S }` or `{ 'up': 52, 'down': 53 }`.
  36760. * @return {object} An object containing the properties mapped to {@link Phaser.Key} values.
  36761. */
  36762. addKeys: function (keys) {
  36763. var output = {};
  36764. for (var key in keys)
  36765. {
  36766. output[key] = this.addKey(keys[key]);
  36767. }
  36768. return output;
  36769. },
  36770. /**
  36771. * Removes a Key object from the Keyboard manager.
  36772. *
  36773. * @method Phaser.Keyboard#removeKey
  36774. * @param {integer} keycode - The {@link Phaser.KeyCode keycode} of the key to remove.
  36775. */
  36776. removeKey: function (keycode) {
  36777. if (this._keys[keycode])
  36778. {
  36779. this._keys[keycode] = null;
  36780. this.removeKeyCapture(keycode);
  36781. }
  36782. },
  36783. /**
  36784. * Creates and returns an object containing 4 hotkeys for Up, Down, Left and Right.
  36785. *
  36786. * @method Phaser.Keyboard#createCursorKeys
  36787. * @return {object} An object containing properties: `up`, `down`, `left` and `right` of {@link Phaser.Key} objects.
  36788. */
  36789. createCursorKeys: function () {
  36790. return this.addKeys({ 'up': Phaser.KeyCode.UP, 'down': Phaser.KeyCode.DOWN, 'left': Phaser.KeyCode.LEFT, 'right': Phaser.KeyCode.RIGHT });
  36791. },
  36792. /**
  36793. * Starts the Keyboard event listeners running (keydown and keyup). They are attached to the window.
  36794. * This is called automatically by Phaser.Input and should not normally be invoked directly.
  36795. *
  36796. * @method Phaser.Keyboard#start
  36797. * @protected
  36798. */
  36799. start: function () {
  36800. if (this.game.device.cocoonJS)
  36801. {
  36802. return;
  36803. }
  36804. if (this._onKeyDown !== null)
  36805. {
  36806. // Avoid setting multiple listeners
  36807. return;
  36808. }
  36809. var _this = this;
  36810. this._onKeyDown = function (event) {
  36811. return _this.processKeyDown(event);
  36812. };
  36813. this._onKeyUp = function (event) {
  36814. return _this.processKeyUp(event);
  36815. };
  36816. this._onKeyPress = function (event) {
  36817. return _this.processKeyPress(event);
  36818. };
  36819. window.addEventListener('keydown', this._onKeyDown, false);
  36820. window.addEventListener('keyup', this._onKeyUp, false);
  36821. window.addEventListener('keypress', this._onKeyPress, false);
  36822. },
  36823. /**
  36824. * Stops the Keyboard event listeners from running (keydown, keyup and keypress). They are removed from the window.
  36825. *
  36826. * @method Phaser.Keyboard#stop
  36827. */
  36828. stop: function () {
  36829. window.removeEventListener('keydown', this._onKeyDown);
  36830. window.removeEventListener('keyup', this._onKeyUp);
  36831. window.removeEventListener('keypress', this._onKeyPress);
  36832. this._onKeyDown = null;
  36833. this._onKeyUp = null;
  36834. this._onKeyPress = null;
  36835. },
  36836. /**
  36837. * Stops the Keyboard event listeners from running (keydown and keyup). They are removed from the window.
  36838. * Also clears all key captures and currently created Key objects.
  36839. *
  36840. * @method Phaser.Keyboard#destroy
  36841. */
  36842. destroy: function () {
  36843. this.stop();
  36844. this.clearCaptures();
  36845. this._keys.length = 0;
  36846. this._i = 0;
  36847. },
  36848. /**
  36849. * By default when a key is pressed Phaser will not stop the event from propagating up to the browser.
  36850. * There are some keys this can be annoying for, like the arrow keys or space bar, which make the browser window scroll.
  36851. *
  36852. * The `addKeyCapture` method enables consuming keyboard event for specific keys so it doesn't bubble up to the the browser
  36853. * and cause the default browser behavior.
  36854. *
  36855. * Pass in either a single keycode or an array/hash of keycodes.
  36856. *
  36857. * @method Phaser.Keyboard#addKeyCapture
  36858. * @param {integer|integer[]|object} keycode - Either a single {@link Phaser.KeyCode keycode} or an array/hash of keycodes such as `[65, 67, 68]`.
  36859. */
  36860. addKeyCapture: function (keycode) {
  36861. if (typeof keycode === 'object')
  36862. {
  36863. for (var key in keycode)
  36864. {
  36865. this._capture[keycode[key]] = true;
  36866. }
  36867. }
  36868. else
  36869. {
  36870. this._capture[keycode] = true;
  36871. }
  36872. },
  36873. /**
  36874. * Removes an existing key capture.
  36875. *
  36876. * @method Phaser.Keyboard#removeKeyCapture
  36877. * @param {integer} keycode - The {@link Phaser.KeyCode keycode} to remove capturing of.
  36878. */
  36879. removeKeyCapture: function (keycode) {
  36880. delete this._capture[keycode];
  36881. },
  36882. /**
  36883. * Clear all set key captures.
  36884. *
  36885. * @method Phaser.Keyboard#clearCaptures
  36886. */
  36887. clearCaptures: function () {
  36888. this._capture = {};
  36889. },
  36890. /**
  36891. * Updates all currently defined keys.
  36892. *
  36893. * @method Phaser.Keyboard#update
  36894. */
  36895. update: function () {
  36896. this._i = this._keys.length;
  36897. while (this._i--)
  36898. {
  36899. if (this._keys[this._i])
  36900. {
  36901. this._keys[this._i].update();
  36902. }
  36903. }
  36904. },
  36905. /**
  36906. * Process the keydown event.
  36907. *
  36908. * @method Phaser.Keyboard#processKeyDown
  36909. * @param {KeyboardEvent} event
  36910. * @protected
  36911. */
  36912. processKeyDown: function (event) {
  36913. this.event = event;
  36914. if (!this.game.input.enabled || !this.enabled)
  36915. {
  36916. return;
  36917. }
  36918. var key = event.keyCode;
  36919. // The event is being captured but another hotkey may need it
  36920. if (this._capture[key])
  36921. {
  36922. event.preventDefault();
  36923. }
  36924. if (!this._keys[key])
  36925. {
  36926. this._keys[key] = new Phaser.Key(this.game, key);
  36927. }
  36928. this._keys[key].processKeyDown(event);
  36929. this._k = key;
  36930. if (this.onDownCallback)
  36931. {
  36932. this.onDownCallback.call(this.callbackContext, event);
  36933. }
  36934. },
  36935. /**
  36936. * Process the keypress event.
  36937. *
  36938. * @method Phaser.Keyboard#processKeyPress
  36939. * @param {KeyboardEvent} event
  36940. * @protected
  36941. */
  36942. processKeyPress: function (event) {
  36943. this.pressEvent = event;
  36944. if (!this.game.input.enabled || !this.enabled)
  36945. {
  36946. return;
  36947. }
  36948. if (this.onPressCallback)
  36949. {
  36950. this.onPressCallback.call(this.callbackContext, String.fromCharCode(event.charCode), event);
  36951. }
  36952. },
  36953. /**
  36954. * Process the keyup event.
  36955. *
  36956. * @method Phaser.Keyboard#processKeyUp
  36957. * @param {KeyboardEvent} event
  36958. * @protected
  36959. */
  36960. processKeyUp: function (event) {
  36961. this.event = event;
  36962. if (!this.game.input.enabled || !this.enabled)
  36963. {
  36964. return;
  36965. }
  36966. var key = event.keyCode;
  36967. if (this._capture[key])
  36968. {
  36969. event.preventDefault();
  36970. }
  36971. if (!this._keys[key])
  36972. {
  36973. this._keys[key] = new Phaser.Key(this.game, key);
  36974. }
  36975. this._keys[key].processKeyUp(event);
  36976. if (this.onUpCallback)
  36977. {
  36978. this.onUpCallback.call(this.callbackContext, event);
  36979. }
  36980. },
  36981. /**
  36982. * Resets all Keys.
  36983. *
  36984. * @method Phaser.Keyboard#reset
  36985. * @param {boolean} [hard=true] - A soft reset won't reset any events or callbacks that are bound to the Keys. A hard reset will.
  36986. */
  36987. reset: function (hard) {
  36988. if (hard === undefined) { hard = true; }
  36989. this.event = null;
  36990. var i = this._keys.length;
  36991. while (i--)
  36992. {
  36993. if (this._keys[i])
  36994. {
  36995. this._keys[i].reset(hard);
  36996. }
  36997. }
  36998. },
  36999. /**
  37000. * Returns `true` if the Key was pressed down within the `duration` value given, or `false` if it either isn't down,
  37001. * or was pressed down longer ago than then given duration.
  37002. *
  37003. * @method Phaser.Keyboard#downDuration
  37004. * @param {integer} keycode - The {@link Phaser.KeyCode keycode} of the key to check: i.e. Phaser.KeyCode.UP or Phaser.KeyCode.SPACEBAR.
  37005. * @param {number} [duration=50] - The duration within which the key is considered as being just pressed. Given in ms.
  37006. * @return {boolean} True if the key was pressed down within the given duration, false if not or null if the Key wasn't found.
  37007. */
  37008. downDuration: function (keycode, duration) {
  37009. if (this._keys[keycode])
  37010. {
  37011. return this._keys[keycode].downDuration(duration);
  37012. }
  37013. else
  37014. {
  37015. return null;
  37016. }
  37017. },
  37018. /**
  37019. * Returns `true` if the Key was pressed down within the `duration` value given, or `false` if it either isn't down,
  37020. * or was pressed down longer ago than then given duration.
  37021. *
  37022. * @method Phaser.Keyboard#upDuration
  37023. * @param {Phaser.KeyCode|integer} keycode - The keycode of the key to check, i.e. Phaser.KeyCode.UP or Phaser.KeyCode.SPACEBAR.
  37024. * @param {number} [duration=50] - The duration within which the key is considered as being just released. Given in ms.
  37025. * @return {boolean} True if the key was released within the given duration, false if not or null if the Key wasn't found.
  37026. */
  37027. upDuration: function (keycode, duration) {
  37028. if (this._keys[keycode])
  37029. {
  37030. return this._keys[keycode].upDuration(duration);
  37031. }
  37032. else
  37033. {
  37034. return null;
  37035. }
  37036. },
  37037. /**
  37038. * Returns true of the key is currently pressed down. Note that it can only detect key presses on the web browser.
  37039. *
  37040. * @method Phaser.Keyboard#isDown
  37041. * @param {integer} keycode - The {@link Phaser.KeyCode keycode} of the key to check: i.e. Phaser.KeyCode.UP or Phaser.KeyCode.SPACEBAR.
  37042. * @return {boolean} True if the key is currently down, false if not or null if the Key wasn't found.
  37043. */
  37044. isDown: function (keycode) {
  37045. if (this._keys[keycode])
  37046. {
  37047. return this._keys[keycode].isDown;
  37048. }
  37049. else
  37050. {
  37051. return null;
  37052. }
  37053. }
  37054. };
  37055. /**
  37056. * Returns the string value of the most recently pressed key.
  37057. * @name Phaser.Keyboard#lastChar
  37058. * @property {string} lastChar - The string value of the most recently pressed key.
  37059. * @readonly
  37060. */
  37061. Object.defineProperty(Phaser.Keyboard.prototype, "lastChar", {
  37062. get: function () {
  37063. if (this.event.charCode === 32)
  37064. {
  37065. return '';
  37066. }
  37067. else
  37068. {
  37069. return String.fromCharCode(this.pressEvent.charCode);
  37070. }
  37071. }
  37072. });
  37073. /**
  37074. * Returns the most recently pressed Key. This is a Phaser.Key object and it changes every time a key is pressed.
  37075. * @name Phaser.Keyboard#lastKey
  37076. * @property {Phaser.Key} lastKey - The most recently pressed Key.
  37077. * @readonly
  37078. */
  37079. Object.defineProperty(Phaser.Keyboard.prototype, "lastKey", {
  37080. get: function () {
  37081. return this._keys[this._k];
  37082. }
  37083. });
  37084. Phaser.Keyboard.prototype.constructor = Phaser.Keyboard;
  37085. /**
  37086. * A key code represents a physical key on a keyboard.
  37087. *
  37088. * The KeyCode class contains commonly supported keyboard key codes which can be used
  37089. * as keycode`-parameters in several {@link Phaser.Keyboard} and {@link Phaser.Key} methods.
  37090. *
  37091. * _Note_: These values should only be used indirectly, eg. as `Phaser.KeyCode.KEY`.
  37092. * Future versions may replace the actual values, such that they remain compatible with `keycode`-parameters.
  37093. * The current implementation maps to the {@link https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode KeyboardEvent.keyCode} property.
  37094. *
  37095. * _Note_: Use `Phaser.KeyCode.KEY` instead of `Phaser.Keyboard.KEY` to refer to a key code;
  37096. * the latter approach is supported for compatibility.
  37097. *
  37098. * @class Phaser.KeyCode
  37099. */
  37100. Phaser.KeyCode = {
  37101. /** @static */
  37102. A: "A".charCodeAt(0),
  37103. /** @static */
  37104. B: "B".charCodeAt(0),
  37105. /** @static */
  37106. C: "C".charCodeAt(0),
  37107. /** @static */
  37108. D: "D".charCodeAt(0),
  37109. /** @static */
  37110. E: "E".charCodeAt(0),
  37111. /** @static */
  37112. F: "F".charCodeAt(0),
  37113. /** @static */
  37114. G: "G".charCodeAt(0),
  37115. /** @static */
  37116. H: "H".charCodeAt(0),
  37117. /** @static */
  37118. I: "I".charCodeAt(0),
  37119. /** @static */
  37120. J: "J".charCodeAt(0),
  37121. /** @static */
  37122. K: "K".charCodeAt(0),
  37123. /** @static */
  37124. L: "L".charCodeAt(0),
  37125. /** @static */
  37126. M: "M".charCodeAt(0),
  37127. /** @static */
  37128. N: "N".charCodeAt(0),
  37129. /** @static */
  37130. O: "O".charCodeAt(0),
  37131. /** @static */
  37132. P: "P".charCodeAt(0),
  37133. /** @static */
  37134. Q: "Q".charCodeAt(0),
  37135. /** @static */
  37136. R: "R".charCodeAt(0),
  37137. /** @static */
  37138. S: "S".charCodeAt(0),
  37139. /** @static */
  37140. T: "T".charCodeAt(0),
  37141. /** @static */
  37142. U: "U".charCodeAt(0),
  37143. /** @static */
  37144. V: "V".charCodeAt(0),
  37145. /** @static */
  37146. W: "W".charCodeAt(0),
  37147. /** @static */
  37148. X: "X".charCodeAt(0),
  37149. /** @static */
  37150. Y: "Y".charCodeAt(0),
  37151. /** @static */
  37152. Z: "Z".charCodeAt(0),
  37153. /** @static */
  37154. ZERO: "0".charCodeAt(0),
  37155. /** @static */
  37156. ONE: "1".charCodeAt(0),
  37157. /** @static */
  37158. TWO: "2".charCodeAt(0),
  37159. /** @static */
  37160. THREE: "3".charCodeAt(0),
  37161. /** @static */
  37162. FOUR: "4".charCodeAt(0),
  37163. /** @static */
  37164. FIVE: "5".charCodeAt(0),
  37165. /** @static */
  37166. SIX: "6".charCodeAt(0),
  37167. /** @static */
  37168. SEVEN: "7".charCodeAt(0),
  37169. /** @static */
  37170. EIGHT: "8".charCodeAt(0),
  37171. /** @static */
  37172. NINE: "9".charCodeAt(0),
  37173. /** @static */
  37174. NUMPAD_0: 96,
  37175. /** @static */
  37176. NUMPAD_1: 97,
  37177. /** @static */
  37178. NUMPAD_2: 98,
  37179. /** @static */
  37180. NUMPAD_3: 99,
  37181. /** @static */
  37182. NUMPAD_4: 100,
  37183. /** @static */
  37184. NUMPAD_5: 101,
  37185. /** @static */
  37186. NUMPAD_6: 102,
  37187. /** @static */
  37188. NUMPAD_7: 103,
  37189. /** @static */
  37190. NUMPAD_8: 104,
  37191. /** @static */
  37192. NUMPAD_9: 105,
  37193. /** @static */
  37194. NUMPAD_MULTIPLY: 106,
  37195. /** @static */
  37196. NUMPAD_ADD: 107,
  37197. /** @static */
  37198. NUMPAD_ENTER: 108,
  37199. /** @static */
  37200. NUMPAD_SUBTRACT: 109,
  37201. /** @static */
  37202. NUMPAD_DECIMAL: 110,
  37203. /** @static */
  37204. NUMPAD_DIVIDE: 111,
  37205. /** @static */
  37206. F1: 112,
  37207. /** @static */
  37208. F2: 113,
  37209. /** @static */
  37210. F3: 114,
  37211. /** @static */
  37212. F4: 115,
  37213. /** @static */
  37214. F5: 116,
  37215. /** @static */
  37216. F6: 117,
  37217. /** @static */
  37218. F7: 118,
  37219. /** @static */
  37220. F8: 119,
  37221. /** @static */
  37222. F9: 120,
  37223. /** @static */
  37224. F10: 121,
  37225. /** @static */
  37226. F11: 122,
  37227. /** @static */
  37228. F12: 123,
  37229. /** @static */
  37230. F13: 124,
  37231. /** @static */
  37232. F14: 125,
  37233. /** @static */
  37234. F15: 126,
  37235. /** @static */
  37236. COLON: 186,
  37237. /** @static */
  37238. EQUALS: 187,
  37239. /** @static */
  37240. COMMA: 188,
  37241. /** @static */
  37242. UNDERSCORE: 189,
  37243. /** @static */
  37244. PERIOD: 190,
  37245. /** @static */
  37246. QUESTION_MARK: 191,
  37247. /** @static */
  37248. TILDE: 192,
  37249. /** @static */
  37250. OPEN_BRACKET: 219,
  37251. /** @static */
  37252. BACKWARD_SLASH: 220,
  37253. /** @static */
  37254. CLOSED_BRACKET: 221,
  37255. /** @static */
  37256. QUOTES: 222,
  37257. /** @static */
  37258. BACKSPACE: 8,
  37259. /** @static */
  37260. TAB: 9,
  37261. /** @static */
  37262. CLEAR: 12,
  37263. /** @static */
  37264. ENTER: 13,
  37265. /** @static */
  37266. SHIFT: 16,
  37267. /** @static */
  37268. CONTROL: 17,
  37269. /** @static */
  37270. ALT: 18,
  37271. /** @static */
  37272. CAPS_LOCK: 20,
  37273. /** @static */
  37274. ESC: 27,
  37275. /** @static */
  37276. SPACEBAR: 32,
  37277. /** @static */
  37278. PAGE_UP: 33,
  37279. /** @static */
  37280. PAGE_DOWN: 34,
  37281. /** @static */
  37282. END: 35,
  37283. /** @static */
  37284. HOME: 36,
  37285. /** @static */
  37286. LEFT: 37,
  37287. /** @static */
  37288. UP: 38,
  37289. /** @static */
  37290. RIGHT: 39,
  37291. /** @static */
  37292. DOWN: 40,
  37293. /** @static */
  37294. PLUS: 43,
  37295. /** @static */
  37296. MINUS: 44,
  37297. /** @static */
  37298. INSERT: 45,
  37299. /** @static */
  37300. DELETE: 46,
  37301. /** @static */
  37302. HELP: 47,
  37303. /** @static */
  37304. NUM_LOCK: 144
  37305. };
  37306. // Duplicate Phaser.KeyCode values in Phaser.Keyboard for compatibility
  37307. for (var key in Phaser.KeyCode)
  37308. {
  37309. if (Phaser.KeyCode.hasOwnProperty(key) && !key.match(/[a-z]/))
  37310. {
  37311. Phaser.Keyboard[key] = Phaser.KeyCode[key];
  37312. }
  37313. }
  37314. /**
  37315. * @author Richard Davey <rich@photonstorm.com>
  37316. * @copyright 2016 Photon Storm Ltd.
  37317. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  37318. */
  37319. Phaser.Component = function () {};
  37320. /**
  37321. * @author Richard Davey <rich@photonstorm.com>
  37322. * @copyright 2016 Photon Storm Ltd.
  37323. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  37324. */
  37325. /**
  37326. * The Angle Component provides access to an `angle` property; the rotation of a Game Object in degrees.
  37327. *
  37328. * @class
  37329. */
  37330. Phaser.Component.Angle = function () {};
  37331. Phaser.Component.Angle.prototype = {
  37332. /**
  37333. * The angle property is the rotation of the Game Object in *degrees* from its original orientation.
  37334. *
  37335. * Values from 0 to 180 represent clockwise rotation; values from 0 to -180 represent counterclockwise rotation.
  37336. *
  37337. * Values outside this range are added to or subtracted from 360 to obtain a value within the range.
  37338. * For example, the statement player.angle = 450 is the same as player.angle = 90.
  37339. *
  37340. * If you wish to work in radians instead of degrees you can use the property `rotation` instead.
  37341. * Working in radians is slightly faster as it doesn't have to perform any calculations.
  37342. *
  37343. * @property {number} angle
  37344. */
  37345. angle: {
  37346. get: function() {
  37347. return Phaser.Math.wrapAngle(Phaser.Math.radToDeg(this.rotation));
  37348. },
  37349. set: function(value) {
  37350. this.rotation = Phaser.Math.degToRad(Phaser.Math.wrapAngle(value));
  37351. }
  37352. }
  37353. };
  37354. /**
  37355. * @author Richard Davey <rich@photonstorm.com>
  37356. * @copyright 2016 Photon Storm Ltd.
  37357. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  37358. */
  37359. /**
  37360. * The Animation Component provides a `play` method, which is a proxy to the `AnimationManager.play` method.
  37361. *
  37362. * @class
  37363. */
  37364. Phaser.Component.Animation = function () {};
  37365. Phaser.Component.Animation.prototype = {
  37366. /**
  37367. * Plays an Animation.
  37368. *
  37369. * The animation should have previously been created via `animations.add`.
  37370. *
  37371. * If the animation is already playing calling this again won't do anything.
  37372. * If you need to reset an already running animation do so directly on the Animation object itself or via `AnimationManager.stop`.
  37373. *
  37374. * @method
  37375. * @param {string} name - The name of the animation to be played, e.g. "fire", "walk", "jump". Must have been previously created via 'AnimationManager.add'.
  37376. * @param {number} [frameRate=null] - The framerate to play the animation at. The speed is given in frames per second. If not provided the previously set frameRate of the Animation is used.
  37377. * @param {boolean} [loop=false] - Should the animation be looped after playback. If not provided the previously set loop value of the Animation is used.
  37378. * @param {boolean} [killOnComplete=false] - If set to true when the animation completes (only happens if loop=false) the parent Sprite will be killed.
  37379. * @return {Phaser.Animation} A reference to playing Animation.
  37380. */
  37381. play: function (name, frameRate, loop, killOnComplete) {
  37382. if (this.animations)
  37383. {
  37384. return this.animations.play(name, frameRate, loop, killOnComplete);
  37385. }
  37386. }
  37387. };
  37388. /**
  37389. * @author Richard Davey <rich@photonstorm.com>
  37390. * @copyright 2016 Photon Storm Ltd.
  37391. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  37392. */
  37393. /**
  37394. * The AutoCull Component is responsible for providing methods that check if a Game Object is within the bounds of the World Camera.
  37395. * It is used by the InWorld component.
  37396. *
  37397. * @class
  37398. */
  37399. Phaser.Component.AutoCull = function () {};
  37400. Phaser.Component.AutoCull.prototype = {
  37401. /**
  37402. * A Game Object with `autoCull` set to true will check its bounds against the World Camera every frame.
  37403. * If it is not intersecting the Camera bounds at any point then it has its `renderable` property set to `false`.
  37404. * This keeps the Game Object alive and still processing updates, but forces it to skip the render step entirely.
  37405. *
  37406. * This is a relatively expensive operation, especially if enabled on hundreds of Game Objects. So enable it only if you know it's required,
  37407. * or you have tested performance and find it acceptable.
  37408. *
  37409. * @property {boolean} autoCull
  37410. * @default
  37411. */
  37412. autoCull: false,
  37413. /**
  37414. * Checks if the Game Objects bounds intersect with the Game Camera bounds.
  37415. * Returns `true` if they do, otherwise `false` if fully outside of the Cameras bounds.
  37416. *
  37417. * @property {boolean} inCamera
  37418. * @readonly
  37419. */
  37420. inCamera: {
  37421. get: function() {
  37422. if (!this.autoCull && !this.checkWorldBounds)
  37423. {
  37424. this._bounds.copyFrom(this.getBounds());
  37425. this._bounds.x += this.game.camera.view.x;
  37426. this._bounds.y += this.game.camera.view.y;
  37427. }
  37428. return this.game.world.camera.view.intersects(this._bounds);
  37429. }
  37430. }
  37431. };
  37432. /**
  37433. * @author Richard Davey <rich@photonstorm.com>
  37434. * @copyright 2016 Photon Storm Ltd.
  37435. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  37436. */
  37437. /**
  37438. * The Bounds component contains properties related to the bounds of the Game Object.
  37439. *
  37440. * @class
  37441. */
  37442. Phaser.Component.Bounds = function () {};
  37443. Phaser.Component.Bounds.prototype = {
  37444. /**
  37445. * The amount the Game Object is visually offset from its x coordinate.
  37446. * This is the same as `width * anchor.x`.
  37447. * It will only be > 0 if anchor.x is not equal to zero.
  37448. *
  37449. * @property {number} offsetX
  37450. * @readOnly
  37451. */
  37452. offsetX: {
  37453. get: function () {
  37454. return this.anchor.x * this.width;
  37455. }
  37456. },
  37457. /**
  37458. * The amount the Game Object is visually offset from its y coordinate.
  37459. * This is the same as `height * anchor.y`.
  37460. * It will only be > 0 if anchor.y is not equal to zero.
  37461. *
  37462. * @property {number} offsetY
  37463. * @readOnly
  37464. */
  37465. offsetY: {
  37466. get: function () {
  37467. return this.anchor.y * this.height;
  37468. }
  37469. },
  37470. /**
  37471. * The center x coordinate of the Game Object.
  37472. * This is the same as `(x - offsetX) + (width / 2)`.
  37473. *
  37474. * @property {number} centerX
  37475. */
  37476. centerX: {
  37477. get: function () {
  37478. return (this.x - this.offsetX) + (this.width * 0.5);
  37479. },
  37480. set: function (value) {
  37481. this.x = (value + this.offsetX) - (this.width * 0.5);
  37482. }
  37483. },
  37484. /**
  37485. * The center y coordinate of the Game Object.
  37486. * This is the same as `(y - offsetY) + (height / 2)`.
  37487. *
  37488. * @property {number} centerY
  37489. */
  37490. centerY: {
  37491. get: function () {
  37492. return (this.y - this.offsetY) + (this.height * 0.5);
  37493. },
  37494. set: function (value) {
  37495. this.y = (value + this.offsetY) - (this.height * 0.5);
  37496. }
  37497. },
  37498. /**
  37499. * The left coordinate of the Game Object.
  37500. * This is the same as `x - offsetX`.
  37501. *
  37502. * @property {number} left
  37503. */
  37504. left: {
  37505. get: function () {
  37506. return this.x - this.offsetX;
  37507. },
  37508. set: function (value) {
  37509. this.x = value + this.offsetX;
  37510. }
  37511. },
  37512. /**
  37513. * The right coordinate of the Game Object.
  37514. * This is the same as `x + width - offsetX`.
  37515. *
  37516. * @property {number} right
  37517. */
  37518. right: {
  37519. get: function () {
  37520. return (this.x + this.width) - this.offsetX;
  37521. },
  37522. set: function (value) {
  37523. this.x = value - (this.width) + this.offsetX;
  37524. }
  37525. },
  37526. /**
  37527. * The y coordinate of the Game Object.
  37528. * This is the same as `y - offsetY`.
  37529. *
  37530. * @property {number} top
  37531. */
  37532. top: {
  37533. get: function () {
  37534. return this.y - this.offsetY;
  37535. },
  37536. set: function (value) {
  37537. this.y = value + this.offsetY;
  37538. }
  37539. },
  37540. /**
  37541. * The sum of the y and height properties.
  37542. * This is the same as `y + height - offsetY`.
  37543. *
  37544. * @property {number} bottom
  37545. */
  37546. bottom: {
  37547. get: function () {
  37548. return (this.y + this.height) - this.offsetY;
  37549. },
  37550. set: function (value) {
  37551. this.y = value - (this.height) + this.offsetY;
  37552. }
  37553. },
  37554. /**
  37555. * Aligns this Game Object within another Game Object, or Rectangle, known as the
  37556. * 'container', to one of 9 possible positions.
  37557. *
  37558. * The container must be a Game Object, or Phaser.Rectangle object. This can include properties
  37559. * such as `World.bounds` or `Camera.view`, for aligning Game Objects within the world
  37560. * and camera bounds. Or it can include other Sprites, Images, Text objects, BitmapText,
  37561. * TileSprites or Buttons.
  37562. *
  37563. * Please note that aligning a Sprite to another Game Object does **not** make it a child of
  37564. * the container. It simply modifies its position coordinates so it aligns with it.
  37565. *
  37566. * The position constants you can use are:
  37567. *
  37568. * `Phaser.TOP_LEFT`, `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_CENTER`,
  37569. * `Phaser.CENTER`, `Phaser.RIGHT_CENTER`, `Phaser.BOTTOM_LEFT`,
  37570. * `Phaser.BOTTOM_CENTER` and `Phaser.BOTTOM_RIGHT`.
  37571. *
  37572. * The Game Objects are placed in such a way that their _bounds_ align with the
  37573. * container, taking into consideration rotation, scale and the anchor property.
  37574. * This allows you to neatly align Game Objects, irrespective of their position value.
  37575. *
  37576. * The optional `offsetX` and `offsetY` arguments allow you to apply extra spacing to the final
  37577. * aligned position of the Game Object. For example:
  37578. *
  37579. * `sprite.alignIn(background, Phaser.BOTTOM_RIGHT, -20, -20)`
  37580. *
  37581. * Would align the `sprite` to the bottom-right, but moved 20 pixels in from the corner.
  37582. * Think of the offsets as applying an adjustment to the containers bounds before the alignment takes place.
  37583. * So providing a negative offset will 'shrink' the container bounds by that amount, and providing a positive
  37584. * one expands it.
  37585. *
  37586. * @method
  37587. * @param {Phaser.Rectangle|Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapText|Phaser.Button|Phaser.Graphics|Phaser.TileSprite} container - The Game Object or Rectangle with which to align this Game Object to. Can also include properties such as `World.bounds` or `Camera.view`.
  37588. * @param {integer} [position] - The position constant. One of `Phaser.TOP_LEFT` (default), `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_CENTER`, `Phaser.CENTER`, `Phaser.RIGHT_CENTER`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` or `Phaser.BOTTOM_RIGHT`.
  37589. * @param {integer} [offsetX=0] - A horizontal adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it.
  37590. * @param {integer} [offsetY=0] - A vertical adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it.
  37591. * @return {Object} This Game Object.
  37592. */
  37593. alignIn: function (container, position, offsetX, offsetY) {
  37594. if (offsetX === undefined) { offsetX = 0; }
  37595. if (offsetY === undefined) { offsetY = 0; }
  37596. switch (position)
  37597. {
  37598. default:
  37599. case Phaser.TOP_LEFT:
  37600. this.left = container.left - offsetX;
  37601. this.top = container.top - offsetY;
  37602. break;
  37603. case Phaser.TOP_CENTER:
  37604. this.centerX = container.centerX + offsetX;
  37605. this.top = container.top - offsetY;
  37606. break;
  37607. case Phaser.TOP_RIGHT:
  37608. this.right = container.right + offsetX;
  37609. this.top = container.top - offsetY;
  37610. break;
  37611. case Phaser.LEFT_CENTER:
  37612. this.left = container.left - offsetX;
  37613. this.centerY = container.centerY + offsetY;
  37614. break;
  37615. case Phaser.CENTER:
  37616. this.centerX = container.centerX + offsetX;
  37617. this.centerY = container.centerY + offsetY;
  37618. break;
  37619. case Phaser.RIGHT_CENTER:
  37620. this.right = container.right + offsetX;
  37621. this.centerY = container.centerY + offsetY;
  37622. break;
  37623. case Phaser.BOTTOM_LEFT:
  37624. this.left = container.left - offsetX;
  37625. this.bottom = container.bottom + offsetY;
  37626. break;
  37627. case Phaser.BOTTOM_CENTER:
  37628. this.centerX = container.centerX + offsetX;
  37629. this.bottom = container.bottom + offsetY;
  37630. break;
  37631. case Phaser.BOTTOM_RIGHT:
  37632. this.right = container.right + offsetX;
  37633. this.bottom = container.bottom + offsetY;
  37634. break;
  37635. }
  37636. return this;
  37637. },
  37638. /**
  37639. * Aligns this Game Object to the side of another Game Object, or Rectangle, known as the
  37640. * 'parent', in one of 11 possible positions.
  37641. *
  37642. * The parent must be a Game Object, or Phaser.Rectangle object. This can include properties
  37643. * such as `World.bounds` or `Camera.view`, for aligning Game Objects within the world
  37644. * and camera bounds. Or it can include other Sprites, Images, Text objects, BitmapText,
  37645. * TileSprites or Buttons.
  37646. *
  37647. * Please note that aligning a Sprite to another Game Object does **not** make it a child of
  37648. * the parent. It simply modifies its position coordinates so it aligns with it.
  37649. *
  37650. * The position constants you can use are:
  37651. *
  37652. * `Phaser.TOP_LEFT` (default), `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_TOP`,
  37653. * `Phaser.LEFT_CENTER`, `Phaser.LEFT_BOTTOM`, `Phaser.RIGHT_TOP`, `Phaser.RIGHT_CENTER`,
  37654. * `Phaser.RIGHT_BOTTOM`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER`
  37655. * and `Phaser.BOTTOM_RIGHT`.
  37656. *
  37657. * The Game Objects are placed in such a way that their _bounds_ align with the
  37658. * parent, taking into consideration rotation, scale and the anchor property.
  37659. * This allows you to neatly align Game Objects, irrespective of their position value.
  37660. *
  37661. * The optional `offsetX` and `offsetY` arguments allow you to apply extra spacing to the final
  37662. * aligned position of the Game Object. For example:
  37663. *
  37664. * `sprite.alignTo(background, Phaser.BOTTOM_RIGHT, -20, -20)`
  37665. *
  37666. * Would align the `sprite` to the bottom-right, but moved 20 pixels in from the corner.
  37667. * Think of the offsets as applying an adjustment to the parents bounds before the alignment takes place.
  37668. * So providing a negative offset will 'shrink' the parent bounds by that amount, and providing a positive
  37669. * one expands it.
  37670. *
  37671. * @method
  37672. * @param {Phaser.Rectangle|Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapText|Phaser.Button|Phaser.Graphics|Phaser.TileSprite} parent - The Game Object or Rectangle with which to align this Game Object to. Can also include properties such as `World.bounds` or `Camera.view`.
  37673. * @param {integer} [position] - The position constant. One of `Phaser.TOP_LEFT`, `Phaser.TOP_CENTER`, `Phaser.TOP_RIGHT`, `Phaser.LEFT_TOP`, `Phaser.LEFT_CENTER`, `Phaser.LEFT_BOTTOM`, `Phaser.RIGHT_TOP`, `Phaser.RIGHT_CENTER`, `Phaser.RIGHT_BOTTOM`, `Phaser.BOTTOM_LEFT`, `Phaser.BOTTOM_CENTER` or `Phaser.BOTTOM_RIGHT`.
  37674. * @param {integer} [offsetX=0] - A horizontal adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it.
  37675. * @param {integer} [offsetY=0] - A vertical adjustment of the Containers bounds, applied to the aligned position of the Game Object. Use a negative value to shrink the bounds, positive to increase it.
  37676. * @return {Object} This Game Object.
  37677. */
  37678. alignTo: function (parent, position, offsetX, offsetY) {
  37679. if (offsetX === undefined) { offsetX = 0; }
  37680. if (offsetY === undefined) { offsetY = 0; }
  37681. switch (position)
  37682. {
  37683. default:
  37684. case Phaser.TOP_LEFT:
  37685. this.left = parent.left - offsetX;
  37686. this.bottom = parent.top - offsetY;
  37687. break;
  37688. case Phaser.TOP_CENTER:
  37689. this.centerX = parent.centerX + offsetX;
  37690. this.bottom = parent.top - offsetY;
  37691. break;
  37692. case Phaser.TOP_RIGHT:
  37693. this.right = parent.right + offsetX;
  37694. this.bottom = parent.top - offsetY;
  37695. break;
  37696. case Phaser.LEFT_TOP:
  37697. this.right = parent.left - offsetX;
  37698. this.top = parent.top - offsetY;
  37699. break;
  37700. case Phaser.LEFT_CENTER:
  37701. this.right = parent.left - offsetX;
  37702. this.centerY = parent.centerY + offsetY;
  37703. break;
  37704. case Phaser.LEFT_BOTTOM:
  37705. this.right = parent.left - offsetX;
  37706. this.bottom = parent.bottom + offsetY;
  37707. break;
  37708. case Phaser.RIGHT_TOP:
  37709. this.left = parent.right + offsetX;
  37710. this.top = parent.top - offsetY;
  37711. break;
  37712. case Phaser.RIGHT_CENTER:
  37713. this.left = parent.right + offsetX;
  37714. this.centerY = parent.centerY + offsetY;
  37715. break;
  37716. case Phaser.RIGHT_BOTTOM:
  37717. this.left = parent.right + offsetX;
  37718. this.bottom = parent.bottom + offsetY;
  37719. break;
  37720. case Phaser.BOTTOM_LEFT:
  37721. this.left = parent.left - offsetX;
  37722. this.top = parent.bottom + offsetY;
  37723. break;
  37724. case Phaser.BOTTOM_CENTER:
  37725. this.centerX = parent.centerX + offsetX;
  37726. this.top = parent.bottom + offsetY;
  37727. break;
  37728. case Phaser.BOTTOM_RIGHT:
  37729. this.right = parent.right + offsetX;
  37730. this.top = parent.bottom + offsetY;
  37731. break;
  37732. }
  37733. return this;
  37734. }
  37735. };
  37736. // Phaser.Group extensions
  37737. Phaser.Group.prototype.alignIn = Phaser.Component.Bounds.prototype.alignIn;
  37738. Phaser.Group.prototype.alignTo = Phaser.Component.Bounds.prototype.alignTo;
  37739. /**
  37740. * @author Richard Davey <rich@photonstorm.com>
  37741. * @copyright 2016 Photon Storm Ltd.
  37742. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  37743. */
  37744. /**
  37745. * The BringToTop Component features quick access to Group sorting related methods.
  37746. *
  37747. * @class
  37748. */
  37749. Phaser.Component.BringToTop = function () {};
  37750. /**
  37751. * Brings this Game Object to the top of its parents display list.
  37752. * Visually this means it will render over the top of any old child in the same Group.
  37753. *
  37754. * If this Game Object hasn't been added to a custom Group then this method will bring it to the top of the Game World,
  37755. * because the World is the root Group from which all Game Objects descend.
  37756. *
  37757. * @method
  37758. * @return {PIXI.DisplayObject} This instance.
  37759. */
  37760. Phaser.Component.BringToTop.prototype.bringToTop = function() {
  37761. if (this.parent)
  37762. {
  37763. this.parent.bringToTop(this);
  37764. }
  37765. return this;
  37766. };
  37767. /**
  37768. * Sends this Game Object to the bottom of its parents display list.
  37769. * Visually this means it will render below all other children in the same Group.
  37770. *
  37771. * If this Game Object hasn't been added to a custom Group then this method will send it to the bottom of the Game World,
  37772. * because the World is the root Group from which all Game Objects descend.
  37773. *
  37774. * @method
  37775. * @return {PIXI.DisplayObject} This instance.
  37776. */
  37777. Phaser.Component.BringToTop.prototype.sendToBack = function() {
  37778. if (this.parent)
  37779. {
  37780. this.parent.sendToBack(this);
  37781. }
  37782. return this;
  37783. };
  37784. /**
  37785. * Moves this Game Object up one place in its parents display list.
  37786. * This call has no effect if the Game Object is already at the top of the display list.
  37787. *
  37788. * If this Game Object hasn't been added to a custom Group then this method will move it one object up within the Game World,
  37789. * because the World is the root Group from which all Game Objects descend.
  37790. *
  37791. * @method
  37792. * @return {PIXI.DisplayObject} This instance.
  37793. */
  37794. Phaser.Component.BringToTop.prototype.moveUp = function () {
  37795. if (this.parent)
  37796. {
  37797. this.parent.moveUp(this);
  37798. }
  37799. return this;
  37800. };
  37801. /**
  37802. * Moves this Game Object down one place in its parents display list.
  37803. * This call has no effect if the Game Object is already at the bottom of the display list.
  37804. *
  37805. * If this Game Object hasn't been added to a custom Group then this method will move it one object down within the Game World,
  37806. * because the World is the root Group from which all Game Objects descend.
  37807. *
  37808. * @method
  37809. * @return {PIXI.DisplayObject} This instance.
  37810. */
  37811. Phaser.Component.BringToTop.prototype.moveDown = function () {
  37812. if (this.parent)
  37813. {
  37814. this.parent.moveDown(this);
  37815. }
  37816. return this;
  37817. };
  37818. /**
  37819. * @author Richard Davey <rich@photonstorm.com>
  37820. * @copyright 2016 Photon Storm Ltd.
  37821. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  37822. */
  37823. /**
  37824. * Core Component Features.
  37825. *
  37826. * @class
  37827. */
  37828. Phaser.Component.Core = function () {};
  37829. /**
  37830. * Installs / registers mixin components.
  37831. *
  37832. * The `this` context should be that of the applicable object instance or prototype.
  37833. *
  37834. * @method
  37835. * @protected
  37836. */
  37837. Phaser.Component.Core.install = function (components) {
  37838. // Always install 'Core' first
  37839. Phaser.Utils.mixinPrototype(this, Phaser.Component.Core.prototype);
  37840. this.components = {};
  37841. for (var i = 0; i < components.length; i++)
  37842. {
  37843. var id = components[i];
  37844. var replace = false;
  37845. if (id === 'Destroy')
  37846. {
  37847. replace = true;
  37848. }
  37849. Phaser.Utils.mixinPrototype(this, Phaser.Component[id].prototype, replace);
  37850. this.components[id] = true;
  37851. }
  37852. };
  37853. /**
  37854. * Initializes the mixin components.
  37855. *
  37856. * The `this` context should be an instance of the component mixin target.
  37857. *
  37858. * @method
  37859. * @protected
  37860. */
  37861. Phaser.Component.Core.init = function (game, x, y, key, frame) {
  37862. this.game = game;
  37863. this.key = key;
  37864. this.data = {};
  37865. this.position.set(x, y);
  37866. this.world = new Phaser.Point(x, y);
  37867. this.previousPosition = new Phaser.Point(x, y);
  37868. this.events = new Phaser.Events(this);
  37869. this._bounds = new Phaser.Rectangle();
  37870. if (this.components.PhysicsBody)
  37871. {
  37872. // Enable-body checks for hasOwnProperty; makes sure to lift property from prototype.
  37873. this.body = this.body;
  37874. }
  37875. if (this.components.Animation)
  37876. {
  37877. this.animations = new Phaser.AnimationManager(this);
  37878. }
  37879. if (this.components.LoadTexture && key !== null)
  37880. {
  37881. this.loadTexture(key, frame);
  37882. }
  37883. if (this.components.FixedToCamera)
  37884. {
  37885. this.cameraOffset = new Phaser.Point(x, y);
  37886. }
  37887. };
  37888. Phaser.Component.Core.preUpdate = function () {
  37889. if (this.pendingDestroy)
  37890. {
  37891. this.destroy();
  37892. return;
  37893. }
  37894. this.previousPosition.set(this.world.x, this.world.y);
  37895. this.previousRotation = this.rotation;
  37896. if (!this.exists || !this.parent.exists)
  37897. {
  37898. this.renderOrderID = -1;
  37899. return false;
  37900. }
  37901. this.world.setTo(this.game.camera.x + this.worldTransform.tx, this.game.camera.y + this.worldTransform.ty);
  37902. if (this.visible)
  37903. {
  37904. this.renderOrderID = this.game.stage.currentRenderOrderID++;
  37905. }
  37906. if (this.animations)
  37907. {
  37908. this.animations.update();
  37909. }
  37910. if (this.body)
  37911. {
  37912. this.body.preUpdate();
  37913. }
  37914. for (var i = 0; i < this.children.length; i++)
  37915. {
  37916. this.children[i].preUpdate();
  37917. }
  37918. return true;
  37919. };
  37920. Phaser.Component.Core.prototype = {
  37921. /**
  37922. * A reference to the currently running Game.
  37923. * @property {Phaser.Game} game
  37924. */
  37925. game: null,
  37926. /**
  37927. * A user defined name given to this Game Object.
  37928. * This value isn't ever used internally by Phaser, it is meant as a game level property.
  37929. * @property {string} name
  37930. * @default
  37931. */
  37932. name: '',
  37933. /**
  37934. * An empty Object that belongs to this Game Object.
  37935. * This value isn't ever used internally by Phaser, but may be used by your own code, or
  37936. * by Phaser Plugins, to store data that needs to be associated with the Game Object,
  37937. * without polluting the Game Object directly.
  37938. * @property {Object} data
  37939. * @default
  37940. */
  37941. data: {},
  37942. /**
  37943. * The components this Game Object has installed.
  37944. * @property {object} components
  37945. * @protected
  37946. */
  37947. components: {},
  37948. /**
  37949. * The z depth of this Game Object within its parent Group.
  37950. * No two objects in a Group can have the same z value.
  37951. * This value is adjusted automatically whenever the Group hierarchy changes.
  37952. * If you wish to re-order the layering of a Game Object then see methods like Group.moveUp or Group.bringToTop.
  37953. * @property {number} z
  37954. * @readOnly
  37955. */
  37956. z: 0,
  37957. /**
  37958. * All Phaser Game Objects have an Events class which contains all of the events that are dispatched when certain things happen to this
  37959. * Game Object, or any of its components.
  37960. * @see Phaser.Events
  37961. * @property {Phaser.Events} events
  37962. */
  37963. events: undefined,
  37964. /**
  37965. * If the Game Object is enabled for animation (such as a Phaser.Sprite) this is a reference to its AnimationManager instance.
  37966. * Through it you can create, play, pause and stop animations.
  37967. * @see Phaser.AnimationManager
  37968. * @property {Phaser.AnimationManager} animations
  37969. */
  37970. animations: undefined,
  37971. /**
  37972. * The key of the image or texture used by this Game Object during rendering.
  37973. * If it is a string it's the string used to retrieve the texture from the Phaser Image Cache.
  37974. * It can also be an instance of a RenderTexture, BitmapData, Video or PIXI.Texture.
  37975. * If a Game Object is created without a key it is automatically assigned the key `__default` which is a 32x32 transparent PNG stored within the Cache.
  37976. * If a Game Object is given a key which doesn't exist in the Image Cache it is re-assigned the key `__missing` which is a 32x32 PNG of a green box with a line through it.
  37977. * @property {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|PIXI.Texture} key
  37978. */
  37979. key: '',
  37980. /**
  37981. * The world coordinates of this Game Object in pixels.
  37982. * Depending on where in the display list this Game Object is placed this value can differ from `position`,
  37983. * which contains the x/y coordinates relative to the Game Objects parent.
  37984. * @property {Phaser.Point} world
  37985. */
  37986. world: null,
  37987. /**
  37988. * A debug flag designed for use with `Game.enableStep`.
  37989. * @property {boolean} debug
  37990. * @default
  37991. */
  37992. debug: false,
  37993. /**
  37994. * The position the Game Object was located in the previous frame.
  37995. * @property {Phaser.Point} previousPosition
  37996. * @readOnly
  37997. */
  37998. previousPosition: null,
  37999. /**
  38000. * The rotation the Game Object was in set to in the previous frame. Value is in radians.
  38001. * @property {number} previousRotation
  38002. * @readOnly
  38003. */
  38004. previousRotation: 0,
  38005. /**
  38006. * The render order ID is used internally by the renderer and Input Manager and should not be modified.
  38007. * This property is mostly used internally by the renderers, but is exposed for the use of plugins.
  38008. * @property {number} renderOrderID
  38009. * @readOnly
  38010. */
  38011. renderOrderID: 0,
  38012. /**
  38013. * A Game Object is considered `fresh` if it has just been created or reset and is yet to receive a renderer transform update.
  38014. * This property is mostly used internally by the physics systems, but is exposed for the use of plugins.
  38015. * @property {boolean} fresh
  38016. * @readOnly
  38017. */
  38018. fresh: true,
  38019. /**
  38020. * A Game Object is that is pendingDestroy is flagged to have its destroy method called on the next logic update.
  38021. * You can set it directly to allow you to flag an object to be destroyed on its next update.
  38022. *
  38023. * This is extremely useful if you wish to destroy an object from within one of its own callbacks
  38024. * such as with Buttons or other Input events.
  38025. *
  38026. * @property {boolean} pendingDestroy
  38027. */
  38028. pendingDestroy: false,
  38029. /**
  38030. * @property {Phaser.Rectangle} _bounds - Internal cache var.
  38031. * @private
  38032. */
  38033. _bounds: null,
  38034. /**
  38035. * @property {boolean} _exists - Internal cache var.
  38036. * @private
  38037. */
  38038. _exists: true,
  38039. /**
  38040. * Controls if this Game Object is processed by the core game loop.
  38041. * If this Game Object has a physics body it also controls if its physics body is updated or not.
  38042. * When `exists` is set to `false` it will remove its physics body from the physics world if it has one.
  38043. * It also toggles the `visible` property to false as well.
  38044. *
  38045. * Setting `exists` to true will add its physics body back in to the physics world, if it has one.
  38046. * It will also set the `visible` property to `true`.
  38047. *
  38048. * @property {boolean} exists
  38049. */
  38050. exists: {
  38051. get: function () {
  38052. return this._exists;
  38053. },
  38054. set: function (value) {
  38055. if (value)
  38056. {
  38057. this._exists = true;
  38058. if (this.body && this.body.type === Phaser.Physics.P2JS)
  38059. {
  38060. this.body.addToWorld();
  38061. }
  38062. this.visible = true;
  38063. }
  38064. else
  38065. {
  38066. this._exists = false;
  38067. if (this.body && this.body.type === Phaser.Physics.P2JS)
  38068. {
  38069. this.body.removeFromWorld();
  38070. }
  38071. this.visible = false;
  38072. }
  38073. }
  38074. },
  38075. /**
  38076. * Override this method in your own custom objects to handle any update requirements.
  38077. * It is called immediately after `preUpdate` and before `postUpdate`.
  38078. * Remember if this Game Object has any children you should call update on those too.
  38079. *
  38080. * @method
  38081. */
  38082. update: function() {
  38083. },
  38084. /**
  38085. * Internal method called by the World postUpdate cycle.
  38086. *
  38087. * @method
  38088. * @protected
  38089. */
  38090. postUpdate: function() {
  38091. if (this.customRender)
  38092. {
  38093. this.key.render();
  38094. }
  38095. if (this.components.PhysicsBody)
  38096. {
  38097. Phaser.Component.PhysicsBody.postUpdate.call(this);
  38098. }
  38099. if (this.components.FixedToCamera)
  38100. {
  38101. Phaser.Component.FixedToCamera.postUpdate.call(this);
  38102. }
  38103. for (var i = 0; i < this.children.length; i++)
  38104. {
  38105. this.children[i].postUpdate();
  38106. }
  38107. }
  38108. };
  38109. /**
  38110. * @author Richard Davey <rich@photonstorm.com>
  38111. * @copyright 2016 Photon Storm Ltd.
  38112. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  38113. */
  38114. /**
  38115. * The Crop component provides the ability to crop a texture based Game Object to a defined rectangle,
  38116. * which can be updated in real-time.
  38117. *
  38118. * @class
  38119. */
  38120. Phaser.Component.Crop = function () {};
  38121. Phaser.Component.Crop.prototype = {
  38122. /**
  38123. * The Rectangle used to crop the texture this Game Object uses.
  38124. * Set this property via `crop`.
  38125. * If you modify this property directly you must call `updateCrop` in order to have the change take effect.
  38126. * @property {Phaser.Rectangle} cropRect
  38127. * @default
  38128. */
  38129. cropRect: null,
  38130. /**
  38131. * @property {Phaser.Rectangle} _crop - Internal cache var.
  38132. * @private
  38133. */
  38134. _crop: null,
  38135. /**
  38136. * Crop allows you to crop the texture being used to display this Game Object.
  38137. * Setting a crop rectangle modifies the core texture frame. The Game Object width and height properties will be adjusted accordingly.
  38138. *
  38139. * Cropping takes place from the top-left and can be modified in real-time either by providing an updated rectangle object to this method,
  38140. * or by modifying `cropRect` property directly and then calling `updateCrop`.
  38141. *
  38142. * The rectangle object given to this method can be either a `Phaser.Rectangle` or any other object
  38143. * so long as it has public `x`, `y`, `width`, `height`, `right` and `bottom` properties.
  38144. *
  38145. * A reference to the rectangle is stored in `cropRect` unless the `copy` parameter is `true`,
  38146. * in which case the values are duplicated to a local object.
  38147. *
  38148. * @method
  38149. * @param {Phaser.Rectangle} rect - The Rectangle used during cropping. Pass null or no parameters to clear a previously set crop rectangle.
  38150. * @param {boolean} [copy=false] - If false `cropRect` will be stored as a reference to the given rect. If true it will copy the rect values into a local Phaser Rectangle object stored in cropRect.
  38151. */
  38152. crop: function (rect, copy) {
  38153. if (copy === undefined) { copy = false; }
  38154. if (rect)
  38155. {
  38156. if (copy && this.cropRect !== null)
  38157. {
  38158. this.cropRect.setTo(rect.x, rect.y, rect.width, rect.height);
  38159. }
  38160. else if (copy && this.cropRect === null)
  38161. {
  38162. this.cropRect = new Phaser.Rectangle(rect.x, rect.y, rect.width, rect.height);
  38163. }
  38164. else
  38165. {
  38166. this.cropRect = rect;
  38167. }
  38168. this.updateCrop();
  38169. }
  38170. else
  38171. {
  38172. this._crop = null;
  38173. this.cropRect = null;
  38174. this.resetFrame();
  38175. }
  38176. },
  38177. /**
  38178. * If you have set a crop rectangle on this Game Object via `crop` and since modified the `cropRect` property,
  38179. * or the rectangle it references, then you need to update the crop frame by calling this method.
  38180. *
  38181. * @method
  38182. */
  38183. updateCrop: function () {
  38184. if (!this.cropRect)
  38185. {
  38186. return;
  38187. }
  38188. var oldX = this.texture.crop.x;
  38189. var oldY = this.texture.crop.y;
  38190. var oldW = this.texture.crop.width;
  38191. var oldH = this.texture.crop.height;
  38192. this._crop = Phaser.Rectangle.clone(this.cropRect, this._crop);
  38193. this._crop.x += this._frame.x;
  38194. this._crop.y += this._frame.y;
  38195. var cx = Math.max(this._frame.x, this._crop.x);
  38196. var cy = Math.max(this._frame.y, this._crop.y);
  38197. var cw = Math.min(this._frame.right, this._crop.right) - cx;
  38198. var ch = Math.min(this._frame.bottom, this._crop.bottom) - cy;
  38199. this.texture.crop.x = cx;
  38200. this.texture.crop.y = cy;
  38201. this.texture.crop.width = cw;
  38202. this.texture.crop.height = ch;
  38203. this.texture.frame.width = Math.min(cw, this.cropRect.width);
  38204. this.texture.frame.height = Math.min(ch, this.cropRect.height);
  38205. this.texture.width = this.texture.frame.width;
  38206. this.texture.height = this.texture.frame.height;
  38207. this.texture._updateUvs();
  38208. if (this.tint !== 0xffffff && (oldX !== cx || oldY !== cy || oldW !== cw || oldH !== ch))
  38209. {
  38210. this.texture.requiresReTint = true;
  38211. }
  38212. }
  38213. };
  38214. /**
  38215. * @author Richard Davey <rich@photonstorm.com>
  38216. * @copyright 2016 Photon Storm Ltd.
  38217. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  38218. */
  38219. /**
  38220. * The Delta component provides access to delta values between the Game Objects current and previous position.
  38221. *
  38222. * @class
  38223. */
  38224. Phaser.Component.Delta = function () {};
  38225. Phaser.Component.Delta.prototype = {
  38226. /**
  38227. * Returns the delta x value. The difference between world.x now and in the previous frame.
  38228. *
  38229. * The value will be positive if the Game Object has moved to the right or negative if to the left.
  38230. *
  38231. * @property {number} deltaX
  38232. * @readonly
  38233. */
  38234. deltaX: {
  38235. get: function() {
  38236. return this.world.x - this.previousPosition.x;
  38237. }
  38238. },
  38239. /**
  38240. * Returns the delta y value. The difference between world.y now and in the previous frame.
  38241. *
  38242. * The value will be positive if the Game Object has moved down or negative if up.
  38243. *
  38244. * @property {number} deltaY
  38245. * @readonly
  38246. */
  38247. deltaY: {
  38248. get: function() {
  38249. return this.world.y - this.previousPosition.y;
  38250. }
  38251. },
  38252. /**
  38253. * Returns the delta z value. The difference between rotation now and in the previous frame.
  38254. *
  38255. * @property {number} deltaZ - The delta value.
  38256. * @readonly
  38257. */
  38258. deltaZ: {
  38259. get: function() {
  38260. return this.rotation - this.previousRotation;
  38261. }
  38262. }
  38263. };
  38264. /**
  38265. * @author Richard Davey <rich@photonstorm.com>
  38266. * @copyright 2016 Photon Storm Ltd.
  38267. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  38268. */
  38269. /**
  38270. * The Destroy component is responsible for destroying a Game Object.
  38271. *
  38272. * @class
  38273. */
  38274. Phaser.Component.Destroy = function () {};
  38275. Phaser.Component.Destroy.prototype = {
  38276. /**
  38277. * As a Game Object runs through its destroy method this flag is set to true,
  38278. * and can be checked in any sub-systems or plugins it is being destroyed from.
  38279. * @property {boolean} destroyPhase
  38280. * @readOnly
  38281. */
  38282. destroyPhase: false,
  38283. /**
  38284. * Destroys the Game Object. This removes it from its parent group, destroys the input, event and animation handlers if present
  38285. * and nulls its reference to `game`, freeing it up for garbage collection.
  38286. *
  38287. * If this Game Object has the Events component it will also dispatch the `onDestroy` event.
  38288. *
  38289. * You can optionally also destroy the BaseTexture this Game Object is using. Be careful if you've
  38290. * more than one Game Object sharing the same BaseTexture.
  38291. *
  38292. * @method
  38293. * @param {boolean} [destroyChildren=true] - Should every child of this object have its destroy method called as well?
  38294. * @param {boolean} [destroyTexture=false] - Destroy the BaseTexture this Game Object is using? Note that if another Game Object is sharing the same BaseTexture it will invalidate it.
  38295. */
  38296. destroy: function (destroyChildren, destroyTexture) {
  38297. if (this.game === null || this.destroyPhase) { return; }
  38298. if (destroyChildren === undefined) { destroyChildren = true; }
  38299. if (destroyTexture === undefined) { destroyTexture = false; }
  38300. this.destroyPhase = true;
  38301. if (this.events)
  38302. {
  38303. this.events.onDestroy$dispatch(this);
  38304. }
  38305. if (this.parent)
  38306. {
  38307. if (this.parent instanceof Phaser.Group)
  38308. {
  38309. this.parent.remove(this);
  38310. }
  38311. else
  38312. {
  38313. this.parent.removeChild(this);
  38314. }
  38315. }
  38316. if (this.input)
  38317. {
  38318. this.input.destroy();
  38319. }
  38320. if (this.animations)
  38321. {
  38322. this.animations.destroy();
  38323. }
  38324. if (this.body)
  38325. {
  38326. this.body.destroy();
  38327. }
  38328. if (this.events)
  38329. {
  38330. this.events.destroy();
  38331. }
  38332. this.game.tweens.removeFrom(this);
  38333. var i = this.children.length;
  38334. if (destroyChildren)
  38335. {
  38336. while (i--)
  38337. {
  38338. this.children[i].destroy(destroyChildren);
  38339. }
  38340. }
  38341. else
  38342. {
  38343. while (i--)
  38344. {
  38345. this.removeChild(this.children[i]);
  38346. }
  38347. }
  38348. if (this._crop)
  38349. {
  38350. this._crop = null;
  38351. this.cropRect = null;
  38352. }
  38353. if (this._frame)
  38354. {
  38355. this._frame = null;
  38356. }
  38357. if (Phaser.Video && this.key instanceof Phaser.Video)
  38358. {
  38359. this.key.onChangeSource.remove(this.resizeFrame, this);
  38360. }
  38361. if (Phaser.BitmapText && this._glyphs)
  38362. {
  38363. this._glyphs = [];
  38364. }
  38365. this.alive = false;
  38366. this.exists = false;
  38367. this.visible = false;
  38368. this.filters = null;
  38369. this.mask = null;
  38370. this.game = null;
  38371. this.data = {};
  38372. // In case Pixi is still going to try and render it even though destroyed
  38373. this.renderable = false;
  38374. if (this.transformCallback)
  38375. {
  38376. this.transformCallback = null;
  38377. this.transformCallbackContext = null;
  38378. }
  38379. // Pixi level DisplayObject destroy
  38380. this.hitArea = null;
  38381. this.parent = null;
  38382. this.stage = null;
  38383. this.worldTransform = null;
  38384. this.filterArea = null;
  38385. this._bounds = null;
  38386. this._currentBounds = null;
  38387. this._mask = null;
  38388. this._destroyCachedSprite();
  38389. // Texture?
  38390. if (destroyTexture)
  38391. {
  38392. this.texture.destroy(true);
  38393. }
  38394. this.destroyPhase = false;
  38395. this.pendingDestroy = false;
  38396. }
  38397. };
  38398. /**
  38399. * @author Richard Davey <rich@photonstorm.com>
  38400. * @copyright 2016 Photon Storm Ltd.
  38401. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  38402. */
  38403. /**
  38404. * The Events component is a collection of events fired by the parent Game Object.
  38405. *
  38406. * Phaser uses what are known as 'Signals' for all event handling. All of the events in
  38407. * this class are signals you can subscribe to, much in the same way you'd "listen" for
  38408. * an event.
  38409. *
  38410. * For example to tell when a Sprite has been added to a new group, you can bind a function
  38411. * to the `onAddedToGroup` signal:
  38412. *
  38413. * `sprite.events.onAddedToGroup.add(yourFunction, this);`
  38414. *
  38415. * Where `yourFunction` is the function you want called when this event occurs.
  38416. *
  38417. * For more details about how signals work please see the Phaser.Signal class.
  38418. *
  38419. * The Input-related events will only be dispatched if the Sprite has had `inputEnabled` set to `true`
  38420. * and the Animation-related events only apply to game objects with animations like {@link Phaser.Sprite}.
  38421. *
  38422. * @class Phaser.Events
  38423. * @constructor
  38424. * @param {Phaser.Sprite} sprite - A reference to the game object / Sprite that owns this Events object.
  38425. */
  38426. Phaser.Events = function (sprite) {
  38427. /**
  38428. * @property {Phaser.Sprite} parent - The Sprite that owns these events.
  38429. */
  38430. this.parent = sprite;
  38431. // The signals are automatically added by the corresponding proxy properties
  38432. };
  38433. Phaser.Events.prototype = {
  38434. /**
  38435. * Removes all events.
  38436. *
  38437. * @method Phaser.Events#destroy
  38438. */
  38439. destroy: function () {
  38440. this._parent = null;
  38441. if (this._onDestroy) { this._onDestroy.dispose(); }
  38442. if (this._onAddedToGroup) { this._onAddedToGroup.dispose(); }
  38443. if (this._onRemovedFromGroup) { this._onRemovedFromGroup.dispose(); }
  38444. if (this._onRemovedFromWorld) { this._onRemovedFromWorld.dispose(); }
  38445. if (this._onKilled) { this._onKilled.dispose(); }
  38446. if (this._onRevived) { this._onRevived.dispose(); }
  38447. if (this._onEnterBounds) { this._onEnterBounds.dispose(); }
  38448. if (this._onOutOfBounds) { this._onOutOfBounds.dispose(); }
  38449. if (this._onInputOver) { this._onInputOver.dispose(); }
  38450. if (this._onInputOut) { this._onInputOut.dispose(); }
  38451. if (this._onInputDown) { this._onInputDown.dispose(); }
  38452. if (this._onInputUp) { this._onInputUp.dispose(); }
  38453. if (this._onDragStart) { this._onDragStart.dispose(); }
  38454. if (this._onDragUpdate) { this._onDragUpdate.dispose(); }
  38455. if (this._onDragStop) { this._onDragStop.dispose(); }
  38456. if (this._onAnimationStart) { this._onAnimationStart.dispose(); }
  38457. if (this._onAnimationComplete) { this._onAnimationComplete.dispose(); }
  38458. if (this._onAnimationLoop) { this._onAnimationLoop.dispose(); }
  38459. },
  38460. // The following properties are sentinels that will be replaced with getters
  38461. /**
  38462. * This signal is dispatched when this Game Object is added to a new Group.
  38463. * It is sent two arguments:
  38464. * {any} The Game Object that was added to the Group.
  38465. * {Phaser.Group} The Group it was added to.
  38466. * @property {Phaser.Signal} onAddedToGroup
  38467. */
  38468. onAddedToGroup: null,
  38469. /**
  38470. * This signal is dispatched when the Game Object is removed from a Group.
  38471. * It is sent two arguments:
  38472. * {any} The Game Object that was removed from the Group.
  38473. * {Phaser.Group} The Group it was removed from.
  38474. * @property {Phaser.Signal} onRemovedFromGroup
  38475. */
  38476. onRemovedFromGroup: null,
  38477. /**
  38478. * This Signal is never used internally by Phaser and is now deprecated.
  38479. * @deprecated
  38480. * @property {Phaser.Signal} onRemovedFromWorld
  38481. */
  38482. onRemovedFromWorld: null,
  38483. /**
  38484. * This signal is dispatched when the Game Object is destroyed.
  38485. * This happens when `Sprite.destroy()` is called, or `Group.destroy()` with `destroyChildren` set to true.
  38486. * It is sent one argument:
  38487. * {any} The Game Object that was destroyed.
  38488. * @property {Phaser.Signal} onDestroy
  38489. */
  38490. onDestroy: null,
  38491. /**
  38492. * This signal is dispatched when the Game Object is killed.
  38493. * This happens when `Sprite.kill()` is called.
  38494. * Please understand the difference between `kill` and `destroy` by looking at their respective methods.
  38495. * It is sent one argument:
  38496. * {any} The Game Object that was killed.
  38497. * @property {Phaser.Signal} onKilled
  38498. */
  38499. onKilled: null,
  38500. /**
  38501. * This signal is dispatched when the Game Object is revived from a previously killed state.
  38502. * This happens when `Sprite.revive()` is called.
  38503. * It is sent one argument:
  38504. * {any} The Game Object that was revived.
  38505. * @property {Phaser.Signal} onRevived
  38506. */
  38507. onRevived: null,
  38508. /**
  38509. * This signal is dispatched when the Game Object leaves the Phaser.World bounds.
  38510. * This signal is only if `Sprite.checkWorldBounds` is set to `true`.
  38511. * It is sent one argument:
  38512. * {any} The Game Object that left the World bounds.
  38513. * @property {Phaser.Signal} onOutOfBounds
  38514. */
  38515. onOutOfBounds: null,
  38516. /**
  38517. * This signal is dispatched when the Game Object returns within the Phaser.World bounds, having previously been outside of them.
  38518. * This signal is only if `Sprite.checkWorldBounds` is set to `true`.
  38519. * It is sent one argument:
  38520. * {any} The Game Object that entered the World bounds.
  38521. * @property {Phaser.Signal} onEnterBounds
  38522. */
  38523. onEnterBounds: null,
  38524. /**
  38525. * This signal is dispatched if the Game Object has `inputEnabled` set to `true`,
  38526. * and receives an over event from a Phaser.Pointer.
  38527. * It is sent two arguments:
  38528. * {any} The Game Object that received the event.
  38529. * {Phaser.Pointer} The Phaser.Pointer object that caused the event.
  38530. * @property {Phaser.Signal} onInputOver
  38531. */
  38532. onInputOver: null,
  38533. /**
  38534. * This signal is dispatched if the Game Object has `inputEnabled` set to `true`,
  38535. * and receives an out event from a Phaser.Pointer, which was previously over it.
  38536. * It is sent two arguments:
  38537. * {any} The Game Object that received the event.
  38538. * {Phaser.Pointer} The Phaser.Pointer object that caused the event.
  38539. * @property {Phaser.Signal} onInputOut
  38540. */
  38541. onInputOut: null,
  38542. /**
  38543. * This signal is dispatched if the Game Object has `inputEnabled` set to `true`,
  38544. * and receives a down event from a Phaser.Pointer. This effectively means the Pointer has been
  38545. * pressed down (but not yet released) on the Game Object.
  38546. * It is sent two arguments:
  38547. * {any} The Game Object that received the event.
  38548. * {Phaser.Pointer} The Phaser.Pointer object that caused the event.
  38549. * @property {Phaser.Signal} onInputDown
  38550. */
  38551. onInputDown: null,
  38552. /**
  38553. * This signal is dispatched if the Game Object has `inputEnabled` set to `true`,
  38554. * and receives an up event from a Phaser.Pointer. This effectively means the Pointer had been
  38555. * pressed down, and was then released on the Game Object.
  38556. * It is sent three arguments:
  38557. * {any} The Game Object that received the event.
  38558. * {Phaser.Pointer} The Phaser.Pointer object that caused the event.
  38559. * {boolean} isOver - Is the Pointer still over the Game Object?
  38560. * @property {Phaser.Signal} onInputUp
  38561. */
  38562. onInputUp: null,
  38563. /**
  38564. * This signal is dispatched if the Game Object has been `inputEnabled` and `enableDrag` has been set.
  38565. * It is sent when a Phaser.Pointer starts to drag the Game Object, taking into consideration the various
  38566. * drag limitations that may be set.
  38567. * It is sent four arguments:
  38568. * {any} The Game Object that received the event.
  38569. * {Phaser.Pointer} The Phaser.Pointer object that caused the event.
  38570. * {number} The x coordinate that the drag started from.
  38571. * {number} The y coordinate that the drag started from.
  38572. * @property {Phaser.Signal} onDragStart
  38573. */
  38574. onDragStart: null,
  38575. /**
  38576. * This signal is dispatched if the Game Object has been `inputEnabled` and `enableDrag` has been set.
  38577. * It is sent when a Phaser.Pointer is actively dragging the Game Object.
  38578. * Be warned: This is a high volume Signal. Be careful what you bind to it.
  38579. * It is sent six arguments:
  38580. * {any} The Game Object that received the event.
  38581. * {Phaser.Pointer} The Phaser.Pointer object that caused the event.
  38582. * {number} The new x coordinate of the Game Object.
  38583. * {number} The new y coordinate of the Game Object.
  38584. * {Phaser.Point} A Point object that contains the point the Game Object was snapped to, if `snapOnDrag` has been enabled.
  38585. * {boolean} The `fromStart` boolean, indicates if this is the first update immediately after the drag has started.
  38586. * @property {Phaser.Signal} onDragUpdate
  38587. */
  38588. onDragUpdate: null,
  38589. /**
  38590. * This signal is dispatched if the Game Object has been `inputEnabled` and `enableDrag` has been set.
  38591. * It is sent when a Phaser.Pointer stops dragging the Game Object.
  38592. * It is sent two arguments:
  38593. * {any} The Game Object that received the event.
  38594. * {Phaser.Pointer} The Phaser.Pointer object that caused the event.
  38595. * @property {Phaser.Signal} onDragStop
  38596. */
  38597. onDragStop: null,
  38598. /**
  38599. * This signal is dispatched if the Game Object has the AnimationManager component,
  38600. * and an Animation has been played.
  38601. * You can also listen to `Animation.onStart` rather than via the Game Objects events.
  38602. * It is sent two arguments:
  38603. * {any} The Game Object that received the event.
  38604. * {Phaser.Animation} The Phaser.Animation that was started.
  38605. * @property {Phaser.Signal} onAnimationStart
  38606. */
  38607. onAnimationStart: null,
  38608. /**
  38609. * This signal is dispatched if the Game Object has the AnimationManager component,
  38610. * and an Animation has been stopped (via `animation.stop()` and the `dispatchComplete` argument has been set.
  38611. * You can also listen to `Animation.onComplete` rather than via the Game Objects events.
  38612. * It is sent two arguments:
  38613. * {any} The Game Object that received the event.
  38614. * {Phaser.Animation} The Phaser.Animation that was stopped.
  38615. * @property {Phaser.Signal} onAnimationComplete
  38616. */
  38617. onAnimationComplete: null,
  38618. /**
  38619. * This signal is dispatched if the Game Object has the AnimationManager component,
  38620. * and an Animation has looped playback.
  38621. * You can also listen to `Animation.onLoop` rather than via the Game Objects events.
  38622. * It is sent two arguments:
  38623. * {any} The Game Object that received the event.
  38624. * {Phaser.Animation} The Phaser.Animation that looped.
  38625. * @property {Phaser.Signal} onAnimationLoop
  38626. */
  38627. onAnimationLoop: null
  38628. };
  38629. Phaser.Events.prototype.constructor = Phaser.Events;
  38630. // Create an auto-create proxy getter and dispatch method for all events.
  38631. // The backing property is the same as the event name, prefixed with '_'
  38632. // and the dispatch method is the same as the event name postfixed with '$dispatch'.
  38633. for (var prop in Phaser.Events.prototype)
  38634. {
  38635. if (!Phaser.Events.prototype.hasOwnProperty(prop) ||
  38636. prop.indexOf('on') !== 0 ||
  38637. Phaser.Events.prototype[prop] !== null)
  38638. {
  38639. continue;
  38640. }
  38641. (function (prop, backing) {
  38642. 'use strict';
  38643. // The accessor creates a new Signal; and so it should only be used from user-code.
  38644. Object.defineProperty(Phaser.Events.prototype, prop, {
  38645. get: function () {
  38646. return this[backing] || (this[backing] = new Phaser.Signal());
  38647. }
  38648. });
  38649. // The dispatcher will only broadcast on an already-created signal; call this internally.
  38650. Phaser.Events.prototype[prop + '$dispatch'] = function () {
  38651. return this[backing] ? this[backing].dispatch.apply(this[backing], arguments) : null;
  38652. };
  38653. })(prop, '_' + prop);
  38654. }
  38655. /**
  38656. * @author Richard Davey <rich@photonstorm.com>
  38657. * @copyright 2016 Photon Storm Ltd.
  38658. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  38659. */
  38660. /**
  38661. * The FixedToCamera component enables a Game Object to be rendered relative to the game camera coordinates, regardless
  38662. * of where in the world the camera is. This is used for things like sticking game UI to the camera that scrolls as it moves around the world.
  38663. *
  38664. * @class
  38665. */
  38666. Phaser.Component.FixedToCamera = function () {};
  38667. /**
  38668. * The FixedToCamera component postUpdate handler.
  38669. * Called automatically by the Game Object.
  38670. *
  38671. * @method
  38672. */
  38673. Phaser.Component.FixedToCamera.postUpdate = function () {
  38674. if (this.fixedToCamera)
  38675. {
  38676. this.position.x = (this.game.camera.view.x + this.cameraOffset.x) / this.game.camera.scale.x;
  38677. this.position.y = (this.game.camera.view.y + this.cameraOffset.y) / this.game.camera.scale.y;
  38678. }
  38679. };
  38680. Phaser.Component.FixedToCamera.prototype = {
  38681. /**
  38682. * @property {boolean} _fixedToCamera
  38683. * @private
  38684. */
  38685. _fixedToCamera: false,
  38686. /**
  38687. * A Game Object that is "fixed" to the camera uses its x/y coordinates as offsets from the top left of the camera during rendering.
  38688. *
  38689. * The values are adjusted at the rendering stage, overriding the Game Objects actual world position.
  38690. *
  38691. * The end result is that the Game Object will appear to be 'fixed' to the camera, regardless of where in the game world
  38692. * the camera is viewing. This is useful if for example this Game Object is a UI item that you wish to be visible at all times
  38693. * regardless where in the world the camera is.
  38694. *
  38695. * The offsets are stored in the `cameraOffset` property.
  38696. *
  38697. * Note that the `cameraOffset` values are in addition to any parent of this Game Object on the display list.
  38698. *
  38699. * Be careful not to set `fixedToCamera` on Game Objects which are in Groups that already have `fixedToCamera` enabled on them.
  38700. *
  38701. * @property {boolean} fixedToCamera
  38702. */
  38703. fixedToCamera: {
  38704. get: function () {
  38705. return this._fixedToCamera;
  38706. },
  38707. set: function (value) {
  38708. if (value)
  38709. {
  38710. this._fixedToCamera = true;
  38711. this.cameraOffset.set(this.x, this.y);
  38712. }
  38713. else
  38714. {
  38715. this._fixedToCamera = false;
  38716. }
  38717. }
  38718. },
  38719. /**
  38720. * The x/y coordinate offset applied to the top-left of the camera that this Game Object will be drawn at if `fixedToCamera` is true.
  38721. *
  38722. * The values are relative to the top-left of the camera view and in addition to any parent of the Game Object on the display list.
  38723. * @property {Phaser.Point} cameraOffset
  38724. */
  38725. cameraOffset: new Phaser.Point()
  38726. };
  38727. /**
  38728. * @author Richard Davey <rich@photonstorm.com>
  38729. * @copyright 2016 Photon Storm Ltd.
  38730. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  38731. */
  38732. /**
  38733. * The Health component provides the ability for Game Objects to have a `health` property
  38734. * that can be damaged and reset through game code.
  38735. * Requires the LifeSpan component.
  38736. *
  38737. * @class
  38738. */
  38739. Phaser.Component.Health = function () {};
  38740. Phaser.Component.Health.prototype = {
  38741. /**
  38742. * The Game Objects health value. This is a handy property for setting and manipulating health on a Game Object.
  38743. *
  38744. * It can be used in combination with the `damage` method or modified directly.
  38745. *
  38746. * @property {number} health
  38747. * @default
  38748. */
  38749. health: 1,
  38750. /**
  38751. * The Game Objects maximum health value. This works in combination with the `heal` method to ensure
  38752. * the health value never exceeds the maximum.
  38753. *
  38754. * @property {number} maxHealth
  38755. * @default
  38756. */
  38757. maxHealth: 100,
  38758. /**
  38759. * Damages the Game Object. This removes the given amount of health from the `health` property.
  38760. *
  38761. * If health is taken below or is equal to zero then the `kill` method is called.
  38762. *
  38763. * @member
  38764. * @param {number} amount - The amount to subtract from the current `health` value.
  38765. * @return {Phaser.Sprite} This instance.
  38766. */
  38767. damage: function (amount) {
  38768. if (this.alive)
  38769. {
  38770. this.health -= amount;
  38771. if (this.health <= 0)
  38772. {
  38773. this.kill();
  38774. }
  38775. }
  38776. return this;
  38777. },
  38778. /**
  38779. * Sets the health property of the Game Object to the given amount.
  38780. * Will never exceed the `maxHealth` value.
  38781. *
  38782. * @member
  38783. * @param {number} amount - The amount to set the `health` value to. The total will never exceed `maxHealth`.
  38784. * @return {Phaser.Sprite} This instance.
  38785. */
  38786. setHealth: function (amount) {
  38787. this.health = amount;
  38788. if (this.health > this.maxHealth)
  38789. {
  38790. this.health = this.maxHealth;
  38791. }
  38792. return this;
  38793. },
  38794. /**
  38795. * Heal the Game Object. This adds the given amount of health to the `health` property.
  38796. *
  38797. * @member
  38798. * @param {number} amount - The amount to add to the current `health` value. The total will never exceed `maxHealth`.
  38799. * @return {Phaser.Sprite} This instance.
  38800. */
  38801. heal: function (amount) {
  38802. if (this.alive)
  38803. {
  38804. this.health += amount;
  38805. if (this.health > this.maxHealth)
  38806. {
  38807. this.health = this.maxHealth;
  38808. }
  38809. }
  38810. return this;
  38811. }
  38812. };
  38813. /**
  38814. * @author Richard Davey <rich@photonstorm.com>
  38815. * @copyright 2016 Photon Storm Ltd.
  38816. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  38817. */
  38818. /**
  38819. * The InCamera component checks if the Game Object intersects with the Game Camera.
  38820. *
  38821. * @class
  38822. */
  38823. Phaser.Component.InCamera = function () {};
  38824. Phaser.Component.InCamera.prototype = {
  38825. /**
  38826. * Checks if this Game Objects bounds intersects with the Game Cameras bounds.
  38827. *
  38828. * It will be `true` if they intersect, or `false` if the Game Object is fully outside of the Cameras bounds.
  38829. *
  38830. * An object outside the bounds can be considered for camera culling if it has the AutoCull component.
  38831. *
  38832. * @property {boolean} inCamera
  38833. * @readonly
  38834. */
  38835. inCamera: {
  38836. get: function() {
  38837. return this.game.world.camera.view.intersects(this._bounds);
  38838. }
  38839. }
  38840. };
  38841. /**
  38842. * @author Richard Davey <rich@photonstorm.com>
  38843. * @copyright 2016 Photon Storm Ltd.
  38844. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  38845. */
  38846. /**
  38847. * The InputEnabled component allows a Game Object to have its own InputHandler and process input related events.
  38848. *
  38849. * @class
  38850. */
  38851. Phaser.Component.InputEnabled = function () {};
  38852. Phaser.Component.InputEnabled.prototype = {
  38853. /**
  38854. * The Input Handler for this Game Object.
  38855. *
  38856. * By default it is disabled. If you wish this Game Object to process input events you should enable it with: `inputEnabled = true`.
  38857. *
  38858. * After you have done this, this property will be a reference to the Phaser InputHandler.
  38859. * @property {Phaser.InputHandler|null} input
  38860. */
  38861. input: null,
  38862. /**
  38863. * By default a Game Object won't process any input events. By setting `inputEnabled` to true a Phaser.InputHandler is created
  38864. * for this Game Object and it will then start to process click / touch events and more.
  38865. *
  38866. * You can then access the Input Handler via `this.input`.
  38867. *
  38868. * Note that Input related events are dispatched from `this.events`, i.e.: `events.onInputDown`.
  38869. *
  38870. * If you set this property to false it will stop the Input Handler from processing any more input events.
  38871. *
  38872. * If you want to _temporarily_ disable input for a Game Object, then it's better to set
  38873. * `input.enabled = false`, as it won't reset any of the Input Handlers internal properties.
  38874. * You can then toggle this back on as needed.
  38875. *
  38876. * @property {boolean} inputEnabled
  38877. */
  38878. inputEnabled: {
  38879. get: function () {
  38880. return (this.input && this.input.enabled);
  38881. },
  38882. set: function (value) {
  38883. if (value)
  38884. {
  38885. if (this.input === null)
  38886. {
  38887. this.input = new Phaser.InputHandler(this);
  38888. this.input.start();
  38889. }
  38890. else if (this.input && !this.input.enabled)
  38891. {
  38892. this.input.start();
  38893. }
  38894. }
  38895. else
  38896. {
  38897. if (this.input && this.input.enabled)
  38898. {
  38899. this.input.stop();
  38900. }
  38901. }
  38902. }
  38903. }
  38904. };
  38905. /**
  38906. * @author Richard Davey <rich@photonstorm.com>
  38907. * @copyright 2016 Photon Storm Ltd.
  38908. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  38909. */
  38910. /**
  38911. * The InWorld component checks if a Game Object is within the Game World Bounds.
  38912. * An object is considered as being "in bounds" so long as its own bounds intersects at any point with the World bounds.
  38913. * If the AutoCull component is enabled on the Game Object then it will check the Game Object against the Camera bounds as well.
  38914. *
  38915. * @class
  38916. */
  38917. Phaser.Component.InWorld = function () {};
  38918. /**
  38919. * The InWorld component preUpdate handler.
  38920. * Called automatically by the Game Object.
  38921. *
  38922. * @method
  38923. */
  38924. Phaser.Component.InWorld.preUpdate = function () {
  38925. // Cache the bounds if we need it
  38926. if (this.autoCull || this.checkWorldBounds)
  38927. {
  38928. this._bounds.copyFrom(this.getBounds());
  38929. this._bounds.x += this.game.camera.view.x;
  38930. this._bounds.y += this.game.camera.view.y;
  38931. if (this.autoCull)
  38932. {
  38933. // Won't get rendered but will still get its transform updated
  38934. if (this.game.world.camera.view.intersects(this._bounds))
  38935. {
  38936. this.renderable = true;
  38937. this.game.world.camera.totalInView++;
  38938. }
  38939. else
  38940. {
  38941. this.renderable = false;
  38942. if (this.outOfCameraBoundsKill)
  38943. {
  38944. this.kill();
  38945. return false;
  38946. }
  38947. }
  38948. }
  38949. if (this.checkWorldBounds)
  38950. {
  38951. // The Sprite is already out of the world bounds, so let's check to see if it has come back again
  38952. if (this._outOfBoundsFired && this.game.world.bounds.intersects(this._bounds))
  38953. {
  38954. this._outOfBoundsFired = false;
  38955. this.events.onEnterBounds$dispatch(this);
  38956. }
  38957. else if (!this._outOfBoundsFired && !this.game.world.bounds.intersects(this._bounds))
  38958. {
  38959. // The Sprite WAS in the screen, but has now left.
  38960. this._outOfBoundsFired = true;
  38961. this.events.onOutOfBounds$dispatch(this);
  38962. if (this.outOfBoundsKill)
  38963. {
  38964. this.kill();
  38965. return false;
  38966. }
  38967. }
  38968. }
  38969. }
  38970. return true;
  38971. };
  38972. Phaser.Component.InWorld.prototype = {
  38973. /**
  38974. * If this is set to `true` the Game Object checks if it is within the World bounds each frame.
  38975. *
  38976. * When it is no longer intersecting the world bounds it dispatches the `onOutOfBounds` event.
  38977. *
  38978. * If it was *previously* out of bounds but is now intersecting the world bounds again it dispatches the `onEnterBounds` event.
  38979. *
  38980. * It also optionally kills the Game Object if `outOfBoundsKill` is `true`.
  38981. *
  38982. * When `checkWorldBounds` is enabled it forces the Game Object to calculate its full bounds every frame.
  38983. *
  38984. * This is a relatively expensive operation, especially if enabled on hundreds of Game Objects. So enable it only if you know it's required,
  38985. * or you have tested performance and find it acceptable.
  38986. *
  38987. * @property {boolean} checkWorldBounds
  38988. * @default
  38989. */
  38990. checkWorldBounds: false,
  38991. /**
  38992. * If this and the `checkWorldBounds` property are both set to `true` then the `kill` method is called as soon as `inWorld` returns false.
  38993. *
  38994. * @property {boolean} outOfBoundsKill
  38995. * @default
  38996. */
  38997. outOfBoundsKill: false,
  38998. /**
  38999. * If this and the `autoCull` property are both set to `true`, then the `kill` method
  39000. * is called as soon as the Game Object leaves the camera bounds.
  39001. *
  39002. * @property {boolean} outOfCameraBoundsKill
  39003. * @default
  39004. */
  39005. outOfCameraBoundsKill: false,
  39006. /**
  39007. * @property {boolean} _outOfBoundsFired - Internal state var.
  39008. * @private
  39009. */
  39010. _outOfBoundsFired: false,
  39011. /**
  39012. * Checks if the Game Objects bounds are within, or intersect at any point with the Game World bounds.
  39013. *
  39014. * @property {boolean} inWorld
  39015. * @readonly
  39016. */
  39017. inWorld: {
  39018. get: function () {
  39019. return this.game.world.bounds.intersects(this.getBounds());
  39020. }
  39021. }
  39022. };
  39023. /**
  39024. * @author Richard Davey <rich@photonstorm.com>
  39025. * @copyright 2016 Photon Storm Ltd.
  39026. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  39027. */
  39028. /**
  39029. * LifeSpan Component Features.
  39030. *
  39031. * @class
  39032. */
  39033. Phaser.Component.LifeSpan = function () {};
  39034. /**
  39035. * The LifeSpan component preUpdate handler.
  39036. * Called automatically by the Game Object.
  39037. *
  39038. * @method
  39039. */
  39040. Phaser.Component.LifeSpan.preUpdate = function () {
  39041. if (this.lifespan > 0)
  39042. {
  39043. this.lifespan -= this.game.time.physicsElapsedMS;
  39044. if (this.lifespan <= 0)
  39045. {
  39046. this.kill();
  39047. return false;
  39048. }
  39049. }
  39050. return true;
  39051. };
  39052. Phaser.Component.LifeSpan.prototype = {
  39053. /**
  39054. * A useful flag to control if the Game Object is alive or dead.
  39055. *
  39056. * This is set automatically by the Health components `damage` method should the object run out of health.
  39057. * Or you can toggle it via your game code.
  39058. *
  39059. * This property is mostly just provided to be used by your game - it doesn't effect rendering or logic updates.
  39060. * However you can use `Group.getFirstAlive` in conjunction with this property for fast object pooling and recycling.
  39061. * @property {boolean} alive
  39062. * @default
  39063. */
  39064. alive: true,
  39065. /**
  39066. * The lifespan allows you to give a Game Object a lifespan in milliseconds.
  39067. *
  39068. * Once the Game Object is 'born' you can set this to a positive value.
  39069. *
  39070. * It is automatically decremented by the millisecond equivalent of `game.time.physicsElapsed` each frame.
  39071. * When it reaches zero it will call the `kill` method.
  39072. *
  39073. * Very handy for particles, bullets, collectibles, or any other short-lived entity.
  39074. *
  39075. * @property {number} lifespan
  39076. * @default
  39077. */
  39078. lifespan: 0,
  39079. /**
  39080. * Brings a 'dead' Game Object back to life, optionally resetting its health value in the process.
  39081. *
  39082. * A resurrected Game Object has its `alive`, `exists` and `visible` properties all set to true.
  39083. *
  39084. * It will dispatch the `onRevived` event. Listen to `events.onRevived` for the signal.
  39085. *
  39086. * @method
  39087. * @param {number} [health=100] - The health to give the Game Object. Only set if the GameObject has the Health component.
  39088. * @return {PIXI.DisplayObject} This instance.
  39089. */
  39090. revive: function (health) {
  39091. if (health === undefined) { health = 100; }
  39092. this.alive = true;
  39093. this.exists = true;
  39094. this.visible = true;
  39095. if (typeof this.setHealth === 'function')
  39096. {
  39097. this.setHealth(health);
  39098. }
  39099. if (this.events)
  39100. {
  39101. this.events.onRevived$dispatch(this);
  39102. }
  39103. return this;
  39104. },
  39105. /**
  39106. * Kills a Game Object. A killed Game Object has its `alive`, `exists` and `visible` properties all set to false.
  39107. *
  39108. * It will dispatch the `onKilled` event. You can listen to `events.onKilled` for the signal.
  39109. *
  39110. * Note that killing a Game Object is a way for you to quickly recycle it in an object pool,
  39111. * it doesn't destroy the object or free it up from memory.
  39112. *
  39113. * If you don't need this Game Object any more you should call `destroy` instead.
  39114. *
  39115. * @method
  39116. * @return {PIXI.DisplayObject} This instance.
  39117. */
  39118. kill: function () {
  39119. this.alive = false;
  39120. this.exists = false;
  39121. this.visible = false;
  39122. if (this.events)
  39123. {
  39124. this.events.onKilled$dispatch(this);
  39125. }
  39126. return this;
  39127. }
  39128. };
  39129. /**
  39130. * @author Richard Davey <rich@photonstorm.com>
  39131. * @copyright 2016 Photon Storm Ltd.
  39132. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  39133. */
  39134. /**
  39135. * The LoadTexture component manages the loading of a texture into the Game Object and the changing of frames.
  39136. *
  39137. * @class
  39138. */
  39139. Phaser.Component.LoadTexture = function () {};
  39140. Phaser.Component.LoadTexture.prototype = {
  39141. /**
  39142. * @property {boolean} customRender - Does this texture require a custom render call? (as set by BitmapData, Video, etc)
  39143. * @private
  39144. */
  39145. customRender: false,
  39146. /**
  39147. * @property {Phaser.Rectangle} _frame - Internal cache var.
  39148. * @private
  39149. */
  39150. _frame: null,
  39151. /**
  39152. * Changes the base texture the Game Object is using. The old texture is removed and the new one is referenced or fetched from the Cache.
  39153. *
  39154. * If your Game Object is using a frame from a texture atlas and you just wish to change to another frame, then see the `frame` or `frameName` properties instead.
  39155. *
  39156. * You should only use `loadTexture` if you want to replace the base texture entirely.
  39157. *
  39158. * Calling this method causes a WebGL texture update, so use sparingly or in low-intensity portions of your game, or if you know the new texture is already on the GPU.
  39159. *
  39160. * You can use the new const `Phaser.PENDING_ATLAS` as the texture key for any sprite.
  39161. * Doing this then sets the key to be the `frame` argument (the frame is set to zero).
  39162. *
  39163. * This allows you to create sprites using `load.image` during development, and then change them
  39164. * to use a Texture Atlas later in development by simply searching your code for 'PENDING_ATLAS'
  39165. * and swapping it to be the key of the atlas data.
  39166. *
  39167. * Note: You cannot use a RenderTexture as a texture for a TileSprite.
  39168. *
  39169. * @method
  39170. * @param {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|PIXI.Texture} key - This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache Image entry, or an instance of a RenderTexture, BitmapData, Video or PIXI.Texture.
  39171. * @param {string|number} [frame] - If this Sprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index.
  39172. * @param {boolean} [stopAnimation=true] - If an animation is already playing on this Sprite you can choose to stop it or let it carry on playing.
  39173. */
  39174. loadTexture: function (key, frame, stopAnimation) {
  39175. if (key === Phaser.PENDING_ATLAS)
  39176. {
  39177. key = frame;
  39178. frame = 0;
  39179. }
  39180. else
  39181. {
  39182. frame = frame || 0;
  39183. }
  39184. if ((stopAnimation || stopAnimation === undefined) && this.animations)
  39185. {
  39186. this.animations.stop();
  39187. }
  39188. this.key = key;
  39189. this.customRender = false;
  39190. var cache = this.game.cache;
  39191. var setFrame = true;
  39192. var smoothed = !this.texture.baseTexture.scaleMode;
  39193. if (Phaser.RenderTexture && key instanceof Phaser.RenderTexture)
  39194. {
  39195. this.key = key.key;
  39196. this.setTexture(key);
  39197. }
  39198. else if (Phaser.BitmapData && key instanceof Phaser.BitmapData)
  39199. {
  39200. this.customRender = true;
  39201. this.setTexture(key.texture);
  39202. if (cache.hasFrameData(key.key, Phaser.Cache.BITMAPDATA))
  39203. {
  39204. setFrame = !this.animations.loadFrameData(cache.getFrameData(key.key, Phaser.Cache.BITMAPDATA), frame);
  39205. }
  39206. else
  39207. {
  39208. setFrame = !this.animations.loadFrameData(key.frameData, 0);
  39209. }
  39210. }
  39211. else if (Phaser.Video && key instanceof Phaser.Video)
  39212. {
  39213. this.customRender = true;
  39214. // This works from a reference, which probably isn't what we need here
  39215. var valid = key.texture.valid;
  39216. this.setTexture(key.texture);
  39217. this.setFrame(key.texture.frame.clone());
  39218. key.onChangeSource.add(this.resizeFrame, this);
  39219. this.texture.valid = valid;
  39220. }
  39221. else if (Phaser.Tilemap && key instanceof Phaser.TilemapLayer)
  39222. {
  39223. // this.customRender = true;
  39224. this.setTexture(PIXI.Texture.fromCanvas(key.canvas));
  39225. }
  39226. else if (key instanceof PIXI.Texture)
  39227. {
  39228. this.setTexture(key);
  39229. }
  39230. else
  39231. {
  39232. var img = cache.getImage(key, true);
  39233. this.key = img.key;
  39234. this.setTexture(new PIXI.Texture(img.base));
  39235. if (key === '__default')
  39236. {
  39237. this.texture.baseTexture.skipRender = true;
  39238. }
  39239. else
  39240. {
  39241. this.texture.baseTexture.skipRender = false;
  39242. }
  39243. setFrame = !this.animations.loadFrameData(img.frameData, frame);
  39244. }
  39245. if (setFrame)
  39246. {
  39247. this._frame = Phaser.Rectangle.clone(this.texture.frame);
  39248. }
  39249. if (!smoothed)
  39250. {
  39251. this.texture.baseTexture.scaleMode = 1;
  39252. }
  39253. },
  39254. /**
  39255. * Sets the texture frame the Game Object uses for rendering.
  39256. *
  39257. * This is primarily an internal method used by `loadTexture`, but is exposed for the use of plugins and custom classes.
  39258. *
  39259. * @method
  39260. * @param {Phaser.Frame} frame - The Frame to be used by the texture.
  39261. */
  39262. setFrame: function (frame) {
  39263. this._frame = frame;
  39264. this.texture.frame.x = frame.x;
  39265. this.texture.frame.y = frame.y;
  39266. this.texture.frame.width = frame.width;
  39267. this.texture.frame.height = frame.height;
  39268. this.texture.crop.x = frame.x;
  39269. this.texture.crop.y = frame.y;
  39270. this.texture.crop.width = frame.width;
  39271. this.texture.crop.height = frame.height;
  39272. if (frame.trimmed)
  39273. {
  39274. if (this.texture.trim)
  39275. {
  39276. this.texture.trim.x = frame.spriteSourceSizeX;
  39277. this.texture.trim.y = frame.spriteSourceSizeY;
  39278. this.texture.trim.width = frame.sourceSizeW;
  39279. this.texture.trim.height = frame.sourceSizeH;
  39280. }
  39281. else
  39282. {
  39283. this.texture.trim = { x: frame.spriteSourceSizeX, y: frame.spriteSourceSizeY, width: frame.sourceSizeW, height: frame.sourceSizeH };
  39284. }
  39285. this.texture.width = frame.sourceSizeW;
  39286. this.texture.height = frame.sourceSizeH;
  39287. this.texture.frame.width = frame.sourceSizeW;
  39288. this.texture.frame.height = frame.sourceSizeH;
  39289. }
  39290. else if (!frame.trimmed && this.texture.trim)
  39291. {
  39292. this.texture.trim = null;
  39293. }
  39294. if (this.cropRect)
  39295. {
  39296. this.updateCrop();
  39297. }
  39298. this.texture.requiresReTint = true;
  39299. this.texture._updateUvs();
  39300. if (this.tilingTexture)
  39301. {
  39302. this.refreshTexture = true;
  39303. }
  39304. },
  39305. /**
  39306. * Resizes the Frame dimensions that the Game Object uses for rendering.
  39307. *
  39308. * You shouldn't normally need to ever call this, but in the case of special texture types such as Video or BitmapData
  39309. * it can be useful to adjust the dimensions directly in this way.
  39310. *
  39311. * @method
  39312. * @param {object} parent - The parent texture object that caused the resize, i.e. a Phaser.Video object.
  39313. * @param {integer} width - The new width of the texture.
  39314. * @param {integer} height - The new height of the texture.
  39315. */
  39316. resizeFrame: function (parent, width, height) {
  39317. this.texture.frame.resize(width, height);
  39318. this.texture.setFrame(this.texture.frame);
  39319. },
  39320. /**
  39321. * Resets the texture frame dimensions that the Game Object uses for rendering.
  39322. *
  39323. * @method
  39324. */
  39325. resetFrame: function () {
  39326. if (this._frame)
  39327. {
  39328. this.setFrame(this._frame);
  39329. }
  39330. },
  39331. /**
  39332. * Gets or sets the current frame index of the texture being used to render this Game Object.
  39333. *
  39334. * To change the frame set `frame` to the index of the new frame in the sprite sheet you wish this Game Object to use,
  39335. * for example: `player.frame = 4`.
  39336. *
  39337. * If the frame index given doesn't exist it will revert to the first frame found in the texture.
  39338. *
  39339. * If you are using a texture atlas then you should use the `frameName` property instead.
  39340. *
  39341. * If you wish to fully replace the texture being used see `loadTexture`.
  39342. * @property {integer} frame
  39343. */
  39344. frame: {
  39345. get: function () {
  39346. return this.animations.frame;
  39347. },
  39348. set: function (value) {
  39349. this.animations.frame = value;
  39350. }
  39351. },
  39352. /**
  39353. * Gets or sets the current frame name of the texture being used to render this Game Object.
  39354. *
  39355. * To change the frame set `frameName` to the name of the new frame in the texture atlas you wish this Game Object to use,
  39356. * for example: `player.frameName = "idle"`.
  39357. *
  39358. * If the frame name given doesn't exist it will revert to the first frame found in the texture and throw a console warning.
  39359. *
  39360. * If you are using a sprite sheet then you should use the `frame` property instead.
  39361. *
  39362. * If you wish to fully replace the texture being used see `loadTexture`.
  39363. * @property {string} frameName
  39364. */
  39365. frameName: {
  39366. get: function () {
  39367. return this.animations.frameName;
  39368. },
  39369. set: function (value) {
  39370. this.animations.frameName = value;
  39371. }
  39372. }
  39373. };
  39374. /**
  39375. * @author Richard Davey <rich@photonstorm.com>
  39376. * @copyright 2016 Photon Storm Ltd.
  39377. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  39378. */
  39379. /**
  39380. * The Overlap component allows a Game Object to check if it overlaps with the bounds of another Game Object.
  39381. *
  39382. * @class
  39383. */
  39384. Phaser.Component.Overlap = function () {};
  39385. Phaser.Component.Overlap.prototype = {
  39386. /**
  39387. * Checks to see if the bounds of this Game Object overlaps with the bounds of the given Display Object,
  39388. * which can be a Sprite, Image, TileSprite or anything that extends those such as Button or provides a `getBounds` method and result.
  39389. *
  39390. * This check ignores the `hitArea` property if set and runs a `getBounds` comparison on both objects to determine the result.
  39391. *
  39392. * Therefore it's relatively expensive to use in large quantities, i.e. with lots of Sprites at a high frequency.
  39393. * It should be fine for low-volume testing where physics isn't required.
  39394. *
  39395. * @method
  39396. * @param {Phaser.Sprite|Phaser.Image|Phaser.TileSprite|Phaser.Button|PIXI.DisplayObject} displayObject - The display object to check against.
  39397. * @return {boolean} True if the bounds of this Game Object intersects at any point with the bounds of the given display object.
  39398. */
  39399. overlap: function (displayObject) {
  39400. return Phaser.Rectangle.intersects(this.getBounds(), displayObject.getBounds());
  39401. }
  39402. };
  39403. /**
  39404. * @author Richard Davey <rich@photonstorm.com>
  39405. * @copyright 2016 Photon Storm Ltd.
  39406. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  39407. */
  39408. /**
  39409. * The PhysicsBody component manages the Game Objects physics body and physics enabling.
  39410. * It also overrides the x and y properties, ensuring that any manual adjustment of them is reflected in the physics body itself.
  39411. *
  39412. * @class
  39413. */
  39414. Phaser.Component.PhysicsBody = function () {};
  39415. /**
  39416. * The PhysicsBody component preUpdate handler.
  39417. * Called automatically by the Game Object.
  39418. *
  39419. * @method
  39420. */
  39421. Phaser.Component.PhysicsBody.preUpdate = function () {
  39422. if (this.fresh && this.exists)
  39423. {
  39424. this.world.setTo(this.parent.position.x + this.position.x, this.parent.position.y + this.position.y);
  39425. this.worldTransform.tx = this.world.x;
  39426. this.worldTransform.ty = this.world.y;
  39427. this.previousPosition.set(this.world.x, this.world.y);
  39428. this.previousRotation = this.rotation;
  39429. if (this.body)
  39430. {
  39431. this.body.preUpdate();
  39432. }
  39433. this.fresh = false;
  39434. return false;
  39435. }
  39436. this.previousPosition.set(this.world.x, this.world.y);
  39437. this.previousRotation = this.rotation;
  39438. if (!this._exists || !this.parent.exists)
  39439. {
  39440. this.renderOrderID = -1;
  39441. return false;
  39442. }
  39443. return true;
  39444. };
  39445. /**
  39446. * The PhysicsBody component postUpdate handler.
  39447. * Called automatically by the Game Object.
  39448. *
  39449. * @method
  39450. */
  39451. Phaser.Component.PhysicsBody.postUpdate = function () {
  39452. if (this.exists && this.body)
  39453. {
  39454. this.body.postUpdate();
  39455. }
  39456. };
  39457. Phaser.Component.PhysicsBody.prototype = {
  39458. /**
  39459. * `body` is the Game Objects physics body. Once a Game Object is enabled for physics you access all associated
  39460. * properties and methods via it.
  39461. *
  39462. * By default Game Objects won't add themselves to any physics system and their `body` property will be `null`.
  39463. *
  39464. * To enable this Game Object for physics you need to call `game.physics.enable(object, system)` where `object` is this object
  39465. * and `system` is the Physics system you are using. If none is given it defaults to `Phaser.Physics.Arcade`.
  39466. *
  39467. * You can alternatively call `game.physics.arcade.enable(object)`, or add this Game Object to a physics enabled Group.
  39468. *
  39469. * Important: Enabling a Game Object for P2 or Ninja physics will automatically set its `anchor` property to 0.5,
  39470. * so the physics body is centered on the Game Object.
  39471. *
  39472. * If you need a different result then adjust or re-create the Body shape offsets manually or reset the anchor after enabling physics.
  39473. *
  39474. * @property {Phaser.Physics.Arcade.Body|Phaser.Physics.P2.Body|Phaser.Physics.Ninja.Body|null} body
  39475. * @default
  39476. */
  39477. body: null,
  39478. /**
  39479. * The position of the Game Object on the x axis relative to the local coordinates of the parent.
  39480. *
  39481. * @property {number} x
  39482. */
  39483. x: {
  39484. get: function () {
  39485. return this.position.x;
  39486. },
  39487. set: function (value) {
  39488. this.position.x = value;
  39489. if (this.body && !this.body.dirty)
  39490. {
  39491. this.body._reset = true;
  39492. }
  39493. }
  39494. },
  39495. /**
  39496. * The position of the Game Object on the y axis relative to the local coordinates of the parent.
  39497. *
  39498. * @property {number} y
  39499. */
  39500. y: {
  39501. get: function () {
  39502. return this.position.y;
  39503. },
  39504. set: function (value) {
  39505. this.position.y = value;
  39506. if (this.body && !this.body.dirty)
  39507. {
  39508. this.body._reset = true;
  39509. }
  39510. }
  39511. }
  39512. };
  39513. /**
  39514. * @author Richard Davey <rich@photonstorm.com>
  39515. * @copyright 2016 Photon Storm Ltd.
  39516. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  39517. */
  39518. /**
  39519. * The Reset component allows a Game Object to be reset and repositioned to a new location.
  39520. *
  39521. * @class
  39522. */
  39523. Phaser.Component.Reset = function () {};
  39524. /**
  39525. * Resets the Game Object.
  39526. *
  39527. * This moves the Game Object to the given x/y world coordinates and sets `fresh`, `exists`,
  39528. * `visible` and `renderable` to true.
  39529. *
  39530. * If this Game Object has the LifeSpan component it will also set `alive` to true and `health` to the given value.
  39531. *
  39532. * If this Game Object has a Physics Body it will reset the Body.
  39533. *
  39534. * @method
  39535. * @param {number} x - The x coordinate (in world space) to position the Game Object at.
  39536. * @param {number} y - The y coordinate (in world space) to position the Game Object at.
  39537. * @param {number} [health=1] - The health to give the Game Object if it has the Health component.
  39538. * @return {PIXI.DisplayObject} This instance.
  39539. */
  39540. Phaser.Component.Reset.prototype.reset = function (x, y, health) {
  39541. if (health === undefined) { health = 1; }
  39542. this.world.set(x, y);
  39543. this.position.set(x, y);
  39544. this.fresh = true;
  39545. this.exists = true;
  39546. this.visible = true;
  39547. this.renderable = true;
  39548. if (this.components.InWorld)
  39549. {
  39550. this._outOfBoundsFired = false;
  39551. }
  39552. if (this.components.LifeSpan)
  39553. {
  39554. this.alive = true;
  39555. this.health = health;
  39556. }
  39557. if (this.components.PhysicsBody)
  39558. {
  39559. if (this.body)
  39560. {
  39561. this.body.reset(x, y, false, false);
  39562. }
  39563. }
  39564. return this;
  39565. };
  39566. /**
  39567. * @author Richard Davey <rich@photonstorm.com>
  39568. * @copyright 2016 Photon Storm Ltd.
  39569. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  39570. */
  39571. /**
  39572. * The ScaleMinMax component allows a Game Object to limit how far it can be scaled by its parent.
  39573. *
  39574. * @class
  39575. */
  39576. Phaser.Component.ScaleMinMax = function () {};
  39577. Phaser.Component.ScaleMinMax.prototype = {
  39578. /**
  39579. * The callback that will apply any scale limiting to the worldTransform.
  39580. * @property {function} transformCallback
  39581. */
  39582. transformCallback: null,
  39583. /**
  39584. * The context under which `transformCallback` is called.
  39585. * @property {object} transformCallbackContext
  39586. */
  39587. transformCallbackContext: this,
  39588. /**
  39589. * The minimum scale this Game Object will scale down to.
  39590. *
  39591. * It allows you to prevent a parent from scaling this Game Object lower than the given value.
  39592. *
  39593. * Set it to `null` to remove the limit.
  39594. * @property {Phaser.Point} scaleMin
  39595. */
  39596. scaleMin: null,
  39597. /**
  39598. * The maximum scale this Game Object will scale up to.
  39599. *
  39600. * It allows you to prevent a parent from scaling this Game Object higher than the given value.
  39601. *
  39602. * Set it to `null` to remove the limit.
  39603. * @property {Phaser.Point} scaleMax
  39604. */
  39605. scaleMax: null,
  39606. /**
  39607. * Adjust scaling limits, if set, to this Game Object.
  39608. *
  39609. * @method
  39610. * @private
  39611. * @param {PIXI.Matrix} wt - The updated worldTransform matrix.
  39612. */
  39613. checkTransform: function (wt) {
  39614. if (this.scaleMin)
  39615. {
  39616. if (wt.a < this.scaleMin.x)
  39617. {
  39618. wt.a = this.scaleMin.x;
  39619. }
  39620. if (wt.d < this.scaleMin.y)
  39621. {
  39622. wt.d = this.scaleMin.y;
  39623. }
  39624. }
  39625. if (this.scaleMax)
  39626. {
  39627. if (wt.a > this.scaleMax.x)
  39628. {
  39629. wt.a = this.scaleMax.x;
  39630. }
  39631. if (wt.d > this.scaleMax.y)
  39632. {
  39633. wt.d = this.scaleMax.y;
  39634. }
  39635. }
  39636. },
  39637. /**
  39638. * Sets the scaleMin and scaleMax values. These values are used to limit how far this Game Object will scale based on its parent.
  39639. *
  39640. * For example if this Game Object has a `minScale` value of 1 and its parent has a `scale` value of 0.5, the 0.5 will be ignored
  39641. * and the scale value of 1 will be used, as the parents scale is lower than the minimum scale this Game Object should adhere to.
  39642. *
  39643. * By setting these values you can carefully control how Game Objects deal with responsive scaling.
  39644. *
  39645. * If only one parameter is given then that value will be used for both scaleMin and scaleMax:
  39646. * `setScaleMinMax(1)` = scaleMin.x, scaleMin.y, scaleMax.x and scaleMax.y all = 1
  39647. *
  39648. * If only two parameters are given the first is set as scaleMin.x and y and the second as scaleMax.x and y:
  39649. * `setScaleMinMax(0.5, 2)` = scaleMin.x and y = 0.5 and scaleMax.x and y = 2
  39650. *
  39651. * If you wish to set `scaleMin` with different values for x and y then either modify Game Object.scaleMin directly,
  39652. * or pass `null` for the `maxX` and `maxY` parameters.
  39653. *
  39654. * Call `setScaleMinMax(null)` to clear all previously set values.
  39655. *
  39656. * @method
  39657. * @param {number|null} minX - The minimum horizontal scale value this Game Object can scale down to.
  39658. * @param {number|null} minY - The minimum vertical scale value this Game Object can scale down to.
  39659. * @param {number|null} maxX - The maximum horizontal scale value this Game Object can scale up to.
  39660. * @param {number|null} maxY - The maximum vertical scale value this Game Object can scale up to.
  39661. */
  39662. setScaleMinMax: function (minX, minY, maxX, maxY) {
  39663. if (minY === undefined)
  39664. {
  39665. // 1 parameter, set all to it
  39666. minY = maxX = maxY = minX;
  39667. }
  39668. else if (maxX === undefined)
  39669. {
  39670. // 2 parameters, the first is min, the second max
  39671. maxX = maxY = minY;
  39672. minY = minX;
  39673. }
  39674. if (minX === null)
  39675. {
  39676. this.scaleMin = null;
  39677. }
  39678. else
  39679. {
  39680. if (this.scaleMin)
  39681. {
  39682. this.scaleMin.set(minX, minY);
  39683. }
  39684. else
  39685. {
  39686. this.scaleMin = new Phaser.Point(minX, minY);
  39687. }
  39688. }
  39689. if (maxX === null)
  39690. {
  39691. this.scaleMax = null;
  39692. }
  39693. else
  39694. {
  39695. if (this.scaleMax)
  39696. {
  39697. this.scaleMax.set(maxX, maxY);
  39698. }
  39699. else
  39700. {
  39701. this.scaleMax = new Phaser.Point(maxX, maxY);
  39702. }
  39703. }
  39704. if (this.scaleMin === null)
  39705. {
  39706. this.transformCallback = null;
  39707. }
  39708. else
  39709. {
  39710. this.transformCallback = this.checkTransform;
  39711. this.transformCallbackContext = this;
  39712. }
  39713. }
  39714. };
  39715. /**
  39716. * @author Richard Davey <rich@photonstorm.com>
  39717. * @copyright 2016 Photon Storm Ltd.
  39718. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  39719. */
  39720. /**
  39721. * The Smoothed component allows a Game Object to control anti-aliasing of an image based texture.
  39722. *
  39723. * @class
  39724. */
  39725. Phaser.Component.Smoothed = function () {};
  39726. Phaser.Component.Smoothed.prototype = {
  39727. /**
  39728. * Enable or disable texture smoothing for this Game Object.
  39729. *
  39730. * It only takes effect if the Game Object is using an image based texture.
  39731. *
  39732. * Smoothing is enabled by default.
  39733. *
  39734. * @property {boolean} smoothed
  39735. */
  39736. smoothed: {
  39737. get: function () {
  39738. return !this.texture.baseTexture.scaleMode;
  39739. },
  39740. set: function (value) {
  39741. if (value)
  39742. {
  39743. if (this.texture)
  39744. {
  39745. this.texture.baseTexture.scaleMode = 0;
  39746. }
  39747. }
  39748. else
  39749. {
  39750. if (this.texture)
  39751. {
  39752. this.texture.baseTexture.scaleMode = 1;
  39753. }
  39754. }
  39755. }
  39756. }
  39757. };
  39758. /**
  39759. * @author Richard Davey <rich@photonstorm.com>
  39760. * @copyright 2016 Photon Storm Ltd.
  39761. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  39762. */
  39763. /**
  39764. * The GameObjectFactory is a quick way to create many common game objects
  39765. * using {@linkcode Phaser.Game#add `game.add`}.
  39766. *
  39767. * Created objects are _automatically added_ to the appropriate Manager, World, or manually specified parent Group.
  39768. *
  39769. * @class Phaser.GameObjectFactory
  39770. * @constructor
  39771. * @param {Phaser.Game} game - A reference to the currently running game.
  39772. */
  39773. Phaser.GameObjectFactory = function (game) {
  39774. /**
  39775. * @property {Phaser.Game} game - A reference to the currently running Game.
  39776. * @protected
  39777. */
  39778. this.game = game;
  39779. /**
  39780. * @property {Phaser.World} world - A reference to the game world.
  39781. * @protected
  39782. */
  39783. this.world = this.game.world;
  39784. };
  39785. Phaser.GameObjectFactory.prototype = {
  39786. /**
  39787. * Adds an existing display object to the game world.
  39788. *
  39789. * @method Phaser.GameObjectFactory#existing
  39790. * @param {any} object - An instance of Phaser.Sprite, Phaser.Button or any other display object.
  39791. * @return {any} The child that was added to the World.
  39792. */
  39793. existing: function (object) {
  39794. return this.world.add(object);
  39795. },
  39796. /**
  39797. * Weapons provide the ability to easily create a bullet pool and manager.
  39798. *
  39799. * Weapons fire Phaser.Bullet objects, which are essentially Sprites with a few extra properties.
  39800. * The Bullets are enabled for Arcade Physics. They do not currently work with P2 Physics.
  39801. *
  39802. * The Bullets are created inside of `Weapon.bullets`, which is a Phaser.Group instance. Anything you
  39803. * can usually do with a Group, such as move it around the display list, iterate it, etc can be done
  39804. * to the bullets Group too.
  39805. *
  39806. * Bullets can have textures and even animations. You can control the speed at which they are fired,
  39807. * the firing rate, the firing angle, and even set things like gravity for them.
  39808. *
  39809. * @method Phaser.GameObjectFactory#weapon
  39810. * @param {integer} [quantity=1] - The quantity of bullets to seed the Weapon with. If -1 it will set the pool to automatically expand.
  39811. * @param {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|PIXI.Texture} [key] - The image used as a texture by the bullets during rendering. If a string Phaser will get for an entry in the Image Cache. Or it can be an instance of a RenderTexture, BitmapData, Video or PIXI.Texture.
  39812. * @param {string|number} [frame] - If a Texture Atlas or Sprite Sheet is used this allows you to specify the frame to be used by the bullets. Use either an integer for a Frame ID or a string for a frame name.
  39813. * @param {Phaser.Group} [group] - Optional Group to add the Weapon to. If not specified it will be added to the World group.
  39814. * @returns {Phaser.Weapon} A Weapon instance.
  39815. */
  39816. weapon: function (quantity, key, frame, group) {
  39817. var weapon = this.game.plugins.add(Phaser.Weapon);
  39818. weapon.createBullets(quantity, key, frame, group);
  39819. return weapon;
  39820. },
  39821. /**
  39822. * Create a new `Image` object.
  39823. *
  39824. * An Image is a light-weight object you can use to display anything that doesn't need physics or animation.
  39825. *
  39826. * It can still rotate, scale, crop and receive input events.
  39827. * This makes it perfect for logos, backgrounds, simple buttons and other non-Sprite graphics.
  39828. *
  39829. * @method Phaser.GameObjectFactory#image
  39830. * @param {number} [x=0] - The x coordinate of the Image. The coordinate is relative to any parent container this Image may be in.
  39831. * @param {number} [y=0] - The y coordinate of the Image. The coordinate is relative to any parent container this Image may be in.
  39832. * @param {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|PIXI.Texture} [key] - The image used as a texture by this display object during rendering. If a string Phaser will get for an entry in the Image Cache. Or it can be an instance of a RenderTexture, BitmapData, Video or PIXI.Texture.
  39833. * @param {string|number} [frame] - If a Texture Atlas or Sprite Sheet is used this allows you to specify the frame to be used. Use either an integer for a Frame ID or a string for a frame name.
  39834. * @param {Phaser.Group} [group] - Optional Group to add the object to. If not specified it will be added to the World group.
  39835. * @returns {Phaser.Image} The newly created Image object.
  39836. */
  39837. image: function (x, y, key, frame, group) {
  39838. if (group === undefined) { group = this.world; }
  39839. return group.add(new Phaser.Image(this.game, x, y, key, frame));
  39840. },
  39841. /**
  39842. * Create a new Sprite with specific position and sprite sheet key.
  39843. *
  39844. * At its most basic a Sprite consists of a set of coordinates and a texture that is used when rendered.
  39845. * They also contain additional properties allowing for physics motion (via Sprite.body), input handling (via Sprite.input),
  39846. * events (via Sprite.events), animation (via Sprite.animations), camera culling and more. Please see the Examples for use cases.
  39847. *
  39848. * @method Phaser.GameObjectFactory#sprite
  39849. * @param {number} [x=0] - The x coordinate of the sprite. The coordinate is relative to any parent container this sprite may be in.
  39850. * @param {number} [y=0] - The y coordinate of the sprite. The coordinate is relative to any parent container this sprite may be in.
  39851. * @param {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|PIXI.Texture} [key] - The image used as a texture by this display object during rendering. If a string Phaser will get for an entry in the Image Cache. Or it can be an instance of a RenderTexture, BitmapData, Video or PIXI.Texture.
  39852. * @param {string|number} [frame] - If a Texture Atlas or Sprite Sheet is used this allows you to specify the frame to be used. Use either an integer for a Frame ID or a string for a frame name.
  39853. * @param {Phaser.Group} [group] - Optional Group to add the object to. If not specified it will be added to the World group.
  39854. * @returns {Phaser.Sprite} The newly created Sprite object.
  39855. */
  39856. sprite: function (x, y, key, frame, group) {
  39857. if (group === undefined) { group = this.world; }
  39858. return group.create(x, y, key, frame);
  39859. },
  39860. /**
  39861. * Create a new Creature Animation object.
  39862. *
  39863. * Creature is a custom Game Object used in conjunction with the Creature Runtime libraries by Kestrel Moon Studios.
  39864. *
  39865. * It allows you to display animated Game Objects that were created with the [Creature Automated Animation Tool](http://www.kestrelmoon.com/creature/).
  39866. *
  39867. * Note 1: You can only use Phaser.Creature objects in WebGL enabled games. They do not work in Canvas mode games.
  39868. *
  39869. * Note 2: You must use a build of Phaser that includes the CreatureMeshBone.js runtime and gl-matrix.js, or have them
  39870. * loaded before your Phaser game boots.
  39871. *
  39872. * See the Phaser custom build process for more details.
  39873. *
  39874. * @method Phaser.GameObjectFactory#creature
  39875. * @param {number} [x=0] - The x coordinate of the creature. The coordinate is relative to any parent container this creature may be in.
  39876. * @param {number} [y=0] - The y coordinate of the creature. The coordinate is relative to any parent container this creature may be in.
  39877. * @param {string|PIXI.Texture} [key] - The image used as a texture by this creature object during rendering. If a string Phaser will get for an entry in the Image Cache. Or it can be an instance of a PIXI.Texture.
  39878. * @param {Phaser.Group} [group] - Optional Group to add the object to. If not specified it will be added to the World group.
  39879. * @returns {Phaser.Creature} The newly created Sprite object.
  39880. */
  39881. creature: function (x, y, key, mesh, group) {
  39882. if (group === undefined) { group = this.world; }
  39883. var obj = new Phaser.Creature(this.game, x, y, key, mesh);
  39884. group.add(obj);
  39885. return obj;
  39886. },
  39887. /**
  39888. * Create a tween on a specific object.
  39889. *
  39890. * The object can be any JavaScript object or Phaser object such as Sprite.
  39891. *
  39892. * @method Phaser.GameObjectFactory#tween
  39893. * @param {object} object - Object the tween will be run on.
  39894. * @return {Phaser.Tween} The newly created Phaser.Tween object.
  39895. */
  39896. tween: function (object) {
  39897. return this.game.tweens.create(object);
  39898. },
  39899. /**
  39900. * A Group is a container for display objects that allows for fast pooling, recycling and collision checks.
  39901. *
  39902. * @method Phaser.GameObjectFactory#group
  39903. * @param {any} [parent] - The parent Group or DisplayObjectContainer that will hold this group, if any. If set to null the Group won't be added to the display list. If undefined it will be added to World by default.
  39904. * @param {string} [name='group'] - A name for this Group. Not used internally but useful for debugging.
  39905. * @param {boolean} [addToStage=false] - If set to true this Group will be added directly to the Game.Stage instead of Game.World.
  39906. * @param {boolean} [enableBody=false] - If true all Sprites created with `Group.create` or `Group.createMulitple` will have a physics body created on them. Change the body type with physicsBodyType.
  39907. * @param {number} [physicsBodyType=0] - If enableBody is true this is the type of physics body that is created on new Sprites. Phaser.Physics.ARCADE, Phaser.Physics.P2, Phaser.Physics.NINJA, etc.
  39908. * @return {Phaser.Group} The newly created Group.
  39909. */
  39910. group: function (parent, name, addToStage, enableBody, physicsBodyType) {
  39911. return new Phaser.Group(this.game, parent, name, addToStage, enableBody, physicsBodyType);
  39912. },
  39913. /**
  39914. * A Group is a container for display objects that allows for fast pooling, recycling and collision checks.
  39915. *
  39916. * A Physics Group is the same as an ordinary Group except that is has enableBody turned on by default, so any Sprites it creates
  39917. * are automatically given a physics body.
  39918. *
  39919. * @method Phaser.GameObjectFactory#physicsGroup
  39920. * @param {number} [physicsBodyType=Phaser.Physics.ARCADE] - If enableBody is true this is the type of physics body that is created on new Sprites. Phaser.Physics.ARCADE, Phaser.Physics.P2JS, Phaser.Physics.NINJA, etc.
  39921. * @param {any} [parent] - The parent Group or DisplayObjectContainer that will hold this group, if any. If set to null the Group won't be added to the display list. If undefined it will be added to World by default.
  39922. * @param {string} [name='group'] - A name for this Group. Not used internally but useful for debugging.
  39923. * @param {boolean} [addToStage=false] - If set to true this Group will be added directly to the Game.Stage instead of Game.World.
  39924. * @return {Phaser.Group} The newly created Group.
  39925. */
  39926. physicsGroup: function (physicsBodyType, parent, name, addToStage) {
  39927. return new Phaser.Group(this.game, parent, name, addToStage, true, physicsBodyType);
  39928. },
  39929. /**
  39930. * A SpriteBatch is a really fast version of a Phaser Group built solely for speed.
  39931. * Use when you need a lot of sprites or particles all sharing the same texture.
  39932. * The speed gains are specifically for WebGL. In Canvas mode you won't see any real difference.
  39933. *
  39934. * @method Phaser.GameObjectFactory#spriteBatch
  39935. * @param {Phaser.Group|null} parent - The parent Group that will hold this Sprite Batch. Set to `undefined` or `null` to add directly to game.world.
  39936. * @param {string} [name='group'] - A name for this Sprite Batch. Not used internally but useful for debugging.
  39937. * @param {boolean} [addToStage=false] - If set to true this Sprite Batch will be added directly to the Game.Stage instead of the parent.
  39938. * @return {Phaser.SpriteBatch} The newly created Sprite Batch.
  39939. */
  39940. spriteBatch: function (parent, name, addToStage) {
  39941. if (parent === undefined) { parent = null; }
  39942. if (name === undefined) { name = 'group'; }
  39943. if (addToStage === undefined) { addToStage = false; }
  39944. return new Phaser.SpriteBatch(this.game, parent, name, addToStage);
  39945. },
  39946. /**
  39947. * Creates a new Sound object.
  39948. *
  39949. * @method Phaser.GameObjectFactory#audio
  39950. * @param {string} key - The Game.cache key of the sound that this object will use.
  39951. * @param {number} [volume=1] - The volume at which the sound will be played.
  39952. * @param {boolean} [loop=false] - Whether or not the sound will loop.
  39953. * @param {boolean} [connect=true] - Controls if the created Sound object will connect to the master gainNode of the SoundManager when running under WebAudio.
  39954. * @return {Phaser.Sound} The newly created sound object.
  39955. */
  39956. audio: function (key, volume, loop, connect) {
  39957. return this.game.sound.add(key, volume, loop, connect);
  39958. },
  39959. /**
  39960. * Creates a new Sound object.
  39961. *
  39962. * @method Phaser.GameObjectFactory#sound
  39963. * @param {string} key - The Game.cache key of the sound that this object will use.
  39964. * @param {number} [volume=1] - The volume at which the sound will be played.
  39965. * @param {boolean} [loop=false] - Whether or not the sound will loop.
  39966. * @param {boolean} [connect=true] - Controls if the created Sound object will connect to the master gainNode of the SoundManager when running under WebAudio.
  39967. * @return {Phaser.Sound} The newly created sound object.
  39968. */
  39969. sound: function (key, volume, loop, connect) {
  39970. return this.game.sound.add(key, volume, loop, connect);
  39971. },
  39972. /**
  39973. * Creates a new AudioSprite object.
  39974. *
  39975. * @method Phaser.GameObjectFactory#audioSprite
  39976. * @param {string} key - The Game.cache key of the sound that this object will use.
  39977. * @return {Phaser.AudioSprite} The newly created AudioSprite object.
  39978. */
  39979. audioSprite: function (key) {
  39980. return this.game.sound.addSprite(key);
  39981. },
  39982. /**
  39983. * Creates a new TileSprite object.
  39984. *
  39985. * @method Phaser.GameObjectFactory#tileSprite
  39986. * @param {number} x - The x coordinate of the TileSprite. The coordinate is relative to any parent container this TileSprite may be in.
  39987. * @param {number} y - The y coordinate of the TileSprite. The coordinate is relative to any parent container this TileSprite may be in.
  39988. * @param {number} width - The width of the TileSprite.
  39989. * @param {number} height - The height of the TileSprite.
  39990. * @param {string|Phaser.BitmapData|PIXI.Texture} key - This is the image or texture used by the TileSprite during rendering. It can be a string which is a reference to the Phaser Image Cache entry, or an instance of a PIXI.Texture or BitmapData.
  39991. * @param {string|number} [frame] - If a Texture Atlas or Sprite Sheet is used this allows you to specify the frame to be used. Use either an integer for a Frame ID or a string for a frame name.
  39992. * @param {Phaser.Group} [group] - Optional Group to add the object to. If not specified it will be added to the World group.
  39993. * @return {Phaser.TileSprite} The newly created TileSprite object.
  39994. */
  39995. tileSprite: function (x, y, width, height, key, frame, group) {
  39996. if (group === undefined) { group = this.world; }
  39997. return group.add(new Phaser.TileSprite(this.game, x, y, width, height, key, frame));
  39998. },
  39999. /**
  40000. * Creates a new Rope object.
  40001. *
  40002. * Example usage: https://github.com/codevinsky/phaser-rope-demo/blob/master/dist/demo.js
  40003. *
  40004. * @method Phaser.GameObjectFactory#rope
  40005. * @param {number} [x=0] - The x coordinate of the Rope. The coordinate is relative to any parent container this rope may be in.
  40006. * @param {number} [y=0] - The y coordinate of the Rope. The coordinate is relative to any parent container this rope may be in.
  40007. * @param {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|PIXI.Texture} [key] - The image used as a texture by this display object during rendering. If a string Phaser will get for an entry in the Image Cache. Or it can be an instance of a RenderTexture, BitmapData, Video or PIXI.Texture.
  40008. * @param {string|number} [frame] - If a Texture Atlas or Sprite Sheet is used this allows you to specify the frame to be used. Use either an integer for a Frame ID or a string for a frame name.
  40009. * @param {Array} points - An array of {Phaser.Point}.
  40010. * @param {Phaser.Group} [group] - Optional Group to add the object to. If not specified it will be added to the World group.
  40011. * @return {Phaser.Rope} The newly created Rope object.
  40012. */
  40013. rope: function (x, y, key, frame, points, group) {
  40014. if (group === undefined) { group = this.world; }
  40015. return group.add(new Phaser.Rope(this.game, x, y, key, frame, points));
  40016. },
  40017. /**
  40018. * Creates a new Text object.
  40019. *
  40020. * @method Phaser.GameObjectFactory#text
  40021. * @param {number} [x=0] - The x coordinate of the Text. The coordinate is relative to any parent container this text may be in.
  40022. * @param {number} [y=0] - The y coordinate of the Text. The coordinate is relative to any parent container this text may be in.
  40023. * @param {string} [text=''] - The text string that will be displayed.
  40024. * @param {object} [style] - The style object containing style attributes like font, font size , etc.
  40025. * @param {Phaser.Group} [group] - Optional Group to add the object to. If not specified it will be added to the World group.
  40026. * @return {Phaser.Text} The newly created text object.
  40027. */
  40028. text: function (x, y, text, style, group) {
  40029. if (group === undefined) { group = this.world; }
  40030. return group.add(new Phaser.Text(this.game, x, y, text, style));
  40031. },
  40032. /**
  40033. * Creates a new Button object.
  40034. *
  40035. * @method Phaser.GameObjectFactory#button
  40036. * @param {number} [x=0] - The x coordinate of the Button. The coordinate is relative to any parent container this button may be in.
  40037. * @param {number} [y=0] - The y coordinate of the Button. The coordinate is relative to any parent container this button may be in.
  40038. * @param {string} [key] - The image key as defined in the Game.Cache to use as the texture for this button.
  40039. * @param {function} [callback] - The function to call when this button is pressed
  40040. * @param {object} [callbackContext] - The context in which the callback will be called (usually 'this')
  40041. * @param {string|number} [overFrame] - This is the frame or frameName that will be set when this button is in an over state. Give either a number to use a frame ID or a string for a frame name.
  40042. * @param {string|number} [outFrame] - This is the frame or frameName that will be set when this button is in an out state. Give either a number to use a frame ID or a string for a frame name.
  40043. * @param {string|number} [downFrame] - This is the frame or frameName that will be set when this button is in a down state. Give either a number to use a frame ID or a string for a frame name.
  40044. * @param {string|number} [upFrame] - This is the frame or frameName that will be set when this button is in an up state. Give either a number to use a frame ID or a string for a frame name.
  40045. * @param {Phaser.Group} [group] - Optional Group to add the object to. If not specified it will be added to the World group.
  40046. * @return {Phaser.Button} The newly created Button object.
  40047. */
  40048. button: function (x, y, key, callback, callbackContext, overFrame, outFrame, downFrame, upFrame, group) {
  40049. if (group === undefined) { group = this.world; }
  40050. return group.add(new Phaser.Button(this.game, x, y, key, callback, callbackContext, overFrame, outFrame, downFrame, upFrame));
  40051. },
  40052. /**
  40053. * Creates a new Graphics object.
  40054. *
  40055. * @method Phaser.GameObjectFactory#graphics
  40056. * @param {number} [x=0] - The x coordinate of the Graphic. The coordinate is relative to any parent container this object may be in.
  40057. * @param {number} [y=0] - The y coordinate of the Graphic. The coordinate is relative to any parent container this object may be in.
  40058. * @param {Phaser.Group} [group] - Optional Group to add the object to. If not specified it will be added to the World group.
  40059. * @return {Phaser.Graphics} The newly created graphics object.
  40060. */
  40061. graphics: function (x, y, group) {
  40062. if (group === undefined) { group = this.world; }
  40063. return group.add(new Phaser.Graphics(this.game, x, y));
  40064. },
  40065. /**
  40066. * Create a new Emitter.
  40067. *
  40068. * A particle emitter can be used for one-time explosions or for
  40069. * continuous effects like rain and fire. All it really does is launch Particle objects out
  40070. * at set intervals, and fixes their positions and velocities accordingly.
  40071. *
  40072. * @method Phaser.GameObjectFactory#emitter
  40073. * @param {number} [x=0] - The x coordinate within the Emitter that the particles are emitted from.
  40074. * @param {number} [y=0] - The y coordinate within the Emitter that the particles are emitted from.
  40075. * @param {number} [maxParticles=50] - The total number of particles in this emitter.
  40076. * @return {Phaser.Particles.Arcade.Emitter} The newly created emitter object.
  40077. */
  40078. emitter: function (x, y, maxParticles) {
  40079. return this.game.particles.add(new Phaser.Particles.Arcade.Emitter(this.game, x, y, maxParticles));
  40080. },
  40081. /**
  40082. * Create a new RetroFont object.
  40083. *
  40084. * A RetroFont can be used as a texture for an Image or Sprite and optionally add it to the Cache.
  40085. * A RetroFont uses a bitmap which contains fixed with characters for the font set. You use character spacing to define the set.
  40086. * If you need variable width character support then use a BitmapText object instead. The main difference between a RetroFont and a BitmapText
  40087. * is that a RetroFont creates a single texture that you can apply to a game object, where-as a BitmapText creates one Sprite object per letter of text.
  40088. * The texture can be asssigned or one or multiple images/sprites, but note that the text the RetroFont uses will be shared across them all,
  40089. * i.e. if you need each Image to have different text in it, then you need to create multiple RetroFont objects.
  40090. *
  40091. * @method Phaser.GameObjectFactory#retroFont
  40092. * @param {string} font - The key of the image in the Game.Cache that the RetroFont will use.
  40093. * @param {number} characterWidth - The width of each character in the font set.
  40094. * @param {number} characterHeight - The height of each character in the font set.
  40095. * @param {string} chars - The characters used in the font set, in display order. You can use the TEXT_SET consts for common font set arrangements.
  40096. * @param {number} charsPerRow - The number of characters per row in the font set.
  40097. * @param {number} [xSpacing=0] - If the characters in the font set have horizontal spacing between them set the required amount here.
  40098. * @param {number} [ySpacing=0] - If the characters in the font set have vertical spacing between them set the required amount here.
  40099. * @param {number} [xOffset=0] - If the font set doesn't start at the top left of the given image, specify the X coordinate offset here.
  40100. * @param {number} [yOffset=0] - If the font set doesn't start at the top left of the given image, specify the Y coordinate offset here.
  40101. * @return {Phaser.RetroFont} The newly created RetroFont texture which can be applied to an Image or Sprite.
  40102. */
  40103. retroFont: function (font, characterWidth, characterHeight, chars, charsPerRow, xSpacing, ySpacing, xOffset, yOffset) {
  40104. return new Phaser.RetroFont(this.game, font, characterWidth, characterHeight, chars, charsPerRow, xSpacing, ySpacing, xOffset, yOffset);
  40105. },
  40106. /**
  40107. * Create a new BitmapText object.
  40108. *
  40109. * BitmapText objects work by taking a texture file and an XML file that describes the font structure.
  40110. * It then generates a new Sprite object for each letter of the text, proportionally spaced out and aligned to
  40111. * match the font structure.
  40112. *
  40113. * BitmapText objects are less flexible than Text objects, in that they have less features such as shadows, fills and the ability
  40114. * to use Web Fonts. However you trade this flexibility for pure rendering speed. You can also create visually compelling BitmapTexts by
  40115. * processing the font texture in an image editor first, applying fills and any other effects required.
  40116. *
  40117. * To create multi-line text insert \r, \n or \r\n escape codes into the text string.
  40118. *
  40119. * To create a BitmapText data files you can use:
  40120. *
  40121. * BMFont (Windows, free): http://www.angelcode.com/products/bmfont/
  40122. * Glyph Designer (OS X, commercial): http://www.71squared.com/en/glyphdesigner
  40123. * Littera (Web-based, free): http://kvazars.com/littera/
  40124. *
  40125. * @method Phaser.GameObjectFactory#bitmapText
  40126. * @param {number} x - X coordinate to display the BitmapText object at.
  40127. * @param {number} y - Y coordinate to display the BitmapText object at.
  40128. * @param {string} font - The key of the BitmapText as stored in Phaser.Cache.
  40129. * @param {string} [text=''] - The text that will be rendered. This can also be set later via BitmapText.text.
  40130. * @param {number} [size=32] - The size the font will be rendered at in pixels.
  40131. * @param {Phaser.Group} [group] - Optional Group to add the object to. If not specified it will be added to the World group.
  40132. * @return {Phaser.BitmapText} The newly created bitmapText object.
  40133. */
  40134. bitmapText: function (x, y, font, text, size, group) {
  40135. if (group === undefined) { group = this.world; }
  40136. return group.add(new Phaser.BitmapText(this.game, x, y, font, text, size));
  40137. },
  40138. /**
  40139. * Creates a new Phaser.Tilemap object.
  40140. *
  40141. * The map can either be populated with data from a Tiled JSON file or from a CSV file.
  40142. * To do this pass the Cache key as the first parameter. When using Tiled data you need only provide the key.
  40143. * When using CSV data you must provide the key and the tileWidth and tileHeight parameters.
  40144. * If creating a blank tilemap to be populated later, you can either specify no parameters at all and then use `Tilemap.create` or pass the map and tile dimensions here.
  40145. * Note that all Tilemaps use a base tile size to calculate dimensions from, but that a TilemapLayer may have its own unique tile size that overrides it.
  40146. *
  40147. * @method Phaser.GameObjectFactory#tilemap
  40148. * @param {string} [key] - The key of the tilemap data as stored in the Cache. If you're creating a blank map either leave this parameter out or pass `null`.
  40149. * @param {number} [tileWidth=32] - The pixel width of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data.
  40150. * @param {number} [tileHeight=32] - The pixel height of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data.
  40151. * @param {number} [width=10] - The width of the map in tiles. If this map is created from Tiled or CSV data you don't need to specify this.
  40152. * @param {number} [height=10] - The height of the map in tiles. If this map is created from Tiled or CSV data you don't need to specify this.
  40153. * @return {Phaser.Tilemap} The newly created tilemap object.
  40154. */
  40155. tilemap: function (key, tileWidth, tileHeight, width, height) {
  40156. return new Phaser.Tilemap(this.game, key, tileWidth, tileHeight, width, height);
  40157. },
  40158. /**
  40159. * A dynamic initially blank canvas to which images can be drawn.
  40160. *
  40161. * @method Phaser.GameObjectFactory#renderTexture
  40162. * @param {number} [width=100] - the width of the RenderTexture.
  40163. * @param {number} [height=100] - the height of the RenderTexture.
  40164. * @param {string} [key=''] - Asset key for the RenderTexture when stored in the Cache (see addToCache parameter).
  40165. * @param {boolean} [addToCache=false] - Should this RenderTexture be added to the Game.Cache? If so you can retrieve it with Cache.getTexture(key)
  40166. * @return {Phaser.RenderTexture} The newly created RenderTexture object.
  40167. */
  40168. renderTexture: function (width, height, key, addToCache) {
  40169. if (key === undefined || key === '') { key = this.game.rnd.uuid(); }
  40170. if (addToCache === undefined) { addToCache = false; }
  40171. var texture = new Phaser.RenderTexture(this.game, width, height, key);
  40172. if (addToCache)
  40173. {
  40174. this.game.cache.addRenderTexture(key, texture);
  40175. }
  40176. return texture;
  40177. },
  40178. /**
  40179. * Create a Video object.
  40180. *
  40181. * This will return a Phaser.Video object which you can pass to a Sprite to be used as a texture.
  40182. *
  40183. * @method Phaser.GameObjectFactory#video
  40184. * @param {string|null} [key=null] - The key of the video file in the Phaser.Cache that this Video object will play. Set to `null` or leave undefined if you wish to use a webcam as the source. See `startMediaStream` to start webcam capture.
  40185. * @param {string|null} [url=null] - If the video hasn't been loaded then you can provide a full URL to the file here (make sure to set key to null)
  40186. * @return {Phaser.Video} The newly created Video object.
  40187. */
  40188. video: function (key, url) {
  40189. return new Phaser.Video(this.game, key, url);
  40190. },
  40191. /**
  40192. * Create a BitmapData object.
  40193. *
  40194. * A BitmapData object can be manipulated and drawn to like a traditional Canvas object and used to texture Sprites.
  40195. *
  40196. * @method Phaser.GameObjectFactory#bitmapData
  40197. * @param {number} [width=256] - The width of the BitmapData in pixels.
  40198. * @param {number} [height=256] - The height of the BitmapData in pixels.
  40199. * @param {string} [key=''] - Asset key for the BitmapData when stored in the Cache (see addToCache parameter).
  40200. * @param {boolean} [addToCache=false] - Should this BitmapData be added to the Game.Cache? If so you can retrieve it with Cache.getBitmapData(key)
  40201. * @return {Phaser.BitmapData} The newly created BitmapData object.
  40202. */
  40203. bitmapData: function (width, height, key, addToCache) {
  40204. if (addToCache === undefined) { addToCache = false; }
  40205. if (key === undefined || key === '') { key = this.game.rnd.uuid(); }
  40206. var texture = new Phaser.BitmapData(this.game, key, width, height);
  40207. if (addToCache)
  40208. {
  40209. this.game.cache.addBitmapData(key, texture);
  40210. }
  40211. return texture;
  40212. },
  40213. /**
  40214. * A WebGL shader/filter that can be applied to Sprites.
  40215. *
  40216. * @method Phaser.GameObjectFactory#filter
  40217. * @param {string} filter - The name of the filter you wish to create, for example HueRotate or SineWave.
  40218. * @param {any} - Whatever parameters are needed to be passed to the filter init function.
  40219. * @return {Phaser.Filter} The newly created Phaser.Filter object.
  40220. */
  40221. filter: function (filter) {
  40222. var args = Array.prototype.slice.call(arguments, 1);
  40223. var filter = new Phaser.Filter[filter](this.game);
  40224. filter.init.apply(filter, args);
  40225. return filter;
  40226. },
  40227. /**
  40228. * Add a new Plugin into the PluginManager.
  40229. *
  40230. * The Plugin must have 2 properties: `game` and `parent`. Plugin.game is set to the game reference the PluginManager uses, and parent is set to the PluginManager.
  40231. *
  40232. * @method Phaser.GameObjectFactory#plugin
  40233. * @param {object|Phaser.Plugin} plugin - The Plugin to add into the PluginManager. This can be a function or an existing object.
  40234. * @param {...*} parameter - Additional parameters that will be passed to the Plugin.init method.
  40235. * @return {Phaser.Plugin} The Plugin that was added to the manager.
  40236. */
  40237. plugin: function (plugin) {
  40238. return this.game.plugins.add(plugin);
  40239. }
  40240. };
  40241. Phaser.GameObjectFactory.prototype.constructor = Phaser.GameObjectFactory;
  40242. /**
  40243. * @author Richard Davey <rich@photonstorm.com>
  40244. * @copyright 2016 Photon Storm Ltd.
  40245. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  40246. */
  40247. /**
  40248. * The GameObjectCreator is a quick way to create common game objects _without_ adding them to the game world.
  40249. * The object creator can be accessed with {@linkcode Phaser.Game#make `game.make`}.
  40250. *
  40251. * @class Phaser.GameObjectCreator
  40252. * @constructor
  40253. * @param {Phaser.Game} game - A reference to the currently running game.
  40254. */
  40255. Phaser.GameObjectCreator = function (game) {
  40256. /**
  40257. * @property {Phaser.Game} game - A reference to the currently running Game.
  40258. * @protected
  40259. */
  40260. this.game = game;
  40261. /**
  40262. * @property {Phaser.World} world - A reference to the game world.
  40263. * @protected
  40264. */
  40265. this.world = this.game.world;
  40266. };
  40267. Phaser.GameObjectCreator.prototype = {
  40268. /**
  40269. * Create a new Image object.
  40270. *
  40271. * An Image is a light-weight object you can use to display anything that doesn't need physics or animation.
  40272. * It can still rotate, scale, crop and receive input events. This makes it perfect for logos, backgrounds, simple buttons and other non-Sprite graphics.
  40273. *
  40274. * @method Phaser.GameObjectCreator#image
  40275. * @param {number} x - X position of the image.
  40276. * @param {number} y - Y position of the image.
  40277. * @param {string|Phaser.RenderTexture|PIXI.Texture} key - This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache entry, or an instance of a RenderTexture or PIXI.Texture.
  40278. * @param {string|number} [frame] - If the sprite uses an image from a texture atlas or sprite sheet you can pass the frame here. Either a number for a frame ID or a string for a frame name.
  40279. * @returns {Phaser.Image} the newly created sprite object.
  40280. */
  40281. image: function (x, y, key, frame) {
  40282. return new Phaser.Image(this.game, x, y, key, frame);
  40283. },
  40284. /**
  40285. * Create a new Sprite with specific position and sprite sheet key.
  40286. *
  40287. * @method Phaser.GameObjectCreator#sprite
  40288. * @param {number} x - X position of the new sprite.
  40289. * @param {number} y - Y position of the new sprite.
  40290. * @param {string|Phaser.RenderTexture|PIXI.Texture} key - This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache entry, or an instance of a RenderTexture or PIXI.Texture.
  40291. * @param {string|number} [frame] - If the sprite uses an image from a texture atlas or sprite sheet you can pass the frame here. Either a number for a frame ID or a string for a frame name.
  40292. * @returns {Phaser.Sprite} the newly created sprite object.
  40293. */
  40294. sprite: function (x, y, key, frame) {
  40295. return new Phaser.Sprite(this.game, x, y, key, frame);
  40296. },
  40297. /**
  40298. * Create a tween object for a specific object.
  40299. *
  40300. * The object can be any JavaScript object or Phaser object such as Sprite.
  40301. *
  40302. * @method Phaser.GameObjectCreator#tween
  40303. * @param {object} obj - Object the tween will be run on.
  40304. * @return {Phaser.Tween} The Tween object.
  40305. */
  40306. tween: function (obj) {
  40307. return new Phaser.Tween(obj, this.game, this.game.tweens);
  40308. },
  40309. /**
  40310. * A Group is a container for display objects that allows for fast pooling, recycling and collision checks.
  40311. *
  40312. * @method Phaser.GameObjectCreator#group
  40313. * @param {any} parent - The parent Group or DisplayObjectContainer that will hold this group, if any.
  40314. * @param {string} [name='group'] - A name for this Group. Not used internally but useful for debugging.
  40315. * @param {boolean} [addToStage=false] - If set to true this Group will be added directly to the Game.Stage instead of Game.World.
  40316. * @param {boolean} [enableBody=false] - If true all Sprites created with `Group.create` or `Group.createMulitple` will have a physics body created on them. Change the body type with physicsBodyType.
  40317. * @param {number} [physicsBodyType=0] - If enableBody is true this is the type of physics body that is created on new Sprites. Phaser.Physics.ARCADE, Phaser.Physics.P2, Phaser.Physics.NINJA, etc.
  40318. * @return {Phaser.Group} The newly created Group.
  40319. */
  40320. group: function (parent, name, addToStage, enableBody, physicsBodyType) {
  40321. return new Phaser.Group(this.game, parent, name, addToStage, enableBody, physicsBodyType);
  40322. },
  40323. /**
  40324. * Create a new SpriteBatch.
  40325. *
  40326. * @method Phaser.GameObjectCreator#spriteBatch
  40327. * @param {any} parent - The parent Group or DisplayObjectContainer that will hold this group, if any.
  40328. * @param {string} [name='group'] - A name for this Group. Not used internally but useful for debugging.
  40329. * @param {boolean} [addToStage=false] - If set to true this Group will be added directly to the Game.Stage instead of Game.World.
  40330. * @return {Phaser.SpriteBatch} The newly created group.
  40331. */
  40332. spriteBatch: function (parent, name, addToStage) {
  40333. if (name === undefined) { name = 'group'; }
  40334. if (addToStage === undefined) { addToStage = false; }
  40335. return new Phaser.SpriteBatch(this.game, parent, name, addToStage);
  40336. },
  40337. /**
  40338. * Creates a new Sound object.
  40339. *
  40340. * @method Phaser.GameObjectCreator#audio
  40341. * @param {string} key - The Game.cache key of the sound that this object will use.
  40342. * @param {number} [volume=1] - The volume at which the sound will be played.
  40343. * @param {boolean} [loop=false] - Whether or not the sound will loop.
  40344. * @param {boolean} [connect=true] - Controls if the created Sound object will connect to the master gainNode of the SoundManager when running under WebAudio.
  40345. * @return {Phaser.Sound} The newly created text object.
  40346. */
  40347. audio: function (key, volume, loop, connect) {
  40348. return this.game.sound.add(key, volume, loop, connect);
  40349. },
  40350. /**
  40351. * Creates a new AudioSprite object.
  40352. *
  40353. * @method Phaser.GameObjectCreator#audioSprite
  40354. * @param {string} key - The Game.cache key of the sound that this object will use.
  40355. * @return {Phaser.AudioSprite} The newly created AudioSprite object.
  40356. */
  40357. audioSprite: function (key) {
  40358. return this.game.sound.addSprite(key);
  40359. },
  40360. /**
  40361. * Creates a new Sound object.
  40362. *
  40363. * @method Phaser.GameObjectCreator#sound
  40364. * @param {string} key - The Game.cache key of the sound that this object will use.
  40365. * @param {number} [volume=1] - The volume at which the sound will be played.
  40366. * @param {boolean} [loop=false] - Whether or not the sound will loop.
  40367. * @param {boolean} [connect=true] - Controls if the created Sound object will connect to the master gainNode of the SoundManager when running under WebAudio.
  40368. * @return {Phaser.Sound} The newly created text object.
  40369. */
  40370. sound: function (key, volume, loop, connect) {
  40371. return this.game.sound.add(key, volume, loop, connect);
  40372. },
  40373. /**
  40374. * Creates a new TileSprite object.
  40375. *
  40376. * @method Phaser.GameObjectCreator#tileSprite
  40377. * @param {number} x - The x coordinate (in world space) to position the TileSprite at.
  40378. * @param {number} y - The y coordinate (in world space) to position the TileSprite at.
  40379. * @param {number} width - The width of the TileSprite.
  40380. * @param {number} height - The height of the TileSprite.
  40381. * @param {string|Phaser.BitmapData|PIXI.Texture} key - This is the image or texture used by the TileSprite during rendering. It can be a string which is a reference to the Phaser Image Cache entry, or an instance of a PIXI.Texture or BitmapData.
  40382. * @param {string|number} frame - If this TileSprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index.
  40383. * @return {Phaser.TileSprite} The newly created tileSprite object.
  40384. */
  40385. tileSprite: function (x, y, width, height, key, frame) {
  40386. return new Phaser.TileSprite(this.game, x, y, width, height, key, frame);
  40387. },
  40388. /**
  40389. * Creates a new Rope object.
  40390. *
  40391. * @method Phaser.GameObjectCreator#rope
  40392. * @param {number} x - The x coordinate (in world space) to position the Rope at.
  40393. * @param {number} y - The y coordinate (in world space) to position the Rope at.
  40394. * @param {number} width - The width of the Rope.
  40395. * @param {number} height - The height of the Rope.
  40396. * @param {string|Phaser.RenderTexture|Phaser.BitmapData|PIXI.Texture} key - This is the image or texture used by the TileSprite during rendering. It can be a string which is a reference to the Cache entry, or an instance of a RenderTexture or PIXI.Texture.
  40397. * @param {string|number} frame - If this Rope is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index.
  40398. * @return {Phaser.Rope} The newly created rope object.
  40399. */
  40400. rope: function (x, y, key, frame, points) {
  40401. return new Phaser.Rope(this.game, x, y, key, frame, points);
  40402. },
  40403. /**
  40404. * Creates a new Text object.
  40405. *
  40406. * @method Phaser.GameObjectCreator#text
  40407. * @param {number} x - X position of the new text object.
  40408. * @param {number} y - Y position of the new text object.
  40409. * @param {string} text - The actual text that will be written.
  40410. * @param {object} style - The style object containing style attributes like font, font size , etc.
  40411. * @return {Phaser.Text} The newly created text object.
  40412. */
  40413. text: function (x, y, text, style) {
  40414. return new Phaser.Text(this.game, x, y, text, style);
  40415. },
  40416. /**
  40417. * Creates a new Button object.
  40418. *
  40419. * @method Phaser.GameObjectCreator#button
  40420. * @param {number} [x] X position of the new button object.
  40421. * @param {number} [y] Y position of the new button object.
  40422. * @param {string} [key] The image key as defined in the Game.Cache to use as the texture for this button.
  40423. * @param {function} [callback] The function to call when this button is pressed
  40424. * @param {object} [callbackContext] The context in which the callback will be called (usually 'this')
  40425. * @param {string|number} [overFrame] This is the frame or frameName that will be set when this button is in an over state. Give either a number to use a frame ID or a string for a frame name.
  40426. * @param {string|number} [outFrame] This is the frame or frameName that will be set when this button is in an out state. Give either a number to use a frame ID or a string for a frame name.
  40427. * @param {string|number} [downFrame] This is the frame or frameName that will be set when this button is in a down state. Give either a number to use a frame ID or a string for a frame name.
  40428. * @param {string|number} [upFrame] This is the frame or frameName that will be set when this button is in an up state. Give either a number to use a frame ID or a string for a frame name.
  40429. * @return {Phaser.Button} The newly created button object.
  40430. */
  40431. button: function (x, y, key, callback, callbackContext, overFrame, outFrame, downFrame, upFrame) {
  40432. return new Phaser.Button(this.game, x, y, key, callback, callbackContext, overFrame, outFrame, downFrame, upFrame);
  40433. },
  40434. /**
  40435. * Creates a new Graphics object.
  40436. *
  40437. * @method Phaser.GameObjectCreator#graphics
  40438. * @param {number} [x=0] - X position of the new graphics object.
  40439. * @param {number} [y=0] - Y position of the new graphics object.
  40440. * @return {Phaser.Graphics} The newly created graphics object.
  40441. */
  40442. graphics: function (x, y) {
  40443. return new Phaser.Graphics(this.game, x, y);
  40444. },
  40445. /**
  40446. * Creat a new Emitter.
  40447. *
  40448. * An Emitter is a lightweight particle emitter. It can be used for one-time explosions or for
  40449. * continuous effects like rain and fire. All it really does is launch Particle objects out
  40450. * at set intervals, and fixes their positions and velocities accorindgly.
  40451. *
  40452. * @method Phaser.GameObjectCreator#emitter
  40453. * @param {number} [x=0] - The x coordinate within the Emitter that the particles are emitted from.
  40454. * @param {number} [y=0] - The y coordinate within the Emitter that the particles are emitted from.
  40455. * @param {number} [maxParticles=50] - The total number of particles in this emitter.
  40456. * @return {Phaser.Emitter} The newly created emitter object.
  40457. */
  40458. emitter: function (x, y, maxParticles) {
  40459. return new Phaser.Particles.Arcade.Emitter(this.game, x, y, maxParticles);
  40460. },
  40461. /**
  40462. * Create a new RetroFont object.
  40463. *
  40464. * A RetroFont can be used as a texture for an Image or Sprite and optionally add it to the Cache.
  40465. * A RetroFont uses a bitmap which contains fixed with characters for the font set. You use character spacing to define the set.
  40466. * If you need variable width character support then use a BitmapText object instead. The main difference between a RetroFont and a BitmapText
  40467. * is that a RetroFont creates a single texture that you can apply to a game object, where-as a BitmapText creates one Sprite object per letter of text.
  40468. * The texture can be asssigned or one or multiple images/sprites, but note that the text the RetroFont uses will be shared across them all,
  40469. * i.e. if you need each Image to have different text in it, then you need to create multiple RetroFont objects.
  40470. *
  40471. * @method Phaser.GameObjectCreator#retroFont
  40472. * @param {string} font - The key of the image in the Game.Cache that the RetroFont will use.
  40473. * @param {number} characterWidth - The width of each character in the font set.
  40474. * @param {number} characterHeight - The height of each character in the font set.
  40475. * @param {string} chars - The characters used in the font set, in display order. You can use the TEXT_SET consts for common font set arrangements.
  40476. * @param {number} charsPerRow - The number of characters per row in the font set.
  40477. * @param {number} [xSpacing=0] - If the characters in the font set have horizontal spacing between them set the required amount here.
  40478. * @param {number} [ySpacing=0] - If the characters in the font set have vertical spacing between them set the required amount here.
  40479. * @param {number} [xOffset=0] - If the font set doesn't start at the top left of the given image, specify the X coordinate offset here.
  40480. * @param {number} [yOffset=0] - If the font set doesn't start at the top left of the given image, specify the Y coordinate offset here.
  40481. * @return {Phaser.RetroFont} The newly created RetroFont texture which can be applied to an Image or Sprite.
  40482. */
  40483. retroFont: function (font, characterWidth, characterHeight, chars, charsPerRow, xSpacing, ySpacing, xOffset, yOffset) {
  40484. return new Phaser.RetroFont(this.game, font, characterWidth, characterHeight, chars, charsPerRow, xSpacing, ySpacing, xOffset, yOffset);
  40485. },
  40486. /**
  40487. * Create a new BitmapText object.
  40488. *
  40489. * BitmapText objects work by taking a texture file and an XML file that describes the font structure.
  40490. * It then generates a new Sprite object for each letter of the text, proportionally spaced out and aligned to
  40491. * match the font structure.
  40492. *
  40493. * BitmapText objects are less flexible than Text objects, in that they have less features such as shadows, fills and the ability
  40494. * to use Web Fonts. However you trade this flexibility for pure rendering speed. You can also create visually compelling BitmapTexts by
  40495. * processing the font texture in an image editor first, applying fills and any other effects required.
  40496. *
  40497. * To create multi-line text insert \r, \n or \r\n escape codes into the text string.
  40498. *
  40499. * To create a BitmapText data files you can use:
  40500. *
  40501. * BMFont (Windows, free): http://www.angelcode.com/products/bmfont/
  40502. * Glyph Designer (OS X, commercial): http://www.71squared.com/en/glyphdesigner
  40503. * Littera (Web-based, free): http://kvazars.com/littera/
  40504. *
  40505. * @method Phaser.GameObjectCreator#bitmapText
  40506. * @param {number} x - X coordinate to display the BitmapText object at.
  40507. * @param {number} y - Y coordinate to display the BitmapText object at.
  40508. * @param {string} font - The key of the BitmapText as stored in Phaser.Cache.
  40509. * @param {string} [text=''] - The text that will be rendered. This can also be set later via BitmapText.text.
  40510. * @param {number} [size=32] - The size the font will be rendered at in pixels.
  40511. * @param {string} [align='left'] - The alignment of multi-line text. Has no effect if there is only one line of text.
  40512. * @return {Phaser.BitmapText} The newly created bitmapText object.
  40513. */
  40514. bitmapText: function (x, y, font, text, size, align) {
  40515. return new Phaser.BitmapText(this.game, x, y, font, text, size, align);
  40516. },
  40517. /**
  40518. * Creates a new Phaser.Tilemap object.
  40519. *
  40520. * The map can either be populated with data from a Tiled JSON file or from a CSV file.
  40521. * To do this pass the Cache key as the first parameter. When using Tiled data you need only provide the key.
  40522. * When using CSV data you must provide the key and the tileWidth and tileHeight parameters.
  40523. * If creating a blank tilemap to be populated later, you can either specify no parameters at all and then use `Tilemap.create` or pass the map and tile dimensions here.
  40524. * Note that all Tilemaps use a base tile size to calculate dimensions from, but that a TilemapLayer may have its own unique tile size that overrides it.
  40525. *
  40526. * @method Phaser.GameObjectCreator#tilemap
  40527. * @param {string} [key] - The key of the tilemap data as stored in the Cache. If you're creating a blank map either leave this parameter out or pass `null`.
  40528. * @param {number} [tileWidth=32] - The pixel width of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data.
  40529. * @param {number} [tileHeight=32] - The pixel height of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data.
  40530. * @param {number} [width=10] - The width of the map in tiles. If this map is created from Tiled or CSV data you don't need to specify this.
  40531. * @param {number} [height=10] - The height of the map in tiles. If this map is created from Tiled or CSV data you don't need to specify this.
  40532. */
  40533. tilemap: function (key, tileWidth, tileHeight, width, height) {
  40534. return new Phaser.Tilemap(this.game, key, tileWidth, tileHeight, width, height);
  40535. },
  40536. /**
  40537. * A dynamic initially blank canvas to which images can be drawn.
  40538. *
  40539. * @method Phaser.GameObjectCreator#renderTexture
  40540. * @param {number} [width=100] - the width of the RenderTexture.
  40541. * @param {number} [height=100] - the height of the RenderTexture.
  40542. * @param {string} [key=''] - Asset key for the RenderTexture when stored in the Cache (see addToCache parameter).
  40543. * @param {boolean} [addToCache=false] - Should this RenderTexture be added to the Game.Cache? If so you can retrieve it with Cache.getTexture(key)
  40544. * @return {Phaser.RenderTexture} The newly created RenderTexture object.
  40545. */
  40546. renderTexture: function (width, height, key, addToCache) {
  40547. if (key === undefined || key === '') { key = this.game.rnd.uuid(); }
  40548. if (addToCache === undefined) { addToCache = false; }
  40549. var texture = new Phaser.RenderTexture(this.game, width, height, key);
  40550. if (addToCache)
  40551. {
  40552. this.game.cache.addRenderTexture(key, texture);
  40553. }
  40554. return texture;
  40555. },
  40556. /**
  40557. * Create a BitmpaData object.
  40558. *
  40559. * A BitmapData object can be manipulated and drawn to like a traditional Canvas object and used to texture Sprites.
  40560. *
  40561. * @method Phaser.GameObjectCreator#bitmapData
  40562. * @param {number} [width=256] - The width of the BitmapData in pixels.
  40563. * @param {number} [height=256] - The height of the BitmapData in pixels.
  40564. * @param {string} [key=''] - Asset key for the BitmapData when stored in the Cache (see addToCache parameter).
  40565. * @param {boolean} [addToCache=false] - Should this BitmapData be added to the Game.Cache? If so you can retrieve it with Cache.getBitmapData(key)
  40566. * @return {Phaser.BitmapData} The newly created BitmapData object.
  40567. */
  40568. bitmapData: function (width, height, key, addToCache) {
  40569. if (addToCache === undefined) { addToCache = false; }
  40570. if (key === undefined || key === '') { key = this.game.rnd.uuid(); }
  40571. var texture = new Phaser.BitmapData(this.game, key, width, height);
  40572. if (addToCache)
  40573. {
  40574. this.game.cache.addBitmapData(key, texture);
  40575. }
  40576. return texture;
  40577. },
  40578. /**
  40579. * A WebGL shader/filter that can be applied to Sprites.
  40580. *
  40581. * @method Phaser.GameObjectCreator#filter
  40582. * @param {string} filter - The name of the filter you wish to create, for example HueRotate or SineWave.
  40583. * @param {any} - Whatever parameters are needed to be passed to the filter init function.
  40584. * @return {Phaser.Filter} The newly created Phaser.Filter object.
  40585. */
  40586. filter: function (filter) {
  40587. var args = Array.prototype.slice.call(arguments, 1);
  40588. var filter = new Phaser.Filter[filter](this.game);
  40589. filter.init.apply(filter, args);
  40590. return filter;
  40591. }
  40592. };
  40593. Phaser.GameObjectCreator.prototype.constructor = Phaser.GameObjectCreator;
  40594. /**
  40595. * @author Richard Davey <rich@photonstorm.com>
  40596. * @copyright 2016 Photon Storm Ltd.
  40597. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  40598. */
  40599. /**
  40600. * Sprites are the lifeblood of your game, used for nearly everything visual.
  40601. *
  40602. * At its most basic a Sprite consists of a set of coordinates and a texture that is rendered to the canvas.
  40603. * They also contain additional properties allowing for physics motion (via Sprite.body), input handling (via Sprite.input),
  40604. * events (via Sprite.events), animation (via Sprite.animations), camera culling and more. Please see the Examples for use cases.
  40605. *
  40606. * @class Phaser.Sprite
  40607. * @constructor
  40608. * @extends PIXI.Sprite
  40609. * @extends Phaser.Component.Core
  40610. * @extends Phaser.Component.Angle
  40611. * @extends Phaser.Component.Animation
  40612. * @extends Phaser.Component.AutoCull
  40613. * @extends Phaser.Component.Bounds
  40614. * @extends Phaser.Component.BringToTop
  40615. * @extends Phaser.Component.Crop
  40616. * @extends Phaser.Component.Delta
  40617. * @extends Phaser.Component.Destroy
  40618. * @extends Phaser.Component.FixedToCamera
  40619. * @extends Phaser.Component.Health
  40620. * @extends Phaser.Component.InCamera
  40621. * @extends Phaser.Component.InputEnabled
  40622. * @extends Phaser.Component.InWorld
  40623. * @extends Phaser.Component.LifeSpan
  40624. * @extends Phaser.Component.LoadTexture
  40625. * @extends Phaser.Component.Overlap
  40626. * @extends Phaser.Component.PhysicsBody
  40627. * @extends Phaser.Component.Reset
  40628. * @extends Phaser.Component.ScaleMinMax
  40629. * @extends Phaser.Component.Smoothed
  40630. * @param {Phaser.Game} game - A reference to the currently running game.
  40631. * @param {number} x - The x coordinate (in world space) to position the Sprite at.
  40632. * @param {number} y - The y coordinate (in world space) to position the Sprite at.
  40633. * @param {string|Phaser.RenderTexture|Phaser.BitmapData|PIXI.Texture} key - This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache entry, or an instance of a RenderTexture or PIXI.Texture.
  40634. * @param {string|number} frame - If this Sprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index.
  40635. */
  40636. Phaser.Sprite = function (game, x, y, key, frame) {
  40637. x = x || 0;
  40638. y = y || 0;
  40639. key = key || null;
  40640. frame = frame || null;
  40641. /**
  40642. * @property {number} type - The const type of this object.
  40643. * @readonly
  40644. */
  40645. this.type = Phaser.SPRITE;
  40646. /**
  40647. * @property {number} physicsType - The const physics body type of this object.
  40648. * @readonly
  40649. */
  40650. this.physicsType = Phaser.SPRITE;
  40651. PIXI.Sprite.call(this, Phaser.Cache.DEFAULT);
  40652. Phaser.Component.Core.init.call(this, game, x, y, key, frame);
  40653. };
  40654. Phaser.Sprite.prototype = Object.create(PIXI.Sprite.prototype);
  40655. Phaser.Sprite.prototype.constructor = Phaser.Sprite;
  40656. Phaser.Component.Core.install.call(Phaser.Sprite.prototype, [
  40657. 'Angle',
  40658. 'Animation',
  40659. 'AutoCull',
  40660. 'Bounds',
  40661. 'BringToTop',
  40662. 'Crop',
  40663. 'Delta',
  40664. 'Destroy',
  40665. 'FixedToCamera',
  40666. 'Health',
  40667. 'InCamera',
  40668. 'InputEnabled',
  40669. 'InWorld',
  40670. 'LifeSpan',
  40671. 'LoadTexture',
  40672. 'Overlap',
  40673. 'PhysicsBody',
  40674. 'Reset',
  40675. 'ScaleMinMax',
  40676. 'Smoothed'
  40677. ]);
  40678. Phaser.Sprite.prototype.preUpdatePhysics = Phaser.Component.PhysicsBody.preUpdate;
  40679. Phaser.Sprite.prototype.preUpdateLifeSpan = Phaser.Component.LifeSpan.preUpdate;
  40680. Phaser.Sprite.prototype.preUpdateInWorld = Phaser.Component.InWorld.preUpdate;
  40681. Phaser.Sprite.prototype.preUpdateCore = Phaser.Component.Core.preUpdate;
  40682. /**
  40683. * Automatically called by World.preUpdate.
  40684. *
  40685. * @method
  40686. * @memberof Phaser.Sprite
  40687. * @return {boolean} True if the Sprite was rendered, otherwise false.
  40688. */
  40689. Phaser.Sprite.prototype.preUpdate = function() {
  40690. if (!this.preUpdatePhysics() || !this.preUpdateLifeSpan() || !this.preUpdateInWorld())
  40691. {
  40692. return false;
  40693. }
  40694. return this.preUpdateCore();
  40695. };
  40696. /**
  40697. * @author Richard Davey <rich@photonstorm.com>
  40698. * @copyright 2016 Photon Storm Ltd.
  40699. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  40700. */
  40701. /**
  40702. * An Image is a light-weight object you can use to display anything that doesn't need physics or animation.
  40703. * It can still rotate, scale, crop and receive input events. This makes it perfect for logos, backgrounds, simple buttons and other non-Sprite graphics.
  40704. *
  40705. * @class Phaser.Image
  40706. * @extends PIXI.Sprite
  40707. * @extends Phaser.Component.Core
  40708. * @extends Phaser.Component.Angle
  40709. * @extends Phaser.Component.Animation
  40710. * @extends Phaser.Component.AutoCull
  40711. * @extends Phaser.Component.Bounds
  40712. * @extends Phaser.Component.BringToTop
  40713. * @extends Phaser.Component.Crop
  40714. * @extends Phaser.Component.Destroy
  40715. * @extends Phaser.Component.FixedToCamera
  40716. * @extends Phaser.Component.InputEnabled
  40717. * @extends Phaser.Component.LifeSpan
  40718. * @extends Phaser.Component.LoadTexture
  40719. * @extends Phaser.Component.Overlap
  40720. * @extends Phaser.Component.Reset
  40721. * @extends Phaser.Component.ScaleMinMax
  40722. * @extends Phaser.Component.Smoothed
  40723. * @constructor
  40724. * @param {Phaser.Game} game - A reference to the currently running game.
  40725. * @param {number} [x=0] - The x coordinate of the Image. The coordinate is relative to any parent container this Image may be in.
  40726. * @param {number} [y=0] - The y coordinate of the Image. The coordinate is relative to any parent container this Image may be in.
  40727. * @param {string|Phaser.RenderTexture|Phaser.BitmapData|PIXI.Texture} [key] - The texture used by the Image during rendering. It can be a string which is a reference to the Cache entry, or an instance of a RenderTexture, BitmapData or PIXI.Texture.
  40728. * @param {string|number} [frame] - If this Image is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index.
  40729. */
  40730. Phaser.Image = function (game, x, y, key, frame) {
  40731. x = x || 0;
  40732. y = y || 0;
  40733. key = key || null;
  40734. frame = frame || null;
  40735. /**
  40736. * @property {number} type - The const type of this object.
  40737. * @readonly
  40738. */
  40739. this.type = Phaser.IMAGE;
  40740. PIXI.Sprite.call(this, Phaser.Cache.DEFAULT);
  40741. Phaser.Component.Core.init.call(this, game, x, y, key, frame);
  40742. };
  40743. Phaser.Image.prototype = Object.create(PIXI.Sprite.prototype);
  40744. Phaser.Image.prototype.constructor = Phaser.Image;
  40745. Phaser.Component.Core.install.call(Phaser.Image.prototype, [
  40746. 'Angle',
  40747. 'Animation',
  40748. 'AutoCull',
  40749. 'Bounds',
  40750. 'BringToTop',
  40751. 'Crop',
  40752. 'Destroy',
  40753. 'FixedToCamera',
  40754. 'InputEnabled',
  40755. 'LifeSpan',
  40756. 'LoadTexture',
  40757. 'Overlap',
  40758. 'Reset',
  40759. 'ScaleMinMax',
  40760. 'Smoothed'
  40761. ]);
  40762. Phaser.Image.prototype.preUpdateInWorld = Phaser.Component.InWorld.preUpdate;
  40763. Phaser.Image.prototype.preUpdateCore = Phaser.Component.Core.preUpdate;
  40764. /**
  40765. * Automatically called by World.preUpdate.
  40766. *
  40767. * @method Phaser.Image#preUpdate
  40768. * @memberof Phaser.Image
  40769. */
  40770. Phaser.Image.prototype.preUpdate = function() {
  40771. if (!this.preUpdateInWorld())
  40772. {
  40773. return false;
  40774. }
  40775. return this.preUpdateCore();
  40776. };
  40777. /**
  40778. * @author Richard Davey <rich@photonstorm.com>
  40779. * @copyright 2016 Photon Storm Ltd.
  40780. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  40781. */
  40782. /**
  40783. * Create a new `Button` object. A Button is a special type of Sprite that is set-up to handle Pointer events automatically.
  40784. *
  40785. * The four states a Button responds to are:
  40786. *
  40787. * * 'Over' - when the Pointer moves over the Button. This is also commonly known as 'hover'.
  40788. * * 'Out' - when the Pointer that was previously over the Button moves out of it.
  40789. * * 'Down' - when the Pointer is pressed down on the Button. I.e. touched on a touch enabled device or clicked with the mouse.
  40790. * * 'Up' - when the Pointer that was pressed down on the Button is released again.
  40791. *
  40792. * A different texture/frame and activation sound can be specified for any of the states.
  40793. *
  40794. * Frames can be specified as either an integer (the frame ID) or a string (the frame name); the same values that can be used with a Sprite constructor.
  40795. *
  40796. * @class Phaser.Button
  40797. * @constructor
  40798. * @extends Phaser.Image
  40799. * @param {Phaser.Game} game Current game instance.
  40800. * @param {number} [x=0] - X position of the Button.
  40801. * @param {number} [y=0] - Y position of the Button.
  40802. * @param {string} [key] - The image key (in the Game.Cache) to use as the texture for this Button.
  40803. * @param {function} [callback] - The function to call when this Button is pressed.
  40804. * @param {object} [callbackContext] - The context in which the callback will be called (usually 'this').
  40805. * @param {string|integer} [overFrame] - The frame / frameName when the button is in the Over state.
  40806. * @param {string|integer} [outFrame] - The frame / frameName when the button is in the Out state.
  40807. * @param {string|integer} [downFrame] - The frame / frameName when the button is in the Down state.
  40808. * @param {string|integer} [upFrame] - The frame / frameName when the button is in the Up state.
  40809. */
  40810. Phaser.Button = function (game, x, y, key, callback, callbackContext, overFrame, outFrame, downFrame, upFrame) {
  40811. x = x || 0;
  40812. y = y || 0;
  40813. key = key || null;
  40814. callback = callback || null;
  40815. callbackContext = callbackContext || this;
  40816. Phaser.Image.call(this, game, x, y, key, outFrame);
  40817. /**
  40818. * The Phaser Object Type.
  40819. * @property {number} type
  40820. * @readonly
  40821. */
  40822. this.type = Phaser.BUTTON;
  40823. /**
  40824. * @property {number} physicsType - The const physics body type of this object.
  40825. * @readonly
  40826. */
  40827. this.physicsType = Phaser.SPRITE;
  40828. /**
  40829. * The name or ID of the Over state frame.
  40830. * @property {string|integer} onOverFrame
  40831. * @private
  40832. */
  40833. this._onOverFrame = null;
  40834. /**
  40835. * The name or ID of the Out state frame.
  40836. * @property {string|integer} onOutFrame
  40837. * @private
  40838. */
  40839. this._onOutFrame = null;
  40840. /**
  40841. * The name or ID of the Down state frame.
  40842. * @property {string|integer} onDownFrame
  40843. * @private
  40844. */
  40845. this._onDownFrame = null;
  40846. /**
  40847. * The name or ID of the Up state frame.
  40848. * @property {string|integer} onUpFrame
  40849. * @private
  40850. */
  40851. this._onUpFrame = null;
  40852. /**
  40853. * The Sound to be played when this Buttons Over state is activated.
  40854. * @property {Phaser.Sound|Phaser.AudioSprite|null} onOverSound
  40855. * @readonly
  40856. */
  40857. this.onOverSound = null;
  40858. /**
  40859. * The Sound to be played when this Buttons Out state is activated.
  40860. * @property {Phaser.Sound|Phaser.AudioSprite|null} onOutSound
  40861. * @readonly
  40862. */
  40863. this.onOutSound = null;
  40864. /**
  40865. * The Sound to be played when this Buttons Down state is activated.
  40866. * @property {Phaser.Sound|Phaser.AudioSprite|null} onDownSound
  40867. * @readonly
  40868. */
  40869. this.onDownSound = null;
  40870. /**
  40871. * The Sound to be played when this Buttons Up state is activated.
  40872. * @property {Phaser.Sound|Phaser.AudioSprite|null} onUpSound
  40873. * @readonly
  40874. */
  40875. this.onUpSound = null;
  40876. /**
  40877. * The Sound Marker used in conjunction with the onOverSound.
  40878. * @property {string} onOverSoundMarker
  40879. * @readonly
  40880. */
  40881. this.onOverSoundMarker = '';
  40882. /**
  40883. * The Sound Marker used in conjunction with the onOutSound.
  40884. * @property {string} onOutSoundMarker
  40885. * @readonly
  40886. */
  40887. this.onOutSoundMarker = '';
  40888. /**
  40889. * The Sound Marker used in conjunction with the onDownSound.
  40890. * @property {string} onDownSoundMarker
  40891. * @readonly
  40892. */
  40893. this.onDownSoundMarker = '';
  40894. /**
  40895. * The Sound Marker used in conjunction with the onUpSound.
  40896. * @property {string} onUpSoundMarker
  40897. * @readonly
  40898. */
  40899. this.onUpSoundMarker = '';
  40900. /**
  40901. * The Signal (or event) dispatched when this Button is in an Over state.
  40902. * @property {Phaser.Signal} onInputOver
  40903. */
  40904. this.onInputOver = new Phaser.Signal();
  40905. /**
  40906. * The Signal (or event) dispatched when this Button is in an Out state.
  40907. * @property {Phaser.Signal} onInputOut
  40908. */
  40909. this.onInputOut = new Phaser.Signal();
  40910. /**
  40911. * The Signal (or event) dispatched when this Button is in an Down state.
  40912. * @property {Phaser.Signal} onInputDown
  40913. */
  40914. this.onInputDown = new Phaser.Signal();
  40915. /**
  40916. * The Signal (or event) dispatched when this Button is in an Up state.
  40917. * @property {Phaser.Signal} onInputUp
  40918. */
  40919. this.onInputUp = new Phaser.Signal();
  40920. /**
  40921. * If true then onOver events (such as onOverSound) will only be triggered if the Pointer object causing them was the Mouse Pointer.
  40922. * The frame will still be changed as applicable.
  40923. *
  40924. * @property {boolean} onOverMouseOnly
  40925. * @default
  40926. */
  40927. this.onOverMouseOnly = true;
  40928. /**
  40929. * Suppress the over event if a pointer was just released and it matches the given {@link Phaser.PointerModer pointer mode bitmask}.
  40930. *
  40931. * This behavior was introduced in Phaser 2.3.1; this property is a soft-revert of the change.
  40932. *
  40933. * @property {Phaser.PointerMode?} justReleasedPreventsOver=ACTIVE_CURSOR
  40934. */
  40935. this.justReleasedPreventsOver = Phaser.PointerMode.TOUCH;
  40936. /**
  40937. * When true the the texture frame will not be automatically switched on up/down/over/out events.
  40938. * @property {boolean} freezeFrames
  40939. * @default
  40940. */
  40941. this.freezeFrames = false;
  40942. /**
  40943. * When the Button is touched / clicked and then released you can force it to enter a state of "out" instead of "up".
  40944. *
  40945. * This can also accept a {@link Phaser.PointerModer pointer mode bitmask} for more refined control.
  40946. *
  40947. * @property {boolean|Phaser.PointerMode} forceOut=false
  40948. * @default
  40949. */
  40950. this.forceOut = false;
  40951. this.inputEnabled = true;
  40952. this.input.start(0, true);
  40953. this.input.useHandCursor = true;
  40954. this.setFrames(overFrame, outFrame, downFrame, upFrame);
  40955. if (callback !== null)
  40956. {
  40957. this.onInputUp.add(callback, callbackContext);
  40958. }
  40959. // Redirect the input events to here so we can handle animation updates, etc
  40960. this.events.onInputOver.add(this.onInputOverHandler, this);
  40961. this.events.onInputOut.add(this.onInputOutHandler, this);
  40962. this.events.onInputDown.add(this.onInputDownHandler, this);
  40963. this.events.onInputUp.add(this.onInputUpHandler, this);
  40964. this.events.onRemovedFromWorld.add(this.removedFromWorld, this);
  40965. };
  40966. Phaser.Button.prototype = Object.create(Phaser.Image.prototype);
  40967. Phaser.Button.prototype.constructor = Phaser.Button;
  40968. // State constants; local only. These are tied to property names in Phaser.Button.
  40969. var STATE_OVER = 'Over';
  40970. var STATE_OUT = 'Out';
  40971. var STATE_DOWN = 'Down';
  40972. var STATE_UP = 'Up';
  40973. /**
  40974. * Clears all of the frames set on this Button.
  40975. *
  40976. * @method Phaser.Button#clearFrames
  40977. */
  40978. Phaser.Button.prototype.clearFrames = function () {
  40979. this.setFrames(null, null, null, null);
  40980. };
  40981. /**
  40982. * Called when this Button is removed from the World.
  40983. *
  40984. * @method Phaser.Button#removedFromWorld
  40985. * @protected
  40986. */
  40987. Phaser.Button.prototype.removedFromWorld = function () {
  40988. this.inputEnabled = false;
  40989. };
  40990. /**
  40991. * Set the frame name/ID for the given state.
  40992. *
  40993. * @method Phaser.Button#setStateFrame
  40994. * @private
  40995. * @param {object} state - See `STATE_*`
  40996. * @param {number|string} frame - The number or string representing the frame.
  40997. * @param {boolean} switchImmediately - Immediately switch to the frame if it was set - and this is true.
  40998. */
  40999. Phaser.Button.prototype.setStateFrame = function (state, frame, switchImmediately)
  41000. {
  41001. var frameKey = '_on' + state + 'Frame';
  41002. if (frame !== null) // not null or undefined
  41003. {
  41004. this[frameKey] = frame;
  41005. if (switchImmediately)
  41006. {
  41007. this.changeStateFrame(state);
  41008. }
  41009. }
  41010. else
  41011. {
  41012. this[frameKey] = null;
  41013. }
  41014. };
  41015. /**
  41016. * Change the frame to that of the given state, _if_ the state has a frame assigned _and_ if the frames are not currently "frozen".
  41017. *
  41018. * @method Phaser.Button#changeStateFrame
  41019. * @private
  41020. * @param {object} state - See `STATE_*`
  41021. * @return {boolean} True only if the frame was assigned a value, possibly the same one it already had.
  41022. */
  41023. Phaser.Button.prototype.changeStateFrame = function (state) {
  41024. if (this.freezeFrames)
  41025. {
  41026. return false;
  41027. }
  41028. var frameKey = '_on' + state + 'Frame';
  41029. var frame = this[frameKey];
  41030. if (typeof frame === 'string')
  41031. {
  41032. this.frameName = frame;
  41033. return true;
  41034. }
  41035. else if (typeof frame === 'number')
  41036. {
  41037. this.frame = frame;
  41038. return true;
  41039. }
  41040. else
  41041. {
  41042. return false;
  41043. }
  41044. };
  41045. /**
  41046. * Used to manually set the frames that will be used for the different states of the Button.
  41047. *
  41048. * Frames can be specified as either an integer (the frame ID) or a string (the frame name); these are the same values that can be used with a Sprite constructor.
  41049. *
  41050. * @method Phaser.Button#setFrames
  41051. * @public
  41052. * @param {string|integer} [overFrame] - The frame / frameName when the button is in the Over state.
  41053. * @param {string|integer} [outFrame] - The frame / frameName when the button is in the Out state.
  41054. * @param {string|integer} [downFrame] - The frame / frameName when the button is in the Down state.
  41055. * @param {string|integer} [upFrame] - The frame / frameName when the button is in the Up state.
  41056. */
  41057. Phaser.Button.prototype.setFrames = function (overFrame, outFrame, downFrame, upFrame) {
  41058. this.setStateFrame(STATE_OVER, overFrame, this.input.pointerOver());
  41059. this.setStateFrame(STATE_OUT, outFrame, !this.input.pointerOver());
  41060. this.setStateFrame(STATE_DOWN, downFrame, this.input.pointerDown());
  41061. this.setStateFrame(STATE_UP, upFrame, this.input.pointerUp());
  41062. };
  41063. /**
  41064. * Set the sound/marker for the given state.
  41065. *
  41066. * @method Phaser.Button#setStateSound
  41067. * @private
  41068. * @param {object} state - See `STATE_*`
  41069. * @param {Phaser.Sound|Phaser.AudioSprite} [sound] - Sound.
  41070. * @param {string} [marker=''] - Sound marker.
  41071. */
  41072. Phaser.Button.prototype.setStateSound = function (state, sound, marker) {
  41073. var soundKey = 'on' + state + 'Sound';
  41074. var markerKey = 'on' + state + 'SoundMarker';
  41075. if (sound instanceof Phaser.Sound || sound instanceof Phaser.AudioSprite)
  41076. {
  41077. this[soundKey] = sound;
  41078. this[markerKey] = typeof marker === 'string' ? marker : '';
  41079. }
  41080. else
  41081. {
  41082. this[soundKey] = null;
  41083. this[markerKey] = '';
  41084. }
  41085. };
  41086. /**
  41087. * Play the sound for the given state, _if_ the state has a sound assigned.
  41088. *
  41089. * @method Phaser.Button#playStateSound
  41090. * @private
  41091. * @param {object} state - See `STATE_*`
  41092. * @return {boolean} True only if a sound was played.
  41093. */
  41094. Phaser.Button.prototype.playStateSound = function (state) {
  41095. var soundKey = 'on' + state + 'Sound';
  41096. var sound = this[soundKey];
  41097. if (sound)
  41098. {
  41099. var markerKey = 'on' + state + 'SoundMarker';
  41100. var marker = this[markerKey];
  41101. sound.play(marker);
  41102. return true;
  41103. }
  41104. else
  41105. {
  41106. return false;
  41107. }
  41108. };
  41109. /**
  41110. * Sets the sounds to be played whenever this Button is interacted with. Sounds can be either full Sound objects, or markers pointing to a section of a Sound object.
  41111. * The most common forms of sounds are 'hover' effects and 'click' effects, which is why the order of the parameters is overSound then downSound.
  41112. *
  41113. * Call this function with no parameters to reset all sounds on this Button.
  41114. *
  41115. * @method Phaser.Button#setSounds
  41116. * @public
  41117. * @param {Phaser.Sound|Phaser.AudioSprite} [overSound] - Over Button Sound.
  41118. * @param {string} [overMarker] - Over Button Sound Marker.
  41119. * @param {Phaser.Sound|Phaser.AudioSprite} [downSound] - Down Button Sound.
  41120. * @param {string} [downMarker] - Down Button Sound Marker.
  41121. * @param {Phaser.Sound|Phaser.AudioSprite} [outSound] - Out Button Sound.
  41122. * @param {string} [outMarker] - Out Button Sound Marker.
  41123. * @param {Phaser.Sound|Phaser.AudioSprite} [upSound] - Up Button Sound.
  41124. * @param {string} [upMarker] - Up Button Sound Marker.
  41125. */
  41126. Phaser.Button.prototype.setSounds = function (overSound, overMarker, downSound, downMarker, outSound, outMarker, upSound, upMarker) {
  41127. this.setStateSound(STATE_OVER, overSound, overMarker);
  41128. this.setStateSound(STATE_OUT, outSound, outMarker);
  41129. this.setStateSound(STATE_DOWN, downSound, downMarker);
  41130. this.setStateSound(STATE_UP, upSound, upMarker);
  41131. };
  41132. /**
  41133. * The Sound to be played when a Pointer moves over this Button.
  41134. *
  41135. * @method Phaser.Button#setOverSound
  41136. * @public
  41137. * @param {Phaser.Sound|Phaser.AudioSprite} sound - The Sound that will be played.
  41138. * @param {string} [marker] - A Sound Marker that will be used in the playback.
  41139. */
  41140. Phaser.Button.prototype.setOverSound = function (sound, marker) {
  41141. this.setStateSound(STATE_OVER, sound, marker);
  41142. };
  41143. /**
  41144. * The Sound to be played when a Pointer moves out of this Button.
  41145. *
  41146. * @method Phaser.Button#setOutSound
  41147. * @public
  41148. * @param {Phaser.Sound|Phaser.AudioSprite} sound - The Sound that will be played.
  41149. * @param {string} [marker] - A Sound Marker that will be used in the playback.
  41150. */
  41151. Phaser.Button.prototype.setOutSound = function (sound, marker) {
  41152. this.setStateSound(STATE_OUT, sound, marker);
  41153. };
  41154. /**
  41155. * The Sound to be played when a Pointer presses down on this Button.
  41156. *
  41157. * @method Phaser.Button#setDownSound
  41158. * @public
  41159. * @param {Phaser.Sound|Phaser.AudioSprite} sound - The Sound that will be played.
  41160. * @param {string} [marker] - A Sound Marker that will be used in the playback.
  41161. */
  41162. Phaser.Button.prototype.setDownSound = function (sound, marker) {
  41163. this.setStateSound(STATE_DOWN, sound, marker);
  41164. };
  41165. /**
  41166. * The Sound to be played when a Pointer has pressed down and is released from this Button.
  41167. *
  41168. * @method Phaser.Button#setUpSound
  41169. * @public
  41170. * @param {Phaser.Sound|Phaser.AudioSprite} sound - The Sound that will be played.
  41171. * @param {string} [marker] - A Sound Marker that will be used in the playback.
  41172. */
  41173. Phaser.Button.prototype.setUpSound = function (sound, marker) {
  41174. this.setStateSound(STATE_UP, sound, marker);
  41175. };
  41176. /**
  41177. * Internal function that handles input events.
  41178. *
  41179. * @method Phaser.Button#onInputOverHandler
  41180. * @protected
  41181. * @param {Phaser.Button} sprite - The Button that the event occurred on.
  41182. * @param {Phaser.Pointer} pointer - The Pointer that activated the Button.
  41183. */
  41184. Phaser.Button.prototype.onInputOverHandler = function (sprite, pointer) {
  41185. if (pointer.justReleased() &&
  41186. (this.justReleasedPreventsOver & pointer.pointerMode) === pointer.pointerMode)
  41187. {
  41188. // If the Pointer was only just released then we don't fire an over event
  41189. return;
  41190. }
  41191. this.changeStateFrame(STATE_OVER);
  41192. if (this.onOverMouseOnly && !pointer.isMouse)
  41193. {
  41194. return;
  41195. }
  41196. this.playStateSound(STATE_OVER);
  41197. if (this.onInputOver)
  41198. {
  41199. this.onInputOver.dispatch(this, pointer);
  41200. }
  41201. };
  41202. /**
  41203. * Internal function that handles input events.
  41204. *
  41205. * @method Phaser.Button#onInputOutHandler
  41206. * @protected
  41207. * @param {Phaser.Button} sprite - The Button that the event occurred on.
  41208. * @param {Phaser.Pointer} pointer - The Pointer that activated the Button.
  41209. */
  41210. Phaser.Button.prototype.onInputOutHandler = function (sprite, pointer) {
  41211. this.changeStateFrame(STATE_OUT);
  41212. this.playStateSound(STATE_OUT);
  41213. if (this.onInputOut)
  41214. {
  41215. this.onInputOut.dispatch(this, pointer);
  41216. }
  41217. };
  41218. /**
  41219. * Internal function that handles input events.
  41220. *
  41221. * @method Phaser.Button#onInputDownHandler
  41222. * @protected
  41223. * @param {Phaser.Button} sprite - The Button that the event occurred on.
  41224. * @param {Phaser.Pointer} pointer - The Pointer that activated the Button.
  41225. */
  41226. Phaser.Button.prototype.onInputDownHandler = function (sprite, pointer) {
  41227. this.changeStateFrame(STATE_DOWN);
  41228. this.playStateSound(STATE_DOWN);
  41229. if (this.onInputDown)
  41230. {
  41231. this.onInputDown.dispatch(this, pointer);
  41232. }
  41233. };
  41234. /**
  41235. * Internal function that handles input events.
  41236. *
  41237. * @method Phaser.Button#onInputUpHandler
  41238. * @protected
  41239. * @param {Phaser.Button} sprite - The Button that the event occurred on.
  41240. * @param {Phaser.Pointer} pointer - The Pointer that activated the Button.
  41241. */
  41242. Phaser.Button.prototype.onInputUpHandler = function (sprite, pointer, isOver) {
  41243. this.playStateSound(STATE_UP);
  41244. // Input dispatched early, before state change (but after sound)
  41245. if (this.onInputUp)
  41246. {
  41247. this.onInputUp.dispatch(this, pointer, isOver);
  41248. }
  41249. if (this.freezeFrames)
  41250. {
  41251. return;
  41252. }
  41253. if (this.forceOut === true || (this.forceOut & pointer.pointerMode) === pointer.pointerMode)
  41254. {
  41255. this.changeStateFrame(STATE_OUT);
  41256. }
  41257. else
  41258. {
  41259. var changedUp = this.changeStateFrame(STATE_UP);
  41260. if (!changedUp)
  41261. {
  41262. // No Up frame to show..
  41263. if (isOver)
  41264. {
  41265. this.changeStateFrame(STATE_OVER);
  41266. }
  41267. else
  41268. {
  41269. this.changeStateFrame(STATE_OUT);
  41270. }
  41271. }
  41272. }
  41273. };
  41274. /**
  41275. * @author Richard Davey <rich@photonstorm.com>
  41276. * @copyright 2016 Photon Storm Ltd.
  41277. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  41278. */
  41279. /**
  41280. * The SpriteBatch class is a really fast version of the DisplayObjectContainer built purely for speed, so use when you need a lot of sprites or particles.
  41281. * It's worth mentioning that by default sprite batches are used through-out the renderer, so you only really need to use a SpriteBatch if you have over
  41282. * 1000 sprites that all share the same texture (or texture atlas). It's also useful if running in Canvas mode and you have a lot of un-rotated or un-scaled
  41283. * Sprites as it skips all of the Canvas setTransform calls, which helps performance, especially on mobile devices.
  41284. *
  41285. * Please note that any Sprite that is part of a SpriteBatch will not have its bounds updated, so will fail checks such as outOfBounds.
  41286. *
  41287. * @class Phaser.SpriteBatch
  41288. * @extends Phaser.Group
  41289. * @constructor
  41290. * @param {Phaser.Game} game - A reference to the currently running game.
  41291. * @param {Phaser.Group|Phaser.Sprite|null} parent - The parent Group, DisplayObject or DisplayObjectContainer that this Group will be added to. If `undefined` or `null` it will use game.world.
  41292. * @param {string} [name=group] - A name for this Group. Not used internally but useful for debugging.
  41293. * @param {boolean} [addToStage=false] - If set to true this Group will be added directly to the Game.Stage instead of Game.World.
  41294. */
  41295. Phaser.SpriteBatch = function (game, parent, name, addToStage) {
  41296. if (parent === undefined || parent === null) { parent = game.world; }
  41297. PIXI.SpriteBatch.call(this);
  41298. Phaser.Group.call(this, game, parent, name, addToStage);
  41299. /**
  41300. * @property {number} type - Internal Phaser Type value.
  41301. * @protected
  41302. */
  41303. this.type = Phaser.SPRITEBATCH;
  41304. };
  41305. Phaser.SpriteBatch.prototype = Phaser.Utils.extend(true, Phaser.SpriteBatch.prototype, PIXI.SpriteBatch.prototype, Phaser.Group.prototype);
  41306. Phaser.SpriteBatch.prototype.constructor = Phaser.SpriteBatch;
  41307. /**
  41308. * @author Richard Davey <rich@photonstorm.com>
  41309. * @copyright 2016 Photon Storm Ltd.
  41310. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  41311. */
  41312. /**
  41313. * A BitmapData object contains a Canvas element to which you can draw anything you like via normal Canvas context operations.
  41314. * A single BitmapData can be used as the texture for one or many Images / Sprites.
  41315. * So if you need to dynamically create a Sprite texture then they are a good choice.
  41316. *
  41317. * Important note: Every BitmapData creates its own Canvas element. Because BitmapData's are now Game Objects themselves, and don't
  41318. * live on the display list, they are NOT automatically cleared when you change State. Therefore you _must_ call BitmapData.destroy
  41319. * in your State's shutdown method if you wish to free-up the resources the BitmapData used, it will not happen for you.
  41320. *
  41321. * @class Phaser.BitmapData
  41322. * @constructor
  41323. * @param {Phaser.Game} game - A reference to the currently running game.
  41324. * @param {string} key - Internal Phaser reference key for the BitmapData.
  41325. * @param {number} [width=256] - The width of the BitmapData in pixels. If undefined or zero it's set to a default value.
  41326. * @param {number} [height=256] - The height of the BitmapData in pixels. If undefined or zero it's set to a default value.
  41327. * @param {boolean} [skipPool=false] - When this BitmapData generates its internal canvas to use for rendering, it will get the canvas from the CanvasPool if false, or create its own if true.
  41328. */
  41329. Phaser.BitmapData = function (game, key, width, height, skipPool) {
  41330. if (width === undefined || width === 0) { width = 256; }
  41331. if (height === undefined || height === 0) { height = 256; }
  41332. if (skipPool === undefined) { skipPool = false; }
  41333. /**
  41334. * @property {Phaser.Game} game - A reference to the currently running game.
  41335. */
  41336. this.game = game;
  41337. /**
  41338. * @property {string} key - The key of the BitmapData in the Cache, if stored there.
  41339. */
  41340. this.key = key;
  41341. /**
  41342. * @property {number} width - The width of the BitmapData in pixels.
  41343. */
  41344. this.width = width;
  41345. /**
  41346. * @property {number} height - The height of the BitmapData in pixels.
  41347. */
  41348. this.height = height;
  41349. /**
  41350. * @property {HTMLCanvasElement} canvas - The canvas to which this BitmapData draws.
  41351. * @default
  41352. */
  41353. this.canvas = Phaser.Canvas.create(this, width, height, null, skipPool);
  41354. /**
  41355. * @property {CanvasRenderingContext2D} context - The 2d context of the canvas.
  41356. * @default
  41357. */
  41358. this.context = this.canvas.getContext('2d', { alpha: true });
  41359. /**
  41360. * @property {CanvasRenderingContext2D} ctx - A reference to BitmapData.context.
  41361. */
  41362. this.ctx = this.context;
  41363. /**
  41364. * @property {string} smoothProperty - The context property needed for smoothing this Canvas.
  41365. */
  41366. this.smoothProperty = (game.renderType === Phaser.CANVAS) ? game.renderer.renderSession.smoothProperty : Phaser.Canvas.getSmoothingPrefix(this.context);
  41367. /**
  41368. * @property {ImageData} imageData - The context image data.
  41369. * Please note that a call to BitmapData.draw() or BitmapData.copy() does not update immediately this property for performance reason. Use BitmapData.update() to do so.
  41370. * This property is updated automatically after the first game loop, according to the dirty flag property.
  41371. */
  41372. this.imageData = this.context.getImageData(0, 0, width, height);
  41373. /**
  41374. * A Uint8ClampedArray view into BitmapData.buffer.
  41375. * Note that this is unavailable in some browsers (such as Epic Browser due to its security restrictions)
  41376. * @property {Uint8ClampedArray} data
  41377. */
  41378. this.data = null;
  41379. if (this.imageData)
  41380. {
  41381. this.data = this.imageData.data;
  41382. }
  41383. /**
  41384. * @property {Uint32Array} pixels - An Uint32Array view into BitmapData.buffer.
  41385. */
  41386. this.pixels = null;
  41387. /**
  41388. * @property {ArrayBuffer} buffer - An ArrayBuffer the same size as the context ImageData.
  41389. */
  41390. if (this.data)
  41391. {
  41392. if (this.imageData.data.buffer)
  41393. {
  41394. this.buffer = this.imageData.data.buffer;
  41395. this.pixels = new Uint32Array(this.buffer);
  41396. }
  41397. else
  41398. {
  41399. if (window['ArrayBuffer'])
  41400. {
  41401. this.buffer = new ArrayBuffer(this.imageData.data.length);
  41402. this.pixels = new Uint32Array(this.buffer);
  41403. }
  41404. else
  41405. {
  41406. this.pixels = this.imageData.data;
  41407. }
  41408. }
  41409. }
  41410. /**
  41411. * @property {PIXI.BaseTexture} baseTexture - The PIXI.BaseTexture.
  41412. * @default
  41413. */
  41414. this.baseTexture = new PIXI.BaseTexture(this.canvas);
  41415. /**
  41416. * @property {PIXI.Texture} texture - The PIXI.Texture.
  41417. * @default
  41418. */
  41419. this.texture = new PIXI.Texture(this.baseTexture);
  41420. /**
  41421. * @property {Phaser.FrameData} frameData - The FrameData container this BitmapData uses for rendering.
  41422. */
  41423. this.frameData = new Phaser.FrameData();
  41424. /**
  41425. * @property {Phaser.Frame} textureFrame - The Frame this BitmapData uses for rendering.
  41426. * @default
  41427. */
  41428. this.textureFrame = this.frameData.addFrame(new Phaser.Frame(0, 0, 0, width, height, 'bitmapData'));
  41429. this.texture.frame = this.textureFrame;
  41430. /**
  41431. * @property {number} type - The const type of this object.
  41432. * @default
  41433. */
  41434. this.type = Phaser.BITMAPDATA;
  41435. /**
  41436. * @property {boolean} disableTextureUpload - If disableTextureUpload is true this BitmapData will never send its image data to the GPU when its dirty flag is true.
  41437. */
  41438. this.disableTextureUpload = false;
  41439. /**
  41440. * @property {boolean} dirty - If dirty this BitmapData will be re-rendered.
  41441. */
  41442. this.dirty = false;
  41443. // Aliases
  41444. this.cls = this.clear;
  41445. /**
  41446. * @property {number} _image - Internal cache var.
  41447. * @private
  41448. */
  41449. this._image = null;
  41450. /**
  41451. * @property {Phaser.Point} _pos - Internal cache var.
  41452. * @private
  41453. */
  41454. this._pos = new Phaser.Point();
  41455. /**
  41456. * @property {Phaser.Point} _size - Internal cache var.
  41457. * @private
  41458. */
  41459. this._size = new Phaser.Point();
  41460. /**
  41461. * @property {Phaser.Point} _scale - Internal cache var.
  41462. * @private
  41463. */
  41464. this._scale = new Phaser.Point();
  41465. /**
  41466. * @property {number} _rotate - Internal cache var.
  41467. * @private
  41468. */
  41469. this._rotate = 0;
  41470. /**
  41471. * @property {object} _alpha - Internal cache var.
  41472. * @private
  41473. */
  41474. this._alpha = { prev: 1, current: 1 };
  41475. /**
  41476. * @property {Phaser.Point} _anchor - Internal cache var.
  41477. * @private
  41478. */
  41479. this._anchor = new Phaser.Point();
  41480. /**
  41481. * @property {number} _tempR - Internal cache var.
  41482. * @private
  41483. */
  41484. this._tempR = 0;
  41485. /**
  41486. * @property {number} _tempG - Internal cache var.
  41487. * @private
  41488. */
  41489. this._tempG = 0;
  41490. /**
  41491. * @property {number} _tempB - Internal cache var.
  41492. * @private
  41493. */
  41494. this._tempB = 0;
  41495. /**
  41496. * @property {Phaser.Circle} _circle - Internal cache var.
  41497. * @private
  41498. */
  41499. this._circle = new Phaser.Circle();
  41500. /**
  41501. * @property {HTMLCanvasElement} _swapCanvas - A swap canvas. Used by moveH and moveV, created in those methods.
  41502. * @private
  41503. */
  41504. this._swapCanvas = undefined;
  41505. };
  41506. Phaser.BitmapData.prototype = {
  41507. /**
  41508. * Shifts the contents of this BitmapData by the distances given.
  41509. *
  41510. * The image will wrap-around the edges on all sides if the wrap argument is true (the default).
  41511. *
  41512. * @method Phaser.BitmapData#move
  41513. * @param {integer} x - The amount of pixels to horizontally shift the canvas by. Use a negative value to shift to the left, positive to the right.
  41514. * @param {integer} y - The amount of pixels to vertically shift the canvas by. Use a negative value to shift up, positive to shift down.
  41515. * @param {boolean} [wrap=true] - Wrap the content of the BitmapData.
  41516. * @return {Phaser.BitmapData} This BitmapData object for method chaining.
  41517. */
  41518. move: function (x, y, wrap) {
  41519. if (x !== 0)
  41520. {
  41521. this.moveH(x, wrap);
  41522. }
  41523. if (y !== 0)
  41524. {
  41525. this.moveV(y, wrap);
  41526. }
  41527. return this;
  41528. },
  41529. /**
  41530. * Shifts the contents of this BitmapData horizontally.
  41531. *
  41532. * The image will wrap-around the sides if the wrap argument is true (the default).
  41533. *
  41534. * @method Phaser.BitmapData#moveH
  41535. * @param {integer} distance - The amount of pixels to horizontally shift the canvas by. Use a negative value to shift to the left, positive to the right.
  41536. * @param {boolean} [wrap=true] - Wrap the content of the BitmapData.
  41537. * @return {Phaser.BitmapData} This BitmapData object for method chaining.
  41538. */
  41539. moveH: function (distance, wrap) {
  41540. if (wrap === undefined) { wrap = true; }
  41541. if (this._swapCanvas === undefined)
  41542. {
  41543. this._swapCanvas = PIXI.CanvasPool.create(this, this.width, this.height);
  41544. }
  41545. var c = this._swapCanvas;
  41546. var ctx = c.getContext('2d');
  41547. var h = this.height;
  41548. var src = this.canvas;
  41549. ctx.clearRect(0, 0, this.width, this.height);
  41550. if (distance < 0)
  41551. {
  41552. distance = Math.abs(distance);
  41553. // Moving to the left
  41554. var w = this.width - distance;
  41555. // Left-hand chunk
  41556. if (wrap)
  41557. {
  41558. ctx.drawImage(src, 0, 0, distance, h, w, 0, distance, h);
  41559. }
  41560. // Rest of the image
  41561. ctx.drawImage(src, distance, 0, w, h, 0, 0, w, h);
  41562. }
  41563. else
  41564. {
  41565. // Moving to the right
  41566. var w = this.width - distance;
  41567. // Right-hand chunk
  41568. if (wrap)
  41569. {
  41570. ctx.drawImage(src, w, 0, distance, h, 0, 0, distance, h);
  41571. }
  41572. // Rest of the image
  41573. ctx.drawImage(src, 0, 0, w, h, distance, 0, w, h);
  41574. }
  41575. this.clear();
  41576. return this.copy(this._swapCanvas);
  41577. },
  41578. /**
  41579. * Shifts the contents of this BitmapData vertically.
  41580. *
  41581. * The image will wrap-around the sides if the wrap argument is true (the default).
  41582. *
  41583. * @method Phaser.BitmapData#moveV
  41584. * @param {integer} distance - The amount of pixels to vertically shift the canvas by. Use a negative value to shift up, positive to shift down.
  41585. * @param {boolean} [wrap=true] - Wrap the content of the BitmapData.
  41586. * @return {Phaser.BitmapData} This BitmapData object for method chaining.
  41587. */
  41588. moveV: function (distance, wrap) {
  41589. if (wrap === undefined) { wrap = true; }
  41590. if (this._swapCanvas === undefined)
  41591. {
  41592. this._swapCanvas = PIXI.CanvasPool.create(this, this.width, this.height);
  41593. }
  41594. var c = this._swapCanvas;
  41595. var ctx = c.getContext('2d');
  41596. var w = this.width;
  41597. var src = this.canvas;
  41598. ctx.clearRect(0, 0, this.width, this.height);
  41599. if (distance < 0)
  41600. {
  41601. distance = Math.abs(distance);
  41602. // Moving up
  41603. var h = this.height - distance;
  41604. // Top chunk
  41605. if (wrap)
  41606. {
  41607. ctx.drawImage(src, 0, 0, w, distance, 0, h, w, distance);
  41608. }
  41609. // Rest of the image
  41610. ctx.drawImage(src, 0, distance, w, h, 0, 0, w, h);
  41611. }
  41612. else
  41613. {
  41614. // Moving down
  41615. var h = this.height - distance;
  41616. // Bottom chunk
  41617. if (wrap)
  41618. {
  41619. ctx.drawImage(src, 0, h, w, distance, 0, 0, w, distance);
  41620. }
  41621. // Rest of the image
  41622. ctx.drawImage(src, 0, 0, w, h, 0, distance, w, h);
  41623. }
  41624. this.clear();
  41625. return this.copy(this._swapCanvas);
  41626. },
  41627. /**
  41628. * Updates the given objects so that they use this BitmapData as their texture.
  41629. * This will replace any texture they will currently have set.
  41630. *
  41631. * @method Phaser.BitmapData#add
  41632. * @param {Phaser.Sprite|Phaser.Sprite[]|Phaser.Image|Phaser.Image[]} object - Either a single Sprite/Image or an Array of Sprites/Images.
  41633. * @return {Phaser.BitmapData} This BitmapData object for method chaining.
  41634. */
  41635. add: function (object) {
  41636. if (Array.isArray(object))
  41637. {
  41638. for (var i = 0; i < object.length; i++)
  41639. {
  41640. if (object[i]['loadTexture'])
  41641. {
  41642. object[i].loadTexture(this);
  41643. }
  41644. }
  41645. }
  41646. else
  41647. {
  41648. object.loadTexture(this);
  41649. }
  41650. return this;
  41651. },
  41652. /**
  41653. * Takes the given Game Object, resizes this BitmapData to match it and then draws it into this BitmapDatas canvas, ready for further processing.
  41654. * The source game object is not modified by this operation.
  41655. * If the source object uses a texture as part of a Texture Atlas or Sprite Sheet, only the current frame will be used for sizing.
  41656. * If a string is given it will assume it's a cache key and look in Phaser.Cache for an image key matching the string.
  41657. *
  41658. * @method Phaser.BitmapData#load
  41659. * @param {Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapData|Image|HTMLCanvasElement|string} source - The object that will be used to populate this BitmapData. If you give a string it will try and find the Image in the Game.Cache first.
  41660. * @return {Phaser.BitmapData} This BitmapData object for method chaining.
  41661. */
  41662. load: function (source) {
  41663. if (typeof source === 'string')
  41664. {
  41665. source = this.game.cache.getImage(source);
  41666. }
  41667. if (source)
  41668. {
  41669. this.resize(source.width, source.height);
  41670. this.cls();
  41671. }
  41672. else
  41673. {
  41674. return;
  41675. }
  41676. this.draw(source);
  41677. this.update();
  41678. return this;
  41679. },
  41680. /**
  41681. * Clears the BitmapData context using a clearRect.
  41682. *
  41683. * @method Phaser.BitmapData#cls
  41684. */
  41685. /**
  41686. * Clears the BitmapData context using a clearRect.
  41687. *
  41688. * You can optionally define the area to clear.
  41689. * If the arguments are left empty it will clear the entire canvas.
  41690. *
  41691. * You may need to call BitmapData.update after this in order to clear out the pixel data,
  41692. * but Phaser will not do this automatically for you.
  41693. *
  41694. * @method Phaser.BitmapData#clear
  41695. * @param {number} [x=0] - The x coordinate of the top-left of the area to clear.
  41696. * @param {number} [y=0] - The y coordinate of the top-left of the area to clear.
  41697. * @param {number} [width] - The width of the area to clear. If undefined it will use BitmapData.width.
  41698. * @param {number} [height] - The height of the area to clear. If undefined it will use BitmapData.height.
  41699. * @return {Phaser.BitmapData} This BitmapData object for method chaining.
  41700. */
  41701. clear: function (x, y, width, height) {
  41702. if (x === undefined) { x = 0; }
  41703. if (y === undefined) { y = 0; }
  41704. if (width === undefined) { width = this.width; }
  41705. if (height === undefined) { height = this.height; }
  41706. this.context.clearRect(x, y, width, height);
  41707. this.dirty = true;
  41708. return this;
  41709. },
  41710. /**
  41711. * Fills the BitmapData with the given color.
  41712. *
  41713. * @method Phaser.BitmapData#fill
  41714. * @param {number} r - The red color value, between 0 and 0xFF (255).
  41715. * @param {number} g - The green color value, between 0 and 0xFF (255).
  41716. * @param {number} b - The blue color value, between 0 and 0xFF (255).
  41717. * @param {number} [a=1] - The alpha color value, between 0 and 1.
  41718. * @return {Phaser.BitmapData} This BitmapData object for method chaining.
  41719. */
  41720. fill: function (r, g, b, a) {
  41721. if (a === undefined) { a = 1; }
  41722. this.context.fillStyle = 'rgba(' + r + ',' + g + ',' + b + ',' + a + ')';
  41723. this.context.fillRect(0, 0, this.width, this.height);
  41724. this.dirty = true;
  41725. return this;
  41726. },
  41727. /**
  41728. * Creates a new Image element by converting this BitmapDatas canvas into a dataURL.
  41729. *
  41730. * The image is then stored in the image Cache using the key given.
  41731. *
  41732. * Finally a PIXI.Texture is created based on the image and returned.
  41733. *
  41734. * You can apply the texture to a sprite or any other supporting object by using either the
  41735. * key or the texture. First call generateTexture:
  41736. *
  41737. * `var texture = bitmapdata.generateTexture('ball');`
  41738. *
  41739. * Then you can either apply the texture to a sprite:
  41740. *
  41741. * `game.add.sprite(0, 0, texture);`
  41742. *
  41743. * or by using the string based key:
  41744. *
  41745. * `game.add.sprite(0, 0, 'ball');`
  41746. *
  41747. * @method Phaser.BitmapData#generateTexture
  41748. * @param {string} key - The key which will be used to store the image in the Cache.
  41749. * @return {PIXI.Texture} The newly generated texture.
  41750. */
  41751. generateTexture: function (key) {
  41752. var image = new Image();
  41753. image.src = this.canvas.toDataURL("image/png");
  41754. var obj = this.game.cache.addImage(key, '', image);
  41755. return new PIXI.Texture(obj.base);
  41756. },
  41757. /**
  41758. * Resizes the BitmapData. This changes the size of the underlying canvas and refreshes the buffer.
  41759. *
  41760. * @method Phaser.BitmapData#resize
  41761. * @param {integer} width - The new width of the BitmapData.
  41762. * @param {integer} height - The new height of the BitmapData.
  41763. * @return {Phaser.BitmapData} This BitmapData object for method chaining.
  41764. */
  41765. resize: function (width, height) {
  41766. if (width !== this.width || height !== this.height)
  41767. {
  41768. this.width = width;
  41769. this.height = height;
  41770. this.canvas.width = width;
  41771. this.canvas.height = height;
  41772. if (this._swapCanvas !== undefined)
  41773. {
  41774. this._swapCanvas.width = width;
  41775. this._swapCanvas.height = height;
  41776. }
  41777. this.baseTexture.width = width;
  41778. this.baseTexture.height = height;
  41779. this.textureFrame.width = width;
  41780. this.textureFrame.height = height;
  41781. this.texture.width = width;
  41782. this.texture.height = height;
  41783. this.texture.crop.width = width;
  41784. this.texture.crop.height = height;
  41785. this.update();
  41786. this.dirty = true;
  41787. }
  41788. return this;
  41789. },
  41790. /**
  41791. * This re-creates the BitmapData.imageData from the current context.
  41792. * It then re-builds the ArrayBuffer, the data Uint8ClampedArray reference and the pixels Int32Array.
  41793. * If not given the dimensions defaults to the full size of the context.
  41794. *
  41795. * Warning: This is a very expensive operation, so use it sparingly.
  41796. *
  41797. * @method Phaser.BitmapData#update
  41798. * @param {number} [x=0] - The x coordinate of the top-left of the image data area to grab from.
  41799. * @param {number} [y=0] - The y coordinate of the top-left of the image data area to grab from.
  41800. * @param {number} [width=1] - The width of the image data area.
  41801. * @param {number} [height=1] - The height of the image data area.
  41802. * @return {Phaser.BitmapData} This BitmapData object for method chaining.
  41803. */
  41804. update: function (x, y, width, height) {
  41805. if (x === undefined) { x = 0; }
  41806. if (y === undefined) { y = 0; }
  41807. if (width === undefined) { width = Math.max(1, this.width); }
  41808. if (height === undefined) { height = Math.max(1, this.height); }
  41809. this.imageData = this.context.getImageData(x, y, width, height);
  41810. this.data = this.imageData.data;
  41811. if (this.imageData.data.buffer)
  41812. {
  41813. this.buffer = this.imageData.data.buffer;
  41814. this.pixels = new Uint32Array(this.buffer);
  41815. }
  41816. else
  41817. {
  41818. if (window['ArrayBuffer'])
  41819. {
  41820. this.buffer = new ArrayBuffer(this.imageData.data.length);
  41821. this.pixels = new Uint32Array(this.buffer);
  41822. }
  41823. else
  41824. {
  41825. this.pixels = this.imageData.data;
  41826. }
  41827. }
  41828. return this;
  41829. },
  41830. /**
  41831. * Scans through the area specified in this BitmapData and sends a color object for every pixel to the given callback.
  41832. * The callback will be sent a color object with 6 properties: `{ r: number, g: number, b: number, a: number, color: number, rgba: string }`.
  41833. * Where r, g, b and a are integers between 0 and 255 representing the color component values for red, green, blue and alpha.
  41834. * The `color` property is an Int32 of the full color. Note the endianess of this will change per system.
  41835. * The `rgba` property is a CSS style rgba() string which can be used with context.fillStyle calls, among others.
  41836. * The callback will also be sent the pixels x and y coordinates respectively.
  41837. * The callback must return either `false`, in which case no change will be made to the pixel, or a new color object.
  41838. * If a new color object is returned the pixel will be set to the r, g, b and a color values given within it.
  41839. *
  41840. * @method Phaser.BitmapData#processPixelRGB
  41841. * @param {function} callback - The callback that will be sent each pixel color object to be processed.
  41842. * @param {object} callbackContext - The context under which the callback will be called.
  41843. * @param {number} [x=0] - The x coordinate of the top-left of the region to process from.
  41844. * @param {number} [y=0] - The y coordinate of the top-left of the region to process from.
  41845. * @param {number} [width] - The width of the region to process.
  41846. * @param {number} [height] - The height of the region to process.
  41847. * @return {Phaser.BitmapData} This BitmapData object for method chaining.
  41848. */
  41849. processPixelRGB: function (callback, callbackContext, x, y, width, height) {
  41850. if (x === undefined) { x = 0; }
  41851. if (y === undefined) { y = 0; }
  41852. if (width === undefined) { width = this.width; }
  41853. if (height === undefined) { height = this.height; }
  41854. var w = x + width;
  41855. var h = y + height;
  41856. var pixel = Phaser.Color.createColor();
  41857. var result = { r: 0, g: 0, b: 0, a: 0 };
  41858. var dirty = false;
  41859. for (var ty = y; ty < h; ty++)
  41860. {
  41861. for (var tx = x; tx < w; tx++)
  41862. {
  41863. Phaser.Color.unpackPixel(this.getPixel32(tx, ty), pixel);
  41864. result = callback.call(callbackContext, pixel, tx, ty);
  41865. if (result !== false && result !== null && result !== undefined)
  41866. {
  41867. this.setPixel32(tx, ty, result.r, result.g, result.b, result.a, false);
  41868. dirty = true;
  41869. }
  41870. }
  41871. }
  41872. if (dirty)
  41873. {
  41874. this.context.putImageData(this.imageData, 0, 0);
  41875. this.dirty = true;
  41876. }
  41877. return this;
  41878. },
  41879. /**
  41880. * Scans through the area specified in this BitmapData and sends the color for every pixel to the given callback along with its x and y coordinates.
  41881. * Whatever value the callback returns is set as the new color for that pixel, unless it returns the same color, in which case it's skipped.
  41882. * Note that the format of the color received will be different depending on if the system is big or little endian.
  41883. * It is expected that your callback will deal with endianess. If you'd rather Phaser did it then use processPixelRGB instead.
  41884. * The callback will also be sent the pixels x and y coordinates respectively.
  41885. *
  41886. * @method Phaser.BitmapData#processPixel
  41887. * @param {function} callback - The callback that will be sent each pixel color to be processed.
  41888. * @param {object} callbackContext - The context under which the callback will be called.
  41889. * @param {number} [x=0] - The x coordinate of the top-left of the region to process from.
  41890. * @param {number} [y=0] - The y coordinate of the top-left of the region to process from.
  41891. * @param {number} [width] - The width of the region to process.
  41892. * @param {number} [height] - The height of the region to process.
  41893. * @return {Phaser.BitmapData} This BitmapData object for method chaining.
  41894. */
  41895. processPixel: function (callback, callbackContext, x, y, width, height) {
  41896. if (x === undefined) { x = 0; }
  41897. if (y === undefined) { y = 0; }
  41898. if (width === undefined) { width = this.width; }
  41899. if (height === undefined) { height = this.height; }
  41900. var w = x + width;
  41901. var h = y + height;
  41902. var pixel = 0;
  41903. var result = 0;
  41904. var dirty = false;
  41905. for (var ty = y; ty < h; ty++)
  41906. {
  41907. for (var tx = x; tx < w; tx++)
  41908. {
  41909. pixel = this.getPixel32(tx, ty);
  41910. result = callback.call(callbackContext, pixel, tx, ty);
  41911. if (result !== pixel)
  41912. {
  41913. this.pixels[ty * this.width + tx] = result;
  41914. dirty = true;
  41915. }
  41916. }
  41917. }
  41918. if (dirty)
  41919. {
  41920. this.context.putImageData(this.imageData, 0, 0);
  41921. this.dirty = true;
  41922. }
  41923. return this;
  41924. },
  41925. /**
  41926. * Replaces all pixels matching one color with another. The color values are given as two sets of RGBA values.
  41927. * An optional region parameter controls if the replacement happens in just a specific area of the BitmapData or the entire thing.
  41928. *
  41929. * @method Phaser.BitmapData#replaceRGB
  41930. * @param {number} r1 - The red color value to be replaced. Between 0 and 255.
  41931. * @param {number} g1 - The green color value to be replaced. Between 0 and 255.
  41932. * @param {number} b1 - The blue color value to be replaced. Between 0 and 255.
  41933. * @param {number} a1 - The alpha color value to be replaced. Between 0 and 255.
  41934. * @param {number} r2 - The red color value that is the replacement color. Between 0 and 255.
  41935. * @param {number} g2 - The green color value that is the replacement color. Between 0 and 255.
  41936. * @param {number} b2 - The blue color value that is the replacement color. Between 0 and 255.
  41937. * @param {number} a2 - The alpha color value that is the replacement color. Between 0 and 255.
  41938. * @param {Phaser.Rectangle} [region] - The area to perform the search over. If not given it will replace over the whole BitmapData.
  41939. * @return {Phaser.BitmapData} This BitmapData object for method chaining.
  41940. */
  41941. replaceRGB: function (r1, g1, b1, a1, r2, g2, b2, a2, region) {
  41942. var sx = 0;
  41943. var sy = 0;
  41944. var w = this.width;
  41945. var h = this.height;
  41946. var source = Phaser.Color.packPixel(r1, g1, b1, a1);
  41947. if (region !== undefined && region instanceof Phaser.Rectangle)
  41948. {
  41949. sx = region.x;
  41950. sy = region.y;
  41951. w = region.width;
  41952. h = region.height;
  41953. }
  41954. for (var y = 0; y < h; y++)
  41955. {
  41956. for (var x = 0; x < w; x++)
  41957. {
  41958. if (this.getPixel32(sx + x, sy + y) === source)
  41959. {
  41960. this.setPixel32(sx + x, sy + y, r2, g2, b2, a2, false);
  41961. }
  41962. }
  41963. }
  41964. this.context.putImageData(this.imageData, 0, 0);
  41965. this.dirty = true;
  41966. return this;
  41967. },
  41968. /**
  41969. * Sets the hue, saturation and lightness values on every pixel in the given region, or the whole BitmapData if no region was specified.
  41970. *
  41971. * @method Phaser.BitmapData#setHSL
  41972. * @param {number} [h=null] - The hue, in the range 0 - 1.
  41973. * @param {number} [s=null] - The saturation, in the range 0 - 1.
  41974. * @param {number} [l=null] - The lightness, in the range 0 - 1.
  41975. * @param {Phaser.Rectangle} [region] - The area to perform the operation on. If not given it will run over the whole BitmapData.
  41976. * @return {Phaser.BitmapData} This BitmapData object for method chaining.
  41977. */
  41978. setHSL: function (h, s, l, region) {
  41979. var bHaveH = h || h === 0;
  41980. var bHaveS = s || s === 0;
  41981. var bHaveL = l || l === 0;
  41982. if (!bHaveH && !bHaveS && !bHaveL)
  41983. {
  41984. return;
  41985. }
  41986. if (region === undefined)
  41987. {
  41988. region = new Phaser.Rectangle(0, 0, this.width, this.height);
  41989. }
  41990. var pixel = Phaser.Color.createColor();
  41991. for (var y = region.y; y < region.bottom; y++)
  41992. {
  41993. for (var x = region.x; x < region.right; x++)
  41994. {
  41995. Phaser.Color.unpackPixel(this.getPixel32(x, y), pixel, true);
  41996. if (bHaveH)
  41997. {
  41998. pixel.h = h;
  41999. }
  42000. if (bHaveS)
  42001. {
  42002. pixel.s = s;
  42003. }
  42004. if (bHaveL)
  42005. {
  42006. pixel.l = l;
  42007. }
  42008. Phaser.Color.HSLtoRGB(pixel.h, pixel.s, pixel.l, pixel);
  42009. this.setPixel32(x, y, pixel.r, pixel.g, pixel.b, pixel.a, false);
  42010. }
  42011. }
  42012. this.context.putImageData(this.imageData, 0, 0);
  42013. this.dirty = true;
  42014. return this;
  42015. },
  42016. /**
  42017. * Shifts any or all of the hue, saturation and lightness values on every pixel in the given region, or the whole BitmapData if no region was specified.
  42018. * Shifting will add the given value onto the current h, s and l values, not replace them.
  42019. * The hue is wrapped to keep it within the range 0 to 1. Saturation and lightness are clamped to not exceed 1.
  42020. *
  42021. * @method Phaser.BitmapData#shiftHSL
  42022. * @param {number} [h=null] - The amount to shift the hue by.
  42023. * @param {number} [s=null] - The amount to shift the saturation by.
  42024. * @param {number} [l=null] - The amount to shift the lightness by.
  42025. * @param {Phaser.Rectangle} [region] - The area to perform the operation on. If not given it will run over the whole BitmapData.
  42026. * @return {Phaser.BitmapData} This BitmapData object for method chaining.
  42027. */
  42028. shiftHSL: function (h, s, l, region) {
  42029. if (h === undefined || h === null) { h = false; }
  42030. if (s === undefined || s === null) { s = false; }
  42031. if (l === undefined || l === null) { l = false; }
  42032. if (!h && !s && !l)
  42033. {
  42034. return;
  42035. }
  42036. if (region === undefined)
  42037. {
  42038. region = new Phaser.Rectangle(0, 0, this.width, this.height);
  42039. }
  42040. var pixel = Phaser.Color.createColor();
  42041. for (var y = region.y; y < region.bottom; y++)
  42042. {
  42043. for (var x = region.x; x < region.right; x++)
  42044. {
  42045. Phaser.Color.unpackPixel(this.getPixel32(x, y), pixel, true);
  42046. if (h)
  42047. {
  42048. pixel.h = this.game.math.wrap(pixel.h + h, 0, 1);
  42049. }
  42050. if (s)
  42051. {
  42052. pixel.s = this.game.math.clamp(pixel.s + s, 0, 1);
  42053. }
  42054. if (l)
  42055. {
  42056. pixel.l = this.game.math.clamp(pixel.l + l, 0, 1);
  42057. }
  42058. Phaser.Color.HSLtoRGB(pixel.h, pixel.s, pixel.l, pixel);
  42059. this.setPixel32(x, y, pixel.r, pixel.g, pixel.b, pixel.a, false);
  42060. }
  42061. }
  42062. this.context.putImageData(this.imageData, 0, 0);
  42063. this.dirty = true;
  42064. return this;
  42065. },
  42066. /**
  42067. * Sets the color of the given pixel to the specified red, green, blue and alpha values.
  42068. *
  42069. * @method Phaser.BitmapData#setPixel32
  42070. * @param {number} x - The x coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData.
  42071. * @param {number} y - The y coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData.
  42072. * @param {number} red - The red color value, between 0 and 0xFF (255).
  42073. * @param {number} green - The green color value, between 0 and 0xFF (255).
  42074. * @param {number} blue - The blue color value, between 0 and 0xFF (255).
  42075. * @param {number} alpha - The alpha color value, between 0 and 0xFF (255).
  42076. * @param {boolean} [immediate=true] - If `true` the context.putImageData will be called and the dirty flag set.
  42077. * @return {Phaser.BitmapData} This BitmapData object for method chaining.
  42078. */
  42079. setPixel32: function (x, y, red, green, blue, alpha, immediate) {
  42080. if (immediate === undefined) { immediate = true; }
  42081. if (x >= 0 && x <= this.width && y >= 0 && y <= this.height)
  42082. {
  42083. if (Phaser.Device.LITTLE_ENDIAN)
  42084. {
  42085. this.pixels[y * this.width + x] = (alpha << 24) | (blue << 16) | (green << 8) | red;
  42086. }
  42087. else
  42088. {
  42089. this.pixels[y * this.width + x] = (red << 24) | (green << 16) | (blue << 8) | alpha;
  42090. }
  42091. if (immediate)
  42092. {
  42093. this.context.putImageData(this.imageData, 0, 0);
  42094. this.dirty = true;
  42095. }
  42096. }
  42097. return this;
  42098. },
  42099. /**
  42100. * Sets the color of the given pixel to the specified red, green and blue values.
  42101. *
  42102. * @method Phaser.BitmapData#setPixel
  42103. * @param {number} x - The x coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData.
  42104. * @param {number} y - The y coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData.
  42105. * @param {number} red - The red color value, between 0 and 0xFF (255).
  42106. * @param {number} green - The green color value, between 0 and 0xFF (255).
  42107. * @param {number} blue - The blue color value, between 0 and 0xFF (255).
  42108. * @param {boolean} [immediate=true] - If `true` the context.putImageData will be called and the dirty flag set.
  42109. * @return {Phaser.BitmapData} This BitmapData object for method chaining.
  42110. */
  42111. setPixel: function (x, y, red, green, blue, immediate) {
  42112. return this.setPixel32(x, y, red, green, blue, 255, immediate);
  42113. },
  42114. /**
  42115. * Get the color of a specific pixel in the context into a color object.
  42116. * If you have drawn anything to the BitmapData since it was created you must call BitmapData.update to refresh the array buffer,
  42117. * otherwise this may return out of date color values, or worse - throw a run-time error as it tries to access an array element that doesn't exist.
  42118. *
  42119. * @method Phaser.BitmapData#getPixel
  42120. * @param {number} x - The x coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData.
  42121. * @param {number} y - The y coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData.
  42122. * @param {object} [out] - An object into which 4 properties will be created: r, g, b and a. If not provided a new object will be created.
  42123. * @return {object} An object with the red, green, blue and alpha values set in the r, g, b and a properties.
  42124. */
  42125. getPixel: function (x, y, out) {
  42126. if (!out)
  42127. {
  42128. out = Phaser.Color.createColor();
  42129. }
  42130. var index = ~~(x + (y * this.width));
  42131. index *= 4;
  42132. out.r = this.data[index];
  42133. out.g = this.data[++index];
  42134. out.b = this.data[++index];
  42135. out.a = this.data[++index];
  42136. return out;
  42137. },
  42138. /**
  42139. * Get the color of a specific pixel including its alpha value.
  42140. * If you have drawn anything to the BitmapData since it was created you must call BitmapData.update to refresh the array buffer,
  42141. * otherwise this may return out of date color values, or worse - throw a run-time error as it tries to access an array element that doesn't exist.
  42142. * Note that on little-endian systems the format is 0xAABBGGRR and on big-endian the format is 0xRRGGBBAA.
  42143. *
  42144. * @method Phaser.BitmapData#getPixel32
  42145. * @param {number} x - The x coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData.
  42146. * @param {number} y - The y coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData.
  42147. * @return {number} A native color value integer (format: 0xAARRGGBB)
  42148. */
  42149. getPixel32: function (x, y) {
  42150. if (x >= 0 && x <= this.width && y >= 0 && y <= this.height)
  42151. {
  42152. return this.pixels[y * this.width + x];
  42153. }
  42154. },
  42155. /**
  42156. * Get the color of a specific pixel including its alpha value as a color object containing r,g,b,a and rgba properties.
  42157. * If you have drawn anything to the BitmapData since it was created you must call BitmapData.update to refresh the array buffer,
  42158. * otherwise this may return out of date color values, or worse - throw a run-time error as it tries to access an array element that doesn't exist.
  42159. *
  42160. * @method Phaser.BitmapData#getPixelRGB
  42161. * @param {number} x - The x coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData.
  42162. * @param {number} y - The y coordinate of the pixel to be set. Must lay within the dimensions of this BitmapData.
  42163. * @param {object} [out] - An object into which 3 properties will be created: r, g and b. If not provided a new object will be created.
  42164. * @param {boolean} [hsl=false] - Also convert the rgb values into hsl?
  42165. * @param {boolean} [hsv=false] - Also convert the rgb values into hsv?
  42166. * @return {object} An object with the red, green and blue values set in the r, g and b properties.
  42167. */
  42168. getPixelRGB: function (x, y, out, hsl, hsv) {
  42169. return Phaser.Color.unpackPixel(this.getPixel32(x, y), out, hsl, hsv);
  42170. },
  42171. /**
  42172. * Gets all the pixels from the region specified by the given Rectangle object.
  42173. *
  42174. * @method Phaser.BitmapData#getPixels
  42175. * @param {Phaser.Rectangle} rect - The Rectangle region to get.
  42176. * @return {ImageData} Returns a ImageData object containing a Uint8ClampedArray data property.
  42177. */
  42178. getPixels: function (rect) {
  42179. return this.context.getImageData(rect.x, rect.y, rect.width, rect.height);
  42180. },
  42181. /**
  42182. * Scans the BitmapData, pixel by pixel, until it encounters a pixel that isn't transparent (i.e. has an alpha value > 0).
  42183. * It then stops scanning and returns an object containing the color of the pixel in r, g and b properties and the location in the x and y properties.
  42184. *
  42185. * The direction parameter controls from which direction it should start the scan:
  42186. *
  42187. * 0 = top to bottom
  42188. * 1 = bottom to top
  42189. * 2 = left to right
  42190. * 3 = right to left
  42191. *
  42192. * @method Phaser.BitmapData#getFirstPixel
  42193. * @param {number} [direction=0] - The direction in which to scan for the first pixel. 0 = top to bottom, 1 = bottom to top, 2 = left to right and 3 = right to left.
  42194. * @return {object} Returns an object containing the color of the pixel in the `r`, `g` and `b` properties and the location in the `x` and `y` properties.
  42195. */
  42196. getFirstPixel: function (direction) {
  42197. if (direction === undefined) { direction = 0; }
  42198. var pixel = Phaser.Color.createColor();
  42199. var x = 0;
  42200. var y = 0;
  42201. var v = 1;
  42202. var scan = false;
  42203. if (direction === 1)
  42204. {
  42205. v = -1;
  42206. y = this.height;
  42207. }
  42208. else if (direction === 3)
  42209. {
  42210. v = -1;
  42211. x = this.width;
  42212. }
  42213. do {
  42214. Phaser.Color.unpackPixel(this.getPixel32(x, y), pixel);
  42215. if (direction === 0 || direction === 1)
  42216. {
  42217. // Top to Bottom / Bottom to Top
  42218. x++;
  42219. if (x === this.width)
  42220. {
  42221. x = 0;
  42222. y += v;
  42223. if (y >= this.height || y <= 0)
  42224. {
  42225. scan = true;
  42226. }
  42227. }
  42228. }
  42229. else if (direction === 2 || direction === 3)
  42230. {
  42231. // Left to Right / Right to Left
  42232. y++;
  42233. if (y === this.height)
  42234. {
  42235. y = 0;
  42236. x += v;
  42237. if (x >= this.width || x <= 0)
  42238. {
  42239. scan = true;
  42240. }
  42241. }
  42242. }
  42243. }
  42244. while (pixel.a === 0 && !scan);
  42245. pixel.x = x;
  42246. pixel.y = y;
  42247. return pixel;
  42248. },
  42249. /**
  42250. * Scans the BitmapData and calculates the bounds. This is a rectangle that defines the extent of all non-transparent pixels.
  42251. * The rectangle returned will extend from the top-left of the image to the bottom-right, excluding transparent pixels.
  42252. *
  42253. * @method Phaser.BitmapData#getBounds
  42254. * @param {Phaser.Rectangle} [rect] - If provided this Rectangle object will be populated with the bounds, otherwise a new object will be created.
  42255. * @return {Phaser.Rectangle} A Rectangle whose dimensions encompass the full extent of non-transparent pixels in this BitmapData.
  42256. */
  42257. getBounds: function (rect) {
  42258. if (rect === undefined) { rect = new Phaser.Rectangle(); }
  42259. rect.x = this.getFirstPixel(2).x;
  42260. // If we hit this, there's no point scanning any more, the image is empty
  42261. if (rect.x === this.width)
  42262. {
  42263. return rect.setTo(0, 0, 0, 0);
  42264. }
  42265. rect.y = this.getFirstPixel(0).y;
  42266. rect.width = (this.getFirstPixel(3).x - rect.x) + 1;
  42267. rect.height = (this.getFirstPixel(1).y - rect.y) + 1;
  42268. return rect;
  42269. },
  42270. /**
  42271. * Creates a new Phaser.Image object, assigns this BitmapData to be its texture, adds it to the world then returns it.
  42272. *
  42273. * @method Phaser.BitmapData#addToWorld
  42274. * @param {number} [x=0] - The x coordinate to place the Image at.
  42275. * @param {number} [y=0] - The y coordinate to place the Image at.
  42276. * @param {number} [anchorX=0] - Set the x anchor point of the Image. A value between 0 and 1, where 0 is the top-left and 1 is bottom-right.
  42277. * @param {number} [anchorY=0] - Set the y anchor point of the Image. A value between 0 and 1, where 0 is the top-left and 1 is bottom-right.
  42278. * @param {number} [scaleX=1] - The horizontal scale factor of the Image. A value of 1 means no scaling. 2 would be twice the size, and so on.
  42279. * @param {number} [scaleY=1] - The vertical scale factor of the Image. A value of 1 means no scaling. 2 would be twice the size, and so on.
  42280. * @return {Phaser.Image} The newly added Image object.
  42281. */
  42282. addToWorld: function (x, y, anchorX, anchorY, scaleX, scaleY) {
  42283. scaleX = scaleX || 1;
  42284. scaleY = scaleY || 1;
  42285. var image = this.game.add.image(x, y, this);
  42286. image.anchor.set(anchorX, anchorY);
  42287. image.scale.set(scaleX, scaleY);
  42288. return image;
  42289. },
  42290. /**
  42291. * Copies a rectangular area from the source object to this BitmapData. If you give `null` as the source it will copy from itself.
  42292. *
  42293. * You can optionally resize, translate, rotate, scale, alpha or blend as it's drawn.
  42294. *
  42295. * All rotation, scaling and drawing takes place around the regions center point by default, but can be changed with the anchor parameters.
  42296. *
  42297. * Note that the source image can also be this BitmapData, which can create some interesting effects.
  42298. *
  42299. * This method has a lot of parameters for maximum control.
  42300. * You can use the more friendly methods like `copyRect` and `draw` to avoid having to remember them all.
  42301. *
  42302. * You may prefer to use `copyTransform` if you're simply trying to draw a Sprite to this BitmapData,
  42303. * and don't wish to translate, scale or rotate it from its original values.
  42304. *
  42305. * @method Phaser.BitmapData#copy
  42306. * @param {Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapData|Phaser.RenderTexture|Image|HTMLCanvasElement|string} [source] - The source to copy from. If you give a string it will try and find the Image in the Game.Cache first. This is quite expensive so try to provide the image itself.
  42307. * @param {number} [x=0] - The x coordinate representing the top-left of the region to copy from the source image.
  42308. * @param {number} [y=0] - The y coordinate representing the top-left of the region to copy from the source image.
  42309. * @param {number} [width] - The width of the region to copy from the source image. If not specified it will use the full source image width.
  42310. * @param {number} [height] - The height of the region to copy from the source image. If not specified it will use the full source image height.
  42311. * @param {number} [tx] - The x coordinate to translate to before drawing. If not specified it will default to the `x` parameter. If `null` and `source` is a Display Object, it will default to `source.x`.
  42312. * @param {number} [ty] - The y coordinate to translate to before drawing. If not specified it will default to the `y` parameter. If `null` and `source` is a Display Object, it will default to `source.y`.
  42313. * @param {number} [newWidth] - The new width of the block being copied. If not specified it will default to the `width` parameter.
  42314. * @param {number} [newHeight] - The new height of the block being copied. If not specified it will default to the `height` parameter.
  42315. * @param {number} [rotate=0] - The angle in radians to rotate the block to before drawing. Rotation takes place around the center by default, but can be changed with the `anchor` parameters.
  42316. * @param {number} [anchorX=0] - The anchor point around which the block is rotated and scaled. A value between 0 and 1, where 0 is the top-left and 1 is bottom-right.
  42317. * @param {number} [anchorY=0] - The anchor point around which the block is rotated and scaled. A value between 0 and 1, where 0 is the top-left and 1 is bottom-right.
  42318. * @param {number} [scaleX=1] - The horizontal scale factor of the block. A value of 1 means no scaling. 2 would be twice the size, and so on.
  42319. * @param {number} [scaleY=1] - The vertical scale factor of the block. A value of 1 means no scaling. 2 would be twice the size, and so on.
  42320. * @param {number} [alpha=1] - The alpha that will be set on the context before drawing. A value between 0 (fully transparent) and 1, opaque.
  42321. * @param {string} [blendMode=null] - The composite blend mode that will be used when drawing. The default is no blend mode at all. This is a Canvas globalCompositeOperation value such as 'lighter' or 'xor'.
  42322. * @param {boolean} [roundPx=false] - Should the x and y values be rounded to integers before drawing? This prevents anti-aliasing in some instances.
  42323. * @return {Phaser.BitmapData} This BitmapData object for method chaining.
  42324. */
  42325. copy: function (source, x, y, width, height, tx, ty, newWidth, newHeight, rotate, anchorX, anchorY, scaleX, scaleY, alpha, blendMode, roundPx) {
  42326. if (source === undefined || source === null) { source = this; }
  42327. if (source instanceof Phaser.RenderTexture || source instanceof PIXI.RenderTexture)
  42328. {
  42329. source = source.getCanvas();
  42330. }
  42331. this._image = source;
  42332. if (source instanceof Phaser.Sprite || source instanceof Phaser.Image || source instanceof Phaser.Text || source instanceof PIXI.Sprite)
  42333. {
  42334. // Copy over sprite values
  42335. this._pos.set(source.texture.crop.x, source.texture.crop.y);
  42336. this._size.set(source.texture.crop.width, source.texture.crop.height);
  42337. this._scale.set(source.scale.x, source.scale.y);
  42338. this._anchor.set(source.anchor.x, source.anchor.y);
  42339. this._rotate = source.rotation;
  42340. this._alpha.current = source.alpha;
  42341. if (source.texture instanceof Phaser.RenderTexture || source.texture instanceof PIXI.RenderTexture)
  42342. {
  42343. this._image = source.texture.getCanvas();
  42344. }
  42345. else
  42346. {
  42347. this._image = source.texture.baseTexture.source;
  42348. }
  42349. if (tx === undefined || tx === null) { tx = source.x; }
  42350. if (ty === undefined || ty === null) { ty = source.y; }
  42351. if (source.texture.trim)
  42352. {
  42353. // Offset the translation coordinates by the trim amount
  42354. tx += source.texture.trim.x - source.anchor.x * source.texture.trim.width;
  42355. ty += source.texture.trim.y - source.anchor.y * source.texture.trim.height;
  42356. }
  42357. if (source.tint !== 0xFFFFFF)
  42358. {
  42359. if (source.cachedTint !== source.tint)
  42360. {
  42361. source.cachedTint = source.tint;
  42362. source.tintedTexture = PIXI.CanvasTinter.getTintedTexture(source, source.tint);
  42363. }
  42364. this._image = source.tintedTexture;
  42365. this._pos.set(0);
  42366. }
  42367. }
  42368. else
  42369. {
  42370. // Reset
  42371. this._pos.set(0);
  42372. this._scale.set(1);
  42373. this._anchor.set(0);
  42374. this._rotate = 0;
  42375. this._alpha.current = 1;
  42376. if (source instanceof Phaser.BitmapData)
  42377. {
  42378. this._image = source.canvas;
  42379. }
  42380. else if (typeof source === 'string')
  42381. {
  42382. source = this.game.cache.getImage(source);
  42383. if (source === null)
  42384. {
  42385. return;
  42386. }
  42387. else
  42388. {
  42389. this._image = source;
  42390. }
  42391. }
  42392. this._size.set(this._image.width, this._image.height);
  42393. }
  42394. // The source region to copy from
  42395. if (x === undefined || x === null) { x = 0; }
  42396. if (y === undefined || y === null) { y = 0; }
  42397. // If they set a width/height then we override the frame values with them
  42398. if (width)
  42399. {
  42400. this._size.x = width;
  42401. }
  42402. if (height)
  42403. {
  42404. this._size.y = height;
  42405. }
  42406. // The destination region to copy to
  42407. if (tx === undefined || tx === null) { tx = x; }
  42408. if (ty === undefined || ty === null) { ty = y; }
  42409. if (newWidth === undefined || newWidth === null) { newWidth = this._size.x; }
  42410. if (newHeight === undefined || newHeight === null) { newHeight = this._size.y; }
  42411. // Rotation - if set this will override any potential Sprite value
  42412. if (typeof rotate === 'number')
  42413. {
  42414. this._rotate = rotate;
  42415. }
  42416. // Anchor - if set this will override any potential Sprite value
  42417. if (typeof anchorX === 'number')
  42418. {
  42419. this._anchor.x = anchorX;
  42420. }
  42421. if (typeof anchorY === 'number')
  42422. {
  42423. this._anchor.y = anchorY;
  42424. }
  42425. // Scaling - if set this will override any potential Sprite value
  42426. if (typeof scaleX === 'number')
  42427. {
  42428. this._scale.x = scaleX;
  42429. }
  42430. if (typeof scaleY === 'number')
  42431. {
  42432. this._scale.y = scaleY;
  42433. }
  42434. // Effects
  42435. if (typeof alpha === 'number')
  42436. {
  42437. this._alpha.current = alpha;
  42438. }
  42439. if (blendMode === undefined) { blendMode = null; }
  42440. if (roundPx === undefined) { roundPx = false; }
  42441. if (this._alpha.current <= 0 || this._scale.x === 0 || this._scale.y === 0 || this._size.x === 0 || this._size.y === 0)
  42442. {
  42443. // Why bother wasting CPU cycles drawing something you can't see?
  42444. return;
  42445. }
  42446. var ctx = this.context;
  42447. this._alpha.prev = ctx.globalAlpha;
  42448. ctx.save();
  42449. ctx.globalAlpha = this._alpha.current;
  42450. if (blendMode)
  42451. {
  42452. this.op = blendMode;
  42453. }
  42454. if (roundPx)
  42455. {
  42456. tx |= 0;
  42457. ty |= 0;
  42458. }
  42459. // Doesn't work fully with children, or nested scale + rotation transforms (see copyTransform)
  42460. ctx.translate(tx, ty);
  42461. ctx.scale(this._scale.x, this._scale.y);
  42462. ctx.rotate(this._rotate);
  42463. ctx.drawImage(this._image, this._pos.x + x, this._pos.y + y, this._size.x, this._size.y, -newWidth * this._anchor.x, -newHeight * this._anchor.y, newWidth, newHeight);
  42464. // Carry on ...
  42465. ctx.restore();
  42466. ctx.globalAlpha = this._alpha.prev;
  42467. this.dirty = true;
  42468. return this;
  42469. },
  42470. /**
  42471. * Draws the given `source` Game Object to this BitmapData, using its `worldTransform` property to set the
  42472. * position, scale and rotation of where it is drawn. This function is used internally by `drawGroup`.
  42473. * It takes the objects tint and scale mode into consideration before drawing.
  42474. *
  42475. * You can optionally specify Blend Mode and Round Pixels arguments.
  42476. *
  42477. * @method Phaser.BitmapData#copyTransform
  42478. * @param {Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapData|Phaser.BitmapText} [source] - The Game Object to draw.
  42479. * @param {string} [blendMode=null] - The composite blend mode that will be used when drawing. The default is no blend mode at all. This is a Canvas globalCompositeOperation value such as 'lighter' or 'xor'.
  42480. * @param {boolean} [roundPx=false] - Should the x and y values be rounded to integers before drawing? This prevents anti-aliasing in some instances.
  42481. * @return {Phaser.BitmapData} This BitmapData object for method chaining.
  42482. */
  42483. copyTransform: function (source, blendMode, roundPx) {
  42484. if (blendMode === undefined) { blendMode = null; }
  42485. if (roundPx === undefined) { roundPx = false; }
  42486. if (!source.hasOwnProperty('worldTransform') || !source.worldVisible || source.worldAlpha === 0)
  42487. {
  42488. return this;
  42489. }
  42490. var wt = source.worldTransform;
  42491. this._pos.set(source.texture.crop.x, source.texture.crop.y);
  42492. this._size.set(source.texture.crop.width, source.texture.crop.height);
  42493. if (wt.a === 0 || wt.d === 0 || this._size.x === 0 || this._size.y === 0)
  42494. {
  42495. // Why bother wasting CPU cycles drawing something you can't see?
  42496. return this;
  42497. }
  42498. if (source.texture instanceof Phaser.RenderTexture || source.texture instanceof PIXI.RenderTexture)
  42499. {
  42500. this._image = source.texture.getCanvas();
  42501. }
  42502. else
  42503. {
  42504. this._image = source.texture.baseTexture.source;
  42505. }
  42506. var tx = wt.tx;
  42507. var ty = wt.ty;
  42508. if (source.texture.trim)
  42509. {
  42510. // Offset the translation coordinates by the trim amount
  42511. tx += source.texture.trim.x - source.anchor.x * source.texture.trim.width;
  42512. ty += source.texture.trim.y - source.anchor.y * source.texture.trim.height;
  42513. }
  42514. if (source.tint !== 0xFFFFFF)
  42515. {
  42516. if (source.cachedTint !== source.tint)
  42517. {
  42518. source.cachedTint = source.tint;
  42519. source.tintedTexture = PIXI.CanvasTinter.getTintedTexture(source, source.tint);
  42520. }
  42521. this._image = source.tintedTexture;
  42522. this._pos.set(0);
  42523. }
  42524. if (roundPx)
  42525. {
  42526. tx |= 0;
  42527. ty |= 0;
  42528. }
  42529. var ctx = this.context;
  42530. this._alpha.prev = ctx.globalAlpha;
  42531. ctx.save();
  42532. ctx.globalAlpha = this._alpha.current;
  42533. if (blendMode)
  42534. {
  42535. this.op = blendMode;
  42536. }
  42537. ctx[this.smoothProperty] = (source.texture.baseTexture.scaleMode === PIXI.scaleModes.LINEAR);
  42538. ctx.setTransform(wt.a, wt.b, wt.c, wt.d, tx, ty);
  42539. ctx.drawImage(this._image,
  42540. this._pos.x,
  42541. this._pos.y,
  42542. this._size.x,
  42543. this._size.y,
  42544. -this._size.x * source.anchor.x,
  42545. -this._size.y * source.anchor.y,
  42546. this._size.x,
  42547. this._size.y);
  42548. ctx.restore();
  42549. ctx.globalAlpha = this._alpha.prev;
  42550. this.dirty = true;
  42551. return this;
  42552. },
  42553. /**
  42554. * Copies the area defined by the Rectangle parameter from the source image to this BitmapData at the given location.
  42555. *
  42556. * @method Phaser.BitmapData#copyRect
  42557. * @param {Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapData|Phaser.RenderTexture|Image|string} source - The Image to copy from. If you give a string it will try and find the Image in the Game.Cache.
  42558. * @param {Phaser.Rectangle} area - The Rectangle region to copy from the source image.
  42559. * @param {number} x - The destination x coordinate to copy the image to.
  42560. * @param {number} y - The destination y coordinate to copy the image to.
  42561. * @param {number} [alpha=1] - The alpha that will be set on the context before drawing. A value between 0 (fully transparent) and 1, opaque.
  42562. * @param {string} [blendMode=null] - The composite blend mode that will be used when drawing. The default is no blend mode at all. This is a Canvas globalCompositeOperation value such as 'lighter' or 'xor'.
  42563. * @param {boolean} [roundPx=false] - Should the x and y values be rounded to integers before drawing? This prevents anti-aliasing in some instances.
  42564. * @return {Phaser.BitmapData} This BitmapData object for method chaining.
  42565. */
  42566. copyRect: function (source, area, x, y, alpha, blendMode, roundPx) {
  42567. return this.copy(source, area.x, area.y, area.width, area.height, x, y, area.width, area.height, 0, 0, 0, 1, 1, alpha, blendMode, roundPx);
  42568. },
  42569. /**
  42570. * Draws the given Phaser.Sprite, Phaser.Image or Phaser.Text to this BitmapData at the coordinates specified.
  42571. * You can use the optional width and height values to 'stretch' the sprite as it is drawn. This uses drawImage stretching, not scaling.
  42572. *
  42573. * The children will be drawn at their `x` and `y` world space coordinates. If this is outside the bounds of the BitmapData they won't be visible.
  42574. * When drawing it will take into account the rotation, scale, scaleMode, alpha and tint values.
  42575. *
  42576. * Note: You should ensure that at least 1 full update has taken place before calling this,
  42577. * otherwise the objects are likely to render incorrectly, if at all.
  42578. * You can trigger an update yourself by calling `stage.updateTransform()` before calling `draw`.
  42579. *
  42580. * @method Phaser.BitmapData#draw
  42581. * @param {Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.RenderTexture} source - The Sprite, Image or Text object to draw onto this BitmapData.
  42582. * @param {number} [x=0] - The x coordinate to translate to before drawing. If not specified it will default to `source.x`.
  42583. * @param {number} [y=0] - The y coordinate to translate to before drawing. If not specified it will default to `source.y`.
  42584. * @param {number} [width] - The new width of the Sprite being copied. If not specified it will default to `source.width`.
  42585. * @param {number} [height] - The new height of the Sprite being copied. If not specified it will default to `source.height`.
  42586. * @param {string} [blendMode=null] - The composite blend mode that will be used when drawing. The default is no blend mode at all. This is a Canvas globalCompositeOperation value such as 'lighter' or 'xor'.
  42587. * @param {boolean} [roundPx=false] - Should the x and y values be rounded to integers before drawing? This prevents anti-aliasing in some instances.
  42588. * @return {Phaser.BitmapData} This BitmapData object for method chaining.
  42589. */
  42590. draw: function (source, x, y, width, height, blendMode, roundPx) {
  42591. // By specifying null for most parameters it will tell `copy` to use the Sprite values instead, which is what we want here
  42592. return this.copy(source, null, null, null, null, x, y, width, height, null, null, null, null, null, null, blendMode, roundPx);
  42593. },
  42594. /**
  42595. * Draws the immediate children of a Phaser.Group to this BitmapData.
  42596. *
  42597. * It's perfectly valid to pass in `game.world` as the Group, and it will iterate through the entire display list.
  42598. *
  42599. * Children are drawn _only_ if they have their `exists` property set to `true`, and have image, or RenderTexture, based Textures.
  42600. *
  42601. * The children will be drawn at their `x` and `y` world space coordinates. If this is outside the bounds of the BitmapData they won't be visible.
  42602. * When drawing it will take into account the rotation, scale, scaleMode, alpha and tint values.
  42603. *
  42604. * Note: You should ensure that at least 1 full update has taken place before calling this,
  42605. * otherwise the objects are likely to render incorrectly, if at all.
  42606. * You can trigger an update yourself by calling `stage.updateTransform()` before calling `drawGroup`.
  42607. *
  42608. * @method Phaser.BitmapData#drawGroup
  42609. * @param {Phaser.Group} group - The Group to draw onto this BitmapData. Can also be Phaser.World.
  42610. * @param {string} [blendMode=null] - The composite blend mode that will be used when drawing. The default is no blend mode at all. This is a Canvas globalCompositeOperation value such as 'lighter' or 'xor'.
  42611. * @param {boolean} [roundPx=false] - Should the x and y values be rounded to integers before drawing? This prevents anti-aliasing in some instances.
  42612. * @return {Phaser.BitmapData} This BitmapData object for method chaining.
  42613. */
  42614. drawGroup: function (group, blendMode, roundPx) {
  42615. if (group.total > 0)
  42616. {
  42617. group.forEachExists(this.drawGroupProxy, this, blendMode, roundPx);
  42618. }
  42619. return this;
  42620. },
  42621. /**
  42622. * A proxy for drawGroup that handles child iteration for more complex Game Objects.
  42623. *
  42624. * @method Phaser.BitmapData#drawGroupProxy
  42625. * @private
  42626. * @param {Phaser.Sprite|Phaser.Image|Phaser.BitmapText} child - The child to draw.
  42627. * @param {string} [blendMode=null] - The composite blend mode that will be used when drawing. The default is no blend mode at all. This is a Canvas globalCompositeOperation value such as 'lighter' or 'xor'.
  42628. * @param {boolean} [roundPx=false] - Should the x and y values be rounded to integers before drawing? This prevents anti-aliasing in some instances.
  42629. */
  42630. drawGroupProxy: function (child, blendMode, roundPx) {
  42631. if (child.hasOwnProperty('texture'))
  42632. {
  42633. this.copyTransform(child, blendMode, roundPx);
  42634. }
  42635. if (child.type === Phaser.GROUP && child.exists)
  42636. {
  42637. this.drawGroup(child, blendMode, roundPx);
  42638. }
  42639. else
  42640. {
  42641. if (child.hasOwnProperty('children') && child.children.length > 0)
  42642. {
  42643. for (var i = 0; i < child.children.length; i++)
  42644. {
  42645. if (child.children[i].exists)
  42646. {
  42647. this.copyTransform(child.children[i], blendMode, roundPx);
  42648. }
  42649. }
  42650. }
  42651. }
  42652. },
  42653. /**
  42654. * Draws the Game Object or Group to this BitmapData and then recursively iterates through all of its children.
  42655. *
  42656. * If a child has an `exists` property then it (and its children) will be only be drawn if exists is `true`.
  42657. *
  42658. * The children will be drawn at their `x` and `y` world space coordinates. If this is outside the bounds of the BitmapData
  42659. * they won't be drawn. Depending on your requirements you may need to resize the BitmapData in advance to match the
  42660. * bounds of the top-level Game Object.
  42661. *
  42662. * When drawing it will take into account the child's world rotation, scale and alpha values.
  42663. *
  42664. * It's perfectly valid to pass in `game.world` as the parent object, and it will iterate through the entire display list.
  42665. *
  42666. * Note: If you are trying to grab your entire game at the start of a State then you should ensure that at least 1 full update
  42667. * has taken place before doing so, otherwise all of the objects will render with incorrect positions and scales. You can
  42668. * trigger an update yourself by calling `stage.updateTransform()` before calling `drawFull`.
  42669. *
  42670. * @method Phaser.BitmapData#drawFull
  42671. * @param {Phaser.World|Phaser.Group|Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapText} parent - The Game Object to draw onto this BitmapData and then recursively draw all of its children.
  42672. * @param {string} [blendMode=null] - The composite blend mode that will be used when drawing. The default is no blend mode at all. This is a Canvas globalCompositeOperation value such as 'lighter' or 'xor'.
  42673. * @param {boolean} [roundPx=false] - Should the x and y values be rounded to integers before drawing? This prevents anti-aliasing in some instances.
  42674. * @return {Phaser.BitmapData} This BitmapData object for method chaining.
  42675. */
  42676. drawFull: function (parent, blendMode, roundPx) {
  42677. if (parent.worldVisible === false || parent.worldAlpha === 0 || (parent.hasOwnProperty('exists') && parent.exists === false))
  42678. {
  42679. return this;
  42680. }
  42681. if (parent.type !== Phaser.GROUP && parent.type !== Phaser.EMITTER && parent.type !== Phaser.BITMAPTEXT)
  42682. {
  42683. if (parent.type === Phaser.GRAPHICS)
  42684. {
  42685. var bounds = parent.getBounds();
  42686. this.ctx.save();
  42687. this.ctx.translate(bounds.x, bounds.y);
  42688. PIXI.CanvasGraphics.renderGraphics(parent, this.ctx);
  42689. this.ctx.restore();
  42690. }
  42691. else
  42692. {
  42693. this.copy(parent, null, null, null, null, parent.worldPosition.x, parent.worldPosition.y, null, null, parent.worldRotation, null, null, parent.worldScale.x, parent.worldScale.y, parent.worldAlpha, blendMode, roundPx);
  42694. }
  42695. }
  42696. if (parent.children)
  42697. {
  42698. for (var i = 0; i < parent.children.length; i++)
  42699. {
  42700. this.drawFull(parent.children[i], blendMode, roundPx);
  42701. }
  42702. }
  42703. return this;
  42704. },
  42705. /**
  42706. * Sets the shadow properties of this BitmapDatas context which will affect all draw operations made to it.
  42707. * You can cancel an existing shadow by calling this method and passing no parameters.
  42708. * Note: At the time of writing (October 2014) Chrome still doesn't support shadowBlur used with drawImage.
  42709. *
  42710. * @method Phaser.BitmapData#shadow
  42711. * @param {string} color - The color of the shadow, given in a CSS format, i.e. `#000000` or `rgba(0,0,0,1)`. If `null` or `undefined` the shadow will be reset.
  42712. * @param {number} [blur=5] - The amount the shadow will be blurred by. Low values = a crisp shadow, high values = a softer shadow.
  42713. * @param {number} [x=10] - The horizontal offset of the shadow in pixels.
  42714. * @param {number} [y=10] - The vertical offset of the shadow in pixels.
  42715. * @return {Phaser.BitmapData} This BitmapData object for method chaining.
  42716. */
  42717. shadow: function (color, blur, x, y) {
  42718. var ctx = this.context;
  42719. if (color === undefined || color === null)
  42720. {
  42721. ctx.shadowColor = 'rgba(0,0,0,0)';
  42722. }
  42723. else
  42724. {
  42725. ctx.shadowColor = color;
  42726. ctx.shadowBlur = blur || 5;
  42727. ctx.shadowOffsetX = x || 10;
  42728. ctx.shadowOffsetY = y || 10;
  42729. }
  42730. return this;
  42731. },
  42732. /**
  42733. * Draws the image onto this BitmapData using an image as an alpha mask.
  42734. *
  42735. * @method Phaser.BitmapData#alphaMask
  42736. * @param {Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapData|Image|HTMLCanvasElement|string} source - The source to copy from. If you give a string it will try and find the Image in the Game.Cache first. This is quite expensive so try to provide the image itself.
  42737. * @param {Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapData|Image|HTMLCanvasElement|string} [mask] - The object to be used as the mask. If you give a string it will try and find the Image in the Game.Cache first. This is quite expensive so try to provide the image itself. If you don't provide a mask it will use this BitmapData as the mask.
  42738. * @param {Phaser.Rectangle} [sourceRect] - A Rectangle where x/y define the coordinates to draw the Source image to and width/height define the size.
  42739. * @param {Phaser.Rectangle} [maskRect] - A Rectangle where x/y define the coordinates to draw the Mask image to and width/height define the size.
  42740. * @return {Phaser.BitmapData} This BitmapData object for method chaining.
  42741. */
  42742. alphaMask: function (source, mask, sourceRect, maskRect) {
  42743. if (maskRect === undefined || maskRect === null)
  42744. {
  42745. this.draw(mask).blendSourceAtop();
  42746. }
  42747. else
  42748. {
  42749. this.draw(mask, maskRect.x, maskRect.y, maskRect.width, maskRect.height).blendSourceAtop();
  42750. }
  42751. if (sourceRect === undefined || sourceRect === null)
  42752. {
  42753. this.draw(source).blendReset();
  42754. }
  42755. else
  42756. {
  42757. this.draw(source, sourceRect.x, sourceRect.y, sourceRect.width, sourceRect.height).blendReset();
  42758. }
  42759. return this;
  42760. },
  42761. /**
  42762. * Scans this BitmapData for all pixels matching the given r,g,b values and then draws them into the given destination BitmapData.
  42763. * The original BitmapData remains unchanged.
  42764. * The destination BitmapData must be large enough to receive all of the pixels that are scanned unless the 'resize' parameter is true.
  42765. * Although the destination BitmapData is returned from this method, it's actually modified directly in place, meaning this call is perfectly valid:
  42766. * `picture.extract(mask, r, g, b)`
  42767. * You can specify optional r2, g2, b2 color values. If given the pixel written to the destination bitmap will be of the r2, g2, b2 color.
  42768. * If not given it will be written as the same color it was extracted. You can provide one or more alternative colors, allowing you to tint
  42769. * the color during extraction.
  42770. *
  42771. * @method Phaser.BitmapData#extract
  42772. * @param {Phaser.BitmapData} destination - The BitmapData that the extracted pixels will be drawn to.
  42773. * @param {number} r - The red color component, in the range 0 - 255.
  42774. * @param {number} g - The green color component, in the range 0 - 255.
  42775. * @param {number} b - The blue color component, in the range 0 - 255.
  42776. * @param {number} [a=255] - The alpha color component, in the range 0 - 255 that the new pixel will be drawn at.
  42777. * @param {boolean} [resize=false] - Should the destination BitmapData be resized to match this one before the pixels are copied?
  42778. * @param {number} [r2] - An alternative red color component to be written to the destination, in the range 0 - 255.
  42779. * @param {number} [g2] - An alternative green color component to be written to the destination, in the range 0 - 255.
  42780. * @param {number} [b2] - An alternative blue color component to be written to the destination, in the range 0 - 255.
  42781. * @returns {Phaser.BitmapData} The BitmapData that the extract pixels were drawn on.
  42782. */
  42783. extract: function (destination, r, g, b, a, resize, r2, g2, b2) {
  42784. if (a === undefined) { a = 255; }
  42785. if (resize === undefined) { resize = false; }
  42786. if (r2 === undefined) { r2 = r; }
  42787. if (g2 === undefined) { g2 = g; }
  42788. if (b2 === undefined) { b2 = b; }
  42789. if (resize)
  42790. {
  42791. destination.resize(this.width, this.height);
  42792. }
  42793. this.processPixelRGB(
  42794. function (pixel, x, y)
  42795. {
  42796. if (pixel.r === r && pixel.g === g && pixel.b === b)
  42797. {
  42798. destination.setPixel32(x, y, r2, g2, b2, a, false);
  42799. }
  42800. return false;
  42801. },
  42802. this);
  42803. destination.context.putImageData(destination.imageData, 0, 0);
  42804. destination.dirty = true;
  42805. return destination;
  42806. },
  42807. /**
  42808. * Draws a filled Rectangle to the BitmapData at the given x, y coordinates and width / height in size.
  42809. *
  42810. * @method Phaser.BitmapData#rect
  42811. * @param {number} x - The x coordinate of the top-left of the Rectangle.
  42812. * @param {number} y - The y coordinate of the top-left of the Rectangle.
  42813. * @param {number} width - The width of the Rectangle.
  42814. * @param {number} height - The height of the Rectangle.
  42815. * @param {string} [fillStyle] - If set the context fillStyle will be set to this value before the rect is drawn.
  42816. * @return {Phaser.BitmapData} This BitmapData object for method chaining.
  42817. */
  42818. rect: function (x, y, width, height, fillStyle) {
  42819. if (typeof fillStyle !== 'undefined')
  42820. {
  42821. this.context.fillStyle = fillStyle;
  42822. }
  42823. this.context.fillRect(x, y, width, height);
  42824. return this;
  42825. },
  42826. /**
  42827. * Draws text to the BitmapData in the given font and color.
  42828. * The default font is 14px Courier, so useful for quickly drawing debug text.
  42829. * If you need to do a lot of font work to this BitmapData we'd recommend implementing your own text draw method.
  42830. *
  42831. * @method Phaser.BitmapData#text
  42832. * @param {string} text - The text to write to the BitmapData.
  42833. * @param {number} x - The x coordinate of the top-left of the text string.
  42834. * @param {number} y - The y coordinate of the top-left of the text string.
  42835. * @param {string} [font='14px Courier'] - The font. This is passed directly to Context.font, so anything that can support, this can.
  42836. * @param {string} [color='rgb(255,255,255)'] - The color the text will be drawn in.
  42837. * @param {boolean} [shadow=true] - Draw a single pixel black shadow below the text (offset by text.x/y + 1)
  42838. * @return {Phaser.BitmapData} This BitmapData object for method chaining.
  42839. */
  42840. text: function (text, x, y, font, color, shadow) {
  42841. if (x === undefined) { x = 0; }
  42842. if (y === undefined) { y = 0; }
  42843. if (font === undefined) { font = '14px Courier'; }
  42844. if (color === undefined) { color = 'rgb(255,255,255)'; }
  42845. if (shadow === undefined) { shadow = true; }
  42846. var ctx = this.context;
  42847. var prevFont = ctx.font;
  42848. ctx.font = font;
  42849. if (shadow)
  42850. {
  42851. ctx.fillStyle = 'rgb(0,0,0)';
  42852. ctx.fillText(text, x + 1, y + 1);
  42853. }
  42854. ctx.fillStyle = color;
  42855. ctx.fillText(text, x, y);
  42856. ctx.font = prevFont;
  42857. return this;
  42858. },
  42859. /**
  42860. * Draws a filled Circle to the BitmapData at the given x, y coordinates and radius in size.
  42861. *
  42862. * @method Phaser.BitmapData#circle
  42863. * @param {number} x - The x coordinate to draw the Circle at. This is the center of the circle.
  42864. * @param {number} y - The y coordinate to draw the Circle at. This is the center of the circle.
  42865. * @param {number} radius - The radius of the Circle in pixels. The radius is half the diameter.
  42866. * @param {string} [fillStyle] - If set the context fillStyle will be set to this value before the circle is drawn.
  42867. * @return {Phaser.BitmapData} This BitmapData object for method chaining.
  42868. */
  42869. circle: function (x, y, radius, fillStyle) {
  42870. var ctx = this.context;
  42871. if (fillStyle !== undefined)
  42872. {
  42873. ctx.fillStyle = fillStyle;
  42874. }
  42875. ctx.beginPath();
  42876. ctx.arc(x, y, radius, 0, Math.PI * 2, false);
  42877. ctx.closePath();
  42878. ctx.fill();
  42879. return this;
  42880. },
  42881. /**
  42882. * Draws a line between the coordinates given in the color and thickness specified.
  42883. *
  42884. * @method Phaser.BitmapData#line
  42885. * @param {number} x1 - The x coordinate to start the line from.
  42886. * @param {number} y1 - The y coordinate to start the line from.
  42887. * @param {number} x2 - The x coordinate to draw the line to.
  42888. * @param {number} y2 - The y coordinate to draw the line to.
  42889. * @param {string} [color='#fff'] - The stroke color that the line will be drawn in.
  42890. * @param {number} [width=1] - The line thickness.
  42891. * @return {Phaser.BitmapData} This BitmapData object for method chaining.
  42892. */
  42893. line: function (x1, y1, x2, y2, color, width) {
  42894. if (color === undefined) { color = '#fff'; }
  42895. if (width === undefined) { width = 1; }
  42896. var ctx = this.context;
  42897. ctx.beginPath();
  42898. ctx.moveTo(x1, y1);
  42899. ctx.lineTo(x2, y2);
  42900. ctx.lineWidth = width;
  42901. ctx.strokeStyle = color;
  42902. ctx.stroke();
  42903. ctx.closePath();
  42904. return this;
  42905. },
  42906. /**
  42907. * Takes the given Line object and image and renders it to this BitmapData as a repeating texture line.
  42908. *
  42909. * @method Phaser.BitmapData#textureLine
  42910. * @param {Phaser.Line} line - A Phaser.Line object that will be used to plot the start and end of the line.
  42911. * @param {string|Image} image - The key of an image in the Phaser.Cache to use as the texture for this line, or an actual Image.
  42912. * @param {string} [repeat='repeat-x'] - The pattern repeat mode to use when drawing the line. Either `repeat`, `repeat-x` or `no-repeat`.
  42913. * @return {Phaser.BitmapData} This BitmapData object for method chaining.
  42914. */
  42915. textureLine: function (line, image, repeat) {
  42916. if (repeat === undefined) { repeat = 'repeat-x'; }
  42917. if (typeof image === 'string')
  42918. {
  42919. image = this.game.cache.getImage(image);
  42920. if (!image)
  42921. {
  42922. return;
  42923. }
  42924. }
  42925. var width = line.length;
  42926. if (repeat === 'no-repeat' && width > image.width)
  42927. {
  42928. width = image.width;
  42929. }
  42930. var ctx = this.context;
  42931. ctx.fillStyle = ctx.createPattern(image, repeat);
  42932. this._circle = new Phaser.Circle(line.start.x, line.start.y, image.height);
  42933. this._circle.circumferencePoint(line.angle - 1.5707963267948966, false, this._pos);
  42934. ctx.save();
  42935. ctx.translate(this._pos.x, this._pos.y);
  42936. ctx.rotate(line.angle);
  42937. ctx.fillRect(0, 0, width, image.height);
  42938. ctx.restore();
  42939. this.dirty = true;
  42940. return this;
  42941. },
  42942. /**
  42943. * If the game is running in WebGL this will push the texture up to the GPU if it's dirty.
  42944. * This is called automatically if the BitmapData is being used by a Sprite, otherwise you need to remember to call it in your render function.
  42945. * If you wish to suppress this functionality set BitmapData.disableTextureUpload to `true`.
  42946. *
  42947. * @method Phaser.BitmapData#render
  42948. * @return {Phaser.BitmapData} This BitmapData object for method chaining.
  42949. */
  42950. render: function () {
  42951. if (!this.disableTextureUpload && this.dirty)
  42952. {
  42953. this.baseTexture.dirty();
  42954. this.dirty = false;
  42955. }
  42956. return this;
  42957. },
  42958. /**
  42959. * Destroys this BitmapData and puts the canvas it was using back into the canvas pool for re-use.
  42960. *
  42961. * @method Phaser.BitmapData#destroy
  42962. */
  42963. destroy: function () {
  42964. this.frameData.destroy();
  42965. this.texture.destroy(true);
  42966. PIXI.CanvasPool.remove(this);
  42967. },
  42968. /**
  42969. * Resets the blend mode (effectively sets it to 'source-over')
  42970. *
  42971. * @method Phaser.BitmapData#blendReset
  42972. * @return {Phaser.BitmapData} This BitmapData object for method chaining.
  42973. */
  42974. blendReset: function () {
  42975. this.op = 'source-over';
  42976. return this;
  42977. },
  42978. /**
  42979. * Sets the blend mode to 'source-over'
  42980. *
  42981. * @method Phaser.BitmapData#blendSourceOver
  42982. * @return {Phaser.BitmapData} This BitmapData object for method chaining.
  42983. */
  42984. blendSourceOver: function () {
  42985. this.op = 'source-over';
  42986. return this;
  42987. },
  42988. /**
  42989. * Sets the blend mode to 'source-in'
  42990. *
  42991. * @method Phaser.BitmapData#blendSourceIn
  42992. * @return {Phaser.BitmapData} This BitmapData object for method chaining.
  42993. */
  42994. blendSourceIn: function () {
  42995. this.op = 'source-in';
  42996. return this;
  42997. },
  42998. /**
  42999. * Sets the blend mode to 'source-out'
  43000. *
  43001. * @method Phaser.BitmapData#blendSourceOut
  43002. * @return {Phaser.BitmapData} This BitmapData object for method chaining.
  43003. */
  43004. blendSourceOut: function () {
  43005. this.op = 'source-out';
  43006. return this;
  43007. },
  43008. /**
  43009. * Sets the blend mode to 'source-atop'
  43010. *
  43011. * @method Phaser.BitmapData#blendSourceAtop
  43012. * @return {Phaser.BitmapData} This BitmapData object for method chaining.
  43013. */
  43014. blendSourceAtop: function () {
  43015. this.op = 'source-atop';
  43016. return this;
  43017. },
  43018. /**
  43019. * Sets the blend mode to 'destination-over'
  43020. *
  43021. * @method Phaser.BitmapData#blendDestinationOver
  43022. * @return {Phaser.BitmapData} This BitmapData object for method chaining.
  43023. */
  43024. blendDestinationOver: function () {
  43025. this.op = 'destination-over';
  43026. return this;
  43027. },
  43028. /**
  43029. * Sets the blend mode to 'destination-in'
  43030. *
  43031. * @method Phaser.BitmapData#blendDestinationIn
  43032. * @return {Phaser.BitmapData} This BitmapData object for method chaining.
  43033. */
  43034. blendDestinationIn: function () {
  43035. this.op = 'destination-in';
  43036. return this;
  43037. },
  43038. /**
  43039. * Sets the blend mode to 'destination-out'
  43040. *
  43041. * @method Phaser.BitmapData#blendDestinationOut
  43042. * @return {Phaser.BitmapData} This BitmapData object for method chaining.
  43043. */
  43044. blendDestinationOut: function () {
  43045. this.op = 'destination-out';
  43046. return this;
  43047. },
  43048. /**
  43049. * Sets the blend mode to 'destination-atop'
  43050. *
  43051. * @method Phaser.BitmapData#blendDestinationAtop
  43052. * @return {Phaser.BitmapData} This BitmapData object for method chaining.
  43053. */
  43054. blendDestinationAtop: function () {
  43055. this.op = 'destination-atop';
  43056. return this;
  43057. },
  43058. /**
  43059. * Sets the blend mode to 'xor'
  43060. *
  43061. * @method Phaser.BitmapData#blendXor
  43062. * @return {Phaser.BitmapData} This BitmapData object for method chaining.
  43063. */
  43064. blendXor: function () {
  43065. this.op = 'xor';
  43066. return this;
  43067. },
  43068. /**
  43069. * Sets the blend mode to 'lighter'
  43070. *
  43071. * @method Phaser.BitmapData#blendAdd
  43072. * @return {Phaser.BitmapData} This BitmapData object for method chaining.
  43073. */
  43074. blendAdd: function () {
  43075. this.op = 'lighter';
  43076. return this;
  43077. },
  43078. /**
  43079. * Sets the blend mode to 'multiply'
  43080. *
  43081. * @method Phaser.BitmapData#blendMultiply
  43082. * @return {Phaser.BitmapData} This BitmapData object for method chaining.
  43083. */
  43084. blendMultiply: function () {
  43085. this.op = 'multiply';
  43086. return this;
  43087. },
  43088. /**
  43089. * Sets the blend mode to 'screen'
  43090. *
  43091. * @method Phaser.BitmapData#blendScreen
  43092. * @return {Phaser.BitmapData} This BitmapData object for method chaining.
  43093. */
  43094. blendScreen: function () {
  43095. this.op = 'screen';
  43096. return this;
  43097. },
  43098. /**
  43099. * Sets the blend mode to 'overlay'
  43100. *
  43101. * @method Phaser.BitmapData#blendOverlay
  43102. * @return {Phaser.BitmapData} This BitmapData object for method chaining.
  43103. */
  43104. blendOverlay: function () {
  43105. this.op = 'overlay';
  43106. return this;
  43107. },
  43108. /**
  43109. * Sets the blend mode to 'darken'
  43110. *
  43111. * @method Phaser.BitmapData#blendDarken
  43112. * @return {Phaser.BitmapData} This BitmapData object for method chaining.
  43113. */
  43114. blendDarken: function () {
  43115. this.op = 'darken';
  43116. return this;
  43117. },
  43118. /**
  43119. * Sets the blend mode to 'lighten'
  43120. *
  43121. * @method Phaser.BitmapData#blendLighten
  43122. * @return {Phaser.BitmapData} This BitmapData object for method chaining.
  43123. */
  43124. blendLighten: function () {
  43125. this.op = 'lighten';
  43126. return this;
  43127. },
  43128. /**
  43129. * Sets the blend mode to 'color-dodge'
  43130. *
  43131. * @method Phaser.BitmapData#blendColorDodge
  43132. * @return {Phaser.BitmapData} This BitmapData object for method chaining.
  43133. */
  43134. blendColorDodge: function () {
  43135. this.op = 'color-dodge';
  43136. return this;
  43137. },
  43138. /**
  43139. * Sets the blend mode to 'color-burn'
  43140. *
  43141. * @method Phaser.BitmapData#blendColorBurn
  43142. * @return {Phaser.BitmapData} This BitmapData object for method chaining.
  43143. */
  43144. blendColorBurn: function () {
  43145. this.op = 'color-burn';
  43146. return this;
  43147. },
  43148. /**
  43149. * Sets the blend mode to 'hard-light'
  43150. *
  43151. * @method Phaser.BitmapData#blendHardLight
  43152. * @return {Phaser.BitmapData} This BitmapData object for method chaining.
  43153. */
  43154. blendHardLight: function () {
  43155. this.op = 'hard-light';
  43156. return this;
  43157. },
  43158. /**
  43159. * Sets the blend mode to 'soft-light'
  43160. *
  43161. * @method Phaser.BitmapData#blendSoftLight
  43162. * @return {Phaser.BitmapData} This BitmapData object for method chaining.
  43163. */
  43164. blendSoftLight: function () {
  43165. this.op = 'soft-light';
  43166. return this;
  43167. },
  43168. /**
  43169. * Sets the blend mode to 'difference'
  43170. *
  43171. * @method Phaser.BitmapData#blendDifference
  43172. * @return {Phaser.BitmapData} This BitmapData object for method chaining.
  43173. */
  43174. blendDifference: function () {
  43175. this.op = 'difference';
  43176. return this;
  43177. },
  43178. /**
  43179. * Sets the blend mode to 'exclusion'
  43180. *
  43181. * @method Phaser.BitmapData#blendExclusion
  43182. * @return {Phaser.BitmapData} This BitmapData object for method chaining.
  43183. */
  43184. blendExclusion: function () {
  43185. this.op = 'exclusion';
  43186. return this;
  43187. },
  43188. /**
  43189. * Sets the blend mode to 'hue'
  43190. *
  43191. * @method Phaser.BitmapData#blendHue
  43192. * @return {Phaser.BitmapData} This BitmapData object for method chaining.
  43193. */
  43194. blendHue: function () {
  43195. this.op = 'hue';
  43196. return this;
  43197. },
  43198. /**
  43199. * Sets the blend mode to 'saturation'
  43200. *
  43201. * @method Phaser.BitmapData#blendSaturation
  43202. * @return {Phaser.BitmapData} This BitmapData object for method chaining.
  43203. */
  43204. blendSaturation: function () {
  43205. this.op = 'saturation';
  43206. return this;
  43207. },
  43208. /**
  43209. * Sets the blend mode to 'color'
  43210. *
  43211. * @method Phaser.BitmapData#blendColor
  43212. * @return {Phaser.BitmapData} This BitmapData object for method chaining.
  43213. */
  43214. blendColor: function () {
  43215. this.op = 'color';
  43216. return this;
  43217. },
  43218. /**
  43219. * Sets the blend mode to 'luminosity'
  43220. *
  43221. * @method Phaser.BitmapData#blendLuminosity
  43222. * @return {Phaser.BitmapData} This BitmapData object for method chaining.
  43223. */
  43224. blendLuminosity: function () {
  43225. this.op = 'luminosity';
  43226. return this;
  43227. }
  43228. };
  43229. /**
  43230. * @memberof Phaser.BitmapData
  43231. * @property {boolean} smoothed - Gets or sets this BitmapData.contexts smoothing enabled value.
  43232. */
  43233. Object.defineProperty(Phaser.BitmapData.prototype, "smoothed", {
  43234. get: function () {
  43235. Phaser.Canvas.getSmoothingEnabled(this.context);
  43236. },
  43237. set: function (value) {
  43238. Phaser.Canvas.setSmoothingEnabled(this.context, value);
  43239. }
  43240. });
  43241. /**
  43242. * @memberof Phaser.BitmapData
  43243. * @property {string} op - A short-hand code to get or set the global composite operation of the BitmapDatas canvas.
  43244. */
  43245. Object.defineProperty(Phaser.BitmapData.prototype, "op", {
  43246. get: function () {
  43247. return this.context.globalCompositeOperation;
  43248. },
  43249. set: function (value) {
  43250. this.context.globalCompositeOperation = value;
  43251. }
  43252. });
  43253. /**
  43254. * Gets a JavaScript object that has 6 properties set that are used by BitmapData in a transform.
  43255. *
  43256. * @method Phaser.BitmapData.getTransform
  43257. * @param {number} translateX - The x translate value.
  43258. * @param {number} translateY - The y translate value.
  43259. * @param {number} scaleX - The scale x value.
  43260. * @param {number} scaleY - The scale y value.
  43261. * @param {number} skewX - The skew x value.
  43262. * @param {number} skewY - The skew y value.
  43263. * @return {object} A JavaScript object containing all of the properties BitmapData needs for transforms.
  43264. */
  43265. Phaser.BitmapData.getTransform = function (translateX, translateY, scaleX, scaleY, skewX, skewY) {
  43266. if (typeof translateX !== 'number') { translateX = 0; }
  43267. if (typeof translateY !== 'number') { translateY = 0; }
  43268. if (typeof scaleX !== 'number') { scaleX = 1; }
  43269. if (typeof scaleY !== 'number') { scaleY = 1; }
  43270. if (typeof skewX !== 'number') { skewX = 0; }
  43271. if (typeof skewY !== 'number') { skewY = 0; }
  43272. return { sx: scaleX, sy: scaleY, scaleX: scaleX, scaleY: scaleY, skewX: skewX, skewY: skewY, translateX: translateX, translateY: translateY, tx: translateX, ty: translateY };
  43273. };
  43274. Phaser.BitmapData.prototype.constructor = Phaser.BitmapData;
  43275. /**
  43276. * @author Mat Groves http://matgroves.com/ @Doormat23
  43277. */
  43278. /**
  43279. * The Graphics class contains methods used to draw primitive shapes such as lines, circles and rectangles to the display, and color and fill them.
  43280. *
  43281. * @class Graphics
  43282. * @extends DisplayObjectContainer
  43283. * @constructor
  43284. */
  43285. PIXI.Graphics = function()
  43286. {
  43287. PIXI.DisplayObjectContainer.call(this);
  43288. this.renderable = true;
  43289. /**
  43290. * The alpha value used when filling the Graphics object.
  43291. *
  43292. * @property fillAlpha
  43293. * @type Number
  43294. */
  43295. this.fillAlpha = 1;
  43296. /**
  43297. * The width (thickness) of any lines drawn.
  43298. *
  43299. * @property lineWidth
  43300. * @type Number
  43301. */
  43302. this.lineWidth = 0;
  43303. /**
  43304. * The color of any lines drawn.
  43305. *
  43306. * @property lineColor
  43307. * @type String
  43308. * @default 0
  43309. */
  43310. this.lineColor = 0;
  43311. /**
  43312. * Graphics data
  43313. *
  43314. * @property graphicsData
  43315. * @type Array
  43316. * @private
  43317. */
  43318. this.graphicsData = [];
  43319. /**
  43320. * The tint applied to the graphic shape. This is a hex value. Apply a value of 0xFFFFFF to reset the tint.
  43321. *
  43322. * @property tint
  43323. * @type Number
  43324. * @default 0xFFFFFF
  43325. */
  43326. this.tint = 0xFFFFFF;
  43327. /**
  43328. * The blend mode to be applied to the graphic shape. Apply a value of PIXI.blendModes.NORMAL to reset the blend mode.
  43329. *
  43330. * @property blendMode
  43331. * @type Number
  43332. * @default PIXI.blendModes.NORMAL;
  43333. */
  43334. this.blendMode = PIXI.blendModes.NORMAL;
  43335. /**
  43336. * Current path
  43337. *
  43338. * @property currentPath
  43339. * @type Object
  43340. * @private
  43341. */
  43342. this.currentPath = null;
  43343. /**
  43344. * Array containing some WebGL-related properties used by the WebGL renderer.
  43345. *
  43346. * @property _webGL
  43347. * @type Array
  43348. * @private
  43349. */
  43350. this._webGL = [];
  43351. /**
  43352. * Whether this shape is being used as a mask.
  43353. *
  43354. * @property isMask
  43355. * @type Boolean
  43356. */
  43357. this.isMask = false;
  43358. /**
  43359. * The bounds' padding used for bounds calculation.
  43360. *
  43361. * @property boundsPadding
  43362. * @type Number
  43363. */
  43364. this.boundsPadding = 0;
  43365. this._localBounds = new PIXI.Rectangle(0,0,1,1);
  43366. /**
  43367. * Used to detect if the graphics object has changed. If this is set to true then the graphics object will be recalculated.
  43368. *
  43369. * @property dirty
  43370. * @type Boolean
  43371. * @private
  43372. */
  43373. this.dirty = true;
  43374. /**
  43375. * Used to detect if the bounds have been invalidated, by this Graphics being cleared or drawn to.
  43376. * If this is set to true then the updateLocalBounds is called once in the postUpdate method.
  43377. *
  43378. * @property _boundsDirty
  43379. * @type Boolean
  43380. * @private
  43381. */
  43382. this._boundsDirty = false;
  43383. /**
  43384. * Used to detect if the webgl graphics object has changed. If this is set to true then the graphics object will be recalculated.
  43385. *
  43386. * @property webGLDirty
  43387. * @type Boolean
  43388. * @private
  43389. */
  43390. this.webGLDirty = false;
  43391. /**
  43392. * Used to detect if the cached sprite object needs to be updated.
  43393. *
  43394. * @property cachedSpriteDirty
  43395. * @type Boolean
  43396. * @private
  43397. */
  43398. this.cachedSpriteDirty = false;
  43399. };
  43400. // constructor
  43401. PIXI.Graphics.prototype = Object.create( PIXI.DisplayObjectContainer.prototype );
  43402. PIXI.Graphics.prototype.constructor = PIXI.Graphics;
  43403. /**
  43404. * Specifies the line style used for subsequent calls to Graphics methods such as the lineTo() method or the drawCircle() method.
  43405. *
  43406. * @method lineStyle
  43407. * @param lineWidth {Number} width of the line to draw, will update the objects stored style
  43408. * @param color {Number} color of the line to draw, will update the objects stored style
  43409. * @param alpha {Number} alpha of the line to draw, will update the objects stored style
  43410. * @return {Graphics}
  43411. */
  43412. PIXI.Graphics.prototype.lineStyle = function(lineWidth, color, alpha)
  43413. {
  43414. this.lineWidth = lineWidth || 0;
  43415. this.lineColor = color || 0;
  43416. this.lineAlpha = (alpha === undefined) ? 1 : alpha;
  43417. if (this.currentPath)
  43418. {
  43419. if (this.currentPath.shape.points.length)
  43420. {
  43421. // halfway through a line? start a new one!
  43422. this.drawShape(new PIXI.Polygon(this.currentPath.shape.points.slice(-2)));
  43423. }
  43424. else
  43425. {
  43426. // otherwise its empty so lets just set the line properties
  43427. this.currentPath.lineWidth = this.lineWidth;
  43428. this.currentPath.lineColor = this.lineColor;
  43429. this.currentPath.lineAlpha = this.lineAlpha;
  43430. }
  43431. }
  43432. return this;
  43433. };
  43434. /**
  43435. * Moves the current drawing position to x, y.
  43436. *
  43437. * @method moveTo
  43438. * @param x {Number} the X coordinate to move to
  43439. * @param y {Number} the Y coordinate to move to
  43440. * @return {Graphics}
  43441. */
  43442. PIXI.Graphics.prototype.moveTo = function(x, y)
  43443. {
  43444. this.drawShape(new PIXI.Polygon([x, y]));
  43445. return this;
  43446. };
  43447. /**
  43448. * Draws a line using the current line style from the current drawing position to (x, y);
  43449. * The current drawing position is then set to (x, y).
  43450. *
  43451. * @method lineTo
  43452. * @param x {Number} the X coordinate to draw to
  43453. * @param y {Number} the Y coordinate to draw to
  43454. * @return {Graphics}
  43455. */
  43456. PIXI.Graphics.prototype.lineTo = function(x, y)
  43457. {
  43458. if (!this.currentPath)
  43459. {
  43460. this.moveTo(0, 0);
  43461. }
  43462. this.currentPath.shape.points.push(x, y);
  43463. this.dirty = true;
  43464. this._boundsDirty = true;
  43465. return this;
  43466. };
  43467. /**
  43468. * Calculate the points for a quadratic bezier curve and then draws it.
  43469. * Based on: https://stackoverflow.com/questions/785097/how-do-i-implement-a-bezier-curve-in-c
  43470. *
  43471. * @method quadraticCurveTo
  43472. * @param cpX {Number} Control point x
  43473. * @param cpY {Number} Control point y
  43474. * @param toX {Number} Destination point x
  43475. * @param toY {Number} Destination point y
  43476. * @return {Graphics}
  43477. */
  43478. PIXI.Graphics.prototype.quadraticCurveTo = function(cpX, cpY, toX, toY)
  43479. {
  43480. if (this.currentPath)
  43481. {
  43482. if (this.currentPath.shape.points.length === 0)
  43483. {
  43484. this.currentPath.shape.points = [0, 0];
  43485. }
  43486. }
  43487. else
  43488. {
  43489. this.moveTo(0,0);
  43490. }
  43491. var xa,
  43492. ya,
  43493. n = 20,
  43494. points = this.currentPath.shape.points;
  43495. if (points.length === 0)
  43496. {
  43497. this.moveTo(0, 0);
  43498. }
  43499. var fromX = points[points.length - 2];
  43500. var fromY = points[points.length - 1];
  43501. var j = 0;
  43502. for (var i = 1; i <= n; ++i)
  43503. {
  43504. j = i / n;
  43505. xa = fromX + ( (cpX - fromX) * j );
  43506. ya = fromY + ( (cpY - fromY) * j );
  43507. points.push( xa + ( ((cpX + ( (toX - cpX) * j )) - xa) * j ),
  43508. ya + ( ((cpY + ( (toY - cpY) * j )) - ya) * j ) );
  43509. }
  43510. this.dirty = true;
  43511. this._boundsDirty = true;
  43512. return this;
  43513. };
  43514. /**
  43515. * Calculate the points for a bezier curve and then draws it.
  43516. *
  43517. * @method bezierCurveTo
  43518. * @param cpX {Number} Control point x
  43519. * @param cpY {Number} Control point y
  43520. * @param cpX2 {Number} Second Control point x
  43521. * @param cpY2 {Number} Second Control point y
  43522. * @param toX {Number} Destination point x
  43523. * @param toY {Number} Destination point y
  43524. * @return {Graphics}
  43525. */
  43526. PIXI.Graphics.prototype.bezierCurveTo = function(cpX, cpY, cpX2, cpY2, toX, toY)
  43527. {
  43528. if (this.currentPath)
  43529. {
  43530. if (this.currentPath.shape.points.length === 0)
  43531. {
  43532. this.currentPath.shape.points = [0, 0];
  43533. }
  43534. }
  43535. else
  43536. {
  43537. this.moveTo(0,0);
  43538. }
  43539. var n = 20,
  43540. dt,
  43541. dt2,
  43542. dt3,
  43543. t2,
  43544. t3,
  43545. points = this.currentPath.shape.points;
  43546. var fromX = points[points.length-2];
  43547. var fromY = points[points.length-1];
  43548. var j = 0;
  43549. for (var i = 1; i <= n; ++i)
  43550. {
  43551. j = i / n;
  43552. dt = (1 - j);
  43553. dt2 = dt * dt;
  43554. dt3 = dt2 * dt;
  43555. t2 = j * j;
  43556. t3 = t2 * j;
  43557. points.push( dt3 * fromX + 3 * dt2 * j * cpX + 3 * dt * t2 * cpX2 + t3 * toX,
  43558. dt3 * fromY + 3 * dt2 * j * cpY + 3 * dt * t2 * cpY2 + t3 * toY);
  43559. }
  43560. this.dirty = true;
  43561. this._boundsDirty = true;
  43562. return this;
  43563. };
  43564. /*
  43565. * The arcTo() method creates an arc/curve between two tangents on the canvas.
  43566. *
  43567. * "borrowed" from https://code.google.com/p/fxcanvas/ - thanks google!
  43568. *
  43569. * @method arcTo
  43570. * @param x1 {Number} The x-coordinate of the beginning of the arc
  43571. * @param y1 {Number} The y-coordinate of the beginning of the arc
  43572. * @param x2 {Number} The x-coordinate of the end of the arc
  43573. * @param y2 {Number} The y-coordinate of the end of the arc
  43574. * @param radius {Number} The radius of the arc
  43575. * @return {Graphics}
  43576. */
  43577. PIXI.Graphics.prototype.arcTo = function(x1, y1, x2, y2, radius)
  43578. {
  43579. if (this.currentPath)
  43580. {
  43581. if (this.currentPath.shape.points.length === 0)
  43582. {
  43583. this.currentPath.shape.points.push(x1, y1);
  43584. }
  43585. }
  43586. else
  43587. {
  43588. this.moveTo(x1, y1);
  43589. }
  43590. var points = this.currentPath.shape.points,
  43591. fromX = points[points.length-2],
  43592. fromY = points[points.length-1],
  43593. a1 = fromY - y1,
  43594. b1 = fromX - x1,
  43595. a2 = y2 - y1,
  43596. b2 = x2 - x1,
  43597. mm = Math.abs(a1 * b2 - b1 * a2);
  43598. if (mm < 1.0e-8 || radius === 0)
  43599. {
  43600. if (points[points.length-2] !== x1 || points[points.length-1] !== y1)
  43601. {
  43602. points.push(x1, y1);
  43603. }
  43604. }
  43605. else
  43606. {
  43607. var dd = a1 * a1 + b1 * b1,
  43608. cc = a2 * a2 + b2 * b2,
  43609. tt = a1 * a2 + b1 * b2,
  43610. k1 = radius * Math.sqrt(dd) / mm,
  43611. k2 = radius * Math.sqrt(cc) / mm,
  43612. j1 = k1 * tt / dd,
  43613. j2 = k2 * tt / cc,
  43614. cx = k1 * b2 + k2 * b1,
  43615. cy = k1 * a2 + k2 * a1,
  43616. px = b1 * (k2 + j1),
  43617. py = a1 * (k2 + j1),
  43618. qx = b2 * (k1 + j2),
  43619. qy = a2 * (k1 + j2),
  43620. startAngle = Math.atan2(py - cy, px - cx),
  43621. endAngle = Math.atan2(qy - cy, qx - cx);
  43622. this.arc(cx + x1, cy + y1, radius, startAngle, endAngle, b1 * a2 > b2 * a1);
  43623. }
  43624. this.dirty = true;
  43625. this._boundsDirty = true;
  43626. return this;
  43627. };
  43628. /**
  43629. * The arc method creates an arc/curve (used to create circles, or parts of circles).
  43630. *
  43631. * @method arc
  43632. * @param cx {Number} The x-coordinate of the center of the circle
  43633. * @param cy {Number} The y-coordinate of the center of the circle
  43634. * @param radius {Number} The radius of the circle
  43635. * @param startAngle {Number} The starting angle, in radians (0 is at the 3 o'clock position of the arc's circle)
  43636. * @param endAngle {Number} The ending angle, in radians
  43637. * @param anticlockwise {Boolean} Optional. Specifies whether the drawing should be counterclockwise or clockwise. False is default, and indicates clockwise, while true indicates counter-clockwise.
  43638. * @param segments {Number} Optional. The number of segments to use when calculating the arc. The default is 40. If you need more fidelity use a higher number.
  43639. * @return {Graphics}
  43640. */
  43641. PIXI.Graphics.prototype.arc = function(cx, cy, radius, startAngle, endAngle, anticlockwise, segments)
  43642. {
  43643. // If we do this we can never draw a full circle
  43644. if (startAngle === endAngle)
  43645. {
  43646. return this;
  43647. }
  43648. if (anticlockwise === undefined) { anticlockwise = false; }
  43649. if (segments === undefined) { segments = 40; }
  43650. if (!anticlockwise && endAngle <= startAngle)
  43651. {
  43652. endAngle += Math.PI * 2;
  43653. }
  43654. else if (anticlockwise && startAngle <= endAngle)
  43655. {
  43656. startAngle += Math.PI * 2;
  43657. }
  43658. var sweep = anticlockwise ? (startAngle - endAngle) * -1 : (endAngle - startAngle);
  43659. var segs = Math.ceil(Math.abs(sweep) / (Math.PI * 2)) * segments;
  43660. // Sweep check - moved here because we don't want to do the moveTo below if the arc fails
  43661. if (sweep === 0)
  43662. {
  43663. return this;
  43664. }
  43665. var startX = cx + Math.cos(startAngle) * radius;
  43666. var startY = cy + Math.sin(startAngle) * radius;
  43667. if (anticlockwise && this.filling)
  43668. {
  43669. this.moveTo(cx, cy);
  43670. }
  43671. else
  43672. {
  43673. this.moveTo(startX, startY);
  43674. }
  43675. // currentPath will always exist after calling a moveTo
  43676. var points = this.currentPath.shape.points;
  43677. var theta = sweep / (segs * 2);
  43678. var theta2 = theta * 2;
  43679. var cTheta = Math.cos(theta);
  43680. var sTheta = Math.sin(theta);
  43681. var segMinus = segs - 1;
  43682. var remainder = (segMinus % 1) / segMinus;
  43683. for (var i = 0; i <= segMinus; i++)
  43684. {
  43685. var real = i + remainder * i;
  43686. var angle = ((theta) + startAngle + (theta2 * real));
  43687. var c = Math.cos(angle);
  43688. var s = -Math.sin(angle);
  43689. points.push(( (cTheta * c) + (sTheta * s) ) * radius + cx,
  43690. ( (cTheta * -s) + (sTheta * c) ) * radius + cy);
  43691. }
  43692. this.dirty = true;
  43693. this._boundsDirty = true;
  43694. return this;
  43695. };
  43696. /**
  43697. * Specifies a simple one-color fill that subsequent calls to other Graphics methods
  43698. * (such as lineTo() or drawCircle()) use when drawing.
  43699. *
  43700. * @method beginFill
  43701. * @param color {Number} the color of the fill
  43702. * @param alpha {Number} the alpha of the fill
  43703. * @return {Graphics}
  43704. */
  43705. PIXI.Graphics.prototype.beginFill = function(color, alpha)
  43706. {
  43707. this.filling = true;
  43708. this.fillColor = color || 0;
  43709. this.fillAlpha = (alpha === undefined) ? 1 : alpha;
  43710. if (this.currentPath)
  43711. {
  43712. if (this.currentPath.shape.points.length <= 2)
  43713. {
  43714. this.currentPath.fill = this.filling;
  43715. this.currentPath.fillColor = this.fillColor;
  43716. this.currentPath.fillAlpha = this.fillAlpha;
  43717. }
  43718. }
  43719. return this;
  43720. };
  43721. /**
  43722. * Applies a fill to the lines and shapes that were added since the last call to the beginFill() method.
  43723. *
  43724. * @method endFill
  43725. * @return {Graphics}
  43726. */
  43727. PIXI.Graphics.prototype.endFill = function()
  43728. {
  43729. this.filling = false;
  43730. this.fillColor = null;
  43731. this.fillAlpha = 1;
  43732. return this;
  43733. };
  43734. /**
  43735. * @method drawRect
  43736. *
  43737. * @param x {Number} The X coord of the top-left of the rectangle
  43738. * @param y {Number} The Y coord of the top-left of the rectangle
  43739. * @param width {Number} The width of the rectangle
  43740. * @param height {Number} The height of the rectangle
  43741. * @return {Graphics}
  43742. */
  43743. PIXI.Graphics.prototype.drawRect = function(x, y, width, height)
  43744. {
  43745. this.drawShape(new PIXI.Rectangle(x, y, width, height));
  43746. return this;
  43747. };
  43748. /**
  43749. * @method drawRoundedRect
  43750. * @param x {Number} The X coord of the top-left of the rectangle
  43751. * @param y {Number} The Y coord of the top-left of the rectangle
  43752. * @param width {Number} The width of the rectangle
  43753. * @param height {Number} The height of the rectangle
  43754. * @param radius {Number} Radius of the rectangle corners. In WebGL this must be a value between 0 and 9.
  43755. */
  43756. PIXI.Graphics.prototype.drawRoundedRect = function(x, y, width, height, radius)
  43757. {
  43758. this.drawShape(new PIXI.RoundedRectangle(x, y, width, height, radius));
  43759. return this;
  43760. };
  43761. /**
  43762. * Draws a circle.
  43763. *
  43764. * @method drawCircle
  43765. * @param x {Number} The X coordinate of the center of the circle
  43766. * @param y {Number} The Y coordinate of the center of the circle
  43767. * @param diameter {Number} The diameter of the circle
  43768. * @return {Graphics}
  43769. */
  43770. PIXI.Graphics.prototype.drawCircle = function(x, y, diameter)
  43771. {
  43772. this.drawShape(new PIXI.Circle(x, y, diameter));
  43773. return this;
  43774. };
  43775. /**
  43776. * Draws an ellipse.
  43777. *
  43778. * @method drawEllipse
  43779. * @param x {Number} The X coordinate of the center of the ellipse
  43780. * @param y {Number} The Y coordinate of the center of the ellipse
  43781. * @param width {Number} The half width of the ellipse
  43782. * @param height {Number} The half height of the ellipse
  43783. * @return {Graphics}
  43784. */
  43785. PIXI.Graphics.prototype.drawEllipse = function(x, y, width, height)
  43786. {
  43787. this.drawShape(new PIXI.Ellipse(x, y, width, height));
  43788. return this;
  43789. };
  43790. /**
  43791. * Draws a polygon using the given path.
  43792. *
  43793. * @method drawPolygon
  43794. * @param path {Array|Phaser.Polygon} The path data used to construct the polygon. Can either be an array of points or a Phaser.Polygon object.
  43795. * @return {Graphics}
  43796. */
  43797. PIXI.Graphics.prototype.drawPolygon = function(path)
  43798. {
  43799. if (path instanceof Phaser.Polygon || path instanceof PIXI.Polygon)
  43800. {
  43801. path = path.points;
  43802. }
  43803. // prevents an argument assignment deopt
  43804. // see section 3.1: https://github.com/petkaantonov/bluebird/wiki/Optimization-killers#3-managing-arguments
  43805. var points = path;
  43806. if (!Array.isArray(points))
  43807. {
  43808. // prevents an argument leak deopt
  43809. // see section 3.2: https://github.com/petkaantonov/bluebird/wiki/Optimization-killers#3-managing-arguments
  43810. points = new Array(arguments.length);
  43811. for (var i = 0; i < points.length; ++i)
  43812. {
  43813. points[i] = arguments[i];
  43814. }
  43815. }
  43816. this.drawShape(new Phaser.Polygon(points));
  43817. return this;
  43818. };
  43819. /**
  43820. * Clears the graphics that were drawn to this Graphics object, and resets fill and line style settings.
  43821. *
  43822. * @method clear
  43823. * @return {Graphics}
  43824. */
  43825. PIXI.Graphics.prototype.clear = function()
  43826. {
  43827. this.lineWidth = 0;
  43828. this.filling = false;
  43829. this.dirty = true;
  43830. this._boundsDirty = true;
  43831. this.clearDirty = true;
  43832. this.graphicsData = [];
  43833. this.updateLocalBounds();
  43834. return this;
  43835. };
  43836. /**
  43837. * Useful function that returns a texture of the graphics object that can then be used to create sprites
  43838. * This can be quite useful if your geometry is complicated and needs to be reused multiple times.
  43839. *
  43840. * @method generateTexture
  43841. * @param [resolution=1] {Number} The resolution of the texture being generated
  43842. * @param [scaleMode=0] {Number} Should be one of the PIXI.scaleMode consts
  43843. * @param [padding=0] {Number} Add optional extra padding to the generated texture (default 0)
  43844. * @return {Texture} a texture of the graphics object
  43845. */
  43846. PIXI.Graphics.prototype.generateTexture = function(resolution, scaleMode, padding)
  43847. {
  43848. if (resolution === undefined) { resolution = 1; }
  43849. if (scaleMode === undefined) { scaleMode = PIXI.scaleModes.DEFAULT; }
  43850. if (padding === undefined) { padding = 0; }
  43851. var bounds = this.getBounds();
  43852. bounds.width += padding;
  43853. bounds.height += padding;
  43854. var canvasBuffer = new PIXI.CanvasBuffer(bounds.width * resolution, bounds.height * resolution);
  43855. var texture = PIXI.Texture.fromCanvas(canvasBuffer.canvas, scaleMode);
  43856. texture.baseTexture.resolution = resolution;
  43857. canvasBuffer.context.scale(resolution, resolution);
  43858. canvasBuffer.context.translate(-bounds.x, -bounds.y);
  43859. PIXI.CanvasGraphics.renderGraphics(this, canvasBuffer.context);
  43860. return texture;
  43861. };
  43862. /**
  43863. * Renders the object using the WebGL renderer
  43864. *
  43865. * @method _renderWebGL
  43866. * @param renderSession {RenderSession}
  43867. * @private
  43868. */
  43869. PIXI.Graphics.prototype._renderWebGL = function(renderSession)
  43870. {
  43871. // if the sprite is not visible or the alpha is 0 then no need to render this element
  43872. if (this.visible === false || this.alpha === 0 || this.isMask === true) return;
  43873. if (this._cacheAsBitmap)
  43874. {
  43875. if (this.dirty || this.cachedSpriteDirty)
  43876. {
  43877. this._generateCachedSprite();
  43878. // we will also need to update the texture on the gpu too!
  43879. this.updateCachedSpriteTexture();
  43880. this.cachedSpriteDirty = false;
  43881. this.dirty = false;
  43882. }
  43883. this._cachedSprite.worldAlpha = this.worldAlpha;
  43884. PIXI.Sprite.prototype._renderWebGL.call(this._cachedSprite, renderSession);
  43885. return;
  43886. }
  43887. else
  43888. {
  43889. renderSession.spriteBatch.stop();
  43890. renderSession.blendModeManager.setBlendMode(this.blendMode);
  43891. if (this._mask) renderSession.maskManager.pushMask(this._mask, renderSession);
  43892. if (this._filters) renderSession.filterManager.pushFilter(this._filterBlock);
  43893. // check blend mode
  43894. if (this.blendMode !== renderSession.spriteBatch.currentBlendMode)
  43895. {
  43896. renderSession.spriteBatch.currentBlendMode = this.blendMode;
  43897. var blendModeWebGL = PIXI.blendModesWebGL[renderSession.spriteBatch.currentBlendMode];
  43898. renderSession.spriteBatch.gl.blendFunc(blendModeWebGL[0], blendModeWebGL[1]);
  43899. }
  43900. // check if the webgl graphic needs to be updated
  43901. if (this.webGLDirty)
  43902. {
  43903. this.dirty = true;
  43904. this.webGLDirty = false;
  43905. }
  43906. PIXI.WebGLGraphics.renderGraphics(this, renderSession);
  43907. // only render if it has children!
  43908. if (this.children.length)
  43909. {
  43910. renderSession.spriteBatch.start();
  43911. // simple render children!
  43912. for (var i = 0; i < this.children.length; i++)
  43913. {
  43914. this.children[i]._renderWebGL(renderSession);
  43915. }
  43916. renderSession.spriteBatch.stop();
  43917. }
  43918. if (this._filters) renderSession.filterManager.popFilter();
  43919. if (this._mask) renderSession.maskManager.popMask(this.mask, renderSession);
  43920. renderSession.drawCount++;
  43921. renderSession.spriteBatch.start();
  43922. }
  43923. };
  43924. /**
  43925. * Renders the object using the Canvas renderer
  43926. *
  43927. * @method _renderCanvas
  43928. * @param renderSession {RenderSession}
  43929. * @private
  43930. */
  43931. PIXI.Graphics.prototype._renderCanvas = function(renderSession)
  43932. {
  43933. // if the sprite is not visible or the alpha is 0 then no need to render this element
  43934. if (this.visible === false || this.alpha === 0 || this.isMask === true) return;
  43935. // if the tint has changed, set the graphics object to dirty.
  43936. if (this._prevTint !== this.tint) {
  43937. this.dirty = true;
  43938. this._prevTint = this.tint;
  43939. }
  43940. if (this._cacheAsBitmap)
  43941. {
  43942. if (this.dirty || this.cachedSpriteDirty)
  43943. {
  43944. this._generateCachedSprite();
  43945. // we will also need to update the texture
  43946. this.updateCachedSpriteTexture();
  43947. this.cachedSpriteDirty = false;
  43948. this.dirty = false;
  43949. }
  43950. this._cachedSprite.alpha = this.alpha;
  43951. PIXI.Sprite.prototype._renderCanvas.call(this._cachedSprite, renderSession);
  43952. return;
  43953. }
  43954. else
  43955. {
  43956. var context = renderSession.context;
  43957. var transform = this.worldTransform;
  43958. if (this.blendMode !== renderSession.currentBlendMode)
  43959. {
  43960. renderSession.currentBlendMode = this.blendMode;
  43961. context.globalCompositeOperation = PIXI.blendModesCanvas[renderSession.currentBlendMode];
  43962. }
  43963. if (this._mask)
  43964. {
  43965. renderSession.maskManager.pushMask(this._mask, renderSession);
  43966. }
  43967. var resolution = renderSession.resolution;
  43968. var tx = (transform.tx * renderSession.resolution) + renderSession.shakeX;
  43969. var ty = (transform.ty * renderSession.resolution) + renderSession.shakeY;
  43970. context.setTransform(transform.a * resolution,
  43971. transform.b * resolution,
  43972. transform.c * resolution,
  43973. transform.d * resolution,
  43974. tx,
  43975. ty);
  43976. PIXI.CanvasGraphics.renderGraphics(this, context);
  43977. // simple render children!
  43978. for (var i = 0; i < this.children.length; i++)
  43979. {
  43980. this.children[i]._renderCanvas(renderSession);
  43981. }
  43982. if (this._mask)
  43983. {
  43984. renderSession.maskManager.popMask(renderSession);
  43985. }
  43986. }
  43987. };
  43988. /**
  43989. * Retrieves the bounds of the graphic shape as a rectangle object
  43990. *
  43991. * @method getBounds
  43992. * @return {Rectangle} the rectangular bounding area
  43993. */
  43994. PIXI.Graphics.prototype.getBounds = function(matrix)
  43995. {
  43996. if (!this._currentBounds)
  43997. {
  43998. // Return an empty object if the item is a mask!
  43999. if (!this.renderable)
  44000. {
  44001. return PIXI.EmptyRectangle;
  44002. }
  44003. if (this.dirty)
  44004. {
  44005. this.updateLocalBounds();
  44006. this.webGLDirty = true;
  44007. this.cachedSpriteDirty = true;
  44008. this.dirty = false;
  44009. }
  44010. var bounds = this._localBounds;
  44011. var w0 = bounds.x;
  44012. var w1 = bounds.width + bounds.x;
  44013. var h0 = bounds.y;
  44014. var h1 = bounds.height + bounds.y;
  44015. var worldTransform = matrix || this.worldTransform;
  44016. var a = worldTransform.a;
  44017. var b = worldTransform.b;
  44018. var c = worldTransform.c;
  44019. var d = worldTransform.d;
  44020. var tx = worldTransform.tx;
  44021. var ty = worldTransform.ty;
  44022. var x1 = a * w1 + c * h1 + tx;
  44023. var y1 = d * h1 + b * w1 + ty;
  44024. var x2 = a * w0 + c * h1 + tx;
  44025. var y2 = d * h1 + b * w0 + ty;
  44026. var x3 = a * w0 + c * h0 + tx;
  44027. var y3 = d * h0 + b * w0 + ty;
  44028. var x4 = a * w1 + c * h0 + tx;
  44029. var y4 = d * h0 + b * w1 + ty;
  44030. var maxX = x1;
  44031. var maxY = y1;
  44032. var minX = x1;
  44033. var minY = y1;
  44034. minX = x2 < minX ? x2 : minX;
  44035. minX = x3 < minX ? x3 : minX;
  44036. minX = x4 < minX ? x4 : minX;
  44037. minY = y2 < minY ? y2 : minY;
  44038. minY = y3 < minY ? y3 : minY;
  44039. minY = y4 < minY ? y4 : minY;
  44040. maxX = x2 > maxX ? x2 : maxX;
  44041. maxX = x3 > maxX ? x3 : maxX;
  44042. maxX = x4 > maxX ? x4 : maxX;
  44043. maxY = y2 > maxY ? y2 : maxY;
  44044. maxY = y3 > maxY ? y3 : maxY;
  44045. maxY = y4 > maxY ? y4 : maxY;
  44046. this._bounds.x = minX;
  44047. this._bounds.width = maxX - minX;
  44048. this._bounds.y = minY;
  44049. this._bounds.height = maxY - minY;
  44050. this._currentBounds = this._bounds;
  44051. }
  44052. return this._currentBounds;
  44053. };
  44054. /**
  44055. * Retrieves the non-global local bounds of the graphic shape as a rectangle. The calculation takes all visible children into consideration.
  44056. *
  44057. * @method getLocalBounds
  44058. * @return {Rectangle} The rectangular bounding area
  44059. */
  44060. PIXI.Graphics.prototype.getLocalBounds = function () {
  44061. var matrixCache = this.worldTransform;
  44062. this.worldTransform = PIXI.identityMatrix;
  44063. for (var i = 0; i < this.children.length; i++) {
  44064. this.children[i].updateTransform();
  44065. }
  44066. var bounds = this.getBounds();
  44067. this.worldTransform = matrixCache;
  44068. for (i = 0; i < this.children.length; i++) {
  44069. this.children[i].updateTransform();
  44070. }
  44071. return bounds;
  44072. };
  44073. /**
  44074. * Tests if a point is inside this graphics object
  44075. *
  44076. * @param point {Point} the point to test
  44077. * @return {boolean} the result of the test
  44078. */
  44079. PIXI.Graphics.prototype.containsPoint = function( point )
  44080. {
  44081. this.worldTransform.applyInverse(point, tempPoint);
  44082. var graphicsData = this.graphicsData;
  44083. for (var i = 0; i < graphicsData.length; i++)
  44084. {
  44085. var data = graphicsData[i];
  44086. if (!data.fill)
  44087. {
  44088. continue;
  44089. }
  44090. // only deal with fills..
  44091. if (data.shape)
  44092. {
  44093. if (data.shape.contains(tempPoint.x, tempPoint.y))
  44094. {
  44095. return true;
  44096. }
  44097. }
  44098. }
  44099. return false;
  44100. };
  44101. /**
  44102. * Update the bounds of the object
  44103. *
  44104. * @method updateLocalBounds
  44105. */
  44106. PIXI.Graphics.prototype.updateLocalBounds = function()
  44107. {
  44108. var minX = Infinity;
  44109. var maxX = -Infinity;
  44110. var minY = Infinity;
  44111. var maxY = -Infinity;
  44112. if (this.graphicsData.length)
  44113. {
  44114. var shape, points, x, y, w, h;
  44115. for (var i = 0; i < this.graphicsData.length; i++)
  44116. {
  44117. var data = this.graphicsData[i];
  44118. var type = data.type;
  44119. var lineWidth = data.lineWidth;
  44120. shape = data.shape;
  44121. if (type === PIXI.Graphics.RECT || type === PIXI.Graphics.RREC)
  44122. {
  44123. x = shape.x - lineWidth / 2;
  44124. y = shape.y - lineWidth / 2;
  44125. w = shape.width + lineWidth;
  44126. h = shape.height + lineWidth;
  44127. minX = x < minX ? x : minX;
  44128. maxX = x + w > maxX ? x + w : maxX;
  44129. minY = y < minY ? y : minY;
  44130. maxY = y + h > maxY ? y + h : maxY;
  44131. }
  44132. else if (type === PIXI.Graphics.CIRC)
  44133. {
  44134. x = shape.x;
  44135. y = shape.y;
  44136. w = shape.radius + lineWidth / 2;
  44137. h = shape.radius + lineWidth / 2;
  44138. minX = x - w < minX ? x - w : minX;
  44139. maxX = x + w > maxX ? x + w : maxX;
  44140. minY = y - h < minY ? y - h : minY;
  44141. maxY = y + h > maxY ? y + h : maxY;
  44142. }
  44143. else if (type === PIXI.Graphics.ELIP)
  44144. {
  44145. x = shape.x;
  44146. y = shape.y;
  44147. w = shape.width + lineWidth / 2;
  44148. h = shape.height + lineWidth / 2;
  44149. minX = x - w < minX ? x - w : minX;
  44150. maxX = x + w > maxX ? x + w : maxX;
  44151. minY = y - h < minY ? y - h : minY;
  44152. maxY = y + h > maxY ? y + h : maxY;
  44153. }
  44154. else
  44155. {
  44156. // POLY - assumes points are sequential, not Point objects
  44157. points = shape.points;
  44158. for (var j = 0; j < points.length; j++)
  44159. {
  44160. if (points[j] instanceof Phaser.Point)
  44161. {
  44162. x = points[j].x;
  44163. y = points[j].y;
  44164. }
  44165. else
  44166. {
  44167. x = points[j];
  44168. y = points[j + 1];
  44169. if (j < points.length - 1)
  44170. {
  44171. j++;
  44172. }
  44173. }
  44174. minX = x - lineWidth < minX ? x - lineWidth : minX;
  44175. maxX = x + lineWidth > maxX ? x + lineWidth : maxX;
  44176. minY = y - lineWidth < minY ? y - lineWidth : minY;
  44177. maxY = y + lineWidth > maxY ? y + lineWidth : maxY;
  44178. }
  44179. }
  44180. }
  44181. }
  44182. else
  44183. {
  44184. minX = 0;
  44185. maxX = 0;
  44186. minY = 0;
  44187. maxY = 0;
  44188. }
  44189. var padding = this.boundsPadding;
  44190. this._localBounds.x = minX - padding;
  44191. this._localBounds.width = (maxX - minX) + padding * 2;
  44192. this._localBounds.y = minY - padding;
  44193. this._localBounds.height = (maxY - minY) + padding * 2;
  44194. };
  44195. /**
  44196. * Generates the cached sprite when the sprite has cacheAsBitmap = true
  44197. *
  44198. * @method _generateCachedSprite
  44199. * @private
  44200. */
  44201. PIXI.Graphics.prototype._generateCachedSprite = function()
  44202. {
  44203. var bounds = this.getLocalBounds();
  44204. if (!this._cachedSprite)
  44205. {
  44206. var canvasBuffer = new PIXI.CanvasBuffer(bounds.width, bounds.height);
  44207. var texture = PIXI.Texture.fromCanvas(canvasBuffer.canvas);
  44208. this._cachedSprite = new PIXI.Sprite(texture);
  44209. this._cachedSprite.buffer = canvasBuffer;
  44210. this._cachedSprite.worldTransform = this.worldTransform;
  44211. }
  44212. else
  44213. {
  44214. this._cachedSprite.buffer.resize(bounds.width, bounds.height);
  44215. }
  44216. // leverage the anchor to account for the offset of the element
  44217. this._cachedSprite.anchor.x = -(bounds.x / bounds.width);
  44218. this._cachedSprite.anchor.y = -(bounds.y / bounds.height);
  44219. // this._cachedSprite.buffer.context.save();
  44220. this._cachedSprite.buffer.context.translate(-bounds.x, -bounds.y);
  44221. // make sure we set the alpha of the graphics to 1 for the render..
  44222. this.worldAlpha = 1;
  44223. // now render the graphic..
  44224. PIXI.CanvasGraphics.renderGraphics(this, this._cachedSprite.buffer.context);
  44225. this._cachedSprite.alpha = this.alpha;
  44226. };
  44227. /**
  44228. * Updates texture size based on canvas size
  44229. *
  44230. * @method updateCachedSpriteTexture
  44231. * @private
  44232. */
  44233. PIXI.Graphics.prototype.updateCachedSpriteTexture = function()
  44234. {
  44235. var cachedSprite = this._cachedSprite;
  44236. var texture = cachedSprite.texture;
  44237. var canvas = cachedSprite.buffer.canvas;
  44238. texture.baseTexture.width = canvas.width;
  44239. texture.baseTexture.height = canvas.height;
  44240. texture.crop.width = texture.frame.width = canvas.width;
  44241. texture.crop.height = texture.frame.height = canvas.height;
  44242. cachedSprite._width = canvas.width;
  44243. cachedSprite._height = canvas.height;
  44244. // update the dirty base textures
  44245. texture.baseTexture.dirty();
  44246. };
  44247. /**
  44248. * Destroys a previous cached sprite.
  44249. *
  44250. * @method destroyCachedSprite
  44251. */
  44252. PIXI.Graphics.prototype.destroyCachedSprite = function()
  44253. {
  44254. this._cachedSprite.texture.destroy(true);
  44255. this._cachedSprite = null;
  44256. };
  44257. /**
  44258. * Draws the given shape to this Graphics object. Can be any of Circle, Rectangle, Ellipse, Line or Polygon.
  44259. *
  44260. * @method drawShape
  44261. * @param {Circle|Rectangle|Ellipse|Line|Polygon} shape The Shape object to draw.
  44262. * @return {GraphicsData} The generated GraphicsData object.
  44263. */
  44264. PIXI.Graphics.prototype.drawShape = function(shape)
  44265. {
  44266. if (this.currentPath)
  44267. {
  44268. // check current path!
  44269. if (this.currentPath.shape.points.length <= 2)
  44270. {
  44271. this.graphicsData.pop();
  44272. }
  44273. }
  44274. this.currentPath = null;
  44275. // Handle mixed-type polygons
  44276. if (shape instanceof Phaser.Polygon)
  44277. {
  44278. shape = shape.clone();
  44279. shape.flatten();
  44280. }
  44281. var data = new PIXI.GraphicsData(this.lineWidth, this.lineColor, this.lineAlpha, this.fillColor, this.fillAlpha, this.filling, shape);
  44282. this.graphicsData.push(data);
  44283. if (data.type === PIXI.Graphics.POLY)
  44284. {
  44285. data.shape.closed = this.filling;
  44286. this.currentPath = data;
  44287. }
  44288. this.dirty = true;
  44289. this._boundsDirty = true;
  44290. return data;
  44291. };
  44292. /**
  44293. * When cacheAsBitmap is set to true the graphics object will be rendered as if it was a sprite.
  44294. * This is useful if your graphics element does not change often, as it will speed up the rendering of the object in exchange for taking up texture memory.
  44295. * It is also useful if you need the graphics object to be anti-aliased, because it will be rendered using canvas.
  44296. * This is not recommended if you are constantly redrawing the graphics element.
  44297. *
  44298. * @property cacheAsBitmap
  44299. * @type Boolean
  44300. * @default false
  44301. * @private
  44302. */
  44303. Object.defineProperty(PIXI.Graphics.prototype, "cacheAsBitmap", {
  44304. get: function() {
  44305. return this._cacheAsBitmap;
  44306. },
  44307. set: function(value) {
  44308. this._cacheAsBitmap = value;
  44309. if (this._cacheAsBitmap)
  44310. {
  44311. this._generateCachedSprite();
  44312. }
  44313. else
  44314. {
  44315. this.destroyCachedSprite();
  44316. }
  44317. this.dirty = true;
  44318. this.webGLDirty = true;
  44319. }
  44320. });
  44321. /**
  44322. * A GraphicsData object.
  44323. *
  44324. * @class GraphicsData
  44325. * @constructor
  44326. PIXI.GraphicsData = function(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape)
  44327. {
  44328. this.lineWidth = lineWidth;
  44329. this.lineColor = lineColor;
  44330. this.lineAlpha = lineAlpha;
  44331. this._lineTint = lineColor;
  44332. this.fillColor = fillColor;
  44333. this.fillAlpha = fillAlpha;
  44334. this._fillTint = fillColor;
  44335. this.fill = fill;
  44336. this.shape = shape;
  44337. this.type = shape.type;
  44338. };
  44339. */
  44340. /**
  44341. * A GraphicsData object.
  44342. *
  44343. * @class
  44344. * @memberof PIXI
  44345. * @param lineWidth {number} the width of the line to draw
  44346. * @param lineColor {number} the color of the line to draw
  44347. * @param lineAlpha {number} the alpha of the line to draw
  44348. * @param fillColor {number} the color of the fill
  44349. * @param fillAlpha {number} the alpha of the fill
  44350. * @param fill {boolean} whether or not the shape is filled with a colour
  44351. * @param shape {Circle|Rectangle|Ellipse|Line|Polygon} The shape object to draw.
  44352. */
  44353. PIXI.GraphicsData = function(lineWidth, lineColor, lineAlpha, fillColor, fillAlpha, fill, shape) {
  44354. /*
  44355. * @member {number} the width of the line to draw
  44356. */
  44357. this.lineWidth = lineWidth;
  44358. /*
  44359. * @member {number} the color of the line to draw
  44360. */
  44361. this.lineColor = lineColor;
  44362. /*
  44363. * @member {number} the alpha of the line to draw
  44364. */
  44365. this.lineAlpha = lineAlpha;
  44366. /*
  44367. * @member {number} cached tint of the line to draw
  44368. */
  44369. this._lineTint = lineColor;
  44370. /*
  44371. * @member {number} the color of the fill
  44372. */
  44373. this.fillColor = fillColor;
  44374. /*
  44375. * @member {number} the alpha of the fill
  44376. */
  44377. this.fillAlpha = fillAlpha;
  44378. /*
  44379. * @member {number} cached tint of the fill
  44380. */
  44381. this._fillTint = fillColor;
  44382. /*
  44383. * @member {boolean} whether or not the shape is filled with a color
  44384. */
  44385. this.fill = fill;
  44386. /*
  44387. * @member {Circle|Rectangle|Ellipse|Line|Polygon} The shape object to draw.
  44388. */
  44389. this.shape = shape;
  44390. /*
  44391. * @member {number} The type of the shape, see the Const.Shapes file for all the existing types,
  44392. */
  44393. this.type = shape.type;
  44394. };
  44395. PIXI.GraphicsData.prototype.constructor = PIXI.GraphicsData;
  44396. /**
  44397. * Creates a new GraphicsData object with the same values as this one.
  44398. *
  44399. * @return {GraphicsData}
  44400. */
  44401. PIXI.GraphicsData.prototype.clone = function() {
  44402. return new GraphicsData(
  44403. this.lineWidth,
  44404. this.lineColor,
  44405. this.lineAlpha,
  44406. this.fillColor,
  44407. this.fillAlpha,
  44408. this.fill,
  44409. this.shape
  44410. );
  44411. };
  44412. /*
  44413. Copyright (c) 2016, Mapbox
  44414. Permission to use, copy, modify, and/or distribute this software for any purpose
  44415. with or without fee is hereby granted, provided that the above copyright notice
  44416. and this permission notice appear in all copies.
  44417. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  44418. REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  44419. FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  44420. INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  44421. OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  44422. TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  44423. THIS SOFTWARE.
  44424. */
  44425. /**
  44426. * @class EarCut
  44427. */
  44428. PIXI.EarCut = {};
  44429. PIXI.EarCut.Triangulate = function (data, holeIndices, dim) {
  44430. dim = dim || 2;
  44431. var hasHoles = holeIndices && holeIndices.length,
  44432. outerLen = hasHoles ? holeIndices[0] * dim : data.length,
  44433. outerNode = PIXI.EarCut.linkedList(data, 0, outerLen, dim, true),
  44434. triangles = [];
  44435. if (!outerNode) return triangles;
  44436. var minX, minY, maxX, maxY, x, y, size;
  44437. if (hasHoles) outerNode = PIXI.EarCut.eliminateHoles(data, holeIndices, outerNode, dim);
  44438. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  44439. if (data.length > 80 * dim) {
  44440. minX = maxX = data[0];
  44441. minY = maxY = data[1];
  44442. for (var i = dim; i < outerLen; i += dim) {
  44443. x = data[i];
  44444. y = data[i + 1];
  44445. if (x < minX) minX = x;
  44446. if (y < minY) minY = y;
  44447. if (x > maxX) maxX = x;
  44448. if (y > maxY) maxY = y;
  44449. }
  44450. // minX, minY and size are later used to transform coords into integers for z-order calculation
  44451. size = Math.max(maxX - minX, maxY - minY);
  44452. }
  44453. PIXI.EarCut.earcutLinked(outerNode, triangles, dim, minX, minY, size);
  44454. return triangles;
  44455. }
  44456. // create a circular doubly linked list from polygon points in the specified winding order
  44457. PIXI.EarCut.linkedList = function (data, start, end, dim, clockwise) {
  44458. var sum = 0,
  44459. i, j, last;
  44460. // calculate original winding order of a polygon ring
  44461. for (i = start, j = end - dim; i < end; i += dim) {
  44462. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  44463. j = i;
  44464. }
  44465. // link points into circular doubly-linked list in the specified winding order
  44466. if (clockwise === (sum > 0)) {
  44467. for (i = start; i < end; i += dim) last = PIXI.EarCut.insertNode(i, data[i], data[i + 1], last);
  44468. } else {
  44469. for (i = end - dim; i >= start; i -= dim) last = PIXI.EarCut.insertNode(i, data[i], data[i + 1], last);
  44470. }
  44471. return last;
  44472. }
  44473. // eliminate colinear or duplicate points
  44474. PIXI.EarCut.filterPoints = function (start, end) {
  44475. if (!start) return start;
  44476. if (!end) end = start;
  44477. var p = start,
  44478. again;
  44479. do {
  44480. again = false;
  44481. if (!p.steiner && (PIXI.EarCut.equals(p, p.next) || PIXI.EarCut.area(p.prev, p, p.next) === 0)) {
  44482. PIXI.EarCut.removeNode(p);
  44483. p = end = p.prev;
  44484. if (p === p.next) return null;
  44485. again = true;
  44486. } else {
  44487. p = p.next;
  44488. }
  44489. } while (again || p !== end);
  44490. return end;
  44491. }
  44492. // main ear slicing loop which triangulates a polygon (given as a linked list)
  44493. PIXI.EarCut.earcutLinked = function (ear, triangles, dim, minX, minY, size, pass) {
  44494. if (!ear) return;
  44495. // interlink polygon nodes in z-order
  44496. if (!pass && size) PIXI.EarCut.indexCurve(ear, minX, minY, size);
  44497. var stop = ear,
  44498. prev, next;
  44499. // iterate through ears, slicing them one by one
  44500. while (ear.prev !== ear.next) {
  44501. prev = ear.prev;
  44502. next = ear.next;
  44503. if (size ? PIXI.EarCut.isEarHashed(ear, minX, minY, size) : PIXI.EarCut.isEar(ear)) {
  44504. // cut off the triangle
  44505. triangles.push(prev.i / dim);
  44506. triangles.push(ear.i / dim);
  44507. triangles.push(next.i / dim);
  44508. PIXI.EarCut.removeNode(ear);
  44509. // skipping the next vertice leads to less sliver triangles
  44510. ear = next.next;
  44511. stop = next.next;
  44512. continue;
  44513. }
  44514. ear = next;
  44515. // if we looped through the whole remaining polygon and can't find any more ears
  44516. if (ear === stop) {
  44517. // try filtering points and slicing again
  44518. if (!pass) {
  44519. PIXI.EarCut.earcutLinked(PIXI.EarCut.filterPoints(ear), triangles, dim, minX, minY, size, 1);
  44520. // if this didn't work, try curing all small self-intersections locally
  44521. } else if (pass === 1) {
  44522. ear = PIXI.EarCut.cureLocalIntersections(ear, triangles, dim);
  44523. PIXI.EarCut.earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  44524. // as a last resort, try splitting the remaining polygon into two
  44525. } else if (pass === 2) {
  44526. PIXI.EarCut.splitEarcut(ear, triangles, dim, minX, minY, size);
  44527. }
  44528. break;
  44529. }
  44530. }
  44531. }
  44532. // check whether a polygon node forms a valid ear with adjacent nodes
  44533. PIXI.EarCut.isEar = function (ear) {
  44534. var a = ear.prev,
  44535. b = ear,
  44536. c = ear.next;
  44537. if (PIXI.EarCut.area(a, b, c) >= 0) return false; // reflex, can't be an ear
  44538. // now make sure we don't have other points inside the potential ear
  44539. var p = ear.next.next;
  44540. while (p !== ear.prev) {
  44541. if (PIXI.EarCut.pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  44542. PIXI.EarCut.area(p.prev, p, p.next) >= 0) return false;
  44543. p = p.next;
  44544. }
  44545. return true;
  44546. }
  44547. PIXI.EarCut.isEarHashed = function (ear, minX, minY, size) {
  44548. var a = ear.prev,
  44549. b = ear,
  44550. c = ear.next;
  44551. if (PIXI.EarCut.area(a, b, c) >= 0) return false; // reflex, can't be an ear
  44552. // triangle bbox; min & max are calculated like this for speed
  44553. var minTX = a.x < b.x ? (a.x < c.x ? a.x : c.x) : (b.x < c.x ? b.x : c.x),
  44554. minTY = a.y < b.y ? (a.y < c.y ? a.y : c.y) : (b.y < c.y ? b.y : c.y),
  44555. maxTX = a.x > b.x ? (a.x > c.x ? a.x : c.x) : (b.x > c.x ? b.x : c.x),
  44556. maxTY = a.y > b.y ? (a.y > c.y ? a.y : c.y) : (b.y > c.y ? b.y : c.y);
  44557. // z-order range for the current triangle bbox;
  44558. var minZ = PIXI.EarCut.zOrder(minTX, minTY, minX, minY, size),
  44559. maxZ = PIXI.EarCut.zOrder(maxTX, maxTY, minX, minY, size);
  44560. // first look for points inside the triangle in increasing z-order
  44561. var p = ear.nextZ;
  44562. while (p && p.z <= maxZ) {
  44563. if (p !== ear.prev && p !== ear.next &&
  44564. PIXI.EarCut.pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  44565. PIXI.EarCut.area(p.prev, p, p.next) >= 0) return false;
  44566. p = p.nextZ;
  44567. }
  44568. // then look for points in decreasing z-order
  44569. p = ear.prevZ;
  44570. while (p && p.z >= minZ) {
  44571. if (p !== ear.prev && p !== ear.next &&
  44572. PIXI.EarCut.pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  44573. PIXI.EarCut.area(p.prev, p, p.next) >= 0) return false;
  44574. p = p.prevZ;
  44575. }
  44576. return true;
  44577. }
  44578. // go through all polygon nodes and cure small local self-intersections
  44579. PIXI.EarCut.cureLocalIntersections = function (start, triangles, dim) {
  44580. var p = start;
  44581. do {
  44582. var a = p.prev,
  44583. b = p.next.next;
  44584. // a self-intersection where edge (v[i-1],v[i]) intersects (v[i+1],v[i+2])
  44585. if (PIXI.EarCut.intersects(a, p, p.next, b) && PIXI.EarCut.locallyInside(a, b) && PIXI.EarCut.locallyInside(b, a)) {
  44586. triangles.push(a.i / dim);
  44587. triangles.push(p.i / dim);
  44588. triangles.push(b.i / dim);
  44589. // remove two nodes involved
  44590. PIXI.EarCut.removeNode(p);
  44591. PIXI.EarCut.removeNode(p.next);
  44592. p = start = b;
  44593. }
  44594. p = p.next;
  44595. } while (p !== start);
  44596. return p;
  44597. }
  44598. // try splitting polygon into two and triangulate them independently
  44599. PIXI.EarCut.splitEarcut = function (start, triangles, dim, minX, minY, size) {
  44600. // look for a valid diagonal that divides the polygon into two
  44601. var a = start;
  44602. do {
  44603. var b = a.next.next;
  44604. while (b !== a.prev) {
  44605. if (a.i !== b.i && PIXI.EarCut.isValidDiagonal(a, b)) {
  44606. // split the polygon in two by the diagonal
  44607. var c = PIXI.EarCut.splitPolygon(a, b);
  44608. // filter colinear points around the cuts
  44609. a = PIXI.EarCut.filterPoints(a, a.next);
  44610. c = PIXI.EarCut.filterPoints(c, c.next);
  44611. // run earcut on each half
  44612. PIXI.EarCut.earcutLinked(a, triangles, dim, minX, minY, size);
  44613. PIXI.EarCut.earcutLinked(c, triangles, dim, minX, minY, size);
  44614. return;
  44615. }
  44616. b = b.next;
  44617. }
  44618. a = a.next;
  44619. } while (a !== start);
  44620. }
  44621. // link every hole into the outer loop, producing a single-ring polygon without holes
  44622. PIXI.EarCut.eliminateHoles = function (data, holeIndices, outerNode, dim) {
  44623. var queue = [],
  44624. i, len, start, end, list;
  44625. for (i = 0, len = holeIndices.length; i < len; i++) {
  44626. start = holeIndices[i] * dim;
  44627. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  44628. list = PIXI.EarCut.linkedList(data, start, end, dim, false);
  44629. if (list === list.next) list.steiner = true;
  44630. queue.push(PIXI.EarCut.getLeftmost(list));
  44631. }
  44632. queue.sort(compareX);
  44633. // process holes from left to right
  44634. for (i = 0; i < queue.length; i++) {
  44635. PIXI.EarCut.eliminateHole(queue[i], outerNode);
  44636. outerNode = PIXI.EarCut.filterPoints(outerNode, outerNode.next);
  44637. }
  44638. return outerNode;
  44639. }
  44640. PIXI.EarCut.compareX = function (a, b) {
  44641. return a.x - b.x;
  44642. }
  44643. // find a bridge between vertices that connects hole with an outer ring and and link it
  44644. PIXI.EarCut.eliminateHole = function (hole, outerNode) {
  44645. outerNode = PIXI.EarCut.findHoleBridge(hole, outerNode);
  44646. if (outerNode) {
  44647. var b = PIXI.EarCut.splitPolygon(outerNode, hole);
  44648. PIXI.EarCut.filterPoints(b, b.next);
  44649. }
  44650. }
  44651. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  44652. PIXI.EarCut.findHoleBridge = function (hole, outerNode) {
  44653. var p = outerNode,
  44654. hx = hole.x,
  44655. hy = hole.y,
  44656. qx = -Infinity,
  44657. m;
  44658. // find a segment intersected by a ray from the hole's leftmost point to the left;
  44659. // segment's endpoint with lesser x will be potential connection point
  44660. do {
  44661. if (hy <= p.y && hy >= p.next.y) {
  44662. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  44663. if (x <= hx && x > qx) {
  44664. qx = x;
  44665. m = p.x < p.next.x ? p : p.next;
  44666. }
  44667. }
  44668. p = p.next;
  44669. } while (p !== outerNode);
  44670. if (!m) return null;
  44671. if (hole.x === m.x) return m.prev; // hole touches outer segment; pick lower endpoint
  44672. // look for points inside the triangle of hole point, segment intersection and endpoint;
  44673. // if there are no points found, we have a valid connection;
  44674. // otherwise choose the point of the minimum angle with the ray as connection point
  44675. var stop = m,
  44676. tanMin = Infinity,
  44677. tan;
  44678. p = m.next;
  44679. while (p !== stop) {
  44680. if (hx >= p.x && p.x >= m.x &&
  44681. PIXI.EarCut.pointInTriangle(hy < m.y ? hx : qx, hy, m.x, m.y, hy < m.y ? qx : hx, hy, p.x, p.y)) {
  44682. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  44683. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && PIXI.EarCut.locallyInside(p, hole)) {
  44684. m = p;
  44685. tanMin = tan;
  44686. }
  44687. }
  44688. p = p.next;
  44689. }
  44690. return m;
  44691. }
  44692. // interlink polygon nodes in z-order
  44693. PIXI.EarCut.indexCurve = function (start, minX, minY, size) {
  44694. var p = start;
  44695. do {
  44696. if (p.z === null) p.z = PIXI.EarCut.zOrder(p.x, p.y, minX, minY, size);
  44697. p.prevZ = p.prev;
  44698. p.nextZ = p.next;
  44699. p = p.next;
  44700. } while (p !== start);
  44701. p.prevZ.nextZ = null;
  44702. p.prevZ = null;
  44703. PIXI.EarCut.sortLinked(p);
  44704. }
  44705. // Simon Tatham's linked list merge sort algorithm
  44706. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  44707. PIXI.EarCut.sortLinked = function (list) {
  44708. var i, p, q, e, tail, numMerges, pSize, qSize,
  44709. inSize = 1;
  44710. do {
  44711. p = list;
  44712. list = null;
  44713. tail = null;
  44714. numMerges = 0;
  44715. while (p) {
  44716. numMerges++;
  44717. q = p;
  44718. pSize = 0;
  44719. for (i = 0; i < inSize; i++) {
  44720. pSize++;
  44721. q = q.nextZ;
  44722. if (!q) break;
  44723. }
  44724. qSize = inSize;
  44725. while (pSize > 0 || (qSize > 0 && q)) {
  44726. if (pSize === 0) {
  44727. e = q;
  44728. q = q.nextZ;
  44729. qSize--;
  44730. } else if (qSize === 0 || !q) {
  44731. e = p;
  44732. p = p.nextZ;
  44733. pSize--;
  44734. } else if (p.z <= q.z) {
  44735. e = p;
  44736. p = p.nextZ;
  44737. pSize--;
  44738. } else {
  44739. e = q;
  44740. q = q.nextZ;
  44741. qSize--;
  44742. }
  44743. if (tail) tail.nextZ = e;
  44744. else list = e;
  44745. e.prevZ = tail;
  44746. tail = e;
  44747. }
  44748. p = q;
  44749. }
  44750. tail.nextZ = null;
  44751. inSize *= 2;
  44752. } while (numMerges > 1);
  44753. return list;
  44754. }
  44755. // z-order of a point given coords and size of the data bounding box
  44756. PIXI.EarCut.zOrder = function (x, y, minX, minY, size) {
  44757. // coords are transformed into non-negative 15-bit integer range
  44758. x = 32767 * (x - minX) / size;
  44759. y = 32767 * (y - minY) / size;
  44760. x = (x | (x << 8)) & 0x00FF00FF;
  44761. x = (x | (x << 4)) & 0x0F0F0F0F;
  44762. x = (x | (x << 2)) & 0x33333333;
  44763. x = (x | (x << 1)) & 0x55555555;
  44764. y = (y | (y << 8)) & 0x00FF00FF;
  44765. y = (y | (y << 4)) & 0x0F0F0F0F;
  44766. y = (y | (y << 2)) & 0x33333333;
  44767. y = (y | (y << 1)) & 0x55555555;
  44768. return x | (y << 1);
  44769. }
  44770. // find the leftmost node of a polygon ring
  44771. PIXI.EarCut.getLeftmost = function (start) {
  44772. var p = start,
  44773. leftmost = start;
  44774. do {
  44775. if (p.x < leftmost.x) leftmost = p;
  44776. p = p.next;
  44777. } while (p !== start);
  44778. return leftmost;
  44779. }
  44780. // check if a point lies within a convex triangle
  44781. PIXI.EarCut.pointInTriangle = function (ax, ay, bx, by, cx, cy, px, py) {
  44782. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  44783. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  44784. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  44785. }
  44786. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  44787. PIXI.EarCut.isValidDiagonal = function (a, b) {
  44788. return PIXI.EarCut.equals(a, b) || a.next.i !== b.i && a.prev.i !== b.i && !PIXI.EarCut.intersectsPolygon(a, b) &&
  44789. PIXI.EarCut.locallyInside(a, b) && PIXI.EarCut.locallyInside(b, a) && PIXI.EarCut.middleInside(a, b);
  44790. }
  44791. // signed area of a triangle
  44792. PIXI.EarCut.area = function (p, q, r) {
  44793. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  44794. }
  44795. // check if two points are equal
  44796. PIXI.EarCut.equals = function (p1, p2) {
  44797. return p1.x === p2.x && p1.y === p2.y;
  44798. }
  44799. // check if two segments intersect
  44800. PIXI.EarCut.intersects = function (p1, q1, p2, q2) {
  44801. return PIXI.EarCut.area(p1, q1, p2) > 0 !== PIXI.EarCut.area(p1, q1, q2) > 0 &&
  44802. PIXI.EarCut.area(p2, q2, p1) > 0 !== PIXI.EarCut.area(p2, q2, q1) > 0;
  44803. }
  44804. // check if a polygon diagonal intersects any polygon segments
  44805. PIXI.EarCut.intersectsPolygon = function (a, b) {
  44806. var p = a;
  44807. do {
  44808. if (p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i &&
  44809. PIXI.EarCut.intersects(p, p.next, a, b)) return true;
  44810. p = p.next;
  44811. } while (p !== a);
  44812. return false;
  44813. }
  44814. // check if a polygon diagonal is locally inside the polygon
  44815. PIXI.EarCut.locallyInside = function (a, b) {
  44816. return PIXI.EarCut.area(a.prev, a, a.next) < 0 ?
  44817. PIXI.EarCut.area(a, b, a.next) >= 0 && PIXI.EarCut.area(a, a.prev, b) >= 0 :
  44818. PIXI.EarCut.area(a, b, a.prev) < 0 || PIXI.EarCut.area(a, a.next, b) < 0;
  44819. }
  44820. // check if the middle point of a polygon diagonal is inside the polygon
  44821. PIXI.EarCut.middleInside = function (a, b) {
  44822. var p = a,
  44823. inside = false,
  44824. px = (a.x + b.x) / 2,
  44825. py = (a.y + b.y) / 2;
  44826. do {
  44827. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  44828. inside = !inside;
  44829. p = p.next;
  44830. } while (p !== a);
  44831. return inside;
  44832. }
  44833. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  44834. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  44835. PIXI.EarCut.splitPolygon = function (a, b) {
  44836. var a2 = new PIXI.EarCut.Node(a.i, a.x, a.y),
  44837. b2 = new PIXI.EarCut.Node(b.i, b.x, b.y),
  44838. an = a.next,
  44839. bp = b.prev;
  44840. a.next = b;
  44841. b.prev = a;
  44842. a2.next = an;
  44843. an.prev = a2;
  44844. b2.next = a2;
  44845. a2.prev = b2;
  44846. bp.next = b2;
  44847. b2.prev = bp;
  44848. return b2;
  44849. }
  44850. // create a node and optionally link it with previous one (in a circular doubly linked list)
  44851. PIXI.EarCut.insertNode = function (i, x, y, last) {
  44852. var p = new PIXI.EarCut.Node(i, x, y);
  44853. if (!last) {
  44854. p.prev = p;
  44855. p.next = p;
  44856. } else {
  44857. p.next = last.next;
  44858. p.prev = last;
  44859. last.next.prev = p;
  44860. last.next = p;
  44861. }
  44862. return p;
  44863. }
  44864. PIXI.EarCut.removeNode = function (p) {
  44865. p.next.prev = p.prev;
  44866. p.prev.next = p.next;
  44867. if (p.prevZ) p.prevZ.nextZ = p.nextZ;
  44868. if (p.nextZ) p.nextZ.prevZ = p.prevZ;
  44869. }
  44870. PIXI.EarCut.Node = function (i, x, y) {
  44871. // vertice index in coordinates array
  44872. this.i = i;
  44873. // vertex coordinates
  44874. this.x = x;
  44875. this.y = y;
  44876. // previous and next vertice nodes in a polygon ring
  44877. this.prev = null;
  44878. this.next = null;
  44879. // z-order curve value
  44880. this.z = null;
  44881. // previous and next nodes in z-order
  44882. this.prevZ = null;
  44883. this.nextZ = null;
  44884. // indicates whether this is a steiner point
  44885. this.steiner = false;
  44886. }
  44887. /**
  44888. * @author Mat Groves http://matgroves.com/ @Doormat23
  44889. */
  44890. /**
  44891. * A set of functions used by the webGL renderer to draw the primitive graphics data
  44892. *
  44893. * @class WebGLGraphics
  44894. * @private
  44895. * @static
  44896. */
  44897. PIXI.WebGLGraphics = function()
  44898. {
  44899. };
  44900. /**
  44901. * The number of points beyond which Pixi swaps to using the Stencil Buffer to render the Graphics.
  44902. *
  44903. * @type {number}
  44904. */
  44905. PIXI.WebGLGraphics.stencilBufferLimit = 6;
  44906. /**
  44907. * Renders the graphics object
  44908. *
  44909. * @static
  44910. * @private
  44911. * @method renderGraphics
  44912. * @param graphics {Graphics}
  44913. * @param renderSession {Object}
  44914. */
  44915. PIXI.WebGLGraphics.renderGraphics = function(graphics, renderSession)//projection, offset)
  44916. {
  44917. var gl = renderSession.gl;
  44918. var projection = renderSession.projection,
  44919. offset = renderSession.offset,
  44920. shader = renderSession.shaderManager.primitiveShader,
  44921. webGLData;
  44922. if(graphics.dirty)
  44923. {
  44924. PIXI.WebGLGraphics.updateGraphics(graphics, gl);
  44925. }
  44926. var webGL = graphics._webGL[gl.id];
  44927. // This could be speeded up for sure!
  44928. for (var i = 0; i < webGL.data.length; i++)
  44929. {
  44930. if(webGL.data[i].mode === 1)
  44931. {
  44932. webGLData = webGL.data[i];
  44933. renderSession.stencilManager.pushStencil(graphics, webGLData, renderSession);
  44934. // render quad..
  44935. gl.drawElements(gl.TRIANGLE_FAN, 4, gl.UNSIGNED_SHORT, ( webGLData.indices.length - 4 ) * 2 );
  44936. renderSession.stencilManager.popStencil(graphics, webGLData, renderSession);
  44937. }
  44938. else
  44939. {
  44940. webGLData = webGL.data[i];
  44941. renderSession.shaderManager.setShader( shader );//activatePrimitiveShader();
  44942. shader = renderSession.shaderManager.primitiveShader;
  44943. gl.uniformMatrix3fv(shader.translationMatrix, false, graphics.worldTransform.toArray(true));
  44944. gl.uniform1f(shader.flipY, 1);
  44945. gl.uniform2f(shader.projectionVector, projection.x, -projection.y);
  44946. gl.uniform2f(shader.offsetVector, -offset.x, -offset.y);
  44947. gl.uniform3fv(shader.tintColor, PIXI.hex2rgb(graphics.tint));
  44948. gl.uniform1f(shader.alpha, graphics.worldAlpha);
  44949. gl.bindBuffer(gl.ARRAY_BUFFER, webGLData.buffer);
  44950. gl.vertexAttribPointer(shader.aVertexPosition, 2, gl.FLOAT, false, 4 * 6, 0);
  44951. gl.vertexAttribPointer(shader.colorAttribute, 4, gl.FLOAT, false,4 * 6, 2 * 4);
  44952. // set the index buffer!
  44953. gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, webGLData.indexBuffer);
  44954. gl.drawElements(gl.TRIANGLE_STRIP, webGLData.indices.length, gl.UNSIGNED_SHORT, 0 );
  44955. }
  44956. }
  44957. };
  44958. /**
  44959. * Updates the graphics object
  44960. *
  44961. * @static
  44962. * @private
  44963. * @method updateGraphics
  44964. * @param graphicsData {Graphics} The graphics object to update
  44965. * @param gl {WebGLContext} the current WebGL drawing context
  44966. */
  44967. PIXI.WebGLGraphics.updateGraphics = function(graphics, gl)
  44968. {
  44969. // get the contexts graphics object
  44970. var webGL = graphics._webGL[gl.id];
  44971. // if the graphics object does not exist in the webGL context time to create it!
  44972. if(!webGL)webGL = graphics._webGL[gl.id] = {lastIndex:0, data:[], gl:gl};
  44973. // flag the graphics as not dirty as we are about to update it...
  44974. graphics.dirty = false;
  44975. var i;
  44976. // if the user cleared the graphics object we will need to clear every object
  44977. if(graphics.clearDirty)
  44978. {
  44979. graphics.clearDirty = false;
  44980. // lop through and return all the webGLDatas to the object pool so than can be reused later on
  44981. for (i = 0; i < webGL.data.length; i++)
  44982. {
  44983. var graphicsData = webGL.data[i];
  44984. graphicsData.reset();
  44985. PIXI.WebGLGraphics.graphicsDataPool.push( graphicsData );
  44986. }
  44987. // clear the array and reset the index..
  44988. webGL.data = [];
  44989. webGL.lastIndex = 0;
  44990. }
  44991. var webGLData;
  44992. // loop through the graphics datas and construct each one..
  44993. // if the object is a complex fill then the new stencil buffer technique will be used
  44994. // other wise graphics objects will be pushed into a batch..
  44995. for (i = webGL.lastIndex; i < graphics.graphicsData.length; i++)
  44996. {
  44997. var data = graphics.graphicsData[i];
  44998. if(data.type === PIXI.Graphics.POLY)
  44999. {
  45000. // need to add the points the the graphics object..
  45001. data.points = data.shape.points.slice();
  45002. if(data.shape.closed)
  45003. {
  45004. // close the poly if the value is true!
  45005. if(data.points[0] !== data.points[data.points.length-2] || data.points[1] !== data.points[data.points.length-1])
  45006. {
  45007. data.points.push(data.points[0], data.points[1]);
  45008. }
  45009. }
  45010. // MAKE SURE WE HAVE THE CORRECT TYPE..
  45011. if(data.fill)
  45012. {
  45013. if(data.points.length >= PIXI.WebGLGraphics.stencilBufferLimit)
  45014. {
  45015. if(data.points.length < PIXI.WebGLGraphics.stencilBufferLimit * 2)
  45016. {
  45017. webGLData = PIXI.WebGLGraphics.switchMode(webGL, 0);
  45018. var canDrawUsingSimple = PIXI.WebGLGraphics.buildPoly(data, webGLData);
  45019. // console.log(canDrawUsingSimple);
  45020. if(!canDrawUsingSimple)
  45021. {
  45022. // console.log("<>>>")
  45023. webGLData = PIXI.WebGLGraphics.switchMode(webGL, 1);
  45024. PIXI.WebGLGraphics.buildComplexPoly(data, webGLData);
  45025. }
  45026. }
  45027. else
  45028. {
  45029. webGLData = PIXI.WebGLGraphics.switchMode(webGL, 1);
  45030. PIXI.WebGLGraphics.buildComplexPoly(data, webGLData);
  45031. }
  45032. }
  45033. }
  45034. if(data.lineWidth > 0)
  45035. {
  45036. webGLData = PIXI.WebGLGraphics.switchMode(webGL, 0);
  45037. PIXI.WebGLGraphics.buildLine(data, webGLData);
  45038. }
  45039. }
  45040. else
  45041. {
  45042. webGLData = PIXI.WebGLGraphics.switchMode(webGL, 0);
  45043. if(data.type === PIXI.Graphics.RECT)
  45044. {
  45045. PIXI.WebGLGraphics.buildRectangle(data, webGLData);
  45046. }
  45047. else if(data.type === PIXI.Graphics.CIRC || data.type === PIXI.Graphics.ELIP)
  45048. {
  45049. PIXI.WebGLGraphics.buildCircle(data, webGLData);
  45050. }
  45051. else if(data.type === PIXI.Graphics.RREC)
  45052. {
  45053. PIXI.WebGLGraphics.buildRoundedRectangle(data, webGLData);
  45054. }
  45055. }
  45056. webGL.lastIndex++;
  45057. }
  45058. // upload all the dirty data...
  45059. for (i = 0; i < webGL.data.length; i++)
  45060. {
  45061. webGLData = webGL.data[i];
  45062. if(webGLData.dirty)webGLData.upload();
  45063. }
  45064. };
  45065. /**
  45066. * @static
  45067. * @private
  45068. * @method switchMode
  45069. * @param webGL {WebGLContext}
  45070. * @param type {Number}
  45071. */
  45072. PIXI.WebGLGraphics.switchMode = function(webGL, type)
  45073. {
  45074. var webGLData;
  45075. if(!webGL.data.length)
  45076. {
  45077. webGLData = PIXI.WebGLGraphics.graphicsDataPool.pop() || new PIXI.WebGLGraphicsData(webGL.gl);
  45078. webGLData.mode = type;
  45079. webGL.data.push(webGLData);
  45080. }
  45081. else
  45082. {
  45083. webGLData = webGL.data[webGL.data.length-1];
  45084. if(webGLData.mode !== type || type === 1)
  45085. {
  45086. webGLData = PIXI.WebGLGraphics.graphicsDataPool.pop() || new PIXI.WebGLGraphicsData(webGL.gl);
  45087. webGLData.mode = type;
  45088. webGL.data.push(webGLData);
  45089. }
  45090. }
  45091. webGLData.dirty = true;
  45092. return webGLData;
  45093. };
  45094. /**
  45095. * Builds a rectangle to draw
  45096. *
  45097. * @static
  45098. * @private
  45099. * @method buildRectangle
  45100. * @param graphicsData {Graphics} The graphics object containing all the necessary properties
  45101. * @param webGLData {Object}
  45102. */
  45103. PIXI.WebGLGraphics.buildRectangle = function(graphicsData, webGLData)
  45104. {
  45105. // --- //
  45106. // need to convert points to a nice regular data
  45107. //
  45108. var rectData = graphicsData.shape;
  45109. var x = rectData.x;
  45110. var y = rectData.y;
  45111. var width = rectData.width;
  45112. var height = rectData.height;
  45113. if(graphicsData.fill)
  45114. {
  45115. var color = PIXI.hex2rgb(graphicsData.fillColor);
  45116. var alpha = graphicsData.fillAlpha;
  45117. var r = color[0] * alpha;
  45118. var g = color[1] * alpha;
  45119. var b = color[2] * alpha;
  45120. var verts = webGLData.points;
  45121. var indices = webGLData.indices;
  45122. var vertPos = verts.length / 6;
  45123. // start
  45124. verts.push(x, y);
  45125. verts.push(r, g, b, alpha);
  45126. verts.push(x + width, y);
  45127. verts.push(r, g, b, alpha);
  45128. verts.push(x , y + height);
  45129. verts.push(r, g, b, alpha);
  45130. verts.push(x + width, y + height);
  45131. verts.push(r, g, b, alpha);
  45132. // insert 2 dead triangles..
  45133. indices.push(vertPos, vertPos, vertPos + 1, vertPos + 2, vertPos + 3, vertPos + 3);
  45134. }
  45135. if (graphicsData.lineWidth)
  45136. {
  45137. var tempPoints = graphicsData.points;
  45138. graphicsData.points = [x, y,
  45139. x + width, y,
  45140. x + width, y + height,
  45141. x, y + height,
  45142. x, y];
  45143. PIXI.WebGLGraphics.buildLine(graphicsData, webGLData);
  45144. graphicsData.points = tempPoints;
  45145. }
  45146. };
  45147. /**
  45148. * Builds a rounded rectangle to draw
  45149. *
  45150. * @static
  45151. * @private
  45152. * @method buildRoundedRectangle
  45153. * @param graphicsData {Graphics} The graphics object containing all the necessary properties
  45154. * @param webGLData {Object}
  45155. */
  45156. PIXI.WebGLGraphics.buildRoundedRectangle = function(graphicsData, webGLData)
  45157. {
  45158. var rrectData = graphicsData.shape;
  45159. var x = rrectData.x;
  45160. var y = rrectData.y;
  45161. var width = rrectData.width;
  45162. var height = rrectData.height;
  45163. var radius = rrectData.radius;
  45164. var recPoints = [];
  45165. recPoints.push(x, y + radius);
  45166. recPoints = recPoints.concat(PIXI.WebGLGraphics.quadraticBezierCurve(x, y + height - radius, x, y + height, x + radius, y + height));
  45167. recPoints = recPoints.concat(PIXI.WebGLGraphics.quadraticBezierCurve(x + width - radius, y + height, x + width, y + height, x + width, y + height - radius));
  45168. recPoints = recPoints.concat(PIXI.WebGLGraphics.quadraticBezierCurve(x + width, y + radius, x + width, y, x + width - radius, y));
  45169. recPoints = recPoints.concat(PIXI.WebGLGraphics.quadraticBezierCurve(x + radius, y, x, y, x, y + radius));
  45170. if (graphicsData.fill) {
  45171. var color = PIXI.hex2rgb(graphicsData.fillColor);
  45172. var alpha = graphicsData.fillAlpha;
  45173. var r = color[0] * alpha;
  45174. var g = color[1] * alpha;
  45175. var b = color[2] * alpha;
  45176. var verts = webGLData.points;
  45177. var indices = webGLData.indices;
  45178. var vecPos = verts.length / 6;
  45179. var triangles = PIXI.EarCut.Triangulate(recPoints, null, 2);
  45180. var i = 0;
  45181. for (i = 0; i < triangles.length; i+=3)
  45182. {
  45183. indices.push(triangles[i] + vecPos);
  45184. indices.push(triangles[i] + vecPos);
  45185. indices.push(triangles[i+1] + vecPos);
  45186. indices.push(triangles[i+2] + vecPos);
  45187. indices.push(triangles[i+2] + vecPos);
  45188. }
  45189. for (i = 0; i < recPoints.length; i++)
  45190. {
  45191. verts.push(recPoints[i], recPoints[++i], r, g, b, alpha);
  45192. }
  45193. }
  45194. if (graphicsData.lineWidth) {
  45195. var tempPoints = graphicsData.points;
  45196. graphicsData.points = recPoints;
  45197. PIXI.WebGLGraphics.buildLine(graphicsData, webGLData);
  45198. graphicsData.points = tempPoints;
  45199. }
  45200. };
  45201. /**
  45202. * Calculate the points for a quadratic bezier curve. (helper function..)
  45203. * Based on: https://stackoverflow.com/questions/785097/how-do-i-implement-a-bezier-curve-in-c
  45204. *
  45205. * @static
  45206. * @private
  45207. * @method quadraticBezierCurve
  45208. * @param fromX {Number} Origin point x
  45209. * @param fromY {Number} Origin point x
  45210. * @param cpX {Number} Control point x
  45211. * @param cpY {Number} Control point y
  45212. * @param toX {Number} Destination point x
  45213. * @param toY {Number} Destination point y
  45214. * @return {Array(Number)}
  45215. */
  45216. PIXI.WebGLGraphics.quadraticBezierCurve = function(fromX, fromY, cpX, cpY, toX, toY) {
  45217. var xa,
  45218. ya,
  45219. xb,
  45220. yb,
  45221. x,
  45222. y,
  45223. n = 20,
  45224. points = [];
  45225. function getPt(n1 , n2, perc) {
  45226. var diff = n2 - n1;
  45227. return n1 + ( diff * perc );
  45228. }
  45229. var j = 0;
  45230. for (var i = 0; i <= n; i++ )
  45231. {
  45232. j = i / n;
  45233. // The Green Line
  45234. xa = getPt( fromX , cpX , j );
  45235. ya = getPt( fromY , cpY , j );
  45236. xb = getPt( cpX , toX , j );
  45237. yb = getPt( cpY , toY , j );
  45238. // The Black Dot
  45239. x = getPt( xa , xb , j );
  45240. y = getPt( ya , yb , j );
  45241. points.push(x, y);
  45242. }
  45243. return points;
  45244. };
  45245. /**
  45246. * Builds a circle to draw
  45247. *
  45248. * @static
  45249. * @private
  45250. * @method buildCircle
  45251. * @param graphicsData {Graphics} The graphics object to draw
  45252. * @param webGLData {Object}
  45253. */
  45254. PIXI.WebGLGraphics.buildCircle = function(graphicsData, webGLData)
  45255. {
  45256. // need to convert points to a nice regular data
  45257. var circleData = graphicsData.shape;
  45258. var x = circleData.x;
  45259. var y = circleData.y;
  45260. var width;
  45261. var height;
  45262. // TODO - bit hacky??
  45263. if(graphicsData.type === PIXI.Graphics.CIRC)
  45264. {
  45265. width = circleData.radius;
  45266. height = circleData.radius;
  45267. }
  45268. else
  45269. {
  45270. width = circleData.width;
  45271. height = circleData.height;
  45272. }
  45273. var totalSegs = 40;
  45274. var seg = (Math.PI * 2) / totalSegs ;
  45275. var i = 0;
  45276. if(graphicsData.fill)
  45277. {
  45278. var color = PIXI.hex2rgb(graphicsData.fillColor);
  45279. var alpha = graphicsData.fillAlpha;
  45280. var r = color[0] * alpha;
  45281. var g = color[1] * alpha;
  45282. var b = color[2] * alpha;
  45283. var verts = webGLData.points;
  45284. var indices = webGLData.indices;
  45285. var vecPos = verts.length / 6;
  45286. indices.push(vecPos);
  45287. for (i = 0; i < totalSegs + 1 ; i++)
  45288. {
  45289. verts.push(x,y, r, g, b, alpha);
  45290. verts.push(x + Math.sin(seg * i) * width,
  45291. y + Math.cos(seg * i) * height,
  45292. r, g, b, alpha);
  45293. indices.push(vecPos++, vecPos++);
  45294. }
  45295. indices.push(vecPos-1);
  45296. }
  45297. if(graphicsData.lineWidth)
  45298. {
  45299. var tempPoints = graphicsData.points;
  45300. graphicsData.points = [];
  45301. for (i = 0; i < totalSegs + 1; i++)
  45302. {
  45303. graphicsData.points.push(x + Math.sin(seg * i) * width,
  45304. y + Math.cos(seg * i) * height);
  45305. }
  45306. PIXI.WebGLGraphics.buildLine(graphicsData, webGLData);
  45307. graphicsData.points = tempPoints;
  45308. }
  45309. };
  45310. /**
  45311. * Builds a line to draw
  45312. *
  45313. * @static
  45314. * @private
  45315. * @method buildLine
  45316. * @param graphicsData {Graphics} The graphics object containing all the necessary properties
  45317. * @param webGLData {Object}
  45318. */
  45319. PIXI.WebGLGraphics.buildLine = function(graphicsData, webGLData)
  45320. {
  45321. // TODO OPTIMISE!
  45322. var i = 0;
  45323. var points = graphicsData.points;
  45324. if(points.length === 0)return;
  45325. // if the line width is an odd number add 0.5 to align to a whole pixel
  45326. if(graphicsData.lineWidth%2)
  45327. {
  45328. for (i = 0; i < points.length; i++) {
  45329. points[i] += 0.5;
  45330. }
  45331. }
  45332. // get first and last point.. figure out the middle!
  45333. var firstPoint = new PIXI.Point( points[0], points[1] );
  45334. var lastPoint = new PIXI.Point( points[points.length - 2], points[points.length - 1] );
  45335. // if the first point is the last point - gonna have issues :)
  45336. if(firstPoint.x === lastPoint.x && firstPoint.y === lastPoint.y)
  45337. {
  45338. // need to clone as we are going to slightly modify the shape..
  45339. points = points.slice();
  45340. points.pop();
  45341. points.pop();
  45342. lastPoint = new PIXI.Point( points[points.length - 2], points[points.length - 1] );
  45343. var midPointX = lastPoint.x + (firstPoint.x - lastPoint.x) *0.5;
  45344. var midPointY = lastPoint.y + (firstPoint.y - lastPoint.y) *0.5;
  45345. points.unshift(midPointX, midPointY);
  45346. points.push(midPointX, midPointY);
  45347. }
  45348. var verts = webGLData.points;
  45349. var indices = webGLData.indices;
  45350. var length = points.length / 2;
  45351. var indexCount = points.length;
  45352. var indexStart = verts.length/6;
  45353. // DRAW the Line
  45354. var width = graphicsData.lineWidth / 2;
  45355. // sort color
  45356. var color = PIXI.hex2rgb(graphicsData.lineColor);
  45357. var alpha = graphicsData.lineAlpha;
  45358. var r = color[0] * alpha;
  45359. var g = color[1] * alpha;
  45360. var b = color[2] * alpha;
  45361. var px, py, p1x, p1y, p2x, p2y, p3x, p3y;
  45362. var perpx, perpy, perp2x, perp2y, perp3x, perp3y;
  45363. var a1, b1, c1, a2, b2, c2;
  45364. var denom, pdist, dist;
  45365. p1x = points[0];
  45366. p1y = points[1];
  45367. p2x = points[2];
  45368. p2y = points[3];
  45369. perpx = -(p1y - p2y);
  45370. perpy = p1x - p2x;
  45371. dist = Math.sqrt(perpx*perpx + perpy*perpy);
  45372. perpx /= dist;
  45373. perpy /= dist;
  45374. perpx *= width;
  45375. perpy *= width;
  45376. // start
  45377. verts.push(p1x - perpx , p1y - perpy,
  45378. r, g, b, alpha);
  45379. verts.push(p1x + perpx , p1y + perpy,
  45380. r, g, b, alpha);
  45381. for (i = 1; i < length-1; i++)
  45382. {
  45383. p1x = points[(i-1)*2];
  45384. p1y = points[(i-1)*2 + 1];
  45385. p2x = points[(i)*2];
  45386. p2y = points[(i)*2 + 1];
  45387. p3x = points[(i+1)*2];
  45388. p3y = points[(i+1)*2 + 1];
  45389. perpx = -(p1y - p2y);
  45390. perpy = p1x - p2x;
  45391. dist = Math.sqrt(perpx*perpx + perpy*perpy);
  45392. perpx /= dist;
  45393. perpy /= dist;
  45394. perpx *= width;
  45395. perpy *= width;
  45396. perp2x = -(p2y - p3y);
  45397. perp2y = p2x - p3x;
  45398. dist = Math.sqrt(perp2x*perp2x + perp2y*perp2y);
  45399. perp2x /= dist;
  45400. perp2y /= dist;
  45401. perp2x *= width;
  45402. perp2y *= width;
  45403. a1 = (-perpy + p1y) - (-perpy + p2y);
  45404. b1 = (-perpx + p2x) - (-perpx + p1x);
  45405. c1 = (-perpx + p1x) * (-perpy + p2y) - (-perpx + p2x) * (-perpy + p1y);
  45406. a2 = (-perp2y + p3y) - (-perp2y + p2y);
  45407. b2 = (-perp2x + p2x) - (-perp2x + p3x);
  45408. c2 = (-perp2x + p3x) * (-perp2y + p2y) - (-perp2x + p2x) * (-perp2y + p3y);
  45409. denom = a1*b2 - a2*b1;
  45410. if(Math.abs(denom) < 0.1 )
  45411. {
  45412. denom+=10.1;
  45413. verts.push(p2x - perpx , p2y - perpy,
  45414. r, g, b, alpha);
  45415. verts.push(p2x + perpx , p2y + perpy,
  45416. r, g, b, alpha);
  45417. continue;
  45418. }
  45419. px = (b1*c2 - b2*c1)/denom;
  45420. py = (a2*c1 - a1*c2)/denom;
  45421. pdist = (px -p2x) * (px -p2x) + (py -p2y) + (py -p2y);
  45422. if(pdist > 140 * 140)
  45423. {
  45424. perp3x = perpx - perp2x;
  45425. perp3y = perpy - perp2y;
  45426. dist = Math.sqrt(perp3x*perp3x + perp3y*perp3y);
  45427. perp3x /= dist;
  45428. perp3y /= dist;
  45429. perp3x *= width;
  45430. perp3y *= width;
  45431. verts.push(p2x - perp3x, p2y -perp3y);
  45432. verts.push(r, g, b, alpha);
  45433. verts.push(p2x + perp3x, p2y +perp3y);
  45434. verts.push(r, g, b, alpha);
  45435. verts.push(p2x - perp3x, p2y -perp3y);
  45436. verts.push(r, g, b, alpha);
  45437. indexCount++;
  45438. }
  45439. else
  45440. {
  45441. verts.push(px , py);
  45442. verts.push(r, g, b, alpha);
  45443. verts.push(p2x - (px-p2x), p2y - (py - p2y));
  45444. verts.push(r, g, b, alpha);
  45445. }
  45446. }
  45447. p1x = points[(length-2)*2];
  45448. p1y = points[(length-2)*2 + 1];
  45449. p2x = points[(length-1)*2];
  45450. p2y = points[(length-1)*2 + 1];
  45451. perpx = -(p1y - p2y);
  45452. perpy = p1x - p2x;
  45453. dist = Math.sqrt(perpx*perpx + perpy*perpy);
  45454. perpx /= dist;
  45455. perpy /= dist;
  45456. perpx *= width;
  45457. perpy *= width;
  45458. verts.push(p2x - perpx , p2y - perpy);
  45459. verts.push(r, g, b, alpha);
  45460. verts.push(p2x + perpx , p2y + perpy);
  45461. verts.push(r, g, b, alpha);
  45462. indices.push(indexStart);
  45463. for (i = 0; i < indexCount; i++)
  45464. {
  45465. indices.push(indexStart++);
  45466. }
  45467. indices.push(indexStart-1);
  45468. };
  45469. /**
  45470. * Builds a complex polygon to draw
  45471. *
  45472. * @static
  45473. * @private
  45474. * @method buildComplexPoly
  45475. * @param graphicsData {Graphics} The graphics object containing all the necessary properties
  45476. * @param webGLData {Object}
  45477. */
  45478. PIXI.WebGLGraphics.buildComplexPoly = function(graphicsData, webGLData)
  45479. {
  45480. //TODO - no need to copy this as it gets turned into a FLoat32Array anyways..
  45481. var points = graphicsData.points.slice();
  45482. if(points.length < 6)return;
  45483. // get first and last point.. figure out the middle!
  45484. var indices = webGLData.indices;
  45485. webGLData.points = points;
  45486. webGLData.alpha = graphicsData.fillAlpha;
  45487. webGLData.color = PIXI.hex2rgb(graphicsData.fillColor);
  45488. /*
  45489. calclate the bounds..
  45490. */
  45491. var minX = Infinity;
  45492. var maxX = -Infinity;
  45493. var minY = Infinity;
  45494. var maxY = -Infinity;
  45495. var x,y;
  45496. // get size..
  45497. for (var i = 0; i < points.length; i+=2)
  45498. {
  45499. x = points[i];
  45500. y = points[i+1];
  45501. minX = x < minX ? x : minX;
  45502. maxX = x > maxX ? x : maxX;
  45503. minY = y < minY ? y : minY;
  45504. maxY = y > maxY ? y : maxY;
  45505. }
  45506. // add a quad to the end cos there is no point making another buffer!
  45507. points.push(minX, minY,
  45508. maxX, minY,
  45509. maxX, maxY,
  45510. minX, maxY);
  45511. // push a quad onto the end..
  45512. //TODO - this aint needed!
  45513. var length = points.length / 2;
  45514. for (i = 0; i < length; i++)
  45515. {
  45516. indices.push( i );
  45517. }
  45518. };
  45519. /**
  45520. * Builds a polygon to draw
  45521. *
  45522. * @static
  45523. * @private
  45524. * @method buildPoly
  45525. * @param graphicsData {Graphics} The graphics object containing all the necessary properties
  45526. * @param webGLData {Object}
  45527. */
  45528. PIXI.WebGLGraphics.buildPoly = function(graphicsData, webGLData)
  45529. {
  45530. var points = graphicsData.points;
  45531. if(points.length < 6)return;
  45532. // get first and last point.. figure out the middle!
  45533. var verts = webGLData.points;
  45534. var indices = webGLData.indices;
  45535. var length = points.length / 2;
  45536. // sort color
  45537. var color = PIXI.hex2rgb(graphicsData.fillColor);
  45538. var alpha = graphicsData.fillAlpha;
  45539. var r = color[0] * alpha;
  45540. var g = color[1] * alpha;
  45541. var b = color[2] * alpha;
  45542. var triangles = PIXI.EarCut.Triangulate(points, null, 2);
  45543. if(!triangles)return false;
  45544. var vertPos = verts.length / 6;
  45545. var i = 0;
  45546. for (i = 0; i < triangles.length; i+=3)
  45547. {
  45548. indices.push(triangles[i] + vertPos);
  45549. indices.push(triangles[i] + vertPos);
  45550. indices.push(triangles[i+1] + vertPos);
  45551. indices.push(triangles[i+2] +vertPos);
  45552. indices.push(triangles[i+2] + vertPos);
  45553. }
  45554. for (i = 0; i < length; i++)
  45555. {
  45556. verts.push(points[i * 2], points[i * 2 + 1],
  45557. r, g, b, alpha);
  45558. }
  45559. return true;
  45560. };
  45561. PIXI.WebGLGraphics.graphicsDataPool = [];
  45562. /**
  45563. * @class WebGLGraphicsData
  45564. * @private
  45565. * @static
  45566. */
  45567. PIXI.WebGLGraphicsData = function(gl)
  45568. {
  45569. this.gl = gl;
  45570. //TODO does this need to be split before uploding??
  45571. this.color = [0,0,0]; // color split!
  45572. this.points = [];
  45573. this.indices = [];
  45574. this.buffer = gl.createBuffer();
  45575. this.indexBuffer = gl.createBuffer();
  45576. this.mode = 1;
  45577. this.alpha = 1;
  45578. this.dirty = true;
  45579. };
  45580. /**
  45581. * @method reset
  45582. */
  45583. PIXI.WebGLGraphicsData.prototype.reset = function()
  45584. {
  45585. this.points = [];
  45586. this.indices = [];
  45587. };
  45588. /**
  45589. * @method upload
  45590. */
  45591. PIXI.WebGLGraphicsData.prototype.upload = function()
  45592. {
  45593. var gl = this.gl;
  45594. // this.lastIndex = graphics.graphicsData.length;
  45595. this.glPoints = new PIXI.Float32Array(this.points);
  45596. gl.bindBuffer(gl.ARRAY_BUFFER, this.buffer);
  45597. gl.bufferData(gl.ARRAY_BUFFER, this.glPoints, gl.STATIC_DRAW);
  45598. this.glIndicies = new PIXI.Uint16Array(this.indices);
  45599. gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this.indexBuffer);
  45600. gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, this.glIndicies, gl.STATIC_DRAW);
  45601. this.dirty = false;
  45602. };
  45603. /**
  45604. * @author Mat Groves http://matgroves.com/ @Doormat23
  45605. */
  45606. /**
  45607. * A set of functions used by the canvas renderer to draw the primitive graphics data.
  45608. *
  45609. * @class CanvasGraphics
  45610. * @static
  45611. */
  45612. PIXI.CanvasGraphics = function()
  45613. {
  45614. };
  45615. /*
  45616. * Renders a PIXI.Graphics object to a canvas.
  45617. *
  45618. * @method renderGraphics
  45619. * @static
  45620. * @param graphics {Graphics} the actual graphics object to render
  45621. * @param context {CanvasRenderingContext2D} the 2d drawing method of the canvas
  45622. */
  45623. PIXI.CanvasGraphics.renderGraphics = function(graphics, context)
  45624. {
  45625. var worldAlpha = graphics.worldAlpha;
  45626. if (graphics.dirty)
  45627. {
  45628. this.updateGraphicsTint(graphics);
  45629. graphics.dirty = false;
  45630. }
  45631. for (var i = 0; i < graphics.graphicsData.length; i++)
  45632. {
  45633. var data = graphics.graphicsData[i];
  45634. var shape = data.shape;
  45635. var fillColor = data._fillTint;
  45636. var lineColor = data._lineTint;
  45637. context.lineWidth = data.lineWidth;
  45638. if (data.type === PIXI.Graphics.POLY)
  45639. {
  45640. context.beginPath();
  45641. var points = shape.points;
  45642. context.moveTo(points[0], points[1]);
  45643. for (var j=1; j < points.length/2; j++)
  45644. {
  45645. context.lineTo(points[j * 2], points[j * 2 + 1]);
  45646. }
  45647. if (shape.closed)
  45648. {
  45649. context.lineTo(points[0], points[1]);
  45650. }
  45651. // if the first and last point are the same close the path - much neater :)
  45652. if (points[0] === points[points.length-2] && points[1] === points[points.length-1])
  45653. {
  45654. context.closePath();
  45655. }
  45656. if (data.fill)
  45657. {
  45658. context.globalAlpha = data.fillAlpha * worldAlpha;
  45659. context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6);
  45660. context.fill();
  45661. }
  45662. if (data.lineWidth)
  45663. {
  45664. context.globalAlpha = data.lineAlpha * worldAlpha;
  45665. context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6);
  45666. context.stroke();
  45667. }
  45668. }
  45669. else if (data.type === PIXI.Graphics.RECT)
  45670. {
  45671. if (data.fillColor || data.fillColor === 0)
  45672. {
  45673. context.globalAlpha = data.fillAlpha * worldAlpha;
  45674. context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6);
  45675. context.fillRect(shape.x, shape.y, shape.width, shape.height);
  45676. }
  45677. if (data.lineWidth)
  45678. {
  45679. context.globalAlpha = data.lineAlpha * worldAlpha;
  45680. context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6);
  45681. context.strokeRect(shape.x, shape.y, shape.width, shape.height);
  45682. }
  45683. }
  45684. else if (data.type === PIXI.Graphics.CIRC)
  45685. {
  45686. // TODO - need to be Undefined!
  45687. context.beginPath();
  45688. context.arc(shape.x, shape.y, shape.radius,0,2*Math.PI);
  45689. context.closePath();
  45690. if (data.fill)
  45691. {
  45692. context.globalAlpha = data.fillAlpha * worldAlpha;
  45693. context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6);
  45694. context.fill();
  45695. }
  45696. if (data.lineWidth)
  45697. {
  45698. context.globalAlpha = data.lineAlpha * worldAlpha;
  45699. context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6);
  45700. context.stroke();
  45701. }
  45702. }
  45703. else if (data.type === PIXI.Graphics.ELIP)
  45704. {
  45705. // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas
  45706. var w = shape.width * 2;
  45707. var h = shape.height * 2;
  45708. var x = shape.x - w/2;
  45709. var y = shape.y - h/2;
  45710. context.beginPath();
  45711. var kappa = 0.5522848,
  45712. ox = (w / 2) * kappa, // control point offset horizontal
  45713. oy = (h / 2) * kappa, // control point offset vertical
  45714. xe = x + w, // x-end
  45715. ye = y + h, // y-end
  45716. xm = x + w / 2, // x-middle
  45717. ym = y + h / 2; // y-middle
  45718. context.moveTo(x, ym);
  45719. context.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y);
  45720. context.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym);
  45721. context.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye);
  45722. context.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym);
  45723. context.closePath();
  45724. if (data.fill)
  45725. {
  45726. context.globalAlpha = data.fillAlpha * worldAlpha;
  45727. context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6);
  45728. context.fill();
  45729. }
  45730. if (data.lineWidth)
  45731. {
  45732. context.globalAlpha = data.lineAlpha * worldAlpha;
  45733. context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6);
  45734. context.stroke();
  45735. }
  45736. }
  45737. else if (data.type === PIXI.Graphics.RREC)
  45738. {
  45739. var rx = shape.x;
  45740. var ry = shape.y;
  45741. var width = shape.width;
  45742. var height = shape.height;
  45743. var radius = shape.radius;
  45744. var maxRadius = Math.min(width, height) / 2 | 0;
  45745. radius = radius > maxRadius ? maxRadius : radius;
  45746. context.beginPath();
  45747. context.moveTo(rx, ry + radius);
  45748. context.lineTo(rx, ry + height - radius);
  45749. context.quadraticCurveTo(rx, ry + height, rx + radius, ry + height);
  45750. context.lineTo(rx + width - radius, ry + height);
  45751. context.quadraticCurveTo(rx + width, ry + height, rx + width, ry + height - radius);
  45752. context.lineTo(rx + width, ry + radius);
  45753. context.quadraticCurveTo(rx + width, ry, rx + width - radius, ry);
  45754. context.lineTo(rx + radius, ry);
  45755. context.quadraticCurveTo(rx, ry, rx, ry + radius);
  45756. context.closePath();
  45757. if (data.fillColor || data.fillColor === 0)
  45758. {
  45759. context.globalAlpha = data.fillAlpha * worldAlpha;
  45760. context.fillStyle = '#' + ('00000' + ( fillColor | 0).toString(16)).substr(-6);
  45761. context.fill();
  45762. }
  45763. if (data.lineWidth)
  45764. {
  45765. context.globalAlpha = data.lineAlpha * worldAlpha;
  45766. context.strokeStyle = '#' + ('00000' + ( lineColor | 0).toString(16)).substr(-6);
  45767. context.stroke();
  45768. }
  45769. }
  45770. }
  45771. };
  45772. /*
  45773. * Renders a graphics mask
  45774. *
  45775. * @static
  45776. * @private
  45777. * @method renderGraphicsMask
  45778. * @param graphics {Graphics} the graphics which will be used as a mask
  45779. * @param context {CanvasRenderingContext2D} the context 2d method of the canvas
  45780. */
  45781. PIXI.CanvasGraphics.renderGraphicsMask = function(graphics, context)
  45782. {
  45783. var len = graphics.graphicsData.length;
  45784. if (len === 0)
  45785. {
  45786. return;
  45787. }
  45788. context.beginPath();
  45789. for (var i = 0; i < len; i++)
  45790. {
  45791. var data = graphics.graphicsData[i];
  45792. var shape = data.shape;
  45793. if (data.type === PIXI.Graphics.POLY)
  45794. {
  45795. var points = shape.points;
  45796. context.moveTo(points[0], points[1]);
  45797. for (var j=1; j < points.length/2; j++)
  45798. {
  45799. context.lineTo(points[j * 2], points[j * 2 + 1]);
  45800. }
  45801. // if the first and last point are the same close the path - much neater :)
  45802. if (points[0] === points[points.length-2] && points[1] === points[points.length-1])
  45803. {
  45804. context.closePath();
  45805. }
  45806. }
  45807. else if (data.type === PIXI.Graphics.RECT)
  45808. {
  45809. context.rect(shape.x, shape.y, shape.width, shape.height);
  45810. context.closePath();
  45811. }
  45812. else if (data.type === PIXI.Graphics.CIRC)
  45813. {
  45814. // TODO - need to be Undefined!
  45815. context.arc(shape.x, shape.y, shape.radius, 0, 2 * Math.PI);
  45816. context.closePath();
  45817. }
  45818. else if (data.type === PIXI.Graphics.ELIP)
  45819. {
  45820. // ellipse code taken from: http://stackoverflow.com/questions/2172798/how-to-draw-an-oval-in-html5-canvas
  45821. var w = shape.width * 2;
  45822. var h = shape.height * 2;
  45823. var x = shape.x - w/2;
  45824. var y = shape.y - h/2;
  45825. var kappa = 0.5522848,
  45826. ox = (w / 2) * kappa, // control point offset horizontal
  45827. oy = (h / 2) * kappa, // control point offset vertical
  45828. xe = x + w, // x-end
  45829. ye = y + h, // y-end
  45830. xm = x + w / 2, // x-middle
  45831. ym = y + h / 2; // y-middle
  45832. context.moveTo(x, ym);
  45833. context.bezierCurveTo(x, ym - oy, xm - ox, y, xm, y);
  45834. context.bezierCurveTo(xm + ox, y, xe, ym - oy, xe, ym);
  45835. context.bezierCurveTo(xe, ym + oy, xm + ox, ye, xm, ye);
  45836. context.bezierCurveTo(xm - ox, ye, x, ym + oy, x, ym);
  45837. context.closePath();
  45838. }
  45839. else if (data.type === PIXI.Graphics.RREC)
  45840. {
  45841. var rx = shape.x;
  45842. var ry = shape.y;
  45843. var width = shape.width;
  45844. var height = shape.height;
  45845. var radius = shape.radius;
  45846. var maxRadius = Math.min(width, height) / 2 | 0;
  45847. radius = radius > maxRadius ? maxRadius : radius;
  45848. context.moveTo(rx, ry + radius);
  45849. context.lineTo(rx, ry + height - radius);
  45850. context.quadraticCurveTo(rx, ry + height, rx + radius, ry + height);
  45851. context.lineTo(rx + width - radius, ry + height);
  45852. context.quadraticCurveTo(rx + width, ry + height, rx + width, ry + height - radius);
  45853. context.lineTo(rx + width, ry + radius);
  45854. context.quadraticCurveTo(rx + width, ry, rx + width - radius, ry);
  45855. context.lineTo(rx + radius, ry);
  45856. context.quadraticCurveTo(rx, ry, rx, ry + radius);
  45857. context.closePath();
  45858. }
  45859. }
  45860. };
  45861. PIXI.CanvasGraphics.updateGraphicsTint = function(graphics)
  45862. {
  45863. if (graphics.tint === 0xFFFFFF)
  45864. {
  45865. return;
  45866. }
  45867. var tintR = (graphics.tint >> 16 & 0xFF) / 255;
  45868. var tintG = (graphics.tint >> 8 & 0xFF) / 255;
  45869. var tintB = (graphics.tint & 0xFF)/ 255;
  45870. for (var i = 0; i < graphics.graphicsData.length; i++)
  45871. {
  45872. var data = graphics.graphicsData[i];
  45873. var fillColor = data.fillColor | 0;
  45874. var lineColor = data.lineColor | 0;
  45875. data._fillTint = (((fillColor >> 16 & 0xFF) / 255 * tintR*255 << 16) + ((fillColor >> 8 & 0xFF) / 255 * tintG*255 << 8) + (fillColor & 0xFF) / 255 * tintB*255);
  45876. data._lineTint = (((lineColor >> 16 & 0xFF) / 255 * tintR*255 << 16) + ((lineColor >> 8 & 0xFF) / 255 * tintG*255 << 8) + (lineColor & 0xFF) / 255 * tintB*255);
  45877. }
  45878. };
  45879. /**
  45880. * @author Richard Davey <rich@photonstorm.com>
  45881. * @copyright 2016 Photon Storm Ltd.
  45882. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  45883. */
  45884. /**
  45885. * A Graphics object is a way to draw primitives to your game. Primitives include forms of geometry, such as Rectangles,
  45886. * Circles and Polygons. They also include lines, arcs and curves. When you initially create a Graphics object it will
  45887. * be empty. To 'draw' to it you first specify a lineStyle or fillStyle (or both), and then draw a shape. For example:
  45888. *
  45889. * ```
  45890. * graphics.beginFill(0xff0000);
  45891. * graphics.drawCircle(50, 50, 100);
  45892. * graphics.endFill();
  45893. * ```
  45894. *
  45895. * This will draw a circle shape to the Graphics object, with a diameter of 100, located at x: 50, y: 50.
  45896. *
  45897. * When a Graphics object is rendered it will render differently based on if the game is running under Canvas or
  45898. * WebGL. Under Canvas it will use the HTML Canvas context drawing operations to draw the path. Under WebGL the
  45899. * graphics data is decomposed into polygons. Both of these are expensive processes, especially with complex shapes.
  45900. *
  45901. * If your Graphics object doesn't change much (or at all) once you've drawn your shape to it, then you will help
  45902. * performance by calling `Graphics.generateTexture`. This will 'bake' the Graphics object into a Texture, and return it.
  45903. * You can then use this Texture for Sprites or other display objects. If your Graphics object updates frequently then
  45904. * you should avoid doing this, as it will constantly generate new textures, which will consume memory.
  45905. *
  45906. * As you can tell, Graphics objects are a bit of a trade-off. While they are extremely useful, you need to be careful
  45907. * in their complexity and quantity of them in your game.
  45908. *
  45909. * @class Phaser.Graphics
  45910. * @constructor
  45911. * @extends PIXI.Graphics
  45912. * @extends Phaser.Component.Core
  45913. * @extends Phaser.Component.Angle
  45914. * @extends Phaser.Component.AutoCull
  45915. * @extends Phaser.Component.Bounds
  45916. * @extends Phaser.Component.Destroy
  45917. * @extends Phaser.Component.FixedToCamera
  45918. * @extends Phaser.Component.InputEnabled
  45919. * @extends Phaser.Component.InWorld
  45920. * @extends Phaser.Component.LifeSpan
  45921. * @extends Phaser.Component.PhysicsBody
  45922. * @extends Phaser.Component.Reset
  45923. * @param {Phaser.Game} game - Current game instance.
  45924. * @param {number} [x=0] - X position of the new graphics object.
  45925. * @param {number} [y=0] - Y position of the new graphics object.
  45926. */
  45927. Phaser.Graphics = function (game, x, y) {
  45928. if (x === undefined) { x = 0; }
  45929. if (y === undefined) { y = 0; }
  45930. /**
  45931. * @property {number} type - The const type of this object.
  45932. * @default
  45933. */
  45934. this.type = Phaser.GRAPHICS;
  45935. /**
  45936. * @property {number} physicsType - The const physics body type of this object.
  45937. * @readonly
  45938. */
  45939. this.physicsType = Phaser.SPRITE;
  45940. /**
  45941. * @property {Phaser.Point} anchor - Required for a Graphics shape to work as a Physics body, do not modify this value.
  45942. * @private
  45943. */
  45944. this.anchor = new Phaser.Point();
  45945. PIXI.Graphics.call(this);
  45946. Phaser.Component.Core.init.call(this, game, x, y, '', null);
  45947. };
  45948. Phaser.Graphics.prototype = Object.create(PIXI.Graphics.prototype);
  45949. Phaser.Graphics.prototype.constructor = Phaser.Graphics;
  45950. Phaser.Component.Core.install.call(Phaser.Graphics.prototype, [
  45951. 'Angle',
  45952. 'AutoCull',
  45953. 'Bounds',
  45954. 'Destroy',
  45955. 'FixedToCamera',
  45956. 'InputEnabled',
  45957. 'InWorld',
  45958. 'LifeSpan',
  45959. 'PhysicsBody',
  45960. 'Reset'
  45961. ]);
  45962. Phaser.Graphics.prototype.preUpdatePhysics = Phaser.Component.PhysicsBody.preUpdate;
  45963. Phaser.Graphics.prototype.preUpdateLifeSpan = Phaser.Component.LifeSpan.preUpdate;
  45964. Phaser.Graphics.prototype.preUpdateInWorld = Phaser.Component.InWorld.preUpdate;
  45965. Phaser.Graphics.prototype.preUpdateCore = Phaser.Component.Core.preUpdate;
  45966. /**
  45967. * Automatically called by World.preUpdate.
  45968. *
  45969. * @method
  45970. * @memberof Phaser.Graphics
  45971. */
  45972. Phaser.Graphics.prototype.preUpdate = function () {
  45973. if (!this.preUpdatePhysics() || !this.preUpdateLifeSpan() || !this.preUpdateInWorld())
  45974. {
  45975. return false;
  45976. }
  45977. return this.preUpdateCore();
  45978. };
  45979. /**
  45980. * Automatically called by World
  45981. * @method Phaser.Graphics.prototype.postUpdate
  45982. */
  45983. Phaser.Graphics.prototype.postUpdate = function () {
  45984. Phaser.Component.PhysicsBody.postUpdate.call(this);
  45985. Phaser.Component.FixedToCamera.postUpdate.call(this);
  45986. if (this._boundsDirty)
  45987. {
  45988. this.updateLocalBounds();
  45989. this._boundsDirty = false;
  45990. }
  45991. for (var i = 0; i < this.children.length; i++)
  45992. {
  45993. this.children[i].postUpdate();
  45994. }
  45995. };
  45996. /**
  45997. * Destroy this Graphics instance.
  45998. *
  45999. * @method Phaser.Graphics.prototype.destroy
  46000. * @param {boolean} [destroyChildren=true] - Should every child of this object have its destroy method called?
  46001. */
  46002. Phaser.Graphics.prototype.destroy = function(destroyChildren) {
  46003. this.clear();
  46004. Phaser.Component.Destroy.prototype.destroy.call(this, destroyChildren);
  46005. };
  46006. /*
  46007. * Draws a single {Phaser.Polygon} triangle from a {Phaser.Point} array
  46008. *
  46009. * @method Phaser.Graphics.prototype.drawTriangle
  46010. * @param {Array<Phaser.Point>} points - An array of Phaser.Points that make up the three vertices of this triangle
  46011. * @param {boolean} [cull=false] - Should we check if the triangle is back-facing
  46012. */
  46013. Phaser.Graphics.prototype.drawTriangle = function(points, cull) {
  46014. if (cull === undefined) { cull = false; }
  46015. var triangle = new Phaser.Polygon(points);
  46016. if (cull)
  46017. {
  46018. var cameraToFace = new Phaser.Point(this.game.camera.x - points[0].x, this.game.camera.y - points[0].y);
  46019. var ab = new Phaser.Point(points[1].x - points[0].x, points[1].y - points[0].y);
  46020. var cb = new Phaser.Point(points[1].x - points[2].x, points[1].y - points[2].y);
  46021. var faceNormal = cb.cross(ab);
  46022. if (cameraToFace.dot(faceNormal) > 0)
  46023. {
  46024. this.drawPolygon(triangle);
  46025. }
  46026. }
  46027. else
  46028. {
  46029. this.drawPolygon(triangle);
  46030. }
  46031. };
  46032. /*
  46033. * Draws {Phaser.Polygon} triangles
  46034. *
  46035. * @method Phaser.Graphics.prototype.drawTriangles
  46036. * @param {Array<Phaser.Point>|Array<number>} vertices - An array of Phaser.Points or numbers that make up the vertices of the triangles
  46037. * @param {Array<number>} {indices=null} - An array of numbers that describe what order to draw the vertices in
  46038. * @param {boolean} [cull=false] - Should we check if the triangle is back-facing
  46039. */
  46040. Phaser.Graphics.prototype.drawTriangles = function(vertices, indices, cull) {
  46041. if (cull === undefined) { cull = false; }
  46042. var point1 = new Phaser.Point();
  46043. var point2 = new Phaser.Point();
  46044. var point3 = new Phaser.Point();
  46045. var points = [];
  46046. var i;
  46047. if (!indices)
  46048. {
  46049. if (vertices[0] instanceof Phaser.Point)
  46050. {
  46051. for (i = 0; i < vertices.length / 3; i++)
  46052. {
  46053. this.drawTriangle([vertices[i * 3], vertices[i * 3 + 1], vertices[i * 3 + 2]], cull);
  46054. }
  46055. }
  46056. else
  46057. {
  46058. for (i = 0; i < vertices.length / 6; i++)
  46059. {
  46060. point1.x = vertices[i * 6 + 0];
  46061. point1.y = vertices[i * 6 + 1];
  46062. point2.x = vertices[i * 6 + 2];
  46063. point2.y = vertices[i * 6 + 3];
  46064. point3.x = vertices[i * 6 + 4];
  46065. point3.y = vertices[i * 6 + 5];
  46066. this.drawTriangle([point1, point2, point3], cull);
  46067. }
  46068. }
  46069. }
  46070. else
  46071. {
  46072. if (vertices[0] instanceof Phaser.Point)
  46073. {
  46074. for (i = 0; i < indices.length /3; i++)
  46075. {
  46076. points.push(vertices[indices[i * 3 ]]);
  46077. points.push(vertices[indices[i * 3 + 1]]);
  46078. points.push(vertices[indices[i * 3 + 2]]);
  46079. if (points.length === 3)
  46080. {
  46081. this.drawTriangle(points, cull);
  46082. points = [];
  46083. }
  46084. }
  46085. }
  46086. else
  46087. {
  46088. for (i = 0; i < indices.length; i++)
  46089. {
  46090. point1.x = vertices[indices[i] * 2];
  46091. point1.y = vertices[indices[i] * 2 + 1];
  46092. points.push(point1.copyTo({}));
  46093. if (points.length === 3)
  46094. {
  46095. this.drawTriangle(points, cull);
  46096. points = [];
  46097. }
  46098. }
  46099. }
  46100. }
  46101. };
  46102. /**
  46103. * @author Richard Davey <rich@photonstorm.com>
  46104. * @copyright 2016 Photon Storm Ltd.
  46105. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  46106. */
  46107. /**
  46108. * A RenderTexture is a special texture that allows any displayObject to be rendered to it. It allows you to take many complex objects and
  46109. * render them down into a single quad (on WebGL) which can then be used to texture other display objects with. A way of generating textures at run-time.
  46110. *
  46111. * @class Phaser.RenderTexture
  46112. * @constructor
  46113. * @extends PIXI.RenderTexture
  46114. * @param {Phaser.Game} game - Current game instance.
  46115. * @param {number} [width=100] - The width of the render texture.
  46116. * @param {number} [height=100] - The height of the render texture.
  46117. * @param {string} [key=''] - The key of the RenderTexture in the Cache, if stored there.
  46118. * @param {number} [scaleMode=Phaser.scaleModes.DEFAULT] - One of the Phaser.scaleModes consts.
  46119. * @param {number} [resolution=1] - The resolution of the texture being generated.
  46120. */
  46121. Phaser.RenderTexture = function (game, width, height, key, scaleMode, resolution) {
  46122. if (key === undefined) { key = ''; }
  46123. if (scaleMode === undefined) { scaleMode = Phaser.scaleModes.DEFAULT; }
  46124. if (resolution === undefined) { resolution = 1; }
  46125. /**
  46126. * @property {Phaser.Game} game - A reference to the currently running game.
  46127. */
  46128. this.game = game;
  46129. /**
  46130. * @property {string} key - The key of the RenderTexture in the Cache, if stored there.
  46131. */
  46132. this.key = key;
  46133. /**
  46134. * @property {number} type - Base Phaser object type.
  46135. */
  46136. this.type = Phaser.RENDERTEXTURE;
  46137. /**
  46138. * @property {PIXI.Matrix} _tempMatrix - The matrix that is applied when display objects are rendered to this RenderTexture.
  46139. * @private
  46140. */
  46141. this._tempMatrix = new PIXI.Matrix();
  46142. PIXI.RenderTexture.call(this, width, height, this.game.renderer, scaleMode, resolution);
  46143. this.render = Phaser.RenderTexture.prototype.render;
  46144. };
  46145. Phaser.RenderTexture.prototype = Object.create(PIXI.RenderTexture.prototype);
  46146. Phaser.RenderTexture.prototype.constructor = Phaser.RenderTexture;
  46147. /**
  46148. * This function will draw the display object to the RenderTexture at the given coordinates.
  46149. *
  46150. * When the display object is drawn it takes into account scale and rotation.
  46151. *
  46152. * If you don't want those then use RenderTexture.renderRawXY instead.
  46153. *
  46154. * @method Phaser.RenderTexture.prototype.renderXY
  46155. * @param {Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapText|Phaser.Group} displayObject - The display object to render to this texture.
  46156. * @param {number} x - The x position to render the object at.
  46157. * @param {number} y - The y position to render the object at.
  46158. * @param {boolean} [clear=false] - If true the texture will be cleared before the display object is drawn.
  46159. */
  46160. Phaser.RenderTexture.prototype.renderXY = function (displayObject, x, y, clear) {
  46161. displayObject.updateTransform();
  46162. this._tempMatrix.copyFrom(displayObject.worldTransform);
  46163. this._tempMatrix.tx = x;
  46164. this._tempMatrix.ty = y;
  46165. if (this.renderer.type === PIXI.WEBGL_RENDERER)
  46166. {
  46167. this.renderWebGL(displayObject, this._tempMatrix, clear);
  46168. }
  46169. else
  46170. {
  46171. this.renderCanvas(displayObject, this._tempMatrix, clear);
  46172. }
  46173. };
  46174. /**
  46175. * This function will draw the display object to the RenderTexture at the given coordinates.
  46176. *
  46177. * When the display object is drawn it doesn't take into account scale, rotation or translation.
  46178. *
  46179. * If you need those then use RenderTexture.renderXY instead.
  46180. *
  46181. * @method Phaser.RenderTexture.prototype.renderRawXY
  46182. * @param {Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapText|Phaser.Group} displayObject - The display object to render to this texture.
  46183. * @param {number} x - The x position to render the object at.
  46184. * @param {number} y - The y position to render the object at.
  46185. * @param {boolean} [clear=false] - If true the texture will be cleared before the display object is drawn.
  46186. */
  46187. Phaser.RenderTexture.prototype.renderRawXY = function (displayObject, x, y, clear) {
  46188. this._tempMatrix.identity().translate(x, y);
  46189. if (this.renderer.type === PIXI.WEBGL_RENDERER)
  46190. {
  46191. this.renderWebGL(displayObject, this._tempMatrix, clear);
  46192. }
  46193. else
  46194. {
  46195. this.renderCanvas(displayObject, this._tempMatrix, clear);
  46196. }
  46197. };
  46198. /**
  46199. * This function will draw the display object to the RenderTexture.
  46200. *
  46201. * In versions of Phaser prior to 2.4.0 the second parameter was a Phaser.Point object.
  46202. * This is now a Matrix allowing you much more control over how the Display Object is rendered.
  46203. * If you need to replicate the earlier behavior please use Phaser.RenderTexture.renderXY instead.
  46204. *
  46205. * If you wish for the displayObject to be rendered taking its current scale, rotation and translation into account then either
  46206. * pass `null`, leave it undefined or pass `displayObject.worldTransform` as the matrix value.
  46207. *
  46208. * @method Phaser.RenderTexture.prototype.render
  46209. * @param {Phaser.Sprite|Phaser.Image|Phaser.Text|Phaser.BitmapText|Phaser.Group} displayObject - The display object to render to this texture.
  46210. * @param {Phaser.Matrix} [matrix] - Optional matrix to apply to the display object before rendering. If null or undefined it will use the worldTransform matrix of the given display object.
  46211. * @param {boolean} [clear=false] - If true the texture will be cleared before the display object is drawn.
  46212. */
  46213. Phaser.RenderTexture.prototype.render = function (displayObject, matrix, clear) {
  46214. if (matrix === undefined || matrix === null)
  46215. {
  46216. this._tempMatrix.copyFrom(displayObject.worldTransform);
  46217. }
  46218. else
  46219. {
  46220. this._tempMatrix.copyFrom(matrix);
  46221. }
  46222. if (this.renderer.type === PIXI.WEBGL_RENDERER)
  46223. {
  46224. this.renderWebGL(displayObject, this._tempMatrix, clear);
  46225. }
  46226. else
  46227. {
  46228. this.renderCanvas(displayObject, this._tempMatrix, clear);
  46229. }
  46230. };
  46231. /**
  46232. * @author Richard Davey <rich@photonstorm.com>
  46233. * @copyright 2016 Photon Storm Ltd.
  46234. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  46235. */
  46236. /**
  46237. * Create a new game object for displaying Text.
  46238. *
  46239. * This uses a local hidden Canvas object and renders the type into it. It then makes a texture from this for rendering to the view.
  46240. * Because of this you can only display fonts that are currently loaded and available to the browser: fonts must be pre-loaded.
  46241. *
  46242. * See {@link http://www.jordanm.co.uk/tinytype this compatibility table} for the available default fonts across mobile browsers.
  46243. *
  46244. * @class Phaser.Text
  46245. * @extends Phaser.Sprite
  46246. * @constructor
  46247. * @param {Phaser.Game} game - Current game instance.
  46248. * @param {number} x - X position of the new text object.
  46249. * @param {number} y - Y position of the new text object.
  46250. * @param {string} text - The actual text that will be written.
  46251. * @param {object} [style] - The style properties to be set on the Text.
  46252. * @param {string} [style.font='bold 20pt Arial'] - The style and size of the font.
  46253. * @param {string} [style.fontStyle=(from font)] - The style of the font (eg. 'italic'): overrides the value in `style.font`.
  46254. * @param {string} [style.fontVariant=(from font)] - The variant of the font (eg. 'small-caps'): overrides the value in `style.font`.
  46255. * @param {string} [style.fontWeight=(from font)] - The weight of the font (eg. 'bold'): overrides the value in `style.font`.
  46256. * @param {string|number} [style.fontSize=(from font)] - The size of the font (eg. 32 or '32px'): overrides the value in `style.font`.
  46257. * @param {string} [style.backgroundColor=null] - A canvas fillstyle that will be used as the background for the whole Text object. Set to `null` to disable.
  46258. * @param {string} [style.fill='black'] - A canvas fillstyle that will be used on the text eg 'red', '#00FF00'.
  46259. * @param {string} [style.align='left'] - Horizontal alignment of each line in multiline text. Can be: 'left', 'center' or 'right'. Does not affect single lines of text (see `textBounds` and `boundsAlignH` for that).
  46260. * @param {string} [style.boundsAlignH='left'] - Horizontal alignment of the text within the `textBounds`. Can be: 'left', 'center' or 'right'.
  46261. * @param {string} [style.boundsAlignV='top'] - Vertical alignment of the text within the `textBounds`. Can be: 'top', 'middle' or 'bottom'.
  46262. * @param {string} [style.stroke='black'] - A canvas stroke style that will be used on the text stroke eg 'blue', '#FCFF00'.
  46263. * @param {number} [style.strokeThickness=0] - A number that represents the thickness of the stroke. Default is 0 (no stroke).
  46264. * @param {boolean} [style.wordWrap=false] - Indicates if word wrap should be used.
  46265. * @param {number} [style.wordWrapWidth=100] - The width in pixels at which text will wrap.
  46266. * @param {number} [style.maxLines=0] - The maximum number of lines to be shown for wrapped text.
  46267. * @param {number} [style.tabs=0] - The size (in pixels) of the tabs, for when text includes tab characters. 0 disables. Can be an array of varying tab sizes, one per tab stop.
  46268. */
  46269. Phaser.Text = function (game, x, y, text, style) {
  46270. x = x || 0;
  46271. y = y || 0;
  46272. if (text === undefined || text === null)
  46273. {
  46274. text = '';
  46275. }
  46276. else
  46277. {
  46278. text = text.toString();
  46279. }
  46280. style = Phaser.Utils.extend({}, style);
  46281. /**
  46282. * @property {number} type - The const type of this object.
  46283. * @default
  46284. */
  46285. this.type = Phaser.TEXT;
  46286. /**
  46287. * @property {number} physicsType - The const physics body type of this object.
  46288. * @readonly
  46289. */
  46290. this.physicsType = Phaser.SPRITE;
  46291. /**
  46292. * Specify a padding value which is added to the line width and height when calculating the Text size.
  46293. * ALlows you to add extra spacing if Phaser is unable to accurately determine the true font dimensions.
  46294. * @property {Phaser.Point} padding
  46295. */
  46296. this.padding = new Phaser.Point();
  46297. /**
  46298. * The textBounds property allows you to specify a rectangular region upon which text alignment is based.
  46299. * See `Text.setTextBounds` for more details.
  46300. * @property {Phaser.Rectangle} textBounds
  46301. * @readOnly
  46302. */
  46303. this.textBounds = null;
  46304. /**
  46305. * @property {HTMLCanvasElement} canvas - The canvas element that the text is rendered.
  46306. */
  46307. this.canvas = PIXI.CanvasPool.create(this);
  46308. /**
  46309. * @property {HTMLCanvasElement} context - The context of the canvas element that the text is rendered to.
  46310. */
  46311. this.context = this.canvas.getContext('2d');
  46312. /**
  46313. * @property {array} colors - An array of the color values as specified by {@link Phaser.Text#addColor addColor}.
  46314. */
  46315. this.colors = [];
  46316. /**
  46317. * @property {array} strokeColors - An array of the stroke color values as specified by {@link Phaser.Text#addStrokeColor addStrokeColor}.
  46318. */
  46319. this.strokeColors = [];
  46320. /**
  46321. * @property {array} fontStyles - An array of the font styles values as specified by {@link Phaser.Text#addFontStyle addFontStyle}.
  46322. */
  46323. this.fontStyles = [];
  46324. /**
  46325. * @property {array} fontWeights - An array of the font weights values as specified by {@link Phaser.Text#addFontWeight addFontWeight}.
  46326. */
  46327. this.fontWeights = [];
  46328. /**
  46329. * Should the linePositionX and Y values be automatically rounded before rendering the Text?
  46330. * You may wish to enable this if you want to remove the effect of sub-pixel aliasing from text.
  46331. * @property {boolean} autoRound
  46332. * @default
  46333. */
  46334. this.autoRound = false;
  46335. /**
  46336. * Will this Text object use Basic or Advanced Word Wrapping?
  46337. *
  46338. * Advanced wrapping breaks long words if they are the first of a line, and repeats the process as necessary.
  46339. * White space is condensed (e.g., consecutive spaces are replaced with one).
  46340. * Lines are trimmed of white space before processing.
  46341. *
  46342. * It throws an error if wordWrapWidth is less than a single character.
  46343. * @property {boolean} useAdvancedWrap
  46344. * @default
  46345. */
  46346. this.useAdvancedWrap = false;
  46347. /**
  46348. * @property {number} _res - Internal canvas resolution var.
  46349. * @private
  46350. */
  46351. this._res = game.renderer.resolution;
  46352. /**
  46353. * @property {string} _text - Internal cache var.
  46354. * @private
  46355. */
  46356. this._text = text;
  46357. /**
  46358. * @property {object} _fontComponents - The font, broken down into components, set in `setStyle`.
  46359. * @private
  46360. */
  46361. this._fontComponents = null;
  46362. /**
  46363. * @property {number} lineSpacing - Additional spacing (in pixels) between each line of text if multi-line.
  46364. * @private
  46365. */
  46366. this._lineSpacing = 0;
  46367. /**
  46368. * @property {number} _charCount - Internal character counter used by the text coloring.
  46369. * @private
  46370. */
  46371. this._charCount = 0;
  46372. /**
  46373. * @property {number} _width - Internal width var.
  46374. * @private
  46375. */
  46376. this._width = 0;
  46377. /**
  46378. * @property {number} _height - Internal height var.
  46379. * @private
  46380. */
  46381. this._height = 0;
  46382. Phaser.Sprite.call(this, game, x, y, PIXI.Texture.fromCanvas(this.canvas));
  46383. this.setStyle(style);
  46384. if (text !== '')
  46385. {
  46386. this.updateText();
  46387. }
  46388. };
  46389. Phaser.Text.prototype = Object.create(Phaser.Sprite.prototype);
  46390. Phaser.Text.prototype.constructor = Phaser.Text;
  46391. /**
  46392. * Automatically called by World.preUpdate.
  46393. *
  46394. * @method Phaser.Text#preUpdate
  46395. * @protected
  46396. */
  46397. Phaser.Text.prototype.preUpdate = function () {
  46398. if (!this.preUpdatePhysics() || !this.preUpdateLifeSpan() || !this.preUpdateInWorld())
  46399. {
  46400. return false;
  46401. }
  46402. return this.preUpdateCore();
  46403. };
  46404. /**
  46405. * Override this function to handle any special update requirements.
  46406. *
  46407. * @method Phaser.Text#update
  46408. * @protected
  46409. */
  46410. Phaser.Text.prototype.update = function() {
  46411. };
  46412. /**
  46413. * Destroy this Text object, removing it from the group it belongs to.
  46414. *
  46415. * @method Phaser.Text#destroy
  46416. * @param {boolean} [destroyChildren=true] - Should every child of this object have its destroy method called?
  46417. */
  46418. Phaser.Text.prototype.destroy = function (destroyChildren) {
  46419. this.texture.destroy(true);
  46420. Phaser.Component.Destroy.prototype.destroy.call(this, destroyChildren);
  46421. };
  46422. /**
  46423. * Sets a drop shadow effect on the Text. You can specify the horizontal and vertical distance of the drop shadow with the `x` and `y` parameters.
  46424. * The color controls the shade of the shadow (default is black) and can be either an `rgba` or `hex` value.
  46425. * The blur is the strength of the shadow. A value of zero means a hard shadow, a value of 10 means a very soft shadow.
  46426. * To remove a shadow already in place you can call this method with no parameters set.
  46427. *
  46428. * @method Phaser.Text#setShadow
  46429. * @param {number} [x=0] - The shadowOffsetX value in pixels. This is how far offset horizontally the shadow effect will be.
  46430. * @param {number} [y=0] - The shadowOffsetY value in pixels. This is how far offset vertically the shadow effect will be.
  46431. * @param {string} [color='rgba(0,0,0,1)'] - The color of the shadow, as given in CSS rgba or hex format. Set the alpha component to 0 to disable the shadow.
  46432. * @param {number} [blur=0] - The shadowBlur value. Make the shadow softer by applying a Gaussian blur to it. A number from 0 (no blur) up to approx. 10 (depending on scene).
  46433. * @param {boolean} [shadowStroke=true] - Apply the drop shadow to the Text stroke (if set).
  46434. * @param {boolean} [shadowFill=true] - Apply the drop shadow to the Text fill (if set).
  46435. * @return {Phaser.Text} This Text instance.
  46436. */
  46437. Phaser.Text.prototype.setShadow = function (x, y, color, blur, shadowStroke, shadowFill) {
  46438. if (x === undefined) { x = 0; }
  46439. if (y === undefined) { y = 0; }
  46440. if (color === undefined) { color = 'rgba(0, 0, 0, 1)'; }
  46441. if (blur === undefined) { blur = 0; }
  46442. if (shadowStroke === undefined) { shadowStroke = true; }
  46443. if (shadowFill === undefined) { shadowFill = true; }
  46444. this.style.shadowOffsetX = x;
  46445. this.style.shadowOffsetY = y;
  46446. this.style.shadowColor = color;
  46447. this.style.shadowBlur = blur;
  46448. this.style.shadowStroke = shadowStroke;
  46449. this.style.shadowFill = shadowFill;
  46450. this.dirty = true;
  46451. return this;
  46452. };
  46453. /**
  46454. * Set the style of the text by passing a single style object to it.
  46455. *
  46456. * @method Phaser.Text#setStyle
  46457. * @param {object} [style] - The style properties to be set on the Text.
  46458. * @param {string} [style.font='bold 20pt Arial'] - The style and size of the font.
  46459. * @param {string} [style.fontStyle=(from font)] - The style of the font (eg. 'italic'): overrides the value in `style.font`.
  46460. * @param {string} [style.fontVariant=(from font)] - The variant of the font (eg. 'small-caps'): overrides the value in `style.font`.
  46461. * @param {string} [style.fontWeight=(from font)] - The weight of the font (eg. 'bold'): overrides the value in `style.font`.
  46462. * @param {string|number} [style.fontSize=(from font)] - The size of the font (eg. 32 or '32px'): overrides the value in `style.font`.
  46463. * @param {string} [style.backgroundColor=null] - A canvas fillstyle that will be used as the background for the whole Text object. Set to `null` to disable.
  46464. * @param {string} [style.fill='black'] - A canvas fillstyle that will be used on the text eg 'red', '#00FF00'.
  46465. * @param {string} [style.align='left'] - Horizontal alignment of each line in multiline text. Can be: 'left', 'center' or 'right'. Does not affect single lines of text (see `textBounds` and `boundsAlignH` for that).
  46466. * @param {string} [style.boundsAlignH='left'] - Horizontal alignment of the text within the `textBounds`. Can be: 'left', 'center' or 'right'.
  46467. * @param {string} [style.boundsAlignV='top'] - Vertical alignment of the text within the `textBounds`. Can be: 'top', 'middle' or 'bottom'.
  46468. * @param {string} [style.stroke='black'] - A canvas stroke style that will be used on the text stroke eg 'blue', '#FCFF00'.
  46469. * @param {number} [style.strokeThickness=0] - A number that represents the thickness of the stroke. Default is 0 (no stroke).
  46470. * @param {boolean} [style.wordWrap=false] - Indicates if word wrap should be used.
  46471. * @param {number} [style.wordWrapWidth=100] - The width in pixels at which text will wrap.
  46472. * @param {number} [style.maxLines=0] - The maximum number of lines to be shown for wrapped text.
  46473. * @param {number|array} [style.tabs=0] - The size (in pixels) of the tabs, for when text includes tab characters. 0 disables. Can be an array of varying tab sizes, one per tab stop.
  46474. * @param {boolean} [update=false] - Immediately update the Text object after setting the new style? Or wait for the next frame.
  46475. * @return {Phaser.Text} This Text instance.
  46476. */
  46477. Phaser.Text.prototype.setStyle = function (style, update) {
  46478. if (update === undefined) { update = false; }
  46479. style = style || {};
  46480. style.font = style.font || 'bold 20pt Arial';
  46481. style.backgroundColor = style.backgroundColor || null;
  46482. style.fill = style.fill || 'black';
  46483. style.align = style.align || 'left';
  46484. style.boundsAlignH = style.boundsAlignH || 'left';
  46485. style.boundsAlignV = style.boundsAlignV || 'top';
  46486. style.stroke = style.stroke || 'black'; //provide a default, see: https://github.com/GoodBoyDigital/pixi.js/issues/136
  46487. style.strokeThickness = style.strokeThickness || 0;
  46488. style.wordWrap = style.wordWrap || false;
  46489. style.wordWrapWidth = style.wordWrapWidth || 100;
  46490. style.maxLines = style.maxLines || 0;
  46491. style.shadowOffsetX = style.shadowOffsetX || 0;
  46492. style.shadowOffsetY = style.shadowOffsetY || 0;
  46493. style.shadowColor = style.shadowColor || 'rgba(0,0,0,0)';
  46494. style.shadowBlur = style.shadowBlur || 0;
  46495. style.tabs = style.tabs || 0;
  46496. var components = this.fontToComponents(style.font);
  46497. if (style.fontStyle)
  46498. {
  46499. components.fontStyle = style.fontStyle;
  46500. }
  46501. if (style.fontVariant)
  46502. {
  46503. components.fontVariant = style.fontVariant;
  46504. }
  46505. if (style.fontWeight)
  46506. {
  46507. components.fontWeight = style.fontWeight;
  46508. }
  46509. if (style.fontSize)
  46510. {
  46511. if (typeof style.fontSize === 'number')
  46512. {
  46513. style.fontSize = style.fontSize + 'px';
  46514. }
  46515. components.fontSize = style.fontSize;
  46516. }
  46517. this._fontComponents = components;
  46518. style.font = this.componentsToFont(this._fontComponents);
  46519. this.style = style;
  46520. this.dirty = true;
  46521. if (update)
  46522. {
  46523. this.updateText();
  46524. }
  46525. return this;
  46526. };
  46527. /**
  46528. * Renders text. This replaces the Pixi.Text.updateText function as we need a few extra bits in here.
  46529. *
  46530. * @method Phaser.Text#updateText
  46531. * @private
  46532. */
  46533. Phaser.Text.prototype.updateText = function () {
  46534. this.texture.baseTexture.resolution = this._res;
  46535. this.context.font = this.style.font;
  46536. var outputText = this.text;
  46537. if (this.style.wordWrap)
  46538. {
  46539. outputText = this.runWordWrap(this.text);
  46540. }
  46541. // Split text into lines
  46542. var lines = outputText.split(/(?:\r\n|\r|\n)/);
  46543. // Calculate text width
  46544. var tabs = this.style.tabs;
  46545. var lineWidths = [];
  46546. var maxLineWidth = 0;
  46547. var fontProperties = this.determineFontProperties(this.style.font);
  46548. var drawnLines = lines.length;
  46549. if (this.style.maxLines > 0 && this.style.maxLines < lines.length)
  46550. {
  46551. drawnLines = this.style.maxLines;
  46552. }
  46553. this._charCount = 0;
  46554. for (var i = 0; i < drawnLines; i++)
  46555. {
  46556. if (tabs === 0)
  46557. {
  46558. // Simple layout (no tabs)
  46559. var lineWidth = this.style.strokeThickness + this.padding.x;
  46560. if (this.colors.length > 0 || this.strokeColors.length > 0 || this.fontWeights.length > 0 || this.fontStyles.length > 0)
  46561. {
  46562. lineWidth += this.measureLine(lines[i]);
  46563. }
  46564. else
  46565. {
  46566. lineWidth += this.context.measureText(lines[i]).width;
  46567. }
  46568. // Adjust for wrapped text
  46569. if (this.style.wordWrap)
  46570. {
  46571. lineWidth -= this.context.measureText(' ').width;
  46572. }
  46573. }
  46574. else
  46575. {
  46576. // Complex layout (tabs)
  46577. var line = lines[i].split(/(?:\t)/);
  46578. var lineWidth = this.padding.x + this.style.strokeThickness;
  46579. if (Array.isArray(tabs))
  46580. {
  46581. var tab = 0;
  46582. for (var c = 0; c < line.length; c++)
  46583. {
  46584. var section = 0;
  46585. if (this.colors.length > 0 || this.strokeColors.length > 0 || this.fontWeights.length > 0 || this.fontStyles.length > 0)
  46586. {
  46587. section = this.measureLine(line[c]);
  46588. }
  46589. else
  46590. {
  46591. section = Math.ceil(this.context.measureText(line[c]).width);
  46592. }
  46593. if (c > 0)
  46594. {
  46595. tab += tabs[c - 1];
  46596. }
  46597. lineWidth = tab + section;
  46598. }
  46599. }
  46600. else
  46601. {
  46602. for (var c = 0; c < line.length; c++)
  46603. {
  46604. // How far to the next tab?
  46605. if (this.colors.length > 0 || this.strokeColors.length > 0 || this.fontWeights.length > 0 || this.fontStyles.length > 0)
  46606. {
  46607. lineWidth += this.measureLine(line[c]);
  46608. }
  46609. else
  46610. {
  46611. lineWidth += Math.ceil(this.context.measureText(line[c]).width);
  46612. }
  46613. var diff = this.game.math.snapToCeil(lineWidth, tabs) - lineWidth;
  46614. lineWidth += diff;
  46615. }
  46616. }
  46617. }
  46618. lineWidths[i] = Math.ceil(lineWidth);
  46619. maxLineWidth = Math.max(maxLineWidth, lineWidths[i]);
  46620. }
  46621. this.canvas.width = maxLineWidth * this._res;
  46622. // Calculate text height
  46623. var lineHeight = fontProperties.fontSize + this.style.strokeThickness + this.padding.y;
  46624. var height = lineHeight * drawnLines;
  46625. var lineSpacing = this._lineSpacing;
  46626. if (lineSpacing < 0 && Math.abs(lineSpacing) > lineHeight)
  46627. {
  46628. lineSpacing = -lineHeight;
  46629. }
  46630. // Adjust for line spacing
  46631. if (lineSpacing !== 0)
  46632. {
  46633. height += (lineSpacing > 0) ? lineSpacing * lines.length : lineSpacing * (lines.length - 1);
  46634. }
  46635. this.canvas.height = height * this._res;
  46636. this.context.scale(this._res, this._res);
  46637. if (navigator.isCocoonJS)
  46638. {
  46639. this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
  46640. }
  46641. if (this.style.backgroundColor)
  46642. {
  46643. this.context.fillStyle = this.style.backgroundColor;
  46644. this.context.fillRect(0, 0, this.canvas.width, this.canvas.height);
  46645. }
  46646. this.context.fillStyle = this.style.fill;
  46647. this.context.font = this.style.font;
  46648. this.context.strokeStyle = this.style.stroke;
  46649. this.context.textBaseline = 'alphabetic';
  46650. this.context.lineWidth = this.style.strokeThickness;
  46651. this.context.lineCap = 'round';
  46652. this.context.lineJoin = 'round';
  46653. var linePositionX;
  46654. var linePositionY;
  46655. this._charCount = 0;
  46656. // Draw text line by line
  46657. for (i = 0; i < drawnLines; i++)
  46658. {
  46659. // Split the line by
  46660. linePositionX = this.style.strokeThickness / 2;
  46661. linePositionY = (this.style.strokeThickness / 2 + i * lineHeight) + fontProperties.ascent;
  46662. if (i > 0)
  46663. {
  46664. linePositionY += (lineSpacing * i);
  46665. }
  46666. if (this.style.align === 'right')
  46667. {
  46668. linePositionX += maxLineWidth - lineWidths[i];
  46669. }
  46670. else if (this.style.align === 'center')
  46671. {
  46672. linePositionX += (maxLineWidth - lineWidths[i]) / 2;
  46673. }
  46674. if (this.autoRound)
  46675. {
  46676. linePositionX = Math.round(linePositionX);
  46677. linePositionY = Math.round(linePositionY);
  46678. }
  46679. if (this.colors.length > 0 || this.strokeColors.length > 0 || this.fontWeights.length > 0 || this.fontStyles.length > 0)
  46680. {
  46681. this.updateLine(lines[i], linePositionX, linePositionY);
  46682. }
  46683. else
  46684. {
  46685. if (this.style.stroke && this.style.strokeThickness)
  46686. {
  46687. this.updateShadow(this.style.shadowStroke);
  46688. if (tabs === 0)
  46689. {
  46690. this.context.strokeText(lines[i], linePositionX, linePositionY);
  46691. }
  46692. else
  46693. {
  46694. this.renderTabLine(lines[i], linePositionX, linePositionY, false);
  46695. }
  46696. }
  46697. if (this.style.fill)
  46698. {
  46699. this.updateShadow(this.style.shadowFill);
  46700. if (tabs === 0)
  46701. {
  46702. this.context.fillText(lines[i], linePositionX, linePositionY);
  46703. }
  46704. else
  46705. {
  46706. this.renderTabLine(lines[i], linePositionX, linePositionY, true);
  46707. }
  46708. }
  46709. }
  46710. }
  46711. this.updateTexture();
  46712. this.dirty = false;
  46713. };
  46714. /**
  46715. * Renders a line of text that contains tab characters if Text.tab > 0.
  46716. * Called automatically by updateText.
  46717. *
  46718. * @method Phaser.Text#renderTabLine
  46719. * @private
  46720. * @param {string} line - The line of text to render.
  46721. * @param {integer} x - The x position to start rendering from.
  46722. * @param {integer} y - The y position to start rendering from.
  46723. * @param {boolean} fill - If true uses fillText, if false uses strokeText.
  46724. */
  46725. Phaser.Text.prototype.renderTabLine = function (line, x, y, fill) {
  46726. var text = line.split(/(?:\t)/);
  46727. var tabs = this.style.tabs;
  46728. var snap = 0;
  46729. if (Array.isArray(tabs))
  46730. {
  46731. var tab = 0;
  46732. for (var c = 0; c < text.length; c++)
  46733. {
  46734. if (c > 0)
  46735. {
  46736. tab += tabs[c - 1];
  46737. }
  46738. snap = x + tab;
  46739. if (fill)
  46740. {
  46741. this.context.fillText(text[c], snap, y);
  46742. }
  46743. else
  46744. {
  46745. this.context.strokeText(text[c], snap, y);
  46746. }
  46747. }
  46748. }
  46749. else
  46750. {
  46751. for (var c = 0; c < text.length; c++)
  46752. {
  46753. var section = Math.ceil(this.context.measureText(text[c]).width);
  46754. // How far to the next tab?
  46755. snap = this.game.math.snapToCeil(x, tabs);
  46756. if (fill)
  46757. {
  46758. this.context.fillText(text[c], snap, y);
  46759. }
  46760. else
  46761. {
  46762. this.context.strokeText(text[c], snap, y);
  46763. }
  46764. x = snap + section;
  46765. }
  46766. }
  46767. };
  46768. /**
  46769. * Sets the Shadow on the Text.context based on the Style settings, or disables it if not enabled.
  46770. * This is called automatically by Text.updateText.
  46771. *
  46772. * @method Phaser.Text#updateShadow
  46773. * @param {boolean} state - If true the shadow will be set to the Style values, otherwise it will be set to zero.
  46774. */
  46775. Phaser.Text.prototype.updateShadow = function (state) {
  46776. if (state)
  46777. {
  46778. this.context.shadowOffsetX = this.style.shadowOffsetX;
  46779. this.context.shadowOffsetY = this.style.shadowOffsetY;
  46780. this.context.shadowColor = this.style.shadowColor;
  46781. this.context.shadowBlur = this.style.shadowBlur;
  46782. }
  46783. else
  46784. {
  46785. this.context.shadowOffsetX = 0;
  46786. this.context.shadowOffsetY = 0;
  46787. this.context.shadowColor = 0;
  46788. this.context.shadowBlur = 0;
  46789. }
  46790. };
  46791. /**
  46792. * Measures a line of text character by character taking into the account the specified character styles.
  46793. *
  46794. * @method Phaser.Text#measureLine
  46795. * @private
  46796. * @param {string} line - The line of text to measure.
  46797. * @return {integer} length of the line.
  46798. */
  46799. Phaser.Text.prototype.measureLine = function (line) {
  46800. var lineLength = 0;
  46801. for (var i = 0; i < line.length; i++)
  46802. {
  46803. var letter = line[i];
  46804. if (this.fontWeights.length > 0 || this.fontStyles.length > 0)
  46805. {
  46806. var components = this.fontToComponents(this.context.font);
  46807. if (this.fontStyles[this._charCount])
  46808. {
  46809. components.fontStyle = this.fontStyles[this._charCount];
  46810. }
  46811. if (this.fontWeights[this._charCount])
  46812. {
  46813. components.fontWeight = this.fontWeights[this._charCount];
  46814. }
  46815. this.context.font = this.componentsToFont(components);
  46816. }
  46817. if (this.style.stroke && this.style.strokeThickness)
  46818. {
  46819. if (this.strokeColors[this._charCount])
  46820. {
  46821. this.context.strokeStyle = this.strokeColors[this._charCount];
  46822. }
  46823. this.updateShadow(this.style.shadowStroke);
  46824. }
  46825. if (this.style.fill)
  46826. {
  46827. if (this.colors[this._charCount])
  46828. {
  46829. this.context.fillStyle = this.colors[this._charCount];
  46830. }
  46831. this.updateShadow(this.style.shadowFill);
  46832. }
  46833. lineLength += this.context.measureText(letter).width;
  46834. this._charCount++;
  46835. }
  46836. return Math.ceil(lineLength);
  46837. };
  46838. /**
  46839. * Updates a line of text, applying fill and stroke per-character colors or style and weight per-character font if applicable.
  46840. *
  46841. * @method Phaser.Text#updateLine
  46842. * @private
  46843. */
  46844. Phaser.Text.prototype.updateLine = function (line, x, y) {
  46845. for (var i = 0; i < line.length; i++)
  46846. {
  46847. var letter = line[i];
  46848. if (this.fontWeights.length > 0 || this.fontStyles.length > 0)
  46849. {
  46850. var components = this.fontToComponents(this.context.font);
  46851. if (this.fontStyles[this._charCount])
  46852. {
  46853. components.fontStyle = this.fontStyles[this._charCount];
  46854. }
  46855. if (this.fontWeights[this._charCount])
  46856. {
  46857. components.fontWeight = this.fontWeights[this._charCount];
  46858. }
  46859. this.context.font = this.componentsToFont(components);
  46860. }
  46861. if (this.style.stroke && this.style.strokeThickness)
  46862. {
  46863. if (this.strokeColors[this._charCount])
  46864. {
  46865. this.context.strokeStyle = this.strokeColors[this._charCount];
  46866. }
  46867. this.updateShadow(this.style.shadowStroke);
  46868. this.context.strokeText(letter, x, y);
  46869. }
  46870. if (this.style.fill)
  46871. {
  46872. if (this.colors[this._charCount])
  46873. {
  46874. this.context.fillStyle = this.colors[this._charCount];
  46875. }
  46876. this.updateShadow(this.style.shadowFill);
  46877. this.context.fillText(letter, x, y);
  46878. }
  46879. x += this.context.measureText(letter).width;
  46880. this._charCount++;
  46881. }
  46882. };
  46883. /**
  46884. * Clears any text fill or stroke colors that were set by `addColor` or `addStrokeColor`.
  46885. *
  46886. * @method Phaser.Text#clearColors
  46887. * @return {Phaser.Text} This Text instance.
  46888. */
  46889. Phaser.Text.prototype.clearColors = function () {
  46890. this.colors = [];
  46891. this.strokeColors = [];
  46892. this.dirty = true;
  46893. return this;
  46894. };
  46895. /**
  46896. * Clears any text styles or weights font that were set by `addFontStyle` or `addFontWeight`.
  46897. *
  46898. * @method Phaser.Text#clearFontValues
  46899. * @return {Phaser.Text} This Text instance.
  46900. */
  46901. Phaser.Text.prototype.clearFontValues = function () {
  46902. this.fontStyles = [];
  46903. this.fontWeights = [];
  46904. this.dirty = true;
  46905. return this;
  46906. };
  46907. /**
  46908. * Set specific colors for certain characters within the Text.
  46909. *
  46910. * It works by taking a color value, which is a typical HTML string such as `#ff0000` or `rgb(255,0,0)` and a position.
  46911. * The position value is the index of the character in the Text string to start applying this color to.
  46912. * Once set the color remains in use until either another color or the end of the string is encountered.
  46913. * For example if the Text was `Photon Storm` and you did `Text.addColor('#ffff00', 6)` it would color in the word `Storm` in yellow.
  46914. *
  46915. * If you wish to change the stroke color see addStrokeColor instead.
  46916. *
  46917. * @method Phaser.Text#addColor
  46918. * @param {string} color - A canvas fillstyle that will be used on the text eg `red`, `#00FF00`, `rgba()`.
  46919. * @param {number} position - The index of the character in the string to start applying this color value from.
  46920. * @return {Phaser.Text} This Text instance.
  46921. */
  46922. Phaser.Text.prototype.addColor = function (color, position) {
  46923. this.colors[position] = color;
  46924. this.dirty = true;
  46925. return this;
  46926. };
  46927. /**
  46928. * Set specific stroke colors for certain characters within the Text.
  46929. *
  46930. * It works by taking a color value, which is a typical HTML string such as `#ff0000` or `rgb(255,0,0)` and a position.
  46931. * The position value is the index of the character in the Text string to start applying this color to.
  46932. * Once set the color remains in use until either another color or the end of the string is encountered.
  46933. * For example if the Text was `Photon Storm` and you did `Text.addColor('#ffff00', 6)` it would color in the word `Storm` in yellow.
  46934. *
  46935. * This has no effect if stroke is disabled or has a thickness of 0.
  46936. *
  46937. * If you wish to change the text fill color see addColor instead.
  46938. *
  46939. * @method Phaser.Text#addStrokeColor
  46940. * @param {string} color - A canvas fillstyle that will be used on the text stroke eg `red`, `#00FF00`, `rgba()`.
  46941. * @param {number} position - The index of the character in the string to start applying this color value from.
  46942. * @return {Phaser.Text} This Text instance.
  46943. */
  46944. Phaser.Text.prototype.addStrokeColor = function (color, position) {
  46945. this.strokeColors[position] = color;
  46946. this.dirty = true;
  46947. return this;
  46948. };
  46949. /**
  46950. * Set specific font styles for certain characters within the Text.
  46951. *
  46952. * It works by taking a font style value, which is a typical string such as `normal`, `italic` or `oblique`.
  46953. * The position value is the index of the character in the Text string to start applying this font style to.
  46954. * Once set the font style remains in use until either another font style or the end of the string is encountered.
  46955. * For example if the Text was `Photon Storm` and you did `Text.addFontStyle('italic', 6)` it would font style in the word `Storm` in italic.
  46956. *
  46957. * If you wish to change the text font weight see addFontWeight instead.
  46958. *
  46959. * @method Phaser.Text#addFontStyle
  46960. * @param {string} style - A canvas font-style that will be used on the text style eg `normal`, `italic`, `oblique`.
  46961. * @param {number} position - The index of the character in the string to start applying this font style value from.
  46962. * @return {Phaser.Text} This Text instance.
  46963. */
  46964. Phaser.Text.prototype.addFontStyle = function (style, position) {
  46965. this.fontStyles[position] = style;
  46966. this.dirty = true;
  46967. return this;
  46968. };
  46969. /**
  46970. * Set specific font weights for certain characters within the Text.
  46971. *
  46972. * It works by taking a font weight value, which is a typical string such as `normal`, `bold`, `bolder`, etc.
  46973. * The position value is the index of the character in the Text string to start applying this font weight to.
  46974. * Once set the font weight remains in use until either another font weight or the end of the string is encountered.
  46975. * For example if the Text was `Photon Storm` and you did `Text.addFontWeight('bold', 6)` it would font weight in the word `Storm` in bold.
  46976. *
  46977. * If you wish to change the text font style see addFontStyle instead.
  46978. *
  46979. * @method Phaser.Text#addFontWeight
  46980. * @param {string} style - A canvas font-weight that will be used on the text weight eg `normal`, `bold`, `bolder`, `lighter`, etc.
  46981. * @param {number} position - The index of the character in the string to start applying this font weight value from.
  46982. * @return {Phaser.Text} This Text instance.
  46983. */
  46984. Phaser.Text.prototype.addFontWeight = function (weight, position) {
  46985. this.fontWeights[position] = weight;
  46986. this.dirty = true;
  46987. return this;
  46988. };
  46989. /**
  46990. * Runs the given text through the Text.runWordWrap function and returns
  46991. * the results as an array, where each element of the array corresponds to a wrapped
  46992. * line of text.
  46993. *
  46994. * Useful if you wish to control pagination on long pieces of content.
  46995. *
  46996. * @method Phaser.Text#precalculateWordWrap
  46997. * @param {string} text - The text for which the wrapping will be calculated.
  46998. * @return {array} An array of strings with the pieces of wrapped text.
  46999. */
  47000. Phaser.Text.prototype.precalculateWordWrap = function (text) {
  47001. this.texture.baseTexture.resolution = this._res;
  47002. this.context.font = this.style.font;
  47003. var wrappedLines = this.runWordWrap(text);
  47004. return wrappedLines.split(/(?:\r\n|\r|\n)/);
  47005. };
  47006. /**
  47007. * Greedy wrapping algorithm that will wrap words as the line grows longer than its horizontal bounds.
  47008. *
  47009. * @method Phaser.Text#runWordWrap
  47010. * @param {string} text - The text to perform word wrap detection against.
  47011. * @private
  47012. */
  47013. Phaser.Text.prototype.runWordWrap = function (text) {
  47014. if (this.useAdvancedWrap)
  47015. {
  47016. return this.advancedWordWrap(text);
  47017. }
  47018. else
  47019. {
  47020. return this.basicWordWrap(text);
  47021. }
  47022. };
  47023. /**
  47024. * Advanced wrapping algorithm that will wrap words as the line grows longer than its horizontal bounds.
  47025. * White space is condensed (e.g., consecutive spaces are replaced with one).
  47026. * Lines are trimmed of white space before processing.
  47027. * Throws an error if the user was smart enough to specify a wordWrapWidth less than a single character.
  47028. *
  47029. * @method Phaser.Text#advancedWordWrap
  47030. * @param {string} text - The text to perform word wrap detection against.
  47031. * @private
  47032. */
  47033. Phaser.Text.prototype.advancedWordWrap = function (text) {
  47034. var context = this.context;
  47035. var wordWrapWidth = this.style.wordWrapWidth;
  47036. var output = '';
  47037. // (1) condense whitespace
  47038. // (2) split into lines
  47039. var lines = text
  47040. .replace(/ +/gi, ' ')
  47041. .split(/\r?\n/gi);
  47042. var linesCount = lines.length;
  47043. for (var i = 0; i < linesCount; i++)
  47044. {
  47045. var line = lines[i];
  47046. var out = '';
  47047. // trim whitespace
  47048. line = line.replace(/^ *|\s*$/gi, '');
  47049. // if entire line is less than wordWrapWidth
  47050. // append the entire line and exit early
  47051. var lineWidth = context.measureText(line).width;
  47052. if (lineWidth < wordWrapWidth)
  47053. {
  47054. output += line + '\n';
  47055. continue;
  47056. }
  47057. // otherwise, calculate new lines
  47058. var currentLineWidth = wordWrapWidth;
  47059. // split into words
  47060. var words = line.split(' ');
  47061. for (var j = 0; j < words.length; j++)
  47062. {
  47063. var word = words[j];
  47064. var wordWithSpace = word + ' ';
  47065. var wordWidth = context.measureText(wordWithSpace).width;
  47066. if (wordWidth > currentLineWidth)
  47067. {
  47068. // break word
  47069. if (j === 0)
  47070. {
  47071. // shave off letters from word until it's small enough
  47072. var newWord = wordWithSpace;
  47073. while (newWord.length)
  47074. {
  47075. newWord = newWord.slice(0, -1);
  47076. wordWidth = context.measureText(newWord).width;
  47077. if (wordWidth <= currentLineWidth)
  47078. {
  47079. break;
  47080. }
  47081. }
  47082. // if wordWrapWidth is too small for even a single
  47083. // letter, shame user failure with a fatal error
  47084. if (!newWord.length)
  47085. {
  47086. throw new Error('This text\'s wordWrapWidth setting is less than a single character!');
  47087. }
  47088. // replace current word in array with remainder
  47089. var secondPart = word.substr(newWord.length);
  47090. words[j] = secondPart;
  47091. // append first piece to output
  47092. out += newWord;
  47093. }
  47094. // if existing word length is 0, don't include it
  47095. var offset = (words[j].length) ? j : j + 1;
  47096. // collapse rest of sentence
  47097. var remainder = words.slice(offset).join(' ')
  47098. // remove any trailing white space
  47099. .replace(/[ \n]*$/gi, '');
  47100. // prepend remainder to next line
  47101. lines[i + 1] = remainder + ' ' + (lines[i + 1] || '');
  47102. linesCount = lines.length;
  47103. break; // processing on this line
  47104. // append word with space to output
  47105. }
  47106. else
  47107. {
  47108. out += wordWithSpace;
  47109. currentLineWidth -= wordWidth;
  47110. }
  47111. }
  47112. // append processed line to output
  47113. output += out.replace(/[ \n]*$/gi, '') + '\n';
  47114. }
  47115. // trim the end of the string
  47116. output = output.replace(/[\s|\n]*$/gi, '');
  47117. return output;
  47118. };
  47119. /**
  47120. * Greedy wrapping algorithm that will wrap words as the line grows longer than its horizontal bounds.
  47121. *
  47122. * @method Phaser.Text#basicWordWrap
  47123. * @param {string} text - The text to perform word wrap detection against.
  47124. * @private
  47125. */
  47126. Phaser.Text.prototype.basicWordWrap = function (text) {
  47127. var result = '';
  47128. var lines = text.split('\n');
  47129. for (var i = 0; i < lines.length; i++)
  47130. {
  47131. var spaceLeft = this.style.wordWrapWidth;
  47132. var words = lines[i].split(' ');
  47133. for (var j = 0; j < words.length; j++)
  47134. {
  47135. var wordWidth = this.context.measureText(words[j]).width;
  47136. var wordWidthWithSpace = wordWidth + this.context.measureText(' ').width;
  47137. if (wordWidthWithSpace > spaceLeft)
  47138. {
  47139. // Skip printing the newline if it's the first word of the line that is greater than the word wrap width.
  47140. if (j > 0)
  47141. {
  47142. result += '\n';
  47143. }
  47144. result += words[j] + ' ';
  47145. spaceLeft = this.style.wordWrapWidth - wordWidth;
  47146. }
  47147. else
  47148. {
  47149. spaceLeft -= wordWidthWithSpace;
  47150. result += words[j] + ' ';
  47151. }
  47152. }
  47153. if (i < lines.length-1)
  47154. {
  47155. result += '\n';
  47156. }
  47157. }
  47158. return result;
  47159. };
  47160. /**
  47161. * Updates the internal `style.font` if it now differs according to generation from components.
  47162. *
  47163. * @method Phaser.Text#updateFont
  47164. * @private
  47165. * @param {object} components - Font components.
  47166. */
  47167. Phaser.Text.prototype.updateFont = function (components) {
  47168. var font = this.componentsToFont(components);
  47169. if (this.style.font !== font)
  47170. {
  47171. this.style.font = font;
  47172. this.dirty = true;
  47173. if (this.parent)
  47174. {
  47175. this.updateTransform();
  47176. }
  47177. }
  47178. };
  47179. /**
  47180. * Converting a short CSS-font string into the relevant components.
  47181. *
  47182. * @method Phaser.Text#fontToComponents
  47183. * @private
  47184. * @param {string} font - a CSS font string
  47185. */
  47186. Phaser.Text.prototype.fontToComponents = function (font) {
  47187. // The format is specified in http://www.w3.org/TR/CSS2/fonts.html#font-shorthand:
  47188. // style - normal | italic | oblique | inherit
  47189. // variant - normal | small-caps | inherit
  47190. // weight - normal | bold | bolder | lighter | 100 | 200 | 300 | 400 | 500 | 600 | 700 | 800 | 900 | inherit
  47191. // size - xx-small | x-small | small | medium | large | x-large | xx-large,
  47192. // larger | smaller
  47193. // {number} (em | ex | ch | rem | vh | vw | vmin | vmax | px | mm | cm | in | pt | pc | %)
  47194. // font-family - rest (but identifiers or quoted with comma separation)
  47195. var m = font.match(/^\s*(?:\b(normal|italic|oblique|inherit)?\b)\s*(?:\b(normal|small-caps|inherit)?\b)\s*(?:\b(normal|bold|bolder|lighter|100|200|300|400|500|600|700|800|900|inherit)?\b)\s*(?:\b(xx-small|x-small|small|medium|large|x-large|xx-large|larger|smaller|0|\d*(?:[.]\d*)?(?:%|[a-z]{2,5}))?\b)\s*(.*)\s*$/);
  47196. if (m)
  47197. {
  47198. var family = m[5].trim();
  47199. // If it looks like the value should be quoted, but isn't, then quote it.
  47200. if (!/^(?:inherit|serif|sans-serif|cursive|fantasy|monospace)$/.exec(family) && !/['",]/.exec(family))
  47201. {
  47202. family = "'" + family + "'";
  47203. }
  47204. return {
  47205. font: font,
  47206. fontStyle: m[1] || 'normal',
  47207. fontVariant: m[2] || 'normal',
  47208. fontWeight: m[3] || 'normal',
  47209. fontSize: m[4] || 'medium',
  47210. fontFamily: family
  47211. };
  47212. }
  47213. else
  47214. {
  47215. console.warn("Phaser.Text - unparsable CSS font: " + font);
  47216. return {
  47217. font: font
  47218. };
  47219. }
  47220. };
  47221. /**
  47222. * Converts individual font components (see `fontToComponents`) to a short CSS font string.
  47223. *
  47224. * @method Phaser.Text#componentsToFont
  47225. * @private
  47226. * @param {object} components - Font components.
  47227. */
  47228. Phaser.Text.prototype.componentsToFont = function (components) {
  47229. var parts = [];
  47230. var v;
  47231. v = components.fontStyle;
  47232. if (v && v !== 'normal') { parts.push(v); }
  47233. v = components.fontVariant;
  47234. if (v && v !== 'normal') { parts.push(v); }
  47235. v = components.fontWeight;
  47236. if (v && v !== 'normal') { parts.push(v); }
  47237. v = components.fontSize;
  47238. if (v && v !== 'medium') { parts.push(v); }
  47239. v = components.fontFamily;
  47240. if (v) { parts.push(v); }
  47241. if (!parts.length)
  47242. {
  47243. // Fallback to whatever value the 'font' was
  47244. parts.push(components.font);
  47245. }
  47246. return parts.join(" ");
  47247. };
  47248. /**
  47249. * The text to be displayed by this Text object.
  47250. * Use a \n to insert a carriage return and split the text.
  47251. * The text will be rendered with any style currently set.
  47252. *
  47253. * Use the optional `immediate` argument if you need the Text display to update immediately.
  47254. *
  47255. * If not it will re-create the texture of this Text object during the next time the render
  47256. * loop is called.
  47257. *
  47258. * @method Phaser.Text#setText
  47259. * @param {string} [text] - The text to be displayed. Set to an empty string to clear text that is already present.
  47260. * @param {boolean} [immediate=false] - Update the texture used by this Text object immediately (true) or automatically during the next render loop (false).
  47261. * @return {Phaser.Text} This Text instance.
  47262. */
  47263. Phaser.Text.prototype.setText = function (text, immediate) {
  47264. if (immediate === undefined) { immediate = false; }
  47265. this.text = text.toString() || '';
  47266. if (immediate)
  47267. {
  47268. this.updateText();
  47269. }
  47270. else
  47271. {
  47272. this.dirty = true;
  47273. }
  47274. return this;
  47275. };
  47276. /**
  47277. * Converts the given array into a tab delimited string and then updates this Text object.
  47278. * This is mostly used when you want to display external data using tab stops.
  47279. *
  47280. * The array can be either single or multi dimensional depending on the result you need:
  47281. *
  47282. * `[ 'a', 'b', 'c' ]` would convert in to `"a\tb\tc"`.
  47283. *
  47284. * Where as:
  47285. *
  47286. * `[
  47287. * [ 'a', 'b', 'c' ],
  47288. * [ 'd', 'e', 'f']
  47289. * ]`
  47290. *
  47291. * would convert in to: `"a\tb\tc\nd\te\tf"`
  47292. *
  47293. * @method Phaser.Text#parseList
  47294. * @param {array} list - The array of data to convert into a string.
  47295. * @return {Phaser.Text} This Text instance.
  47296. */
  47297. Phaser.Text.prototype.parseList = function (list) {
  47298. if (!Array.isArray(list))
  47299. {
  47300. return this;
  47301. }
  47302. else
  47303. {
  47304. var s = "";
  47305. for (var i = 0; i < list.length; i++)
  47306. {
  47307. if (Array.isArray(list[i]))
  47308. {
  47309. s += list[i].join("\t");
  47310. if (i < list.length - 1)
  47311. {
  47312. s += "\n";
  47313. }
  47314. }
  47315. else
  47316. {
  47317. s += list[i];
  47318. if (i < list.length - 1)
  47319. {
  47320. s += "\t";
  47321. }
  47322. }
  47323. }
  47324. }
  47325. this.text = s;
  47326. this.dirty = true;
  47327. return this;
  47328. };
  47329. /**
  47330. * The Text Bounds is a rectangular region that you control the dimensions of into which the Text object itself is positioned,
  47331. * regardless of the number of lines in the text, the font size or any other attribute.
  47332. *
  47333. * Alignment is controlled via the properties `boundsAlignH` and `boundsAlignV` within the Text.style object, or can be directly
  47334. * set through the setters `Text.boundsAlignH` and `Text.boundsAlignV`. Bounds alignment is independent of text alignment.
  47335. *
  47336. * For example: If your game is 800x600 in size and you set the text bounds to be 0,0,800,600 then by setting boundsAlignH to
  47337. * 'center' and boundsAlignV to 'bottom' the text will render in the center and at the bottom of your game window, regardless of
  47338. * how many lines of text there may be. Even if you adjust the text content or change the style it will remain at the bottom center
  47339. * of the text bounds.
  47340. *
  47341. * This is especially powerful when you need to align text against specific coordinates in your game, but the actual text dimensions
  47342. * may vary based on font (say for multi-lingual games).
  47343. *
  47344. * If `Text.wordWrapWidth` is greater than the width of the text bounds it is clamped to match the bounds width.
  47345. *
  47346. * Call this method with no arguments given to reset an existing textBounds.
  47347. *
  47348. * It works by calculating the final position based on the Text.canvas size, which is modified as the text is updated. Some fonts
  47349. * have additional padding around them which you can mitigate by tweaking the Text.padding property. It then adjusts the `pivot`
  47350. * property based on the given bounds and canvas size. This means if you need to set the pivot property directly in your game then
  47351. * you either cannot use `setTextBounds` or you must place the Text object inside another DisplayObject on which you set the pivot.
  47352. *
  47353. * @method Phaser.Text#setTextBounds
  47354. * @param {number} [x] - The x coordinate of the Text Bounds region.
  47355. * @param {number} [y] - The y coordinate of the Text Bounds region.
  47356. * @param {number} [width] - The width of the Text Bounds region.
  47357. * @param {number} [height] - The height of the Text Bounds region.
  47358. * @return {Phaser.Text} This Text instance.
  47359. */
  47360. Phaser.Text.prototype.setTextBounds = function (x, y, width, height) {
  47361. if (x === undefined)
  47362. {
  47363. this.textBounds = null;
  47364. }
  47365. else
  47366. {
  47367. if (!this.textBounds)
  47368. {
  47369. this.textBounds = new Phaser.Rectangle(x, y, width, height);
  47370. }
  47371. else
  47372. {
  47373. this.textBounds.setTo(x, y, width, height);
  47374. }
  47375. if (this.style.wordWrapWidth > width)
  47376. {
  47377. this.style.wordWrapWidth = width;
  47378. }
  47379. }
  47380. this.updateTexture();
  47381. return this;
  47382. };
  47383. /**
  47384. * Updates the texture based on the canvas dimensions.
  47385. *
  47386. * @method Phaser.Text#updateTexture
  47387. * @private
  47388. */
  47389. Phaser.Text.prototype.updateTexture = function () {
  47390. var base = this.texture.baseTexture;
  47391. var crop = this.texture.crop;
  47392. var frame = this.texture.frame;
  47393. var w = this.canvas.width;
  47394. var h = this.canvas.height;
  47395. base.width = w;
  47396. base.height = h;
  47397. crop.width = w;
  47398. crop.height = h;
  47399. frame.width = w;
  47400. frame.height = h;
  47401. this.texture.width = w;
  47402. this.texture.height = h;
  47403. this._width = w;
  47404. this._height = h;
  47405. if (this.textBounds)
  47406. {
  47407. var x = this.textBounds.x;
  47408. var y = this.textBounds.y;
  47409. // Align the canvas based on the bounds
  47410. if (this.style.boundsAlignH === 'right')
  47411. {
  47412. x += this.textBounds.width - this.canvas.width / this.resolution;
  47413. }
  47414. else if (this.style.boundsAlignH === 'center')
  47415. {
  47416. x += this.textBounds.halfWidth - (this.canvas.width / this.resolution / 2);
  47417. }
  47418. if (this.style.boundsAlignV === 'bottom')
  47419. {
  47420. y += this.textBounds.height - this.canvas.height / this.resolution;
  47421. }
  47422. else if (this.style.boundsAlignV === 'middle')
  47423. {
  47424. y += this.textBounds.halfHeight - (this.canvas.height / this.resolution / 2);
  47425. }
  47426. this.pivot.x = -x;
  47427. this.pivot.y = -y;
  47428. }
  47429. // Can't render something with a zero sized dimension
  47430. this.renderable = (w !== 0 && h !== 0);
  47431. this.texture.requiresReTint = true;
  47432. this.texture.baseTexture.dirty();
  47433. };
  47434. /**
  47435. * Renders the object using the WebGL renderer
  47436. *
  47437. * @method Phaser.Text#_renderWebGL
  47438. * @private
  47439. * @param {RenderSession} renderSession - The Render Session to render the Text on.
  47440. */
  47441. Phaser.Text.prototype._renderWebGL = function (renderSession) {
  47442. if (this.dirty)
  47443. {
  47444. this.updateText();
  47445. this.dirty = false;
  47446. }
  47447. PIXI.Sprite.prototype._renderWebGL.call(this, renderSession);
  47448. };
  47449. /**
  47450. * Renders the object using the Canvas renderer.
  47451. *
  47452. * @method Phaser.Text#_renderCanvas
  47453. * @private
  47454. * @param {RenderSession} renderSession - The Render Session to render the Text on.
  47455. */
  47456. Phaser.Text.prototype._renderCanvas = function (renderSession) {
  47457. if (this.dirty)
  47458. {
  47459. this.updateText();
  47460. this.dirty = false;
  47461. }
  47462. PIXI.Sprite.prototype._renderCanvas.call(this, renderSession);
  47463. };
  47464. /**
  47465. * Calculates the ascent, descent and fontSize of a given font style.
  47466. *
  47467. * @method Phaser.Text#determineFontProperties
  47468. * @private
  47469. * @param {object} fontStyle
  47470. */
  47471. Phaser.Text.prototype.determineFontProperties = function (fontStyle) {
  47472. var properties = Phaser.Text.fontPropertiesCache[fontStyle];
  47473. if (!properties)
  47474. {
  47475. properties = {};
  47476. var canvas = Phaser.Text.fontPropertiesCanvas;
  47477. var context = Phaser.Text.fontPropertiesContext;
  47478. context.font = fontStyle;
  47479. var width = Math.ceil(context.measureText('|MÉq').width);
  47480. var baseline = Math.ceil(context.measureText('|MÉq').width);
  47481. var height = 2 * baseline;
  47482. baseline = baseline * 1.4 | 0;
  47483. canvas.width = width;
  47484. canvas.height = height;
  47485. context.fillStyle = '#f00';
  47486. context.fillRect(0, 0, width, height);
  47487. context.font = fontStyle;
  47488. context.textBaseline = 'alphabetic';
  47489. context.fillStyle = '#000';
  47490. context.fillText('|MÉq', 0, baseline);
  47491. if (!context.getImageData(0, 0, width, height))
  47492. {
  47493. properties.ascent = baseline;
  47494. properties.descent = baseline + 6;
  47495. properties.fontSize = properties.ascent + properties.descent;
  47496. Phaser.Text.fontPropertiesCache[fontStyle] = properties;
  47497. return properties;
  47498. }
  47499. var imagedata = context.getImageData(0, 0, width, height).data;
  47500. var pixels = imagedata.length;
  47501. var line = width * 4;
  47502. var i, j;
  47503. var idx = 0;
  47504. var stop = false;
  47505. // ascent. scan from top to bottom until we find a non red pixel
  47506. for (i = 0; i < baseline; i++)
  47507. {
  47508. for (j = 0; j < line; j += 4)
  47509. {
  47510. if (imagedata[idx + j] !== 255)
  47511. {
  47512. stop = true;
  47513. break;
  47514. }
  47515. }
  47516. if (!stop)
  47517. {
  47518. idx += line;
  47519. }
  47520. else
  47521. {
  47522. break;
  47523. }
  47524. }
  47525. properties.ascent = baseline - i;
  47526. idx = pixels - line;
  47527. stop = false;
  47528. // descent. scan from bottom to top until we find a non red pixel
  47529. for (i = height; i > baseline; i--)
  47530. {
  47531. for (j = 0; j < line; j += 4)
  47532. {
  47533. if (imagedata[idx + j] !== 255)
  47534. {
  47535. stop = true;
  47536. break;
  47537. }
  47538. }
  47539. if (!stop)
  47540. {
  47541. idx -= line;
  47542. }
  47543. else
  47544. {
  47545. break;
  47546. }
  47547. }
  47548. properties.descent = i - baseline;
  47549. //TODO might need a tweak. kind of a temp fix!
  47550. properties.descent += 6;
  47551. properties.fontSize = properties.ascent + properties.descent;
  47552. Phaser.Text.fontPropertiesCache[fontStyle] = properties;
  47553. }
  47554. return properties;
  47555. };
  47556. /**
  47557. * Returns the bounds of the Text as a rectangle.
  47558. * The bounds calculation takes the worldTransform into account.
  47559. *
  47560. * @method Phaser.Text#getBounds
  47561. * @param {Phaser.Matrix} matrix - The transformation matrix of the Text.
  47562. * @return {Phaser.Rectangle} The framing rectangle
  47563. */
  47564. Phaser.Text.prototype.getBounds = function (matrix) {
  47565. if (this.dirty)
  47566. {
  47567. this.updateText();
  47568. this.dirty = false;
  47569. }
  47570. return PIXI.Sprite.prototype.getBounds.call(this, matrix);
  47571. };
  47572. /**
  47573. * The text to be displayed by this Text object.
  47574. * Use a \n to insert a carriage return and split the text.
  47575. * The text will be rendered with any style currently set.
  47576. *
  47577. * @name Phaser.Text#text
  47578. * @property {string} text
  47579. */
  47580. Object.defineProperty(Phaser.Text.prototype, 'text', {
  47581. get: function() {
  47582. return this._text;
  47583. },
  47584. set: function(value) {
  47585. if (value !== this._text)
  47586. {
  47587. this._text = value.toString() || '';
  47588. this.dirty = true;
  47589. if (this.parent)
  47590. {
  47591. this.updateTransform();
  47592. }
  47593. }
  47594. }
  47595. });
  47596. /**
  47597. * Change the font used.
  47598. *
  47599. * This is equivalent of the `font` property specified to {@link Phaser.Text#setStyle setStyle}, except
  47600. * that unlike using `setStyle` this will not change any current font fill/color settings.
  47601. *
  47602. * The CSS font string can also be individually altered with the `font`, `fontSize`, `fontWeight`, `fontStyle`, and `fontVariant` properties.
  47603. *
  47604. * @name Phaser.Text#cssFont
  47605. * @property {string} cssFont
  47606. */
  47607. Object.defineProperty(Phaser.Text.prototype, 'cssFont', {
  47608. get: function() {
  47609. return this.componentsToFont(this._fontComponents);
  47610. },
  47611. set: function (value)
  47612. {
  47613. value = value || 'bold 20pt Arial';
  47614. this._fontComponents = this.fontToComponents(value);
  47615. this.updateFont(this._fontComponents);
  47616. }
  47617. });
  47618. /**
  47619. * Change the font family that the text will be rendered in, such as 'Arial'.
  47620. *
  47621. * Multiple CSS font families and generic fallbacks can be specified as long as
  47622. * {@link http://www.w3.org/TR/CSS2/fonts.html#propdef-font-family CSS font-family rules} are followed.
  47623. *
  47624. * To change the entire font string use {@link Phaser.Text#cssFont cssFont} instead: eg. `text.cssFont = 'bold 20pt Arial'`.
  47625. *
  47626. * @name Phaser.Text#font
  47627. * @property {string} font
  47628. */
  47629. Object.defineProperty(Phaser.Text.prototype, 'font', {
  47630. get: function() {
  47631. return this._fontComponents.fontFamily;
  47632. },
  47633. set: function(value) {
  47634. value = value || 'Arial';
  47635. value = value.trim();
  47636. // If it looks like the value should be quoted, but isn't, then quote it.
  47637. if (!/^(?:inherit|serif|sans-serif|cursive|fantasy|monospace)$/.exec(value) && !/['",]/.exec(value))
  47638. {
  47639. value = "'" + value + "'";
  47640. }
  47641. this._fontComponents.fontFamily = value;
  47642. this.updateFont(this._fontComponents);
  47643. }
  47644. });
  47645. /**
  47646. * The size of the font.
  47647. *
  47648. * If the font size is specified in pixels (eg. `32` or `'32px`') then a number (ie. `32`) representing
  47649. * the font size in pixels is returned; otherwise the value with CSS unit is returned as a string (eg. `'12pt'`).
  47650. *
  47651. * @name Phaser.Text#fontSize
  47652. * @property {number|string} fontSize
  47653. */
  47654. Object.defineProperty(Phaser.Text.prototype, 'fontSize', {
  47655. get: function() {
  47656. var size = this._fontComponents.fontSize;
  47657. if (size && /(?:^0$|px$)/.exec(size))
  47658. {
  47659. return parseInt(size, 10);
  47660. }
  47661. else
  47662. {
  47663. return size;
  47664. }
  47665. },
  47666. set: function(value) {
  47667. value = value || '0';
  47668. if (typeof value === 'number')
  47669. {
  47670. value = value + 'px';
  47671. }
  47672. this._fontComponents.fontSize = value;
  47673. this.updateFont(this._fontComponents);
  47674. }
  47675. });
  47676. /**
  47677. * The weight of the font: 'normal', 'bold', or {@link http://www.w3.org/TR/CSS2/fonts.html#propdef-font-weight a valid CSS font weight}.
  47678. * @name Phaser.Text#fontWeight
  47679. * @property {string} fontWeight
  47680. */
  47681. Object.defineProperty(Phaser.Text.prototype, 'fontWeight', {
  47682. get: function() {
  47683. return this._fontComponents.fontWeight || 'normal';
  47684. },
  47685. set: function(value) {
  47686. value = value || 'normal';
  47687. this._fontComponents.fontWeight = value;
  47688. this.updateFont(this._fontComponents);
  47689. }
  47690. });
  47691. /**
  47692. * The style of the font: 'normal', 'italic', 'oblique'
  47693. * @name Phaser.Text#fontStyle
  47694. * @property {string} fontStyle
  47695. */
  47696. Object.defineProperty(Phaser.Text.prototype, 'fontStyle', {
  47697. get: function() {
  47698. return this._fontComponents.fontStyle || 'normal';
  47699. },
  47700. set: function(value) {
  47701. value = value || 'normal';
  47702. this._fontComponents.fontStyle = value;
  47703. this.updateFont(this._fontComponents);
  47704. }
  47705. });
  47706. /**
  47707. * The variant the font: 'normal', 'small-caps'
  47708. * @name Phaser.Text#fontVariant
  47709. * @property {string} fontVariant
  47710. */
  47711. Object.defineProperty(Phaser.Text.prototype, 'fontVariant', {
  47712. get: function() {
  47713. return this._fontComponents.fontVariant || 'normal';
  47714. },
  47715. set: function(value) {
  47716. value = value || 'normal';
  47717. this._fontComponents.fontVariant = value;
  47718. this.updateFont(this._fontComponents);
  47719. }
  47720. });
  47721. /**
  47722. * @name Phaser.Text#fill
  47723. * @property {object} fill - A canvas fillstyle that will be used on the text eg 'red', '#00FF00'.
  47724. */
  47725. Object.defineProperty(Phaser.Text.prototype, 'fill', {
  47726. get: function() {
  47727. return this.style.fill;
  47728. },
  47729. set: function(value) {
  47730. if (value !== this.style.fill)
  47731. {
  47732. this.style.fill = value;
  47733. this.dirty = true;
  47734. }
  47735. }
  47736. });
  47737. /**
  47738. * Controls the horizontal alignment for multiline text.
  47739. * Can be: 'left', 'center' or 'right'.
  47740. * Does not affect single lines of text. For that please see `setTextBounds`.
  47741. * @name Phaser.Text#align
  47742. * @property {string} align
  47743. */
  47744. Object.defineProperty(Phaser.Text.prototype, 'align', {
  47745. get: function() {
  47746. return this.style.align;
  47747. },
  47748. set: function(value) {
  47749. if (value !== this.style.align)
  47750. {
  47751. this.style.align = value;
  47752. this.dirty = true;
  47753. }
  47754. }
  47755. });
  47756. /**
  47757. * The resolution of the canvas the text is rendered to.
  47758. * This defaults to match the resolution of the renderer, but can be changed on a per Text object basis.
  47759. * @name Phaser.Text#resolution
  47760. * @property {integer} resolution
  47761. */
  47762. Object.defineProperty(Phaser.Text.prototype, 'resolution', {
  47763. get: function() {
  47764. return this._res;
  47765. },
  47766. set: function(value) {
  47767. if (value !== this._res)
  47768. {
  47769. this._res = value;
  47770. this.dirty = true;
  47771. }
  47772. }
  47773. });
  47774. /**
  47775. * The size (in pixels) of the tabs, for when text includes tab characters. 0 disables.
  47776. * Can be an integer or an array of varying tab sizes, one tab per element.
  47777. * For example if you set tabs to 100 then when Text encounters a tab it will jump ahead 100 pixels.
  47778. * If you set tabs to be `[100,200]` then it will set the first tab at 100px and the second at 200px.
  47779. *
  47780. * @name Phaser.Text#tabs
  47781. * @property {integer|array} tabs
  47782. */
  47783. Object.defineProperty(Phaser.Text.prototype, 'tabs', {
  47784. get: function() {
  47785. return this.style.tabs;
  47786. },
  47787. set: function(value) {
  47788. if (value !== this.style.tabs)
  47789. {
  47790. this.style.tabs = value;
  47791. this.dirty = true;
  47792. }
  47793. }
  47794. });
  47795. /**
  47796. * Horizontal alignment of the text within the `textBounds`. Can be: 'left', 'center' or 'right'.
  47797. * @name Phaser.Text#boundsAlignH
  47798. * @property {string} boundsAlignH
  47799. */
  47800. Object.defineProperty(Phaser.Text.prototype, 'boundsAlignH', {
  47801. get: function() {
  47802. return this.style.boundsAlignH;
  47803. },
  47804. set: function(value) {
  47805. if (value !== this.style.boundsAlignH)
  47806. {
  47807. this.style.boundsAlignH = value;
  47808. this.dirty = true;
  47809. }
  47810. }
  47811. });
  47812. /**
  47813. * Vertical alignment of the text within the `textBounds`. Can be: 'top', 'middle' or 'bottom'.
  47814. * @name Phaser.Text#boundsAlignV
  47815. * @property {string} boundsAlignV
  47816. */
  47817. Object.defineProperty(Phaser.Text.prototype, 'boundsAlignV', {
  47818. get: function() {
  47819. return this.style.boundsAlignV;
  47820. },
  47821. set: function(value) {
  47822. if (value !== this.style.boundsAlignV)
  47823. {
  47824. this.style.boundsAlignV = value;
  47825. this.dirty = true;
  47826. }
  47827. }
  47828. });
  47829. /**
  47830. * @name Phaser.Text#stroke
  47831. * @property {string} stroke - A canvas fillstyle that will be used on the text stroke eg 'blue', '#FCFF00'.
  47832. */
  47833. Object.defineProperty(Phaser.Text.prototype, 'stroke', {
  47834. get: function() {
  47835. return this.style.stroke;
  47836. },
  47837. set: function(value) {
  47838. if (value !== this.style.stroke)
  47839. {
  47840. this.style.stroke = value;
  47841. this.dirty = true;
  47842. }
  47843. }
  47844. });
  47845. /**
  47846. * @name Phaser.Text#strokeThickness
  47847. * @property {number} strokeThickness - A number that represents the thickness of the stroke. Default is 0 (no stroke)
  47848. */
  47849. Object.defineProperty(Phaser.Text.prototype, 'strokeThickness', {
  47850. get: function() {
  47851. return this.style.strokeThickness;
  47852. },
  47853. set: function(value) {
  47854. if (value !== this.style.strokeThickness)
  47855. {
  47856. this.style.strokeThickness = value;
  47857. this.dirty = true;
  47858. }
  47859. }
  47860. });
  47861. /**
  47862. * @name Phaser.Text#wordWrap
  47863. * @property {boolean} wordWrap - Indicates if word wrap should be used.
  47864. */
  47865. Object.defineProperty(Phaser.Text.prototype, 'wordWrap', {
  47866. get: function() {
  47867. return this.style.wordWrap;
  47868. },
  47869. set: function(value) {
  47870. if (value !== this.style.wordWrap)
  47871. {
  47872. this.style.wordWrap = value;
  47873. this.dirty = true;
  47874. }
  47875. }
  47876. });
  47877. /**
  47878. * @name Phaser.Text#wordWrapWidth
  47879. * @property {number} wordWrapWidth - The width at which text will wrap.
  47880. */
  47881. Object.defineProperty(Phaser.Text.prototype, 'wordWrapWidth', {
  47882. get: function() {
  47883. return this.style.wordWrapWidth;
  47884. },
  47885. set: function(value) {
  47886. if (value !== this.style.wordWrapWidth)
  47887. {
  47888. this.style.wordWrapWidth = value;
  47889. this.dirty = true;
  47890. }
  47891. }
  47892. });
  47893. /**
  47894. * @name Phaser.Text#lineSpacing
  47895. * @property {number} lineSpacing - Additional spacing (in pixels) between each line of text if multi-line.
  47896. */
  47897. Object.defineProperty(Phaser.Text.prototype, 'lineSpacing', {
  47898. get: function() {
  47899. return this._lineSpacing;
  47900. },
  47901. set: function(value) {
  47902. if (value !== this._lineSpacing)
  47903. {
  47904. this._lineSpacing = parseFloat(value);
  47905. this.dirty = true;
  47906. if (this.parent)
  47907. {
  47908. this.updateTransform();
  47909. }
  47910. }
  47911. }
  47912. });
  47913. /**
  47914. * @name Phaser.Text#shadowOffsetX
  47915. * @property {number} shadowOffsetX - The shadowOffsetX value in pixels. This is how far offset horizontally the shadow effect will be.
  47916. */
  47917. Object.defineProperty(Phaser.Text.prototype, 'shadowOffsetX', {
  47918. get: function() {
  47919. return this.style.shadowOffsetX;
  47920. },
  47921. set: function(value) {
  47922. if (value !== this.style.shadowOffsetX)
  47923. {
  47924. this.style.shadowOffsetX = value;
  47925. this.dirty = true;
  47926. }
  47927. }
  47928. });
  47929. /**
  47930. * @name Phaser.Text#shadowOffsetY
  47931. * @property {number} shadowOffsetY - The shadowOffsetY value in pixels. This is how far offset vertically the shadow effect will be.
  47932. */
  47933. Object.defineProperty(Phaser.Text.prototype, 'shadowOffsetY', {
  47934. get: function() {
  47935. return this.style.shadowOffsetY;
  47936. },
  47937. set: function(value) {
  47938. if (value !== this.style.shadowOffsetY)
  47939. {
  47940. this.style.shadowOffsetY = value;
  47941. this.dirty = true;
  47942. }
  47943. }
  47944. });
  47945. /**
  47946. * @name Phaser.Text#shadowColor
  47947. * @property {string} shadowColor - The color of the shadow, as given in CSS rgba format. Set the alpha component to 0 to disable the shadow.
  47948. */
  47949. Object.defineProperty(Phaser.Text.prototype, 'shadowColor', {
  47950. get: function() {
  47951. return this.style.shadowColor;
  47952. },
  47953. set: function(value) {
  47954. if (value !== this.style.shadowColor)
  47955. {
  47956. this.style.shadowColor = value;
  47957. this.dirty = true;
  47958. }
  47959. }
  47960. });
  47961. /**
  47962. * @name Phaser.Text#shadowBlur
  47963. * @property {number} shadowBlur - The shadowBlur value. Make the shadow softer by applying a Gaussian blur to it. A number from 0 (no blur) up to approx. 10 (depending on scene).
  47964. */
  47965. Object.defineProperty(Phaser.Text.prototype, 'shadowBlur', {
  47966. get: function() {
  47967. return this.style.shadowBlur;
  47968. },
  47969. set: function(value) {
  47970. if (value !== this.style.shadowBlur)
  47971. {
  47972. this.style.shadowBlur = value;
  47973. this.dirty = true;
  47974. }
  47975. }
  47976. });
  47977. /**
  47978. * @name Phaser.Text#shadowStroke
  47979. * @property {boolean} shadowStroke - Sets if the drop shadow is applied to the Text stroke.
  47980. */
  47981. Object.defineProperty(Phaser.Text.prototype, 'shadowStroke', {
  47982. get: function() {
  47983. return this.style.shadowStroke;
  47984. },
  47985. set: function(value) {
  47986. if (value !== this.style.shadowStroke)
  47987. {
  47988. this.style.shadowStroke = value;
  47989. this.dirty = true;
  47990. }
  47991. }
  47992. });
  47993. /**
  47994. * @name Phaser.Text#shadowFill
  47995. * @property {boolean} shadowFill - Sets if the drop shadow is applied to the Text fill.
  47996. */
  47997. Object.defineProperty(Phaser.Text.prototype, 'shadowFill', {
  47998. get: function() {
  47999. return this.style.shadowFill;
  48000. },
  48001. set: function(value) {
  48002. if (value !== this.style.shadowFill)
  48003. {
  48004. this.style.shadowFill = value;
  48005. this.dirty = true;
  48006. }
  48007. }
  48008. });
  48009. /**
  48010. * @name Phaser.Text#width
  48011. * @property {number} width - The width of the Text. Setting this will modify the scale to achieve the value requested.
  48012. */
  48013. Object.defineProperty(Phaser.Text.prototype, 'width', {
  48014. get: function() {
  48015. if (this.dirty)
  48016. {
  48017. this.updateText();
  48018. this.dirty = false;
  48019. }
  48020. return this.scale.x * this.texture.frame.width;
  48021. },
  48022. set: function(value) {
  48023. this.scale.x = value / this.texture.frame.width;
  48024. this._width = value;
  48025. }
  48026. });
  48027. /**
  48028. * @name Phaser.Text#height
  48029. * @property {number} height - The height of the Text. Setting this will modify the scale to achieve the value requested.
  48030. */
  48031. Object.defineProperty(Phaser.Text.prototype, 'height', {
  48032. get: function() {
  48033. if (this.dirty)
  48034. {
  48035. this.updateText();
  48036. this.dirty = false;
  48037. }
  48038. return this.scale.y * this.texture.frame.height;
  48039. },
  48040. set: function(value) {
  48041. this.scale.y = value / this.texture.frame.height;
  48042. this._height = value;
  48043. }
  48044. });
  48045. Phaser.Text.fontPropertiesCache = {};
  48046. Phaser.Text.fontPropertiesCanvas = document.createElement('canvas');
  48047. Phaser.Text.fontPropertiesContext = Phaser.Text.fontPropertiesCanvas.getContext('2d');
  48048. /**
  48049. * @author Richard Davey <rich@photonstorm.com>
  48050. * @copyright 2016 Photon Storm Ltd.
  48051. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  48052. */
  48053. /**
  48054. * BitmapText objects work by taking a texture file and an XML or JSON file that describes the font structure.
  48055. * It then generates a new Sprite object for each letter of the text, proportionally spaced out and aligned to
  48056. * match the font structure.
  48057. *
  48058. * BitmapText objects are less flexible than Text objects, in that they have less features such as shadows, fills and the ability
  48059. * to use Web Fonts, however you trade this flexibility for rendering speed. You can also create visually compelling BitmapTexts by
  48060. * processing the font texture in an image editor, applying fills and any other effects required.
  48061. *
  48062. * To create multi-line text insert \r, \n or \r\n escape codes into the text string.
  48063. *
  48064. * If you are having performance issues due to the volume of sprites being rendered, and do not require the text to be constantly
  48065. * updating, you can use BitmapText.generateTexture to create a static texture from this BitmapText.
  48066. *
  48067. * To create a BitmapText data files you can use:
  48068. *
  48069. * BMFont (Windows, free): http://www.angelcode.com/products/bmfont/
  48070. * Glyph Designer (OS X, commercial): http://www.71squared.com/en/glyphdesigner
  48071. * Littera (Web-based, free): http://kvazars.com/littera/
  48072. *
  48073. * For most use cases it is recommended to use XML. If you wish to use JSON, the formatting should be equal to the result of
  48074. * converting a valid XML file through the popular X2JS library. An online tool for conversion can be found here: http://codebeautify.org/xmltojson
  48075. *
  48076. * If you were using an older version of Phaser (< 2.4) and using the DOMish parser hack, please remove this. It isn't required any longer.
  48077. *
  48078. * @class Phaser.BitmapText
  48079. * @constructor
  48080. * @extends PIXI.DisplayObjectContainer
  48081. * @extends Phaser.Component.Core
  48082. * @extends Phaser.Component.Angle
  48083. * @extends Phaser.Component.AutoCull
  48084. * @extends Phaser.Component.Bounds
  48085. * @extends Phaser.Component.Destroy
  48086. * @extends Phaser.Component.FixedToCamera
  48087. * @extends Phaser.Component.InputEnabled
  48088. * @extends Phaser.Component.InWorld
  48089. * @extends Phaser.Component.LifeSpan
  48090. * @extends Phaser.Component.PhysicsBody
  48091. * @extends Phaser.Component.Reset
  48092. * @param {Phaser.Game} game - A reference to the currently running game.
  48093. * @param {number} x - X coordinate to display the BitmapText object at.
  48094. * @param {number} y - Y coordinate to display the BitmapText object at.
  48095. * @param {string} font - The key of the BitmapText as stored in Phaser.Cache.
  48096. * @param {string} [text=''] - The text that will be rendered. This can also be set later via BitmapText.text.
  48097. * @param {number} [size=32] - The size the font will be rendered at in pixels.
  48098. * @param {string} [align='left'] - The alignment of multi-line text. Has no effect if there is only one line of text.
  48099. */
  48100. Phaser.BitmapText = function (game, x, y, font, text, size, align) {
  48101. x = x || 0;
  48102. y = y || 0;
  48103. font = font || '';
  48104. text = text || '';
  48105. size = size || 32;
  48106. align = align || 'left';
  48107. PIXI.DisplayObjectContainer.call(this);
  48108. /**
  48109. * @property {number} type - The const type of this object.
  48110. * @readonly
  48111. */
  48112. this.type = Phaser.BITMAPTEXT;
  48113. /**
  48114. * @property {number} physicsType - The const physics body type of this object.
  48115. * @readonly
  48116. */
  48117. this.physicsType = Phaser.SPRITE;
  48118. /**
  48119. * @property {number} textWidth - The width in pixels of the overall text area, taking into consideration multi-line text.
  48120. * @readOnly
  48121. */
  48122. this.textWidth = 0;
  48123. /**
  48124. * @property {number} textHeight - The height in pixels of the overall text area, taking into consideration multi-line text.
  48125. * @readOnly
  48126. */
  48127. this.textHeight = 0;
  48128. /**
  48129. * @property {Phaser.Point} anchor - The anchor value of this BitmapText.
  48130. */
  48131. this.anchor = new Phaser.Point();
  48132. /**
  48133. * @property {Phaser.Point} _prevAnchor - The previous anchor value.
  48134. * @private
  48135. */
  48136. this._prevAnchor = new Phaser.Point();
  48137. /**
  48138. * @property {array} _glyphs - Private tracker for the letter sprite pool.
  48139. * @private
  48140. */
  48141. this._glyphs = [];
  48142. /**
  48143. * @property {number} _maxWidth - Internal cache var.
  48144. * @private
  48145. */
  48146. this._maxWidth = 0;
  48147. /**
  48148. * @property {string} _text - Internal cache var.
  48149. * @private
  48150. */
  48151. this._text = text.toString() || '';
  48152. /**
  48153. * @property {string} _data - Internal cache var.
  48154. * @private
  48155. */
  48156. this._data = game.cache.getBitmapFont(font);
  48157. /**
  48158. * @property {string} _font - Internal cache var.
  48159. * @private
  48160. */
  48161. this._font = font;
  48162. /**
  48163. * @property {number} _fontSize - Internal cache var.
  48164. * @private
  48165. */
  48166. this._fontSize = size;
  48167. /**
  48168. * @property {string} _align - Internal cache var.
  48169. * @private
  48170. */
  48171. this._align = align;
  48172. /**
  48173. * @property {number} _tint - Internal cache var.
  48174. * @private
  48175. */
  48176. this._tint = 0xFFFFFF;
  48177. this.updateText();
  48178. /**
  48179. * @property {boolean} dirty - The dirty state of this object.
  48180. */
  48181. this.dirty = false;
  48182. Phaser.Component.Core.init.call(this, game, x, y, '', null);
  48183. };
  48184. Phaser.BitmapText.prototype = Object.create(PIXI.DisplayObjectContainer.prototype);
  48185. Phaser.BitmapText.prototype.constructor = Phaser.BitmapText;
  48186. Phaser.Component.Core.install.call(Phaser.BitmapText.prototype, [
  48187. 'Angle',
  48188. 'AutoCull',
  48189. 'Bounds',
  48190. 'Destroy',
  48191. 'FixedToCamera',
  48192. 'InputEnabled',
  48193. 'InWorld',
  48194. 'LifeSpan',
  48195. 'PhysicsBody',
  48196. 'Reset'
  48197. ]);
  48198. Phaser.BitmapText.prototype.preUpdatePhysics = Phaser.Component.PhysicsBody.preUpdate;
  48199. Phaser.BitmapText.prototype.preUpdateLifeSpan = Phaser.Component.LifeSpan.preUpdate;
  48200. Phaser.BitmapText.prototype.preUpdateInWorld = Phaser.Component.InWorld.preUpdate;
  48201. Phaser.BitmapText.prototype.preUpdateCore = Phaser.Component.Core.preUpdate;
  48202. /**
  48203. * Automatically called by World.preUpdate.
  48204. *
  48205. * @method
  48206. * @memberof Phaser.BitmapText
  48207. * @return {boolean} True if the BitmapText was rendered, otherwise false.
  48208. */
  48209. Phaser.BitmapText.prototype.preUpdate = function () {
  48210. if (!this.preUpdatePhysics() || !this.preUpdateLifeSpan() || !this.preUpdateInWorld())
  48211. {
  48212. return false;
  48213. }
  48214. return this.preUpdateCore();
  48215. };
  48216. /**
  48217. * Automatically called by World.preUpdate.
  48218. * @method Phaser.BitmapText.prototype.postUpdate
  48219. */
  48220. Phaser.BitmapText.prototype.postUpdate = function () {
  48221. Phaser.Component.PhysicsBody.postUpdate.call(this);
  48222. Phaser.Component.FixedToCamera.postUpdate.call(this);
  48223. if (this.body && this.body.type === Phaser.Physics.ARCADE)
  48224. {
  48225. if ((this.textWidth !== this.body.sourceWidth) || (this.textHeight !== this.body.sourceHeight))
  48226. {
  48227. this.body.setSize(this.textWidth, this.textHeight);
  48228. }
  48229. }
  48230. };
  48231. /**
  48232. * The text to be displayed by this BitmapText object.
  48233. *
  48234. * It's faster to use `BitmapText.text = string`, but this is kept for backwards compatibility.
  48235. *
  48236. * @method Phaser.BitmapText.prototype.setText
  48237. * @param {string} text - The text to be displayed by this BitmapText object.
  48238. */
  48239. Phaser.BitmapText.prototype.setText = function (text) {
  48240. this.text = text;
  48241. };
  48242. /**
  48243. * Given the input text this will scan the characters until either a newline is encountered,
  48244. * or the line exceeds maxWidth, taking into account kerning, character widths and scaling.
  48245. *
  48246. * @method Phaser.BitmapText.prototype.scanLine
  48247. * @private
  48248. * @param {object} data - A reference to the font object in the Phaser.Cache.
  48249. * @param {float} scale - The scale of the font in relation to the texture.
  48250. * @param {string} text - The text to parse.
  48251. * @return {object} An object containing the parsed characters, total pixel width and x offsets.
  48252. */
  48253. Phaser.BitmapText.prototype.scanLine = function (data, scale, text) {
  48254. var x = 0;
  48255. var w = 0;
  48256. var lastSpace = -1;
  48257. var wrappedWidth = 0;
  48258. var prevCharCode = null;
  48259. var maxWidth = (this._maxWidth > 0) ? this._maxWidth : null;
  48260. var chars = [];
  48261. // Let's scan the text and work out if any of the lines are > maxWidth
  48262. for (var i = 0; i < text.length; i++)
  48263. {
  48264. var end = (i === text.length - 1) ? true : false;
  48265. if (/(?:\r\n|\r|\n)/.test(text.charAt(i)))
  48266. {
  48267. return { width: w, text: text.substr(0, i), end: end, chars: chars };
  48268. }
  48269. else
  48270. {
  48271. var charCode = text.charCodeAt(i);
  48272. var charData = data.chars[charCode];
  48273. var c = 0;
  48274. // If the character data isn't found in the data array
  48275. // then we replace it with a blank space
  48276. if (charData === undefined)
  48277. {
  48278. charCode = 32;
  48279. charData = data.chars[charCode];
  48280. }
  48281. // Adjust for kerning from previous character to this one
  48282. var kerning = (prevCharCode && charData.kerning[prevCharCode]) ? charData.kerning[prevCharCode] : 0;
  48283. // Record the last space in the string and the current width
  48284. if (/(\s)/.test(text.charAt(i)))
  48285. {
  48286. lastSpace = i;
  48287. wrappedWidth = w;
  48288. }
  48289. // What will the line width be if we add this character to it?
  48290. c = (kerning + charData.texture.width + charData.xOffset) * scale;
  48291. // Do we need to line-wrap?
  48292. if (maxWidth && ((w + c) >= maxWidth) && lastSpace > -1)
  48293. {
  48294. // The last space was at "lastSpace" which was "i - lastSpace" characters ago
  48295. return { width: wrappedWidth || w, text: text.substr(0, i - (i - lastSpace)), end: end, chars: chars };
  48296. }
  48297. else
  48298. {
  48299. w += (charData.xAdvance + kerning) * scale;
  48300. chars.push(x + (charData.xOffset + kerning) * scale);
  48301. x += (charData.xAdvance + kerning) * scale;
  48302. prevCharCode = charCode;
  48303. }
  48304. }
  48305. }
  48306. return { width: w, text: text, end: end, chars: chars };
  48307. };
  48308. /**
  48309. * Given a text string this will scan each character in the string to ensure it exists
  48310. * in the BitmapText font data. If it doesn't the character is removed, or replaced with the `replace` argument.
  48311. *
  48312. * If no font data has been loaded at all this returns an empty string, as nothing can be rendered.
  48313. *
  48314. * @method Phaser.BitmapText.prototype.cleanText
  48315. * @param {string} text - The text to parse.
  48316. * @param {string} [replace=''] - The replacement string for any missing characters.
  48317. * @return {string} The cleaned text string.
  48318. */
  48319. Phaser.BitmapText.prototype.cleanText = function (text, replace) {
  48320. if (replace === undefined)
  48321. {
  48322. replace = '';
  48323. }
  48324. var data = this._data.font;
  48325. if (!data)
  48326. {
  48327. return '';
  48328. }
  48329. var re = /\r\n|\n\r|\n|\r/g;
  48330. var lines = text.replace(re, "\n").split("\n");
  48331. for (var i = 0; i < lines.length; i++)
  48332. {
  48333. var output = '';
  48334. var line = lines[i];
  48335. for (var c = 0; c < line.length; c++)
  48336. {
  48337. if (data.chars[line.charCodeAt(c)])
  48338. {
  48339. output = output.concat(line[c]);
  48340. }
  48341. else
  48342. {
  48343. output = output.concat(replace);
  48344. }
  48345. }
  48346. lines[i] = output;
  48347. }
  48348. return lines.join("\n");
  48349. };
  48350. /**
  48351. * Renders text and updates it when needed.
  48352. *
  48353. * @method Phaser.BitmapText.prototype.updateText
  48354. * @private
  48355. */
  48356. Phaser.BitmapText.prototype.updateText = function () {
  48357. var data = this._data.font;
  48358. if (!data)
  48359. {
  48360. return;
  48361. }
  48362. var text = this.text;
  48363. var scale = this._fontSize / data.size;
  48364. var lines = [];
  48365. var y = 0;
  48366. this.textWidth = 0;
  48367. do
  48368. {
  48369. var line = this.scanLine(data, scale, text);
  48370. line.y = y;
  48371. lines.push(line);
  48372. if (line.width > this.textWidth)
  48373. {
  48374. this.textWidth = line.width;
  48375. }
  48376. y += (data.lineHeight * scale);
  48377. text = text.substr(line.text.length + 1);
  48378. } while (line.end === false);
  48379. this.textHeight = y;
  48380. var t = 0;
  48381. var align = 0;
  48382. var ax = this.textWidth * this.anchor.x;
  48383. var ay = this.textHeight * this.anchor.y;
  48384. for (var i = 0; i < lines.length; i++)
  48385. {
  48386. var line = lines[i];
  48387. if (this._align === 'right')
  48388. {
  48389. align = this.textWidth - line.width;
  48390. }
  48391. else if (this._align === 'center')
  48392. {
  48393. align = (this.textWidth - line.width) / 2;
  48394. }
  48395. for (var c = 0; c < line.text.length; c++)
  48396. {
  48397. var charCode = line.text.charCodeAt(c);
  48398. var charData = data.chars[charCode];
  48399. if (charData === undefined)
  48400. {
  48401. charCode = 32;
  48402. charData = data.chars[charCode];
  48403. }
  48404. var g = this._glyphs[t];
  48405. if (g)
  48406. {
  48407. // Sprite already exists in the glyphs pool, so we'll reuse it for this letter
  48408. g.texture = charData.texture;
  48409. }
  48410. else
  48411. {
  48412. // We need a new sprite as the pool is empty or exhausted
  48413. g = new PIXI.Sprite(charData.texture);
  48414. g.name = line.text[c];
  48415. this._glyphs.push(g);
  48416. }
  48417. g.position.x = (line.chars[c] + align) - ax;
  48418. g.position.y = (line.y + (charData.yOffset * scale)) - ay;
  48419. g.scale.set(scale);
  48420. g.tint = this.tint;
  48421. g.texture.requiresReTint = true;
  48422. if (!g.parent)
  48423. {
  48424. this.addChild(g);
  48425. }
  48426. t++;
  48427. }
  48428. }
  48429. // Remove unnecessary children
  48430. // This moves them from the display list (children array) but retains them in the _glyphs pool
  48431. for (i = t; i < this._glyphs.length; i++)
  48432. {
  48433. this.removeChild(this._glyphs[i]);
  48434. }
  48435. };
  48436. /**
  48437. * If a BitmapText changes from having a large number of characters to having very few characters it will cause lots of
  48438. * Sprites to be retained in the BitmapText._glyphs array. Although they are not attached to the display list they
  48439. * still take up memory while sat in the glyphs pool waiting to be re-used in the future.
  48440. *
  48441. * If you know that the BitmapText will not grow any larger then you can purge out the excess glyphs from the pool
  48442. * by calling this method.
  48443. *
  48444. * Calling this doesn't prevent you from increasing the length of the text again in the future.
  48445. *
  48446. * @method Phaser.BitmapText.prototype.purgeGlyphs
  48447. * @return {integer} The amount of glyphs removed from the pool.
  48448. */
  48449. Phaser.BitmapText.prototype.purgeGlyphs = function () {
  48450. var len = this._glyphs.length;
  48451. var kept = [];
  48452. for (var i = 0; i < this._glyphs.length; i++)
  48453. {
  48454. if (this._glyphs[i].parent !== this)
  48455. {
  48456. this._glyphs[i].destroy();
  48457. }
  48458. else
  48459. {
  48460. kept.push(this._glyphs[i]);
  48461. }
  48462. }
  48463. this._glyphs = [];
  48464. this._glyphs = kept;
  48465. this.updateText();
  48466. return len - kept.length;
  48467. };
  48468. /**
  48469. * Updates the transform of this object.
  48470. *
  48471. * @method Phaser.BitmapText.prototype.updateTransform
  48472. * @private
  48473. */
  48474. Phaser.BitmapText.prototype.updateTransform = function () {
  48475. if (this.dirty || !this.anchor.equals(this._prevAnchor))
  48476. {
  48477. this.updateText();
  48478. this.dirty = false;
  48479. this._prevAnchor.copyFrom(this.anchor);
  48480. }
  48481. PIXI.DisplayObjectContainer.prototype.updateTransform.call(this);
  48482. };
  48483. /**
  48484. * @name Phaser.BitmapText#align
  48485. * @property {string} align - Alignment for multi-line text ('left', 'center' or 'right'), does not affect single lines of text.
  48486. */
  48487. Object.defineProperty(Phaser.BitmapText.prototype, 'align', {
  48488. get: function() {
  48489. return this._align;
  48490. },
  48491. set: function(value) {
  48492. if (value !== this._align && (value === 'left' || value === 'center' || value === 'right'))
  48493. {
  48494. this._align = value;
  48495. this.updateText();
  48496. }
  48497. }
  48498. });
  48499. /**
  48500. * @name Phaser.BitmapText#tint
  48501. * @property {number} tint - The tint applied to the BitmapText. This is a hex value. Set to white to disable (0xFFFFFF)
  48502. */
  48503. Object.defineProperty(Phaser.BitmapText.prototype, 'tint', {
  48504. get: function() {
  48505. return this._tint;
  48506. },
  48507. set: function(value) {
  48508. if (value !== this._tint)
  48509. {
  48510. this._tint = value;
  48511. this.updateText();
  48512. }
  48513. }
  48514. });
  48515. /**
  48516. * @name Phaser.BitmapText#font
  48517. * @property {string} font - The font the text will be rendered in, i.e. 'Arial'. Must be loaded in the browser before use.
  48518. */
  48519. Object.defineProperty(Phaser.BitmapText.prototype, 'font', {
  48520. get: function() {
  48521. return this._font;
  48522. },
  48523. set: function(value) {
  48524. if (value !== this._font)
  48525. {
  48526. this._font = value.trim();
  48527. this._data = this.game.cache.getBitmapFont(this._font);
  48528. this.updateText();
  48529. }
  48530. }
  48531. });
  48532. /**
  48533. * @name Phaser.BitmapText#fontSize
  48534. * @property {number} fontSize - The size of the font in pixels.
  48535. */
  48536. Object.defineProperty(Phaser.BitmapText.prototype, 'fontSize', {
  48537. get: function() {
  48538. return this._fontSize;
  48539. },
  48540. set: function(value) {
  48541. value = parseInt(value, 10);
  48542. if (value !== this._fontSize && value > 0)
  48543. {
  48544. this._fontSize = value;
  48545. this.updateText();
  48546. }
  48547. }
  48548. });
  48549. /**
  48550. * @name Phaser.BitmapText#text
  48551. * @property {string} text - The text to be displayed by this BitmapText object.
  48552. */
  48553. Object.defineProperty(Phaser.BitmapText.prototype, 'text', {
  48554. get: function() {
  48555. return this._text;
  48556. },
  48557. set: function(value) {
  48558. if (value !== this._text)
  48559. {
  48560. this._text = value.toString() || '';
  48561. this.updateText();
  48562. }
  48563. }
  48564. });
  48565. /**
  48566. * The maximum display width of this BitmapText in pixels.
  48567. *
  48568. * If BitmapText.text is longer than maxWidth then the lines will be automatically wrapped
  48569. * based on the last whitespace character found in the line.
  48570. *
  48571. * If no whitespace was found then no wrapping will take place and consequently the maxWidth value will not be honored.
  48572. *
  48573. * Disable maxWidth by setting the value to 0.
  48574. *
  48575. * @name Phaser.BitmapText#maxWidth
  48576. * @property {number} maxWidth - The maximum width of this BitmapText in pixels.
  48577. */
  48578. Object.defineProperty(Phaser.BitmapText.prototype, 'maxWidth', {
  48579. get: function() {
  48580. return this._maxWidth;
  48581. },
  48582. set: function(value) {
  48583. if (value !== this._maxWidth)
  48584. {
  48585. this._maxWidth = value;
  48586. this.updateText();
  48587. }
  48588. }
  48589. });
  48590. /**
  48591. * Enable or disable texture smoothing for this BitmapText.
  48592. *
  48593. * The smoothing is applied to the BaseTexture of this font, which all letters of the text reference.
  48594. *
  48595. * Smoothing is enabled by default.
  48596. *
  48597. * @name Phaser.BitmapText#smoothed
  48598. * @property {boolean} smoothed
  48599. */
  48600. Object.defineProperty(Phaser.BitmapText.prototype, 'smoothed', {
  48601. get: function() {
  48602. return !this._data.base.scaleMode;
  48603. },
  48604. set: function(value) {
  48605. if (value)
  48606. {
  48607. this._data.base.scaleMode = 0;
  48608. }
  48609. else
  48610. {
  48611. this._data.base.scaleMode = 1;
  48612. }
  48613. }
  48614. });
  48615. /**
  48616. * @author Richard Davey <rich@photonstorm.com>
  48617. * @copyright 2016 Photon Storm Ltd.
  48618. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  48619. */
  48620. /**
  48621. * A Retro Font is similar to a BitmapFont, in that it uses a texture to render the text. However unlike a BitmapFont every character in a RetroFont
  48622. * is the same size. This makes it similar to a sprite sheet. You typically find font sheets like this from old 8/16-bit games and demos.
  48623. *
  48624. * @class Phaser.RetroFont
  48625. * @extends Phaser.RenderTexture
  48626. * @constructor
  48627. * @param {Phaser.Game} game - Current game instance.
  48628. * @param {string} key - The font set graphic set as stored in the Game.Cache.
  48629. * @param {number} characterWidth - The width of each character in the font set.
  48630. * @param {number} characterHeight - The height of each character in the font set.
  48631. * @param {string} chars - The characters used in the font set, in display order. You can use the TEXT_SET consts for common font set arrangements.
  48632. * @param {number} [charsPerRow] - The number of characters per row in the font set. If not given charsPerRow will be the image width / characterWidth.
  48633. * @param {number} [xSpacing=0] - If the characters in the font set have horizontal spacing between them set the required amount here.
  48634. * @param {number} [ySpacing=0] - If the characters in the font set have vertical spacing between them set the required amount here.
  48635. * @param {number} [xOffset=0] - If the font set doesn't start at the top left of the given image, specify the X coordinate offset here.
  48636. * @param {number} [yOffset=0] - If the font set doesn't start at the top left of the given image, specify the Y coordinate offset here.
  48637. */
  48638. Phaser.RetroFont = function (game, key, characterWidth, characterHeight, chars, charsPerRow, xSpacing, ySpacing, xOffset, yOffset) {
  48639. if (!game.cache.checkImageKey(key))
  48640. {
  48641. return false;
  48642. }
  48643. if (charsPerRow === undefined || charsPerRow === null)
  48644. {
  48645. charsPerRow = game.cache.getImage(key).width / characterWidth;
  48646. }
  48647. /**
  48648. * @property {number} characterWidth - The width of each character in the font set.
  48649. */
  48650. this.characterWidth = characterWidth;
  48651. /**
  48652. * @property {number} characterHeight - The height of each character in the font set.
  48653. */
  48654. this.characterHeight = characterHeight;
  48655. /**
  48656. * @property {number} characterSpacingX - If the characters in the font set have horizontal spacing between them set the required amount here.
  48657. */
  48658. this.characterSpacingX = xSpacing || 0;
  48659. /**
  48660. * @property {number} characterSpacingY - If the characters in the font set have vertical spacing between them set the required amount here.
  48661. */
  48662. this.characterSpacingY = ySpacing || 0;
  48663. /**
  48664. * @property {number} characterPerRow - The number of characters per row in the font set.
  48665. */
  48666. this.characterPerRow = charsPerRow;
  48667. /**
  48668. * @property {number} offsetX - If the font set doesn't start at the top left of the given image, specify the X coordinate offset here.
  48669. * @readonly
  48670. */
  48671. this.offsetX = xOffset || 0;
  48672. /**
  48673. * @property {number} offsetY - If the font set doesn't start at the top left of the given image, specify the Y coordinate offset here.
  48674. * @readonly
  48675. */
  48676. this.offsetY = yOffset || 0;
  48677. /**
  48678. * @property {string} align - Alignment of the text when multiLine = true or a fixedWidth is set. Set to RetroFont.ALIGN_LEFT (default), RetroFont.ALIGN_RIGHT or RetroFont.ALIGN_CENTER.
  48679. */
  48680. this.align = "left";
  48681. /**
  48682. * @property {boolean} multiLine - If set to true all carriage-returns in text will form new lines (see align). If false the font will only contain one single line of text (the default)
  48683. * @default
  48684. */
  48685. this.multiLine = false;
  48686. /**
  48687. * @property {boolean} autoUpperCase - Automatically convert any text to upper case. Lots of old bitmap fonts only contain upper-case characters, so the default is true.
  48688. * @default
  48689. */
  48690. this.autoUpperCase = true;
  48691. /**
  48692. * @property {number} customSpacingX - Adds horizontal spacing between each character of the font, in pixels.
  48693. * @default
  48694. */
  48695. this.customSpacingX = 0;
  48696. /**
  48697. * @property {number} customSpacingY - Adds vertical spacing between each line of multi-line text, set in pixels.
  48698. * @default
  48699. */
  48700. this.customSpacingY = 0;
  48701. /**
  48702. * If you need this RetroFont image to have a fixed width you can set the width in this value.
  48703. * If text is wider than the width specified it will be cropped off.
  48704. * @property {number} fixedWidth
  48705. */
  48706. this.fixedWidth = 0;
  48707. /**
  48708. * @property {Image} fontSet - A reference to the image stored in the Game.Cache that contains the font.
  48709. */
  48710. this.fontSet = game.cache.getImage(key);
  48711. /**
  48712. * @property {string} _text - The text of the font image.
  48713. * @private
  48714. */
  48715. this._text = '';
  48716. /**
  48717. * @property {array} grabData - An array of rects for faster character pasting.
  48718. * @private
  48719. */
  48720. this.grabData = [];
  48721. /**
  48722. * @property {Phaser.FrameData} frameData - The FrameData representing this Retro Font.
  48723. */
  48724. this.frameData = new Phaser.FrameData();
  48725. // Now generate our rects for faster copying later on
  48726. var currentX = this.offsetX;
  48727. var currentY = this.offsetY;
  48728. var r = 0;
  48729. for (var c = 0; c < chars.length; c++)
  48730. {
  48731. var frame = this.frameData.addFrame(new Phaser.Frame(c, currentX, currentY, this.characterWidth, this.characterHeight));
  48732. this.grabData[chars.charCodeAt(c)] = frame.index;
  48733. r++;
  48734. if (r === this.characterPerRow)
  48735. {
  48736. r = 0;
  48737. currentX = this.offsetX;
  48738. currentY += this.characterHeight + this.characterSpacingY;
  48739. }
  48740. else
  48741. {
  48742. currentX += this.characterWidth + this.characterSpacingX;
  48743. }
  48744. }
  48745. game.cache.updateFrameData(key, this.frameData);
  48746. /**
  48747. * @property {Phaser.Image} stamp - The image that is stamped to the RenderTexture for each character in the font.
  48748. * @readonly
  48749. */
  48750. this.stamp = new Phaser.Image(game, 0, 0, key, 0);
  48751. Phaser.RenderTexture.call(this, game, 100, 100, '', Phaser.scaleModes.NEAREST);
  48752. /**
  48753. * @property {number} type - Base Phaser object type.
  48754. */
  48755. this.type = Phaser.RETROFONT;
  48756. };
  48757. Phaser.RetroFont.prototype = Object.create(Phaser.RenderTexture.prototype);
  48758. Phaser.RetroFont.prototype.constructor = Phaser.RetroFont;
  48759. /**
  48760. * Align each line of multi-line text to the left.
  48761. * @constant
  48762. * @type {string}
  48763. */
  48764. Phaser.RetroFont.ALIGN_LEFT = "left";
  48765. /**
  48766. * Align each line of multi-line text to the right.
  48767. * @constant
  48768. * @type {string}
  48769. */
  48770. Phaser.RetroFont.ALIGN_RIGHT = "right";
  48771. /**
  48772. * Align each line of multi-line text in the center.
  48773. * @constant
  48774. * @type {string}
  48775. */
  48776. Phaser.RetroFont.ALIGN_CENTER = "center";
  48777. /**
  48778. * Text Set 1 = !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~
  48779. * @constant
  48780. * @type {string}
  48781. */
  48782. Phaser.RetroFont.TEXT_SET1 = " !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~";
  48783. /**
  48784. * Text Set 2 = !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ
  48785. * @constant
  48786. * @type {string}
  48787. */
  48788. Phaser.RetroFont.TEXT_SET2 = " !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  48789. /**
  48790. * Text Set 3 = ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789
  48791. * @constant
  48792. * @type {string}
  48793. */
  48794. Phaser.RetroFont.TEXT_SET3 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 ";
  48795. /**
  48796. * Text Set 4 = ABCDEFGHIJKLMNOPQRSTUVWXYZ 0123456789
  48797. * @constant
  48798. * @type {string}
  48799. */
  48800. Phaser.RetroFont.TEXT_SET4 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ 0123456789";
  48801. /**
  48802. * Text Set 5 = ABCDEFGHIJKLMNOPQRSTUVWXYZ.,/() '!?-*:0123456789
  48803. * @constant
  48804. * @type {string}
  48805. */
  48806. Phaser.RetroFont.TEXT_SET5 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ.,/() '!?-*:0123456789";
  48807. /**
  48808. * Text Set 6 = ABCDEFGHIJKLMNOPQRSTUVWXYZ!?:;0123456789"(),-.'
  48809. * @constant
  48810. * @type {string}
  48811. */
  48812. Phaser.RetroFont.TEXT_SET6 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ!?:;0123456789\"(),-.' ";
  48813. /**
  48814. * Text Set 7 = AGMSY+:4BHNTZ!;5CIOU.?06DJPV,(17EKQW")28FLRX-'39
  48815. * @constant
  48816. * @type {string}
  48817. */
  48818. Phaser.RetroFont.TEXT_SET7 = "AGMSY+:4BHNTZ!;5CIOU.?06DJPV,(17EKQW\")28FLRX-'39";
  48819. /**
  48820. * Text Set 8 = 0123456789 .ABCDEFGHIJKLMNOPQRSTUVWXYZ
  48821. * @constant
  48822. * @type {string}
  48823. */
  48824. Phaser.RetroFont.TEXT_SET8 = "0123456789 .ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  48825. /**
  48826. * Text Set 9 = ABCDEFGHIJKLMNOPQRSTUVWXYZ()-0123456789.:,'"?!
  48827. * @constant
  48828. * @type {string}
  48829. */
  48830. Phaser.RetroFont.TEXT_SET9 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ()-0123456789.:,'\"?!";
  48831. /**
  48832. * Text Set 10 = ABCDEFGHIJKLMNOPQRSTUVWXYZ
  48833. * @constant
  48834. * @type {string}
  48835. */
  48836. Phaser.RetroFont.TEXT_SET10 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  48837. /**
  48838. * Text Set 11 = ABCDEFGHIJKLMNOPQRSTUVWXYZ.,"-+!?()':;0123456789
  48839. * @constant
  48840. * @type {string}
  48841. */
  48842. Phaser.RetroFont.TEXT_SET11 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ.,\"-+!?()':;0123456789";
  48843. /**
  48844. * If you need this RetroFont to have a fixed width and custom alignment you can set the width here.
  48845. * If text is wider than the width specified it will be cropped off.
  48846. *
  48847. * @method Phaser.RetroFont#setFixedWidth
  48848. * @memberof Phaser.RetroFont
  48849. * @param {number} width - Width in pixels of this RetroFont. Set to zero to disable and re-enable automatic resizing.
  48850. * @param {string} [lineAlignment='left'] - Align the text within this width. Set to RetroFont.ALIGN_LEFT (default), RetroFont.ALIGN_RIGHT or RetroFont.ALIGN_CENTER.
  48851. */
  48852. Phaser.RetroFont.prototype.setFixedWidth = function (width, lineAlignment) {
  48853. if (lineAlignment === undefined) { lineAlignment = 'left'; }
  48854. this.fixedWidth = width;
  48855. this.align = lineAlignment;
  48856. };
  48857. /**
  48858. * A helper function that quickly sets lots of variables at once, and then updates the text.
  48859. *
  48860. * @method Phaser.RetroFont#setText
  48861. * @memberof Phaser.RetroFont
  48862. * @param {string} content - The text of this sprite.
  48863. * @param {boolean} [multiLine=false] - Set to true if you want to support carriage-returns in the text and create a multi-line sprite instead of a single line.
  48864. * @param {number} [characterSpacing=0] - To add horizontal spacing between each character specify the amount in pixels.
  48865. * @param {number} [lineSpacing=0] - To add vertical spacing between each line of text, set the amount in pixels.
  48866. * @param {string} [lineAlignment='left'] - Align each line of multi-line text. Set to RetroFont.ALIGN_LEFT, RetroFont.ALIGN_RIGHT or RetroFont.ALIGN_CENTER.
  48867. * @param {boolean} [allowLowerCase=false] - Lots of bitmap font sets only include upper-case characters, if yours needs to support lower case then set this to true.
  48868. */
  48869. Phaser.RetroFont.prototype.setText = function (content, multiLine, characterSpacing, lineSpacing, lineAlignment, allowLowerCase) {
  48870. this.multiLine = multiLine || false;
  48871. this.customSpacingX = characterSpacing || 0;
  48872. this.customSpacingY = lineSpacing || 0;
  48873. this.align = lineAlignment || 'left';
  48874. if (allowLowerCase)
  48875. {
  48876. this.autoUpperCase = false;
  48877. }
  48878. else
  48879. {
  48880. this.autoUpperCase = true;
  48881. }
  48882. if (content.length > 0)
  48883. {
  48884. this.text = content;
  48885. }
  48886. };
  48887. /**
  48888. * Updates the texture with the new text.
  48889. *
  48890. * @method Phaser.RetroFont#buildRetroFontText
  48891. * @memberof Phaser.RetroFont
  48892. */
  48893. Phaser.RetroFont.prototype.buildRetroFontText = function () {
  48894. var cx = 0;
  48895. var cy = 0;
  48896. // Clears the textureBuffer
  48897. this.clear();
  48898. if (this.multiLine)
  48899. {
  48900. var lines = this._text.split("\n");
  48901. if (this.fixedWidth > 0)
  48902. {
  48903. this.resize(this.fixedWidth, (lines.length * (this.characterHeight + this.customSpacingY)) - this.customSpacingY, true);
  48904. }
  48905. else
  48906. {
  48907. this.resize(this.getLongestLine() * (this.characterWidth + this.customSpacingX), (lines.length * (this.characterHeight + this.customSpacingY)) - this.customSpacingY, true);
  48908. }
  48909. // Loop through each line of text
  48910. for (var i = 0; i < lines.length; i++)
  48911. {
  48912. // Phaser.RetroFont.ALIGN_LEFT
  48913. cx = 0;
  48914. // This line of text is held in lines[i] - need to work out the alignment
  48915. if (this.align === Phaser.RetroFont.ALIGN_RIGHT)
  48916. {
  48917. cx = this.width - (lines[i].length * (this.characterWidth + this.customSpacingX));
  48918. }
  48919. else if (this.align === Phaser.RetroFont.ALIGN_CENTER)
  48920. {
  48921. cx = (this.width / 2) - ((lines[i].length * (this.characterWidth + this.customSpacingX)) / 2);
  48922. cx += this.customSpacingX / 2;
  48923. }
  48924. // Sanity checks
  48925. if (cx < 0)
  48926. {
  48927. cx = 0;
  48928. }
  48929. this.pasteLine(lines[i], cx, cy, this.customSpacingX);
  48930. cy += this.characterHeight + this.customSpacingY;
  48931. }
  48932. }
  48933. else
  48934. {
  48935. if (this.fixedWidth > 0)
  48936. {
  48937. this.resize(this.fixedWidth, this.characterHeight, true);
  48938. }
  48939. else
  48940. {
  48941. this.resize(this._text.length * (this.characterWidth + this.customSpacingX), this.characterHeight, true);
  48942. }
  48943. // Phaser.RetroFont.ALIGN_LEFT
  48944. cx = 0;
  48945. if (this.align === Phaser.RetroFont.ALIGN_RIGHT)
  48946. {
  48947. cx = this.width - (this._text.length * (this.characterWidth + this.customSpacingX));
  48948. }
  48949. else if (this.align === Phaser.RetroFont.ALIGN_CENTER)
  48950. {
  48951. cx = (this.width / 2) - ((this._text.length * (this.characterWidth + this.customSpacingX)) / 2);
  48952. cx += this.customSpacingX / 2;
  48953. }
  48954. // Sanity checks
  48955. if (cx < 0)
  48956. {
  48957. cx = 0;
  48958. }
  48959. this.pasteLine(this._text, cx, 0, this.customSpacingX);
  48960. }
  48961. this.requiresReTint = true;
  48962. };
  48963. /**
  48964. * Internal function that takes a single line of text (2nd parameter) and pastes it into the BitmapData at the given coordinates.
  48965. * Used by getLine and getMultiLine
  48966. *
  48967. * @method Phaser.RetroFont#pasteLine
  48968. * @memberof Phaser.RetroFont
  48969. * @param {string} line - The single line of text to paste.
  48970. * @param {number} x - The x coordinate.
  48971. * @param {number} y - The y coordinate.
  48972. * @param {number} customSpacingX - Custom X spacing.
  48973. */
  48974. Phaser.RetroFont.prototype.pasteLine = function (line, x, y, customSpacingX) {
  48975. for (var c = 0; c < line.length; c++)
  48976. {
  48977. // If it's a space then there is no point copying, so leave a blank space
  48978. if (line.charAt(c) === " ")
  48979. {
  48980. x += this.characterWidth + customSpacingX;
  48981. }
  48982. else
  48983. {
  48984. // If the character doesn't exist in the font then we don't want a blank space, we just want to skip it
  48985. if (this.grabData[line.charCodeAt(c)] >= 0)
  48986. {
  48987. this.stamp.frame = this.grabData[line.charCodeAt(c)];
  48988. this.renderXY(this.stamp, x, y, false);
  48989. x += this.characterWidth + customSpacingX;
  48990. if (x > this.width)
  48991. {
  48992. break;
  48993. }
  48994. }
  48995. }
  48996. }
  48997. };
  48998. /**
  48999. * Works out the longest line of text in _text and returns its length
  49000. *
  49001. * @method Phaser.RetroFont#getLongestLine
  49002. * @memberof Phaser.RetroFont
  49003. * @return {number} The length of the longest line of text.
  49004. */
  49005. Phaser.RetroFont.prototype.getLongestLine = function () {
  49006. var longestLine = 0;
  49007. if (this._text.length > 0)
  49008. {
  49009. var lines = this._text.split("\n");
  49010. for (var i = 0; i < lines.length; i++)
  49011. {
  49012. if (lines[i].length > longestLine)
  49013. {
  49014. longestLine = lines[i].length;
  49015. }
  49016. }
  49017. }
  49018. return longestLine;
  49019. };
  49020. /**
  49021. * Internal helper function that removes all unsupported characters from the _text String, leaving only characters contained in the font set.
  49022. *
  49023. * @method Phaser.RetroFont#removeUnsupportedCharacters
  49024. * @memberof Phaser.RetroFont
  49025. * @protected
  49026. * @param {boolean} [stripCR=true] - Should it strip carriage returns as well?
  49027. * @return {string} A clean version of the string.
  49028. */
  49029. Phaser.RetroFont.prototype.removeUnsupportedCharacters = function (stripCR) {
  49030. var newString = "";
  49031. for (var c = 0; c < this._text.length; c++)
  49032. {
  49033. var aChar = this._text[c];
  49034. var code = aChar.charCodeAt(0);
  49035. if (this.grabData[code] >= 0 || (!stripCR && aChar === "\n"))
  49036. {
  49037. newString = newString.concat(aChar);
  49038. }
  49039. }
  49040. return newString;
  49041. };
  49042. /**
  49043. * Updates the x and/or y offset that the font is rendered from. This updates all of the texture frames, so be careful how often it is called.
  49044. * Note that the values given for the x and y properties are either ADDED to or SUBTRACTED from (if negative) the existing offsetX/Y values of the characters.
  49045. * So if the current offsetY is 8 and you want it to start rendering from y16 you would call updateOffset(0, 8) to add 8 to the current y offset.
  49046. *
  49047. * @method Phaser.RetroFont#updateOffset
  49048. * @memberof Phaser.RetroFont
  49049. * @param {number} [xOffset=0] - If the font set doesn't start at the top left of the given image, specify the X coordinate offset here.
  49050. * @param {number} [yOffset=0] - If the font set doesn't start at the top left of the given image, specify the Y coordinate offset here.
  49051. */
  49052. Phaser.RetroFont.prototype.updateOffset = function (x, y) {
  49053. if (this.offsetX === x && this.offsetY === y)
  49054. {
  49055. return;
  49056. }
  49057. var diffX = x - this.offsetX;
  49058. var diffY = y - this.offsetY;
  49059. var frames = this.game.cache.getFrameData(this.stamp.key).getFrames();
  49060. var i = frames.length;
  49061. while (i--)
  49062. {
  49063. frames[i].x += diffX;
  49064. frames[i].y += diffY;
  49065. }
  49066. this.buildRetroFontText();
  49067. };
  49068. /**
  49069. * @name Phaser.RetroFont#text
  49070. * @property {string} text - Set this value to update the text in this sprite. Carriage returns are automatically stripped out if multiLine is false. Text is converted to upper case if autoUpperCase is true.
  49071. */
  49072. Object.defineProperty(Phaser.RetroFont.prototype, "text", {
  49073. get: function () {
  49074. return this._text;
  49075. },
  49076. set: function (value) {
  49077. var newText;
  49078. if (this.autoUpperCase)
  49079. {
  49080. newText = value.toUpperCase();
  49081. }
  49082. else
  49083. {
  49084. newText = value;
  49085. }
  49086. if (newText !== this._text)
  49087. {
  49088. this._text = newText;
  49089. this.removeUnsupportedCharacters(this.multiLine);
  49090. this.buildRetroFontText();
  49091. }
  49092. }
  49093. });
  49094. /**
  49095. * @name Phaser.RetroFont#smoothed
  49096. * @property {boolean} smoothed - Sets if the stamp is smoothed or not.
  49097. */
  49098. Object.defineProperty(Phaser.RetroFont.prototype, "smoothed", {
  49099. get: function () {
  49100. return this.stamp.smoothed;
  49101. },
  49102. set: function (value) {
  49103. this.stamp.smoothed = value;
  49104. this.buildRetroFontText();
  49105. }
  49106. });
  49107. /**
  49108. * @author Richard Davey <rich@photonstorm.com>
  49109. * @copyright 2016 Photon Storm Ltd, Richard Davey
  49110. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  49111. */
  49112. /**
  49113. * A Rope is a Sprite that has a repeating texture.
  49114. *
  49115. * The texture will automatically wrap on the edges as it moves.
  49116. *
  49117. * Please note that Ropes cannot have an input handler.
  49118. *
  49119. * @class Phaser.Rope
  49120. * @constructor
  49121. * @extends PIXI.Rope
  49122. * @extends Phaser.Component.Core
  49123. * @extends Phaser.Component.Angle
  49124. * @extends Phaser.Component.Animation
  49125. * @extends Phaser.Component.AutoCull
  49126. * @extends Phaser.Component.Bounds
  49127. * @extends Phaser.Component.BringToTop
  49128. * @extends Phaser.Component.Crop
  49129. * @extends Phaser.Component.Delta
  49130. * @extends Phaser.Component.Destroy
  49131. * @extends Phaser.Component.FixedToCamera
  49132. * @extends Phaser.Component.InWorld
  49133. * @extends Phaser.Component.LifeSpan
  49134. * @extends Phaser.Component.LoadTexture
  49135. * @extends Phaser.Component.Overlap
  49136. * @extends Phaser.Component.PhysicsBody
  49137. * @extends Phaser.Component.Reset
  49138. * @extends Phaser.Component.ScaleMinMax
  49139. * @extends Phaser.Component.Smoothed
  49140. * @param {Phaser.Game} game - A reference to the currently running game.
  49141. * @param {number} x - The x coordinate (in world space) to position the Rope at.
  49142. * @param {number} y - The y coordinate (in world space) to position the Rope at.
  49143. * @param {string|Phaser.RenderTexture|Phaser.BitmapData|PIXI.Texture} key - This is the image or texture used by the Rope during rendering. It can be a string which is a reference to the Cache entry, or an instance of a RenderTexture or PIXI.Texture.
  49144. * @param {string|number} frame - If this Rope is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index.
  49145. * @param {Array} points - An array of {Phaser.Point}.
  49146. */
  49147. Phaser.Rope = function (game, x, y, key, frame, points) {
  49148. this.points = [];
  49149. this.points = points;
  49150. this._hasUpdateAnimation = false;
  49151. this._updateAnimationCallback = null;
  49152. x = x || 0;
  49153. y = y || 0;
  49154. key = key || null;
  49155. frame = frame || null;
  49156. /**
  49157. * @property {number} type - The const type of this object.
  49158. * @readonly
  49159. */
  49160. this.type = Phaser.ROPE;
  49161. PIXI.Rope.call(this, Phaser.Cache.DEFAULT, this.points);
  49162. Phaser.Component.Core.init.call(this, game, x, y, key, frame);
  49163. };
  49164. Phaser.Rope.prototype = Object.create(PIXI.Rope.prototype);
  49165. Phaser.Rope.prototype.constructor = Phaser.Rope;
  49166. Phaser.Component.Core.install.call(Phaser.Rope.prototype, [
  49167. 'Angle',
  49168. 'Animation',
  49169. 'AutoCull',
  49170. 'Bounds',
  49171. 'BringToTop',
  49172. 'Crop',
  49173. 'Delta',
  49174. 'Destroy',
  49175. 'FixedToCamera',
  49176. 'InWorld',
  49177. 'LifeSpan',
  49178. 'LoadTexture',
  49179. 'Overlap',
  49180. 'PhysicsBody',
  49181. 'Reset',
  49182. 'ScaleMinMax',
  49183. 'Smoothed'
  49184. ]);
  49185. Phaser.Rope.prototype.preUpdatePhysics = Phaser.Component.PhysicsBody.preUpdate;
  49186. Phaser.Rope.prototype.preUpdateLifeSpan = Phaser.Component.LifeSpan.preUpdate;
  49187. Phaser.Rope.prototype.preUpdateInWorld = Phaser.Component.InWorld.preUpdate;
  49188. Phaser.Rope.prototype.preUpdateCore = Phaser.Component.Core.preUpdate;
  49189. /**
  49190. * Automatically called by World.preUpdate.
  49191. *
  49192. * @method Phaser.Rope#preUpdate
  49193. * @memberof Phaser.Rope
  49194. */
  49195. Phaser.Rope.prototype.preUpdate = function() {
  49196. if (!this.preUpdatePhysics() || !this.preUpdateLifeSpan() || !this.preUpdateInWorld())
  49197. {
  49198. return false;
  49199. }
  49200. return this.preUpdateCore();
  49201. };
  49202. /**
  49203. * Override and use this function in your own custom objects to handle any update requirements you may have.
  49204. *
  49205. * @method Phaser.Rope#update
  49206. * @memberof Phaser.Rope
  49207. */
  49208. Phaser.Rope.prototype.update = function() {
  49209. if (this._hasUpdateAnimation)
  49210. {
  49211. this.updateAnimation.call(this);
  49212. }
  49213. };
  49214. /**
  49215. * Resets the Rope. This places the Rope at the given x/y world coordinates and then
  49216. * sets alive, exists, visible and renderable all to true. Also resets the outOfBounds state.
  49217. * If the Rope has a physics body that too is reset.
  49218. *
  49219. * @method Phaser.Rope#reset
  49220. * @memberof Phaser.Rope
  49221. * @param {number} x - The x coordinate (in world space) to position the Sprite at.
  49222. * @param {number} y - The y coordinate (in world space) to position the Sprite at.
  49223. * @return {Phaser.Rope} This instance.
  49224. */
  49225. Phaser.Rope.prototype.reset = function(x, y) {
  49226. Phaser.Component.Reset.prototype.reset.call(this, x, y);
  49227. return this;
  49228. };
  49229. /**
  49230. * A Rope will call its updateAnimation function on each update loop if it has one.
  49231. *
  49232. * @name Phaser.Rope#updateAnimation
  49233. * @property {function} updateAnimation - Set to a function if you'd like the rope to animate during the update phase. Set to false or null to remove it.
  49234. */
  49235. Object.defineProperty(Phaser.Rope.prototype, "updateAnimation", {
  49236. get: function () {
  49237. return this._updateAnimation;
  49238. },
  49239. set: function (value) {
  49240. if (value && typeof value === 'function')
  49241. {
  49242. this._hasUpdateAnimation = true;
  49243. this._updateAnimation = value;
  49244. }
  49245. else
  49246. {
  49247. this._hasUpdateAnimation = false;
  49248. this._updateAnimation = null;
  49249. }
  49250. }
  49251. });
  49252. /**
  49253. * The segments that make up the rope body as an array of Phaser.Rectangles
  49254. *
  49255. * @name Phaser.Rope#segments
  49256. * @property {Phaser.Rectangles[]} updateAnimation - Returns an array of Phaser.Rectangles that represent the segments of the given rope
  49257. */
  49258. Object.defineProperty(Phaser.Rope.prototype, "segments", {
  49259. get: function() {
  49260. var segments = [];
  49261. var index, x1, y1, x2, y2, width, height, rect;
  49262. for (var i = 0; i < this.points.length; i++)
  49263. {
  49264. index = i * 4;
  49265. x1 = this.vertices[index] * this.scale.x;
  49266. y1 = this.vertices[index + 1] * this.scale.y;
  49267. x2 = this.vertices[index + 4] * this.scale.x;
  49268. y2 = this.vertices[index + 3] * this.scale.y;
  49269. width = Phaser.Math.difference(x1, x2);
  49270. height = Phaser.Math.difference(y1, y2);
  49271. x1 += this.world.x;
  49272. y1 += this.world.y;
  49273. rect = new Phaser.Rectangle(x1, y1, width, height);
  49274. segments.push(rect);
  49275. }
  49276. return segments;
  49277. }
  49278. });
  49279. /**
  49280. * @author Richard Davey <rich@photonstorm.com>
  49281. * @copyright 2016 Photon Storm Ltd.
  49282. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  49283. */
  49284. /**
  49285. * A TileSprite is a Sprite that has a repeating texture. The texture can be scrolled and scaled independently of the TileSprite itself.
  49286. * Textures will automatically wrap and are designed so that you can create game backdrops using seamless textures as a source.
  49287. *
  49288. * TileSprites have no input handler or physics bodies by default, both need enabling in the same way as for normal Sprites.
  49289. *
  49290. * You shouldn't ever create a TileSprite any larger than your actual screen size. If you want to create a large repeating background
  49291. * that scrolls across the whole map of your game, then you create a TileSprite that fits the screen size and then use the `tilePosition`
  49292. * property to scroll the texture as the player moves. If you create a TileSprite that is thousands of pixels in size then it will
  49293. * consume huge amounts of memory and cause performance issues. Remember: use `tilePosition` to scroll your texture and `tileScale` to
  49294. * adjust the scale of the texture - don't resize the sprite itself or make it larger than it needs.
  49295. *
  49296. * An important note about texture dimensions:
  49297. *
  49298. * When running under Canvas a TileSprite can use any texture size without issue. When running under WebGL the texture should ideally be
  49299. * a power of two in size (i.e. 4, 8, 16, 32, 64, 128, 256, 512, etc pixels width by height). If the texture isn't a power of two
  49300. * it will be rendered to a blank canvas that is the correct size, which means you may have 'blank' areas appearing to the right and
  49301. * bottom of your frame. To avoid this ensure your textures are perfect powers of two.
  49302. *
  49303. * TileSprites support animations in the same way that Sprites do. You add and play animations using the AnimationManager. However
  49304. * if your game is running under WebGL please note that each frame of the animation must be a power of two in size, or it will receive
  49305. * additional padding to enforce it to be so.
  49306. *
  49307. * @class Phaser.TileSprite
  49308. * @constructor
  49309. * @extends PIXI.TilingSprite
  49310. * @extends Phaser.Component.Core
  49311. * @extends Phaser.Component.Angle
  49312. * @extends Phaser.Component.Animation
  49313. * @extends Phaser.Component.AutoCull
  49314. * @extends Phaser.Component.Bounds
  49315. * @extends Phaser.Component.BringToTop
  49316. * @extends Phaser.Component.Destroy
  49317. * @extends Phaser.Component.FixedToCamera
  49318. * @extends Phaser.Component.Health
  49319. * @extends Phaser.Component.InCamera
  49320. * @extends Phaser.Component.InputEnabled
  49321. * @extends Phaser.Component.InWorld
  49322. * @extends Phaser.Component.LifeSpan
  49323. * @extends Phaser.Component.LoadTexture
  49324. * @extends Phaser.Component.Overlap
  49325. * @extends Phaser.Component.PhysicsBody
  49326. * @extends Phaser.Component.Reset
  49327. * @extends Phaser.Component.Smoothed
  49328. * @param {Phaser.Game} game - A reference to the currently running game.
  49329. * @param {number} x - The x coordinate (in world space) to position the TileSprite at.
  49330. * @param {number} y - The y coordinate (in world space) to position the TileSprite at.
  49331. * @param {number} width - The width of the TileSprite.
  49332. * @param {number} height - The height of the TileSprite.
  49333. * @param {string|Phaser.BitmapData|PIXI.Texture} key - This is the image or texture used by the TileSprite during rendering. It can be a string which is a reference to the Phaser Image Cache entry, or an instance of a PIXI.Texture or BitmapData.
  49334. * @param {string|number} frame - If this TileSprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index.
  49335. */
  49336. Phaser.TileSprite = function (game, x, y, width, height, key, frame) {
  49337. x = x || 0;
  49338. y = y || 0;
  49339. width = width || 256;
  49340. height = height || 256;
  49341. key = key || null;
  49342. frame = frame || null;
  49343. /**
  49344. * @property {number} type - The const type of this object.
  49345. * @readonly
  49346. */
  49347. this.type = Phaser.TILESPRITE;
  49348. /**
  49349. * @property {number} physicsType - The const physics body type of this object.
  49350. * @readonly
  49351. */
  49352. this.physicsType = Phaser.SPRITE;
  49353. /**
  49354. * @property {Phaser.Point} _scroll - Internal cache var.
  49355. * @private
  49356. */
  49357. this._scroll = new Phaser.Point();
  49358. var def = game.cache.getImage('__default', true);
  49359. PIXI.TilingSprite.call(this, new PIXI.Texture(def.base), width, height);
  49360. Phaser.Component.Core.init.call(this, game, x, y, key, frame);
  49361. };
  49362. Phaser.TileSprite.prototype = Object.create(PIXI.TilingSprite.prototype);
  49363. Phaser.TileSprite.prototype.constructor = Phaser.TileSprite;
  49364. Phaser.Component.Core.install.call(Phaser.TileSprite.prototype, [
  49365. 'Angle',
  49366. 'Animation',
  49367. 'AutoCull',
  49368. 'Bounds',
  49369. 'BringToTop',
  49370. 'Destroy',
  49371. 'FixedToCamera',
  49372. 'Health',
  49373. 'InCamera',
  49374. 'InputEnabled',
  49375. 'InWorld',
  49376. 'LifeSpan',
  49377. 'LoadTexture',
  49378. 'Overlap',
  49379. 'PhysicsBody',
  49380. 'Reset',
  49381. 'Smoothed'
  49382. ]);
  49383. Phaser.TileSprite.prototype.preUpdatePhysics = Phaser.Component.PhysicsBody.preUpdate;
  49384. Phaser.TileSprite.prototype.preUpdateLifeSpan = Phaser.Component.LifeSpan.preUpdate;
  49385. Phaser.TileSprite.prototype.preUpdateInWorld = Phaser.Component.InWorld.preUpdate;
  49386. Phaser.TileSprite.prototype.preUpdateCore = Phaser.Component.Core.preUpdate;
  49387. /**
  49388. * Automatically called by World.preUpdate.
  49389. *
  49390. * @method Phaser.TileSprite#preUpdate
  49391. * @memberof Phaser.TileSprite
  49392. */
  49393. Phaser.TileSprite.prototype.preUpdate = function() {
  49394. if (this._scroll.x !== 0)
  49395. {
  49396. this.tilePosition.x += this._scroll.x * this.game.time.physicsElapsed;
  49397. }
  49398. if (this._scroll.y !== 0)
  49399. {
  49400. this.tilePosition.y += this._scroll.y * this.game.time.physicsElapsed;
  49401. }
  49402. if (!this.preUpdatePhysics() || !this.preUpdateLifeSpan() || !this.preUpdateInWorld())
  49403. {
  49404. return false;
  49405. }
  49406. return this.preUpdateCore();
  49407. };
  49408. /**
  49409. * Sets this TileSprite to automatically scroll in the given direction until stopped via TileSprite.stopScroll().
  49410. * The scroll speed is specified in pixels per second.
  49411. * A negative x value will scroll to the left. A positive x value will scroll to the right.
  49412. * A negative y value will scroll up. A positive y value will scroll down.
  49413. *
  49414. * @method Phaser.TileSprite#autoScroll
  49415. * @memberof Phaser.TileSprite
  49416. * @param {number} x - Horizontal scroll speed in pixels per second.
  49417. * @param {number} y - Vertical scroll speed in pixels per second.
  49418. */
  49419. Phaser.TileSprite.prototype.autoScroll = function(x, y) {
  49420. this._scroll.set(x, y);
  49421. };
  49422. /**
  49423. * Stops an automatically scrolling TileSprite.
  49424. *
  49425. * @method Phaser.TileSprite#stopScroll
  49426. * @memberof Phaser.TileSprite
  49427. */
  49428. Phaser.TileSprite.prototype.stopScroll = function() {
  49429. this._scroll.set(0, 0);
  49430. };
  49431. /**
  49432. * Destroys the TileSprite. This removes it from its parent group, destroys the event and animation handlers if present
  49433. * and nulls its reference to game, freeing it up for garbage collection.
  49434. *
  49435. * @method Phaser.TileSprite#destroy
  49436. * @memberof Phaser.TileSprite
  49437. * @param {boolean} [destroyChildren=true] - Should every child of this object have its destroy method called?
  49438. */
  49439. Phaser.TileSprite.prototype.destroy = function(destroyChildren) {
  49440. Phaser.Component.Destroy.prototype.destroy.call(this, destroyChildren);
  49441. PIXI.TilingSprite.prototype.destroy.call(this);
  49442. };
  49443. /**
  49444. * Resets the TileSprite. This places the TileSprite at the given x/y world coordinates, resets the tilePosition and then
  49445. * sets alive, exists, visible and renderable all to true. Also resets the outOfBounds state.
  49446. * If the TileSprite has a physics body that too is reset.
  49447. *
  49448. * @method Phaser.TileSprite#reset
  49449. * @memberof Phaser.TileSprite
  49450. * @param {number} x - The x coordinate (in world space) to position the Sprite at.
  49451. * @param {number} y - The y coordinate (in world space) to position the Sprite at.
  49452. * @return {Phaser.TileSprite} This instance.
  49453. */
  49454. Phaser.TileSprite.prototype.reset = function(x, y) {
  49455. Phaser.Component.Reset.prototype.reset.call(this, x, y);
  49456. this.tilePosition.x = 0;
  49457. this.tilePosition.y = 0;
  49458. return this;
  49459. };
  49460. /**
  49461. * @author Richard Davey <rich@photonstorm.com>
  49462. * @copyright 2016 Photon Storm Ltd.
  49463. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  49464. */
  49465. /**
  49466. * @classdesc
  49467. * Detects device support capabilities and is responsible for device initialization - see {@link Phaser.Device.whenReady whenReady}.
  49468. *
  49469. * This class represents a singleton object that can be accessed directly as `game.device`
  49470. * (or, as a fallback, `Phaser.Device` when a game instance is not available) without the need to instantiate it.
  49471. *
  49472. * Unless otherwise noted the device capabilities are only guaranteed after initialization. Initialization
  49473. * occurs automatically and is guaranteed complete before {@link Phaser.Game} begins its "boot" phase.
  49474. * Feature detection can be modified in the {@link Phaser.Device.onInitialized onInitialized} signal.
  49475. *
  49476. * When checking features using the exposed properties only the *truth-iness* of the value should be relied upon
  49477. * unless the documentation states otherwise: properties may return `false`, `''`, `null`, or even `undefined`
  49478. * when indicating the lack of a feature.
  49479. *
  49480. * Uses elements from System.js by MrDoob and Modernizr
  49481. *
  49482. * @description
  49483. * It is not possible to instantiate the Device class manually.
  49484. *
  49485. * @class
  49486. * @protected
  49487. */
  49488. Phaser.Device = function () {
  49489. /**
  49490. * The time the device became ready.
  49491. * @property {integer} deviceReadyAt
  49492. * @protected
  49493. */
  49494. this.deviceReadyAt = 0;
  49495. /**
  49496. * The time as which initialization has completed.
  49497. * @property {boolean} initialized
  49498. * @protected
  49499. */
  49500. this.initialized = false;
  49501. // Browser / Host / Operating System
  49502. /**
  49503. * @property {boolean} desktop - Is running on a desktop?
  49504. * @default
  49505. */
  49506. this.desktop = false;
  49507. /**
  49508. * @property {boolean} iOS - Is running on iOS?
  49509. * @default
  49510. */
  49511. this.iOS = false;
  49512. /**
  49513. * @property {number} iOSVersion - If running in iOS this will contain the major version number.
  49514. * @default
  49515. */
  49516. this.iOSVersion = 0;
  49517. /**
  49518. * @property {boolean} cocoonJS - Is the game running under CocoonJS?
  49519. * @default
  49520. */
  49521. this.cocoonJS = false;
  49522. /**
  49523. * @property {boolean} cocoonJSApp - Is this game running with CocoonJS.App?
  49524. * @default
  49525. */
  49526. this.cocoonJSApp = false;
  49527. /**
  49528. * @property {boolean} cordova - Is the game running under Apache Cordova?
  49529. * @default
  49530. */
  49531. this.cordova = false;
  49532. /**
  49533. * @property {boolean} node - Is the game running under Node.js?
  49534. * @default
  49535. */
  49536. this.node = false;
  49537. /**
  49538. * @property {boolean} nodeWebkit - Is the game running under Node-Webkit?
  49539. * @default
  49540. */
  49541. this.nodeWebkit = false;
  49542. /**
  49543. * @property {boolean} electron - Is the game running under GitHub Electron?
  49544. * @default
  49545. */
  49546. this.electron = false;
  49547. /**
  49548. * @property {boolean} ejecta - Is the game running under Ejecta?
  49549. * @default
  49550. */
  49551. this.ejecta = false;
  49552. /**
  49553. * @property {boolean} crosswalk - Is the game running under the Intel Crosswalk XDK?
  49554. * @default
  49555. */
  49556. this.crosswalk = false;
  49557. /**
  49558. * @property {boolean} android - Is running on android?
  49559. * @default
  49560. */
  49561. this.android = false;
  49562. /**
  49563. * @property {boolean} chromeOS - Is running on chromeOS?
  49564. * @default
  49565. */
  49566. this.chromeOS = false;
  49567. /**
  49568. * @property {boolean} linux - Is running on linux?
  49569. * @default
  49570. */
  49571. this.linux = false;
  49572. /**
  49573. * @property {boolean} macOS - Is running on macOS?
  49574. * @default
  49575. */
  49576. this.macOS = false;
  49577. /**
  49578. * @property {boolean} windows - Is running on windows?
  49579. * @default
  49580. */
  49581. this.windows = false;
  49582. /**
  49583. * @property {boolean} windowsPhone - Is running on a Windows Phone?
  49584. * @default
  49585. */
  49586. this.windowsPhone = false;
  49587. // Features
  49588. /**
  49589. * @property {boolean} canvas - Is canvas available?
  49590. * @default
  49591. */
  49592. this.canvas = false;
  49593. /**
  49594. * @property {?boolean} canvasBitBltShift - True if canvas supports a 'copy' bitblt onto itself when the source and destination regions overlap.
  49595. * @default
  49596. */
  49597. this.canvasBitBltShift = null;
  49598. /**
  49599. * @property {boolean} webGL - Is webGL available?
  49600. * @default
  49601. */
  49602. this.webGL = false;
  49603. /**
  49604. * @property {boolean} file - Is file available?
  49605. * @default
  49606. */
  49607. this.file = false;
  49608. /**
  49609. * @property {boolean} fileSystem - Is fileSystem available?
  49610. * @default
  49611. */
  49612. this.fileSystem = false;
  49613. /**
  49614. * @property {boolean} localStorage - Is localStorage available?
  49615. * @default
  49616. */
  49617. this.localStorage = false;
  49618. /**
  49619. * @property {boolean} worker - Is worker available?
  49620. * @default
  49621. */
  49622. this.worker = false;
  49623. /**
  49624. * @property {boolean} css3D - Is css3D available?
  49625. * @default
  49626. */
  49627. this.css3D = false;
  49628. /**
  49629. * @property {boolean} pointerLock - Is Pointer Lock available?
  49630. * @default
  49631. */
  49632. this.pointerLock = false;
  49633. /**
  49634. * @property {boolean} typedArray - Does the browser support TypedArrays?
  49635. * @default
  49636. */
  49637. this.typedArray = false;
  49638. /**
  49639. * @property {boolean} vibration - Does the device support the Vibration API?
  49640. * @default
  49641. */
  49642. this.vibration = false;
  49643. /**
  49644. * @property {boolean} getUserMedia - Does the device support the getUserMedia API?
  49645. * @default
  49646. */
  49647. this.getUserMedia = true;
  49648. /**
  49649. * @property {boolean} quirksMode - Is the browser running in strict mode (false) or quirks mode? (true)
  49650. * @default
  49651. */
  49652. this.quirksMode = false;
  49653. // Input
  49654. /**
  49655. * @property {boolean} touch - Is touch available?
  49656. * @default
  49657. */
  49658. this.touch = false;
  49659. /**
  49660. * @property {boolean} mspointer - Is mspointer available?
  49661. * @default
  49662. */
  49663. this.mspointer = false;
  49664. /**
  49665. * @property {?string} wheelType - The newest type of Wheel/Scroll event supported: 'wheel', 'mousewheel', 'DOMMouseScroll'
  49666. * @default
  49667. * @protected
  49668. */
  49669. this.wheelEvent = null;
  49670. // Browser
  49671. /**
  49672. * @property {boolean} arora - Set to true if running in Arora.
  49673. * @default
  49674. */
  49675. this.arora = false;
  49676. /**
  49677. * @property {boolean} chrome - Set to true if running in Chrome.
  49678. * @default
  49679. */
  49680. this.chrome = false;
  49681. /**
  49682. * @property {number} chromeVersion - If running in Chrome this will contain the major version number.
  49683. * @default
  49684. */
  49685. this.chromeVersion = 0;
  49686. /**
  49687. * @property {boolean} epiphany - Set to true if running in Epiphany.
  49688. * @default
  49689. */
  49690. this.epiphany = false;
  49691. /**
  49692. * @property {boolean} firefox - Set to true if running in Firefox.
  49693. * @default
  49694. */
  49695. this.firefox = false;
  49696. /**
  49697. * @property {number} firefoxVersion - If running in Firefox this will contain the major version number.
  49698. * @default
  49699. */
  49700. this.firefoxVersion = 0;
  49701. /**
  49702. * @property {boolean} ie - Set to true if running in Internet Explorer.
  49703. * @default
  49704. */
  49705. this.ie = false;
  49706. /**
  49707. * @property {number} ieVersion - If running in Internet Explorer this will contain the major version number. Beyond IE10 you should use Device.trident and Device.tridentVersion.
  49708. * @default
  49709. */
  49710. this.ieVersion = 0;
  49711. /**
  49712. * @property {boolean} trident - Set to true if running a Trident version of Internet Explorer (IE11+)
  49713. * @default
  49714. */
  49715. this.trident = false;
  49716. /**
  49717. * @property {number} tridentVersion - If running in Internet Explorer 11 this will contain the major version number. See {@link http://msdn.microsoft.com/en-us/library/ie/ms537503(v=vs.85).aspx}
  49718. * @default
  49719. */
  49720. this.tridentVersion = 0;
  49721. /**
  49722. * @property {boolean} edge - Set to true if running in Microsoft Edge browser.
  49723. * @default
  49724. */
  49725. this.edge = false;
  49726. /**
  49727. * @property {boolean} mobileSafari - Set to true if running in Mobile Safari.
  49728. * @default
  49729. */
  49730. this.mobileSafari = false;
  49731. /**
  49732. * @property {boolean} midori - Set to true if running in Midori.
  49733. * @default
  49734. */
  49735. this.midori = false;
  49736. /**
  49737. * @property {boolean} opera - Set to true if running in Opera.
  49738. * @default
  49739. */
  49740. this.opera = false;
  49741. /**
  49742. * @property {boolean} safari - Set to true if running in Safari.
  49743. * @default
  49744. */
  49745. this.safari = false;
  49746. /**
  49747. * @property {number} safariVersion - If running in Safari this will contain the major version number.
  49748. * @default
  49749. */
  49750. this.safariVersion = 0;
  49751. /**
  49752. * @property {boolean} webApp - Set to true if running as a WebApp, i.e. within a WebView
  49753. * @default
  49754. */
  49755. this.webApp = false;
  49756. /**
  49757. * @property {boolean} silk - Set to true if running in the Silk browser (as used on the Amazon Kindle)
  49758. * @default
  49759. */
  49760. this.silk = false;
  49761. // Audio
  49762. /**
  49763. * @property {boolean} audioData - Are Audio tags available?
  49764. * @default
  49765. */
  49766. this.audioData = false;
  49767. /**
  49768. * @property {boolean} webAudio - Is the WebAudio API available?
  49769. * @default
  49770. */
  49771. this.webAudio = false;
  49772. /**
  49773. * @property {boolean} ogg - Can this device play ogg files?
  49774. * @default
  49775. */
  49776. this.ogg = false;
  49777. /**
  49778. * @property {boolean} opus - Can this device play opus files?
  49779. * @default
  49780. */
  49781. this.opus = false;
  49782. /**
  49783. * @property {boolean} mp3 - Can this device play mp3 files?
  49784. * @default
  49785. */
  49786. this.mp3 = false;
  49787. /**
  49788. * @property {boolean} wav - Can this device play wav files?
  49789. * @default
  49790. */
  49791. this.wav = false;
  49792. /**
  49793. * Can this device play m4a files?
  49794. * @property {boolean} m4a - True if this device can play m4a files.
  49795. * @default
  49796. */
  49797. this.m4a = false;
  49798. /**
  49799. * @property {boolean} webm - Can this device play webm files?
  49800. * @default
  49801. */
  49802. this.webm = false;
  49803. /**
  49804. * @property {boolean} dolby - Can this device play EC-3 Dolby Digital Plus files?
  49805. * @default
  49806. */
  49807. this.dolby = false;
  49808. // Video
  49809. /**
  49810. * @property {boolean} oggVideo - Can this device play ogg video files?
  49811. * @default
  49812. */
  49813. this.oggVideo = false;
  49814. /**
  49815. * @property {boolean} h264Video - Can this device play h264 mp4 video files?
  49816. * @default
  49817. */
  49818. this.h264Video = false;
  49819. /**
  49820. * @property {boolean} mp4Video - Can this device play h264 mp4 video files?
  49821. * @default
  49822. */
  49823. this.mp4Video = false;
  49824. /**
  49825. * @property {boolean} webmVideo - Can this device play webm video files?
  49826. * @default
  49827. */
  49828. this.webmVideo = false;
  49829. /**
  49830. * @property {boolean} vp9Video - Can this device play vp9 video files?
  49831. * @default
  49832. */
  49833. this.vp9Video = false;
  49834. /**
  49835. * @property {boolean} hlsVideo - Can this device play hls video files?
  49836. * @default
  49837. */
  49838. this.hlsVideo = false;
  49839. // Device
  49840. /**
  49841. * @property {boolean} iPhone - Is running on iPhone?
  49842. * @default
  49843. */
  49844. this.iPhone = false;
  49845. /**
  49846. * @property {boolean} iPhone4 - Is running on iPhone4?
  49847. * @default
  49848. */
  49849. this.iPhone4 = false;
  49850. /**
  49851. * @property {boolean} iPad - Is running on iPad?
  49852. * @default
  49853. */
  49854. this.iPad = false;
  49855. // Device features
  49856. /**
  49857. * @property {number} pixelRatio - PixelRatio of the host device?
  49858. * @default
  49859. */
  49860. this.pixelRatio = 0;
  49861. /**
  49862. * @property {boolean} littleEndian - Is the device big or little endian? (only detected if the browser supports TypedArrays)
  49863. * @default
  49864. */
  49865. this.littleEndian = false;
  49866. /**
  49867. * @property {boolean} LITTLE_ENDIAN - Same value as `littleEndian`.
  49868. * @default
  49869. */
  49870. this.LITTLE_ENDIAN = false;
  49871. /**
  49872. * @property {boolean} support32bit - Does the device context support 32bit pixel manipulation using array buffer views?
  49873. * @default
  49874. */
  49875. this.support32bit = false;
  49876. /**
  49877. * @property {boolean} fullscreen - Does the browser support the Full Screen API?
  49878. * @default
  49879. */
  49880. this.fullscreen = false;
  49881. /**
  49882. * @property {string} requestFullscreen - If the browser supports the Full Screen API this holds the call you need to use to activate it.
  49883. * @default
  49884. */
  49885. this.requestFullscreen = '';
  49886. /**
  49887. * @property {string} cancelFullscreen - If the browser supports the Full Screen API this holds the call you need to use to cancel it.
  49888. * @default
  49889. */
  49890. this.cancelFullscreen = '';
  49891. /**
  49892. * @property {boolean} fullscreenKeyboard - Does the browser support access to the Keyboard during Full Screen mode?
  49893. * @default
  49894. */
  49895. this.fullscreenKeyboard = false;
  49896. };
  49897. // Device is really a singleton/static entity; instantiate it
  49898. // and add new methods directly sans-prototype.
  49899. Phaser.Device = new Phaser.Device();
  49900. /**
  49901. * This signal is dispatched after device initialization occurs but before any of the ready
  49902. * callbacks (see {@link Phaser.Device.whenReady whenReady}) have been invoked.
  49903. *
  49904. * Local "patching" for a particular device can/should be done in this event.
  49905. *
  49906. * _Note_: This signal is removed after the device has been readied; if a handler has not been
  49907. * added _before_ `new Phaser.Game(..)` it is probably too late.
  49908. *
  49909. * @type {?Phaser.Signal}
  49910. * @static
  49911. */
  49912. Phaser.Device.onInitialized = new Phaser.Signal();
  49913. /**
  49914. * Add a device-ready handler and ensure the device ready sequence is started.
  49915. *
  49916. * Phaser.Device will _not_ activate or initialize until at least one `whenReady` handler is added,
  49917. * which is normally done automatically be calling `new Phaser.Game(..)`.
  49918. *
  49919. * The handler is invoked when the device is considered "ready", which may be immediately
  49920. * if the device is already "ready". See {@link Phaser.Device#deviceReadyAt deviceReadyAt}.
  49921. *
  49922. * @method
  49923. * @param {function} handler - Callback to invoke when the device is ready. It is invoked with the given context the Phaser.Device object is supplied as the first argument.
  49924. * @param {object} [context] - Context in which to invoke the handler
  49925. * @param {boolean} [nonPrimer=false] - If true the device ready check will not be started.
  49926. */
  49927. Phaser.Device.whenReady = function (callback, context, nonPrimer) {
  49928. var readyCheck = this._readyCheck;
  49929. if (this.deviceReadyAt || !readyCheck)
  49930. {
  49931. callback.call(context, this);
  49932. }
  49933. else if (readyCheck._monitor || nonPrimer)
  49934. {
  49935. readyCheck._queue = readyCheck._queue || [];
  49936. readyCheck._queue.push([callback, context]);
  49937. }
  49938. else
  49939. {
  49940. readyCheck._monitor = readyCheck.bind(this);
  49941. readyCheck._queue = readyCheck._queue || [];
  49942. readyCheck._queue.push([callback, context]);
  49943. var cordova = typeof window.cordova !== 'undefined';
  49944. var cocoonJS = navigator['isCocoonJS'];
  49945. if (document.readyState === 'complete' || document.readyState === 'interactive')
  49946. {
  49947. // Why is there an additional timeout here?
  49948. window.setTimeout(readyCheck._monitor, 0);
  49949. }
  49950. else if (cordova && !cocoonJS)
  49951. {
  49952. // Ref. http://docs.phonegap.com/en/3.5.0/cordova_events_events.md.html#deviceready
  49953. // Cordova, but NOT Cocoon?
  49954. document.addEventListener('deviceready', readyCheck._monitor, false);
  49955. }
  49956. else
  49957. {
  49958. document.addEventListener('DOMContentLoaded', readyCheck._monitor, false);
  49959. window.addEventListener('load', readyCheck._monitor, false);
  49960. }
  49961. }
  49962. };
  49963. /**
  49964. * Internal method used for checking when the device is ready.
  49965. * This function is removed from Phaser.Device when the device becomes ready.
  49966. *
  49967. * @method
  49968. * @private
  49969. */
  49970. Phaser.Device._readyCheck = function () {
  49971. var readyCheck = this._readyCheck;
  49972. if (!document.body)
  49973. {
  49974. window.setTimeout(readyCheck._monitor, 20);
  49975. }
  49976. else if (!this.deviceReadyAt)
  49977. {
  49978. this.deviceReadyAt = Date.now();
  49979. document.removeEventListener('deviceready', readyCheck._monitor);
  49980. document.removeEventListener('DOMContentLoaded', readyCheck._monitor);
  49981. window.removeEventListener('load', readyCheck._monitor);
  49982. this._initialize();
  49983. this.initialized = true;
  49984. this.onInitialized.dispatch(this);
  49985. var item;
  49986. while ((item = readyCheck._queue.shift()))
  49987. {
  49988. var callback = item[0];
  49989. var context = item[1];
  49990. callback.call(context, this);
  49991. }
  49992. // Remove no longer useful methods and properties.
  49993. this._readyCheck = null;
  49994. this._initialize = null;
  49995. this.onInitialized = null;
  49996. }
  49997. };
  49998. /**
  49999. * Internal method to initialize the capability checks.
  50000. * This function is removed from Phaser.Device once the device is initialized.
  50001. *
  50002. * @method
  50003. * @private
  50004. */
  50005. Phaser.Device._initialize = function () {
  50006. var device = this;
  50007. /**
  50008. * Check which OS is game running on.
  50009. */
  50010. function _checkOS () {
  50011. var ua = navigator.userAgent;
  50012. if (/Playstation Vita/.test(ua))
  50013. {
  50014. device.vita = true;
  50015. }
  50016. else if (/Kindle/.test(ua) || /\bKF[A-Z][A-Z]+/.test(ua) || /Silk.*Mobile Safari/.test(ua))
  50017. {
  50018. device.kindle = true;
  50019. // This will NOT detect early generations of Kindle Fire, I think there is no reliable way...
  50020. // E.g. "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_3; en-us; Silk/1.1.0-80) AppleWebKit/533.16 (KHTML, like Gecko) Version/5.0 Safari/533.16 Silk-Accelerated=true"
  50021. }
  50022. else if (/Android/.test(ua))
  50023. {
  50024. device.android = true;
  50025. }
  50026. else if (/CrOS/.test(ua))
  50027. {
  50028. device.chromeOS = true;
  50029. }
  50030. else if (/iP[ao]d|iPhone/i.test(ua))
  50031. {
  50032. device.iOS = true;
  50033. (navigator.appVersion).match(/OS (\d+)/);
  50034. device.iOSVersion = parseInt(RegExp.$1, 10);
  50035. }
  50036. else if (/Linux/.test(ua))
  50037. {
  50038. device.linux = true;
  50039. }
  50040. else if (/Mac OS/.test(ua))
  50041. {
  50042. device.macOS = true;
  50043. }
  50044. else if (/Windows/.test(ua))
  50045. {
  50046. device.windows = true;
  50047. }
  50048. if (/Windows Phone/i.test(ua) || /IEMobile/i.test(ua))
  50049. {
  50050. device.android = false;
  50051. device.iOS = false;
  50052. device.macOS = false;
  50053. device.windows = true;
  50054. device.windowsPhone = true;
  50055. }
  50056. var silk = /Silk/.test(ua); // detected in browsers
  50057. if (device.windows || device.macOS || (device.linux && !silk) || device.chromeOS)
  50058. {
  50059. device.desktop = true;
  50060. }
  50061. // Windows Phone / Table reset
  50062. if (device.windowsPhone || ((/Windows NT/i.test(ua)) && (/Touch/i.test(ua))))
  50063. {
  50064. device.desktop = false;
  50065. }
  50066. }
  50067. /**
  50068. * Check HTML5 features of the host environment.
  50069. */
  50070. function _checkFeatures () {
  50071. device.canvas = !!window['CanvasRenderingContext2D'] || device.cocoonJS;
  50072. try {
  50073. device.localStorage = !!localStorage.getItem;
  50074. } catch (error) {
  50075. device.localStorage = false;
  50076. }
  50077. device.file = !!window['File'] && !!window['FileReader'] && !!window['FileList'] && !!window['Blob'];
  50078. device.fileSystem = !!window['requestFileSystem'];
  50079. device.webGL = ( function () { try { var canvas = document.createElement( 'canvas' ); /*Force screencanvas to false*/ canvas.screencanvas = false; return !! window.WebGLRenderingContext && ( canvas.getContext( 'webgl' ) || canvas.getContext( 'experimental-webgl' ) ); } catch( e ) { return false; } } )();
  50080. device.webGL = !!device.webGL;
  50081. device.worker = !!window['Worker'];
  50082. device.pointerLock = 'pointerLockElement' in document || 'mozPointerLockElement' in document || 'webkitPointerLockElement' in document;
  50083. device.quirksMode = (document.compatMode === 'CSS1Compat') ? false : true;
  50084. navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia || navigator.oGetUserMedia;
  50085. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  50086. device.getUserMedia = device.getUserMedia && !!navigator.getUserMedia && !!window.URL;
  50087. // Older versions of firefox (< 21) apparently claim support but user media does not actually work
  50088. if (device.firefox && device.firefoxVersion < 21)
  50089. {
  50090. device.getUserMedia = false;
  50091. }
  50092. // TODO: replace canvasBitBltShift detection with actual feature check
  50093. // Excludes iOS versions as they generally wrap UIWebView (eg. Safari WebKit) and it
  50094. // is safer to not try and use the fast copy-over method.
  50095. if (!device.iOS && (device.ie || device.firefox || device.chrome))
  50096. {
  50097. device.canvasBitBltShift = true;
  50098. }
  50099. // Known not to work
  50100. if (device.safari || device.mobileSafari)
  50101. {
  50102. device.canvasBitBltShift = false;
  50103. }
  50104. }
  50105. /**
  50106. * Checks/configures various input.
  50107. */
  50108. function _checkInput () {
  50109. if ('ontouchstart' in document.documentElement || (window.navigator.maxTouchPoints && window.navigator.maxTouchPoints >= 1))
  50110. {
  50111. device.touch = true;
  50112. }
  50113. if (window.navigator.msPointerEnabled || window.navigator.pointerEnabled)
  50114. {
  50115. device.mspointer = true;
  50116. }
  50117. if (!device.cocoonJS)
  50118. {
  50119. // See https://developer.mozilla.org/en-US/docs/Web/Events/wheel
  50120. if ('onwheel' in window || (device.ie && 'WheelEvent' in window))
  50121. {
  50122. // DOM3 Wheel Event: FF 17+, IE 9+, Chrome 31+, Safari 7+
  50123. device.wheelEvent = 'wheel';
  50124. }
  50125. else if ('onmousewheel' in window)
  50126. {
  50127. // Non-FF legacy: IE 6-9, Chrome 1-31, Safari 5-7.
  50128. device.wheelEvent = 'mousewheel';
  50129. }
  50130. else if (device.firefox && 'MouseScrollEvent' in window)
  50131. {
  50132. // FF prior to 17. This should probably be scrubbed.
  50133. device.wheelEvent = 'DOMMouseScroll';
  50134. }
  50135. }
  50136. }
  50137. /**
  50138. * Checks for support of the Full Screen API.
  50139. */
  50140. function _checkFullScreenSupport () {
  50141. var fs = [
  50142. 'requestFullscreen',
  50143. 'requestFullScreen',
  50144. 'webkitRequestFullscreen',
  50145. 'webkitRequestFullScreen',
  50146. 'msRequestFullscreen',
  50147. 'msRequestFullScreen',
  50148. 'mozRequestFullScreen',
  50149. 'mozRequestFullscreen'
  50150. ];
  50151. var element = document.createElement('div');
  50152. for (var i = 0; i < fs.length; i++)
  50153. {
  50154. if (element[fs[i]])
  50155. {
  50156. device.fullscreen = true;
  50157. device.requestFullscreen = fs[i];
  50158. break;
  50159. }
  50160. }
  50161. var cfs = [
  50162. 'cancelFullScreen',
  50163. 'exitFullscreen',
  50164. 'webkitCancelFullScreen',
  50165. 'webkitExitFullscreen',
  50166. 'msCancelFullScreen',
  50167. 'msExitFullscreen',
  50168. 'mozCancelFullScreen',
  50169. 'mozExitFullscreen'
  50170. ];
  50171. if (device.fullscreen)
  50172. {
  50173. for (var i = 0; i < cfs.length; i++)
  50174. {
  50175. if (document[cfs[i]])
  50176. {
  50177. device.cancelFullscreen = cfs[i];
  50178. break;
  50179. }
  50180. }
  50181. }
  50182. // Keyboard Input?
  50183. if (window['Element'] && Element['ALLOW_KEYBOARD_INPUT'])
  50184. {
  50185. device.fullscreenKeyboard = true;
  50186. }
  50187. }
  50188. /**
  50189. * Check what browser is game running in.
  50190. */
  50191. function _checkBrowser () {
  50192. var ua = navigator.userAgent;
  50193. if (/Arora/.test(ua))
  50194. {
  50195. device.arora = true;
  50196. }
  50197. else if (/Edge\/\d+/.test(ua))
  50198. {
  50199. device.edge = true;
  50200. }
  50201. else if (/Chrome\/(\d+)/.test(ua) && !device.windowsPhone)
  50202. {
  50203. device.chrome = true;
  50204. device.chromeVersion = parseInt(RegExp.$1, 10);
  50205. }
  50206. else if (/Epiphany/.test(ua))
  50207. {
  50208. device.epiphany = true;
  50209. }
  50210. else if (/Firefox\D+(\d+)/.test(ua))
  50211. {
  50212. device.firefox = true;
  50213. device.firefoxVersion = parseInt(RegExp.$1, 10);
  50214. }
  50215. else if (/AppleWebKit/.test(ua) && device.iOS)
  50216. {
  50217. device.mobileSafari = true;
  50218. }
  50219. else if (/MSIE (\d+\.\d+);/.test(ua))
  50220. {
  50221. device.ie = true;
  50222. device.ieVersion = parseInt(RegExp.$1, 10);
  50223. }
  50224. else if (/Midori/.test(ua))
  50225. {
  50226. device.midori = true;
  50227. }
  50228. else if (/Opera/.test(ua))
  50229. {
  50230. device.opera = true;
  50231. }
  50232. else if (/Safari\/(\d+)/.test(ua) && !device.windowsPhone)
  50233. {
  50234. device.safari = true;
  50235. if (/Version\/(\d+)\./.test(ua))
  50236. {
  50237. device.safariVersion = parseInt(RegExp.$1, 10);
  50238. }
  50239. }
  50240. else if (/Trident\/(\d+\.\d+)(.*)rv:(\d+\.\d+)/.test(ua))
  50241. {
  50242. device.ie = true;
  50243. device.trident = true;
  50244. device.tridentVersion = parseInt(RegExp.$1, 10);
  50245. device.ieVersion = parseInt(RegExp.$3, 10);
  50246. }
  50247. // Silk gets its own if clause because its ua also contains 'Safari'
  50248. if (/Silk/.test(ua))
  50249. {
  50250. device.silk = true;
  50251. }
  50252. // WebApp mode in iOS
  50253. if (navigator['standalone'])
  50254. {
  50255. device.webApp = true;
  50256. }
  50257. if (typeof window.cordova !== 'undefined')
  50258. {
  50259. device.cordova = true;
  50260. }
  50261. if (typeof process !== 'undefined' && typeof require !== 'undefined')
  50262. {
  50263. device.node = true;
  50264. }
  50265. if (device.node && typeof process.versions === 'object')
  50266. {
  50267. device.nodeWebkit = !!process.versions['node-webkit'];
  50268. device.electron = !!process.versions.electron;
  50269. }
  50270. if (navigator['isCocoonJS'])
  50271. {
  50272. device.cocoonJS = true;
  50273. }
  50274. if (device.cocoonJS)
  50275. {
  50276. try {
  50277. device.cocoonJSApp = (typeof CocoonJS !== 'undefined');
  50278. }
  50279. catch(error)
  50280. {
  50281. device.cocoonJSApp = false;
  50282. }
  50283. }
  50284. if (typeof window.ejecta !== 'undefined')
  50285. {
  50286. device.ejecta = true;
  50287. }
  50288. if (/Crosswalk/.test(ua))
  50289. {
  50290. device.crosswalk = true;
  50291. }
  50292. }
  50293. /**
  50294. * Check video support.
  50295. */
  50296. function _checkVideo () {
  50297. var videoElement = document.createElement("video");
  50298. var result = false;
  50299. try {
  50300. if (result = !!videoElement.canPlayType)
  50301. {
  50302. if (videoElement.canPlayType('video/ogg; codecs="theora"').replace(/^no$/, ''))
  50303. {
  50304. device.oggVideo = true;
  50305. }
  50306. if (videoElement.canPlayType('video/mp4; codecs="avc1.42E01E"').replace(/^no$/, ''))
  50307. {
  50308. // Without QuickTime, this value will be `undefined`. github.com/Modernizr/Modernizr/issues/546
  50309. device.h264Video = true;
  50310. device.mp4Video = true;
  50311. }
  50312. if (videoElement.canPlayType('video/webm; codecs="vp8, vorbis"').replace(/^no$/, ''))
  50313. {
  50314. device.webmVideo = true;
  50315. }
  50316. if (videoElement.canPlayType('video/webm; codecs="vp9"').replace(/^no$/, ''))
  50317. {
  50318. device.vp9Video = true;
  50319. }
  50320. if (videoElement.canPlayType('application/x-mpegURL; codecs="avc1.42E01E"').replace(/^no$/, ''))
  50321. {
  50322. device.hlsVideo = true;
  50323. }
  50324. }
  50325. } catch (e) {}
  50326. }
  50327. /**
  50328. * Check audio support.
  50329. */
  50330. function _checkAudio () {
  50331. device.audioData = !!(window['Audio']);
  50332. device.webAudio = !!(window['AudioContext'] || window['webkitAudioContext']);
  50333. var audioElement = document.createElement('audio');
  50334. var result = false;
  50335. try {
  50336. if (result = !!audioElement.canPlayType)
  50337. {
  50338. if (audioElement.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, ''))
  50339. {
  50340. device.ogg = true;
  50341. }
  50342. if (audioElement.canPlayType('audio/ogg; codecs="opus"').replace(/^no$/, '') || audioElement.canPlayType('audio/opus;').replace(/^no$/, ''))
  50343. {
  50344. device.opus = true;
  50345. }
  50346. if (audioElement.canPlayType('audio/mpeg;').replace(/^no$/, ''))
  50347. {
  50348. device.mp3 = true;
  50349. }
  50350. // Mimetypes accepted:
  50351. // developer.mozilla.org/En/Media_formats_supported_by_the_audio_and_video_elements
  50352. // bit.ly/iphoneoscodecs
  50353. if (audioElement.canPlayType('audio/wav; codecs="1"').replace(/^no$/, ''))
  50354. {
  50355. device.wav = true;
  50356. }
  50357. if (audioElement.canPlayType('audio/x-m4a;') || audioElement.canPlayType('audio/aac;').replace(/^no$/, ''))
  50358. {
  50359. device.m4a = true;
  50360. }
  50361. if (audioElement.canPlayType('audio/webm; codecs="vorbis"').replace(/^no$/, ''))
  50362. {
  50363. device.webm = true;
  50364. }
  50365. if (audioElement.canPlayType('audio/mp4;codecs="ec-3"') !== '')
  50366. {
  50367. if (device.edge)
  50368. {
  50369. device.dolby = true;
  50370. }
  50371. else if (device.safari && device.safariVersion >= 9)
  50372. {
  50373. if (/Mac OS X (\d+)_(\d+)/.test(navigator.userAgent))
  50374. {
  50375. var major = parseInt(RegExp.$1, 10);
  50376. var minor = parseInt(RegExp.$2, 10);
  50377. if ((major === 10 && minor >= 11) || major > 10)
  50378. {
  50379. device.dolby = true;
  50380. }
  50381. }
  50382. }
  50383. }
  50384. }
  50385. } catch (e) {
  50386. }
  50387. }
  50388. /**
  50389. * Check Little or Big Endian system.
  50390. *
  50391. * @author Matt DesLauriers (@mattdesl)
  50392. */
  50393. function _checkIsLittleEndian () {
  50394. var a = new ArrayBuffer(4);
  50395. var b = new Uint8Array(a);
  50396. var c = new Uint32Array(a);
  50397. b[0] = 0xa1;
  50398. b[1] = 0xb2;
  50399. b[2] = 0xc3;
  50400. b[3] = 0xd4;
  50401. if (c[0] === 0xd4c3b2a1)
  50402. {
  50403. return true;
  50404. }
  50405. if (c[0] === 0xa1b2c3d4)
  50406. {
  50407. return false;
  50408. }
  50409. else
  50410. {
  50411. // Could not determine endianness
  50412. return null;
  50413. }
  50414. }
  50415. /**
  50416. * Test to see if ImageData uses CanvasPixelArray or Uint8ClampedArray.
  50417. *
  50418. * @author Matt DesLauriers (@mattdesl)
  50419. */
  50420. function _checkIsUint8ClampedImageData () {
  50421. if (Uint8ClampedArray === undefined)
  50422. {
  50423. return false;
  50424. }
  50425. var elem = PIXI.CanvasPool.create(this, 1, 1);
  50426. var ctx = elem.getContext('2d');
  50427. if (!ctx)
  50428. {
  50429. return false;
  50430. }
  50431. var image = ctx.createImageData(1, 1);
  50432. PIXI.CanvasPool.remove(this);
  50433. return image.data instanceof Uint8ClampedArray;
  50434. }
  50435. /**
  50436. * Check PixelRatio, iOS device, Vibration API, ArrayBuffers and endianess.
  50437. */
  50438. function _checkDevice () {
  50439. device.pixelRatio = window['devicePixelRatio'] || 1;
  50440. device.iPhone = navigator.userAgent.toLowerCase().indexOf('iphone') !== -1;
  50441. device.iPhone4 = (device.pixelRatio === 2 && device.iPhone);
  50442. device.iPad = navigator.userAgent.toLowerCase().indexOf('ipad') !== -1;
  50443. if (typeof Int8Array !== 'undefined')
  50444. {
  50445. device.typedArray = true;
  50446. }
  50447. else
  50448. {
  50449. device.typedArray = false;
  50450. }
  50451. if (typeof ArrayBuffer !== 'undefined' && typeof Uint8Array !== 'undefined' && typeof Uint32Array !== 'undefined')
  50452. {
  50453. device.littleEndian = _checkIsLittleEndian();
  50454. device.LITTLE_ENDIAN = device.littleEndian;
  50455. }
  50456. device.support32bit = (typeof ArrayBuffer !== 'undefined' && typeof Uint8ClampedArray !== 'undefined' && typeof Int32Array !== 'undefined' && device.littleEndian !== null && _checkIsUint8ClampedImageData());
  50457. navigator.vibrate = navigator.vibrate || navigator.webkitVibrate || navigator.mozVibrate || navigator.msVibrate;
  50458. if (navigator.vibrate)
  50459. {
  50460. device.vibration = true;
  50461. }
  50462. }
  50463. /**
  50464. * Check whether the host environment support 3D CSS.
  50465. */
  50466. function _checkCSS3D () {
  50467. var el = document.createElement('p');
  50468. var has3d;
  50469. var transforms = {
  50470. 'webkitTransform': '-webkit-transform',
  50471. 'OTransform': '-o-transform',
  50472. 'msTransform': '-ms-transform',
  50473. 'MozTransform': '-moz-transform',
  50474. 'transform': 'transform'
  50475. };
  50476. // Add it to the body to get the computed style.
  50477. document.body.insertBefore(el, null);
  50478. for (var t in transforms)
  50479. {
  50480. if (el.style[t] !== undefined)
  50481. {
  50482. el.style[t] = "translate3d(1px,1px,1px)";
  50483. has3d = window.getComputedStyle(el).getPropertyValue(transforms[t]);
  50484. }
  50485. }
  50486. document.body.removeChild(el);
  50487. device.css3D = (has3d !== undefined && has3d.length > 0 && has3d !== "none");
  50488. }
  50489. // Run the checks
  50490. _checkOS();
  50491. _checkBrowser();
  50492. _checkAudio();
  50493. _checkVideo();
  50494. _checkCSS3D();
  50495. _checkDevice();
  50496. _checkFeatures();
  50497. _checkFullScreenSupport();
  50498. _checkInput();
  50499. };
  50500. /**
  50501. * Check whether the host environment can play audio.
  50502. *
  50503. * @method canPlayAudio
  50504. * @memberof Phaser.Device.prototype
  50505. * @param {string} type - One of 'mp3, 'ogg', 'm4a', 'wav', 'webm' or 'opus'.
  50506. * @return {boolean} True if the given file type is supported by the browser, otherwise false.
  50507. */
  50508. Phaser.Device.canPlayAudio = function (type) {
  50509. if (type === 'mp3' && this.mp3)
  50510. {
  50511. return true;
  50512. }
  50513. else if (type === 'ogg' && (this.ogg || this.opus))
  50514. {
  50515. return true;
  50516. }
  50517. else if (type === 'm4a' && this.m4a)
  50518. {
  50519. return true;
  50520. }
  50521. else if (type === 'opus' && this.opus)
  50522. {
  50523. return true;
  50524. }
  50525. else if (type === 'wav' && this.wav)
  50526. {
  50527. return true;
  50528. }
  50529. else if (type === 'webm' && this.webm)
  50530. {
  50531. return true;
  50532. }
  50533. else if (type === 'mp4' && this.dolby)
  50534. {
  50535. return true;
  50536. }
  50537. return false;
  50538. };
  50539. /**
  50540. * Check whether the host environment can play video files.
  50541. *
  50542. * @method canPlayVideo
  50543. * @memberof Phaser.Device.prototype
  50544. * @param {string} type - One of 'mp4, 'ogg', 'webm' or 'mpeg'.
  50545. * @return {boolean} True if the given file type is supported by the browser, otherwise false.
  50546. */
  50547. Phaser.Device.canPlayVideo = function (type) {
  50548. if (type === 'webm' && (this.webmVideo || this.vp9Video))
  50549. {
  50550. return true;
  50551. }
  50552. else if (type === 'mp4' && (this.mp4Video || this.h264Video))
  50553. {
  50554. return true;
  50555. }
  50556. else if ((type === 'ogg' || type === 'ogv') && this.oggVideo)
  50557. {
  50558. return true;
  50559. }
  50560. else if (type === 'mpeg' && this.hlsVideo)
  50561. {
  50562. return true;
  50563. }
  50564. return false;
  50565. };
  50566. /**
  50567. * Check whether the console is open.
  50568. * Note that this only works in Firefox with Firebug and earlier versions of Chrome.
  50569. * It used to work in Chrome, but then they removed the ability: {@link http://src.chromium.org/viewvc/blink?view=revision&revision=151136}
  50570. *
  50571. * @method isConsoleOpen
  50572. * @memberof Phaser.Device.prototype
  50573. */
  50574. Phaser.Device.isConsoleOpen = function () {
  50575. if (window.console && window.console['firebug'])
  50576. {
  50577. return true;
  50578. }
  50579. if (window.console)
  50580. {
  50581. console.profile();
  50582. console.profileEnd();
  50583. if (console.clear)
  50584. {
  50585. console.clear();
  50586. }
  50587. if (console['profiles'])
  50588. {
  50589. return console['profiles'].length > 0;
  50590. }
  50591. }
  50592. return false;
  50593. };
  50594. /**
  50595. * Detect if the host is a an Android Stock browser.
  50596. * This is available before the device "ready" event.
  50597. *
  50598. * Authors might want to scale down on effects and switch to the CANVAS rendering method on those devices.
  50599. *
  50600. * @example
  50601. * var defaultRenderingMode = Phaser.Device.isAndroidStockBrowser() ? Phaser.CANVAS : Phaser.AUTO;
  50602. *
  50603. * @method isAndroidStockBrowser
  50604. * @memberof Phaser.Device.prototype
  50605. */
  50606. Phaser.Device.isAndroidStockBrowser = function () {
  50607. var matches = window.navigator.userAgent.match(/Android.*AppleWebKit\/([\d.]+)/);
  50608. return matches && matches[1] < 537;
  50609. };
  50610. /**
  50611. * @author Richard Davey <rich@photonstorm.com>
  50612. * @copyright 2016 Photon Storm Ltd.
  50613. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  50614. */
  50615. /**
  50616. * The Canvas class handles everything related to creating the `canvas` DOM tag that Phaser will use,
  50617. * including styles, offset and aspect ratio.
  50618. *
  50619. * @class Phaser.Canvas
  50620. * @static
  50621. */
  50622. Phaser.Canvas = {
  50623. /**
  50624. * Creates a `canvas` DOM element. The element is not automatically added to the document.
  50625. *
  50626. * @method Phaser.Canvas.create
  50627. * @param {object} parent - The object that will own the canvas that is created.
  50628. * @param {number} [width=256] - The width of the canvas element.
  50629. * @param {number} [height=256] - The height of the canvas element..
  50630. * @param {string} [id=(none)] - If specified, and not the empty string, this will be set as the ID of the canvas element. Otherwise no ID will be set.
  50631. * @param {boolean} [skipPool=false] - If `true` the canvas will not be placed in the CanvasPool global.
  50632. * @return {HTMLCanvasElement} The newly created canvas element.
  50633. */
  50634. create: function (parent, width, height, id, skipPool) {
  50635. width = width || 256;
  50636. height = height || 256;
  50637. var canvas = (skipPool) ? document.createElement('canvas') : PIXI.CanvasPool.create(parent, width, height);
  50638. if (typeof id === 'string' && id !== '')
  50639. {
  50640. canvas.id = id;
  50641. }
  50642. canvas.width = width;
  50643. canvas.height = height;
  50644. canvas.style.display = 'block';
  50645. return canvas;
  50646. },
  50647. /**
  50648. * Sets the background color behind the canvas. This changes the canvas style property.
  50649. *
  50650. * @method Phaser.Canvas.setBackgroundColor
  50651. * @param {HTMLCanvasElement} canvas - The canvas to set the background color on.
  50652. * @param {string} [color='rgb(0,0,0)'] - The color to set. Can be in the format 'rgb(r,g,b)', or '#RRGGBB' or any valid CSS color.
  50653. * @return {HTMLCanvasElement} Returns the source canvas.
  50654. */
  50655. setBackgroundColor: function (canvas, color) {
  50656. color = color || 'rgb(0,0,0)';
  50657. canvas.style.backgroundColor = color;
  50658. return canvas;
  50659. },
  50660. /**
  50661. * Sets the touch-action property on the canvas style. Can be used to disable default browser touch actions.
  50662. *
  50663. * @method Phaser.Canvas.setTouchAction
  50664. * @param {HTMLCanvasElement} canvas - The canvas to set the touch action on.
  50665. * @param {string} [value] - The touch action to set. Defaults to 'none'.
  50666. * @return {HTMLCanvasElement} The source canvas.
  50667. */
  50668. setTouchAction: function (canvas, value) {
  50669. value = value || 'none';
  50670. canvas.style.msTouchAction = value;
  50671. canvas.style['ms-touch-action'] = value;
  50672. canvas.style['touch-action'] = value;
  50673. return canvas;
  50674. },
  50675. /**
  50676. * Sets the user-select property on the canvas style. Can be used to disable default browser selection actions.
  50677. *
  50678. * @method Phaser.Canvas.setUserSelect
  50679. * @param {HTMLCanvasElement} canvas - The canvas to set the touch action on.
  50680. * @param {string} [value] - The touch action to set. Defaults to 'none'.
  50681. * @return {HTMLCanvasElement} The source canvas.
  50682. */
  50683. setUserSelect: function (canvas, value) {
  50684. value = value || 'none';
  50685. canvas.style['-webkit-touch-callout'] = value;
  50686. canvas.style['-webkit-user-select'] = value;
  50687. canvas.style['-khtml-user-select'] = value;
  50688. canvas.style['-moz-user-select'] = value;
  50689. canvas.style['-ms-user-select'] = value;
  50690. canvas.style['user-select'] = value;
  50691. canvas.style['-webkit-tap-highlight-color'] = 'rgba(0, 0, 0, 0)';
  50692. return canvas;
  50693. },
  50694. /**
  50695. * Adds the given canvas element to the DOM. The canvas will be added as a child of the given parent.
  50696. * If no parent is given it will be added as a child of the document.body.
  50697. *
  50698. * @method Phaser.Canvas.addToDOM
  50699. * @param {HTMLCanvasElement} canvas - The canvas to be added to the DOM.
  50700. * @param {string|HTMLElement} parent - The DOM element to add the canvas to.
  50701. * @param {boolean} [overflowHidden=true] - If set to true it will add the overflow='hidden' style to the parent DOM element.
  50702. * @return {HTMLCanvasElement} Returns the source canvas.
  50703. */
  50704. addToDOM: function (canvas, parent, overflowHidden) {
  50705. var target;
  50706. if (overflowHidden === undefined) { overflowHidden = true; }
  50707. if (parent)
  50708. {
  50709. if (typeof parent === 'string')
  50710. {
  50711. // hopefully an element ID
  50712. target = document.getElementById(parent);
  50713. }
  50714. else if (typeof parent === 'object' && parent.nodeType === 1)
  50715. {
  50716. // quick test for a HTMLelement
  50717. target = parent;
  50718. }
  50719. }
  50720. // Fallback, covers an invalid ID and a non HTMLelement object
  50721. if (!target)
  50722. {
  50723. target = document.body;
  50724. }
  50725. if (overflowHidden && target.style)
  50726. {
  50727. target.style.overflow = 'hidden';
  50728. }
  50729. target.appendChild(canvas);
  50730. return canvas;
  50731. },
  50732. /**
  50733. * Removes the given canvas element from the DOM.
  50734. *
  50735. * @method Phaser.Canvas.removeFromDOM
  50736. * @param {HTMLCanvasElement} canvas - The canvas to be removed from the DOM.
  50737. */
  50738. removeFromDOM: function (canvas) {
  50739. if (canvas.parentNode)
  50740. {
  50741. canvas.parentNode.removeChild(canvas);
  50742. }
  50743. },
  50744. /**
  50745. * Sets the transform of the given canvas to the matrix values provided.
  50746. *
  50747. * @method Phaser.Canvas.setTransform
  50748. * @param {CanvasRenderingContext2D} context - The context to set the transform on.
  50749. * @param {number} translateX - The value to translate horizontally by.
  50750. * @param {number} translateY - The value to translate vertically by.
  50751. * @param {number} scaleX - The value to scale horizontally by.
  50752. * @param {number} scaleY - The value to scale vertically by.
  50753. * @param {number} skewX - The value to skew horizontaly by.
  50754. * @param {number} skewY - The value to skew vertically by.
  50755. * @return {CanvasRenderingContext2D} Returns the source context.
  50756. */
  50757. setTransform: function (context, translateX, translateY, scaleX, scaleY, skewX, skewY) {
  50758. context.setTransform(scaleX, skewX, skewY, scaleY, translateX, translateY);
  50759. return context;
  50760. },
  50761. /**
  50762. * Sets the Image Smoothing property on the given context. Set to false to disable image smoothing.
  50763. * By default browsers have image smoothing enabled, which isn't always what you visually want, especially
  50764. * when using pixel art in a game. Note that this sets the property on the context itself, so that any image
  50765. * drawn to the context will be affected. This sets the property across all current browsers but support is
  50766. * patchy on earlier browsers, especially on mobile.
  50767. *
  50768. * @method Phaser.Canvas.setSmoothingEnabled
  50769. * @param {CanvasRenderingContext2D} context - The context to enable or disable the image smoothing on.
  50770. * @param {boolean} value - If set to true it will enable image smoothing, false will disable it.
  50771. * @return {CanvasRenderingContext2D} Returns the source context.
  50772. */
  50773. setSmoothingEnabled: function (context, value) {
  50774. var s = Phaser.Canvas.getSmoothingPrefix(context);
  50775. if (s)
  50776. {
  50777. context[s] = value;
  50778. }
  50779. return context;
  50780. },
  50781. /**
  50782. * Gets the Smoothing Enabled vendor prefix being used on the given context, or null if not set.
  50783. *
  50784. * @method Phaser.Canvas.getSmoothingPrefix
  50785. * @param {CanvasRenderingContext2D} context - The context to enable or disable the image smoothing on.
  50786. * @return {string|null} Returns the smoothingEnabled vendor prefix, or null if not set on the context.
  50787. */
  50788. getSmoothingPrefix: function (context) {
  50789. var vendor = [ 'i', 'webkitI', 'msI', 'mozI', 'oI' ];
  50790. for (var prefix in vendor)
  50791. {
  50792. var s = vendor[prefix] + 'mageSmoothingEnabled';
  50793. if (s in context)
  50794. {
  50795. return s;
  50796. }
  50797. }
  50798. return null;
  50799. },
  50800. /**
  50801. * Returns `true` if the given context has image smoothing enabled, otherwise returns `false`.
  50802. *
  50803. * @method Phaser.Canvas.getSmoothingEnabled
  50804. * @param {CanvasRenderingContext2D} context - The context to check for smoothing on.
  50805. * @return {boolean} True if the given context has image smoothing enabled, otherwise false.
  50806. */
  50807. getSmoothingEnabled: function (context) {
  50808. var s = Phaser.Canvas.getSmoothingPrefix(context);
  50809. if (s)
  50810. {
  50811. return context[s];
  50812. }
  50813. },
  50814. /**
  50815. * Sets the CSS image-rendering property on the given canvas to be 'crisp' (aka 'optimize contrast' on webkit).
  50816. * Note that if this doesn't given the desired result then see the setSmoothingEnabled.
  50817. *
  50818. * @method Phaser.Canvas.setImageRenderingCrisp
  50819. * @param {HTMLCanvasElement} canvas - The canvas to set image-rendering crisp on.
  50820. * @return {HTMLCanvasElement} Returns the source canvas.
  50821. */
  50822. setImageRenderingCrisp: function (canvas) {
  50823. var types = [ 'optimizeSpeed', 'crisp-edges', '-moz-crisp-edges', '-webkit-optimize-contrast', 'optimize-contrast', 'pixelated' ];
  50824. for (var i = 0; i < types.length; i++)
  50825. {
  50826. canvas.style['image-rendering'] = types[i];
  50827. }
  50828. canvas.style.msInterpolationMode = 'nearest-neighbor';
  50829. return canvas;
  50830. },
  50831. /**
  50832. * Sets the CSS image-rendering property on the given canvas to be 'bicubic' (aka 'auto').
  50833. * Note that if this doesn't given the desired result then see the CanvasUtils.setSmoothingEnabled method.
  50834. *
  50835. * @method Phaser.Canvas.setImageRenderingBicubic
  50836. * @param {HTMLCanvasElement} canvas The canvas to set image-rendering bicubic on.
  50837. * @return {HTMLCanvasElement} Returns the source canvas.
  50838. */
  50839. setImageRenderingBicubic: function (canvas) {
  50840. canvas.style['image-rendering'] = 'auto';
  50841. canvas.style.msInterpolationMode = 'bicubic';
  50842. return canvas;
  50843. }
  50844. };
  50845. /**
  50846. * @author Richard Davey <rich@photonstorm.com>
  50847. * @copyright 2016 Photon Storm Ltd.
  50848. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  50849. */
  50850. /**
  50851. * Abstracts away the use of RAF or setTimeOut for the core game update loop.
  50852. *
  50853. * @class Phaser.RequestAnimationFrame
  50854. * @constructor
  50855. * @param {Phaser.Game} game - A reference to the currently running game.
  50856. * @param {boolean} [forceSetTimeOut=false] - Tell Phaser to use setTimeOut even if raf is available.
  50857. */
  50858. Phaser.RequestAnimationFrame = function(game, forceSetTimeOut) {
  50859. if (forceSetTimeOut === undefined) { forceSetTimeOut = false; }
  50860. /**
  50861. * @property {Phaser.Game} game - The currently running game.
  50862. */
  50863. this.game = game;
  50864. /**
  50865. * @property {boolean} isRunning - true if RequestAnimationFrame is running, otherwise false.
  50866. * @default
  50867. */
  50868. this.isRunning = false;
  50869. /**
  50870. * @property {boolean} forceSetTimeOut - Tell Phaser to use setTimeOut even if raf is available.
  50871. */
  50872. this.forceSetTimeOut = forceSetTimeOut;
  50873. var vendors = [
  50874. 'ms',
  50875. 'moz',
  50876. 'webkit',
  50877. 'o'
  50878. ];
  50879. for (var x = 0; x < vendors.length && !window.requestAnimationFrame; x++)
  50880. {
  50881. window.requestAnimationFrame = window[vendors[x] + 'RequestAnimationFrame'];
  50882. window.cancelAnimationFrame = window[vendors[x] + 'CancelAnimationFrame'];
  50883. }
  50884. /**
  50885. * @property {boolean} _isSetTimeOut - true if the browser is using setTimeout instead of raf.
  50886. * @private
  50887. */
  50888. this._isSetTimeOut = false;
  50889. /**
  50890. * @property {function} _onLoop - The function called by the update.
  50891. * @private
  50892. */
  50893. this._onLoop = null;
  50894. /**
  50895. * @property {number} _timeOutID - The callback ID used when calling cancel.
  50896. * @private
  50897. */
  50898. this._timeOutID = null;
  50899. };
  50900. Phaser.RequestAnimationFrame.prototype = {
  50901. /**
  50902. * Starts the requestAnimationFrame running or setTimeout if unavailable in browser
  50903. * @method Phaser.RequestAnimationFrame#start
  50904. */
  50905. start: function () {
  50906. this.isRunning = true;
  50907. var _this = this;
  50908. if (!window.requestAnimationFrame || this.forceSetTimeOut)
  50909. {
  50910. this._isSetTimeOut = true;
  50911. this._onLoop = function () {
  50912. return _this.updateSetTimeout();
  50913. };
  50914. this._timeOutID = window.setTimeout(this._onLoop, 0);
  50915. }
  50916. else
  50917. {
  50918. this._isSetTimeOut = false;
  50919. this._onLoop = function (time) {
  50920. return _this.updateRAF(time);
  50921. };
  50922. this._timeOutID = window.requestAnimationFrame(this._onLoop);
  50923. }
  50924. },
  50925. /**
  50926. * The update method for the requestAnimationFrame
  50927. * @method Phaser.RequestAnimationFrame#updateRAF
  50928. */
  50929. updateRAF: function (rafTime) {
  50930. if (this.isRunning)
  50931. {
  50932. // floor the rafTime to make it equivalent to the Date.now() provided by updateSetTimeout (just below)
  50933. this.game.update(Math.floor(rafTime));
  50934. this._timeOutID = window.requestAnimationFrame(this._onLoop);
  50935. }
  50936. },
  50937. /**
  50938. * The update method for the setTimeout.
  50939. * @method Phaser.RequestAnimationFrame#updateSetTimeout
  50940. */
  50941. updateSetTimeout: function () {
  50942. if (this.isRunning)
  50943. {
  50944. this.game.update(Date.now());
  50945. this._timeOutID = window.setTimeout(this._onLoop, this.game.time.timeToCall);
  50946. }
  50947. },
  50948. /**
  50949. * Stops the requestAnimationFrame from running.
  50950. * @method Phaser.RequestAnimationFrame#stop
  50951. */
  50952. stop: function () {
  50953. if (this._isSetTimeOut)
  50954. {
  50955. clearTimeout(this._timeOutID);
  50956. }
  50957. else
  50958. {
  50959. window.cancelAnimationFrame(this._timeOutID);
  50960. }
  50961. this.isRunning = false;
  50962. },
  50963. /**
  50964. * Is the browser using setTimeout?
  50965. * @method Phaser.RequestAnimationFrame#isSetTimeOut
  50966. * @return {boolean}
  50967. */
  50968. isSetTimeOut: function () {
  50969. return this._isSetTimeOut;
  50970. },
  50971. /**
  50972. * Is the browser using requestAnimationFrame?
  50973. * @method Phaser.RequestAnimationFrame#isRAF
  50974. * @return {boolean}
  50975. */
  50976. isRAF: function () {
  50977. return (this._isSetTimeOut === false);
  50978. }
  50979. };
  50980. Phaser.RequestAnimationFrame.prototype.constructor = Phaser.RequestAnimationFrame;
  50981. /**
  50982. * @author Richard Davey <rich@photonstorm.com>
  50983. * @copyright 2016 Photon Storm Ltd.
  50984. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  50985. */
  50986. /**
  50987. * A collection of useful mathematical functions.
  50988. *
  50989. * These are normally accessed through `game.math`.
  50990. *
  50991. * @class Phaser.Math
  50992. * @static
  50993. * @see {@link Phaser.Utils}
  50994. * @see {@link Phaser.ArrayUtils}
  50995. */
  50996. Phaser.Math = {
  50997. /**
  50998. * Twice PI.
  50999. * @property {number} Phaser.Math#PI2
  51000. * @default ~6.283
  51001. */
  51002. PI2: Math.PI * 2,
  51003. /**
  51004. * Returns a number between the `min` and `max` values.
  51005. *
  51006. * @method Phaser.Math#between
  51007. * @param {number} min - The minimum value. Must be positive, and less than 'max'.
  51008. * @param {number} max - The maximum value. Must be position, and greater than 'min'.
  51009. * @return {number} A value between the range min to max.
  51010. */
  51011. between: function (min, max) {
  51012. return Math.floor(Math.random() * (max - min + 1) + min);
  51013. },
  51014. /**
  51015. * Two number are fuzzyEqual if their difference is less than epsilon.
  51016. *
  51017. * @method Phaser.Math#fuzzyEqual
  51018. * @param {number} a - The first number to compare.
  51019. * @param {number} b - The second number to compare.
  51020. * @param {number} [epsilon=0.0001] - The epsilon (a small value used in the calculation)
  51021. * @return {boolean} True if |a-b|<epsilon
  51022. */
  51023. fuzzyEqual: function (a, b, epsilon) {
  51024. if (epsilon === undefined) { epsilon = 0.0001; }
  51025. return Math.abs(a - b) < epsilon;
  51026. },
  51027. /**
  51028. * `a` is fuzzyLessThan `b` if it is less than b + epsilon.
  51029. *
  51030. * @method Phaser.Math#fuzzyLessThan
  51031. * @param {number} a - The first number to compare.
  51032. * @param {number} b - The second number to compare.
  51033. * @param {number} [epsilon=0.0001] - The epsilon (a small value used in the calculation)
  51034. * @return {boolean} True if a<b+epsilon
  51035. */
  51036. fuzzyLessThan: function (a, b, epsilon) {
  51037. if (epsilon === undefined) { epsilon = 0.0001; }
  51038. return a < b + epsilon;
  51039. },
  51040. /**
  51041. * `a` is fuzzyGreaterThan `b` if it is more than b - epsilon.
  51042. *
  51043. * @method Phaser.Math#fuzzyGreaterThan
  51044. * @param {number} a - The first number to compare.
  51045. * @param {number} b - The second number to compare.
  51046. * @param {number} [epsilon=0.0001] - The epsilon (a small value used in the calculation)
  51047. * @return {boolean} True if a>b+epsilon
  51048. */
  51049. fuzzyGreaterThan: function (a, b, epsilon) {
  51050. if (epsilon === undefined) { epsilon = 0.0001; }
  51051. return a > b - epsilon;
  51052. },
  51053. /**
  51054. * Applies a fuzzy ceil to the given value.
  51055. *
  51056. * @method Phaser.Math#fuzzyCeil
  51057. * @param {number} val - The value to ceil.
  51058. * @param {number} [epsilon=0.0001] - The epsilon (a small value used in the calculation)
  51059. * @return {number} ceiling(val-epsilon)
  51060. */
  51061. fuzzyCeil: function (val, epsilon) {
  51062. if (epsilon === undefined) { epsilon = 0.0001; }
  51063. return Math.ceil(val - epsilon);
  51064. },
  51065. /**
  51066. * Applies a fuzzy floor to the given value.
  51067. *
  51068. * @method Phaser.Math#fuzzyFloor
  51069. * @param {number} val - The value to floor.
  51070. * @param {number} [epsilon=0.0001] - The epsilon (a small value used in the calculation)
  51071. * @return {number} floor(val+epsilon)
  51072. */
  51073. fuzzyFloor: function (val, epsilon) {
  51074. if (epsilon === undefined) { epsilon = 0.0001; }
  51075. return Math.floor(val + epsilon);
  51076. },
  51077. /**
  51078. * Averages all values passed to the function and returns the result.
  51079. *
  51080. * @method Phaser.Math#average
  51081. * @params {...number} The numbers to average
  51082. * @return {number} The average of all given values.
  51083. */
  51084. average: function () {
  51085. var sum = 0;
  51086. var len = arguments.length;
  51087. for (var i = 0; i < len; i++)
  51088. {
  51089. sum += (+arguments[i]);
  51090. }
  51091. return sum / len;
  51092. },
  51093. /**
  51094. * @method Phaser.Math#shear
  51095. * @param {number} n
  51096. * @return {number} n mod 1
  51097. */
  51098. shear: function (n) {
  51099. return n % 1;
  51100. },
  51101. /**
  51102. * Snap a value to nearest grid slice, using rounding.
  51103. *
  51104. * Example: if you have an interval gap of 5 and a position of 12... you will snap to 10 whereas 14 will snap to 15.
  51105. *
  51106. * @method Phaser.Math#snapTo
  51107. * @param {number} input - The value to snap.
  51108. * @param {number} gap - The interval gap of the grid.
  51109. * @param {number} [start=0] - Optional starting offset for gap.
  51110. * @return {number} The snapped value.
  51111. */
  51112. snapTo: function (input, gap, start) {
  51113. if (start === undefined) { start = 0; }
  51114. if (gap === 0) {
  51115. return input;
  51116. }
  51117. input -= start;
  51118. input = gap * Math.round(input / gap);
  51119. return start + input;
  51120. },
  51121. /**
  51122. * Snap a value to nearest grid slice, using floor.
  51123. *
  51124. * Example: if you have an interval gap of 5 and a position of 12... you will snap to 10.
  51125. * As will 14 snap to 10... but 16 will snap to 15.
  51126. *
  51127. * @method Phaser.Math#snapToFloor
  51128. * @param {number} input - The value to snap.
  51129. * @param {number} gap - The interval gap of the grid.
  51130. * @param {number} [start=0] - Optional starting offset for gap.
  51131. * @return {number} The snapped value.
  51132. */
  51133. snapToFloor: function (input, gap, start) {
  51134. if (start === undefined) { start = 0; }
  51135. if (gap === 0) {
  51136. return input;
  51137. }
  51138. input -= start;
  51139. input = gap * Math.floor(input / gap);
  51140. return start + input;
  51141. },
  51142. /**
  51143. * Snap a value to nearest grid slice, using ceil.
  51144. *
  51145. * Example: if you have an interval gap of 5 and a position of 12... you will snap to 15.
  51146. * As will 14 will snap to 15... but 16 will snap to 20.
  51147. *
  51148. * @method Phaser.Math#snapToCeil
  51149. * @param {number} input - The value to snap.
  51150. * @param {number} gap - The interval gap of the grid.
  51151. * @param {number} [start=0] - Optional starting offset for gap.
  51152. * @return {number} The snapped value.
  51153. */
  51154. snapToCeil: function (input, gap, start) {
  51155. if (start === undefined) { start = 0; }
  51156. if (gap === 0) {
  51157. return input;
  51158. }
  51159. input -= start;
  51160. input = gap * Math.ceil(input / gap);
  51161. return start + input;
  51162. },
  51163. /**
  51164. * Round to some place comparative to a `base`, default is 10 for decimal place.
  51165. * The `place` is represented by the power applied to `base` to get that place.
  51166. *
  51167. * e.g. 2000/7 ~= 285.714285714285714285714 ~= (bin)100011101.1011011011011011
  51168. *
  51169. * roundTo(2000/7,3) === 0
  51170. * roundTo(2000/7,2) == 300
  51171. * roundTo(2000/7,1) == 290
  51172. * roundTo(2000/7,0) == 286
  51173. * roundTo(2000/7,-1) == 285.7
  51174. * roundTo(2000/7,-2) == 285.71
  51175. * roundTo(2000/7,-3) == 285.714
  51176. * roundTo(2000/7,-4) == 285.7143
  51177. * roundTo(2000/7,-5) == 285.71429
  51178. *
  51179. * roundTo(2000/7,3,2) == 288 -- 100100000
  51180. * roundTo(2000/7,2,2) == 284 -- 100011100
  51181. * roundTo(2000/7,1,2) == 286 -- 100011110
  51182. * roundTo(2000/7,0,2) == 286 -- 100011110
  51183. * roundTo(2000/7,-1,2) == 285.5 -- 100011101.1
  51184. * roundTo(2000/7,-2,2) == 285.75 -- 100011101.11
  51185. * roundTo(2000/7,-3,2) == 285.75 -- 100011101.11
  51186. * roundTo(2000/7,-4,2) == 285.6875 -- 100011101.1011
  51187. * roundTo(2000/7,-5,2) == 285.71875 -- 100011101.10111
  51188. *
  51189. * Note what occurs when we round to the 3rd space (8ths place), 100100000, this is to be assumed
  51190. * because we are rounding 100011.1011011011011011 which rounds up.
  51191. *
  51192. * @method Phaser.Math#roundTo
  51193. * @param {number} value - The value to round.
  51194. * @param {number} [place=0] - The place to round to.
  51195. * @param {number} [base=10] - The base to round in. Default is 10 for decimal.
  51196. * @return {number} The rounded value.
  51197. */
  51198. roundTo: function (value, place, base) {
  51199. if (place === undefined) { place = 0; }
  51200. if (base === undefined) { base = 10; }
  51201. var p = Math.pow(base, -place);
  51202. return Math.round(value * p) / p;
  51203. },
  51204. /**
  51205. * Floors to some place comparative to a `base`, default is 10 for decimal place.
  51206. * The `place` is represented by the power applied to `base` to get that place.
  51207. *
  51208. * @method Phaser.Math#floorTo
  51209. * @param {number} value - The value to round.
  51210. * @param {number} [place=0] - The place to round to.
  51211. * @param {number} [base=10] - The base to round in. Default is 10 for decimal.
  51212. * @return {number} The rounded value.
  51213. */
  51214. floorTo: function (value, place, base) {
  51215. if (place === undefined) { place = 0; }
  51216. if (base === undefined) { base = 10; }
  51217. var p = Math.pow(base, -place);
  51218. return Math.floor(value * p) / p;
  51219. },
  51220. /**
  51221. * Ceils to some place comparative to a `base`, default is 10 for decimal place.
  51222. * The `place` is represented by the power applied to `base` to get that place.
  51223. *
  51224. * @method Phaser.Math#ceilTo
  51225. * @param {number} value - The value to round.
  51226. * @param {number} [place=0] - The place to round to.
  51227. * @param {number} [base=10] - The base to round in. Default is 10 for decimal.
  51228. * @return {number} The rounded value.
  51229. */
  51230. ceilTo: function (value, place, base) {
  51231. if (place === undefined) { place = 0; }
  51232. if (base === undefined) { base = 10; }
  51233. var p = Math.pow(base, -place);
  51234. return Math.ceil(value * p) / p;
  51235. },
  51236. /**
  51237. * Rotates currentAngle towards targetAngle, taking the shortest rotation distance.
  51238. * The lerp argument is the amount to rotate by in this call.
  51239. *
  51240. * @method Phaser.Math#rotateToAngle
  51241. * @param {number} currentAngle - The current angle, in radians.
  51242. * @param {number} targetAngle - The target angle to rotate to, in radians.
  51243. * @param {number} [lerp=0.05] - The lerp value to add to the current angle.
  51244. * @return {number} The adjusted angle.
  51245. */
  51246. rotateToAngle: function (currentAngle, targetAngle, lerp) {
  51247. if (lerp === undefined) { lerp = 0.05; }
  51248. if (currentAngle === targetAngle)
  51249. {
  51250. return currentAngle;
  51251. }
  51252. if (Math.abs(targetAngle - currentAngle) <= lerp || Math.abs(targetAngle - currentAngle) >= (Phaser.Math.PI2 - lerp))
  51253. {
  51254. currentAngle = targetAngle;
  51255. }
  51256. else
  51257. {
  51258. if (Math.abs(targetAngle - currentAngle) > Math.PI)
  51259. {
  51260. if (targetAngle < currentAngle)
  51261. {
  51262. targetAngle += Phaser.Math.PI2;
  51263. }
  51264. else
  51265. {
  51266. targetAngle -= Phaser.Math.PI2;
  51267. }
  51268. }
  51269. if (targetAngle > currentAngle)
  51270. {
  51271. currentAngle += lerp;
  51272. }
  51273. else if (targetAngle < currentAngle)
  51274. {
  51275. currentAngle -= lerp;
  51276. }
  51277. }
  51278. return currentAngle;
  51279. },
  51280. /**
  51281. * Gets the shortest angle between `angle1` and `angle2`.
  51282. * Both angles must be in the range -180 to 180, which is the same clamped
  51283. * range that `sprite.angle` uses, so you can pass in two sprite angles to
  51284. * this method, and get the shortest angle back between the two of them.
  51285. *
  51286. * The angle returned will be in the same range. If the returned angle is
  51287. * greater than 0 then it's a counter-clockwise rotation, if < 0 then it's
  51288. * a clockwise rotation.
  51289. *
  51290. * @method Phaser.Math#getShortestAngle
  51291. * @param {number} angle1 - The first angle. In the range -180 to 180.
  51292. * @param {number} angle2 - The second angle. In the range -180 to 180.
  51293. * @return {number} The shortest angle, in degrees. If greater than zero it's a counter-clockwise rotation.
  51294. */
  51295. getShortestAngle: function (angle1, angle2) {
  51296. var difference = angle2 - angle1;
  51297. if (difference === 0)
  51298. {
  51299. return 0;
  51300. }
  51301. var times = Math.floor((difference - (-180)) / 360);
  51302. return difference - (times * 360);
  51303. },
  51304. /**
  51305. * Find the angle of a segment from (x1, y1) -> (x2, y2).
  51306. *
  51307. * @method Phaser.Math#angleBetween
  51308. * @param {number} x1 - The x coordinate of the first value.
  51309. * @param {number} y1 - The y coordinate of the first value.
  51310. * @param {number} x2 - The x coordinate of the second value.
  51311. * @param {number} y2 - The y coordinate of the second value.
  51312. * @return {number} The angle, in radians.
  51313. */
  51314. angleBetween: function (x1, y1, x2, y2) {
  51315. return Math.atan2(y2 - y1, x2 - x1);
  51316. },
  51317. /**
  51318. * Find the angle of a segment from (x1, y1) -> (x2, y2).
  51319. *
  51320. * The difference between this method and Math.angleBetween is that this assumes the y coordinate travels
  51321. * down the screen.
  51322. *
  51323. * @method Phaser.Math#angleBetweenY
  51324. * @param {number} x1 - The x coordinate of the first value.
  51325. * @param {number} y1 - The y coordinate of the first value.
  51326. * @param {number} x2 - The x coordinate of the second value.
  51327. * @param {number} y2 - The y coordinate of the second value.
  51328. * @return {number} The angle, in radians.
  51329. */
  51330. angleBetweenY: function (x1, y1, x2, y2) {
  51331. return Math.atan2(x2 - x1, y2 - y1);
  51332. },
  51333. /**
  51334. * Find the angle of a segment from (point1.x, point1.y) -> (point2.x, point2.y).
  51335. *
  51336. * @method Phaser.Math#angleBetweenPoints
  51337. * @param {Phaser.Point} point1 - The first point.
  51338. * @param {Phaser.Point} point2 - The second point.
  51339. * @return {number} The angle between the two points, in radians.
  51340. */
  51341. angleBetweenPoints: function (point1, point2) {
  51342. return Math.atan2(point2.y - point1.y, point2.x - point1.x);
  51343. },
  51344. /**
  51345. * Find the angle of a segment from (point1.x, point1.y) -> (point2.x, point2.y).
  51346. * @method Phaser.Math#angleBetweenPointsY
  51347. * @param {Phaser.Point} point1
  51348. * @param {Phaser.Point} point2
  51349. * @return {number} The angle, in radians.
  51350. */
  51351. angleBetweenPointsY: function (point1, point2) {
  51352. return Math.atan2(point2.x - point1.x, point2.y - point1.y);
  51353. },
  51354. /**
  51355. * Reverses an angle.
  51356. * @method Phaser.Math#reverseAngle
  51357. * @param {number} angleRad - The angle to reverse, in radians.
  51358. * @return {number} The reverse angle, in radians.
  51359. */
  51360. reverseAngle: function (angleRad) {
  51361. return this.normalizeAngle(angleRad + Math.PI, true);
  51362. },
  51363. /**
  51364. * Normalizes an angle to the [0,2pi) range.
  51365. * @method Phaser.Math#normalizeAngle
  51366. * @param {number} angleRad - The angle to normalize, in radians.
  51367. * @return {number} The angle, fit within the [0,2pi] range, in radians.
  51368. */
  51369. normalizeAngle: function (angleRad) {
  51370. angleRad = angleRad % (2 * Math.PI);
  51371. return angleRad >= 0 ? angleRad : angleRad + 2 * Math.PI;
  51372. },
  51373. /**
  51374. * Adds the given amount to the value, but never lets the value go over the specified maximum.
  51375. *
  51376. * @method Phaser.Math#maxAdd
  51377. * @param {number} value - The value to add the amount to.
  51378. * @param {number} amount - The amount to add to the value.
  51379. * @param {number} max - The maximum the value is allowed to be.
  51380. * @return {number} The new value.
  51381. */
  51382. maxAdd: function (value, amount, max) {
  51383. return Math.min(value + amount, max);
  51384. },
  51385. /**
  51386. * Subtracts the given amount from the value, but never lets the value go below the specified minimum.
  51387. *
  51388. * @method Phaser.Math#minSub
  51389. * @param {number} value - The base value.
  51390. * @param {number} amount - The amount to subtract from the base value.
  51391. * @param {number} min - The minimum the value is allowed to be.
  51392. * @return {number} The new value.
  51393. */
  51394. minSub: function (value, amount, min) {
  51395. return Math.max(value - amount, min);
  51396. },
  51397. /**
  51398. * Ensures that the value always stays between min and max, by wrapping the value around.
  51399. *
  51400. * If `max` is not larger than `min` the result is 0.
  51401. *
  51402. * @method Phaser.Math#wrap
  51403. * @param {number} value - The value to wrap.
  51404. * @param {number} min - The minimum the value is allowed to be.
  51405. * @param {number} max - The maximum the value is allowed to be, should be larger than `min`.
  51406. * @return {number} The wrapped value.
  51407. */
  51408. wrap: function (value, min, max) {
  51409. var range = max - min;
  51410. if (range <= 0)
  51411. {
  51412. return 0;
  51413. }
  51414. var result = (value - min) % range;
  51415. if (result < 0)
  51416. {
  51417. result += range;
  51418. }
  51419. return result + min;
  51420. },
  51421. /**
  51422. * Adds value to amount and ensures that the result always stays between 0 and max, by wrapping the value around.
  51423. *
  51424. * Values _must_ be positive integers, and are passed through Math.abs. See {@link Phaser.Math#wrap} for an alternative.
  51425. *
  51426. * @method Phaser.Math#wrapValue
  51427. * @param {number} value - The value to add the amount to.
  51428. * @param {number} amount - The amount to add to the value.
  51429. * @param {number} max - The maximum the value is allowed to be.
  51430. * @return {number} The wrapped value.
  51431. */
  51432. wrapValue: function (value, amount, max) {
  51433. var diff;
  51434. value = Math.abs(value);
  51435. amount = Math.abs(amount);
  51436. max = Math.abs(max);
  51437. diff = (value + amount) % max;
  51438. return diff;
  51439. },
  51440. /**
  51441. * Returns true if the number given is odd.
  51442. *
  51443. * @method Phaser.Math#isOdd
  51444. * @param {integer} n - The number to check.
  51445. * @return {boolean} True if the given number is odd. False if the given number is even.
  51446. */
  51447. isOdd: function (n) {
  51448. // Does not work with extremely large values
  51449. return !!(n & 1);
  51450. },
  51451. /**
  51452. * Returns true if the number given is even.
  51453. *
  51454. * @method Phaser.Math#isEven
  51455. * @param {integer} n - The number to check.
  51456. * @return {boolean} True if the given number is even. False if the given number is odd.
  51457. */
  51458. isEven: function (n) {
  51459. // Does not work with extremely large values
  51460. return !(n & 1);
  51461. },
  51462. /**
  51463. * Variation of Math.min that can be passed either an array of numbers or the numbers as parameters.
  51464. *
  51465. * Prefer the standard `Math.min` function when appropriate.
  51466. *
  51467. * @method Phaser.Math#min
  51468. * @return {number} The lowest value from those given.
  51469. * @see {@link http://jsperf.com/math-s-min-max-vs-homemade}
  51470. */
  51471. min: function () {
  51472. if (arguments.length === 1 && typeof arguments[0] === 'object')
  51473. {
  51474. var data = arguments[0];
  51475. }
  51476. else
  51477. {
  51478. var data = arguments;
  51479. }
  51480. for (var i = 1, min = 0, len = data.length; i < len; i++)
  51481. {
  51482. if (data[i] < data[min])
  51483. {
  51484. min = i;
  51485. }
  51486. }
  51487. return data[min];
  51488. },
  51489. /**
  51490. * Variation of Math.max that can be passed either an array of numbers or the numbers as parameters.
  51491. *
  51492. * Prefer the standard `Math.max` function when appropriate.
  51493. *
  51494. * @method Phaser.Math#max
  51495. * @return {number} The largest value from those given.
  51496. * @see {@link http://jsperf.com/math-s-min-max-vs-homemade}
  51497. */
  51498. max: function () {
  51499. if (arguments.length === 1 && typeof arguments[0] === 'object')
  51500. {
  51501. var data = arguments[0];
  51502. }
  51503. else
  51504. {
  51505. var data = arguments;
  51506. }
  51507. for (var i = 1, max = 0, len = data.length; i < len; i++)
  51508. {
  51509. if (data[i] > data[max])
  51510. {
  51511. max = i;
  51512. }
  51513. }
  51514. return data[max];
  51515. },
  51516. /**
  51517. * Variation of Math.min that can be passed a property and either an array of objects or the objects as parameters.
  51518. * It will find the lowest matching property value from the given objects.
  51519. *
  51520. * @method Phaser.Math#minProperty
  51521. * @return {number} The lowest value from those given.
  51522. */
  51523. minProperty: function (property) {
  51524. if (arguments.length === 2 && typeof arguments[1] === 'object')
  51525. {
  51526. var data = arguments[1];
  51527. }
  51528. else
  51529. {
  51530. var data = arguments.slice(1);
  51531. }
  51532. for (var i = 1, min = 0, len = data.length; i < len; i++)
  51533. {
  51534. if (data[i][property] < data[min][property])
  51535. {
  51536. min = i;
  51537. }
  51538. }
  51539. return data[min][property];
  51540. },
  51541. /**
  51542. * Variation of Math.max that can be passed a property and either an array of objects or the objects as parameters.
  51543. * It will find the largest matching property value from the given objects.
  51544. *
  51545. * @method Phaser.Math#maxProperty
  51546. * @return {number} The largest value from those given.
  51547. */
  51548. maxProperty: function (property) {
  51549. if (arguments.length === 2 && typeof arguments[1] === 'object')
  51550. {
  51551. var data = arguments[1];
  51552. }
  51553. else
  51554. {
  51555. var data = arguments.slice(1);
  51556. }
  51557. for (var i = 1, max = 0, len = data.length; i < len; i++)
  51558. {
  51559. if (data[i][property] > data[max][property])
  51560. {
  51561. max = i;
  51562. }
  51563. }
  51564. return data[max][property];
  51565. },
  51566. /**
  51567. * Keeps an angle value between -180 and +180; or -PI and PI if radians.
  51568. *
  51569. * @method Phaser.Math#wrapAngle
  51570. * @param {number} angle - The angle value to wrap
  51571. * @param {boolean} [radians=false] - Set to `true` if the angle is given in radians, otherwise degrees is expected.
  51572. * @return {number} The new angle value; will be the same as the input angle if it was within bounds.
  51573. */
  51574. wrapAngle: function (angle, radians) {
  51575. return radians ? this.wrap(angle, -Math.PI, Math.PI) : this.wrap(angle, -180, 180);
  51576. },
  51577. /**
  51578. * A Linear Interpolation Method, mostly used by Phaser.Tween.
  51579. *
  51580. * @method Phaser.Math#linearInterpolation
  51581. * @param {Array} v - The input array of values to interpolate between.
  51582. * @param {number} k - The percentage of interpolation, between 0 and 1.
  51583. * @return {number} The interpolated value
  51584. */
  51585. linearInterpolation: function (v, k) {
  51586. var m = v.length - 1;
  51587. var f = m * k;
  51588. var i = Math.floor(f);
  51589. if (k < 0)
  51590. {
  51591. return this.linear(v[0], v[1], f);
  51592. }
  51593. if (k > 1)
  51594. {
  51595. return this.linear(v[m], v[m - 1], m - f);
  51596. }
  51597. return this.linear(v[i], v[i + 1 > m ? m : i + 1], f - i);
  51598. },
  51599. /**
  51600. * A Bezier Interpolation Method, mostly used by Phaser.Tween.
  51601. *
  51602. * @method Phaser.Math#bezierInterpolation
  51603. * @param {Array} v - The input array of values to interpolate between.
  51604. * @param {number} k - The percentage of interpolation, between 0 and 1.
  51605. * @return {number} The interpolated value
  51606. */
  51607. bezierInterpolation: function (v, k) {
  51608. var b = 0;
  51609. var n = v.length - 1;
  51610. for (var i = 0; i <= n; i++)
  51611. {
  51612. b += Math.pow(1 - k, n - i) * Math.pow(k, i) * v[i] * this.bernstein(n, i);
  51613. }
  51614. return b;
  51615. },
  51616. /**
  51617. * A Catmull Rom Interpolation Method, mostly used by Phaser.Tween.
  51618. *
  51619. * @method Phaser.Math#catmullRomInterpolation
  51620. * @param {Array} v - The input array of values to interpolate between.
  51621. * @param {number} k - The percentage of interpolation, between 0 and 1.
  51622. * @return {number} The interpolated value
  51623. */
  51624. catmullRomInterpolation: function (v, k) {
  51625. var m = v.length - 1;
  51626. var f = m * k;
  51627. var i = Math.floor(f);
  51628. if (v[0] === v[m])
  51629. {
  51630. if (k < 0)
  51631. {
  51632. i = Math.floor(f = m * (1 + k));
  51633. }
  51634. return this.catmullRom(v[(i - 1 + m) % m], v[i], v[(i + 1) % m], v[(i + 2) % m], f - i);
  51635. }
  51636. else
  51637. {
  51638. if (k < 0)
  51639. {
  51640. return v[0] - (this.catmullRom(v[0], v[0], v[1], v[1], -f) - v[0]);
  51641. }
  51642. if (k > 1)
  51643. {
  51644. return v[m] - (this.catmullRom(v[m], v[m], v[m - 1], v[m - 1], f - m) - v[m]);
  51645. }
  51646. return this.catmullRom(v[i ? i - 1 : 0], v[i], v[m < i + 1 ? m : i + 1], v[m < i + 2 ? m : i + 2], f - i);
  51647. }
  51648. },
  51649. /**
  51650. * Calculates a linear (interpolation) value over t.
  51651. *
  51652. * @method Phaser.Math#linear
  51653. * @param {number} p0
  51654. * @param {number} p1
  51655. * @param {number} t - A value between 0 and 1.
  51656. * @return {number}
  51657. */
  51658. linear: function (p0, p1, t) {
  51659. return (p1 - p0) * t + p0;
  51660. },
  51661. /**
  51662. * @method Phaser.Math#bernstein
  51663. * @protected
  51664. * @param {number} n
  51665. * @param {number} i
  51666. * @return {number}
  51667. */
  51668. bernstein: function (n, i) {
  51669. return this.factorial(n) / this.factorial(i) / this.factorial(n - i);
  51670. },
  51671. /**
  51672. * @method Phaser.Math#factorial
  51673. * @param {number} value - the number you want to evaluate
  51674. * @return {number}
  51675. */
  51676. factorial: function (value) {
  51677. if (value === 0)
  51678. {
  51679. return 1;
  51680. }
  51681. var res = value;
  51682. while(--value)
  51683. {
  51684. res *= value;
  51685. }
  51686. return res;
  51687. },
  51688. /**
  51689. * Calculates a catmum rom value.
  51690. *
  51691. * @method Phaser.Math#catmullRom
  51692. * @protected
  51693. * @param {number} p0
  51694. * @param {number} p1
  51695. * @param {number} p2
  51696. * @param {number} p3
  51697. * @param {number} t
  51698. * @return {number}
  51699. */
  51700. catmullRom: function (p0, p1, p2, p3, t) {
  51701. var v0 = (p2 - p0) * 0.5, v1 = (p3 - p1) * 0.5, t2 = t * t, t3 = t * t2;
  51702. return (2 * p1 - 2 * p2 + v0 + v1) * t3 + (-3 * p1 + 3 * p2 - 2 * v0 - v1) * t2 + v0 * t + p1;
  51703. },
  51704. /**
  51705. * The absolute difference between two values.
  51706. *
  51707. * @method Phaser.Math#difference
  51708. * @param {number} a - The first value to check.
  51709. * @param {number} b - The second value to check.
  51710. * @return {number} The absolute difference between the two values.
  51711. */
  51712. difference: function (a, b) {
  51713. return Math.abs(a - b);
  51714. },
  51715. /**
  51716. * Round to the next whole number _away_ from zero.
  51717. *
  51718. * @method Phaser.Math#roundAwayFromZero
  51719. * @param {number} value - Any number.
  51720. * @return {integer} The rounded value of that number.
  51721. */
  51722. roundAwayFromZero: function (value) {
  51723. // "Opposite" of truncate.
  51724. return (value > 0) ? Math.ceil(value) : Math.floor(value);
  51725. },
  51726. /**
  51727. * Generate a sine and cosine table simultaneously and extremely quickly.
  51728. * The parameters allow you to specify the length, amplitude and frequency of the wave.
  51729. * This generator is fast enough to be used in real-time.
  51730. * Code based on research by Franky of scene.at
  51731. *
  51732. * @method Phaser.Math#sinCosGenerator
  51733. * @param {number} length - The length of the wave
  51734. * @param {number} sinAmplitude - The amplitude to apply to the sine table (default 1.0) if you need values between say -+ 125 then give 125 as the value
  51735. * @param {number} cosAmplitude - The amplitude to apply to the cosine table (default 1.0) if you need values between say -+ 125 then give 125 as the value
  51736. * @param {number} frequency - The frequency of the sine and cosine table data
  51737. * @return {{sin:number[], cos:number[]}} Returns the table data.
  51738. */
  51739. sinCosGenerator: function (length, sinAmplitude, cosAmplitude, frequency) {
  51740. if (sinAmplitude === undefined) { sinAmplitude = 1.0; }
  51741. if (cosAmplitude === undefined) { cosAmplitude = 1.0; }
  51742. if (frequency === undefined) { frequency = 1.0; }
  51743. var sin = sinAmplitude;
  51744. var cos = cosAmplitude;
  51745. var frq = frequency * Math.PI / length;
  51746. var cosTable = [];
  51747. var sinTable = [];
  51748. for (var c = 0; c < length; c++) {
  51749. cos -= sin * frq;
  51750. sin += cos * frq;
  51751. cosTable[c] = cos;
  51752. sinTable[c] = sin;
  51753. }
  51754. return { sin: sinTable, cos: cosTable, length: length };
  51755. },
  51756. /**
  51757. * Returns the euclidian distance between the two given set of coordinates.
  51758. *
  51759. * @method Phaser.Math#distance
  51760. * @param {number} x1
  51761. * @param {number} y1
  51762. * @param {number} x2
  51763. * @param {number} y2
  51764. * @return {number} The distance between the two sets of coordinates.
  51765. */
  51766. distance: function (x1, y1, x2, y2) {
  51767. var dx = x1 - x2;
  51768. var dy = y1 - y2;
  51769. return Math.sqrt(dx * dx + dy * dy);
  51770. },
  51771. /**
  51772. * Returns the euclidean distance squared between the two given set of
  51773. * coordinates (cuts out a square root operation before returning).
  51774. *
  51775. * @method Phaser.Math#distanceSq
  51776. * @param {number} x1
  51777. * @param {number} y1
  51778. * @param {number} x2
  51779. * @param {number} y2
  51780. * @return {number} The distance squared between the two sets of coordinates.
  51781. */
  51782. distanceSq: function (x1, y1, x2, y2) {
  51783. var dx = x1 - x2;
  51784. var dy = y1 - y2;
  51785. return dx * dx + dy * dy;
  51786. },
  51787. /**
  51788. * Returns the distance between the two given set of coordinates at the power given.
  51789. *
  51790. * @method Phaser.Math#distancePow
  51791. * @param {number} x1
  51792. * @param {number} y1
  51793. * @param {number} x2
  51794. * @param {number} y2
  51795. * @param {number} [pow=2]
  51796. * @return {number} The distance between the two sets of coordinates.
  51797. */
  51798. distancePow: function (x1, y1, x2, y2, pow) {
  51799. if (pow === undefined) { pow = 2; }
  51800. return Math.sqrt(Math.pow(x2 - x1, pow) + Math.pow(y2 - y1, pow));
  51801. },
  51802. /**
  51803. * Force a value within the boundaries by clamping it to the range `min`, `max`.
  51804. *
  51805. * @method Phaser.Math#clamp
  51806. * @param {float} v - The value to be clamped.
  51807. * @param {float} min - The minimum bounds.
  51808. * @param {float} max - The maximum bounds.
  51809. * @return {number} The clamped value.
  51810. */
  51811. clamp: function (v, min, max) {
  51812. if (v < min)
  51813. {
  51814. return min;
  51815. }
  51816. else if (max < v)
  51817. {
  51818. return max;
  51819. }
  51820. else
  51821. {
  51822. return v;
  51823. }
  51824. },
  51825. /**
  51826. * Clamp `x` to the range `[a, Infinity)`.
  51827. * Roughly the same as `Math.max(x, a)`, except for NaN handling.
  51828. *
  51829. * @method Phaser.Math#clampBottom
  51830. * @param {number} x
  51831. * @param {number} a
  51832. * @return {number}
  51833. */
  51834. clampBottom: function (x, a) {
  51835. return x < a ? a : x;
  51836. },
  51837. /**
  51838. * Checks if two values are within the given tolerance of each other.
  51839. *
  51840. * @method Phaser.Math#within
  51841. * @param {number} a - The first number to check
  51842. * @param {number} b - The second number to check
  51843. * @param {number} tolerance - The tolerance. Anything equal to or less than this is considered within the range.
  51844. * @return {boolean} True if a is <= tolerance of b.
  51845. * @see {@link Phaser.Math.fuzzyEqual}
  51846. */
  51847. within: function (a, b, tolerance) {
  51848. return (Math.abs(a - b) <= tolerance);
  51849. },
  51850. /**
  51851. * Linear mapping from range <a1, a2> to range <b1, b2>
  51852. *
  51853. * @method Phaser.Math#mapLinear
  51854. * @param {number} x - The value to map
  51855. * @param {number} a1 - First endpoint of the range <a1, a2>
  51856. * @param {number} a2 - Final endpoint of the range <a1, a2>
  51857. * @param {number} b1 - First endpoint of the range <b1, b2>
  51858. * @param {number} b2 - Final endpoint of the range <b1, b2>
  51859. * @return {number}
  51860. */
  51861. mapLinear: function (x, a1, a2, b1, b2) {
  51862. return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
  51863. },
  51864. /**
  51865. * Smoothstep function as detailed at http://en.wikipedia.org/wiki/Smoothstep
  51866. *
  51867. * @method Phaser.Math#smoothstep
  51868. * @param {float} x - The input value.
  51869. * @param {float} min - The left edge. Should be smaller than the right edge.
  51870. * @param {float} max - The right edge.
  51871. * @return {float} A value between 0 and 1.
  51872. */
  51873. smoothstep: function (x, min, max) {
  51874. // Scale, bias and saturate x to 0..1 range
  51875. x = Math.max(0, Math.min(1, (x - min) / (max - min)));
  51876. // Evaluate polynomial
  51877. return x * x * (3 - 2 * x);
  51878. },
  51879. /**
  51880. * Smootherstep function as detailed at http://en.wikipedia.org/wiki/Smoothstep
  51881. *
  51882. * @method Phaser.Math#smootherstep
  51883. * @param {float} x - The input value.
  51884. * @param {float} min - The left edge. Should be smaller than the right edge.
  51885. * @param {float} max - The right edge.
  51886. * @return {float} A value between 0 and 1.
  51887. */
  51888. smootherstep: function (x, min, max) {
  51889. x = Math.max(0, Math.min(1, (x - min) / (max - min)));
  51890. return x * x * x * (x * (x * 6 - 15) + 10);
  51891. },
  51892. /**
  51893. * A value representing the sign of the value: -1 for negative, +1 for positive, 0 if value is 0.
  51894. *
  51895. * This works differently from `Math.sign` for values of NaN and -0, etc.
  51896. *
  51897. * @method Phaser.Math#sign
  51898. * @param {number} x
  51899. * @return {integer} An integer in {-1, 0, 1}
  51900. */
  51901. sign: function (x) {
  51902. return ( x < 0 ) ? -1 : ( ( x > 0 ) ? 1 : 0 );
  51903. },
  51904. /**
  51905. * Work out what percentage value `a` is of value `b` using the given base.
  51906. *
  51907. * @method Phaser.Math#percent
  51908. * @param {number} a - The value to work out the percentage for.
  51909. * @param {number} b - The value you wish to get the percentage of.
  51910. * @param {number} [base=0] - The base value.
  51911. * @return {number} The percentage a is of b, between 0 and 1.
  51912. */
  51913. percent: function (a, b, base) {
  51914. if (base === undefined) { base = 0; }
  51915. if (a > b || base > b)
  51916. {
  51917. return 1;
  51918. }
  51919. else if (a < base || base > a)
  51920. {
  51921. return 0;
  51922. }
  51923. else
  51924. {
  51925. return (a - base) / b;
  51926. }
  51927. }
  51928. };
  51929. var degreeToRadiansFactor = Math.PI / 180;
  51930. var radianToDegreesFactor = 180 / Math.PI;
  51931. /**
  51932. * Convert degrees to radians.
  51933. *
  51934. * @method Phaser.Math#degToRad
  51935. * @param {number} degrees - Angle in degrees.
  51936. * @return {number} Angle in radians.
  51937. */
  51938. Phaser.Math.degToRad = function degToRad (degrees) {
  51939. return degrees * degreeToRadiansFactor;
  51940. };
  51941. /**
  51942. * Convert radians to degrees.
  51943. *
  51944. * @method Phaser.Math#radToDeg
  51945. * @param {number} radians - Angle in radians.
  51946. * @return {number} Angle in degrees
  51947. */
  51948. Phaser.Math.radToDeg = function radToDeg (radians) {
  51949. return radians * radianToDegreesFactor;
  51950. };
  51951. /* jshint noempty: false */
  51952. /**
  51953. * @author Richard Davey <rich@photonstorm.com>
  51954. * @copyright 2016 Photon Storm Ltd.
  51955. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  51956. */
  51957. /**
  51958. * An extremely useful repeatable random data generator.
  51959. *
  51960. * Based on Nonsense by Josh Faul https://github.com/jocafa/Nonsense.
  51961. *
  51962. * The random number genererator is based on the Alea PRNG, but is modified.
  51963. * - https://github.com/coverslide/node-alea
  51964. * - https://github.com/nquinlan/better-random-numbers-for-javascript-mirror
  51965. * - http://baagoe.org/en/wiki/Better_random_numbers_for_javascript (original, perm. 404)
  51966. *
  51967. * @class Phaser.RandomDataGenerator
  51968. * @constructor
  51969. * @param {any[]|string} [seeds] - An array of values to use as the seed, or a generator state (from {#state}).
  51970. */
  51971. Phaser.RandomDataGenerator = function (seeds) {
  51972. if (seeds === undefined) { seeds = []; }
  51973. /**
  51974. * @property {number} c - Internal var.
  51975. * @private
  51976. */
  51977. this.c = 1;
  51978. /**
  51979. * @property {number} s0 - Internal var.
  51980. * @private
  51981. */
  51982. this.s0 = 0;
  51983. /**
  51984. * @property {number} s1 - Internal var.
  51985. * @private
  51986. */
  51987. this.s1 = 0;
  51988. /**
  51989. * @property {number} s2 - Internal var.
  51990. * @private
  51991. */
  51992. this.s2 = 0;
  51993. if (typeof seeds === 'string')
  51994. {
  51995. this.state(seeds);
  51996. }
  51997. else
  51998. {
  51999. this.sow(seeds);
  52000. }
  52001. };
  52002. Phaser.RandomDataGenerator.prototype = {
  52003. /**
  52004. * Private random helper.
  52005. *
  52006. * @method Phaser.RandomDataGenerator#rnd
  52007. * @private
  52008. * @return {number}
  52009. */
  52010. rnd: function () {
  52011. var t = 2091639 * this.s0 + this.c * 2.3283064365386963e-10; // 2^-32
  52012. this.c = t | 0;
  52013. this.s0 = this.s1;
  52014. this.s1 = this.s2;
  52015. this.s2 = t - this.c;
  52016. return this.s2;
  52017. },
  52018. /**
  52019. * Reset the seed of the random data generator.
  52020. *
  52021. * _Note_: the seed array is only processed up to the first `undefined` (or `null`) value, should such be present.
  52022. *
  52023. * @method Phaser.RandomDataGenerator#sow
  52024. * @param {any[]} seeds - The array of seeds: the `toString()` of each value is used.
  52025. */
  52026. sow: function (seeds) {
  52027. // Always reset to default seed
  52028. this.s0 = this.hash(' ');
  52029. this.s1 = this.hash(this.s0);
  52030. this.s2 = this.hash(this.s1);
  52031. this.c = 1;
  52032. if (!seeds)
  52033. {
  52034. return;
  52035. }
  52036. // Apply any seeds
  52037. for (var i = 0; i < seeds.length && (seeds[i] != null); i++)
  52038. {
  52039. var seed = seeds[i];
  52040. this.s0 -= this.hash(seed);
  52041. this.s0 += ~~(this.s0 < 0);
  52042. this.s1 -= this.hash(seed);
  52043. this.s1 += ~~(this.s1 < 0);
  52044. this.s2 -= this.hash(seed);
  52045. this.s2 += ~~(this.s2 < 0);
  52046. }
  52047. },
  52048. /**
  52049. * Internal method that creates a seed hash.
  52050. *
  52051. * @method Phaser.RandomDataGenerator#hash
  52052. * @private
  52053. * @param {any} data
  52054. * @return {number} hashed value.
  52055. */
  52056. hash: function (data) {
  52057. var h, i, n;
  52058. n = 0xefc8249d;
  52059. data = data.toString();
  52060. for (i = 0; i < data.length; i++) {
  52061. n += data.charCodeAt(i);
  52062. h = 0.02519603282416938 * n;
  52063. n = h >>> 0;
  52064. h -= n;
  52065. h *= n;
  52066. n = h >>> 0;
  52067. h -= n;
  52068. n += h * 0x100000000;// 2^32
  52069. }
  52070. return (n >>> 0) * 2.3283064365386963e-10;// 2^-32
  52071. },
  52072. /**
  52073. * Returns a random integer between 0 and 2^32.
  52074. *
  52075. * @method Phaser.RandomDataGenerator#integer
  52076. * @return {number} A random integer between 0 and 2^32.
  52077. */
  52078. integer: function() {
  52079. return this.rnd.apply(this) * 0x100000000;// 2^32
  52080. },
  52081. /**
  52082. * Returns a random real number between 0 and 1.
  52083. *
  52084. * @method Phaser.RandomDataGenerator#frac
  52085. * @return {number} A random real number between 0 and 1.
  52086. */
  52087. frac: function() {
  52088. return this.rnd.apply(this) + (this.rnd.apply(this) * 0x200000 | 0) * 1.1102230246251565e-16; // 2^-53
  52089. },
  52090. /**
  52091. * Returns a random real number between 0 and 2^32.
  52092. *
  52093. * @method Phaser.RandomDataGenerator#real
  52094. * @return {number} A random real number between 0 and 2^32.
  52095. */
  52096. real: function() {
  52097. return this.integer() + this.frac();
  52098. },
  52099. /**
  52100. * Returns a random integer between and including min and max.
  52101. *
  52102. * @method Phaser.RandomDataGenerator#integerInRange
  52103. * @param {number} min - The minimum value in the range.
  52104. * @param {number} max - The maximum value in the range.
  52105. * @return {number} A random number between min and max.
  52106. */
  52107. integerInRange: function (min, max) {
  52108. return Math.floor(this.realInRange(0, max - min + 1) + min);
  52109. },
  52110. /**
  52111. * Returns a random integer between and including min and max.
  52112. * This method is an alias for RandomDataGenerator.integerInRange.
  52113. *
  52114. * @method Phaser.RandomDataGenerator#between
  52115. * @param {number} min - The minimum value in the range.
  52116. * @param {number} max - The maximum value in the range.
  52117. * @return {number} A random number between min and max.
  52118. */
  52119. between: function (min, max) {
  52120. return this.integerInRange(min, max);
  52121. },
  52122. /**
  52123. * Returns a random real number between min and max.
  52124. *
  52125. * @method Phaser.RandomDataGenerator#realInRange
  52126. * @param {number} min - The minimum value in the range.
  52127. * @param {number} max - The maximum value in the range.
  52128. * @return {number} A random number between min and max.
  52129. */
  52130. realInRange: function (min, max) {
  52131. return this.frac() * (max - min) + min;
  52132. },
  52133. /**
  52134. * Returns a random real number between -1 and 1.
  52135. *
  52136. * @method Phaser.RandomDataGenerator#normal
  52137. * @return {number} A random real number between -1 and 1.
  52138. */
  52139. normal: function () {
  52140. return 1 - 2 * this.frac();
  52141. },
  52142. /**
  52143. * Returns a valid RFC4122 version4 ID hex string from https://gist.github.com/1308368
  52144. *
  52145. * @method Phaser.RandomDataGenerator#uuid
  52146. * @return {string} A valid RFC4122 version4 ID hex string
  52147. */
  52148. uuid: function () {
  52149. var a = '';
  52150. var b = '';
  52151. for (b = a = ''; a++ < 36; b +=~a % 5 | a * 3&4 ? (a^15 ? 8^this.frac() * (a^20 ? 16 : 4) : 4).toString(16) : '-')
  52152. {
  52153. }
  52154. return b;
  52155. },
  52156. /**
  52157. * Returns a random member of `array`.
  52158. *
  52159. * @method Phaser.RandomDataGenerator#pick
  52160. * @param {Array} ary - An Array to pick a random member of.
  52161. * @return {any} A random member of the array.
  52162. */
  52163. pick: function (ary) {
  52164. return ary[this.integerInRange(0, ary.length - 1)];
  52165. },
  52166. /**
  52167. * Returns a sign to be used with multiplication operator.
  52168. *
  52169. * @method Phaser.RandomDataGenerator#sign
  52170. * @return {number} -1 or +1.
  52171. */
  52172. sign: function () {
  52173. return this.pick([-1, 1]);
  52174. },
  52175. /**
  52176. * Returns a random member of `array`, favoring the earlier entries.
  52177. *
  52178. * @method Phaser.RandomDataGenerator#weightedPick
  52179. * @param {Array} ary - An Array to pick a random member of.
  52180. * @return {any} A random member of the array.
  52181. */
  52182. weightedPick: function (ary) {
  52183. return ary[~~(Math.pow(this.frac(), 2) * (ary.length - 1) + 0.5)];
  52184. },
  52185. /**
  52186. * Returns a random timestamp between min and max, or between the beginning of 2000 and the end of 2020 if min and max aren't specified.
  52187. *
  52188. * @method Phaser.RandomDataGenerator#timestamp
  52189. * @param {number} min - The minimum value in the range.
  52190. * @param {number} max - The maximum value in the range.
  52191. * @return {number} A random timestamp between min and max.
  52192. */
  52193. timestamp: function (min, max) {
  52194. return this.realInRange(min || 946684800000, max || 1577862000000);
  52195. },
  52196. /**
  52197. * Returns a random angle between -180 and 180.
  52198. *
  52199. * @method Phaser.RandomDataGenerator#angle
  52200. * @return {number} A random number between -180 and 180.
  52201. */
  52202. angle: function() {
  52203. return this.integerInRange(-180, 180);
  52204. },
  52205. /**
  52206. * Gets or Sets the state of the generator. This allows you to retain the values
  52207. * that the generator is using between games, i.e. in a game save file.
  52208. *
  52209. * To seed this generator with a previously saved state you can pass it as the
  52210. * `seed` value in your game config, or call this method directly after Phaser has booted.
  52211. *
  52212. * Call this method with no parameters to return the current state.
  52213. *
  52214. * If providing a state it should match the same format that this method
  52215. * returns, which is a string with a header `!rnd` followed by the `c`,
  52216. * `s0`, `s1` and `s2` values respectively, each comma-delimited.
  52217. *
  52218. * @method Phaser.RandomDataGenerator#state
  52219. * @param {string} [state] - Generator state to be set.
  52220. * @return {string} The current state of the generator.
  52221. */
  52222. state: function (state) {
  52223. if (typeof state === 'string' && state.match(/^!rnd/))
  52224. {
  52225. state = state.split(',');
  52226. this.c = parseFloat(state[1]);
  52227. this.s0 = parseFloat(state[2]);
  52228. this.s1 = parseFloat(state[3]);
  52229. this.s2 = parseFloat(state[4]);
  52230. }
  52231. return ['!rnd', this.c, this.s0, this.s1, this.s2].join(',');
  52232. }
  52233. };
  52234. Phaser.RandomDataGenerator.prototype.constructor = Phaser.RandomDataGenerator;
  52235. /**
  52236. * @author Timo Hausmann
  52237. * @author Richard Davey <rich@photonstorm.com>
  52238. * @copyright 2016 Photon Storm Ltd.
  52239. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  52240. */
  52241. /**
  52242. * A QuadTree implementation. The original code was a conversion of the Java code posted to GameDevTuts.
  52243. * However I've tweaked it massively to add node indexing, removed lots of temp. var creation and significantly increased performance as a result.
  52244. * Original version at https://github.com/timohausmann/quadtree-js/
  52245. *
  52246. * @class Phaser.QuadTree
  52247. * @constructor
  52248. * @param {number} x - The top left coordinate of the quadtree.
  52249. * @param {number} y - The top left coordinate of the quadtree.
  52250. * @param {number} width - The width of the quadtree in pixels.
  52251. * @param {number} height - The height of the quadtree in pixels.
  52252. * @param {number} [maxObjects=10] - The maximum number of objects per node.
  52253. * @param {number} [maxLevels=4] - The maximum number of levels to iterate to.
  52254. * @param {number} [level=0] - Which level is this?
  52255. */
  52256. Phaser.QuadTree = function(x, y, width, height, maxObjects, maxLevels, level) {
  52257. /**
  52258. * @property {number} maxObjects - The maximum number of objects per node.
  52259. * @default
  52260. */
  52261. this.maxObjects = 10;
  52262. /**
  52263. * @property {number} maxLevels - The maximum number of levels to break down to.
  52264. * @default
  52265. */
  52266. this.maxLevels = 4;
  52267. /**
  52268. * @property {number} level - The current level.
  52269. */
  52270. this.level = 0;
  52271. /**
  52272. * @property {object} bounds - Object that contains the quadtree bounds.
  52273. */
  52274. this.bounds = {};
  52275. /**
  52276. * @property {array} objects - Array of quadtree children.
  52277. */
  52278. this.objects = [];
  52279. /**
  52280. * @property {array} nodes - Array of associated child nodes.
  52281. */
  52282. this.nodes = [];
  52283. /**
  52284. * @property {array} _empty - Internal empty array.
  52285. * @private
  52286. */
  52287. this._empty = [];
  52288. this.reset(x, y, width, height, maxObjects, maxLevels, level);
  52289. };
  52290. Phaser.QuadTree.prototype = {
  52291. /**
  52292. * Resets the QuadTree.
  52293. *
  52294. * @method Phaser.QuadTree#reset
  52295. * @param {number} x - The top left coordinate of the quadtree.
  52296. * @param {number} y - The top left coordinate of the quadtree.
  52297. * @param {number} width - The width of the quadtree in pixels.
  52298. * @param {number} height - The height of the quadtree in pixels.
  52299. * @param {number} [maxObjects=10] - The maximum number of objects per node.
  52300. * @param {number} [maxLevels=4] - The maximum number of levels to iterate to.
  52301. * @param {number} [level=0] - Which level is this?
  52302. */
  52303. reset: function (x, y, width, height, maxObjects, maxLevels, level) {
  52304. this.maxObjects = maxObjects || 10;
  52305. this.maxLevels = maxLevels || 4;
  52306. this.level = level || 0;
  52307. this.bounds = {
  52308. x: Math.round(x),
  52309. y: Math.round(y),
  52310. width: width,
  52311. height: height,
  52312. subWidth: Math.floor(width / 2),
  52313. subHeight: Math.floor(height / 2),
  52314. right: Math.round(x) + Math.floor(width / 2),
  52315. bottom: Math.round(y) + Math.floor(height / 2)
  52316. };
  52317. this.objects.length = 0;
  52318. this.nodes.length = 0;
  52319. },
  52320. /**
  52321. * Populates this quadtree with the children of the given Group. In order to be added the child must exist and have a body property.
  52322. *
  52323. * @method Phaser.QuadTree#populate
  52324. * @param {Phaser.Group} group - The Group to add to the quadtree.
  52325. */
  52326. populate: function (group) {
  52327. group.forEach(this.populateHandler, this, true);
  52328. },
  52329. /**
  52330. * Handler for the populate method.
  52331. *
  52332. * @method Phaser.QuadTree#populateHandler
  52333. * @param {Phaser.Sprite|object} sprite - The Sprite to check.
  52334. */
  52335. populateHandler: function (sprite) {
  52336. if (sprite.body && sprite.exists)
  52337. {
  52338. this.insert(sprite.body);
  52339. }
  52340. },
  52341. /**
  52342. * Split the node into 4 subnodes
  52343. *
  52344. * @method Phaser.QuadTree#split
  52345. */
  52346. split: function () {
  52347. // top right node
  52348. this.nodes[0] = new Phaser.QuadTree(this.bounds.right, this.bounds.y, this.bounds.subWidth, this.bounds.subHeight, this.maxObjects, this.maxLevels, (this.level + 1));
  52349. // top left node
  52350. this.nodes[1] = new Phaser.QuadTree(this.bounds.x, this.bounds.y, this.bounds.subWidth, this.bounds.subHeight, this.maxObjects, this.maxLevels, (this.level + 1));
  52351. // bottom left node
  52352. this.nodes[2] = new Phaser.QuadTree(this.bounds.x, this.bounds.bottom, this.bounds.subWidth, this.bounds.subHeight, this.maxObjects, this.maxLevels, (this.level + 1));
  52353. // bottom right node
  52354. this.nodes[3] = new Phaser.QuadTree(this.bounds.right, this.bounds.bottom, this.bounds.subWidth, this.bounds.subHeight, this.maxObjects, this.maxLevels, (this.level + 1));
  52355. },
  52356. /**
  52357. * Insert the object into the node. If the node exceeds the capacity, it will split and add all objects to their corresponding subnodes.
  52358. *
  52359. * @method Phaser.QuadTree#insert
  52360. * @param {Phaser.Physics.Arcade.Body|object} body - The Body object to insert into the quadtree. Can be any object so long as it exposes x, y, right and bottom properties.
  52361. */
  52362. insert: function (body) {
  52363. var i = 0;
  52364. var index;
  52365. // if we have subnodes ...
  52366. if (this.nodes[0] != null)
  52367. {
  52368. index = this.getIndex(body);
  52369. if (index !== -1)
  52370. {
  52371. this.nodes[index].insert(body);
  52372. return;
  52373. }
  52374. }
  52375. this.objects.push(body);
  52376. if (this.objects.length > this.maxObjects && this.level < this.maxLevels)
  52377. {
  52378. // Split if we don't already have subnodes
  52379. if (this.nodes[0] == null)
  52380. {
  52381. this.split();
  52382. }
  52383. // Add objects to subnodes
  52384. while (i < this.objects.length)
  52385. {
  52386. index = this.getIndex(this.objects[i]);
  52387. if (index !== -1)
  52388. {
  52389. // this is expensive - see what we can do about it
  52390. this.nodes[index].insert(this.objects.splice(i, 1)[0]);
  52391. }
  52392. else
  52393. {
  52394. i++;
  52395. }
  52396. }
  52397. }
  52398. },
  52399. /**
  52400. * Determine which node the object belongs to.
  52401. *
  52402. * @method Phaser.QuadTree#getIndex
  52403. * @param {Phaser.Rectangle|object} rect - The bounds in which to check.
  52404. * @return {number} index - Index of the subnode (0-3), or -1 if rect cannot completely fit within a subnode and is part of the parent node.
  52405. */
  52406. getIndex: function (rect) {
  52407. // default is that rect doesn't fit, i.e. it straddles the internal quadrants
  52408. var index = -1;
  52409. if (rect.x < this.bounds.right && rect.right < this.bounds.right)
  52410. {
  52411. if (rect.y < this.bounds.bottom && rect.bottom < this.bounds.bottom)
  52412. {
  52413. // rect fits within the top-left quadrant of this quadtree
  52414. index = 1;
  52415. }
  52416. else if (rect.y > this.bounds.bottom)
  52417. {
  52418. // rect fits within the bottom-left quadrant of this quadtree
  52419. index = 2;
  52420. }
  52421. }
  52422. else if (rect.x > this.bounds.right)
  52423. {
  52424. // rect can completely fit within the right quadrants
  52425. if (rect.y < this.bounds.bottom && rect.bottom < this.bounds.bottom)
  52426. {
  52427. // rect fits within the top-right quadrant of this quadtree
  52428. index = 0;
  52429. }
  52430. else if (rect.y > this.bounds.bottom)
  52431. {
  52432. // rect fits within the bottom-right quadrant of this quadtree
  52433. index = 3;
  52434. }
  52435. }
  52436. return index;
  52437. },
  52438. /**
  52439. * Return all objects that could collide with the given Sprite or Rectangle.
  52440. *
  52441. * @method Phaser.QuadTree#retrieve
  52442. * @param {Phaser.Sprite|Phaser.Rectangle} source - The source object to check the QuadTree against. Either a Sprite or Rectangle.
  52443. * @return {array} - Array with all detected objects.
  52444. */
  52445. retrieve: function (source) {
  52446. if (source instanceof Phaser.Rectangle)
  52447. {
  52448. var returnObjects = this.objects;
  52449. var index = this.getIndex(source);
  52450. }
  52451. else
  52452. {
  52453. if (!source.body)
  52454. {
  52455. return this._empty;
  52456. }
  52457. var returnObjects = this.objects;
  52458. var index = this.getIndex(source.body);
  52459. }
  52460. if (this.nodes[0])
  52461. {
  52462. // If rect fits into a subnode ..
  52463. if (index !== -1)
  52464. {
  52465. returnObjects = returnObjects.concat(this.nodes[index].retrieve(source));
  52466. }
  52467. else
  52468. {
  52469. // If rect does not fit into a subnode, check it against all subnodes (unrolled for speed)
  52470. returnObjects = returnObjects.concat(this.nodes[0].retrieve(source));
  52471. returnObjects = returnObjects.concat(this.nodes[1].retrieve(source));
  52472. returnObjects = returnObjects.concat(this.nodes[2].retrieve(source));
  52473. returnObjects = returnObjects.concat(this.nodes[3].retrieve(source));
  52474. }
  52475. }
  52476. return returnObjects;
  52477. },
  52478. /**
  52479. * Clear the quadtree.
  52480. * @method Phaser.QuadTree#clear
  52481. */
  52482. clear: function () {
  52483. this.objects.length = 0;
  52484. var i = this.nodes.length;
  52485. while (i--)
  52486. {
  52487. this.nodes[i].clear();
  52488. this.nodes.splice(i, 1);
  52489. }
  52490. this.nodes.length = 0;
  52491. }
  52492. };
  52493. Phaser.QuadTree.prototype.constructor = Phaser.QuadTree;
  52494. /**
  52495. * Javascript QuadTree
  52496. * @version 1.0
  52497. *
  52498. * @version 1.3, March 11th 2014
  52499. * @author Richard Davey
  52500. * The original code was a conversion of the Java code posted to GameDevTuts. However I've tweaked
  52501. * it massively to add node indexing, removed lots of temp. var creation and significantly
  52502. * increased performance as a result.
  52503. *
  52504. * Original version at https://github.com/timohausmann/quadtree-js/
  52505. */
  52506. /**
  52507. * @copyright © 2012 Timo Hausmann
  52508. *
  52509. * Permission is hereby granted, free of charge, to any person obtaining
  52510. * a copy of this software and associated documentation files (the
  52511. * "Software"), to deal in the Software without restriction, including
  52512. * without limitation the rights to use, copy, modify, merge, publish,
  52513. * distribute, sublicense, and/or sell copies of the Software, and to
  52514. * permit persons to whom the Software is furnished to do so, subject to
  52515. * the following conditions:
  52516. *
  52517. * The above copyright notice and this permission notice shall be
  52518. * included in all copies or substantial portions of the Software.
  52519. *
  52520. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  52521. * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  52522. * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  52523. * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  52524. * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  52525. * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  52526. * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  52527. */
  52528. /**
  52529. * @author Richard Davey <rich@photonstorm.com>
  52530. * @copyright 2016 Photon Storm Ltd.
  52531. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  52532. */
  52533. /**
  52534. * Phaser.Net handles browser URL related tasks such as checking host names, domain names and query string manipulation.
  52535. *
  52536. * @class Phaser.Net
  52537. * @constructor
  52538. * @param {Phaser.Game} game - A reference to the currently running game.
  52539. */
  52540. Phaser.Net = function (game) {
  52541. this.game = game;
  52542. };
  52543. Phaser.Net.prototype = {
  52544. /**
  52545. * Returns the hostname given by the browser.
  52546. *
  52547. * @method Phaser.Net#getHostName
  52548. * @return {string}
  52549. */
  52550. getHostName: function () {
  52551. if (window.location && window.location.hostname) {
  52552. return window.location.hostname;
  52553. }
  52554. return null;
  52555. },
  52556. /**
  52557. * Compares the given domain name against the hostname of the browser containing the game.
  52558. * If the domain name is found it returns true.
  52559. * You can specify a part of a domain, for example 'google' would match 'google.com', 'google.co.uk', etc.
  52560. * Do not include 'http://' at the start.
  52561. *
  52562. * @method Phaser.Net#checkDomainName
  52563. * @param {string} domain
  52564. * @return {boolean} true if the given domain fragment can be found in the window.location.hostname
  52565. */
  52566. checkDomainName: function (domain) {
  52567. return window.location.hostname.indexOf(domain) !== -1;
  52568. },
  52569. /**
  52570. * Updates a value on the Query String and returns it in full.
  52571. * If the value doesn't already exist it is set.
  52572. * If the value exists it is replaced with the new value given. If you don't provide a new value it is removed from the query string.
  52573. * Optionally you can redirect to the new url, or just return it as a string.
  52574. *
  52575. * @method Phaser.Net#updateQueryString
  52576. * @param {string} key - The querystring key to update.
  52577. * @param {string} value - The new value to be set. If it already exists it will be replaced.
  52578. * @param {boolean} redirect - If true the browser will issue a redirect to the url with the new querystring.
  52579. * @param {string} url - The URL to modify. If none is given it uses window.location.href.
  52580. * @return {string} If redirect is false then the modified url and query string is returned.
  52581. */
  52582. updateQueryString: function (key, value, redirect, url) {
  52583. if (redirect === undefined) { redirect = false; }
  52584. if (url === undefined || url === '') { url = window.location.href; }
  52585. var output = '';
  52586. var re = new RegExp("([?|&])" + key + "=.*?(&|#|$)(.*)", "gi");
  52587. if (re.test(url))
  52588. {
  52589. if (typeof value !== 'undefined' && value !== null)
  52590. {
  52591. output = url.replace(re, '$1' + key + "=" + value + '$2$3');
  52592. }
  52593. else
  52594. {
  52595. output = url.replace(re, '$1$3').replace(/(&|\?)$/, '');
  52596. }
  52597. }
  52598. else
  52599. {
  52600. if (typeof value !== 'undefined' && value !== null)
  52601. {
  52602. var separator = url.indexOf('?') !== -1 ? '&' : '?';
  52603. var hash = url.split('#');
  52604. url = hash[0] + separator + key + '=' + value;
  52605. if (hash[1]) {
  52606. url += '#' + hash[1];
  52607. }
  52608. output = url;
  52609. }
  52610. else
  52611. {
  52612. output = url;
  52613. }
  52614. }
  52615. if (redirect)
  52616. {
  52617. window.location.href = output;
  52618. }
  52619. else
  52620. {
  52621. return output;
  52622. }
  52623. },
  52624. /**
  52625. * Returns the Query String as an object.
  52626. * If you specify a parameter it will return just the value of that parameter, should it exist.
  52627. *
  52628. * @method Phaser.Net#getQueryString
  52629. * @param {string} [parameter=''] - If specified this will return just the value for that key.
  52630. * @return {string|object} An object containing the key value pairs found in the query string or just the value if a parameter was given.
  52631. */
  52632. getQueryString: function (parameter) {
  52633. if (parameter === undefined) { parameter = ''; }
  52634. var output = {};
  52635. var keyValues = location.search.substring(1).split('&');
  52636. for (var i in keyValues)
  52637. {
  52638. var key = keyValues[i].split('=');
  52639. if (key.length > 1)
  52640. {
  52641. if (parameter && parameter === this.decodeURI(key[0]))
  52642. {
  52643. return this.decodeURI(key[1]);
  52644. }
  52645. else
  52646. {
  52647. output[this.decodeURI(key[0])] = this.decodeURI(key[1]);
  52648. }
  52649. }
  52650. }
  52651. return output;
  52652. },
  52653. /**
  52654. * Takes a Uniform Resource Identifier (URI) component (previously created by encodeURIComponent or by a similar routine) and
  52655. * decodes it, replacing \ with spaces in the return. Used internally by the Net classes.
  52656. *
  52657. * @method Phaser.Net#decodeURI
  52658. * @param {string} value - The URI component to be decoded.
  52659. * @return {string} The decoded value.
  52660. */
  52661. decodeURI: function (value) {
  52662. return decodeURIComponent(value.replace(/\+/g, " "));
  52663. }
  52664. };
  52665. Phaser.Net.prototype.constructor = Phaser.Net;
  52666. /**
  52667. * @author Richard Davey <rich@photonstorm.com>
  52668. * @copyright 2016 Photon Storm Ltd.
  52669. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  52670. */
  52671. /**
  52672. * Phaser.Game has a single instance of the TweenManager through which all Tween objects are created and updated.
  52673. * Tweens are hooked into the game clock and pause system, adjusting based on the game state.
  52674. *
  52675. * TweenManager is based heavily on tween.js by http://soledadpenades.com.
  52676. * The difference being that tweens belong to a games instance of TweenManager, rather than to a global TWEEN object.
  52677. * It also has callbacks swapped for Signals and a few issues patched with regard to properties and completion errors.
  52678. * Please see https://github.com/sole/tween.js for a full list of contributors.
  52679. *
  52680. * @class Phaser.TweenManager
  52681. * @constructor
  52682. * @param {Phaser.Game} game - A reference to the currently running game.
  52683. */
  52684. Phaser.TweenManager = function (game) {
  52685. /**
  52686. * @property {Phaser.Game} game - Local reference to game.
  52687. */
  52688. this.game = game;
  52689. /**
  52690. * Are all newly created Tweens frame or time based? A frame based tween will use the physics elapsed timer when updating. This means
  52691. * it will retain the same consistent frame rate, regardless of the speed of the device. The duration value given should
  52692. * be given in frames.
  52693. *
  52694. * If the Tween uses a time based update (which is the default) then the duration is given in milliseconds.
  52695. * In this situation a 2000ms tween will last exactly 2 seconds, regardless of the device and how many visual updates the tween
  52696. * has actually been through. For very short tweens you may wish to experiment with a frame based update instead.
  52697. * @property {boolean} frameBased
  52698. * @default
  52699. */
  52700. this.frameBased = false;
  52701. /**
  52702. * @property {array<Phaser.Tween>} _tweens - All of the currently running tweens.
  52703. * @private
  52704. */
  52705. this._tweens = [];
  52706. /**
  52707. * @property {array<Phaser.Tween>} _add - All of the tweens queued to be added in the next update.
  52708. * @private
  52709. */
  52710. this._add = [];
  52711. this.easeMap = {
  52712. "Power0": Phaser.Easing.Power0,
  52713. "Power1": Phaser.Easing.Power1,
  52714. "Power2": Phaser.Easing.Power2,
  52715. "Power3": Phaser.Easing.Power3,
  52716. "Power4": Phaser.Easing.Power4,
  52717. "Linear": Phaser.Easing.Linear.None,
  52718. "Quad": Phaser.Easing.Quadratic.Out,
  52719. "Cubic": Phaser.Easing.Cubic.Out,
  52720. "Quart": Phaser.Easing.Quartic.Out,
  52721. "Quint": Phaser.Easing.Quintic.Out,
  52722. "Sine": Phaser.Easing.Sinusoidal.Out,
  52723. "Expo": Phaser.Easing.Exponential.Out,
  52724. "Circ": Phaser.Easing.Circular.Out,
  52725. "Elastic": Phaser.Easing.Elastic.Out,
  52726. "Back": Phaser.Easing.Back.Out,
  52727. "Bounce": Phaser.Easing.Bounce.Out,
  52728. "Quad.easeIn": Phaser.Easing.Quadratic.In,
  52729. "Cubic.easeIn": Phaser.Easing.Cubic.In,
  52730. "Quart.easeIn": Phaser.Easing.Quartic.In,
  52731. "Quint.easeIn": Phaser.Easing.Quintic.In,
  52732. "Sine.easeIn": Phaser.Easing.Sinusoidal.In,
  52733. "Expo.easeIn": Phaser.Easing.Exponential.In,
  52734. "Circ.easeIn": Phaser.Easing.Circular.In,
  52735. "Elastic.easeIn": Phaser.Easing.Elastic.In,
  52736. "Back.easeIn": Phaser.Easing.Back.In,
  52737. "Bounce.easeIn": Phaser.Easing.Bounce.In,
  52738. "Quad.easeOut": Phaser.Easing.Quadratic.Out,
  52739. "Cubic.easeOut": Phaser.Easing.Cubic.Out,
  52740. "Quart.easeOut": Phaser.Easing.Quartic.Out,
  52741. "Quint.easeOut": Phaser.Easing.Quintic.Out,
  52742. "Sine.easeOut": Phaser.Easing.Sinusoidal.Out,
  52743. "Expo.easeOut": Phaser.Easing.Exponential.Out,
  52744. "Circ.easeOut": Phaser.Easing.Circular.Out,
  52745. "Elastic.easeOut": Phaser.Easing.Elastic.Out,
  52746. "Back.easeOut": Phaser.Easing.Back.Out,
  52747. "Bounce.easeOut": Phaser.Easing.Bounce.Out,
  52748. "Quad.easeInOut": Phaser.Easing.Quadratic.InOut,
  52749. "Cubic.easeInOut": Phaser.Easing.Cubic.InOut,
  52750. "Quart.easeInOut": Phaser.Easing.Quartic.InOut,
  52751. "Quint.easeInOut": Phaser.Easing.Quintic.InOut,
  52752. "Sine.easeInOut": Phaser.Easing.Sinusoidal.InOut,
  52753. "Expo.easeInOut": Phaser.Easing.Exponential.InOut,
  52754. "Circ.easeInOut": Phaser.Easing.Circular.InOut,
  52755. "Elastic.easeInOut": Phaser.Easing.Elastic.InOut,
  52756. "Back.easeInOut": Phaser.Easing.Back.InOut,
  52757. "Bounce.easeInOut": Phaser.Easing.Bounce.InOut
  52758. };
  52759. this.game.onPause.add(this._pauseAll, this);
  52760. this.game.onResume.add(this._resumeAll, this);
  52761. };
  52762. Phaser.TweenManager.prototype = {
  52763. /**
  52764. * Get all the tween objects in an array.
  52765. * @method Phaser.TweenManager#getAll
  52766. * @returns {Phaser.Tween[]} Array with all tween objects.
  52767. */
  52768. getAll: function () {
  52769. return this._tweens;
  52770. },
  52771. /**
  52772. * Remove all tweens running and in the queue. Doesn't call any of the tween onComplete events.
  52773. * @method Phaser.TweenManager#removeAll
  52774. */
  52775. removeAll: function () {
  52776. for (var i = 0; i < this._tweens.length; i++)
  52777. {
  52778. this._tweens[i].pendingDelete = true;
  52779. }
  52780. this._add = [];
  52781. },
  52782. /**
  52783. * Remove all tweens from a specific object, array of objects or Group.
  52784. *
  52785. * @method Phaser.TweenManager#removeFrom
  52786. * @param {object|object[]|Phaser.Group} obj - The object you want to remove the tweens from.
  52787. * @param {boolean} [children=true] - If passing a group, setting this to true will remove the tweens from all of its children instead of the group itself.
  52788. */
  52789. removeFrom: function (obj, children) {
  52790. if (children === undefined) { children = true; }
  52791. var i;
  52792. var len;
  52793. if (Array.isArray(obj))
  52794. {
  52795. for (i = 0, len = obj.length; i < len; i++)
  52796. {
  52797. this.removeFrom(obj[i]);
  52798. }
  52799. }
  52800. else if (obj.type === Phaser.GROUP && children)
  52801. {
  52802. for (var i = 0, len = obj.children.length; i < len; i++)
  52803. {
  52804. this.removeFrom(obj.children[i]);
  52805. }
  52806. }
  52807. else
  52808. {
  52809. for (i = 0, len = this._tweens.length; i < len; i++)
  52810. {
  52811. if (obj === this._tweens[i].target)
  52812. {
  52813. this.remove(this._tweens[i]);
  52814. }
  52815. }
  52816. for (i = 0, len = this._add.length; i < len; i++)
  52817. {
  52818. if (obj === this._add[i].target)
  52819. {
  52820. this.remove(this._add[i]);
  52821. }
  52822. }
  52823. }
  52824. },
  52825. /**
  52826. * Add a new tween into the TweenManager.
  52827. *
  52828. * @method Phaser.TweenManager#add
  52829. * @param {Phaser.Tween} tween - The tween object you want to add.
  52830. * @returns {Phaser.Tween} The tween object you added to the manager.
  52831. */
  52832. add: function (tween) {
  52833. tween._manager = this;
  52834. this._add.push(tween);
  52835. },
  52836. /**
  52837. * Create a tween object for a specific object. The object can be any JavaScript object or Phaser object such as Sprite.
  52838. *
  52839. * @method Phaser.TweenManager#create
  52840. * @param {object} object - Object the tween will be run on.
  52841. * @returns {Phaser.Tween} The newly created tween object.
  52842. */
  52843. create: function (object) {
  52844. return new Phaser.Tween(object, this.game, this);
  52845. },
  52846. /**
  52847. * Remove a tween from this manager.
  52848. *
  52849. * @method Phaser.TweenManager#remove
  52850. * @param {Phaser.Tween} tween - The tween object you want to remove.
  52851. */
  52852. remove: function (tween) {
  52853. var i = this._tweens.indexOf(tween);
  52854. if (i !== -1)
  52855. {
  52856. this._tweens[i].pendingDelete = true;
  52857. }
  52858. else
  52859. {
  52860. i = this._add.indexOf(tween);
  52861. if (i !== -1)
  52862. {
  52863. this._add[i].pendingDelete = true;
  52864. }
  52865. }
  52866. },
  52867. /**
  52868. * Update all the tween objects you added to this manager.
  52869. *
  52870. * @method Phaser.TweenManager#update
  52871. * @returns {boolean} Return false if there's no tween to update, otherwise return true.
  52872. */
  52873. update: function () {
  52874. var addTweens = this._add.length;
  52875. var numTweens = this._tweens.length;
  52876. if (numTweens === 0 && addTweens === 0)
  52877. {
  52878. return false;
  52879. }
  52880. var i = 0;
  52881. while (i < numTweens)
  52882. {
  52883. if (this._tweens[i].update(this.game.time.time))
  52884. {
  52885. i++;
  52886. }
  52887. else
  52888. {
  52889. this._tweens.splice(i, 1);
  52890. numTweens--;
  52891. }
  52892. }
  52893. // If there are any new tweens to be added, do so now - otherwise they can be spliced out of the array before ever running
  52894. if (addTweens > 0)
  52895. {
  52896. this._tweens = this._tweens.concat(this._add);
  52897. this._add.length = 0;
  52898. }
  52899. return true;
  52900. },
  52901. /**
  52902. * Checks to see if a particular Sprite is currently being tweened.
  52903. *
  52904. * @method Phaser.TweenManager#isTweening
  52905. * @param {object} object - The object to check for tweens against.
  52906. * @returns {boolean} Returns true if the object is currently being tweened, false if not.
  52907. */
  52908. isTweening: function(object) {
  52909. return this._tweens.some(function(tween) {
  52910. return tween.target === object;
  52911. });
  52912. },
  52913. /**
  52914. * Private. Called by game focus loss. Pauses all currently running tweens.
  52915. *
  52916. * @method Phaser.TweenManager#_pauseAll
  52917. * @private
  52918. */
  52919. _pauseAll: function () {
  52920. for (var i = this._tweens.length - 1; i >= 0; i--)
  52921. {
  52922. this._tweens[i]._pause();
  52923. }
  52924. },
  52925. /**
  52926. * Private. Called by game focus loss. Resumes all currently paused tweens.
  52927. *
  52928. * @method Phaser.TweenManager#_resumeAll
  52929. * @private
  52930. */
  52931. _resumeAll: function () {
  52932. for (var i = this._tweens.length - 1; i >= 0; i--)
  52933. {
  52934. this._tweens[i]._resume();
  52935. }
  52936. },
  52937. /**
  52938. * Pauses all currently running tweens.
  52939. *
  52940. * @method Phaser.TweenManager#pauseAll
  52941. */
  52942. pauseAll: function () {
  52943. for (var i = this._tweens.length - 1; i >= 0; i--)
  52944. {
  52945. this._tweens[i].pause();
  52946. }
  52947. },
  52948. /**
  52949. * Resumes all currently paused tweens.
  52950. *
  52951. * @method Phaser.TweenManager#resumeAll
  52952. */
  52953. resumeAll: function () {
  52954. for (var i = this._tweens.length - 1; i >= 0; i--)
  52955. {
  52956. this._tweens[i].resume(true);
  52957. }
  52958. }
  52959. };
  52960. Phaser.TweenManager.prototype.constructor = Phaser.TweenManager;
  52961. /**
  52962. * @author Richard Davey <rich@photonstorm.com>
  52963. * @copyright 2016 Photon Storm Ltd.
  52964. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  52965. */
  52966. /**
  52967. * A Tween allows you to alter one or more properties of a target object over a defined period of time.
  52968. * This can be used for things such as alpha fading Sprites, scaling them or motion.
  52969. * Use `Tween.to` or `Tween.from` to set-up the tween values. You can create multiple tweens on the same object
  52970. * by calling Tween.to multiple times on the same Tween. Additional tweens specified in this way become "child" tweens and
  52971. * are played through in sequence. You can use Tween.timeScale and Tween.reverse to control the playback of this Tween and all of its children.
  52972. *
  52973. * @class Phaser.Tween
  52974. * @constructor
  52975. * @param {object} target - The target object, such as a Phaser.Sprite or Phaser.Sprite.scale.
  52976. * @param {Phaser.Game} game - Current game instance.
  52977. * @param {Phaser.TweenManager} manager - The TweenManager responsible for looking after this Tween.
  52978. */
  52979. Phaser.Tween = function (target, game, manager) {
  52980. /**
  52981. * @property {Phaser.Game} game - A reference to the currently running Game.
  52982. */
  52983. this.game = game;
  52984. /**
  52985. * @property {object} target - The target object, such as a Phaser.Sprite or property like Phaser.Sprite.scale.
  52986. */
  52987. this.target = target;
  52988. /**
  52989. * @property {Phaser.TweenManager} manager - Reference to the TweenManager responsible for updating this Tween.
  52990. */
  52991. this.manager = manager;
  52992. /**
  52993. * @property {Array} timeline - An Array of TweenData objects that comprise the different parts of this Tween.
  52994. */
  52995. this.timeline = [];
  52996. /**
  52997. * If set to `true` the current tween will play in reverse.
  52998. * If the tween hasn't yet started this has no effect.
  52999. * If there are child tweens then all child tweens will play in reverse from the current point.
  53000. * @property {boolean} reverse
  53001. * @default
  53002. */
  53003. this.reverse = false;
  53004. /**
  53005. * The speed at which the tweens will run. A value of 1 means it will match the game frame rate. 0.5 will run at half the frame rate. 2 at double the frame rate, etc.
  53006. * If a tweens duration is 1 second but timeScale is 0.5 then it will take 2 seconds to complete.
  53007. *
  53008. * @property {number} timeScale
  53009. * @default
  53010. */
  53011. this.timeScale = 1;
  53012. /**
  53013. * @property {number} repeatCounter - If the Tween and any child tweens are set to repeat this contains the current repeat count.
  53014. */
  53015. this.repeatCounter = 0;
  53016. /**
  53017. * @property {boolean} pendingDelete - True if this Tween is ready to be deleted by the TweenManager.
  53018. * @default
  53019. * @readonly
  53020. */
  53021. this.pendingDelete = false;
  53022. /**
  53023. * The onStart event is fired when the Tween begins. If there is a delay before the tween starts then onStart fires after the delay is finished.
  53024. * It will be sent 2 parameters: the target object and this tween.
  53025. * @property {Phaser.Signal} onStart
  53026. */
  53027. this.onStart = new Phaser.Signal();
  53028. /**
  53029. * The onLoop event is fired if the Tween, or any child tweens loop.
  53030. * It will be sent 2 parameters: the target object and this tween.
  53031. *
  53032. * @property {Phaser.Signal} onLoop
  53033. */
  53034. this.onLoop = new Phaser.Signal();
  53035. /**
  53036. * The onRepeat event is fired if the Tween and all of its children repeats. If this tween has no children this will never be fired.
  53037. * It will be sent 2 parameters: the target object and this tween.
  53038. * @property {Phaser.Signal} onRepeat
  53039. */
  53040. this.onRepeat = new Phaser.Signal();
  53041. /**
  53042. * The onChildComplete event is fired when the Tween or any of its children completes.
  53043. * Fires every time a child completes unless a child is set to repeat forever.
  53044. * It will be sent 2 parameters: the target object and this tween.
  53045. * @property {Phaser.Signal} onChildComplete
  53046. */
  53047. this.onChildComplete = new Phaser.Signal();
  53048. /**
  53049. * The onComplete event is fired when the Tween and all of its children completes. Does not fire if the Tween is set to loop or repeatAll(-1).
  53050. * It will be sent 2 parameters: the target object and this tween.
  53051. * @property {Phaser.Signal} onComplete
  53052. */
  53053. this.onComplete = new Phaser.Signal();
  53054. /**
  53055. * @property {boolean} isRunning - If the tween is running this is set to true, otherwise false. Tweens that are in a delayed state or waiting to start are considered as being running.
  53056. * @default
  53057. */
  53058. this.isRunning = false;
  53059. /**
  53060. * @property {number} current - The current Tween child being run.
  53061. * @default
  53062. * @readonly
  53063. */
  53064. this.current = 0;
  53065. /**
  53066. * @property {object} properties - Target property cache used when building the child data values.
  53067. */
  53068. this.properties = {};
  53069. /**
  53070. * @property {Phaser.Tween} chainedTween - If this Tween is chained to another this holds a reference to it.
  53071. */
  53072. this.chainedTween = null;
  53073. /**
  53074. * @property {boolean} isPaused - Is this Tween paused or not?
  53075. * @default
  53076. */
  53077. this.isPaused = false;
  53078. /**
  53079. * Is this Tween frame or time based? A frame based tween will use the physics elapsed timer when updating. This means
  53080. * it will retain the same consistent frame rate, regardless of the speed of the device. The duration value given should
  53081. * be given in frames.
  53082. *
  53083. * If the Tween uses a time based update (which is the default) then the duration is given in milliseconds.
  53084. * In this situation a 2000ms tween will last exactly 2 seconds, regardless of the device and how many visual updates the tween
  53085. * has actually been through. For very short tweens you may wish to experiment with a frame based update instead.
  53086. *
  53087. * The default value is whatever you've set in TweenManager.frameBased.
  53088. *
  53089. * @property {boolean} frameBased
  53090. * @default
  53091. */
  53092. this.frameBased = manager.frameBased;
  53093. /**
  53094. * @property {function} _onUpdateCallback - An onUpdate callback.
  53095. * @private
  53096. * @default null
  53097. */
  53098. this._onUpdateCallback = null;
  53099. /**
  53100. * @property {object} _onUpdateCallbackContext - The context in which to call the onUpdate callback.
  53101. * @private
  53102. * @default null
  53103. */
  53104. this._onUpdateCallbackContext = null;
  53105. /**
  53106. * @property {number} _pausedTime - Private pause timer.
  53107. * @private
  53108. * @default
  53109. */
  53110. this._pausedTime = 0;
  53111. /**
  53112. * @property {boolean} _codePaused - Was the Tween paused by code or by Game focus loss?
  53113. * @private
  53114. */
  53115. this._codePaused = false;
  53116. /**
  53117. * @property {boolean} _hasStarted - Internal var to track if the Tween has started yet or not.
  53118. * @private
  53119. */
  53120. this._hasStarted = false;
  53121. };
  53122. Phaser.Tween.prototype = {
  53123. /**
  53124. * Sets this tween to be a `to` tween on the properties given. A `to` tween starts at the current value and tweens to the destination value given.
  53125. * For example a Sprite with an `x` coordinate of 100 could be tweened to `x` 200 by giving a properties object of `{ x: 200 }`.
  53126. * The ease function allows you define the rate of change. You can pass either a function such as Phaser.Easing.Circular.Out or a string such as "Circ".
  53127. * ".easeIn", ".easeOut" and "easeInOut" variants are all supported for all ease types.
  53128. *
  53129. * @method Phaser.Tween#to
  53130. * @param {object} properties - An object containing the properties you want to tween, such as `Sprite.x` or `Sound.volume`. Given as a JavaScript object.
  53131. * @param {number} [duration=1000] - Duration of this tween in ms. Or if `Tween.frameBased` is true this represents the number of frames that should elapse.
  53132. * @param {function|string} [ease=null] - Easing function. If not set it will default to Phaser.Easing.Default, which is Phaser.Easing.Linear.None by default but can be over-ridden.
  53133. * @param {boolean} [autoStart=false] - Set to `true` to allow this tween to start automatically. Otherwise call Tween.start().
  53134. * @param {number} [delay=0] - Delay before this tween will start in milliseconds. Defaults to 0, no delay.
  53135. * @param {number} [repeat=0] - Should the tween automatically restart once complete? If you want it to run forever set as -1. This only effects this individual tween, not any chained tweens.
  53136. * @param {boolean} [yoyo=false] - A tween that yoyos will reverse itself and play backwards automatically. A yoyo'd tween doesn't fire the Tween.onComplete event, so listen for Tween.onLoop instead.
  53137. * @return {Phaser.Tween} This Tween object.
  53138. */
  53139. to: function (properties, duration, ease, autoStart, delay, repeat, yoyo) {
  53140. if (duration === undefined || duration <= 0) { duration = 1000; }
  53141. if (ease === undefined || ease === null) { ease = Phaser.Easing.Default; }
  53142. if (autoStart === undefined) { autoStart = false; }
  53143. if (delay === undefined) { delay = 0; }
  53144. if (repeat === undefined) { repeat = 0; }
  53145. if (yoyo === undefined) { yoyo = false; }
  53146. if (typeof ease === 'string' && this.manager.easeMap[ease])
  53147. {
  53148. ease = this.manager.easeMap[ease];
  53149. }
  53150. if (this.isRunning)
  53151. {
  53152. console.warn('Phaser.Tween.to cannot be called after Tween.start');
  53153. return this;
  53154. }
  53155. this.timeline.push(new Phaser.TweenData(this).to(properties, duration, ease, delay, repeat, yoyo));
  53156. if (autoStart)
  53157. {
  53158. this.start();
  53159. }
  53160. return this;
  53161. },
  53162. /**
  53163. * Sets this tween to be a `from` tween on the properties given. A `from` tween sets the target to the destination value and tweens to its current value.
  53164. * For example a Sprite with an `x` coordinate of 100 tweened from `x` 500 would be set to `x` 500 and then tweened to `x` 100 by giving a properties object of `{ x: 500 }`.
  53165. * The ease function allows you define the rate of change. You can pass either a function such as Phaser.Easing.Circular.Out or a string such as "Circ".
  53166. * ".easeIn", ".easeOut" and "easeInOut" variants are all supported for all ease types.
  53167. *
  53168. * @method Phaser.Tween#from
  53169. * @param {object} properties - An object containing the properties you want to tween., such as `Sprite.x` or `Sound.volume`. Given as a JavaScript object.
  53170. * @param {number} [duration=1000] - Duration of this tween in ms. Or if `Tween.frameBased` is true this represents the number of frames that should elapse.
  53171. * @param {function|string} [ease=null] - Easing function. If not set it will default to Phaser.Easing.Default, which is Phaser.Easing.Linear.None by default but can be over-ridden.
  53172. * @param {boolean} [autoStart=false] - Set to `true` to allow this tween to start automatically. Otherwise call Tween.start().
  53173. * @param {number} [delay=0] - Delay before this tween will start in milliseconds. Defaults to 0, no delay.
  53174. * @param {number} [repeat=0] - Should the tween automatically restart once complete? If you want it to run forever set as -1. This only effects this individual tween, not any chained tweens.
  53175. * @param {boolean} [yoyo=false] - A tween that yoyos will reverse itself and play backwards automatically. A yoyo'd tween doesn't fire the Tween.onComplete event, so listen for Tween.onLoop instead.
  53176. * @return {Phaser.Tween} This Tween object.
  53177. */
  53178. from: function (properties, duration, ease, autoStart, delay, repeat, yoyo) {
  53179. if (duration === undefined) { duration = 1000; }
  53180. if (ease === undefined || ease === null) { ease = Phaser.Easing.Default; }
  53181. if (autoStart === undefined) { autoStart = false; }
  53182. if (delay === undefined) { delay = 0; }
  53183. if (repeat === undefined) { repeat = 0; }
  53184. if (yoyo === undefined) { yoyo = false; }
  53185. if (typeof ease === 'string' && this.manager.easeMap[ease])
  53186. {
  53187. ease = this.manager.easeMap[ease];
  53188. }
  53189. if (this.isRunning)
  53190. {
  53191. console.warn('Phaser.Tween.from cannot be called after Tween.start');
  53192. return this;
  53193. }
  53194. this.timeline.push(new Phaser.TweenData(this).from(properties, duration, ease, delay, repeat, yoyo));
  53195. if (autoStart)
  53196. {
  53197. this.start();
  53198. }
  53199. return this;
  53200. },
  53201. /**
  53202. * Starts the tween running. Can also be called by the autoStart parameter of `Tween.to` or `Tween.from`.
  53203. * This sets the `Tween.isRunning` property to `true` and dispatches a `Tween.onStart` signal.
  53204. * If the Tween has a delay set then nothing will start tweening until the delay has expired.
  53205. *
  53206. * @method Phaser.Tween#start
  53207. * @param {number} [index=0] - If this Tween contains child tweens you can specify which one to start from. The default is zero, i.e. the first tween created.
  53208. * @return {Phaser.Tween} This tween. Useful for method chaining.
  53209. */
  53210. start: function (index) {
  53211. if (index === undefined) { index = 0; }
  53212. if (this.game === null || this.target === null || this.timeline.length === 0 || this.isRunning)
  53213. {
  53214. return this;
  53215. }
  53216. // Populate the tween data
  53217. for (var i = 0; i < this.timeline.length; i++)
  53218. {
  53219. // Build our master property list with the starting values
  53220. for (var property in this.timeline[i].vEnd)
  53221. {
  53222. this.properties[property] = this.target[property] || 0;
  53223. if (!Array.isArray(this.properties[property]))
  53224. {
  53225. // Ensures we're using numbers, not strings
  53226. this.properties[property] *= 1.0;
  53227. }
  53228. }
  53229. }
  53230. for (var i = 0; i < this.timeline.length; i++)
  53231. {
  53232. this.timeline[i].loadValues();
  53233. }
  53234. this.manager.add(this);
  53235. this.isRunning = true;
  53236. if (index < 0 || index > this.timeline.length - 1)
  53237. {
  53238. index = 0;
  53239. }
  53240. this.current = index;
  53241. this.timeline[this.current].start();
  53242. return this;
  53243. },
  53244. /**
  53245. * Stops the tween if running and flags it for deletion from the TweenManager.
  53246. * If called directly the `Tween.onComplete` signal is not dispatched and no chained tweens are started unless the complete parameter is set to `true`.
  53247. * If you just wish to pause a tween then use Tween.pause instead.
  53248. *
  53249. * @method Phaser.Tween#stop
  53250. * @param {boolean} [complete=false] - Set to `true` to dispatch the Tween.onComplete signal.
  53251. * @return {Phaser.Tween} This tween. Useful for method chaining.
  53252. */
  53253. stop: function (complete) {
  53254. if (complete === undefined) { complete = false; }
  53255. this.isRunning = false;
  53256. this._onUpdateCallback = null;
  53257. this._onUpdateCallbackContext = null;
  53258. if (complete)
  53259. {
  53260. this.onComplete.dispatch(this.target, this);
  53261. this._hasStarted = false;
  53262. if (this.chainedTween)
  53263. {
  53264. this.chainedTween.start();
  53265. }
  53266. }
  53267. this.manager.remove(this);
  53268. return this;
  53269. },
  53270. /**
  53271. * Updates either a single TweenData or all TweenData objects properties to the given value.
  53272. * Used internally by methods like Tween.delay, Tween.yoyo, etc. but can also be called directly if you know which property you want to tweak.
  53273. * The property is not checked, so if you pass an invalid one you'll generate a run-time error.
  53274. *
  53275. * @method Phaser.Tween#updateTweenData
  53276. * @param {string} property - The property to update.
  53277. * @param {number|function} value - The value to set the property to.
  53278. * @param {number} [index=0] - If this tween has more than one child this allows you to target a specific child. If set to -1 it will set the delay on all the children.
  53279. * @return {Phaser.Tween} This tween. Useful for method chaining.
  53280. */
  53281. updateTweenData: function (property, value, index) {
  53282. if (this.timeline.length === 0) { return this; }
  53283. if (index === undefined) { index = 0; }
  53284. if (index === -1)
  53285. {
  53286. for (var i = 0; i < this.timeline.length; i++)
  53287. {
  53288. this.timeline[i][property] = value;
  53289. }
  53290. }
  53291. else
  53292. {
  53293. this.timeline[index][property] = value;
  53294. }
  53295. return this;
  53296. },
  53297. /**
  53298. * Sets the delay in milliseconds before this tween will start. If there are child tweens it sets the delay before the first child starts.
  53299. * The delay is invoked as soon as you call `Tween.start`. If the tween is already running this method doesn't do anything for the current active tween.
  53300. * If you have not yet called `Tween.to` or `Tween.from` at least once then this method will do nothing, as there are no tweens to delay.
  53301. * If you have child tweens and pass -1 as the index value it sets the delay across all of them.
  53302. *
  53303. * @method Phaser.Tween#delay
  53304. * @param {number} duration - The amount of time in ms that the Tween should wait until it begins once started is called. Set to zero to remove any active delay.
  53305. * @param {number} [index=0] - If this tween has more than one child this allows you to target a specific child. If set to -1 it will set the delay on all the children.
  53306. * @return {Phaser.Tween} This tween. Useful for method chaining.
  53307. */
  53308. delay: function (duration, index) {
  53309. return this.updateTweenData('delay', duration, index);
  53310. },
  53311. /**
  53312. * Sets the number of times this tween will repeat.
  53313. * If you have not yet called `Tween.to` or `Tween.from` at least once then this method will do nothing, as there are no tweens to repeat.
  53314. * If you have child tweens and pass -1 as the index value it sets the number of times they'll repeat across all of them.
  53315. * If you wish to define how many times this Tween and all children will repeat see Tween.repeatAll.
  53316. *
  53317. * @method Phaser.Tween#repeat
  53318. * @param {number} total - How many times a tween should repeat before completing. Set to zero to remove an active repeat. Set to -1 to repeat forever.
  53319. * @param {number} [repeat=0] - This is the amount of time to pause (in ms) before the repeat will start.
  53320. * @param {number} [index=0] - If this tween has more than one child this allows you to target a specific child. If set to -1 it will set the repeat value on all the children.
  53321. * @return {Phaser.Tween} This tween. Useful for method chaining.
  53322. */
  53323. repeat: function (total, repeatDelay, index) {
  53324. if (repeatDelay === undefined) { repeatDelay = 0; }
  53325. this.updateTweenData('repeatCounter', total, index);
  53326. return this.updateTweenData('repeatDelay', repeatDelay, index);
  53327. },
  53328. /**
  53329. * Sets the delay in milliseconds before this tween will repeat itself.
  53330. * The repeatDelay is invoked as soon as you call `Tween.start`. If the tween is already running this method doesn't do anything for the current active tween.
  53331. * If you have not yet called `Tween.to` or `Tween.from` at least once then this method will do nothing, as there are no tweens to set repeatDelay on.
  53332. * If you have child tweens and pass -1 as the index value it sets the repeatDelay across all of them.
  53333. *
  53334. * @method Phaser.Tween#repeatDelay
  53335. * @param {number} duration - The amount of time in ms that the Tween should wait until it repeats or yoyos once start is called. Set to zero to remove any active repeatDelay.
  53336. * @param {number} [index=0] - If this tween has more than one child this allows you to target a specific child. If set to -1 it will set the repeatDelay on all the children.
  53337. * @return {Phaser.Tween} This tween. Useful for method chaining.
  53338. */
  53339. repeatDelay: function (duration, index) {
  53340. return this.updateTweenData('repeatDelay', duration, index);
  53341. },
  53342. /**
  53343. * A Tween that has yoyo set to true will run through from its starting values to its end values and then play back in reverse from end to start.
  53344. * Used in combination with repeat you can create endless loops.
  53345. * If you have not yet called `Tween.to` or `Tween.from` at least once then this method will do nothing, as there are no tweens to yoyo.
  53346. * If you have child tweens and pass -1 as the index value it sets the yoyo property across all of them.
  53347. * If you wish to yoyo this Tween and all of its children then see Tween.yoyoAll.
  53348. *
  53349. * @method Phaser.Tween#yoyo
  53350. * @param {boolean} enable - Set to true to yoyo this tween, or false to disable an already active yoyo.
  53351. * @param {number} [yoyoDelay=0] - This is the amount of time to pause (in ms) before the yoyo will start.
  53352. * @param {number} [index=0] - If this tween has more than one child this allows you to target a specific child. If set to -1 it will set yoyo on all the children.
  53353. * @return {Phaser.Tween} This tween. Useful for method chaining.
  53354. */
  53355. yoyo: function(enable, yoyoDelay, index) {
  53356. if (yoyoDelay === undefined) { yoyoDelay = 0; }
  53357. this.updateTweenData('yoyo', enable, index);
  53358. return this.updateTweenData('yoyoDelay', yoyoDelay, index);
  53359. },
  53360. /**
  53361. * Sets the delay in milliseconds before this tween will run a yoyo (only applies if yoyo is enabled).
  53362. * The repeatDelay is invoked as soon as you call `Tween.start`. If the tween is already running this method doesn't do anything for the current active tween.
  53363. * If you have not yet called `Tween.to` or `Tween.from` at least once then this method will do nothing, as there are no tweens to set repeatDelay on.
  53364. * If you have child tweens and pass -1 as the index value it sets the repeatDelay across all of them.
  53365. *
  53366. * @method Phaser.Tween#yoyoDelay
  53367. * @param {number} duration - The amount of time in ms that the Tween should wait until it repeats or yoyos once start is called. Set to zero to remove any active yoyoDelay.
  53368. * @param {number} [index=0] - If this tween has more than one child this allows you to target a specific child. If set to -1 it will set the yoyoDelay on all the children.
  53369. * @return {Phaser.Tween} This tween. Useful for method chaining.
  53370. */
  53371. yoyoDelay: function (duration, index) {
  53372. return this.updateTweenData('yoyoDelay', duration, index);
  53373. },
  53374. /**
  53375. * Set easing function this tween will use, i.e. Phaser.Easing.Linear.None.
  53376. * The ease function allows you define the rate of change. You can pass either a function such as Phaser.Easing.Circular.Out or a string such as "Circ".
  53377. * ".easeIn", ".easeOut" and "easeInOut" variants are all supported for all ease types.
  53378. * If you have child tweens and pass -1 as the index value it sets the easing function defined here across all of them.
  53379. *
  53380. * @method Phaser.Tween#easing
  53381. * @param {function|string} ease - The easing function this tween will use, i.e. Phaser.Easing.Linear.None.
  53382. * @param {number} [index=0] - If this tween has more than one child this allows you to target a specific child. If set to -1 it will set the easing function on all children.
  53383. * @return {Phaser.Tween} This tween. Useful for method chaining.
  53384. */
  53385. easing: function (ease, index) {
  53386. if (typeof ease === 'string' && this.manager.easeMap[ease])
  53387. {
  53388. ease = this.manager.easeMap[ease];
  53389. }
  53390. return this.updateTweenData('easingFunction', ease, index);
  53391. },
  53392. /**
  53393. * Sets the interpolation function the tween will use. By default it uses Phaser.Math.linearInterpolation.
  53394. * Also available: Phaser.Math.bezierInterpolation and Phaser.Math.catmullRomInterpolation.
  53395. * The interpolation function is only used if the target properties is an array.
  53396. * If you have child tweens and pass -1 as the index value and it will set the interpolation function across all of them.
  53397. *
  53398. * @method Phaser.Tween#interpolation
  53399. * @param {function} interpolation - The interpolation function to use (Phaser.Math.linearInterpolation by default)
  53400. * @param {object} [context] - The context under which the interpolation function will be run.
  53401. * @param {number} [index=0] - If this tween has more than one child this allows you to target a specific child. If set to -1 it will set the interpolation function on all children.
  53402. * @return {Phaser.Tween} This tween. Useful for method chaining.
  53403. */
  53404. interpolation: function (interpolation, context, index) {
  53405. if (context === undefined) { context = Phaser.Math; }
  53406. this.updateTweenData('interpolationFunction', interpolation, index);
  53407. return this.updateTweenData('interpolationContext', context, index);
  53408. },
  53409. /**
  53410. * Set how many times this tween and all of its children will repeat.
  53411. * A tween (A) with 3 children (B,C,D) with a `repeatAll` value of 2 would play as: ABCDABCD before completing.
  53412. *
  53413. * @method Phaser.Tween#repeatAll
  53414. * @param {number} [total=0] - How many times this tween and all children should repeat before completing. Set to zero to remove an active repeat. Set to -1 to repeat forever.
  53415. * @return {Phaser.Tween} This tween. Useful for method chaining.
  53416. */
  53417. repeatAll: function (total) {
  53418. if (total === undefined) { total = 0; }
  53419. this.repeatCounter = total;
  53420. return this;
  53421. },
  53422. /**
  53423. * This method allows you to chain tweens together. Any tween chained to this tween will have its `Tween.start` method called
  53424. * as soon as this tween completes. If this tween never completes (i.e. repeatAll or loop is set) then the chain will never progress.
  53425. * Note that `Tween.onComplete` will fire when *this* tween completes, not when the whole chain completes.
  53426. * For that you should listen to `onComplete` on the final tween in your chain.
  53427. *
  53428. * If you pass multiple tweens to this method they will be joined into a single long chain.
  53429. * For example if this is Tween A and you pass in B, C and D then B will be chained to A, C will be chained to B and D will be chained to C.
  53430. * Any previously chained tweens that may have been set will be overwritten.
  53431. *
  53432. * @method Phaser.Tween#chain
  53433. * @param {...Phaser.Tween} tweens - One or more tweens that will be chained to this one.
  53434. * @return {Phaser.Tween} This tween. Useful for method chaining.
  53435. */
  53436. chain: function () {
  53437. var i = arguments.length;
  53438. while (i--)
  53439. {
  53440. if (i > 0)
  53441. {
  53442. arguments[i - 1].chainedTween = arguments[i];
  53443. }
  53444. else
  53445. {
  53446. this.chainedTween = arguments[i];
  53447. }
  53448. }
  53449. return this;
  53450. },
  53451. /**
  53452. * Enables the looping of this tween. The tween will loop forever, and onComplete will never fire.
  53453. *
  53454. * If `value` is `true` then this is the same as setting `Tween.repeatAll(-1)`.
  53455. * If `value` is `false` it is the same as setting `Tween.repeatAll(0)` and will reset the `repeatCounter` to zero.
  53456. *
  53457. * Usage:
  53458. * game.add.tween(p).to({ x: 700 }, 1000, Phaser.Easing.Linear.None, true)
  53459. * .to({ y: 300 }, 1000, Phaser.Easing.Linear.None)
  53460. * .to({ x: 0 }, 1000, Phaser.Easing.Linear.None)
  53461. * .to({ y: 0 }, 1000, Phaser.Easing.Linear.None)
  53462. * .loop();
  53463. * @method Phaser.Tween#loop
  53464. * @param {boolean} [value=true] - If `true` this tween will loop once it reaches the end. Set to `false` to remove an active loop.
  53465. * @return {Phaser.Tween} This tween. Useful for method chaining.
  53466. */
  53467. loop: function (value) {
  53468. if (value === undefined) { value = true; }
  53469. this.repeatCounter = (value) ? -1 : 0;
  53470. return this;
  53471. },
  53472. /**
  53473. * Sets a callback to be fired each time this tween updates.
  53474. *
  53475. * @method Phaser.Tween#onUpdateCallback
  53476. * @param {function} callback - The callback to invoke each time this tween is updated. Set to `null` to remove an already active callback.
  53477. * @param {object} callbackContext - The context in which to call the onUpdate callback.
  53478. * @return {Phaser.Tween} This tween. Useful for method chaining.
  53479. */
  53480. onUpdateCallback: function (callback, callbackContext) {
  53481. this._onUpdateCallback = callback;
  53482. this._onUpdateCallbackContext = callbackContext;
  53483. return this;
  53484. },
  53485. /**
  53486. * Pauses the tween. Resume playback with Tween.resume.
  53487. *
  53488. * @method Phaser.Tween#pause
  53489. */
  53490. pause: function () {
  53491. this.isPaused = true;
  53492. this._codePaused = true;
  53493. this._pausedTime = this.game.time.time;
  53494. },
  53495. /**
  53496. * This is called by the core Game loop. Do not call it directly, instead use Tween.pause.
  53497. *
  53498. * @private
  53499. * @method Phaser.Tween#_pause
  53500. */
  53501. _pause: function () {
  53502. if (!this._codePaused)
  53503. {
  53504. this.isPaused = true;
  53505. this._pausedTime = this.game.time.time;
  53506. }
  53507. },
  53508. /**
  53509. * Resumes a paused tween.
  53510. *
  53511. * @method Phaser.Tween#resume
  53512. */
  53513. resume: function () {
  53514. if (this.isPaused)
  53515. {
  53516. this.isPaused = false;
  53517. this._codePaused = false;
  53518. for (var i = 0; i < this.timeline.length; i++)
  53519. {
  53520. if (!this.timeline[i].isRunning)
  53521. {
  53522. this.timeline[i].startTime += (this.game.time.time - this._pausedTime);
  53523. }
  53524. }
  53525. }
  53526. },
  53527. /**
  53528. * This is called by the core Game loop. Do not call it directly, instead use Tween.pause.
  53529. * @method Phaser.Tween#_resume
  53530. * @private
  53531. */
  53532. _resume: function () {
  53533. if (this._codePaused)
  53534. {
  53535. return;
  53536. }
  53537. else
  53538. {
  53539. this.resume();
  53540. }
  53541. },
  53542. /**
  53543. * Core tween update function called by the TweenManager. Does not need to be invoked directly.
  53544. *
  53545. * @method Phaser.Tween#update
  53546. * @param {number} time - A timestamp passed in by the TweenManager.
  53547. * @return {boolean} false if the tween and all child tweens have completed and should be deleted from the manager, otherwise true (still active).
  53548. */
  53549. update: function (time) {
  53550. if (this.pendingDelete || !this.target)
  53551. {
  53552. return false;
  53553. }
  53554. if (this.isPaused)
  53555. {
  53556. return true;
  53557. }
  53558. var status = this.timeline[this.current].update(time);
  53559. if (status === Phaser.TweenData.PENDING)
  53560. {
  53561. return true;
  53562. }
  53563. else if (status === Phaser.TweenData.RUNNING)
  53564. {
  53565. if (!this._hasStarted)
  53566. {
  53567. this.onStart.dispatch(this.target, this);
  53568. this._hasStarted = true;
  53569. }
  53570. if (this._onUpdateCallback !== null)
  53571. {
  53572. this._onUpdateCallback.call(this._onUpdateCallbackContext, this, this.timeline[this.current].value, this.timeline[this.current]);
  53573. }
  53574. // In case the update callback modifies this tween
  53575. return this.isRunning;
  53576. }
  53577. else if (status === Phaser.TweenData.LOOPED)
  53578. {
  53579. if (this.timeline[this.current].repeatCounter === -1)
  53580. {
  53581. this.onLoop.dispatch(this.target, this);
  53582. }
  53583. else
  53584. {
  53585. this.onRepeat.dispatch(this.target, this);
  53586. }
  53587. return true;
  53588. }
  53589. else if (status === Phaser.TweenData.COMPLETE)
  53590. {
  53591. var complete = false;
  53592. // What now?
  53593. if (this.reverse)
  53594. {
  53595. this.current--;
  53596. if (this.current < 0)
  53597. {
  53598. this.current = this.timeline.length - 1;
  53599. complete = true;
  53600. }
  53601. }
  53602. else
  53603. {
  53604. this.current++;
  53605. if (this.current === this.timeline.length)
  53606. {
  53607. this.current = 0;
  53608. complete = true;
  53609. }
  53610. }
  53611. if (complete)
  53612. {
  53613. // We've reached the start or end of the child tweens (depending on Tween.reverse), should we repeat it?
  53614. if (this.repeatCounter === -1)
  53615. {
  53616. this.timeline[this.current].start();
  53617. this.onLoop.dispatch(this.target, this);
  53618. return true;
  53619. }
  53620. else if (this.repeatCounter > 0)
  53621. {
  53622. this.repeatCounter--;
  53623. this.timeline[this.current].start();
  53624. this.onRepeat.dispatch(this.target, this);
  53625. return true;
  53626. }
  53627. else
  53628. {
  53629. // No more repeats and no more children, so we're done
  53630. this.isRunning = false;
  53631. this.onComplete.dispatch(this.target, this);
  53632. this._hasStarted = false;
  53633. if (this.chainedTween)
  53634. {
  53635. this.chainedTween.start();
  53636. }
  53637. return false;
  53638. }
  53639. }
  53640. else
  53641. {
  53642. // We've still got some children to go
  53643. this.onChildComplete.dispatch(this.target, this);
  53644. this.timeline[this.current].start();
  53645. return true;
  53646. }
  53647. }
  53648. },
  53649. /**
  53650. * This will generate an array populated with the tweened object values from start to end.
  53651. * It works by running the tween simulation at the given frame rate based on the values set-up in Tween.to and Tween.from.
  53652. * It ignores delay and repeat counts and any chained tweens, but does include child tweens.
  53653. * Just one play through of the tween data is returned, including yoyo if set.
  53654. *
  53655. * @method Phaser.Tween#generateData
  53656. * @param {number} [frameRate=60] - The speed in frames per second that the data should be generated at. The higher the value, the larger the array it creates.
  53657. * @param {array} [data] - If given the generated data will be appended to this array, otherwise a new array will be returned.
  53658. * @return {array} An array of tweened values.
  53659. */
  53660. generateData: function (frameRate, data) {
  53661. if (this.game === null || this.target === null)
  53662. {
  53663. return null;
  53664. }
  53665. if (frameRate === undefined) { frameRate = 60; }
  53666. if (data === undefined) { data = []; }
  53667. // Populate the tween data
  53668. for (var i = 0; i < this.timeline.length; i++)
  53669. {
  53670. // Build our master property list with the starting values
  53671. for (var property in this.timeline[i].vEnd)
  53672. {
  53673. this.properties[property] = this.target[property] || 0;
  53674. if (!Array.isArray(this.properties[property]))
  53675. {
  53676. // Ensures we're using numbers, not strings
  53677. this.properties[property] *= 1.0;
  53678. }
  53679. }
  53680. }
  53681. for (var i = 0; i < this.timeline.length; i++)
  53682. {
  53683. this.timeline[i].loadValues();
  53684. }
  53685. for (var i = 0; i < this.timeline.length; i++)
  53686. {
  53687. data = data.concat(this.timeline[i].generateData(frameRate));
  53688. }
  53689. return data;
  53690. }
  53691. };
  53692. /**
  53693. * @name Phaser.Tween#totalDuration
  53694. * @property {Phaser.TweenData} totalDuration - Gets the total duration of this Tween, including all child tweens, in milliseconds.
  53695. */
  53696. Object.defineProperty(Phaser.Tween.prototype, 'totalDuration', {
  53697. get: function () {
  53698. var total = 0;
  53699. for (var i = 0; i < this.timeline.length; i++)
  53700. {
  53701. total += this.timeline[i].duration;
  53702. }
  53703. return total;
  53704. }
  53705. });
  53706. Phaser.Tween.prototype.constructor = Phaser.Tween;
  53707. /**
  53708. * @author Richard Davey <rich@photonstorm.com>
  53709. * @copyright 2016 Photon Storm Ltd.
  53710. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  53711. */
  53712. /**
  53713. * A Phaser.Tween contains at least one TweenData object. It contains all of the tween data values, such as the
  53714. * starting and ending values, the ease function, interpolation and duration. The Tween acts as a timeline manager for
  53715. * TweenData objects and can contain multiple TweenData objects.
  53716. *
  53717. * @class Phaser.TweenData
  53718. * @constructor
  53719. * @param {Phaser.Tween} parent - The Tween that owns this TweenData object.
  53720. */
  53721. Phaser.TweenData = function (parent) {
  53722. /**
  53723. * @property {Phaser.Tween} parent - The Tween which owns this TweenData.
  53724. */
  53725. this.parent = parent;
  53726. /**
  53727. * @property {Phaser.Game} game - A reference to the currently running Game.
  53728. */
  53729. this.game = parent.game;
  53730. /**
  53731. * @property {object} vStart - An object containing the values at the start of the tween.
  53732. * @private
  53733. */
  53734. this.vStart = {};
  53735. /**
  53736. * @property {object} vStartCache - Cached starting values.
  53737. * @private
  53738. */
  53739. this.vStartCache = {};
  53740. /**
  53741. * @property {object} vEnd - An object containing the values at the end of the tween.
  53742. * @private
  53743. */
  53744. this.vEnd = {};
  53745. /**
  53746. * @property {object} vEndCache - Cached ending values.
  53747. * @private
  53748. */
  53749. this.vEndCache = {};
  53750. /**
  53751. * @property {number} duration - The duration of the tween in ms.
  53752. * @default
  53753. */
  53754. this.duration = 1000;
  53755. /**
  53756. * @property {number} percent - A value between 0 and 1 that represents how far through the duration this tween is.
  53757. * @readonly
  53758. */
  53759. this.percent = 0;
  53760. /**
  53761. * @property {number} value - The current calculated value.
  53762. * @readonly
  53763. */
  53764. this.value = 0;
  53765. /**
  53766. * @property {number} repeatCounter - If the Tween is set to repeat this contains the current repeat count.
  53767. */
  53768. this.repeatCounter = 0;
  53769. /**
  53770. * @property {number} repeatDelay - The amount of time in ms between repeats of this tween.
  53771. */
  53772. this.repeatDelay = 0;
  53773. /**
  53774. * @property {number} repeatTotal - The total number of times this Tween will repeat.
  53775. * @readonly
  53776. */
  53777. this.repeatTotal = 0;
  53778. /**
  53779. * @property {boolean} interpolate - True if the Tween will use interpolation (i.e. is an Array to Array tween)
  53780. * @default
  53781. */
  53782. this.interpolate = false;
  53783. /**
  53784. * @property {boolean} yoyo - True if the Tween is set to yoyo, otherwise false.
  53785. * @default
  53786. */
  53787. this.yoyo = false;
  53788. /**
  53789. * @property {number} yoyoDelay - The amount of time in ms between yoyos of this tween.
  53790. */
  53791. this.yoyoDelay = 0;
  53792. /**
  53793. * @property {boolean} inReverse - When a Tween is yoyoing this value holds if it's currently playing forwards (false) or in reverse (true).
  53794. * @default
  53795. */
  53796. this.inReverse = false;
  53797. /**
  53798. * @property {number} delay - The amount to delay by until the Tween starts (in ms). Only applies to the start, use repeatDelay to handle repeats.
  53799. * @default
  53800. */
  53801. this.delay = 0;
  53802. /**
  53803. * @property {number} dt - Current time value.
  53804. */
  53805. this.dt = 0;
  53806. /**
  53807. * @property {number} startTime - The time the Tween started or null if it hasn't yet started.
  53808. */
  53809. this.startTime = null;
  53810. /**
  53811. * @property {function} easingFunction - The easing function used for the Tween.
  53812. * @default Phaser.Easing.Default
  53813. */
  53814. this.easingFunction = Phaser.Easing.Default;
  53815. /**
  53816. * @property {function} interpolationFunction - The interpolation function used for the Tween.
  53817. * @default Phaser.Math.linearInterpolation
  53818. */
  53819. this.interpolationFunction = Phaser.Math.linearInterpolation;
  53820. /**
  53821. * @property {object} interpolationContext - The interpolation function context used for the Tween.
  53822. * @default Phaser.Math
  53823. */
  53824. this.interpolationContext = Phaser.Math;
  53825. /**
  53826. * @property {boolean} isRunning - If the tween is running this is set to `true`. Unless Phaser.Tween a TweenData that is waiting for a delay to expire is *not* considered as running.
  53827. * @default
  53828. */
  53829. this.isRunning = false;
  53830. /**
  53831. * @property {boolean} isFrom - Is this a from tween or a to tween?
  53832. * @default
  53833. */
  53834. this.isFrom = false;
  53835. };
  53836. /**
  53837. * @constant
  53838. * @type {number}
  53839. */
  53840. Phaser.TweenData.PENDING = 0;
  53841. /**
  53842. * @constant
  53843. * @type {number}
  53844. */
  53845. Phaser.TweenData.RUNNING = 1;
  53846. /**
  53847. * @constant
  53848. * @type {number}
  53849. */
  53850. Phaser.TweenData.LOOPED = 2;
  53851. /**
  53852. * @constant
  53853. * @type {number}
  53854. */
  53855. Phaser.TweenData.COMPLETE = 3;
  53856. Phaser.TweenData.prototype = {
  53857. /**
  53858. * Sets this tween to be a `to` tween on the properties given. A `to` tween starts at the current value and tweens to the destination value given.
  53859. * For example a Sprite with an `x` coordinate of 100 could be tweened to `x` 200 by giving a properties object of `{ x: 200 }`.
  53860. *
  53861. * @method Phaser.TweenData#to
  53862. * @param {object} properties - The properties you want to tween, such as `Sprite.x` or `Sound.volume`. Given as a JavaScript object.
  53863. * @param {number} [duration=1000] - Duration of this tween in ms.
  53864. * @param {function} [ease=null] - Easing function. If not set it will default to Phaser.Easing.Default, which is Phaser.Easing.Linear.None by default but can be over-ridden at will.
  53865. * @param {number} [delay=0] - Delay before this tween will start, defaults to 0 (no delay). Value given is in ms.
  53866. * @param {number} [repeat=0] - Should the tween automatically restart once complete? If you want it to run forever set as -1. This ignores any chained tweens.
  53867. * @param {boolean} [yoyo=false] - A tween that yoyos will reverse itself and play backwards automatically. A yoyo'd tween doesn't fire the Tween.onComplete event, so listen for Tween.onLoop instead.
  53868. * @return {Phaser.TweenData} This Tween object.
  53869. */
  53870. to: function (properties, duration, ease, delay, repeat, yoyo) {
  53871. this.vEnd = properties;
  53872. this.duration = duration;
  53873. this.easingFunction = ease;
  53874. this.delay = delay;
  53875. this.repeatTotal = repeat;
  53876. this.yoyo = yoyo;
  53877. this.isFrom = false;
  53878. return this;
  53879. },
  53880. /**
  53881. * Sets this tween to be a `from` tween on the properties given. A `from` tween sets the target to the destination value and tweens to its current value.
  53882. * For example a Sprite with an `x` coordinate of 100 tweened from `x` 500 would be set to `x` 500 and then tweened to `x` 100 by giving a properties object of `{ x: 500 }`.
  53883. *
  53884. * @method Phaser.TweenData#from
  53885. * @param {object} properties - The properties you want to tween, such as `Sprite.x` or `Sound.volume`. Given as a JavaScript object.
  53886. * @param {number} [duration=1000] - Duration of this tween in ms.
  53887. * @param {function} [ease=null] - Easing function. If not set it will default to Phaser.Easing.Default, which is Phaser.Easing.Linear.None by default but can be over-ridden at will.
  53888. * @param {number} [delay=0] - Delay before this tween will start, defaults to 0 (no delay). Value given is in ms.
  53889. * @param {number} [repeat=0] - Should the tween automatically restart once complete? If you want it to run forever set as -1. This ignores any chained tweens.
  53890. * @param {boolean} [yoyo=false] - A tween that yoyos will reverse itself and play backwards automatically. A yoyo'd tween doesn't fire the Tween.onComplete event, so listen for Tween.onLoop instead.
  53891. * @return {Phaser.TweenData} This Tween object.
  53892. */
  53893. from: function (properties, duration, ease, delay, repeat, yoyo) {
  53894. this.vEnd = properties;
  53895. this.duration = duration;
  53896. this.easingFunction = ease;
  53897. this.delay = delay;
  53898. this.repeatTotal = repeat;
  53899. this.yoyo = yoyo;
  53900. this.isFrom = true;
  53901. return this;
  53902. },
  53903. /**
  53904. * Starts the Tween running.
  53905. *
  53906. * @method Phaser.TweenData#start
  53907. * @return {Phaser.TweenData} This Tween object.
  53908. */
  53909. start: function () {
  53910. this.startTime = this.game.time.time + this.delay;
  53911. if (this.parent.reverse)
  53912. {
  53913. this.dt = this.duration;
  53914. }
  53915. else
  53916. {
  53917. this.dt = 0;
  53918. }
  53919. if (this.delay > 0)
  53920. {
  53921. this.isRunning = false;
  53922. }
  53923. else
  53924. {
  53925. this.isRunning = true;
  53926. }
  53927. if (this.isFrom)
  53928. {
  53929. // Reverse them all and instant set them
  53930. for (var property in this.vStartCache)
  53931. {
  53932. this.vStart[property] = this.vEndCache[property];
  53933. this.vEnd[property] = this.vStartCache[property];
  53934. this.parent.target[property] = this.vStart[property];
  53935. }
  53936. }
  53937. this.value = 0;
  53938. this.yoyoCounter = 0;
  53939. this.repeatCounter = this.repeatTotal;
  53940. return this;
  53941. },
  53942. /**
  53943. * Loads the values from the target object into this Tween.
  53944. *
  53945. * @private
  53946. * @method Phaser.TweenData#loadValues
  53947. * @return {Phaser.TweenData} This Tween object.
  53948. */
  53949. loadValues: function () {
  53950. for (var property in this.parent.properties)
  53951. {
  53952. // Load the property from the parent object
  53953. this.vStart[property] = this.parent.properties[property];
  53954. // Check if an Array was provided as property value
  53955. if (Array.isArray(this.vEnd[property]))
  53956. {
  53957. if (this.vEnd[property].length === 0)
  53958. {
  53959. continue;
  53960. }
  53961. if (this.percent === 0)
  53962. {
  53963. // Put the start value at the beginning of the array
  53964. // but we only want to do this once, if the Tween hasn't run before
  53965. this.vEnd[property] = [this.vStart[property]].concat(this.vEnd[property]);
  53966. }
  53967. }
  53968. if (typeof this.vEnd[property] !== 'undefined')
  53969. {
  53970. if (typeof this.vEnd[property] === 'string')
  53971. {
  53972. // Parses relative end values with start as base (e.g.: +10, -3)
  53973. this.vEnd[property] = this.vStart[property] + parseFloat(this.vEnd[property], 10);
  53974. }
  53975. this.parent.properties[property] = this.vEnd[property];
  53976. }
  53977. else
  53978. {
  53979. // Null tween
  53980. this.vEnd[property] = this.vStart[property];
  53981. }
  53982. this.vStartCache[property] = this.vStart[property];
  53983. this.vEndCache[property] = this.vEnd[property];
  53984. }
  53985. return this;
  53986. },
  53987. /**
  53988. * Updates this Tween. This is called automatically by Phaser.Tween.
  53989. *
  53990. * @protected
  53991. * @method Phaser.TweenData#update
  53992. * @param {number} time - A timestamp passed in by the Tween parent.
  53993. * @return {number} The current status of this Tween. One of the Phaser.TweenData constants: PENDING, RUNNING, LOOPED or COMPLETE.
  53994. */
  53995. update: function (time) {
  53996. if (!this.isRunning)
  53997. {
  53998. if (time >= this.startTime)
  53999. {
  54000. this.isRunning = true;
  54001. }
  54002. else
  54003. {
  54004. return Phaser.TweenData.PENDING;
  54005. }
  54006. }
  54007. else
  54008. {
  54009. // Is Running, but is waiting to repeat
  54010. if (time < this.startTime)
  54011. {
  54012. return Phaser.TweenData.RUNNING;
  54013. }
  54014. }
  54015. var ms = (this.parent.frameBased) ? this.game.time.physicsElapsedMS : this.game.time.elapsedMS;
  54016. if (this.parent.reverse)
  54017. {
  54018. this.dt -= ms * this.parent.timeScale;
  54019. this.dt = Math.max(this.dt, 0);
  54020. }
  54021. else
  54022. {
  54023. this.dt += ms * this.parent.timeScale;
  54024. this.dt = Math.min(this.dt, this.duration);
  54025. }
  54026. this.percent = this.dt / this.duration;
  54027. this.value = this.easingFunction(this.percent);
  54028. for (var property in this.vEnd)
  54029. {
  54030. var start = this.vStart[property];
  54031. var end = this.vEnd[property];
  54032. if (Array.isArray(end))
  54033. {
  54034. this.parent.target[property] = this.interpolationFunction.call(this.interpolationContext, end, this.value);
  54035. }
  54036. else
  54037. {
  54038. this.parent.target[property] = start + ((end - start) * this.value);
  54039. }
  54040. }
  54041. if ((!this.parent.reverse && this.percent === 1) || (this.parent.reverse && this.percent === 0))
  54042. {
  54043. return this.repeat();
  54044. }
  54045. return Phaser.TweenData.RUNNING;
  54046. },
  54047. /**
  54048. * This will generate an array populated with the tweened object values from start to end.
  54049. * It works by running the tween simulation at the given frame rate based on the values set-up in Tween.to and Tween.from.
  54050. * Just one play through of the tween data is returned, including yoyo if set.
  54051. *
  54052. * @method Phaser.TweenData#generateData
  54053. * @param {number} [frameRate=60] - The speed in frames per second that the data should be generated at. The higher the value, the larger the array it creates.
  54054. * @return {array} An array of tweened values.
  54055. */
  54056. generateData: function (frameRate) {
  54057. if (this.parent.reverse)
  54058. {
  54059. this.dt = this.duration;
  54060. }
  54061. else
  54062. {
  54063. this.dt = 0;
  54064. }
  54065. var data = [];
  54066. var complete = false;
  54067. var fps = (1 / frameRate) * 1000;
  54068. do
  54069. {
  54070. if (this.parent.reverse)
  54071. {
  54072. this.dt -= fps;
  54073. this.dt = Math.max(this.dt, 0);
  54074. }
  54075. else
  54076. {
  54077. this.dt += fps;
  54078. this.dt = Math.min(this.dt, this.duration);
  54079. }
  54080. this.percent = this.dt / this.duration;
  54081. this.value = this.easingFunction(this.percent);
  54082. var blob = {};
  54083. for (var property in this.vEnd)
  54084. {
  54085. var start = this.vStart[property];
  54086. var end = this.vEnd[property];
  54087. if (Array.isArray(end))
  54088. {
  54089. blob[property] = this.interpolationFunction(end, this.value);
  54090. }
  54091. else
  54092. {
  54093. blob[property] = start + ((end - start) * this.value);
  54094. }
  54095. }
  54096. data.push(blob);
  54097. if ((!this.parent.reverse && this.percent === 1) || (this.parent.reverse && this.percent === 0))
  54098. {
  54099. complete = true;
  54100. }
  54101. } while (!complete);
  54102. if (this.yoyo)
  54103. {
  54104. var reversed = data.slice();
  54105. reversed.reverse();
  54106. data = data.concat(reversed);
  54107. }
  54108. return data;
  54109. },
  54110. /**
  54111. * Checks if this Tween is meant to repeat or yoyo and handles doing so.
  54112. *
  54113. * @private
  54114. * @method Phaser.TweenData#repeat
  54115. * @return {number} Either Phaser.TweenData.LOOPED or Phaser.TweenData.COMPLETE.
  54116. */
  54117. repeat: function () {
  54118. // If not a yoyo and repeatCounter = 0 then we're done
  54119. if (this.yoyo)
  54120. {
  54121. // We're already in reverse mode, which means the yoyo has finished and there's no repeats, so end
  54122. if (this.inReverse && this.repeatCounter === 0)
  54123. {
  54124. // Restore the properties
  54125. for (var property in this.vStartCache)
  54126. {
  54127. this.vStart[property] = this.vStartCache[property];
  54128. this.vEnd[property] = this.vEndCache[property];
  54129. }
  54130. this.inReverse = false;
  54131. return Phaser.TweenData.COMPLETE;
  54132. }
  54133. this.inReverse = !this.inReverse;
  54134. }
  54135. else
  54136. {
  54137. if (this.repeatCounter === 0)
  54138. {
  54139. return Phaser.TweenData.COMPLETE;
  54140. }
  54141. }
  54142. if (this.inReverse)
  54143. {
  54144. // If inReverse we're going from vEnd to vStartCache
  54145. for (var property in this.vStartCache)
  54146. {
  54147. this.vStart[property] = this.vEndCache[property];
  54148. this.vEnd[property] = this.vStartCache[property];
  54149. }
  54150. }
  54151. else
  54152. {
  54153. // If not inReverse we're just repopulating the cache again
  54154. for (var property in this.vStartCache)
  54155. {
  54156. this.vStart[property] = this.vStartCache[property];
  54157. this.vEnd[property] = this.vEndCache[property];
  54158. }
  54159. // -1 means repeat forever, otherwise decrement the repeatCounter
  54160. // We only decrement this counter if the tween isn't doing a yoyo, as that doesn't count towards the repeat total
  54161. if (this.repeatCounter > 0)
  54162. {
  54163. this.repeatCounter--;
  54164. }
  54165. }
  54166. this.startTime = this.game.time.time;
  54167. if (this.yoyo && this.inReverse)
  54168. {
  54169. this.startTime += this.yoyoDelay;
  54170. }
  54171. else if (!this.inReverse)
  54172. {
  54173. this.startTime += this.repeatDelay;
  54174. }
  54175. if (this.parent.reverse)
  54176. {
  54177. this.dt = this.duration;
  54178. }
  54179. else
  54180. {
  54181. this.dt = 0;
  54182. }
  54183. return Phaser.TweenData.LOOPED;
  54184. }
  54185. };
  54186. Phaser.TweenData.prototype.constructor = Phaser.TweenData;
  54187. /* jshint curly: false */
  54188. /**
  54189. * @author Richard Davey <rich@photonstorm.com>
  54190. * @copyright 2016 Photon Storm Ltd.
  54191. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  54192. */
  54193. /**
  54194. * A collection of easing methods defining ease-in and ease-out curves.
  54195. *
  54196. * @class Phaser.Easing
  54197. */
  54198. Phaser.Easing = {
  54199. /**
  54200. * Linear easing.
  54201. *
  54202. * @class Phaser.Easing.Linear
  54203. */
  54204. Linear: {
  54205. /**
  54206. * Linear Easing (no variation).
  54207. *
  54208. * @method Phaser.Easing.Linear#None
  54209. * @param {number} k - The value to be tweened.
  54210. * @returns {number} k.
  54211. */
  54212. None: function ( k ) {
  54213. return k;
  54214. }
  54215. },
  54216. /**
  54217. * Quadratic easing.
  54218. *
  54219. * @class Phaser.Easing.Quadratic
  54220. */
  54221. Quadratic: {
  54222. /**
  54223. * Ease-in.
  54224. *
  54225. * @method Phaser.Easing.Quadratic#In
  54226. * @param {number} k - The value to be tweened.
  54227. * @returns {number} k^2.
  54228. */
  54229. In: function ( k ) {
  54230. return k * k;
  54231. },
  54232. /**
  54233. * Ease-out.
  54234. *
  54235. * @method Phaser.Easing.Quadratic#Out
  54236. * @param {number} k - The value to be tweened.
  54237. * @returns {number} k* (2-k).
  54238. */
  54239. Out: function ( k ) {
  54240. return k * ( 2 - k );
  54241. },
  54242. /**
  54243. * Ease-in/out.
  54244. *
  54245. * @method Phaser.Easing.Quadratic#InOut
  54246. * @param {number} k - The value to be tweened.
  54247. * @returns {number} The tweened value.
  54248. */
  54249. InOut: function ( k ) {
  54250. if ( ( k *= 2 ) < 1 ) return 0.5 * k * k;
  54251. return - 0.5 * ( --k * ( k - 2 ) - 1 );
  54252. }
  54253. },
  54254. /**
  54255. * Cubic easing.
  54256. *
  54257. * @class Phaser.Easing.Cubic
  54258. */
  54259. Cubic: {
  54260. /**
  54261. * Cubic ease-in.
  54262. *
  54263. * @method Phaser.Easing.Cubic#In
  54264. * @param {number} k - The value to be tweened.
  54265. * @returns {number} The tweened value.
  54266. */
  54267. In: function ( k ) {
  54268. return k * k * k;
  54269. },
  54270. /**
  54271. * Cubic ease-out.
  54272. *
  54273. * @method Phaser.Easing.Cubic#Out
  54274. * @param {number} k - The value to be tweened.
  54275. * @returns {number} The tweened value.
  54276. */
  54277. Out: function ( k ) {
  54278. return --k * k * k + 1;
  54279. },
  54280. /**
  54281. * Cubic ease-in/out.
  54282. *
  54283. * @method Phaser.Easing.Cubic#InOut
  54284. * @param {number} k - The value to be tweened.
  54285. * @returns {number} The tweened value.
  54286. */
  54287. InOut: function ( k ) {
  54288. if ( ( k *= 2 ) < 1 ) return 0.5 * k * k * k;
  54289. return 0.5 * ( ( k -= 2 ) * k * k + 2 );
  54290. }
  54291. },
  54292. /**
  54293. * Quartic easing.
  54294. *
  54295. * @class Phaser.Easing.Quartic
  54296. */
  54297. Quartic: {
  54298. /**
  54299. * Quartic ease-in.
  54300. *
  54301. * @method Phaser.Easing.Quartic#In
  54302. * @param {number} k - The value to be tweened.
  54303. * @returns {number} The tweened value.
  54304. */
  54305. In: function ( k ) {
  54306. return k * k * k * k;
  54307. },
  54308. /**
  54309. * Quartic ease-out.
  54310. *
  54311. * @method Phaser.Easing.Quartic#Out
  54312. * @param {number} k - The value to be tweened.
  54313. * @returns {number} The tweened value.
  54314. */
  54315. Out: function ( k ) {
  54316. return 1 - ( --k * k * k * k );
  54317. },
  54318. /**
  54319. * Quartic ease-in/out.
  54320. *
  54321. * @method Phaser.Easing.Quartic#InOut
  54322. * @param {number} k - The value to be tweened.
  54323. * @returns {number} The tweened value.
  54324. */
  54325. InOut: function ( k ) {
  54326. if ( ( k *= 2 ) < 1) return 0.5 * k * k * k * k;
  54327. return - 0.5 * ( ( k -= 2 ) * k * k * k - 2 );
  54328. }
  54329. },
  54330. /**
  54331. * Quintic easing.
  54332. *
  54333. * @class Phaser.Easing.Quintic
  54334. */
  54335. Quintic: {
  54336. /**
  54337. * Quintic ease-in.
  54338. *
  54339. * @method Phaser.Easing.Quintic#In
  54340. * @param {number} k - The value to be tweened.
  54341. * @returns {number} The tweened value.
  54342. */
  54343. In: function ( k ) {
  54344. return k * k * k * k * k;
  54345. },
  54346. /**
  54347. * Quintic ease-out.
  54348. *
  54349. * @method Phaser.Easing.Quintic#Out
  54350. * @param {number} k - The value to be tweened.
  54351. * @returns {number} The tweened value.
  54352. */
  54353. Out: function ( k ) {
  54354. return --k * k * k * k * k + 1;
  54355. },
  54356. /**
  54357. * Quintic ease-in/out.
  54358. *
  54359. * @method Phaser.Easing.Quintic#InOut
  54360. * @param {number} k - The value to be tweened.
  54361. * @returns {number} The tweened value.
  54362. */
  54363. InOut: function ( k ) {
  54364. if ( ( k *= 2 ) < 1 ) return 0.5 * k * k * k * k * k;
  54365. return 0.5 * ( ( k -= 2 ) * k * k * k * k + 2 );
  54366. }
  54367. },
  54368. /**
  54369. * Sinusoidal easing.
  54370. *
  54371. * @class Phaser.Easing.Sinusoidal
  54372. */
  54373. Sinusoidal: {
  54374. /**
  54375. * Sinusoidal ease-in.
  54376. *
  54377. * @method Phaser.Easing.Sinusoidal#In
  54378. * @param {number} k - The value to be tweened.
  54379. * @returns {number} The tweened value.
  54380. */
  54381. In: function ( k ) {
  54382. if (k === 0) return 0;
  54383. if (k === 1) return 1;
  54384. return 1 - Math.cos( k * Math.PI / 2 );
  54385. },
  54386. /**
  54387. * Sinusoidal ease-out.
  54388. *
  54389. * @method Phaser.Easing.Sinusoidal#Out
  54390. * @param {number} k - The value to be tweened.
  54391. * @returns {number} The tweened value.
  54392. */
  54393. Out: function ( k ) {
  54394. if (k === 0) return 0;
  54395. if (k === 1) return 1;
  54396. return Math.sin( k * Math.PI / 2 );
  54397. },
  54398. /**
  54399. * Sinusoidal ease-in/out.
  54400. *
  54401. * @method Phaser.Easing.Sinusoidal#InOut
  54402. * @param {number} k - The value to be tweened.
  54403. * @returns {number} The tweened value.
  54404. */
  54405. InOut: function ( k ) {
  54406. if (k === 0) return 0;
  54407. if (k === 1) return 1;
  54408. return 0.5 * ( 1 - Math.cos( Math.PI * k ) );
  54409. }
  54410. },
  54411. /**
  54412. * Exponential easing.
  54413. *
  54414. * @class Phaser.Easing.Exponential
  54415. */
  54416. Exponential: {
  54417. /**
  54418. * Exponential ease-in.
  54419. *
  54420. * @method Phaser.Easing.Exponential#In
  54421. * @param {number} k - The value to be tweened.
  54422. * @returns {number} The tweened value.
  54423. */
  54424. In: function ( k ) {
  54425. return k === 0 ? 0 : Math.pow( 1024, k - 1 );
  54426. },
  54427. /**
  54428. * Exponential ease-out.
  54429. *
  54430. * @method Phaser.Easing.Exponential#Out
  54431. * @param {number} k - The value to be tweened.
  54432. * @returns {number} The tweened value.
  54433. */
  54434. Out: function ( k ) {
  54435. return k === 1 ? 1 : 1 - Math.pow( 2, - 10 * k );
  54436. },
  54437. /**
  54438. * Exponential ease-in/out.
  54439. *
  54440. * @method Phaser.Easing.Exponential#InOut
  54441. * @param {number} k - The value to be tweened.
  54442. * @returns {number} The tweened value.
  54443. */
  54444. InOut: function ( k ) {
  54445. if ( k === 0 ) return 0;
  54446. if ( k === 1 ) return 1;
  54447. if ( ( k *= 2 ) < 1 ) return 0.5 * Math.pow( 1024, k - 1 );
  54448. return 0.5 * ( - Math.pow( 2, - 10 * ( k - 1 ) ) + 2 );
  54449. }
  54450. },
  54451. /**
  54452. * Circular easing.
  54453. *
  54454. * @class Phaser.Easing.Circular
  54455. */
  54456. Circular: {
  54457. /**
  54458. * Circular ease-in.
  54459. *
  54460. * @method Phaser.Easing.Circular#In
  54461. * @param {number} k - The value to be tweened.
  54462. * @returns {number} The tweened value.
  54463. */
  54464. In: function ( k ) {
  54465. return 1 - Math.sqrt( 1 - k * k );
  54466. },
  54467. /**
  54468. * Circular ease-out.
  54469. *
  54470. * @method Phaser.Easing.Circular#Out
  54471. * @param {number} k - The value to be tweened.
  54472. * @returns {number} The tweened value.
  54473. */
  54474. Out: function ( k ) {
  54475. return Math.sqrt( 1 - ( --k * k ) );
  54476. },
  54477. /**
  54478. * Circular ease-in/out.
  54479. *
  54480. * @method Phaser.Easing.Circular#InOut
  54481. * @param {number} k - The value to be tweened.
  54482. * @returns {number} The tweened value.
  54483. */
  54484. InOut: function ( k ) {
  54485. if ( ( k *= 2 ) < 1) return - 0.5 * ( Math.sqrt( 1 - k * k) - 1);
  54486. return 0.5 * ( Math.sqrt( 1 - ( k -= 2) * k) + 1);
  54487. }
  54488. },
  54489. /**
  54490. * Elastic easing.
  54491. *
  54492. * @class Phaser.Easing.Elastic
  54493. */
  54494. Elastic: {
  54495. /**
  54496. * Elastic ease-in.
  54497. *
  54498. * @method Phaser.Easing.Elastic#In
  54499. * @param {number} k - The value to be tweened.
  54500. * @returns {number} The tweened value.
  54501. */
  54502. In: function ( k ) {
  54503. var s, a = 0.1, p = 0.4;
  54504. if ( k === 0 ) return 0;
  54505. if ( k === 1 ) return 1;
  54506. if ( !a || a < 1 ) { a = 1; s = p / 4; }
  54507. else s = p * Math.asin( 1 / a ) / ( 2 * Math.PI );
  54508. return - ( a * Math.pow( 2, 10 * ( k -= 1 ) ) * Math.sin( ( k - s ) * ( 2 * Math.PI ) / p ) );
  54509. },
  54510. /**
  54511. * Elastic ease-out.
  54512. *
  54513. * @method Phaser.Easing.Elastic#Out
  54514. * @param {number} k - The value to be tweened.
  54515. * @returns {number} The tweened value.
  54516. */
  54517. Out: function ( k ) {
  54518. var s, a = 0.1, p = 0.4;
  54519. if ( k === 0 ) return 0;
  54520. if ( k === 1 ) return 1;
  54521. if ( !a || a < 1 ) { a = 1; s = p / 4; }
  54522. else s = p * Math.asin( 1 / a ) / ( 2 * Math.PI );
  54523. return ( a * Math.pow( 2, - 10 * k) * Math.sin( ( k - s ) * ( 2 * Math.PI ) / p ) + 1 );
  54524. },
  54525. /**
  54526. * Elastic ease-in/out.
  54527. *
  54528. * @method Phaser.Easing.Elastic#InOut
  54529. * @param {number} k - The value to be tweened.
  54530. * @returns {number} The tweened value.
  54531. */
  54532. InOut: function ( k ) {
  54533. var s, a = 0.1, p = 0.4;
  54534. if ( k === 0 ) return 0;
  54535. if ( k === 1 ) return 1;
  54536. if ( !a || a < 1 ) { a = 1; s = p / 4; }
  54537. else s = p * Math.asin( 1 / a ) / ( 2 * Math.PI );
  54538. if ( ( k *= 2 ) < 1 ) return - 0.5 * ( a * Math.pow( 2, 10 * ( k -= 1 ) ) * Math.sin( ( k - s ) * ( 2 * Math.PI ) / p ) );
  54539. return a * Math.pow( 2, -10 * ( k -= 1 ) ) * Math.sin( ( k - s ) * ( 2 * Math.PI ) / p ) * 0.5 + 1;
  54540. }
  54541. },
  54542. /**
  54543. * Back easing.
  54544. *
  54545. * @class Phaser.Easing.Back
  54546. */
  54547. Back: {
  54548. /**
  54549. * Back ease-in.
  54550. *
  54551. * @method Phaser.Easing.Back#In
  54552. * @param {number} k - The value to be tweened.
  54553. * @returns {number} The tweened value.
  54554. */
  54555. In: function ( k ) {
  54556. var s = 1.70158;
  54557. return k * k * ( ( s + 1 ) * k - s );
  54558. },
  54559. /**
  54560. * Back ease-out.
  54561. *
  54562. * @method Phaser.Easing.Back#Out
  54563. * @param {number} k - The value to be tweened.
  54564. * @returns {number} The tweened value.
  54565. */
  54566. Out: function ( k ) {
  54567. var s = 1.70158;
  54568. return --k * k * ( ( s + 1 ) * k + s ) + 1;
  54569. },
  54570. /**
  54571. * Back ease-in/out.
  54572. *
  54573. * @method Phaser.Easing.Back#InOut
  54574. * @param {number} k - The value to be tweened.
  54575. * @returns {number} The tweened value.
  54576. */
  54577. InOut: function ( k ) {
  54578. var s = 1.70158 * 1.525;
  54579. if ( ( k *= 2 ) < 1 ) return 0.5 * ( k * k * ( ( s + 1 ) * k - s ) );
  54580. return 0.5 * ( ( k -= 2 ) * k * ( ( s + 1 ) * k + s ) + 2 );
  54581. }
  54582. },
  54583. /**
  54584. * Bounce easing.
  54585. *
  54586. * @class Phaser.Easing.Bounce
  54587. */
  54588. Bounce: {
  54589. /**
  54590. * Bounce ease-in.
  54591. *
  54592. * @method Phaser.Easing.Bounce#In
  54593. * @param {number} k - The value to be tweened.
  54594. * @returns {number} The tweened value.
  54595. */
  54596. In: function ( k ) {
  54597. return 1 - Phaser.Easing.Bounce.Out( 1 - k );
  54598. },
  54599. /**
  54600. * Bounce ease-out.
  54601. *
  54602. * @method Phaser.Easing.Bounce#Out
  54603. * @param {number} k - The value to be tweened.
  54604. * @returns {number} The tweened value.
  54605. */
  54606. Out: function ( k ) {
  54607. if ( k < ( 1 / 2.75 ) ) {
  54608. return 7.5625 * k * k;
  54609. } else if ( k < ( 2 / 2.75 ) ) {
  54610. return 7.5625 * ( k -= ( 1.5 / 2.75 ) ) * k + 0.75;
  54611. } else if ( k < ( 2.5 / 2.75 ) ) {
  54612. return 7.5625 * ( k -= ( 2.25 / 2.75 ) ) * k + 0.9375;
  54613. } else {
  54614. return 7.5625 * ( k -= ( 2.625 / 2.75 ) ) * k + 0.984375;
  54615. }
  54616. },
  54617. /**
  54618. * Bounce ease-in/out.
  54619. *
  54620. * @method Phaser.Easing.Bounce#InOut
  54621. * @param {number} k - The value to be tweened.
  54622. * @returns {number} The tweened value.
  54623. */
  54624. InOut: function ( k ) {
  54625. if ( k < 0.5 ) return Phaser.Easing.Bounce.In( k * 2 ) * 0.5;
  54626. return Phaser.Easing.Bounce.Out( k * 2 - 1 ) * 0.5 + 0.5;
  54627. }
  54628. }
  54629. };
  54630. Phaser.Easing.Default = Phaser.Easing.Linear.None;
  54631. Phaser.Easing.Power0 = Phaser.Easing.Linear.None;
  54632. Phaser.Easing.Power1 = Phaser.Easing.Quadratic.Out;
  54633. Phaser.Easing.Power2 = Phaser.Easing.Cubic.Out;
  54634. Phaser.Easing.Power3 = Phaser.Easing.Quartic.Out;
  54635. Phaser.Easing.Power4 = Phaser.Easing.Quintic.Out;
  54636. /**
  54637. * @author Richard Davey <rich@photonstorm.com>
  54638. * @copyright 2016 Photon Storm Ltd.
  54639. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  54640. */
  54641. /**
  54642. * This is the core internal game clock.
  54643. *
  54644. * It manages the elapsed time and calculation of elapsed values, used for game object motion and tweens,
  54645. * and also handles the standard Timer pool.
  54646. *
  54647. * To create a general timed event, use the master {@link Phaser.Timer} accessible through {@link Phaser.Time.events events}.
  54648. *
  54649. * There are different *types* of time in Phaser:
  54650. *
  54651. * - ***Game time*** always runs at the speed of time in real life.
  54652. *
  54653. * Unlike wall-clock time, *game time stops when Phaser is paused*.
  54654. *
  54655. * Game time is used for {@link Phaser.Timer timer events}.
  54656. *
  54657. * - ***Physics time*** represents the amount of time given to physics calculations.
  54658. *
  54659. * *When {@link #slowMotion} is in effect physics time runs slower than game time.*
  54660. * Like game time, physics time stops when Phaser is paused.
  54661. *
  54662. * Physics time is used for physics calculations and {@link Phaser.Tween tweens}.
  54663. *
  54664. * - {@link https://en.wikipedia.org/wiki/Wall-clock_time ***Wall-clock time***} represents the duration between two events in real life time.
  54665. *
  54666. * This time is independent of Phaser and always progresses, regardless of if Phaser is paused.
  54667. *
  54668. * @class Phaser.Time
  54669. * @constructor
  54670. * @param {Phaser.Game} game A reference to the currently running game.
  54671. */
  54672. Phaser.Time = function (game) {
  54673. /**
  54674. * @property {Phaser.Game} game - Local reference to game.
  54675. * @protected
  54676. */
  54677. this.game = game;
  54678. /**
  54679. * The `Date.now()` value when the time was last updated.
  54680. * @property {integer} time
  54681. * @protected
  54682. */
  54683. this.time = 0;
  54684. /**
  54685. * The `now` when the previous update occurred.
  54686. * @property {number} prevTime
  54687. * @protected
  54688. */
  54689. this.prevTime = 0;
  54690. /**
  54691. * An increasing value representing cumulative milliseconds since an undisclosed epoch.
  54692. *
  54693. * While this value is in milliseconds and can be used to compute time deltas,
  54694. * it must must _not_ be used with `Date.now()` as it may not use the same epoch / starting reference.
  54695. *
  54696. * The source may either be from a high-res source (eg. if RAF is available) or the standard Date.now;
  54697. * the value can only be relied upon within a particular game instance.
  54698. *
  54699. * @property {number} now
  54700. * @protected
  54701. */
  54702. this.now = 0;
  54703. /**
  54704. * Elapsed time since the last time update, in milliseconds, based on `now`.
  54705. *
  54706. * This value _may_ include time that the game is paused/inactive.
  54707. *
  54708. * _Note:_ This is updated only once per game loop - even if multiple logic update steps are done.
  54709. * Use {@link Phaser.Timer#physicsTime physicsTime} as a basis of game/logic calculations instead.
  54710. *
  54711. * @property {number} elapsed
  54712. * @see Phaser.Time.time
  54713. * @protected
  54714. */
  54715. this.elapsed = 0;
  54716. /**
  54717. * The time in ms since the last time update, in milliseconds, based on `time`.
  54718. *
  54719. * This value is corrected for game pauses and will be "about zero" after a game is resumed.
  54720. *
  54721. * _Note:_ This is updated once per game loop - even if multiple logic update steps are done.
  54722. * Use {@link Phaser.Timer#physicsTime physicsTime} as a basis of game/logic calculations instead.
  54723. *
  54724. * @property {integer} elapsedMS
  54725. * @protected
  54726. */
  54727. this.elapsedMS = 0;
  54728. /**
  54729. * The physics update delta, in fractional seconds.
  54730. *
  54731. * This should be used as an applicable multiplier by all logic update steps (eg. `preUpdate/postUpdate/update`)
  54732. * to ensure consistent game timing. Game/logic timing can drift from real-world time if the system
  54733. * is unable to consistently maintain the desired FPS.
  54734. *
  54735. * With fixed-step updates this is normally equivalent to `1.0 / desiredFps`.
  54736. *
  54737. * @property {number} physicsElapsed
  54738. */
  54739. this.physicsElapsed = 1 / 60;
  54740. /**
  54741. * The physics update delta, in milliseconds - equivalent to `physicsElapsed * 1000`.
  54742. *
  54743. * @property {number} physicsElapsedMS
  54744. */
  54745. this.physicsElapsedMS = (1 / 60) * 1000;
  54746. /**
  54747. * The desiredFps multiplier as used by Game.update.
  54748. * @property {integer} desiredFpsMult
  54749. * @protected
  54750. */
  54751. this.desiredFpsMult = 1.0 / 60;
  54752. /**
  54753. * The desired frame rate of the game.
  54754. *
  54755. * This is used is used to calculate the physic/logic multiplier and how to apply catch-up logic updates.
  54756. *
  54757. * @property {number} _desiredFps
  54758. * @private
  54759. * @default
  54760. */
  54761. this._desiredFps = 60;
  54762. /**
  54763. * The suggested frame rate for your game, based on an averaged real frame rate.
  54764. * This value is only populated if `Time.advancedTiming` is enabled.
  54765. *
  54766. * _Note:_ This is not available until after a few frames have passed; until then
  54767. * it's set to the same value as desiredFps.
  54768. *
  54769. * @property {number} suggestedFps
  54770. * @default
  54771. */
  54772. this.suggestedFps = this.desiredFps;
  54773. /**
  54774. * Scaling factor to make the game move smoothly in slow motion
  54775. * - 1.0 = normal speed
  54776. * - 2.0 = half speed
  54777. * @property {number} slowMotion
  54778. * @default
  54779. */
  54780. this.slowMotion = 1.0;
  54781. /**
  54782. * If true then advanced profiling, including the fps rate, fps min/max, suggestedFps and msMin/msMax are updated.
  54783. * @property {boolean} advancedTiming
  54784. * @default
  54785. */
  54786. this.advancedTiming = false;
  54787. /**
  54788. * Advanced timing result: The number of render frames record in the last second.
  54789. *
  54790. * Only calculated if {@link Phaser.Time#advancedTiming advancedTiming} is enabled.
  54791. * @property {integer} frames
  54792. * @readonly
  54793. */
  54794. this.frames = 0;
  54795. /**
  54796. * Advanced timing result: Frames per second.
  54797. *
  54798. * Only calculated if {@link Phaser.Time#advancedTiming advancedTiming} is enabled.
  54799. * @property {number} fps
  54800. * @readonly
  54801. */
  54802. this.fps = 0;
  54803. /**
  54804. * Advanced timing result: The lowest rate the fps has dropped to.
  54805. *
  54806. * Only calculated if {@link Phaser.Time#advancedTiming advancedTiming} is enabled.
  54807. * This value can be manually reset.
  54808. * @property {number} fpsMin
  54809. */
  54810. this.fpsMin = 1000;
  54811. /**
  54812. * Advanced timing result: The highest rate the fps has reached (usually no higher than 60fps).
  54813. *
  54814. * Only calculated if {@link Phaser.Time#advancedTiming advancedTiming} is enabled.
  54815. * This value can be manually reset.
  54816. * @property {number} fpsMax
  54817. */
  54818. this.fpsMax = 0;
  54819. /**
  54820. * Advanced timing result: The minimum amount of time the game has taken between consecutive frames.
  54821. *
  54822. * Only calculated if {@link Phaser.Time#advancedTiming advancedTiming} is enabled.
  54823. * This value can be manually reset.
  54824. * @property {number} msMin
  54825. * @default
  54826. */
  54827. this.msMin = 1000;
  54828. /**
  54829. * Advanced timing result: The maximum amount of time the game has taken between consecutive frames.
  54830. *
  54831. * Only calculated if {@link Phaser.Time#advancedTiming advancedTiming} is enabled.
  54832. * This value can be manually reset.
  54833. * @property {number} msMax
  54834. */
  54835. this.msMax = 0;
  54836. /**
  54837. * Records how long the game was last paused, in milliseconds.
  54838. * (This is not updated until the game is resumed.)
  54839. * @property {number} pauseDuration
  54840. */
  54841. this.pauseDuration = 0;
  54842. /**
  54843. * @property {number} timeToCall - The value that setTimeout needs to work out when to next update
  54844. * @protected
  54845. */
  54846. this.timeToCall = 0;
  54847. /**
  54848. * @property {number} timeExpected - The time when the next call is expected when using setTimer to control the update loop
  54849. * @protected
  54850. */
  54851. this.timeExpected = 0;
  54852. /**
  54853. * A {@link Phaser.Timer} object bound to the master clock (this Time object) which events can be added to.
  54854. * @property {Phaser.Timer} events
  54855. */
  54856. this.events = new Phaser.Timer(this.game, false);
  54857. /**
  54858. * @property {number} _frameCount - count the number of calls to time.update since the last suggestedFps was calculated
  54859. * @private
  54860. */
  54861. this._frameCount = 0;
  54862. /**
  54863. * @property {number} _elapsedAcumulator - sum of the elapsed time since the last suggestedFps was calculated
  54864. * @private
  54865. */
  54866. this._elapsedAccumulator = 0;
  54867. /**
  54868. * @property {number} _started - The time at which the Game instance started.
  54869. * @private
  54870. */
  54871. this._started = 0;
  54872. /**
  54873. * @property {number} _timeLastSecond - The time (in ms) that the last second counter ticked over.
  54874. * @private
  54875. */
  54876. this._timeLastSecond = 0;
  54877. /**
  54878. * @property {number} _pauseStarted - The time the game started being paused.
  54879. * @private
  54880. */
  54881. this._pauseStarted = 0;
  54882. /**
  54883. * @property {boolean} _justResumed - Internal value used to recover from the game pause state.
  54884. * @private
  54885. */
  54886. this._justResumed = false;
  54887. /**
  54888. * @property {Phaser.Timer[]} _timers - Internal store of Phaser.Timer objects.
  54889. * @private
  54890. */
  54891. this._timers = [];
  54892. };
  54893. Phaser.Time.prototype = {
  54894. /**
  54895. * Called automatically by Phaser.Game after boot. Should not be called directly.
  54896. *
  54897. * @method Phaser.Time#boot
  54898. * @protected
  54899. */
  54900. boot: function () {
  54901. this._started = Date.now();
  54902. this.time = Date.now();
  54903. this.events.start();
  54904. this.timeExpected = this.time;
  54905. },
  54906. /**
  54907. * Adds an existing Phaser.Timer object to the Timer pool.
  54908. *
  54909. * @method Phaser.Time#add
  54910. * @param {Phaser.Timer} timer - An existing Phaser.Timer object.
  54911. * @return {Phaser.Timer} The given Phaser.Timer object.
  54912. */
  54913. add: function (timer) {
  54914. this._timers.push(timer);
  54915. return timer;
  54916. },
  54917. /**
  54918. * Creates a new stand-alone Phaser.Timer object.
  54919. *
  54920. * @method Phaser.Time#create
  54921. * @param {boolean} [autoDestroy=true] - A Timer that is set to automatically destroy itself will do so after all of its events have been dispatched (assuming no looping events).
  54922. * @return {Phaser.Timer} The Timer object that was created.
  54923. */
  54924. create: function (autoDestroy) {
  54925. if (autoDestroy === undefined) { autoDestroy = true; }
  54926. var timer = new Phaser.Timer(this.game, autoDestroy);
  54927. this._timers.push(timer);
  54928. return timer;
  54929. },
  54930. /**
  54931. * Remove all Timer objects, regardless of their state and clears all Timers from the {@link Phaser.Time#events events} timer.
  54932. *
  54933. * @method Phaser.Time#removeAll
  54934. */
  54935. removeAll: function () {
  54936. for (var i = 0; i < this._timers.length; i++)
  54937. {
  54938. this._timers[i].destroy();
  54939. }
  54940. this._timers = [];
  54941. this.events.removeAll();
  54942. },
  54943. /**
  54944. * Refreshes the Time.time and Time.elapsedMS properties from the system clock.
  54945. *
  54946. * @method Phaser.Time#refresh
  54947. */
  54948. refresh: function () {
  54949. // Set to the old Date.now value
  54950. var previousDateNow = this.time;
  54951. // this.time always holds a Date.now value
  54952. this.time = Date.now();
  54953. // Adjust accordingly.
  54954. this.elapsedMS = this.time - previousDateNow;
  54955. },
  54956. /**
  54957. * Updates the game clock and if enabled the advanced timing data. This is called automatically by Phaser.Game.
  54958. *
  54959. * @method Phaser.Time#update
  54960. * @protected
  54961. * @param {number} time - The current relative timestamp; see {@link Phaser.Time#now now}.
  54962. */
  54963. update: function (time) {
  54964. // Set to the old Date.now value
  54965. var previousDateNow = this.time;
  54966. // this.time always holds a Date.now value
  54967. this.time = Date.now();
  54968. // Adjust accordingly.
  54969. this.elapsedMS = this.time - previousDateNow;
  54970. // 'now' is currently still holding the time of the last call, move it into prevTime
  54971. this.prevTime = this.now;
  54972. // update 'now' to hold the current time
  54973. // this.now may hold the RAF high resolution time value if RAF is available (otherwise it also holds Date.now)
  54974. this.now = time;
  54975. // elapsed time between previous call and now - this could be a high resolution value
  54976. this.elapsed = this.now - this.prevTime;
  54977. if (this.game.raf._isSetTimeOut)
  54978. {
  54979. // console.log('Time isSet', this._desiredFps, 'te', this.timeExpected, 'time', time);
  54980. // time to call this function again in ms in case we're using timers instead of RequestAnimationFrame to update the game
  54981. this.timeToCall = Math.floor(Math.max(0, (1000.0 / this._desiredFps) - (this.timeExpected - time)));
  54982. // time when the next call is expected if using timers
  54983. this.timeExpected = time + this.timeToCall;
  54984. // console.log('Time expect', this.timeExpected);
  54985. }
  54986. if (this.advancedTiming)
  54987. {
  54988. this.updateAdvancedTiming();
  54989. }
  54990. // Paused but still running?
  54991. if (!this.game.paused)
  54992. {
  54993. // Our internal Phaser.Timer
  54994. this.events.update(this.time);
  54995. if (this._timers.length)
  54996. {
  54997. this.updateTimers();
  54998. }
  54999. }
  55000. },
  55001. /**
  55002. * Handles the updating of the Phaser.Timers (if any)
  55003. * Called automatically by Time.update.
  55004. *
  55005. * @method Phaser.Time#updateTimers
  55006. * @private
  55007. */
  55008. updateTimers: function () {
  55009. // Any game level timers
  55010. var i = 0;
  55011. var len = this._timers.length;
  55012. while (i < len)
  55013. {
  55014. if (this._timers[i].update(this.time))
  55015. {
  55016. i++;
  55017. }
  55018. else
  55019. {
  55020. // Timer requests to be removed
  55021. this._timers.splice(i, 1);
  55022. len--;
  55023. }
  55024. }
  55025. },
  55026. /**
  55027. * Handles the updating of the advanced timing values (if enabled)
  55028. * Called automatically by Time.update.
  55029. *
  55030. * @method Phaser.Time#updateAdvancedTiming
  55031. * @private
  55032. */
  55033. updateAdvancedTiming: function () {
  55034. // count the number of time.update calls
  55035. this._frameCount++;
  55036. this._elapsedAccumulator += this.elapsed;
  55037. // occasionally recalculate the suggestedFps based on the accumulated elapsed time
  55038. if (this._frameCount >= this._desiredFps * 2)
  55039. {
  55040. // this formula calculates suggestedFps in multiples of 5 fps
  55041. this.suggestedFps = Math.floor(200 / (this._elapsedAccumulator / this._frameCount)) * 5;
  55042. this._frameCount = 0;
  55043. this._elapsedAccumulator = 0;
  55044. }
  55045. this.msMin = Math.min(this.msMin, this.elapsed);
  55046. this.msMax = Math.max(this.msMax, this.elapsed);
  55047. this.frames++;
  55048. if (this.now > this._timeLastSecond + 1000)
  55049. {
  55050. this.fps = Math.round((this.frames * 1000) / (this.now - this._timeLastSecond));
  55051. this.fpsMin = Math.min(this.fpsMin, this.fps);
  55052. this.fpsMax = Math.max(this.fpsMax, this.fps);
  55053. this._timeLastSecond = this.now;
  55054. this.frames = 0;
  55055. }
  55056. },
  55057. /**
  55058. * Called when the game enters a paused state.
  55059. *
  55060. * @method Phaser.Time#gamePaused
  55061. * @private
  55062. */
  55063. gamePaused: function () {
  55064. this._pauseStarted = Date.now();
  55065. this.events.pause();
  55066. var i = this._timers.length;
  55067. while (i--)
  55068. {
  55069. this._timers[i]._pause();
  55070. }
  55071. },
  55072. /**
  55073. * Called when the game resumes from a paused state.
  55074. *
  55075. * @method Phaser.Time#gameResumed
  55076. * @private
  55077. */
  55078. gameResumed: function () {
  55079. // Set the parameter which stores Date.now() to make sure it's correct on resume
  55080. this.time = Date.now();
  55081. this.pauseDuration = this.time - this._pauseStarted;
  55082. this.events.resume();
  55083. var i = this._timers.length;
  55084. while (i--)
  55085. {
  55086. this._timers[i]._resume();
  55087. }
  55088. },
  55089. /**
  55090. * The number of seconds that have elapsed since the game was started.
  55091. *
  55092. * @method Phaser.Time#totalElapsedSeconds
  55093. * @return {number} The number of seconds that have elapsed since the game was started.
  55094. */
  55095. totalElapsedSeconds: function() {
  55096. return (this.time - this._started) * 0.001;
  55097. },
  55098. /**
  55099. * How long has passed since the given time.
  55100. *
  55101. * @method Phaser.Time#elapsedSince
  55102. * @param {number} since - The time you want to measure against.
  55103. * @return {number} The difference between the given time and now.
  55104. */
  55105. elapsedSince: function (since) {
  55106. return this.time - since;
  55107. },
  55108. /**
  55109. * How long has passed since the given time (in seconds).
  55110. *
  55111. * @method Phaser.Time#elapsedSecondsSince
  55112. * @param {number} since - The time you want to measure (in seconds).
  55113. * @return {number} Duration between given time and now (in seconds).
  55114. */
  55115. elapsedSecondsSince: function (since) {
  55116. return (this.time - since) * 0.001;
  55117. },
  55118. /**
  55119. * Resets the private _started value to now and removes all currently running Timers.
  55120. *
  55121. * @method Phaser.Time#reset
  55122. */
  55123. reset: function () {
  55124. this._started = this.time;
  55125. this.removeAll();
  55126. }
  55127. };
  55128. /**
  55129. * The desired frame rate of the game.
  55130. *
  55131. * This is used is used to calculate the physic / logic multiplier and how to apply catch-up logic updates.
  55132. *
  55133. * @name Phaser.Time#desiredFps
  55134. * @property {integer} desiredFps - The desired frame rate of the game. Defaults to 60.
  55135. */
  55136. Object.defineProperty(Phaser.Time.prototype, "desiredFps", {
  55137. get: function () {
  55138. return this._desiredFps;
  55139. },
  55140. set: function (value) {
  55141. this._desiredFps = value;
  55142. // Set the physics elapsed time... this will always be 1 / this.desiredFps
  55143. // because we're using fixed time steps in game.update
  55144. this.physicsElapsed = 1 / value;
  55145. this.physicsElapsedMS = this.physicsElapsed * 1000;
  55146. this.desiredFpsMult = 1.0 / value;
  55147. }
  55148. });
  55149. Phaser.Time.prototype.constructor = Phaser.Time;
  55150. /**
  55151. * @author Richard Davey <rich@photonstorm.com>
  55152. * @copyright 2016 Photon Storm Ltd.
  55153. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  55154. */
  55155. /**
  55156. * A Timer is a way to create and manage {@link Phaser.TimerEvent timer events} that wait for a specific duration and then run a callback.
  55157. * Many different timer events, with individual delays, can be added to the same Timer.
  55158. *
  55159. * All Timer delays are in milliseconds (there are 1000 ms in 1 second); so a delay value of 250 represents a quarter of a second.
  55160. *
  55161. * Timers are based on real life time, adjusted for game pause durations.
  55162. * That is, *timer events are based on elapsed {@link Phaser.Time game time}* and do *not* take physics time or slow motion into account.
  55163. *
  55164. * @class Phaser.Timer
  55165. * @constructor
  55166. * @param {Phaser.Game} game - A reference to the currently running game.
  55167. * @param {boolean} [autoDestroy=true] - If true, the timer will automatically destroy itself after all the events have been dispatched (assuming no looping events).
  55168. */
  55169. Phaser.Timer = function (game, autoDestroy) {
  55170. if (autoDestroy === undefined) { autoDestroy = true; }
  55171. /**
  55172. * @property {Phaser.Game} game - Local reference to game.
  55173. * @protected
  55174. */
  55175. this.game = game;
  55176. /**
  55177. * True if the Timer is actively running.
  55178. *
  55179. * Do not modify this boolean - use {@link Phaser.Timer#pause pause} (and {@link Phaser.Timer#resume resume}) to pause the timer.
  55180. * @property {boolean} running
  55181. * @default
  55182. * @readonly
  55183. */
  55184. this.running = false;
  55185. /**
  55186. * If true, the timer will automatically destroy itself after all the events have been dispatched (assuming no looping events).
  55187. * @property {boolean} autoDestroy
  55188. */
  55189. this.autoDestroy = autoDestroy;
  55190. /**
  55191. * @property {boolean} expired - An expired Timer is one in which all of its events have been dispatched and none are pending.
  55192. * @readonly
  55193. * @default
  55194. */
  55195. this.expired = false;
  55196. /**
  55197. * @property {number} elapsed - Elapsed time since the last frame (in ms).
  55198. * @protected
  55199. */
  55200. this.elapsed = 0;
  55201. /**
  55202. * @property {Phaser.TimerEvent[]} events - An array holding all of this timers Phaser.TimerEvent objects. Use the methods add, repeat and loop to populate it.
  55203. */
  55204. this.events = [];
  55205. /**
  55206. * This signal will be dispatched when this Timer has completed which means that there are no more events in the queue.
  55207. *
  55208. * The signal is supplied with one argument, `timer`, which is this Timer object.
  55209. *
  55210. * @property {Phaser.Signal} onComplete
  55211. */
  55212. this.onComplete = new Phaser.Signal();
  55213. /**
  55214. * @property {number} nextTick - The time the next tick will occur.
  55215. * @readonly
  55216. * @protected
  55217. */
  55218. this.nextTick = 0;
  55219. /**
  55220. * @property {number} timeCap - If the difference in time between two frame updates exceeds this value, the event times are reset to avoid catch-up situations.
  55221. */
  55222. this.timeCap = 1000;
  55223. /**
  55224. * @property {boolean} paused - The paused state of the Timer. You can pause the timer by calling Timer.pause() and Timer.resume() or by the game pausing.
  55225. * @readonly
  55226. * @default
  55227. */
  55228. this.paused = false;
  55229. /**
  55230. * @property {boolean} _codePaused - Was the Timer paused by code or by Game focus loss?
  55231. * @private
  55232. */
  55233. this._codePaused = false;
  55234. /**
  55235. * @property {number} _started - The time at which this Timer instance started running.
  55236. * @private
  55237. * @default
  55238. */
  55239. this._started = 0;
  55240. /**
  55241. * @property {number} _pauseStarted - The time the game started being paused.
  55242. * @private
  55243. */
  55244. this._pauseStarted = 0;
  55245. /**
  55246. * @property {number} _pauseTotal - Total paused time.
  55247. * @private
  55248. */
  55249. this._pauseTotal = 0;
  55250. /**
  55251. * @property {number} _now - The current start-time adjusted time.
  55252. * @private
  55253. */
  55254. this._now = Date.now();
  55255. /**
  55256. * @property {number} _len - Temp. array length variable.
  55257. * @private
  55258. */
  55259. this._len = 0;
  55260. /**
  55261. * @property {number} _marked - Temp. counter variable.
  55262. * @private
  55263. */
  55264. this._marked = 0;
  55265. /**
  55266. * @property {number} _i - Temp. array counter variable.
  55267. * @private
  55268. */
  55269. this._i = 0;
  55270. /**
  55271. * @property {number} _diff - Internal cache var.
  55272. * @private
  55273. */
  55274. this._diff = 0;
  55275. /**
  55276. * @property {number} _newTick - Internal cache var.
  55277. * @private
  55278. */
  55279. this._newTick = 0;
  55280. };
  55281. /**
  55282. * Number of milliseconds in a minute.
  55283. * @constant
  55284. * @type {integer}
  55285. */
  55286. Phaser.Timer.MINUTE = 60000;
  55287. /**
  55288. * Number of milliseconds in a second.
  55289. * @constant
  55290. * @type {integer}
  55291. */
  55292. Phaser.Timer.SECOND = 1000;
  55293. /**
  55294. * Number of milliseconds in half a second.
  55295. * @constant
  55296. * @type {integer}
  55297. */
  55298. Phaser.Timer.HALF = 500;
  55299. /**
  55300. * Number of milliseconds in a quarter of a second.
  55301. * @constant
  55302. * @type {integer}
  55303. */
  55304. Phaser.Timer.QUARTER = 250;
  55305. Phaser.Timer.prototype = {
  55306. /**
  55307. * Creates a new TimerEvent on this Timer.
  55308. *
  55309. * Use {@link Phaser.Timer#add}, {@link Phaser.Timer#repeat}, or {@link Phaser.Timer#loop} methods to create a new event.
  55310. *
  55311. * @method Phaser.Timer#create
  55312. * @private
  55313. * @param {integer} delay - The number of milliseconds, in {@link Phaser.Time game time}, before the timer event occurs.
  55314. * @param {boolean} loop - Should the event loop or not?
  55315. * @param {number} repeatCount - The number of times the event will repeat.
  55316. * @param {function} callback - The callback that will be called when the timer event occurs.
  55317. * @param {object} callbackContext - The context in which the callback will be called.
  55318. * @param {any[]} arguments - The values to be sent to your callback function when it is called.
  55319. * @return {Phaser.TimerEvent} The Phaser.TimerEvent object that was created.
  55320. */
  55321. create: function (delay, loop, repeatCount, callback, callbackContext, args) {
  55322. delay = Math.round(delay);
  55323. var tick = delay;
  55324. if (this._now === 0)
  55325. {
  55326. tick += this.game.time.time;
  55327. }
  55328. else
  55329. {
  55330. tick += this._now;
  55331. }
  55332. var event = new Phaser.TimerEvent(this, delay, tick, repeatCount, loop, callback, callbackContext, args);
  55333. this.events.push(event);
  55334. this.order();
  55335. this.expired = false;
  55336. return event;
  55337. },
  55338. /**
  55339. * Adds a new Event to this Timer.
  55340. *
  55341. * The event will fire after the given amount of `delay` in milliseconds has passed, once the Timer has started running.
  55342. * The delay is in relation to when the Timer starts, not the time it was added. If the Timer is already running the delay will be calculated based on the timers current time.
  55343. *
  55344. * Make sure to call {@link Phaser.Timer#start start} after adding all of the Events you require for this Timer.
  55345. *
  55346. * @method Phaser.Timer#add
  55347. * @param {integer} delay - The number of milliseconds, in {@link Phaser.Time game time}, before the timer event occurs.
  55348. * @param {function} callback - The callback that will be called when the timer event occurs.
  55349. * @param {object} callbackContext - The context in which the callback will be called.
  55350. * @param {...*} arguments - Additional arguments that will be supplied to the callback.
  55351. * @return {Phaser.TimerEvent} The Phaser.TimerEvent object that was created.
  55352. */
  55353. add: function (delay, callback, callbackContext) {
  55354. return this.create(delay, false, 0, callback, callbackContext, Array.prototype.slice.call(arguments, 3));
  55355. },
  55356. /**
  55357. * Adds a new TimerEvent that will always play through once and then repeat for the given number of iterations.
  55358. *
  55359. * The event will fire after the given amount of `delay` in milliseconds has passed, once the Timer has started running.
  55360. * The delay is in relation to when the Timer starts, not the time it was added.
  55361. * If the Timer is already running the delay will be calculated based on the timers current time.
  55362. *
  55363. * Make sure to call {@link Phaser.Timer#start start} after adding all of the Events you require for this Timer.
  55364. *
  55365. * @method Phaser.Timer#repeat
  55366. * @param {integer} delay - The number of milliseconds, in {@link Phaser.Time game time}, before the timer event occurs.
  55367. * @param {number} repeatCount - The number of times the event will repeat once is has finished playback. A repeatCount of 1 means it will repeat itself once, playing the event twice in total.
  55368. * @param {function} callback - The callback that will be called when the timer event occurs.
  55369. * @param {object} callbackContext - The context in which the callback will be called.
  55370. * @param {...*} arguments - Additional arguments that will be supplied to the callback.
  55371. * @return {Phaser.TimerEvent} The Phaser.TimerEvent object that was created.
  55372. */
  55373. repeat: function (delay, repeatCount, callback, callbackContext) {
  55374. return this.create(delay, false, repeatCount, callback, callbackContext, Array.prototype.slice.call(arguments, 4));
  55375. },
  55376. /**
  55377. * Adds a new looped Event to this Timer that will repeat forever or until the Timer is stopped.
  55378. *
  55379. * The event will fire after the given amount of `delay` in milliseconds has passed, once the Timer has started running.
  55380. * The delay is in relation to when the Timer starts, not the time it was added. If the Timer is already running the delay will be calculated based on the timers current time.
  55381. *
  55382. * Make sure to call {@link Phaser.Timer#start start} after adding all of the Events you require for this Timer.
  55383. *
  55384. * @method Phaser.Timer#loop
  55385. * @param {integer} delay - The number of milliseconds, in {@link Phaser.Time game time}, before the timer event occurs.
  55386. * @param {function} callback - The callback that will be called when the timer event occurs.
  55387. * @param {object} callbackContext - The context in which the callback will be called.
  55388. * @param {...*} arguments - Additional arguments that will be supplied to the callback.
  55389. * @return {Phaser.TimerEvent} The Phaser.TimerEvent object that was created.
  55390. */
  55391. loop: function (delay, callback, callbackContext) {
  55392. return this.create(delay, true, 0, callback, callbackContext, Array.prototype.slice.call(arguments, 3));
  55393. },
  55394. /**
  55395. * Starts this Timer running.
  55396. * @method Phaser.Timer#start
  55397. * @param {integer} [delay=0] - The number of milliseconds, in {@link Phaser.Time game time}, that should elapse before the Timer will start.
  55398. */
  55399. start: function (delay) {
  55400. if (this.running)
  55401. {
  55402. return;
  55403. }
  55404. this._started = this.game.time.time + (delay || 0);
  55405. this.running = true;
  55406. for (var i = 0; i < this.events.length; i++)
  55407. {
  55408. this.events[i].tick = this.events[i].delay + this._started;
  55409. }
  55410. },
  55411. /**
  55412. * Stops this Timer from running. Does not cause it to be destroyed if autoDestroy is set to true.
  55413. * @method Phaser.Timer#stop
  55414. * @param {boolean} [clearEvents=true] - If true all the events in Timer will be cleared, otherwise they will remain.
  55415. */
  55416. stop: function (clearEvents) {
  55417. this.running = false;
  55418. if (clearEvents === undefined) { clearEvents = true; }
  55419. if (clearEvents)
  55420. {
  55421. this.events.length = 0;
  55422. }
  55423. },
  55424. /**
  55425. * Removes a pending TimerEvent from the queue.
  55426. * @param {Phaser.TimerEvent} event - The event to remove from the queue.
  55427. * @method Phaser.Timer#remove
  55428. */
  55429. remove: function (event) {
  55430. for (var i = 0; i < this.events.length; i++)
  55431. {
  55432. if (this.events[i] === event)
  55433. {
  55434. this.events[i].pendingDelete = true;
  55435. return true;
  55436. }
  55437. }
  55438. return false;
  55439. },
  55440. /**
  55441. * Orders the events on this Timer so they are in tick order.
  55442. * This is called automatically when new events are created.
  55443. * @method Phaser.Timer#order
  55444. * @protected
  55445. */
  55446. order: function () {
  55447. if (this.events.length > 0)
  55448. {
  55449. // Sort the events so the one with the lowest tick is first
  55450. this.events.sort(this.sortHandler);
  55451. this.nextTick = this.events[0].tick;
  55452. }
  55453. },
  55454. /**
  55455. * Sort handler used by Phaser.Timer.order.
  55456. * @method Phaser.Timer#sortHandler
  55457. * @private
  55458. */
  55459. sortHandler: function (a, b) {
  55460. if (a.tick < b.tick)
  55461. {
  55462. return -1;
  55463. }
  55464. else if (a.tick > b.tick)
  55465. {
  55466. return 1;
  55467. }
  55468. return 0;
  55469. },
  55470. /**
  55471. * Clears any events from the Timer which have pendingDelete set to true and then resets the private _len and _i values.
  55472. *
  55473. * @method Phaser.Timer#clearPendingEvents
  55474. * @protected
  55475. */
  55476. clearPendingEvents: function () {
  55477. this._i = this.events.length;
  55478. while (this._i--)
  55479. {
  55480. if (this.events[this._i].pendingDelete)
  55481. {
  55482. this.events.splice(this._i, 1);
  55483. }
  55484. }
  55485. this._len = this.events.length;
  55486. this._i = 0;
  55487. },
  55488. /**
  55489. * The main Timer update event, called automatically by Phaser.Time.update.
  55490. *
  55491. * @method Phaser.Timer#update
  55492. * @protected
  55493. * @param {number} time - The time from the core game clock.
  55494. * @return {boolean} True if there are still events waiting to be dispatched, otherwise false if this Timer can be destroyed.
  55495. */
  55496. update: function (time) {
  55497. if (this.paused)
  55498. {
  55499. return true;
  55500. }
  55501. this.elapsed = time - this._now;
  55502. this._now = time;
  55503. // spike-dislike
  55504. if (this.elapsed > this.timeCap)
  55505. {
  55506. // For some reason the time between now and the last time the game was updated was larger than our timeCap.
  55507. // This can happen if the Stage.disableVisibilityChange is true and you swap tabs, which makes the raf pause.
  55508. // In this case we need to adjust the TimerEvents and nextTick.
  55509. this.adjustEvents(time - this.elapsed);
  55510. }
  55511. this._marked = 0;
  55512. // Clears events marked for deletion and resets _len and _i to 0.
  55513. this.clearPendingEvents();
  55514. if (this.running && this._now >= this.nextTick && this._len > 0)
  55515. {
  55516. while (this._i < this._len && this.running)
  55517. {
  55518. if (this._now >= this.events[this._i].tick && !this.events[this._i].pendingDelete)
  55519. {
  55520. // (now + delay) - (time difference from last tick to now)
  55521. this._newTick = (this._now + this.events[this._i].delay) - (this._now - this.events[this._i].tick);
  55522. if (this._newTick < 0)
  55523. {
  55524. this._newTick = this._now + this.events[this._i].delay;
  55525. }
  55526. if (this.events[this._i].loop === true)
  55527. {
  55528. this.events[this._i].tick = this._newTick;
  55529. this.events[this._i].callback.apply(this.events[this._i].callbackContext, this.events[this._i].args);
  55530. }
  55531. else if (this.events[this._i].repeatCount > 0)
  55532. {
  55533. this.events[this._i].repeatCount--;
  55534. this.events[this._i].tick = this._newTick;
  55535. this.events[this._i].callback.apply(this.events[this._i].callbackContext, this.events[this._i].args);
  55536. }
  55537. else
  55538. {
  55539. this._marked++;
  55540. this.events[this._i].pendingDelete = true;
  55541. this.events[this._i].callback.apply(this.events[this._i].callbackContext, this.events[this._i].args);
  55542. }
  55543. this._i++;
  55544. }
  55545. else
  55546. {
  55547. break;
  55548. }
  55549. }
  55550. // Are there any events left?
  55551. if (this.events.length > this._marked)
  55552. {
  55553. this.order();
  55554. }
  55555. else
  55556. {
  55557. this.expired = true;
  55558. this.onComplete.dispatch(this);
  55559. }
  55560. }
  55561. if (this.expired && this.autoDestroy)
  55562. {
  55563. return false;
  55564. }
  55565. else
  55566. {
  55567. return true;
  55568. }
  55569. },
  55570. /**
  55571. * Pauses the Timer and all events in the queue.
  55572. * @method Phaser.Timer#pause
  55573. */
  55574. pause: function () {
  55575. if (!this.running)
  55576. {
  55577. return;
  55578. }
  55579. this._codePaused = true;
  55580. if (this.paused)
  55581. {
  55582. return;
  55583. }
  55584. this._pauseStarted = this.game.time.time;
  55585. this.paused = true;
  55586. },
  55587. /**
  55588. * Internal pause/resume control - user code should use Timer.pause instead.
  55589. * @method Phaser.Timer#_pause
  55590. * @private
  55591. */
  55592. _pause: function () {
  55593. if (this.paused || !this.running)
  55594. {
  55595. return;
  55596. }
  55597. this._pauseStarted = this.game.time.time;
  55598. this.paused = true;
  55599. },
  55600. /**
  55601. * Adjusts the time of all pending events and the nextTick by the given baseTime.
  55602. *
  55603. * @method Phaser.Timer#adjustEvents
  55604. * @protected
  55605. */
  55606. adjustEvents: function (baseTime) {
  55607. for (var i = 0; i < this.events.length; i++)
  55608. {
  55609. if (!this.events[i].pendingDelete)
  55610. {
  55611. // Work out how long there would have been from when the game paused until the events next tick
  55612. var t = this.events[i].tick - baseTime;
  55613. if (t < 0)
  55614. {
  55615. t = 0;
  55616. }
  55617. // Add the difference on to the time now
  55618. this.events[i].tick = this._now + t;
  55619. }
  55620. }
  55621. var d = this.nextTick - baseTime;
  55622. if (d < 0)
  55623. {
  55624. this.nextTick = this._now;
  55625. }
  55626. else
  55627. {
  55628. this.nextTick = this._now + d;
  55629. }
  55630. },
  55631. /**
  55632. * Resumes the Timer and updates all pending events.
  55633. *
  55634. * @method Phaser.Timer#resume
  55635. */
  55636. resume: function () {
  55637. if (!this.paused)
  55638. {
  55639. return;
  55640. }
  55641. var now = this.game.time.time;
  55642. this._pauseTotal += now - this._now;
  55643. this._now = now;
  55644. this.adjustEvents(this._pauseStarted);
  55645. this.paused = false;
  55646. this._codePaused = false;
  55647. },
  55648. /**
  55649. * Internal pause/resume control - user code should use Timer.resume instead.
  55650. * @method Phaser.Timer#_resume
  55651. * @private
  55652. */
  55653. _resume: function () {
  55654. if (this._codePaused)
  55655. {
  55656. return;
  55657. }
  55658. else
  55659. {
  55660. this.resume();
  55661. }
  55662. },
  55663. /**
  55664. * Removes all Events from this Timer and all callbacks linked to onComplete, but leaves the Timer running.
  55665. * The onComplete callbacks won't be called.
  55666. *
  55667. * @method Phaser.Timer#removeAll
  55668. */
  55669. removeAll: function () {
  55670. this.onComplete.removeAll();
  55671. this.events.length = 0;
  55672. this._len = 0;
  55673. this._i = 0;
  55674. },
  55675. /**
  55676. * Destroys this Timer. Any pending Events are not dispatched.
  55677. * The onComplete callbacks won't be called.
  55678. *
  55679. * @method Phaser.Timer#destroy
  55680. */
  55681. destroy: function () {
  55682. this.onComplete.removeAll();
  55683. this.running = false;
  55684. this.events = [];
  55685. this._len = 0;
  55686. this._i = 0;
  55687. }
  55688. };
  55689. /**
  55690. * @name Phaser.Timer#next
  55691. * @property {number} next - The time at which the next event will occur.
  55692. * @readonly
  55693. */
  55694. Object.defineProperty(Phaser.Timer.prototype, "next", {
  55695. get: function () {
  55696. return this.nextTick;
  55697. }
  55698. });
  55699. /**
  55700. * @name Phaser.Timer#duration
  55701. * @property {number} duration - The duration in ms remaining until the next event will occur.
  55702. * @readonly
  55703. */
  55704. Object.defineProperty(Phaser.Timer.prototype, "duration", {
  55705. get: function () {
  55706. if (this.running && this.nextTick > this._now)
  55707. {
  55708. return this.nextTick - this._now;
  55709. }
  55710. else
  55711. {
  55712. return 0;
  55713. }
  55714. }
  55715. });
  55716. /**
  55717. * @name Phaser.Timer#length
  55718. * @property {number} length - The number of pending events in the queue.
  55719. * @readonly
  55720. */
  55721. Object.defineProperty(Phaser.Timer.prototype, "length", {
  55722. get: function () {
  55723. return this.events.length;
  55724. }
  55725. });
  55726. /**
  55727. * @name Phaser.Timer#ms
  55728. * @property {number} ms - The duration in milliseconds that this Timer has been running for.
  55729. * @readonly
  55730. */
  55731. Object.defineProperty(Phaser.Timer.prototype, "ms", {
  55732. get: function () {
  55733. if (this.running)
  55734. {
  55735. return this._now - this._started - this._pauseTotal;
  55736. }
  55737. else
  55738. {
  55739. return 0;
  55740. }
  55741. }
  55742. });
  55743. /**
  55744. * @name Phaser.Timer#seconds
  55745. * @property {number} seconds - The duration in seconds that this Timer has been running for.
  55746. * @readonly
  55747. */
  55748. Object.defineProperty(Phaser.Timer.prototype, "seconds", {
  55749. get: function () {
  55750. if (this.running)
  55751. {
  55752. return this.ms * 0.001;
  55753. }
  55754. else
  55755. {
  55756. return 0;
  55757. }
  55758. }
  55759. });
  55760. Phaser.Timer.prototype.constructor = Phaser.Timer;
  55761. /**
  55762. * @author Richard Davey <rich@photonstorm.com>
  55763. * @copyright 2016 Photon Storm Ltd.
  55764. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  55765. */
  55766. /**
  55767. * A TimerEvent is a single event that is processed by a Phaser.Timer.
  55768. *
  55769. * It consists of a delay, which is a value in milliseconds after which the event will fire.
  55770. * When the event fires it calls a specific callback with the specified arguments.
  55771. *
  55772. * TimerEvents are removed by their parent timer once finished firing or repeating.
  55773. *
  55774. * Use {@link Phaser.Timer#add}, {@link Phaser.Timer#repeat}, or {@link Phaser.Timer#loop} methods to create a new event.
  55775. *
  55776. * @class Phaser.TimerEvent
  55777. * @constructor
  55778. * @param {Phaser.Timer} timer - The Timer object that this TimerEvent belongs to.
  55779. * @param {number} delay - The delay in ms at which this TimerEvent fires.
  55780. * @param {number} tick - The tick is the next game clock time that this event will fire at.
  55781. * @param {number} repeatCount - If this TimerEvent repeats it will do so this many times.
  55782. * @param {boolean} loop - True if this TimerEvent loops, otherwise false.
  55783. * @param {function} callback - The callback that will be called when the TimerEvent occurs.
  55784. * @param {object} callbackContext - The context in which the callback will be called.
  55785. * @param {any[]} arguments - Additional arguments to be passed to the callback.
  55786. */
  55787. Phaser.TimerEvent = function (timer, delay, tick, repeatCount, loop, callback, callbackContext, args) {
  55788. /**
  55789. * @property {Phaser.Timer} timer - The Timer object that this TimerEvent belongs to.
  55790. * @protected
  55791. * @readonly
  55792. */
  55793. this.timer = timer;
  55794. /**
  55795. * @property {number} delay - The delay in ms at which this TimerEvent fires.
  55796. */
  55797. this.delay = delay;
  55798. /**
  55799. * @property {number} tick - The tick is the next game clock time that this event will fire at.
  55800. */
  55801. this.tick = tick;
  55802. /**
  55803. * @property {number} repeatCount - If this TimerEvent repeats it will do so this many times.
  55804. */
  55805. this.repeatCount = repeatCount - 1;
  55806. /**
  55807. * @property {boolean} loop - True if this TimerEvent loops, otherwise false.
  55808. */
  55809. this.loop = loop;
  55810. /**
  55811. * @property {function} callback - The callback that will be called when the TimerEvent occurs.
  55812. */
  55813. this.callback = callback;
  55814. /**
  55815. * @property {object} callbackContext - The context in which the callback will be called.
  55816. */
  55817. this.callbackContext = callbackContext;
  55818. /**
  55819. * @property {any[]} arguments - Additional arguments to be passed to the callback.
  55820. */
  55821. this.args = args;
  55822. /**
  55823. * @property {boolean} pendingDelete - A flag that controls if the TimerEvent is pending deletion.
  55824. * @protected
  55825. */
  55826. this.pendingDelete = false;
  55827. };
  55828. Phaser.TimerEvent.prototype.constructor = Phaser.TimerEvent;
  55829. /**
  55830. * @author Richard Davey <rich@photonstorm.com>
  55831. * @copyright 2016 Photon Storm Ltd.
  55832. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  55833. */
  55834. /**
  55835. * The Animation Manager is used to add, play and update Phaser Animations.
  55836. * Any Game Object such as Phaser.Sprite that supports animation contains a single AnimationManager instance.
  55837. *
  55838. * @class Phaser.AnimationManager
  55839. * @constructor
  55840. * @param {Phaser.Sprite} sprite - A reference to the Game Object that owns this AnimationManager.
  55841. */
  55842. Phaser.AnimationManager = function (sprite) {
  55843. /**
  55844. * @property {Phaser.Sprite} sprite - A reference to the parent Sprite that owns this AnimationManager.
  55845. */
  55846. this.sprite = sprite;
  55847. /**
  55848. * @property {Phaser.Game} game - A reference to the currently running Game.
  55849. */
  55850. this.game = sprite.game;
  55851. /**
  55852. * The currently displayed Frame of animation, if any.
  55853. * This property is only set once an Animation starts playing. Until that point it remains set as `null`.
  55854. *
  55855. * @property {Phaser.Frame} currentFrame
  55856. * @default
  55857. */
  55858. this.currentFrame = null;
  55859. /**
  55860. * @property {Phaser.Animation} currentAnim - The currently displayed animation, if any.
  55861. * @default
  55862. */
  55863. this.currentAnim = null;
  55864. /**
  55865. * @property {boolean} updateIfVisible - Should the animation data continue to update even if the Sprite.visible is set to false.
  55866. * @default
  55867. */
  55868. this.updateIfVisible = true;
  55869. /**
  55870. * @property {boolean} isLoaded - Set to true once animation data has been loaded.
  55871. * @default
  55872. */
  55873. this.isLoaded = false;
  55874. /**
  55875. * @property {Phaser.FrameData} _frameData - A temp. var for holding the currently playing Animations FrameData.
  55876. * @private
  55877. * @default
  55878. */
  55879. this._frameData = null;
  55880. /**
  55881. * @property {object} _anims - An internal object that stores all of the Animation instances.
  55882. * @private
  55883. */
  55884. this._anims = {};
  55885. /**
  55886. * @property {object} _outputFrames - An internal object to help avoid gc.
  55887. * @private
  55888. */
  55889. this._outputFrames = [];
  55890. };
  55891. Phaser.AnimationManager.prototype = {
  55892. /**
  55893. * Loads FrameData into the internal temporary vars and resets the frame index to zero.
  55894. * This is called automatically when a new Sprite is created.
  55895. *
  55896. * @method Phaser.AnimationManager#loadFrameData
  55897. * @private
  55898. * @param {Phaser.FrameData} frameData - The FrameData set to load.
  55899. * @param {string|number} frame - The frame to default to.
  55900. * @return {boolean} Returns `true` if the frame data was loaded successfully, otherwise `false`
  55901. */
  55902. loadFrameData: function (frameData, frame) {
  55903. if (frameData === undefined)
  55904. {
  55905. return false;
  55906. }
  55907. if (this.isLoaded)
  55908. {
  55909. // We need to update the frameData that the animations are using
  55910. for (var anim in this._anims)
  55911. {
  55912. this._anims[anim].updateFrameData(frameData);
  55913. }
  55914. }
  55915. this._frameData = frameData;
  55916. if (frame === undefined || frame === null)
  55917. {
  55918. this.frame = 0;
  55919. }
  55920. else
  55921. {
  55922. if (typeof frame === 'string')
  55923. {
  55924. this.frameName = frame;
  55925. }
  55926. else
  55927. {
  55928. this.frame = frame;
  55929. }
  55930. }
  55931. this.isLoaded = true;
  55932. return true;
  55933. },
  55934. /**
  55935. * Loads FrameData into the internal temporary vars and resets the frame index to zero.
  55936. * This is called automatically when a new Sprite is created.
  55937. *
  55938. * @method Phaser.AnimationManager#copyFrameData
  55939. * @private
  55940. * @param {Phaser.FrameData} frameData - The FrameData set to load.
  55941. * @param {string|number} frame - The frame to default to.
  55942. * @return {boolean} Returns `true` if the frame data was loaded successfully, otherwise `false`
  55943. */
  55944. copyFrameData: function (frameData, frame) {
  55945. this._frameData = frameData.clone();
  55946. if (this.isLoaded)
  55947. {
  55948. // We need to update the frameData that the animations are using
  55949. for (var anim in this._anims)
  55950. {
  55951. this._anims[anim].updateFrameData(this._frameData);
  55952. }
  55953. }
  55954. if (frame === undefined || frame === null)
  55955. {
  55956. this.frame = 0;
  55957. }
  55958. else
  55959. {
  55960. if (typeof frame === 'string')
  55961. {
  55962. this.frameName = frame;
  55963. }
  55964. else
  55965. {
  55966. this.frame = frame;
  55967. }
  55968. }
  55969. this.isLoaded = true;
  55970. return true;
  55971. },
  55972. /**
  55973. * Adds a new animation under the given key. Optionally set the frames, frame rate and loop.
  55974. * Animations added in this way are played back with the play function.
  55975. *
  55976. * @method Phaser.AnimationManager#add
  55977. * @param {string} name - The unique (within this Sprite) name for the animation, i.e. "run", "fire", "walk".
  55978. * @param {Array} [frames=null] - An array of numbers/strings that correspond to the frames to add to this animation and in which order. e.g. [1, 2, 3] or ['run0', 'run1', run2]). If null then all frames will be used.
  55979. * @param {number} [frameRate=60] - The speed at which the animation should play. The speed is given in frames per second.
  55980. * @param {boolean} [loop=false] - Whether or not the animation is looped or just plays once.
  55981. * @param {boolean} [useNumericIndex=true] - Are the given frames using numeric indexes (default) or strings?
  55982. * @return {Phaser.Animation} The Animation object that was created.
  55983. */
  55984. add: function (name, frames, frameRate, loop, useNumericIndex) {
  55985. frames = frames || [];
  55986. frameRate = frameRate || 60;
  55987. if (loop === undefined) { loop = false; }
  55988. // If they didn't set the useNumericIndex then let's at least try and guess it
  55989. if (useNumericIndex === undefined)
  55990. {
  55991. if (frames && typeof frames[0] === 'number')
  55992. {
  55993. useNumericIndex = true;
  55994. }
  55995. else
  55996. {
  55997. useNumericIndex = false;
  55998. }
  55999. }
  56000. this._outputFrames = [];
  56001. this._frameData.getFrameIndexes(frames, useNumericIndex, this._outputFrames);
  56002. this._anims[name] = new Phaser.Animation(this.game, this.sprite, name, this._frameData, this._outputFrames, frameRate, loop);
  56003. this.currentAnim = this._anims[name];
  56004. if (this.sprite.tilingTexture)
  56005. {
  56006. this.sprite.refreshTexture = true;
  56007. }
  56008. return this._anims[name];
  56009. },
  56010. /**
  56011. * Check whether the frames in the given array are valid and exist.
  56012. *
  56013. * @method Phaser.AnimationManager#validateFrames
  56014. * @param {Array} frames - An array of frames to be validated.
  56015. * @param {boolean} [useNumericIndex=true] - Validate the frames based on their numeric index (true) or string index (false)
  56016. * @return {boolean} True if all given Frames are valid, otherwise false.
  56017. */
  56018. validateFrames: function (frames, useNumericIndex) {
  56019. if (useNumericIndex === undefined) { useNumericIndex = true; }
  56020. for (var i = 0; i < frames.length; i++)
  56021. {
  56022. if (useNumericIndex === true)
  56023. {
  56024. if (frames[i] > this._frameData.total)
  56025. {
  56026. return false;
  56027. }
  56028. }
  56029. else
  56030. {
  56031. if (this._frameData.checkFrameName(frames[i]) === false)
  56032. {
  56033. return false;
  56034. }
  56035. }
  56036. }
  56037. return true;
  56038. },
  56039. /**
  56040. * Play an animation based on the given key. The animation should previously have been added via `animations.add`
  56041. *
  56042. * If the requested animation is already playing this request will be ignored.
  56043. * If you need to reset an already running animation do so directly on the Animation object itself.
  56044. *
  56045. * @method Phaser.AnimationManager#play
  56046. * @param {string} name - The name of the animation to be played, e.g. "fire", "walk", "jump".
  56047. * @param {number} [frameRate=null] - The framerate to play the animation at. The speed is given in frames per second. If not provided the previously set frameRate of the Animation is used.
  56048. * @param {boolean} [loop=false] - Should the animation be looped after playback. If not provided the previously set loop value of the Animation is used.
  56049. * @param {boolean} [killOnComplete=false] - If set to true when the animation completes (only happens if loop=false) the parent Sprite will be killed.
  56050. * @return {Phaser.Animation} A reference to playing Animation instance.
  56051. */
  56052. play: function (name, frameRate, loop, killOnComplete) {
  56053. if (this._anims[name])
  56054. {
  56055. if (this.currentAnim === this._anims[name])
  56056. {
  56057. if (this.currentAnim.isPlaying === false)
  56058. {
  56059. this.currentAnim.paused = false;
  56060. return this.currentAnim.play(frameRate, loop, killOnComplete);
  56061. }
  56062. return this.currentAnim;
  56063. }
  56064. else
  56065. {
  56066. if (this.currentAnim && this.currentAnim.isPlaying)
  56067. {
  56068. this.currentAnim.stop();
  56069. }
  56070. this.currentAnim = this._anims[name];
  56071. this.currentAnim.paused = false;
  56072. this.currentFrame = this.currentAnim.currentFrame;
  56073. return this.currentAnim.play(frameRate, loop, killOnComplete);
  56074. }
  56075. }
  56076. },
  56077. /**
  56078. * Stop playback of an animation. If a name is given that specific animation is stopped, otherwise the current animation is stopped.
  56079. * The currentAnim property of the AnimationManager is automatically set to the animation given.
  56080. *
  56081. * @method Phaser.AnimationManager#stop
  56082. * @param {string} [name=null] - The name of the animation to be stopped, e.g. "fire". If none is given the currently running animation is stopped.
  56083. * @param {boolean} [resetFrame=false] - When the animation is stopped should the currentFrame be set to the first frame of the animation (true) or paused on the last frame displayed (false)
  56084. */
  56085. stop: function (name, resetFrame) {
  56086. if (resetFrame === undefined) { resetFrame = false; }
  56087. if (this.currentAnim && (typeof name !== 'string' || name === this.currentAnim.name))
  56088. {
  56089. this.currentAnim.stop(resetFrame);
  56090. }
  56091. },
  56092. /**
  56093. * The main update function is called by the Sprites update loop. It's responsible for updating animation frames and firing related events.
  56094. *
  56095. * @method Phaser.AnimationManager#update
  56096. * @protected
  56097. * @return {boolean} True if a new animation frame has been set, otherwise false.
  56098. */
  56099. update: function () {
  56100. if (this.updateIfVisible && !this.sprite.visible)
  56101. {
  56102. return false;
  56103. }
  56104. if (this.currentAnim && this.currentAnim.update())
  56105. {
  56106. this.currentFrame = this.currentAnim.currentFrame;
  56107. return true;
  56108. }
  56109. return false;
  56110. },
  56111. /**
  56112. * Advances by the given number of frames in the current animation, taking the loop value into consideration.
  56113. *
  56114. * @method Phaser.AnimationManager#next
  56115. * @param {number} [quantity=1] - The number of frames to advance.
  56116. */
  56117. next: function (quantity) {
  56118. if (this.currentAnim)
  56119. {
  56120. this.currentAnim.next(quantity);
  56121. this.currentFrame = this.currentAnim.currentFrame;
  56122. }
  56123. },
  56124. /**
  56125. * Moves backwards the given number of frames in the current animation, taking the loop value into consideration.
  56126. *
  56127. * @method Phaser.AnimationManager#previous
  56128. * @param {number} [quantity=1] - The number of frames to move back.
  56129. */
  56130. previous: function (quantity) {
  56131. if (this.currentAnim)
  56132. {
  56133. this.currentAnim.previous(quantity);
  56134. this.currentFrame = this.currentAnim.currentFrame;
  56135. }
  56136. },
  56137. /**
  56138. * Returns an animation that was previously added by name.
  56139. *
  56140. * @method Phaser.AnimationManager#getAnimation
  56141. * @param {string} name - The name of the animation to be returned, e.g. "fire".
  56142. * @return {Phaser.Animation} The Animation instance, if found, otherwise null.
  56143. */
  56144. getAnimation: function (name) {
  56145. if (typeof name === 'string')
  56146. {
  56147. if (this._anims[name])
  56148. {
  56149. return this._anims[name];
  56150. }
  56151. }
  56152. return null;
  56153. },
  56154. /**
  56155. * Refreshes the current frame data back to the parent Sprite and also resets the texture data.
  56156. *
  56157. * @method Phaser.AnimationManager#refreshFrame
  56158. */
  56159. refreshFrame: function () {
  56160. // TODO
  56161. // this.sprite.setTexture(PIXI.TextureCache[this.currentFrame.uuid]);
  56162. },
  56163. /**
  56164. * Destroys all references this AnimationManager contains.
  56165. * Iterates through the list of animations stored in this manager and calls destroy on each of them.
  56166. *
  56167. * @method Phaser.AnimationManager#destroy
  56168. */
  56169. destroy: function () {
  56170. var anim = null;
  56171. for (var anim in this._anims)
  56172. {
  56173. if (this._anims.hasOwnProperty(anim))
  56174. {
  56175. this._anims[anim].destroy();
  56176. }
  56177. }
  56178. this._anims = {};
  56179. this._outputFrames = [];
  56180. this._frameData = null;
  56181. this.currentAnim = null;
  56182. this.currentFrame = null;
  56183. this.sprite = null;
  56184. this.game = null;
  56185. }
  56186. };
  56187. Phaser.AnimationManager.prototype.constructor = Phaser.AnimationManager;
  56188. /**
  56189. * @name Phaser.AnimationManager#frameData
  56190. * @property {Phaser.FrameData} frameData - The current animations FrameData.
  56191. * @readonly
  56192. */
  56193. Object.defineProperty(Phaser.AnimationManager.prototype, 'frameData', {
  56194. get: function () {
  56195. return this._frameData;
  56196. }
  56197. });
  56198. /**
  56199. * @name Phaser.AnimationManager#frameTotal
  56200. * @property {number} frameTotal - The total number of frames in the currently loaded FrameData, or -1 if no FrameData is loaded.
  56201. * @readonly
  56202. */
  56203. Object.defineProperty(Phaser.AnimationManager.prototype, 'frameTotal', {
  56204. get: function () {
  56205. return this._frameData.total;
  56206. }
  56207. });
  56208. /**
  56209. * @name Phaser.AnimationManager#paused
  56210. * @property {boolean} paused - Gets and sets the paused state of the current animation.
  56211. */
  56212. Object.defineProperty(Phaser.AnimationManager.prototype, 'paused', {
  56213. get: function () {
  56214. return this.currentAnim.isPaused;
  56215. },
  56216. set: function (value) {
  56217. this.currentAnim.paused = value;
  56218. }
  56219. });
  56220. /**
  56221. * @name Phaser.AnimationManager#name
  56222. * @property {string} name - Gets the current animation name, if set.
  56223. */
  56224. Object.defineProperty(Phaser.AnimationManager.prototype, 'name', {
  56225. get: function () {
  56226. if (this.currentAnim)
  56227. {
  56228. return this.currentAnim.name;
  56229. }
  56230. }
  56231. });
  56232. /**
  56233. * @name Phaser.AnimationManager#frame
  56234. * @property {number} frame - Gets or sets the current frame index and updates the Texture Cache for display.
  56235. */
  56236. Object.defineProperty(Phaser.AnimationManager.prototype, 'frame', {
  56237. get: function () {
  56238. if (this.currentFrame)
  56239. {
  56240. return this.currentFrame.index;
  56241. }
  56242. },
  56243. set: function (value) {
  56244. if (typeof value === 'number' && this._frameData && this._frameData.getFrame(value) !== null)
  56245. {
  56246. this.currentFrame = this._frameData.getFrame(value);
  56247. if (this.currentFrame)
  56248. {
  56249. this.sprite.setFrame(this.currentFrame);
  56250. }
  56251. }
  56252. }
  56253. });
  56254. /**
  56255. * @name Phaser.AnimationManager#frameName
  56256. * @property {string} frameName - Gets or sets the current frame name and updates the Texture Cache for display.
  56257. */
  56258. Object.defineProperty(Phaser.AnimationManager.prototype, 'frameName', {
  56259. get: function () {
  56260. if (this.currentFrame)
  56261. {
  56262. return this.currentFrame.name;
  56263. }
  56264. },
  56265. set: function (value) {
  56266. if (typeof value === 'string' && this._frameData && this._frameData.getFrameByName(value) !== null)
  56267. {
  56268. this.currentFrame = this._frameData.getFrameByName(value);
  56269. if (this.currentFrame)
  56270. {
  56271. this._frameIndex = this.currentFrame.index;
  56272. this.sprite.setFrame(this.currentFrame);
  56273. }
  56274. }
  56275. else
  56276. {
  56277. console.warn('Cannot set frameName: ' + value);
  56278. }
  56279. }
  56280. });
  56281. /**
  56282. * @author Richard Davey <rich@photonstorm.com>
  56283. * @copyright 2016 Photon Storm Ltd.
  56284. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  56285. */
  56286. /**
  56287. * An Animation instance contains a single animation and the controls to play it.
  56288. *
  56289. * It is created by the AnimationManager, consists of Animation.Frame objects and belongs to a single Game Object such as a Sprite.
  56290. *
  56291. * @class Phaser.Animation
  56292. * @constructor
  56293. * @param {Phaser.Game} game - A reference to the currently running game.
  56294. * @param {Phaser.Sprite} parent - A reference to the owner of this Animation.
  56295. * @param {string} name - The unique name for this animation, used in playback commands.
  56296. * @param {Phaser.FrameData} frameData - The FrameData object that contains all frames used by this Animation.
  56297. * @param {number[]|string[]} frames - An array of numbers or strings indicating which frames to play in which order.
  56298. * @param {number} [frameRate=60] - The speed at which the animation should play. The speed is given in frames per second.
  56299. * @param {boolean} [loop=false] - Whether or not the animation is looped or just plays once.
  56300. */
  56301. Phaser.Animation = function (game, parent, name, frameData, frames, frameRate, loop) {
  56302. if (loop === undefined) { loop = false; }
  56303. /**
  56304. * @property {Phaser.Game} game - A reference to the currently running Game.
  56305. */
  56306. this.game = game;
  56307. /**
  56308. * @property {Phaser.Sprite} _parent - A reference to the parent Sprite that owns this Animation.
  56309. * @private
  56310. */
  56311. this._parent = parent;
  56312. /**
  56313. * @property {Phaser.FrameData} _frameData - The FrameData the Animation uses.
  56314. * @private
  56315. */
  56316. this._frameData = frameData;
  56317. /**
  56318. * @property {string} name - The user defined name given to this Animation.
  56319. */
  56320. this.name = name;
  56321. /**
  56322. * @property {array} _frames
  56323. * @private
  56324. */
  56325. this._frames = [];
  56326. this._frames = this._frames.concat(frames);
  56327. /**
  56328. * @property {number} delay - The delay in ms between each frame of the Animation, based on the given frameRate.
  56329. */
  56330. this.delay = 1000 / frameRate;
  56331. /**
  56332. * @property {boolean} loop - The loop state of the Animation.
  56333. */
  56334. this.loop = loop;
  56335. /**
  56336. * @property {number} loopCount - The number of times the animation has looped since it was last started.
  56337. */
  56338. this.loopCount = 0;
  56339. /**
  56340. * @property {boolean} killOnComplete - Should the parent of this Animation be killed when the animation completes?
  56341. * @default
  56342. */
  56343. this.killOnComplete = false;
  56344. /**
  56345. * @property {boolean} isFinished - The finished state of the Animation. Set to true once playback completes, false during playback.
  56346. * @default
  56347. */
  56348. this.isFinished = false;
  56349. /**
  56350. * @property {boolean} isPlaying - The playing state of the Animation. Set to false once playback completes, true during playback.
  56351. * @default
  56352. */
  56353. this.isPlaying = false;
  56354. /**
  56355. * @property {boolean} isPaused - The paused state of the Animation.
  56356. * @default
  56357. */
  56358. this.isPaused = false;
  56359. /**
  56360. * @property {boolean} _pauseStartTime - The time the animation paused.
  56361. * @private
  56362. * @default
  56363. */
  56364. this._pauseStartTime = 0;
  56365. /**
  56366. * @property {number} _frameIndex
  56367. * @private
  56368. * @default
  56369. */
  56370. this._frameIndex = 0;
  56371. /**
  56372. * @property {number} _frameDiff
  56373. * @private
  56374. * @default
  56375. */
  56376. this._frameDiff = 0;
  56377. /**
  56378. * @property {number} _frameSkip
  56379. * @private
  56380. * @default
  56381. */
  56382. this._frameSkip = 1;
  56383. /**
  56384. * @property {Phaser.Frame} currentFrame - The currently displayed frame of the Animation.
  56385. */
  56386. this.currentFrame = this._frameData.getFrame(this._frames[this._frameIndex]);
  56387. /**
  56388. * @property {Phaser.Signal} onStart - This event is dispatched when this Animation starts playback.
  56389. */
  56390. this.onStart = new Phaser.Signal();
  56391. /**
  56392. * This event is dispatched when the Animation changes frame.
  56393. * By default this event is disabled due to its intensive nature. Enable it with: `Animation.enableUpdate = true`.
  56394. * Note that the event is only dispatched with the current frame. In a low-FPS environment Animations
  56395. * will automatically frame-skip to try and claw back time, so do not base your code on expecting to
  56396. * receive a perfectly sequential set of frames from this event.
  56397. * @property {Phaser.Signal|null} onUpdate
  56398. * @default
  56399. */
  56400. this.onUpdate = null;
  56401. /**
  56402. * @property {Phaser.Signal} onComplete - This event is dispatched when this Animation completes playback. If the animation is set to loop this is never fired, listen for onLoop instead.
  56403. */
  56404. this.onComplete = new Phaser.Signal();
  56405. /**
  56406. * @property {Phaser.Signal} onLoop - This event is dispatched when this Animation loops.
  56407. */
  56408. this.onLoop = new Phaser.Signal();
  56409. /**
  56410. * @property {boolean} isReversed - Indicates if the animation will play backwards.
  56411. * @default
  56412. */
  56413. this.isReversed = false;
  56414. // Set-up some event listeners
  56415. this.game.onPause.add(this.onPause, this);
  56416. this.game.onResume.add(this.onResume, this);
  56417. };
  56418. Phaser.Animation.prototype = {
  56419. /**
  56420. * Plays this animation.
  56421. *
  56422. * @method Phaser.Animation#play
  56423. * @param {number} [frameRate=null] - The framerate to play the animation at. The speed is given in frames per second. If not provided the previously set frameRate of the Animation is used.
  56424. * @param {boolean} [loop=false] - Should the animation be looped after playback. If not provided the previously set loop value of the Animation is used.
  56425. * @param {boolean} [killOnComplete=false] - If set to true when the animation completes (only happens if loop=false) the parent Sprite will be killed.
  56426. * @return {Phaser.Animation} - A reference to this Animation instance.
  56427. */
  56428. play: function (frameRate, loop, killOnComplete) {
  56429. if (typeof frameRate === 'number')
  56430. {
  56431. // If they set a new frame rate then use it, otherwise use the one set on creation
  56432. this.delay = 1000 / frameRate;
  56433. }
  56434. if (typeof loop === 'boolean')
  56435. {
  56436. // If they set a new loop value then use it, otherwise use the one set on creation
  56437. this.loop = loop;
  56438. }
  56439. if (typeof killOnComplete !== 'undefined')
  56440. {
  56441. // Remove the parent sprite once the animation has finished?
  56442. this.killOnComplete = killOnComplete;
  56443. }
  56444. this.isPlaying = true;
  56445. this.isFinished = false;
  56446. this.paused = false;
  56447. this.loopCount = 0;
  56448. this._timeLastFrame = this.game.time.time;
  56449. this._timeNextFrame = this.game.time.time + this.delay;
  56450. this._frameIndex = this.isReversed ? this._frames.length - 1 : 0;
  56451. this.updateCurrentFrame(false, true);
  56452. this._parent.events.onAnimationStart$dispatch(this._parent, this);
  56453. this.onStart.dispatch(this._parent, this);
  56454. this._parent.animations.currentAnim = this;
  56455. this._parent.animations.currentFrame = this.currentFrame;
  56456. return this;
  56457. },
  56458. /**
  56459. * Sets this animation back to the first frame and restarts the animation.
  56460. *
  56461. * @method Phaser.Animation#restart
  56462. */
  56463. restart: function () {
  56464. this.isPlaying = true;
  56465. this.isFinished = false;
  56466. this.paused = false;
  56467. this.loopCount = 0;
  56468. this._timeLastFrame = this.game.time.time;
  56469. this._timeNextFrame = this.game.time.time + this.delay;
  56470. this._frameIndex = 0;
  56471. this.currentFrame = this._frameData.getFrame(this._frames[this._frameIndex]);
  56472. this._parent.setFrame(this.currentFrame);
  56473. this._parent.animations.currentAnim = this;
  56474. this._parent.animations.currentFrame = this.currentFrame;
  56475. this.onStart.dispatch(this._parent, this);
  56476. },
  56477. /**
  56478. * Reverses the animation direction.
  56479. *
  56480. * @method Phaser.Animation#reverse
  56481. * @return {Phaser.Animation} The animation instance.
  56482. */
  56483. reverse: function () {
  56484. this.reversed = !this.reversed;
  56485. return this;
  56486. },
  56487. /**
  56488. * Reverses the animation direction for the current/next animation only
  56489. * Once the onComplete event is called this method will be called again and revert
  56490. * the reversed state.
  56491. *
  56492. * @method Phaser.Animation#reverseOnce
  56493. * @return {Phaser.Animation} The animation instance.
  56494. */
  56495. reverseOnce: function () {
  56496. this.onComplete.addOnce(this.reverse, this);
  56497. return this.reverse();
  56498. },
  56499. /**
  56500. * Sets this animations playback to a given frame with the given ID.
  56501. *
  56502. * @method Phaser.Animation#setFrame
  56503. * @param {string|number} [frameId] - The identifier of the frame to set. Can be the name of the frame, the sprite index of the frame, or the animation-local frame index.
  56504. * @param {boolean} [useLocalFrameIndex=false] - If you provide a number for frameId, should it use the numeric indexes of the frameData, or the 0-indexed frame index local to the animation.
  56505. */
  56506. setFrame: function(frameId, useLocalFrameIndex) {
  56507. var frameIndex;
  56508. if (useLocalFrameIndex === undefined)
  56509. {
  56510. useLocalFrameIndex = false;
  56511. }
  56512. // Find the index to the desired frame.
  56513. if (typeof frameId === "string")
  56514. {
  56515. for (var i = 0; i < this._frames.length; i++)
  56516. {
  56517. if (this._frameData.getFrame(this._frames[i]).name === frameId)
  56518. {
  56519. frameIndex = i;
  56520. }
  56521. }
  56522. }
  56523. else if (typeof frameId === "number")
  56524. {
  56525. if (useLocalFrameIndex)
  56526. {
  56527. frameIndex = frameId;
  56528. }
  56529. else
  56530. {
  56531. for (var i = 0; i < this._frames.length; i++)
  56532. {
  56533. if (this._frames[i] === frameId)
  56534. {
  56535. frameIndex = i;
  56536. }
  56537. }
  56538. }
  56539. }
  56540. if (frameIndex)
  56541. {
  56542. // Set the current frame index to the found index. Subtract 1 so that it animates to the desired frame on update.
  56543. this._frameIndex = frameIndex - 1;
  56544. // Make the animation update at next update
  56545. this._timeNextFrame = this.game.time.time;
  56546. this.update();
  56547. }
  56548. },
  56549. /**
  56550. * Stops playback of this animation and set it to a finished state. If a resetFrame is provided it will stop playback and set frame to the first in the animation.
  56551. * If `dispatchComplete` is true it will dispatch the complete events, otherwise they'll be ignored.
  56552. *
  56553. * @method Phaser.Animation#stop
  56554. * @param {boolean} [resetFrame=false] - If true after the animation stops the currentFrame value will be set to the first frame in this animation.
  56555. * @param {boolean} [dispatchComplete=false] - Dispatch the Animation.onComplete and parent.onAnimationComplete events?
  56556. */
  56557. stop: function (resetFrame, dispatchComplete) {
  56558. if (resetFrame === undefined) { resetFrame = false; }
  56559. if (dispatchComplete === undefined) { dispatchComplete = false; }
  56560. this.isPlaying = false;
  56561. this.isFinished = true;
  56562. this.paused = false;
  56563. if (resetFrame)
  56564. {
  56565. this.currentFrame = this._frameData.getFrame(this._frames[0]);
  56566. this._parent.setFrame(this.currentFrame);
  56567. }
  56568. if (dispatchComplete)
  56569. {
  56570. this._parent.events.onAnimationComplete$dispatch(this._parent, this);
  56571. this.onComplete.dispatch(this._parent, this);
  56572. }
  56573. },
  56574. /**
  56575. * Called when the Game enters a paused state.
  56576. *
  56577. * @method Phaser.Animation#onPause
  56578. */
  56579. onPause: function () {
  56580. if (this.isPlaying)
  56581. {
  56582. this._frameDiff = this._timeNextFrame - this.game.time.time;
  56583. }
  56584. },
  56585. /**
  56586. * Called when the Game resumes from a paused state.
  56587. *
  56588. * @method Phaser.Animation#onResume
  56589. */
  56590. onResume: function () {
  56591. if (this.isPlaying)
  56592. {
  56593. this._timeNextFrame = this.game.time.time + this._frameDiff;
  56594. }
  56595. },
  56596. /**
  56597. * Updates this animation. Called automatically by the AnimationManager.
  56598. *
  56599. * @method Phaser.Animation#update
  56600. */
  56601. update: function () {
  56602. if (this.isPaused)
  56603. {
  56604. return false;
  56605. }
  56606. if (this.isPlaying && this.game.time.time >= this._timeNextFrame)
  56607. {
  56608. this._frameSkip = 1;
  56609. // Lagging?
  56610. this._frameDiff = this.game.time.time - this._timeNextFrame;
  56611. this._timeLastFrame = this.game.time.time;
  56612. if (this._frameDiff > this.delay)
  56613. {
  56614. // We need to skip a frame, work out how many
  56615. this._frameSkip = Math.floor(this._frameDiff / this.delay);
  56616. this._frameDiff -= (this._frameSkip * this.delay);
  56617. }
  56618. // And what's left now?
  56619. this._timeNextFrame = this.game.time.time + (this.delay - this._frameDiff);
  56620. if (this.isReversed)
  56621. {
  56622. this._frameIndex -= this._frameSkip;
  56623. }
  56624. else
  56625. {
  56626. this._frameIndex += this._frameSkip;
  56627. }
  56628. if (!this.isReversed && this._frameIndex >= this._frames.length || this.isReversed && this._frameIndex <= -1)
  56629. {
  56630. if (this.loop)
  56631. {
  56632. // Update current state before event callback
  56633. this._frameIndex = Math.abs(this._frameIndex) % this._frames.length;
  56634. if (this.isReversed)
  56635. {
  56636. this._frameIndex = this._frames.length - 1 - this._frameIndex;
  56637. }
  56638. this.currentFrame = this._frameData.getFrame(this._frames[this._frameIndex]);
  56639. // Instead of calling updateCurrentFrame we do it here instead
  56640. if (this.currentFrame)
  56641. {
  56642. this._parent.setFrame(this.currentFrame);
  56643. }
  56644. this.loopCount++;
  56645. this._parent.events.onAnimationLoop$dispatch(this._parent, this);
  56646. this.onLoop.dispatch(this._parent, this);
  56647. if (this.onUpdate)
  56648. {
  56649. this.onUpdate.dispatch(this, this.currentFrame);
  56650. // False if the animation was destroyed from within a callback
  56651. return !!this._frameData;
  56652. }
  56653. else
  56654. {
  56655. return true;
  56656. }
  56657. }
  56658. else
  56659. {
  56660. this.complete();
  56661. return false;
  56662. }
  56663. }
  56664. else
  56665. {
  56666. return this.updateCurrentFrame(true);
  56667. }
  56668. }
  56669. return false;
  56670. },
  56671. /**
  56672. * Changes the currentFrame per the _frameIndex, updates the display state,
  56673. * and triggers the update signal.
  56674. *
  56675. * Returns true if the current frame update was 'successful', false otherwise.
  56676. *
  56677. * @method Phaser.Animation#updateCurrentFrame
  56678. * @private
  56679. * @param {boolean} signalUpdate - If true the `Animation.onUpdate` signal will be dispatched.
  56680. * @param {boolean} fromPlay - Was this call made from the playing of a new animation?
  56681. * @return {boolean} True if the current frame was updated, otherwise false.
  56682. */
  56683. updateCurrentFrame: function (signalUpdate, fromPlay) {
  56684. if (fromPlay === undefined) { fromPlay = false; }
  56685. if (!this._frameData)
  56686. {
  56687. // The animation is already destroyed, probably from a callback
  56688. return false;
  56689. }
  56690. // Previous index
  56691. var idx = this.currentFrame.index;
  56692. this.currentFrame = this._frameData.getFrame(this._frames[this._frameIndex]);
  56693. if (this.currentFrame && (fromPlay || (!fromPlay && idx !== this.currentFrame.index)))
  56694. {
  56695. this._parent.setFrame(this.currentFrame);
  56696. }
  56697. if (this.onUpdate && signalUpdate)
  56698. {
  56699. this.onUpdate.dispatch(this, this.currentFrame);
  56700. // False if the animation was destroyed from within a callback
  56701. return !!this._frameData;
  56702. }
  56703. else
  56704. {
  56705. return true;
  56706. }
  56707. },
  56708. /**
  56709. * Advances by the given number of frames in the Animation, taking the loop value into consideration.
  56710. *
  56711. * @method Phaser.Animation#next
  56712. * @param {number} [quantity=1] - The number of frames to advance.
  56713. */
  56714. next: function (quantity) {
  56715. if (quantity === undefined) { quantity = 1; }
  56716. var frame = this._frameIndex + quantity;
  56717. if (frame >= this._frames.length)
  56718. {
  56719. if (this.loop)
  56720. {
  56721. frame %= this._frames.length;
  56722. }
  56723. else
  56724. {
  56725. frame = this._frames.length - 1;
  56726. }
  56727. }
  56728. if (frame !== this._frameIndex)
  56729. {
  56730. this._frameIndex = frame;
  56731. this.updateCurrentFrame(true);
  56732. }
  56733. },
  56734. /**
  56735. * Moves backwards the given number of frames in the Animation, taking the loop value into consideration.
  56736. *
  56737. * @method Phaser.Animation#previous
  56738. * @param {number} [quantity=1] - The number of frames to move back.
  56739. */
  56740. previous: function (quantity) {
  56741. if (quantity === undefined) { quantity = 1; }
  56742. var frame = this._frameIndex - quantity;
  56743. if (frame < 0)
  56744. {
  56745. if (this.loop)
  56746. {
  56747. frame = this._frames.length + frame;
  56748. }
  56749. else
  56750. {
  56751. frame++;
  56752. }
  56753. }
  56754. if (frame !== this._frameIndex)
  56755. {
  56756. this._frameIndex = frame;
  56757. this.updateCurrentFrame(true);
  56758. }
  56759. },
  56760. /**
  56761. * Changes the FrameData object this Animation is using.
  56762. *
  56763. * @method Phaser.Animation#updateFrameData
  56764. * @param {Phaser.FrameData} frameData - The FrameData object that contains all frames used by this Animation.
  56765. */
  56766. updateFrameData: function (frameData) {
  56767. this._frameData = frameData;
  56768. this.currentFrame = this._frameData ? this._frameData.getFrame(this._frames[this._frameIndex % this._frames.length]) : null;
  56769. },
  56770. /**
  56771. * Cleans up this animation ready for deletion. Nulls all values and references.
  56772. *
  56773. * @method Phaser.Animation#destroy
  56774. */
  56775. destroy: function () {
  56776. if (!this._frameData)
  56777. {
  56778. // Already destroyed
  56779. return;
  56780. }
  56781. this.game.onPause.remove(this.onPause, this);
  56782. this.game.onResume.remove(this.onResume, this);
  56783. this.game = null;
  56784. this._parent = null;
  56785. this._frames = null;
  56786. this._frameData = null;
  56787. this.currentFrame = null;
  56788. this.isPlaying = false;
  56789. this.onStart.dispose();
  56790. this.onLoop.dispose();
  56791. this.onComplete.dispose();
  56792. if (this.onUpdate)
  56793. {
  56794. this.onUpdate.dispose();
  56795. }
  56796. },
  56797. /**
  56798. * Called internally when the animation finishes playback.
  56799. * Sets the isPlaying and isFinished states and dispatches the onAnimationComplete event if it exists on the parent and local onComplete event.
  56800. *
  56801. * @method Phaser.Animation#complete
  56802. */
  56803. complete: function () {
  56804. this._frameIndex = this._frames.length - 1;
  56805. this.currentFrame = this._frameData.getFrame(this._frames[this._frameIndex]);
  56806. this.isPlaying = false;
  56807. this.isFinished = true;
  56808. this.paused = false;
  56809. this._parent.events.onAnimationComplete$dispatch(this._parent, this);
  56810. this.onComplete.dispatch(this._parent, this);
  56811. if (this.killOnComplete)
  56812. {
  56813. this._parent.kill();
  56814. }
  56815. }
  56816. };
  56817. Phaser.Animation.prototype.constructor = Phaser.Animation;
  56818. /**
  56819. * @name Phaser.Animation#paused
  56820. * @property {boolean} paused - Gets and sets the paused state of this Animation.
  56821. */
  56822. Object.defineProperty(Phaser.Animation.prototype, 'paused', {
  56823. get: function () {
  56824. return this.isPaused;
  56825. },
  56826. set: function (value) {
  56827. this.isPaused = value;
  56828. if (value)
  56829. {
  56830. // Paused
  56831. this._pauseStartTime = this.game.time.time;
  56832. }
  56833. else
  56834. {
  56835. // Un-paused
  56836. if (this.isPlaying)
  56837. {
  56838. this._timeNextFrame = this.game.time.time + this.delay;
  56839. }
  56840. }
  56841. }
  56842. });
  56843. /**
  56844. * @name Phaser.Animation#reversed
  56845. * @property {boolean} reversed - Gets and sets the isReversed state of this Animation.
  56846. */
  56847. Object.defineProperty(Phaser.Animation.prototype, 'reversed', {
  56848. get: function () {
  56849. return this.isReversed;
  56850. },
  56851. set: function (value) {
  56852. this.isReversed = value;
  56853. }
  56854. });
  56855. /**
  56856. * @name Phaser.Animation#frameTotal
  56857. * @property {number} frameTotal - The total number of frames in the currently loaded FrameData, or -1 if no FrameData is loaded.
  56858. * @readonly
  56859. */
  56860. Object.defineProperty(Phaser.Animation.prototype, 'frameTotal', {
  56861. get: function () {
  56862. return this._frames.length;
  56863. }
  56864. });
  56865. /**
  56866. * @name Phaser.Animation#frame
  56867. * @property {number} frame - Gets or sets the current frame index and updates the Texture Cache for display.
  56868. */
  56869. Object.defineProperty(Phaser.Animation.prototype, 'frame', {
  56870. get: function () {
  56871. if (this.currentFrame !== null)
  56872. {
  56873. return this.currentFrame.index;
  56874. }
  56875. else
  56876. {
  56877. return this._frameIndex;
  56878. }
  56879. },
  56880. set: function (value) {
  56881. this.currentFrame = this._frameData.getFrame(this._frames[value]);
  56882. if (this.currentFrame !== null)
  56883. {
  56884. this._frameIndex = value;
  56885. this._parent.setFrame(this.currentFrame);
  56886. if (this.onUpdate)
  56887. {
  56888. this.onUpdate.dispatch(this, this.currentFrame);
  56889. }
  56890. }
  56891. }
  56892. });
  56893. /**
  56894. * @name Phaser.Animation#speed
  56895. * @property {number} speed - Gets or sets the current speed of the animation in frames per second. Changing this in a playing animation will take effect from the next frame. Value must be greater than 0.
  56896. */
  56897. Object.defineProperty(Phaser.Animation.prototype, 'speed', {
  56898. get: function () {
  56899. return 1000 / this.delay;
  56900. },
  56901. set: function (value) {
  56902. if (value > 0)
  56903. {
  56904. this.delay = 1000 / value;
  56905. }
  56906. }
  56907. });
  56908. /**
  56909. * @name Phaser.Animation#enableUpdate
  56910. * @property {boolean} enableUpdate - Gets or sets if this animation will dispatch the onUpdate events upon changing frame.
  56911. */
  56912. Object.defineProperty(Phaser.Animation.prototype, 'enableUpdate', {
  56913. get: function () {
  56914. return (this.onUpdate !== null);
  56915. },
  56916. set: function (value) {
  56917. if (value && this.onUpdate === null)
  56918. {
  56919. this.onUpdate = new Phaser.Signal();
  56920. }
  56921. else if (!value && this.onUpdate !== null)
  56922. {
  56923. this.onUpdate.dispose();
  56924. this.onUpdate = null;
  56925. }
  56926. }
  56927. });
  56928. /**
  56929. * Really handy function for when you are creating arrays of animation data but it's using frame names and not numbers.
  56930. * For example imagine you've got 30 frames named: 'explosion_0001-large' to 'explosion_0030-large'
  56931. * You could use this function to generate those by doing: Phaser.Animation.generateFrameNames('explosion_', 1, 30, '-large', 4);
  56932. *
  56933. * @method Phaser.Animation.generateFrameNames
  56934. * @static
  56935. * @param {string} prefix - The start of the filename. If the filename was 'explosion_0001-large' the prefix would be 'explosion_'.
  56936. * @param {number} start - The number to start sequentially counting from. If your frames are named 'explosion_0001' to 'explosion_0034' the start is 1.
  56937. * @param {number} stop - The number to count to. If your frames are named 'explosion_0001' to 'explosion_0034' the stop value is 34.
  56938. * @param {string} [suffix=''] - The end of the filename. If the filename was 'explosion_0001-large' the prefix would be '-large'.
  56939. * @param {number} [zeroPad=0] - The number of zeros to pad the min and max values with. If your frames are named 'explosion_0001' to 'explosion_0034' then the zeroPad is 4.
  56940. * @return {string[]} An array of framenames.
  56941. */
  56942. Phaser.Animation.generateFrameNames = function (prefix, start, stop, suffix, zeroPad) {
  56943. if (suffix === undefined) { suffix = ''; }
  56944. var output = [];
  56945. var frame = '';
  56946. if (start < stop)
  56947. {
  56948. for (var i = start; i <= stop; i++)
  56949. {
  56950. if (typeof zeroPad === 'number')
  56951. {
  56952. // str, len, pad, dir
  56953. frame = Phaser.Utils.pad(i.toString(), zeroPad, '0', 1);
  56954. }
  56955. else
  56956. {
  56957. frame = i.toString();
  56958. }
  56959. frame = prefix + frame + suffix;
  56960. output.push(frame);
  56961. }
  56962. }
  56963. else
  56964. {
  56965. for (var i = start; i >= stop; i--)
  56966. {
  56967. if (typeof zeroPad === 'number')
  56968. {
  56969. // str, len, pad, dir
  56970. frame = Phaser.Utils.pad(i.toString(), zeroPad, '0', 1);
  56971. }
  56972. else
  56973. {
  56974. frame = i.toString();
  56975. }
  56976. frame = prefix + frame + suffix;
  56977. output.push(frame);
  56978. }
  56979. }
  56980. return output;
  56981. };
  56982. /**
  56983. * @author Richard Davey <rich@photonstorm.com>
  56984. * @copyright 2016 Photon Storm Ltd.
  56985. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  56986. */
  56987. /**
  56988. * A Frame is a single frame of an animation and is part of a FrameData collection.
  56989. *
  56990. * @class Phaser.Frame
  56991. * @constructor
  56992. * @param {number} index - The index of this Frame within the FrameData set it is being added to.
  56993. * @param {number} x - X position of the frame within the texture image.
  56994. * @param {number} y - Y position of the frame within the texture image.
  56995. * @param {number} width - Width of the frame within the texture image.
  56996. * @param {number} height - Height of the frame within the texture image.
  56997. * @param {string} name - The name of the frame. In Texture Atlas data this is usually set to the filename.
  56998. */
  56999. Phaser.Frame = function (index, x, y, width, height, name) {
  57000. /**
  57001. * @property {number} index - The index of this Frame within the FrameData set it is being added to.
  57002. */
  57003. this.index = index;
  57004. /**
  57005. * @property {number} x - X position within the image to cut from.
  57006. */
  57007. this.x = x;
  57008. /**
  57009. * @property {number} y - Y position within the image to cut from.
  57010. */
  57011. this.y = y;
  57012. /**
  57013. * @property {number} width - Width of the frame.
  57014. */
  57015. this.width = width;
  57016. /**
  57017. * @property {number} height - Height of the frame.
  57018. */
  57019. this.height = height;
  57020. /**
  57021. * @property {string} name - Useful for Texture Atlas files (is set to the filename value).
  57022. */
  57023. this.name = name;
  57024. /**
  57025. * @property {number} centerX - Center X position within the image to cut from.
  57026. */
  57027. this.centerX = Math.floor(width / 2);
  57028. /**
  57029. * @property {number} centerY - Center Y position within the image to cut from.
  57030. */
  57031. this.centerY = Math.floor(height / 2);
  57032. /**
  57033. * @property {number} distance - The distance from the top left to the bottom-right of this Frame.
  57034. */
  57035. this.distance = Phaser.Math.distance(0, 0, width, height);
  57036. /**
  57037. * @property {boolean} rotated - Rotated? (not yet implemented)
  57038. * @default
  57039. */
  57040. this.rotated = false;
  57041. /**
  57042. * @property {string} rotationDirection - Either 'cw' or 'ccw', rotation is always 90 degrees.
  57043. * @default 'cw'
  57044. */
  57045. this.rotationDirection = 'cw';
  57046. /**
  57047. * @property {boolean} trimmed - Was it trimmed when packed?
  57048. * @default
  57049. */
  57050. this.trimmed = false;
  57051. /**
  57052. * @property {number} sourceSizeW - Width of the original sprite before it was trimmed.
  57053. */
  57054. this.sourceSizeW = width;
  57055. /**
  57056. * @property {number} sourceSizeH - Height of the original sprite before it was trimmed.
  57057. */
  57058. this.sourceSizeH = height;
  57059. /**
  57060. * @property {number} spriteSourceSizeX - X position of the trimmed sprite inside original sprite.
  57061. * @default
  57062. */
  57063. this.spriteSourceSizeX = 0;
  57064. /**
  57065. * @property {number} spriteSourceSizeY - Y position of the trimmed sprite inside original sprite.
  57066. * @default
  57067. */
  57068. this.spriteSourceSizeY = 0;
  57069. /**
  57070. * @property {number} spriteSourceSizeW - Width of the trimmed sprite.
  57071. * @default
  57072. */
  57073. this.spriteSourceSizeW = 0;
  57074. /**
  57075. * @property {number} spriteSourceSizeH - Height of the trimmed sprite.
  57076. * @default
  57077. */
  57078. this.spriteSourceSizeH = 0;
  57079. /**
  57080. * @property {number} right - The right of the Frame (x + width).
  57081. */
  57082. this.right = this.x + this.width;
  57083. /**
  57084. * @property {number} bottom - The bottom of the frame (y + height).
  57085. */
  57086. this.bottom = this.y + this.height;
  57087. };
  57088. Phaser.Frame.prototype = {
  57089. /**
  57090. * Adjusts of all the Frame properties based on the given width and height values.
  57091. *
  57092. * @method Phaser.Frame#resize
  57093. * @param {integer} width - The new width of the Frame.
  57094. * @param {integer} height - The new height of the Frame.
  57095. */
  57096. resize: function (width, height) {
  57097. this.width = width;
  57098. this.height = height;
  57099. this.centerX = Math.floor(width / 2);
  57100. this.centerY = Math.floor(height / 2);
  57101. this.distance = Phaser.Math.distance(0, 0, width, height);
  57102. this.sourceSizeW = width;
  57103. this.sourceSizeH = height;
  57104. this.right = this.x + width;
  57105. this.bottom = this.y + height;
  57106. },
  57107. /**
  57108. * If the frame was trimmed when added to the Texture Atlas this records the trim and source data.
  57109. *
  57110. * @method Phaser.Frame#setTrim
  57111. * @param {boolean} trimmed - If this frame was trimmed or not.
  57112. * @param {number} actualWidth - The width of the frame before being trimmed.
  57113. * @param {number} actualHeight - The height of the frame before being trimmed.
  57114. * @param {number} destX - The destination X position of the trimmed frame for display.
  57115. * @param {number} destY - The destination Y position of the trimmed frame for display.
  57116. * @param {number} destWidth - The destination width of the trimmed frame for display.
  57117. * @param {number} destHeight - The destination height of the trimmed frame for display.
  57118. */
  57119. setTrim: function (trimmed, actualWidth, actualHeight, destX, destY, destWidth, destHeight) {
  57120. this.trimmed = trimmed;
  57121. if (trimmed)
  57122. {
  57123. this.sourceSizeW = actualWidth;
  57124. this.sourceSizeH = actualHeight;
  57125. this.centerX = Math.floor(actualWidth / 2);
  57126. this.centerY = Math.floor(actualHeight / 2);
  57127. this.spriteSourceSizeX = destX;
  57128. this.spriteSourceSizeY = destY;
  57129. this.spriteSourceSizeW = destWidth;
  57130. this.spriteSourceSizeH = destHeight;
  57131. }
  57132. },
  57133. /**
  57134. * Clones this Frame into a new Phaser.Frame object and returns it.
  57135. * Note that all properties are cloned, including the name, index and UUID.
  57136. *
  57137. * @method Phaser.Frame#clone
  57138. * @return {Phaser.Frame} An exact copy of this Frame object.
  57139. */
  57140. clone: function () {
  57141. var output = new Phaser.Frame(this.index, this.x, this.y, this.width, this.height, this.name);
  57142. for (var prop in this)
  57143. {
  57144. if (this.hasOwnProperty(prop))
  57145. {
  57146. output[prop] = this[prop];
  57147. }
  57148. }
  57149. return output;
  57150. },
  57151. /**
  57152. * Returns a Rectangle set to the dimensions of this Frame.
  57153. *
  57154. * @method Phaser.Frame#getRect
  57155. * @param {Phaser.Rectangle} [out] - A rectangle to copy the frame dimensions to.
  57156. * @return {Phaser.Rectangle} A rectangle.
  57157. */
  57158. getRect: function (out) {
  57159. if (out === undefined)
  57160. {
  57161. out = new Phaser.Rectangle(this.x, this.y, this.width, this.height);
  57162. }
  57163. else
  57164. {
  57165. out.setTo(this.x, this.y, this.width, this.height);
  57166. }
  57167. return out;
  57168. }
  57169. };
  57170. Phaser.Frame.prototype.constructor = Phaser.Frame;
  57171. /**
  57172. * @author Richard Davey <rich@photonstorm.com>
  57173. * @copyright 2016 Photon Storm Ltd.
  57174. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  57175. */
  57176. /**
  57177. * FrameData is a container for Frame objects, which are the internal representation of animation data in Phaser.
  57178. *
  57179. * @class Phaser.FrameData
  57180. * @constructor
  57181. */
  57182. Phaser.FrameData = function () {
  57183. /**
  57184. * @property {Array} _frames - Local array of frames.
  57185. * @private
  57186. */
  57187. this._frames = [];
  57188. /**
  57189. * @property {Array} _frameNames - Local array of frame names for name to index conversions.
  57190. * @private
  57191. */
  57192. this._frameNames = [];
  57193. };
  57194. Phaser.FrameData.prototype = {
  57195. /**
  57196. * Adds a new Frame to this FrameData collection. Typically called by the Animation.Parser and not directly.
  57197. *
  57198. * @method Phaser.FrameData#addFrame
  57199. * @param {Phaser.Frame} frame - The frame to add to this FrameData set.
  57200. * @return {Phaser.Frame} The frame that was just added.
  57201. */
  57202. addFrame: function (frame) {
  57203. frame.index = this._frames.length;
  57204. this._frames.push(frame);
  57205. if (frame.name !== '')
  57206. {
  57207. this._frameNames[frame.name] = frame.index;
  57208. }
  57209. return frame;
  57210. },
  57211. /**
  57212. * Get a Frame by its numerical index.
  57213. *
  57214. * @method Phaser.FrameData#getFrame
  57215. * @param {number} index - The index of the frame you want to get.
  57216. * @return {Phaser.Frame} The frame, if found.
  57217. */
  57218. getFrame: function (index) {
  57219. if (index >= this._frames.length)
  57220. {
  57221. index = 0;
  57222. }
  57223. return this._frames[index];
  57224. },
  57225. /**
  57226. * Get a Frame by its frame name.
  57227. *
  57228. * @method Phaser.FrameData#getFrameByName
  57229. * @param {string} name - The name of the frame you want to get.
  57230. * @return {Phaser.Frame} The frame, if found.
  57231. */
  57232. getFrameByName: function (name) {
  57233. if (typeof this._frameNames[name] === 'number')
  57234. {
  57235. return this._frames[this._frameNames[name]];
  57236. }
  57237. return null;
  57238. },
  57239. /**
  57240. * Check if there is a Frame with the given name.
  57241. *
  57242. * @method Phaser.FrameData#checkFrameName
  57243. * @param {string} name - The name of the frame you want to check.
  57244. * @return {boolean} True if the frame is found, otherwise false.
  57245. */
  57246. checkFrameName: function (name) {
  57247. if (this._frameNames[name] == null)
  57248. {
  57249. return false;
  57250. }
  57251. return true;
  57252. },
  57253. /**
  57254. * Makes a copy of this FrameData including copies (not references) to all of the Frames it contains.
  57255. *
  57256. * @method Phaser.FrameData#clone
  57257. * @return {Phaser.FrameData} A clone of this object, including clones of the Frame objects it contains.
  57258. */
  57259. clone: function () {
  57260. var output = new Phaser.FrameData();
  57261. // No input array, so we loop through all frames
  57262. for (var i = 0; i < this._frames.length; i++)
  57263. {
  57264. output._frames.push(this._frames[i].clone());
  57265. }
  57266. for (var p in this._frameNames)
  57267. {
  57268. if (this._frameNames.hasOwnProperty(p))
  57269. {
  57270. output._frameNames.push(this._frameNames[p]);
  57271. }
  57272. }
  57273. return output;
  57274. },
  57275. /**
  57276. * Returns a range of frames based on the given start and end frame indexes and returns them in an Array.
  57277. *
  57278. * @method Phaser.FrameData#getFrameRange
  57279. * @param {number} start - The starting frame index.
  57280. * @param {number} end - The ending frame index.
  57281. * @param {Array} [output] - If given the results will be appended to the end of this array otherwise a new array will be created.
  57282. * @return {Array} An array of Frames between the start and end index values, or an empty array if none were found.
  57283. */
  57284. getFrameRange: function (start, end, output) {
  57285. if (output === undefined) { output = []; }
  57286. for (var i = start; i <= end; i++)
  57287. {
  57288. output.push(this._frames[i]);
  57289. }
  57290. return output;
  57291. },
  57292. /**
  57293. * Returns all of the Frames in this FrameData set where the frame index is found in the input array.
  57294. * The frames are returned in the output array, or if none is provided in a new Array object.
  57295. *
  57296. * @method Phaser.FrameData#getFrames
  57297. * @param {Array} [frames] - An Array containing the indexes of the frames to retrieve. If the array is empty or undefined then all frames in the FrameData are returned.
  57298. * @param {boolean} [useNumericIndex=true] - Are the given frames using numeric indexes (default) or strings? (false)
  57299. * @param {Array} [output] - If given the results will be appended to the end of this array otherwise a new array will be created.
  57300. * @return {Array} An array of all Frames in this FrameData set matching the given names or IDs.
  57301. */
  57302. getFrames: function (frames, useNumericIndex, output) {
  57303. if (useNumericIndex === undefined) { useNumericIndex = true; }
  57304. if (output === undefined) { output = []; }
  57305. if (frames === undefined || frames.length === 0)
  57306. {
  57307. // No input array, so we loop through all frames
  57308. for (var i = 0; i < this._frames.length; i++)
  57309. {
  57310. // We only need the indexes
  57311. output.push(this._frames[i]);
  57312. }
  57313. }
  57314. else
  57315. {
  57316. // Input array given, loop through that instead
  57317. for (var i = 0; i < frames.length; i++)
  57318. {
  57319. // Does the input array contain names or indexes?
  57320. if (useNumericIndex)
  57321. {
  57322. // The actual frame
  57323. output.push(this.getFrame(frames[i]));
  57324. }
  57325. else
  57326. {
  57327. // The actual frame
  57328. output.push(this.getFrameByName(frames[i]));
  57329. }
  57330. }
  57331. }
  57332. return output;
  57333. },
  57334. /**
  57335. * Returns all of the Frame indexes in this FrameData set.
  57336. * The frames indexes are returned in the output array, or if none is provided in a new Array object.
  57337. *
  57338. * @method Phaser.FrameData#getFrameIndexes
  57339. * @param {Array} [frames] - An Array containing the indexes of the frames to retrieve. If undefined or the array is empty then all frames in the FrameData are returned.
  57340. * @param {boolean} [useNumericIndex=true] - Are the given frames using numeric indexes (default) or strings? (false)
  57341. * @param {Array} [output] - If given the results will be appended to the end of this array otherwise a new array will be created.
  57342. * @return {Array} An array of all Frame indexes matching the given names or IDs.
  57343. */
  57344. getFrameIndexes: function (frames, useNumericIndex, output) {
  57345. if (useNumericIndex === undefined) { useNumericIndex = true; }
  57346. if (output === undefined) { output = []; }
  57347. if (frames === undefined || frames.length === 0)
  57348. {
  57349. // No frames array, so we loop through all frames
  57350. for (var i = 0; i < this._frames.length; i++)
  57351. {
  57352. output.push(this._frames[i].index);
  57353. }
  57354. }
  57355. else
  57356. {
  57357. // Input array given, loop through that instead
  57358. for (var i = 0; i < frames.length; i++)
  57359. {
  57360. // Does the frames array contain names or indexes?
  57361. if (useNumericIndex && this._frames[frames[i]])
  57362. {
  57363. output.push(this._frames[frames[i]].index);
  57364. }
  57365. else
  57366. {
  57367. if (this.getFrameByName(frames[i]))
  57368. {
  57369. output.push(this.getFrameByName(frames[i]).index);
  57370. }
  57371. }
  57372. }
  57373. }
  57374. return output;
  57375. },
  57376. /**
  57377. * Destroys this FrameData collection by nulling the _frames and _frameNames arrays.
  57378. *
  57379. * @method Phaser.FrameData#destroy
  57380. */
  57381. destroy: function () {
  57382. this._frames = null;
  57383. this._frameNames = null;
  57384. }
  57385. };
  57386. Phaser.FrameData.prototype.constructor = Phaser.FrameData;
  57387. /**
  57388. * @name Phaser.FrameData#total
  57389. * @property {number} total - The total number of frames in this FrameData set.
  57390. * @readonly
  57391. */
  57392. Object.defineProperty(Phaser.FrameData.prototype, "total", {
  57393. get: function () {
  57394. return this._frames.length;
  57395. }
  57396. });
  57397. /**
  57398. * @author Richard Davey <rich@photonstorm.com>
  57399. * @copyright 2016 Photon Storm Ltd.
  57400. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  57401. */
  57402. /**
  57403. * Responsible for parsing sprite sheet and JSON data into the internal FrameData format that Phaser uses for animations.
  57404. *
  57405. * @class Phaser.AnimationParser
  57406. * @static
  57407. */
  57408. Phaser.AnimationParser = {
  57409. /**
  57410. * Parse a Sprite Sheet and extract the animation frame data from it.
  57411. *
  57412. * @method Phaser.AnimationParser.spriteSheet
  57413. * @param {Phaser.Game} game - A reference to the currently running game.
  57414. * @param {string|Image} key - The Game.Cache asset key of the Sprite Sheet image or an actual HTML Image element.
  57415. * @param {number} frameWidth - The fixed width of each frame of the animation.
  57416. * @param {number} frameHeight - The fixed height of each frame of the animation.
  57417. * @param {number} [frameMax=-1] - The total number of animation frames to extract from the Sprite Sheet. The default value of -1 means "extract all frames".
  57418. * @param {number} [margin=0] - If the frames have been drawn with a margin, specify the amount here.
  57419. * @param {number} [spacing=0] - If the frames have been drawn with spacing between them, specify the amount here.
  57420. * @return {Phaser.FrameData} A FrameData object containing the parsed frames.
  57421. */
  57422. spriteSheet: function (game, key, frameWidth, frameHeight, frameMax, margin, spacing) {
  57423. var img = key;
  57424. if (typeof key === 'string')
  57425. {
  57426. img = game.cache.getImage(key);
  57427. }
  57428. if (img === null)
  57429. {
  57430. return null;
  57431. }
  57432. var width = img.width;
  57433. var height = img.height;
  57434. if (frameWidth <= 0)
  57435. {
  57436. frameWidth = Math.floor(-width / Math.min(-1, frameWidth));
  57437. }
  57438. if (frameHeight <= 0)
  57439. {
  57440. frameHeight = Math.floor(-height / Math.min(-1, frameHeight));
  57441. }
  57442. var row = Math.floor((width - margin) / (frameWidth + spacing));
  57443. var column = Math.floor((height - margin) / (frameHeight + spacing));
  57444. var total = row * column;
  57445. if (frameMax !== -1)
  57446. {
  57447. total = frameMax;
  57448. }
  57449. // Zero or smaller than frame sizes?
  57450. if (width === 0 || height === 0 || width < frameWidth || height < frameHeight || total === 0)
  57451. {
  57452. console.warn("Phaser.AnimationParser.spriteSheet: '" + key + "'s width/height zero or width/height < given frameWidth/frameHeight");
  57453. return null;
  57454. }
  57455. // Let's create some frames then
  57456. var data = new Phaser.FrameData();
  57457. var x = margin;
  57458. var y = margin;
  57459. for (var i = 0; i < total; i++)
  57460. {
  57461. data.addFrame(new Phaser.Frame(i, x, y, frameWidth, frameHeight, ''));
  57462. x += frameWidth + spacing;
  57463. if (x + frameWidth > width)
  57464. {
  57465. x = margin;
  57466. y += frameHeight + spacing;
  57467. }
  57468. }
  57469. return data;
  57470. },
  57471. /**
  57472. * Parse the JSON data and extract the animation frame data from it.
  57473. *
  57474. * @method Phaser.AnimationParser.JSONData
  57475. * @param {Phaser.Game} game - A reference to the currently running game.
  57476. * @param {object} json - The JSON data from the Texture Atlas. Must be in Array format.
  57477. * @return {Phaser.FrameData} A FrameData object containing the parsed frames.
  57478. */
  57479. JSONData: function (game, json) {
  57480. // Malformed?
  57481. if (!json['frames'])
  57482. {
  57483. console.warn("Phaser.AnimationParser.JSONData: Invalid Texture Atlas JSON given, missing 'frames' array");
  57484. console.log(json);
  57485. return;
  57486. }
  57487. // Let's create some frames then
  57488. var data = new Phaser.FrameData();
  57489. // By this stage frames is a fully parsed array
  57490. var frames = json['frames'];
  57491. var newFrame;
  57492. for (var i = 0; i < frames.length; i++)
  57493. {
  57494. newFrame = data.addFrame(new Phaser.Frame(
  57495. i,
  57496. frames[i].frame.x,
  57497. frames[i].frame.y,
  57498. frames[i].frame.w,
  57499. frames[i].frame.h,
  57500. frames[i].filename
  57501. ));
  57502. if (frames[i].trimmed)
  57503. {
  57504. newFrame.setTrim(
  57505. frames[i].trimmed,
  57506. frames[i].sourceSize.w,
  57507. frames[i].sourceSize.h,
  57508. frames[i].spriteSourceSize.x,
  57509. frames[i].spriteSourceSize.y,
  57510. frames[i].spriteSourceSize.w,
  57511. frames[i].spriteSourceSize.h
  57512. );
  57513. }
  57514. }
  57515. return data;
  57516. },
  57517. /**
  57518. * Parse the JSON data and extract the animation frame data from it.
  57519. *
  57520. * @method Phaser.AnimationParser.JSONDataPyxel
  57521. * @param {Phaser.Game} game - A reference to the currently running game.
  57522. * @param {object} json - The JSON data from the Texture Atlas. Must be in Pyxel JSON format.
  57523. * @return {Phaser.FrameData} A FrameData object containing the parsed frames.
  57524. */
  57525. JSONDataPyxel: function (game, json) {
  57526. // Malformed? There are a few keys to check here.
  57527. var signature = ['layers', 'tilewidth','tileheight','tileswide', 'tileshigh'];
  57528. signature.forEach( function(key) {
  57529. if (!json[key])
  57530. {
  57531. console.warn('Phaser.AnimationParser.JSONDataPyxel: Invalid Pyxel Tilemap JSON given, missing "' + key + '" key.');
  57532. console.log(json);
  57533. return;
  57534. }
  57535. });
  57536. // For this purpose, I only care about parsing tilemaps with a single layer.
  57537. if (json['layers'].length !== 1)
  57538. {
  57539. console.warn('Phaser.AnimationParser.JSONDataPyxel: Too many layers, this parser only supports flat Tilemaps.');
  57540. console.log(json);
  57541. return;
  57542. }
  57543. var data = new Phaser.FrameData();
  57544. var tileheight = json['tileheight'];
  57545. var tilewidth = json['tilewidth'];
  57546. var frames = json['layers'][0]['tiles'];
  57547. var newFrame;
  57548. for (var i = 0; i < frames.length; i++)
  57549. {
  57550. newFrame = data.addFrame(new Phaser.Frame(
  57551. i,
  57552. frames[i].x,
  57553. frames[i].y,
  57554. tilewidth,
  57555. tileheight,
  57556. "frame_" + i // No names are included in pyxel tilemap data.
  57557. ));
  57558. // No trim data is included.
  57559. newFrame.setTrim(false);
  57560. }
  57561. return data;
  57562. },
  57563. /**
  57564. * Parse the JSON data and extract the animation frame data from it.
  57565. *
  57566. * @method Phaser.AnimationParser.JSONDataHash
  57567. * @param {Phaser.Game} game - A reference to the currently running game.
  57568. * @param {object} json - The JSON data from the Texture Atlas. Must be in JSON Hash format.
  57569. * @return {Phaser.FrameData} A FrameData object containing the parsed frames.
  57570. */
  57571. JSONDataHash: function (game, json) {
  57572. // Malformed?
  57573. if (!json['frames'])
  57574. {
  57575. console.warn("Phaser.AnimationParser.JSONDataHash: Invalid Texture Atlas JSON given, missing 'frames' object");
  57576. console.log(json);
  57577. return;
  57578. }
  57579. // Let's create some frames then
  57580. var data = new Phaser.FrameData();
  57581. // By this stage frames is a fully parsed array
  57582. var frames = json['frames'];
  57583. var newFrame;
  57584. var i = 0;
  57585. for (var key in frames)
  57586. {
  57587. newFrame = data.addFrame(new Phaser.Frame(
  57588. i,
  57589. frames[key].frame.x,
  57590. frames[key].frame.y,
  57591. frames[key].frame.w,
  57592. frames[key].frame.h,
  57593. key
  57594. ));
  57595. if (frames[key].trimmed)
  57596. {
  57597. newFrame.setTrim(
  57598. frames[key].trimmed,
  57599. frames[key].sourceSize.w,
  57600. frames[key].sourceSize.h,
  57601. frames[key].spriteSourceSize.x,
  57602. frames[key].spriteSourceSize.y,
  57603. frames[key].spriteSourceSize.w,
  57604. frames[key].spriteSourceSize.h
  57605. );
  57606. }
  57607. i++;
  57608. }
  57609. return data;
  57610. },
  57611. /**
  57612. * Parse the XML data and extract the animation frame data from it.
  57613. *
  57614. * @method Phaser.AnimationParser.XMLData
  57615. * @param {Phaser.Game} game - A reference to the currently running game.
  57616. * @param {object} xml - The XML data from the Texture Atlas. Must be in Starling XML format.
  57617. * @return {Phaser.FrameData} A FrameData object containing the parsed frames.
  57618. */
  57619. XMLData: function (game, xml) {
  57620. // Malformed?
  57621. if (!xml.getElementsByTagName('TextureAtlas'))
  57622. {
  57623. console.warn("Phaser.AnimationParser.XMLData: Invalid Texture Atlas XML given, missing <TextureAtlas> tag");
  57624. return;
  57625. }
  57626. // Let's create some frames then
  57627. var data = new Phaser.FrameData();
  57628. var frames = xml.getElementsByTagName('SubTexture');
  57629. var newFrame;
  57630. var name;
  57631. var frame;
  57632. var x;
  57633. var y;
  57634. var width;
  57635. var height;
  57636. var frameX;
  57637. var frameY;
  57638. var frameWidth;
  57639. var frameHeight;
  57640. for (var i = 0; i < frames.length; i++)
  57641. {
  57642. frame = frames[i].attributes;
  57643. name = frame.name.value;
  57644. x = parseInt(frame.x.value, 10);
  57645. y = parseInt(frame.y.value, 10);
  57646. width = parseInt(frame.width.value, 10);
  57647. height = parseInt(frame.height.value, 10);
  57648. frameX = null;
  57649. frameY = null;
  57650. if (frame.frameX)
  57651. {
  57652. frameX = Math.abs(parseInt(frame.frameX.value, 10));
  57653. frameY = Math.abs(parseInt(frame.frameY.value, 10));
  57654. frameWidth = parseInt(frame.frameWidth.value, 10);
  57655. frameHeight = parseInt(frame.frameHeight.value, 10);
  57656. }
  57657. newFrame = data.addFrame(new Phaser.Frame(i, x, y, width, height, name));
  57658. // Trimmed?
  57659. if (frameX !== null || frameY !== null)
  57660. {
  57661. newFrame.setTrim(true, width, height, frameX, frameY, frameWidth, frameHeight);
  57662. }
  57663. }
  57664. return data;
  57665. }
  57666. };
  57667. /**
  57668. * @author Richard Davey <rich@photonstorm.com>
  57669. * @copyright 2016 Photon Storm Ltd.
  57670. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  57671. */
  57672. /**
  57673. * Phaser has one single cache in which it stores all assets.
  57674. *
  57675. * The cache is split up into sections, such as images, sounds, video, json, etc. All assets are stored using
  57676. * a unique string-based key as their identifier. Assets stored in different areas of the cache can have the
  57677. * same key, for example 'playerWalking' could be used as the key for both a sprite sheet and an audio file,
  57678. * because they are unique data types.
  57679. *
  57680. * The cache is automatically populated by the Phaser.Loader. When you use the loader to pull in external assets
  57681. * such as images they are automatically placed into their respective cache. Most common Game Objects, such as
  57682. * Sprites and Videos automatically query the cache to extract the assets they need on instantiation.
  57683. *
  57684. * You can access the cache from within a State via `this.cache`. From here you can call any public method it has,
  57685. * including adding new entries to it, deleting them or querying them.
  57686. *
  57687. * Understand that almost without exception when you get an item from the cache it will return a reference to the
  57688. * item stored in the cache, not a copy of it. Therefore if you retrieve an item and then modify it, the original
  57689. * object in the cache will also be updated, even if you don't put it back into the cache again.
  57690. *
  57691. * By default when you change State the cache is _not_ cleared, although there is an option to clear it should
  57692. * your game require it. In a typical game set-up the cache is populated once after the main game has loaded and
  57693. * then used as an asset store.
  57694. *
  57695. * @class Phaser.Cache
  57696. * @constructor
  57697. * @param {Phaser.Game} game - A reference to the currently running game.
  57698. */
  57699. Phaser.Cache = function (game) {
  57700. /**
  57701. * @property {Phaser.Game} game - Local reference to game.
  57702. */
  57703. this.game = game;
  57704. /**
  57705. * Automatically resolve resource URLs to absolute paths for use with the Cache.getURL method.
  57706. * @property {boolean} autoResolveURL
  57707. */
  57708. this.autoResolveURL = false;
  57709. /**
  57710. * The main cache object into which all resources are placed.
  57711. * @property {object} _cache
  57712. * @private
  57713. */
  57714. this._cache = {
  57715. canvas: {},
  57716. image: {},
  57717. texture: {},
  57718. sound: {},
  57719. video: {},
  57720. text: {},
  57721. json: {},
  57722. xml: {},
  57723. physics: {},
  57724. tilemap: {},
  57725. binary: {},
  57726. bitmapData: {},
  57727. bitmapFont: {},
  57728. shader: {},
  57729. renderTexture: {}
  57730. };
  57731. /**
  57732. * @property {object} _urlMap - Maps URLs to resources.
  57733. * @private
  57734. */
  57735. this._urlMap = {};
  57736. /**
  57737. * @property {Image} _urlResolver - Used to resolve URLs to the absolute path.
  57738. * @private
  57739. */
  57740. this._urlResolver = new Image();
  57741. /**
  57742. * @property {string} _urlTemp - Temporary variable to hold a resolved url.
  57743. * @private
  57744. */
  57745. this._urlTemp = null;
  57746. /**
  57747. * @property {Phaser.Signal} onSoundUnlock - This event is dispatched when the sound system is unlocked via a touch event on cellular devices.
  57748. */
  57749. this.onSoundUnlock = new Phaser.Signal();
  57750. /**
  57751. * @property {array} _cacheMap - Const to cache object look-up array.
  57752. * @private
  57753. */
  57754. this._cacheMap = [];
  57755. this._cacheMap[Phaser.Cache.CANVAS] = this._cache.canvas;
  57756. this._cacheMap[Phaser.Cache.IMAGE] = this._cache.image;
  57757. this._cacheMap[Phaser.Cache.TEXTURE] = this._cache.texture;
  57758. this._cacheMap[Phaser.Cache.SOUND] = this._cache.sound;
  57759. this._cacheMap[Phaser.Cache.TEXT] = this._cache.text;
  57760. this._cacheMap[Phaser.Cache.PHYSICS] = this._cache.physics;
  57761. this._cacheMap[Phaser.Cache.TILEMAP] = this._cache.tilemap;
  57762. this._cacheMap[Phaser.Cache.BINARY] = this._cache.binary;
  57763. this._cacheMap[Phaser.Cache.BITMAPDATA] = this._cache.bitmapData;
  57764. this._cacheMap[Phaser.Cache.BITMAPFONT] = this._cache.bitmapFont;
  57765. this._cacheMap[Phaser.Cache.JSON] = this._cache.json;
  57766. this._cacheMap[Phaser.Cache.XML] = this._cache.xml;
  57767. this._cacheMap[Phaser.Cache.VIDEO] = this._cache.video;
  57768. this._cacheMap[Phaser.Cache.SHADER] = this._cache.shader;
  57769. this._cacheMap[Phaser.Cache.RENDER_TEXTURE] = this._cache.renderTexture;
  57770. this.addDefaultImage();
  57771. this.addMissingImage();
  57772. };
  57773. /**
  57774. * @constant
  57775. * @type {number}
  57776. */
  57777. Phaser.Cache.CANVAS = 1;
  57778. /**
  57779. * @constant
  57780. * @type {number}
  57781. */
  57782. Phaser.Cache.IMAGE = 2;
  57783. /**
  57784. * @constant
  57785. * @type {number}
  57786. */
  57787. Phaser.Cache.TEXTURE = 3;
  57788. /**
  57789. * @constant
  57790. * @type {number}
  57791. */
  57792. Phaser.Cache.SOUND = 4;
  57793. /**
  57794. * @constant
  57795. * @type {number}
  57796. */
  57797. Phaser.Cache.TEXT = 5;
  57798. /**
  57799. * @constant
  57800. * @type {number}
  57801. */
  57802. Phaser.Cache.PHYSICS = 6;
  57803. /**
  57804. * @constant
  57805. * @type {number}
  57806. */
  57807. Phaser.Cache.TILEMAP = 7;
  57808. /**
  57809. * @constant
  57810. * @type {number}
  57811. */
  57812. Phaser.Cache.BINARY = 8;
  57813. /**
  57814. * @constant
  57815. * @type {number}
  57816. */
  57817. Phaser.Cache.BITMAPDATA = 9;
  57818. /**
  57819. * @constant
  57820. * @type {number}
  57821. */
  57822. Phaser.Cache.BITMAPFONT = 10;
  57823. /**
  57824. * @constant
  57825. * @type {number}
  57826. */
  57827. Phaser.Cache.JSON = 11;
  57828. /**
  57829. * @constant
  57830. * @type {number}
  57831. */
  57832. Phaser.Cache.XML = 12;
  57833. /**
  57834. * @constant
  57835. * @type {number}
  57836. */
  57837. Phaser.Cache.VIDEO = 13;
  57838. /**
  57839. * @constant
  57840. * @type {number}
  57841. */
  57842. Phaser.Cache.SHADER = 14;
  57843. /**
  57844. * @constant
  57845. * @type {number}
  57846. */
  57847. Phaser.Cache.RENDER_TEXTURE = 15;
  57848. /**
  57849. * The default image used for a texture when no other is specified.
  57850. * @constant
  57851. * @type {PIXI.Texture}
  57852. */
  57853. Phaser.Cache.DEFAULT = null;
  57854. /**
  57855. * The default image used for a texture when the source image is missing.
  57856. * @constant
  57857. * @type {PIXI.Texture}
  57858. */
  57859. Phaser.Cache.MISSING = null;
  57860. Phaser.Cache.prototype = {
  57861. //////////////////
  57862. // Add Methods //
  57863. //////////////////
  57864. /**
  57865. * Add a new canvas object in to the cache.
  57866. *
  57867. * @method Phaser.Cache#addCanvas
  57868. * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache.
  57869. * @param {HTMLCanvasElement} canvas - The Canvas DOM element.
  57870. * @param {CanvasRenderingContext2D} [context] - The context of the canvas element. If not specified it will default go `getContext('2d')`.
  57871. */
  57872. addCanvas: function (key, canvas, context) {
  57873. if (context === undefined) { context = canvas.getContext('2d'); }
  57874. this._cache.canvas[key] = { canvas: canvas, context: context };
  57875. },
  57876. /**
  57877. * Adds an Image file into the Cache. The file must have already been loaded, typically via Phaser.Loader, but can also have been loaded into the DOM.
  57878. * If an image already exists in the cache with the same key then it is removed and destroyed, and the new image inserted in its place.
  57879. *
  57880. * @method Phaser.Cache#addImage
  57881. * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache.
  57882. * @param {string} url - The URL the asset was loaded from. If the asset was not loaded externally set to `null`.
  57883. * @param {object} data - Extra image data.
  57884. * @return {object} The full image object that was added to the cache.
  57885. */
  57886. addImage: function (key, url, data) {
  57887. if (this.checkImageKey(key))
  57888. {
  57889. this.removeImage(key);
  57890. }
  57891. var img = {
  57892. key: key,
  57893. url: url,
  57894. data: data,
  57895. base: new PIXI.BaseTexture(data),
  57896. frame: new Phaser.Frame(0, 0, 0, data.width, data.height, key),
  57897. frameData: new Phaser.FrameData()
  57898. };
  57899. img.frameData.addFrame(new Phaser.Frame(0, 0, 0, data.width, data.height, url));
  57900. this._cache.image[key] = img;
  57901. this._resolveURL(url, img);
  57902. if (key === '__default')
  57903. {
  57904. Phaser.Cache.DEFAULT = new PIXI.Texture(img.base);
  57905. }
  57906. else if (key === '__missing')
  57907. {
  57908. Phaser.Cache.MISSING = new PIXI.Texture(img.base);
  57909. }
  57910. return img;
  57911. },
  57912. /**
  57913. * Adds a default image to be used in special cases such as WebGL Filters.
  57914. * It uses the special reserved key of `__default`.
  57915. * This method is called automatically when the Cache is created.
  57916. * This image is skipped when `Cache.destroy` is called due to its internal requirements.
  57917. *
  57918. * @method Phaser.Cache#addDefaultImage
  57919. * @protected
  57920. */
  57921. addDefaultImage: function () {
  57922. var img = new Image();
  57923. img.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgAQMAAABJtOi3AAAAA1BMVEX///+nxBvIAAAAAXRSTlMAQObYZgAAABVJREFUeF7NwIEAAAAAgKD9qdeocAMAoAABm3DkcAAAAABJRU5ErkJggg==";
  57924. var obj = this.addImage('__default', null, img);
  57925. // Because we don't want to invalidate the sprite batch for an invisible texture
  57926. obj.base.skipRender = true;
  57927. // Make it easily available within the rest of Phaser / Pixi
  57928. Phaser.Cache.DEFAULT = new PIXI.Texture(obj.base);
  57929. },
  57930. /**
  57931. * Adds an image to be used when a key is wrong / missing.
  57932. * It uses the special reserved key of `__missing`.
  57933. * This method is called automatically when the Cache is created.
  57934. * This image is skipped when `Cache.destroy` is called due to its internal requirements.
  57935. *
  57936. * @method Phaser.Cache#addMissingImage
  57937. * @protected
  57938. */
  57939. addMissingImage: function () {
  57940. var img = new Image();
  57941. img.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAIAAAD8GO2jAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAJ9JREFUeNq01ssOwyAMRFG46v//Mt1ESmgh+DFmE2GPOBARKb2NVjo+17PXLD8a1+pl5+A+wSgFygymWYHBb0FtsKhJDdZlncG2IzJ4ayoMDv20wTmSMzClEgbWYNTAkQ0Z+OJ+A/eWnAaR9+oxCF4Os0H8htsMUp+pwcgBBiMNnAwF8GqIgL2hAzaGFFgZauDPKABmowZ4GL369/0rwACp2yA/ttmvsQAAAABJRU5ErkJggg==";
  57942. var obj = this.addImage('__missing', null, img);
  57943. // Make it easily available within the rest of Phaser / Pixi
  57944. Phaser.Cache.MISSING = new PIXI.Texture(obj.base);
  57945. },
  57946. /**
  57947. * Adds a Sound file into the Cache. The file must have already been loaded, typically via Phaser.Loader.
  57948. *
  57949. * @method Phaser.Cache#addSound
  57950. * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache.
  57951. * @param {string} url - The URL the asset was loaded from. If the asset was not loaded externally set to `null`.
  57952. * @param {object} data - Extra sound data.
  57953. * @param {boolean} webAudio - True if the file is using web audio.
  57954. * @param {boolean} audioTag - True if the file is using legacy HTML audio.
  57955. */
  57956. addSound: function (key, url, data, webAudio, audioTag) {
  57957. if (webAudio === undefined) { webAudio = true; audioTag = false; }
  57958. if (audioTag === undefined) { webAudio = false; audioTag = true; }
  57959. var decoded = false;
  57960. if (audioTag)
  57961. {
  57962. decoded = true;
  57963. }
  57964. this._cache.sound[key] = {
  57965. url: url,
  57966. data: data,
  57967. isDecoding: false,
  57968. decoded: decoded,
  57969. webAudio: webAudio,
  57970. audioTag: audioTag,
  57971. locked: this.game.sound.touchLocked
  57972. };
  57973. this._resolveURL(url, this._cache.sound[key]);
  57974. },
  57975. /**
  57976. * Add a new text data.
  57977. *
  57978. * @method Phaser.Cache#addText
  57979. * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache.
  57980. * @param {string} url - The URL the asset was loaded from. If the asset was not loaded externally set to `null`.
  57981. * @param {object} data - Extra text data.
  57982. */
  57983. addText: function (key, url, data) {
  57984. this._cache.text[key] = { url: url, data: data };
  57985. this._resolveURL(url, this._cache.text[key]);
  57986. },
  57987. /**
  57988. * Add a new physics data object to the Cache.
  57989. *
  57990. * @method Phaser.Cache#addPhysicsData
  57991. * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache.
  57992. * @param {string} url - The URL the asset was loaded from. If the asset was not loaded externally set to `null`.
  57993. * @param {object} JSONData - The physics data object (a JSON file).
  57994. * @param {number} format - The format of the physics data.
  57995. */
  57996. addPhysicsData: function (key, url, JSONData, format) {
  57997. this._cache.physics[key] = { url: url, data: JSONData, format: format };
  57998. this._resolveURL(url, this._cache.physics[key]);
  57999. },
  58000. /**
  58001. * Add a new tilemap to the Cache.
  58002. *
  58003. * @method Phaser.Cache#addTilemap
  58004. * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache.
  58005. * @param {string} url - The URL the asset was loaded from. If the asset was not loaded externally set to `null`.
  58006. * @param {object} mapData - The tilemap data object (either a CSV or JSON file).
  58007. * @param {number} format - The format of the tilemap data.
  58008. */
  58009. addTilemap: function (key, url, mapData, format) {
  58010. this._cache.tilemap[key] = { url: url, data: mapData, format: format };
  58011. this._resolveURL(url, this._cache.tilemap[key]);
  58012. },
  58013. /**
  58014. * Add a binary object in to the cache.
  58015. *
  58016. * @method Phaser.Cache#addBinary
  58017. * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache.
  58018. * @param {object} binaryData - The binary object to be added to the cache.
  58019. */
  58020. addBinary: function (key, binaryData) {
  58021. this._cache.binary[key] = binaryData;
  58022. },
  58023. /**
  58024. * Add a BitmapData object to the cache.
  58025. *
  58026. * @method Phaser.Cache#addBitmapData
  58027. * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache.
  58028. * @param {Phaser.BitmapData} bitmapData - The BitmapData object to be addded to the cache.
  58029. * @param {Phaser.FrameData|null} [frameData=(auto create)] - Optional FrameData set associated with the given BitmapData. If not specified (or `undefined`) a new FrameData object is created containing the Bitmap's Frame. If `null` is supplied then no FrameData will be created.
  58030. * @return {Phaser.BitmapData} The BitmapData object to be addded to the cache.
  58031. */
  58032. addBitmapData: function (key, bitmapData, frameData) {
  58033. bitmapData.key = key;
  58034. if (frameData === undefined)
  58035. {
  58036. frameData = new Phaser.FrameData();
  58037. frameData.addFrame(bitmapData.textureFrame);
  58038. }
  58039. this._cache.bitmapData[key] = { data: bitmapData, frameData: frameData };
  58040. return bitmapData;
  58041. },
  58042. /**
  58043. * Add a new Bitmap Font to the Cache.
  58044. *
  58045. * @method Phaser.Cache#addBitmapFont
  58046. * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache.
  58047. * @param {string} url - The URL the asset was loaded from. If the asset was not loaded externally set to `null`.
  58048. * @param {object} data - Extra font data.
  58049. * @param {object} atlasData - Texture atlas frames data.
  58050. * @param {string} [atlasType='xml'] - The format of the texture atlas ( 'json' or 'xml' ).
  58051. * @param {number} [xSpacing=0] - If you'd like to add additional horizontal spacing between the characters then set the pixel value here.
  58052. * @param {number} [ySpacing=0] - If you'd like to add additional vertical spacing between the lines then set the pixel value here.
  58053. */
  58054. addBitmapFont: function (key, url, data, atlasData, atlasType, xSpacing, ySpacing) {
  58055. var obj = {
  58056. url: url,
  58057. data: data,
  58058. font: null,
  58059. base: new PIXI.BaseTexture(data)
  58060. };
  58061. if (xSpacing === undefined) { xSpacing = 0; }
  58062. if (ySpacing === undefined) { ySpacing = 0; }
  58063. if (atlasType === 'json')
  58064. {
  58065. obj.font = Phaser.LoaderParser.jsonBitmapFont(atlasData, obj.base, xSpacing, ySpacing);
  58066. }
  58067. else
  58068. {
  58069. obj.font = Phaser.LoaderParser.xmlBitmapFont(atlasData, obj.base, xSpacing, ySpacing);
  58070. }
  58071. this._cache.bitmapFont[key] = obj;
  58072. this._resolveURL(url, obj);
  58073. },
  58074. /**
  58075. * Add a new json object into the cache.
  58076. *
  58077. * @method Phaser.Cache#addJSON
  58078. * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache.
  58079. * @param {string} url - The URL the asset was loaded from. If the asset was not loaded externally set to `null`.
  58080. * @param {object} data - Extra json data.
  58081. */
  58082. addJSON: function (key, url, data) {
  58083. this._cache.json[key] = { url: url, data: data };
  58084. this._resolveURL(url, this._cache.json[key]);
  58085. },
  58086. /**
  58087. * Add a new xml object into the cache.
  58088. *
  58089. * @method Phaser.Cache#addXML
  58090. * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache.
  58091. * @param {string} url - The URL the asset was loaded from. If the asset was not loaded externally set to `null`.
  58092. * @param {object} data - Extra text data.
  58093. */
  58094. addXML: function (key, url, data) {
  58095. this._cache.xml[key] = { url: url, data: data };
  58096. this._resolveURL(url, this._cache.xml[key]);
  58097. },
  58098. /**
  58099. * Adds a Video file into the Cache. The file must have already been loaded, typically via Phaser.Loader.
  58100. *
  58101. * @method Phaser.Cache#addVideo
  58102. * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache.
  58103. * @param {string} url - The URL the asset was loaded from. If the asset was not loaded externally set to `null`.
  58104. * @param {object} data - Extra video data.
  58105. * @param {boolean} isBlob - True if the file was preloaded via xhr and the data parameter is a Blob. false if a Video tag was created instead.
  58106. */
  58107. addVideo: function (key, url, data, isBlob) {
  58108. this._cache.video[key] = { url: url, data: data, isBlob: isBlob, locked: true };
  58109. this._resolveURL(url, this._cache.video[key]);
  58110. },
  58111. /**
  58112. * Adds a Fragment Shader in to the Cache. The file must have already been loaded, typically via Phaser.Loader.
  58113. *
  58114. * @method Phaser.Cache#addShader
  58115. * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache.
  58116. * @param {string} url - The URL the asset was loaded from. If the asset was not loaded externally set to `null`.
  58117. * @param {object} data - Extra shader data.
  58118. */
  58119. addShader: function (key, url, data) {
  58120. this._cache.shader[key] = { url: url, data: data };
  58121. this._resolveURL(url, this._cache.shader[key]);
  58122. },
  58123. /**
  58124. * Add a new Phaser.RenderTexture in to the cache.
  58125. *
  58126. * @method Phaser.Cache#addRenderTexture
  58127. * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache.
  58128. * @param {Phaser.RenderTexture} texture - The texture to use as the base of the RenderTexture.
  58129. */
  58130. addRenderTexture: function (key, texture) {
  58131. this._cache.renderTexture[key] = { texture: texture, frame: new Phaser.Frame(0, 0, 0, texture.width, texture.height, '', '') };
  58132. },
  58133. /**
  58134. * Add a new sprite sheet in to the cache.
  58135. *
  58136. * @method Phaser.Cache#addSpriteSheet
  58137. * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache.
  58138. * @param {string} url - The URL the asset was loaded from. If the asset was not loaded externally set to `null`.
  58139. * @param {object} data - Extra sprite sheet data.
  58140. * @param {number} frameWidth - Width of the sprite sheet.
  58141. * @param {number} frameHeight - Height of the sprite sheet.
  58142. * @param {number} [frameMax=-1] - How many frames stored in the sprite sheet. If -1 then it divides the whole sheet evenly.
  58143. * @param {number} [margin=0] - If the frames have been drawn with a margin, specify the amount here.
  58144. * @param {number} [spacing=0] - If the frames have been drawn with spacing between them, specify the amount here.
  58145. */
  58146. addSpriteSheet: function (key, url, data, frameWidth, frameHeight, frameMax, margin, spacing) {
  58147. if (frameMax === undefined) { frameMax = -1; }
  58148. if (margin === undefined) { margin = 0; }
  58149. if (spacing === undefined) { spacing = 0; }
  58150. var obj = {
  58151. key: key,
  58152. url: url,
  58153. data: data,
  58154. frameWidth: frameWidth,
  58155. frameHeight: frameHeight,
  58156. margin: margin,
  58157. spacing: spacing,
  58158. base: new PIXI.BaseTexture(data),
  58159. frameData: Phaser.AnimationParser.spriteSheet(this.game, data, frameWidth, frameHeight, frameMax, margin, spacing)
  58160. };
  58161. this._cache.image[key] = obj;
  58162. this._resolveURL(url, obj);
  58163. },
  58164. /**
  58165. * Add a new texture atlas to the Cache.
  58166. *
  58167. * @method Phaser.Cache#addTextureAtlas
  58168. * @param {string} key - The key that this asset will be stored in the cache under. This should be unique within this cache.
  58169. * @param {string} url - The URL the asset was loaded from. If the asset was not loaded externally set to `null`.
  58170. * @param {object} data - Extra texture atlas data.
  58171. * @param {object} atlasData - Texture atlas frames data.
  58172. * @param {number} format - The format of the texture atlas.
  58173. */
  58174. addTextureAtlas: function (key, url, data, atlasData, format) {
  58175. var obj = {
  58176. key: key,
  58177. url: url,
  58178. data: data,
  58179. base: new PIXI.BaseTexture(data)
  58180. };
  58181. if (format === Phaser.Loader.TEXTURE_ATLAS_XML_STARLING)
  58182. {
  58183. obj.frameData = Phaser.AnimationParser.XMLData(this.game, atlasData, key);
  58184. }
  58185. else if (format === Phaser.Loader.TEXTURE_ATLAS_JSON_PYXEL)
  58186. {
  58187. obj.frameData = Phaser.AnimationParser.JSONDataPyxel(this.game, atlasData, key);
  58188. }
  58189. else
  58190. {
  58191. // Let's just work it out from the frames array
  58192. if (Array.isArray(atlasData.frames))
  58193. {
  58194. obj.frameData = Phaser.AnimationParser.JSONData(this.game, atlasData, key);
  58195. }
  58196. else
  58197. {
  58198. obj.frameData = Phaser.AnimationParser.JSONDataHash(this.game, atlasData, key);
  58199. }
  58200. }
  58201. this._cache.image[key] = obj;
  58202. this._resolveURL(url, obj);
  58203. },
  58204. ////////////////////////////
  58205. // Sound Related Methods //
  58206. ////////////////////////////
  58207. /**
  58208. * Reload a Sound file from the server.
  58209. *
  58210. * @method Phaser.Cache#reloadSound
  58211. * @param {string} key - The key of the asset within the cache.
  58212. */
  58213. reloadSound: function (key) {
  58214. var _this = this;
  58215. var sound = this.getSound(key);
  58216. if (sound)
  58217. {
  58218. sound.data.src = sound.url;
  58219. sound.data.addEventListener('canplaythrough', function () {
  58220. return _this.reloadSoundComplete(key);
  58221. }, false);
  58222. sound.data.load();
  58223. }
  58224. },
  58225. /**
  58226. * Fires the onSoundUnlock event when the sound has completed reloading.
  58227. *
  58228. * @method Phaser.Cache#reloadSoundComplete
  58229. * @param {string} key - The key of the asset within the cache.
  58230. */
  58231. reloadSoundComplete: function (key) {
  58232. var sound = this.getSound(key);
  58233. if (sound)
  58234. {
  58235. sound.locked = false;
  58236. this.onSoundUnlock.dispatch(key);
  58237. }
  58238. },
  58239. /**
  58240. * Updates the sound object in the cache.
  58241. *
  58242. * @method Phaser.Cache#updateSound
  58243. * @param {string} key - The key of the asset within the cache.
  58244. */
  58245. updateSound: function (key, property, value) {
  58246. var sound = this.getSound(key);
  58247. if (sound)
  58248. {
  58249. sound[property] = value;
  58250. }
  58251. },
  58252. /**
  58253. * Add a new decoded sound.
  58254. *
  58255. * @method Phaser.Cache#decodedSound
  58256. * @param {string} key - The key of the asset within the cache.
  58257. * @param {object} data - Extra sound data.
  58258. */
  58259. decodedSound: function (key, data) {
  58260. var sound = this.getSound(key);
  58261. sound.data = data;
  58262. sound.decoded = true;
  58263. sound.isDecoding = false;
  58264. },
  58265. /**
  58266. * Check if the given sound has finished decoding.
  58267. *
  58268. * @method Phaser.Cache#isSoundDecoded
  58269. * @param {string} key - The key of the asset within the cache.
  58270. * @return {boolean} The decoded state of the Sound object.
  58271. */
  58272. isSoundDecoded: function (key) {
  58273. var sound = this.getItem(key, Phaser.Cache.SOUND, 'isSoundDecoded');
  58274. if (sound)
  58275. {
  58276. return sound.decoded;
  58277. }
  58278. },
  58279. /**
  58280. * Check if the given sound is ready for playback.
  58281. * A sound is considered ready when it has finished decoding and the device is no longer touch locked.
  58282. *
  58283. * @method Phaser.Cache#isSoundReady
  58284. * @param {string} key - The key of the asset within the cache.
  58285. * @return {boolean} True if the sound is decoded and the device is not touch locked.
  58286. */
  58287. isSoundReady: function (key) {
  58288. var sound = this.getItem(key, Phaser.Cache.SOUND, 'isSoundDecoded');
  58289. if (sound)
  58290. {
  58291. return (sound.decoded && !this.game.sound.touchLocked);
  58292. }
  58293. },
  58294. ////////////////////////
  58295. // Check Key Methods //
  58296. ////////////////////////
  58297. /**
  58298. * Checks if a key for the given cache object type exists.
  58299. *
  58300. * @method Phaser.Cache#checkKey
  58301. * @param {integer} cache - The cache to search. One of the Cache consts such as `Phaser.Cache.IMAGE` or `Phaser.Cache.SOUND`.
  58302. * @param {string} key - The key of the asset within the cache.
  58303. * @return {boolean} True if the key exists, otherwise false.
  58304. */
  58305. checkKey: function (cache, key) {
  58306. if (this._cacheMap[cache][key])
  58307. {
  58308. return true;
  58309. }
  58310. return false;
  58311. },
  58312. /**
  58313. * Checks if the given URL has been loaded into the Cache.
  58314. * This method will only work if Cache.autoResolveURL was set to `true` before any preloading took place.
  58315. * The method will make a DOM src call to the URL given, so please be aware of this for certain file types, such as Sound files on Firefox
  58316. * which may cause double-load instances.
  58317. *
  58318. * @method Phaser.Cache#checkURL
  58319. * @param {string} url - The url to check for in the cache.
  58320. * @return {boolean} True if the url exists, otherwise false.
  58321. */
  58322. checkURL: function (url) {
  58323. if (this._urlMap[this._resolveURL(url)])
  58324. {
  58325. return true;
  58326. }
  58327. return false;
  58328. },
  58329. /**
  58330. * Checks if the given key exists in the Canvas Cache.
  58331. *
  58332. * @method Phaser.Cache#checkCanvasKey
  58333. * @param {string} key - The key of the asset within the cache.
  58334. * @return {boolean} True if the key exists in the cache, otherwise false.
  58335. */
  58336. checkCanvasKey: function (key) {
  58337. return this.checkKey(Phaser.Cache.CANVAS, key);
  58338. },
  58339. /**
  58340. * Checks if the given key exists in the Image Cache. Note that this also includes Texture Atlases, Sprite Sheets and Retro Fonts.
  58341. *
  58342. * @method Phaser.Cache#checkImageKey
  58343. * @param {string} key - The key of the asset within the cache.
  58344. * @return {boolean} True if the key exists in the cache, otherwise false.
  58345. */
  58346. checkImageKey: function (key) {
  58347. return this.checkKey(Phaser.Cache.IMAGE, key);
  58348. },
  58349. /**
  58350. * Checks if the given key exists in the Texture Cache.
  58351. *
  58352. * @method Phaser.Cache#checkTextureKey
  58353. * @param {string} key - The key of the asset within the cache.
  58354. * @return {boolean} True if the key exists in the cache, otherwise false.
  58355. */
  58356. checkTextureKey: function (key) {
  58357. return this.checkKey(Phaser.Cache.TEXTURE, key);
  58358. },
  58359. /**
  58360. * Checks if the given key exists in the Sound Cache.
  58361. *
  58362. * @method Phaser.Cache#checkSoundKey
  58363. * @param {string} key - The key of the asset within the cache.
  58364. * @return {boolean} True if the key exists in the cache, otherwise false.
  58365. */
  58366. checkSoundKey: function (key) {
  58367. return this.checkKey(Phaser.Cache.SOUND, key);
  58368. },
  58369. /**
  58370. * Checks if the given key exists in the Text Cache.
  58371. *
  58372. * @method Phaser.Cache#checkTextKey
  58373. * @param {string} key - The key of the asset within the cache.
  58374. * @return {boolean} True if the key exists in the cache, otherwise false.
  58375. */
  58376. checkTextKey: function (key) {
  58377. return this.checkKey(Phaser.Cache.TEXT, key);
  58378. },
  58379. /**
  58380. * Checks if the given key exists in the Physics Cache.
  58381. *
  58382. * @method Phaser.Cache#checkPhysicsKey
  58383. * @param {string} key - The key of the asset within the cache.
  58384. * @return {boolean} True if the key exists in the cache, otherwise false.
  58385. */
  58386. checkPhysicsKey: function (key) {
  58387. return this.checkKey(Phaser.Cache.PHYSICS, key);
  58388. },
  58389. /**
  58390. * Checks if the given key exists in the Tilemap Cache.
  58391. *
  58392. * @method Phaser.Cache#checkTilemapKey
  58393. * @param {string} key - The key of the asset within the cache.
  58394. * @return {boolean} True if the key exists in the cache, otherwise false.
  58395. */
  58396. checkTilemapKey: function (key) {
  58397. return this.checkKey(Phaser.Cache.TILEMAP, key);
  58398. },
  58399. /**
  58400. * Checks if the given key exists in the Binary Cache.
  58401. *
  58402. * @method Phaser.Cache#checkBinaryKey
  58403. * @param {string} key - The key of the asset within the cache.
  58404. * @return {boolean} True if the key exists in the cache, otherwise false.
  58405. */
  58406. checkBinaryKey: function (key) {
  58407. return this.checkKey(Phaser.Cache.BINARY, key);
  58408. },
  58409. /**
  58410. * Checks if the given key exists in the BitmapData Cache.
  58411. *
  58412. * @method Phaser.Cache#checkBitmapDataKey
  58413. * @param {string} key - The key of the asset within the cache.
  58414. * @return {boolean} True if the key exists in the cache, otherwise false.
  58415. */
  58416. checkBitmapDataKey: function (key) {
  58417. return this.checkKey(Phaser.Cache.BITMAPDATA, key);
  58418. },
  58419. /**
  58420. * Checks if the given key exists in the BitmapFont Cache.
  58421. *
  58422. * @method Phaser.Cache#checkBitmapFontKey
  58423. * @param {string} key - The key of the asset within the cache.
  58424. * @return {boolean} True if the key exists in the cache, otherwise false.
  58425. */
  58426. checkBitmapFontKey: function (key) {
  58427. return this.checkKey(Phaser.Cache.BITMAPFONT, key);
  58428. },
  58429. /**
  58430. * Checks if the given key exists in the JSON Cache.
  58431. *
  58432. * @method Phaser.Cache#checkJSONKey
  58433. * @param {string} key - The key of the asset within the cache.
  58434. * @return {boolean} True if the key exists in the cache, otherwise false.
  58435. */
  58436. checkJSONKey: function (key) {
  58437. return this.checkKey(Phaser.Cache.JSON, key);
  58438. },
  58439. /**
  58440. * Checks if the given key exists in the XML Cache.
  58441. *
  58442. * @method Phaser.Cache#checkXMLKey
  58443. * @param {string} key - The key of the asset within the cache.
  58444. * @return {boolean} True if the key exists in the cache, otherwise false.
  58445. */
  58446. checkXMLKey: function (key) {
  58447. return this.checkKey(Phaser.Cache.XML, key);
  58448. },
  58449. /**
  58450. * Checks if the given key exists in the Video Cache.
  58451. *
  58452. * @method Phaser.Cache#checkVideoKey
  58453. * @param {string} key - The key of the asset within the cache.
  58454. * @return {boolean} True if the key exists in the cache, otherwise false.
  58455. */
  58456. checkVideoKey: function (key) {
  58457. return this.checkKey(Phaser.Cache.VIDEO, key);
  58458. },
  58459. /**
  58460. * Checks if the given key exists in the Fragment Shader Cache.
  58461. *
  58462. * @method Phaser.Cache#checkShaderKey
  58463. * @param {string} key - The key of the asset within the cache.
  58464. * @return {boolean} True if the key exists in the cache, otherwise false.
  58465. */
  58466. checkShaderKey: function (key) {
  58467. return this.checkKey(Phaser.Cache.SHADER, key);
  58468. },
  58469. /**
  58470. * Checks if the given key exists in the Render Texture Cache.
  58471. *
  58472. * @method Phaser.Cache#checkRenderTextureKey
  58473. * @param {string} key - The key of the asset within the cache.
  58474. * @return {boolean} True if the key exists in the cache, otherwise false.
  58475. */
  58476. checkRenderTextureKey: function (key) {
  58477. return this.checkKey(Phaser.Cache.RENDER_TEXTURE, key);
  58478. },
  58479. ////////////////
  58480. // Get Items //
  58481. ////////////////
  58482. /**
  58483. * Get an item from a cache based on the given key and property.
  58484. *
  58485. * This method is mostly used internally by other Cache methods such as `getImage` but is exposed
  58486. * publicly for your own use as well.
  58487. *
  58488. * @method Phaser.Cache#getItem
  58489. * @param {string} key - The key of the asset within the cache.
  58490. * @param {integer} cache - The cache to search. One of the Cache consts such as `Phaser.Cache.IMAGE` or `Phaser.Cache.SOUND`.
  58491. * @param {string} [method] - The string name of the method calling getItem. Can be empty, in which case no console warning is output.
  58492. * @param {string} [property] - If you require a specific property from the cache item, specify it here.
  58493. * @return {object} The cached item if found, otherwise `null`. If the key is invalid and `method` is set then a console.warn is output.
  58494. */
  58495. getItem: function (key, cache, method, property) {
  58496. if (!this.checkKey(cache, key))
  58497. {
  58498. if (method)
  58499. {
  58500. console.warn('Phaser.Cache.' + method + ': Key "' + key + '" not found in Cache.');
  58501. }
  58502. }
  58503. else
  58504. {
  58505. if (property === undefined)
  58506. {
  58507. return this._cacheMap[cache][key];
  58508. }
  58509. else
  58510. {
  58511. return this._cacheMap[cache][key][property];
  58512. }
  58513. }
  58514. return null;
  58515. },
  58516. /**
  58517. * Gets a Canvas object from the cache.
  58518. *
  58519. * The object is looked-up based on the key given.
  58520. *
  58521. * Note: If the object cannot be found a `console.warn` message is displayed.
  58522. *
  58523. * @method Phaser.Cache#getCanvas
  58524. * @param {string} key - The key of the asset to retrieve from the cache.
  58525. * @return {object} The canvas object or `null` if no item could be found matching the given key.
  58526. */
  58527. getCanvas: function (key) {
  58528. return this.getItem(key, Phaser.Cache.CANVAS, 'getCanvas', 'canvas');
  58529. },
  58530. /**
  58531. * Gets a Image object from the cache. This returns a DOM Image object, not a Phaser.Image object.
  58532. *
  58533. * The object is looked-up based on the key given.
  58534. *
  58535. * Note: If the object cannot be found a `console.warn` message is displayed.
  58536. *
  58537. * Only the Image cache is searched, which covers images loaded via Loader.image, Sprite Sheets and Texture Atlases.
  58538. *
  58539. * If you need the image used by a bitmap font or similar then please use those respective 'get' methods.
  58540. *
  58541. * @method Phaser.Cache#getImage
  58542. * @param {string} [key] - The key of the asset to retrieve from the cache. If not given or null it will return a default image. If given but not found in the cache it will throw a warning and return the missing image.
  58543. * @param {boolean} [full=false] - If true the full image object will be returned, if false just the HTML Image object is returned.
  58544. * @return {Image} The Image object if found in the Cache, otherwise `null`. If `full` was true then a JavaScript object is returned.
  58545. */
  58546. getImage: function (key, full) {
  58547. if (key === undefined || key === null)
  58548. {
  58549. key = '__default';
  58550. }
  58551. if (full === undefined) { full = false; }
  58552. var img = this.getItem(key, Phaser.Cache.IMAGE, 'getImage');
  58553. if (img === null)
  58554. {
  58555. img = this.getItem('__missing', Phaser.Cache.IMAGE, 'getImage');
  58556. }
  58557. if (full)
  58558. {
  58559. return img;
  58560. }
  58561. else
  58562. {
  58563. return img.data;
  58564. }
  58565. },
  58566. /**
  58567. * Get a single texture frame by key.
  58568. *
  58569. * You'd only do this to get the default Frame created for a non-atlas / spritesheet image.
  58570. *
  58571. * @method Phaser.Cache#getTextureFrame
  58572. * @param {string} key - The key of the asset to retrieve from the cache.
  58573. * @return {Phaser.Frame} The frame data.
  58574. */
  58575. getTextureFrame: function (key) {
  58576. return this.getItem(key, Phaser.Cache.TEXTURE, 'getTextureFrame', 'frame');
  58577. },
  58578. /**
  58579. * Gets a Phaser.Sound object from the cache.
  58580. *
  58581. * The object is looked-up based on the key given.
  58582. *
  58583. * Note: If the object cannot be found a `console.warn` message is displayed.
  58584. *
  58585. * @method Phaser.Cache#getSound
  58586. * @param {string} key - The key of the asset to retrieve from the cache.
  58587. * @return {Phaser.Sound} The sound object.
  58588. */
  58589. getSound: function (key) {
  58590. return this.getItem(key, Phaser.Cache.SOUND, 'getSound');
  58591. },
  58592. /**
  58593. * Gets a raw Sound data object from the cache.
  58594. *
  58595. * The object is looked-up based on the key given.
  58596. *
  58597. * Note: If the object cannot be found a `console.warn` message is displayed.
  58598. *
  58599. * @method Phaser.Cache#getSoundData
  58600. * @param {string} key - The key of the asset to retrieve from the cache.
  58601. * @return {object} The sound data.
  58602. */
  58603. getSoundData: function (key) {
  58604. return this.getItem(key, Phaser.Cache.SOUND, 'getSoundData', 'data');
  58605. },
  58606. /**
  58607. * Gets a Text object from the cache.
  58608. *
  58609. * The object is looked-up based on the key given.
  58610. *
  58611. * Note: If the object cannot be found a `console.warn` message is displayed.
  58612. *
  58613. * @method Phaser.Cache#getText
  58614. * @param {string} key - The key of the asset to retrieve from the cache.
  58615. * @return {object} The text data.
  58616. */
  58617. getText: function (key) {
  58618. return this.getItem(key, Phaser.Cache.TEXT, 'getText', 'data');
  58619. },
  58620. /**
  58621. * Gets a Physics Data object from the cache.
  58622. *
  58623. * The object is looked-up based on the key given.
  58624. *
  58625. * Note: If the object cannot be found a `console.warn` message is displayed.
  58626. *
  58627. * You can get either the entire data set, a single object or a single fixture of an object from it.
  58628. *
  58629. * @method Phaser.Cache#getPhysicsData
  58630. * @param {string} key - The key of the asset to retrieve from the cache.
  58631. * @param {string} [object=null] - If specified it will return just the physics object that is part of the given key, if null it will return them all.
  58632. * @param {string} fixtureKey - Fixture key of fixture inside an object. This key can be set per fixture with the Phaser Exporter.
  58633. * @return {object} The requested physics object data if found.
  58634. */
  58635. getPhysicsData: function (key, object, fixtureKey) {
  58636. var data = this.getItem(key, Phaser.Cache.PHYSICS, 'getPhysicsData', 'data');
  58637. if (data === null || object === undefined || object === null)
  58638. {
  58639. return data;
  58640. }
  58641. else
  58642. {
  58643. if (data[object])
  58644. {
  58645. var fixtures = data[object];
  58646. // Try to find a fixture by its fixture key if given
  58647. if (fixtures && fixtureKey)
  58648. {
  58649. for (var fixture in fixtures)
  58650. {
  58651. // This contains the fixture data of a polygon or a circle
  58652. fixture = fixtures[fixture];
  58653. // Test the key
  58654. if (fixture.fixtureKey === fixtureKey)
  58655. {
  58656. return fixture;
  58657. }
  58658. }
  58659. // We did not find the requested fixture
  58660. console.warn('Phaser.Cache.getPhysicsData: Could not find given fixtureKey: "' + fixtureKey + ' in ' + key + '"');
  58661. }
  58662. else
  58663. {
  58664. return fixtures;
  58665. }
  58666. }
  58667. else
  58668. {
  58669. console.warn('Phaser.Cache.getPhysicsData: Invalid key/object: "' + key + ' / ' + object + '"');
  58670. }
  58671. }
  58672. return null;
  58673. },
  58674. /**
  58675. * Gets a raw Tilemap data object from the cache. This will be in either CSV or JSON format.
  58676. *
  58677. * The object is looked-up based on the key given.
  58678. *
  58679. * Note: If the object cannot be found a `console.warn` message is displayed.
  58680. *
  58681. * @method Phaser.Cache#getTilemapData
  58682. * @param {string} key - The key of the asset to retrieve from the cache.
  58683. * @return {object} The raw tilemap data in CSV or JSON format.
  58684. */
  58685. getTilemapData: function (key) {
  58686. return this.getItem(key, Phaser.Cache.TILEMAP, 'getTilemapData');
  58687. },
  58688. /**
  58689. * Gets a binary object from the cache.
  58690. *
  58691. * The object is looked-up based on the key given.
  58692. *
  58693. * Note: If the object cannot be found a `console.warn` message is displayed.
  58694. *
  58695. * @method Phaser.Cache#getBinary
  58696. * @param {string} key - The key of the asset to retrieve from the cache.
  58697. * @return {object} The binary data object.
  58698. */
  58699. getBinary: function (key) {
  58700. return this.getItem(key, Phaser.Cache.BINARY, 'getBinary');
  58701. },
  58702. /**
  58703. * Gets a BitmapData object from the cache.
  58704. *
  58705. * The object is looked-up based on the key given.
  58706. *
  58707. * Note: If the object cannot be found a `console.warn` message is displayed.
  58708. *
  58709. * @method Phaser.Cache#getBitmapData
  58710. * @param {string} key - The key of the asset to retrieve from the cache.
  58711. * @return {Phaser.BitmapData} The requested BitmapData object if found, or null if not.
  58712. */
  58713. getBitmapData: function (key) {
  58714. return this.getItem(key, Phaser.Cache.BITMAPDATA, 'getBitmapData', 'data');
  58715. },
  58716. /**
  58717. * Gets a Bitmap Font object from the cache.
  58718. *
  58719. * The object is looked-up based on the key given.
  58720. *
  58721. * Note: If the object cannot be found a `console.warn` message is displayed.
  58722. *
  58723. * @method Phaser.Cache#getBitmapFont
  58724. * @param {string} key - The key of the asset to retrieve from the cache.
  58725. * @return {Phaser.BitmapFont} The requested BitmapFont object if found, or null if not.
  58726. */
  58727. getBitmapFont: function (key) {
  58728. return this.getItem(key, Phaser.Cache.BITMAPFONT, 'getBitmapFont');
  58729. },
  58730. /**
  58731. * Gets a JSON object from the cache.
  58732. *
  58733. * The object is looked-up based on the key given.
  58734. *
  58735. * Note: If the object cannot be found a `console.warn` message is displayed.
  58736. *
  58737. * You can either return the object by reference (the default), or return a clone
  58738. * of it by setting the `clone` argument to `true`.
  58739. *
  58740. * @method Phaser.Cache#getJSON
  58741. * @param {string} key - The key of the asset to retrieve from the cache.
  58742. * @param {boolean} [clone=false] - Return a clone of the original object (true) or a reference to it? (false)
  58743. * @return {object} The JSON object, or an Array if the key points to an Array property. If the property wasn't found, it returns null.
  58744. */
  58745. getJSON: function (key, clone) {
  58746. var data = this.getItem(key, Phaser.Cache.JSON, 'getJSON', 'data');
  58747. if (data)
  58748. {
  58749. if (clone)
  58750. {
  58751. return Phaser.Utils.extend(true, Array.isArray(data) ? [] : {}, data);
  58752. }
  58753. else
  58754. {
  58755. return data;
  58756. }
  58757. }
  58758. else
  58759. {
  58760. return null;
  58761. }
  58762. },
  58763. /**
  58764. * Gets an XML object from the cache.
  58765. *
  58766. * The object is looked-up based on the key given.
  58767. *
  58768. * Note: If the object cannot be found a `console.warn` message is displayed.
  58769. *
  58770. * @method Phaser.Cache#getXML
  58771. * @param {string} key - The key of the asset to retrieve from the cache.
  58772. * @return {object} The XML object.
  58773. */
  58774. getXML: function (key) {
  58775. return this.getItem(key, Phaser.Cache.XML, 'getXML', 'data');
  58776. },
  58777. /**
  58778. * Gets a Phaser.Video object from the cache.
  58779. *
  58780. * The object is looked-up based on the key given.
  58781. *
  58782. * Note: If the object cannot be found a `console.warn` message is displayed.
  58783. *
  58784. * @method Phaser.Cache#getVideo
  58785. * @param {string} key - The key of the asset to retrieve from the cache.
  58786. * @return {Phaser.Video} The video object.
  58787. */
  58788. getVideo: function (key) {
  58789. return this.getItem(key, Phaser.Cache.VIDEO, 'getVideo');
  58790. },
  58791. /**
  58792. * Gets a fragment shader object from the cache.
  58793. *
  58794. * The object is looked-up based on the key given.
  58795. *
  58796. * Note: If the object cannot be found a `console.warn` message is displayed.
  58797. *
  58798. * @method Phaser.Cache#getShader
  58799. * @param {string} key - The key of the asset to retrieve from the cache.
  58800. * @return {string} The shader object.
  58801. */
  58802. getShader: function (key) {
  58803. return this.getItem(key, Phaser.Cache.SHADER, 'getShader', 'data');
  58804. },
  58805. /**
  58806. * Gets a RenderTexture object from the cache.
  58807. *
  58808. * The object is looked-up based on the key given.
  58809. *
  58810. * Note: If the object cannot be found a `console.warn` message is displayed.
  58811. *
  58812. * @method Phaser.Cache#getRenderTexture
  58813. * @param {string} key - The key of the asset to retrieve from the cache.
  58814. * @return {Object} The object with Phaser.RenderTexture and Phaser.Frame.
  58815. */
  58816. getRenderTexture: function (key) {
  58817. return this.getItem(key, Phaser.Cache.RENDER_TEXTURE, 'getRenderTexture');
  58818. },
  58819. ////////////////////////////
  58820. // Frame Related Methods //
  58821. ////////////////////////////
  58822. /**
  58823. * Gets a PIXI.BaseTexture by key from the given Cache.
  58824. *
  58825. * @method Phaser.Cache#getBaseTexture
  58826. * @param {string} key - Asset key of the image for which you want the BaseTexture for.
  58827. * @param {integer} [cache=Phaser.Cache.IMAGE] - The cache to search for the item in.
  58828. * @return {PIXI.BaseTexture} The BaseTexture object.
  58829. */
  58830. getBaseTexture: function (key, cache) {
  58831. if (cache === undefined) { cache = Phaser.Cache.IMAGE; }
  58832. return this.getItem(key, cache, 'getBaseTexture', 'base');
  58833. },
  58834. /**
  58835. * Get a single frame by key. You'd only do this to get the default Frame created for a non-atlas/spritesheet image.
  58836. *
  58837. * @method Phaser.Cache#getFrame
  58838. * @param {string} key - Asset key of the frame data to retrieve from the Cache.
  58839. * @param {integer} [cache=Phaser.Cache.IMAGE] - The cache to search for the item in.
  58840. * @return {Phaser.Frame} The frame data.
  58841. */
  58842. getFrame: function (key, cache) {
  58843. if (cache === undefined) { cache = Phaser.Cache.IMAGE; }
  58844. return this.getItem(key, cache, 'getFrame', 'frame');
  58845. },
  58846. /**
  58847. * Get the total number of frames contained in the FrameData object specified by the given key.
  58848. *
  58849. * @method Phaser.Cache#getFrameCount
  58850. * @param {string} key - Asset key of the FrameData you want.
  58851. * @param {integer} [cache=Phaser.Cache.IMAGE] - The cache to search for the item in.
  58852. * @return {number} Then number of frames. 0 if the image is not found.
  58853. */
  58854. getFrameCount: function (key, cache) {
  58855. var data = this.getFrameData(key, cache);
  58856. if (data)
  58857. {
  58858. return data.total;
  58859. }
  58860. else
  58861. {
  58862. return 0;
  58863. }
  58864. },
  58865. /**
  58866. * Gets a Phaser.FrameData object from the Image Cache.
  58867. *
  58868. * The object is looked-up based on the key given.
  58869. *
  58870. * Note: If the object cannot be found a `console.warn` message is displayed.
  58871. *
  58872. * @method Phaser.Cache#getFrameData
  58873. * @param {string} key - Asset key of the frame data to retrieve from the Cache.
  58874. * @param {integer} [cache=Phaser.Cache.IMAGE] - The cache to search for the item in.
  58875. * @return {Phaser.FrameData} The frame data.
  58876. */
  58877. getFrameData: function (key, cache) {
  58878. if (cache === undefined) { cache = Phaser.Cache.IMAGE; }
  58879. return this.getItem(key, cache, 'getFrameData', 'frameData');
  58880. },
  58881. /**
  58882. * Check if the FrameData for the given key exists in the Image Cache.
  58883. *
  58884. * @method Phaser.Cache#hasFrameData
  58885. * @param {string} key - Asset key of the frame data to retrieve from the Cache.
  58886. * @param {integer} [cache=Phaser.Cache.IMAGE] - The cache to search for the item in.
  58887. * @return {boolean} True if the given key has frameData in the cache, otherwise false.
  58888. */
  58889. hasFrameData: function (key, cache) {
  58890. if (cache === undefined) { cache = Phaser.Cache.IMAGE; }
  58891. return (this.getItem(key, cache, '', 'frameData') !== null);
  58892. },
  58893. /**
  58894. * Replaces a set of frameData with a new Phaser.FrameData object.
  58895. *
  58896. * @method Phaser.Cache#updateFrameData
  58897. * @param {string} key - The unique key by which you will reference this object.
  58898. * @param {number} frameData - The new FrameData.
  58899. * @param {integer} [cache=Phaser.Cache.IMAGE] - The cache to search. One of the Cache consts such as `Phaser.Cache.IMAGE` or `Phaser.Cache.SOUND`.
  58900. */
  58901. updateFrameData: function (key, frameData, cache) {
  58902. if (cache === undefined) { cache = Phaser.Cache.IMAGE; }
  58903. if (this._cacheMap[cache][key])
  58904. {
  58905. this._cacheMap[cache][key].frameData = frameData;
  58906. }
  58907. },
  58908. /**
  58909. * Get a single frame out of a frameData set by key.
  58910. *
  58911. * @method Phaser.Cache#getFrameByIndex
  58912. * @param {string} key - Asset key of the frame data to retrieve from the Cache.
  58913. * @param {number} index - The index of the frame you want to get.
  58914. * @param {integer} [cache=Phaser.Cache.IMAGE] - The cache to search. One of the Cache consts such as `Phaser.Cache.IMAGE` or `Phaser.Cache.SOUND`.
  58915. * @return {Phaser.Frame} The frame object.
  58916. */
  58917. getFrameByIndex: function (key, index, cache) {
  58918. var data = this.getFrameData(key, cache);
  58919. if (data)
  58920. {
  58921. return data.getFrame(index);
  58922. }
  58923. else
  58924. {
  58925. return null;
  58926. }
  58927. },
  58928. /**
  58929. * Get a single frame out of a frameData set by key.
  58930. *
  58931. * @method Phaser.Cache#getFrameByName
  58932. * @param {string} key - Asset key of the frame data to retrieve from the Cache.
  58933. * @param {string} name - The name of the frame you want to get.
  58934. * @param {integer} [cache=Phaser.Cache.IMAGE] - The cache to search. One of the Cache consts such as `Phaser.Cache.IMAGE` or `Phaser.Cache.SOUND`.
  58935. * @return {Phaser.Frame} The frame object.
  58936. */
  58937. getFrameByName: function (key, name, cache) {
  58938. var data = this.getFrameData(key, cache);
  58939. if (data)
  58940. {
  58941. return data.getFrameByName(name);
  58942. }
  58943. else
  58944. {
  58945. return null;
  58946. }
  58947. },
  58948. /**
  58949. * Get a cached object by the URL.
  58950. * This only returns a value if you set Cache.autoResolveURL to `true` *before* starting the preload of any assets.
  58951. * Be aware that every call to this function makes a DOM src query, so use carefully and double-check for implications in your target browsers/devices.
  58952. *
  58953. * @method Phaser.Cache#getURL
  58954. * @param {string} url - The url for the object loaded to get from the cache.
  58955. * @return {object} The cached object.
  58956. */
  58957. getURL: function (url) {
  58958. var url = this._resolveURL(url);
  58959. if (url)
  58960. {
  58961. return this._urlMap[url];
  58962. }
  58963. else
  58964. {
  58965. console.warn('Phaser.Cache.getUrl: Invalid url: "' + url + '" or Cache.autoResolveURL was false');
  58966. return null;
  58967. }
  58968. },
  58969. /**
  58970. * Gets all keys used in the requested Cache.
  58971. *
  58972. * @method Phaser.Cache#getKeys
  58973. * @param {integer} [cache=Phaser.Cache.IMAGE] - The Cache you wish to get the keys from. Can be any of the Cache consts such as `Phaser.Cache.IMAGE`, `Phaser.Cache.SOUND` etc.
  58974. * @return {Array} The array of keys in the requested cache.
  58975. */
  58976. getKeys: function (cache) {
  58977. if (cache === undefined) { cache = Phaser.Cache.IMAGE; }
  58978. var out = [];
  58979. if (this._cacheMap[cache])
  58980. {
  58981. for (var key in this._cacheMap[cache])
  58982. {
  58983. if (key !== '__default' && key !== '__missing')
  58984. {
  58985. out.push(key);
  58986. }
  58987. }
  58988. }
  58989. return out;
  58990. },
  58991. /////////////////////
  58992. // Remove Methods //
  58993. /////////////////////
  58994. /**
  58995. * Removes a canvas from the cache.
  58996. *
  58997. * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere
  58998. * then it will persist in memory.
  58999. *
  59000. * @method Phaser.Cache#removeCanvas
  59001. * @param {string} key - Key of the asset you want to remove.
  59002. */
  59003. removeCanvas: function (key) {
  59004. delete this._cache.canvas[key];
  59005. },
  59006. /**
  59007. * Removes an image from the cache.
  59008. *
  59009. * You can optionally elect to destroy it as well. This calls BaseTexture.destroy on it.
  59010. *
  59011. * Note that this only removes it from the Phaser Cache. If you still have references to the data elsewhere
  59012. * then it will persist in memory.
  59013. *
  59014. * @method Phaser.Cache#removeImage
  59015. * @param {string} key - Key of the asset you want to remove.
  59016. * @param {boolean} [destroyBaseTexture=true] - Should the BaseTexture behind this image also be destroyed?
  59017. */
  59018. removeImage: function (key, destroyBaseTexture) {
  59019. if (destroyBaseTexture === undefined) { destroyBaseTexture = true; }
  59020. var img = this.getImage(key, true);
  59021. if (destroyBaseTexture && img.base)
  59022. {
  59023. img.base.destroy();
  59024. }
  59025. delete this._cache.image[key];
  59026. },
  59027. /**
  59028. * Removes a sound from the cache.
  59029. *
  59030. * If any `Phaser.Sound` objects use the audio file in the cache that you remove with this method, they will
  59031. * _automatically_ destroy themselves. If you wish to have full control over when Sounds are destroyed then
  59032. * you must finish your house-keeping and destroy them all yourself first, before calling this method.
  59033. *
  59034. * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere
  59035. * then it will persist in memory.
  59036. *
  59037. * @method Phaser.Cache#removeSound
  59038. * @param {string} key - Key of the asset you want to remove.
  59039. */
  59040. removeSound: function (key) {
  59041. delete this._cache.sound[key];
  59042. },
  59043. /**
  59044. * Removes a text file from the cache.
  59045. *
  59046. * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere
  59047. * then it will persist in memory.
  59048. *
  59049. * @method Phaser.Cache#removeText
  59050. * @param {string} key - Key of the asset you want to remove.
  59051. */
  59052. removeText: function (key) {
  59053. delete this._cache.text[key];
  59054. },
  59055. /**
  59056. * Removes a physics data file from the cache.
  59057. *
  59058. * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere
  59059. * then it will persist in memory.
  59060. *
  59061. * @method Phaser.Cache#removePhysics
  59062. * @param {string} key - Key of the asset you want to remove.
  59063. */
  59064. removePhysics: function (key) {
  59065. delete this._cache.physics[key];
  59066. },
  59067. /**
  59068. * Removes a tilemap from the cache.
  59069. *
  59070. * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere
  59071. * then it will persist in memory.
  59072. *
  59073. * @method Phaser.Cache#removeTilemap
  59074. * @param {string} key - Key of the asset you want to remove.
  59075. */
  59076. removeTilemap: function (key) {
  59077. delete this._cache.tilemap[key];
  59078. },
  59079. /**
  59080. * Removes a binary file from the cache.
  59081. *
  59082. * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere
  59083. * then it will persist in memory.
  59084. *
  59085. * @method Phaser.Cache#removeBinary
  59086. * @param {string} key - Key of the asset you want to remove.
  59087. */
  59088. removeBinary: function (key) {
  59089. delete this._cache.binary[key];
  59090. },
  59091. /**
  59092. * Removes a bitmap data from the cache.
  59093. *
  59094. * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere
  59095. * then it will persist in memory.
  59096. *
  59097. * @method Phaser.Cache#removeBitmapData
  59098. * @param {string} key - Key of the asset you want to remove.
  59099. */
  59100. removeBitmapData: function (key) {
  59101. delete this._cache.bitmapData[key];
  59102. },
  59103. /**
  59104. * Removes a bitmap font from the cache.
  59105. *
  59106. * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere
  59107. * then it will persist in memory.
  59108. *
  59109. * @method Phaser.Cache#removeBitmapFont
  59110. * @param {string} key - Key of the asset you want to remove.
  59111. */
  59112. removeBitmapFont: function (key) {
  59113. delete this._cache.bitmapFont[key];
  59114. },
  59115. /**
  59116. * Removes a json object from the cache.
  59117. *
  59118. * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere
  59119. * then it will persist in memory.
  59120. *
  59121. * @method Phaser.Cache#removeJSON
  59122. * @param {string} key - Key of the asset you want to remove.
  59123. */
  59124. removeJSON: function (key) {
  59125. delete this._cache.json[key];
  59126. },
  59127. /**
  59128. * Removes a xml object from the cache.
  59129. *
  59130. * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere
  59131. * then it will persist in memory.
  59132. *
  59133. * @method Phaser.Cache#removeXML
  59134. * @param {string} key - Key of the asset you want to remove.
  59135. */
  59136. removeXML: function (key) {
  59137. delete this._cache.xml[key];
  59138. },
  59139. /**
  59140. * Removes a video from the cache.
  59141. *
  59142. * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere
  59143. * then it will persist in memory.
  59144. *
  59145. * @method Phaser.Cache#removeVideo
  59146. * @param {string} key - Key of the asset you want to remove.
  59147. */
  59148. removeVideo: function (key) {
  59149. delete this._cache.video[key];
  59150. },
  59151. /**
  59152. * Removes a shader from the cache.
  59153. *
  59154. * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere
  59155. * then it will persist in memory.
  59156. *
  59157. * @method Phaser.Cache#removeShader
  59158. * @param {string} key - Key of the asset you want to remove.
  59159. */
  59160. removeShader: function (key) {
  59161. delete this._cache.shader[key];
  59162. },
  59163. /**
  59164. * Removes a Render Texture from the cache.
  59165. *
  59166. * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere
  59167. * then it will persist in memory.
  59168. *
  59169. * @method Phaser.Cache#removeRenderTexture
  59170. * @param {string} key - Key of the asset you want to remove.
  59171. */
  59172. removeRenderTexture: function (key) {
  59173. delete this._cache.renderTexture[key];
  59174. },
  59175. /**
  59176. * Removes a Sprite Sheet from the cache.
  59177. *
  59178. * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere
  59179. * then it will persist in memory.
  59180. *
  59181. * @method Phaser.Cache#removeSpriteSheet
  59182. * @param {string} key - Key of the asset you want to remove.
  59183. */
  59184. removeSpriteSheet: function (key) {
  59185. delete this._cache.spriteSheet[key];
  59186. },
  59187. /**
  59188. * Removes a Texture Atlas from the cache.
  59189. *
  59190. * Note that this only removes it from the Phaser.Cache. If you still have references to the data elsewhere
  59191. * then it will persist in memory.
  59192. *
  59193. * @method Phaser.Cache#removeTextureAtlas
  59194. * @param {string} key - Key of the asset you want to remove.
  59195. */
  59196. removeTextureAtlas: function (key) {
  59197. delete this._cache.atlas[key];
  59198. },
  59199. /**
  59200. * Empties out all of the GL Textures from Images stored in the cache.
  59201. * This is called automatically when the WebGL context is lost and then restored.
  59202. *
  59203. * @method Phaser.Cache#clearGLTextures
  59204. * @protected
  59205. */
  59206. clearGLTextures: function () {
  59207. for (var key in this._cache.image)
  59208. {
  59209. this._cache.image[key].base._glTextures = [];
  59210. }
  59211. },
  59212. /**
  59213. * Resolves a URL to its absolute form and stores it in Cache._urlMap as long as Cache.autoResolveURL is set to `true`.
  59214. * This is then looked-up by the Cache.getURL and Cache.checkURL calls.
  59215. *
  59216. * @method Phaser.Cache#_resolveURL
  59217. * @private
  59218. * @param {string} url - The URL to resolve. This is appended to Loader.baseURL.
  59219. * @param {object} [data] - The data associated with the URL to be stored to the URL Map.
  59220. * @return {string} The resolved URL.
  59221. */
  59222. _resolveURL: function (url, data) {
  59223. if (!this.autoResolveURL)
  59224. {
  59225. return null;
  59226. }
  59227. this._urlResolver.src = this.game.load.baseURL + url;
  59228. this._urlTemp = this._urlResolver.src;
  59229. // Ensure no request is actually made
  59230. this._urlResolver.src = '';
  59231. // Record the URL to the map
  59232. if (data)
  59233. {
  59234. this._urlMap[this._urlTemp] = data;
  59235. }
  59236. return this._urlTemp;
  59237. },
  59238. /**
  59239. * Clears the cache. Removes every local cache object reference.
  59240. * If an object in the cache has a `destroy` method it will also be called.
  59241. *
  59242. * @method Phaser.Cache#destroy
  59243. */
  59244. destroy: function () {
  59245. for (var i = 0; i < this._cacheMap.length; i++)
  59246. {
  59247. var cache = this._cacheMap[i];
  59248. for (var key in cache)
  59249. {
  59250. if (key !== '__default' && key !== '__missing')
  59251. {
  59252. if (cache[key]['destroy'])
  59253. {
  59254. cache[key].destroy();
  59255. }
  59256. delete cache[key];
  59257. }
  59258. }
  59259. }
  59260. this._urlMap = null;
  59261. this._urlResolver = null;
  59262. this._urlTemp = null;
  59263. }
  59264. };
  59265. Phaser.Cache.prototype.constructor = Phaser.Cache;
  59266. /* jshint wsh:true */
  59267. /**
  59268. * @author Richard Davey <rich@photonstorm.com>
  59269. * @copyright 2016 Photon Storm Ltd.
  59270. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  59271. */
  59272. /**
  59273. * The Loader handles loading all external content such as Images, Sounds, Texture Atlases and data files.
  59274. *
  59275. * The loader uses a combination of tag loading (eg. Image elements) and XHR and provides progress and completion callbacks.
  59276. *
  59277. * Parallel loading (see {@link #enableParallel}) is supported and enabled by default.
  59278. * Load-before behavior of parallel resources is controlled by synchronization points as discussed in {@link #withSyncPoint}.
  59279. *
  59280. * Texture Atlases can be created with tools such as [Texture Packer](https://www.codeandweb.com/texturepacker/phaser) and
  59281. * [Shoebox](http://renderhjs.net/shoebox/)
  59282. *
  59283. * @class Phaser.Loader
  59284. * @param {Phaser.Game} game - A reference to the currently running game.
  59285. */
  59286. Phaser.Loader = function (game) {
  59287. /**
  59288. * Local reference to game.
  59289. * @property {Phaser.Game} game
  59290. * @protected
  59291. */
  59292. this.game = game;
  59293. /**
  59294. * Local reference to the Phaser.Cache.
  59295. * @property {Phaser.Cache} cache
  59296. * @protected
  59297. */
  59298. this.cache = game.cache;
  59299. /**
  59300. * If true all calls to Loader.reset will be ignored. Useful if you need to create a load queue before swapping to a preloader state.
  59301. * @property {boolean} resetLocked
  59302. * @default
  59303. */
  59304. this.resetLocked = false;
  59305. /**
  59306. * True if the Loader is in the process of loading the queue.
  59307. * @property {boolean} isLoading
  59308. * @default
  59309. */
  59310. this.isLoading = false;
  59311. /**
  59312. * True if all assets in the queue have finished loading.
  59313. * @property {boolean} hasLoaded
  59314. * @default
  59315. */
  59316. this.hasLoaded = false;
  59317. /**
  59318. * You can optionally link a progress sprite with {@link Phaser.Loader#setPreloadSprite setPreloadSprite}.
  59319. *
  59320. * This property is an object containing: sprite, rect, direction, width and height
  59321. *
  59322. * @property {?object} preloadSprite
  59323. * @protected
  59324. */
  59325. this.preloadSprite = null;
  59326. /**
  59327. * The crossOrigin value applied to loaded images. Very often this needs to be set to 'anonymous'.
  59328. * @property {boolean|string} crossOrigin
  59329. * @default
  59330. */
  59331. this.crossOrigin = false;
  59332. /**
  59333. * If you want to append a URL before the path of any asset you can set this here.
  59334. * Useful if allowing the asset base url to be configured outside of the game code.
  59335. * The string _must_ end with a "/".
  59336. *
  59337. * @property {string} baseURL
  59338. */
  59339. this.baseURL = '';
  59340. /**
  59341. * The value of `path`, if set, is placed before any _relative_ file path given. For example:
  59342. *
  59343. * `load.path = "images/sprites/";
  59344. * load.image("ball", "ball.png");
  59345. * load.image("tree", "level1/oaktree.png");
  59346. * load.image("boom", "http://server.com/explode.png");`
  59347. *
  59348. * Would load the `ball` file from `images/sprites/ball.png` and the tree from
  59349. * `images/sprites/level1/oaktree.png` but the file `boom` would load from the URL
  59350. * given as it's an absolute URL.
  59351. *
  59352. * Please note that the path is added before the filename but *after* the baseURL (if set.)
  59353. *
  59354. * The string _must_ end with a "/".
  59355. *
  59356. * @property {string} path
  59357. */
  59358. this.path = '';
  59359. /**
  59360. * Used to map the application mime-types to to the Accept header in XHR requests.
  59361. * If you don't require these mappings, or they cause problems on your server, then
  59362. * remove them from the headers object and the XHR request will not try to use them.
  59363. *
  59364. * This object can also be used to set the `X-Requested-With` header to
  59365. * `XMLHttpRequest` (or any other value you need). To enable this do:
  59366. *
  59367. * `this.load.headers.requestedWith = 'XMLHttpRequest'`
  59368. *
  59369. * before adding anything to the Loader. The XHR loader will then call:
  59370. *
  59371. * `setRequestHeader('X-Requested-With', this.headers['requestedWith'])`
  59372. *
  59373. * @property {object} headers
  59374. * @default
  59375. */
  59376. this.headers = {
  59377. "requestedWith": false,
  59378. "json": "application/json",
  59379. "xml": "application/xml"
  59380. };
  59381. /**
  59382. * This event is dispatched when the loading process starts: before the first file has been requested,
  59383. * but after all the initial packs have been loaded.
  59384. *
  59385. * @property {Phaser.Signal} onLoadStart
  59386. */
  59387. this.onLoadStart = new Phaser.Signal();
  59388. /**
  59389. * This event is dispatched when the final file in the load queue has either loaded or failed.
  59390. *
  59391. * @property {Phaser.Signal} onLoadComplete
  59392. */
  59393. this.onLoadComplete = new Phaser.Signal();
  59394. /**
  59395. * This event is dispatched when an asset pack has either loaded or failed to load.
  59396. *
  59397. * This is called when the asset pack manifest file has loaded and successfully added its contents to the loader queue.
  59398. *
  59399. * Params: `(pack key, success?, total packs loaded, total packs)`
  59400. *
  59401. * @property {Phaser.Signal} onPackComplete
  59402. */
  59403. this.onPackComplete = new Phaser.Signal();
  59404. /**
  59405. * This event is dispatched immediately before a file starts loading.
  59406. * It's possible the file may fail (eg. download error, invalid format) after this event is sent.
  59407. *
  59408. * Params: `(progress, file key, file url)`
  59409. *
  59410. * @property {Phaser.Signal} onFileStart
  59411. */
  59412. this.onFileStart = new Phaser.Signal();
  59413. /**
  59414. * This event is dispatched when a file has either loaded or failed to load.
  59415. *
  59416. * Any function bound to this will receive the following parameters:
  59417. *
  59418. * progress, file key, success?, total loaded files, total files
  59419. *
  59420. * Where progress is a number between 1 and 100 (inclusive) representing the percentage of the load.
  59421. *
  59422. * @property {Phaser.Signal} onFileComplete
  59423. */
  59424. this.onFileComplete = new Phaser.Signal();
  59425. /**
  59426. * This event is dispatched when a file (or pack) errors as a result of the load request.
  59427. *
  59428. * For files it will be triggered before `onFileComplete`. For packs it will be triggered before `onPackComplete`.
  59429. *
  59430. * Params: `(file key, file)`
  59431. *
  59432. * @property {Phaser.Signal} onFileError
  59433. */
  59434. this.onFileError = new Phaser.Signal();
  59435. /**
  59436. * If true and if the browser supports XDomainRequest, it will be used in preference for XHR.
  59437. *
  59438. * This is only relevant for IE 9 and should _only_ be enabled for IE 9 clients when required by the server/CDN.
  59439. *
  59440. * @property {boolean} useXDomainRequest
  59441. * @deprecated This is only relevant for IE 9.
  59442. */
  59443. this.useXDomainRequest = false;
  59444. /**
  59445. * @private
  59446. * @property {boolean} _warnedAboutXDomainRequest - Control number of warnings for using XDR outside of IE 9.
  59447. */
  59448. this._warnedAboutXDomainRequest = false;
  59449. /**
  59450. * If true (the default) then parallel downloading will be enabled.
  59451. *
  59452. * To disable all parallel downloads this must be set to false prior to any resource being loaded.
  59453. *
  59454. * @property {boolean} enableParallel
  59455. */
  59456. this.enableParallel = true;
  59457. /**
  59458. * The number of concurrent / parallel resources to try and fetch at once.
  59459. *
  59460. * Many current browsers limit 6 requests per domain; this is slightly conservative.
  59461. *
  59462. * @property {integer} maxParallelDownloads
  59463. * @protected
  59464. */
  59465. this.maxParallelDownloads = 4;
  59466. /**
  59467. * A counter: if more than zero, files will be automatically added as a synchronization point.
  59468. * @property {integer} _withSyncPointDepth;
  59469. */
  59470. this._withSyncPointDepth = 0;
  59471. /**
  59472. * Contains all the information for asset files (including packs) to load.
  59473. *
  59474. * File/assets are only removed from the list after all loading completes.
  59475. *
  59476. * @property {file[]} _fileList
  59477. * @private
  59478. */
  59479. this._fileList = [];
  59480. /**
  59481. * Inflight files (or packs) that are being fetched/processed.
  59482. *
  59483. * This means that if there are any files in the flight queue there should still be processing
  59484. * going on; it should only be empty before or after loading.
  59485. *
  59486. * The files in the queue may have additional properties added to them,
  59487. * including `requestObject` which is normally the associated XHR.
  59488. *
  59489. * @property {file[]} _flightQueue
  59490. * @private
  59491. */
  59492. this._flightQueue = [];
  59493. /**
  59494. * The offset into the fileList past all the complete (loaded or error) entries.
  59495. *
  59496. * @property {integer} _processingHead
  59497. * @private
  59498. */
  59499. this._processingHead = 0;
  59500. /**
  59501. * True when the first file (not pack) has loading started.
  59502. * This used to to control dispatching `onLoadStart` which happens after any initial packs are loaded.
  59503. *
  59504. * @property {boolean} _initialPacksLoaded
  59505. * @private
  59506. */
  59507. this._fileLoadStarted = false;
  59508. /**
  59509. * Total packs seen - adjusted when a pack is added.
  59510. * @property {integer} _totalPackCount
  59511. * @private
  59512. */
  59513. this._totalPackCount = 0;
  59514. /**
  59515. * Total files seen - adjusted when a file is added.
  59516. * @property {integer} _totalFileCount
  59517. * @private
  59518. */
  59519. this._totalFileCount = 0;
  59520. /**
  59521. * Total packs loaded - adjusted just prior to `onPackComplete`.
  59522. * @property {integer} _loadedPackCount
  59523. * @private
  59524. */
  59525. this._loadedPackCount = 0;
  59526. /**
  59527. * Total files loaded - adjusted just prior to `onFileComplete`.
  59528. * @property {integer} _loadedFileCount
  59529. * @private
  59530. */
  59531. this._loadedFileCount = 0;
  59532. };
  59533. /**
  59534. * @constant
  59535. * @type {number}
  59536. */
  59537. Phaser.Loader.TEXTURE_ATLAS_JSON_ARRAY = 0;
  59538. /**
  59539. * @constant
  59540. * @type {number}
  59541. */
  59542. Phaser.Loader.TEXTURE_ATLAS_JSON_HASH = 1;
  59543. /**
  59544. * @constant
  59545. * @type {number}
  59546. */
  59547. Phaser.Loader.TEXTURE_ATLAS_XML_STARLING = 2;
  59548. /**
  59549. * @constant
  59550. * @type {number}
  59551. */
  59552. Phaser.Loader.PHYSICS_LIME_CORONA_JSON = 3;
  59553. /**
  59554. * @constant
  59555. * @type {number}
  59556. */
  59557. Phaser.Loader.PHYSICS_PHASER_JSON = 4;
  59558. /**
  59559. * @constant
  59560. * @type {number}
  59561. */
  59562. Phaser.Loader.TEXTURE_ATLAS_JSON_PYXEL = 5;
  59563. Phaser.Loader.prototype = {
  59564. /**
  59565. * Set a Sprite to be a "preload" sprite by passing it to this method.
  59566. *
  59567. * A "preload" sprite will have its width or height crop adjusted based on the percentage of the loader in real-time.
  59568. * This allows you to easily make loading bars for games.
  59569. *
  59570. * The sprite will automatically be made visible when calling this.
  59571. *
  59572. * @method Phaser.Loader#setPreloadSprite
  59573. * @param {Phaser.Sprite|Phaser.Image} sprite - The sprite or image that will be cropped during the load.
  59574. * @param {number} [direction=0] - A value of zero means the sprite will be cropped horizontally, a value of 1 means its will be cropped vertically.
  59575. */
  59576. setPreloadSprite: function (sprite, direction) {
  59577. direction = direction || 0;
  59578. this.preloadSprite = { sprite: sprite, direction: direction, width: sprite.width, height: sprite.height, rect: null };
  59579. if (direction === 0)
  59580. {
  59581. // Horizontal rect
  59582. this.preloadSprite.rect = new Phaser.Rectangle(0, 0, 1, sprite.height);
  59583. }
  59584. else
  59585. {
  59586. // Vertical rect
  59587. this.preloadSprite.rect = new Phaser.Rectangle(0, 0, sprite.width, 1);
  59588. }
  59589. sprite.crop(this.preloadSprite.rect);
  59590. sprite.visible = true;
  59591. },
  59592. /**
  59593. * Called automatically by ScaleManager when the game resizes in RESIZE scalemode.
  59594. *
  59595. * This can be used to adjust the preloading sprite size, eg.
  59596. *
  59597. * @method Phaser.Loader#resize
  59598. * @protected
  59599. */
  59600. resize: function () {
  59601. if (this.preloadSprite && this.preloadSprite.height !== this.preloadSprite.sprite.height)
  59602. {
  59603. this.preloadSprite.rect.height = this.preloadSprite.sprite.height;
  59604. }
  59605. },
  59606. /**
  59607. * Check whether a file/asset with a specific key is queued to be loaded.
  59608. *
  59609. * To access a loaded asset use Phaser.Cache, eg. {@link Phaser.Cache#checkImageKey}
  59610. *
  59611. * @method Phaser.Loader#checkKeyExists
  59612. * @param {string} type - The type asset you want to check.
  59613. * @param {string} key - Key of the asset you want to check.
  59614. * @return {boolean} Return true if exists, otherwise return false.
  59615. */
  59616. checkKeyExists: function (type, key) {
  59617. return this.getAssetIndex(type, key) > -1;
  59618. },
  59619. /**
  59620. * Get the queue-index of the file/asset with a specific key.
  59621. *
  59622. * Only assets in the download file queue will be found.
  59623. *
  59624. * @method Phaser.Loader#getAssetIndex
  59625. * @param {string} type - The type asset you want to check.
  59626. * @param {string} key - Key of the asset you want to check.
  59627. * @return {number} The index of this key in the filelist, or -1 if not found.
  59628. * The index may change and should only be used immediately following this call
  59629. */
  59630. getAssetIndex: function (type, key) {
  59631. var bestFound = -1;
  59632. for (var i = 0; i < this._fileList.length; i++)
  59633. {
  59634. var file = this._fileList[i];
  59635. if (file.type === type && file.key === key)
  59636. {
  59637. bestFound = i;
  59638. // An already loaded/loading file may be superceded.
  59639. if (!file.loaded && !file.loading)
  59640. {
  59641. break;
  59642. }
  59643. }
  59644. }
  59645. return bestFound;
  59646. },
  59647. /**
  59648. * Find a file/asset with a specific key.
  59649. *
  59650. * Only assets in the download file queue will be found.
  59651. *
  59652. * @method Phaser.Loader#getAsset
  59653. * @param {string} type - The type asset you want to check.
  59654. * @param {string} key - Key of the asset you want to check.
  59655. * @return {any} Returns an object if found that has 2 properties: `index` and `file`; otherwise a non-true value is returned.
  59656. * The index may change and should only be used immediately following this call.
  59657. */
  59658. getAsset: function (type, key) {
  59659. var fileIndex = this.getAssetIndex(type, key);
  59660. if (fileIndex > -1)
  59661. {
  59662. return { index: fileIndex, file: this._fileList[fileIndex] };
  59663. }
  59664. return false;
  59665. },
  59666. /**
  59667. * Reset the loader and clear any queued assets. If `Loader.resetLocked` is true this operation will abort.
  59668. *
  59669. * This will abort any loading and clear any queued assets.
  59670. *
  59671. * Optionally you can clear any associated events.
  59672. *
  59673. * @method Phaser.Loader#reset
  59674. * @protected
  59675. * @param {boolean} [hard=false] - If true then the preload sprite and other artifacts may also be cleared.
  59676. * @param {boolean} [clearEvents=false] - If true then the all Loader signals will have removeAll called on them.
  59677. */
  59678. reset: function (hard, clearEvents) {
  59679. if (clearEvents === undefined) { clearEvents = false; }
  59680. if (this.resetLocked)
  59681. {
  59682. return;
  59683. }
  59684. if (hard)
  59685. {
  59686. this.preloadSprite = null;
  59687. }
  59688. this.isLoading = false;
  59689. this._processingHead = 0;
  59690. this._fileList.length = 0;
  59691. this._flightQueue.length = 0;
  59692. this._fileLoadStarted = false;
  59693. this._totalFileCount = 0;
  59694. this._totalPackCount = 0;
  59695. this._loadedPackCount = 0;
  59696. this._loadedFileCount = 0;
  59697. if (clearEvents)
  59698. {
  59699. this.onLoadStart.removeAll();
  59700. this.onLoadComplete.removeAll();
  59701. this.onPackComplete.removeAll();
  59702. this.onFileStart.removeAll();
  59703. this.onFileComplete.removeAll();
  59704. this.onFileError.removeAll();
  59705. }
  59706. },
  59707. /**
  59708. * Internal function that adds a new entry to the file list. Do not call directly.
  59709. *
  59710. * @method Phaser.Loader#addToFileList
  59711. * @protected
  59712. * @param {string} type - The type of resource to add to the list (image, audio, xml, etc).
  59713. * @param {string} key - The unique Cache ID key of this resource.
  59714. * @param {string} [url] - The URL the asset will be loaded from.
  59715. * @param {object} [properties=(none)] - Any additional properties needed to load the file. These are added directly to the added file object and overwrite any defaults.
  59716. * @param {boolean} [overwrite=false] - If true then this will overwrite a file asset of the same type/key. Otherwise it will only add a new asset. If overwrite is true, and the asset is already being loaded (or has been loaded), then it is appended instead.
  59717. * @param {string} [extension] - If no URL is given the Loader will sometimes auto-generate the URL based on the key, using this as the extension.
  59718. * @return {Phaser.Loader} This instance of the Phaser Loader.
  59719. */
  59720. addToFileList: function (type, key, url, properties, overwrite, extension) {
  59721. if (overwrite === undefined) { overwrite = false; }
  59722. if (key === undefined || key === '')
  59723. {
  59724. console.warn("Phaser.Loader: Invalid or no key given of type " + type);
  59725. return this;
  59726. }
  59727. if (url === undefined || url === null)
  59728. {
  59729. if (extension)
  59730. {
  59731. url = key + extension;
  59732. }
  59733. else
  59734. {
  59735. console.warn("Phaser.Loader: No URL given for file type: " + type + " key: " + key);
  59736. return this;
  59737. }
  59738. }
  59739. var file = {
  59740. type: type,
  59741. key: key,
  59742. path: this.path,
  59743. url: url,
  59744. syncPoint: this._withSyncPointDepth > 0,
  59745. data: null,
  59746. loading: false,
  59747. loaded: false,
  59748. error: false
  59749. };
  59750. if (properties)
  59751. {
  59752. for (var prop in properties)
  59753. {
  59754. file[prop] = properties[prop];
  59755. }
  59756. }
  59757. var fileIndex = this.getAssetIndex(type, key);
  59758. if (overwrite && fileIndex > -1)
  59759. {
  59760. var currentFile = this._fileList[fileIndex];
  59761. if (!currentFile.loading && !currentFile.loaded)
  59762. {
  59763. this._fileList[fileIndex] = file;
  59764. }
  59765. else
  59766. {
  59767. this._fileList.push(file);
  59768. this._totalFileCount++;
  59769. }
  59770. }
  59771. else if (fileIndex === -1)
  59772. {
  59773. this._fileList.push(file);
  59774. this._totalFileCount++;
  59775. }
  59776. return this;
  59777. },
  59778. /**
  59779. * Internal function that replaces an existing entry in the file list with a new one. Do not call directly.
  59780. *
  59781. * @method Phaser.Loader#replaceInFileList
  59782. * @protected
  59783. * @param {string} type - The type of resource to add to the list (image, audio, xml, etc).
  59784. * @param {string} key - The unique Cache ID key of this resource.
  59785. * @param {string} url - The URL the asset will be loaded from.
  59786. * @param {object} properties - Any additional properties needed to load the file.
  59787. */
  59788. replaceInFileList: function (type, key, url, properties) {
  59789. return this.addToFileList(type, key, url, properties, true);
  59790. },
  59791. /**
  59792. * Add a JSON resource pack ('packfile') to the Loader.
  59793. *
  59794. * A packfile is a JSON file that contains a list of assets to the be loaded.
  59795. * Please see the example 'loader/asset pack' in the Phaser Examples repository.
  59796. *
  59797. * Packs are always put before the first non-pack file that is not loaded / loading.
  59798. *
  59799. * This means that all packs added before any loading has started are added to the front
  59800. * of the file queue, in the order added.
  59801. *
  59802. * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load.
  59803. *
  59804. * The URL of the packfile can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it.
  59805. *
  59806. * @method Phaser.Loader#pack
  59807. * @param {string} key - Unique asset key of this resource pack.
  59808. * @param {string} [url] - URL of the Asset Pack JSON file. If you wish to pass a json object instead set this to null and pass the object as the data parameter.
  59809. * @param {object} [data] - The Asset Pack JSON data. Use this to pass in a json data object rather than loading it from a URL. TODO
  59810. * @param {object} [callbackContext=(loader)] - Some Loader operations, like Binary and Script require a context for their callbacks. Pass the context here.
  59811. * @return {Phaser.Loader} This Loader instance.
  59812. */
  59813. pack: function (key, url, data, callbackContext) {
  59814. if (url === undefined) { url = null; }
  59815. if (data === undefined) { data = null; }
  59816. if (callbackContext === undefined) { callbackContext = null; }
  59817. if (!url && !data)
  59818. {
  59819. console.warn('Phaser.Loader.pack - Both url and data are null. One must be set.');
  59820. return this;
  59821. }
  59822. var pack = {
  59823. type: 'packfile',
  59824. key: key,
  59825. url: url,
  59826. path: this.path,
  59827. syncPoint: true,
  59828. data: null,
  59829. loading: false,
  59830. loaded: false,
  59831. error: false,
  59832. callbackContext: callbackContext
  59833. };
  59834. // A data object has been given
  59835. if (data)
  59836. {
  59837. if (typeof data === 'string')
  59838. {
  59839. data = JSON.parse(data);
  59840. }
  59841. pack.data = data || {};
  59842. // Already consider 'loaded'
  59843. pack.loaded = true;
  59844. }
  59845. // Add before first non-pack/no-loaded ~ last pack from start prior to loading
  59846. // (Read one past for splice-to-end)
  59847. for (var i = 0; i < this._fileList.length + 1; i++)
  59848. {
  59849. var file = this._fileList[i];
  59850. if (!file || (!file.loaded && !file.loading && file.type !== 'packfile'))
  59851. {
  59852. this._fileList.splice(i, 0, pack);
  59853. this._totalPackCount++;
  59854. break;
  59855. }
  59856. }
  59857. return this;
  59858. },
  59859. /**
  59860. * Adds an Image to the current load queue.
  59861. *
  59862. * The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts.
  59863. *
  59864. * Phaser can load all common image types: png, jpg, gif and any other format the browser can natively handle.
  59865. *
  59866. * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load.
  59867. *
  59868. * Retrieve the image via `Cache.getImage(key)`
  59869. *
  59870. * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it.
  59871. *
  59872. * If the URL isn't specified the Loader will take the key and create a filename from that. For example if the key is "alien"
  59873. * and no URL is given then the Loader will set the URL to be "alien.png". It will always add `.png` as the extension.
  59874. * If you do not desire this action then provide a URL.
  59875. *
  59876. * @method Phaser.Loader#image
  59877. * @param {string} key - Unique asset key of this image file.
  59878. * @param {string} [url] - URL of an image file. If undefined or `null` the url will be set to `<key>.png`, i.e. if `key` was "alien" then the URL will be "alien.png".
  59879. * @param {boolean} [overwrite=false] - If an unloaded file with a matching key already exists in the queue, this entry will overwrite it.
  59880. * @return {Phaser.Loader} This Loader instance.
  59881. */
  59882. image: function (key, url, overwrite) {
  59883. return this.addToFileList('image', key, url, undefined, overwrite, '.png');
  59884. },
  59885. /**
  59886. * Adds an array of images to the current load queue.
  59887. *
  59888. * It works by passing each element of the array to the Loader.image method.
  59889. *
  59890. * The files are **not** loaded immediately after calling this method. The files are added to the queue ready to be loaded when the loader starts.
  59891. *
  59892. * Phaser can load all common image types: png, jpg, gif and any other format the browser can natively handle.
  59893. *
  59894. * The keys must be unique Strings. They are used to add the files to the Phaser.Cache upon successful load.
  59895. *
  59896. * Retrieve the images via `Cache.getImage(key)`
  59897. *
  59898. * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it.
  59899. *
  59900. * If the URL isn't specified the Loader will take the key and create a filename from that. For example if the key is "alien"
  59901. * and no URL is given then the Loader will set the URL to be "alien.png". It will always add `.png` as the extension.
  59902. * If you do not desire this action then provide a URL.
  59903. *
  59904. * @method Phaser.Loader#images
  59905. * @param {array} keys - An array of unique asset keys of the image files.
  59906. * @param {array} [urls] - Optional array of URLs. If undefined or `null` the url will be set to `<key>.png`, i.e. if `key` was "alien" then the URL will be "alien.png". If provided the URLs array length must match the keys array length.
  59907. * @return {Phaser.Loader} This Loader instance.
  59908. */
  59909. images: function (keys, urls) {
  59910. if (Array.isArray(urls))
  59911. {
  59912. for (var i = 0; i < keys.length; i++)
  59913. {
  59914. this.image(keys[i], urls[i]);
  59915. }
  59916. }
  59917. else
  59918. {
  59919. for (var i = 0; i < keys.length; i++)
  59920. {
  59921. this.image(keys[i]);
  59922. }
  59923. }
  59924. return this;
  59925. },
  59926. /**
  59927. * Adds a Text file to the current load queue.
  59928. *
  59929. * The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts.
  59930. *
  59931. * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load.
  59932. *
  59933. * Retrieve the file via `Cache.getText(key)`
  59934. *
  59935. * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it.
  59936. *
  59937. * If the URL isn't specified the Loader will take the key and create a filename from that. For example if the key is "alien"
  59938. * and no URL is given then the Loader will set the URL to be "alien.txt". It will always add `.txt` as the extension.
  59939. * If you do not desire this action then provide a URL.
  59940. *
  59941. * @method Phaser.Loader#text
  59942. * @param {string} key - Unique asset key of the text file.
  59943. * @param {string} [url] - URL of the text file. If undefined or `null` the url will be set to `<key>.txt`, i.e. if `key` was "alien" then the URL will be "alien.txt".
  59944. * @param {boolean} [overwrite=false] - If an unloaded file with a matching key already exists in the queue, this entry will overwrite it.
  59945. * @return {Phaser.Loader} This Loader instance.
  59946. */
  59947. text: function (key, url, overwrite) {
  59948. return this.addToFileList('text', key, url, undefined, overwrite, '.txt');
  59949. },
  59950. /**
  59951. * Adds a JSON file to the current load queue.
  59952. *
  59953. * The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts.
  59954. *
  59955. * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load.
  59956. *
  59957. * Retrieve the file via `Cache.getJSON(key)`. JSON files are automatically parsed upon load.
  59958. * If you need to control when the JSON is parsed then use `Loader.text` instead and parse the text file as needed.
  59959. *
  59960. * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it.
  59961. *
  59962. * If the URL isn't specified the Loader will take the key and create a filename from that. For example if the key is "alien"
  59963. * and no URL is given then the Loader will set the URL to be "alien.json". It will always add `.json` as the extension.
  59964. * If you do not desire this action then provide a URL.
  59965. *
  59966. * @method Phaser.Loader#json
  59967. * @param {string} key - Unique asset key of the json file.
  59968. * @param {string} [url] - URL of the JSON file. If undefined or `null` the url will be set to `<key>.json`, i.e. if `key` was "alien" then the URL will be "alien.json".
  59969. * @param {boolean} [overwrite=false] - If an unloaded file with a matching key already exists in the queue, this entry will overwrite it.
  59970. * @return {Phaser.Loader} This Loader instance.
  59971. */
  59972. json: function (key, url, overwrite) {
  59973. return this.addToFileList('json', key, url, undefined, overwrite, '.json');
  59974. },
  59975. /**
  59976. * Adds a fragment shader file to the current load queue.
  59977. *
  59978. * The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts.
  59979. *
  59980. * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load.
  59981. *
  59982. * Retrieve the file via `Cache.getShader(key)`.
  59983. *
  59984. * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it.
  59985. *
  59986. * If the URL isn't specified the Loader will take the key and create a filename from that. For example if the key is "blur"
  59987. * and no URL is given then the Loader will set the URL to be "blur.frag". It will always add `.frag` as the extension.
  59988. * If you do not desire this action then provide a URL.
  59989. *
  59990. * @method Phaser.Loader#shader
  59991. * @param {string} key - Unique asset key of the fragment file.
  59992. * @param {string} [url] - URL of the fragment file. If undefined or `null` the url will be set to `<key>.frag`, i.e. if `key` was "blur" then the URL will be "blur.frag".
  59993. * @param {boolean} [overwrite=false] - If an unloaded file with a matching key already exists in the queue, this entry will overwrite it.
  59994. * @return {Phaser.Loader} This Loader instance.
  59995. */
  59996. shader: function (key, url, overwrite) {
  59997. return this.addToFileList('shader', key, url, undefined, overwrite, '.frag');
  59998. },
  59999. /**
  60000. * Adds an XML file to the current load queue.
  60001. *
  60002. * The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts.
  60003. *
  60004. * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load.
  60005. *
  60006. * Retrieve the file via `Cache.getXML(key)`.
  60007. *
  60008. * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it.
  60009. *
  60010. * If the URL isn't specified the Loader will take the key and create a filename from that. For example if the key is "alien"
  60011. * and no URL is given then the Loader will set the URL to be "alien.xml". It will always add `.xml` as the extension.
  60012. * If you do not desire this action then provide a URL.
  60013. *
  60014. * @method Phaser.Loader#xml
  60015. * @param {string} key - Unique asset key of the xml file.
  60016. * @param {string} [url] - URL of the XML file. If undefined or `null` the url will be set to `<key>.xml`, i.e. if `key` was "alien" then the URL will be "alien.xml".
  60017. * @param {boolean} [overwrite=false] - If an unloaded file with a matching key already exists in the queue, this entry will overwrite it.
  60018. * @return {Phaser.Loader} This Loader instance.
  60019. */
  60020. xml: function (key, url, overwrite) {
  60021. return this.addToFileList('xml', key, url, undefined, overwrite, '.xml');
  60022. },
  60023. /**
  60024. * Adds a JavaScript file to the current load queue.
  60025. *
  60026. * The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts.
  60027. *
  60028. * The key must be a unique String.
  60029. *
  60030. * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it.
  60031. *
  60032. * If the URL isn't specified the Loader will take the key and create a filename from that. For example if the key is "alien"
  60033. * and no URL is given then the Loader will set the URL to be "alien.js". It will always add `.js` as the extension.
  60034. * If you do not desire this action then provide a URL.
  60035. *
  60036. * Upon successful load the JavaScript is automatically turned into a script tag and executed, so be careful what you load!
  60037. *
  60038. * A callback, which will be invoked as the script tag has been created, can also be specified.
  60039. * The callback must return relevant `data`.
  60040. *
  60041. * @method Phaser.Loader#script
  60042. * @param {string} key - Unique asset key of the script file.
  60043. * @param {string} [url] - URL of the JavaScript file. If undefined or `null` the url will be set to `<key>.js`, i.e. if `key` was "alien" then the URL will be "alien.js".
  60044. * @param {function} [callback=(none)] - Optional callback that will be called after the script tag has loaded, so you can perform additional processing.
  60045. * @param {object} [callbackContext=(loader)] - The context under which the callback will be applied. If not specified it will use the Phaser Loader as the context.
  60046. * @return {Phaser.Loader} This Loader instance.
  60047. */
  60048. script: function (key, url, callback, callbackContext) {
  60049. if (callback === undefined) { callback = false; }
  60050. if (callback !== false && callbackContext === undefined) { callbackContext = this; }
  60051. return this.addToFileList('script', key, url, { syncPoint: true, callback: callback, callbackContext: callbackContext }, false, '.js');
  60052. },
  60053. /**
  60054. * Adds a binary file to the current load queue.
  60055. *
  60056. * The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts.
  60057. *
  60058. * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load.
  60059. *
  60060. * Retrieve the file via `Cache.getBinary(key)`.
  60061. *
  60062. * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it.
  60063. *
  60064. * If the URL isn't specified the Loader will take the key and create a filename from that. For example if the key is "alien"
  60065. * and no URL is given then the Loader will set the URL to be "alien.bin". It will always add `.bin` as the extension.
  60066. * If you do not desire this action then provide a URL.
  60067. *
  60068. * It will be loaded via xhr with a responseType of "arraybuffer". You can specify an optional callback to process the file after load.
  60069. * When the callback is called it will be passed 2 parameters: the key of the file and the file data.
  60070. *
  60071. * WARNING: If a callback is specified the data will be set to whatever it returns. Always return the data object, even if you didn't modify it.
  60072. *
  60073. * @method Phaser.Loader#binary
  60074. * @param {string} key - Unique asset key of the binary file.
  60075. * @param {string} [url] - URL of the binary file. If undefined or `null` the url will be set to `<key>.bin`, i.e. if `key` was "alien" then the URL will be "alien.bin".
  60076. * @param {function} [callback=(none)] - Optional callback that will be passed the file after loading, so you can perform additional processing on it.
  60077. * @param {object} [callbackContext] - The context under which the callback will be applied. If not specified it will use the callback itself as the context.
  60078. * @return {Phaser.Loader} This Loader instance.
  60079. */
  60080. binary: function (key, url, callback, callbackContext) {
  60081. if (callback === undefined) { callback = false; }
  60082. // Why is the default callback context the ..callback?
  60083. if (callback !== false && callbackContext === undefined) { callbackContext = callback; }
  60084. return this.addToFileList('binary', key, url, { callback: callback, callbackContext: callbackContext }, false, '.bin');
  60085. },
  60086. /**
  60087. * Adds a Sprite Sheet to the current load queue.
  60088. *
  60089. * The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts.
  60090. *
  60091. * To clarify the terminology that Phaser uses: A Sprite Sheet is an image containing frames, usually of an animation, that are all equal
  60092. * dimensions and often in sequence. For example if the frame size is 32x32 then every frame in the sprite sheet will be that size.
  60093. * Sometimes (outside of Phaser) the term "sprite sheet" is used to refer to a texture atlas.
  60094. * A Texture Atlas works by packing together images as best it can, using whatever frame sizes it likes, often with cropping and trimming
  60095. * the frames in the process. Software such as Texture Packer, Flash CC or Shoebox all generate texture atlases, not sprite sheets.
  60096. * If you've got an atlas then use `Loader.atlas` instead.
  60097. *
  60098. * The key must be a unique String. It is used to add the image to the Phaser.Cache upon successful load.
  60099. *
  60100. * Retrieve the file via `Cache.getImage(key)`. Sprite sheets, being image based, live in the same Cache as all other Images.
  60101. *
  60102. * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it.
  60103. *
  60104. * If the URL isn't specified the Loader will take the key and create a filename from that. For example if the key is "alien"
  60105. * and no URL is given then the Loader will set the URL to be "alien.png". It will always add `.png` as the extension.
  60106. * If you do not desire this action then provide a URL.
  60107. *
  60108. * @method Phaser.Loader#spritesheet
  60109. * @param {string} key - Unique asset key of the sheet file.
  60110. * @param {string} url - URL of the sprite sheet file. If undefined or `null` the url will be set to `<key>.png`, i.e. if `key` was "alien" then the URL will be "alien.png".
  60111. * @param {number} frameWidth - Width in pixels of a single frame in the sprite sheet.
  60112. * @param {number} frameHeight - Height in pixels of a single frame in the sprite sheet.
  60113. * @param {number} [frameMax=-1] - How many frames in this sprite sheet. If not specified it will divide the whole image into frames.
  60114. * @param {number} [margin=0] - If the frames have been drawn with a margin, specify the amount here.
  60115. * @param {number} [spacing=0] - If the frames have been drawn with spacing between them, specify the amount here.
  60116. * @return {Phaser.Loader} This Loader instance.
  60117. */
  60118. spritesheet: function (key, url, frameWidth, frameHeight, frameMax, margin, spacing) {
  60119. if (frameMax === undefined) { frameMax = -1; }
  60120. if (margin === undefined) { margin = 0; }
  60121. if (spacing === undefined) { spacing = 0; }
  60122. return this.addToFileList('spritesheet', key, url, { frameWidth: frameWidth, frameHeight: frameHeight, frameMax: frameMax, margin: margin, spacing: spacing }, false, '.png');
  60123. },
  60124. /**
  60125. * Adds an audio file to the current load queue.
  60126. *
  60127. * The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts.
  60128. *
  60129. * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load.
  60130. *
  60131. * Retrieve the file via `Cache.getSound(key)`.
  60132. *
  60133. * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it.
  60134. *
  60135. * Mobile warning: There are some mobile devices (certain iPad 2 and iPad Mini revisions) that cannot play 48000 Hz audio.
  60136. * When they try to play the audio becomes extremely distorted and buzzes, eventually crashing the sound system.
  60137. * The solution is to use a lower encoding rate such as 44100 Hz.
  60138. *
  60139. * @method Phaser.Loader#audio
  60140. * @param {string} key - Unique asset key of the audio file.
  60141. * @param {string|string[]|object[]} urls - Either a single string or an array of URIs or pairs of `{uri: .., type: ..}`.
  60142. * If an array is specified then the first URI (or URI + mime pair) that is device-compatible will be selected.
  60143. * For example: `"jump.mp3"`, `['jump.mp3', 'jump.ogg', 'jump.m4a']`, or `[{uri: "data:<opus_resource>", type: 'opus'}, 'fallback.mp3']`.
  60144. * BLOB and DATA URIs can be used but only support automatic detection when used in the pair form; otherwise the format must be manually checked before adding the resource.
  60145. * @param {boolean} [autoDecode=true] - When using Web Audio the audio files can either be decoded at load time or run-time.
  60146. * Audio files can't be played until they are decoded and, if specified, this enables immediate decoding. Decoding is a non-blocking async process, however it consumes huge amounts of CPU time on mobiles especially.
  60147. * @return {Phaser.Loader} This Loader instance.
  60148. */
  60149. audio: function (key, urls, autoDecode) {
  60150. if (this.game.sound.noAudio)
  60151. {
  60152. return this;
  60153. }
  60154. if (autoDecode === undefined) { autoDecode = true; }
  60155. if (typeof urls === 'string')
  60156. {
  60157. urls = [urls];
  60158. }
  60159. return this.addToFileList('audio', key, urls, { buffer: null, autoDecode: autoDecode });
  60160. },
  60161. /**
  60162. * Adds an audio sprite file to the current load queue.
  60163. *
  60164. * The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts.
  60165. *
  60166. * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load.
  60167. *
  60168. * Audio Sprites are a combination of audio files and a JSON configuration.
  60169. *
  60170. * The JSON follows the format of that created by https://github.com/tonistiigi/audiosprite
  60171. *
  60172. * Retrieve the file via `Cache.getSoundData(key)`.
  60173. *
  60174. * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it.
  60175. *
  60176. * @method Phaser.Loader#audioSprite
  60177. * @param {string} key - Unique asset key of the audio file.
  60178. * @param {Array|string} urls - An array containing the URLs of the audio files, i.e.: [ 'audiosprite.mp3', 'audiosprite.ogg', 'audiosprite.m4a' ] or a single string containing just one URL.
  60179. * @param {string} [jsonURL=null] - The URL of the audiosprite configuration JSON object. If you wish to pass the data directly set this parameter to null.
  60180. * @param {string|object} [jsonData=null] - A JSON object or string containing the audiosprite configuration data. This is ignored if jsonURL is not null.
  60181. * @param {boolean} [autoDecode=true] - When using Web Audio the audio files can either be decoded at load time or run-time.
  60182. * Audio files can't be played until they are decoded and, if specified, this enables immediate decoding. Decoding is a non-blocking async process, however it consumes huge amounts of CPU time on mobiles especially.
  60183. * @return {Phaser.Loader} This Loader instance.
  60184. */
  60185. audioSprite: function (key, urls, jsonURL, jsonData, autoDecode) {
  60186. if (this.game.sound.noAudio)
  60187. {
  60188. return this;
  60189. }
  60190. if (jsonURL === undefined) { jsonURL = null; }
  60191. if (jsonData === undefined) { jsonData = null; }
  60192. if (autoDecode === undefined) { autoDecode = true; }
  60193. this.audio(key, urls, autoDecode);
  60194. if (jsonURL)
  60195. {
  60196. this.json(key + '-audioatlas', jsonURL);
  60197. }
  60198. else if (jsonData)
  60199. {
  60200. if (typeof jsonData === 'string')
  60201. {
  60202. jsonData = JSON.parse(jsonData);
  60203. }
  60204. this.cache.addJSON(key + '-audioatlas', '', jsonData);
  60205. }
  60206. else
  60207. {
  60208. console.warn('Phaser.Loader.audiosprite - You must specify either a jsonURL or provide a jsonData object');
  60209. }
  60210. return this;
  60211. },
  60212. /**
  60213. * A legacy alias for Loader.audioSprite. Please see that method for documentation.
  60214. *
  60215. * @method Phaser.Loader#audiosprite
  60216. * @param {string} key - Unique asset key of the audio file.
  60217. * @param {Array|string} urls - An array containing the URLs of the audio files, i.e.: [ 'audiosprite.mp3', 'audiosprite.ogg', 'audiosprite.m4a' ] or a single string containing just one URL.
  60218. * @param {string} [jsonURL=null] - The URL of the audiosprite configuration JSON object. If you wish to pass the data directly set this parameter to null.
  60219. * @param {string|object} [jsonData=null] - A JSON object or string containing the audiosprite configuration data. This is ignored if jsonURL is not null.
  60220. * @param {boolean} [autoDecode=true] - When using Web Audio the audio files can either be decoded at load time or run-time.
  60221. * Audio files can't be played until they are decoded and, if specified, this enables immediate decoding. Decoding is a non-blocking async process, however it consumes huge amounts of CPU time on mobiles especially.
  60222. * @return {Phaser.Loader} This Loader instance.
  60223. */
  60224. audiosprite: function (key, urls, jsonURL, jsonData, autoDecode) {
  60225. return this.audioSprite(key, urls, jsonURL, jsonData, autoDecode);
  60226. },
  60227. /**
  60228. * Adds a video file to the current load queue.
  60229. *
  60230. * The file is **not** loaded immediately after calling this method. The file is added to the queue ready to be loaded when the loader starts.
  60231. *
  60232. * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load.
  60233. *
  60234. * Retrieve the file via `Cache.getVideo(key)`.
  60235. *
  60236. * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it.
  60237. *
  60238. * You don't need to preload a video in order to play it in your game. See `Video.createVideoFromURL` for details.
  60239. *
  60240. * @method Phaser.Loader#video
  60241. * @param {string} key - Unique asset key of the video file.
  60242. * @param {string|string[]|object[]} urls - Either a single string or an array of URIs or pairs of `{uri: .., type: ..}`.
  60243. * If an array is specified then the first URI (or URI + mime pair) that is device-compatible will be selected.
  60244. * For example: `"boom.mp4"`, `['boom.mp4', 'boom.ogg', 'boom.webm']`, or `[{uri: "data:<opus_resource>", type: 'opus'}, 'fallback.mp4']`.
  60245. * BLOB and DATA URIs can be used but only support automatic detection when used in the pair form; otherwise the format must be manually checked before adding the resource.
  60246. * @param {string} [loadEvent='canplaythrough'] - This sets the Video source event to listen for before the load is considered complete.
  60247. * 'canplaythrough' implies the video has downloaded enough, and bandwidth is high enough that it can be played to completion.
  60248. * 'canplay' implies the video has downloaded enough to start playing, but not necessarily to finish.
  60249. * 'loadeddata' just makes sure that the video meta data and first frame have downloaded. Phaser uses this value automatically if the
  60250. * browser is detected as being Firefox and no `loadEvent` is given, otherwise it defaults to `canplaythrough`.
  60251. * @param {boolean} [asBlob=false] - Video files can either be loaded via the creation of a video element which has its src property set.
  60252. * Or they can be loaded via xhr, stored as binary data in memory and then converted to a Blob. This isn't supported in IE9 or Android 2.
  60253. * If you need to have the same video playing at different times across multiple Sprites then you need to load it as a Blob.
  60254. * @return {Phaser.Loader} This Loader instance.
  60255. */
  60256. video: function (key, urls, loadEvent, asBlob) {
  60257. if (loadEvent === undefined)
  60258. {
  60259. if (this.game.device.firefox)
  60260. {
  60261. loadEvent = 'loadeddata';
  60262. }
  60263. else
  60264. {
  60265. loadEvent = 'canplaythrough';
  60266. }
  60267. }
  60268. if (asBlob === undefined) { asBlob = false; }
  60269. if (typeof urls === 'string')
  60270. {
  60271. urls = [urls];
  60272. }
  60273. return this.addToFileList('video', key, urls, { buffer: null, asBlob: asBlob, loadEvent: loadEvent });
  60274. },
  60275. /**
  60276. * Adds a Tile Map data file to the current load queue.
  60277. *
  60278. * Phaser can load data in two different formats: CSV and Tiled JSON.
  60279. *
  60280. * Tiled is a free software package, specifically for creating tilemaps, and is available from http://www.mapeditor.org
  60281. *
  60282. * You can choose to either load the data externally, by providing a URL to a json file.
  60283. * Or you can pass in a JSON object or String via the `data` parameter.
  60284. * If you pass a String the data is automatically run through `JSON.parse` and then immediately added to the Phaser.Cache.
  60285. *
  60286. * If a URL is provided the file is **not** loaded immediately after calling this method, but is added to the load queue.
  60287. *
  60288. * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load.
  60289. *
  60290. * Retrieve the file via `Cache.getTilemapData(key)`. JSON files are automatically parsed upon load.
  60291. * If you need to control when the JSON is parsed then use `Loader.text` instead and parse the text file as needed.
  60292. *
  60293. * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it.
  60294. *
  60295. * If the URL isn't specified and no data is given then the Loader will take the key and create a filename from that.
  60296. * For example if the key is "level1" and no URL or data is given then the Loader will set the URL to be "level1.json".
  60297. * If you set the format to be Tilemap.CSV it will set the URL to be "level1.csv" instead.
  60298. *
  60299. * If you do not desire this action then provide a URL or data object.
  60300. *
  60301. * @method Phaser.Loader#tilemap
  60302. * @param {string} key - Unique asset key of the tilemap data.
  60303. * @param {string} [url] - URL of the tile map file. If undefined or `null` and no data is given the url will be set to `<key>.json`, i.e. if `key` was "level1" then the URL will be "level1.json".
  60304. * @param {object|string} [data] - An optional JSON data object. If given then the url is ignored and this JSON object is used for map data instead.
  60305. * @param {number} [format=Phaser.Tilemap.CSV] - The format of the map data. Either Phaser.Tilemap.CSV or Phaser.Tilemap.TILED_JSON.
  60306. * @return {Phaser.Loader} This Loader instance.
  60307. */
  60308. tilemap: function (key, url, data, format) {
  60309. if (url === undefined) { url = null; }
  60310. if (data === undefined) { data = null; }
  60311. if (format === undefined) { format = Phaser.Tilemap.CSV; }
  60312. if (!url && !data)
  60313. {
  60314. if (format === Phaser.Tilemap.CSV)
  60315. {
  60316. url = key + '.csv';
  60317. }
  60318. else
  60319. {
  60320. url = key + '.json';
  60321. }
  60322. }
  60323. // A map data object has been given
  60324. if (data)
  60325. {
  60326. switch (format)
  60327. {
  60328. // A csv string or object has been given
  60329. case Phaser.Tilemap.CSV:
  60330. break;
  60331. // A json string or object has been given
  60332. case Phaser.Tilemap.TILED_JSON:
  60333. if (typeof data === 'string')
  60334. {
  60335. data = JSON.parse(data);
  60336. }
  60337. break;
  60338. }
  60339. this.cache.addTilemap(key, null, data, format);
  60340. }
  60341. else
  60342. {
  60343. this.addToFileList('tilemap', key, url, { format: format });
  60344. }
  60345. return this;
  60346. },
  60347. /**
  60348. * Adds a physics data file to the current load queue.
  60349. *
  60350. * The data must be in `Lime + Corona` JSON format. [Physics Editor](https://www.codeandweb.com) by code'n'web exports in this format natively.
  60351. *
  60352. * You can choose to either load the data externally, by providing a URL to a json file.
  60353. * Or you can pass in a JSON object or String via the `data` parameter.
  60354. * If you pass a String the data is automatically run through `JSON.parse` and then immediately added to the Phaser.Cache.
  60355. *
  60356. * If a URL is provided the file is **not** loaded immediately after calling this method, but is added to the load queue.
  60357. *
  60358. * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load.
  60359. *
  60360. * Retrieve the file via `Cache.getJSON(key)`. JSON files are automatically parsed upon load.
  60361. * If you need to control when the JSON is parsed then use `Loader.text` instead and parse the text file as needed.
  60362. *
  60363. * The URL can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it.
  60364. *
  60365. * If the URL isn't specified and no data is given then the Loader will take the key and create a filename from that.
  60366. * For example if the key is "alien" and no URL or data is given then the Loader will set the URL to be "alien.json".
  60367. * It will always use `.json` as the extension.
  60368. *
  60369. * If you do not desire this action then provide a URL or data object.
  60370. *
  60371. * @method Phaser.Loader#physics
  60372. * @param {string} key - Unique asset key of the physics json data.
  60373. * @param {string} [url] - URL of the physics data file. If undefined or `null` and no data is given the url will be set to `<key>.json`, i.e. if `key` was "alien" then the URL will be "alien.json".
  60374. * @param {object|string} [data] - An optional JSON data object. If given then the url is ignored and this JSON object is used for physics data instead.
  60375. * @param {string} [format=Phaser.Physics.LIME_CORONA_JSON] - The format of the physics data.
  60376. * @return {Phaser.Loader} This Loader instance.
  60377. */
  60378. physics: function (key, url, data, format) {
  60379. if (url === undefined) { url = null; }
  60380. if (data === undefined) { data = null; }
  60381. if (format === undefined) { format = Phaser.Physics.LIME_CORONA_JSON; }
  60382. if (!url && !data)
  60383. {
  60384. url = key + '.json';
  60385. }
  60386. // A map data object has been given
  60387. if (data)
  60388. {
  60389. if (typeof data === 'string')
  60390. {
  60391. data = JSON.parse(data);
  60392. }
  60393. this.cache.addPhysicsData(key, null, data, format);
  60394. }
  60395. else
  60396. {
  60397. this.addToFileList('physics', key, url, { format: format });
  60398. }
  60399. return this;
  60400. },
  60401. /**
  60402. * Adds Bitmap Font files to the current load queue.
  60403. *
  60404. * To create the Bitmap Font files you can use:
  60405. *
  60406. * BMFont (Windows, free): http://www.angelcode.com/products/bmfont/
  60407. * Glyph Designer (OS X, commercial): http://www.71squared.com/en/glyphdesigner
  60408. * Littera (Web-based, free): http://kvazars.com/littera/
  60409. *
  60410. * You can choose to either load the data externally, by providing a URL to an xml file.
  60411. * Or you can pass in an XML object or String via the `xmlData` parameter.
  60412. * If you pass a String the data is automatically run through `Loader.parseXML` and then immediately added to the Phaser.Cache.
  60413. *
  60414. * If URLs are provided the files are **not** loaded immediately after calling this method, but are added to the load queue.
  60415. *
  60416. * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load.
  60417. *
  60418. * Retrieve the file via `Cache.getBitmapFont(key)`. XML files are automatically parsed upon load.
  60419. * If you need to control when the XML is parsed then use `Loader.text` instead and parse the XML file as needed.
  60420. *
  60421. * The URLs can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it.
  60422. *
  60423. * If the textureURL isn't specified then the Loader will take the key and create a filename from that.
  60424. * For example if the key is "megaFont" and textureURL is null then the Loader will set the URL to be "megaFont.png".
  60425. * The same is true for the atlasURL. If atlasURL isn't specified and no atlasData has been provided then the Loader will
  60426. * set the atlasURL to be the key. For example if the key is "megaFont" the atlasURL will be set to "megaFont.xml".
  60427. *
  60428. * If you do not desire this action then provide URLs and / or a data object.
  60429. *
  60430. * @method Phaser.Loader#bitmapFont
  60431. * @param {string} key - Unique asset key of the bitmap font.
  60432. * @param {string} textureURL - URL of the Bitmap Font texture file. If undefined or `null` the url will be set to `<key>.png`, i.e. if `key` was "megaFont" then the URL will be "megaFont.png".
  60433. * @param {string} atlasURL - URL of the Bitmap Font atlas file (xml/json). If undefined or `null` AND `atlasData` is null, the url will be set to `<key>.xml`, i.e. if `key` was "megaFont" then the URL will be "megaFont.xml".
  60434. * @param {object} atlasData - An optional Bitmap Font atlas in string form (stringified xml/json).
  60435. * @param {number} [xSpacing=0] - If you'd like to add additional horizontal spacing between the characters then set the pixel value here.
  60436. * @param {number} [ySpacing=0] - If you'd like to add additional vertical spacing between the lines then set the pixel value here.
  60437. * @return {Phaser.Loader} This Loader instance.
  60438. */
  60439. bitmapFont: function (key, textureURL, atlasURL, atlasData, xSpacing, ySpacing) {
  60440. if (textureURL === undefined || textureURL === null)
  60441. {
  60442. textureURL = key + '.png';
  60443. }
  60444. if (atlasURL === undefined) { atlasURL = null; }
  60445. if (atlasData === undefined) { atlasData = null; }
  60446. if (atlasURL === null && atlasData === null)
  60447. {
  60448. atlasURL = key + '.xml';
  60449. }
  60450. if (xSpacing === undefined) { xSpacing = 0; }
  60451. if (ySpacing === undefined) { ySpacing = 0; }
  60452. // A URL to a json/xml atlas has been given
  60453. if (atlasURL)
  60454. {
  60455. this.addToFileList('bitmapfont', key, textureURL, { atlasURL: atlasURL, xSpacing: xSpacing, ySpacing: ySpacing });
  60456. }
  60457. else
  60458. {
  60459. // A stringified xml/json atlas has been given
  60460. if (typeof atlasData === 'string')
  60461. {
  60462. var json, xml;
  60463. try
  60464. {
  60465. json = JSON.parse(atlasData);
  60466. }
  60467. catch ( e )
  60468. {
  60469. xml = this.parseXml(atlasData);
  60470. }
  60471. if (!xml && !json)
  60472. {
  60473. throw new Error("Phaser.Loader. Invalid Bitmap Font atlas given");
  60474. }
  60475. this.addToFileList('bitmapfont', key, textureURL, { atlasURL: null, atlasData: json || xml,
  60476. atlasType: (!!json ? 'json' : 'xml'), xSpacing: xSpacing, ySpacing: ySpacing });
  60477. }
  60478. }
  60479. return this;
  60480. },
  60481. /**
  60482. * Adds a Texture Atlas file to the current load queue.
  60483. *
  60484. * Unlike `Loader.atlasJSONHash` this call expects the atlas data to be in a JSON Array format.
  60485. *
  60486. * To create the Texture Atlas you can use tools such as:
  60487. *
  60488. * [Texture Packer](https://www.codeandweb.com/texturepacker/phaser)
  60489. * [Shoebox](http://renderhjs.net/shoebox/)
  60490. *
  60491. * If using Texture Packer we recommend you enable "Trim sprite names".
  60492. * If your atlas software has an option to "rotate" the resulting frames, you must disable it.
  60493. *
  60494. * You can choose to either load the data externally, by providing a URL to a json file.
  60495. * Or you can pass in a JSON object or String via the `atlasData` parameter.
  60496. * If you pass a String the data is automatically run through `JSON.parse` and then immediately added to the Phaser.Cache.
  60497. *
  60498. * If URLs are provided the files are **not** loaded immediately after calling this method, but are added to the load queue.
  60499. *
  60500. * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load.
  60501. *
  60502. * Retrieve the file via `Cache.getImage(key)`. JSON files are automatically parsed upon load.
  60503. * If you need to control when the JSON is parsed then use `Loader.text` instead and parse the JSON file as needed.
  60504. *
  60505. * The URLs can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it.
  60506. *
  60507. * If the textureURL isn't specified then the Loader will take the key and create a filename from that.
  60508. * For example if the key is "player" and textureURL is null then the Loader will set the URL to be "player.png".
  60509. * The same is true for the atlasURL. If atlasURL isn't specified and no atlasData has been provided then the Loader will
  60510. * set the atlasURL to be the key. For example if the key is "player" the atlasURL will be set to "player.json".
  60511. *
  60512. * If you do not desire this action then provide URLs and / or a data object.
  60513. *
  60514. * @method Phaser.Loader#atlasJSONArray
  60515. * @param {string} key - Unique asset key of the texture atlas file.
  60516. * @param {string} [textureURL] - URL of the texture atlas image file. If undefined or `null` the url will be set to `<key>.png`, i.e. if `key` was "alien" then the URL will be "alien.png".
  60517. * @param {string} [atlasURL] - URL of the texture atlas data file. If undefined or `null` and no atlasData is given, the url will be set to `<key>.json`, i.e. if `key` was "alien" then the URL will be "alien.json".
  60518. * @param {object} [atlasData] - A JSON data object. You don't need this if the data is being loaded from a URL.
  60519. * @return {Phaser.Loader} This Loader instance.
  60520. */
  60521. atlasJSONArray: function (key, textureURL, atlasURL, atlasData) {
  60522. return this.atlas(key, textureURL, atlasURL, atlasData, Phaser.Loader.TEXTURE_ATLAS_JSON_ARRAY);
  60523. },
  60524. /**
  60525. * Adds a Texture Atlas file to the current load queue.
  60526. *
  60527. * Unlike `Loader.atlas` this call expects the atlas data to be in a JSON Hash format.
  60528. *
  60529. * To create the Texture Atlas you can use tools such as:
  60530. *
  60531. * [Texture Packer](https://www.codeandweb.com/texturepacker/phaser)
  60532. * [Shoebox](http://renderhjs.net/shoebox/)
  60533. *
  60534. * If using Texture Packer we recommend you enable "Trim sprite names".
  60535. * If your atlas software has an option to "rotate" the resulting frames, you must disable it.
  60536. *
  60537. * You can choose to either load the data externally, by providing a URL to a json file.
  60538. * Or you can pass in a JSON object or String via the `atlasData` parameter.
  60539. * If you pass a String the data is automatically run through `JSON.parse` and then immediately added to the Phaser.Cache.
  60540. *
  60541. * If URLs are provided the files are **not** loaded immediately after calling this method, but are added to the load queue.
  60542. *
  60543. * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load.
  60544. *
  60545. * Retrieve the file via `Cache.getImage(key)`. JSON files are automatically parsed upon load.
  60546. * If you need to control when the JSON is parsed then use `Loader.text` instead and parse the JSON file as needed.
  60547. *
  60548. * The URLs can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it.
  60549. *
  60550. * If the textureURL isn't specified then the Loader will take the key and create a filename from that.
  60551. * For example if the key is "player" and textureURL is null then the Loader will set the URL to be "player.png".
  60552. * The same is true for the atlasURL. If atlasURL isn't specified and no atlasData has been provided then the Loader will
  60553. * set the atlasURL to be the key. For example if the key is "player" the atlasURL will be set to "player.json".
  60554. *
  60555. * If you do not desire this action then provide URLs and / or a data object.
  60556. *
  60557. * @method Phaser.Loader#atlasJSONHash
  60558. * @param {string} key - Unique asset key of the texture atlas file.
  60559. * @param {string} [textureURL] - URL of the texture atlas image file. If undefined or `null` the url will be set to `<key>.png`, i.e. if `key` was "alien" then the URL will be "alien.png".
  60560. * @param {string} [atlasURL] - URL of the texture atlas data file. If undefined or `null` and no atlasData is given, the url will be set to `<key>.json`, i.e. if `key` was "alien" then the URL will be "alien.json".
  60561. * @param {object} [atlasData] - A JSON data object. You don't need this if the data is being loaded from a URL.
  60562. * @return {Phaser.Loader} This Loader instance.
  60563. */
  60564. atlasJSONHash: function (key, textureURL, atlasURL, atlasData) {
  60565. return this.atlas(key, textureURL, atlasURL, atlasData, Phaser.Loader.TEXTURE_ATLAS_JSON_HASH);
  60566. },
  60567. /**
  60568. * Adds a Texture Atlas file to the current load queue.
  60569. *
  60570. * This call expects the atlas data to be in the Starling XML data format.
  60571. *
  60572. * To create the Texture Atlas you can use tools such as:
  60573. *
  60574. * [Texture Packer](https://www.codeandweb.com/texturepacker/phaser)
  60575. * [Shoebox](http://renderhjs.net/shoebox/)
  60576. *
  60577. * If using Texture Packer we recommend you enable "Trim sprite names".
  60578. * If your atlas software has an option to "rotate" the resulting frames, you must disable it.
  60579. *
  60580. * You can choose to either load the data externally, by providing a URL to an xml file.
  60581. * Or you can pass in an XML object or String via the `atlasData` parameter.
  60582. * If you pass a String the data is automatically run through `Loader.parseXML` and then immediately added to the Phaser.Cache.
  60583. *
  60584. * If URLs are provided the files are **not** loaded immediately after calling this method, but are added to the load queue.
  60585. *
  60586. * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load.
  60587. *
  60588. * Retrieve the file via `Cache.getImage(key)`. XML files are automatically parsed upon load.
  60589. * If you need to control when the XML is parsed then use `Loader.text` instead and parse the XML file as needed.
  60590. *
  60591. * The URLs can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it.
  60592. *
  60593. * If the textureURL isn't specified then the Loader will take the key and create a filename from that.
  60594. * For example if the key is "player" and textureURL is null then the Loader will set the URL to be "player.png".
  60595. * The same is true for the atlasURL. If atlasURL isn't specified and no atlasData has been provided then the Loader will
  60596. * set the atlasURL to be the key. For example if the key is "player" the atlasURL will be set to "player.xml".
  60597. *
  60598. * If you do not desire this action then provide URLs and / or a data object.
  60599. *
  60600. * @method Phaser.Loader#atlasXML
  60601. * @param {string} key - Unique asset key of the texture atlas file.
  60602. * @param {string} [textureURL] - URL of the texture atlas image file. If undefined or `null` the url will be set to `<key>.png`, i.e. if `key` was "alien" then the URL will be "alien.png".
  60603. * @param {string} [atlasURL] - URL of the texture atlas data file. If undefined or `null` and no atlasData is given, the url will be set to `<key>.json`, i.e. if `key` was "alien" then the URL will be "alien.xml".
  60604. * @param {object} [atlasData] - An XML data object. You don't need this if the data is being loaded from a URL.
  60605. * @return {Phaser.Loader} This Loader instance.
  60606. */
  60607. atlasXML: function (key, textureURL, atlasURL, atlasData) {
  60608. if (atlasURL === undefined) { atlasURL = null; }
  60609. if (atlasData === undefined) { atlasData = null; }
  60610. if (!atlasURL && !atlasData)
  60611. {
  60612. atlasURL = key + '.xml';
  60613. }
  60614. return this.atlas(key, textureURL, atlasURL, atlasData, Phaser.Loader.TEXTURE_ATLAS_XML_STARLING);
  60615. },
  60616. /**
  60617. * Adds a Texture Atlas file to the current load queue.
  60618. *
  60619. * To create the Texture Atlas you can use tools such as:
  60620. *
  60621. * [Texture Packer](https://www.codeandweb.com/texturepacker/phaser)
  60622. * [Shoebox](http://renderhjs.net/shoebox/)
  60623. *
  60624. * If using Texture Packer we recommend you enable "Trim sprite names".
  60625. * If your atlas software has an option to "rotate" the resulting frames, you must disable it.
  60626. *
  60627. * You can choose to either load the data externally, by providing a URL to a json file.
  60628. * Or you can pass in a JSON object or String via the `atlasData` parameter.
  60629. * If you pass a String the data is automatically run through `JSON.parse` and then immediately added to the Phaser.Cache.
  60630. *
  60631. * If URLs are provided the files are **not** loaded immediately after calling this method, but are added to the load queue.
  60632. *
  60633. * The key must be a unique String. It is used to add the file to the Phaser.Cache upon successful load.
  60634. *
  60635. * Retrieve the file via `Cache.getImage(key)`. JSON files are automatically parsed upon load.
  60636. * If you need to control when the JSON is parsed then use `Loader.text` instead and parse the JSON file as needed.
  60637. *
  60638. * The URLs can be relative or absolute. If the URL is relative the `Loader.baseURL` and `Loader.path` values will be prepended to it.
  60639. *
  60640. * If the textureURL isn't specified then the Loader will take the key and create a filename from that.
  60641. * For example if the key is "player" and textureURL is null then the Loader will set the URL to be "player.png".
  60642. * The same is true for the atlasURL. If atlasURL isn't specified and no atlasData has been provided then the Loader will
  60643. * set the atlasURL to be the key. For example if the key is "player" the atlasURL will be set to "player.json".
  60644. *
  60645. * If you do not desire this action then provide URLs and / or a data object.
  60646. *
  60647. * @method Phaser.Loader#atlas
  60648. * @param {string} key - Unique asset key of the texture atlas file.
  60649. * @param {string} [textureURL] - URL of the texture atlas image file. If undefined or `null` the url will be set to `<key>.png`, i.e. if `key` was "alien" then the URL will be "alien.png".
  60650. * @param {string} [atlasURL] - URL of the texture atlas data file. If undefined or `null` and no atlasData is given, the url will be set to `<key>.json`, i.e. if `key` was "alien" then the URL will be "alien.json".
  60651. * @param {object} [atlasData] - A JSON or XML data object. You don't need this if the data is being loaded from a URL.
  60652. * @param {number} [format] - The format of the data. Can be Phaser.Loader.TEXTURE_ATLAS_JSON_ARRAY (the default), Phaser.Loader.TEXTURE_ATLAS_JSON_HASH or Phaser.Loader.TEXTURE_ATLAS_XML_STARLING.
  60653. * @return {Phaser.Loader} This Loader instance.
  60654. */
  60655. atlas: function (key, textureURL, atlasURL, atlasData, format) {
  60656. if (textureURL === undefined || textureURL === null)
  60657. {
  60658. textureURL = key + '.png';
  60659. }
  60660. if (atlasURL === undefined) { atlasURL = null; }
  60661. if (atlasData === undefined) { atlasData = null; }
  60662. if (format === undefined) { format = Phaser.Loader.TEXTURE_ATLAS_JSON_ARRAY; }
  60663. if (!atlasURL && !atlasData)
  60664. {
  60665. if (format === Phaser.Loader.TEXTURE_ATLAS_XML_STARLING)
  60666. {
  60667. atlasURL = key + '.xml';
  60668. }
  60669. else
  60670. {
  60671. atlasURL = key + '.json';
  60672. }
  60673. }
  60674. // A URL to a json/xml file has been given
  60675. if (atlasURL)
  60676. {
  60677. this.addToFileList('textureatlas', key, textureURL, { atlasURL: atlasURL, format: format });
  60678. }
  60679. else
  60680. {
  60681. switch (format)
  60682. {
  60683. // A json string or object has been given
  60684. case Phaser.Loader.TEXTURE_ATLAS_JSON_ARRAY:
  60685. if (typeof atlasData === 'string')
  60686. {
  60687. atlasData = JSON.parse(atlasData);
  60688. }
  60689. break;
  60690. // An xml string or object has been given
  60691. case Phaser.Loader.TEXTURE_ATLAS_XML_STARLING:
  60692. if (typeof atlasData === 'string')
  60693. {
  60694. var xml = this.parseXml(atlasData);
  60695. if (!xml)
  60696. {
  60697. throw new Error("Phaser.Loader. Invalid Texture Atlas XML given");
  60698. }
  60699. atlasData = xml;
  60700. }
  60701. break;
  60702. }
  60703. this.addToFileList('textureatlas', key, textureURL, { atlasURL: null, atlasData: atlasData, format: format });
  60704. }
  60705. return this;
  60706. },
  60707. /**
  60708. * Add a synchronization point to the assets/files added within the supplied callback.
  60709. *
  60710. * A synchronization point denotes that an asset _must_ be completely loaded before
  60711. * subsequent assets can be loaded. An asset marked as a sync-point does not need to wait
  60712. * for previous assets to load (unless they are sync-points). Resources, such as packs, may still
  60713. * be downloaded around sync-points, as long as they do not finalize loading.
  60714. *
  60715. * @method Phaser.Loader#withSyncPoints
  60716. * @param {function} callback - The callback is invoked and is supplied with a single argument: the loader.
  60717. * @param {object} [callbackContext=(loader)] - Context for the callback.
  60718. * @return {Phaser.Loader} This Loader instance.
  60719. */
  60720. withSyncPoint: function (callback, callbackContext) {
  60721. this._withSyncPointDepth++;
  60722. try {
  60723. callback.call(callbackContext || this, this);
  60724. } finally {
  60725. this._withSyncPointDepth--;
  60726. }
  60727. return this;
  60728. },
  60729. /**
  60730. * Add a synchronization point to a specific file/asset in the load queue.
  60731. *
  60732. * This has no effect on already loaded assets.
  60733. *
  60734. * @method Phaser.Loader#addSyncPoint
  60735. * @param {string} type - The type of resource to turn into a sync point (image, audio, xml, etc).
  60736. * @param {string} key - Key of the file you want to turn into a sync point.
  60737. * @return {Phaser.Loader} This Loader instance.
  60738. * @see {@link Phaser.Loader#withSyncPoint withSyncPoint}
  60739. */
  60740. addSyncPoint: function (type, key) {
  60741. var asset = this.getAsset(type, key);
  60742. if (asset)
  60743. {
  60744. asset.file.syncPoint = true;
  60745. }
  60746. return this;
  60747. },
  60748. /**
  60749. * Remove a file/asset from the loading queue.
  60750. *
  60751. * A file that is loaded or has started loading cannot be removed.
  60752. *
  60753. * @method Phaser.Loader#removeFile
  60754. * @protected
  60755. * @param {string} type - The type of resource to add to the list (image, audio, xml, etc).
  60756. * @param {string} key - Key of the file you want to remove.
  60757. */
  60758. removeFile: function (type, key) {
  60759. var asset = this.getAsset(type, key);
  60760. if (asset)
  60761. {
  60762. if (!asset.loaded && !asset.loading)
  60763. {
  60764. this._fileList.splice(asset.index, 1);
  60765. }
  60766. }
  60767. },
  60768. /**
  60769. * Remove all file loading requests - this is _insufficient_ to stop current loading. Use `reset` instead.
  60770. *
  60771. * @method Phaser.Loader#removeAll
  60772. * @protected
  60773. */
  60774. removeAll: function () {
  60775. this._fileList.length = 0;
  60776. this._flightQueue.length = 0;
  60777. },
  60778. /**
  60779. * Start loading the assets. Normally you don't need to call this yourself as the StateManager will do so.
  60780. *
  60781. * @method Phaser.Loader#start
  60782. */
  60783. start: function () {
  60784. if (this.isLoading)
  60785. {
  60786. return;
  60787. }
  60788. this.hasLoaded = false;
  60789. this.isLoading = true;
  60790. this.updateProgress();
  60791. this.processLoadQueue();
  60792. },
  60793. /**
  60794. * Process the next item(s) in the file/asset queue.
  60795. *
  60796. * Process the queue and start loading enough items to fill up the inflight queue.
  60797. *
  60798. * If a sync-file is encountered then subsequent asset processing is delayed until it completes.
  60799. * The exception to this rule is that packfiles can be downloaded (but not processed) even if
  60800. * there appear other sync files (ie. packs) - this enables multiple packfiles to be fetched in parallel.
  60801. * such as during the start phaser.
  60802. *
  60803. * @method Phaser.Loader#processLoadQueue
  60804. * @private
  60805. */
  60806. processLoadQueue: function () {
  60807. if (!this.isLoading)
  60808. {
  60809. console.warn('Phaser.Loader - active loading canceled / reset');
  60810. this.finishedLoading(true);
  60811. return;
  60812. }
  60813. // Empty the flight queue as applicable
  60814. for (var i = 0; i < this._flightQueue.length; i++)
  60815. {
  60816. var file = this._flightQueue[i];
  60817. if (file.loaded || file.error)
  60818. {
  60819. this._flightQueue.splice(i, 1);
  60820. i--;
  60821. file.loading = false;
  60822. file.requestUrl = null;
  60823. file.requestObject = null;
  60824. if (file.error)
  60825. {
  60826. this.onFileError.dispatch(file.key, file);
  60827. }
  60828. if (file.type !== 'packfile')
  60829. {
  60830. this._loadedFileCount++;
  60831. this.onFileComplete.dispatch(this.progress, file.key, !file.error, this._loadedFileCount, this._totalFileCount);
  60832. }
  60833. else if (file.type === 'packfile' && file.error)
  60834. {
  60835. // Non-error pack files are handled when processing the file queue
  60836. this._loadedPackCount++;
  60837. this.onPackComplete.dispatch(file.key, !file.error, this._loadedPackCount, this._totalPackCount);
  60838. }
  60839. }
  60840. }
  60841. // When true further non-pack file downloads are suppressed
  60842. var syncblock = false;
  60843. var inflightLimit = this.enableParallel ? Phaser.Math.clamp(this.maxParallelDownloads, 1, 12) : 1;
  60844. for (var i = this._processingHead; i < this._fileList.length; i++)
  60845. {
  60846. var file = this._fileList[i];
  60847. // Pack is fetched (ie. has data) and is currently at the start of the process queue.
  60848. if (file.type === 'packfile' && !file.error && file.loaded && i === this._processingHead)
  60849. {
  60850. // Processing the pack / adds more files
  60851. this.processPack(file);
  60852. this._loadedPackCount++;
  60853. this.onPackComplete.dispatch(file.key, !file.error, this._loadedPackCount, this._totalPackCount);
  60854. }
  60855. if (file.loaded || file.error)
  60856. {
  60857. // Item at the start of file list finished, can skip it in future
  60858. if (i === this._processingHead)
  60859. {
  60860. this._processingHead = i + 1;
  60861. }
  60862. }
  60863. else if (!file.loading && this._flightQueue.length < inflightLimit)
  60864. {
  60865. // -> not loaded/failed, not loading
  60866. if (file.type === 'packfile' && !file.data)
  60867. {
  60868. // Fetches the pack data: the pack is processed above as it reaches queue-start.
  60869. // (Packs do not trigger onLoadStart or onFileStart.)
  60870. this._flightQueue.push(file);
  60871. file.loading = true;
  60872. this.loadFile(file);
  60873. }
  60874. else if (!syncblock)
  60875. {
  60876. if (!this._fileLoadStarted)
  60877. {
  60878. this._fileLoadStarted = true;
  60879. this.onLoadStart.dispatch();
  60880. }
  60881. this._flightQueue.push(file);
  60882. file.loading = true;
  60883. this.onFileStart.dispatch(this.progress, file.key, file.url);
  60884. this.loadFile(file);
  60885. }
  60886. }
  60887. if (!file.loaded && file.syncPoint)
  60888. {
  60889. syncblock = true;
  60890. }
  60891. // Stop looking if queue full - or if syncblocked and there are no more packs.
  60892. // (As only packs can be loaded around a syncblock)
  60893. if (this._flightQueue.length >= inflightLimit ||
  60894. (syncblock && this._loadedPackCount === this._totalPackCount))
  60895. {
  60896. break;
  60897. }
  60898. }
  60899. this.updateProgress();
  60900. // True when all items in the queue have been advanced over
  60901. // (There should be no inflight items as they are complete - loaded/error.)
  60902. if (this._processingHead >= this._fileList.length)
  60903. {
  60904. this.finishedLoading();
  60905. }
  60906. else if (!this._flightQueue.length)
  60907. {
  60908. // Flight queue is empty but file list is not done being processed.
  60909. // This indicates a critical internal error with no known recovery.
  60910. console.warn("Phaser.Loader - aborting: processing queue empty, loading may have stalled");
  60911. var _this = this;
  60912. setTimeout(function () {
  60913. _this.finishedLoading(true);
  60914. }, 2000);
  60915. }
  60916. },
  60917. /**
  60918. * The loading is all finished.
  60919. *
  60920. * @method Phaser.Loader#finishedLoading
  60921. * @private
  60922. * @param {boolean} [abnormal=true] - True if the loading finished abnormally.
  60923. */
  60924. finishedLoading: function (abnormal) {
  60925. if (this.hasLoaded)
  60926. {
  60927. return;
  60928. }
  60929. this.hasLoaded = true;
  60930. this.isLoading = false;
  60931. // If there were no files make sure to trigger the event anyway, for consistency
  60932. if (!abnormal && !this._fileLoadStarted)
  60933. {
  60934. this._fileLoadStarted = true;
  60935. this.onLoadStart.dispatch();
  60936. }
  60937. this.onLoadComplete.dispatch();
  60938. this.game.state.loadComplete();
  60939. this.reset();
  60940. },
  60941. /**
  60942. * Informs the loader that the given file resource has been fetched and processed;
  60943. * or such a request has failed.
  60944. *
  60945. * @method Phaser.Loader#asyncComplete
  60946. * @private
  60947. * @param {object} file
  60948. * @param {string} [error=''] - The error message, if any. No message implies no error.
  60949. */
  60950. asyncComplete: function (file, errorMessage) {
  60951. if (errorMessage === undefined) { errorMessage = ''; }
  60952. file.loaded = true;
  60953. file.error = !!errorMessage;
  60954. if (errorMessage)
  60955. {
  60956. file.errorMessage = errorMessage;
  60957. console.warn('Phaser.Loader - ' + file.type + '[' + file.key + ']' + ': ' + errorMessage);
  60958. // debugger;
  60959. }
  60960. this.processLoadQueue();
  60961. },
  60962. /**
  60963. * Process pack data. This will usually modify the file list.
  60964. *
  60965. * @method Phaser.Loader#processPack
  60966. * @private
  60967. * @param {object} pack
  60968. */
  60969. processPack: function (pack) {
  60970. var packData = pack.data[pack.key];
  60971. if (!packData)
  60972. {
  60973. console.warn('Phaser.Loader - ' + pack.key + ': pack has data, but not for pack key');
  60974. return;
  60975. }
  60976. for (var i = 0; i < packData.length; i++)
  60977. {
  60978. var file = packData[i];
  60979. switch (file.type)
  60980. {
  60981. case "image":
  60982. this.image(file.key, file.url, file.overwrite);
  60983. break;
  60984. case "text":
  60985. this.text(file.key, file.url, file.overwrite);
  60986. break;
  60987. case "json":
  60988. this.json(file.key, file.url, file.overwrite);
  60989. break;
  60990. case "xml":
  60991. this.xml(file.key, file.url, file.overwrite);
  60992. break;
  60993. case "script":
  60994. this.script(file.key, file.url, file.callback, pack.callbackContext || this);
  60995. break;
  60996. case "binary":
  60997. this.binary(file.key, file.url, file.callback, pack.callbackContext || this);
  60998. break;
  60999. case "spritesheet":
  61000. this.spritesheet(file.key, file.url, file.frameWidth, file.frameHeight, file.frameMax, file.margin, file.spacing);
  61001. break;
  61002. case "video":
  61003. this.video(file.key, file.urls);
  61004. break;
  61005. case "audio":
  61006. this.audio(file.key, file.urls, file.autoDecode);
  61007. break;
  61008. case "audiosprite":
  61009. this.audiosprite(file.key, file.urls, file.jsonURL, file.jsonData, file.autoDecode);
  61010. break;
  61011. case "tilemap":
  61012. this.tilemap(file.key, file.url, file.data, Phaser.Tilemap[file.format]);
  61013. break;
  61014. case "physics":
  61015. this.physics(file.key, file.url, file.data, Phaser.Loader[file.format]);
  61016. break;
  61017. case "bitmapFont":
  61018. this.bitmapFont(file.key, file.textureURL, file.atlasURL, file.atlasData, file.xSpacing, file.ySpacing);
  61019. break;
  61020. case "atlasJSONArray":
  61021. this.atlasJSONArray(file.key, file.textureURL, file.atlasURL, file.atlasData);
  61022. break;
  61023. case "atlasJSONHash":
  61024. this.atlasJSONHash(file.key, file.textureURL, file.atlasURL, file.atlasData);
  61025. break;
  61026. case "atlasXML":
  61027. this.atlasXML(file.key, file.textureURL, file.atlasURL, file.atlasData);
  61028. break;
  61029. case "atlas":
  61030. this.atlas(file.key, file.textureURL, file.atlasURL, file.atlasData, Phaser.Loader[file.format]);
  61031. break;
  61032. case "shader":
  61033. this.shader(file.key, file.url, file.overwrite);
  61034. break;
  61035. }
  61036. }
  61037. },
  61038. /**
  61039. * Transforms the asset URL.
  61040. *
  61041. * The default implementation prepends the baseURL if the url doesn't begin with http or //
  61042. *
  61043. * @method Phaser.Loader#transformUrl
  61044. * @protected
  61045. * @param {string} url - The url to transform.
  61046. * @param {object} file - The file object being transformed.
  61047. * @return {string} The transformed url. In rare cases where the url isn't specified it will return false instead.
  61048. */
  61049. transformUrl: function (url, file) {
  61050. if (!url)
  61051. {
  61052. return false;
  61053. }
  61054. if (url.match(/^(?:blob:|data:|http:\/\/|https:\/\/|\/\/)/))
  61055. {
  61056. return url;
  61057. }
  61058. else
  61059. {
  61060. return this.baseURL + file.path + url;
  61061. }
  61062. },
  61063. /**
  61064. * Start fetching a resource.
  61065. *
  61066. * All code paths, async or otherwise, from this function must return to `asyncComplete`.
  61067. *
  61068. * @method Phaser.Loader#loadFile
  61069. * @private
  61070. * @param {object} file
  61071. */
  61072. loadFile: function (file) {
  61073. // Image or Data?
  61074. switch (file.type)
  61075. {
  61076. case 'packfile':
  61077. this.xhrLoad(file, this.transformUrl(file.url, file), 'text', this.fileComplete);
  61078. break;
  61079. case 'image':
  61080. case 'spritesheet':
  61081. case 'textureatlas':
  61082. case 'bitmapfont':
  61083. this.loadImageTag(file);
  61084. break;
  61085. case 'audio':
  61086. file.url = this.getAudioURL(file.url);
  61087. if (file.url)
  61088. {
  61089. // WebAudio or Audio Tag?
  61090. if (this.game.sound.usingWebAudio)
  61091. {
  61092. this.xhrLoad(file, this.transformUrl(file.url, file), 'arraybuffer', this.fileComplete);
  61093. }
  61094. else if (this.game.sound.usingAudioTag)
  61095. {
  61096. this.loadAudioTag(file);
  61097. }
  61098. }
  61099. else
  61100. {
  61101. this.fileError(file, null, 'No supported audio URL specified or device does not have audio playback support');
  61102. }
  61103. break;
  61104. case 'video':
  61105. file.url = this.getVideoURL(file.url);
  61106. if (file.url)
  61107. {
  61108. if (file.asBlob)
  61109. {
  61110. this.xhrLoad(file, this.transformUrl(file.url, file), 'blob', this.fileComplete);
  61111. }
  61112. else
  61113. {
  61114. this.loadVideoTag(file);
  61115. }
  61116. }
  61117. else
  61118. {
  61119. this.fileError(file, null, 'No supported video URL specified or device does not have video playback support');
  61120. }
  61121. break;
  61122. case 'json':
  61123. this.xhrLoad(file, this.transformUrl(file.url, file), 'text', this.jsonLoadComplete);
  61124. break;
  61125. case 'xml':
  61126. this.xhrLoad(file, this.transformUrl(file.url, file), 'text', this.xmlLoadComplete);
  61127. break;
  61128. case 'tilemap':
  61129. if (file.format === Phaser.Tilemap.TILED_JSON)
  61130. {
  61131. this.xhrLoad(file, this.transformUrl(file.url, file), 'text', this.jsonLoadComplete);
  61132. }
  61133. else if (file.format === Phaser.Tilemap.CSV)
  61134. {
  61135. this.xhrLoad(file, this.transformUrl(file.url, file), 'text', this.csvLoadComplete);
  61136. }
  61137. else
  61138. {
  61139. this.asyncComplete(file, "invalid Tilemap format: " + file.format);
  61140. }
  61141. break;
  61142. case 'text':
  61143. case 'script':
  61144. case 'shader':
  61145. case 'physics':
  61146. this.xhrLoad(file, this.transformUrl(file.url, file), 'text', this.fileComplete);
  61147. break;
  61148. case 'binary':
  61149. this.xhrLoad(file, this.transformUrl(file.url, file), 'arraybuffer', this.fileComplete);
  61150. break;
  61151. }
  61152. },
  61153. /**
  61154. * Continue async loading through an Image tag.
  61155. * @private
  61156. */
  61157. loadImageTag: function (file) {
  61158. var _this = this;
  61159. file.data = new Image();
  61160. file.data.name = file.key;
  61161. if (this.crossOrigin)
  61162. {
  61163. file.data.crossOrigin = this.crossOrigin;
  61164. }
  61165. file.data.onload = function () {
  61166. if (file.data.onload)
  61167. {
  61168. file.data.onload = null;
  61169. file.data.onerror = null;
  61170. _this.fileComplete(file);
  61171. }
  61172. };
  61173. file.data.onerror = function () {
  61174. if (file.data.onload)
  61175. {
  61176. file.data.onload = null;
  61177. file.data.onerror = null;
  61178. _this.fileError(file);
  61179. }
  61180. };
  61181. file.data.src = this.transformUrl(file.url, file);
  61182. // Image is immediately-available/cached
  61183. if (file.data.complete && file.data.width && file.data.height)
  61184. {
  61185. file.data.onload = null;
  61186. file.data.onerror = null;
  61187. this.fileComplete(file);
  61188. }
  61189. },
  61190. /**
  61191. * Continue async loading through a Video tag.
  61192. * @private
  61193. */
  61194. loadVideoTag: function (file) {
  61195. var _this = this;
  61196. file.data = document.createElement("video");
  61197. file.data.name = file.key;
  61198. file.data.controls = false;
  61199. file.data.autoplay = false;
  61200. var videoLoadEvent = function () {
  61201. file.data.removeEventListener(file.loadEvent, videoLoadEvent, false);
  61202. file.data.onerror = null;
  61203. file.data.canplay = true;
  61204. Phaser.GAMES[_this.game.id].load.fileComplete(file);
  61205. };
  61206. file.data.onerror = function () {
  61207. file.data.removeEventListener(file.loadEvent, videoLoadEvent, false);
  61208. file.data.onerror = null;
  61209. file.data.canplay = false;
  61210. _this.fileError(file);
  61211. };
  61212. file.data.addEventListener(file.loadEvent, videoLoadEvent, false);
  61213. file.data.src = this.transformUrl(file.url, file);
  61214. file.data.load();
  61215. },
  61216. /**
  61217. * Continue async loading through an Audio tag.
  61218. * @private
  61219. */
  61220. loadAudioTag: function (file) {
  61221. var _this = this;
  61222. if (this.game.sound.touchLocked)
  61223. {
  61224. // If audio is locked we can't do this yet, so need to queue this load request. Bum.
  61225. file.data = new Audio();
  61226. file.data.name = file.key;
  61227. file.data.preload = 'auto';
  61228. file.data.src = this.transformUrl(file.url, file);
  61229. this.fileComplete(file);
  61230. }
  61231. else
  61232. {
  61233. file.data = new Audio();
  61234. file.data.name = file.key;
  61235. var playThroughEvent = function () {
  61236. file.data.removeEventListener('canplaythrough', playThroughEvent, false);
  61237. file.data.onerror = null;
  61238. _this.fileComplete(file);
  61239. };
  61240. file.data.onerror = function () {
  61241. file.data.removeEventListener('canplaythrough', playThroughEvent, false);
  61242. file.data.onerror = null;
  61243. _this.fileError(file);
  61244. };
  61245. file.data.preload = 'auto';
  61246. file.data.src = this.transformUrl(file.url, file);
  61247. file.data.addEventListener('canplaythrough', playThroughEvent, false);
  61248. file.data.load();
  61249. }
  61250. },
  61251. /**
  61252. * Starts the xhr loader.
  61253. *
  61254. * This is designed specifically to use with asset file processing.
  61255. *
  61256. * @method Phaser.Loader#xhrLoad
  61257. * @private
  61258. * @param {object} file - The file/pack to load.
  61259. * @param {string} url - The URL of the file.
  61260. * @param {string} type - The xhr responseType.
  61261. * @param {function} onload - The function to call on success. Invoked in `this` context and supplied with `(file, xhr)` arguments.
  61262. * @param {function} [onerror=fileError] The function to call on error. Invoked in `this` context and supplied with `(file, xhr)` arguments.
  61263. */
  61264. xhrLoad: function (file, url, type, onload, onerror) {
  61265. if (this.useXDomainRequest && window.XDomainRequest)
  61266. {
  61267. this.xhrLoadWithXDR(file, url, type, onload, onerror);
  61268. return;
  61269. }
  61270. var xhr = new XMLHttpRequest();
  61271. xhr.open("GET", url, true);
  61272. xhr.responseType = type;
  61273. if (this.headers['requestedWith'] !== false)
  61274. {
  61275. xhr.setRequestHeader('X-Requested-With', this.headers['requestedWith']);
  61276. }
  61277. if (this.headers[file.type])
  61278. {
  61279. xhr.setRequestHeader('Accept', this.headers[file.type]);
  61280. }
  61281. onerror = onerror || this.fileError;
  61282. var _this = this;
  61283. xhr.onload = function () {
  61284. try {
  61285. if (xhr.readyState === 4 && xhr.status >= 400 && xhr.status <= 599) { // Handle HTTP status codes of 4xx and 5xx as errors, even if xhr.onerror was not called.
  61286. return onerror.call(_this, file, xhr);
  61287. }
  61288. else {
  61289. return onload.call(_this, file, xhr);
  61290. }
  61291. } catch (e) {
  61292. // If this was the last file in the queue and an error is thrown in the create method
  61293. // then it's caught here, so be sure we don't carry on processing it
  61294. if (!_this.hasLoaded)
  61295. {
  61296. _this.asyncComplete(file, e.message || 'Exception');
  61297. }
  61298. else
  61299. {
  61300. if (window['console'])
  61301. {
  61302. console.error(e);
  61303. }
  61304. }
  61305. }
  61306. };
  61307. xhr.onerror = function () {
  61308. try {
  61309. return onerror.call(_this, file, xhr);
  61310. } catch (e) {
  61311. if (!_this.hasLoaded)
  61312. {
  61313. _this.asyncComplete(file, e.message || 'Exception');
  61314. }
  61315. else
  61316. {
  61317. if (window['console'])
  61318. {
  61319. console.error(e);
  61320. }
  61321. }
  61322. }
  61323. };
  61324. file.requestObject = xhr;
  61325. file.requestUrl = url;
  61326. xhr.send();
  61327. },
  61328. /**
  61329. * Starts the xhr loader - using XDomainRequest.
  61330. * This should _only_ be used with IE 9. Phaser does not support IE 8 and XDR is deprecated in IE 10.
  61331. *
  61332. * This is designed specifically to use with asset file processing.
  61333. *
  61334. * @method Phaser.Loader#xhrLoad
  61335. * @private
  61336. * @param {object} file - The file/pack to load.
  61337. * @param {string} url - The URL of the file.
  61338. * @param {string} type - The xhr responseType.
  61339. * @param {function} onload - The function to call on success. Invoked in `this` context and supplied with `(file, xhr)` arguments.
  61340. * @param {function} [onerror=fileError] The function to call on error. Invoked in `this` context and supplied with `(file, xhr)` arguments.
  61341. * @deprecated This is only relevant for IE 9.
  61342. */
  61343. xhrLoadWithXDR: function (file, url, type, onload, onerror) {
  61344. // Special IE9 magic .. only
  61345. if (!this._warnedAboutXDomainRequest &&
  61346. (!this.game.device.ie || this.game.device.ieVersion >= 10))
  61347. {
  61348. this._warnedAboutXDomainRequest = true;
  61349. console.warn("Phaser.Loader - using XDomainRequest outside of IE 9");
  61350. }
  61351. // Ref: http://blogs.msdn.com/b/ieinternals/archive/2010/05/13/xdomainrequest-restrictions-limitations-and-workarounds.aspx
  61352. var xhr = new window.XDomainRequest();
  61353. xhr.open('GET', url, true);
  61354. xhr.responseType = type;
  61355. // XDomainRequest has a few quirks. Occasionally it will abort requests
  61356. // A way to avoid this is to make sure ALL callbacks are set even if not used
  61357. // More info here: http://stackoverflow.com/questions/15786966/xdomainrequest-aborts-post-on-ie-9
  61358. xhr.timeout = 3000;
  61359. onerror = onerror || this.fileError;
  61360. var _this = this;
  61361. xhr.onerror = function () {
  61362. try {
  61363. return onerror.call(_this, file, xhr);
  61364. } catch (e) {
  61365. _this.asyncComplete(file, e.message || 'Exception');
  61366. }
  61367. };
  61368. xhr.ontimeout = function () {
  61369. try {
  61370. return onerror.call(_this, file, xhr);
  61371. } catch (e) {
  61372. _this.asyncComplete(file, e.message || 'Exception');
  61373. }
  61374. };
  61375. xhr.onprogress = function() {};
  61376. xhr.onload = function () {
  61377. try {
  61378. if (xhr.readyState === 4 && xhr.status >= 400 && xhr.status <= 599) { // Handle HTTP status codes of 4xx and 5xx as errors, even if xhr.onerror was not called.
  61379. return onerror.call(_this, file, xhr);
  61380. }
  61381. else {
  61382. return onload.call(_this, file, xhr);
  61383. }
  61384. return onload.call(_this, file, xhr);
  61385. } catch (e) {
  61386. _this.asyncComplete(file, e.message || 'Exception');
  61387. }
  61388. };
  61389. file.requestObject = xhr;
  61390. file.requestUrl = url;
  61391. // Note: The xdr.send() call is wrapped in a timeout to prevent an issue with the interface where some requests are lost
  61392. // if multiple XDomainRequests are being sent at the same time.
  61393. setTimeout(function () {
  61394. xhr.send();
  61395. }, 0);
  61396. },
  61397. /**
  61398. * Give a bunch of URLs, return the first URL that has an extension this device thinks it can play.
  61399. *
  61400. * It is assumed that the device can play "blob:" or "data:" URIs - There is no mime-type checking on data URIs.
  61401. *
  61402. * @method Phaser.Loader#getVideoURL
  61403. * @private
  61404. * @param {object[]|string[]} urls - See {@link #video} for format.
  61405. * @return {string} The URL to try and fetch; or null.
  61406. */
  61407. getVideoURL: function (urls) {
  61408. for (var i = 0; i < urls.length; i++)
  61409. {
  61410. var url = urls[i];
  61411. var videoType;
  61412. if (url.uri) // {uri: .., type: ..} pair
  61413. {
  61414. videoType = url.type;
  61415. url = url.uri;
  61416. if (this.game.device.canPlayVideo(videoType))
  61417. {
  61418. return url;
  61419. }
  61420. }
  61421. else
  61422. {
  61423. // Assume direct-data URI can be played if not in a paired form; select immediately
  61424. if (url.indexOf("blob:") === 0 || url.indexOf("data:") === 0)
  61425. {
  61426. return url;
  61427. }
  61428. if (url.indexOf("?") >= 0) // Remove query from URL
  61429. {
  61430. url = url.substr(0, url.indexOf("?"));
  61431. }
  61432. var extension = url.substr((Math.max(0, url.lastIndexOf(".")) || Infinity) + 1);
  61433. videoType = extension.toLowerCase();
  61434. if (this.game.device.canPlayVideo(videoType))
  61435. {
  61436. return urls[i];
  61437. }
  61438. }
  61439. }
  61440. return null;
  61441. },
  61442. /**
  61443. * Give a bunch of URLs, return the first URL that has an extension this device thinks it can play.
  61444. *
  61445. * It is assumed that the device can play "blob:" or "data:" URIs - There is no mime-type checking on data URIs.
  61446. *
  61447. * @method Phaser.Loader#getAudioURL
  61448. * @private
  61449. * @param {object[]|string[]} urls - See {@link #audio} for format.
  61450. * @return {string} The URL to try and fetch; or null.
  61451. */
  61452. getAudioURL: function (urls) {
  61453. if (this.game.sound.noAudio)
  61454. {
  61455. return null;
  61456. }
  61457. for (var i = 0; i < urls.length; i++)
  61458. {
  61459. var url = urls[i];
  61460. var audioType;
  61461. if (url.uri) // {uri: .., type: ..} pair
  61462. {
  61463. audioType = url.type;
  61464. url = url.uri;
  61465. if (this.game.device.canPlayAudio(audioType))
  61466. {
  61467. return url;
  61468. }
  61469. }
  61470. else
  61471. {
  61472. // Assume direct-data URI can be played if not in a paired form; select immediately
  61473. if (url.indexOf("blob:") === 0 || url.indexOf("data:") === 0)
  61474. {
  61475. return url;
  61476. }
  61477. if (url.indexOf("?") >= 0) // Remove query from URL
  61478. {
  61479. url = url.substr(0, url.indexOf("?"));
  61480. }
  61481. var extension = url.substr((Math.max(0, url.lastIndexOf(".")) || Infinity) + 1);
  61482. audioType = extension.toLowerCase();
  61483. if (this.game.device.canPlayAudio(audioType))
  61484. {
  61485. return urls[i];
  61486. }
  61487. }
  61488. }
  61489. return null;
  61490. },
  61491. /**
  61492. * Error occurred when loading a file.
  61493. *
  61494. * @method Phaser.Loader#fileError
  61495. * @private
  61496. * @param {object} file
  61497. * @param {?XMLHttpRequest} xhr - XHR request, unspecified if loaded via other means (eg. tags)
  61498. * @param {string} reason
  61499. */
  61500. fileError: function (file, xhr, reason) {
  61501. var url = file.requestUrl || this.transformUrl(file.url, file);
  61502. var message = 'error loading asset from URL ' + url;
  61503. if (!reason && xhr)
  61504. {
  61505. reason = xhr.status;
  61506. }
  61507. if (reason)
  61508. {
  61509. message = message + ' (' + reason + ')';
  61510. }
  61511. this.asyncComplete(file, message);
  61512. },
  61513. /**
  61514. * Called when a file/resources had been downloaded and needs to be processed further.
  61515. *
  61516. * @method Phaser.Loader#fileComplete
  61517. * @private
  61518. * @param {object} file - File loaded
  61519. * @param {?XMLHttpRequest} xhr - XHR request, unspecified if loaded via other means (eg. tags)
  61520. */
  61521. fileComplete: function (file, xhr) {
  61522. var loadNext = true;
  61523. switch (file.type)
  61524. {
  61525. case 'packfile':
  61526. // Pack data must never be false-ish after it is fetched without error
  61527. var data = JSON.parse(xhr.responseText);
  61528. file.data = data || {};
  61529. break;
  61530. case 'image':
  61531. this.cache.addImage(file.key, file.url, file.data);
  61532. break;
  61533. case 'spritesheet':
  61534. this.cache.addSpriteSheet(file.key, file.url, file.data, file.frameWidth, file.frameHeight, file.frameMax, file.margin, file.spacing);
  61535. break;
  61536. case 'textureatlas':
  61537. if (file.atlasURL == null)
  61538. {
  61539. this.cache.addTextureAtlas(file.key, file.url, file.data, file.atlasData, file.format);
  61540. }
  61541. else
  61542. {
  61543. // Load the JSON or XML before carrying on with the next file
  61544. loadNext = false;
  61545. if (file.format === Phaser.Loader.TEXTURE_ATLAS_JSON_ARRAY || file.format === Phaser.Loader.TEXTURE_ATLAS_JSON_HASH || file.format === Phaser.Loader.TEXTURE_ATLAS_JSON_PYXEL)
  61546. {
  61547. this.xhrLoad(file, this.transformUrl(file.atlasURL, file), 'text', this.jsonLoadComplete);
  61548. }
  61549. else if (file.format === Phaser.Loader.TEXTURE_ATLAS_XML_STARLING)
  61550. {
  61551. this.xhrLoad(file, this.transformUrl(file.atlasURL, file), 'text', this.xmlLoadComplete);
  61552. }
  61553. else
  61554. {
  61555. throw new Error("Phaser.Loader. Invalid Texture Atlas format: " + file.format);
  61556. }
  61557. }
  61558. break;
  61559. case 'bitmapfont':
  61560. if (!file.atlasURL)
  61561. {
  61562. this.cache.addBitmapFont(file.key, file.url, file.data, file.atlasData, file.atlasType, file.xSpacing, file.ySpacing);
  61563. }
  61564. else
  61565. {
  61566. // Load the XML before carrying on with the next file
  61567. loadNext = false;
  61568. this.xhrLoad(file, this.transformUrl(file.atlasURL, file), 'text', function (file, xhr) {
  61569. var json;
  61570. try
  61571. {
  61572. // Try to parse as JSON, if it fails, then it's hopefully XML
  61573. json = JSON.parse(xhr.responseText);
  61574. }
  61575. catch (e) {}
  61576. if (!!json)
  61577. {
  61578. file.atlasType = 'json';
  61579. this.jsonLoadComplete(file, xhr);
  61580. }
  61581. else
  61582. {
  61583. file.atlasType = 'xml';
  61584. this.xmlLoadComplete(file, xhr);
  61585. }
  61586. });
  61587. }
  61588. break;
  61589. case 'video':
  61590. if (file.asBlob)
  61591. {
  61592. try
  61593. {
  61594. file.data = xhr.response;
  61595. }
  61596. catch (e)
  61597. {
  61598. throw new Error("Phaser.Loader. Unable to parse video file as Blob: " + file.key);
  61599. }
  61600. }
  61601. this.cache.addVideo(file.key, file.url, file.data, file.asBlob);
  61602. break;
  61603. case 'audio':
  61604. if (this.game.sound.usingWebAudio)
  61605. {
  61606. file.data = xhr.response;
  61607. this.cache.addSound(file.key, file.url, file.data, true, false);
  61608. if (file.autoDecode)
  61609. {
  61610. this.game.sound.decode(file.key);
  61611. }
  61612. }
  61613. else
  61614. {
  61615. this.cache.addSound(file.key, file.url, file.data, false, true);
  61616. }
  61617. break;
  61618. case 'text':
  61619. file.data = xhr.responseText;
  61620. this.cache.addText(file.key, file.url, file.data);
  61621. break;
  61622. case 'shader':
  61623. file.data = xhr.responseText;
  61624. this.cache.addShader(file.key, file.url, file.data);
  61625. break;
  61626. case 'physics':
  61627. var data = JSON.parse(xhr.responseText);
  61628. this.cache.addPhysicsData(file.key, file.url, data, file.format);
  61629. break;
  61630. case 'script':
  61631. file.data = document.createElement('script');
  61632. file.data.language = 'javascript';
  61633. file.data.type = 'text/javascript';
  61634. file.data.defer = false;
  61635. file.data.text = xhr.responseText;
  61636. document.head.appendChild(file.data);
  61637. if (file.callback)
  61638. {
  61639. file.data = file.callback.call(file.callbackContext, file.key, xhr.responseText);
  61640. }
  61641. break;
  61642. case 'binary':
  61643. if (file.callback)
  61644. {
  61645. file.data = file.callback.call(file.callbackContext, file.key, xhr.response);
  61646. }
  61647. else
  61648. {
  61649. file.data = xhr.response;
  61650. }
  61651. this.cache.addBinary(file.key, file.data);
  61652. break;
  61653. }
  61654. if (loadNext)
  61655. {
  61656. this.asyncComplete(file);
  61657. }
  61658. },
  61659. /**
  61660. * Successfully loaded a JSON file - only used for certain types.
  61661. *
  61662. * @method Phaser.Loader#jsonLoadComplete
  61663. * @private
  61664. * @param {object} file - File associated with this request
  61665. * @param {XMLHttpRequest} xhr
  61666. */
  61667. jsonLoadComplete: function (file, xhr) {
  61668. var data = JSON.parse(xhr.responseText);
  61669. if (file.type === 'tilemap')
  61670. {
  61671. this.cache.addTilemap(file.key, file.url, data, file.format);
  61672. }
  61673. else if (file.type === 'bitmapfont')
  61674. {
  61675. this.cache.addBitmapFont(file.key, file.url, file.data, data, file.atlasType, file.xSpacing, file.ySpacing);
  61676. }
  61677. else if (file.type === 'json')
  61678. {
  61679. this.cache.addJSON(file.key, file.url, data);
  61680. }
  61681. else
  61682. {
  61683. this.cache.addTextureAtlas(file.key, file.url, file.data, data, file.format);
  61684. }
  61685. this.asyncComplete(file);
  61686. },
  61687. /**
  61688. * Successfully loaded a CSV file - only used for certain types.
  61689. *
  61690. * @method Phaser.Loader#csvLoadComplete
  61691. * @private
  61692. * @param {object} file - File associated with this request
  61693. * @param {XMLHttpRequest} xhr
  61694. */
  61695. csvLoadComplete: function (file, xhr) {
  61696. var data = xhr.responseText;
  61697. this.cache.addTilemap(file.key, file.url, data, file.format);
  61698. this.asyncComplete(file);
  61699. },
  61700. /**
  61701. * Successfully loaded an XML file - only used for certain types.
  61702. *
  61703. * @method Phaser.Loader#xmlLoadComplete
  61704. * @private
  61705. * @param {object} file - File associated with this request
  61706. * @param {XMLHttpRequest} xhr
  61707. */
  61708. xmlLoadComplete: function (file, xhr) {
  61709. // Always try parsing the content as XML, regardless of actually response type
  61710. var data = xhr.responseText;
  61711. var xml = this.parseXml(data);
  61712. if (!xml)
  61713. {
  61714. var responseType = xhr.responseType || xhr.contentType; // contentType for MS-XDomainRequest
  61715. console.warn('Phaser.Loader - ' + file.key + ': invalid XML (' + responseType + ')');
  61716. this.asyncComplete(file, "invalid XML");
  61717. return;
  61718. }
  61719. if (file.type === 'bitmapfont')
  61720. {
  61721. this.cache.addBitmapFont(file.key, file.url, file.data, xml, file.atlasType, file.xSpacing, file.ySpacing);
  61722. }
  61723. else if (file.type === 'textureatlas')
  61724. {
  61725. this.cache.addTextureAtlas(file.key, file.url, file.data, xml, file.format);
  61726. }
  61727. else if (file.type === 'xml')
  61728. {
  61729. this.cache.addXML(file.key, file.url, xml);
  61730. }
  61731. this.asyncComplete(file);
  61732. },
  61733. /**
  61734. * Parses string data as XML.
  61735. *
  61736. * @method Phaser.Loader#parseXml
  61737. * @private
  61738. * @param {string} data - The XML text to parse
  61739. * @return {?XMLDocument} Returns the xml document, or null if such could not parsed to a valid document.
  61740. */
  61741. parseXml: function (data) {
  61742. var xml;
  61743. try
  61744. {
  61745. if (window['DOMParser'])
  61746. {
  61747. var domparser = new DOMParser();
  61748. xml = domparser.parseFromString(data, "text/xml");
  61749. }
  61750. else
  61751. {
  61752. xml = new ActiveXObject("Microsoft.XMLDOM");
  61753. // Why is this 'false'?
  61754. xml.async = 'false';
  61755. xml.loadXML(data);
  61756. }
  61757. }
  61758. catch (e)
  61759. {
  61760. xml = null;
  61761. }
  61762. if (!xml || !xml.documentElement || xml.getElementsByTagName("parsererror").length)
  61763. {
  61764. return null;
  61765. }
  61766. else
  61767. {
  61768. return xml;
  61769. }
  61770. },
  61771. /**
  61772. * Update the loading sprite progress.
  61773. *
  61774. * @method Phaser.Loader#nextFile
  61775. * @private
  61776. * @param {object} previousFile
  61777. * @param {boolean} success - Whether the previous asset loaded successfully or not.
  61778. */
  61779. updateProgress: function () {
  61780. if (this.preloadSprite)
  61781. {
  61782. if (this.preloadSprite.direction === 0)
  61783. {
  61784. this.preloadSprite.rect.width = Math.floor((this.preloadSprite.width / 100) * this.progress);
  61785. }
  61786. else
  61787. {
  61788. this.preloadSprite.rect.height = Math.floor((this.preloadSprite.height / 100) * this.progress);
  61789. }
  61790. if (this.preloadSprite.sprite)
  61791. {
  61792. this.preloadSprite.sprite.updateCrop();
  61793. }
  61794. else
  61795. {
  61796. // We seem to have lost our sprite - maybe it was destroyed?
  61797. this.preloadSprite = null;
  61798. }
  61799. }
  61800. },
  61801. /**
  61802. * Returns the number of files that have already been loaded, even if they errored.
  61803. *
  61804. * @method Phaser.Loader#totalLoadedFiles
  61805. * @protected
  61806. * @return {number} The number of files that have already been loaded (even if they errored)
  61807. */
  61808. totalLoadedFiles: function () {
  61809. return this._loadedFileCount;
  61810. },
  61811. /**
  61812. * Returns the number of files still waiting to be processed in the load queue. This value decreases as each file in the queue is loaded.
  61813. *
  61814. * @method Phaser.Loader#totalQueuedFiles
  61815. * @protected
  61816. * @return {number} The number of files that still remain in the load queue.
  61817. */
  61818. totalQueuedFiles: function () {
  61819. return this._totalFileCount - this._loadedFileCount;
  61820. },
  61821. /**
  61822. * Returns the number of asset packs that have already been loaded, even if they errored.
  61823. *
  61824. * @method Phaser.Loader#totalLoadedPacks
  61825. * @protected
  61826. * @return {number} The number of asset packs that have already been loaded (even if they errored)
  61827. */
  61828. totalLoadedPacks: function () {
  61829. return this._totalPackCount;
  61830. },
  61831. /**
  61832. * Returns the number of asset packs still waiting to be processed in the load queue. This value decreases as each pack in the queue is loaded.
  61833. *
  61834. * @method Phaser.Loader#totalQueuedPacks
  61835. * @protected
  61836. * @return {number} The number of asset packs that still remain in the load queue.
  61837. */
  61838. totalQueuedPacks: function () {
  61839. return this._totalPackCount - this._loadedPackCount;
  61840. }
  61841. };
  61842. /**
  61843. * The non-rounded load progress value (from 0.0 to 100.0).
  61844. *
  61845. * A general indicator of the progress.
  61846. * It is possible for the progress to decrease, after `onLoadStart`, if more files are dynamically added.
  61847. *
  61848. * @name Phaser.Loader#progressFloat
  61849. * @property {number}
  61850. */
  61851. Object.defineProperty(Phaser.Loader.prototype, "progressFloat", {
  61852. get: function () {
  61853. var progress = (this._loadedFileCount / this._totalFileCount) * 100;
  61854. return Phaser.Math.clamp(progress || 0, 0, 100);
  61855. }
  61856. });
  61857. /**
  61858. * The rounded load progress percentage value (from 0 to 100). See {@link Phaser.Loader#progressFloat}.
  61859. *
  61860. * @name Phaser.Loader#progress
  61861. * @property {integer}
  61862. */
  61863. Object.defineProperty(Phaser.Loader.prototype, "progress", {
  61864. get: function () {
  61865. return Math.round(this.progressFloat);
  61866. }
  61867. });
  61868. Phaser.Loader.prototype.constructor = Phaser.Loader;
  61869. /**
  61870. * @author Richard Davey <rich@photonstorm.com>
  61871. * @copyright 2016 Photon Storm Ltd.
  61872. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  61873. */
  61874. /**
  61875. * Phaser.LoaderParser parses data objects from Phaser.Loader that need more preparation before they can be inserted into the Cache.
  61876. *
  61877. * @class Phaser.LoaderParser
  61878. */
  61879. Phaser.LoaderParser = {
  61880. /**
  61881. * Alias for xmlBitmapFont, for backwards compatibility.
  61882. *
  61883. * @method Phaser.LoaderParser.bitmapFont
  61884. * @param {object} xml - XML data you want to parse.
  61885. * @param {PIXI.BaseTexture} baseTexture - The BaseTexture this font uses.
  61886. * @param {number} [xSpacing=0] - Additional horizontal spacing between the characters.
  61887. * @param {number} [ySpacing=0] - Additional vertical spacing between the characters.
  61888. * @return {object} The parsed Bitmap Font data.
  61889. */
  61890. bitmapFont: function (xml, baseTexture, xSpacing, ySpacing) {
  61891. return this.xmlBitmapFont(xml, baseTexture, xSpacing, ySpacing);
  61892. },
  61893. /**
  61894. * Parse a Bitmap Font from an XML file.
  61895. *
  61896. * @method Phaser.LoaderParser.xmlBitmapFont
  61897. * @param {object} xml - XML data you want to parse.
  61898. * @param {PIXI.BaseTexture} baseTexture - The BaseTexture this font uses.
  61899. * @param {number} [xSpacing=0] - Additional horizontal spacing between the characters.
  61900. * @param {number} [ySpacing=0] - Additional vertical spacing between the characters.
  61901. * @return {object} The parsed Bitmap Font data.
  61902. */
  61903. xmlBitmapFont: function (xml, baseTexture, xSpacing, ySpacing) {
  61904. var data = {};
  61905. var info = xml.getElementsByTagName('info')[0];
  61906. var common = xml.getElementsByTagName('common')[0];
  61907. data.font = info.getAttribute('face');
  61908. data.size = parseInt(info.getAttribute('size'), 10);
  61909. data.lineHeight = parseInt(common.getAttribute('lineHeight'), 10) + ySpacing;
  61910. data.chars = {};
  61911. var letters = xml.getElementsByTagName('char');
  61912. for (var i = 0; i < letters.length; i++)
  61913. {
  61914. var charCode = parseInt(letters[i].getAttribute('id'), 10);
  61915. data.chars[charCode] = {
  61916. x: parseInt(letters[i].getAttribute('x'), 10),
  61917. y: parseInt(letters[i].getAttribute('y'), 10),
  61918. width: parseInt(letters[i].getAttribute('width'), 10),
  61919. height: parseInt(letters[i].getAttribute('height'), 10),
  61920. xOffset: parseInt(letters[i].getAttribute('xoffset'), 10),
  61921. yOffset: parseInt(letters[i].getAttribute('yoffset'), 10),
  61922. xAdvance: parseInt(letters[i].getAttribute('xadvance'), 10) + xSpacing,
  61923. kerning: {}
  61924. };
  61925. }
  61926. var kernings = xml.getElementsByTagName('kerning');
  61927. for (i = 0; i < kernings.length; i++)
  61928. {
  61929. var first = parseInt(kernings[i].getAttribute('first'), 10);
  61930. var second = parseInt(kernings[i].getAttribute('second'), 10);
  61931. var amount = parseInt(kernings[i].getAttribute('amount'), 10);
  61932. data.chars[second].kerning[first] = amount;
  61933. }
  61934. return this.finalizeBitmapFont(baseTexture, data);
  61935. },
  61936. /**
  61937. * Parse a Bitmap Font from a JSON file.
  61938. *
  61939. * @method Phaser.LoaderParser.jsonBitmapFont
  61940. * @param {object} json - JSON data you want to parse.
  61941. * @param {PIXI.BaseTexture} baseTexture - The BaseTexture this font uses.
  61942. * @param {number} [xSpacing=0] - Additional horizontal spacing between the characters.
  61943. * @param {number} [ySpacing=0] - Additional vertical spacing between the characters.
  61944. * @return {object} The parsed Bitmap Font data.
  61945. */
  61946. jsonBitmapFont: function (json, baseTexture, xSpacing, ySpacing) {
  61947. var data = {
  61948. font: json.font.info._face,
  61949. size: parseInt(json.font.info._size, 10),
  61950. lineHeight: parseInt(json.font.common._lineHeight, 10) + ySpacing,
  61951. chars: {}
  61952. };
  61953. json.font.chars["char"].forEach(
  61954. function parseChar(letter) {
  61955. var charCode = parseInt(letter._id, 10);
  61956. data.chars[charCode] = {
  61957. x: parseInt(letter._x, 10),
  61958. y: parseInt(letter._y, 10),
  61959. width: parseInt(letter._width, 10),
  61960. height: parseInt(letter._height, 10),
  61961. xOffset: parseInt(letter._xoffset, 10),
  61962. yOffset: parseInt(letter._yoffset, 10),
  61963. xAdvance: parseInt(letter._xadvance, 10) + xSpacing,
  61964. kerning: {}
  61965. };
  61966. }
  61967. );
  61968. if (json.font.kernings && json.font.kernings.kerning) {
  61969. json.font.kernings.kerning.forEach(
  61970. function parseKerning(kerning) {
  61971. data.chars[kerning._second].kerning[kerning._first] = parseInt(kerning._amount, 10);
  61972. }
  61973. );
  61974. }
  61975. return this.finalizeBitmapFont(baseTexture, data);
  61976. },
  61977. /**
  61978. * Finalize Bitmap Font parsing.
  61979. *
  61980. * @method Phaser.LoaderParser.finalizeBitmapFont
  61981. * @private
  61982. * @param {PIXI.BaseTexture} baseTexture - The BaseTexture this font uses.
  61983. * @param {object} bitmapFontData - Pre-parsed bitmap font data.
  61984. * @return {object} The parsed Bitmap Font data.
  61985. */
  61986. finalizeBitmapFont: function (baseTexture, bitmapFontData) {
  61987. Object.keys(bitmapFontData.chars).forEach(
  61988. function addTexture(charCode) {
  61989. var letter = bitmapFontData.chars[charCode];
  61990. letter.texture = new PIXI.Texture(baseTexture, new Phaser.Rectangle(letter.x, letter.y, letter.width, letter.height));
  61991. }
  61992. );
  61993. return bitmapFontData;
  61994. }
  61995. };
  61996. /**
  61997. * @author Jeremy Dowell <jeremy@codevinsky.com>
  61998. * @author Richard Davey <rich@photonstorm.com>
  61999. * @copyright 2016 Photon Storm Ltd.
  62000. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  62001. */
  62002. /**
  62003. * Audio Sprites are a combination of audio files and a JSON configuration.
  62004. * The JSON follows the format of that created by https://github.com/tonistiigi/audiosprite
  62005. *
  62006. * @class Phaser.AudioSprite
  62007. * @constructor
  62008. * @param {Phaser.Game} game - Reference to the current game instance.
  62009. * @param {string} key - Asset key for the sound.
  62010. */
  62011. Phaser.AudioSprite = function (game, key) {
  62012. /**
  62013. * A reference to the currently running Game.
  62014. * @property {Phaser.Game} game
  62015. */
  62016. this.game = game;
  62017. /**
  62018. * Asset key for the Audio Sprite.
  62019. * @property {string} key
  62020. */
  62021. this.key = key;
  62022. /**
  62023. * JSON audio atlas object.
  62024. * @property {object} config
  62025. */
  62026. this.config = this.game.cache.getJSON(key + '-audioatlas');
  62027. /**
  62028. * If a sound is set to auto play, this holds the marker key of it.
  62029. * @property {string} autoplayKey
  62030. */
  62031. this.autoplayKey = null;
  62032. /**
  62033. * Is a sound set to autoplay or not?
  62034. * @property {boolean} autoplay
  62035. * @default
  62036. */
  62037. this.autoplay = false;
  62038. /**
  62039. * An object containing the Phaser.Sound objects for the Audio Sprite.
  62040. * @property {object} sounds
  62041. */
  62042. this.sounds = {};
  62043. for (var k in this.config.spritemap)
  62044. {
  62045. var marker = this.config.spritemap[k];
  62046. var sound = this.game.add.sound(this.key);
  62047. sound.addMarker(k, marker.start, (marker.end - marker.start), null, marker.loop);
  62048. this.sounds[k] = sound;
  62049. }
  62050. if (this.config.autoplay)
  62051. {
  62052. this.autoplayKey = this.config.autoplay;
  62053. this.play(this.autoplayKey);
  62054. this.autoplay = this.sounds[this.autoplayKey];
  62055. }
  62056. };
  62057. Phaser.AudioSprite.prototype = {
  62058. /**
  62059. * Play a sound with the given name.
  62060. *
  62061. * @method Phaser.AudioSprite#play
  62062. * @param {string} [marker] - The name of sound to play
  62063. * @param {number} [volume=1] - Volume of the sound you want to play. If none is given it will use the volume given to the Sound when it was created (which defaults to 1 if none was specified).
  62064. * @return {Phaser.Sound} This sound instance.
  62065. */
  62066. play: function (marker, volume) {
  62067. if (volume === undefined) { volume = 1; }
  62068. return this.sounds[marker].play(marker, null, volume);
  62069. },
  62070. /**
  62071. * Stop a sound with the given name.
  62072. *
  62073. * @method Phaser.AudioSprite#stop
  62074. * @param {string} [marker=''] - The name of sound to stop. If none is given it will stop all sounds in the audio sprite.
  62075. */
  62076. stop: function (marker) {
  62077. if (!marker)
  62078. {
  62079. for (var key in this.sounds)
  62080. {
  62081. this.sounds[key].stop();
  62082. }
  62083. }
  62084. else
  62085. {
  62086. this.sounds[marker].stop();
  62087. }
  62088. },
  62089. /**
  62090. * Get a sound with the given name.
  62091. *
  62092. * @method Phaser.AudioSprite#get
  62093. * @param {string} marker - The name of sound to get.
  62094. * @return {Phaser.Sound} The sound instance.
  62095. */
  62096. get: function(marker) {
  62097. return this.sounds[marker];
  62098. }
  62099. };
  62100. Phaser.AudioSprite.prototype.constructor = Phaser.AudioSprite;
  62101. /**
  62102. * @author Richard Davey <rich@photonstorm.com>
  62103. * @copyright 2016 Photon Storm Ltd.
  62104. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  62105. */
  62106. /**
  62107. * The Sound class constructor.
  62108. *
  62109. * @class Phaser.Sound
  62110. * @constructor
  62111. * @param {Phaser.Game} game - Reference to the current game instance.
  62112. * @param {string} key - Asset key for the sound.
  62113. * @param {number} [volume=1] - Default value for the volume, between 0 and 1.
  62114. * @param {boolean} [loop=false] - Whether or not the sound will loop.
  62115. */
  62116. Phaser.Sound = function (game, key, volume, loop, connect) {
  62117. if (volume === undefined) { volume = 1; }
  62118. if (loop === undefined) { loop = false; }
  62119. if (connect === undefined) { connect = game.sound.connectToMaster; }
  62120. /**
  62121. * A reference to the currently running Game.
  62122. * @property {Phaser.Game} game
  62123. */
  62124. this.game = game;
  62125. /**
  62126. * @property {string} name - Name of the sound.
  62127. */
  62128. this.name = key;
  62129. /**
  62130. * @property {string} key - Asset key for the sound.
  62131. */
  62132. this.key = key;
  62133. /**
  62134. * @property {boolean} loop - Whether or not the sound or current sound marker will loop.
  62135. */
  62136. this.loop = loop;
  62137. /**
  62138. * @property {object} markers - The sound markers.
  62139. */
  62140. this.markers = {};
  62141. /**
  62142. * @property {AudioContext} context - Reference to the AudioContext instance.
  62143. */
  62144. this.context = null;
  62145. /**
  62146. * @property {boolean} autoplay - Boolean indicating whether the sound should start automatically.
  62147. */
  62148. this.autoplay = false;
  62149. /**
  62150. * @property {number} totalDuration - The total duration of the sound in seconds.
  62151. */
  62152. this.totalDuration = 0;
  62153. /**
  62154. * @property {number} startTime - The time the Sound starts at (typically 0 unless starting from a marker)
  62155. * @default
  62156. */
  62157. this.startTime = 0;
  62158. /**
  62159. * @property {number} currentTime - The current time the sound is at.
  62160. */
  62161. this.currentTime = 0;
  62162. /**
  62163. * @property {number} duration - The duration of the current sound marker in seconds.
  62164. */
  62165. this.duration = 0;
  62166. /**
  62167. * @property {number} durationMS - The duration of the current sound marker in ms.
  62168. */
  62169. this.durationMS = 0;
  62170. /**
  62171. * @property {number} position - The position of the current sound marker.
  62172. */
  62173. this.position = 0;
  62174. /**
  62175. * @property {number} stopTime - The time the sound stopped.
  62176. */
  62177. this.stopTime = 0;
  62178. /**
  62179. * @property {boolean} paused - true if the sound is paused, otherwise false.
  62180. * @default
  62181. */
  62182. this.paused = false;
  62183. /**
  62184. * @property {number} pausedPosition - The position the sound had reached when it was paused.
  62185. */
  62186. this.pausedPosition = 0;
  62187. /**
  62188. * @property {number} pausedTime - The game time at which the sound was paused.
  62189. */
  62190. this.pausedTime = 0;
  62191. /**
  62192. * @property {boolean} isPlaying - true if the sound is currently playing, otherwise false.
  62193. * @default
  62194. */
  62195. this.isPlaying = false;
  62196. /**
  62197. * @property {string} currentMarker - The string ID of the currently playing marker, if any.
  62198. * @default
  62199. */
  62200. this.currentMarker = '';
  62201. /**
  62202. * @property {Phaser.Tween} fadeTween - The tween that fades the audio, set via Sound.fadeIn and Sound.fadeOut.
  62203. */
  62204. this.fadeTween = null;
  62205. /**
  62206. * @property {boolean} pendingPlayback - true if the sound file is pending playback
  62207. * @readonly
  62208. */
  62209. this.pendingPlayback = false;
  62210. /**
  62211. * @property {boolean} override - if true when you play this sound it will always start from the beginning.
  62212. * @default
  62213. */
  62214. this.override = false;
  62215. /**
  62216. * @property {boolean} allowMultiple - This will allow you to have multiple instances of this Sound playing at once. This is only useful when running under Web Audio, and we recommend you implement a local pooling system to not flood the sound channels.
  62217. * @default
  62218. */
  62219. this.allowMultiple = false;
  62220. /**
  62221. * @property {boolean} usingWebAudio - true if this sound is being played with Web Audio.
  62222. * @readonly
  62223. */
  62224. this.usingWebAudio = this.game.sound.usingWebAudio;
  62225. /**
  62226. * @property {boolean} usingAudioTag - true if the sound is being played via the Audio tag.
  62227. */
  62228. this.usingAudioTag = this.game.sound.usingAudioTag;
  62229. /**
  62230. * @property {object} externalNode - If defined this Sound won't connect to the SoundManager master gain node, but will instead connect to externalNode.
  62231. */
  62232. this.externalNode = null;
  62233. /**
  62234. * @property {object} masterGainNode - The master gain node in a Web Audio system.
  62235. */
  62236. this.masterGainNode = null;
  62237. /**
  62238. * @property {object} gainNode - The gain node in a Web Audio system.
  62239. */
  62240. this.gainNode = null;
  62241. /**
  62242. * @property {object} _sound - Internal var.
  62243. * @private
  62244. */
  62245. this._sound = null;
  62246. if (this.usingWebAudio)
  62247. {
  62248. this.context = this.game.sound.context;
  62249. this.masterGainNode = this.game.sound.masterGain;
  62250. if (this.context.createGain === undefined)
  62251. {
  62252. this.gainNode = this.context.createGainNode();
  62253. }
  62254. else
  62255. {
  62256. this.gainNode = this.context.createGain();
  62257. }
  62258. this.gainNode.gain.value = volume * this.game.sound.volume;
  62259. if (connect)
  62260. {
  62261. this.gainNode.connect(this.masterGainNode);
  62262. }
  62263. }
  62264. else if (this.usingAudioTag)
  62265. {
  62266. if (this.game.cache.getSound(key) && this.game.cache.isSoundReady(key))
  62267. {
  62268. this._sound = this.game.cache.getSoundData(key);
  62269. this.totalDuration = 0;
  62270. if (this._sound.duration)
  62271. {
  62272. this.totalDuration = this._sound.duration;
  62273. }
  62274. }
  62275. else
  62276. {
  62277. this.game.cache.onSoundUnlock.add(this.soundHasUnlocked, this);
  62278. }
  62279. }
  62280. /**
  62281. * @property {Phaser.Signal} onDecoded - The onDecoded event is dispatched when the sound has finished decoding (typically for mp3 files)
  62282. */
  62283. this.onDecoded = new Phaser.Signal();
  62284. /**
  62285. * @property {Phaser.Signal} onPlay - The onPlay event is dispatched each time this sound is played.
  62286. */
  62287. this.onPlay = new Phaser.Signal();
  62288. /**
  62289. * @property {Phaser.Signal} onPause - The onPause event is dispatched when this sound is paused.
  62290. */
  62291. this.onPause = new Phaser.Signal();
  62292. /**
  62293. * @property {Phaser.Signal} onResume - The onResume event is dispatched when this sound is resumed from a paused state.
  62294. */
  62295. this.onResume = new Phaser.Signal();
  62296. /**
  62297. * @property {Phaser.Signal} onLoop - The onLoop event is dispatched when this sound loops during playback.
  62298. */
  62299. this.onLoop = new Phaser.Signal();
  62300. /**
  62301. * @property {Phaser.Signal} onStop - The onStop event is dispatched when this sound stops playback.
  62302. */
  62303. this.onStop = new Phaser.Signal();
  62304. /**
  62305. * @property {Phaser.Signal} onMute - The onMute event is dispatched when this sound is muted.
  62306. */
  62307. this.onMute = new Phaser.Signal();
  62308. /**
  62309. * @property {Phaser.Signal} onMarkerComplete - The onMarkerComplete event is dispatched when a marker within this sound completes playback.
  62310. */
  62311. this.onMarkerComplete = new Phaser.Signal();
  62312. /**
  62313. * @property {Phaser.Signal} onFadeComplete - The onFadeComplete event is dispatched when this sound finishes fading either in or out.
  62314. */
  62315. this.onFadeComplete = new Phaser.Signal();
  62316. /**
  62317. * @property {number} _volume - The global audio volume. A value between 0 (silence) and 1 (full volume).
  62318. * @private
  62319. */
  62320. this._volume = volume;
  62321. /**
  62322. * @property {any} _buffer - Decoded data buffer / Audio tag.
  62323. * @private
  62324. */
  62325. this._buffer = null;
  62326. /**
  62327. * @property {boolean} _muted - Boolean indicating whether the sound is muted or not.
  62328. * @private
  62329. */
  62330. this._muted = false;
  62331. /**
  62332. * @property {number} _tempMarker - Internal marker var.
  62333. * @private
  62334. */
  62335. this._tempMarker = 0;
  62336. /**
  62337. * @property {number} _tempPosition - Internal marker var.
  62338. * @private
  62339. */
  62340. this._tempPosition = 0;
  62341. /**
  62342. * @property {number} _tempVolume - Internal marker var.
  62343. * @private
  62344. */
  62345. this._tempVolume = 0;
  62346. /**
  62347. * @property {number} _tempPause - Internal marker var.
  62348. * @private
  62349. */
  62350. this._tempPause = 0;
  62351. /**
  62352. * @property {number} _muteVolume - Internal cache var.
  62353. * @private
  62354. */
  62355. this._muteVolume = 0;
  62356. /**
  62357. * @property {boolean} _tempLoop - Internal cache var.
  62358. * @private
  62359. */
  62360. this._tempLoop = 0;
  62361. /**
  62362. * @property {boolean} _paused - Was this sound paused via code or a game event?
  62363. * @private
  62364. */
  62365. this._paused = false;
  62366. /**
  62367. * @property {boolean} _onDecodedEventDispatched - Was the onDecoded event dispatched?
  62368. * @private
  62369. */
  62370. this._onDecodedEventDispatched = false;
  62371. };
  62372. Phaser.Sound.prototype = {
  62373. /**
  62374. * Called automatically when this sound is unlocked.
  62375. * @method Phaser.Sound#soundHasUnlocked
  62376. * @param {string} key - The Phaser.Cache key of the sound file to check for decoding.
  62377. * @protected
  62378. */
  62379. soundHasUnlocked: function (key) {
  62380. if (key === this.key)
  62381. {
  62382. this._sound = this.game.cache.getSoundData(this.key);
  62383. this.totalDuration = this._sound.duration;
  62384. }
  62385. },
  62386. /**
  62387. * Adds a marker into the current Sound. A marker is represented by a unique key and a start time and duration.
  62388. * This allows you to bundle multiple sounds together into a single audio file and use markers to jump between them for playback.
  62389. *
  62390. * @method Phaser.Sound#addMarker
  62391. * @param {string} name - A unique name for this marker, i.e. 'explosion', 'gunshot', etc.
  62392. * @param {number} start - The start point of this marker in the audio file, given in seconds. 2.5 = 2500ms, 0.5 = 500ms, etc.
  62393. * @param {number} [duration=1] - The duration of the marker in seconds. 2.5 = 2500ms, 0.5 = 500ms, etc.
  62394. * @param {number} [volume=1] - The volume the sound will play back at, between 0 (silent) and 1 (full volume).
  62395. * @param {boolean} [loop=false] - Sets if the sound will loop or not.
  62396. */
  62397. addMarker: function (name, start, duration, volume, loop) {
  62398. if (duration === undefined || duration === null) { duration = 1; }
  62399. if (volume === undefined || volume === null) { volume = 1; }
  62400. if (loop === undefined) { loop = false; }
  62401. this.markers[name] = {
  62402. name: name,
  62403. start: start,
  62404. stop: start + duration,
  62405. volume: volume,
  62406. duration: duration,
  62407. durationMS: duration * 1000,
  62408. loop: loop
  62409. };
  62410. },
  62411. /**
  62412. * Removes a marker from the sound.
  62413. * @method Phaser.Sound#removeMarker
  62414. * @param {string} name - The key of the marker to remove.
  62415. */
  62416. removeMarker: function (name) {
  62417. delete this.markers[name];
  62418. },
  62419. /**
  62420. * Called automatically by the AudioContext when the sound stops playing.
  62421. * Doesn't get called if the sound is set to loop or is a section of an Audio Sprite.
  62422. *
  62423. * @method Phaser.Sound#onEndedHandler
  62424. * @protected
  62425. */
  62426. onEndedHandler: function () {
  62427. this._sound.onended = null;
  62428. this.isPlaying = false;
  62429. this.currentTime = this.durationMS;
  62430. this.stop();
  62431. },
  62432. /**
  62433. * Called automatically by Phaser.SoundManager.
  62434. * @method Phaser.Sound#update
  62435. * @protected
  62436. */
  62437. update: function () {
  62438. if (!this.game.cache.checkSoundKey(this.key))
  62439. {
  62440. this.destroy();
  62441. return;
  62442. }
  62443. if (this.isDecoded && !this._onDecodedEventDispatched)
  62444. {
  62445. this.onDecoded.dispatch(this);
  62446. this._onDecodedEventDispatched = true;
  62447. }
  62448. if (this.pendingPlayback && this.game.cache.isSoundReady(this.key))
  62449. {
  62450. this.pendingPlayback = false;
  62451. this.play(this._tempMarker, this._tempPosition, this._tempVolume, this._tempLoop);
  62452. }
  62453. if (this.isPlaying)
  62454. {
  62455. this.currentTime = this.game.time.time - this.startTime;
  62456. if (this.currentTime >= this.durationMS)
  62457. {
  62458. if (this.usingWebAudio)
  62459. {
  62460. if (this.loop)
  62461. {
  62462. // won't work with markers, needs to reset the position
  62463. this.onLoop.dispatch(this);
  62464. // Gets reset by the play function
  62465. this.isPlaying = false;
  62466. if (this.currentMarker === '')
  62467. {
  62468. this.currentTime = 0;
  62469. this.startTime = this.game.time.time;
  62470. this.isPlaying = true; // play not called again in this case
  62471. }
  62472. else
  62473. {
  62474. this.onMarkerComplete.dispatch(this.currentMarker, this);
  62475. this.play(this.currentMarker, 0, this.volume, true, true);
  62476. }
  62477. }
  62478. else
  62479. {
  62480. // Stop if we're using an audio marker, otherwise we let onended handle it
  62481. if (this.currentMarker !== '')
  62482. {
  62483. this.stop();
  62484. }
  62485. }
  62486. }
  62487. else
  62488. {
  62489. if (this.loop)
  62490. {
  62491. this.onLoop.dispatch(this);
  62492. if (this.currentMarker === '')
  62493. {
  62494. this.currentTime = 0;
  62495. this.startTime = this.game.time.time;
  62496. }
  62497. // Gets reset by the play function
  62498. this.isPlaying = false;
  62499. this.play(this.currentMarker, 0, this.volume, true, true);
  62500. }
  62501. else
  62502. {
  62503. this.stop();
  62504. }
  62505. }
  62506. }
  62507. }
  62508. },
  62509. /**
  62510. * Loops this entire sound. If you need to loop a section of it then use Sound.play and the marker and loop parameters.
  62511. *
  62512. * @method Phaser.Sound#loopFull
  62513. * @param {number} [volume=1] - Volume of the sound you want to play. If none is given it will use the volume given to the Sound when it was created (which defaults to 1 if none was specified).
  62514. * @return {Phaser.Sound} This sound instance.
  62515. */
  62516. loopFull: function (volume) {
  62517. return this.play(null, 0, volume, true);
  62518. },
  62519. /**
  62520. * Play this sound, or a marked section of it.
  62521. *
  62522. * @method Phaser.Sound#play
  62523. * @param {string} [marker=''] - If you want to play a marker then give the key here, otherwise leave blank to play the full sound.
  62524. * @param {number} [position=0] - The starting position to play the sound from - this is ignored if you provide a marker.
  62525. * @param {number} [volume=1] - Volume of the sound you want to play. If none is given it will use the volume given to the Sound when it was created (which defaults to 1 if none was specified).
  62526. * @param {boolean} [loop=false] - Loop when finished playing? If not using a marker / audio sprite the looping will be done via the WebAudio loop property, otherwise it's time based.
  62527. * @param {boolean} [forceRestart=true] - If the sound is already playing you can set forceRestart to restart it from the beginning.
  62528. * @return {Phaser.Sound} This sound instance.
  62529. */
  62530. play: function (marker, position, volume, loop, forceRestart) {
  62531. if (marker === undefined || marker === false || marker === null) { marker = ''; }
  62532. if (forceRestart === undefined) { forceRestart = true; }
  62533. if (this.isPlaying && !this.allowMultiple && !forceRestart && !this.override)
  62534. {
  62535. // Use Restart instead
  62536. return this;
  62537. }
  62538. if (this._sound && this.isPlaying && !this.allowMultiple && (this.override || forceRestart))
  62539. {
  62540. if (this.usingWebAudio)
  62541. {
  62542. if (this._sound.stop === undefined)
  62543. {
  62544. this._sound.noteOff(0);
  62545. }
  62546. else
  62547. {
  62548. try {
  62549. this._sound.stop(0);
  62550. }
  62551. catch (e) {
  62552. }
  62553. }
  62554. if (this.externalNode)
  62555. {
  62556. this._sound.disconnect(this.externalNode);
  62557. }
  62558. else if (this.gainNode)
  62559. {
  62560. this._sound.disconnect(this.gainNode);
  62561. }
  62562. }
  62563. else if (this.usingAudioTag)
  62564. {
  62565. this._sound.pause();
  62566. this._sound.currentTime = 0;
  62567. }
  62568. this.isPlaying = false;
  62569. }
  62570. if (marker === '' && Object.keys(this.markers).length > 0)
  62571. {
  62572. // If they didn't specify a marker but this is an audio sprite,
  62573. // we should never play the entire thing
  62574. return this;
  62575. }
  62576. if (marker !== '')
  62577. {
  62578. if (this.markers[marker])
  62579. {
  62580. this.currentMarker = marker;
  62581. // Playing a marker? Then we default to the marker values
  62582. this.position = this.markers[marker].start;
  62583. this.volume = this.markers[marker].volume;
  62584. this.loop = this.markers[marker].loop;
  62585. this.duration = this.markers[marker].duration;
  62586. this.durationMS = this.markers[marker].durationMS;
  62587. if (typeof volume !== 'undefined')
  62588. {
  62589. this.volume = volume;
  62590. }
  62591. if (typeof loop !== 'undefined')
  62592. {
  62593. this.loop = loop;
  62594. }
  62595. this._tempMarker = marker;
  62596. this._tempPosition = this.position;
  62597. this._tempVolume = this.volume;
  62598. this._tempLoop = this.loop;
  62599. }
  62600. else
  62601. {
  62602. console.warn("Phaser.Sound.play: audio marker " + marker + " doesn't exist");
  62603. return this;
  62604. }
  62605. }
  62606. else
  62607. {
  62608. position = position || 0;
  62609. if (volume === undefined) { volume = this._volume; }
  62610. if (loop === undefined) { loop = this.loop; }
  62611. this.position = Math.max(0, position);
  62612. this.volume = volume;
  62613. this.loop = loop;
  62614. this.duration = 0;
  62615. this.durationMS = 0;
  62616. this._tempMarker = marker;
  62617. this._tempPosition = position;
  62618. this._tempVolume = volume;
  62619. this._tempLoop = loop;
  62620. }
  62621. if (this.usingWebAudio)
  62622. {
  62623. // Does the sound need decoding?
  62624. if (this.game.cache.isSoundDecoded(this.key))
  62625. {
  62626. this._sound = this.context.createBufferSource();
  62627. if (this.externalNode)
  62628. {
  62629. this._sound.connect(this.externalNode);
  62630. }
  62631. else
  62632. {
  62633. this._sound.connect(this.gainNode);
  62634. }
  62635. this._buffer = this.game.cache.getSoundData(this.key);
  62636. this._sound.buffer = this._buffer;
  62637. if (this.loop && marker === '')
  62638. {
  62639. this._sound.loop = true;
  62640. }
  62641. if (!this.loop && marker === '')
  62642. {
  62643. this._sound.onended = this.onEndedHandler.bind(this);
  62644. }
  62645. this.totalDuration = this._sound.buffer.duration;
  62646. if (this.duration === 0)
  62647. {
  62648. this.duration = this.totalDuration;
  62649. this.durationMS = Math.ceil(this.totalDuration * 1000);
  62650. }
  62651. // Useful to cache this somewhere perhaps?
  62652. if (this._sound.start === undefined)
  62653. {
  62654. this._sound.noteGrainOn(0, this.position, this.duration);
  62655. }
  62656. else
  62657. {
  62658. if (this.loop && marker === '')
  62659. {
  62660. this._sound.start(0, 0);
  62661. }
  62662. else
  62663. {
  62664. this._sound.start(0, this.position, this.duration);
  62665. }
  62666. }
  62667. this.isPlaying = true;
  62668. this.startTime = this.game.time.time;
  62669. this.currentTime = 0;
  62670. this.stopTime = this.startTime + this.durationMS;
  62671. this.onPlay.dispatch(this);
  62672. }
  62673. else
  62674. {
  62675. this.pendingPlayback = true;
  62676. if (this.game.cache.getSound(this.key) && this.game.cache.getSound(this.key).isDecoding === false)
  62677. {
  62678. this.game.sound.decode(this.key, this);
  62679. }
  62680. }
  62681. }
  62682. else
  62683. {
  62684. if (this.game.cache.getSound(this.key) && this.game.cache.getSound(this.key).locked)
  62685. {
  62686. this.game.cache.reloadSound(this.key);
  62687. this.pendingPlayback = true;
  62688. }
  62689. else
  62690. {
  62691. if (this._sound && (this.game.device.cocoonJS || this._sound.readyState === 4))
  62692. {
  62693. this._sound.play();
  62694. // This doesn't become available until you call play(), wonderful ...
  62695. this.totalDuration = this._sound.duration;
  62696. if (this.duration === 0)
  62697. {
  62698. this.duration = this.totalDuration;
  62699. this.durationMS = this.totalDuration * 1000;
  62700. }
  62701. this._sound.currentTime = this.position;
  62702. this._sound.muted = this._muted;
  62703. if (this._muted || this.game.sound.mute)
  62704. {
  62705. this._sound.volume = 0;
  62706. }
  62707. else
  62708. {
  62709. this._sound.volume = this._volume;
  62710. }
  62711. this.isPlaying = true;
  62712. this.startTime = this.game.time.time;
  62713. this.currentTime = 0;
  62714. this.stopTime = this.startTime + this.durationMS;
  62715. this.onPlay.dispatch(this);
  62716. }
  62717. else
  62718. {
  62719. this.pendingPlayback = true;
  62720. }
  62721. }
  62722. }
  62723. return this;
  62724. },
  62725. /**
  62726. * Restart the sound, or a marked section of it.
  62727. *
  62728. * @method Phaser.Sound#restart
  62729. * @param {string} [marker=''] - If you want to play a marker then give the key here, otherwise leave blank to play the full sound.
  62730. * @param {number} [position=0] - The starting position to play the sound from - this is ignored if you provide a marker.
  62731. * @param {number} [volume=1] - Volume of the sound you want to play.
  62732. * @param {boolean} [loop=false] - Loop when it finished playing?
  62733. */
  62734. restart: function (marker, position, volume, loop) {
  62735. marker = marker || '';
  62736. position = position || 0;
  62737. volume = volume || 1;
  62738. if (loop === undefined) { loop = false; }
  62739. this.play(marker, position, volume, loop, true);
  62740. },
  62741. /**
  62742. * Pauses the sound.
  62743. *
  62744. * @method Phaser.Sound#pause
  62745. */
  62746. pause: function () {
  62747. if (this.isPlaying && this._sound)
  62748. {
  62749. this.paused = true;
  62750. this.pausedPosition = this.currentTime;
  62751. this.pausedTime = this.game.time.time;
  62752. this._tempPause = this._sound.currentTime;
  62753. this.onPause.dispatch(this);
  62754. this.stop();
  62755. }
  62756. },
  62757. /**
  62758. * Resumes the sound.
  62759. *
  62760. * @method Phaser.Sound#resume
  62761. */
  62762. resume: function () {
  62763. if (this.paused && this._sound)
  62764. {
  62765. if (this.usingWebAudio)
  62766. {
  62767. var p = Math.max(0, this.position + (this.pausedPosition / 1000));
  62768. this._sound = this.context.createBufferSource();
  62769. this._sound.buffer = this._buffer;
  62770. if (this.externalNode)
  62771. {
  62772. this._sound.connect(this.externalNode);
  62773. }
  62774. else
  62775. {
  62776. this._sound.connect(this.gainNode);
  62777. }
  62778. if (this.loop)
  62779. {
  62780. this._sound.loop = true;
  62781. }
  62782. if (!this.loop && this.currentMarker === '')
  62783. {
  62784. this._sound.onended = this.onEndedHandler.bind(this);
  62785. }
  62786. var duration = this.duration - (this.pausedPosition / 1000);
  62787. if (this._sound.start === undefined)
  62788. {
  62789. this._sound.noteGrainOn(0, p, duration);
  62790. //this._sound.noteOn(0); // the zero is vitally important, crashes iOS6 without it
  62791. }
  62792. else
  62793. {
  62794. if (this.loop && this.game.device.chrome)
  62795. {
  62796. // Handle chrome bug: https://code.google.com/p/chromium/issues/detail?id=457099
  62797. if (this.game.device.chromeVersion === 42)
  62798. {
  62799. this._sound.start(0);
  62800. }
  62801. else
  62802. {
  62803. this._sound.start(0, p);
  62804. }
  62805. }
  62806. else
  62807. {
  62808. this._sound.start(0, p, duration);
  62809. }
  62810. }
  62811. }
  62812. else
  62813. {
  62814. this._sound.currentTime = this._tempPause;
  62815. this._sound.play();
  62816. }
  62817. this.isPlaying = true;
  62818. this.paused = false;
  62819. this.startTime += (this.game.time.time - this.pausedTime);
  62820. this.onResume.dispatch(this);
  62821. }
  62822. },
  62823. /**
  62824. * Stop playing this sound.
  62825. *
  62826. * @method Phaser.Sound#stop
  62827. */
  62828. stop: function () {
  62829. if (this.isPlaying && this._sound)
  62830. {
  62831. if (this.usingWebAudio)
  62832. {
  62833. if (this._sound.stop === undefined)
  62834. {
  62835. this._sound.noteOff(0);
  62836. }
  62837. else
  62838. {
  62839. try {
  62840. this._sound.stop(0);
  62841. }
  62842. catch (e)
  62843. {
  62844. // Thanks Android 4.4
  62845. }
  62846. }
  62847. if (this.externalNode)
  62848. {
  62849. this._sound.disconnect(this.externalNode);
  62850. }
  62851. else if (this.gainNode)
  62852. {
  62853. this._sound.disconnect(this.gainNode);
  62854. }
  62855. }
  62856. else if (this.usingAudioTag)
  62857. {
  62858. this._sound.pause();
  62859. this._sound.currentTime = 0;
  62860. }
  62861. }
  62862. this.pendingPlayback = false;
  62863. this.isPlaying = false;
  62864. if (!this.paused)
  62865. {
  62866. var prevMarker = this.currentMarker;
  62867. if (this.currentMarker !== '')
  62868. {
  62869. this.onMarkerComplete.dispatch(this.currentMarker, this);
  62870. }
  62871. this.currentMarker = '';
  62872. if (this.fadeTween !== null)
  62873. {
  62874. this.fadeTween.stop();
  62875. }
  62876. this.onStop.dispatch(this, prevMarker);
  62877. }
  62878. },
  62879. /**
  62880. * Starts this sound playing (or restarts it if already doing so) and sets the volume to zero.
  62881. * Then increases the volume from 0 to 1 over the duration specified.
  62882. *
  62883. * At the end of the fade Sound.onFadeComplete is dispatched with this Sound object as the first parameter,
  62884. * and the final volume (1) as the second parameter.
  62885. *
  62886. * @method Phaser.Sound#fadeIn
  62887. * @param {number} [duration=1000] - The time in milliseconds over which the Sound should fade in.
  62888. * @param {boolean} [loop=false] - Should the Sound be set to loop? Note that this doesn't cause the fade to repeat.
  62889. * @param {string} [marker=(current marker)] - The marker to start at; defaults to the current (last played) marker. To start playing from the beginning specify specify a marker of `''`.
  62890. */
  62891. fadeIn: function (duration, loop, marker) {
  62892. if (loop === undefined) { loop = false; }
  62893. if (marker === undefined) { marker = this.currentMarker; }
  62894. if (this.paused)
  62895. {
  62896. return;
  62897. }
  62898. this.play(marker, 0, 0, loop);
  62899. this.fadeTo(duration, 1);
  62900. },
  62901. /**
  62902. * Decreases the volume of this Sound from its current value to 0 over the duration specified.
  62903. * At the end of the fade Sound.onFadeComplete is dispatched with this Sound object as the first parameter,
  62904. * and the final volume (0) as the second parameter.
  62905. *
  62906. * @method Phaser.Sound#fadeOut
  62907. * @param {number} [duration=1000] - The time in milliseconds over which the Sound should fade out.
  62908. */
  62909. fadeOut: function (duration) {
  62910. this.fadeTo(duration, 0);
  62911. },
  62912. /**
  62913. * Fades the volume of this Sound from its current value to the given volume over the duration specified.
  62914. * At the end of the fade Sound.onFadeComplete is dispatched with this Sound object as the first parameter,
  62915. * and the final volume (volume) as the second parameter.
  62916. *
  62917. * @method Phaser.Sound#fadeTo
  62918. * @param {number} [duration=1000] - The time in milliseconds during which the Sound should fade out.
  62919. * @param {number} [volume] - The volume which the Sound should fade to. This is a value between 0 and 1.
  62920. */
  62921. fadeTo: function (duration, volume) {
  62922. if (!this.isPlaying || this.paused || volume === this.volume)
  62923. {
  62924. return;
  62925. }
  62926. if (duration === undefined) { duration = 1000; }
  62927. if (volume === undefined)
  62928. {
  62929. console.warn("Phaser.Sound.fadeTo: No Volume Specified.");
  62930. return;
  62931. }
  62932. this.fadeTween = this.game.add.tween(this).to( { volume: volume }, duration, Phaser.Easing.Linear.None, true);
  62933. this.fadeTween.onComplete.add(this.fadeComplete, this);
  62934. },
  62935. /**
  62936. * Internal handler for Sound.fadeIn, Sound.fadeOut and Sound.fadeTo.
  62937. *
  62938. * @method Phaser.Sound#fadeComplete
  62939. * @private
  62940. */
  62941. fadeComplete: function () {
  62942. this.onFadeComplete.dispatch(this, this.volume);
  62943. if (this.volume === 0)
  62944. {
  62945. this.stop();
  62946. }
  62947. },
  62948. /**
  62949. * Called automatically by SoundManager.volume.
  62950. *
  62951. * Sets the volume of AudioTag Sounds as a percentage of the Global Volume.
  62952. *
  62953. * You should not normally call this directly.
  62954. *
  62955. * @method Phaser.Sound#updateGlobalVolume
  62956. * @protected
  62957. * @param {float} globalVolume - The global SoundManager volume.
  62958. */
  62959. updateGlobalVolume: function (globalVolume) {
  62960. // this._volume is the % of the global volume this sound should be played at
  62961. if (this.usingAudioTag && this._sound)
  62962. {
  62963. this._sound.volume = globalVolume * this._volume;
  62964. }
  62965. },
  62966. /**
  62967. * Destroys this sound and all associated events and removes it from the SoundManager.
  62968. *
  62969. * @method Phaser.Sound#destroy
  62970. * @param {boolean} [remove=true] - If true this Sound is automatically removed from the SoundManager.
  62971. */
  62972. destroy: function (remove) {
  62973. if (remove === undefined) { remove = true; }
  62974. this.stop();
  62975. if (remove)
  62976. {
  62977. this.game.sound.remove(this);
  62978. }
  62979. else
  62980. {
  62981. this.markers = {};
  62982. this.context = null;
  62983. this._buffer = null;
  62984. this.externalNode = null;
  62985. this.onDecoded.dispose();
  62986. this.onPlay.dispose();
  62987. this.onPause.dispose();
  62988. this.onResume.dispose();
  62989. this.onLoop.dispose();
  62990. this.onStop.dispose();
  62991. this.onMute.dispose();
  62992. this.onMarkerComplete.dispose();
  62993. }
  62994. }
  62995. };
  62996. Phaser.Sound.prototype.constructor = Phaser.Sound;
  62997. /**
  62998. * @name Phaser.Sound#isDecoding
  62999. * @property {boolean} isDecoding - Returns true if the sound file is still decoding.
  63000. * @readonly
  63001. */
  63002. Object.defineProperty(Phaser.Sound.prototype, "isDecoding", {
  63003. get: function () {
  63004. return this.game.cache.getSound(this.key).isDecoding;
  63005. }
  63006. });
  63007. /**
  63008. * @name Phaser.Sound#isDecoded
  63009. * @property {boolean} isDecoded - Returns true if the sound file has decoded.
  63010. * @readonly
  63011. */
  63012. Object.defineProperty(Phaser.Sound.prototype, "isDecoded", {
  63013. get: function () {
  63014. return this.game.cache.isSoundDecoded(this.key);
  63015. }
  63016. });
  63017. /**
  63018. * @name Phaser.Sound#mute
  63019. * @property {boolean} mute - Gets or sets the muted state of this sound.
  63020. */
  63021. Object.defineProperty(Phaser.Sound.prototype, "mute", {
  63022. get: function () {
  63023. return (this._muted || this.game.sound.mute);
  63024. },
  63025. set: function (value) {
  63026. value = value || false;
  63027. if (value === this._muted)
  63028. {
  63029. return;
  63030. }
  63031. if (value)
  63032. {
  63033. this._muted = true;
  63034. this._muteVolume = this._tempVolume;
  63035. if (this.usingWebAudio)
  63036. {
  63037. this.gainNode.gain.value = 0;
  63038. }
  63039. else if (this.usingAudioTag && this._sound)
  63040. {
  63041. this._sound.volume = 0;
  63042. }
  63043. }
  63044. else
  63045. {
  63046. this._muted = false;
  63047. if (this.usingWebAudio)
  63048. {
  63049. this.gainNode.gain.value = this._muteVolume;
  63050. }
  63051. else if (this.usingAudioTag && this._sound)
  63052. {
  63053. this._sound.volume = this._muteVolume;
  63054. }
  63055. }
  63056. this.onMute.dispatch(this);
  63057. }
  63058. });
  63059. /**
  63060. * @name Phaser.Sound#volume
  63061. * @property {number} volume - Gets or sets the volume of this sound, a value between 0 and 1. The value given is clamped to the range 0 to 1.
  63062. */
  63063. Object.defineProperty(Phaser.Sound.prototype, "volume", {
  63064. get: function () {
  63065. return this._volume;
  63066. },
  63067. set: function (value) {
  63068. // Causes an Index size error in Firefox if you don't clamp the value
  63069. if (this.game.device.firefox && this.usingAudioTag)
  63070. {
  63071. value = this.game.math.clamp(value, 0, 1);
  63072. }
  63073. if (this._muted)
  63074. {
  63075. this._muteVolume = value;
  63076. return;
  63077. }
  63078. this._tempVolume = value;
  63079. this._volume = value;
  63080. if (this.usingWebAudio)
  63081. {
  63082. this.gainNode.gain.value = value;
  63083. }
  63084. else if (this.usingAudioTag && this._sound)
  63085. {
  63086. this._sound.volume = value;
  63087. }
  63088. }
  63089. });
  63090. /**
  63091. * @author Richard Davey <rich@photonstorm.com>
  63092. * @copyright 2016 Photon Storm Ltd.
  63093. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  63094. */
  63095. /**
  63096. * The Sound Manager is responsible for playing back audio via either the Legacy HTML Audio tag or via Web Audio if the browser supports it.
  63097. * Note: On Firefox 25+ on Linux if you have media.gstreamer disabled in about:config then it cannot play back mp3 or m4a files.
  63098. * The audio file type and the encoding of those files are extremely important. Not all browsers can play all audio formats.
  63099. * There is a good guide to what's supported here: http://hpr.dogphilosophy.net/test/
  63100. *
  63101. * If you are reloading a Phaser Game on a page that never properly refreshes (such as in an AngularJS project) then you will quickly run out
  63102. * of AudioContext nodes. If this is the case create a global var called PhaserGlobal on the window object before creating the game. The active
  63103. * AudioContext will then be saved to window.PhaserGlobal.audioContext when the Phaser game is destroyed, and re-used when it starts again.
  63104. *
  63105. * Mobile warning: There are some mobile devices (certain iPad 2 and iPad Mini revisions) that cannot play 48000 Hz audio.
  63106. * When they try to play the audio becomes extremely distorted and buzzes, eventually crashing the sound system.
  63107. * The solution is to use a lower encoding rate such as 44100 Hz. Sometimes the audio context will
  63108. * be created with a sampleRate of 48000. If this happens and audio distorts you should re-create the context.
  63109. *
  63110. * @class Phaser.SoundManager
  63111. * @constructor
  63112. * @param {Phaser.Game} game - Reference to the current game instance.
  63113. */
  63114. Phaser.SoundManager = function (game) {
  63115. /**
  63116. * @property {Phaser.Game} game - Local reference to game.
  63117. */
  63118. this.game = game;
  63119. /**
  63120. * @property {Phaser.Signal} onSoundDecode - The event dispatched when a sound decodes (typically only for mp3 files)
  63121. */
  63122. this.onSoundDecode = new Phaser.Signal();
  63123. /**
  63124. * This signal is dispatched whenever the global volume changes. The new volume is passed as the only parameter to your callback.
  63125. * @property {Phaser.Signal} onVolumeChange
  63126. */
  63127. this.onVolumeChange = new Phaser.Signal();
  63128. /**
  63129. * This signal is dispatched when the SoundManager is globally muted, either directly via game code or as a result of the game pausing.
  63130. * @property {Phaser.Signal} onMute
  63131. */
  63132. this.onMute = new Phaser.Signal();
  63133. /**
  63134. * This signal is dispatched when the SoundManager is globally un-muted, either directly via game code or as a result of the game resuming from a pause.
  63135. * @property {Phaser.Signal} onUnMute
  63136. */
  63137. this.onUnMute = new Phaser.Signal();
  63138. /**
  63139. * @property {AudioContext} context - The AudioContext being used for playback.
  63140. * @default
  63141. */
  63142. this.context = null;
  63143. /**
  63144. * @property {boolean} usingWebAudio - True the SoundManager and device are both using Web Audio.
  63145. * @readonly
  63146. */
  63147. this.usingWebAudio = false;
  63148. /**
  63149. * @property {boolean} usingAudioTag - True the SoundManager and device are both using the Audio tag instead of Web Audio.
  63150. * @readonly
  63151. */
  63152. this.usingAudioTag = false;
  63153. /**
  63154. * @property {boolean} noAudio - True if audio been disabled via the PhaserGlobal (useful if you need to use a 3rd party audio library) or the device doesn't support any audio.
  63155. * @default
  63156. */
  63157. this.noAudio = false;
  63158. /**
  63159. * @property {boolean} connectToMaster - Used in conjunction with Sound.externalNode this allows you to stop a Sound node being connected to the SoundManager master gain node.
  63160. * @default
  63161. */
  63162. this.connectToMaster = true;
  63163. /**
  63164. * @property {boolean} touchLocked - true if the audio system is currently locked awaiting a touch event.
  63165. * @default
  63166. */
  63167. this.touchLocked = false;
  63168. /**
  63169. * @property {number} channels - The number of audio channels to use in playback.
  63170. * @default
  63171. */
  63172. this.channels = 32;
  63173. /**
  63174. * Set to true to have all sound muted when the Phaser game pauses (such as on loss of focus),
  63175. * or set to false to keep audio playing, regardless of the game pause state. You may need to
  63176. * do this should you wish to control audio muting via external DOM buttons or similar.
  63177. * @property {boolean} muteOnPause
  63178. * @default
  63179. */
  63180. this.muteOnPause = true;
  63181. /**
  63182. * @property {boolean} _codeMuted - Internal mute tracking var.
  63183. * @private
  63184. * @default
  63185. */
  63186. this._codeMuted = false;
  63187. /**
  63188. * @property {boolean} _muted - Internal mute tracking var.
  63189. * @private
  63190. * @default
  63191. */
  63192. this._muted = false;
  63193. /**
  63194. * @property {AudioContext} _unlockSource - Internal unlock tracking var.
  63195. * @private
  63196. * @default
  63197. */
  63198. this._unlockSource = null;
  63199. /**
  63200. * @property {number} _volume - The global audio volume. A value between 0 (silence) and 1 (full volume).
  63201. * @private
  63202. * @default
  63203. */
  63204. this._volume = 1;
  63205. /**
  63206. * @property {array} _sounds - An array containing all the sounds
  63207. * @private
  63208. */
  63209. this._sounds = [];
  63210. /**
  63211. * @property {Phaser.ArraySet} _watchList - An array set containing all the sounds being monitored for decoding status.
  63212. * @private
  63213. */
  63214. this._watchList = new Phaser.ArraySet();
  63215. /**
  63216. * @property {boolean} _watching - Is the SoundManager monitoring the watchList?
  63217. * @private
  63218. */
  63219. this._watching = false;
  63220. /**
  63221. * @property {function} _watchCallback - The callback to invoke once the watchlist is clear.
  63222. * @private
  63223. */
  63224. this._watchCallback = null;
  63225. /**
  63226. * @property {object} _watchContext - The context in which to call the watchlist callback.
  63227. * @private
  63228. */
  63229. this._watchContext = null;
  63230. };
  63231. Phaser.SoundManager.prototype = {
  63232. /**
  63233. * Initialises the sound manager.
  63234. * @method Phaser.SoundManager#boot
  63235. * @protected
  63236. */
  63237. boot: function () {
  63238. if (this.game.device.iOS && this.game.device.webAudio === false)
  63239. {
  63240. this.channels = 1;
  63241. }
  63242. // PhaserGlobal overrides
  63243. if (window['PhaserGlobal'])
  63244. {
  63245. // Check to see if all audio playback is disabled (i.e. handled by a 3rd party class)
  63246. if (window['PhaserGlobal'].disableAudio === true)
  63247. {
  63248. this.noAudio = true;
  63249. this.touchLocked = false;
  63250. return;
  63251. }
  63252. // Check if the Web Audio API is disabled (for testing Audio Tag playback during development)
  63253. if (window['PhaserGlobal'].disableWebAudio === true)
  63254. {
  63255. this.usingAudioTag = true;
  63256. this.touchLocked = false;
  63257. return;
  63258. }
  63259. }
  63260. if (window['PhaserGlobal'] && window['PhaserGlobal'].audioContext)
  63261. {
  63262. this.context = window['PhaserGlobal'].audioContext;
  63263. }
  63264. else
  63265. {
  63266. if (!!window['AudioContext'])
  63267. {
  63268. try {
  63269. this.context = new window['AudioContext']();
  63270. } catch (error) {
  63271. this.context = null;
  63272. this.usingWebAudio = false;
  63273. this.touchLocked = false;
  63274. }
  63275. }
  63276. else if (!!window['webkitAudioContext'])
  63277. {
  63278. try {
  63279. this.context = new window['webkitAudioContext']();
  63280. } catch (error) {
  63281. this.context = null;
  63282. this.usingWebAudio = false;
  63283. this.touchLocked = false;
  63284. }
  63285. }
  63286. }
  63287. if (this.context === null)
  63288. {
  63289. // No Web Audio support - how about legacy Audio?
  63290. if (window['Audio'] === undefined)
  63291. {
  63292. this.noAudio = true;
  63293. return;
  63294. }
  63295. else
  63296. {
  63297. this.usingAudioTag = true;
  63298. }
  63299. }
  63300. else
  63301. {
  63302. this.usingWebAudio = true;
  63303. if (this.context.createGain === undefined)
  63304. {
  63305. this.masterGain = this.context.createGainNode();
  63306. }
  63307. else
  63308. {
  63309. this.masterGain = this.context.createGain();
  63310. }
  63311. this.masterGain.gain.value = 1;
  63312. this.masterGain.connect(this.context.destination);
  63313. }
  63314. if (!this.noAudio)
  63315. {
  63316. // On mobile we need a native touch event before we can play anything, so capture it here
  63317. if (!this.game.device.cocoonJS && this.game.device.iOS || (window['PhaserGlobal'] && window['PhaserGlobal'].fakeiOSTouchLock))
  63318. {
  63319. this.setTouchLock();
  63320. }
  63321. }
  63322. },
  63323. /**
  63324. * Sets the Input Manager touch callback to be SoundManager.unlock.
  63325. * Required for iOS audio device unlocking. Mostly just used internally.
  63326. *
  63327. * @method Phaser.SoundManager#setTouchLock
  63328. */
  63329. setTouchLock: function () {
  63330. if (this.noAudio || (window['PhaserGlobal'] && window['PhaserGlobal'].disableAudio === true))
  63331. {
  63332. return;
  63333. }
  63334. if (this.game.device.iOSVersion > 8)
  63335. {
  63336. this.game.input.touch.addTouchLockCallback(this.unlock, this, true);
  63337. }
  63338. else
  63339. {
  63340. this.game.input.touch.addTouchLockCallback(this.unlock, this);
  63341. }
  63342. this.touchLocked = true;
  63343. },
  63344. /**
  63345. * Enables the audio, usually after the first touch.
  63346. *
  63347. * @method Phaser.SoundManager#unlock
  63348. * @return {boolean} True if the callback should be removed, otherwise false.
  63349. */
  63350. unlock: function () {
  63351. if (this.noAudio || !this.touchLocked || this._unlockSource !== null)
  63352. {
  63353. return true;
  63354. }
  63355. // Global override (mostly for Audio Tag testing)
  63356. if (this.usingAudioTag)
  63357. {
  63358. this.touchLocked = false;
  63359. this._unlockSource = null;
  63360. }
  63361. else if (this.usingWebAudio)
  63362. {
  63363. // Create empty buffer and play it
  63364. // The SoundManager.update loop captures the state of it and then resets touchLocked to false
  63365. var buffer = this.context.createBuffer(1, 1, 22050);
  63366. this._unlockSource = this.context.createBufferSource();
  63367. this._unlockSource.buffer = buffer;
  63368. this._unlockSource.connect(this.context.destination);
  63369. if (this._unlockSource.start === undefined)
  63370. {
  63371. this._unlockSource.noteOn(0);
  63372. }
  63373. else
  63374. {
  63375. this._unlockSource.start(0);
  63376. }
  63377. }
  63378. // We can remove the event because we've done what we needed (started the unlock sound playing)
  63379. return true;
  63380. },
  63381. /**
  63382. * Stops all the sounds in the game.
  63383. *
  63384. * @method Phaser.SoundManager#stopAll
  63385. */
  63386. stopAll: function () {
  63387. if (this.noAudio)
  63388. {
  63389. return;
  63390. }
  63391. for (var i = 0; i < this._sounds.length; i++)
  63392. {
  63393. if (this._sounds[i])
  63394. {
  63395. this._sounds[i].stop();
  63396. }
  63397. }
  63398. },
  63399. /**
  63400. * Pauses all the sounds in the game.
  63401. *
  63402. * @method Phaser.SoundManager#pauseAll
  63403. */
  63404. pauseAll: function () {
  63405. if (this.noAudio)
  63406. {
  63407. return;
  63408. }
  63409. for (var i = 0; i < this._sounds.length; i++)
  63410. {
  63411. if (this._sounds[i])
  63412. {
  63413. this._sounds[i].pause();
  63414. }
  63415. }
  63416. },
  63417. /**
  63418. * Resumes every sound in the game.
  63419. *
  63420. * @method Phaser.SoundManager#resumeAll
  63421. */
  63422. resumeAll: function () {
  63423. if (this.noAudio)
  63424. {
  63425. return;
  63426. }
  63427. for (var i = 0; i < this._sounds.length; i++)
  63428. {
  63429. if (this._sounds[i])
  63430. {
  63431. this._sounds[i].resume();
  63432. }
  63433. }
  63434. },
  63435. /**
  63436. * Decode a sound by its asset key.
  63437. *
  63438. * @method Phaser.SoundManager#decode
  63439. * @param {string} key - Assets key of the sound to be decoded.
  63440. * @param {Phaser.Sound} [sound] - Its buffer will be set to decoded data.
  63441. */
  63442. decode: function (key, sound) {
  63443. sound = sound || null;
  63444. var soundData = this.game.cache.getSoundData(key);
  63445. if (soundData)
  63446. {
  63447. if (this.game.cache.isSoundDecoded(key) === false)
  63448. {
  63449. this.game.cache.updateSound(key, 'isDecoding', true);
  63450. var _this = this;
  63451. try {
  63452. this.context.decodeAudioData(soundData, function (buffer) {
  63453. if (buffer)
  63454. {
  63455. _this.game.cache.decodedSound(key, buffer);
  63456. _this.onSoundDecode.dispatch(key, sound);
  63457. }
  63458. });
  63459. }
  63460. catch (e) {}
  63461. }
  63462. }
  63463. },
  63464. /**
  63465. * This method allows you to give the SoundManager a list of Sound files, or keys, and a callback.
  63466. * Once all of the Sound files have finished decoding the callback will be invoked.
  63467. * The amount of time spent decoding depends on the codec used and file size.
  63468. * If all of the files given have already decoded the callback is triggered immediately.
  63469. *
  63470. * @method Phaser.SoundManager#setDecodedCallback
  63471. * @param {string|array} files - An array containing either Phaser.Sound objects or their key strings as found in the Phaser.Cache.
  63472. * @param {Function} callback - The callback which will be invoked once all files have finished decoding.
  63473. * @param {Object} callbackContext - The context in which the callback will run.
  63474. */
  63475. setDecodedCallback: function (files, callback, callbackContext) {
  63476. if (typeof files === 'string')
  63477. {
  63478. files = [ files ];
  63479. }
  63480. this._watchList.reset();
  63481. for (var i = 0; i < files.length; i++)
  63482. {
  63483. if (files[i] instanceof Phaser.Sound)
  63484. {
  63485. if (!this.game.cache.isSoundDecoded(files[i].key))
  63486. {
  63487. this._watchList.add(files[i].key);
  63488. }
  63489. }
  63490. else if (!this.game.cache.isSoundDecoded(files[i]))
  63491. {
  63492. this._watchList.add(files[i]);
  63493. }
  63494. }
  63495. // All decoded already?
  63496. if (this._watchList.total === 0)
  63497. {
  63498. this._watching = false;
  63499. callback.call(callbackContext);
  63500. }
  63501. else
  63502. {
  63503. this._watching = true;
  63504. this._watchCallback = callback;
  63505. this._watchContext = callbackContext;
  63506. }
  63507. },
  63508. /**
  63509. * Updates every sound in the game, checks for audio unlock on mobile and monitors the decoding watch list.
  63510. *
  63511. * @method Phaser.SoundManager#update
  63512. * @protected
  63513. */
  63514. update: function () {
  63515. if (this.noAudio)
  63516. {
  63517. return;
  63518. }
  63519. if (this.touchLocked && this._unlockSource !== null && (this._unlockSource.playbackState === this._unlockSource.PLAYING_STATE || this._unlockSource.playbackState === this._unlockSource.FINISHED_STATE))
  63520. {
  63521. this.touchLocked = false;
  63522. this._unlockSource = null;
  63523. }
  63524. for (var i = 0; i < this._sounds.length; i++)
  63525. {
  63526. this._sounds[i].update();
  63527. }
  63528. if (this._watching)
  63529. {
  63530. var key = this._watchList.first;
  63531. while (key)
  63532. {
  63533. if (this.game.cache.isSoundDecoded(key))
  63534. {
  63535. this._watchList.remove(key);
  63536. }
  63537. key = this._watchList.next;
  63538. }
  63539. if (this._watchList.total === 0)
  63540. {
  63541. this._watching = false;
  63542. this._watchCallback.call(this._watchContext);
  63543. }
  63544. }
  63545. },
  63546. /**
  63547. * Adds a new Sound into the SoundManager.
  63548. *
  63549. * @method Phaser.SoundManager#add
  63550. * @param {string} key - Asset key for the sound.
  63551. * @param {number} [volume=1] - Default value for the volume.
  63552. * @param {boolean} [loop=false] - Whether or not the sound will loop.
  63553. * @param {boolean} [connect=true] - Controls if the created Sound object will connect to the master gainNode of the SoundManager when running under WebAudio.
  63554. * @return {Phaser.Sound} The new sound instance.
  63555. */
  63556. add: function (key, volume, loop, connect) {
  63557. if (volume === undefined) { volume = 1; }
  63558. if (loop === undefined) { loop = false; }
  63559. if (connect === undefined) { connect = this.connectToMaster; }
  63560. var sound = new Phaser.Sound(this.game, key, volume, loop, connect);
  63561. this._sounds.push(sound);
  63562. return sound;
  63563. },
  63564. /**
  63565. * Adds a new AudioSprite into the SoundManager.
  63566. *
  63567. * @method Phaser.SoundManager#addSprite
  63568. * @param {string} key - Asset key for the sound.
  63569. * @return {Phaser.AudioSprite} The new AudioSprite instance.
  63570. */
  63571. addSprite: function(key) {
  63572. var audioSprite = new Phaser.AudioSprite(this.game, key);
  63573. return audioSprite;
  63574. },
  63575. /**
  63576. * Removes a Sound from the SoundManager. The removed Sound is destroyed before removal.
  63577. *
  63578. * @method Phaser.SoundManager#remove
  63579. * @param {Phaser.Sound} sound - The sound object to remove.
  63580. * @return {boolean} True if the sound was removed successfully, otherwise false.
  63581. */
  63582. remove: function (sound) {
  63583. var i = this._sounds.length;
  63584. while (i--)
  63585. {
  63586. if (this._sounds[i] === sound)
  63587. {
  63588. this._sounds[i].destroy(false);
  63589. this._sounds.splice(i, 1);
  63590. return true;
  63591. }
  63592. }
  63593. return false;
  63594. },
  63595. /**
  63596. * Removes all Sounds from the SoundManager that have an asset key matching the given value.
  63597. * The removed Sounds are destroyed before removal.
  63598. *
  63599. * @method Phaser.SoundManager#removeByKey
  63600. * @param {string} key - The key to match when removing sound objects.
  63601. * @return {number} The number of matching sound objects that were removed.
  63602. */
  63603. removeByKey: function (key) {
  63604. var i = this._sounds.length;
  63605. var removed = 0;
  63606. while (i--)
  63607. {
  63608. if (this._sounds[i].key === key)
  63609. {
  63610. this._sounds[i].destroy(false);
  63611. this._sounds.splice(i, 1);
  63612. removed++;
  63613. }
  63614. }
  63615. return removed;
  63616. },
  63617. /**
  63618. * Adds a new Sound into the SoundManager and starts it playing.
  63619. *
  63620. * @method Phaser.SoundManager#play
  63621. * @param {string} key - Asset key for the sound.
  63622. * @param {number} [volume=1] - Default value for the volume.
  63623. * @param {boolean} [loop=false] - Whether or not the sound will loop.
  63624. * @return {Phaser.Sound} The new sound instance.
  63625. */
  63626. play: function (key, volume, loop) {
  63627. if (this.noAudio)
  63628. {
  63629. return;
  63630. }
  63631. var sound = this.add(key, volume, loop);
  63632. sound.play();
  63633. return sound;
  63634. },
  63635. /**
  63636. * Internal mute handler called automatically by the SoundManager.mute setter.
  63637. *
  63638. * @method Phaser.SoundManager#setMute
  63639. * @private
  63640. */
  63641. setMute: function () {
  63642. if (this._muted)
  63643. {
  63644. return;
  63645. }
  63646. this._muted = true;
  63647. if (this.usingWebAudio)
  63648. {
  63649. this._muteVolume = this.masterGain.gain.value;
  63650. this.masterGain.gain.value = 0;
  63651. }
  63652. // Loop through sounds
  63653. for (var i = 0; i < this._sounds.length; i++)
  63654. {
  63655. if (this._sounds[i].usingAudioTag)
  63656. {
  63657. this._sounds[i].mute = true;
  63658. }
  63659. }
  63660. this.onMute.dispatch();
  63661. },
  63662. /**
  63663. * Internal mute handler called automatically by the SoundManager.mute setter.
  63664. *
  63665. * @method Phaser.SoundManager#unsetMute
  63666. * @private
  63667. */
  63668. unsetMute: function () {
  63669. if (!this._muted || this._codeMuted)
  63670. {
  63671. return;
  63672. }
  63673. this._muted = false;
  63674. if (this.usingWebAudio)
  63675. {
  63676. this.masterGain.gain.value = this._muteVolume;
  63677. }
  63678. // Loop through sounds
  63679. for (var i = 0; i < this._sounds.length; i++)
  63680. {
  63681. if (this._sounds[i].usingAudioTag)
  63682. {
  63683. this._sounds[i].mute = false;
  63684. }
  63685. }
  63686. this.onUnMute.dispatch();
  63687. },
  63688. /**
  63689. * Stops all the sounds in the game, then destroys them and finally clears up any callbacks.
  63690. *
  63691. * @method Phaser.SoundManager#destroy
  63692. */
  63693. destroy: function () {
  63694. this.stopAll();
  63695. for (var i = 0; i < this._sounds.length; i++)
  63696. {
  63697. if (this._sounds[i])
  63698. {
  63699. this._sounds[i].destroy();
  63700. }
  63701. }
  63702. this._sounds = [];
  63703. this.onSoundDecode.dispose();
  63704. if (this.context)
  63705. {
  63706. if (window['PhaserGlobal'])
  63707. {
  63708. // Store this in the PhaserGlobal window var, if set, to allow for re-use if the game is created again without the page refreshing
  63709. window['PhaserGlobal'].audioContext = this.context;
  63710. }
  63711. else
  63712. {
  63713. if (this.context.close)
  63714. {
  63715. this.context.close();
  63716. }
  63717. }
  63718. }
  63719. }
  63720. };
  63721. Phaser.SoundManager.prototype.constructor = Phaser.SoundManager;
  63722. /**
  63723. * @name Phaser.SoundManager#mute
  63724. * @property {boolean} mute - Gets or sets the muted state of the SoundManager. This effects all sounds in the game.
  63725. */
  63726. Object.defineProperty(Phaser.SoundManager.prototype, "mute", {
  63727. get: function () {
  63728. return this._muted;
  63729. },
  63730. set: function (value) {
  63731. value = value || false;
  63732. if (value)
  63733. {
  63734. if (this._muted)
  63735. {
  63736. return;
  63737. }
  63738. this._codeMuted = true;
  63739. this.setMute();
  63740. }
  63741. else
  63742. {
  63743. if (!this._muted)
  63744. {
  63745. return;
  63746. }
  63747. this._codeMuted = false;
  63748. this.unsetMute();
  63749. }
  63750. }
  63751. });
  63752. /**
  63753. * @name Phaser.SoundManager#volume
  63754. * @property {number} volume - Gets or sets the global volume of the SoundManager, a value between 0 and 1. The value given is clamped to the range 0 to 1.
  63755. */
  63756. Object.defineProperty(Phaser.SoundManager.prototype, "volume", {
  63757. get: function () {
  63758. return this._volume;
  63759. },
  63760. set: function (value) {
  63761. if (value < 0)
  63762. {
  63763. value = 0;
  63764. }
  63765. else if (value > 1)
  63766. {
  63767. value = 1;
  63768. }
  63769. if (this._volume !== value)
  63770. {
  63771. this._volume = value;
  63772. if (this.usingWebAudio)
  63773. {
  63774. this.masterGain.gain.value = value;
  63775. }
  63776. else
  63777. {
  63778. // Loop through the sound cache and change the volume of all html audio tags
  63779. for (var i = 0; i < this._sounds.length; i++)
  63780. {
  63781. if (this._sounds[i].usingAudioTag)
  63782. {
  63783. this._sounds[i].updateGlobalVolume(value);
  63784. }
  63785. }
  63786. }
  63787. this.onVolumeChange.dispatch(value);
  63788. }
  63789. }
  63790. });
  63791. /**
  63792. * @author Richard Davey <rich@photonstorm.com>
  63793. * @copyright 2016 Photon Storm Ltd.
  63794. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  63795. */
  63796. /**
  63797. * @classdesc
  63798. * The ScaleManager object handles the the scaling, resizing, and alignment of the
  63799. * Game size and the game Display canvas.
  63800. *
  63801. * The Game size is the logical size of the game; the Display canvas has size as an HTML element.
  63802. *
  63803. * The calculations of these are heavily influenced by the bounding Parent size which is the computed
  63804. * dimensions of the Display canvas's Parent container/element - the _effective CSS rules of the
  63805. * canvas's Parent element play an important role_ in the operation of the ScaleManager.
  63806. *
  63807. * The Display canvas - or Game size, depending {@link #scaleMode} - is updated to best utilize the Parent size.
  63808. * When in Fullscreen mode or with {@link #parentIsWindow} the Parent size is that of the visual viewport (see {@link Phaser.ScaleManager#getParentBounds getParentBounds}).
  63809. *
  63810. * Parent and Display canvas containment guidelines:
  63811. *
  63812. * - Style the Parent element (of the game canvas) to control the Parent size and
  63813. * thus the Display canvas's size and layout.
  63814. *
  63815. * - The Parent element's CSS styles should _effectively_ apply maximum (and minimum) bounding behavior.
  63816. *
  63817. * - The Parent element should _not_ apply a padding as this is not accounted for.
  63818. * If a padding is required apply it to the Parent's parent or apply a margin to the Parent.
  63819. * If you need to add a border, margin or any other CSS around your game container, then use a parent element and
  63820. * apply the CSS to this instead, otherwise you'll be constantly resizing the shape of the game container.
  63821. *
  63822. * - The Display canvas layout CSS styles (i.e. margins, size) should not be altered/specified as
  63823. * they may be updated by the ScaleManager.
  63824. *
  63825. * @description
  63826. * Create a new ScaleManager object - this is done automatically by {@link Phaser.Game}
  63827. *
  63828. * The `width` and `height` constructor parameters can either be a number which represents pixels or a string that represents a percentage: e.g. `800` (for 800 pixels) or `"80%"` for 80%.
  63829. *
  63830. * @class
  63831. * @param {Phaser.Game} game - A reference to the currently running game.
  63832. * @param {number|string} width - The width of the game. See above.
  63833. * @param {number|string} height - The height of the game. See above.
  63834. */
  63835. Phaser.ScaleManager = function (game, width, height) {
  63836. /**
  63837. * A reference to the currently running game.
  63838. * @property {Phaser.Game} game
  63839. * @protected
  63840. * @readonly
  63841. */
  63842. this.game = game;
  63843. /**
  63844. * Provides access to some cross-device DOM functions.
  63845. * @property {Phaser.DOM} dom
  63846. * @protected
  63847. * @readonly
  63848. */
  63849. this.dom = Phaser.DOM;
  63850. /**
  63851. * _EXPERIMENTAL:_ A responsive grid on which you can align game objects.
  63852. * @property {Phaser.FlexGrid} grid
  63853. * @public
  63854. */
  63855. this.grid = null;
  63856. /**
  63857. * Target width (in pixels) of the Display canvas.
  63858. * @property {number} width
  63859. * @readonly
  63860. */
  63861. this.width = 0;
  63862. /**
  63863. * Target height (in pixels) of the Display canvas.
  63864. * @property {number} height
  63865. * @readonly
  63866. */
  63867. this.height = 0;
  63868. /**
  63869. * Minimum width the canvas should be scaled to (in pixels).
  63870. * Change with {@link #setMinMax}.
  63871. * @property {?number} minWidth
  63872. * @readonly
  63873. * @protected
  63874. */
  63875. this.minWidth = null;
  63876. /**
  63877. * Maximum width the canvas should be scaled to (in pixels).
  63878. * If null it will scale to whatever width the browser can handle.
  63879. * Change with {@link #setMinMax}.
  63880. * @property {?number} maxWidth
  63881. * @readonly
  63882. * @protected
  63883. */
  63884. this.maxWidth = null;
  63885. /**
  63886. * Minimum height the canvas should be scaled to (in pixels).
  63887. * Change with {@link #setMinMax}.
  63888. * @property {?number} minHeight
  63889. * @readonly
  63890. * @protected
  63891. */
  63892. this.minHeight = null;
  63893. /**
  63894. * Maximum height the canvas should be scaled to (in pixels).
  63895. * If null it will scale to whatever height the browser can handle.
  63896. * Change with {@link #setMinMax}.
  63897. * @property {?number} maxHeight
  63898. * @readonly
  63899. * @protected
  63900. */
  63901. this.maxHeight = null;
  63902. /**
  63903. * The offset coordinates of the Display canvas from the top-left of the browser window.
  63904. * The is used internally by Phaser.Pointer (for Input) and possibly other types.
  63905. * @property {Phaser.Point} offset
  63906. * @readonly
  63907. * @protected
  63908. */
  63909. this.offset = new Phaser.Point();
  63910. /**
  63911. * If true, the game should only run in a landscape orientation.
  63912. * Change with {@link #forceOrientation}.
  63913. * @property {boolean} forceLandscape
  63914. * @readonly
  63915. * @default
  63916. * @protected
  63917. */
  63918. this.forceLandscape = false;
  63919. /**
  63920. * If true, the game should only run in a portrait
  63921. * Change with {@link #forceOrientation}.
  63922. * @property {boolean} forcePortrait
  63923. * @readonly
  63924. * @default
  63925. * @protected
  63926. */
  63927. this.forcePortrait = false;
  63928. /**
  63929. * True if {@link #forceLandscape} or {@link #forcePortrait} are set and do not agree with the browser orientation.
  63930. *
  63931. * This value is not updated immediately.
  63932. *
  63933. * @property {boolean} incorrectOrientation
  63934. * @readonly
  63935. * @protected
  63936. */
  63937. this.incorrectOrientation = false;
  63938. /**
  63939. * See {@link #pageAlignHorizontally}.
  63940. * @property {boolean} _pageAlignHorizontally
  63941. * @private
  63942. */
  63943. this._pageAlignHorizontally = false;
  63944. /**
  63945. * See {@link #pageAlignVertically}.
  63946. * @property {boolean} _pageAlignVertically
  63947. * @private
  63948. */
  63949. this._pageAlignVertically = false;
  63950. /**
  63951. * This signal is dispatched when the orientation changes _or_ the validity of the current orientation changes.
  63952. *
  63953. * The signal is supplied with the following arguments:
  63954. * - `scale` - the ScaleManager object
  63955. * - `prevOrientation`, a string - The previous orientation as per {@link Phaser.ScaleManager#screenOrientation screenOrientation}.
  63956. * - `wasIncorrect`, a boolean - True if the previous orientation was last determined to be incorrect.
  63957. *
  63958. * Access the current orientation and validity with `scale.screenOrientation` and `scale.incorrectOrientation`.
  63959. * Thus the following tests can be done:
  63960. *
  63961. * // The orientation itself changed:
  63962. * scale.screenOrientation !== prevOrientation
  63963. * // The orientation just became incorrect:
  63964. * scale.incorrectOrientation && !wasIncorrect
  63965. *
  63966. * It is possible that this signal is triggered after {@link #forceOrientation} so the orientation
  63967. * correctness changes even if the orientation itself does not change.
  63968. *
  63969. * This is signaled from `preUpdate` (or `pauseUpdate`) _even when_ the game is paused.
  63970. *
  63971. * @property {Phaser.Signal} onOrientationChange
  63972. * @public
  63973. */
  63974. this.onOrientationChange = new Phaser.Signal();
  63975. /**
  63976. * This signal is dispatched when the browser enters an incorrect orientation, as defined by {@link #forceOrientation}.
  63977. *
  63978. * This is signaled from `preUpdate` (or `pauseUpdate`) _even when_ the game is paused.
  63979. *
  63980. * @property {Phaser.Signal} enterIncorrectOrientation
  63981. * @public
  63982. */
  63983. this.enterIncorrectOrientation = new Phaser.Signal();
  63984. /**
  63985. * This signal is dispatched when the browser leaves an incorrect orientation, as defined by {@link #forceOrientation}.
  63986. *
  63987. * This is signaled from `preUpdate` (or `pauseUpdate`) _even when_ the game is paused.
  63988. *
  63989. * @property {Phaser.Signal} leaveIncorrectOrientation
  63990. * @public
  63991. */
  63992. this.leaveIncorrectOrientation = new Phaser.Signal();
  63993. /**
  63994. * This boolean provides you with a way to determine if the browser is in Full Screen
  63995. * mode (via the Full Screen API), and Phaser was the one responsible for activating it.
  63996. *
  63997. * It's possible that ScaleManager.isFullScreen returns `true` even if Phaser wasn't the
  63998. * one that made the browser go full-screen, so this flag lets you determine that.
  63999. *
  64000. * @property {boolean} hasPhaserSetFullScreen
  64001. * @default
  64002. */
  64003. this.hasPhaserSetFullScreen = false;
  64004. /**
  64005. * If specified, this is the DOM element on which the Fullscreen API enter request will be invoked.
  64006. * The target element must have the correct CSS styling and contain the Display canvas.
  64007. *
  64008. * The elements style will be modified (ie. the width and height might be set to 100%)
  64009. * but it will not be added to, removed from, or repositioned within the DOM.
  64010. * An attempt is made to restore relevant style changes when fullscreen mode is left.
  64011. *
  64012. * For pre-2.2.0 behavior set `game.scale.fullScreenTarget = game.canvas`.
  64013. *
  64014. * @property {?DOMElement} fullScreenTarget
  64015. * @default
  64016. */
  64017. this.fullScreenTarget = null;
  64018. /**
  64019. * The fullscreen target, as created by {@link #createFullScreenTarget}.
  64020. * This is not set if {@link #fullScreenTarget} is used and is cleared when fullscreen mode ends.
  64021. * @property {?DOMElement} _createdFullScreenTarget
  64022. * @private
  64023. */
  64024. this._createdFullScreenTarget = null;
  64025. /**
  64026. * This signal is dispatched when fullscreen mode is ready to be initialized but
  64027. * before the fullscreen request.
  64028. *
  64029. * The signal is passed two arguments: `scale` (the ScaleManager), and an object in the form `{targetElement: DOMElement}`.
  64030. *
  64031. * The `targetElement` is the {@link #fullScreenTarget} element,
  64032. * if such is assigned, or a new element created by {@link #createFullScreenTarget}.
  64033. *
  64034. * Custom CSS styling or resets can be applied to `targetElement` as required.
  64035. *
  64036. * If `targetElement` is _not_ the same element as {@link #fullScreenTarget}:
  64037. * - After initialization the Display canvas is moved onto the `targetElement` for
  64038. * the duration of the fullscreen mode, and restored to it's original DOM location when fullscreen is exited.
  64039. * - The `targetElement` is moved/re-parented within the DOM and may have its CSS styles updated.
  64040. *
  64041. * The behavior of a pre-assigned target element is covered in {@link Phaser.ScaleManager#fullScreenTarget fullScreenTarget}.
  64042. *
  64043. * @property {Phaser.Signal} onFullScreenInit
  64044. * @public
  64045. */
  64046. this.onFullScreenInit = new Phaser.Signal();
  64047. /**
  64048. * This signal is dispatched when the browser enters or leaves fullscreen mode, if supported.
  64049. *
  64050. * The signal is supplied with a single argument: `scale` (the ScaleManager). Use `scale.isFullScreen` to determine
  64051. * if currently running in Fullscreen mode.
  64052. *
  64053. * @property {Phaser.Signal} onFullScreenChange
  64054. * @public
  64055. */
  64056. this.onFullScreenChange = new Phaser.Signal();
  64057. /**
  64058. * This signal is dispatched when the browser fails to enter fullscreen mode;
  64059. * or if the device does not support fullscreen mode and `startFullScreen` is invoked.
  64060. *
  64061. * The signal is supplied with a single argument: `scale` (the ScaleManager).
  64062. *
  64063. * @property {Phaser.Signal} onFullScreenError
  64064. * @public
  64065. */
  64066. this.onFullScreenError = new Phaser.Signal();
  64067. /**
  64068. * The _last known_ orientation of the screen, as defined in the Window Screen Web API.
  64069. * See {@link Phaser.DOM.getScreenOrientation} for possible values.
  64070. *
  64071. * @property {string} screenOrientation
  64072. * @readonly
  64073. * @public
  64074. */
  64075. this.screenOrientation = this.dom.getScreenOrientation();
  64076. /**
  64077. * The _current_ scale factor based on the game dimensions vs. the scaled dimensions.
  64078. * @property {Phaser.Point} scaleFactor
  64079. * @readonly
  64080. */
  64081. this.scaleFactor = new Phaser.Point(1, 1);
  64082. /**
  64083. * The _current_ inversed scale factor. The displayed dimensions divided by the game dimensions.
  64084. * @property {Phaser.Point} scaleFactorInversed
  64085. * @readonly
  64086. * @protected
  64087. */
  64088. this.scaleFactorInversed = new Phaser.Point(1, 1);
  64089. /**
  64090. * The Display canvas is aligned by adjusting the margins; the last margins are stored here.
  64091. *
  64092. * @property {Bounds-like} margin
  64093. * @readonly
  64094. * @protected
  64095. */
  64096. this.margin = {left: 0, top: 0, right: 0, bottom: 0, x: 0, y: 0};
  64097. /**
  64098. * The bounds of the scaled game. The x/y will match the offset of the canvas element and the width/height the scaled width and height.
  64099. * @property {Phaser.Rectangle} bounds
  64100. * @readonly
  64101. */
  64102. this.bounds = new Phaser.Rectangle();
  64103. /**
  64104. * The aspect ratio of the scaled Display canvas.
  64105. * @property {number} aspectRatio
  64106. * @readonly
  64107. */
  64108. this.aspectRatio = 0;
  64109. /**
  64110. * The aspect ratio of the original game dimensions.
  64111. * @property {number} sourceAspectRatio
  64112. * @readonly
  64113. */
  64114. this.sourceAspectRatio = 0;
  64115. /**
  64116. * The native browser events from Fullscreen API changes.
  64117. * @property {any} event
  64118. * @readonly
  64119. * @private
  64120. */
  64121. this.event = null;
  64122. /**
  64123. * The edges on which to constrain the game Display/canvas in _addition_ to the restrictions of the parent container.
  64124. *
  64125. * The properties are strings and can be '', 'visual', 'layout', or 'layout-soft'.
  64126. * - If 'visual', the edge will be constrained to the Window / displayed screen area
  64127. * - If 'layout', the edge will be constrained to the CSS Layout bounds
  64128. * - An invalid value is treated as 'visual'
  64129. *
  64130. * @member
  64131. * @property {string} bottom
  64132. * @property {string} right
  64133. * @default
  64134. */
  64135. this.windowConstraints = {
  64136. right: 'layout',
  64137. bottom: ''
  64138. };
  64139. /**
  64140. * Various compatibility settings.
  64141. * A value of "(auto)" indicates the setting is configured based on device and runtime information.
  64142. *
  64143. * A {@link #refresh} may need to be performed after making changes.
  64144. *
  64145. * @protected
  64146. *
  64147. * @property {boolean} [supportsFullScreen=(auto)] - True only if fullscreen support will be used. (Changing to fullscreen still might not work.)
  64148. *
  64149. * @property {boolean} [orientationFallback=(auto)] - See {@link Phaser.DOM.getScreenOrientation}.
  64150. *
  64151. * @property {boolean} [noMargins=false] - If true then the Display canvas's margins will not be updated anymore: existing margins must be manually cleared. Disabling margins prevents automatic canvas alignment/centering, possibly in fullscreen.
  64152. *
  64153. * @property {?Phaser.Point} [scrollTo=(auto)] - If specified the window will be scrolled to this position on every refresh.
  64154. *
  64155. * @property {boolean} [forceMinimumDocumentHeight=false] - If enabled the document elements minimum height is explicitly set on updates.
  64156. * The height set varies by device and may either be the height of the window or the viewport.
  64157. *
  64158. * @property {boolean} [canExpandParent=true] - If enabled then SHOW_ALL and USER_SCALE modes can try and expand the parent element. It may be necessary for the parent element to impose CSS width/height restrictions.
  64159. *
  64160. * @property {string} [clickTrampoline=(auto)] - On certain browsers (eg. IE) FullScreen events need to be triggered via 'click' events.
  64161. * A value of 'when-not-mouse' uses a click trampoline when a pointer that is not the primary mouse is used.
  64162. * Any other string value (including the empty string) prevents using click trampolines.
  64163. * For more details on click trampolines see {@link Phaser.Pointer#addClickTrampoline}.
  64164. */
  64165. this.compatibility = {
  64166. supportsFullScreen: false,
  64167. orientationFallback: null,
  64168. noMargins: false,
  64169. scrollTo: null,
  64170. forceMinimumDocumentHeight: false,
  64171. canExpandParent: true,
  64172. clickTrampoline: ''
  64173. };
  64174. /**
  64175. * Scale mode to be used when not in fullscreen.
  64176. * @property {number} _scaleMode
  64177. * @private
  64178. */
  64179. this._scaleMode = Phaser.ScaleManager.NO_SCALE;
  64180. /*
  64181. * Scale mode to be used in fullscreen.
  64182. * @property {number} _fullScreenScaleMode
  64183. * @private
  64184. */
  64185. this._fullScreenScaleMode = Phaser.ScaleManager.NO_SCALE;
  64186. /**
  64187. * If the parent container of the Game canvas is the browser window itself (i.e. document.body),
  64188. * rather than another div, this should set to `true`.
  64189. *
  64190. * The {@link #parentNode} property is generally ignored while this is in effect.
  64191. *
  64192. * @property {boolean} parentIsWindow
  64193. */
  64194. this.parentIsWindow = false;
  64195. /**
  64196. * The _original_ DOM element for the parent of the Display canvas.
  64197. * This may be different in fullscreen - see {@link #createFullScreenTarget}.
  64198. *
  64199. * This should only be changed after moving the Game canvas to a different DOM parent.
  64200. *
  64201. * @property {?DOMElement} parentNode
  64202. */
  64203. this.parentNode = null;
  64204. /**
  64205. * The scale of the game in relation to its parent container.
  64206. * @property {Phaser.Point} parentScaleFactor
  64207. * @readonly
  64208. */
  64209. this.parentScaleFactor = new Phaser.Point(1, 1);
  64210. /**
  64211. * The maximum time (in ms) between dimension update checks for the Canvas's parent element (or window).
  64212. * Update checks normally happen quicker in response to other events.
  64213. *
  64214. * @property {integer} trackParentInterval
  64215. * @default
  64216. * @protected
  64217. * @see {@link Phaser.ScaleManager#refresh refresh}
  64218. */
  64219. this.trackParentInterval = 2000;
  64220. /**
  64221. * This signal is dispatched when the size of the Display canvas changes _or_ the size of the Game changes.
  64222. * When invoked this is done _after_ the Canvas size/position have been updated.
  64223. *
  64224. * This signal is _only_ called when a change occurs and a reflow may be required.
  64225. * For example, if the canvas does not change sizes because of CSS settings (such as min-width)
  64226. * then this signal will _not_ be triggered.
  64227. *
  64228. * Use this to handle responsive game layout options.
  64229. *
  64230. * This is signaled from `preUpdate` (or `pauseUpdate`) _even when_ the game is paused.
  64231. *
  64232. * @property {Phaser.Signal} onSizeChange
  64233. * @todo Formalize the arguments, if any, supplied to this signal.
  64234. */
  64235. this.onSizeChange = new Phaser.Signal();
  64236. /**
  64237. * The callback that will be called each the parent container resizes.
  64238. * @property {function} onResize
  64239. * @private
  64240. */
  64241. this.onResize = null;
  64242. /**
  64243. * The context in which the {@link #onResize} callback will be called.
  64244. * @property {object} onResizeContext
  64245. * @private
  64246. */
  64247. this.onResizeContext = null;
  64248. /**
  64249. * @property {integer} _pendingScaleMode - Used to retain the scale mode if set from config before Boot.
  64250. * @private
  64251. */
  64252. this._pendingScaleMode = null;
  64253. /**
  64254. * Information saved when fullscreen mode is started.
  64255. * @property {?object} _fullScreenRestore
  64256. * @private
  64257. */
  64258. this._fullScreenRestore = null;
  64259. /**
  64260. * The _actual_ game dimensions, as initially set or set by {@link #setGameSize}.
  64261. * @property {Phaser.Rectangle} _gameSize
  64262. * @private
  64263. */
  64264. this._gameSize = new Phaser.Rectangle();
  64265. /**
  64266. * The user-supplied scale factor, used with the USER_SCALE scaling mode.
  64267. * @property {Phaser.Point} _userScaleFactor
  64268. * @private
  64269. */
  64270. this._userScaleFactor = new Phaser.Point(1, 1);
  64271. /**
  64272. * The user-supplied scale trim, used with the USER_SCALE scaling mode.
  64273. * @property {Phaser.Point} _userScaleTrim
  64274. * @private
  64275. */
  64276. this._userScaleTrim = new Phaser.Point(0, 0);
  64277. /**
  64278. * The last time the bounds were checked in `preUpdate`.
  64279. * @property {number} _lastUpdate
  64280. * @private
  64281. */
  64282. this._lastUpdate = 0;
  64283. /**
  64284. * Size checks updates are delayed according to the throttle.
  64285. * The throttle increases to `trackParentInterval` over time and is used to more
  64286. * rapidly detect changes in certain browsers (eg. IE) while providing back-off safety.
  64287. * @property {integer} _updateThrottle
  64288. * @private
  64289. */
  64290. this._updateThrottle = 0;
  64291. /**
  64292. * The minimum throttle allowed until it has slowed down sufficiently.
  64293. * @property {integer} _updateThrottleReset
  64294. * @private
  64295. */
  64296. this._updateThrottleReset = 100;
  64297. /**
  64298. * The cached result of the parent (possibly window) bounds; used to invalidate sizing.
  64299. * @property {Phaser.Rectangle} _parentBounds
  64300. * @private
  64301. */
  64302. this._parentBounds = new Phaser.Rectangle();
  64303. /**
  64304. * Temporary bounds used for internal work to cut down on new objects created.
  64305. * @property {Phaser.Rectangle} _parentBounds
  64306. * @private
  64307. */
  64308. this._tempBounds = new Phaser.Rectangle();
  64309. /**
  64310. * The Canvas size at which the last onSizeChange signal was triggered.
  64311. * @property {Phaser.Rectangle} _lastReportedCanvasSize
  64312. * @private
  64313. */
  64314. this._lastReportedCanvasSize = new Phaser.Rectangle();
  64315. /**
  64316. * The Game size at which the last onSizeChange signal was triggered.
  64317. * @property {Phaser.Rectangle} _lastReportedGameSize
  64318. * @private
  64319. */
  64320. this._lastReportedGameSize = new Phaser.Rectangle();
  64321. /**
  64322. * @property {boolean} _booted - ScaleManager booted state.
  64323. * @private
  64324. */
  64325. this._booted = false;
  64326. if (game.config)
  64327. {
  64328. this.parseConfig(game.config);
  64329. }
  64330. this.setupScale(width, height);
  64331. };
  64332. /**
  64333. * A scale mode that stretches content to fill all available space - see {@link Phaser.ScaleManager#scaleMode scaleMode}.
  64334. *
  64335. * @constant
  64336. * @type {integer}
  64337. */
  64338. Phaser.ScaleManager.EXACT_FIT = 0;
  64339. /**
  64340. * A scale mode that prevents any scaling - see {@link Phaser.ScaleManager#scaleMode scaleMode}.
  64341. *
  64342. * @constant
  64343. * @type {integer}
  64344. */
  64345. Phaser.ScaleManager.NO_SCALE = 1;
  64346. /**
  64347. * A scale mode that shows the entire game while maintaining proportions - see {@link Phaser.ScaleManager#scaleMode scaleMode}.
  64348. *
  64349. * @constant
  64350. * @type {integer}
  64351. */
  64352. Phaser.ScaleManager.SHOW_ALL = 2;
  64353. /**
  64354. * A scale mode that causes the Game size to change - see {@link Phaser.ScaleManager#scaleMode scaleMode}.
  64355. *
  64356. * @constant
  64357. * @type {integer}
  64358. */
  64359. Phaser.ScaleManager.RESIZE = 3;
  64360. /**
  64361. * A scale mode that allows a custom scale factor - see {@link Phaser.ScaleManager#scaleMode scaleMode}.
  64362. *
  64363. * @constant
  64364. * @type {integer}
  64365. */
  64366. Phaser.ScaleManager.USER_SCALE = 4;
  64367. Phaser.ScaleManager.prototype = {
  64368. /**
  64369. * Start the ScaleManager.
  64370. *
  64371. * @method Phaser.ScaleManager#boot
  64372. * @protected
  64373. */
  64374. boot: function () {
  64375. // Configure device-dependent compatibility
  64376. var compat = this.compatibility;
  64377. compat.supportsFullScreen = this.game.device.fullscreen && !this.game.device.cocoonJS;
  64378. // We can't do anything about the status bars in iPads, web apps or desktops
  64379. if (!this.game.device.iPad && !this.game.device.webApp && !this.game.device.desktop)
  64380. {
  64381. if (this.game.device.android && !this.game.device.chrome)
  64382. {
  64383. compat.scrollTo = new Phaser.Point(0, 1);
  64384. }
  64385. else
  64386. {
  64387. compat.scrollTo = new Phaser.Point(0, 0);
  64388. }
  64389. }
  64390. if (this.game.device.desktop)
  64391. {
  64392. compat.orientationFallback = 'screen';
  64393. compat.clickTrampoline = 'when-not-mouse';
  64394. }
  64395. else
  64396. {
  64397. compat.orientationFallback = '';
  64398. compat.clickTrampoline = '';
  64399. }
  64400. // Configure event listeners
  64401. var _this = this;
  64402. this._orientationChange = function(event) {
  64403. return _this.orientationChange(event);
  64404. };
  64405. this._windowResize = function(event) {
  64406. return _this.windowResize(event);
  64407. };
  64408. // This does not appear to be on the standards track
  64409. window.addEventListener('orientationchange', this._orientationChange, false);
  64410. window.addEventListener('resize', this._windowResize, false);
  64411. if (this.compatibility.supportsFullScreen)
  64412. {
  64413. this._fullScreenChange = function(event) {
  64414. return _this.fullScreenChange(event);
  64415. };
  64416. this._fullScreenError = function(event) {
  64417. return _this.fullScreenError(event);
  64418. };
  64419. document.addEventListener('webkitfullscreenchange', this._fullScreenChange, false);
  64420. document.addEventListener('mozfullscreenchange', this._fullScreenChange, false);
  64421. document.addEventListener('MSFullscreenChange', this._fullScreenChange, false);
  64422. document.addEventListener('fullscreenchange', this._fullScreenChange, false);
  64423. document.addEventListener('webkitfullscreenerror', this._fullScreenError, false);
  64424. document.addEventListener('mozfullscreenerror', this._fullScreenError, false);
  64425. document.addEventListener('MSFullscreenError', this._fullScreenError, false);
  64426. document.addEventListener('fullscreenerror', this._fullScreenError, false);
  64427. }
  64428. this.game.onResume.add(this._gameResumed, this);
  64429. // Initialize core bounds
  64430. this.dom.getOffset(this.game.canvas, this.offset);
  64431. this.bounds.setTo(this.offset.x, this.offset.y, this.width, this.height);
  64432. this.setGameSize(this.game.width, this.game.height);
  64433. // Don't use updateOrientationState so events are not fired
  64434. this.screenOrientation = this.dom.getScreenOrientation(this.compatibility.orientationFallback);
  64435. if (Phaser.FlexGrid)
  64436. {
  64437. this.grid = new Phaser.FlexGrid(this, this.width, this.height);
  64438. }
  64439. this._booted = true;
  64440. if (this._pendingScaleMode !== null)
  64441. {
  64442. this.scaleMode = this._pendingScaleMode;
  64443. this._pendingScaleMode = null;
  64444. }
  64445. },
  64446. /**
  64447. * Load configuration settings.
  64448. *
  64449. * @method Phaser.ScaleManager#parseConfig
  64450. * @protected
  64451. * @param {object} config - The game configuration object.
  64452. */
  64453. parseConfig: function (config) {
  64454. if (config['scaleMode'] !== undefined)
  64455. {
  64456. if (this._booted)
  64457. {
  64458. this.scaleMode = config['scaleMode'];
  64459. }
  64460. else
  64461. {
  64462. this._pendingScaleMode = config['scaleMode'];
  64463. }
  64464. }
  64465. if (config['fullScreenScaleMode'] !== undefined)
  64466. {
  64467. this.fullScreenScaleMode = config['fullScreenScaleMode'];
  64468. }
  64469. if (config['fullScreenTarget'])
  64470. {
  64471. this.fullScreenTarget = config['fullScreenTarget'];
  64472. }
  64473. },
  64474. /**
  64475. * Calculates and sets the game dimensions based on the given width and height.
  64476. *
  64477. * This should _not_ be called when in fullscreen mode.
  64478. *
  64479. * @method Phaser.ScaleManager#setupScale
  64480. * @protected
  64481. * @param {number|string} width - The width of the game.
  64482. * @param {number|string} height - The height of the game.
  64483. */
  64484. setupScale: function (width, height) {
  64485. var target;
  64486. var rect = new Phaser.Rectangle();
  64487. if (this.game.parent !== '')
  64488. {
  64489. if (typeof this.game.parent === 'string')
  64490. {
  64491. // hopefully an element ID
  64492. target = document.getElementById(this.game.parent);
  64493. }
  64494. else if (this.game.parent && this.game.parent.nodeType === 1)
  64495. {
  64496. // quick test for a HTMLelement
  64497. target = this.game.parent;
  64498. }
  64499. }
  64500. // Fallback, covers an invalid ID and a non HTMLelement object
  64501. if (!target)
  64502. {
  64503. // Use the full window
  64504. this.parentNode = null;
  64505. this.parentIsWindow = true;
  64506. rect.width = this.dom.visualBounds.width;
  64507. rect.height = this.dom.visualBounds.height;
  64508. this.offset.set(0, 0);
  64509. }
  64510. else
  64511. {
  64512. this.parentNode = target;
  64513. this.parentIsWindow = false;
  64514. this.getParentBounds(this._parentBounds);
  64515. rect.width = this._parentBounds.width;
  64516. rect.height = this._parentBounds.height;
  64517. this.offset.set(this._parentBounds.x, this._parentBounds.y);
  64518. }
  64519. var newWidth = 0;
  64520. var newHeight = 0;
  64521. if (typeof width === 'number')
  64522. {
  64523. newWidth = width;
  64524. }
  64525. else
  64526. {
  64527. // Percentage based
  64528. this.parentScaleFactor.x = parseInt(width, 10) / 100;
  64529. newWidth = rect.width * this.parentScaleFactor.x;
  64530. }
  64531. if (typeof height === 'number')
  64532. {
  64533. newHeight = height;
  64534. }
  64535. else
  64536. {
  64537. // Percentage based
  64538. this.parentScaleFactor.y = parseInt(height, 10) / 100;
  64539. newHeight = rect.height * this.parentScaleFactor.y;
  64540. }
  64541. newWidth = Math.floor(newWidth);
  64542. newHeight = Math.floor(newHeight);
  64543. this._gameSize.setTo(0, 0, newWidth, newHeight);
  64544. this.updateDimensions(newWidth, newHeight, false);
  64545. },
  64546. /**
  64547. * Invoked when the game is resumed.
  64548. *
  64549. * @method Phaser.ScaleManager#_gameResumed
  64550. * @private
  64551. */
  64552. _gameResumed: function () {
  64553. this.queueUpdate(true);
  64554. },
  64555. /**
  64556. * Set the actual Game size.
  64557. * Use this instead of directly changing `game.width` or `game.height`.
  64558. *
  64559. * The actual physical display (Canvas element size) depends on various settings including
  64560. * - Scale mode
  64561. * - Scaling factor
  64562. * - Size of Canvas's parent element or CSS rules such as min-height/max-height;
  64563. * - The size of the Window
  64564. *
  64565. * @method Phaser.ScaleManager#setGameSize
  64566. * @public
  64567. * @param {integer} width - _Game width_, in pixels.
  64568. * @param {integer} height - _Game height_, in pixels.
  64569. */
  64570. setGameSize: function (width, height) {
  64571. this._gameSize.setTo(0, 0, width, height);
  64572. if (this.currentScaleMode !== Phaser.ScaleManager.RESIZE)
  64573. {
  64574. this.updateDimensions(width, height, true);
  64575. }
  64576. this.queueUpdate(true);
  64577. },
  64578. /**
  64579. * Set a User scaling factor used in the USER_SCALE scaling mode.
  64580. *
  64581. * The target canvas size is computed by:
  64582. *
  64583. * canvas.width = (game.width * hScale) - hTrim
  64584. * canvas.height = (game.height * vScale) - vTrim
  64585. *
  64586. * This method can be used in the {@link Phaser.ScaleManager#setResizeCallback resize callback}.
  64587. *
  64588. * @method Phaser.ScaleManager#setUserScale
  64589. * @param {number} hScale - Horizontal scaling factor.
  64590. * @param {numer} vScale - Vertical scaling factor.
  64591. * @param {integer} [hTrim=0] - Horizontal trim, applied after scaling.
  64592. * @param {integer} [vTrim=0] - Vertical trim, applied after scaling.
  64593. */
  64594. setUserScale: function (hScale, vScale, hTrim, vTrim) {
  64595. this._userScaleFactor.setTo(hScale, vScale);
  64596. this._userScaleTrim.setTo(hTrim | 0, vTrim | 0);
  64597. this.queueUpdate(true);
  64598. },
  64599. /**
  64600. * Sets the callback that will be invoked before sizing calculations.
  64601. *
  64602. * This is the appropriate place to call {@link #setUserScale} if needing custom dynamic scaling.
  64603. *
  64604. * The callback is supplied with two arguments `scale` and `parentBounds` where `scale` is the ScaleManager
  64605. * and `parentBounds`, a Phaser.Rectangle, is the size of the Parent element.
  64606. *
  64607. * This callback
  64608. * - May be invoked even though the parent container or canvas sizes have not changed
  64609. * - Unlike {@link #onSizeChange}, it runs _before_ the canvas is guaranteed to be updated
  64610. * - Will be invoked from `preUpdate`, _even when_ the game is paused
  64611. *
  64612. * See {@link #onSizeChange} for a better way of reacting to layout updates.
  64613. *
  64614. * @method Phaser.ScaleManager#setResizeCallback
  64615. * @public
  64616. * @param {function} callback - The callback that will be called each time a window.resize event happens or if set, the parent container resizes.
  64617. * @param {object} context - The context in which the callback will be called.
  64618. */
  64619. setResizeCallback: function (callback, context) {
  64620. this.onResize = callback;
  64621. this.onResizeContext = context;
  64622. },
  64623. /**
  64624. * Signals a resize - IF the canvas or Game size differs from the last signal.
  64625. *
  64626. * This also triggers updates on {@link #grid} (FlexGrid) and, if in a RESIZE mode, `game.state` (StateManager).
  64627. *
  64628. * @method Phaser.ScaleManager#signalSizeChange
  64629. * @private
  64630. */
  64631. signalSizeChange: function () {
  64632. if (!Phaser.Rectangle.sameDimensions(this, this._lastReportedCanvasSize) ||
  64633. !Phaser.Rectangle.sameDimensions(this.game, this._lastReportedGameSize))
  64634. {
  64635. var width = this.width;
  64636. var height = this.height;
  64637. this._lastReportedCanvasSize.setTo(0, 0, width, height);
  64638. this._lastReportedGameSize.setTo(0, 0, this.game.width, this.game.height);
  64639. if (this.grid)
  64640. {
  64641. this.grid.onResize(width, height);
  64642. }
  64643. this.onSizeChange.dispatch(this, width, height);
  64644. // Per StateManager#onResizeCallback, it only occurs when in RESIZE mode.
  64645. if (this.currentScaleMode === Phaser.ScaleManager.RESIZE)
  64646. {
  64647. this.game.state.resize(width, height);
  64648. this.game.load.resize(width, height);
  64649. }
  64650. }
  64651. },
  64652. /**
  64653. * Set the min and max dimensions for the Display canvas.
  64654. *
  64655. * _Note:_ The min/max dimensions are only applied in some cases
  64656. * - When the device is not in an incorrect orientation; or
  64657. * - The scale mode is EXACT_FIT when not in fullscreen
  64658. *
  64659. * @method Phaser.ScaleManager#setMinMax
  64660. * @public
  64661. * @param {number} minWidth - The minimum width the game is allowed to scale down to.
  64662. * @param {number} minHeight - The minimum height the game is allowed to scale down to.
  64663. * @param {number} [maxWidth] - The maximum width the game is allowed to scale up to; only changed if specified.
  64664. * @param {number} [maxHeight] - The maximum height the game is allowed to scale up to; only changed if specified.
  64665. * @todo These values are only sometimes honored.
  64666. */
  64667. setMinMax: function (minWidth, minHeight, maxWidth, maxHeight) {
  64668. this.minWidth = minWidth;
  64669. this.minHeight = minHeight;
  64670. if (typeof maxWidth !== 'undefined')
  64671. {
  64672. this.maxWidth = maxWidth;
  64673. }
  64674. if (typeof maxHeight !== 'undefined')
  64675. {
  64676. this.maxHeight = maxHeight;
  64677. }
  64678. },
  64679. /**
  64680. * The ScaleManager.preUpdate is called automatically by the core Game loop.
  64681. *
  64682. * @method Phaser.ScaleManager#preUpdate
  64683. * @protected
  64684. */
  64685. preUpdate: function () {
  64686. if (this.game.time.time < (this._lastUpdate + this._updateThrottle))
  64687. {
  64688. return;
  64689. }
  64690. var prevThrottle = this._updateThrottle;
  64691. this._updateThrottleReset = prevThrottle >= 400 ? 0 : 100;
  64692. this.dom.getOffset(this.game.canvas, this.offset);
  64693. var prevWidth = this._parentBounds.width;
  64694. var prevHeight = this._parentBounds.height;
  64695. var bounds = this.getParentBounds(this._parentBounds);
  64696. var boundsChanged = bounds.width !== prevWidth || bounds.height !== prevHeight;
  64697. // Always invalidate on a newly detected orientation change
  64698. var orientationChanged = this.updateOrientationState();
  64699. if (boundsChanged || orientationChanged)
  64700. {
  64701. if (this.onResize)
  64702. {
  64703. this.onResize.call(this.onResizeContext, this, bounds);
  64704. }
  64705. this.updateLayout();
  64706. this.signalSizeChange();
  64707. }
  64708. // Next throttle, eg. 25, 50, 100, 200..
  64709. var throttle = this._updateThrottle * 2;
  64710. // Don't let an update be too eager about resetting the throttle.
  64711. if (this._updateThrottle < prevThrottle)
  64712. {
  64713. throttle = Math.min(prevThrottle, this._updateThrottleReset);
  64714. }
  64715. this._updateThrottle = Phaser.Math.clamp(throttle, 25, this.trackParentInterval);
  64716. this._lastUpdate = this.game.time.time;
  64717. },
  64718. /**
  64719. * Update method while paused.
  64720. *
  64721. * @method Phaser.ScaleManager#pauseUpdate
  64722. * @private
  64723. */
  64724. pauseUpdate: function () {
  64725. this.preUpdate();
  64726. // Updates at slowest.
  64727. this._updateThrottle = this.trackParentInterval;
  64728. },
  64729. /**
  64730. * Update the dimensions taking the parent scaling factor into account.
  64731. *
  64732. * @method Phaser.ScaleManager#updateDimensions
  64733. * @private
  64734. * @param {number} width - The new width of the parent container.
  64735. * @param {number} height - The new height of the parent container.
  64736. * @param {boolean} resize - True if the renderer should be resized, otherwise false to just update the internal vars.
  64737. */
  64738. updateDimensions: function (width, height, resize) {
  64739. this.width = width * this.parentScaleFactor.x;
  64740. this.height = height * this.parentScaleFactor.y;
  64741. this.game.width = this.width;
  64742. this.game.height = this.height;
  64743. this.sourceAspectRatio = this.width / this.height;
  64744. this.updateScalingAndBounds();
  64745. if (resize)
  64746. {
  64747. // Resize the renderer (which in turn resizes the Display canvas!)
  64748. this.game.renderer.resize(this.width, this.height);
  64749. // The Camera can never be smaller than the Game size
  64750. this.game.camera.setSize(this.width, this.height);
  64751. // This should only happen if the world is smaller than the new canvas size
  64752. this.game.world.resize(this.width, this.height);
  64753. }
  64754. },
  64755. /**
  64756. * Update relevant scaling values based on the ScaleManager dimension and game dimensions,
  64757. * which should already be set. This does not change {@link #sourceAspectRatio}.
  64758. *
  64759. * @method Phaser.ScaleManager#updateScalingAndBounds
  64760. * @private
  64761. */
  64762. updateScalingAndBounds: function () {
  64763. this.scaleFactor.x = this.game.width / this.width;
  64764. this.scaleFactor.y = this.game.height / this.height;
  64765. this.scaleFactorInversed.x = this.width / this.game.width;
  64766. this.scaleFactorInversed.y = this.height / this.game.height;
  64767. this.aspectRatio = this.width / this.height;
  64768. // This can be invoked in boot pre-canvas
  64769. if (this.game.canvas)
  64770. {
  64771. this.dom.getOffset(this.game.canvas, this.offset);
  64772. }
  64773. this.bounds.setTo(this.offset.x, this.offset.y, this.width, this.height);
  64774. // Can be invoked in boot pre-input
  64775. if (this.game.input && this.game.input.scale)
  64776. {
  64777. this.game.input.scale.setTo(this.scaleFactor.x, this.scaleFactor.y);
  64778. }
  64779. },
  64780. /**
  64781. * Force the game to run in only one orientation.
  64782. *
  64783. * This enables generation of incorrect orientation signals and affects resizing but does not otherwise rotate or lock the orientation.
  64784. *
  64785. * Orientation checks are performed via the Screen Orientation API, if available in browser. This means it will check your monitor
  64786. * orientation on desktop, or your device orientation on mobile, rather than comparing actual game dimensions. If you need to check the
  64787. * viewport dimensions instead and bypass the Screen Orientation API then set: `ScaleManager.compatibility.orientationFallback = 'viewport'`
  64788. *
  64789. * @method Phaser.ScaleManager#forceOrientation
  64790. * @public
  64791. * @param {boolean} forceLandscape - true if the game should run in landscape mode only.
  64792. * @param {boolean} [forcePortrait=false] - true if the game should run in portrait mode only.
  64793. */
  64794. forceOrientation: function (forceLandscape, forcePortrait) {
  64795. if (forcePortrait === undefined) { forcePortrait = false; }
  64796. this.forceLandscape = forceLandscape;
  64797. this.forcePortrait = forcePortrait;
  64798. this.queueUpdate(true);
  64799. },
  64800. /**
  64801. * Classify the orientation, per `getScreenOrientation`.
  64802. *
  64803. * @method Phaser.ScaleManager#classifyOrientation
  64804. * @private
  64805. * @param {string} orientation - The orientation string, e.g. 'portrait-primary'.
  64806. * @return {?string} The classified orientation: 'portrait', 'landscape`, or null.
  64807. */
  64808. classifyOrientation: function (orientation) {
  64809. if (orientation === 'portrait-primary' || orientation === 'portrait-secondary')
  64810. {
  64811. return 'portrait';
  64812. }
  64813. else if (orientation === 'landscape-primary' || orientation === 'landscape-secondary')
  64814. {
  64815. return 'landscape';
  64816. }
  64817. else
  64818. {
  64819. return null;
  64820. }
  64821. },
  64822. /**
  64823. * Updates the current orientation and dispatches orientation change events.
  64824. *
  64825. * @method Phaser.ScaleManager#updateOrientationState
  64826. * @private
  64827. * @return {boolean} True if the orientation state changed which means a forced update is likely required.
  64828. */
  64829. updateOrientationState: function () {
  64830. var previousOrientation = this.screenOrientation;
  64831. var previouslyIncorrect = this.incorrectOrientation;
  64832. this.screenOrientation = this.dom.getScreenOrientation(this.compatibility.orientationFallback);
  64833. this.incorrectOrientation = (this.forceLandscape && !this.isLandscape) ||
  64834. (this.forcePortrait && !this.isPortrait);
  64835. var changed = previousOrientation !== this.screenOrientation;
  64836. var correctnessChanged = previouslyIncorrect !== this.incorrectOrientation;
  64837. if (correctnessChanged)
  64838. {
  64839. if (this.incorrectOrientation)
  64840. {
  64841. this.enterIncorrectOrientation.dispatch();
  64842. }
  64843. else
  64844. {
  64845. this.leaveIncorrectOrientation.dispatch();
  64846. }
  64847. }
  64848. if (changed || correctnessChanged)
  64849. {
  64850. this.onOrientationChange.dispatch(this, previousOrientation, previouslyIncorrect);
  64851. }
  64852. return changed || correctnessChanged;
  64853. },
  64854. /**
  64855. * window.orientationchange event handler.
  64856. *
  64857. * @method Phaser.ScaleManager#orientationChange
  64858. * @private
  64859. * @param {Event} event - The orientationchange event data.
  64860. */
  64861. orientationChange: function (event) {
  64862. this.event = event;
  64863. this.queueUpdate(true);
  64864. },
  64865. /**
  64866. * window.resize event handler.
  64867. *
  64868. * @method Phaser.ScaleManager#windowResize
  64869. * @private
  64870. * @param {Event} event - The resize event data.
  64871. */
  64872. windowResize: function (event) {
  64873. this.event = event;
  64874. this.queueUpdate(true);
  64875. },
  64876. /**
  64877. * Scroll to the top - in some environments. See `compatibility.scrollTo`.
  64878. *
  64879. * @method Phaser.ScaleManager#scrollTop
  64880. * @private
  64881. */
  64882. scrollTop: function () {
  64883. var scrollTo = this.compatibility.scrollTo;
  64884. if (scrollTo)
  64885. {
  64886. window.scrollTo(scrollTo.x, scrollTo.y);
  64887. }
  64888. },
  64889. /**
  64890. * The "refresh" methods informs the ScaleManager that a layout refresh is required.
  64891. *
  64892. * The ScaleManager automatically queues a layout refresh (eg. updates the Game size or Display canvas layout)
  64893. * when the browser is resized, the orientation changes, or when there is a detected change
  64894. * of the Parent size. Refreshing is also done automatically when public properties,
  64895. * such as {@link #scaleMode}, are updated or state-changing methods are invoked.
  64896. *
  64897. * The "refresh" method _may_ need to be used in a few (rare) situtations when
  64898. *
  64899. * - a device change event is not correctly detected; or
  64900. * - the Parent size changes (and an immediate reflow is desired); or
  64901. * - the ScaleManager state is updated by non-standard means; or
  64902. * - certain {@link #compatibility} properties are manually changed.
  64903. *
  64904. * The queued layout refresh is not immediate but will run promptly in an upcoming `preRender`.
  64905. *
  64906. * @method Phaser.ScaleManager#refresh
  64907. * @public
  64908. */
  64909. refresh: function () {
  64910. this.scrollTop();
  64911. this.queueUpdate(true);
  64912. },
  64913. /**
  64914. * Updates the game / canvas position and size.
  64915. *
  64916. * @method Phaser.ScaleManager#updateLayout
  64917. * @private
  64918. */
  64919. updateLayout: function () {
  64920. var scaleMode = this.currentScaleMode;
  64921. if (scaleMode === Phaser.ScaleManager.RESIZE)
  64922. {
  64923. this.reflowGame();
  64924. return;
  64925. }
  64926. this.scrollTop();
  64927. if (this.compatibility.forceMinimumDocumentHeight)
  64928. {
  64929. // (This came from older code, by why is it here?)
  64930. // Set minimum height of content to new window height
  64931. document.documentElement.style.minHeight = window.innerHeight + 'px';
  64932. }
  64933. if (this.incorrectOrientation)
  64934. {
  64935. this.setMaximum();
  64936. }
  64937. else
  64938. {
  64939. if (scaleMode === Phaser.ScaleManager.EXACT_FIT)
  64940. {
  64941. this.setExactFit();
  64942. }
  64943. else if (scaleMode === Phaser.ScaleManager.SHOW_ALL)
  64944. {
  64945. if (!this.isFullScreen && this.boundingParent &&
  64946. this.compatibility.canExpandParent)
  64947. {
  64948. // Try to expand parent out, but choosing maximizing dimensions.
  64949. // Then select minimize dimensions which should then honor parent
  64950. // maximum bound applications.
  64951. this.setShowAll(true);
  64952. this.resetCanvas();
  64953. this.setShowAll();
  64954. }
  64955. else
  64956. {
  64957. this.setShowAll();
  64958. }
  64959. }
  64960. else if (scaleMode === Phaser.ScaleManager.NO_SCALE)
  64961. {
  64962. this.width = this.game.width;
  64963. this.height = this.game.height;
  64964. }
  64965. else if (scaleMode === Phaser.ScaleManager.USER_SCALE)
  64966. {
  64967. this.width = (this.game.width * this._userScaleFactor.x) - this._userScaleTrim.x;
  64968. this.height = (this.game.height * this._userScaleFactor.y) - this._userScaleTrim.y;
  64969. }
  64970. }
  64971. if (!this.compatibility.canExpandParent &&
  64972. (scaleMode === Phaser.ScaleManager.SHOW_ALL || scaleMode === Phaser.ScaleManager.USER_SCALE))
  64973. {
  64974. var bounds = this.getParentBounds(this._tempBounds);
  64975. this.width = Math.min(this.width, bounds.width);
  64976. this.height = Math.min(this.height, bounds.height);
  64977. }
  64978. // Always truncate / force to integer
  64979. this.width = this.width | 0;
  64980. this.height = this.height | 0;
  64981. this.reflowCanvas();
  64982. },
  64983. /**
  64984. * Returns the computed Parent size/bounds that the Display canvas is allowed/expected to fill.
  64985. *
  64986. * If in fullscreen mode or without parent (see {@link #parentIsWindow}),
  64987. * this will be the bounds of the visual viewport itself.
  64988. *
  64989. * This function takes the {@link #windowConstraints} into consideration - if the parent is partially outside
  64990. * the viewport then this function may return a smaller than expected size.
  64991. *
  64992. * Values are rounded to the nearest pixel.
  64993. *
  64994. * @method Phaser.ScaleManager#getParentBounds
  64995. * @protected
  64996. * @param {Phaser.Rectangle} [target=(new Rectangle)] - The rectangle to update; a new one is created as needed.
  64997. * @return {Phaser.Rectangle} The established parent bounds.
  64998. */
  64999. getParentBounds: function (target) {
  65000. var bounds = target || new Phaser.Rectangle();
  65001. var parentNode = this.boundingParent;
  65002. var visualBounds = this.dom.visualBounds;
  65003. var layoutBounds = this.dom.layoutBounds;
  65004. if (!parentNode)
  65005. {
  65006. bounds.setTo(0, 0, visualBounds.width, visualBounds.height);
  65007. }
  65008. else
  65009. {
  65010. // Ref. http://msdn.microsoft.com/en-us/library/hh781509(v=vs.85).aspx for getBoundingClientRect
  65011. var clientRect = parentNode.getBoundingClientRect();
  65012. var parentRect = (parentNode.offsetParent) ? parentNode.offsetParent.getBoundingClientRect() : parentNode.getBoundingClientRect();
  65013. bounds.setTo(clientRect.left - parentRect.left, clientRect.top - parentRect.top, clientRect.width, clientRect.height);
  65014. var wc = this.windowConstraints;
  65015. if (wc.right)
  65016. {
  65017. var windowBounds = wc.right === 'layout' ? layoutBounds : visualBounds;
  65018. bounds.right = Math.min(bounds.right, windowBounds.width);
  65019. }
  65020. if (wc.bottom)
  65021. {
  65022. var windowBounds = wc.bottom === 'layout' ? layoutBounds : visualBounds;
  65023. bounds.bottom = Math.min(bounds.bottom, windowBounds.height);
  65024. }
  65025. }
  65026. bounds.setTo(
  65027. Math.round(bounds.x), Math.round(bounds.y),
  65028. Math.round(bounds.width), Math.round(bounds.height));
  65029. return bounds;
  65030. },
  65031. /**
  65032. * Update the canvas position/margins - for alignment within the parent container.
  65033. *
  65034. * The canvas margins _must_ be reset/cleared prior to invoking this.
  65035. *
  65036. * @method Phaser.ScaleManager#alignCanvas
  65037. * @private
  65038. * @param {boolean} horizontal - Align horizontally?
  65039. * @param {boolean} vertical - Align vertically?
  65040. */
  65041. alignCanvas: function (horizontal, vertical) {
  65042. var parentBounds = this.getParentBounds(this._tempBounds);
  65043. var canvas = this.game.canvas;
  65044. var margin = this.margin;
  65045. if (horizontal)
  65046. {
  65047. margin.left = margin.right = 0;
  65048. var canvasBounds = canvas.getBoundingClientRect();
  65049. if (this.width < parentBounds.width && !this.incorrectOrientation)
  65050. {
  65051. var currentEdge = canvasBounds.left - parentBounds.x;
  65052. var targetEdge = (parentBounds.width / 2) - (this.width / 2);
  65053. targetEdge = Math.max(targetEdge, 0);
  65054. var offset = targetEdge - currentEdge;
  65055. margin.left = Math.round(offset);
  65056. }
  65057. canvas.style.marginLeft = margin.left + 'px';
  65058. if (margin.left !== 0)
  65059. {
  65060. margin.right = -(parentBounds.width - canvasBounds.width - margin.left);
  65061. canvas.style.marginRight = margin.right + 'px';
  65062. }
  65063. }
  65064. if (vertical)
  65065. {
  65066. margin.top = margin.bottom = 0;
  65067. var canvasBounds = canvas.getBoundingClientRect();
  65068. if (this.height < parentBounds.height && !this.incorrectOrientation)
  65069. {
  65070. var currentEdge = canvasBounds.top - parentBounds.y;
  65071. var targetEdge = (parentBounds.height / 2) - (this.height / 2);
  65072. targetEdge = Math.max(targetEdge, 0);
  65073. var offset = targetEdge - currentEdge;
  65074. margin.top = Math.round(offset);
  65075. }
  65076. canvas.style.marginTop = margin.top + 'px';
  65077. if (margin.top !== 0)
  65078. {
  65079. margin.bottom = -(parentBounds.height - canvasBounds.height - margin.top);
  65080. canvas.style.marginBottom = margin.bottom + 'px';
  65081. }
  65082. }
  65083. // Silly backwards compatibility..
  65084. margin.x = margin.left;
  65085. margin.y = margin.top;
  65086. },
  65087. /**
  65088. * Updates the Game state / size.
  65089. *
  65090. * The canvas margins may always be adjusted, even if alignment is not in effect.
  65091. *
  65092. * @method Phaser.ScaleManager#reflowGame
  65093. * @private
  65094. */
  65095. reflowGame: function () {
  65096. this.resetCanvas('', '');
  65097. var bounds = this.getParentBounds(this._tempBounds);
  65098. this.updateDimensions(bounds.width, bounds.height, true);
  65099. },
  65100. /**
  65101. * Updates the Display canvas size.
  65102. *
  65103. * The canvas margins may always be adjusted, even alignment is not in effect.
  65104. *
  65105. * @method Phaser.ScaleManager#reflowCanvas
  65106. * @private
  65107. */
  65108. reflowCanvas: function () {
  65109. if (!this.incorrectOrientation)
  65110. {
  65111. this.width = Phaser.Math.clamp(this.width, this.minWidth || 0, this.maxWidth || this.width);
  65112. this.height = Phaser.Math.clamp(this.height, this.minHeight || 0, this.maxHeight || this.height);
  65113. }
  65114. this.resetCanvas();
  65115. if (!this.compatibility.noMargins)
  65116. {
  65117. if (this.isFullScreen && this._createdFullScreenTarget)
  65118. {
  65119. this.alignCanvas(true, true);
  65120. }
  65121. else
  65122. {
  65123. this.alignCanvas(this.pageAlignHorizontally, this.pageAlignVertically);
  65124. }
  65125. }
  65126. this.updateScalingAndBounds();
  65127. },
  65128. /**
  65129. * "Reset" the Display canvas and set the specified width/height.
  65130. *
  65131. * @method Phaser.ScaleManager#resetCanvas
  65132. * @private
  65133. * @param {string} [cssWidth=(current width)] - The css width to set.
  65134. * @param {string} [cssHeight=(current height)] - The css height to set.
  65135. */
  65136. resetCanvas: function (cssWidth, cssHeight) {
  65137. if (cssWidth === undefined) { cssWidth = this.width + 'px'; }
  65138. if (cssHeight === undefined) { cssHeight = this.height + 'px'; }
  65139. var canvas = this.game.canvas;
  65140. if (!this.compatibility.noMargins)
  65141. {
  65142. canvas.style.marginLeft = '';
  65143. canvas.style.marginTop = '';
  65144. canvas.style.marginRight = '';
  65145. canvas.style.marginBottom = '';
  65146. }
  65147. canvas.style.width = cssWidth;
  65148. canvas.style.height = cssHeight;
  65149. },
  65150. /**
  65151. * Queues/marks a size/bounds check as needing to occur (from `preUpdate`).
  65152. *
  65153. * @method Phaser.ScaleManager#queueUpdate
  65154. * @private
  65155. * @param {boolean} force - If true resets the parent bounds to ensure the check is dirty.
  65156. */
  65157. queueUpdate: function (force) {
  65158. if (force)
  65159. {
  65160. this._parentBounds.width = 0;
  65161. this._parentBounds.height = 0;
  65162. }
  65163. this._updateThrottle = this._updateThrottleReset;
  65164. },
  65165. /**
  65166. * Reset internal data/state.
  65167. *
  65168. * @method Phaser.ScaleManager#reset
  65169. * @private
  65170. */
  65171. reset: function (clearWorld) {
  65172. if (clearWorld && this.grid)
  65173. {
  65174. this.grid.reset();
  65175. }
  65176. },
  65177. /**
  65178. * Updates the width/height to that of the window.
  65179. *
  65180. * @method Phaser.ScaleManager#setMaximum
  65181. * @private
  65182. */
  65183. setMaximum: function () {
  65184. this.width = this.dom.visualBounds.width;
  65185. this.height = this.dom.visualBounds.height;
  65186. },
  65187. /**
  65188. * Updates the width/height such that the game is scaled proportionally.
  65189. *
  65190. * @method Phaser.ScaleManager#setShowAll
  65191. * @private
  65192. * @param {boolean} expanding - If true then the maximizing dimension is chosen.
  65193. */
  65194. setShowAll: function (expanding) {
  65195. var bounds = this.getParentBounds(this._tempBounds);
  65196. var width = bounds.width;
  65197. var height = bounds.height;
  65198. var multiplier;
  65199. if (expanding)
  65200. {
  65201. multiplier = Math.max((height / this.game.height), (width / this.game.width));
  65202. }
  65203. else
  65204. {
  65205. multiplier = Math.min((height / this.game.height), (width / this.game.width));
  65206. }
  65207. this.width = Math.round(this.game.width * multiplier);
  65208. this.height = Math.round(this.game.height * multiplier);
  65209. },
  65210. /**
  65211. * Updates the width/height such that the game is stretched to the available size.
  65212. * Honors {@link #maxWidth} and {@link #maxHeight} when _not_ in fullscreen.
  65213. *
  65214. * @method Phaser.ScaleManager#setExactFit
  65215. * @private
  65216. */
  65217. setExactFit: function () {
  65218. var bounds = this.getParentBounds(this._tempBounds);
  65219. this.width = bounds.width;
  65220. this.height = bounds.height;
  65221. if (this.isFullScreen)
  65222. {
  65223. // Max/min not honored fullscreen
  65224. return;
  65225. }
  65226. if (this.maxWidth)
  65227. {
  65228. this.width = Math.min(this.width, this.maxWidth);
  65229. }
  65230. if (this.maxHeight)
  65231. {
  65232. this.height = Math.min(this.height, this.maxHeight);
  65233. }
  65234. },
  65235. /**
  65236. * Creates a fullscreen target. This is called automatically as as needed when entering
  65237. * fullscreen mode and the resulting element is supplied to {@link #onFullScreenInit}.
  65238. *
  65239. * Use {@link #onFullScreenInit} to customize the created object.
  65240. *
  65241. * @method Phaser.ScaleManager#createFullScreenTarget
  65242. * @protected
  65243. */
  65244. createFullScreenTarget: function () {
  65245. var fsTarget = document.createElement('div');
  65246. fsTarget.style.margin = '0';
  65247. fsTarget.style.padding = '0';
  65248. fsTarget.style.background = '#000';
  65249. return fsTarget;
  65250. },
  65251. /**
  65252. * Start the browsers fullscreen mode - this _must_ be called from a user input Pointer or Mouse event.
  65253. *
  65254. * The Fullscreen API must be supported by the browser for this to work - it is not the same as setting
  65255. * the game size to fill the browser window. See {@link Phaser.ScaleManager#compatibility compatibility.supportsFullScreen} to check if the current
  65256. * device is reported to support fullscreen mode.
  65257. *
  65258. * The {@link #fullScreenFailed} signal will be dispatched if the fullscreen change request failed or the game does not support the Fullscreen API.
  65259. *
  65260. * @method Phaser.ScaleManager#startFullScreen
  65261. * @public
  65262. * @param {boolean} [antialias] - Changes the anti-alias feature of the canvas before jumping in to fullscreen (false = retain pixel art, true = smooth art). If not specified then no change is made. Only works in CANVAS mode.
  65263. * @param {boolean} [allowTrampoline=undefined] - Internal argument. If `false` click trampolining is suppressed.
  65264. * @return {boolean} Returns true if the device supports fullscreen mode and fullscreen mode was attempted to be started. (It might not actually start, wait for the signals.)
  65265. */
  65266. startFullScreen: function (antialias, allowTrampoline) {
  65267. if (this.isFullScreen)
  65268. {
  65269. return false;
  65270. }
  65271. if (!this.compatibility.supportsFullScreen)
  65272. {
  65273. // Error is called in timeout to emulate the real fullscreenerror event better
  65274. var _this = this;
  65275. setTimeout(function () {
  65276. _this.fullScreenError();
  65277. }, 10);
  65278. return;
  65279. }
  65280. if (this.compatibility.clickTrampoline === 'when-not-mouse')
  65281. {
  65282. var input = this.game.input;
  65283. if (input.activePointer &&
  65284. input.activePointer !== input.mousePointer &&
  65285. (allowTrampoline || allowTrampoline !== false))
  65286. {
  65287. input.activePointer.addClickTrampoline("startFullScreen", this.startFullScreen, this, [antialias, false]);
  65288. return;
  65289. }
  65290. }
  65291. if (antialias !== undefined && this.game.renderType === Phaser.CANVAS)
  65292. {
  65293. this.game.stage.smoothed = antialias;
  65294. }
  65295. var fsTarget = this.fullScreenTarget;
  65296. if (!fsTarget)
  65297. {
  65298. this.cleanupCreatedTarget();
  65299. this._createdFullScreenTarget = this.createFullScreenTarget();
  65300. fsTarget = this._createdFullScreenTarget;
  65301. }
  65302. var initData = {
  65303. targetElement: fsTarget
  65304. };
  65305. this.hasPhaserSetFullScreen = true;
  65306. this.onFullScreenInit.dispatch(this, initData);
  65307. if (this._createdFullScreenTarget)
  65308. {
  65309. // Move the Display canvas inside of the target and add the target to the DOM
  65310. // (The target has to be added for the Fullscreen API to work.)
  65311. var canvas = this.game.canvas;
  65312. var parent = canvas.parentNode;
  65313. parent.insertBefore(fsTarget, canvas);
  65314. fsTarget.appendChild(canvas);
  65315. }
  65316. if (this.game.device.fullscreenKeyboard)
  65317. {
  65318. fsTarget[this.game.device.requestFullscreen](Element.ALLOW_KEYBOARD_INPUT);
  65319. }
  65320. else
  65321. {
  65322. fsTarget[this.game.device.requestFullscreen]();
  65323. }
  65324. return true;
  65325. },
  65326. /**
  65327. * Stops / exits fullscreen mode, if active.
  65328. *
  65329. * @method Phaser.ScaleManager#stopFullScreen
  65330. * @public
  65331. * @return {boolean} Returns true if the browser supports fullscreen mode and fullscreen mode will be exited.
  65332. */
  65333. stopFullScreen: function () {
  65334. if (!this.isFullScreen || !this.compatibility.supportsFullScreen)
  65335. {
  65336. return false;
  65337. }
  65338. this.hasPhaserSetFullScreen = false;
  65339. document[this.game.device.cancelFullscreen]();
  65340. return true;
  65341. },
  65342. /**
  65343. * Cleans up the previous fullscreen target, if such was automatically created.
  65344. * This ensures the canvas is restored to its former parent, assuming the target didn't move.
  65345. *
  65346. * @method Phaser.ScaleManager#cleanupCreatedTarget
  65347. * @private
  65348. */
  65349. cleanupCreatedTarget: function () {
  65350. var fsTarget = this._createdFullScreenTarget;
  65351. if (fsTarget && fsTarget.parentNode)
  65352. {
  65353. // Make sure to cleanup synthetic target for sure;
  65354. // swap the canvas back to the parent.
  65355. var parent = fsTarget.parentNode;
  65356. parent.insertBefore(this.game.canvas, fsTarget);
  65357. parent.removeChild(fsTarget);
  65358. }
  65359. this._createdFullScreenTarget = null;
  65360. },
  65361. /**
  65362. * Used to prepare/restore extra fullscreen mode settings.
  65363. * (This does move any elements within the DOM tree.)
  65364. *
  65365. * @method Phaser.ScaleManager#prepScreenMode
  65366. * @private
  65367. * @param {boolean} enteringFullscreen - True if _entering_ fullscreen, false if _leaving_.
  65368. */
  65369. prepScreenMode: function (enteringFullscreen) {
  65370. var createdTarget = !!this._createdFullScreenTarget;
  65371. var fsTarget = this._createdFullScreenTarget || this.fullScreenTarget;
  65372. if (enteringFullscreen)
  65373. {
  65374. if (createdTarget || this.fullScreenScaleMode === Phaser.ScaleManager.EXACT_FIT)
  65375. {
  65376. // Resize target, as long as it's not the canvas
  65377. if (fsTarget !== this.game.canvas)
  65378. {
  65379. this._fullScreenRestore = {
  65380. targetWidth: fsTarget.style.width,
  65381. targetHeight: fsTarget.style.height
  65382. };
  65383. fsTarget.style.width = '100%';
  65384. fsTarget.style.height = '100%';
  65385. }
  65386. }
  65387. }
  65388. else
  65389. {
  65390. // Have restore information
  65391. if (this._fullScreenRestore)
  65392. {
  65393. fsTarget.style.width = this._fullScreenRestore.targetWidth;
  65394. fsTarget.style.height = this._fullScreenRestore.targetHeight;
  65395. this._fullScreenRestore = null;
  65396. }
  65397. // Always reset to game size
  65398. this.updateDimensions(this._gameSize.width, this._gameSize.height, true);
  65399. this.resetCanvas();
  65400. }
  65401. },
  65402. /**
  65403. * Called automatically when the browser enters of leaves fullscreen mode.
  65404. *
  65405. * @method Phaser.ScaleManager#fullScreenChange
  65406. * @private
  65407. * @param {Event} [event=undefined] - The fullscreenchange event
  65408. */
  65409. fullScreenChange: function (event) {
  65410. this.event = event;
  65411. if (this.isFullScreen)
  65412. {
  65413. this.prepScreenMode(true);
  65414. this.updateLayout();
  65415. this.queueUpdate(true);
  65416. }
  65417. else
  65418. {
  65419. this.prepScreenMode(false);
  65420. this.cleanupCreatedTarget();
  65421. this.updateLayout();
  65422. this.queueUpdate(true);
  65423. }
  65424. this.onFullScreenChange.dispatch(this, this.width, this.height);
  65425. },
  65426. /**
  65427. * Called automatically when the browser fullscreen request fails;
  65428. * or called when a fullscreen request is made on a device for which it is not supported.
  65429. *
  65430. * @method Phaser.ScaleManager#fullScreenError
  65431. * @private
  65432. * @param {Event} [event=undefined] - The fullscreenerror event; undefined if invoked on a device that does not support the Fullscreen API.
  65433. */
  65434. fullScreenError: function (event) {
  65435. this.event = event;
  65436. this.cleanupCreatedTarget();
  65437. console.warn('Phaser.ScaleManager: requestFullscreen failed or device does not support the Fullscreen API');
  65438. this.onFullScreenError.dispatch(this);
  65439. },
  65440. /**
  65441. * Takes a Sprite or Image object and scales it to fit the given dimensions.
  65442. * Scaling happens proportionally without distortion to the sprites texture.
  65443. * The letterBox parameter controls if scaling will produce a letter-box effect or zoom the
  65444. * sprite until it fills the given values. Note that with letterBox set to false the scaled sprite may spill out over either
  65445. * the horizontal or vertical sides of the target dimensions. If you wish to stop this you can crop the Sprite.
  65446. *
  65447. * @method Phaser.ScaleManager#scaleSprite
  65448. * @protected
  65449. * @param {Phaser.Sprite|Phaser.Image} sprite - The sprite we want to scale.
  65450. * @param {integer} [width] - The target width that we want to fit the sprite in to. If not given it defaults to ScaleManager.width.
  65451. * @param {integer} [height] - The target height that we want to fit the sprite in to. If not given it defaults to ScaleManager.height.
  65452. * @param {boolean} [letterBox=false] - True if we want the `fitted` mode. Otherwise, the function uses the `zoom` mode.
  65453. * @return {Phaser.Sprite|Phaser.Image} The scaled sprite.
  65454. */
  65455. scaleSprite: function (sprite, width, height, letterBox) {
  65456. if (width === undefined) { width = this.width; }
  65457. if (height === undefined) { height = this.height; }
  65458. if (letterBox === undefined) { letterBox = false; }
  65459. if (!sprite || !sprite['scale'])
  65460. {
  65461. return sprite;
  65462. }
  65463. sprite.scale.x = 1;
  65464. sprite.scale.y = 1;
  65465. if ((sprite.width <= 0) || (sprite.height <= 0) || (width <= 0) || (height <= 0))
  65466. {
  65467. return sprite;
  65468. }
  65469. var scaleX1 = width;
  65470. var scaleY1 = (sprite.height * width) / sprite.width;
  65471. var scaleX2 = (sprite.width * height) / sprite.height;
  65472. var scaleY2 = height;
  65473. var scaleOnWidth = (scaleX2 > width);
  65474. if (scaleOnWidth)
  65475. {
  65476. scaleOnWidth = letterBox;
  65477. }
  65478. else
  65479. {
  65480. scaleOnWidth = !letterBox;
  65481. }
  65482. if (scaleOnWidth)
  65483. {
  65484. sprite.width = Math.floor(scaleX1);
  65485. sprite.height = Math.floor(scaleY1);
  65486. }
  65487. else
  65488. {
  65489. sprite.width = Math.floor(scaleX2);
  65490. sprite.height = Math.floor(scaleY2);
  65491. }
  65492. // Enable at some point?
  65493. // sprite.x = Math.floor((width - sprite.width) / 2);
  65494. // sprite.y = Math.floor((height - sprite.height) / 2);
  65495. return sprite;
  65496. },
  65497. /**
  65498. * Destroys the ScaleManager and removes any event listeners.
  65499. * This should probably only be called when the game is destroyed.
  65500. *
  65501. * @method Phaser.ScaleManager#destroy
  65502. * @protected
  65503. */
  65504. destroy: function () {
  65505. this.game.onResume.remove(this._gameResumed, this);
  65506. window.removeEventListener('orientationchange', this._orientationChange, false);
  65507. window.removeEventListener('resize', this._windowResize, false);
  65508. if (this.compatibility.supportsFullScreen)
  65509. {
  65510. document.removeEventListener('webkitfullscreenchange', this._fullScreenChange, false);
  65511. document.removeEventListener('mozfullscreenchange', this._fullScreenChange, false);
  65512. document.removeEventListener('MSFullscreenChange', this._fullScreenChange, false);
  65513. document.removeEventListener('fullscreenchange', this._fullScreenChange, false);
  65514. document.removeEventListener('webkitfullscreenerror', this._fullScreenError, false);
  65515. document.removeEventListener('mozfullscreenerror', this._fullScreenError, false);
  65516. document.removeEventListener('MSFullscreenError', this._fullScreenError, false);
  65517. document.removeEventListener('fullscreenerror', this._fullScreenError, false);
  65518. }
  65519. }
  65520. };
  65521. Phaser.ScaleManager.prototype.constructor = Phaser.ScaleManager;
  65522. /**
  65523. * The DOM element that is considered the Parent bounding element, if any.
  65524. *
  65525. * This `null` if {@link #parentIsWindow} is true or if fullscreen mode is entered and {@link #fullScreenTarget} is specified.
  65526. * It will also be null if there is no game canvas or if the game canvas has no parent.
  65527. *
  65528. * @name Phaser.ScaleManager#boundingParent
  65529. * @property {?DOMElement} boundingParent
  65530. * @readonly
  65531. */
  65532. Object.defineProperty(Phaser.ScaleManager.prototype, "boundingParent", {
  65533. get: function () {
  65534. if (this.parentIsWindow ||
  65535. (this.isFullScreen && this.hasPhaserSetFullScreen && !this._createdFullScreenTarget))
  65536. {
  65537. return null;
  65538. }
  65539. var parentNode = this.game.canvas && this.game.canvas.parentNode;
  65540. return parentNode || null;
  65541. }
  65542. });
  65543. /**
  65544. * The scaling method used by the ScaleManager when not in fullscreen.
  65545. *
  65546. * <dl>
  65547. * <dt>{@link Phaser.ScaleManager.NO_SCALE}</dt>
  65548. * <dd>
  65549. * The Game display area will not be scaled - even if it is too large for the canvas/screen.
  65550. * This mode _ignores_ any applied scaling factor and displays the canvas at the Game size.
  65551. * </dd>
  65552. * <dt>{@link Phaser.ScaleManager.EXACT_FIT}</dt>
  65553. * <dd>
  65554. * The Game display area will be _stretched_ to fill the entire size of the canvas's parent element and/or screen.
  65555. * Proportions are not maintained.
  65556. * </dd>
  65557. * <dt>{@link Phaser.ScaleManager.SHOW_ALL}</dt>
  65558. * <dd>
  65559. * Show the entire game display area while _maintaining_ the original aspect ratio.
  65560. * </dd>
  65561. * <dt>{@link Phaser.ScaleManager.RESIZE}</dt>
  65562. * <dd>
  65563. * The dimensions of the game display area are changed to match the size of the parent container.
  65564. * That is, this mode _changes the Game size_ to match the display size.
  65565. * <p>
  65566. * Any manually set Game size (see {@link #setGameSize}) is ignored while in effect.
  65567. * </dd>
  65568. * <dt>{@link Phaser.ScaleManager.USER_SCALE}</dt>
  65569. * <dd>
  65570. * The game Display is scaled according to the user-specified scale set by {@link Phaser.ScaleManager#setUserScale setUserScale}.
  65571. * <p>
  65572. * This scale can be adjusted in the {@link Phaser.ScaleManager#setResizeCallback resize callback}
  65573. * for flexible custom-sizing needs.
  65574. * </dd>
  65575. * </dl>
  65576. *
  65577. * @name Phaser.ScaleManager#scaleMode
  65578. * @property {integer} scaleMode
  65579. */
  65580. Object.defineProperty(Phaser.ScaleManager.prototype, "scaleMode", {
  65581. get: function () {
  65582. return this._scaleMode;
  65583. },
  65584. set: function (value) {
  65585. if (value !== this._scaleMode)
  65586. {
  65587. if (!this.isFullScreen)
  65588. {
  65589. this.updateDimensions(this._gameSize.width, this._gameSize.height, true);
  65590. this.queueUpdate(true);
  65591. }
  65592. this._scaleMode = value;
  65593. }
  65594. return this._scaleMode;
  65595. }
  65596. });
  65597. /**
  65598. * The scaling method used by the ScaleManager when in fullscreen.
  65599. *
  65600. * See {@link Phaser.ScaleManager#scaleMode scaleMode} for the different modes allowed.
  65601. *
  65602. * @name Phaser.ScaleManager#fullScreenScaleMode
  65603. * @property {integer} fullScreenScaleMode
  65604. */
  65605. Object.defineProperty(Phaser.ScaleManager.prototype, "fullScreenScaleMode", {
  65606. get: function () {
  65607. return this._fullScreenScaleMode;
  65608. },
  65609. set: function (value) {
  65610. if (value !== this._fullScreenScaleMode)
  65611. {
  65612. // If in fullscreen then need a wee bit more work
  65613. if (this.isFullScreen)
  65614. {
  65615. this.prepScreenMode(false);
  65616. this._fullScreenScaleMode = value;
  65617. this.prepScreenMode(true);
  65618. this.queueUpdate(true);
  65619. }
  65620. else
  65621. {
  65622. this._fullScreenScaleMode = value;
  65623. }
  65624. }
  65625. return this._fullScreenScaleMode;
  65626. }
  65627. });
  65628. /**
  65629. * Returns the current scale mode - for normal or fullscreen operation.
  65630. *
  65631. * See {@link Phaser.ScaleManager#scaleMode scaleMode} for the different modes allowed.
  65632. *
  65633. * @name Phaser.ScaleManager#currentScaleMode
  65634. * @property {number} currentScaleMode
  65635. * @protected
  65636. * @readonly
  65637. */
  65638. Object.defineProperty(Phaser.ScaleManager.prototype, "currentScaleMode", {
  65639. get: function () {
  65640. return this.isFullScreen ? this._fullScreenScaleMode : this._scaleMode;
  65641. }
  65642. });
  65643. /**
  65644. * When enabled the Display canvas will be horizontally-aligned _in the Parent container_ (or {@link Phaser.ScaleManager#parentIsWindow window}).
  65645. *
  65646. * To align horizontally across the page the Display canvas should be added directly to page;
  65647. * or the parent container should itself be horizontally aligned.
  65648. *
  65649. * Horizontal alignment is not applicable with the {@link .RESIZE} scaling mode.
  65650. *
  65651. * @name Phaser.ScaleManager#pageAlignHorizontally
  65652. * @property {boolean} pageAlignHorizontally
  65653. * @default false
  65654. */
  65655. Object.defineProperty(Phaser.ScaleManager.prototype, "pageAlignHorizontally", {
  65656. get: function () {
  65657. return this._pageAlignHorizontally;
  65658. },
  65659. set: function (value) {
  65660. if (value !== this._pageAlignHorizontally)
  65661. {
  65662. this._pageAlignHorizontally = value;
  65663. this.queueUpdate(true);
  65664. }
  65665. }
  65666. });
  65667. /**
  65668. * When enabled the Display canvas will be vertically-aligned _in the Parent container_ (or {@link Phaser.ScaleManager#parentIsWindow window}).
  65669. *
  65670. * To align vertically the Parent element should have a _non-collapsible_ height, such that it will maintain
  65671. * a height _larger_ than the height of the contained Game canvas - the game canvas will then be scaled vertically
  65672. * _within_ the remaining available height dictated by the Parent element.
  65673. *
  65674. * One way to prevent the parent from collapsing is to add an absolute "min-height" CSS property to the parent element.
  65675. * If specifying a relative "min-height/height" or adjusting margins, the Parent height must still be non-collapsible (see note).
  65676. *
  65677. * _Note_: In version 2.2 the minimum document height is _not_ automatically set to the viewport/window height.
  65678. * To automatically update the minimum document height set {@link Phaser.ScaleManager#compatibility compatibility.forceMinimumDocumentHeight} to true.
  65679. *
  65680. * Vertical alignment is not applicable with the {@link .RESIZE} scaling mode.
  65681. *
  65682. * @name Phaser.ScaleManager#pageAlignVertically
  65683. * @property {boolean} pageAlignVertically
  65684. * @default false
  65685. */
  65686. Object.defineProperty(Phaser.ScaleManager.prototype, "pageAlignVertically", {
  65687. get: function () {
  65688. return this._pageAlignVertically;
  65689. },
  65690. set: function (value) {
  65691. if (value !== this._pageAlignVertically)
  65692. {
  65693. this._pageAlignVertically = value;
  65694. this.queueUpdate(true);
  65695. }
  65696. }
  65697. });
  65698. /**
  65699. * Returns true if the browser is in fullscreen mode, otherwise false.
  65700. * @name Phaser.ScaleManager#isFullScreen
  65701. * @property {boolean} isFullScreen
  65702. * @readonly
  65703. */
  65704. Object.defineProperty(Phaser.ScaleManager.prototype, "isFullScreen", {
  65705. get: function () {
  65706. return !!(document['fullscreenElement'] ||
  65707. document['webkitFullscreenElement'] ||
  65708. document['mozFullScreenElement'] ||
  65709. document['msFullscreenElement']);
  65710. }
  65711. });
  65712. /**
  65713. * Returns true if the screen orientation is in portrait mode.
  65714. *
  65715. * @name Phaser.ScaleManager#isPortrait
  65716. * @property {boolean} isPortrait
  65717. * @readonly
  65718. */
  65719. Object.defineProperty(Phaser.ScaleManager.prototype, "isPortrait", {
  65720. get: function () {
  65721. return this.classifyOrientation(this.screenOrientation) === 'portrait';
  65722. }
  65723. });
  65724. /**
  65725. * Returns true if the screen orientation is in landscape mode.
  65726. *
  65727. * @name Phaser.ScaleManager#isLandscape
  65728. * @property {boolean} isLandscape
  65729. * @readonly
  65730. */
  65731. Object.defineProperty(Phaser.ScaleManager.prototype, "isLandscape", {
  65732. get: function () {
  65733. return this.classifyOrientation(this.screenOrientation) === 'landscape';
  65734. }
  65735. });
  65736. /**
  65737. * Returns true if the game dimensions are portrait (height > width).
  65738. * This is especially useful to check when using the RESIZE scale mode
  65739. * but wanting to maintain game orientation on desktop browsers,
  65740. * where typically the screen orientation will always be landscape regardless of the browser viewport.
  65741. *
  65742. * @name Phaser.ScaleManager#isGamePortrait
  65743. * @property {boolean} isGamePortrait
  65744. * @readonly
  65745. */
  65746. Object.defineProperty(Phaser.ScaleManager.prototype, "isGamePortrait", {
  65747. get: function () {
  65748. return (this.height > this.width);
  65749. }
  65750. });
  65751. /**
  65752. * Returns true if the game dimensions are landscape (width > height).
  65753. * This is especially useful to check when using the RESIZE scale mode
  65754. * but wanting to maintain game orientation on desktop browsers,
  65755. * where typically the screen orientation will always be landscape regardless of the browser viewport.
  65756. *
  65757. * @name Phaser.ScaleManager#isGameLandscape
  65758. * @property {boolean} isGameLandscape
  65759. * @readonly
  65760. */
  65761. Object.defineProperty(Phaser.ScaleManager.prototype, "isGameLandscape", {
  65762. get: function () {
  65763. return (this.width > this.height);
  65764. }
  65765. });
  65766. /**
  65767. * @author Richard Davey <rich@photonstorm.com>
  65768. * @copyright 2016 Photon Storm Ltd.
  65769. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  65770. */
  65771. /**
  65772. * A collection of methods for displaying debug information about game objects.
  65773. *
  65774. * If your game is running in Canvas mode, then you should invoke all of the Debug methods from
  65775. * your games `render` function. This is because they are drawn directly onto the game canvas
  65776. * itself, so if you call any debug methods outside of `render` they are likely to be overwritten
  65777. * by the game itself.
  65778. *
  65779. * If your game is running in WebGL then Debug will create a Sprite that is placed at the top of the Stage display list and bind a canvas texture
  65780. * to it, which must be uploaded every frame. Be advised: this is very expensive, especially in browsers like Firefox. So please only enable Debug
  65781. * in WebGL mode if you really need it (or your desktop can cope with it well) and disable it for production!
  65782. *
  65783. * @class Phaser.Utils.Debug
  65784. * @constructor
  65785. * @param {Phaser.Game} game - A reference to the currently running game.
  65786. */
  65787. Phaser.Utils.Debug = function (game) {
  65788. /**
  65789. * @property {Phaser.Game} game - A reference to the currently running Game.
  65790. */
  65791. this.game = game;
  65792. /**
  65793. * @property {Phaser.Image} sprite - If debugging in WebGL mode we need this.
  65794. */
  65795. this.sprite = null;
  65796. /**
  65797. * @property {Phaser.BitmapData} bmd - In WebGL mode this BitmapData contains a copy of the debug canvas.
  65798. */
  65799. this.bmd = null;
  65800. /**
  65801. * @property {HTMLCanvasElement} canvas - The canvas to which Debug calls draws.
  65802. */
  65803. this.canvas = null;
  65804. /**
  65805. * @property {CanvasRenderingContext2D} context - The 2d context of the canvas.
  65806. */
  65807. this.context = null;
  65808. /**
  65809. * @property {string} font - The font that the debug information is rendered in.
  65810. * @default '14px Courier'
  65811. */
  65812. this.font = '14px Courier';
  65813. /**
  65814. * @property {number} columnWidth - The spacing between columns.
  65815. */
  65816. this.columnWidth = 100;
  65817. /**
  65818. * @property {number} lineHeight - The line height between the debug text.
  65819. */
  65820. this.lineHeight = 16;
  65821. /**
  65822. * @property {boolean} renderShadow - Should the text be rendered with a slight shadow? Makes it easier to read on different types of background.
  65823. */
  65824. this.renderShadow = true;
  65825. /**
  65826. * @property {number} currentX - The current X position the debug information will be rendered at.
  65827. * @default
  65828. */
  65829. this.currentX = 0;
  65830. /**
  65831. * @property {number} currentY - The current Y position the debug information will be rendered at.
  65832. * @default
  65833. */
  65834. this.currentY = 0;
  65835. /**
  65836. * @property {number} currentAlpha - The alpha of the Debug context, set before all debug information is rendered to it.
  65837. * @default
  65838. */
  65839. this.currentAlpha = 1;
  65840. /**
  65841. * @property {boolean} dirty - Does the canvas need re-rendering?
  65842. */
  65843. this.dirty = false;
  65844. };
  65845. Phaser.Utils.Debug.prototype = {
  65846. /**
  65847. * Internal method that boots the debug displayer.
  65848. *
  65849. * @method Phaser.Utils.Debug#boot
  65850. * @protected
  65851. */
  65852. boot: function () {
  65853. if (this.game.renderType === Phaser.CANVAS)
  65854. {
  65855. this.context = this.game.context;
  65856. }
  65857. else
  65858. {
  65859. this.bmd = new Phaser.BitmapData(this.game, '__DEBUG', this.game.width, this.game.height, true);
  65860. this.sprite = this.game.make.image(0, 0, this.bmd);
  65861. this.game.stage.addChild(this.sprite);
  65862. this.game.scale.onSizeChange.add(this.resize, this);
  65863. this.canvas = PIXI.CanvasPool.create(this, this.game.width, this.game.height);
  65864. this.context = this.canvas.getContext('2d');
  65865. }
  65866. },
  65867. /**
  65868. * Internal method that resizes the BitmapData and Canvas.
  65869. * Called by ScaleManager.onSizeChange only in WebGL mode.
  65870. *
  65871. * @method Phaser.Utils.Debug#resize
  65872. * @protected
  65873. * @param {Phaser.ScaleManager} scaleManager - The Phaser ScaleManager.
  65874. * @param {number} width - The new width of the game.
  65875. * @param {number} height - The new height of the game.
  65876. */
  65877. resize: function (scaleManager, width, height) {
  65878. this.bmd.resize(width, height);
  65879. this.canvas.width = width;
  65880. this.canvas.height = height;
  65881. },
  65882. /**
  65883. * Internal method that clears the canvas (if a Sprite) ready for a new debug session.
  65884. *
  65885. * @method Phaser.Utils.Debug#preUpdate
  65886. * @protected
  65887. */
  65888. preUpdate: function () {
  65889. if (this.dirty && this.sprite)
  65890. {
  65891. this.bmd.clear();
  65892. this.bmd.draw(this.canvas, 0, 0);
  65893. this.context.clearRect(0, 0, this.game.width, this.game.height);
  65894. this.dirty = false;
  65895. }
  65896. },
  65897. /**
  65898. * Clears the Debug canvas.
  65899. *
  65900. * @method Phaser.Utils.Debug#reset
  65901. */
  65902. reset: function () {
  65903. if (this.context)
  65904. {
  65905. this.context.clearRect(0, 0, this.game.width, this.game.height);
  65906. }
  65907. if (this.sprite)
  65908. {
  65909. this.bmd.clear();
  65910. }
  65911. },
  65912. /**
  65913. * Internal method that resets and starts the debug output values.
  65914. *
  65915. * @method Phaser.Utils.Debug#start
  65916. * @protected
  65917. * @param {number} [x=0] - The X value the debug info will start from.
  65918. * @param {number} [y=0] - The Y value the debug info will start from.
  65919. * @param {string} [color='rgb(255,255,255)'] - The color the debug text will drawn in.
  65920. * @param {number} [columnWidth=0] - The spacing between columns.
  65921. */
  65922. start: function (x, y, color, columnWidth) {
  65923. if (typeof x !== 'number') { x = 0; }
  65924. if (typeof y !== 'number') { y = 0; }
  65925. color = color || 'rgb(255,255,255)';
  65926. if (columnWidth === undefined) { columnWidth = 0; }
  65927. this.currentX = x;
  65928. this.currentY = y;
  65929. this.currentColor = color;
  65930. this.columnWidth = columnWidth;
  65931. this.dirty = true;
  65932. this.context.save();
  65933. this.context.setTransform(1, 0, 0, 1, 0, 0);
  65934. this.context.strokeStyle = color;
  65935. this.context.fillStyle = color;
  65936. this.context.font = this.font;
  65937. this.context.globalAlpha = this.currentAlpha;
  65938. },
  65939. /**
  65940. * Internal method that stops the debug output.
  65941. *
  65942. * @method Phaser.Utils.Debug#stop
  65943. * @protected
  65944. */
  65945. stop: function () {
  65946. this.context.restore();
  65947. },
  65948. /**
  65949. * Internal method that outputs a single line of text split over as many columns as needed, one per parameter.
  65950. *
  65951. * @method Phaser.Utils.Debug#line
  65952. * @protected
  65953. */
  65954. line: function () {
  65955. var x = this.currentX;
  65956. for (var i = 0; i < arguments.length; i++)
  65957. {
  65958. if (this.renderShadow)
  65959. {
  65960. this.context.fillStyle = 'rgb(0,0,0)';
  65961. this.context.fillText(arguments[i], x + 1, this.currentY + 1);
  65962. this.context.fillStyle = this.currentColor;
  65963. }
  65964. this.context.fillText(arguments[i], x, this.currentY);
  65965. x += this.columnWidth;
  65966. }
  65967. this.currentY += this.lineHeight;
  65968. },
  65969. /**
  65970. * Render Sound information, including decoded state, duration, volume and more.
  65971. *
  65972. * @method Phaser.Utils.Debug#soundInfo
  65973. * @param {Phaser.Sound} sound - The sound object to debug.
  65974. * @param {number} x - X position of the debug info to be rendered.
  65975. * @param {number} y - Y position of the debug info to be rendered.
  65976. * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string).
  65977. */
  65978. soundInfo: function (sound, x, y, color) {
  65979. this.start(x, y, color);
  65980. this.line('Sound: ' + sound.key + ' Locked: ' + sound.game.sound.touchLocked);
  65981. this.line('Is Ready?: ' + this.game.cache.isSoundReady(sound.key) + ' Pending Playback: ' + sound.pendingPlayback);
  65982. this.line('Decoded: ' + sound.isDecoded + ' Decoding: ' + sound.isDecoding);
  65983. this.line('Total Duration: ' + sound.totalDuration + ' Playing: ' + sound.isPlaying);
  65984. this.line('Time: ' + sound.currentTime);
  65985. this.line('Volume: ' + sound.volume + ' Muted: ' + sound.mute);
  65986. this.line('WebAudio: ' + sound.usingWebAudio + ' Audio: ' + sound.usingAudioTag);
  65987. if (sound.currentMarker !== '')
  65988. {
  65989. this.line('Marker: ' + sound.currentMarker + ' Duration: ' + sound.duration + ' (ms: ' + sound.durationMS + ')');
  65990. this.line('Start: ' + sound.markers[sound.currentMarker].start + ' Stop: ' + sound.markers[sound.currentMarker].stop);
  65991. this.line('Position: ' + sound.position);
  65992. }
  65993. this.stop();
  65994. },
  65995. /**
  65996. * Render camera information including dimensions and location.
  65997. *
  65998. * @method Phaser.Utils.Debug#cameraInfo
  65999. * @param {Phaser.Camera} camera - The Phaser.Camera to show the debug information for.
  66000. * @param {number} x - X position of the debug info to be rendered.
  66001. * @param {number} y - Y position of the debug info to be rendered.
  66002. * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string).
  66003. */
  66004. cameraInfo: function (camera, x, y, color) {
  66005. this.start(x, y, color);
  66006. this.line('Camera (' + camera.width + ' x ' + camera.height + ')');
  66007. this.line('X: ' + camera.x + ' Y: ' + camera.y);
  66008. if (camera.bounds)
  66009. {
  66010. this.line('Bounds x: ' + camera.bounds.x + ' Y: ' + camera.bounds.y + ' w: ' + camera.bounds.width + ' h: ' + camera.bounds.height);
  66011. }
  66012. this.line('View x: ' + camera.view.x + ' Y: ' + camera.view.y + ' w: ' + camera.view.width + ' h: ' + camera.view.height);
  66013. // this.line('Screen View x: ' + camera.screenView.x + ' Y: ' + camera.screenView.y + ' w: ' + camera.screenView.width + ' h: ' + camera.screenView.height);
  66014. this.line('Total in view: ' + camera.totalInView);
  66015. this.stop();
  66016. },
  66017. /**
  66018. * Render Timer information.
  66019. *
  66020. * @method Phaser.Utils.Debug#timer
  66021. * @param {Phaser.Timer} timer - The Phaser.Timer to show the debug information for.
  66022. * @param {number} x - X position of the debug info to be rendered.
  66023. * @param {number} y - Y position of the debug info to be rendered.
  66024. * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string).
  66025. */
  66026. timer: function (timer, x, y, color) {
  66027. this.start(x, y, color);
  66028. this.line('Timer (running: ' + timer.running + ' expired: ' + timer.expired + ')');
  66029. this.line('Next Tick: ' + timer.next + ' Duration: ' + timer.duration);
  66030. this.line('Paused: ' + timer.paused + ' Length: ' + timer.length);
  66031. this.stop();
  66032. },
  66033. /**
  66034. * Renders the Pointer.circle object onto the stage in green if down or red if up along with debug text.
  66035. *
  66036. * @method Phaser.Utils.Debug#pointer
  66037. * @param {Phaser.Pointer} pointer - The Pointer you wish to display.
  66038. * @param {boolean} [hideIfUp=false] - Doesn't render the circle if the pointer is up.
  66039. * @param {string} [downColor='rgba(0,255,0,0.5)'] - The color the circle is rendered in if down.
  66040. * @param {string} [upColor='rgba(255,0,0,0.5)'] - The color the circle is rendered in if up (and hideIfUp is false).
  66041. * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string).
  66042. */
  66043. pointer: function (pointer, hideIfUp, downColor, upColor, color) {
  66044. if (pointer == null)
  66045. {
  66046. return;
  66047. }
  66048. if (hideIfUp === undefined) { hideIfUp = false; }
  66049. downColor = downColor || 'rgba(0,255,0,0.5)';
  66050. upColor = upColor || 'rgba(255,0,0,0.5)';
  66051. if (hideIfUp === true && pointer.isUp === true)
  66052. {
  66053. return;
  66054. }
  66055. this.start(pointer.x, pointer.y - 100, color);
  66056. this.context.beginPath();
  66057. this.context.arc(pointer.x, pointer.y, pointer.circle.radius, 0, Math.PI * 2);
  66058. if (pointer.active)
  66059. {
  66060. this.context.fillStyle = downColor;
  66061. }
  66062. else
  66063. {
  66064. this.context.fillStyle = upColor;
  66065. }
  66066. this.context.fill();
  66067. this.context.closePath();
  66068. // Render the points
  66069. this.context.beginPath();
  66070. this.context.moveTo(pointer.positionDown.x, pointer.positionDown.y);
  66071. this.context.lineTo(pointer.position.x, pointer.position.y);
  66072. this.context.lineWidth = 2;
  66073. this.context.stroke();
  66074. this.context.closePath();
  66075. // Render the text
  66076. this.line('ID: ' + pointer.id + " Active: " + pointer.active);
  66077. this.line('World X: ' + pointer.worldX + " World Y: " + pointer.worldY);
  66078. this.line('Screen X: ' + pointer.x + " Screen Y: " + pointer.y + " In: " + pointer.withinGame);
  66079. this.line('Duration: ' + pointer.duration + " ms");
  66080. this.line('is Down: ' + pointer.isDown + " is Up: " + pointer.isUp);
  66081. this.stop();
  66082. },
  66083. /**
  66084. * Render Sprite Input Debug information.
  66085. *
  66086. * @method Phaser.Utils.Debug#spriteInputInfo
  66087. * @param {Phaser.Sprite|Phaser.Image} sprite - The sprite to display the input data for.
  66088. * @param {number} x - X position of the debug info to be rendered.
  66089. * @param {number} y - Y position of the debug info to be rendered.
  66090. * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string).
  66091. */
  66092. spriteInputInfo: function (sprite, x, y, color) {
  66093. this.start(x, y, color);
  66094. this.line('Sprite Input: (' + sprite.width + ' x ' + sprite.height + ')');
  66095. this.line('x: ' + sprite.input.pointerX().toFixed(1) + ' y: ' + sprite.input.pointerY().toFixed(1));
  66096. this.line('over: ' + sprite.input.pointerOver() + ' duration: ' + sprite.input.overDuration().toFixed(0));
  66097. this.line('down: ' + sprite.input.pointerDown() + ' duration: ' + sprite.input.downDuration().toFixed(0));
  66098. this.line('just over: ' + sprite.input.justOver() + ' just out: ' + sprite.input.justOut());
  66099. this.stop();
  66100. },
  66101. /**
  66102. * Renders Phaser.Key object information.
  66103. *
  66104. * @method Phaser.Utils.Debug#key
  66105. * @param {Phaser.Key} key - The Key to render the information for.
  66106. * @param {number} x - X position of the debug info to be rendered.
  66107. * @param {number} y - Y position of the debug info to be rendered.
  66108. * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string).
  66109. */
  66110. key: function (key, x, y, color) {
  66111. this.start(x, y, color, 150);
  66112. this.line('Key:', key.keyCode, 'isDown:', key.isDown);
  66113. this.line('justDown:', key.justDown, 'justUp:', key.justUp);
  66114. this.line('Time Down:', key.timeDown.toFixed(0), 'duration:', key.duration.toFixed(0));
  66115. this.stop();
  66116. },
  66117. /**
  66118. * Render debug information about the Input object.
  66119. *
  66120. * @method Phaser.Utils.Debug#inputInfo
  66121. * @param {number} x - X position of the debug info to be rendered.
  66122. * @param {number} y - Y position of the debug info to be rendered.
  66123. * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string).
  66124. */
  66125. inputInfo: function (x, y, color) {
  66126. this.start(x, y, color);
  66127. this.line('Input');
  66128. this.line('X: ' + this.game.input.x + ' Y: ' + this.game.input.y);
  66129. this.line('World X: ' + this.game.input.worldX + ' World Y: ' + this.game.input.worldY);
  66130. this.line('Scale X: ' + this.game.input.scale.x.toFixed(1) + ' Scale Y: ' + this.game.input.scale.x.toFixed(1));
  66131. this.line('Screen X: ' + this.game.input.activePointer.screenX + ' Screen Y: ' + this.game.input.activePointer.screenY);
  66132. this.stop();
  66133. },
  66134. /**
  66135. * Renders the Sprites bounds. Note: This is really expensive as it has to calculate the bounds every time you call it!
  66136. *
  66137. * @method Phaser.Utils.Debug#spriteBounds
  66138. * @param {Phaser.Sprite|Phaser.Image} sprite - The sprite to display the bounds of.
  66139. * @param {string} [color] - Color of the debug info to be rendered (format is css color string).
  66140. * @param {boolean} [filled=true] - Render the rectangle as a fillRect (default, true) or a strokeRect (false)
  66141. */
  66142. spriteBounds: function (sprite, color, filled) {
  66143. var bounds = sprite.getBounds();
  66144. bounds.x += this.game.camera.x;
  66145. bounds.y += this.game.camera.y;
  66146. this.rectangle(bounds, color, filled);
  66147. },
  66148. /**
  66149. * Renders the Rope's segments. Note: This is really expensive as it has to calculate new segments every time you call it
  66150. *
  66151. * @method Phaser.Utils.Debug#ropeSegments
  66152. * @param {Phaser.Rope} rope - The rope to display the segments of.
  66153. * @param {string} [color] - Color of the debug info to be rendered (format is css color string).
  66154. * @param {boolean} [filled=true] - Render the rectangle as a fillRect (default, true) or a strokeRect (false)
  66155. */
  66156. ropeSegments: function (rope, color, filled) {
  66157. var segments = rope.segments;
  66158. var self = this;
  66159. segments.forEach(function(segment) {
  66160. self.rectangle(segment, color, filled);
  66161. }, this);
  66162. },
  66163. /**
  66164. * Render debug infos (including name, bounds info, position and some other properties) about the Sprite.
  66165. *
  66166. * @method Phaser.Utils.Debug#spriteInfo
  66167. * @param {Phaser.Sprite} sprite - The Sprite to display the information of.
  66168. * @param {number} x - X position of the debug info to be rendered.
  66169. * @param {number} y - Y position of the debug info to be rendered.
  66170. * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string).
  66171. */
  66172. spriteInfo: function (sprite, x, y, color) {
  66173. this.start(x, y, color);
  66174. this.line('Sprite: ' + ' (' + sprite.width + ' x ' + sprite.height + ') anchor: ' + sprite.anchor.x + ' x ' + sprite.anchor.y);
  66175. this.line('x: ' + sprite.x.toFixed(1) + ' y: ' + sprite.y.toFixed(1));
  66176. this.line('angle: ' + sprite.angle.toFixed(1) + ' rotation: ' + sprite.rotation.toFixed(1));
  66177. this.line('visible: ' + sprite.visible + ' in camera: ' + sprite.inCamera);
  66178. this.line('bounds x: ' + sprite._bounds.x.toFixed(1) + ' y: ' + sprite._bounds.y.toFixed(1) + ' w: ' + sprite._bounds.width.toFixed(1) + ' h: ' + sprite._bounds.height.toFixed(1));
  66179. this.stop();
  66180. },
  66181. /**
  66182. * Renders the sprite coordinates in local, positional and world space.
  66183. *
  66184. * @method Phaser.Utils.Debug#spriteCoords
  66185. * @param {Phaser.Sprite|Phaser.Image} sprite - The sprite to display the coordinates for.
  66186. * @param {number} x - X position of the debug info to be rendered.
  66187. * @param {number} y - Y position of the debug info to be rendered.
  66188. * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string).
  66189. */
  66190. spriteCoords: function (sprite, x, y, color) {
  66191. this.start(x, y, color, 100);
  66192. if (sprite.name)
  66193. {
  66194. this.line(sprite.name);
  66195. }
  66196. this.line('x:', sprite.x.toFixed(2), 'y:', sprite.y.toFixed(2));
  66197. this.line('pos x:', sprite.position.x.toFixed(2), 'pos y:', sprite.position.y.toFixed(2));
  66198. this.line('world x:', sprite.world.x.toFixed(2), 'world y:', sprite.world.y.toFixed(2));
  66199. this.stop();
  66200. },
  66201. /**
  66202. * Renders Line information in the given color.
  66203. *
  66204. * @method Phaser.Utils.Debug#lineInfo
  66205. * @param {Phaser.Line} line - The Line to display the data for.
  66206. * @param {number} x - X position of the debug info to be rendered.
  66207. * @param {number} y - Y position of the debug info to be rendered.
  66208. * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string).
  66209. */
  66210. lineInfo: function (line, x, y, color) {
  66211. this.start(x, y, color, 80);
  66212. this.line('start.x:', line.start.x.toFixed(2), 'start.y:', line.start.y.toFixed(2));
  66213. this.line('end.x:', line.end.x.toFixed(2), 'end.y:', line.end.y.toFixed(2));
  66214. this.line('length:', line.length.toFixed(2), 'angle:', line.angle);
  66215. this.stop();
  66216. },
  66217. /**
  66218. * Renders a single pixel at the given size.
  66219. *
  66220. * @method Phaser.Utils.Debug#pixel
  66221. * @param {number} x - X position of the pixel to be rendered.
  66222. * @param {number} y - Y position of the pixel to be rendered.
  66223. * @param {string} [color] - Color of the pixel (format is css color string).
  66224. * @param {number} [size=2] - The 'size' to render the pixel at.
  66225. */
  66226. pixel: function (x, y, color, size) {
  66227. size = size || 2;
  66228. this.start();
  66229. this.context.fillStyle = color;
  66230. this.context.fillRect(x, y, size, size);
  66231. this.stop();
  66232. },
  66233. /**
  66234. * Renders a Phaser geometry object including Rectangle, Circle, Point or Line.
  66235. *
  66236. * @method Phaser.Utils.Debug#geom
  66237. * @param {Phaser.Rectangle|Phaser.Circle|Phaser.Point|Phaser.Line} object - The geometry object to render.
  66238. * @param {string} [color] - Color of the debug info to be rendered (format is css color string).
  66239. * @param {boolean} [filled=true] - Render the objected as a filled (default, true) or a stroked (false)
  66240. * @param {number} [forceType=0] - Force rendering of a specific type. If 0 no type will be forced, otherwise 1 = Rectangle, 2 = Circle, 3 = Point and 4 = Line.
  66241. */
  66242. geom: function (object, color, filled, forceType) {
  66243. if (filled === undefined) { filled = true; }
  66244. if (forceType === undefined) { forceType = 0; }
  66245. color = color || 'rgba(0,255,0,0.4)';
  66246. this.start();
  66247. this.context.fillStyle = color;
  66248. this.context.strokeStyle = color;
  66249. if (object instanceof Phaser.Rectangle || forceType === 1)
  66250. {
  66251. if (filled)
  66252. {
  66253. this.context.fillRect(object.x - this.game.camera.x, object.y - this.game.camera.y, object.width, object.height);
  66254. }
  66255. else
  66256. {
  66257. this.context.strokeRect(object.x - this.game.camera.x, object.y - this.game.camera.y, object.width, object.height);
  66258. }
  66259. }
  66260. else if (object instanceof Phaser.Circle || forceType === 2)
  66261. {
  66262. this.context.beginPath();
  66263. this.context.arc(object.x - this.game.camera.x, object.y - this.game.camera.y, object.radius, 0, Math.PI * 2, false);
  66264. this.context.closePath();
  66265. if (filled)
  66266. {
  66267. this.context.fill();
  66268. }
  66269. else
  66270. {
  66271. this.context.stroke();
  66272. }
  66273. }
  66274. else if (object instanceof Phaser.Point || forceType === 3)
  66275. {
  66276. this.context.fillRect(object.x - this.game.camera.x, object.y - this.game.camera.y, 4, 4);
  66277. }
  66278. else if (object instanceof Phaser.Line || forceType === 4)
  66279. {
  66280. this.context.lineWidth = 1;
  66281. this.context.beginPath();
  66282. this.context.moveTo((object.start.x + 0.5) - this.game.camera.x, (object.start.y + 0.5) - this.game.camera.y);
  66283. this.context.lineTo((object.end.x + 0.5) - this.game.camera.x, (object.end.y + 0.5) - this.game.camera.y);
  66284. this.context.closePath();
  66285. this.context.stroke();
  66286. }
  66287. this.stop();
  66288. },
  66289. /**
  66290. * Renders a Rectangle.
  66291. *
  66292. * @method Phaser.Utils.Debug#geom
  66293. * @param {Phaser.Rectangle|object} object - The geometry object to render.
  66294. * @param {string} [color] - Color of the debug info to be rendered (format is css color string).
  66295. * @param {boolean} [filled=true] - Render the objected as a filled (default, true) or a stroked (false)
  66296. */
  66297. rectangle: function (object, color, filled) {
  66298. if (filled === undefined) { filled = true; }
  66299. color = color || 'rgba(0, 255, 0, 0.4)';
  66300. this.start();
  66301. if (filled)
  66302. {
  66303. this.context.fillStyle = color;
  66304. this.context.fillRect(object.x - this.game.camera.x, object.y - this.game.camera.y, object.width, object.height);
  66305. }
  66306. else
  66307. {
  66308. this.context.strokeStyle = color;
  66309. this.context.strokeRect(object.x - this.game.camera.x, object.y - this.game.camera.y, object.width, object.height);
  66310. }
  66311. this.stop();
  66312. },
  66313. /**
  66314. * Render a string of text.
  66315. *
  66316. * @method Phaser.Utils.Debug#text
  66317. * @param {string} text - The line of text to draw.
  66318. * @param {number} x - X position of the debug info to be rendered.
  66319. * @param {number} y - Y position of the debug info to be rendered.
  66320. * @param {string} [color] - Color of the debug info to be rendered (format is css color string).
  66321. * @param {string} [font] - The font of text to draw.
  66322. */
  66323. text: function (text, x, y, color, font) {
  66324. color = color || 'rgb(255,255,255)';
  66325. font = font || '16px Courier';
  66326. this.start();
  66327. this.context.font = font;
  66328. if (this.renderShadow)
  66329. {
  66330. this.context.fillStyle = 'rgb(0,0,0)';
  66331. this.context.fillText(text, x + 1, y + 1);
  66332. }
  66333. this.context.fillStyle = color;
  66334. this.context.fillText(text, x, y);
  66335. this.stop();
  66336. },
  66337. /**
  66338. * Visually renders a QuadTree to the display.
  66339. *
  66340. * @method Phaser.Utils.Debug#quadTree
  66341. * @param {Phaser.QuadTree} quadtree - The quadtree to render.
  66342. * @param {string} color - The color of the lines in the quadtree.
  66343. */
  66344. quadTree: function (quadtree, color) {
  66345. color = color || 'rgba(255,0,0,0.3)';
  66346. this.start();
  66347. var bounds = quadtree.bounds;
  66348. if (quadtree.nodes.length === 0)
  66349. {
  66350. this.context.strokeStyle = color;
  66351. this.context.strokeRect(bounds.x, bounds.y, bounds.width, bounds.height);
  66352. this.text('size: ' + quadtree.objects.length, bounds.x + 4, bounds.y + 16, 'rgb(0,200,0)', '12px Courier');
  66353. this.context.strokeStyle = 'rgb(0,255,0)';
  66354. for (var i = 0; i < quadtree.objects.length; i++)
  66355. {
  66356. this.context.strokeRect(quadtree.objects[i].x, quadtree.objects[i].y, quadtree.objects[i].width, quadtree.objects[i].height);
  66357. }
  66358. }
  66359. else
  66360. {
  66361. for (var i = 0; i < quadtree.nodes.length; i++)
  66362. {
  66363. this.quadTree(quadtree.nodes[i]);
  66364. }
  66365. }
  66366. this.stop();
  66367. },
  66368. /**
  66369. * Render a Sprites Physics body if it has one set. The body is rendered as a filled or stroked rectangle.
  66370. * This only works for Arcade Physics, Ninja Physics (AABB and Circle only) and Box2D Physics bodies.
  66371. * To display a P2 Physics body you should enable debug mode on the body when creating it.
  66372. *
  66373. * @method Phaser.Utils.Debug#body
  66374. * @param {Phaser.Sprite} sprite - The Sprite who's body will be rendered.
  66375. * @param {string} [color='rgba(0,255,0,0.4)'] - Color of the debug rectangle to be rendered. The format is a CSS color string such as '#ff0000' or 'rgba(255,0,0,0.5)'.
  66376. * @param {boolean} [filled=true] - Render the body as a filled rectangle (true) or a stroked rectangle (false)
  66377. */
  66378. body: function (sprite, color, filled) {
  66379. if (sprite.body)
  66380. {
  66381. this.start();
  66382. if (sprite.body.type === Phaser.Physics.ARCADE)
  66383. {
  66384. Phaser.Physics.Arcade.Body.render(this.context, sprite.body, color, filled);
  66385. }
  66386. else if (sprite.body.type === Phaser.Physics.NINJA)
  66387. {
  66388. Phaser.Physics.Ninja.Body.render(this.context, sprite.body, color, filled);
  66389. }
  66390. else if (sprite.body.type === Phaser.Physics.BOX2D)
  66391. {
  66392. Phaser.Physics.Box2D.renderBody(this.context, sprite.body, color);
  66393. }
  66394. this.stop();
  66395. }
  66396. },
  66397. /**
  66398. * Render a Sprites Physic Body information.
  66399. *
  66400. * @method Phaser.Utils.Debug#bodyInfo
  66401. * @param {Phaser.Sprite} sprite - The sprite to be rendered.
  66402. * @param {number} x - X position of the debug info to be rendered.
  66403. * @param {number} y - Y position of the debug info to be rendered.
  66404. * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string).
  66405. */
  66406. bodyInfo: function (sprite, x, y, color) {
  66407. if (sprite.body)
  66408. {
  66409. this.start(x, y, color, 210);
  66410. if (sprite.body.type === Phaser.Physics.ARCADE)
  66411. {
  66412. Phaser.Physics.Arcade.Body.renderBodyInfo(this, sprite.body);
  66413. }
  66414. else if (sprite.body.type === Phaser.Physics.BOX2D)
  66415. {
  66416. this.game.physics.box2d.renderBodyInfo(this, sprite.body);
  66417. }
  66418. this.stop();
  66419. }
  66420. },
  66421. /**
  66422. * Renders 'debug draw' data for the Box2D world if it exists.
  66423. * This uses the standard debug drawing feature of Box2D, so colors will be decided by
  66424. * the Box2D engine.
  66425. *
  66426. * @method Phaser.Utils.Debug#box2dWorld
  66427. */
  66428. box2dWorld: function () {
  66429. this.start();
  66430. this.context.translate(-this.game.camera.view.x, -this.game.camera.view.y, 0);
  66431. this.game.physics.box2d.renderDebugDraw(this.context);
  66432. this.stop();
  66433. },
  66434. /**
  66435. * Renders 'debug draw' data for the given Box2D body.
  66436. * This uses the standard debug drawing feature of Box2D, so colors will be decided by the Box2D engine.
  66437. *
  66438. * @method Phaser.Utils.Debug#box2dBody
  66439. * @param {Phaser.Sprite} sprite - The sprite whos body will be rendered.
  66440. * @param {string} [color='rgb(0,255,0)'] - color of the debug info to be rendered. (format is css color string).
  66441. */
  66442. box2dBody: function (body, color) {
  66443. this.start();
  66444. Phaser.Physics.Box2D.renderBody(this.context, body, color);
  66445. this.stop();
  66446. },
  66447. /**
  66448. * Call this function from the Dev Tools console.
  66449. *
  66450. * It will scan the display list and output all of the Objects it finds, and their renderOrderIDs.
  66451. *
  66452. * **Note** Requires a browser that supports console.group and console.groupEnd (such as Chrome)
  66453. *
  66454. * @method displayList
  66455. * @param {Object} [displayObject] - The displayObject level display object to start from. Defaults to the World.
  66456. */
  66457. displayList: function (displayObject) {
  66458. if (displayObject === undefined) { displayObject = this.game.world; }
  66459. if (displayObject.hasOwnProperty('renderOrderID'))
  66460. {
  66461. console.log('[' + displayObject.renderOrderID + ']', displayObject);
  66462. }
  66463. else
  66464. {
  66465. console.log('[]', displayObject);
  66466. }
  66467. if (displayObject.children && displayObject.children.length > 0)
  66468. {
  66469. for (var i = 0; i < displayObject.children.length; i++)
  66470. {
  66471. this.game.debug.displayList(displayObject.children[i]);
  66472. }
  66473. }
  66474. },
  66475. /**
  66476. * Destroy this object.
  66477. *
  66478. * @method Phaser.Utils.Debug#destroy
  66479. */
  66480. destroy: function () {
  66481. PIXI.CanvasPool.remove(this);
  66482. }
  66483. };
  66484. Phaser.Utils.Debug.prototype.constructor = Phaser.Utils.Debug;
  66485. /**
  66486. * @author Richard Davey <rich@photonstorm.com>
  66487. * @copyright 2016 Photon Storm Ltd.
  66488. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  66489. */
  66490. /**
  66491. * DOM utility class.
  66492. *
  66493. * Provides a useful Window and Element functions as well as cross-browser compatibility buffer.
  66494. *
  66495. * Some code originally derived from {@link https://github.com/ryanve/verge verge}.
  66496. * Some parts were inspired by the research of Ryan Van Etten, released under MIT License 2013.
  66497. *
  66498. * @class Phaser.DOM
  66499. * @static
  66500. */
  66501. Phaser.DOM = {
  66502. /**
  66503. * Get the [absolute] position of the element relative to the Document.
  66504. *
  66505. * The value may vary slightly as the page is scrolled due to rounding errors.
  66506. *
  66507. * @method Phaser.DOM.getOffset
  66508. * @param {DOMElement} element - The targeted element that we want to retrieve the offset.
  66509. * @param {Phaser.Point} [point] - The point we want to take the x/y values of the offset.
  66510. * @return {Phaser.Point} - A point objet with the offsetX and Y as its properties.
  66511. */
  66512. getOffset: function (element, point) {
  66513. point = point || new Phaser.Point();
  66514. var box = element.getBoundingClientRect();
  66515. var scrollTop = Phaser.DOM.scrollY;
  66516. var scrollLeft = Phaser.DOM.scrollX;
  66517. var clientTop = document.documentElement.clientTop;
  66518. var clientLeft = document.documentElement.clientLeft;
  66519. point.x = box.left + scrollLeft - clientLeft;
  66520. point.y = box.top + scrollTop - clientTop;
  66521. return point;
  66522. },
  66523. /**
  66524. * A cross-browser element.getBoundingClientRect method with optional cushion.
  66525. *
  66526. * Returns a plain object containing the properties `top/bottom/left/right/width/height` with respect to the top-left corner of the current viewport.
  66527. * Its properties match the native rectangle.
  66528. * The cushion parameter is an amount of pixels (+/-) to cushion the element.
  66529. * It adjusts the measurements such that it is possible to detect when an element is near the viewport.
  66530. *
  66531. * @method Phaser.DOM.getBounds
  66532. * @param {DOMElement|Object} element - The element or stack (uses first item) to get the bounds for.
  66533. * @param {number} [cushion] - A +/- pixel adjustment amount.
  66534. * @return {Object|boolean} A plain object containing the properties `top/bottom/left/right/width/height` or `false` if a non-valid element is given.
  66535. */
  66536. getBounds: function (element, cushion) {
  66537. if (cushion === undefined) { cushion = 0; }
  66538. element = element && !element.nodeType ? element[0] : element;
  66539. if (!element || element.nodeType !== 1)
  66540. {
  66541. return false;
  66542. }
  66543. else
  66544. {
  66545. return this.calibrate(element.getBoundingClientRect(), cushion);
  66546. }
  66547. },
  66548. /**
  66549. * Calibrates element coordinates for `inLayoutViewport` checks.
  66550. *
  66551. * @method Phaser.DOM.calibrate
  66552. * @private
  66553. * @param {object} coords - An object containing the following properties: `{top: number, right: number, bottom: number, left: number}`
  66554. * @param {number} [cushion] - A value to adjust the coordinates by.
  66555. * @return {object} The calibrated element coordinates
  66556. */
  66557. calibrate: function (coords, cushion) {
  66558. cushion = +cushion || 0;
  66559. var output = { width: 0, height: 0, left: 0, right: 0, top: 0, bottom: 0 };
  66560. output.width = (output.right = coords.right + cushion) - (output.left = coords.left - cushion);
  66561. output.height = (output.bottom = coords.bottom + cushion) - (output.top = coords.top - cushion);
  66562. return output;
  66563. },
  66564. /**
  66565. * Get the Visual viewport aspect ratio (or the aspect ratio of an object or element)
  66566. *
  66567. * @method Phaser.DOM.getAspectRatio
  66568. * @param {(DOMElement|Object)} [object=(visualViewport)] - The object to determine the aspect ratio for. Must have public `width` and `height` properties or methods.
  66569. * @return {number} The aspect ratio.
  66570. */
  66571. getAspectRatio: function (object) {
  66572. object = null == object ? this.visualBounds : 1 === object.nodeType ? this.getBounds(object) : object;
  66573. var w = object['width'];
  66574. var h = object['height'];
  66575. if (typeof w === 'function')
  66576. {
  66577. w = w.call(object);
  66578. }
  66579. if (typeof h === 'function')
  66580. {
  66581. h = h.call(object);
  66582. }
  66583. return w / h;
  66584. },
  66585. /**
  66586. * Tests if the given DOM element is within the Layout viewport.
  66587. *
  66588. * The optional cushion parameter allows you to specify a distance.
  66589. *
  66590. * inLayoutViewport(element, 100) is `true` if the element is in the viewport or 100px near it.
  66591. * inLayoutViewport(element, -100) is `true` if the element is in the viewport or at least 100px near it.
  66592. *
  66593. * @method Phaser.DOM.inLayoutViewport
  66594. * @param {DOMElement|Object} element - The DOM element to check. If no element is given it defaults to the Phaser game canvas.
  66595. * @param {number} [cushion] - The cushion allows you to specify a distance within which the element must be within the viewport.
  66596. * @return {boolean} True if the element is within the viewport, or within `cushion` distance from it.
  66597. */
  66598. inLayoutViewport: function (element, cushion) {
  66599. var r = this.getBounds(element, cushion);
  66600. return !!r && r.bottom >= 0 && r.right >= 0 && r.top <= this.layoutBounds.width && r.left <= this.layoutBounds.height;
  66601. },
  66602. /**
  66603. * Returns the device screen orientation.
  66604. *
  66605. * Orientation values: 'portrait-primary', 'landscape-primary', 'portrait-secondary', 'landscape-secondary'.
  66606. *
  66607. * Order of resolving:
  66608. * - Screen Orientation API, or variation of - Future track. Most desktop and mobile browsers.
  66609. * - Screen size ratio check - If fallback is 'screen', suited for desktops.
  66610. * - Viewport size ratio check - If fallback is 'viewport', suited for mobile.
  66611. * - window.orientation - If fallback is 'window.orientation', works iOS and probably most Android; non-recommended track.
  66612. * - Media query
  66613. * - Viewport size ratio check (probably only IE9 and legacy mobile gets here..)
  66614. *
  66615. * See
  66616. * - https://w3c.github.io/screen-orientation/ (conflicts with mozOrientation/msOrientation)
  66617. * - https://developer.mozilla.org/en-US/docs/Web/API/Screen.orientation (mozOrientation)
  66618. * - http://msdn.microsoft.com/en-us/library/ie/dn342934(v=vs.85).aspx
  66619. * - https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Testing_media_queries
  66620. * - http://stackoverflow.com/questions/4917664/detect-viewport-orientation
  66621. * - http://www.matthewgifford.com/blog/2011/12/22/a-misconception-about-window-orientation
  66622. *
  66623. * @method Phaser.DOM.getScreenOrientation
  66624. * @protected
  66625. * @param {string} [primaryFallback=(none)] - Specify 'screen', 'viewport', or 'window.orientation'.
  66626. */
  66627. getScreenOrientation: function (primaryFallback) {
  66628. var screen = window.screen;
  66629. var orientation = screen.orientation || screen.mozOrientation || screen.msOrientation;
  66630. if (orientation && typeof orientation.type === 'string')
  66631. {
  66632. // Screen Orientation API specification
  66633. return orientation.type;
  66634. }
  66635. else if (typeof orientation === 'string')
  66636. {
  66637. // moz/ms-orientation are strings
  66638. return orientation;
  66639. }
  66640. var PORTRAIT = 'portrait-primary';
  66641. var LANDSCAPE = 'landscape-primary';
  66642. if (primaryFallback === 'screen')
  66643. {
  66644. return (screen.height > screen.width) ? PORTRAIT : LANDSCAPE;
  66645. }
  66646. else if (primaryFallback === 'viewport')
  66647. {
  66648. return (this.visualBounds.height > this.visualBounds.width) ? PORTRAIT : LANDSCAPE;
  66649. }
  66650. else if (primaryFallback === 'window.orientation' && typeof window.orientation === 'number')
  66651. {
  66652. // This may change by device based on "natural" orientation.
  66653. return (window.orientation === 0 || window.orientation === 180) ? PORTRAIT : LANDSCAPE;
  66654. }
  66655. else if (window.matchMedia)
  66656. {
  66657. if (window.matchMedia("(orientation: portrait)").matches)
  66658. {
  66659. return PORTRAIT;
  66660. }
  66661. else if (window.matchMedia("(orientation: landscape)").matches)
  66662. {
  66663. return LANDSCAPE;
  66664. }
  66665. }
  66666. return (this.visualBounds.height > this.visualBounds.width) ? PORTRAIT : LANDSCAPE;
  66667. },
  66668. /**
  66669. * The bounds of the Visual viewport, as discussed in
  66670. * {@link http://www.quirksmode.org/mobile/viewports.html A tale of two viewports — part one}
  66671. * with one difference: the viewport size _excludes_ scrollbars, as found on some desktop browsers.
  66672. *
  66673. * Supported mobile:
  66674. * iOS/Safari, Android 4, IE10, Firefox OS (maybe not Firefox Android), Opera Mobile 16
  66675. *
  66676. * The properties change dynamically.
  66677. *
  66678. * @type {Phaser.Rectangle}
  66679. * @property {number} x - Scroll, left offset - eg. "scrollX"
  66680. * @property {number} y - Scroll, top offset - eg. "scrollY"
  66681. * @property {number} width - Viewport width in pixels.
  66682. * @property {number} height - Viewport height in pixels.
  66683. * @readonly
  66684. */
  66685. visualBounds: new Phaser.Rectangle(),
  66686. /**
  66687. * The bounds of the Layout viewport, as discussed in
  66688. * {@link http://www.quirksmode.org/mobile/viewports2.html A tale of two viewports — part two};
  66689. * but honoring the constraints as specified applicable viewport meta-tag.
  66690. *
  66691. * The bounds returned are not guaranteed to be fully aligned with CSS media queries (see
  66692. * {@link http://www.matanich.com/2013/01/07/viewport-size/ What size is my viewport?}).
  66693. *
  66694. * This is _not_ representative of the Visual bounds: in particular the non-primary axis will
  66695. * generally be significantly larger than the screen height on mobile devices when running with a
  66696. * constrained viewport.
  66697. *
  66698. * The properties change dynamically.
  66699. *
  66700. * @type {Phaser.Rectangle}
  66701. * @property {number} width - Viewport width in pixels.
  66702. * @property {number} height - Viewport height in pixels.
  66703. * @readonly
  66704. */
  66705. layoutBounds: new Phaser.Rectangle(),
  66706. /**
  66707. * The size of the document / Layout viewport.
  66708. *
  66709. * This incorrectly reports the dimensions in IE.
  66710. *
  66711. * The properties change dynamically.
  66712. *
  66713. * @type {Phaser.Rectangle}
  66714. * @property {number} width - Document width in pixels.
  66715. * @property {number} height - Document height in pixels.
  66716. * @readonly
  66717. */
  66718. documentBounds: new Phaser.Rectangle()
  66719. };
  66720. Phaser.Device.whenReady(function (device) {
  66721. // All target browsers should support page[XY]Offset.
  66722. var scrollX = window && ('pageXOffset' in window) ?
  66723. function () { return window.pageXOffset; } :
  66724. function () { return document.documentElement.scrollLeft; };
  66725. var scrollY = window && ('pageYOffset' in window) ?
  66726. function () { return window.pageYOffset; } :
  66727. function () { return document.documentElement.scrollTop; };
  66728. /**
  66729. * A cross-browser window.scrollX.
  66730. *
  66731. * @name Phaser.DOM.scrollX
  66732. * @property {number} scrollX
  66733. * @readonly
  66734. * @protected
  66735. */
  66736. Object.defineProperty(Phaser.DOM, "scrollX", {
  66737. get: scrollX
  66738. });
  66739. /**
  66740. * A cross-browser window.scrollY.
  66741. *
  66742. * @name Phaser.DOM.scrollY
  66743. * @property {number} scrollY
  66744. * @readonly
  66745. * @protected
  66746. */
  66747. Object.defineProperty(Phaser.DOM, "scrollY", {
  66748. get: scrollY
  66749. });
  66750. Object.defineProperty(Phaser.DOM.visualBounds, "x", {
  66751. get: scrollX
  66752. });
  66753. Object.defineProperty(Phaser.DOM.visualBounds, "y", {
  66754. get: scrollY
  66755. });
  66756. Object.defineProperty(Phaser.DOM.layoutBounds, "x", {
  66757. value: 0
  66758. });
  66759. Object.defineProperty(Phaser.DOM.layoutBounds, "y", {
  66760. value: 0
  66761. });
  66762. var treatAsDesktop = device.desktop &&
  66763. (document.documentElement.clientWidth <= window.innerWidth) &&
  66764. (document.documentElement.clientHeight <= window.innerHeight);
  66765. // Desktop browsers align the layout viewport with the visual viewport.
  66766. // This differs from mobile browsers with their zooming design.
  66767. // Ref. http://quirksmode.org/mobile/tableViewport.html
  66768. if (treatAsDesktop)
  66769. {
  66770. // PST- When scrollbars are not included this causes upstream issues in ScaleManager.
  66771. // So reverted to the old "include scrollbars."
  66772. var clientWidth = function () {
  66773. return Math.max(window.innerWidth, document.documentElement.clientWidth);
  66774. };
  66775. var clientHeight = function () {
  66776. return Math.max(window.innerHeight, document.documentElement.clientHeight);
  66777. };
  66778. // Interested in area sans-scrollbar
  66779. Object.defineProperty(Phaser.DOM.visualBounds, "width", {
  66780. get: clientWidth
  66781. });
  66782. Object.defineProperty(Phaser.DOM.visualBounds, "height", {
  66783. get: clientHeight
  66784. });
  66785. Object.defineProperty(Phaser.DOM.layoutBounds, "width", {
  66786. get: clientWidth
  66787. });
  66788. Object.defineProperty(Phaser.DOM.layoutBounds, "height", {
  66789. get: clientHeight
  66790. });
  66791. } else {
  66792. Object.defineProperty(Phaser.DOM.visualBounds, "width", {
  66793. get: function () {
  66794. return window.innerWidth;
  66795. }
  66796. });
  66797. Object.defineProperty(Phaser.DOM.visualBounds, "height", {
  66798. get: function () {
  66799. return window.innerHeight;
  66800. }
  66801. });
  66802. Object.defineProperty(Phaser.DOM.layoutBounds, "width", {
  66803. get: function () {
  66804. var a = document.documentElement.clientWidth;
  66805. var b = window.innerWidth;
  66806. return a < b ? b : a; // max
  66807. }
  66808. });
  66809. Object.defineProperty(Phaser.DOM.layoutBounds, "height", {
  66810. get: function () {
  66811. var a = document.documentElement.clientHeight;
  66812. var b = window.innerHeight;
  66813. return a < b ? b : a; // max
  66814. }
  66815. });
  66816. }
  66817. // For Phaser.DOM.documentBounds
  66818. // Ref. http://www.quirksmode.org/mobile/tableViewport_desktop.html
  66819. Object.defineProperty(Phaser.DOM.documentBounds, "x", {
  66820. value: 0
  66821. });
  66822. Object.defineProperty(Phaser.DOM.documentBounds, "y", {
  66823. value: 0
  66824. });
  66825. Object.defineProperty(Phaser.DOM.documentBounds, "width", {
  66826. get: function () {
  66827. var d = document.documentElement;
  66828. return Math.max(d.clientWidth, d.offsetWidth, d.scrollWidth);
  66829. }
  66830. });
  66831. Object.defineProperty(Phaser.DOM.documentBounds, "height", {
  66832. get: function () {
  66833. var d = document.documentElement;
  66834. return Math.max(d.clientHeight, d.offsetHeight, d.scrollHeight);
  66835. }
  66836. });
  66837. }, null, true);
  66838. /**
  66839. * @author Richard Davey <rich@photonstorm.com>
  66840. * @copyright 2016 Photon Storm Ltd.
  66841. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  66842. */
  66843. /**
  66844. * ArraySet is a Set data structure (items must be unique within the set) that also maintains order.
  66845. * This allows specific items to be easily added or removed from the Set.
  66846. *
  66847. * Item equality (and uniqueness) is determined by the behavior of `Array.indexOf`.
  66848. *
  66849. * This used primarily by the Input subsystem.
  66850. *
  66851. * @class Phaser.ArraySet
  66852. * @constructor
  66853. * @param {any[]} [list=(new array)] - The backing array: if specified the items in the list _must_ be unique, per `Array.indexOf`, and the ownership of the array _should_ be relinquished to the ArraySet.
  66854. */
  66855. Phaser.ArraySet = function (list) {
  66856. /**
  66857. * Current cursor position as established by `first` and `next`.
  66858. * @property {integer} position
  66859. * @default
  66860. */
  66861. this.position = 0;
  66862. /**
  66863. * The backing array.
  66864. * @property {any[]} list
  66865. */
  66866. this.list = list || [];
  66867. };
  66868. Phaser.ArraySet.prototype = {
  66869. /**
  66870. * Adds a new element to the end of the list.
  66871. * If the item already exists in the list it is not moved.
  66872. *
  66873. * @method Phaser.ArraySet#add
  66874. * @param {any} item - The element to add to this list.
  66875. * @return {any} The item that was added.
  66876. */
  66877. add: function (item) {
  66878. if (!this.exists(item))
  66879. {
  66880. this.list.push(item);
  66881. }
  66882. return item;
  66883. },
  66884. /**
  66885. * Gets the index of the item in the list, or -1 if it isn't in the list.
  66886. *
  66887. * @method Phaser.ArraySet#getIndex
  66888. * @param {any} item - The element to get the list index for.
  66889. * @return {integer} The index of the item or -1 if not found.
  66890. */
  66891. getIndex: function (item) {
  66892. return this.list.indexOf(item);
  66893. },
  66894. /**
  66895. * Gets an item from the set based on the property strictly equaling the value given.
  66896. * Returns null if not found.
  66897. *
  66898. * @method Phaser.ArraySet#getByKey
  66899. * @param {string} property - The property to check against the value.
  66900. * @param {any} value - The value to check if the property strictly equals.
  66901. * @return {any} The item that was found, or null if nothing matched.
  66902. */
  66903. getByKey: function (property, value) {
  66904. var i = this.list.length;
  66905. while (i--)
  66906. {
  66907. if (this.list[i][property] === value)
  66908. {
  66909. return this.list[i];
  66910. }
  66911. }
  66912. return null;
  66913. },
  66914. /**
  66915. * Checks for the item within this list.
  66916. *
  66917. * @method Phaser.ArraySet#exists
  66918. * @param {any} item - The element to get the list index for.
  66919. * @return {boolean} True if the item is found in the list, otherwise false.
  66920. */
  66921. exists: function (item) {
  66922. return (this.list.indexOf(item) > -1);
  66923. },
  66924. /**
  66925. * Removes all the items.
  66926. *
  66927. * @method Phaser.ArraySet#reset
  66928. */
  66929. reset: function () {
  66930. this.list.length = 0;
  66931. },
  66932. /**
  66933. * Removes the given element from this list if it exists.
  66934. *
  66935. * @method Phaser.ArraySet#remove
  66936. * @param {any} item - The item to be removed from the list.
  66937. * @return {any} item - The item that was removed.
  66938. */
  66939. remove: function (item) {
  66940. var idx = this.list.indexOf(item);
  66941. if (idx > -1)
  66942. {
  66943. this.list.splice(idx, 1);
  66944. return item;
  66945. }
  66946. },
  66947. /**
  66948. * Sets the property `key` to the given value on all members of this list.
  66949. *
  66950. * @method Phaser.ArraySet#setAll
  66951. * @param {any} key - The property of the item to set.
  66952. * @param {any} value - The value to set the property to.
  66953. */
  66954. setAll: function (key, value) {
  66955. var i = this.list.length;
  66956. while (i--)
  66957. {
  66958. if (this.list[i])
  66959. {
  66960. this.list[i][key] = value;
  66961. }
  66962. }
  66963. },
  66964. /**
  66965. * Calls a function on all members of this list, using the member as the context for the callback.
  66966. *
  66967. * If the `key` property is present it must be a function.
  66968. * The function is invoked using the item as the context.
  66969. *
  66970. * @method Phaser.ArraySet#callAll
  66971. * @param {string} key - The name of the property with the function to call.
  66972. * @param {...*} parameter - Additional parameters that will be passed to the callback.
  66973. */
  66974. callAll: function (key) {
  66975. var args = Array.prototype.slice.call(arguments, 1);
  66976. var i = this.list.length;
  66977. while (i--)
  66978. {
  66979. if (this.list[i] && this.list[i][key])
  66980. {
  66981. this.list[i][key].apply(this.list[i], args);
  66982. }
  66983. }
  66984. },
  66985. /**
  66986. * Removes every member from this ArraySet and optionally destroys it.
  66987. *
  66988. * @method Phaser.ArraySet#removeAll
  66989. * @param {boolean} [destroy=false] - Call `destroy` on each member as it's removed from this set.
  66990. */
  66991. removeAll: function (destroy) {
  66992. if (destroy === undefined) { destroy = false; }
  66993. var i = this.list.length;
  66994. while (i--)
  66995. {
  66996. if (this.list[i])
  66997. {
  66998. var item = this.remove(this.list[i]);
  66999. if (destroy)
  67000. {
  67001. item.destroy();
  67002. }
  67003. }
  67004. }
  67005. this.position = 0;
  67006. this.list = [];
  67007. }
  67008. };
  67009. /**
  67010. * Number of items in the ArraySet. Same as `list.length`.
  67011. *
  67012. * @name Phaser.ArraySet#total
  67013. * @property {integer} total
  67014. */
  67015. Object.defineProperty(Phaser.ArraySet.prototype, "total", {
  67016. get: function () {
  67017. return this.list.length;
  67018. }
  67019. });
  67020. /**
  67021. * Returns the first item and resets the cursor to the start.
  67022. *
  67023. * @name Phaser.ArraySet#first
  67024. * @property {any} first
  67025. */
  67026. Object.defineProperty(Phaser.ArraySet.prototype, "first", {
  67027. get: function () {
  67028. this.position = 0;
  67029. if (this.list.length > 0)
  67030. {
  67031. return this.list[0];
  67032. }
  67033. else
  67034. {
  67035. return null;
  67036. }
  67037. }
  67038. });
  67039. /**
  67040. * Returns the the next item (based on the cursor) and advances the cursor.
  67041. *
  67042. * @name Phaser.ArraySet#next
  67043. * @property {any} next
  67044. */
  67045. Object.defineProperty(Phaser.ArraySet.prototype, "next", {
  67046. get: function () {
  67047. if (this.position < this.list.length)
  67048. {
  67049. this.position++;
  67050. return this.list[this.position];
  67051. }
  67052. else
  67053. {
  67054. return null;
  67055. }
  67056. }
  67057. });
  67058. Phaser.ArraySet.prototype.constructor = Phaser.ArraySet;
  67059. /**
  67060. * @author Richard Davey <rich@photonstorm.com>
  67061. * @copyright 2016 Photon Storm Ltd.
  67062. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  67063. */
  67064. /**
  67065. * Utility functions for dealing with Arrays.
  67066. *
  67067. * @class Phaser.ArrayUtils
  67068. * @static
  67069. */
  67070. Phaser.ArrayUtils = {
  67071. /**
  67072. * Fetch a random entry from the given array.
  67073. *
  67074. * Will return null if there are no array items that fall within the specified range
  67075. * or if there is no item for the randomly chosen index.
  67076. *
  67077. * @method
  67078. * @param {any[]} objects - An array of objects.
  67079. * @param {integer} startIndex - Optional offset off the front of the array. Default value is 0, or the beginning of the array.
  67080. * @param {integer} length - Optional restriction on the number of values you want to randomly select from.
  67081. * @return {object} The random object that was selected.
  67082. */
  67083. getRandomItem: function (objects, startIndex, length) {
  67084. if (objects === null) { return null; }
  67085. if (startIndex === undefined) { startIndex = 0; }
  67086. if (length === undefined) { length = objects.length; }
  67087. var randomIndex = startIndex + Math.floor(Math.random() * length);
  67088. return objects[randomIndex] === undefined ? null : objects[randomIndex];
  67089. },
  67090. /**
  67091. * Removes a random object from the given array and returns it.
  67092. *
  67093. * Will return null if there are no array items that fall within the specified range
  67094. * or if there is no item for the randomly chosen index.
  67095. *
  67096. * @method
  67097. * @param {any[]} objects - An array of objects.
  67098. * @param {integer} startIndex - Optional offset off the front of the array. Default value is 0, or the beginning of the array.
  67099. * @param {integer} length - Optional restriction on the number of values you want to randomly select from.
  67100. * @return {object} The random object that was removed.
  67101. */
  67102. removeRandomItem: function (objects, startIndex, length) {
  67103. if (objects == null) { // undefined or null
  67104. return null;
  67105. }
  67106. if (startIndex === undefined) { startIndex = 0; }
  67107. if (length === undefined) { length = objects.length; }
  67108. var randomIndex = startIndex + Math.floor(Math.random() * length);
  67109. if (randomIndex < objects.length)
  67110. {
  67111. var removed = objects.splice(randomIndex, 1);
  67112. return removed[0] === undefined ? null : removed[0];
  67113. }
  67114. else
  67115. {
  67116. return null;
  67117. }
  67118. },
  67119. /**
  67120. * A standard Fisher-Yates Array shuffle implementation which modifies the array in place.
  67121. *
  67122. * @method
  67123. * @param {any[]} array - The array to shuffle.
  67124. * @return {any[]} The original array, now shuffled.
  67125. */
  67126. shuffle: function (array) {
  67127. for (var i = array.length - 1; i > 0; i--)
  67128. {
  67129. var j = Math.floor(Math.random() * (i + 1));
  67130. var temp = array[i];
  67131. array[i] = array[j];
  67132. array[j] = temp;
  67133. }
  67134. return array;
  67135. },
  67136. /**
  67137. * Transposes the elements of the given matrix (array of arrays).
  67138. *
  67139. * @method
  67140. * @param {Array<any[]>} array - The matrix to transpose.
  67141. * @return {Array<any[]>} A new transposed matrix
  67142. */
  67143. transposeMatrix: function (array) {
  67144. var sourceRowCount = array.length;
  67145. var sourceColCount = array[0].length;
  67146. var result = new Array(sourceColCount);
  67147. for (var i = 0; i < sourceColCount; i++)
  67148. {
  67149. result[i] = new Array(sourceRowCount);
  67150. for (var j = sourceRowCount - 1; j > -1; j--)
  67151. {
  67152. result[i][j] = array[j][i];
  67153. }
  67154. }
  67155. return result;
  67156. },
  67157. /**
  67158. * Rotates the given matrix (array of arrays).
  67159. *
  67160. * Based on the routine from {@link http://jsfiddle.net/MrPolywhirl/NH42z/}.
  67161. *
  67162. * @method
  67163. * @param {Array<any[]>} matrix - The array to rotate; this matrix _may_ be altered.
  67164. * @param {number|string} direction - The amount to rotate: the rotation in degrees (90, -90, 270, -270, 180) or a string command ('rotateLeft', 'rotateRight' or 'rotate180').
  67165. * @return {Array<any[]>} The rotated matrix. The source matrix should be discarded for the returned matrix.
  67166. */
  67167. rotateMatrix: function (matrix, direction) {
  67168. if (typeof direction !== 'string')
  67169. {
  67170. direction = ((direction % 360) + 360) % 360;
  67171. }
  67172. if (direction === 90 || direction === -270 || direction === 'rotateLeft')
  67173. {
  67174. matrix = Phaser.ArrayUtils.transposeMatrix(matrix);
  67175. matrix = matrix.reverse();
  67176. }
  67177. else if (direction === -90 || direction === 270 || direction === 'rotateRight')
  67178. {
  67179. matrix = matrix.reverse();
  67180. matrix = Phaser.ArrayUtils.transposeMatrix(matrix);
  67181. }
  67182. else if (Math.abs(direction) === 180 || direction === 'rotate180')
  67183. {
  67184. for (var i = 0; i < matrix.length; i++)
  67185. {
  67186. matrix[i].reverse();
  67187. }
  67188. matrix = matrix.reverse();
  67189. }
  67190. return matrix;
  67191. },
  67192. /**
  67193. * Snaps a value to the nearest value in an array.
  67194. * The result will always be in the range `[first_value, last_value]`.
  67195. *
  67196. * @method
  67197. * @param {number} value - The search value
  67198. * @param {number[]} arr - The input array which _must_ be sorted.
  67199. * @return {number} The nearest value found.
  67200. */
  67201. findClosest: function (value, arr) {
  67202. if (!arr.length)
  67203. {
  67204. return NaN;
  67205. }
  67206. else if (arr.length === 1 || value < arr[0])
  67207. {
  67208. return arr[0];
  67209. }
  67210. var i = 1;
  67211. while (arr[i] < value) {
  67212. i++;
  67213. }
  67214. var low = arr[i - 1];
  67215. var high = (i < arr.length) ? arr[i] : Number.POSITIVE_INFINITY;
  67216. return ((high - value) <= (value - low)) ? high : low;
  67217. },
  67218. /**
  67219. * Moves the element from the end of the array to the start, shifting all items in the process.
  67220. * The "rotation" happens to the right.
  67221. *
  67222. * Before: `[ A, B, C, D, E, F ]`
  67223. * After: `[ F, A, B, C, D, E ]`
  67224. *
  67225. * See also Phaser.ArrayUtils.rotateLeft.
  67226. *
  67227. * @method Phaser.ArrayUtils.rotateRight
  67228. * @param {any[]} array - The array to rotate. The array is modified.
  67229. * @return {any} The shifted value.
  67230. */
  67231. rotateRight: function (array) {
  67232. var s = array.pop();
  67233. array.unshift(s);
  67234. return s;
  67235. },
  67236. /**
  67237. * Moves the element from the start of the array to the end, shifting all items in the process.
  67238. * The "rotation" happens to the left.
  67239. *
  67240. * Before: `[ A, B, C, D, E, F ]`
  67241. * After: `[ B, C, D, E, F, A ]`
  67242. *
  67243. * See also Phaser.ArrayUtils.rotateRight
  67244. *
  67245. * @method Phaser.ArrayUtils.rotateLeft
  67246. * @param {any[]} array - The array to rotate. The array is modified.
  67247. * @return {any} The rotated value.
  67248. */
  67249. rotateLeft: function (array) {
  67250. var s = array.shift();
  67251. array.push(s);
  67252. return s;
  67253. },
  67254. /**
  67255. * Moves the element from the start of the array to the end, shifting all items in the process.
  67256. * The "rotation" happens to the left.
  67257. *
  67258. * Before: `[ A, B, C, D, E, F ]`
  67259. * After: `[ B, C, D, E, F, A ]`
  67260. *
  67261. * See also Phaser.ArrayUtils.rotateRight
  67262. *
  67263. * @method Phaser.ArrayUtils.rotate
  67264. * @deprecated Please use Phaser.ArrayUtils.rotate instead.
  67265. * @param {any[]} array - The array to rotate. The array is modified.
  67266. * @return {any} The rotated value.
  67267. */
  67268. rotate: function (array) {
  67269. var s = array.shift();
  67270. array.push(s);
  67271. return s;
  67272. },
  67273. /**
  67274. * Create an array representing the inclusive range of numbers (usually integers) in `[start, end]`.
  67275. * This is equivalent to `numberArrayStep(start, end, 1)`.
  67276. *
  67277. * @method Phaser.ArrayUtils#numberArray
  67278. * @param {number} start - The minimum value the array starts with.
  67279. * @param {number} end - The maximum value the array contains.
  67280. * @return {number[]} The array of number values.
  67281. */
  67282. numberArray: function (start, end) {
  67283. var result = [];
  67284. for (var i = start; i <= end; i++)
  67285. {
  67286. result.push(i);
  67287. }
  67288. return result;
  67289. },
  67290. /**
  67291. * Create an array of numbers (positive and/or negative) progressing from `start`
  67292. * up to but not including `end` by advancing by `step`.
  67293. *
  67294. * If `start` is less than `end` a zero-length range is created unless a negative `step` is specified.
  67295. *
  67296. * Certain values for `start` and `end` (eg. NaN/undefined/null) are currently coerced to 0;
  67297. * for forward compatibility make sure to pass in actual numbers.
  67298. *
  67299. * @method Phaser.ArrayUtils#numberArrayStep
  67300. * @param {number} start - The start of the range.
  67301. * @param {number} [end] - The end of the range.
  67302. * @param {number} [step=1] - The value to increment or decrement by.
  67303. * @returns {Array} Returns the new array of numbers.
  67304. * @example
  67305. * Phaser.ArrayUtils.numberArrayStep(4);
  67306. * // => [0, 1, 2, 3]
  67307. *
  67308. * Phaser.ArrayUtils.numberArrayStep(1, 5);
  67309. * // => [1, 2, 3, 4]
  67310. *
  67311. * Phaser.ArrayUtils.numberArrayStep(0, 20, 5);
  67312. * // => [0, 5, 10, 15]
  67313. *
  67314. * Phaser.ArrayUtils.numberArrayStep(0, -4, -1);
  67315. * // => [0, -1, -2, -3]
  67316. *
  67317. * Phaser.ArrayUtils.numberArrayStep(1, 4, 0);
  67318. * // => [1, 1, 1]
  67319. *
  67320. * Phaser.ArrayUtils.numberArrayStep(0);
  67321. * // => []
  67322. */
  67323. numberArrayStep: function (start, end, step) {
  67324. if (start === undefined || start === null) { start = 0; }
  67325. if (end === undefined || end === null)
  67326. {
  67327. end = start;
  67328. start = 0;
  67329. }
  67330. if (step === undefined) { step = 1; }
  67331. var result = [];
  67332. var total = Math.max(Phaser.Math.roundAwayFromZero((end - start) / (step || 1)), 0);
  67333. for (var i = 0; i < total; i++)
  67334. {
  67335. result.push(start);
  67336. start += step;
  67337. }
  67338. return result;
  67339. }
  67340. };
  67341. /**
  67342. * @author Richard Davey <rich@photonstorm.com>
  67343. * @copyright 2016 Photon Storm Ltd.
  67344. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  67345. */
  67346. /**
  67347. * A basic Linked List data structure.
  67348. *
  67349. * This implementation _modifies_ the `prev` and `next` properties of each item added:
  67350. * - The `prev` and `next` properties must be writable and should not be used for any other purpose.
  67351. * - Items _cannot_ be added to multiple LinkedLists at the same time.
  67352. * - Only objects can be added.
  67353. *
  67354. * @class Phaser.LinkedList
  67355. * @constructor
  67356. */
  67357. Phaser.LinkedList = function () {
  67358. /**
  67359. * Next element in the list.
  67360. * @property {object} next
  67361. * @default
  67362. */
  67363. this.next = null;
  67364. /**
  67365. * Previous element in the list.
  67366. * @property {object} prev
  67367. * @default
  67368. */
  67369. this.prev = null;
  67370. /**
  67371. * First element in the list.
  67372. * @property {object} first
  67373. * @default
  67374. */
  67375. this.first = null;
  67376. /**
  67377. * Last element in the list.
  67378. * @property {object} last
  67379. * @default
  67380. */
  67381. this.last = null;
  67382. /**
  67383. * Number of elements in the list.
  67384. * @property {integer} total
  67385. * @default
  67386. */
  67387. this.total = 0;
  67388. };
  67389. Phaser.LinkedList.prototype = {
  67390. /**
  67391. * Adds a new element to this linked list.
  67392. *
  67393. * @method Phaser.LinkedList#add
  67394. * @param {object} item - The element to add to this list. Can be a Phaser.Sprite or any other object you need to quickly iterate through.
  67395. * @return {object} The item that was added.
  67396. */
  67397. add: function (item) {
  67398. // If the list is empty
  67399. if (this.total === 0 && this.first === null && this.last === null)
  67400. {
  67401. this.first = item;
  67402. this.last = item;
  67403. this.next = item;
  67404. item.prev = this;
  67405. this.total++;
  67406. return item;
  67407. }
  67408. // Gets appended to the end of the list, regardless of anything, and it won't have any children of its own (non-nested list)
  67409. this.last.next = item;
  67410. item.prev = this.last;
  67411. this.last = item;
  67412. this.total++;
  67413. return item;
  67414. },
  67415. /**
  67416. * Resets the first, last, next and previous node pointers in this list.
  67417. *
  67418. * @method Phaser.LinkedList#reset
  67419. */
  67420. reset: function () {
  67421. this.first = null;
  67422. this.last = null;
  67423. this.next = null;
  67424. this.prev = null;
  67425. this.total = 0;
  67426. },
  67427. /**
  67428. * Removes the given element from this linked list if it exists.
  67429. *
  67430. * @method Phaser.LinkedList#remove
  67431. * @param {object} item - The item to be removed from the list.
  67432. */
  67433. remove: function (item) {
  67434. if (this.total === 1)
  67435. {
  67436. this.reset();
  67437. item.next = item.prev = null;
  67438. return;
  67439. }
  67440. if (item === this.first)
  67441. {
  67442. // It was 'first', make 'first' point to first.next
  67443. this.first = this.first.next;
  67444. }
  67445. else if (item === this.last)
  67446. {
  67447. // It was 'last', make 'last' point to last.prev
  67448. this.last = this.last.prev;
  67449. }
  67450. if (item.prev)
  67451. {
  67452. // make item.prev.next point to childs.next instead of item
  67453. item.prev.next = item.next;
  67454. }
  67455. if (item.next)
  67456. {
  67457. // make item.next.prev point to item.prev instead of item
  67458. item.next.prev = item.prev;
  67459. }
  67460. item.next = item.prev = null;
  67461. if (this.first === null )
  67462. {
  67463. this.last = null;
  67464. }
  67465. this.total--;
  67466. },
  67467. /**
  67468. * Calls a function on all members of this list, using the member as the context for the callback.
  67469. * The function must exist on the member.
  67470. *
  67471. * @method Phaser.LinkedList#callAll
  67472. * @param {function} callback - The function to call.
  67473. */
  67474. callAll: function (callback) {
  67475. if (!this.first || !this.last)
  67476. {
  67477. return;
  67478. }
  67479. var entity = this.first;
  67480. do
  67481. {
  67482. if (entity && entity[callback])
  67483. {
  67484. entity[callback].call(entity);
  67485. }
  67486. entity = entity.next;
  67487. }
  67488. while (entity !== this.last.next);
  67489. }
  67490. };
  67491. Phaser.LinkedList.prototype.constructor = Phaser.LinkedList;
  67492. /**
  67493. * @author Richard Davey <rich@photonstorm.com>
  67494. * @copyright 2016 Photon Storm Ltd.
  67495. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  67496. */
  67497. /**
  67498. * The Phaser.Create class is a collection of smaller helper methods that allow you to generate game content
  67499. * quickly and easily, without the need for any external files. You can create textures for sprites and in
  67500. * coming releases we'll add dynamic sound effect generation support as well (like sfxr).
  67501. *
  67502. * Access this via `Game.create` (`this.game.create` from within a State object)
  67503. *
  67504. * @class Phaser.Create
  67505. * @constructor
  67506. * @param {Phaser.Game} game - Game reference to the currently running game.
  67507. */
  67508. Phaser.Create = function (game) {
  67509. /**
  67510. * @property {Phaser.Game} game - A reference to the currently running Game.
  67511. */
  67512. this.game = game;
  67513. /**
  67514. * @property {Phaser.BitmapData} bmd - The internal BitmapData Create uses to generate textures from.
  67515. */
  67516. this.bmd = null;
  67517. /**
  67518. * @property {HTMLCanvasElement} canvas - The canvas the BitmapData uses.
  67519. */
  67520. this.canvas = null;
  67521. /**
  67522. * @property {CanvasRenderingContext2D} context - The 2d context of the canvas.
  67523. */
  67524. this.ctx = null;
  67525. /**
  67526. * @property {array} palettes - A range of 16 color palettes for use with sprite generation.
  67527. */
  67528. this.palettes = [
  67529. { 0: '#000', 1: '#9D9D9D', 2: '#FFF', 3: '#BE2633', 4: '#E06F8B', 5: '#493C2B', 6: '#A46422', 7: '#EB8931', 8: '#F7E26B', 9: '#2F484E', A: '#44891A', B: '#A3CE27', C: '#1B2632', D: '#005784', E: '#31A2F2', F: '#B2DCEF' },
  67530. { 0: '#000', 1: '#191028', 2: '#46af45', 3: '#a1d685', 4: '#453e78', 5: '#7664fe', 6: '#833129', 7: '#9ec2e8', 8: '#dc534b', 9: '#e18d79', A: '#d6b97b', B: '#e9d8a1', C: '#216c4b', D: '#d365c8', E: '#afaab9', F: '#f5f4eb' },
  67531. { 0: '#000', 1: '#2234d1', 2: '#0c7e45', 3: '#44aacc', 4: '#8a3622', 5: '#5c2e78', 6: '#aa5c3d', 7: '#b5b5b5', 8: '#5e606e', 9: '#4c81fb', A: '#6cd947', B: '#7be2f9', C: '#eb8a60', D: '#e23d69', E: '#ffd93f', F: '#fff' },
  67532. { 0: '#000', 1: '#fff', 2: '#8b4131', 3: '#7bbdc5', 4: '#8b41ac', 5: '#6aac41', 6: '#3931a4', 7: '#d5de73', 8: '#945a20', 9: '#5a4100', A: '#bd736a', B: '#525252', C: '#838383', D: '#acee8b', E: '#7b73de', F: '#acacac' },
  67533. { 0: '#000', 1: '#191028', 2: '#46af45', 3: '#a1d685', 4: '#453e78', 5: '#7664fe', 6: '#833129', 7: '#9ec2e8', 8: '#dc534b', 9: '#e18d79', A: '#d6b97b', B: '#e9d8a1', C: '#216c4b', D: '#d365c8', E: '#afaab9', F: '#fff' }
  67534. ];
  67535. };
  67536. /**
  67537. * A 16 color palette by [Arne](http://androidarts.com/palette/16pal.htm)
  67538. * @constant
  67539. * @type {number}
  67540. */
  67541. Phaser.Create.PALETTE_ARNE = 0;
  67542. /**
  67543. * A 16 color JMP inspired palette.
  67544. * @constant
  67545. * @type {number}
  67546. */
  67547. Phaser.Create.PALETTE_JMP = 1;
  67548. /**
  67549. * A 16 color CGA inspired palette.
  67550. * @constant
  67551. * @type {number}
  67552. */
  67553. Phaser.Create.PALETTE_CGA = 2;
  67554. /**
  67555. * A 16 color C64 inspired palette.
  67556. * @constant
  67557. * @type {number}
  67558. */
  67559. Phaser.Create.PALETTE_C64 = 3;
  67560. /**
  67561. * A 16 color palette inspired by Japanese computers like the MSX.
  67562. * @constant
  67563. * @type {number}
  67564. */
  67565. Phaser.Create.PALETTE_JAPANESE_MACHINE = 4;
  67566. Phaser.Create.prototype = {
  67567. /**
  67568. * Generates a new PIXI.Texture from the given data, which can be applied to a Sprite.
  67569. *
  67570. * This allows you to create game graphics quickly and easily, with no external files but that use actual proper images
  67571. * rather than Phaser.Graphics objects, which are expensive to render and limited in scope.
  67572. *
  67573. * Each element of the array is a string holding the pixel color values, as mapped to one of the Phaser.Create PALETTE consts.
  67574. *
  67575. * For example:
  67576. *
  67577. * `var data = [
  67578. * ' 333 ',
  67579. * ' 777 ',
  67580. * 'E333E',
  67581. * ' 333 ',
  67582. * ' 3 3 '
  67583. * ];`
  67584. *
  67585. * `game.create.texture('bob', data);`
  67586. *
  67587. * The above will create a new texture called `bob`, which will look like a little man wearing a hat. You can then use it
  67588. * for sprites the same way you use any other texture: `game.add.sprite(0, 0, 'bob');`
  67589. *
  67590. * @method Phaser.Create#texture
  67591. * @param {string} key - The key used to store this texture in the Phaser Cache.
  67592. * @param {array} data - An array of pixel data.
  67593. * @param {integer} [pixelWidth=8] - The width of each pixel.
  67594. * @param {integer} [pixelHeight=8] - The height of each pixel.
  67595. * @param {integer} [palette=0] - The palette to use when rendering the texture. One of the Phaser.Create.PALETTE consts.
  67596. * @return {PIXI.Texture} The newly generated texture.
  67597. */
  67598. texture: function (key, data, pixelWidth, pixelHeight, palette) {
  67599. if (pixelWidth === undefined) { pixelWidth = 8; }
  67600. if (pixelHeight === undefined) { pixelHeight = pixelWidth; }
  67601. if (palette === undefined) { palette = 0; }
  67602. var w = data[0].length * pixelWidth;
  67603. var h = data.length * pixelHeight;
  67604. // No bmd? Let's make one
  67605. if (this.bmd === null)
  67606. {
  67607. this.bmd = this.game.make.bitmapData();
  67608. this.canvas = this.bmd.canvas;
  67609. this.ctx = this.bmd.context;
  67610. }
  67611. this.bmd.resize(w, h);
  67612. this.bmd.clear();
  67613. // Draw it
  67614. for (var y = 0; y < data.length; y++)
  67615. {
  67616. var row = data[y];
  67617. for (var x = 0; x < row.length; x++)
  67618. {
  67619. var d = row[x];
  67620. if (d !== '.' && d !== ' ')
  67621. {
  67622. this.ctx.fillStyle = this.palettes[palette][d];
  67623. this.ctx.fillRect(x * pixelWidth, y * pixelHeight, pixelWidth, pixelHeight);
  67624. }
  67625. }
  67626. }
  67627. return this.bmd.generateTexture(key);
  67628. },
  67629. /**
  67630. * Creates a grid texture based on the given dimensions.
  67631. *
  67632. * @method Phaser.Create#grid
  67633. * @param {string} key - The key used to store this texture in the Phaser Cache.
  67634. * @param {integer} width - The width of the grid in pixels.
  67635. * @param {integer} height - The height of the grid in pixels.
  67636. * @param {integer} cellWidth - The width of the grid cells in pixels.
  67637. * @param {integer} cellHeight - The height of the grid cells in pixels.
  67638. * @param {string} color - The color to draw the grid lines in. Should be a Canvas supported color string like `#ff5500` or `rgba(200,50,3,0.5)`.
  67639. * @return {PIXI.Texture} The newly generated texture.
  67640. */
  67641. grid: function (key, width, height, cellWidth, cellHeight, color) {
  67642. // No bmd? Let's make one
  67643. if (this.bmd === null)
  67644. {
  67645. this.bmd = this.game.make.bitmapData();
  67646. this.canvas = this.bmd.canvas;
  67647. this.ctx = this.bmd.context;
  67648. }
  67649. this.bmd.resize(width, height);
  67650. this.ctx.fillStyle = color;
  67651. for (var y = 0; y < height; y += cellHeight)
  67652. {
  67653. this.ctx.fillRect(0, y, width, 1);
  67654. }
  67655. for (var x = 0; x < width; x += cellWidth)
  67656. {
  67657. this.ctx.fillRect(x, 0, 1, height);
  67658. }
  67659. return this.bmd.generateTexture(key);
  67660. }
  67661. };
  67662. Phaser.Create.prototype.constructor = Phaser.Create;
  67663. /**
  67664. * @author Richard Davey <rich@photonstorm.com>
  67665. * @copyright 2016 Photon Storm Ltd.
  67666. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  67667. */
  67668. /**
  67669. * WARNING: This is an EXPERIMENTAL class. The API will change significantly in the coming versions and is incomplete.
  67670. * Please try to avoid using in production games with a long time to build.
  67671. * This is also why the documentation is incomplete.
  67672. *
  67673. * FlexGrid is a a responsive grid manager that works in conjunction with the ScaleManager RESIZE scaling mode and FlexLayers
  67674. * to provide for game object positioning in a responsive manner.
  67675. *
  67676. * @class Phaser.FlexGrid
  67677. * @constructor
  67678. * @param {Phaser.ScaleManager} manager - The ScaleManager.
  67679. * @param {number} width - The width of the game.
  67680. * @param {number} height - The height of the game.
  67681. */
  67682. Phaser.FlexGrid = function (manager, width, height) {
  67683. /**
  67684. * @property {Phaser.Game} game - A reference to the currently running Game.
  67685. */
  67686. this.game = manager.game;
  67687. /**
  67688. * @property {Phaser.ScaleManager} manager - A reference to the ScaleManager.
  67689. */
  67690. this.manager = manager;
  67691. // The perfect dimensions on which everything else is based
  67692. this.width = width;
  67693. this.height = height;
  67694. this.boundsCustom = new Phaser.Rectangle(0, 0, width, height);
  67695. this.boundsFluid = new Phaser.Rectangle(0, 0, width, height);
  67696. this.boundsFull = new Phaser.Rectangle(0, 0, width, height);
  67697. this.boundsNone = new Phaser.Rectangle(0, 0, width, height);
  67698. /**
  67699. * @property {Phaser.Point} position -
  67700. * @readonly
  67701. */
  67702. this.positionCustom = new Phaser.Point(0, 0);
  67703. this.positionFluid = new Phaser.Point(0, 0);
  67704. this.positionFull = new Phaser.Point(0, 0);
  67705. this.positionNone = new Phaser.Point(0, 0);
  67706. /**
  67707. * @property {Phaser.Point} scaleFactor - The scale factor based on the game dimensions vs. the scaled dimensions.
  67708. * @readonly
  67709. */
  67710. this.scaleCustom = new Phaser.Point(1, 1);
  67711. this.scaleFluid = new Phaser.Point(1, 1);
  67712. this.scaleFluidInversed = new Phaser.Point(1, 1);
  67713. this.scaleFull = new Phaser.Point(1, 1);
  67714. this.scaleNone = new Phaser.Point(1, 1);
  67715. this.customWidth = 0;
  67716. this.customHeight = 0;
  67717. this.customOffsetX = 0;
  67718. this.customOffsetY = 0;
  67719. this.ratioH = width / height;
  67720. this.ratioV = height / width;
  67721. this.multiplier = 0;
  67722. this.layers = [];
  67723. };
  67724. Phaser.FlexGrid.prototype = {
  67725. /**
  67726. * Sets the core game size. This resets the w/h parameters and bounds.
  67727. *
  67728. * @method Phaser.FlexGrid#setSize
  67729. * @param {number} width - The new dimensions.
  67730. * @param {number} height - The new dimensions.
  67731. */
  67732. setSize: function (width, height) {
  67733. // These are locked and don't change until setSize is called again
  67734. this.width = width;
  67735. this.height = height;
  67736. this.ratioH = width / height;
  67737. this.ratioV = height / width;
  67738. this.scaleNone = new Phaser.Point(1, 1);
  67739. this.boundsNone.width = this.width;
  67740. this.boundsNone.height = this.height;
  67741. this.refresh();
  67742. },
  67743. // Need ability to create your own layers with custom scaling, etc.
  67744. /**
  67745. * A custom layer is centered on the game and maintains its aspect ratio as it scales up and down.
  67746. *
  67747. * @method Phaser.FlexGrid#createCustomLayer
  67748. * @param {number} width - Width of this layer in pixels.
  67749. * @param {number} height - Height of this layer in pixels.
  67750. * @param {PIXI.DisplayObject[]} [children] - An array of children that are used to populate the FlexLayer.
  67751. * @return {Phaser.FlexLayer} The Layer object.
  67752. */
  67753. createCustomLayer: function (width, height, children, addToWorld) {
  67754. if (addToWorld === undefined) { addToWorld = true; }
  67755. this.customWidth = width;
  67756. this.customHeight = height;
  67757. this.boundsCustom.width = width;
  67758. this.boundsCustom.height = height;
  67759. var layer = new Phaser.FlexLayer(this, this.positionCustom, this.boundsCustom, this.scaleCustom);
  67760. if (addToWorld)
  67761. {
  67762. this.game.world.add(layer);
  67763. }
  67764. this.layers.push(layer);
  67765. if (typeof children !== 'undefined' && typeof children !== null)
  67766. {
  67767. layer.addMultiple(children);
  67768. }
  67769. return layer;
  67770. },
  67771. /**
  67772. * A fluid layer is centered on the game and maintains its aspect ratio as it scales up and down.
  67773. *
  67774. * @method Phaser.FlexGrid#createFluidLayer
  67775. * @param {array} [children] - An array of children that are used to populate the FlexLayer.
  67776. * @return {Phaser.FlexLayer} The Layer object.
  67777. */
  67778. createFluidLayer: function (children, addToWorld) {
  67779. if (addToWorld === undefined) { addToWorld = true; }
  67780. var layer = new Phaser.FlexLayer(this, this.positionFluid, this.boundsFluid, this.scaleFluid);
  67781. if (addToWorld)
  67782. {
  67783. this.game.world.add(layer);
  67784. }
  67785. this.layers.push(layer);
  67786. if (typeof children !== 'undefined' && typeof children !== null)
  67787. {
  67788. layer.addMultiple(children);
  67789. }
  67790. return layer;
  67791. },
  67792. /**
  67793. * A full layer is placed at 0,0 and extends to the full size of the game. Children are scaled according to the fluid ratios.
  67794. *
  67795. * @method Phaser.FlexGrid#createFullLayer
  67796. * @param {array} [children] - An array of children that are used to populate the FlexLayer.
  67797. * @return {Phaser.FlexLayer} The Layer object.
  67798. */
  67799. createFullLayer: function (children) {
  67800. var layer = new Phaser.FlexLayer(this, this.positionFull, this.boundsFull, this.scaleFluid);
  67801. this.game.world.add(layer);
  67802. this.layers.push(layer);
  67803. if (typeof children !== 'undefined')
  67804. {
  67805. layer.addMultiple(children);
  67806. }
  67807. return layer;
  67808. },
  67809. /**
  67810. * A fixed layer is centered on the game and is the size of the required dimensions and is never scaled.
  67811. *
  67812. * @method Phaser.FlexGrid#createFixedLayer
  67813. * @param {PIXI.DisplayObject[]} [children] - An array of children that are used to populate the FlexLayer.
  67814. * @return {Phaser.FlexLayer} The Layer object.
  67815. */
  67816. createFixedLayer: function (children) {
  67817. var layer = new Phaser.FlexLayer(this, this.positionNone, this.boundsNone, this.scaleNone);
  67818. this.game.world.add(layer);
  67819. this.layers.push(layer);
  67820. if (typeof children !== 'undefined')
  67821. {
  67822. layer.addMultiple(children);
  67823. }
  67824. return layer;
  67825. },
  67826. /**
  67827. * Resets the layer children references
  67828. *
  67829. * @method Phaser.FlexGrid#reset
  67830. */
  67831. reset: function () {
  67832. var i = this.layers.length;
  67833. while (i--)
  67834. {
  67835. if (!this.layers[i].persist)
  67836. {
  67837. // Remove references to this class
  67838. this.layers[i].position = null;
  67839. this.layers[i].scale = null;
  67840. this.layers.slice(i, 1);
  67841. }
  67842. }
  67843. },
  67844. /**
  67845. * Called when the game container changes dimensions.
  67846. *
  67847. * @method Phaser.FlexGrid#onResize
  67848. * @param {number} width - The new width of the game container.
  67849. * @param {number} height - The new height of the game container.
  67850. */
  67851. onResize: function (width, height) {
  67852. this.ratioH = width / height;
  67853. this.ratioV = height / width;
  67854. this.refresh(width, height);
  67855. },
  67856. /**
  67857. * Updates all internal vars such as the bounds and scale values.
  67858. *
  67859. * @method Phaser.FlexGrid#refresh
  67860. */
  67861. refresh: function () {
  67862. this.multiplier = Math.min((this.manager.height / this.height), (this.manager.width / this.width));
  67863. this.boundsFluid.width = Math.round(this.width * this.multiplier);
  67864. this.boundsFluid.height = Math.round(this.height * this.multiplier);
  67865. this.scaleFluid.set(this.boundsFluid.width / this.width, this.boundsFluid.height / this.height);
  67866. this.scaleFluidInversed.set(this.width / this.boundsFluid.width, this.height / this.boundsFluid.height);
  67867. this.scaleFull.set(this.boundsFull.width / this.width, this.boundsFull.height / this.height);
  67868. this.boundsFull.width = Math.round(this.manager.width * this.scaleFluidInversed.x);
  67869. this.boundsFull.height = Math.round(this.manager.height * this.scaleFluidInversed.y);
  67870. this.boundsFluid.centerOn(this.manager.bounds.centerX, this.manager.bounds.centerY);
  67871. this.boundsNone.centerOn(this.manager.bounds.centerX, this.manager.bounds.centerY);
  67872. this.positionFluid.set(this.boundsFluid.x, this.boundsFluid.y);
  67873. this.positionNone.set(this.boundsNone.x, this.boundsNone.y);
  67874. },
  67875. /**
  67876. * Fits a sprites width to the bounds.
  67877. *
  67878. * @method Phaser.FlexGrid#fitSprite
  67879. * @param {Phaser.Sprite} sprite - The Sprite to fit.
  67880. */
  67881. fitSprite: function (sprite) {
  67882. this.manager.scaleSprite(sprite);
  67883. sprite.x = this.manager.bounds.centerX;
  67884. sprite.y = this.manager.bounds.centerY;
  67885. },
  67886. /**
  67887. * Call in the render function to output the bounds rects.
  67888. *
  67889. * @method Phaser.FlexGrid#debug
  67890. */
  67891. debug: function () {
  67892. // for (var i = 0; i < this.layers.length; i++)
  67893. // {
  67894. // this.layers[i].debug();
  67895. // }
  67896. // this.game.debug.text(this.boundsFull.width + ' x ' + this.boundsFull.height, this.boundsFull.x + 4, this.boundsFull.y + 16);
  67897. // this.game.debug.geom(this.boundsFull, 'rgba(0,0,255,0.9', false);
  67898. this.game.debug.text(this.boundsFluid.width + ' x ' + this.boundsFluid.height, this.boundsFluid.x + 4, this.boundsFluid.y + 16);
  67899. this.game.debug.geom(this.boundsFluid, 'rgba(255,0,0,0.9', false);
  67900. // this.game.debug.text(this.boundsNone.width + ' x ' + this.boundsNone.height, this.boundsNone.x + 4, this.boundsNone.y + 16);
  67901. // this.game.debug.geom(this.boundsNone, 'rgba(0,255,0,0.9', false);
  67902. // this.game.debug.text(this.boundsCustom.width + ' x ' + this.boundsCustom.height, this.boundsCustom.x + 4, this.boundsCustom.y + 16);
  67903. // this.game.debug.geom(this.boundsCustom, 'rgba(255,255,0,0.9', false);
  67904. }
  67905. };
  67906. Phaser.FlexGrid.prototype.constructor = Phaser.FlexGrid;
  67907. /**
  67908. * @author Richard Davey <rich@photonstorm.com>
  67909. * @copyright 2016 Photon Storm Ltd.
  67910. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  67911. */
  67912. /**
  67913. * WARNING: This is an EXPERIMENTAL class. The API will change significantly in the coming versions and is incomplete.
  67914. * Please try to avoid using in production games with a long time to build.
  67915. * This is also why the documentation is incomplete.
  67916. *
  67917. * A responsive grid layer.
  67918. *
  67919. * @class Phaser.FlexLayer
  67920. * @extends Phaser.Group
  67921. * @constructor
  67922. * @param {Phaser.FlexGrid} manager - The FlexGrid that owns this FlexLayer.
  67923. * @param {Phaser.Point} position - A reference to the Point object used for positioning.
  67924. * @param {Phaser.Rectangle} bounds - A reference to the Rectangle used for the layer bounds.
  67925. * @param {Phaser.Point} scale - A reference to the Point object used for layer scaling.
  67926. */
  67927. Phaser.FlexLayer = function (manager, position, bounds, scale) {
  67928. Phaser.Group.call(this, manager.game, null, '__flexLayer' + manager.game.rnd.uuid(), false);
  67929. /**
  67930. * @property {Phaser.ScaleManager} scale - A reference to the ScaleManager.
  67931. */
  67932. this.manager = manager.manager;
  67933. /**
  67934. * @property {Phaser.FlexGrid} grid - A reference to the FlexGrid that owns this layer.
  67935. */
  67936. this.grid = manager;
  67937. /**
  67938. * Should the FlexLayer remain through a State swap?
  67939. *
  67940. * @type {boolean}
  67941. */
  67942. this.persist = false;
  67943. /**
  67944. * @property {Phaser.Point} position
  67945. */
  67946. this.position = position;
  67947. /**
  67948. * @property {Phaser.Rectangle} bounds
  67949. */
  67950. this.bounds = bounds;
  67951. /**
  67952. * @property {Phaser.Point} scale
  67953. */
  67954. this.scale = scale;
  67955. /**
  67956. * @property {Phaser.Point} topLeft
  67957. */
  67958. this.topLeft = bounds.topLeft;
  67959. /**
  67960. * @property {Phaser.Point} topMiddle
  67961. */
  67962. this.topMiddle = new Phaser.Point(bounds.halfWidth, 0);
  67963. /**
  67964. * @property {Phaser.Point} topRight
  67965. */
  67966. this.topRight = bounds.topRight;
  67967. /**
  67968. * @property {Phaser.Point} bottomLeft
  67969. */
  67970. this.bottomLeft = bounds.bottomLeft;
  67971. /**
  67972. * @property {Phaser.Point} bottomMiddle
  67973. */
  67974. this.bottomMiddle = new Phaser.Point(bounds.halfWidth, bounds.bottom);
  67975. /**
  67976. * @property {Phaser.Point} bottomRight
  67977. */
  67978. this.bottomRight = bounds.bottomRight;
  67979. };
  67980. Phaser.FlexLayer.prototype = Object.create(Phaser.Group.prototype);
  67981. Phaser.FlexLayer.prototype.constructor = Phaser.FlexLayer;
  67982. /**
  67983. * Resize.
  67984. *
  67985. * @method Phaser.FlexLayer#resize
  67986. */
  67987. Phaser.FlexLayer.prototype.resize = function () {
  67988. };
  67989. /**
  67990. * Debug.
  67991. *
  67992. * @method Phaser.FlexLayer#debug
  67993. */
  67994. Phaser.FlexLayer.prototype.debug = function () {
  67995. this.game.debug.text(this.bounds.width + ' x ' + this.bounds.height, this.bounds.x + 4, this.bounds.y + 16);
  67996. this.game.debug.geom(this.bounds, 'rgba(0,0,255,0.9', false);
  67997. this.game.debug.geom(this.topLeft, 'rgba(255,255,255,0.9');
  67998. this.game.debug.geom(this.topMiddle, 'rgba(255,255,255,0.9');
  67999. this.game.debug.geom(this.topRight, 'rgba(255,255,255,0.9');
  68000. };
  68001. /**
  68002. * @author Richard Davey <rich@photonstorm.com>
  68003. * @copyright 2016 Photon Storm Ltd.
  68004. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  68005. */
  68006. /**
  68007. * The Phaser.Color class is a set of static methods that assist in color manipulation and conversion.
  68008. *
  68009. * @class Phaser.Color
  68010. */
  68011. Phaser.Color = {
  68012. /**
  68013. * Packs the r, g, b, a components into a single integer, for use with Int32Array.
  68014. * If device is little endian then ABGR order is used. Otherwise RGBA order is used.
  68015. *
  68016. * @author Matt DesLauriers (@mattdesl)
  68017. * @method Phaser.Color.packPixel
  68018. * @static
  68019. * @param {number} r - The red color component, in the range 0 - 255.
  68020. * @param {number} g - The green color component, in the range 0 - 255.
  68021. * @param {number} b - The blue color component, in the range 0 - 255.
  68022. * @param {number} a - The alpha color component, in the range 0 - 255.
  68023. * @return {number} The packed color as uint32
  68024. */
  68025. packPixel: function (r, g, b, a) {
  68026. if (Phaser.Device.LITTLE_ENDIAN)
  68027. {
  68028. return ( (a << 24) | (b << 16) | (g << 8) | r ) >>> 0;
  68029. }
  68030. else
  68031. {
  68032. return ( (r << 24) | (g << 16) | (b << 8) | a ) >>> 0;
  68033. }
  68034. },
  68035. /**
  68036. * Unpacks the r, g, b, a components into the specified color object, or a new
  68037. * object, for use with Int32Array. If little endian, then ABGR order is used when
  68038. * unpacking, otherwise, RGBA order is used. The resulting color object has the
  68039. * `r, g, b, a` properties which are unrelated to endianness.
  68040. *
  68041. * Note that the integer is assumed to be packed in the correct endianness. On little-endian
  68042. * the format is 0xAABBGGRR and on big-endian the format is 0xRRGGBBAA. If you want a
  68043. * endian-independent method, use fromRGBA(rgba) and toRGBA(r, g, b, a).
  68044. *
  68045. * @author Matt DesLauriers (@mattdesl)
  68046. * @method Phaser.Color.unpackPixel
  68047. * @static
  68048. * @param {number} rgba - The integer, packed in endian order by packPixel.
  68049. * @param {object} [out] - An object into which 3 properties will be created: r, g and b. If not provided a new object will be created.
  68050. * @param {boolean} [hsl=false] - Also convert the rgb values into hsl?
  68051. * @param {boolean} [hsv=false] - Also convert the rgb values into hsv?
  68052. * @return {object} An object with the red, green and blue values set in the r, g and b properties.
  68053. */
  68054. unpackPixel: function (rgba, out, hsl, hsv) {
  68055. if (out === undefined || out === null) { out = Phaser.Color.createColor(); }
  68056. if (hsl === undefined || hsl === null) { hsl = false; }
  68057. if (hsv === undefined || hsv === null) { hsv = false; }
  68058. if (Phaser.Device.LITTLE_ENDIAN)
  68059. {
  68060. out.a = ((rgba & 0xff000000) >>> 24);
  68061. out.b = ((rgba & 0x00ff0000) >>> 16);
  68062. out.g = ((rgba & 0x0000ff00) >>> 8);
  68063. out.r = ((rgba & 0x000000ff));
  68064. }
  68065. else
  68066. {
  68067. out.r = ((rgba & 0xff000000) >>> 24);
  68068. out.g = ((rgba & 0x00ff0000) >>> 16);
  68069. out.b = ((rgba & 0x0000ff00) >>> 8);
  68070. out.a = ((rgba & 0x000000ff));
  68071. }
  68072. out.color = rgba;
  68073. out.rgba = 'rgba(' + out.r + ',' + out.g + ',' + out.b + ',' + (out.a / 255) + ')';
  68074. if (hsl)
  68075. {
  68076. Phaser.Color.RGBtoHSL(out.r, out.g, out.b, out);
  68077. }
  68078. if (hsv)
  68079. {
  68080. Phaser.Color.RGBtoHSV(out.r, out.g, out.b, out);
  68081. }
  68082. return out;
  68083. },
  68084. /**
  68085. * A utility to convert an integer in 0xRRGGBBAA format to a color object.
  68086. * This does not rely on endianness.
  68087. *
  68088. * @author Matt DesLauriers (@mattdesl)
  68089. * @method Phaser.Color.fromRGBA
  68090. * @static
  68091. * @param {number} rgba - An RGBA hex
  68092. * @param {object} [out] - The object to use, optional.
  68093. * @return {object} A color object.
  68094. */
  68095. fromRGBA: function (rgba, out) {
  68096. if (!out)
  68097. {
  68098. out = Phaser.Color.createColor();
  68099. }
  68100. out.r = ((rgba & 0xff000000) >>> 24);
  68101. out.g = ((rgba & 0x00ff0000) >>> 16);
  68102. out.b = ((rgba & 0x0000ff00) >>> 8);
  68103. out.a = ((rgba & 0x000000ff));
  68104. out.rgba = 'rgba(' + out.r + ',' + out.g + ',' + out.b + ',' + out.a + ')';
  68105. return out;
  68106. },
  68107. /**
  68108. * A utility to convert RGBA components to a 32 bit integer in RRGGBBAA format.
  68109. *
  68110. * @author Matt DesLauriers (@mattdesl)
  68111. * @method Phaser.Color.toRGBA
  68112. * @static
  68113. * @param {number} r - The red color component, in the range 0 - 255.
  68114. * @param {number} g - The green color component, in the range 0 - 255.
  68115. * @param {number} b - The blue color component, in the range 0 - 255.
  68116. * @param {number} a - The alpha color component, in the range 0 - 255.
  68117. * @return {number} A RGBA-packed 32 bit integer
  68118. */
  68119. toRGBA: function (r, g, b, a) {
  68120. return (r << 24) | (g << 16) | (b << 8) | a;
  68121. },
  68122. /**
  68123. * Converts RGBA components to a 32 bit integer in AABBGGRR format.
  68124. *
  68125. * @method Phaser.Color.toABGR
  68126. * @static
  68127. * @param {number} r - The red color component, in the range 0 - 255.
  68128. * @param {number} g - The green color component, in the range 0 - 255.
  68129. * @param {number} b - The blue color component, in the range 0 - 255.
  68130. * @param {number} a - The alpha color component, in the range 0 - 255.
  68131. * @return {number} A RGBA-packed 32 bit integer
  68132. */
  68133. toABGR: function (r, g, b, a) {
  68134. return ((a << 24) | (b << 16) | (g << 8) | r) >>> 0;
  68135. },
  68136. /**
  68137. * Converts an RGB color value to HSL (hue, saturation and lightness).
  68138. * Conversion forumla from http://en.wikipedia.org/wiki/HSL_color_space.
  68139. * Assumes RGB values are contained in the set [0, 255] and returns h, s and l in the set [0, 1].
  68140. * Based on code by Michael Jackson (https://github.com/mjijackson)
  68141. *
  68142. * @method Phaser.Color.RGBtoHSL
  68143. * @static
  68144. * @param {number} r - The red color component, in the range 0 - 255.
  68145. * @param {number} g - The green color component, in the range 0 - 255.
  68146. * @param {number} b - The blue color component, in the range 0 - 255.
  68147. * @param {object} [out] - An object into which 3 properties will be created, h, s and l. If not provided a new object will be created.
  68148. * @return {object} An object with the hue, saturation and lightness values set in the h, s and l properties.
  68149. */
  68150. RGBtoHSL: function (r, g, b, out) {
  68151. if (!out)
  68152. {
  68153. out = Phaser.Color.createColor(r, g, b, 1);
  68154. }
  68155. r /= 255;
  68156. g /= 255;
  68157. b /= 255;
  68158. var min = Math.min(r, g, b);
  68159. var max = Math.max(r, g, b);
  68160. // achromatic by default
  68161. out.h = 0;
  68162. out.s = 0;
  68163. out.l = (max + min) / 2;
  68164. if (max !== min)
  68165. {
  68166. var d = max - min;
  68167. out.s = out.l > 0.5 ? d / (2 - max - min) : d / (max + min);
  68168. if (max === r)
  68169. {
  68170. out.h = (g - b) / d + (g < b ? 6 : 0);
  68171. }
  68172. else if (max === g)
  68173. {
  68174. out.h = (b - r) / d + 2;
  68175. }
  68176. else if (max === b)
  68177. {
  68178. out.h = (r - g) / d + 4;
  68179. }
  68180. out.h /= 6;
  68181. }
  68182. return out;
  68183. },
  68184. /**
  68185. * Converts an HSL (hue, saturation and lightness) color value to RGB.
  68186. * Conversion forumla from http://en.wikipedia.org/wiki/HSL_color_space.
  68187. * Assumes HSL values are contained in the set [0, 1] and returns r, g and b values in the set [0, 255].
  68188. * Based on code by Michael Jackson (https://github.com/mjijackson)
  68189. *
  68190. * @method Phaser.Color.HSLtoRGB
  68191. * @static
  68192. * @param {number} h - The hue, in the range 0 - 1.
  68193. * @param {number} s - The saturation, in the range 0 - 1.
  68194. * @param {number} l - The lightness, in the range 0 - 1.
  68195. * @param {object} [out] - An object into which 3 properties will be created: r, g and b. If not provided a new object will be created.
  68196. * @return {object} An object with the red, green and blue values set in the r, g and b properties.
  68197. */
  68198. HSLtoRGB: function (h, s, l, out) {
  68199. if (!out)
  68200. {
  68201. out = Phaser.Color.createColor(l, l, l);
  68202. }
  68203. else
  68204. {
  68205. // achromatic by default
  68206. out.r = l;
  68207. out.g = l;
  68208. out.b = l;
  68209. }
  68210. if (s !== 0)
  68211. {
  68212. var q = l < 0.5 ? l * (1 + s) : l + s - l * s;
  68213. var p = 2 * l - q;
  68214. out.r = Phaser.Color.hueToColor(p, q, h + 1 / 3);
  68215. out.g = Phaser.Color.hueToColor(p, q, h);
  68216. out.b = Phaser.Color.hueToColor(p, q, h - 1 / 3);
  68217. }
  68218. // out.r = (out.r * 255 | 0);
  68219. // out.g = (out.g * 255 | 0);
  68220. // out.b = (out.b * 255 | 0);
  68221. out.r = Math.floor((out.r * 255 | 0));
  68222. out.g = Math.floor((out.g * 255 | 0));
  68223. out.b = Math.floor((out.b * 255 | 0));
  68224. Phaser.Color.updateColor(out);
  68225. return out;
  68226. },
  68227. /**
  68228. * Converts an RGB color value to HSV (hue, saturation and value).
  68229. * Conversion forumla from http://en.wikipedia.org/wiki/HSL_color_space.
  68230. * Assumes RGB values are contained in the set [0, 255] and returns h, s and v in the set [0, 1].
  68231. * Based on code by Michael Jackson (https://github.com/mjijackson)
  68232. *
  68233. * @method Phaser.Color.RGBtoHSV
  68234. * @static
  68235. * @param {number} r - The red color component, in the range 0 - 255.
  68236. * @param {number} g - The green color component, in the range 0 - 255.
  68237. * @param {number} b - The blue color component, in the range 0 - 255.
  68238. * @param {object} [out] - An object into which 3 properties will be created, h, s and v. If not provided a new object will be created.
  68239. * @return {object} An object with the hue, saturation and value set in the h, s and v properties.
  68240. */
  68241. RGBtoHSV: function (r, g, b, out) {
  68242. if (!out)
  68243. {
  68244. out = Phaser.Color.createColor(r, g, b, 255);
  68245. }
  68246. r /= 255;
  68247. g /= 255;
  68248. b /= 255;
  68249. var min = Math.min(r, g, b);
  68250. var max = Math.max(r, g, b);
  68251. var d = max - min;
  68252. // achromatic by default
  68253. out.h = 0;
  68254. out.s = max === 0 ? 0 : d / max;
  68255. out.v = max;
  68256. if (max !== min)
  68257. {
  68258. if (max === r)
  68259. {
  68260. out.h = (g - b) / d + (g < b ? 6 : 0);
  68261. }
  68262. else if (max === g)
  68263. {
  68264. out.h = (b - r) / d + 2;
  68265. }
  68266. else if (max === b)
  68267. {
  68268. out.h = (r - g) / d + 4;
  68269. }
  68270. out.h /= 6;
  68271. }
  68272. return out;
  68273. },
  68274. /**
  68275. * Converts an HSV (hue, saturation and value) color value to RGB.
  68276. * Conversion forumla from http://en.wikipedia.org/wiki/HSL_color_space.
  68277. * Assumes HSV values are contained in the set [0, 1] and returns r, g and b values in the set [0, 255].
  68278. * Based on code by Michael Jackson (https://github.com/mjijackson)
  68279. *
  68280. * @method Phaser.Color.HSVtoRGB
  68281. * @static
  68282. * @param {number} h - The hue, in the range 0 - 1.
  68283. * @param {number} s - The saturation, in the range 0 - 1.
  68284. * @param {number} v - The value, in the range 0 - 1.
  68285. * @param {object} [out] - An object into which 3 properties will be created: r, g and b. If not provided a new object will be created.
  68286. * @return {object} An object with the red, green and blue values set in the r, g and b properties.
  68287. */
  68288. HSVtoRGB: function (h, s, v, out) {
  68289. if (out === undefined) { out = Phaser.Color.createColor(0, 0, 0, 1, h, s, 0, v); }
  68290. var r, g, b;
  68291. var i = Math.floor(h * 6);
  68292. var f = h * 6 - i;
  68293. var p = v * (1 - s);
  68294. var q = v * (1 - f * s);
  68295. var t = v * (1 - (1 - f) * s);
  68296. switch (i % 6)
  68297. {
  68298. case 0:
  68299. r = v;
  68300. g = t;
  68301. b = p;
  68302. break;
  68303. case 1:
  68304. r = q;
  68305. g = v;
  68306. b = p;
  68307. break;
  68308. case 2:
  68309. r = p;
  68310. g = v;
  68311. b = t;
  68312. break;
  68313. case 3:
  68314. r = p;
  68315. g = q;
  68316. b = v;
  68317. break;
  68318. case 4:
  68319. r = t;
  68320. g = p;
  68321. b = v;
  68322. break;
  68323. case 5:
  68324. r = v;
  68325. g = p;
  68326. b = q;
  68327. break;
  68328. }
  68329. out.r = Math.floor(r * 255);
  68330. out.g = Math.floor(g * 255);
  68331. out.b = Math.floor(b * 255);
  68332. Phaser.Color.updateColor(out);
  68333. return out;
  68334. },
  68335. /**
  68336. * Converts a hue to an RGB color.
  68337. * Based on code by Michael Jackson (https://github.com/mjijackson)
  68338. *
  68339. * @method Phaser.Color.hueToColor
  68340. * @static
  68341. * @param {number} p
  68342. * @param {number} q
  68343. * @param {number} t
  68344. * @return {number} The color component value.
  68345. */
  68346. hueToColor: function (p, q, t) {
  68347. if (t < 0)
  68348. {
  68349. t += 1;
  68350. }
  68351. if (t > 1)
  68352. {
  68353. t -= 1;
  68354. }
  68355. if (t < 1 / 6)
  68356. {
  68357. return p + (q - p) * 6 * t;
  68358. }
  68359. if (t < 1 / 2)
  68360. {
  68361. return q;
  68362. }
  68363. if (t < 2 / 3)
  68364. {
  68365. return p + (q - p) * (2 / 3 - t) * 6;
  68366. }
  68367. return p;
  68368. },
  68369. /**
  68370. * A utility function to create a lightweight 'color' object with the default components.
  68371. * Any components that are not specified will default to zero.
  68372. *
  68373. * This is useful when you want to use a shared color object for the getPixel and getPixelAt methods.
  68374. *
  68375. * @author Matt DesLauriers (@mattdesl)
  68376. * @method Phaser.Color.createColor
  68377. * @static
  68378. * @param {number} [r=0] - The red color component, in the range 0 - 255.
  68379. * @param {number} [g=0] - The green color component, in the range 0 - 255.
  68380. * @param {number} [b=0] - The blue color component, in the range 0 - 255.
  68381. * @param {number} [a=1] - The alpha color component, in the range 0 - 1.
  68382. * @param {number} [h=0] - The hue, in the range 0 - 1.
  68383. * @param {number} [s=0] - The saturation, in the range 0 - 1.
  68384. * @param {number} [l=0] - The lightness, in the range 0 - 1.
  68385. * @param {number} [v=0] - The value, in the range 0 - 1.
  68386. * @return {object} The resulting object with r, g, b, a properties and h, s, l and v.
  68387. */
  68388. createColor: function (r, g, b, a, h, s, l, v) {
  68389. var out = { r: r || 0, g: g || 0, b: b || 0, a: a || 1, h: h || 0, s: s || 0, l: l || 0, v: v || 0, color: 0, color32: 0, rgba: '' };
  68390. return Phaser.Color.updateColor(out);
  68391. },
  68392. /**
  68393. * Takes a color object and updates the rgba, color and color32 properties.
  68394. *
  68395. * @method Phaser.Color.updateColor
  68396. * @static
  68397. * @param {object} out - The color object to update.
  68398. * @returns {number} A native color value integer (format: 0xAARRGGBB).
  68399. */
  68400. updateColor: function (out) {
  68401. out.rgba = 'rgba(' + out.r.toString() + ',' + out.g.toString() + ',' + out.b.toString() + ',' + out.a.toString() + ')';
  68402. out.color = Phaser.Color.getColor(out.r, out.g, out.b);
  68403. out.color32 = Phaser.Color.getColor32(out.a * 255, out.r, out.g, out.b);
  68404. return out;
  68405. },
  68406. /**
  68407. * Given an alpha and 3 color values this will return an integer representation of it.
  68408. *
  68409. * @method Phaser.Color.getColor32
  68410. * @static
  68411. * @param {number} a - The alpha color component, in the range 0 - 255.
  68412. * @param {number} r - The red color component, in the range 0 - 255.
  68413. * @param {number} g - The green color component, in the range 0 - 255.
  68414. * @param {number} b - The blue color component, in the range 0 - 255.
  68415. * @returns {number} A native color value integer (format: 0xAARRGGBB).
  68416. */
  68417. getColor32: function (a, r, g, b) {
  68418. return a << 24 | r << 16 | g << 8 | b;
  68419. },
  68420. /**
  68421. * Given 3 color values this will return an integer representation of it.
  68422. *
  68423. * @method Phaser.Color.getColor
  68424. * @static
  68425. * @param {number} r - The red color component, in the range 0 - 255.
  68426. * @param {number} g - The green color component, in the range 0 - 255.
  68427. * @param {number} b - The blue color component, in the range 0 - 255.
  68428. * @returns {number} A native color value integer (format: 0xRRGGBB).
  68429. */
  68430. getColor: function (r, g, b) {
  68431. return r << 16 | g << 8 | b;
  68432. },
  68433. /**
  68434. * Converts the given color values into a string.
  68435. * If prefix was '#' it will be in the format `#RRGGBB` otherwise `0xAARRGGBB`.
  68436. *
  68437. * @method Phaser.Color.RGBtoString
  68438. * @static
  68439. * @param {number} r - The red color component, in the range 0 - 255.
  68440. * @param {number} g - The green color component, in the range 0 - 255.
  68441. * @param {number} b - The blue color component, in the range 0 - 255.
  68442. * @param {number} [a=255] - The alpha color component, in the range 0 - 255.
  68443. * @param {string} [prefix='#'] - The prefix used in the return string. If '#' it will return `#RRGGBB`, else `0xAARRGGBB`.
  68444. * @return {string} A string containing the color values. If prefix was '#' it will be in the format `#RRGGBB` otherwise `0xAARRGGBB`.
  68445. */
  68446. RGBtoString: function (r, g, b, a, prefix) {
  68447. if (a === undefined) { a = 255; }
  68448. if (prefix === undefined) { prefix = '#'; }
  68449. if (prefix === '#')
  68450. {
  68451. return '#' + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
  68452. }
  68453. else
  68454. {
  68455. return '0x' + Phaser.Color.componentToHex(a) + Phaser.Color.componentToHex(r) + Phaser.Color.componentToHex(g) + Phaser.Color.componentToHex(b);
  68456. }
  68457. },
  68458. /**
  68459. * Converts a hex string into an integer color value.
  68460. *
  68461. * @method Phaser.Color.hexToRGB
  68462. * @static
  68463. * @param {string} hex - The hex string to convert. Can be in the short-hand format `#03f` or `#0033ff`.
  68464. * @return {number} The rgb color value in the format 0xAARRGGBB.
  68465. */
  68466. hexToRGB: function (hex) {
  68467. var rgb = Phaser.Color.hexToColor(hex);
  68468. if (rgb)
  68469. {
  68470. return Phaser.Color.getColor32(rgb.a, rgb.r, rgb.g, rgb.b);
  68471. }
  68472. },
  68473. /**
  68474. * Converts a hex string into a Phaser Color object.
  68475. *
  68476. * The hex string can supplied as `'#0033ff'` or the short-hand format of `'#03f'`; it can begin with an optional "#" or "0x", or be unprefixed.
  68477. *
  68478. * An alpha channel is _not_ supported.
  68479. *
  68480. * @method Phaser.Color.hexToColor
  68481. * @static
  68482. * @param {string} hex - The color string in a hex format.
  68483. * @param {object} [out] - An object into which 3 properties will be created or set: r, g and b. If not provided a new object will be created.
  68484. * @return {object} An object with the red, green and blue values set in the r, g and b properties.
  68485. */
  68486. hexToColor: function (hex, out) {
  68487. // Expand shorthand form (e.g. "03F") to full form (e.g. "0033FF")
  68488. hex = hex.replace(/^(?:#|0x)?([a-f\d])([a-f\d])([a-f\d])$/i, function(m, r, g, b) {
  68489. return r + r + g + g + b + b;
  68490. });
  68491. var result = /^(?:#|0x)?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
  68492. if (result)
  68493. {
  68494. var r = parseInt(result[1], 16);
  68495. var g = parseInt(result[2], 16);
  68496. var b = parseInt(result[3], 16);
  68497. if (!out)
  68498. {
  68499. out = Phaser.Color.createColor(r, g, b);
  68500. }
  68501. else
  68502. {
  68503. out.r = r;
  68504. out.g = g;
  68505. out.b = b;
  68506. }
  68507. }
  68508. return out;
  68509. },
  68510. /**
  68511. * Converts a CSS 'web' string into a Phaser Color object.
  68512. *
  68513. * The web string can be in the format `'rgb(r,g,b)'` or `'rgba(r,g,b,a)'` where r/g/b are in the range [0..255] and a is in the range [0..1].
  68514. *
  68515. * @method Phaser.Color.webToColor
  68516. * @static
  68517. * @param {string} web - The color string in CSS 'web' format.
  68518. * @param {object} [out] - An object into which 4 properties will be created: r, g, b and a. If not provided a new object will be created.
  68519. * @return {object} An object with the red, green, blue and alpha values set in the r, g, b and a properties.
  68520. */
  68521. webToColor: function (web, out) {
  68522. if (!out)
  68523. {
  68524. out = Phaser.Color.createColor();
  68525. }
  68526. var result = /^rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d+(?:\.\d+)?))?\s*\)$/.exec(web);
  68527. if (result)
  68528. {
  68529. out.r = parseInt(result[1], 10);
  68530. out.g = parseInt(result[2], 10);
  68531. out.b = parseInt(result[3], 10);
  68532. out.a = result[4] !== undefined ? parseFloat(result[4]) : 1;
  68533. Phaser.Color.updateColor(out);
  68534. }
  68535. return out;
  68536. },
  68537. /**
  68538. * Converts a value - a "hex" string, a "CSS 'web' string", or a number - into red, green, blue, and alpha components.
  68539. *
  68540. * The value can be a string (see `hexToColor` and `webToColor` for the supported formats) or a packed integer (see `getRGB`).
  68541. *
  68542. * An alpha channel is _not_ supported when specifying a hex string.
  68543. *
  68544. * @method Phaser.Color.valueToColor
  68545. * @static
  68546. * @param {string|number} value - The color expressed as a recognized string format or a packed integer.
  68547. * @param {object} [out] - The object to use for the output. If not provided a new object will be created.
  68548. * @return {object} The (`out`) object with the red, green, blue, and alpha values set as the r/g/b/a properties.
  68549. */
  68550. valueToColor: function (value, out) {
  68551. // The behavior is not consistent between hexToColor/webToColor on invalid input.
  68552. // This unifies both by returning a new object, but returning null may be better.
  68553. if (!out)
  68554. {
  68555. out = Phaser.Color.createColor();
  68556. }
  68557. if (typeof value === 'string')
  68558. {
  68559. if (value.indexOf('rgb') === 0)
  68560. {
  68561. return Phaser.Color.webToColor(value, out);
  68562. }
  68563. else
  68564. {
  68565. // `hexToColor` does not support alpha; match `createColor`.
  68566. out.a = 1;
  68567. return Phaser.Color.hexToColor(value, out);
  68568. }
  68569. }
  68570. else if (typeof value === 'number')
  68571. {
  68572. // `getRGB` does not take optional object to modify;
  68573. // alpha is also adjusted to match `createColor`.
  68574. var tempColor = Phaser.Color.getRGB(value);
  68575. out.r = tempColor.r;
  68576. out.g = tempColor.g;
  68577. out.b = tempColor.b;
  68578. out.a = tempColor.a / 255;
  68579. return out;
  68580. }
  68581. else
  68582. {
  68583. return out;
  68584. }
  68585. },
  68586. /**
  68587. * Return a string containing a hex representation of the given color component.
  68588. *
  68589. * @method Phaser.Color.componentToHex
  68590. * @static
  68591. * @param {number} color - The color channel to get the hex value for, must be a value between 0 and 255.
  68592. * @returns {string} A string of length 2 characters, i.e. 255 = ff, 100 = 64.
  68593. */
  68594. componentToHex: function (color) {
  68595. var hex = color.toString(16);
  68596. return (hex.length === 1) ? '0' + hex : hex;
  68597. },
  68598. /**
  68599. * Get HSV color wheel values in an array which will be 360 elements in size.
  68600. *
  68601. * @method Phaser.Color.HSVColorWheel
  68602. * @static
  68603. * @param {number} [s=1] - The saturation, in the range 0 - 1.
  68604. * @param {number} [v=1] - The value, in the range 0 - 1.
  68605. * @return {array} An array containing 360 elements corresponding to the HSV color wheel.
  68606. */
  68607. HSVColorWheel: function (s, v) {
  68608. if (s === undefined) { s = 1.0; }
  68609. if (v === undefined) { v = 1.0; }
  68610. var colors = [];
  68611. for (var c = 0; c <= 359; c++)
  68612. {
  68613. colors.push(Phaser.Color.HSVtoRGB(c / 359, s, v));
  68614. }
  68615. return colors;
  68616. },
  68617. /**
  68618. * Get HSL color wheel values in an array which will be 360 elements in size.
  68619. *
  68620. * @method Phaser.Color.HSLColorWheel
  68621. * @static
  68622. * @param {number} [s=0.5] - The saturation, in the range 0 - 1.
  68623. * @param {number} [l=0.5] - The lightness, in the range 0 - 1.
  68624. * @return {array} An array containing 360 elements corresponding to the HSL color wheel.
  68625. */
  68626. HSLColorWheel: function (s, l) {
  68627. if (s === undefined) { s = 0.5; }
  68628. if (l === undefined) { l = 0.5; }
  68629. var colors = [];
  68630. for (var c = 0; c <= 359; c++)
  68631. {
  68632. colors.push(Phaser.Color.HSLtoRGB(c / 359, s, l));
  68633. }
  68634. return colors;
  68635. },
  68636. /**
  68637. * Interpolates the two given colours based on the supplied step and currentStep properties.
  68638. *
  68639. * @method Phaser.Color.interpolateColor
  68640. * @static
  68641. * @param {number} color1 - The first color value.
  68642. * @param {number} color2 - The second color value.
  68643. * @param {number} steps - The number of steps to run the interpolation over.
  68644. * @param {number} currentStep - The currentStep value. If the interpolation will take 100 steps, a currentStep value of 50 would be half-way between the two.
  68645. * @param {number} alpha - The alpha of the returned color.
  68646. * @returns {number} The interpolated color value.
  68647. */
  68648. interpolateColor: function (color1, color2, steps, currentStep, alpha) {
  68649. if (alpha === undefined) { alpha = 255; }
  68650. var src1 = Phaser.Color.getRGB(color1);
  68651. var src2 = Phaser.Color.getRGB(color2);
  68652. var r = (((src2.red - src1.red) * currentStep) / steps) + src1.red;
  68653. var g = (((src2.green - src1.green) * currentStep) / steps) + src1.green;
  68654. var b = (((src2.blue - src1.blue) * currentStep) / steps) + src1.blue;
  68655. return Phaser.Color.getColor32(alpha, r, g, b);
  68656. },
  68657. /**
  68658. * Interpolates the two given colours based on the supplied step and currentStep properties.
  68659. *
  68660. * @method Phaser.Color.interpolateColorWithRGB
  68661. * @static
  68662. * @param {number} color - The first color value.
  68663. * @param {number} r - The red color value, between 0 and 0xFF (255).
  68664. * @param {number} g - The green color value, between 0 and 0xFF (255).
  68665. * @param {number} b - The blue color value, between 0 and 0xFF (255).
  68666. * @param {number} steps - The number of steps to run the interpolation over.
  68667. * @param {number} currentStep - The currentStep value. If the interpolation will take 100 steps, a currentStep value of 50 would be half-way between the two.
  68668. * @returns {number} The interpolated color value.
  68669. */
  68670. interpolateColorWithRGB: function (color, r, g, b, steps, currentStep) {
  68671. var src = Phaser.Color.getRGB(color);
  68672. var or = (((r - src.red) * currentStep) / steps) + src.red;
  68673. var og = (((g - src.green) * currentStep) / steps) + src.green;
  68674. var ob = (((b - src.blue) * currentStep) / steps) + src.blue;
  68675. return Phaser.Color.getColor(or, og, ob);
  68676. },
  68677. /**
  68678. * Interpolates the two given colours based on the supplied step and currentStep properties.
  68679. * @method Phaser.Color.interpolateRGB
  68680. * @static
  68681. * @param {number} r1 - The red color value, between 0 and 0xFF (255).
  68682. * @param {number} g1 - The green color value, between 0 and 0xFF (255).
  68683. * @param {number} b1 - The blue color value, between 0 and 0xFF (255).
  68684. * @param {number} r2 - The red color value, between 0 and 0xFF (255).
  68685. * @param {number} g2 - The green color value, between 0 and 0xFF (255).
  68686. * @param {number} b2 - The blue color value, between 0 and 0xFF (255).
  68687. * @param {number} steps - The number of steps to run the interpolation over.
  68688. * @param {number} currentStep - The currentStep value. If the interpolation will take 100 steps, a currentStep value of 50 would be half-way between the two.
  68689. * @returns {number} The interpolated color value.
  68690. */
  68691. interpolateRGB: function (r1, g1, b1, r2, g2, b2, steps, currentStep) {
  68692. var r = (((r2 - r1) * currentStep) / steps) + r1;
  68693. var g = (((g2 - g1) * currentStep) / steps) + g1;
  68694. var b = (((b2 - b1) * currentStep) / steps) + b1;
  68695. return Phaser.Color.getColor(r, g, b);
  68696. },
  68697. /**
  68698. * Returns a random color value between black and white
  68699. * Set the min value to start each channel from the given offset.
  68700. * Set the max value to restrict the maximum color used per channel.
  68701. *
  68702. * @method Phaser.Color.getRandomColor
  68703. * @static
  68704. * @param {number} [min=0] - The lowest value to use for the color.
  68705. * @param {number} [max=255] - The highest value to use for the color.
  68706. * @param {number} [alpha=255] - The alpha value of the returning color (default 255 = fully opaque).
  68707. * @returns {number} 32-bit color value with alpha.
  68708. */
  68709. getRandomColor: function (min, max, alpha) {
  68710. if (min === undefined) { min = 0; }
  68711. if (max === undefined) { max = 255; }
  68712. if (alpha === undefined) { alpha = 255; }
  68713. // Sanity checks
  68714. if (max > 255 || min > max)
  68715. {
  68716. return Phaser.Color.getColor(255, 255, 255);
  68717. }
  68718. var red = min + Math.round(Math.random() * (max - min));
  68719. var green = min + Math.round(Math.random() * (max - min));
  68720. var blue = min + Math.round(Math.random() * (max - min));
  68721. return Phaser.Color.getColor32(alpha, red, green, blue);
  68722. },
  68723. /**
  68724. * Return the component parts of a color as an Object with the properties alpha, red, green, blue.
  68725. *
  68726. * Alpha will only be set if it exist in the given color (0xAARRGGBB)
  68727. *
  68728. * @method Phaser.Color.getRGB
  68729. * @static
  68730. * @param {number} color - Color in RGB (0xRRGGBB) or ARGB format (0xAARRGGBB).
  68731. * @returns {object} An Object with properties: alpha, red, green, blue (also r, g, b and a). Alpha will only be present if a color value > 16777215 was given.
  68732. */
  68733. getRGB: function (color) {
  68734. if (color > 16777215)
  68735. {
  68736. // The color value has an alpha component
  68737. return {
  68738. alpha: color >>> 24,
  68739. red: color >> 16 & 0xFF,
  68740. green: color >> 8 & 0xFF,
  68741. blue: color & 0xFF,
  68742. a: color >>> 24,
  68743. r: color >> 16 & 0xFF,
  68744. g: color >> 8 & 0xFF,
  68745. b: color & 0xFF
  68746. };
  68747. }
  68748. else
  68749. {
  68750. return {
  68751. alpha: 255,
  68752. red: color >> 16 & 0xFF,
  68753. green: color >> 8 & 0xFF,
  68754. blue: color & 0xFF,
  68755. a: 255,
  68756. r: color >> 16 & 0xFF,
  68757. g: color >> 8 & 0xFF,
  68758. b: color & 0xFF
  68759. };
  68760. }
  68761. },
  68762. /**
  68763. * Returns a CSS friendly string value from the given color.
  68764. *
  68765. * @method Phaser.Color.getWebRGB
  68766. * @static
  68767. * @param {number|Object} color - Color in RGB (0xRRGGBB), ARGB format (0xAARRGGBB) or an Object with r, g, b, a properties.
  68768. * @returns {string} A string in the format: 'rgba(r,g,b,a)'
  68769. */
  68770. getWebRGB: function (color) {
  68771. if (typeof color === 'object')
  68772. {
  68773. return 'rgba(' + color.r.toString() + ',' + color.g.toString() + ',' + color.b.toString() + ',' + (color.a / 255).toString() + ')';
  68774. }
  68775. else
  68776. {
  68777. var rgb = Phaser.Color.getRGB(color);
  68778. return 'rgba(' + rgb.r.toString() + ',' + rgb.g.toString() + ',' + rgb.b.toString() + ',' + (rgb.a / 255).toString() + ')';
  68779. }
  68780. },
  68781. /**
  68782. * Given a native color value (in the format 0xAARRGGBB) this will return the Alpha component, as a value between 0 and 255.
  68783. *
  68784. * @method Phaser.Color.getAlpha
  68785. * @static
  68786. * @param {number} color - In the format 0xAARRGGBB.
  68787. * @returns {number} The Alpha component of the color, will be between 0 and 1 (0 being no Alpha (opaque), 1 full Alpha (transparent)).
  68788. */
  68789. getAlpha: function (color) {
  68790. return color >>> 24;
  68791. },
  68792. /**
  68793. * Given a native color value (in the format 0xAARRGGBB) this will return the Alpha component as a value between 0 and 1.
  68794. *
  68795. * @method Phaser.Color.getAlphaFloat
  68796. * @static
  68797. * @param {number} color - In the format 0xAARRGGBB.
  68798. * @returns {number} The Alpha component of the color, will be between 0 and 1 (0 being no Alpha (opaque), 1 full Alpha (transparent)).
  68799. */
  68800. getAlphaFloat: function (color) {
  68801. return (color >>> 24) / 255;
  68802. },
  68803. /**
  68804. * Given a native color value (in the format 0xAARRGGBB) this will return the Red component, as a value between 0 and 255.
  68805. *
  68806. * @method Phaser.Color.getRed
  68807. * @static
  68808. * @param {number} color In the format 0xAARRGGBB.
  68809. * @returns {number} The Red component of the color, will be between 0 and 255 (0 being no color, 255 full Red).
  68810. */
  68811. getRed: function (color) {
  68812. return color >> 16 & 0xFF;
  68813. },
  68814. /**
  68815. * Given a native color value (in the format 0xAARRGGBB) this will return the Green component, as a value between 0 and 255.
  68816. *
  68817. * @method Phaser.Color.getGreen
  68818. * @static
  68819. * @param {number} color - In the format 0xAARRGGBB.
  68820. * @returns {number} The Green component of the color, will be between 0 and 255 (0 being no color, 255 full Green).
  68821. */
  68822. getGreen: function (color) {
  68823. return color >> 8 & 0xFF;
  68824. },
  68825. /**
  68826. * Given a native color value (in the format 0xAARRGGBB) this will return the Blue component, as a value between 0 and 255.
  68827. *
  68828. * @method Phaser.Color.getBlue
  68829. * @static
  68830. * @param {number} color - In the format 0xAARRGGBB.
  68831. * @returns {number} The Blue component of the color, will be between 0 and 255 (0 being no color, 255 full Blue).
  68832. */
  68833. getBlue: function (color) {
  68834. return color & 0xFF;
  68835. },
  68836. /**
  68837. * Blends the source color, ignoring the backdrop.
  68838. *
  68839. * @method Phaser.Color.blendNormal
  68840. * @static
  68841. * @param {integer} a - The source color to blend, in the range 1 to 255.
  68842. * @param {integer} b - The backdrop color to blend, in the range 1 to 255.
  68843. * @returns {integer} The blended color value, in the range 1 to 255.
  68844. */
  68845. blendNormal: function (a) {
  68846. return a;
  68847. },
  68848. /**
  68849. * Selects the lighter of the backdrop and source colors.
  68850. *
  68851. * @method Phaser.Color.blendLighten
  68852. * @static
  68853. * @param {integer} a - The source color to blend, in the range 1 to 255.
  68854. * @param {integer} b - The backdrop color to blend, in the range 1 to 255.
  68855. * @returns {integer} The blended color value, in the range 1 to 255.
  68856. */
  68857. blendLighten: function (a, b) {
  68858. return (b > a) ? b : a;
  68859. },
  68860. /**
  68861. * Selects the darker of the backdrop and source colors.
  68862. *
  68863. * @method Phaser.Color.blendDarken
  68864. * @static
  68865. * @param {integer} a - The source color to blend, in the range 1 to 255.
  68866. * @param {integer} b - The backdrop color to blend, in the range 1 to 255.
  68867. * @returns {integer} The blended color value, in the range 1 to 255.
  68868. */
  68869. blendDarken: function (a, b) {
  68870. return (b > a) ? a : b;
  68871. },
  68872. /**
  68873. * Multiplies the backdrop and source color values.
  68874. * The result color is always at least as dark as either of the two constituent
  68875. * colors. Multiplying any color with black produces black;
  68876. * multiplying with white leaves the original color unchanged.
  68877. *
  68878. * @method Phaser.Color.blendMultiply
  68879. * @static
  68880. * @param {integer} a - The source color to blend, in the range 1 to 255.
  68881. * @param {integer} b - The backdrop color to blend, in the range 1 to 255.
  68882. * @returns {integer} The blended color value, in the range 1 to 255.
  68883. */
  68884. blendMultiply: function (a, b) {
  68885. return (a * b) / 255;
  68886. },
  68887. /**
  68888. * Takes the average of the source and backdrop colors.
  68889. *
  68890. * @method Phaser.Color.blendAverage
  68891. * @static
  68892. * @param {integer} a - The source color to blend, in the range 1 to 255.
  68893. * @param {integer} b - The backdrop color to blend, in the range 1 to 255.
  68894. * @returns {integer} The blended color value, in the range 1 to 255.
  68895. */
  68896. blendAverage: function (a, b) {
  68897. return (a + b) / 2;
  68898. },
  68899. /**
  68900. * Adds the source and backdrop colors together and returns the value, up to a maximum of 255.
  68901. *
  68902. * @method Phaser.Color.blendAdd
  68903. * @static
  68904. * @param {integer} a - The source color to blend, in the range 1 to 255.
  68905. * @param {integer} b - The backdrop color to blend, in the range 1 to 255.
  68906. * @returns {integer} The blended color value, in the range 1 to 255.
  68907. */
  68908. blendAdd: function (a, b) {
  68909. return Math.min(255, a + b);
  68910. },
  68911. /**
  68912. * Combines the source and backdrop colors and returns their value minus 255.
  68913. *
  68914. * @method Phaser.Color.blendSubtract
  68915. * @static
  68916. * @param {integer} a - The source color to blend, in the range 1 to 255.
  68917. * @param {integer} b - The backdrop color to blend, in the range 1 to 255.
  68918. * @returns {integer} The blended color value, in the range 1 to 255.
  68919. */
  68920. blendSubtract: function (a, b) {
  68921. return Math.max(0, a + b - 255);
  68922. },
  68923. /**
  68924. * Subtracts the darker of the two constituent colors from the lighter.
  68925. *
  68926. * Painting with white inverts the backdrop color; painting with black produces no change.
  68927. *
  68928. * @method Phaser.Color.blendDifference
  68929. * @static
  68930. * @param {integer} a - The source color to blend, in the range 1 to 255.
  68931. * @param {integer} b - The backdrop color to blend, in the range 1 to 255.
  68932. * @returns {integer} The blended color value, in the range 1 to 255.
  68933. */
  68934. blendDifference: function (a, b) {
  68935. return Math.abs(a - b);
  68936. },
  68937. /**
  68938. * Negation blend mode.
  68939. *
  68940. * @method Phaser.Color.blendNegation
  68941. * @static
  68942. * @param {integer} a - The source color to blend, in the range 1 to 255.
  68943. * @param {integer} b - The backdrop color to blend, in the range 1 to 255.
  68944. * @returns {integer} The blended color value, in the range 1 to 255.
  68945. */
  68946. blendNegation: function (a, b) {
  68947. return 255 - Math.abs(255 - a - b);
  68948. },
  68949. /**
  68950. * Multiplies the complements of the backdrop and source color values, then complements the result.
  68951. * The result color is always at least as light as either of the two constituent colors.
  68952. * Screening any color with white produces white; screening with black leaves the original color unchanged.
  68953. *
  68954. * @method Phaser.Color.blendScreen
  68955. * @static
  68956. * @param {integer} a - The source color to blend, in the range 1 to 255.
  68957. * @param {integer} b - The backdrop color to blend, in the range 1 to 255.
  68958. * @returns {integer} The blended color value, in the range 1 to 255.
  68959. */
  68960. blendScreen: function (a, b) {
  68961. return 255 - (((255 - a) * (255 - b)) >> 8);
  68962. },
  68963. /**
  68964. * Produces an effect similar to that of the Difference mode, but lower in contrast.
  68965. * Painting with white inverts the backdrop color; painting with black produces no change.
  68966. *
  68967. * @method Phaser.Color.blendExclusion
  68968. * @static
  68969. * @param {integer} a - The source color to blend, in the range 1 to 255.
  68970. * @param {integer} b - The backdrop color to blend, in the range 1 to 255.
  68971. * @returns {integer} The blended color value, in the range 1 to 255.
  68972. */
  68973. blendExclusion: function (a, b) {
  68974. return a + b - 2 * a * b / 255;
  68975. },
  68976. /**
  68977. * Multiplies or screens the colors, depending on the backdrop color.
  68978. * Source colors overlay the backdrop while preserving its highlights and shadows.
  68979. * The backdrop color is not replaced, but is mixed with the source color to reflect the lightness or darkness of the backdrop.
  68980. *
  68981. * @method Phaser.Color.blendOverlay
  68982. * @static
  68983. * @param {integer} a - The source color to blend, in the range 1 to 255.
  68984. * @param {integer} b - The backdrop color to blend, in the range 1 to 255.
  68985. * @returns {integer} The blended color value, in the range 1 to 255.
  68986. */
  68987. blendOverlay: function (a, b) {
  68988. return b < 128 ? (2 * a * b / 255) : (255 - 2 * (255 - a) * (255 - b) / 255);
  68989. },
  68990. /**
  68991. * Darkens or lightens the colors, depending on the source color value.
  68992. *
  68993. * If the source color is lighter than 0.5, the backdrop is lightened, as if it were dodged;
  68994. * this is useful for adding highlights to a scene.
  68995. *
  68996. * If the source color is darker than 0.5, the backdrop is darkened, as if it were burned in.
  68997. * The degree of lightening or darkening is proportional to the difference between the source color and 0.5;
  68998. * if it is equal to 0.5, the backdrop is unchanged.
  68999. *
  69000. * Painting with pure black or white produces a distinctly darker or lighter area, but does not result in pure black or white.
  69001. * The effect is similar to shining a diffused spotlight on the backdrop.
  69002. *
  69003. * @method Phaser.Color.blendSoftLight
  69004. * @static
  69005. * @param {integer} a - The source color to blend, in the range 1 to 255.
  69006. * @param {integer} b - The backdrop color to blend, in the range 1 to 255.
  69007. * @returns {integer} The blended color value, in the range 1 to 255.
  69008. */
  69009. blendSoftLight: function (a, b) {
  69010. return b < 128 ? (2 * ((a >> 1) + 64)) * (b / 255) : 255 - (2 * (255 - ((a >> 1) + 64)) * (255 - b) / 255);
  69011. },
  69012. /**
  69013. * Multiplies or screens the colors, depending on the source color value.
  69014. *
  69015. * If the source color is lighter than 0.5, the backdrop is lightened, as if it were screened;
  69016. * this is useful for adding highlights to a scene.
  69017. *
  69018. * If the source color is darker than 0.5, the backdrop is darkened, as if it were multiplied;
  69019. * this is useful for adding shadows to a scene.
  69020. *
  69021. * The degree of lightening or darkening is proportional to the difference between the source color and 0.5;
  69022. * if it is equal to 0.5, the backdrop is unchanged.
  69023. *
  69024. * Painting with pure black or white produces pure black or white. The effect is similar to shining a harsh spotlight on the backdrop.
  69025. *
  69026. * @method Phaser.Color.blendHardLight
  69027. * @static
  69028. * @param {integer} a - The source color to blend, in the range 1 to 255.
  69029. * @param {integer} b - The backdrop color to blend, in the range 1 to 255.
  69030. * @returns {integer} The blended color value, in the range 1 to 255.
  69031. */
  69032. blendHardLight: function (a, b) {
  69033. return Phaser.Color.blendOverlay(b, a);
  69034. },
  69035. /**
  69036. * Brightens the backdrop color to reflect the source color.
  69037. * Painting with black produces no change.
  69038. *
  69039. * @method Phaser.Color.blendColorDodge
  69040. * @static
  69041. * @param {integer} a - The source color to blend, in the range 1 to 255.
  69042. * @param {integer} b - The backdrop color to blend, in the range 1 to 255.
  69043. * @returns {integer} The blended color value, in the range 1 to 255.
  69044. */
  69045. blendColorDodge: function (a, b) {
  69046. return b === 255 ? b : Math.min(255, ((a << 8) / (255 - b)));
  69047. },
  69048. /**
  69049. * Darkens the backdrop color to reflect the source color.
  69050. * Painting with white produces no change.
  69051. *
  69052. * @method Phaser.Color.blendColorBurn
  69053. * @static
  69054. * @param {integer} a - The source color to blend, in the range 1 to 255.
  69055. * @param {integer} b - The backdrop color to blend, in the range 1 to 255.
  69056. * @returns {integer} The blended color value, in the range 1 to 255.
  69057. */
  69058. blendColorBurn: function (a, b) {
  69059. return b === 0 ? b : Math.max(0, (255 - ((255 - a) << 8) / b));
  69060. },
  69061. /**
  69062. * An alias for blendAdd, it simply sums the values of the two colors.
  69063. *
  69064. * @method Phaser.Color.blendLinearDodge
  69065. * @static
  69066. * @param {integer} a - The source color to blend, in the range 1 to 255.
  69067. * @param {integer} b - The backdrop color to blend, in the range 1 to 255.
  69068. * @returns {integer} The blended color value, in the range 1 to 255.
  69069. */
  69070. blendLinearDodge: function (a, b) {
  69071. return Phaser.Color.blendAdd(a, b);
  69072. },
  69073. /**
  69074. * An alias for blendSubtract, it simply sums the values of the two colors and subtracts 255.
  69075. *
  69076. * @method Phaser.Color.blendLinearBurn
  69077. * @static
  69078. * @param {integer} a - The source color to blend, in the range 1 to 255.
  69079. * @param {integer} b - The backdrop color to blend, in the range 1 to 255.
  69080. * @returns {integer} The blended color value, in the range 1 to 255.
  69081. */
  69082. blendLinearBurn: function (a, b) {
  69083. return Phaser.Color.blendSubtract(a, b);
  69084. },
  69085. /**
  69086. * This blend mode combines Linear Dodge and Linear Burn (rescaled so that neutral colors become middle gray).
  69087. * Dodge applies to values of top layer lighter than middle gray, and burn to darker values.
  69088. * The calculation simplifies to the sum of bottom layer and twice the top layer, subtract 128. The contrast decreases.
  69089. *
  69090. * @method Phaser.Color.blendLinearLight
  69091. * @static
  69092. * @param {integer} a - The source color to blend, in the range 1 to 255.
  69093. * @param {integer} b - The backdrop color to blend, in the range 1 to 255.
  69094. * @returns {integer} The blended color value, in the range 1 to 255.
  69095. */
  69096. blendLinearLight: function (a, b) {
  69097. return b < 128 ? Phaser.Color.blendLinearBurn(a, 2 * b) : Phaser.Color.blendLinearDodge(a, (2 * (b - 128)));
  69098. },
  69099. /**
  69100. * This blend mode combines Color Dodge and Color Burn (rescaled so that neutral colors become middle gray).
  69101. * Dodge applies when values in the top layer are lighter than middle gray, and burn to darker values.
  69102. * The middle gray is the neutral color. When color is lighter than this, this effectively moves the white point of the bottom
  69103. * layer down by twice the difference; when it is darker, the black point is moved up by twice the difference. The perceived contrast increases.
  69104. *
  69105. * @method Phaser.Color.blendVividLight
  69106. * @static
  69107. * @param {integer} a - The source color to blend, in the range 1 to 255.
  69108. * @param {integer} b - The backdrop color to blend, in the range 1 to 255.
  69109. * @returns {integer} The blended color value, in the range 1 to 255.
  69110. */
  69111. blendVividLight: function (a, b) {
  69112. return b < 128 ? Phaser.Color.blendColorBurn(a, 2 * b) : Phaser.Color.blendColorDodge(a, (2 * (b - 128)));
  69113. },
  69114. /**
  69115. * If the backdrop color (light source) is lighter than 50%, the blendDarken mode is used, and colors lighter than the backdrop color do not change.
  69116. * If the backdrop color is darker than 50% gray, colors lighter than the blend color are replaced, and colors darker than the blend color do not change.
  69117. *
  69118. * @method Phaser.Color.blendPinLight
  69119. * @static
  69120. * @param {integer} a - The source color to blend, in the range 1 to 255.
  69121. * @param {integer} b - The backdrop color to blend, in the range 1 to 255.
  69122. * @returns {integer} The blended color value, in the range 1 to 255.
  69123. */
  69124. blendPinLight: function (a, b) {
  69125. return b < 128 ? Phaser.Color.blendDarken(a, 2 * b) : Phaser.Color.blendLighten(a, (2 * (b - 128)));
  69126. },
  69127. /**
  69128. * Runs blendVividLight on the source and backdrop colors.
  69129. * If the resulting color is 128 or more, it receives a value of 255; if less than 128, a value of 0.
  69130. * Therefore, all blended pixels have red, green, and blue channel values of either 0 or 255.
  69131. * This changes all pixels to primary additive colors (red, green, or blue), white, or black.
  69132. *
  69133. * @method Phaser.Color.blendHardMix
  69134. * @static
  69135. * @param {integer} a - The source color to blend, in the range 1 to 255.
  69136. * @param {integer} b - The backdrop color to blend, in the range 1 to 255.
  69137. * @returns {integer} The blended color value, in the range 1 to 255.
  69138. */
  69139. blendHardMix: function (a, b) {
  69140. return Phaser.Color.blendVividLight(a, b) < 128 ? 0 : 255;
  69141. },
  69142. /**
  69143. * Reflect blend mode. This mode is useful when adding shining objects or light zones to images.
  69144. *
  69145. * @method Phaser.Color.blendReflect
  69146. * @static
  69147. * @param {integer} a - The source color to blend, in the range 1 to 255.
  69148. * @param {integer} b - The backdrop color to blend, in the range 1 to 255.
  69149. * @returns {integer} The blended color value, in the range 1 to 255.
  69150. */
  69151. blendReflect: function (a, b) {
  69152. return b === 255 ? b : Math.min(255, (a * a / (255 - b)));
  69153. },
  69154. /**
  69155. * Glow blend mode. This mode is a variation of reflect mode with the source and backdrop colors swapped.
  69156. *
  69157. * @method Phaser.Color.blendGlow
  69158. * @static
  69159. * @param {integer} a - The source color to blend, in the range 1 to 255.
  69160. * @param {integer} b - The backdrop color to blend, in the range 1 to 255.
  69161. * @returns {integer} The blended color value, in the range 1 to 255.
  69162. */
  69163. blendGlow: function (a, b) {
  69164. return Phaser.Color.blendReflect(b, a);
  69165. },
  69166. /**
  69167. * Phoenix blend mode. This subtracts the lighter color from the darker color, and adds 255, giving a bright result.
  69168. *
  69169. * @method Phaser.Color.blendPhoenix
  69170. * @static
  69171. * @param {integer} a - The source color to blend, in the range 1 to 255.
  69172. * @param {integer} b - The backdrop color to blend, in the range 1 to 255.
  69173. * @returns {integer} The blended color value, in the range 1 to 255.
  69174. */
  69175. blendPhoenix: function (a, b) {
  69176. return Math.min(a, b) - Math.max(a, b) + 255;
  69177. }
  69178. };
  69179. /**
  69180. * @author Richard Davey <rich@photonstorm.com>
  69181. * @copyright 2016 Photon Storm Ltd.
  69182. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  69183. */
  69184. /**
  69185. * The Physics Manager is responsible for looking after all of the running physics systems.
  69186. * Phaser supports 4 physics systems: Arcade Physics, P2, Ninja Physics and Box2D via a commercial plugin.
  69187. *
  69188. * Game Objects (such as Sprites) can only belong to 1 physics system, but you can have multiple systems active in a single game.
  69189. *
  69190. * For example you could have P2 managing a polygon-built terrain landscape that an vehicle drives over, while it could be firing bullets that use the
  69191. * faster (due to being much simpler) Arcade Physics system.
  69192. *
  69193. * @class Phaser.Physics
  69194. * @constructor
  69195. * @param {Phaser.Game} game - A reference to the currently running game.
  69196. * @param {object} [physicsConfig=null] - A physics configuration object to pass to the Physics world on creation.
  69197. */
  69198. Phaser.Physics = function (game, config) {
  69199. config = config || {};
  69200. /**
  69201. * @property {Phaser.Game} game - Local reference to game.
  69202. */
  69203. this.game = game;
  69204. /**
  69205. * @property {object} config - The physics configuration object as passed to the game on creation.
  69206. */
  69207. this.config = config;
  69208. /**
  69209. * @property {Phaser.Physics.Arcade} arcade - The Arcade Physics system.
  69210. */
  69211. this.arcade = null;
  69212. /**
  69213. * @property {Phaser.Physics.P2} p2 - The P2.JS Physics system.
  69214. */
  69215. this.p2 = null;
  69216. /**
  69217. * @property {Phaser.Physics.Ninja} ninja - The N+ Ninja Physics system.
  69218. */
  69219. this.ninja = null;
  69220. /**
  69221. * @property {Phaser.Physics.Box2D} box2d - The Box2D Physics system.
  69222. */
  69223. this.box2d = null;
  69224. /**
  69225. * @property {Phaser.Physics.Chipmunk} chipmunk - The Chipmunk Physics system (to be done).
  69226. */
  69227. this.chipmunk = null;
  69228. /**
  69229. * @property {Phaser.Physics.Matter} matter - The MatterJS Physics system (coming soon).
  69230. */
  69231. this.matter = null;
  69232. this.parseConfig();
  69233. };
  69234. /**
  69235. * @const
  69236. * @type {number}
  69237. */
  69238. Phaser.Physics.ARCADE = 0;
  69239. /**
  69240. * @const
  69241. * @type {number}
  69242. */
  69243. Phaser.Physics.P2JS = 1;
  69244. /**
  69245. * @const
  69246. * @type {number}
  69247. */
  69248. Phaser.Physics.NINJA = 2;
  69249. /**
  69250. * @const
  69251. * @type {number}
  69252. */
  69253. Phaser.Physics.BOX2D = 3;
  69254. /**
  69255. * @const
  69256. * @type {number}
  69257. */
  69258. Phaser.Physics.CHIPMUNK = 4;
  69259. /**
  69260. * @const
  69261. * @type {number}
  69262. */
  69263. Phaser.Physics.MATTERJS = 5;
  69264. Phaser.Physics.prototype = {
  69265. /**
  69266. * Parses the Physics Configuration object passed to the Game constructor and starts any physics systems specified within.
  69267. *
  69268. * @method Phaser.Physics#parseConfig
  69269. */
  69270. parseConfig: function () {
  69271. if ((!this.config.hasOwnProperty('arcade') || this.config['arcade'] === true) && Phaser.Physics.hasOwnProperty('Arcade'))
  69272. {
  69273. // If Arcade isn't specified, we create it automatically if we can
  69274. this.arcade = new Phaser.Physics.Arcade(this.game);
  69275. }
  69276. if (this.config.hasOwnProperty('ninja') && this.config['ninja'] === true && Phaser.Physics.hasOwnProperty('Ninja'))
  69277. {
  69278. this.ninja = new Phaser.Physics.Ninja(this.game);
  69279. }
  69280. if (this.config.hasOwnProperty('p2') && this.config['p2'] === true && Phaser.Physics.hasOwnProperty('P2'))
  69281. {
  69282. this.p2 = new Phaser.Physics.P2(this.game, this.config);
  69283. }
  69284. if (this.config.hasOwnProperty('box2d') && this.config['box2d'] === true && Phaser.Physics.hasOwnProperty('BOX2D'))
  69285. {
  69286. this.box2d = new Phaser.Physics.BOX2D(this.game, this.config);
  69287. }
  69288. if (this.config.hasOwnProperty('matter') && this.config['matter'] === true && Phaser.Physics.hasOwnProperty('Matter'))
  69289. {
  69290. this.matter = new Phaser.Physics.Matter(this.game, this.config);
  69291. }
  69292. },
  69293. /**
  69294. * This will create an instance of the requested physics simulation.
  69295. * Phaser.Physics.Arcade is running by default, but all others need activating directly.
  69296. *
  69297. * You can start the following physics systems:
  69298. *
  69299. * Phaser.Physics.P2JS - A full-body advanced physics system by Stefan Hedman.
  69300. * Phaser.Physics.NINJA - A port of Metanet Softwares N+ physics system.
  69301. * Phaser.Physics.BOX2D - A commercial Phaser Plugin (see http://phaser.io)
  69302. *
  69303. * Both Ninja Physics and Box2D require their respective plugins to be loaded before you can start them.
  69304. * They are not bundled into the core Phaser library.
  69305. *
  69306. * If the physics world has already been created (i.e. in another state in your game) then
  69307. * calling startSystem will reset the physics world, not re-create it. If you need to start them again from their constructors
  69308. * then set Phaser.Physics.p2 (or whichever system you want to recreate) to `null` before calling `startSystem`.
  69309. *
  69310. * @method Phaser.Physics#startSystem
  69311. * @param {number} system - The physics system to start: Phaser.Physics.ARCADE, Phaser.Physics.P2JS, Phaser.Physics.NINJA or Phaser.Physics.BOX2D.
  69312. */
  69313. startSystem: function (system) {
  69314. if (system === Phaser.Physics.ARCADE)
  69315. {
  69316. this.arcade = new Phaser.Physics.Arcade(this.game);
  69317. }
  69318. else if (system === Phaser.Physics.P2JS)
  69319. {
  69320. if (this.p2 === null)
  69321. {
  69322. this.p2 = new Phaser.Physics.P2(this.game, this.config);
  69323. }
  69324. else
  69325. {
  69326. this.p2.reset();
  69327. }
  69328. }
  69329. else if (system === Phaser.Physics.NINJA)
  69330. {
  69331. this.ninja = new Phaser.Physics.Ninja(this.game);
  69332. }
  69333. else if (system === Phaser.Physics.BOX2D)
  69334. {
  69335. if (this.box2d === null)
  69336. {
  69337. this.box2d = new Phaser.Physics.Box2D(this.game, this.config);
  69338. }
  69339. else
  69340. {
  69341. this.box2d.reset();
  69342. }
  69343. }
  69344. else if (system === Phaser.Physics.MATTERJS)
  69345. {
  69346. if (this.matter === null)
  69347. {
  69348. this.matter = new Phaser.Physics.Matter(this.game, this.config);
  69349. }
  69350. else
  69351. {
  69352. this.matter.reset();
  69353. }
  69354. }
  69355. },
  69356. /**
  69357. * This will create a default physics body on the given game object or array of objects.
  69358. * A game object can only have 1 physics body active at any one time, and it can't be changed until the object is destroyed.
  69359. * It can be for any of the physics systems that have been started:
  69360. *
  69361. * Phaser.Physics.Arcade - A light weight AABB based collision system with basic separation.
  69362. * Phaser.Physics.P2JS - A full-body advanced physics system supporting multiple object shapes, polygon loading, contact materials, springs and constraints.
  69363. * Phaser.Physics.NINJA - A port of Metanet Softwares N+ physics system. Advanced AABB and Circle vs. Tile collision.
  69364. * Phaser.Physics.BOX2D - A port of https://code.google.com/p/box2d-html5
  69365. * Phaser.Physics.MATTER - A full-body and light-weight advanced physics system (still in development)
  69366. * Phaser.Physics.CHIPMUNK is still in development.
  69367. *
  69368. * If you require more control over what type of body is created, for example to create a Ninja Physics Circle instead of the default AABB, then see the
  69369. * individual physics systems `enable` methods instead of using this generic one.
  69370. *
  69371. * @method Phaser.Physics#enable
  69372. * @param {object|array} object - The game object to create the physics body on. Can also be an array of objects, a body will be created on every object in the array.
  69373. * @param {number} [system=Phaser.Physics.ARCADE] - The physics system that will be used to create the body. Defaults to Arcade Physics.
  69374. * @param {boolean} [debug=false] - Enable the debug drawing for this body. Defaults to false.
  69375. */
  69376. enable: function (object, system, debug) {
  69377. if (system === undefined) { system = Phaser.Physics.ARCADE; }
  69378. if (debug === undefined) { debug = false; }
  69379. if (system === Phaser.Physics.ARCADE)
  69380. {
  69381. this.arcade.enable(object);
  69382. }
  69383. else if (system === Phaser.Physics.P2JS && this.p2)
  69384. {
  69385. this.p2.enable(object, debug);
  69386. }
  69387. else if (system === Phaser.Physics.NINJA && this.ninja)
  69388. {
  69389. this.ninja.enableAABB(object);
  69390. }
  69391. else if (system === Phaser.Physics.BOX2D && this.box2d)
  69392. {
  69393. this.box2d.enable(object);
  69394. }
  69395. else if (system === Phaser.Physics.MATTERJS && this.matter)
  69396. {
  69397. this.matter.enable(object);
  69398. }
  69399. else
  69400. {
  69401. console.warn(object.key + ' is attempting to enable a physics body using an unknown physics system.');
  69402. }
  69403. },
  69404. /**
  69405. * preUpdate checks.
  69406. *
  69407. * @method Phaser.Physics#preUpdate
  69408. * @protected
  69409. */
  69410. preUpdate: function () {
  69411. // ArcadePhysics / Ninja don't have a core to preUpdate
  69412. if (this.p2)
  69413. {
  69414. this.p2.preUpdate();
  69415. }
  69416. if (this.box2d)
  69417. {
  69418. this.box2d.preUpdate();
  69419. }
  69420. if (this.matter)
  69421. {
  69422. this.matter.preUpdate();
  69423. }
  69424. },
  69425. /**
  69426. * Updates all running physics systems.
  69427. *
  69428. * @method Phaser.Physics#update
  69429. * @protected
  69430. */
  69431. update: function () {
  69432. // ArcadePhysics / Ninja don't have a core to update
  69433. if (this.p2)
  69434. {
  69435. this.p2.update();
  69436. }
  69437. if (this.box2d)
  69438. {
  69439. this.box2d.update();
  69440. }
  69441. if (this.matter)
  69442. {
  69443. this.matter.update();
  69444. }
  69445. },
  69446. /**
  69447. * Updates the physics bounds to match the world dimensions.
  69448. *
  69449. * @method Phaser.Physics#setBoundsToWorld
  69450. * @protected
  69451. */
  69452. setBoundsToWorld: function () {
  69453. if (this.arcade)
  69454. {
  69455. this.arcade.setBoundsToWorld();
  69456. }
  69457. if (this.ninja)
  69458. {
  69459. this.ninja.setBoundsToWorld();
  69460. }
  69461. if (this.p2)
  69462. {
  69463. this.p2.setBoundsToWorld();
  69464. }
  69465. if (this.box2d)
  69466. {
  69467. this.box2d.setBoundsToWorld();
  69468. }
  69469. if (this.matter)
  69470. {
  69471. this.matter.setBoundsToWorld();
  69472. }
  69473. },
  69474. /**
  69475. * Clears down all active physics systems. This doesn't destroy them, it just clears them of objects and is called when the State changes.
  69476. *
  69477. * @method Phaser.Physics#clear
  69478. * @protected
  69479. */
  69480. clear: function () {
  69481. if (this.p2)
  69482. {
  69483. this.p2.clear();
  69484. }
  69485. if (this.box2d)
  69486. {
  69487. this.box2d.clear();
  69488. }
  69489. if (this.matter)
  69490. {
  69491. this.matter.clear();
  69492. }
  69493. },
  69494. /**
  69495. * Resets the active physics system. Called automatically on a Phaser.State swap.
  69496. *
  69497. * @method Phaser.Physics#reset
  69498. * @protected
  69499. */
  69500. reset: function () {
  69501. if (this.p2)
  69502. {
  69503. this.p2.reset();
  69504. }
  69505. if (this.box2d)
  69506. {
  69507. this.box2d.reset();
  69508. }
  69509. if (this.matter)
  69510. {
  69511. this.matter.reset();
  69512. }
  69513. },
  69514. /**
  69515. * Destroys all active physics systems. Usually only called on a Game Shutdown, not on a State swap.
  69516. *
  69517. * @method Phaser.Physics#destroy
  69518. */
  69519. destroy: function () {
  69520. if (this.p2)
  69521. {
  69522. this.p2.destroy();
  69523. }
  69524. if (this.box2d)
  69525. {
  69526. this.box2d.destroy();
  69527. }
  69528. if (this.matter)
  69529. {
  69530. this.matter.destroy();
  69531. }
  69532. this.arcade = null;
  69533. this.ninja = null;
  69534. this.p2 = null;
  69535. this.box2d = null;
  69536. this.matter = null;
  69537. }
  69538. };
  69539. Phaser.Physics.prototype.constructor = Phaser.Physics;
  69540. /**
  69541. * @author Richard Davey <rich@photonstorm.com>
  69542. * @copyright 2016 Photon Storm Ltd.
  69543. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  69544. */
  69545. /**
  69546. * The Arcade Physics world. Contains Arcade Physics related collision, overlap and motion methods.
  69547. *
  69548. * @class Phaser.Physics.Arcade
  69549. * @constructor
  69550. * @param {Phaser.Game} game - reference to the current game instance.
  69551. */
  69552. Phaser.Physics.Arcade = function (game) {
  69553. /**
  69554. * @property {Phaser.Game} game - Local reference to game.
  69555. */
  69556. this.game = game;
  69557. /**
  69558. * @property {Phaser.Point} gravity - The World gravity setting. Defaults to x: 0, y: 0, or no gravity.
  69559. */
  69560. this.gravity = new Phaser.Point();
  69561. /**
  69562. * @property {Phaser.Rectangle} bounds - The bounds inside of which the physics world exists. Defaults to match the world bounds.
  69563. */
  69564. this.bounds = new Phaser.Rectangle(0, 0, game.world.width, game.world.height);
  69565. /**
  69566. * Set the checkCollision properties to control for which bounds collision is processed.
  69567. * For example checkCollision.down = false means Bodies cannot collide with the World.bounds.bottom.
  69568. * @property {object} checkCollision - An object containing allowed collision flags.
  69569. */
  69570. this.checkCollision = { up: true, down: true, left: true, right: true };
  69571. /**
  69572. * @property {number} maxObjects - Used by the QuadTree to set the maximum number of objects per quad.
  69573. */
  69574. this.maxObjects = 10;
  69575. /**
  69576. * @property {number} maxLevels - Used by the QuadTree to set the maximum number of iteration levels.
  69577. */
  69578. this.maxLevels = 4;
  69579. /**
  69580. * @property {number} OVERLAP_BIAS - A value added to the delta values during collision checks.
  69581. */
  69582. this.OVERLAP_BIAS = 4;
  69583. /**
  69584. * @property {boolean} forceX - If true World.separate will always separate on the X axis before Y. Otherwise it will check gravity totals first.
  69585. */
  69586. this.forceX = false;
  69587. /**
  69588. * @property {number} sortDirection - Used when colliding a Sprite vs. a Group, or a Group vs. a Group, this defines the direction the sort is based on. Default is Phaser.Physics.Arcade.LEFT_RIGHT.
  69589. * @default
  69590. */
  69591. this.sortDirection = Phaser.Physics.Arcade.LEFT_RIGHT;
  69592. /**
  69593. * @property {boolean} skipQuadTree - If true the QuadTree will not be used for any collision. QuadTrees are great if objects are well spread out in your game, otherwise they are a performance hit. If you enable this you can disable on a per body basis via `Body.skipQuadTree`.
  69594. */
  69595. this.skipQuadTree = true;
  69596. /**
  69597. * @property {boolean} isPaused - If `true` the `Body.preUpdate` method will be skipped, halting all motion for all bodies. Note that other methods such as `collide` will still work, so be careful not to call them on paused bodies.
  69598. */
  69599. this.isPaused = false;
  69600. /**
  69601. * @property {Phaser.QuadTree} quadTree - The world QuadTree.
  69602. */
  69603. this.quadTree = new Phaser.QuadTree(this.game.world.bounds.x, this.game.world.bounds.y, this.game.world.bounds.width, this.game.world.bounds.height, this.maxObjects, this.maxLevels);
  69604. /**
  69605. * @property {number} _total - Internal cache var.
  69606. * @private
  69607. */
  69608. this._total = 0;
  69609. // By default we want the bounds the same size as the world bounds
  69610. this.setBoundsToWorld();
  69611. };
  69612. Phaser.Physics.Arcade.prototype.constructor = Phaser.Physics.Arcade;
  69613. /**
  69614. * A constant used for the sortDirection value.
  69615. * Use this if you don't wish to perform any pre-collision sorting at all, or will manually sort your Groups.
  69616. * @constant
  69617. * @type {number}
  69618. */
  69619. Phaser.Physics.Arcade.SORT_NONE = 0;
  69620. /**
  69621. * A constant used for the sortDirection value.
  69622. * Use this if your game world is wide but short and scrolls from the left to the right (i.e. Mario)
  69623. * @constant
  69624. * @type {number}
  69625. */
  69626. Phaser.Physics.Arcade.LEFT_RIGHT = 1;
  69627. /**
  69628. * A constant used for the sortDirection value.
  69629. * Use this if your game world is wide but short and scrolls from the right to the left (i.e. Mario backwards)
  69630. * @constant
  69631. * @type {number}
  69632. */
  69633. Phaser.Physics.Arcade.RIGHT_LEFT = 2;
  69634. /**
  69635. * A constant used for the sortDirection value.
  69636. * Use this if your game world is narrow but tall and scrolls from the top to the bottom (i.e. Dig Dug)
  69637. * @constant
  69638. * @type {number}
  69639. */
  69640. Phaser.Physics.Arcade.TOP_BOTTOM = 3;
  69641. /**
  69642. * A constant used for the sortDirection value.
  69643. * Use this if your game world is narrow but tall and scrolls from the bottom to the top (i.e. Commando or a vertically scrolling shoot-em-up)
  69644. * @constant
  69645. * @type {number}
  69646. */
  69647. Phaser.Physics.Arcade.BOTTOM_TOP = 4;
  69648. Phaser.Physics.Arcade.prototype = {
  69649. /**
  69650. * Updates the size of this physics world.
  69651. *
  69652. * @method Phaser.Physics.Arcade#setBounds
  69653. * @param {number} x - Top left most corner of the world.
  69654. * @param {number} y - Top left most corner of the world.
  69655. * @param {number} width - New width of the world. Can never be smaller than the Game.width.
  69656. * @param {number} height - New height of the world. Can never be smaller than the Game.height.
  69657. */
  69658. setBounds: function (x, y, width, height) {
  69659. this.bounds.setTo(x, y, width, height);
  69660. },
  69661. /**
  69662. * Updates the size of this physics world to match the size of the game world.
  69663. *
  69664. * @method Phaser.Physics.Arcade#setBoundsToWorld
  69665. */
  69666. setBoundsToWorld: function () {
  69667. this.bounds.copyFrom(this.game.world.bounds);
  69668. },
  69669. /**
  69670. * This will create an Arcade Physics body on the given game object or array of game objects.
  69671. * A game object can only have 1 physics body active at any one time, and it can't be changed until the object is destroyed.
  69672. *
  69673. * @method Phaser.Physics.Arcade#enable
  69674. * @param {object|array|Phaser.Group} object - The game object to create the physics body on. Can also be an array or Group of objects, a body will be created on every child that has a `body` property.
  69675. * @param {boolean} [children=true] - Should a body be created on all children of this object? If true it will recurse down the display list as far as it can go.
  69676. */
  69677. enable: function (object, children) {
  69678. if (children === undefined) { children = true; }
  69679. var i = 1;
  69680. if (Array.isArray(object))
  69681. {
  69682. i = object.length;
  69683. while (i--)
  69684. {
  69685. if (object[i] instanceof Phaser.Group)
  69686. {
  69687. // If it's a Group then we do it on the children regardless
  69688. this.enable(object[i].children, children);
  69689. }
  69690. else
  69691. {
  69692. this.enableBody(object[i]);
  69693. if (children && object[i].hasOwnProperty('children') && object[i].children.length > 0)
  69694. {
  69695. this.enable(object[i], true);
  69696. }
  69697. }
  69698. }
  69699. }
  69700. else
  69701. {
  69702. if (object instanceof Phaser.Group)
  69703. {
  69704. // If it's a Group then we do it on the children regardless
  69705. this.enable(object.children, children);
  69706. }
  69707. else
  69708. {
  69709. this.enableBody(object);
  69710. if (children && object.hasOwnProperty('children') && object.children.length > 0)
  69711. {
  69712. this.enable(object.children, true);
  69713. }
  69714. }
  69715. }
  69716. },
  69717. /**
  69718. * Creates an Arcade Physics body on the given game object.
  69719. *
  69720. * A game object can only have 1 physics body active at any one time, and it can't be changed until the body is nulled.
  69721. *
  69722. * When you add an Arcade Physics body to an object it will automatically add the object into its parent Groups hash array.
  69723. *
  69724. * @method Phaser.Physics.Arcade#enableBody
  69725. * @param {object} object - The game object to create the physics body on. A body will only be created if this object has a null `body` property.
  69726. */
  69727. enableBody: function (object) {
  69728. if (object.hasOwnProperty('body') && object.body === null)
  69729. {
  69730. object.body = new Phaser.Physics.Arcade.Body(object);
  69731. if (object.parent && object.parent instanceof Phaser.Group)
  69732. {
  69733. object.parent.addToHash(object);
  69734. }
  69735. }
  69736. },
  69737. /**
  69738. * Called automatically by a Physics body, it updates all motion related values on the Body unless `World.isPaused` is `true`.
  69739. *
  69740. * @method Phaser.Physics.Arcade#updateMotion
  69741. * @param {Phaser.Physics.Arcade.Body} The Body object to be updated.
  69742. */
  69743. updateMotion: function (body) {
  69744. var velocityDelta = this.computeVelocity(0, body, body.angularVelocity, body.angularAcceleration, body.angularDrag, body.maxAngular) - body.angularVelocity;
  69745. body.angularVelocity += velocityDelta;
  69746. body.rotation += (body.angularVelocity * this.game.time.physicsElapsed);
  69747. body.velocity.x = this.computeVelocity(1, body, body.velocity.x, body.acceleration.x, body.drag.x, body.maxVelocity.x);
  69748. body.velocity.y = this.computeVelocity(2, body, body.velocity.y, body.acceleration.y, body.drag.y, body.maxVelocity.y);
  69749. },
  69750. /**
  69751. * A tween-like function that takes a starting velocity and some other factors and returns an altered velocity.
  69752. * Based on a function in Flixel by @ADAMATOMIC
  69753. *
  69754. * @method Phaser.Physics.Arcade#computeVelocity
  69755. * @param {number} axis - 0 for nothing, 1 for horizontal, 2 for vertical.
  69756. * @param {Phaser.Physics.Arcade.Body} body - The Body object to be updated.
  69757. * @param {number} velocity - Any component of velocity (e.g. 20).
  69758. * @param {number} acceleration - Rate at which the velocity is changing.
  69759. * @param {number} drag - Really kind of a deceleration, this is how much the velocity changes if Acceleration is not set.
  69760. * @param {number} [max=10000] - An absolute value cap for the velocity.
  69761. * @return {number} The altered Velocity value.
  69762. */
  69763. computeVelocity: function (axis, body, velocity, acceleration, drag, max) {
  69764. if (max === undefined) { max = 10000; }
  69765. if (axis === 1 && body.allowGravity)
  69766. {
  69767. velocity += (this.gravity.x + body.gravity.x) * this.game.time.physicsElapsed;
  69768. }
  69769. else if (axis === 2 && body.allowGravity)
  69770. {
  69771. velocity += (this.gravity.y + body.gravity.y) * this.game.time.physicsElapsed;
  69772. }
  69773. if (acceleration)
  69774. {
  69775. velocity += acceleration * this.game.time.physicsElapsed;
  69776. }
  69777. else if (drag)
  69778. {
  69779. drag *= this.game.time.physicsElapsed;
  69780. if (velocity - drag > 0)
  69781. {
  69782. velocity -= drag;
  69783. }
  69784. else if (velocity + drag < 0)
  69785. {
  69786. velocity += drag;
  69787. }
  69788. else
  69789. {
  69790. velocity = 0;
  69791. }
  69792. }
  69793. if (velocity > max)
  69794. {
  69795. velocity = max;
  69796. }
  69797. else if (velocity < -max)
  69798. {
  69799. velocity = -max;
  69800. }
  69801. return velocity;
  69802. },
  69803. /**
  69804. * Checks for overlaps between two game objects. The objects can be Sprites, Groups or Emitters.
  69805. * You can perform Sprite vs. Sprite, Sprite vs. Group and Group vs. Group overlap checks.
  69806. * Unlike collide the objects are NOT automatically separated or have any physics applied, they merely test for overlap results.
  69807. * Both the first and second parameter can be arrays of objects, of differing types.
  69808. * If two arrays are passed, the contents of the first parameter will be tested against all contents of the 2nd parameter.
  69809. * NOTE: This function is not recursive, and will not test against children of objects passed (i.e. Groups within Groups).
  69810. *
  69811. * @method Phaser.Physics.Arcade#overlap
  69812. * @param {Phaser.Sprite|Phaser.Group|Phaser.Particles.Emitter|array} object1 - The first object or array of objects to check. Can be Phaser.Sprite, Phaser.Group or Phaser.Particles.Emitter.
  69813. * @param {Phaser.Sprite|Phaser.Group|Phaser.Particles.Emitter|array} object2 - The second object or array of objects to check. Can be Phaser.Sprite, Phaser.Group or Phaser.Particles.Emitter.
  69814. * @param {function} [overlapCallback=null] - An optional callback function that is called if the objects overlap. The two objects will be passed to this function in the same order in which you specified them, unless you are checking Group vs. Sprite, in which case Sprite will always be the first parameter.
  69815. * @param {function} [processCallback=null] - A callback function that lets you perform additional checks against the two objects if they overlap. If this is set then `overlapCallback` will only be called if this callback returns `true`.
  69816. * @param {object} [callbackContext] - The context in which to run the callbacks.
  69817. * @return {boolean} True if an overlap occurred otherwise false.
  69818. */
  69819. overlap: function (object1, object2, overlapCallback, processCallback, callbackContext) {
  69820. overlapCallback = overlapCallback || null;
  69821. processCallback = processCallback || null;
  69822. callbackContext = callbackContext || overlapCallback;
  69823. this._total = 0;
  69824. if (!Array.isArray(object1) && Array.isArray(object2))
  69825. {
  69826. for (var i = 0; i < object2.length; i++)
  69827. {
  69828. this.collideHandler(object1, object2[i], overlapCallback, processCallback, callbackContext, true);
  69829. }
  69830. }
  69831. else if (Array.isArray(object1) && !Array.isArray(object2))
  69832. {
  69833. for (var i = 0; i < object1.length; i++)
  69834. {
  69835. this.collideHandler(object1[i], object2, overlapCallback, processCallback, callbackContext, true);
  69836. }
  69837. }
  69838. else if (Array.isArray(object1) && Array.isArray(object2))
  69839. {
  69840. for (var i = 0; i < object1.length; i++)
  69841. {
  69842. for (var j = 0; j < object2.length; j++)
  69843. {
  69844. this.collideHandler(object1[i], object2[j], overlapCallback, processCallback, callbackContext, true);
  69845. }
  69846. }
  69847. }
  69848. else
  69849. {
  69850. this.collideHandler(object1, object2, overlapCallback, processCallback, callbackContext, true);
  69851. }
  69852. return (this._total > 0);
  69853. },
  69854. /**
  69855. * Checks for collision between two game objects. You can perform Sprite vs. Sprite, Sprite vs. Group, Group vs. Group, Sprite vs. Tilemap Layer or Group vs. Tilemap Layer collisions.
  69856. * Both the first and second parameter can be arrays of objects, of differing types.
  69857. * If two arrays are passed, the contents of the first parameter will be tested against all contents of the 2nd parameter.
  69858. * The objects are also automatically separated. If you don't require separation then use ArcadePhysics.overlap instead.
  69859. * An optional processCallback can be provided. If given this function will be called when two sprites are found to be colliding. It is called before any separation takes place,
  69860. * giving you the chance to perform additional checks. If the function returns true then the collision and separation is carried out. If it returns false it is skipped.
  69861. * The collideCallback is an optional function that is only called if two sprites collide. If a processCallback has been set then it needs to return true for collideCallback to be called.
  69862. * NOTE: This function is not recursive, and will not test against children of objects passed (i.e. Groups or Tilemaps within other Groups).
  69863. *
  69864. * @method Phaser.Physics.Arcade#collide
  69865. * @param {Phaser.Sprite|Phaser.Group|Phaser.Particles.Emitter|Phaser.TilemapLayer|array} object1 - The first object or array of objects to check. Can be Phaser.Sprite, Phaser.Group, Phaser.Particles.Emitter, or Phaser.TilemapLayer.
  69866. * @param {Phaser.Sprite|Phaser.Group|Phaser.Particles.Emitter|Phaser.TilemapLayer|array} object2 - The second object or array of objects to check. Can be Phaser.Sprite, Phaser.Group, Phaser.Particles.Emitter or Phaser.TilemapLayer.
  69867. * @param {function} [collideCallback=null] - An optional callback function that is called if the objects collide. The two objects will be passed to this function in the same order in which you specified them, unless you are colliding Group vs. Sprite, in which case Sprite will always be the first parameter.
  69868. * @param {function} [processCallback=null] - A callback function that lets you perform additional checks against the two objects if they overlap. If this is set then collision will only happen if processCallback returns true. The two objects will be passed to this function in the same order in which you specified them, unless you are colliding Group vs. Sprite, in which case Sprite will always be the first parameter.
  69869. * @param {object} [callbackContext] - The context in which to run the callbacks.
  69870. * @return {boolean} True if a collision occurred otherwise false.
  69871. */
  69872. collide: function (object1, object2, collideCallback, processCallback, callbackContext) {
  69873. collideCallback = collideCallback || null;
  69874. processCallback = processCallback || null;
  69875. callbackContext = callbackContext || collideCallback;
  69876. this._total = 0;
  69877. if (!Array.isArray(object1) && Array.isArray(object2))
  69878. {
  69879. for (var i = 0; i < object2.length; i++)
  69880. {
  69881. this.collideHandler(object1, object2[i], collideCallback, processCallback, callbackContext, false);
  69882. }
  69883. }
  69884. else if (Array.isArray(object1) && !Array.isArray(object2))
  69885. {
  69886. for (var i = 0; i < object1.length; i++)
  69887. {
  69888. this.collideHandler(object1[i], object2, collideCallback, processCallback, callbackContext, false);
  69889. }
  69890. }
  69891. else if (Array.isArray(object1) && Array.isArray(object2))
  69892. {
  69893. for (var i = 0; i < object1.length; i++)
  69894. {
  69895. for (var j = 0; j < object2.length; j++)
  69896. {
  69897. this.collideHandler(object1[i], object2[j], collideCallback, processCallback, callbackContext, false);
  69898. }
  69899. }
  69900. }
  69901. else
  69902. {
  69903. this.collideHandler(object1, object2, collideCallback, processCallback, callbackContext, false);
  69904. }
  69905. return (this._total > 0);
  69906. },
  69907. /**
  69908. * A Sort function for sorting two bodies based on a LEFT to RIGHT sort direction.
  69909. *
  69910. * This is called automatically by World.sort
  69911. *
  69912. * @method Phaser.Physics.Arcade#sortLeftRight
  69913. * @param {Phaser.Sprite} a - The first Sprite to test. The Sprite must have an Arcade Physics Body.
  69914. * @param {Phaser.Sprite} b - The second Sprite to test. The Sprite must have an Arcade Physics Body.
  69915. * @return {integer} A negative value if `a > b`, a positive value if `a < b` or 0 if `a === b` or the bodies are invalid.
  69916. */
  69917. sortLeftRight: function (a, b) {
  69918. if (!a.body || !b.body)
  69919. {
  69920. return 0;
  69921. }
  69922. return a.body.x - b.body.x;
  69923. },
  69924. /**
  69925. * A Sort function for sorting two bodies based on a RIGHT to LEFT sort direction.
  69926. *
  69927. * This is called automatically by World.sort
  69928. *
  69929. * @method Phaser.Physics.Arcade#sortRightLeft
  69930. * @param {Phaser.Sprite} a - The first Sprite to test. The Sprite must have an Arcade Physics Body.
  69931. * @param {Phaser.Sprite} b - The second Sprite to test. The Sprite must have an Arcade Physics Body.
  69932. * @return {integer} A negative value if `a > b`, a positive value if `a < b` or 0 if `a === b` or the bodies are invalid.
  69933. */
  69934. sortRightLeft: function (a, b) {
  69935. if (!a.body || !b.body)
  69936. {
  69937. return 0;
  69938. }
  69939. return b.body.x - a.body.x;
  69940. },
  69941. /**
  69942. * A Sort function for sorting two bodies based on a TOP to BOTTOM sort direction.
  69943. *
  69944. * This is called automatically by World.sort
  69945. *
  69946. * @method Phaser.Physics.Arcade#sortTopBottom
  69947. * @param {Phaser.Sprite} a - The first Sprite to test. The Sprite must have an Arcade Physics Body.
  69948. * @param {Phaser.Sprite} b - The second Sprite to test. The Sprite must have an Arcade Physics Body.
  69949. * @return {integer} A negative value if `a > b`, a positive value if `a < b` or 0 if `a === b` or the bodies are invalid.
  69950. */
  69951. sortTopBottom: function (a, b) {
  69952. if (!a.body || !b.body)
  69953. {
  69954. return 0;
  69955. }
  69956. return a.body.y - b.body.y;
  69957. },
  69958. /**
  69959. * A Sort function for sorting two bodies based on a BOTTOM to TOP sort direction.
  69960. *
  69961. * This is called automatically by World.sort
  69962. *
  69963. * @method Phaser.Physics.Arcade#sortBottomTop
  69964. * @param {Phaser.Sprite} a - The first Sprite to test. The Sprite must have an Arcade Physics Body.
  69965. * @param {Phaser.Sprite} b - The second Sprite to test. The Sprite must have an Arcade Physics Body.
  69966. * @return {integer} A negative value if `a > b`, a positive value if `a < b` or 0 if `a === b` or the bodies are invalid.
  69967. */
  69968. sortBottomTop: function (a, b) {
  69969. if (!a.body || !b.body)
  69970. {
  69971. return 0;
  69972. }
  69973. return b.body.y - a.body.y;
  69974. },
  69975. /**
  69976. * This method will sort a Groups hash array.
  69977. *
  69978. * If the Group has `physicsSortDirection` set it will use the sort direction defined.
  69979. *
  69980. * Otherwise if the sortDirection parameter is undefined, or Group.physicsSortDirection is null, it will use Phaser.Physics.Arcade.sortDirection.
  69981. *
  69982. * By changing Group.physicsSortDirection you can customise each Group to sort in a different order.
  69983. *
  69984. * @method Phaser.Physics.Arcade#sort
  69985. * @param {Phaser.Group} group - The Group to sort.
  69986. * @param {integer} [sortDirection] - The sort direction used to sort this Group.
  69987. */
  69988. sort: function (group, sortDirection) {
  69989. if (group.physicsSortDirection !== null)
  69990. {
  69991. sortDirection = group.physicsSortDirection;
  69992. }
  69993. else
  69994. {
  69995. if (sortDirection === undefined) { sortDirection = this.sortDirection; }
  69996. }
  69997. if (sortDirection === Phaser.Physics.Arcade.LEFT_RIGHT)
  69998. {
  69999. // Game world is say 2000x600 and you start at 0
  70000. group.hash.sort(this.sortLeftRight);
  70001. }
  70002. else if (sortDirection === Phaser.Physics.Arcade.RIGHT_LEFT)
  70003. {
  70004. // Game world is say 2000x600 and you start at 2000
  70005. group.hash.sort(this.sortRightLeft);
  70006. }
  70007. else if (sortDirection === Phaser.Physics.Arcade.TOP_BOTTOM)
  70008. {
  70009. // Game world is say 800x2000 and you start at 0
  70010. group.hash.sort(this.sortTopBottom);
  70011. }
  70012. else if (sortDirection === Phaser.Physics.Arcade.BOTTOM_TOP)
  70013. {
  70014. // Game world is say 800x2000 and you start at 2000
  70015. group.hash.sort(this.sortBottomTop);
  70016. }
  70017. },
  70018. /**
  70019. * Internal collision handler.
  70020. *
  70021. * @method Phaser.Physics.Arcade#collideHandler
  70022. * @private
  70023. * @param {Phaser.Sprite|Phaser.Group|Phaser.Particles.Emitter|Phaser.TilemapLayer} object1 - The first object to check. Can be an instance of Phaser.Sprite, Phaser.Group, Phaser.Particles.Emitter, or Phaser.TilemapLayer.
  70024. * @param {Phaser.Sprite|Phaser.Group|Phaser.Particles.Emitter|Phaser.TilemapLayer} object2 - The second object to check. Can be an instance of Phaser.Sprite, Phaser.Group, Phaser.Particles.Emitter or Phaser.TilemapLayer. Can also be an array of objects to check.
  70025. * @param {function} collideCallback - An optional callback function that is called if the objects collide. The two objects will be passed to this function in the same order in which you specified them.
  70026. * @param {function} processCallback - A callback function that lets you perform additional checks against the two objects if they overlap. If this is set then collision will only happen if processCallback returns true. The two objects will be passed to this function in the same order in which you specified them.
  70027. * @param {object} callbackContext - The context in which to run the callbacks.
  70028. * @param {boolean} overlapOnly - Just run an overlap or a full collision.
  70029. */
  70030. collideHandler: function (object1, object2, collideCallback, processCallback, callbackContext, overlapOnly) {
  70031. // Only collide valid objects
  70032. if (object2 === undefined && object1.physicsType === Phaser.GROUP)
  70033. {
  70034. this.sort(object1);
  70035. this.collideGroupVsSelf(object1, collideCallback, processCallback, callbackContext, overlapOnly);
  70036. return;
  70037. }
  70038. // If neither of the objects are set or exist then bail out
  70039. if (!object1 || !object2 || !object1.exists || !object2.exists)
  70040. {
  70041. return;
  70042. }
  70043. // Groups? Sort them
  70044. if (this.sortDirection !== Phaser.Physics.Arcade.SORT_NONE)
  70045. {
  70046. if (object1.physicsType === Phaser.GROUP)
  70047. {
  70048. this.sort(object1);
  70049. }
  70050. if (object2.physicsType === Phaser.GROUP)
  70051. {
  70052. this.sort(object2);
  70053. }
  70054. }
  70055. // SPRITES
  70056. if (object1.physicsType === Phaser.SPRITE)
  70057. {
  70058. if (object2.physicsType === Phaser.SPRITE)
  70059. {
  70060. this.collideSpriteVsSprite(object1, object2, collideCallback, processCallback, callbackContext, overlapOnly);
  70061. }
  70062. else if (object2.physicsType === Phaser.GROUP)
  70063. {
  70064. this.collideSpriteVsGroup(object1, object2, collideCallback, processCallback, callbackContext, overlapOnly);
  70065. }
  70066. else if (object2.physicsType === Phaser.TILEMAPLAYER)
  70067. {
  70068. this.collideSpriteVsTilemapLayer(object1, object2, collideCallback, processCallback, callbackContext, overlapOnly);
  70069. }
  70070. }
  70071. // GROUPS
  70072. else if (object1.physicsType === Phaser.GROUP)
  70073. {
  70074. if (object2.physicsType === Phaser.SPRITE)
  70075. {
  70076. this.collideSpriteVsGroup(object2, object1, collideCallback, processCallback, callbackContext, overlapOnly);
  70077. }
  70078. else if (object2.physicsType === Phaser.GROUP)
  70079. {
  70080. this.collideGroupVsGroup(object1, object2, collideCallback, processCallback, callbackContext, overlapOnly);
  70081. }
  70082. else if (object2.physicsType === Phaser.TILEMAPLAYER)
  70083. {
  70084. this.collideGroupVsTilemapLayer(object1, object2, collideCallback, processCallback, callbackContext, overlapOnly);
  70085. }
  70086. }
  70087. // TILEMAP LAYERS
  70088. else if (object1.physicsType === Phaser.TILEMAPLAYER)
  70089. {
  70090. if (object2.physicsType === Phaser.SPRITE)
  70091. {
  70092. this.collideSpriteVsTilemapLayer(object2, object1, collideCallback, processCallback, callbackContext, overlapOnly);
  70093. }
  70094. else if (object2.physicsType === Phaser.GROUP)
  70095. {
  70096. this.collideGroupVsTilemapLayer(object2, object1, collideCallback, processCallback, callbackContext, overlapOnly);
  70097. }
  70098. }
  70099. },
  70100. /**
  70101. * An internal function. Use Phaser.Physics.Arcade.collide instead.
  70102. *
  70103. * @method Phaser.Physics.Arcade#collideSpriteVsSprite
  70104. * @private
  70105. * @param {Phaser.Sprite} sprite1 - The first sprite to check.
  70106. * @param {Phaser.Sprite} sprite2 - The second sprite to check.
  70107. * @param {function} collideCallback - An optional callback function that is called if the objects collide. The two objects will be passed to this function in the same order in which you specified them.
  70108. * @param {function} processCallback - A callback function that lets you perform additional checks against the two objects if they overlap. If this is set then collision will only happen if processCallback returns true. The two objects will be passed to this function in the same order in which you specified them.
  70109. * @param {object} callbackContext - The context in which to run the callbacks.
  70110. * @param {boolean} overlapOnly - Just run an overlap or a full collision.
  70111. * @return {boolean} True if there was a collision, otherwise false.
  70112. */
  70113. collideSpriteVsSprite: function (sprite1, sprite2, collideCallback, processCallback, callbackContext, overlapOnly) {
  70114. if (!sprite1.body || !sprite2.body)
  70115. {
  70116. return false;
  70117. }
  70118. if (this.separate(sprite1.body, sprite2.body, processCallback, callbackContext, overlapOnly))
  70119. {
  70120. if (collideCallback)
  70121. {
  70122. collideCallback.call(callbackContext, sprite1, sprite2);
  70123. }
  70124. this._total++;
  70125. }
  70126. return true;
  70127. },
  70128. /**
  70129. * An internal function. Use Phaser.Physics.Arcade.collide instead.
  70130. *
  70131. * @method Phaser.Physics.Arcade#collideSpriteVsGroup
  70132. * @private
  70133. * @param {Phaser.Sprite} sprite - The sprite to check.
  70134. * @param {Phaser.Group} group - The Group to check.
  70135. * @param {function} collideCallback - An optional callback function that is called if the objects collide. The two objects will be passed to this function in the same order in which you specified them.
  70136. * @param {function} processCallback - A callback function that lets you perform additional checks against the two objects if they overlap. If this is set then collision will only happen if processCallback returns true. The two objects will be passed to this function in the same order in which you specified them.
  70137. * @param {object} callbackContext - The context in which to run the callbacks.
  70138. * @param {boolean} overlapOnly - Just run an overlap or a full collision.
  70139. */
  70140. collideSpriteVsGroup: function (sprite, group, collideCallback, processCallback, callbackContext, overlapOnly) {
  70141. if (group.length === 0 || !sprite.body)
  70142. {
  70143. return;
  70144. }
  70145. if (this.skipQuadTree || sprite.body.skipQuadTree)
  70146. {
  70147. var bounds = {};
  70148. for (var i = 0; i < group.hash.length; i++)
  70149. {
  70150. var object1 = group.hash[i];
  70151. // Skip duff entries - we can't check a non-existent sprite or one with no body
  70152. if (!object1 || !object1.exists || !object1.body)
  70153. {
  70154. continue;
  70155. }
  70156. // Inject the Body bounds data into the bounds object
  70157. bounds = object1.body.getBounds(bounds);
  70158. // Skip items either side of the sprite
  70159. if (this.sortDirection === Phaser.Physics.Arcade.LEFT_RIGHT)
  70160. {
  70161. if (sprite.body.right < bounds.x)
  70162. {
  70163. break;
  70164. }
  70165. else if (bounds.right < sprite.body.x)
  70166. {
  70167. continue;
  70168. }
  70169. }
  70170. else if (this.sortDirection === Phaser.Physics.Arcade.RIGHT_LEFT)
  70171. {
  70172. if (sprite.body.x > bounds.right)
  70173. {
  70174. break;
  70175. }
  70176. else if (bounds.x > sprite.body.right)
  70177. {
  70178. continue;
  70179. }
  70180. }
  70181. else if (this.sortDirection === Phaser.Physics.Arcade.TOP_BOTTOM)
  70182. {
  70183. if (sprite.body.bottom < bounds.y)
  70184. {
  70185. break;
  70186. }
  70187. else if (bounds.bottom < sprite.body.y)
  70188. {
  70189. continue;
  70190. }
  70191. }
  70192. else if (this.sortDirection === Phaser.Physics.Arcade.BOTTOM_TOP)
  70193. {
  70194. if (sprite.body.y > bounds.bottom)
  70195. {
  70196. break;
  70197. }
  70198. else if (bounds.y > sprite.body.bottom)
  70199. {
  70200. continue;
  70201. }
  70202. }
  70203. this.collideSpriteVsSprite(sprite, object1, collideCallback, processCallback, callbackContext, overlapOnly);
  70204. }
  70205. }
  70206. else
  70207. {
  70208. // What is the sprite colliding with in the quadtree?
  70209. this.quadTree.clear();
  70210. this.quadTree.reset(this.game.world.bounds.x, this.game.world.bounds.y, this.game.world.bounds.width, this.game.world.bounds.height, this.maxObjects, this.maxLevels);
  70211. this.quadTree.populate(group);
  70212. var items = this.quadTree.retrieve(sprite);
  70213. for (var i = 0; i < items.length; i++)
  70214. {
  70215. // We have our potential suspects, are they in this group?
  70216. if (this.separate(sprite.body, items[i], processCallback, callbackContext, overlapOnly))
  70217. {
  70218. if (collideCallback)
  70219. {
  70220. collideCallback.call(callbackContext, sprite, items[i].sprite);
  70221. }
  70222. this._total++;
  70223. }
  70224. }
  70225. }
  70226. },
  70227. /**
  70228. * An internal function. Use Phaser.Physics.Arcade.collide instead.
  70229. *
  70230. * @method Phaser.Physics.Arcade#collideGroupVsSelf
  70231. * @private
  70232. * @param {Phaser.Group} group - The Group to check.
  70233. * @param {function} collideCallback - An optional callback function that is called if the objects collide. The two objects will be passed to this function in the same order in which you specified them.
  70234. * @param {function} processCallback - A callback function that lets you perform additional checks against the two objects if they overlap. If this is set then collision will only happen if processCallback returns true. The two objects will be passed to this function in the same order in which you specified them.
  70235. * @param {object} callbackContext - The context in which to run the callbacks.
  70236. * @param {boolean} overlapOnly - Just run an overlap or a full collision.
  70237. * @return {boolean} True if there was a collision, otherwise false.
  70238. */
  70239. collideGroupVsSelf: function (group, collideCallback, processCallback, callbackContext, overlapOnly) {
  70240. if (group.length === 0)
  70241. {
  70242. return;
  70243. }
  70244. for (var i = 0; i < group.hash.length; i++)
  70245. {
  70246. var bounds1 = {};
  70247. var object1 = group.hash[i];
  70248. // Skip duff entries - we can't check a non-existent sprite or one with no body
  70249. if (!object1 || !object1.exists || !object1.body)
  70250. {
  70251. continue;
  70252. }
  70253. // Inject the Body bounds data into the bounds1 object
  70254. bounds1 = object1.body.getBounds(bounds1);
  70255. for (var j = i + 1; j < group.hash.length; j++)
  70256. {
  70257. var bounds2 = {};
  70258. var object2 = group.hash[j];
  70259. // Skip duff entries - we can't check a non-existent sprite or one with no body
  70260. if (!object2 || !object2.exists || !object2.body)
  70261. {
  70262. continue;
  70263. }
  70264. // Inject the Body bounds data into the bounds2 object
  70265. bounds2 = object2.body.getBounds(bounds2);
  70266. // Skip items either side of the sprite
  70267. if (this.sortDirection === Phaser.Physics.Arcade.LEFT_RIGHT)
  70268. {
  70269. if (bounds1.right < bounds2.x)
  70270. {
  70271. break;
  70272. }
  70273. else if (bounds2.right < bounds1.x)
  70274. {
  70275. continue;
  70276. }
  70277. }
  70278. else if (this.sortDirection === Phaser.Physics.Arcade.RIGHT_LEFT)
  70279. {
  70280. if (bounds1.x > bounds2.right)
  70281. {
  70282. continue;
  70283. }
  70284. else if (bounds2.x > bounds1.right)
  70285. {
  70286. break;
  70287. }
  70288. }
  70289. else if (this.sortDirection === Phaser.Physics.Arcade.TOP_BOTTOM)
  70290. {
  70291. if (bounds1.bottom < bounds2.y)
  70292. {
  70293. continue;
  70294. }
  70295. else if (bounds2.bottom < bounds1.y)
  70296. {
  70297. break;
  70298. }
  70299. }
  70300. else if (this.sortDirection === Phaser.Physics.Arcade.BOTTOM_TOP)
  70301. {
  70302. if (bounds1.y > bounds2.bottom)
  70303. {
  70304. continue;
  70305. }
  70306. else if (bounds2.y > object1.body.bottom)
  70307. {
  70308. break;
  70309. }
  70310. }
  70311. this.collideSpriteVsSprite(object1, object2, collideCallback, processCallback, callbackContext, overlapOnly);
  70312. }
  70313. }
  70314. },
  70315. /**
  70316. * An internal function. Use Phaser.Physics.Arcade.collide instead.
  70317. *
  70318. * @method Phaser.Physics.Arcade#collideGroupVsGroup
  70319. * @private
  70320. * @param {Phaser.Group} group1 - The first Group to check.
  70321. * @param {Phaser.Group} group2 - The second Group to check.
  70322. * @param {function} collideCallback - An optional callback function that is called if the objects collide. The two objects will be passed to this function in the same order in which you specified them.
  70323. * @param {function} processCallback - A callback function that lets you perform additional checks against the two objects if they overlap. If this is set then collision will only happen if processCallback returns true. The two objects will be passed to this function in the same order in which you specified them.
  70324. * @param {object} callbackContext - The context in which to run the callbacks.
  70325. * @param {boolean} overlapOnly - Just run an overlap or a full collision.
  70326. */
  70327. collideGroupVsGroup: function (group1, group2, collideCallback, processCallback, callbackContext, overlapOnly) {
  70328. if (group1.length === 0 || group2.length === 0)
  70329. {
  70330. return;
  70331. }
  70332. for (var i = 0; i < group1.children.length; i++)
  70333. {
  70334. if (group1.children[i].exists)
  70335. {
  70336. if (group1.children[i].physicsType === Phaser.GROUP)
  70337. {
  70338. this.collideGroupVsGroup(group1.children[i], group2, collideCallback, processCallback, callbackContext, overlapOnly);
  70339. }
  70340. else
  70341. {
  70342. this.collideSpriteVsGroup(group1.children[i], group2, collideCallback, processCallback, callbackContext, overlapOnly);
  70343. }
  70344. }
  70345. }
  70346. },
  70347. /**
  70348. * The core separation function to separate two physics bodies.
  70349. *
  70350. * @private
  70351. * @method Phaser.Physics.Arcade#separate
  70352. * @param {Phaser.Physics.Arcade.Body} body1 - The first Body object to separate.
  70353. * @param {Phaser.Physics.Arcade.Body} body2 - The second Body object to separate.
  70354. * @param {function} [processCallback=null] - A callback function that lets you perform additional checks against the two objects if they overlap. If this function is set then the sprites will only be collided if it returns true.
  70355. * @param {object} [callbackContext] - The context in which to run the process callback.
  70356. * @param {boolean} overlapOnly - Just run an overlap or a full collision.
  70357. * @return {boolean} Returns true if the bodies collided, otherwise false.
  70358. */
  70359. separate: function (body1, body2, processCallback, callbackContext, overlapOnly) {
  70360. if (
  70361. !body1.enable ||
  70362. !body2.enable ||
  70363. body1.checkCollision.none ||
  70364. body2.checkCollision.none ||
  70365. !this.intersects(body1, body2))
  70366. {
  70367. return false;
  70368. }
  70369. // They overlap. Is there a custom process callback? If it returns true then we can carry on, otherwise we should abort.
  70370. if (processCallback && processCallback.call(callbackContext, body1.sprite, body2.sprite) === false)
  70371. {
  70372. return false;
  70373. }
  70374. // Circle vs. Circle quick bail out
  70375. if (body1.isCircle && body2.isCircle)
  70376. {
  70377. return this.separateCircle(body1, body2, overlapOnly);
  70378. }
  70379. // We define the behavior of bodies in a collision circle and rectangle
  70380. // If a collision occurs in the corner points of the rectangle, the body behave like circles
  70381. // Either body1 or body2 is a circle
  70382. if (body1.isCircle !== body2.isCircle)
  70383. {
  70384. var bodyRect = (body1.isCircle) ? body2 : body1;
  70385. var bodyCircle = (body1.isCircle) ? body1 : body2;
  70386. var rect = {
  70387. x: bodyRect.x,
  70388. y: bodyRect.y,
  70389. right: bodyRect.right,
  70390. bottom: bodyRect.bottom
  70391. };
  70392. var circle = {
  70393. x: bodyCircle.x + bodyCircle.radius,
  70394. y: bodyCircle.y + bodyCircle.radius
  70395. };
  70396. if (circle.y < rect.y || circle.y > rect.bottom)
  70397. {
  70398. if (circle.x < rect.x || circle.x > rect.right)
  70399. {
  70400. return this.separateCircle(body1, body2, overlapOnly);
  70401. }
  70402. }
  70403. }
  70404. var resultX = false;
  70405. var resultY = false;
  70406. // Do we separate on x or y first?
  70407. if (this.forceX || Math.abs(this.gravity.y + body1.gravity.y) < Math.abs(this.gravity.x + body1.gravity.x))
  70408. {
  70409. resultX = this.separateX(body1, body2, overlapOnly);
  70410. // Are they still intersecting? Let's do the other axis then
  70411. if (this.intersects(body1, body2))
  70412. {
  70413. resultY = this.separateY(body1, body2, overlapOnly);
  70414. }
  70415. }
  70416. else
  70417. {
  70418. resultY = this.separateY(body1, body2, overlapOnly);
  70419. // Are they still intersecting? Let's do the other axis then
  70420. if (this.intersects(body1, body2))
  70421. {
  70422. resultX = this.separateX(body1, body2, overlapOnly);
  70423. }
  70424. }
  70425. var result = (resultX || resultY);
  70426. if (result)
  70427. {
  70428. if (overlapOnly)
  70429. {
  70430. if (body1.onOverlap)
  70431. {
  70432. body1.onOverlap.dispatch(body1.sprite, body2.sprite);
  70433. }
  70434. if (body2.onOverlap)
  70435. {
  70436. body2.onOverlap.dispatch(body2.sprite, body1.sprite);
  70437. }
  70438. }
  70439. else
  70440. {
  70441. if (body1.onCollide)
  70442. {
  70443. body1.onCollide.dispatch(body1.sprite, body2.sprite);
  70444. }
  70445. if (body2.onCollide)
  70446. {
  70447. body2.onCollide.dispatch(body2.sprite, body1.sprite);
  70448. }
  70449. }
  70450. }
  70451. return result;
  70452. },
  70453. /**
  70454. * Check for intersection against two bodies.
  70455. *
  70456. * @method Phaser.Physics.Arcade#intersects
  70457. * @param {Phaser.Physics.Arcade.Body} body1 - The first Body object to check.
  70458. * @param {Phaser.Physics.Arcade.Body} body2 - The second Body object to check.
  70459. * @return {boolean} True if they intersect, otherwise false.
  70460. */
  70461. intersects: function (body1, body2) {
  70462. if (body1 === body2)
  70463. {
  70464. return false;
  70465. }
  70466. if (body1.isCircle)
  70467. {
  70468. if (body2.isCircle)
  70469. {
  70470. // Circle vs. Circle
  70471. return Phaser.Math.distance(body1.center.x, body1.center.y, body2.center.x, body2.center.y) <= (body1.radius + body2.radius);
  70472. }
  70473. else
  70474. {
  70475. // Circle vs. Rect
  70476. return this.circleBodyIntersects(body1, body2);
  70477. }
  70478. }
  70479. else
  70480. {
  70481. if (body2.isCircle)
  70482. {
  70483. // Rect vs. Circle
  70484. return this.circleBodyIntersects(body2, body1);
  70485. }
  70486. else
  70487. {
  70488. // Rect vs. Rect
  70489. if (body1.right <= body2.position.x)
  70490. {
  70491. return false;
  70492. }
  70493. if (body1.bottom <= body2.position.y)
  70494. {
  70495. return false;
  70496. }
  70497. if (body1.position.x >= body2.right)
  70498. {
  70499. return false;
  70500. }
  70501. if (body1.position.y >= body2.bottom)
  70502. {
  70503. return false;
  70504. }
  70505. return true;
  70506. }
  70507. }
  70508. },
  70509. /**
  70510. * Checks to see if a circular Body intersects with a Rectangular Body.
  70511. *
  70512. * @method Phaser.Physics.Arcade#circleBodyIntersects
  70513. * @param {Phaser.Physics.Arcade.Body} circle - The Body with `isCircle` set.
  70514. * @param {Phaser.Physics.Arcade.Body} body - The Body with `isCircle` not set (i.e. uses Rectangle shape)
  70515. * @return {boolean} Returns true if the bodies intersect, otherwise false.
  70516. */
  70517. circleBodyIntersects: function (circle, body) {
  70518. var x = Phaser.Math.clamp(circle.center.x, body.left, body.right);
  70519. var y = Phaser.Math.clamp(circle.center.y, body.top, body.bottom);
  70520. var dx = (circle.center.x - x) * (circle.center.x - x);
  70521. var dy = (circle.center.y - y) * (circle.center.y - y);
  70522. return (dx + dy) <= (circle.radius * circle.radius);
  70523. },
  70524. /**
  70525. * The core separation function to separate two circular physics bodies.
  70526. *
  70527. * @method Phaser.Physics.Arcade#separateCircle
  70528. * @private
  70529. * @param {Phaser.Physics.Arcade.Body} body1 - The first Body to separate. Must have `Body.isCircle` true and a positive `radius`.
  70530. * @param {Phaser.Physics.Arcade.Body} body2 - The second Body to separate. Must have `Body.isCircle` true and a positive `radius`.
  70531. * @param {boolean} overlapOnly - If true the bodies will only have their overlap data set, no separation or exchange of velocity will take place.
  70532. * @return {boolean} Returns true if the bodies were separated or overlap, otherwise false.
  70533. */
  70534. separateCircle: function (body1, body2, overlapOnly) {
  70535. // Set the bounding box overlap values
  70536. this.getOverlapX(body1, body2);
  70537. this.getOverlapY(body1, body2);
  70538. var dx = body2.center.x - body1.center.x;
  70539. var dy = body2.center.y - body1.center.y;
  70540. var angleCollision = Math.atan2(dy, dx);
  70541. var overlap = 0;
  70542. if (body1.isCircle !== body2.isCircle)
  70543. {
  70544. var rect = {
  70545. x: (body2.isCircle) ? body1.position.x : body2.position.x,
  70546. y: (body2.isCircle) ? body1.position.y : body2.position.y,
  70547. right: (body2.isCircle) ? body1.right : body2.right,
  70548. bottom: (body2.isCircle) ? body1.bottom : body2.bottom
  70549. };
  70550. var circle = {
  70551. x: (body1.isCircle) ? (body1.position.x + body1.radius) : (body2.position.x + body2.radius),
  70552. y: (body1.isCircle) ? (body1.position.y + body1.radius) : (body2.position.y + body2.radius),
  70553. radius: (body1.isCircle) ? body1.radius : body2.radius
  70554. };
  70555. if (circle.y < rect.y)
  70556. {
  70557. if (circle.x < rect.x)
  70558. {
  70559. overlap = Phaser.Math.distance(circle.x, circle.y, rect.x, rect.y) - circle.radius;
  70560. }
  70561. else if (circle.x > rect.right)
  70562. {
  70563. overlap = Phaser.Math.distance(circle.x, circle.y, rect.right, rect.y) - circle.radius;
  70564. }
  70565. }
  70566. else if (circle.y > rect.bottom)
  70567. {
  70568. if (circle.x < rect.x)
  70569. {
  70570. overlap = Phaser.Math.distance(circle.x, circle.y, rect.x, rect.bottom) - circle.radius;
  70571. }
  70572. else if (circle.x > rect.right)
  70573. {
  70574. overlap = Phaser.Math.distance(circle.x, circle.y, rect.right, rect.bottom) - circle.radius;
  70575. }
  70576. }
  70577. overlap *= -1;
  70578. }
  70579. else
  70580. {
  70581. overlap = (body1.radius + body2.radius) - Phaser.Math.distance(body1.center.x, body1.center.y, body2.center.x, body2.center.y);
  70582. }
  70583. // Can't separate two immovable bodies, or a body with its own custom separation logic
  70584. if (overlapOnly || overlap === 0 || (body1.immovable && body2.immovable) || body1.customSeparateX || body2.customSeparateX)
  70585. {
  70586. if (overlap !== 0)
  70587. {
  70588. if (body1.onOverlap)
  70589. {
  70590. body1.onOverlap.dispatch(body1.sprite, body2.sprite);
  70591. }
  70592. if (body2.onOverlap)
  70593. {
  70594. body2.onOverlap.dispatch(body2.sprite, body1.sprite);
  70595. }
  70596. }
  70597. // return true if there was some overlap, otherwise false
  70598. return (overlap !== 0);
  70599. }
  70600. // Transform the velocity vector to the coordinate system oriented along the direction of impact.
  70601. // This is done to eliminate the vertical component of the velocity
  70602. var v1 = {
  70603. x: body1.velocity.x * Math.cos(angleCollision) + body1.velocity.y * Math.sin(angleCollision),
  70604. y: body1.velocity.x * Math.sin(angleCollision) - body1.velocity.y * Math.cos(angleCollision)
  70605. };
  70606. var v2 = {
  70607. x: body2.velocity.x * Math.cos(angleCollision) + body2.velocity.y * Math.sin(angleCollision),
  70608. y: body2.velocity.x * Math.sin(angleCollision) - body2.velocity.y * Math.cos(angleCollision)
  70609. };
  70610. // We expect the new velocity after impact
  70611. var tempVel1 = ((body1.mass - body2.mass) * v1.x + 2 * body2.mass * v2.x) / (body1.mass + body2.mass);
  70612. var tempVel2 = (2 * body1.mass * v1.x + (body2.mass - body1.mass) * v2.x) / (body1.mass + body2.mass);
  70613. // We convert the vector to the original coordinate system and multiplied by factor of rebound
  70614. if (!body1.immovable)
  70615. {
  70616. body1.velocity.x = (tempVel1 * Math.cos(angleCollision) - v1.y * Math.sin(angleCollision)) * body1.bounce.x;
  70617. body1.velocity.y = (v1.y * Math.cos(angleCollision) + tempVel1 * Math.sin(angleCollision)) * body1.bounce.y;
  70618. }
  70619. if (!body2.immovable)
  70620. {
  70621. body2.velocity.x = (tempVel2 * Math.cos(angleCollision) - v2.y * Math.sin(angleCollision)) * body2.bounce.x;
  70622. body2.velocity.y = (v2.y * Math.cos(angleCollision) + tempVel2 * Math.sin(angleCollision)) * body2.bounce.y;
  70623. }
  70624. // When the collision angle is almost perpendicular to the total initial velocity vector
  70625. // (collision on a tangent) vector direction can be determined incorrectly.
  70626. // This code fixes the problem
  70627. if (Math.abs(angleCollision) < Math.PI / 2)
  70628. {
  70629. if ((body1.velocity.x > 0) && !body1.immovable && (body2.velocity.x > body1.velocity.x))
  70630. {
  70631. body1.velocity.x *= -1;
  70632. }
  70633. else if ((body2.velocity.x < 0) && !body2.immovable && (body1.velocity.x < body2.velocity.x))
  70634. {
  70635. body2.velocity.x *= -1;
  70636. }
  70637. else if ((body1.velocity.y > 0) && !body1.immovable && (body2.velocity.y > body1.velocity.y))
  70638. {
  70639. body1.velocity.y *= -1;
  70640. }
  70641. else if ((body2.velocity.y < 0) && !body2.immovable && (body1.velocity.y < body2.velocity.y))
  70642. {
  70643. body2.velocity.y *= -1;
  70644. }
  70645. }
  70646. else if (Math.abs(angleCollision) > Math.PI / 2)
  70647. {
  70648. if ((body1.velocity.x < 0) && !body1.immovable && (body2.velocity.x < body1.velocity.x))
  70649. {
  70650. body1.velocity.x *= -1;
  70651. }
  70652. else if ((body2.velocity.x > 0) && !body2.immovable && (body1.velocity.x > body2.velocity.x))
  70653. {
  70654. body2.velocity.x *= -1;
  70655. }
  70656. else if ((body1.velocity.y < 0) && !body1.immovable && (body2.velocity.y < body1.velocity.y))
  70657. {
  70658. body1.velocity.y *= -1;
  70659. }
  70660. else if ((body2.velocity.y > 0) && !body2.immovable && (body1.velocity.x > body2.velocity.y))
  70661. {
  70662. body2.velocity.y *= -1;
  70663. }
  70664. }
  70665. if (!body1.immovable)
  70666. {
  70667. body1.x += (body1.velocity.x * this.game.time.physicsElapsed) - overlap * Math.cos(angleCollision);
  70668. body1.y += (body1.velocity.y * this.game.time.physicsElapsed) - overlap * Math.sin(angleCollision);
  70669. }
  70670. if (!body2.immovable)
  70671. {
  70672. body2.x += (body2.velocity.x * this.game.time.physicsElapsed) + overlap * Math.cos(angleCollision);
  70673. body2.y += (body2.velocity.y * this.game.time.physicsElapsed) + overlap * Math.sin(angleCollision);
  70674. }
  70675. if (body1.onCollide)
  70676. {
  70677. body1.onCollide.dispatch(body1.sprite, body2.sprite);
  70678. }
  70679. if (body2.onCollide)
  70680. {
  70681. body2.onCollide.dispatch(body2.sprite, body1.sprite);
  70682. }
  70683. return true;
  70684. },
  70685. /**
  70686. * Calculates the horizontal overlap between two Bodies and sets their properties accordingly, including:
  70687. * `touching.left`, `touching.right` and `overlapX`.
  70688. *
  70689. * @method Phaser.Physics.Arcade#getOverlapX
  70690. * @param {Phaser.Physics.Arcade.Body} body1 - The first Body to separate.
  70691. * @param {Phaser.Physics.Arcade.Body} body2 - The second Body to separate.
  70692. * @param {boolean} overlapOnly - Is this an overlap only check, or part of separation?
  70693. * @return {float} Returns the amount of horizontal overlap between the two bodies.
  70694. */
  70695. getOverlapX: function (body1, body2, overlapOnly) {
  70696. var overlap = 0;
  70697. var maxOverlap = body1.deltaAbsX() + body2.deltaAbsX() + this.OVERLAP_BIAS;
  70698. if (body1.deltaX() === 0 && body2.deltaX() === 0)
  70699. {
  70700. // They overlap but neither of them are moving
  70701. body1.embedded = true;
  70702. body2.embedded = true;
  70703. }
  70704. else if (body1.deltaX() > body2.deltaX())
  70705. {
  70706. // Body1 is moving right and / or Body2 is moving left
  70707. overlap = body1.right - body2.x;
  70708. if ((overlap > maxOverlap && !overlapOnly) || body1.checkCollision.right === false || body2.checkCollision.left === false)
  70709. {
  70710. overlap = 0;
  70711. }
  70712. else
  70713. {
  70714. body1.touching.none = false;
  70715. body1.touching.right = true;
  70716. body2.touching.none = false;
  70717. body2.touching.left = true;
  70718. }
  70719. }
  70720. else if (body1.deltaX() < body2.deltaX())
  70721. {
  70722. // Body1 is moving left and/or Body2 is moving right
  70723. overlap = body1.x - body2.width - body2.x;
  70724. if ((-overlap > maxOverlap && !overlapOnly) || body1.checkCollision.left === false || body2.checkCollision.right === false)
  70725. {
  70726. overlap = 0;
  70727. }
  70728. else
  70729. {
  70730. body1.touching.none = false;
  70731. body1.touching.left = true;
  70732. body2.touching.none = false;
  70733. body2.touching.right = true;
  70734. }
  70735. }
  70736. // Resets the overlapX to zero if there is no overlap, or to the actual pixel value if there is
  70737. body1.overlapX = overlap;
  70738. body2.overlapX = overlap;
  70739. return overlap;
  70740. },
  70741. /**
  70742. * Calculates the vertical overlap between two Bodies and sets their properties accordingly, including:
  70743. * `touching.up`, `touching.down` and `overlapY`.
  70744. *
  70745. * @method Phaser.Physics.Arcade#getOverlapY
  70746. * @param {Phaser.Physics.Arcade.Body} body1 - The first Body to separate.
  70747. * @param {Phaser.Physics.Arcade.Body} body2 - The second Body to separate.
  70748. * @param {boolean} overlapOnly - Is this an overlap only check, or part of separation?
  70749. * @return {float} Returns the amount of vertical overlap between the two bodies.
  70750. */
  70751. getOverlapY: function (body1, body2, overlapOnly) {
  70752. var overlap = 0;
  70753. var maxOverlap = body1.deltaAbsY() + body2.deltaAbsY() + this.OVERLAP_BIAS;
  70754. if (body1.deltaY() === 0 && body2.deltaY() === 0)
  70755. {
  70756. // They overlap but neither of them are moving
  70757. body1.embedded = true;
  70758. body2.embedded = true;
  70759. }
  70760. else if (body1.deltaY() > body2.deltaY())
  70761. {
  70762. // Body1 is moving down and/or Body2 is moving up
  70763. overlap = body1.bottom - body2.y;
  70764. if ((overlap > maxOverlap && !overlapOnly) || body1.checkCollision.down === false || body2.checkCollision.up === false)
  70765. {
  70766. overlap = 0;
  70767. }
  70768. else
  70769. {
  70770. body1.touching.none = false;
  70771. body1.touching.down = true;
  70772. body2.touching.none = false;
  70773. body2.touching.up = true;
  70774. }
  70775. }
  70776. else if (body1.deltaY() < body2.deltaY())
  70777. {
  70778. // Body1 is moving up and/or Body2 is moving down
  70779. overlap = body1.y - body2.bottom;
  70780. if ((-overlap > maxOverlap && !overlapOnly) || body1.checkCollision.up === false || body2.checkCollision.down === false)
  70781. {
  70782. overlap = 0;
  70783. }
  70784. else
  70785. {
  70786. body1.touching.none = false;
  70787. body1.touching.up = true;
  70788. body2.touching.none = false;
  70789. body2.touching.down = true;
  70790. }
  70791. }
  70792. // Resets the overlapY to zero if there is no overlap, or to the actual pixel value if there is
  70793. body1.overlapY = overlap;
  70794. body2.overlapY = overlap;
  70795. return overlap;
  70796. },
  70797. /**
  70798. * The core separation function to separate two physics bodies on the x axis.
  70799. *
  70800. * @method Phaser.Physics.Arcade#separateX
  70801. * @private
  70802. * @param {Phaser.Physics.Arcade.Body} body1 - The first Body to separate.
  70803. * @param {Phaser.Physics.Arcade.Body} body2 - The second Body to separate.
  70804. * @param {boolean} overlapOnly - If true the bodies will only have their overlap data set, no separation or exchange of velocity will take place.
  70805. * @return {boolean} Returns true if the bodies were separated or overlap, otherwise false.
  70806. */
  70807. separateX: function (body1, body2, overlapOnly) {
  70808. var overlap = this.getOverlapX(body1, body2, overlapOnly);
  70809. // Can't separate two immovable bodies, or a body with its own custom separation logic
  70810. if (overlapOnly || overlap === 0 || (body1.immovable && body2.immovable) || body1.customSeparateX || body2.customSeparateX)
  70811. {
  70812. // return true if there was some overlap, otherwise false
  70813. return (overlap !== 0) || (body1.embedded && body2.embedded);
  70814. }
  70815. // Adjust their positions and velocities accordingly (if there was any overlap)
  70816. var v1 = body1.velocity.x;
  70817. var v2 = body2.velocity.x;
  70818. if (!body1.immovable && !body2.immovable)
  70819. {
  70820. overlap *= 0.5;
  70821. body1.x -= overlap;
  70822. body2.x += overlap;
  70823. var nv1 = Math.sqrt((v2 * v2 * body2.mass) / body1.mass) * ((v2 > 0) ? 1 : -1);
  70824. var nv2 = Math.sqrt((v1 * v1 * body1.mass) / body2.mass) * ((v1 > 0) ? 1 : -1);
  70825. var avg = (nv1 + nv2) * 0.5;
  70826. nv1 -= avg;
  70827. nv2 -= avg;
  70828. body1.velocity.x = avg + nv1 * body1.bounce.x;
  70829. body2.velocity.x = avg + nv2 * body2.bounce.x;
  70830. }
  70831. else if (!body1.immovable)
  70832. {
  70833. body1.x -= overlap;
  70834. body1.velocity.x = v2 - v1 * body1.bounce.x;
  70835. // This is special case code that handles things like vertically moving platforms you can ride
  70836. if (body2.moves)
  70837. {
  70838. body1.y += (body2.y - body2.prev.y) * body2.friction.y;
  70839. }
  70840. }
  70841. else
  70842. {
  70843. body2.x += overlap;
  70844. body2.velocity.x = v1 - v2 * body2.bounce.x;
  70845. // This is special case code that handles things like vertically moving platforms you can ride
  70846. if (body1.moves)
  70847. {
  70848. body2.y += (body1.y - body1.prev.y) * body1.friction.y;
  70849. }
  70850. }
  70851. // If we got this far then there WAS overlap, and separation is complete, so return true
  70852. return true;
  70853. },
  70854. /**
  70855. * The core separation function to separate two physics bodies on the y axis.
  70856. *
  70857. * @private
  70858. * @method Phaser.Physics.Arcade#separateY
  70859. * @param {Phaser.Physics.Arcade.Body} body1 - The first Body to separate.
  70860. * @param {Phaser.Physics.Arcade.Body} body2 - The second Body to separate.
  70861. * @param {boolean} overlapOnly - If true the bodies will only have their overlap data set, no separation or exchange of velocity will take place.
  70862. * @return {boolean} Returns true if the bodies were separated or overlap, otherwise false.
  70863. */
  70864. separateY: function (body1, body2, overlapOnly) {
  70865. var overlap = this.getOverlapY(body1, body2, overlapOnly);
  70866. // Can't separate two immovable bodies, or a body with its own custom separation logic
  70867. if (overlapOnly || overlap === 0 || (body1.immovable && body2.immovable) || body1.customSeparateY || body2.customSeparateY)
  70868. {
  70869. // return true if there was some overlap, otherwise false
  70870. return (overlap !== 0) || (body1.embedded && body2.embedded);
  70871. }
  70872. // Adjust their positions and velocities accordingly (if there was any overlap)
  70873. var v1 = body1.velocity.y;
  70874. var v2 = body2.velocity.y;
  70875. if (!body1.immovable && !body2.immovable)
  70876. {
  70877. overlap *= 0.5;
  70878. body1.y -= overlap;
  70879. body2.y += overlap;
  70880. var nv1 = Math.sqrt((v2 * v2 * body2.mass) / body1.mass) * ((v2 > 0) ? 1 : -1);
  70881. var nv2 = Math.sqrt((v1 * v1 * body1.mass) / body2.mass) * ((v1 > 0) ? 1 : -1);
  70882. var avg = (nv1 + nv2) * 0.5;
  70883. nv1 -= avg;
  70884. nv2 -= avg;
  70885. body1.velocity.y = avg + nv1 * body1.bounce.y;
  70886. body2.velocity.y = avg + nv2 * body2.bounce.y;
  70887. }
  70888. else if (!body1.immovable)
  70889. {
  70890. body1.y -= overlap;
  70891. body1.velocity.y = v2 - v1 * body1.bounce.y;
  70892. // This is special case code that handles things like horizontal moving platforms you can ride
  70893. if (body2.moves)
  70894. {
  70895. body1.x += (body2.x - body2.prev.x) * body2.friction.x;
  70896. }
  70897. }
  70898. else
  70899. {
  70900. body2.y += overlap;
  70901. body2.velocity.y = v1 - v2 * body2.bounce.y;
  70902. // This is special case code that handles things like horizontal moving platforms you can ride
  70903. if (body1.moves)
  70904. {
  70905. body2.x += (body1.x - body1.prev.x) * body1.friction.x;
  70906. }
  70907. }
  70908. // If we got this far then there WAS overlap, and separation is complete, so return true
  70909. return true;
  70910. },
  70911. /**
  70912. * Given a Group and a Pointer this will check to see which Group children overlap with the Pointer coordinates.
  70913. * Each child will be sent to the given callback for further processing.
  70914. * Note that the children are not checked for depth order, but simply if they overlap the Pointer or not.
  70915. *
  70916. * @method Phaser.Physics.Arcade#getObjectsUnderPointer
  70917. * @param {Phaser.Pointer} pointer - The Pointer to check.
  70918. * @param {Phaser.Group} group - The Group to check.
  70919. * @param {function} [callback] - A callback function that is called if the object overlaps with the Pointer. The callback will be sent two parameters: the Pointer and the Object that overlapped with it.
  70920. * @param {object} [callbackContext] - The context in which to run the callback.
  70921. * @return {PIXI.DisplayObject[]} An array of the Sprites from the Group that overlapped the Pointer coordinates.
  70922. */
  70923. getObjectsUnderPointer: function (pointer, group, callback, callbackContext) {
  70924. if (group.length === 0 || !pointer.exists)
  70925. {
  70926. return;
  70927. }
  70928. return this.getObjectsAtLocation(pointer.x, pointer.y, group, callback, callbackContext, pointer);
  70929. },
  70930. /**
  70931. * Given a Group and a location this will check to see which Group children overlap with the coordinates.
  70932. * Each child will be sent to the given callback for further processing.
  70933. * Note that the children are not checked for depth order, but simply if they overlap the coordinate or not.
  70934. *
  70935. * @method Phaser.Physics.Arcade#getObjectsAtLocation
  70936. * @param {number} x - The x coordinate to check.
  70937. * @param {number} y - The y coordinate to check.
  70938. * @param {Phaser.Group} group - The Group to check.
  70939. * @param {function} [callback] - A callback function that is called if the object overlaps the coordinates. The callback will be sent two parameters: the callbackArg and the Object that overlapped the location.
  70940. * @param {object} [callbackContext] - The context in which to run the callback.
  70941. * @param {object} [callbackArg] - An argument to pass to the callback.
  70942. * @return {PIXI.DisplayObject[]} An array of the Sprites from the Group that overlapped the coordinates.
  70943. */
  70944. getObjectsAtLocation: function (x, y, group, callback, callbackContext, callbackArg) {
  70945. this.quadTree.clear();
  70946. this.quadTree.reset(this.game.world.bounds.x, this.game.world.bounds.y, this.game.world.bounds.width, this.game.world.bounds.height, this.maxObjects, this.maxLevels);
  70947. this.quadTree.populate(group);
  70948. var rect = new Phaser.Rectangle(x, y, 1, 1);
  70949. var output = [];
  70950. var items = this.quadTree.retrieve(rect);
  70951. for (var i = 0; i < items.length; i++)
  70952. {
  70953. if (items[i].hitTest(x, y))
  70954. {
  70955. if (callback)
  70956. {
  70957. callback.call(callbackContext, callbackArg, items[i].sprite);
  70958. }
  70959. output.push(items[i].sprite);
  70960. }
  70961. }
  70962. return output;
  70963. },
  70964. /**
  70965. * Move the given display object towards the destination object at a steady velocity.
  70966. * If you specify a maxTime then it will adjust the speed (overwriting what you set) so it arrives at the destination in that number of seconds.
  70967. * Timings are approximate due to the way browser timers work. Allow for a variance of +- 50ms.
  70968. * Note: The display object does not continuously track the target. If the target changes location during transit the display object will not modify its course.
  70969. * Note: The display object doesn't stop moving once it reaches the destination coordinates.
  70970. * Note: Doesn't take into account acceleration, maxVelocity or drag (if you've set drag or acceleration too high this object may not move at all)
  70971. *
  70972. * @method Phaser.Physics.Arcade#moveToObject
  70973. * @param {any} displayObject - The display object to move.
  70974. * @param {any} destination - The display object to move towards. Can be any object but must have visible x/y properties.
  70975. * @param {number} [speed=60] - The speed it will move, in pixels per second (default is 60 pixels/sec)
  70976. * @param {number} [maxTime=0] - Time given in milliseconds (1000 = 1 sec). If set the speed is adjusted so the object will arrive at destination in the given number of ms.
  70977. * @return {number} The angle (in radians) that the object should be visually set to in order to match its new velocity.
  70978. */
  70979. moveToObject: function (displayObject, destination, speed, maxTime) {
  70980. if (speed === undefined) { speed = 60; }
  70981. if (maxTime === undefined) { maxTime = 0; }
  70982. var angle = Math.atan2(destination.y - displayObject.y, destination.x - displayObject.x);
  70983. if (maxTime > 0)
  70984. {
  70985. // We know how many pixels we need to move, but how fast?
  70986. speed = this.distanceBetween(displayObject, destination) / (maxTime / 1000);
  70987. }
  70988. displayObject.body.velocity.x = Math.cos(angle) * speed;
  70989. displayObject.body.velocity.y = Math.sin(angle) * speed;
  70990. return angle;
  70991. },
  70992. /**
  70993. * Move the given display object towards the pointer at a steady velocity. If no pointer is given it will use Phaser.Input.activePointer.
  70994. * If you specify a maxTime then it will adjust the speed (over-writing what you set) so it arrives at the destination in that number of seconds.
  70995. * Timings are approximate due to the way browser timers work. Allow for a variance of +- 50ms.
  70996. * Note: The display object does not continuously track the target. If the target changes location during transit the display object will not modify its course.
  70997. * Note: The display object doesn't stop moving once it reaches the destination coordinates.
  70998. *
  70999. * @method Phaser.Physics.Arcade#moveToPointer
  71000. * @param {any} displayObject - The display object to move.
  71001. * @param {number} [speed=60] - The speed it will move, in pixels per second (default is 60 pixels/sec)
  71002. * @param {Phaser.Pointer} [pointer] - The pointer to move towards. Defaults to Phaser.Input.activePointer.
  71003. * @param {number} [maxTime=0] - Time given in milliseconds (1000 = 1 sec). If set the speed is adjusted so the object will arrive at destination in the given number of ms.
  71004. * @return {number} The angle (in radians) that the object should be visually set to in order to match its new velocity.
  71005. */
  71006. moveToPointer: function (displayObject, speed, pointer, maxTime) {
  71007. if (speed === undefined) { speed = 60; }
  71008. pointer = pointer || this.game.input.activePointer;
  71009. if (maxTime === undefined) { maxTime = 0; }
  71010. var angle = this.angleToPointer(displayObject, pointer);
  71011. if (maxTime > 0)
  71012. {
  71013. // We know how many pixels we need to move, but how fast?
  71014. speed = this.distanceToPointer(displayObject, pointer) / (maxTime / 1000);
  71015. }
  71016. displayObject.body.velocity.x = Math.cos(angle) * speed;
  71017. displayObject.body.velocity.y = Math.sin(angle) * speed;
  71018. return angle;
  71019. },
  71020. /**
  71021. * Move the given display object towards the x/y coordinates at a steady velocity.
  71022. * If you specify a maxTime then it will adjust the speed (over-writing what you set) so it arrives at the destination in that number of seconds.
  71023. * Timings are approximate due to the way browser timers work. Allow for a variance of +- 50ms.
  71024. * Note: The display object does not continuously track the target. If the target changes location during transit the display object will not modify its course.
  71025. * Note: The display object doesn't stop moving once it reaches the destination coordinates.
  71026. * Note: Doesn't take into account acceleration, maxVelocity or drag (if you've set drag or acceleration too high this object may not move at all)
  71027. *
  71028. * @method Phaser.Physics.Arcade#moveToXY
  71029. * @param {any} displayObject - The display object to move.
  71030. * @param {number} x - The x coordinate to move towards.
  71031. * @param {number} y - The y coordinate to move towards.
  71032. * @param {number} [speed=60] - The speed it will move, in pixels per second (default is 60 pixels/sec)
  71033. * @param {number} [maxTime=0] - Time given in milliseconds (1000 = 1 sec). If set the speed is adjusted so the object will arrive at destination in the given number of ms.
  71034. * @return {number} The angle (in radians) that the object should be visually set to in order to match its new velocity.
  71035. */
  71036. moveToXY: function (displayObject, x, y, speed, maxTime) {
  71037. if (speed === undefined) { speed = 60; }
  71038. if (maxTime === undefined) { maxTime = 0; }
  71039. var angle = Math.atan2(y - displayObject.y, x - displayObject.x);
  71040. if (maxTime > 0)
  71041. {
  71042. // We know how many pixels we need to move, but how fast?
  71043. speed = this.distanceToXY(displayObject, x, y) / (maxTime / 1000);
  71044. }
  71045. displayObject.body.velocity.x = Math.cos(angle) * speed;
  71046. displayObject.body.velocity.y = Math.sin(angle) * speed;
  71047. return angle;
  71048. },
  71049. /**
  71050. * Given the angle (in degrees) and speed calculate the velocity and return it as a Point object, or set it to the given point object.
  71051. * One way to use this is: velocityFromAngle(angle, 200, sprite.velocity) which will set the values directly to the sprites velocity and not create a new Point object.
  71052. *
  71053. * @method Phaser.Physics.Arcade#velocityFromAngle
  71054. * @param {number} angle - The angle in degrees calculated in clockwise positive direction (down = 90 degrees positive, right = 0 degrees positive, up = 90 degrees negative)
  71055. * @param {number} [speed=60] - The speed it will move, in pixels per second sq.
  71056. * @param {Phaser.Point|object} [point] - The Point object in which the x and y properties will be set to the calculated velocity.
  71057. * @return {Phaser.Point} - A Point where point.x contains the velocity x value and point.y contains the velocity y value.
  71058. */
  71059. velocityFromAngle: function (angle, speed, point) {
  71060. if (speed === undefined) { speed = 60; }
  71061. point = point || new Phaser.Point();
  71062. return point.setTo((Math.cos(this.game.math.degToRad(angle)) * speed), (Math.sin(this.game.math.degToRad(angle)) * speed));
  71063. },
  71064. /**
  71065. * Given the rotation (in radians) and speed calculate the velocity and return it as a Point object, or set it to the given point object.
  71066. * One way to use this is: velocityFromRotation(rotation, 200, sprite.velocity) which will set the values directly to the sprites velocity and not create a new Point object.
  71067. *
  71068. * @method Phaser.Physics.Arcade#velocityFromRotation
  71069. * @param {number} rotation - The angle in radians.
  71070. * @param {number} [speed=60] - The speed it will move, in pixels per second sq.
  71071. * @param {Phaser.Point|object} [point] - The Point object in which the x and y properties will be set to the calculated velocity.
  71072. * @return {Phaser.Point} - A Point where point.x contains the velocity x value and point.y contains the velocity y value.
  71073. */
  71074. velocityFromRotation: function (rotation, speed, point) {
  71075. if (speed === undefined) { speed = 60; }
  71076. point = point || new Phaser.Point();
  71077. return point.setTo((Math.cos(rotation) * speed), (Math.sin(rotation) * speed));
  71078. },
  71079. /**
  71080. * Given the rotation (in radians) and speed calculate the acceleration and return it as a Point object, or set it to the given point object.
  71081. * One way to use this is: accelerationFromRotation(rotation, 200, sprite.acceleration) which will set the values directly to the sprites acceleration and not create a new Point object.
  71082. *
  71083. * @method Phaser.Physics.Arcade#accelerationFromRotation
  71084. * @param {number} rotation - The angle in radians.
  71085. * @param {number} [speed=60] - The speed it will move, in pixels per second sq.
  71086. * @param {Phaser.Point|object} [point] - The Point object in which the x and y properties will be set to the calculated acceleration.
  71087. * @return {Phaser.Point} - A Point where point.x contains the acceleration x value and point.y contains the acceleration y value.
  71088. */
  71089. accelerationFromRotation: function (rotation, speed, point) {
  71090. if (speed === undefined) { speed = 60; }
  71091. point = point || new Phaser.Point();
  71092. return point.setTo((Math.cos(rotation) * speed), (Math.sin(rotation) * speed));
  71093. },
  71094. /**
  71095. * Sets the acceleration.x/y property on the display object so it will move towards the target at the given speed (in pixels per second sq.)
  71096. * You must give a maximum speed value, beyond which the display object won't go any faster.
  71097. * Note: The display object does not continuously track the target. If the target changes location during transit the display object will not modify its course.
  71098. * Note: The display object doesn't stop moving once it reaches the destination coordinates.
  71099. *
  71100. * @method Phaser.Physics.Arcade#accelerateToObject
  71101. * @param {any} displayObject - The display object to move.
  71102. * @param {any} destination - The display object to move towards. Can be any object but must have visible x/y properties.
  71103. * @param {number} [speed=60] - The speed it will accelerate in pixels per second.
  71104. * @param {number} [xSpeedMax=500] - The maximum x velocity the display object can reach.
  71105. * @param {number} [ySpeedMax=500] - The maximum y velocity the display object can reach.
  71106. * @return {number} The angle (in radians) that the object should be visually set to in order to match its new trajectory.
  71107. */
  71108. accelerateToObject: function (displayObject, destination, speed, xSpeedMax, ySpeedMax) {
  71109. if (speed === undefined) { speed = 60; }
  71110. if (xSpeedMax === undefined) { xSpeedMax = 1000; }
  71111. if (ySpeedMax === undefined) { ySpeedMax = 1000; }
  71112. var angle = this.angleBetween(displayObject, destination);
  71113. displayObject.body.acceleration.setTo(Math.cos(angle) * speed, Math.sin(angle) * speed);
  71114. displayObject.body.maxVelocity.setTo(xSpeedMax, ySpeedMax);
  71115. return angle;
  71116. },
  71117. /**
  71118. * Sets the acceleration.x/y property on the display object so it will move towards the target at the given speed (in pixels per second sq.)
  71119. * You must give a maximum speed value, beyond which the display object won't go any faster.
  71120. * Note: The display object does not continuously track the target. If the target changes location during transit the display object will not modify its course.
  71121. * Note: The display object doesn't stop moving once it reaches the destination coordinates.
  71122. *
  71123. * @method Phaser.Physics.Arcade#accelerateToPointer
  71124. * @param {any} displayObject - The display object to move.
  71125. * @param {Phaser.Pointer} [pointer] - The pointer to move towards. Defaults to Phaser.Input.activePointer.
  71126. * @param {number} [speed=60] - The speed it will accelerate in pixels per second.
  71127. * @param {number} [xSpeedMax=500] - The maximum x velocity the display object can reach.
  71128. * @param {number} [ySpeedMax=500] - The maximum y velocity the display object can reach.
  71129. * @return {number} The angle (in radians) that the object should be visually set to in order to match its new trajectory.
  71130. */
  71131. accelerateToPointer: function (displayObject, pointer, speed, xSpeedMax, ySpeedMax) {
  71132. if (speed === undefined) { speed = 60; }
  71133. if (pointer === undefined) { pointer = this.game.input.activePointer; }
  71134. if (xSpeedMax === undefined) { xSpeedMax = 1000; }
  71135. if (ySpeedMax === undefined) { ySpeedMax = 1000; }
  71136. var angle = this.angleToPointer(displayObject, pointer);
  71137. displayObject.body.acceleration.setTo(Math.cos(angle) * speed, Math.sin(angle) * speed);
  71138. displayObject.body.maxVelocity.setTo(xSpeedMax, ySpeedMax);
  71139. return angle;
  71140. },
  71141. /**
  71142. * Sets the acceleration.x/y property on the display object so it will move towards the x/y coordinates at the given speed (in pixels per second sq.)
  71143. * You must give a maximum speed value, beyond which the display object won't go any faster.
  71144. * Note: The display object does not continuously track the target. If the target changes location during transit the display object will not modify its course.
  71145. * Note: The display object doesn't stop moving once it reaches the destination coordinates.
  71146. *
  71147. * @method Phaser.Physics.Arcade#accelerateToXY
  71148. * @param {any} displayObject - The display object to move.
  71149. * @param {number} x - The x coordinate to accelerate towards.
  71150. * @param {number} y - The y coordinate to accelerate towards.
  71151. * @param {number} [speed=60] - The speed it will accelerate in pixels per second.
  71152. * @param {number} [xSpeedMax=500] - The maximum x velocity the display object can reach.
  71153. * @param {number} [ySpeedMax=500] - The maximum y velocity the display object can reach.
  71154. * @return {number} The angle (in radians) that the object should be visually set to in order to match its new trajectory.
  71155. */
  71156. accelerateToXY: function (displayObject, x, y, speed, xSpeedMax, ySpeedMax) {
  71157. if (speed === undefined) { speed = 60; }
  71158. if (xSpeedMax === undefined) { xSpeedMax = 1000; }
  71159. if (ySpeedMax === undefined) { ySpeedMax = 1000; }
  71160. var angle = this.angleToXY(displayObject, x, y);
  71161. displayObject.body.acceleration.setTo(Math.cos(angle) * speed, Math.sin(angle) * speed);
  71162. displayObject.body.maxVelocity.setTo(xSpeedMax, ySpeedMax);
  71163. return angle;
  71164. },
  71165. /**
  71166. * Find the distance between two display objects (like Sprites).
  71167. *
  71168. * The optional `world` argument allows you to return the result based on the Game Objects `world` property,
  71169. * instead of its `x` and `y` values. This is useful of the object has been nested inside an offset Group,
  71170. * or parent Game Object.
  71171. *
  71172. * @method Phaser.Physics.Arcade#distanceBetween
  71173. * @param {any} source - The Display Object to test from.
  71174. * @param {any} target - The Display Object to test to.
  71175. * @param {boolean} [world=false] - Calculate the distance using World coordinates (true), or Object coordinates (false, the default)
  71176. * @return {number} The distance between the source and target objects.
  71177. */
  71178. distanceBetween: function (source, target, world) {
  71179. if (world === undefined) { world = false; }
  71180. var dx = (world) ? source.world.x - target.world.x : source.x - target.x;
  71181. var dy = (world) ? source.world.y - target.world.y : source.y - target.y;
  71182. return Math.sqrt(dx * dx + dy * dy);
  71183. },
  71184. /**
  71185. * Find the distance between a display object (like a Sprite) and the given x/y coordinates.
  71186. * The calculation is made from the display objects x/y coordinate. This may be the top-left if its anchor hasn't been changed.
  71187. * If you need to calculate from the center of a display object instead use the method distanceBetweenCenters()
  71188. *
  71189. * The optional `world` argument allows you to return the result based on the Game Objects `world` property,
  71190. * instead of its `x` and `y` values. This is useful of the object has been nested inside an offset Group,
  71191. * or parent Game Object.
  71192. *
  71193. * @method Phaser.Physics.Arcade#distanceToXY
  71194. * @param {any} displayObject - The Display Object to test from.
  71195. * @param {number} x - The x coordinate to move towards.
  71196. * @param {number} y - The y coordinate to move towards.
  71197. * @param {boolean} [world=false] - Calculate the distance using World coordinates (true), or Object coordinates (false, the default)
  71198. * @return {number} The distance between the object and the x/y coordinates.
  71199. */
  71200. distanceToXY: function (displayObject, x, y, world) {
  71201. if (world === undefined) { world = false; }
  71202. var dx = (world) ? displayObject.world.x - x : displayObject.x - x;
  71203. var dy = (world) ? displayObject.world.y - y : displayObject.y - y;
  71204. return Math.sqrt(dx * dx + dy * dy);
  71205. },
  71206. /**
  71207. * Find the distance between a display object (like a Sprite) and a Pointer. If no Pointer is given the Input.activePointer is used.
  71208. * The calculation is made from the display objects x/y coordinate. This may be the top-left if its anchor hasn't been changed.
  71209. * If you need to calculate from the center of a display object instead use the method distanceBetweenCenters()
  71210. *
  71211. * The optional `world` argument allows you to return the result based on the Game Objects `world` property,
  71212. * instead of its `x` and `y` values. This is useful of the object has been nested inside an offset Group,
  71213. * or parent Game Object.
  71214. *
  71215. * @method Phaser.Physics.Arcade#distanceToPointer
  71216. * @param {any} displayObject - The Display Object to test from.
  71217. * @param {Phaser.Pointer} [pointer] - The Phaser.Pointer to test to. If none is given then Input.activePointer is used.
  71218. * @param {boolean} [world=false] - Calculate the distance using World coordinates (true), or Object coordinates (false, the default)
  71219. * @return {number} The distance between the object and the Pointer.
  71220. */
  71221. distanceToPointer: function (displayObject, pointer, world) {
  71222. if (pointer === undefined) { pointer = this.game.input.activePointer; }
  71223. if (world === undefined) { world = false; }
  71224. var dx = (world) ? displayObject.world.x - pointer.worldX : displayObject.x - pointer.worldX;
  71225. var dy = (world) ? displayObject.world.y - pointer.worldY : displayObject.y - pointer.worldY;
  71226. return Math.sqrt(dx * dx + dy * dy);
  71227. },
  71228. /**
  71229. * Find the angle in radians between two display objects (like Sprites).
  71230. *
  71231. * The optional `world` argument allows you to return the result based on the Game Objects `world` property,
  71232. * instead of its `x` and `y` values. This is useful of the object has been nested inside an offset Group,
  71233. * or parent Game Object.
  71234. *
  71235. * @method Phaser.Physics.Arcade#angleBetween
  71236. * @param {any} source - The Display Object to test from.
  71237. * @param {any} target - The Display Object to test to.
  71238. * @param {boolean} [world=false] - Calculate the angle using World coordinates (true), or Object coordinates (false, the default)
  71239. * @return {number} The angle in radians between the source and target display objects.
  71240. */
  71241. angleBetween: function (source, target, world) {
  71242. if (world === undefined) { world = false; }
  71243. if (world)
  71244. {
  71245. return Math.atan2(target.world.y - source.world.y, target.world.x - source.world.x);
  71246. }
  71247. else
  71248. {
  71249. return Math.atan2(target.y - source.y, target.x - source.x);
  71250. }
  71251. },
  71252. /**
  71253. * Find the angle in radians between centers of two display objects (like Sprites).
  71254. *
  71255. * @method Phaser.Physics.Arcade#angleBetweenCenters
  71256. * @param {any} source - The Display Object to test from.
  71257. * @param {any} target - The Display Object to test to.
  71258. * @return {number} The angle in radians between the source and target display objects.
  71259. */
  71260. angleBetweenCenters: function (source, target) {
  71261. var dx = target.centerX - source.centerX;
  71262. var dy = target.centerY - source.centerY;
  71263. return Math.atan2(dy, dx);
  71264. },
  71265. /**
  71266. * Find the angle in radians between a display object (like a Sprite) and the given x/y coordinate.
  71267. *
  71268. * The optional `world` argument allows you to return the result based on the Game Objects `world` property,
  71269. * instead of its `x` and `y` values. This is useful of the object has been nested inside an offset Group,
  71270. * or parent Game Object.
  71271. *
  71272. * @method Phaser.Physics.Arcade#angleToXY
  71273. * @param {any} displayObject - The Display Object to test from.
  71274. * @param {number} x - The x coordinate to get the angle to.
  71275. * @param {number} y - The y coordinate to get the angle to.
  71276. * @param {boolean} [world=false] - Calculate the angle using World coordinates (true), or Object coordinates (false, the default)
  71277. * @return {number} The angle in radians between displayObject.x/y to Pointer.x/y
  71278. */
  71279. angleToXY: function (displayObject, x, y, world) {
  71280. if (world === undefined) { world = false; }
  71281. if (world)
  71282. {
  71283. return Math.atan2(y - displayObject.world.y, x - displayObject.world.x);
  71284. }
  71285. else
  71286. {
  71287. return Math.atan2(y - displayObject.y, x - displayObject.x);
  71288. }
  71289. },
  71290. /**
  71291. * Find the angle in radians between a display object (like a Sprite) and a Pointer, taking their x/y and center into account.
  71292. *
  71293. * The optional `world` argument allows you to return the result based on the Game Objects `world` property,
  71294. * instead of its `x` and `y` values. This is useful of the object has been nested inside an offset Group,
  71295. * or parent Game Object.
  71296. *
  71297. * @method Phaser.Physics.Arcade#angleToPointer
  71298. * @param {any} displayObject - The Display Object to test from.
  71299. * @param {Phaser.Pointer} [pointer] - The Phaser.Pointer to test to. If none is given then Input.activePointer is used.
  71300. * @param {boolean} [world=false] - Calculate the angle using World coordinates (true), or Object coordinates (false, the default)
  71301. * @return {number} The angle in radians between displayObject.x/y to Pointer.x/y
  71302. */
  71303. angleToPointer: function (displayObject, pointer, world) {
  71304. if (pointer === undefined) { pointer = this.game.input.activePointer; }
  71305. if (world === undefined) { world = false; }
  71306. if (world)
  71307. {
  71308. return Math.atan2(pointer.worldY - displayObject.world.y, pointer.worldX - displayObject.world.x);
  71309. }
  71310. else
  71311. {
  71312. return Math.atan2(pointer.worldY - displayObject.y, pointer.worldX - displayObject.x);
  71313. }
  71314. },
  71315. /**
  71316. * Find the angle in radians between a display object (like a Sprite) and a Pointer,
  71317. * taking their x/y and center into account relative to the world.
  71318. *
  71319. * @method Phaser.Physics.Arcade#worldAngleToPointer
  71320. * @param {any} displayObject - The DisplayObjerct to test from.
  71321. * @param {Phaser.Pointer} [pointer] - The Phaser.Pointer to test to. If none is given then Input.activePointer is used.
  71322. * @return {number} The angle in radians between displayObject.world.x/y to Pointer.worldX / worldY
  71323. */
  71324. worldAngleToPointer: function (displayObject, pointer) {
  71325. return this.angleToPointer(displayObject, pointer, true);
  71326. }
  71327. };
  71328. /**
  71329. * @author Richard Davey <rich@photonstorm.com>
  71330. * @copyright 2016 Photon Storm Ltd.
  71331. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  71332. */
  71333. /**
  71334. * The Physics Body is linked to a single Sprite. All physics operations should be performed against the body rather than
  71335. * the Sprite itself. For example you can set the velocity, acceleration, bounce values etc all on the Body.
  71336. *
  71337. * @class Phaser.Physics.Arcade.Body
  71338. * @constructor
  71339. * @param {Phaser.Sprite} sprite - The Sprite object this physics body belongs to.
  71340. */
  71341. Phaser.Physics.Arcade.Body = function (sprite) {
  71342. /**
  71343. * @property {Phaser.Sprite} sprite - Reference to the parent Sprite.
  71344. */
  71345. this.sprite = sprite;
  71346. /**
  71347. * @property {Phaser.Game} game - Local reference to game.
  71348. */
  71349. this.game = sprite.game;
  71350. /**
  71351. * @property {number} type - The type of physics system this body belongs to.
  71352. */
  71353. this.type = Phaser.Physics.ARCADE;
  71354. /**
  71355. * @property {boolean} enable - A disabled body won't be checked for any form of collision or overlap or have its pre/post updates run.
  71356. * @default
  71357. */
  71358. this.enable = true;
  71359. /**
  71360. * If `true` this Body is using circular collision detection. If `false` it is using rectangular.
  71361. * Use `Body.setCircle` to control the collision shape this Body uses.
  71362. * @property {boolean} isCircle
  71363. * @default
  71364. * @readOnly
  71365. */
  71366. this.isCircle = false;
  71367. /**
  71368. * The radius of the circular collision shape this Body is using if Body.setCircle has been enabled.
  71369. * If you wish to change the radius then call `setCircle` again with the new value.
  71370. * If you wish to stop the Body using a circle then call `setCircle` with a radius of zero (or undefined).
  71371. * @property {number} radius
  71372. * @default
  71373. * @readOnly
  71374. */
  71375. this.radius = 0;
  71376. /**
  71377. * @property {Phaser.Point} offset - The offset of the Physics Body from the Sprite x/y position.
  71378. */
  71379. this.offset = new Phaser.Point();
  71380. /**
  71381. * @property {Phaser.Point} position - The position of the physics body.
  71382. * @readonly
  71383. */
  71384. this.position = new Phaser.Point(sprite.x, sprite.y);
  71385. /**
  71386. * @property {Phaser.Point} prev - The previous position of the physics body.
  71387. * @readonly
  71388. */
  71389. this.prev = new Phaser.Point(this.position.x, this.position.y);
  71390. /**
  71391. * @property {boolean} allowRotation - Allow this Body to be rotated? (via angularVelocity, etc)
  71392. * @default
  71393. */
  71394. this.allowRotation = true;
  71395. /**
  71396. * The Body's rotation in degrees, as calculated by its angularVelocity and angularAcceleration. Please understand that the collision Body
  71397. * itself never rotates, it is always axis-aligned. However these values are passed up to the parent Sprite and updates its rotation.
  71398. * @property {number} rotation
  71399. */
  71400. this.rotation = sprite.angle;
  71401. /**
  71402. * @property {number} preRotation - The previous rotation of the physics body.
  71403. * @readonly
  71404. */
  71405. this.preRotation = sprite.angle;
  71406. /**
  71407. * @property {number} width - The calculated width of the physics body.
  71408. * @readonly
  71409. */
  71410. this.width = sprite.width;
  71411. /**
  71412. * @property {number} height - The calculated height of the physics body.
  71413. * @readonly
  71414. */
  71415. this.height = sprite.height;
  71416. /**
  71417. * @property {number} sourceWidth - The un-scaled original size.
  71418. * @readonly
  71419. */
  71420. this.sourceWidth = sprite.width;
  71421. /**
  71422. * @property {number} sourceHeight - The un-scaled original size.
  71423. * @readonly
  71424. */
  71425. this.sourceHeight = sprite.height;
  71426. if (sprite.texture)
  71427. {
  71428. this.sourceWidth = sprite.texture.frame.width;
  71429. this.sourceHeight = sprite.texture.frame.height;
  71430. }
  71431. /**
  71432. * @property {number} halfWidth - The calculated width / 2 of the physics body.
  71433. * @readonly
  71434. */
  71435. this.halfWidth = Math.abs(sprite.width / 2);
  71436. /**
  71437. * @property {number} halfHeight - The calculated height / 2 of the physics body.
  71438. * @readonly
  71439. */
  71440. this.halfHeight = Math.abs(sprite.height / 2);
  71441. /**
  71442. * @property {Phaser.Point} center - The center coordinate of the Physics Body.
  71443. * @readonly
  71444. */
  71445. this.center = new Phaser.Point(sprite.x + this.halfWidth, sprite.y + this.halfHeight);
  71446. /**
  71447. * @property {Phaser.Point} velocity - The velocity, or rate of change in speed of the Body. Measured in pixels per second.
  71448. */
  71449. this.velocity = new Phaser.Point();
  71450. /**
  71451. * @property {Phaser.Point} newVelocity - The new velocity. Calculated during the Body.preUpdate and applied to its position.
  71452. * @readonly
  71453. */
  71454. this.newVelocity = new Phaser.Point();
  71455. /**
  71456. * @property {Phaser.Point} deltaMax - The Sprite position is updated based on the delta x/y values. You can set a cap on those (both +-) using deltaMax.
  71457. */
  71458. this.deltaMax = new Phaser.Point();
  71459. /**
  71460. * @property {Phaser.Point} acceleration - The acceleration is the rate of change of the velocity. Measured in pixels per second squared.
  71461. */
  71462. this.acceleration = new Phaser.Point();
  71463. /**
  71464. * @property {Phaser.Point} drag - The drag applied to the motion of the Body.
  71465. */
  71466. this.drag = new Phaser.Point();
  71467. /**
  71468. * @property {boolean} allowGravity - Allow this Body to be influenced by gravity? Either world or local.
  71469. * @default
  71470. */
  71471. this.allowGravity = true;
  71472. /**
  71473. * @property {Phaser.Point} gravity - A local gravity applied to this Body. If non-zero this over rides any world gravity, unless Body.allowGravity is set to false.
  71474. */
  71475. this.gravity = new Phaser.Point();
  71476. /**
  71477. * @property {Phaser.Point} bounce - The elasticity of the Body when colliding. bounce.x/y = 1 means full rebound, bounce.x/y = 0.5 means 50% rebound velocity.
  71478. */
  71479. this.bounce = new Phaser.Point();
  71480. /**
  71481. * The elasticity of the Body when colliding with the World bounds.
  71482. * By default this property is `null`, in which case `Body.bounce` is used instead. Set this property
  71483. * to a Phaser.Point object in order to enable a World bounds specific bounce value.
  71484. * @property {Phaser.Point} worldBounce
  71485. */
  71486. this.worldBounce = null;
  71487. /**
  71488. * A Signal that is dispatched when this Body collides with the world bounds.
  71489. * Due to the potentially high volume of signals this could create it is disabled by default.
  71490. * To use this feature set this property to a Phaser.Signal: `sprite.body.onWorldBounds = new Phaser.Signal()`
  71491. * and it will be called when a collision happens, passing five arguments:
  71492. * `onWorldBounds(sprite, up, down, left, right)`
  71493. * where the Sprite is a reference to the Sprite that owns this Body, and the other arguments are booleans
  71494. * indicating on which side of the world the Body collided.
  71495. * @property {Phaser.Signal} onWorldBounds
  71496. */
  71497. this.onWorldBounds = null;
  71498. /**
  71499. * A Signal that is dispatched when this Body collides with another Body.
  71500. *
  71501. * You still need to call `game.physics.arcade.collide` in your `update` method in order
  71502. * for this signal to be dispatched.
  71503. *
  71504. * Usually you'd pass a callback to the `collide` method, but this signal provides for
  71505. * a different level of notification.
  71506. *
  71507. * Due to the potentially high volume of signals this could create it is disabled by default.
  71508. *
  71509. * To use this feature set this property to a Phaser.Signal: `sprite.body.onCollide = new Phaser.Signal()`
  71510. * and it will be called when a collision happens, passing two arguments: the sprites which collided.
  71511. * The first sprite in the argument is always the owner of this Body.
  71512. *
  71513. * If two Bodies with this Signal set collide, both will dispatch the Signal.
  71514. * @property {Phaser.Signal} onCollide
  71515. */
  71516. this.onCollide = null;
  71517. /**
  71518. * A Signal that is dispatched when this Body overlaps with another Body.
  71519. *
  71520. * You still need to call `game.physics.arcade.overlap` in your `update` method in order
  71521. * for this signal to be dispatched.
  71522. *
  71523. * Usually you'd pass a callback to the `overlap` method, but this signal provides for
  71524. * a different level of notification.
  71525. *
  71526. * Due to the potentially high volume of signals this could create it is disabled by default.
  71527. *
  71528. * To use this feature set this property to a Phaser.Signal: `sprite.body.onOverlap = new Phaser.Signal()`
  71529. * and it will be called when a collision happens, passing two arguments: the sprites which collided.
  71530. * The first sprite in the argument is always the owner of this Body.
  71531. *
  71532. * If two Bodies with this Signal set collide, both will dispatch the Signal.
  71533. * @property {Phaser.Signal} onOverlap
  71534. */
  71535. this.onOverlap = null;
  71536. /**
  71537. * @property {Phaser.Point} maxVelocity - The maximum velocity in pixels per second sq. that the Body can reach.
  71538. * @default
  71539. */
  71540. this.maxVelocity = new Phaser.Point(10000, 10000);
  71541. /**
  71542. * @property {Phaser.Point} friction - The amount of movement that will occur if another object 'rides' this one.
  71543. */
  71544. this.friction = new Phaser.Point(1, 0);
  71545. /**
  71546. * @property {number} angularVelocity - The angular velocity controls the rotation speed of the Body. It is measured in degrees per second.
  71547. * @default
  71548. */
  71549. this.angularVelocity = 0;
  71550. /**
  71551. * @property {number} angularAcceleration - The angular acceleration is the rate of change of the angular velocity. Measured in degrees per second squared.
  71552. * @default
  71553. */
  71554. this.angularAcceleration = 0;
  71555. /**
  71556. * @property {number} angularDrag - The drag applied during the rotation of the Body. Measured in degrees per second squared.
  71557. * @default
  71558. */
  71559. this.angularDrag = 0;
  71560. /**
  71561. * @property {number} maxAngular - The maximum angular velocity in degrees per second that the Body can reach.
  71562. * @default
  71563. */
  71564. this.maxAngular = 1000;
  71565. /**
  71566. * @property {number} mass - The mass of the Body. When two bodies collide their mass is used in the calculation to determine the exchange of velocity.
  71567. * @default
  71568. */
  71569. this.mass = 1;
  71570. /**
  71571. * @property {number} angle - The angle of the Body's velocity in radians.
  71572. * @readonly
  71573. */
  71574. this.angle = 0;
  71575. /**
  71576. * @property {number} speed - The speed of the Body as calculated by its velocity.
  71577. * @readonly
  71578. */
  71579. this.speed = 0;
  71580. /**
  71581. * @property {number} facing - A const reference to the direction the Body is traveling or facing.
  71582. * @default
  71583. */
  71584. this.facing = Phaser.NONE;
  71585. /**
  71586. * @property {boolean} immovable - An immovable Body will not receive any impacts from other bodies.
  71587. * @default
  71588. */
  71589. this.immovable = false;
  71590. /**
  71591. * If you have a Body that is being moved around the world via a tween or a Group motion, but its local x/y position never
  71592. * actually changes, then you should set Body.moves = false. Otherwise it will most likely fly off the screen.
  71593. * If you want the physics system to move the body around, then set moves to true.
  71594. * @property {boolean} moves - Set to true to allow the Physics system to move this Body, otherwise false to move it manually.
  71595. * @default
  71596. */
  71597. this.moves = true;
  71598. /**
  71599. * This flag allows you to disable the custom x separation that takes place by Physics.Arcade.separate.
  71600. * Used in combination with your own collision processHandler you can create whatever type of collision response you need.
  71601. * @property {boolean} customSeparateX - Use a custom separation system or the built-in one?
  71602. * @default
  71603. */
  71604. this.customSeparateX = false;
  71605. /**
  71606. * This flag allows you to disable the custom y separation that takes place by Physics.Arcade.separate.
  71607. * Used in combination with your own collision processHandler you can create whatever type of collision response you need.
  71608. * @property {boolean} customSeparateY - Use a custom separation system or the built-in one?
  71609. * @default
  71610. */
  71611. this.customSeparateY = false;
  71612. /**
  71613. * When this body collides with another, the amount of overlap is stored here.
  71614. * @property {number} overlapX - The amount of horizontal overlap during the collision.
  71615. */
  71616. this.overlapX = 0;
  71617. /**
  71618. * When this body collides with another, the amount of overlap is stored here.
  71619. * @property {number} overlapY - The amount of vertical overlap during the collision.
  71620. */
  71621. this.overlapY = 0;
  71622. /**
  71623. * If `Body.isCircle` is true, and this body collides with another circular body, the amount of overlap is stored here.
  71624. * @property {number} overlapR - The amount of overlap during the collision.
  71625. */
  71626. this.overlapR = 0;
  71627. /**
  71628. * If a body is overlapping with another body, but neither of them are moving (maybe they spawned on-top of each other?) this is set to true.
  71629. * @property {boolean} embedded - Body embed value.
  71630. */
  71631. this.embedded = false;
  71632. /**
  71633. * A Body can be set to collide against the World bounds automatically and rebound back into the World if this is set to true. Otherwise it will leave the World.
  71634. * @property {boolean} collideWorldBounds - Should the Body collide with the World bounds?
  71635. */
  71636. this.collideWorldBounds = false;
  71637. /**
  71638. * Set the checkCollision properties to control which directions collision is processed for this Body.
  71639. * For example checkCollision.up = false means it won't collide when the collision happened while moving up.
  71640. * If you need to disable a Body entirely, use `body.enable = false`, this will also disable motion.
  71641. * If you need to disable just collision and/or overlap checks, but retain motion, set `checkCollision.none = true`.
  71642. * @property {object} checkCollision - An object containing allowed collision.
  71643. */
  71644. this.checkCollision = { none: false, any: true, up: true, down: true, left: true, right: true };
  71645. /**
  71646. * This object is populated with boolean values when the Body collides with another.
  71647. * touching.up = true means the collision happened to the top of this Body for example.
  71648. * @property {object} touching - An object containing touching results.
  71649. */
  71650. this.touching = { none: true, up: false, down: false, left: false, right: false };
  71651. /**
  71652. * This object is populated with previous touching values from the bodies previous collision.
  71653. * @property {object} wasTouching - An object containing previous touching results.
  71654. */
  71655. this.wasTouching = { none: true, up: false, down: false, left: false, right: false };
  71656. /**
  71657. * This object is populated with boolean values when the Body collides with the World bounds or a Tile.
  71658. * For example if blocked.up is true then the Body cannot move up.
  71659. * @property {object} blocked - An object containing on which faces this Body is blocked from moving, if any.
  71660. */
  71661. this.blocked = { up: false, down: false, left: false, right: false };
  71662. /**
  71663. * If this is an especially small or fast moving object then it can sometimes skip over tilemap collisions if it moves through a tile in a step.
  71664. * Set this padding value to add extra padding to its bounds. tilePadding.x applied to its width, y to its height.
  71665. * @property {Phaser.Point} tilePadding - Extra padding to be added to this sprite's dimensions when checking for tile collision.
  71666. */
  71667. this.tilePadding = new Phaser.Point();
  71668. /**
  71669. * @property {boolean} dirty - If this Body in a preUpdate (true) or postUpdate (false) state?
  71670. */
  71671. this.dirty = false;
  71672. /**
  71673. * @property {boolean} skipQuadTree - If true and you collide this Sprite against a Group, it will disable the collision check from using a QuadTree.
  71674. */
  71675. this.skipQuadTree = false;
  71676. /**
  71677. * If true the Body will check itself against the Sprite.getBounds() dimensions and adjust its width and height accordingly.
  71678. * If false it will compare its dimensions against the Sprite scale instead, and adjust its width height if the scale has changed.
  71679. * Typically you would need to enable syncBounds if your sprite is the child of a responsive display object such as a FlexLayer,
  71680. * or in any situation where the Sprite scale doesn't change, but its parents scale is effecting the dimensions regardless.
  71681. * @property {boolean} syncBounds
  71682. * @default
  71683. */
  71684. this.syncBounds = false;
  71685. /**
  71686. * @property {boolean} isMoving - Set by the `moveTo` and `moveFrom` methods.
  71687. */
  71688. this.isMoving = false;
  71689. /**
  71690. * @property {boolean} stopVelocityOnCollide - Set by the `moveTo` and `moveFrom` methods.
  71691. */
  71692. this.stopVelocityOnCollide = true;
  71693. /**
  71694. * @property {integer} moveTimer - Internal time used by the `moveTo` and `moveFrom` methods.
  71695. * @private
  71696. */
  71697. this.moveTimer = 0;
  71698. /**
  71699. * @property {integer} moveDistance - Internal distance value, used by the `moveTo` and `moveFrom` methods.
  71700. * @private
  71701. */
  71702. this.moveDistance = 0;
  71703. /**
  71704. * @property {integer} moveDuration - Internal duration value, used by the `moveTo` and `moveFrom` methods.
  71705. * @private
  71706. */
  71707. this.moveDuration = 0;
  71708. /**
  71709. * @property {Phaser.Line} moveTarget - Set by the `moveTo` method, and updated each frame.
  71710. * @private
  71711. */
  71712. this.moveTarget = null;
  71713. /**
  71714. * @property {Phaser.Point} moveEnd - Set by the `moveTo` method, and updated each frame.
  71715. * @private
  71716. */
  71717. this.moveEnd = null;
  71718. /**
  71719. * @property {Phaser.Signal} onMoveComplete - Listen for the completion of `moveTo` or `moveFrom` events.
  71720. */
  71721. this.onMoveComplete = new Phaser.Signal();
  71722. /**
  71723. * @property {function} movementCallback - Optional callback. If set, invoked during the running of `moveTo` or `moveFrom` events.
  71724. */
  71725. this.movementCallback = null;
  71726. /**
  71727. * @property {object} movementCallbackContext - Context in which to call the movementCallback.
  71728. */
  71729. this.movementCallbackContext = null;
  71730. /**
  71731. * @property {boolean} _reset - Internal cache var.
  71732. * @private
  71733. */
  71734. this._reset = true;
  71735. /**
  71736. * @property {number} _sx - Internal cache var.
  71737. * @private
  71738. */
  71739. this._sx = sprite.scale.x;
  71740. /**
  71741. * @property {number} _sy - Internal cache var.
  71742. * @private
  71743. */
  71744. this._sy = sprite.scale.y;
  71745. /**
  71746. * @property {number} _dx - Internal cache var.
  71747. * @private
  71748. */
  71749. this._dx = 0;
  71750. /**
  71751. * @property {number} _dy - Internal cache var.
  71752. * @private
  71753. */
  71754. this._dy = 0;
  71755. };
  71756. Phaser.Physics.Arcade.Body.prototype = {
  71757. /**
  71758. * Internal method.
  71759. *
  71760. * @method Phaser.Physics.Arcade.Body#updateBounds
  71761. * @protected
  71762. */
  71763. updateBounds: function () {
  71764. if (this.syncBounds)
  71765. {
  71766. var b = this.sprite.getBounds();
  71767. b.ceilAll();
  71768. if (b.width !== this.width || b.height !== this.height)
  71769. {
  71770. this.width = b.width;
  71771. this.height = b.height;
  71772. this._reset = true;
  71773. }
  71774. }
  71775. else
  71776. {
  71777. var asx = Math.abs(this.sprite.scale.x);
  71778. var asy = Math.abs(this.sprite.scale.y);
  71779. if (asx !== this._sx || asy !== this._sy)
  71780. {
  71781. this.width = this.sourceWidth * asx;
  71782. this.height = this.sourceHeight * asy;
  71783. this._sx = asx;
  71784. this._sy = asy;
  71785. this._reset = true;
  71786. }
  71787. }
  71788. if (this._reset)
  71789. {
  71790. this.halfWidth = Math.floor(this.width / 2);
  71791. this.halfHeight = Math.floor(this.height / 2);
  71792. this.center.setTo(this.position.x + this.halfWidth, this.position.y + this.halfHeight);
  71793. }
  71794. },
  71795. /**
  71796. * Internal method.
  71797. *
  71798. * @method Phaser.Physics.Arcade.Body#preUpdate
  71799. * @protected
  71800. */
  71801. preUpdate: function () {
  71802. if (!this.enable || this.game.physics.arcade.isPaused)
  71803. {
  71804. return;
  71805. }
  71806. this.dirty = true;
  71807. // Store and reset collision flags
  71808. this.wasTouching.none = this.touching.none;
  71809. this.wasTouching.up = this.touching.up;
  71810. this.wasTouching.down = this.touching.down;
  71811. this.wasTouching.left = this.touching.left;
  71812. this.wasTouching.right = this.touching.right;
  71813. this.touching.none = true;
  71814. this.touching.up = false;
  71815. this.touching.down = false;
  71816. this.touching.left = false;
  71817. this.touching.right = false;
  71818. this.blocked.up = false;
  71819. this.blocked.down = false;
  71820. this.blocked.left = false;
  71821. this.blocked.right = false;
  71822. this.embedded = false;
  71823. this.updateBounds();
  71824. this.position.x = (this.sprite.world.x - (this.sprite.anchor.x * this.sprite.width)) + this.sprite.scale.x * this.offset.x;
  71825. this.position.x -= this.sprite.scale.x < 0 ? this.width : 0;
  71826. this.position.y = (this.sprite.world.y - (this.sprite.anchor.y * this.sprite.height)) + this.sprite.scale.y * this.offset.y;
  71827. this.position.y -= this.sprite.scale.y < 0 ? this.height : 0;
  71828. this.rotation = this.sprite.angle;
  71829. this.preRotation = this.rotation;
  71830. if (this._reset || this.sprite.fresh)
  71831. {
  71832. this.prev.x = this.position.x;
  71833. this.prev.y = this.position.y;
  71834. }
  71835. if (this.moves)
  71836. {
  71837. this.game.physics.arcade.updateMotion(this);
  71838. this.newVelocity.set(this.velocity.x * this.game.time.physicsElapsed, this.velocity.y * this.game.time.physicsElapsed);
  71839. this.position.x += this.newVelocity.x;
  71840. this.position.y += this.newVelocity.y;
  71841. if (this.position.x !== this.prev.x || this.position.y !== this.prev.y)
  71842. {
  71843. this.angle = Math.atan2(this.velocity.y, this.velocity.x);
  71844. }
  71845. this.speed = Math.sqrt(this.velocity.x * this.velocity.x + this.velocity.y * this.velocity.y);
  71846. // Now the State update will throw collision checks at the Body
  71847. // And finally we'll integrate the new position back to the Sprite in postUpdate
  71848. if (this.collideWorldBounds)
  71849. {
  71850. if (this.checkWorldBounds() && this.onWorldBounds)
  71851. {
  71852. this.onWorldBounds.dispatch(this.sprite, this.blocked.up, this.blocked.down, this.blocked.left, this.blocked.right);
  71853. }
  71854. }
  71855. }
  71856. this._dx = this.deltaX();
  71857. this._dy = this.deltaY();
  71858. this._reset = false;
  71859. },
  71860. /**
  71861. * Internal method.
  71862. *
  71863. * @method Phaser.Physics.Arcade.Body#updateMovement
  71864. * @protected
  71865. */
  71866. updateMovement: function () {
  71867. var percent = 0;
  71868. var collided = (this.overlapX !== 0 || this.overlapY !== 0);
  71869. // Duration or Distance based?
  71870. if (this.moveDuration > 0)
  71871. {
  71872. this.moveTimer += this.game.time.elapsedMS;
  71873. percent = this.moveTimer / this.moveDuration;
  71874. }
  71875. else
  71876. {
  71877. this.moveTarget.end.set(this.position.x, this.position.y);
  71878. percent = this.moveTarget.length / this.moveDistance;
  71879. }
  71880. if (this.movementCallback)
  71881. {
  71882. var result = this.movementCallback.call(this.movementCallbackContext, this, this.velocity, percent);
  71883. }
  71884. if (collided || percent >= 1 || (result !== undefined && result !== true))
  71885. {
  71886. this.stopMovement((percent >= 1) || (this.stopVelocityOnCollide && collided));
  71887. return false;
  71888. }
  71889. return true;
  71890. },
  71891. /**
  71892. * If this Body is moving as a result of a call to `moveTo` or `moveFrom` (i.e. it
  71893. * has Body.isMoving true), then calling this method will stop the movement before
  71894. * either the duration or distance counters expire.
  71895. *
  71896. * The `onMoveComplete` signal is dispatched.
  71897. *
  71898. * @method Phaser.Physics.Arcade.Body#stopMovement
  71899. * @param {boolean} [stopVelocity] - Should the Body.velocity be set to zero?
  71900. */
  71901. stopMovement: function (stopVelocity) {
  71902. if (this.isMoving)
  71903. {
  71904. this.isMoving = false;
  71905. if (stopVelocity)
  71906. {
  71907. this.velocity.set(0);
  71908. }
  71909. // Send the Sprite this Body belongs to
  71910. // and a boolean indicating if it stopped because of a collision or not
  71911. this.onMoveComplete.dispatch(this.sprite, (this.overlapX !== 0 || this.overlapY !== 0));
  71912. }
  71913. },
  71914. /**
  71915. * Internal method.
  71916. *
  71917. * @method Phaser.Physics.Arcade.Body#postUpdate
  71918. * @protected
  71919. */
  71920. postUpdate: function () {
  71921. // Only allow postUpdate to be called once per frame
  71922. if (!this.enable || !this.dirty)
  71923. {
  71924. return;
  71925. }
  71926. // Moving?
  71927. if (this.isMoving)
  71928. {
  71929. this.updateMovement();
  71930. }
  71931. this.dirty = false;
  71932. if (this.deltaX() < 0)
  71933. {
  71934. this.facing = Phaser.LEFT;
  71935. }
  71936. else if (this.deltaX() > 0)
  71937. {
  71938. this.facing = Phaser.RIGHT;
  71939. }
  71940. if (this.deltaY() < 0)
  71941. {
  71942. this.facing = Phaser.UP;
  71943. }
  71944. else if (this.deltaY() > 0)
  71945. {
  71946. this.facing = Phaser.DOWN;
  71947. }
  71948. if (this.moves)
  71949. {
  71950. this._dx = this.deltaX();
  71951. this._dy = this.deltaY();
  71952. if (this.deltaMax.x !== 0 && this._dx !== 0)
  71953. {
  71954. if (this._dx < 0 && this._dx < -this.deltaMax.x)
  71955. {
  71956. this._dx = -this.deltaMax.x;
  71957. }
  71958. else if (this._dx > 0 && this._dx > this.deltaMax.x)
  71959. {
  71960. this._dx = this.deltaMax.x;
  71961. }
  71962. }
  71963. if (this.deltaMax.y !== 0 && this._dy !== 0)
  71964. {
  71965. if (this._dy < 0 && this._dy < -this.deltaMax.y)
  71966. {
  71967. this._dy = -this.deltaMax.y;
  71968. }
  71969. else if (this._dy > 0 && this._dy > this.deltaMax.y)
  71970. {
  71971. this._dy = this.deltaMax.y;
  71972. }
  71973. }
  71974. this.sprite.position.x += this._dx;
  71975. this.sprite.position.y += this._dy;
  71976. this._reset = true;
  71977. }
  71978. this.center.setTo(this.position.x + this.halfWidth, this.position.y + this.halfHeight);
  71979. if (this.allowRotation)
  71980. {
  71981. this.sprite.angle += this.deltaZ();
  71982. }
  71983. this.prev.x = this.position.x;
  71984. this.prev.y = this.position.y;
  71985. },
  71986. /**
  71987. * Internal method.
  71988. *
  71989. * @method Phaser.Physics.Arcade.Body#checkWorldBounds
  71990. * @protected
  71991. * @return {boolean} True if the Body collided with the world bounds, otherwise false.
  71992. */
  71993. checkWorldBounds: function () {
  71994. var pos = this.position;
  71995. var bounds = this.game.physics.arcade.bounds;
  71996. var check = this.game.physics.arcade.checkCollision;
  71997. var bx = (this.worldBounce) ? -this.worldBounce.x : -this.bounce.x;
  71998. var by = (this.worldBounce) ? -this.worldBounce.y : -this.bounce.y;
  71999. if (this.isCircle)
  72000. {
  72001. var bodyBounds = {
  72002. x: this.center.x - this.radius,
  72003. y: this.center.y - this.radius,
  72004. right: this.center.x + this.radius,
  72005. bottom: this.center.y + this.radius
  72006. };
  72007. if (bodyBounds.x < bounds.x && check.left)
  72008. {
  72009. pos.x = bounds.x - this.halfWidth + this.radius;
  72010. this.velocity.x *= bx;
  72011. this.blocked.left = true;
  72012. }
  72013. else if (bodyBounds.right > bounds.right && check.right)
  72014. {
  72015. pos.x = bounds.right - this.halfWidth - this.radius;
  72016. this.velocity.x *= bx;
  72017. this.blocked.right = true;
  72018. }
  72019. if (bodyBounds.y < bounds.y && check.up)
  72020. {
  72021. pos.y = bounds.y - this.halfHeight + this.radius;
  72022. this.velocity.y *= by;
  72023. this.blocked.up = true;
  72024. }
  72025. else if (bodyBounds.bottom > bounds.bottom && check.down)
  72026. {
  72027. pos.y = bounds.bottom - this.halfHeight - this.radius;
  72028. this.velocity.y *= by;
  72029. this.blocked.down = true;
  72030. }
  72031. }
  72032. else
  72033. {
  72034. if (pos.x < bounds.x && check.left)
  72035. {
  72036. pos.x = bounds.x;
  72037. this.velocity.x *= bx;
  72038. this.blocked.left = true;
  72039. }
  72040. else if (this.right > bounds.right && check.right)
  72041. {
  72042. pos.x = bounds.right - this.width;
  72043. this.velocity.x *= bx;
  72044. this.blocked.right = true;
  72045. }
  72046. if (pos.y < bounds.y && check.up)
  72047. {
  72048. pos.y = bounds.y;
  72049. this.velocity.y *= by;
  72050. this.blocked.up = true;
  72051. }
  72052. else if (this.bottom > bounds.bottom && check.down)
  72053. {
  72054. pos.y = bounds.bottom - this.height;
  72055. this.velocity.y *= by;
  72056. this.blocked.down = true;
  72057. }
  72058. }
  72059. return (this.blocked.up || this.blocked.down || this.blocked.left || this.blocked.right);
  72060. },
  72061. /**
  72062. * Note: This method is experimental, and may be changed or removed in a future release.
  72063. *
  72064. * This method moves the Body in the given direction, for the duration specified.
  72065. * It works by setting the velocity on the Body, and an internal timer, and then
  72066. * monitoring the duration each frame. When the duration is up the movement is
  72067. * stopped and the `Body.onMoveComplete` signal is dispatched.
  72068. *
  72069. * Movement also stops if the Body collides or overlaps with any other Body.
  72070. *
  72071. * You can control if the velocity should be reset to zero on collision, by using
  72072. * the property `Body.stopVelocityOnCollide`.
  72073. *
  72074. * Stop the movement at any time by calling `Body.stopMovement`.
  72075. *
  72076. * You can optionally set a speed in pixels per second. If not specified it
  72077. * will use the current `Body.speed` value. If this is zero, the function will return false.
  72078. *
  72079. * Please note that due to browser timings you should allow for a variance in
  72080. * when the duration will actually expire. Depending on system it may be as much as
  72081. * +- 50ms. Also this method doesn't take into consideration any other forces acting
  72082. * on the Body, such as Gravity, drag or maxVelocity, all of which may impact the
  72083. * movement.
  72084. *
  72085. * @method Phaser.Physics.Arcade.Body#moveFrom
  72086. * @param {integer} duration - The duration of the movement, in ms.
  72087. * @param {integer} [speed] - The speed of the movement, in pixels per second. If not provided `Body.speed` is used.
  72088. * @param {integer} [direction] - The angle of movement. If not provided `Body.angle` is used.
  72089. * @return {boolean} True if the movement successfully started, otherwise false.
  72090. */
  72091. moveFrom: function (duration, speed, direction) {
  72092. if (speed === undefined) { speed = this.speed; }
  72093. if (speed === 0)
  72094. {
  72095. return false;
  72096. }
  72097. var angle;
  72098. if (direction === undefined)
  72099. {
  72100. angle = this.angle;
  72101. direction = this.game.math.radToDeg(angle);
  72102. }
  72103. else
  72104. {
  72105. angle = this.game.math.degToRad(direction);
  72106. }
  72107. this.moveTimer = 0;
  72108. this.moveDuration = duration;
  72109. // Avoid sin/cos
  72110. if (direction === 0 || direction === 180)
  72111. {
  72112. this.velocity.set(Math.cos(angle) * speed, 0);
  72113. }
  72114. else if (direction === 90 || direction === 270)
  72115. {
  72116. this.velocity.set(0, Math.sin(angle) * speed);
  72117. }
  72118. else
  72119. {
  72120. this.velocity.set(Math.cos(angle) * speed, Math.sin(angle) * speed);
  72121. }
  72122. this.isMoving = true;
  72123. return true;
  72124. },
  72125. /**
  72126. * Note: This method is experimental, and may be changed or removed in a future release.
  72127. *
  72128. * This method moves the Body in the given direction, for the duration specified.
  72129. * It works by setting the velocity on the Body, and an internal distance counter.
  72130. * The distance is monitored each frame. When the distance equals the distance
  72131. * specified in this call, the movement is stopped, and the `Body.onMoveComplete`
  72132. * signal is dispatched.
  72133. *
  72134. * Movement also stops if the Body collides or overlaps with any other Body.
  72135. *
  72136. * You can control if the velocity should be reset to zero on collision, by using
  72137. * the property `Body.stopVelocityOnCollide`.
  72138. *
  72139. * Stop the movement at any time by calling `Body.stopMovement`.
  72140. *
  72141. * Please note that due to browser timings you should allow for a variance in
  72142. * when the distance will actually expire.
  72143. *
  72144. * Note: This method doesn't take into consideration any other forces acting
  72145. * on the Body, such as Gravity, drag or maxVelocity, all of which may impact the
  72146. * movement.
  72147. *
  72148. * @method Phaser.Physics.Arcade.Body#moveTo
  72149. * @param {integer} duration - The duration of the movement, in ms.
  72150. * @param {integer} distance - The distance, in pixels, the Body will move.
  72151. * @param {integer} [direction] - The angle of movement. If not provided `Body.angle` is used.
  72152. * @return {boolean} True if the movement successfully started, otherwise false.
  72153. */
  72154. moveTo: function (duration, distance, direction) {
  72155. var speed = distance / (duration / 1000);
  72156. if (speed === 0)
  72157. {
  72158. return false;
  72159. }
  72160. var angle;
  72161. if (direction === undefined)
  72162. {
  72163. angle = this.angle;
  72164. direction = this.game.math.radToDeg(angle);
  72165. }
  72166. else
  72167. {
  72168. angle = this.game.math.degToRad(direction);
  72169. }
  72170. distance = Math.abs(distance);
  72171. this.moveDuration = 0;
  72172. this.moveDistance = distance;
  72173. if (this.moveTarget === null)
  72174. {
  72175. this.moveTarget = new Phaser.Line();
  72176. this.moveEnd = new Phaser.Point();
  72177. }
  72178. this.moveTarget.fromAngle(this.x, this.y, angle, distance);
  72179. this.moveEnd.set(this.moveTarget.end.x, this.moveTarget.end.y);
  72180. this.moveTarget.setTo(this.x, this.y, this.x, this.y);
  72181. // Avoid sin/cos
  72182. if (direction === 0 || direction === 180)
  72183. {
  72184. this.velocity.set(Math.cos(angle) * speed, 0);
  72185. }
  72186. else if (direction === 90 || direction === 270)
  72187. {
  72188. this.velocity.set(0, Math.sin(angle) * speed);
  72189. }
  72190. else
  72191. {
  72192. this.velocity.set(Math.cos(angle) * speed, Math.sin(angle) * speed);
  72193. }
  72194. this.isMoving = true;
  72195. return true;
  72196. },
  72197. /**
  72198. * You can modify the size of the physics Body to be any dimension you need.
  72199. * This allows you to make it smaller, or larger, than the parent Sprite.
  72200. * You can also control the x and y offset of the Body. This is the position of the
  72201. * Body relative to the top-left of the Sprite _texture_.
  72202. *
  72203. * For example: If you have a Sprite with a texture that is 80x100 in size,
  72204. * and you want the physics body to be 32x32 pixels in the middle of the texture, you would do:
  72205. *
  72206. * `setSize(32, 32, 24, 34)`
  72207. *
  72208. * Where the first two parameters is the new Body size (32x32 pixels).
  72209. * 24 is the horizontal offset of the Body from the top-left of the Sprites texture, and 34
  72210. * is the vertical offset.
  72211. *
  72212. * Calling `setSize` on a Body that has already had `setCircle` will reset all of the Circle
  72213. * properties, making this Body rectangular again.
  72214. *
  72215. * @method Phaser.Physics.Arcade.Body#setSize
  72216. * @param {number} width - The width of the Body.
  72217. * @param {number} height - The height of the Body.
  72218. * @param {number} [offsetX] - The X offset of the Body from the top-left of the Sprites texture.
  72219. * @param {number} [offsetY] - The Y offset of the Body from the top-left of the Sprites texture.
  72220. */
  72221. setSize: function (width, height, offsetX, offsetY) {
  72222. if (offsetX === undefined) { offsetX = this.offset.x; }
  72223. if (offsetY === undefined) { offsetY = this.offset.y; }
  72224. this.sourceWidth = width;
  72225. this.sourceHeight = height;
  72226. this.width = this.sourceWidth * this._sx;
  72227. this.height = this.sourceHeight * this._sy;
  72228. this.halfWidth = Math.floor(this.width / 2);
  72229. this.halfHeight = Math.floor(this.height / 2);
  72230. this.offset.setTo(offsetX, offsetY);
  72231. this.center.setTo(this.position.x + this.halfWidth, this.position.y + this.halfHeight);
  72232. this.isCircle = false;
  72233. this.radius = 0;
  72234. },
  72235. /**
  72236. * Sets this Body as using a circle, of the given radius, for all collision detection instead of a rectangle.
  72237. * The radius is given in pixels and is the distance from the center of the circle to the edge.
  72238. *
  72239. * You can also control the x and y offset, which is the position of the Body relative to the top-left of the Sprite.
  72240. *
  72241. * To change a Body back to being rectangular again call `Body.setSize`.
  72242. *
  72243. * Note: Circular collision only happens with other Arcade Physics bodies, it does not
  72244. * work against tile maps, where rectangular collision is the only method supported.
  72245. *
  72246. * @method Phaser.Physics.Arcade.Body#setCircle
  72247. * @param {number} [radius] - The radius of the Body in pixels. Pass a value of zero / undefined, to stop the Body using a circle for collision.
  72248. * @param {number} [offsetX] - The X offset of the Body from the Sprite position.
  72249. * @param {number} [offsetY] - The Y offset of the Body from the Sprite position.
  72250. */
  72251. setCircle: function (radius, offsetX, offsetY) {
  72252. if (offsetX === undefined) { offsetX = this.offset.x; }
  72253. if (offsetY === undefined) { offsetY = this.offset.y; }
  72254. if (radius > 0)
  72255. {
  72256. this.isCircle = true;
  72257. this.radius = radius;
  72258. this.sourceWidth = radius * 2;
  72259. this.sourceHeight = radius * 2;
  72260. this.width = this.sourceWidth * this._sx;
  72261. this.height = this.sourceHeight * this._sy;
  72262. this.halfWidth = Math.floor(this.width / 2);
  72263. this.halfHeight = Math.floor(this.height / 2);
  72264. this.offset.setTo(offsetX, offsetY);
  72265. this.center.setTo(this.position.x + this.halfWidth, this.position.y + this.halfHeight);
  72266. }
  72267. else
  72268. {
  72269. this.isCircle = false;
  72270. }
  72271. },
  72272. /**
  72273. * Resets all Body values (velocity, acceleration, rotation, etc)
  72274. *
  72275. * @method Phaser.Physics.Arcade.Body#reset
  72276. * @param {number} x - The new x position of the Body.
  72277. * @param {number} y - The new y position of the Body.
  72278. */
  72279. reset: function (x, y) {
  72280. this.velocity.set(0);
  72281. this.acceleration.set(0);
  72282. this.speed = 0;
  72283. this.angularVelocity = 0;
  72284. this.angularAcceleration = 0;
  72285. this.position.x = (x - (this.sprite.anchor.x * this.sprite.width)) + this.sprite.scale.x * this.offset.x;
  72286. this.position.x -= this.sprite.scale.x < 0 ? this.width : 0;
  72287. this.position.y = (y - (this.sprite.anchor.y * this.sprite.height)) + this.sprite.scale.y * this.offset.y;
  72288. this.position.y -= this.sprite.scale.y < 0 ? this.height : 0;
  72289. this.prev.x = this.position.x;
  72290. this.prev.y = this.position.y;
  72291. this.rotation = this.sprite.angle;
  72292. this.preRotation = this.rotation;
  72293. this._sx = this.sprite.scale.x;
  72294. this._sy = this.sprite.scale.y;
  72295. this.center.setTo(this.position.x + this.halfWidth, this.position.y + this.halfHeight);
  72296. },
  72297. /**
  72298. * Returns the bounds of this physics body.
  72299. *
  72300. * Only used internally by the World collision methods.
  72301. *
  72302. * @method Phaser.Physics.Arcade.Body#getBounds
  72303. * @param {object} obj - The object in which to set the bounds values.
  72304. * @return {object} The object that was given to this method.
  72305. */
  72306. getBounds: function (obj) {
  72307. if (this.isCircle)
  72308. {
  72309. obj.x = this.center.x - this.radius;
  72310. obj.y = this.center.y - this.radius;
  72311. obj.right = this.center.x + this.radius;
  72312. obj.bottom = this.center.y + this.radius;
  72313. }
  72314. else
  72315. {
  72316. obj.x = this.x;
  72317. obj.y = this.y;
  72318. obj.right = this.right;
  72319. obj.bottom = this.bottom;
  72320. }
  72321. return obj;
  72322. },
  72323. /**
  72324. * Tests if a world point lies within this Body.
  72325. *
  72326. * @method Phaser.Physics.Arcade.Body#hitTest
  72327. * @param {number} x - The world x coordinate to test.
  72328. * @param {number} y - The world y coordinate to test.
  72329. * @return {boolean} True if the given coordinates are inside this Body, otherwise false.
  72330. */
  72331. hitTest: function (x, y) {
  72332. return (this.isCircle) ? Phaser.Circle.contains(this, x, y) : Phaser.Rectangle.contains(this, x, y);
  72333. },
  72334. /**
  72335. * Returns true if the bottom of this Body is in contact with either the world bounds or a tile.
  72336. *
  72337. * @method Phaser.Physics.Arcade.Body#onFloor
  72338. * @return {boolean} True if in contact with either the world bounds or a tile.
  72339. */
  72340. onFloor: function () {
  72341. return this.blocked.down;
  72342. },
  72343. /**
  72344. * Returns true if the top of this Body is in contact with either the world bounds or a tile.
  72345. *
  72346. * @method Phaser.Physics.Arcade.Body#onCeiling
  72347. * @return {boolean} True if in contact with either the world bounds or a tile.
  72348. */
  72349. onCeiling: function(){
  72350. return this.blocked.up;
  72351. },
  72352. /**
  72353. * Returns true if either side of this Body is in contact with either the world bounds or a tile.
  72354. *
  72355. * @method Phaser.Physics.Arcade.Body#onWall
  72356. * @return {boolean} True if in contact with either the world bounds or a tile.
  72357. */
  72358. onWall: function () {
  72359. return (this.blocked.left || this.blocked.right);
  72360. },
  72361. /**
  72362. * Returns the absolute delta x value.
  72363. *
  72364. * @method Phaser.Physics.Arcade.Body#deltaAbsX
  72365. * @return {number} The absolute delta value.
  72366. */
  72367. deltaAbsX: function () {
  72368. return (this.deltaX() > 0 ? this.deltaX() : -this.deltaX());
  72369. },
  72370. /**
  72371. * Returns the absolute delta y value.
  72372. *
  72373. * @method Phaser.Physics.Arcade.Body#deltaAbsY
  72374. * @return {number} The absolute delta value.
  72375. */
  72376. deltaAbsY: function () {
  72377. return (this.deltaY() > 0 ? this.deltaY() : -this.deltaY());
  72378. },
  72379. /**
  72380. * Returns the delta x value. The difference between Body.x now and in the previous step.
  72381. *
  72382. * @method Phaser.Physics.Arcade.Body#deltaX
  72383. * @return {number} The delta value. Positive if the motion was to the right, negative if to the left.
  72384. */
  72385. deltaX: function () {
  72386. return this.position.x - this.prev.x;
  72387. },
  72388. /**
  72389. * Returns the delta y value. The difference between Body.y now and in the previous step.
  72390. *
  72391. * @method Phaser.Physics.Arcade.Body#deltaY
  72392. * @return {number} The delta value. Positive if the motion was downwards, negative if upwards.
  72393. */
  72394. deltaY: function () {
  72395. return this.position.y - this.prev.y;
  72396. },
  72397. /**
  72398. * Returns the delta z value. The difference between Body.rotation now and in the previous step.
  72399. *
  72400. * @method Phaser.Physics.Arcade.Body#deltaZ
  72401. * @return {number} The delta value. Positive if the motion was clockwise, negative if anti-clockwise.
  72402. */
  72403. deltaZ: function () {
  72404. return this.rotation - this.preRotation;
  72405. },
  72406. /**
  72407. * Destroys this Body.
  72408. *
  72409. * First it calls Group.removeFromHash if the Game Object this Body belongs to is part of a Group.
  72410. * Then it nulls the Game Objects body reference, and nulls this Body.sprite reference.
  72411. *
  72412. * @method Phaser.Physics.Arcade.Body#destroy
  72413. */
  72414. destroy: function () {
  72415. if (this.sprite.parent && this.sprite.parent instanceof Phaser.Group)
  72416. {
  72417. this.sprite.parent.removeFromHash(this.sprite);
  72418. }
  72419. this.sprite.body = null;
  72420. this.sprite = null;
  72421. }
  72422. };
  72423. /**
  72424. * @name Phaser.Physics.Arcade.Body#left
  72425. * @property {number} left - The x position of the Body. The same as `Body.x`.
  72426. */
  72427. Object.defineProperty(Phaser.Physics.Arcade.Body.prototype, "left", {
  72428. get: function () {
  72429. return this.position.x;
  72430. }
  72431. });
  72432. /**
  72433. * @name Phaser.Physics.Arcade.Body#right
  72434. * @property {number} right - The right value of this Body (same as Body.x + Body.width)
  72435. * @readonly
  72436. */
  72437. Object.defineProperty(Phaser.Physics.Arcade.Body.prototype, "right", {
  72438. get: function () {
  72439. return this.position.x + this.width;
  72440. }
  72441. });
  72442. /**
  72443. * @name Phaser.Physics.Arcade.Body#top
  72444. * @property {number} top - The y position of the Body. The same as `Body.y`.
  72445. */
  72446. Object.defineProperty(Phaser.Physics.Arcade.Body.prototype, "top", {
  72447. get: function () {
  72448. return this.position.y;
  72449. }
  72450. });
  72451. /**
  72452. * @name Phaser.Physics.Arcade.Body#bottom
  72453. * @property {number} bottom - The bottom value of this Body (same as Body.y + Body.height)
  72454. * @readonly
  72455. */
  72456. Object.defineProperty(Phaser.Physics.Arcade.Body.prototype, "bottom", {
  72457. get: function () {
  72458. return this.position.y + this.height;
  72459. }
  72460. });
  72461. /**
  72462. * @name Phaser.Physics.Arcade.Body#x
  72463. * @property {number} x - The x position.
  72464. */
  72465. Object.defineProperty(Phaser.Physics.Arcade.Body.prototype, "x", {
  72466. get: function () {
  72467. return this.position.x;
  72468. },
  72469. set: function (value) {
  72470. this.position.x = value;
  72471. }
  72472. });
  72473. /**
  72474. * @name Phaser.Physics.Arcade.Body#y
  72475. * @property {number} y - The y position.
  72476. */
  72477. Object.defineProperty(Phaser.Physics.Arcade.Body.prototype, "y", {
  72478. get: function () {
  72479. return this.position.y;
  72480. },
  72481. set: function (value) {
  72482. this.position.y = value;
  72483. }
  72484. });
  72485. /**
  72486. * Render Sprite Body.
  72487. *
  72488. * @method Phaser.Physics.Arcade.Body#render
  72489. * @param {object} context - The context to render to.
  72490. * @param {Phaser.Physics.Arcade.Body} body - The Body to render the info of.
  72491. * @param {string} [color='rgba(0,255,0,0.4)'] - color of the debug info to be rendered. (format is css color string).
  72492. * @param {boolean} [filled=true] - Render the objected as a filled (default, true) or a stroked (false)
  72493. */
  72494. Phaser.Physics.Arcade.Body.render = function (context, body, color, filled) {
  72495. if (filled === undefined) { filled = true; }
  72496. color = color || 'rgba(0,255,0,0.4)';
  72497. context.fillStyle = color;
  72498. context.strokeStyle = color;
  72499. if (body.isCircle)
  72500. {
  72501. context.beginPath();
  72502. context.arc(body.center.x - body.game.camera.x, body.center.y - body.game.camera.y, body.radius, 0, 2 * Math.PI);
  72503. if (filled)
  72504. {
  72505. context.fill();
  72506. }
  72507. else
  72508. {
  72509. context.stroke();
  72510. }
  72511. }
  72512. else
  72513. {
  72514. if (filled)
  72515. {
  72516. context.fillRect(body.position.x - body.game.camera.x, body.position.y - body.game.camera.y, body.width, body.height);
  72517. }
  72518. else
  72519. {
  72520. context.strokeRect(body.position.x - body.game.camera.x, body.position.y - body.game.camera.y, body.width, body.height);
  72521. }
  72522. }
  72523. };
  72524. /**
  72525. * Render Sprite Body Physics Data as text.
  72526. *
  72527. * @method Phaser.Physics.Arcade.Body#renderBodyInfo
  72528. * @param {Phaser.Physics.Arcade.Body} body - The Body to render the info of.
  72529. * @param {number} x - X position of the debug info to be rendered.
  72530. * @param {number} y - Y position of the debug info to be rendered.
  72531. * @param {string} [color='rgb(255,255,255)'] - color of the debug info to be rendered. (format is css color string).
  72532. */
  72533. Phaser.Physics.Arcade.Body.renderBodyInfo = function (debug, body) {
  72534. debug.line('x: ' + body.x.toFixed(2), 'y: ' + body.y.toFixed(2), 'width: ' + body.width, 'height: ' + body.height);
  72535. debug.line('velocity x: ' + body.velocity.x.toFixed(2), 'y: ' + body.velocity.y.toFixed(2), 'deltaX: ' + body._dx.toFixed(2), 'deltaY: ' + body._dy.toFixed(2));
  72536. debug.line('acceleration x: ' + body.acceleration.x.toFixed(2), 'y: ' + body.acceleration.y.toFixed(2), 'speed: ' + body.speed.toFixed(2), 'angle: ' + body.angle.toFixed(2));
  72537. debug.line('gravity x: ' + body.gravity.x, 'y: ' + body.gravity.y, 'bounce x: ' + body.bounce.x.toFixed(2), 'y: ' + body.bounce.y.toFixed(2));
  72538. debug.line('touching left: ' + body.touching.left, 'right: ' + body.touching.right, 'up: ' + body.touching.up, 'down: ' + body.touching.down);
  72539. debug.line('blocked left: ' + body.blocked.left, 'right: ' + body.blocked.right, 'up: ' + body.blocked.up, 'down: ' + body.blocked.down);
  72540. };
  72541. Phaser.Physics.Arcade.Body.prototype.constructor = Phaser.Physics.Arcade.Body;
  72542. /**
  72543. * @author Richard Davey <rich@photonstorm.com>
  72544. * @copyright 2016 Photon Storm Ltd.
  72545. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  72546. */
  72547. /**
  72548. * The Arcade Physics Tile map collision methods.
  72549. *
  72550. * @class Phaser.Physics.Arcade.TilemapCollision
  72551. * @constructor
  72552. */
  72553. Phaser.Physics.Arcade.TilemapCollision = function () {};
  72554. Phaser.Physics.Arcade.TilemapCollision.prototype = {
  72555. /**
  72556. * @property {number} TILE_BIAS - A value added to the delta values during collision with tiles. Adjust this if you get tunneling.
  72557. */
  72558. TILE_BIAS: 16,
  72559. /**
  72560. * An internal function. Use Phaser.Physics.Arcade.collide instead.
  72561. *
  72562. * @method Phaser.Physics.Arcade#collideSpriteVsTilemapLayer
  72563. * @private
  72564. * @param {Phaser.Sprite} sprite - The sprite to check.
  72565. * @param {Phaser.TilemapLayer} tilemapLayer - The layer to check.
  72566. * @param {function} collideCallback - An optional callback function that is called if the objects collide. The two objects will be passed to this function in the same order in which you specified them.
  72567. * @param {function} processCallback - A callback function that lets you perform additional checks against the two objects if they overlap. If this is set then collision will only happen if processCallback returns true. The two objects will be passed to this function in the same order in which you specified them.
  72568. * @param {object} callbackContext - The context in which to run the callbacks.
  72569. * @param {boolean} overlapOnly - Just run an overlap or a full collision.
  72570. */
  72571. collideSpriteVsTilemapLayer: function (sprite, tilemapLayer, collideCallback, processCallback, callbackContext, overlapOnly) {
  72572. if (!sprite.body)
  72573. {
  72574. return;
  72575. }
  72576. var mapData = tilemapLayer.getTiles(
  72577. sprite.body.position.x - sprite.body.tilePadding.x,
  72578. sprite.body.position.y - sprite.body.tilePadding.y,
  72579. sprite.body.width + sprite.body.tilePadding.x,
  72580. sprite.body.height + sprite.body.tilePadding.y,
  72581. false, false);
  72582. if (mapData.length === 0)
  72583. {
  72584. return;
  72585. }
  72586. for (var i = 0; i < mapData.length; i++)
  72587. {
  72588. if (processCallback)
  72589. {
  72590. if (processCallback.call(callbackContext, sprite, mapData[i]))
  72591. {
  72592. if (this.separateTile(i, sprite.body, mapData[i], tilemapLayer, overlapOnly))
  72593. {
  72594. this._total++;
  72595. if (collideCallback)
  72596. {
  72597. collideCallback.call(callbackContext, sprite, mapData[i]);
  72598. }
  72599. }
  72600. }
  72601. }
  72602. else
  72603. {
  72604. if (this.separateTile(i, sprite.body, mapData[i], tilemapLayer, overlapOnly))
  72605. {
  72606. this._total++;
  72607. if (collideCallback)
  72608. {
  72609. collideCallback.call(callbackContext, sprite, mapData[i]);
  72610. }
  72611. }
  72612. }
  72613. }
  72614. },
  72615. /**
  72616. * An internal function. Use Phaser.Physics.Arcade.collide instead.
  72617. *
  72618. * @private
  72619. * @method Phaser.Physics.Arcade#collideGroupVsTilemapLayer
  72620. * @param {Phaser.Group} group - The Group to check.
  72621. * @param {Phaser.TilemapLayer} tilemapLayer - The layer to check.
  72622. * @param {function} collideCallback - An optional callback function that is called if the objects collide. The two objects will be passed to this function in the same order in which you specified them.
  72623. * @param {function} processCallback - A callback function that lets you perform additional checks against the two objects if they overlap. If this is set then collision will only happen if processCallback returns true. The two objects will be passed to this function in the same order in which you specified them.
  72624. * @param {object} callbackContext - The context in which to run the callbacks.
  72625. * @param {boolean} overlapOnly - Just run an overlap or a full collision.
  72626. */
  72627. collideGroupVsTilemapLayer: function (group, tilemapLayer, collideCallback, processCallback, callbackContext, overlapOnly) {
  72628. if (group.length === 0)
  72629. {
  72630. return;
  72631. }
  72632. for (var i = 0; i < group.children.length; i++)
  72633. {
  72634. if (group.children[i].exists)
  72635. {
  72636. this.collideSpriteVsTilemapLayer(group.children[i], tilemapLayer, collideCallback, processCallback, callbackContext, overlapOnly);
  72637. }
  72638. }
  72639. },
  72640. /**
  72641. * The core separation function to separate a physics body and a tile.
  72642. *
  72643. * @private
  72644. * @method Phaser.Physics.Arcade#separateTile
  72645. * @param {Phaser.Physics.Arcade.Body} body - The Body object to separate.
  72646. * @param {Phaser.Tile} tile - The tile to collide against.
  72647. * @param {Phaser.TilemapLayer} tilemapLayer - The tilemapLayer to collide against.
  72648. * @return {boolean} Returns true if the body was separated, otherwise false.
  72649. */
  72650. separateTile: function (i, body, tile, tilemapLayer, overlapOnly) {
  72651. if (!body.enable)
  72652. {
  72653. return false;
  72654. }
  72655. var tilemapLayerOffsetX = (!tilemapLayer.fixedToCamera) ? tilemapLayer.position.x : 0;
  72656. var tilemapLayerOffsetY = (!tilemapLayer.fixedToCamera) ? tilemapLayer.position.y : 0;
  72657. // We re-check for collision in case body was separated in a previous step
  72658. if (!tile.intersects((body.position.x - tilemapLayerOffsetX), (body.position.y - tilemapLayerOffsetY), (body.right - tilemapLayerOffsetX), (body.bottom - tilemapLayerOffsetY)))
  72659. {
  72660. // no collision so bail out (separated in a previous step)
  72661. return false;
  72662. }
  72663. else if (overlapOnly)
  72664. {
  72665. // There is an overlap, and we don't need to separate. Bail.
  72666. return true;
  72667. }
  72668. // They overlap. Any custom callbacks?
  72669. // A local callback always takes priority over a layer level callback
  72670. if (tile.collisionCallback && !tile.collisionCallback.call(tile.collisionCallbackContext, body.sprite, tile))
  72671. {
  72672. // If it returns true then we can carry on, otherwise we should abort.
  72673. return false;
  72674. }
  72675. else if (typeof tile.layer.callbacks !== 'undefined' && tile.layer.callbacks[tile.index] && !tile.layer.callbacks[tile.index].callback.call(tile.layer.callbacks[tile.index].callbackContext, body.sprite, tile))
  72676. {
  72677. // If it returns true then we can carry on, otherwise we should abort.
  72678. return false;
  72679. }
  72680. // We don't need to go any further if this tile doesn't actually separate
  72681. if (!tile.faceLeft && !tile.faceRight && !tile.faceTop && !tile.faceBottom)
  72682. {
  72683. // This could happen if the tile was meant to be collided with re: a callback, but otherwise isn't needed for separation
  72684. return false;
  72685. }
  72686. var ox = 0;
  72687. var oy = 0;
  72688. var minX = 0;
  72689. var minY = 1;
  72690. if (body.deltaAbsX() > body.deltaAbsY())
  72691. {
  72692. // Moving faster horizontally, check X axis first
  72693. minX = -1;
  72694. }
  72695. else if (body.deltaAbsX() < body.deltaAbsY())
  72696. {
  72697. // Moving faster vertically, check Y axis first
  72698. minY = -1;
  72699. }
  72700. if (body.deltaX() !== 0 && body.deltaY() !== 0 && (tile.faceLeft || tile.faceRight) && (tile.faceTop || tile.faceBottom))
  72701. {
  72702. // We only need do this if both axis have checking faces AND we're moving in both directions
  72703. minX = Math.min(Math.abs((body.position.x - tilemapLayerOffsetX) - tile.right), Math.abs((body.right - tilemapLayerOffsetX) - tile.left));
  72704. minY = Math.min(Math.abs((body.position.y - tilemapLayerOffsetY) - tile.bottom), Math.abs((body.bottom - tilemapLayerOffsetY) - tile.top));
  72705. }
  72706. if (minX < minY)
  72707. {
  72708. if (tile.faceLeft || tile.faceRight)
  72709. {
  72710. ox = this.tileCheckX(body, tile, tilemapLayer);
  72711. // That's horizontal done, check if we still intersects? If not then we can return now
  72712. if (ox !== 0 && !tile.intersects((body.position.x - tilemapLayerOffsetX), (body.position.y - tilemapLayerOffsetY), (body.right - tilemapLayerOffsetX), (body.bottom - tilemapLayerOffsetY)))
  72713. {
  72714. return true;
  72715. }
  72716. }
  72717. if (tile.faceTop || tile.faceBottom)
  72718. {
  72719. oy = this.tileCheckY(body, tile, tilemapLayer);
  72720. }
  72721. }
  72722. else
  72723. {
  72724. if (tile.faceTop || tile.faceBottom)
  72725. {
  72726. oy = this.tileCheckY(body, tile, tilemapLayer);
  72727. // That's vertical done, check if we still intersects? If not then we can return now
  72728. if (oy !== 0 && !tile.intersects((body.position.x - tilemapLayerOffsetX), (body.position.y - tilemapLayerOffsetY), (body.right - tilemapLayerOffsetX), (body.bottom - tilemapLayerOffsetY)))
  72729. {
  72730. return true;
  72731. }
  72732. }
  72733. if (tile.faceLeft || tile.faceRight)
  72734. {
  72735. ox = this.tileCheckX(body, tile, tilemapLayer);
  72736. }
  72737. }
  72738. return (ox !== 0 || oy !== 0);
  72739. },
  72740. /**
  72741. * Check the body against the given tile on the X axis.
  72742. *
  72743. * @private
  72744. * @method Phaser.Physics.Arcade#tileCheckX
  72745. * @param {Phaser.Physics.Arcade.Body} body - The Body object to separate.
  72746. * @param {Phaser.Tile} tile - The tile to check.
  72747. * @param {Phaser.TilemapLayer} tilemapLayer - The tilemapLayer to collide against.
  72748. * @return {number} The amount of separation that occurred.
  72749. */
  72750. tileCheckX: function (body, tile, tilemapLayer) {
  72751. var ox = 0;
  72752. var tilemapLayerOffsetX = (!tilemapLayer.fixedToCamera) ? tilemapLayer.position.x : 0;
  72753. if (body.deltaX() < 0 && !body.blocked.left && tile.collideRight && body.checkCollision.left)
  72754. {
  72755. // Body is moving LEFT
  72756. if (tile.faceRight && (body.x - tilemapLayerOffsetX) < tile.right)
  72757. {
  72758. ox = (body.x - tilemapLayerOffsetX) - tile.right;
  72759. if (ox < -this.TILE_BIAS)
  72760. {
  72761. ox = 0;
  72762. }
  72763. }
  72764. }
  72765. else if (body.deltaX() > 0 && !body.blocked.right && tile.collideLeft && body.checkCollision.right)
  72766. {
  72767. // Body is moving RIGHT
  72768. if (tile.faceLeft && (body.right - tilemapLayerOffsetX) > tile.left)
  72769. {
  72770. ox = (body.right - tilemapLayerOffsetX) - tile.left;
  72771. if (ox > this.TILE_BIAS)
  72772. {
  72773. ox = 0;
  72774. }
  72775. }
  72776. }
  72777. if (ox !== 0)
  72778. {
  72779. if (body.customSeparateX)
  72780. {
  72781. body.overlapX = ox;
  72782. }
  72783. else
  72784. {
  72785. this.processTileSeparationX(body, ox);
  72786. }
  72787. }
  72788. return ox;
  72789. },
  72790. /**
  72791. * Check the body against the given tile on the Y axis.
  72792. *
  72793. * @private
  72794. * @method Phaser.Physics.Arcade#tileCheckY
  72795. * @param {Phaser.Physics.Arcade.Body} body - The Body object to separate.
  72796. * @param {Phaser.Tile} tile - The tile to check.
  72797. * @param {Phaser.TilemapLayer} tilemapLayer - The tilemapLayer to collide against.
  72798. * @return {number} The amount of separation that occurred.
  72799. */
  72800. tileCheckY: function (body, tile, tilemapLayer) {
  72801. var oy = 0;
  72802. var tilemapLayerOffsetY = (!tilemapLayer.fixedToCamera) ? tilemapLayer.position.y : 0;
  72803. if (body.deltaY() < 0 && !body.blocked.up && tile.collideDown && body.checkCollision.up)
  72804. {
  72805. // Body is moving UP
  72806. if (tile.faceBottom && (body.y - tilemapLayerOffsetY) < tile.bottom)
  72807. {
  72808. oy = (body.y - tilemapLayerOffsetY) - tile.bottom;
  72809. if (oy < -this.TILE_BIAS)
  72810. {
  72811. oy = 0;
  72812. }
  72813. }
  72814. }
  72815. else if (body.deltaY() > 0 && !body.blocked.down && tile.collideUp && body.checkCollision.down)
  72816. {
  72817. // Body is moving DOWN
  72818. if (tile.faceTop && (body.bottom - tilemapLayerOffsetY) > tile.top)
  72819. {
  72820. oy = (body.bottom - tilemapLayerOffsetY) - tile.top;
  72821. if (oy > this.TILE_BIAS)
  72822. {
  72823. oy = 0;
  72824. }
  72825. }
  72826. }
  72827. if (oy !== 0)
  72828. {
  72829. if (body.customSeparateY)
  72830. {
  72831. body.overlapY = oy;
  72832. }
  72833. else
  72834. {
  72835. this.processTileSeparationY(body, oy);
  72836. }
  72837. }
  72838. return oy;
  72839. },
  72840. /**
  72841. * Internal function to process the separation of a physics body from a tile.
  72842. *
  72843. * @private
  72844. * @method Phaser.Physics.Arcade#processTileSeparationX
  72845. * @param {Phaser.Physics.Arcade.Body} body - The Body object to separate.
  72846. * @param {number} x - The x separation amount.
  72847. */
  72848. processTileSeparationX: function (body, x) {
  72849. if (x < 0)
  72850. {
  72851. body.blocked.left = true;
  72852. }
  72853. else if (x > 0)
  72854. {
  72855. body.blocked.right = true;
  72856. }
  72857. body.position.x -= x;
  72858. if (body.bounce.x === 0)
  72859. {
  72860. body.velocity.x = 0;
  72861. }
  72862. else
  72863. {
  72864. body.velocity.x = -body.velocity.x * body.bounce.x;
  72865. }
  72866. },
  72867. /**
  72868. * Internal function to process the separation of a physics body from a tile.
  72869. *
  72870. * @private
  72871. * @method Phaser.Physics.Arcade#processTileSeparationY
  72872. * @param {Phaser.Physics.Arcade.Body} body - The Body object to separate.
  72873. * @param {number} y - The y separation amount.
  72874. */
  72875. processTileSeparationY: function (body, y) {
  72876. if (y < 0)
  72877. {
  72878. body.blocked.up = true;
  72879. }
  72880. else if (y > 0)
  72881. {
  72882. body.blocked.down = true;
  72883. }
  72884. body.position.y -= y;
  72885. if (body.bounce.y === 0)
  72886. {
  72887. body.velocity.y = 0;
  72888. }
  72889. else
  72890. {
  72891. body.velocity.y = -body.velocity.y * body.bounce.y;
  72892. }
  72893. }
  72894. };
  72895. // Merge this with the Arcade Physics prototype
  72896. Phaser.Utils.mixinPrototype(Phaser.Physics.Arcade.prototype, Phaser.Physics.Arcade.TilemapCollision.prototype);
  72897. /**
  72898. * @author Richard Davey <rich@photonstorm.com>
  72899. * @copyright 2016 Photon Storm Ltd.
  72900. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  72901. */
  72902. // Add an extra properties to p2 that we need
  72903. p2.Body.prototype.parent = null;
  72904. p2.Spring.prototype.parent = null;
  72905. /**
  72906. * This is your main access to the P2 Physics World.
  72907. * From here you can create materials, listen for events and add bodies into the physics simulation.
  72908. *
  72909. * @class Phaser.Physics.P2
  72910. * @constructor
  72911. * @param {Phaser.Game} game - Reference to the current game instance.
  72912. * @param {object} [config] - Physics configuration object passed in from the game constructor.
  72913. */
  72914. Phaser.Physics.P2 = function (game, config) {
  72915. /**
  72916. * @property {Phaser.Game} game - Local reference to game.
  72917. */
  72918. this.game = game;
  72919. if (config === undefined)
  72920. {
  72921. config = { gravity: [0, 0], broadphase: new p2.SAPBroadphase() };
  72922. }
  72923. else
  72924. {
  72925. if (!config.hasOwnProperty('gravity'))
  72926. {
  72927. config.gravity = [0, 0];
  72928. }
  72929. if (!config.hasOwnProperty('broadphase'))
  72930. {
  72931. config.broadphase = new p2.SAPBroadphase();
  72932. }
  72933. }
  72934. /**
  72935. * @property {object} config - The p2 World configuration object.
  72936. * @protected
  72937. */
  72938. this.config = config;
  72939. /**
  72940. * @property {p2.World} world - The p2 World in which the simulation is run.
  72941. * @protected
  72942. */
  72943. this.world = new p2.World(this.config);
  72944. /**
  72945. * @property {number} frameRate - The frame rate the world will be stepped at. Defaults to 1 / 60, but you can change here. Also see useElapsedTime property.
  72946. * @default
  72947. */
  72948. this.frameRate = 1 / 60;
  72949. /**
  72950. * @property {boolean} useElapsedTime - If true the frameRate value will be ignored and instead p2 will step with the value of Game.Time.physicsElapsed, which is a delta time value.
  72951. * @default
  72952. */
  72953. this.useElapsedTime = false;
  72954. /**
  72955. * @property {boolean} paused - The paused state of the P2 World.
  72956. * @default
  72957. */
  72958. this.paused = false;
  72959. /**
  72960. * @property {array<Phaser.Physics.P2.Material>} materials - A local array of all created Materials.
  72961. * @protected
  72962. */
  72963. this.materials = [];
  72964. /**
  72965. * @property {Phaser.Physics.P2.InversePointProxy} gravity - The gravity applied to all bodies each step.
  72966. */
  72967. this.gravity = new Phaser.Physics.P2.InversePointProxy(this, this.world.gravity);
  72968. /**
  72969. * @property {object} walls - An object containing the 4 wall bodies that bound the physics world.
  72970. */
  72971. this.walls = { left: null, right: null, top: null, bottom: null };
  72972. /**
  72973. * This signal is dispatched when a new Body is added to the World.
  72974. *
  72975. * It sends 1 argument: `body` which is the `Phaser.Physics.P2.Body` that was added to the world.
  72976. *
  72977. * @property {Phaser.Signal} onBodyAdded
  72978. */
  72979. this.onBodyAdded = new Phaser.Signal();
  72980. /**
  72981. * This signal is dispatched when a Body is removed to the World.
  72982. *
  72983. * It sends 1 argument: `body` which is the `Phaser.Physics.P2.Body` that was removed from the world.
  72984. *
  72985. * @property {Phaser.Signal} onBodyRemoved
  72986. */
  72987. this.onBodyRemoved = new Phaser.Signal();
  72988. /**
  72989. * This signal is dispatched when a Spring is added to the World.
  72990. *
  72991. * It sends 1 argument: `spring` which is either a `Phaser.Physics.P2.Spring`, `p2.LinearSpring` or `p2.RotationalSpring` that was added to the world.
  72992. *
  72993. * @property {Phaser.Signal} onSpringAdded
  72994. */
  72995. this.onSpringAdded = new Phaser.Signal();
  72996. /**
  72997. * This signal is dispatched when a Spring is removed from the World.
  72998. *
  72999. * It sends 1 argument: `spring` which is either a `Phaser.Physics.P2.Spring`, `p2.LinearSpring` or `p2.RotationalSpring` that was removed from the world.
  73000. *
  73001. * @property {Phaser.Signal} onSpringRemoved
  73002. */
  73003. this.onSpringRemoved = new Phaser.Signal();
  73004. /**
  73005. * This signal is dispatched when a Constraint is added to the World.
  73006. *
  73007. * It sends 1 argument: `constraint` which is the `Phaser.Physics.P2.Constraint` that was added to the world.
  73008. *
  73009. * @property {Phaser.Signal} onConstraintAdded
  73010. */
  73011. this.onConstraintAdded = new Phaser.Signal();
  73012. /**
  73013. * This signal is dispatched when a Constraint is removed from the World.
  73014. *
  73015. * It sends 1 argument: `constraint` which is the `Phaser.Physics.P2.Constraint` that was removed from the world.
  73016. *
  73017. * @property {Phaser.Signal} onConstraintRemoved
  73018. */
  73019. this.onConstraintRemoved = new Phaser.Signal();
  73020. /**
  73021. * This signal is dispatched when a Contact Material is added to the World.
  73022. *
  73023. * It sends 1 argument: `material` which is the `Phaser.Physics.P2.ContactMaterial` that was added to the world.
  73024. *
  73025. * @property {Phaser.Signal} onContactMaterialAdded
  73026. */
  73027. this.onContactMaterialAdded = new Phaser.Signal();
  73028. /**
  73029. * This signal is dispatched when a Contact Material is removed from the World.
  73030. *
  73031. * It sends 1 argument: `material` which is the `Phaser.Physics.P2.ContactMaterial` that was removed from the world.
  73032. *
  73033. * @property {Phaser.Signal} onContactMaterialRemoved
  73034. */
  73035. this.onContactMaterialRemoved = new Phaser.Signal();
  73036. /**
  73037. * @property {function} postBroadphaseCallback - A postBroadphase callback.
  73038. */
  73039. this.postBroadphaseCallback = null;
  73040. /**
  73041. * @property {object} callbackContext - The context under which the callbacks are fired.
  73042. */
  73043. this.callbackContext = null;
  73044. /**
  73045. * This Signal is dispatched when a first contact is created between two bodies. This happens *before* the step has been done.
  73046. *
  73047. * It sends 5 arguments: `bodyA`, `bodyB`, `shapeA`, `shapeB` and `contactEquations`.
  73048. *
  73049. * It is possible that in certain situations the `bodyA` or `bodyB` values are `null`. You should check for this
  73050. * in your own code to avoid processing potentially null physics bodies.
  73051. *
  73052. * @property {Phaser.Signal} onBeginContact
  73053. */
  73054. this.onBeginContact = new Phaser.Signal();
  73055. /**
  73056. * This Signal is dispatched when final contact occurs between two bodies. This happens *before* the step has been done.
  73057. *
  73058. * It sends 4 arguments: `bodyA`, `bodyB`, `shapeA` and `shapeB`.
  73059. *
  73060. * It is possible that in certain situations the `bodyA` or `bodyB` values are `null`. You should check for this
  73061. * in your own code to avoid processing potentially null physics bodies.
  73062. *
  73063. * @property {Phaser.Signal} onEndContact
  73064. */
  73065. this.onEndContact = new Phaser.Signal();
  73066. // Pixel to meter function overrides
  73067. if (config.hasOwnProperty('mpx') && config.hasOwnProperty('pxm') && config.hasOwnProperty('mpxi') && config.hasOwnProperty('pxmi'))
  73068. {
  73069. this.mpx = config.mpx;
  73070. this.mpxi = config.mpxi;
  73071. this.pxm = config.pxm;
  73072. this.pxmi = config.pxmi;
  73073. }
  73074. // Hook into the World events
  73075. this.world.on("beginContact", this.beginContactHandler, this);
  73076. this.world.on("endContact", this.endContactHandler, this);
  73077. /**
  73078. * @property {array} collisionGroups - An array containing the collision groups that have been defined in the World.
  73079. */
  73080. this.collisionGroups = [];
  73081. /**
  73082. * @property {Phaser.Physics.P2.CollisionGroup} nothingCollisionGroup - A default collision group.
  73083. */
  73084. this.nothingCollisionGroup = new Phaser.Physics.P2.CollisionGroup(1);
  73085. /**
  73086. * @property {Phaser.Physics.P2.CollisionGroup} boundsCollisionGroup - A default collision group.
  73087. */
  73088. this.boundsCollisionGroup = new Phaser.Physics.P2.CollisionGroup(2);
  73089. /**
  73090. * @property {Phaser.Physics.P2.CollisionGroup} everythingCollisionGroup - A default collision group.
  73091. */
  73092. this.everythingCollisionGroup = new Phaser.Physics.P2.CollisionGroup(2147483648);
  73093. /**
  73094. * @property {array} boundsCollidesWith - An array of the bodies the world bounds collides with.
  73095. */
  73096. this.boundsCollidesWith = [];
  73097. /**
  73098. * @property {array} _toRemove - Internal var used to hold references to bodies to remove from the world on the next step.
  73099. * @private
  73100. */
  73101. this._toRemove = [];
  73102. /**
  73103. * @property {number} _collisionGroupID - Internal var.
  73104. * @private
  73105. */
  73106. this._collisionGroupID = 2;
  73107. /**
  73108. * @property {boolean} _boundsLeft - Internal var that keeps track of world bounds settings.
  73109. * @private
  73110. */
  73111. this._boundsLeft = true;
  73112. /**
  73113. * @property {boolean} _boundsRight - Internal var that keeps track of world bounds settings.
  73114. * @private
  73115. */
  73116. this._boundsRight = true;
  73117. /**
  73118. * @property {boolean} _boundsTop - Internal var that keeps track of world bounds settings.
  73119. * @private
  73120. */
  73121. this._boundsTop = true;
  73122. /**
  73123. * @property {boolean} _boundsBottom - Internal var that keeps track of world bounds settings.
  73124. * @private
  73125. */
  73126. this._boundsBottom = true;
  73127. /**
  73128. * @property {boolean} _boundsOwnGroup - Internal var that keeps track of world bounds settings.
  73129. * @private
  73130. */
  73131. this._boundsOwnGroup = false;
  73132. // By default we want everything colliding with everything
  73133. this.setBoundsToWorld(true, true, true, true, false);
  73134. };
  73135. Phaser.Physics.P2.prototype = {
  73136. /**
  73137. * This will add a P2 Physics body into the removal list for the next step.
  73138. *
  73139. * @method Phaser.Physics.P2#removeBodyNextStep
  73140. * @param {Phaser.Physics.P2.Body} body - The body to remove at the start of the next step.
  73141. */
  73142. removeBodyNextStep: function (body) {
  73143. this._toRemove.push(body);
  73144. },
  73145. /**
  73146. * Called at the start of the core update loop. Purges flagged bodies from the world.
  73147. *
  73148. * @method Phaser.Physics.P2#preUpdate
  73149. */
  73150. preUpdate: function () {
  73151. var i = this._toRemove.length;
  73152. while (i--)
  73153. {
  73154. this.removeBody(this._toRemove[i]);
  73155. }
  73156. this._toRemove.length = 0;
  73157. },
  73158. /**
  73159. * This will create a P2 Physics body on the given game object or array of game objects.
  73160. * A game object can only have 1 physics body active at any one time, and it can't be changed until the object is destroyed.
  73161. * Note: When the game object is enabled for P2 physics it has its anchor x/y set to 0.5 so it becomes centered.
  73162. *
  73163. * @method Phaser.Physics.P2#enable
  73164. * @param {object|array|Phaser.Group} object - The game object to create the physics body on. Can also be an array or Group of objects, a body will be created on every child that has a `body` property.
  73165. * @param {boolean} [debug=false] - Create a debug object to go with this body?
  73166. * @param {boolean} [children=true] - Should a body be created on all children of this object? If true it will recurse down the display list as far as it can go.
  73167. */
  73168. enable: function (object, debug, children) {
  73169. if (debug === undefined) { debug = false; }
  73170. if (children === undefined) { children = true; }
  73171. var i = 1;
  73172. if (Array.isArray(object))
  73173. {
  73174. i = object.length;
  73175. while (i--)
  73176. {
  73177. if (object[i] instanceof Phaser.Group)
  73178. {
  73179. // If it's a Group then we do it on the children regardless
  73180. this.enable(object[i].children, debug, children);
  73181. }
  73182. else
  73183. {
  73184. this.enableBody(object[i], debug);
  73185. if (children && object[i].hasOwnProperty('children') && object[i].children.length > 0)
  73186. {
  73187. this.enable(object[i], debug, true);
  73188. }
  73189. }
  73190. }
  73191. }
  73192. else
  73193. {
  73194. if (object instanceof Phaser.Group)
  73195. {
  73196. // If it's a Group then we do it on the children regardless
  73197. this.enable(object.children, debug, children);
  73198. }
  73199. else
  73200. {
  73201. this.enableBody(object, debug);
  73202. if (children && object.hasOwnProperty('children') && object.children.length > 0)
  73203. {
  73204. this.enable(object.children, debug, true);
  73205. }
  73206. }
  73207. }
  73208. },
  73209. /**
  73210. * Creates a P2 Physics body on the given game object.
  73211. * A game object can only have 1 physics body active at any one time, and it can't be changed until the body is nulled.
  73212. *
  73213. * @method Phaser.Physics.P2#enableBody
  73214. * @param {object} object - The game object to create the physics body on. A body will only be created if this object has a null `body` property.
  73215. * @param {boolean} debug - Create a debug object to go with this body?
  73216. */
  73217. enableBody: function (object, debug) {
  73218. if (object.hasOwnProperty('body') && object.body === null)
  73219. {
  73220. object.body = new Phaser.Physics.P2.Body(this.game, object, object.x, object.y, 1);
  73221. object.body.debug = debug;
  73222. if (typeof object.anchor !== 'undefined') {
  73223. object.anchor.set(0.5);
  73224. }
  73225. }
  73226. },
  73227. /**
  73228. * Impact event handling is disabled by default. Enable it before any impact events will be dispatched.
  73229. * In a busy world hundreds of impact events can be generated every step, so only enable this if you cannot do what you need via beginContact or collision masks.
  73230. *
  73231. * @method Phaser.Physics.P2#setImpactEvents
  73232. * @param {boolean} state - Set to true to enable impact events, or false to disable.
  73233. */
  73234. setImpactEvents: function (state) {
  73235. if (state)
  73236. {
  73237. this.world.on("impact", this.impactHandler, this);
  73238. }
  73239. else
  73240. {
  73241. this.world.off("impact", this.impactHandler, this);
  73242. }
  73243. },
  73244. /**
  73245. * Sets a callback to be fired after the Broadphase has collected collision pairs in the world.
  73246. * Just because a pair exists it doesn't mean they *will* collide, just that they potentially could do.
  73247. * If your calback returns `false` the pair will be removed from the narrowphase. This will stop them testing for collision this step.
  73248. * Returning `true` from the callback will ensure they are checked in the narrowphase.
  73249. *
  73250. * @method Phaser.Physics.P2#setPostBroadphaseCallback
  73251. * @param {function} callback - The callback that will receive the postBroadphase event data. It must return a boolean. Set to null to disable an existing callback.
  73252. * @param {object} context - The context under which the callback will be fired.
  73253. */
  73254. setPostBroadphaseCallback: function (callback, context) {
  73255. this.postBroadphaseCallback = callback;
  73256. this.callbackContext = context;
  73257. if (callback !== null)
  73258. {
  73259. this.world.on("postBroadphase", this.postBroadphaseHandler, this);
  73260. }
  73261. else
  73262. {
  73263. this.world.off("postBroadphase", this.postBroadphaseHandler, this);
  73264. }
  73265. },
  73266. /**
  73267. * Internal handler for the postBroadphase event.
  73268. *
  73269. * @method Phaser.Physics.P2#postBroadphaseHandler
  73270. * @private
  73271. * @param {object} event - The event data.
  73272. */
  73273. postBroadphaseHandler: function (event) {
  73274. if (!this.postBroadphaseCallback || event.pairs.length === 0)
  73275. {
  73276. return;
  73277. }
  73278. for (var i = event.pairs.length - 2; i >= 0; i -= 2)
  73279. {
  73280. if (event.pairs[i].parent && event.pairs[i+1].parent && !this.postBroadphaseCallback.call(this.callbackContext, event.pairs[i].parent, event.pairs[i+1].parent))
  73281. {
  73282. event.pairs.splice(i, 2);
  73283. }
  73284. }
  73285. },
  73286. /**
  73287. * Handles a p2 impact event.
  73288. *
  73289. * @method Phaser.Physics.P2#impactHandler
  73290. * @private
  73291. * @param {object} event - The event data.
  73292. */
  73293. impactHandler: function (event) {
  73294. if (event.bodyA.parent && event.bodyB.parent)
  73295. {
  73296. // Body vs. Body callbacks
  73297. var a = event.bodyA.parent;
  73298. var b = event.bodyB.parent;
  73299. if (a._bodyCallbacks[event.bodyB.id])
  73300. {
  73301. a._bodyCallbacks[event.bodyB.id].call(a._bodyCallbackContext[event.bodyB.id], a, b, event.shapeA, event.shapeB);
  73302. }
  73303. if (b._bodyCallbacks[event.bodyA.id])
  73304. {
  73305. b._bodyCallbacks[event.bodyA.id].call(b._bodyCallbackContext[event.bodyA.id], b, a, event.shapeB, event.shapeA);
  73306. }
  73307. // Body vs. Group callbacks
  73308. if (a._groupCallbacks[event.shapeB.collisionGroup])
  73309. {
  73310. a._groupCallbacks[event.shapeB.collisionGroup].call(a._groupCallbackContext[event.shapeB.collisionGroup], a, b, event.shapeA, event.shapeB);
  73311. }
  73312. if (b._groupCallbacks[event.shapeA.collisionGroup])
  73313. {
  73314. b._groupCallbacks[event.shapeA.collisionGroup].call(b._groupCallbackContext[event.shapeA.collisionGroup], b, a, event.shapeB, event.shapeA);
  73315. }
  73316. }
  73317. },
  73318. /**
  73319. * Handles a p2 begin contact event.
  73320. *
  73321. * @method Phaser.Physics.P2#beginContactHandler
  73322. * @param {object} event - The event data.
  73323. */
  73324. beginContactHandler: function (event) {
  73325. if (event.bodyA && event.bodyB)
  73326. {
  73327. this.onBeginContact.dispatch(event.bodyA, event.bodyB, event.shapeA, event.shapeB, event.contactEquations);
  73328. if (event.bodyA.parent)
  73329. {
  73330. event.bodyA.parent.onBeginContact.dispatch(event.bodyB.parent, event.bodyB, event.shapeA, event.shapeB, event.contactEquations);
  73331. }
  73332. if (event.bodyB.parent)
  73333. {
  73334. event.bodyB.parent.onBeginContact.dispatch(event.bodyA.parent, event.bodyA, event.shapeB, event.shapeA, event.contactEquations);
  73335. }
  73336. }
  73337. },
  73338. /**
  73339. * Handles a p2 end contact event.
  73340. *
  73341. * @method Phaser.Physics.P2#endContactHandler
  73342. * @param {object} event - The event data.
  73343. */
  73344. endContactHandler: function (event) {
  73345. if (event.bodyA && event.bodyB)
  73346. {
  73347. this.onEndContact.dispatch(event.bodyA, event.bodyB, event.shapeA, event.shapeB);
  73348. if (event.bodyA.parent)
  73349. {
  73350. event.bodyA.parent.onEndContact.dispatch(event.bodyB.parent, event.bodyB, event.shapeA, event.shapeB);
  73351. }
  73352. if (event.bodyB.parent)
  73353. {
  73354. event.bodyB.parent.onEndContact.dispatch(event.bodyA.parent, event.bodyA, event.shapeB, event.shapeA);
  73355. }
  73356. }
  73357. },
  73358. /**
  73359. * Sets the bounds of the Physics world to match the Game.World dimensions.
  73360. * You can optionally set which 'walls' to create: left, right, top or bottom.
  73361. *
  73362. * @method Phaser.Physics#setBoundsToWorld
  73363. * @param {boolean} [left=true] - If true will create the left bounds wall.
  73364. * @param {boolean} [right=true] - If true will create the right bounds wall.
  73365. * @param {boolean} [top=true] - If true will create the top bounds wall.
  73366. * @param {boolean} [bottom=true] - If true will create the bottom bounds wall.
  73367. * @param {boolean} [setCollisionGroup=true] - If true the Bounds will be set to use its own Collision Group.
  73368. */
  73369. setBoundsToWorld: function (left, right, top, bottom, setCollisionGroup) {
  73370. this.setBounds(this.game.world.bounds.x, this.game.world.bounds.y, this.game.world.bounds.width, this.game.world.bounds.height, left, right, top, bottom, setCollisionGroup);
  73371. },
  73372. /**
  73373. * Sets the given material against the 4 bounds of this World.
  73374. *
  73375. * @method Phaser.Physics#setWorldMaterial
  73376. * @param {Phaser.Physics.P2.Material} material - The material to set.
  73377. * @param {boolean} [left=true] - If true will set the material on the left bounds wall.
  73378. * @param {boolean} [right=true] - If true will set the material on the right bounds wall.
  73379. * @param {boolean} [top=true] - If true will set the material on the top bounds wall.
  73380. * @param {boolean} [bottom=true] - If true will set the material on the bottom bounds wall.
  73381. */
  73382. setWorldMaterial: function (material, left, right, top, bottom) {
  73383. if (left === undefined) { left = true; }
  73384. if (right === undefined) { right = true; }
  73385. if (top === undefined) { top = true; }
  73386. if (bottom === undefined) { bottom = true; }
  73387. if (left && this.walls.left)
  73388. {
  73389. this.walls.left.shapes[0].material = material;
  73390. }
  73391. if (right && this.walls.right)
  73392. {
  73393. this.walls.right.shapes[0].material = material;
  73394. }
  73395. if (top && this.walls.top)
  73396. {
  73397. this.walls.top.shapes[0].material = material;
  73398. }
  73399. if (bottom && this.walls.bottom)
  73400. {
  73401. this.walls.bottom.shapes[0].material = material;
  73402. }
  73403. },
  73404. /**
  73405. * By default the World will be set to collide everything with everything. The bounds of the world is a Body with 4 shapes, one for each face.
  73406. * If you start to use your own collision groups then your objects will no longer collide with the bounds.
  73407. * To fix this you need to adjust the bounds to use its own collision group first BEFORE changing your Sprites collision group.
  73408. *
  73409. * @method Phaser.Physics.P2#updateBoundsCollisionGroup
  73410. * @param {boolean} [setCollisionGroup=true] - If true the Bounds will be set to use its own Collision Group.
  73411. */
  73412. updateBoundsCollisionGroup: function (setCollisionGroup) {
  73413. if (setCollisionGroup === undefined) { setCollisionGroup = true; }
  73414. var mask = (setCollisionGroup) ? this.boundsCollisionGroup.mask : this.everythingCollisionGroup.mask;
  73415. if (this.walls.left)
  73416. {
  73417. this.walls.left.shapes[0].collisionGroup = mask;
  73418. }
  73419. if (this.walls.right)
  73420. {
  73421. this.walls.right.shapes[0].collisionGroup = mask;
  73422. }
  73423. if (this.walls.top)
  73424. {
  73425. this.walls.top.shapes[0].collisionGroup = mask;
  73426. }
  73427. if (this.walls.bottom)
  73428. {
  73429. this.walls.bottom.shapes[0].collisionGroup = mask;
  73430. }
  73431. this._boundsOwnGroup = setCollisionGroup;
  73432. },
  73433. /**
  73434. * Sets the bounds of the Physics world to match the given world pixel dimensions.
  73435. * You can optionally set which 'walls' to create: left, right, top or bottom.
  73436. * If none of the walls are given it will default to use the walls settings it had previously.
  73437. * I.e. if you previously told it to not have the left or right walls, and you then adjust the world size
  73438. * the newly created bounds will also not have the left and right walls.
  73439. * Explicitly state them in the parameters to override this.
  73440. *
  73441. * @method Phaser.Physics.P2#setBounds
  73442. * @param {number} x - The x coordinate of the top-left corner of the bounds.
  73443. * @param {number} y - The y coordinate of the top-left corner of the bounds.
  73444. * @param {number} width - The width of the bounds.
  73445. * @param {number} height - The height of the bounds.
  73446. * @param {boolean} [left=true] - If true will create the left bounds wall.
  73447. * @param {boolean} [right=true] - If true will create the right bounds wall.
  73448. * @param {boolean} [top=true] - If true will create the top bounds wall.
  73449. * @param {boolean} [bottom=true] - If true will create the bottom bounds wall.
  73450. * @param {boolean} [setCollisionGroup=true] - If true the Bounds will be set to use its own Collision Group.
  73451. */
  73452. setBounds: function (x, y, width, height, left, right, top, bottom, setCollisionGroup) {
  73453. if (left === undefined) { left = this._boundsLeft; }
  73454. if (right === undefined) { right = this._boundsRight; }
  73455. if (top === undefined) { top = this._boundsTop; }
  73456. if (bottom === undefined) { bottom = this._boundsBottom; }
  73457. if (setCollisionGroup === undefined) { setCollisionGroup = this._boundsOwnGroup; }
  73458. this.setupWall(left, 'left', x, y, 1.5707963267948966, setCollisionGroup);
  73459. this.setupWall(right, 'right', x + width, y, -1.5707963267948966, setCollisionGroup);
  73460. this.setupWall(top, 'top', x, y, -3.141592653589793, setCollisionGroup);
  73461. this.setupWall(bottom, 'bottom', x, y + height, 0, setCollisionGroup);
  73462. // Remember the bounds settings in case they change later on via World.setBounds
  73463. this._boundsLeft = left;
  73464. this._boundsRight = right;
  73465. this._boundsTop = top;
  73466. this._boundsBottom = bottom;
  73467. this._boundsOwnGroup = setCollisionGroup;
  73468. },
  73469. /**
  73470. * Internal method called by setBounds. Responsible for creating, updating or
  73471. * removing the wall body shapes.
  73472. *
  73473. * @method Phaser.Physics.P2#setupWall
  73474. * @private
  73475. * @param {boolean} create - True to create the wall shape, false to remove it.
  73476. * @param {string} wall - The wall segment to update.
  73477. * @param {number} x - The x coordinate of the wall.
  73478. * @param {number} y - The y coordinate of the wall.
  73479. * @param {float} angle - The angle of the wall.
  73480. * @param {boolean} [setCollisionGroup=true] - If true the Bounds will be set to use its own Collision Group.
  73481. */
  73482. setupWall: function (create, wall, x, y, angle, setCollisionGroup) {
  73483. if (create)
  73484. {
  73485. // We need a left wall. Do we have one already?
  73486. if (this.walls[wall])
  73487. {
  73488. this.walls[wall].position = [ this.pxmi(x), this.pxmi(y) ];
  73489. }
  73490. else
  73491. {
  73492. this.walls[wall] = new p2.Body({ mass: 0, position: [ this.pxmi(x), this.pxmi(y) ], angle: angle });
  73493. this.walls[wall].addShape(new p2.Plane());
  73494. this.world.addBody(this.walls[wall]);
  73495. }
  73496. if (setCollisionGroup)
  73497. {
  73498. this.walls[wall].shapes[0].collisionGroup = this.boundsCollisionGroup.mask;
  73499. }
  73500. }
  73501. else
  73502. {
  73503. if (this.walls[wall])
  73504. {
  73505. this.world.removeBody(this.walls[wall]);
  73506. this.walls[wall] = null;
  73507. }
  73508. }
  73509. },
  73510. /**
  73511. * Pauses the P2 World independent of the game pause state.
  73512. *
  73513. * @method Phaser.Physics.P2#pause
  73514. */
  73515. pause: function() {
  73516. this.paused = true;
  73517. },
  73518. /**
  73519. * Resumes a paused P2 World.
  73520. *
  73521. * @method Phaser.Physics.P2#resume
  73522. */
  73523. resume: function() {
  73524. this.paused = false;
  73525. },
  73526. /**
  73527. * Internal P2 update loop.
  73528. *
  73529. * @method Phaser.Physics.P2#update
  73530. */
  73531. update: function () {
  73532. // Do nothing if the physics engine was paused before
  73533. if (this.paused)
  73534. {
  73535. return;
  73536. }
  73537. if (this.useElapsedTime)
  73538. {
  73539. this.world.step(this.game.time.physicsElapsed);
  73540. }
  73541. else
  73542. {
  73543. this.world.step(this.frameRate);
  73544. }
  73545. },
  73546. /**
  73547. * Called by Phaser.Physics when a State swap occurs.
  73548. * Starts the begin and end Contact listeners again.
  73549. *
  73550. * @method Phaser.Physics.P2#reset
  73551. */
  73552. reset: function () {
  73553. this.world.on("beginContact", this.beginContactHandler, this);
  73554. this.world.on("endContact", this.endContactHandler, this);
  73555. this.nothingCollisionGroup = new Phaser.Physics.P2.CollisionGroup(1);
  73556. this.boundsCollisionGroup = new Phaser.Physics.P2.CollisionGroup(2);
  73557. this.everythingCollisionGroup = new Phaser.Physics.P2.CollisionGroup(2147483648);
  73558. this._collisionGroupID = 2;
  73559. this.setBoundsToWorld(true, true, true, true, false);
  73560. },
  73561. /**
  73562. * Clears all bodies from the simulation, resets callbacks and resets the collision bitmask.
  73563. *
  73564. * The P2 world is also cleared:
  73565. *
  73566. * * Removes all solver equations
  73567. * * Removes all constraints
  73568. * * Removes all bodies
  73569. * * Removes all springs
  73570. * * Removes all contact materials
  73571. *
  73572. * This is called automatically when you switch state.
  73573. *
  73574. * @method Phaser.Physics.P2#clear
  73575. */
  73576. clear: function () {
  73577. this.world.time = 0;
  73578. this.world.fixedStepTime = 0;
  73579. // Remove all solver equations
  73580. if (this.world.solver && this.world.solver.equations.length)
  73581. {
  73582. this.world.solver.removeAllEquations();
  73583. }
  73584. // Remove all constraints
  73585. var cs = this.world.constraints;
  73586. for (var i = cs.length - 1; i >= 0; i--)
  73587. {
  73588. this.world.removeConstraint(cs[i]);
  73589. }
  73590. // Remove all bodies
  73591. var bodies = this.world.bodies;
  73592. for (var i = bodies.length - 1; i >= 0; i--)
  73593. {
  73594. this.world.removeBody(bodies[i]);
  73595. }
  73596. // Remove all springs
  73597. var springs = this.world.springs;
  73598. for (var i = springs.length - 1; i >= 0; i--)
  73599. {
  73600. this.world.removeSpring(springs[i]);
  73601. }
  73602. // Remove all contact materials
  73603. var cms = this.world.contactMaterials;
  73604. for (var i = cms.length - 1; i >= 0; i--)
  73605. {
  73606. this.world.removeContactMaterial(cms[i]);
  73607. }
  73608. this.world.off("beginContact", this.beginContactHandler, this);
  73609. this.world.off("endContact", this.endContactHandler, this);
  73610. this.postBroadphaseCallback = null;
  73611. this.callbackContext = null;
  73612. this.impactCallback = null;
  73613. this.collisionGroups = [];
  73614. this._toRemove = [];
  73615. this.boundsCollidesWith = [];
  73616. // Remove the world bounds
  73617. this.walls = { left: null, right: null, top: null, bottom: null };
  73618. },
  73619. /**
  73620. * Clears all bodies from the simulation and unlinks World from Game. Should only be called on game shutdown. Call `clear` on a State change.
  73621. *
  73622. * @method Phaser.Physics.P2#destroy
  73623. */
  73624. destroy: function () {
  73625. this.clear();
  73626. this.game = null;
  73627. },
  73628. /**
  73629. * Add a body to the world.
  73630. *
  73631. * @method Phaser.Physics.P2#addBody
  73632. * @param {Phaser.Physics.P2.Body} body - The Body to add to the World.
  73633. * @return {boolean} True if the Body was added successfully, otherwise false.
  73634. */
  73635. addBody: function (body) {
  73636. if (body.data.world)
  73637. {
  73638. return false;
  73639. }
  73640. else
  73641. {
  73642. this.world.addBody(body.data);
  73643. this.onBodyAdded.dispatch(body);
  73644. return true;
  73645. }
  73646. },
  73647. /**
  73648. * Removes a body from the world. This will silently fail if the body wasn't part of the world to begin with.
  73649. *
  73650. * @method Phaser.Physics.P2#removeBody
  73651. * @param {Phaser.Physics.P2.Body} body - The Body to remove from the World.
  73652. * @return {Phaser.Physics.P2.Body} The Body that was removed.
  73653. */
  73654. removeBody: function (body) {
  73655. if (body.data.world === this.world)
  73656. {
  73657. this.world.removeBody(body.data);
  73658. this.onBodyRemoved.dispatch(body);
  73659. }
  73660. return body;
  73661. },
  73662. /**
  73663. * Adds a Spring to the world.
  73664. *
  73665. * @method Phaser.Physics.P2#addSpring
  73666. * @param {Phaser.Physics.P2.Spring|p2.LinearSpring|p2.RotationalSpring} spring - The Spring to add to the World.
  73667. * @return {Phaser.Physics.P2.Spring} The Spring that was added.
  73668. */
  73669. addSpring: function (spring) {
  73670. if (spring instanceof Phaser.Physics.P2.Spring || spring instanceof Phaser.Physics.P2.RotationalSpring)
  73671. {
  73672. this.world.addSpring(spring.data);
  73673. }
  73674. else
  73675. {
  73676. this.world.addSpring(spring);
  73677. }
  73678. this.onSpringAdded.dispatch(spring);
  73679. return spring;
  73680. },
  73681. /**
  73682. * Removes a Spring from the world.
  73683. *
  73684. * @method Phaser.Physics.P2#removeSpring
  73685. * @param {Phaser.Physics.P2.Spring} spring - The Spring to remove from the World.
  73686. * @return {Phaser.Physics.P2.Spring} The Spring that was removed.
  73687. */
  73688. removeSpring: function (spring) {
  73689. if (spring instanceof Phaser.Physics.P2.Spring || spring instanceof Phaser.Physics.P2.RotationalSpring)
  73690. {
  73691. this.world.removeSpring(spring.data);
  73692. }
  73693. else
  73694. {
  73695. this.world.removeSpring(spring);
  73696. }
  73697. this.onSpringRemoved.dispatch(spring);
  73698. return spring;
  73699. },
  73700. /**
  73701. * Creates a constraint that tries to keep the distance between two bodies constant.
  73702. *
  73703. * @method Phaser.Physics.P2#createDistanceConstraint
  73704. * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyA - First connected body.
  73705. * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyB - Second connected body.
  73706. * @param {number} distance - The distance to keep between the bodies.
  73707. * @param {Array} [localAnchorA] - The anchor point for bodyA, defined locally in bodyA frame. Defaults to [0,0].
  73708. * @param {Array} [localAnchorB] - The anchor point for bodyB, defined locally in bodyB frame. Defaults to [0,0].
  73709. * @param {number} [maxForce] - The maximum force that should be applied to constrain the bodies.
  73710. * @return {Phaser.Physics.P2.DistanceConstraint} The constraint
  73711. */
  73712. createDistanceConstraint: function (bodyA, bodyB, distance, localAnchorA, localAnchorB, maxForce) {
  73713. bodyA = this.getBody(bodyA);
  73714. bodyB = this.getBody(bodyB);
  73715. if (!bodyA || !bodyB)
  73716. {
  73717. console.warn('Cannot create Constraint, invalid body objects given');
  73718. }
  73719. else
  73720. {
  73721. return this.addConstraint(new Phaser.Physics.P2.DistanceConstraint(this, bodyA, bodyB, distance, localAnchorA, localAnchorB, maxForce));
  73722. }
  73723. },
  73724. /**
  73725. * Creates a constraint that tries to keep the distance between two bodies constant.
  73726. *
  73727. * @method Phaser.Physics.P2#createGearConstraint
  73728. * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyA - First connected body.
  73729. * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyB - Second connected body.
  73730. * @param {number} [angle=0] - The relative angle
  73731. * @param {number} [ratio=1] - The gear ratio.
  73732. * @return {Phaser.Physics.P2.GearConstraint} The constraint
  73733. */
  73734. createGearConstraint: function (bodyA, bodyB, angle, ratio) {
  73735. bodyA = this.getBody(bodyA);
  73736. bodyB = this.getBody(bodyB);
  73737. if (!bodyA || !bodyB)
  73738. {
  73739. console.warn('Cannot create Constraint, invalid body objects given');
  73740. }
  73741. else
  73742. {
  73743. return this.addConstraint(new Phaser.Physics.P2.GearConstraint(this, bodyA, bodyB, angle, ratio));
  73744. }
  73745. },
  73746. /**
  73747. * Connects two bodies at given offset points, letting them rotate relative to each other around this point.
  73748. * The pivot points are given in world (pixel) coordinates.
  73749. *
  73750. * @method Phaser.Physics.P2#createRevoluteConstraint
  73751. * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyA - First connected body.
  73752. * @param {Array} pivotA - The point relative to the center of mass of bodyA which bodyA is constrained to. The value is an array with 2 elements matching x and y, i.e: [32, 32].
  73753. * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyB - Second connected body.
  73754. * @param {Array} pivotB - The point relative to the center of mass of bodyB which bodyB is constrained to. The value is an array with 2 elements matching x and y, i.e: [32, 32].
  73755. * @param {number} [maxForce=0] - The maximum force that should be applied to constrain the bodies.
  73756. * @param {Float32Array} [worldPivot=null] - A pivot point given in world coordinates. If specified, localPivotA and localPivotB are automatically computed from this value.
  73757. * @return {Phaser.Physics.P2.RevoluteConstraint} The constraint
  73758. */
  73759. createRevoluteConstraint: function (bodyA, pivotA, bodyB, pivotB, maxForce, worldPivot) {
  73760. bodyA = this.getBody(bodyA);
  73761. bodyB = this.getBody(bodyB);
  73762. if (!bodyA || !bodyB)
  73763. {
  73764. console.warn('Cannot create Constraint, invalid body objects given');
  73765. }
  73766. else
  73767. {
  73768. return this.addConstraint(new Phaser.Physics.P2.RevoluteConstraint(this, bodyA, pivotA, bodyB, pivotB, maxForce, worldPivot));
  73769. }
  73770. },
  73771. /**
  73772. * Locks the relative position between two bodies.
  73773. *
  73774. * @method Phaser.Physics.P2#createLockConstraint
  73775. * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyA - First connected body.
  73776. * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyB - Second connected body.
  73777. * @param {Array} [offset] - The offset of bodyB in bodyA's frame. The value is an array with 2 elements matching x and y, i.e: [32, 32].
  73778. * @param {number} [angle=0] - The angle of bodyB in bodyA's frame.
  73779. * @param {number} [maxForce] - The maximum force that should be applied to constrain the bodies.
  73780. * @return {Phaser.Physics.P2.LockConstraint} The constraint
  73781. */
  73782. createLockConstraint: function (bodyA, bodyB, offset, angle, maxForce) {
  73783. bodyA = this.getBody(bodyA);
  73784. bodyB = this.getBody(bodyB);
  73785. if (!bodyA || !bodyB)
  73786. {
  73787. console.warn('Cannot create Constraint, invalid body objects given');
  73788. }
  73789. else
  73790. {
  73791. return this.addConstraint(new Phaser.Physics.P2.LockConstraint(this, bodyA, bodyB, offset, angle, maxForce));
  73792. }
  73793. },
  73794. /**
  73795. * Constraint that only allows bodies to move along a line, relative to each other.
  73796. * See http://www.iforce2d.net/b2dtut/joints-prismatic
  73797. *
  73798. * @method Phaser.Physics.P2#createPrismaticConstraint
  73799. * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyA - First connected body.
  73800. * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyB - Second connected body.
  73801. * @param {boolean} [lockRotation=true] - If set to false, bodyB will be free to rotate around its anchor point.
  73802. * @param {Array} [anchorA] - Body A's anchor point, defined in its own local frame. The value is an array with 2 elements matching x and y, i.e: [32, 32].
  73803. * @param {Array} [anchorB] - Body A's anchor point, defined in its own local frame. The value is an array with 2 elements matching x and y, i.e: [32, 32].
  73804. * @param {Array} [axis] - An axis, defined in body A frame, that body B's anchor point may slide along. The value is an array with 2 elements matching x and y, i.e: [32, 32].
  73805. * @param {number} [maxForce] - The maximum force that should be applied to constrain the bodies.
  73806. * @return {Phaser.Physics.P2.PrismaticConstraint} The constraint
  73807. */
  73808. createPrismaticConstraint: function (bodyA, bodyB, lockRotation, anchorA, anchorB, axis, maxForce) {
  73809. bodyA = this.getBody(bodyA);
  73810. bodyB = this.getBody(bodyB);
  73811. if (!bodyA || !bodyB)
  73812. {
  73813. console.warn('Cannot create Constraint, invalid body objects given');
  73814. }
  73815. else
  73816. {
  73817. return this.addConstraint(new Phaser.Physics.P2.PrismaticConstraint(this, bodyA, bodyB, lockRotation, anchorA, anchorB, axis, maxForce));
  73818. }
  73819. },
  73820. /**
  73821. * Adds a Constraint to the world.
  73822. *
  73823. * @method Phaser.Physics.P2#addConstraint
  73824. * @param {Phaser.Physics.P2.Constraint} constraint - The Constraint to add to the World.
  73825. * @return {Phaser.Physics.P2.Constraint} The Constraint that was added.
  73826. */
  73827. addConstraint: function (constraint) {
  73828. this.world.addConstraint(constraint);
  73829. this.onConstraintAdded.dispatch(constraint);
  73830. return constraint;
  73831. },
  73832. /**
  73833. * Removes a Constraint from the world.
  73834. *
  73835. * @method Phaser.Physics.P2#removeConstraint
  73836. * @param {Phaser.Physics.P2.Constraint} constraint - The Constraint to be removed from the World.
  73837. * @return {Phaser.Physics.P2.Constraint} The Constraint that was removed.
  73838. */
  73839. removeConstraint: function (constraint) {
  73840. this.world.removeConstraint(constraint);
  73841. this.onConstraintRemoved.dispatch(constraint);
  73842. return constraint;
  73843. },
  73844. /**
  73845. * Adds a Contact Material to the world.
  73846. *
  73847. * @method Phaser.Physics.P2#addContactMaterial
  73848. * @param {Phaser.Physics.P2.ContactMaterial} material - The Contact Material to be added to the World.
  73849. * @return {Phaser.Physics.P2.ContactMaterial} The Contact Material that was added.
  73850. */
  73851. addContactMaterial: function (material) {
  73852. this.world.addContactMaterial(material);
  73853. this.onContactMaterialAdded.dispatch(material);
  73854. return material;
  73855. },
  73856. /**
  73857. * Removes a Contact Material from the world.
  73858. *
  73859. * @method Phaser.Physics.P2#removeContactMaterial
  73860. * @param {Phaser.Physics.P2.ContactMaterial} material - The Contact Material to be removed from the World.
  73861. * @return {Phaser.Physics.P2.ContactMaterial} The Contact Material that was removed.
  73862. */
  73863. removeContactMaterial: function (material) {
  73864. this.world.removeContactMaterial(material);
  73865. this.onContactMaterialRemoved.dispatch(material);
  73866. return material;
  73867. },
  73868. /**
  73869. * Gets a Contact Material based on the two given Materials.
  73870. *
  73871. * @method Phaser.Physics.P2#getContactMaterial
  73872. * @param {Phaser.Physics.P2.Material} materialA - The first Material to search for.
  73873. * @param {Phaser.Physics.P2.Material} materialB - The second Material to search for.
  73874. * @return {Phaser.Physics.P2.ContactMaterial|boolean} The Contact Material or false if none was found matching the Materials given.
  73875. */
  73876. getContactMaterial: function (materialA, materialB) {
  73877. return this.world.getContactMaterial(materialA, materialB);
  73878. },
  73879. /**
  73880. * Sets the given Material against all Shapes owned by all the Bodies in the given array.
  73881. *
  73882. * @method Phaser.Physics.P2#setMaterial
  73883. * @param {Phaser.Physics.P2.Material} material - The Material to be applied to the given Bodies.
  73884. * @param {array<Phaser.Physics.P2.Body>} bodies - An Array of Body objects that the given Material will be set on.
  73885. */
  73886. setMaterial: function (material, bodies) {
  73887. var i = bodies.length;
  73888. while (i--)
  73889. {
  73890. bodies[i].setMaterial(material);
  73891. }
  73892. },
  73893. /**
  73894. * Creates a Material. Materials are applied to Shapes owned by a Body and can be set with Body.setMaterial().
  73895. * Materials are a way to control what happens when Shapes collide. Combine unique Materials together to create Contact Materials.
  73896. * Contact Materials have properties such as friction and restitution that allow for fine-grained collision control between different Materials.
  73897. *
  73898. * @method Phaser.Physics.P2#createMaterial
  73899. * @param {string} [name] - Optional name of the Material. Each Material has a unique ID but string names are handy for debugging.
  73900. * @param {Phaser.Physics.P2.Body} [body] - Optional Body. If given it will assign the newly created Material to the Body shapes.
  73901. * @return {Phaser.Physics.P2.Material} The Material that was created. This is also stored in Phaser.Physics.P2.materials.
  73902. */
  73903. createMaterial: function (name, body) {
  73904. name = name || '';
  73905. var material = new Phaser.Physics.P2.Material(name);
  73906. this.materials.push(material);
  73907. if (typeof body !== 'undefined')
  73908. {
  73909. body.setMaterial(material);
  73910. }
  73911. return material;
  73912. },
  73913. /**
  73914. * Creates a Contact Material from the two given Materials. You can then edit the properties of the Contact Material directly.
  73915. *
  73916. * @method Phaser.Physics.P2#createContactMaterial
  73917. * @param {Phaser.Physics.P2.Material} [materialA] - The first Material to create the ContactMaterial from. If undefined it will create a new Material object first.
  73918. * @param {Phaser.Physics.P2.Material} [materialB] - The second Material to create the ContactMaterial from. If undefined it will create a new Material object first.
  73919. * @param {object} [options] - Material options object.
  73920. * @return {Phaser.Physics.P2.ContactMaterial} The Contact Material that was created.
  73921. */
  73922. createContactMaterial: function (materialA, materialB, options) {
  73923. if (materialA === undefined) { materialA = this.createMaterial(); }
  73924. if (materialB === undefined) { materialB = this.createMaterial(); }
  73925. var contact = new Phaser.Physics.P2.ContactMaterial(materialA, materialB, options);
  73926. return this.addContactMaterial(contact);
  73927. },
  73928. /**
  73929. * Populates and returns an array with references to of all current Bodies in the world.
  73930. *
  73931. * @method Phaser.Physics.P2#getBodies
  73932. * @return {array<Phaser.Physics.P2.Body>} An array containing all current Bodies in the world.
  73933. */
  73934. getBodies: function () {
  73935. var output = [];
  73936. var i = this.world.bodies.length;
  73937. while (i--)
  73938. {
  73939. output.push(this.world.bodies[i].parent);
  73940. }
  73941. return output;
  73942. },
  73943. /**
  73944. * Checks the given object to see if it has a p2.Body and if so returns it.
  73945. *
  73946. * @method Phaser.Physics.P2#getBody
  73947. * @param {object} object - The object to check for a p2.Body on.
  73948. * @return {p2.Body} The p2.Body, or null if not found.
  73949. */
  73950. getBody: function (object) {
  73951. if (object instanceof p2.Body)
  73952. {
  73953. // Native p2 body
  73954. return object;
  73955. }
  73956. else if (object instanceof Phaser.Physics.P2.Body)
  73957. {
  73958. // Phaser P2 Body
  73959. return object.data;
  73960. }
  73961. else if (object['body'] && object['body'].type === Phaser.Physics.P2JS)
  73962. {
  73963. // Sprite, TileSprite, etc
  73964. return object.body.data;
  73965. }
  73966. return null;
  73967. },
  73968. /**
  73969. * Populates and returns an array of all current Springs in the world.
  73970. *
  73971. * @method Phaser.Physics.P2#getSprings
  73972. * @return {array<Phaser.Physics.P2.Spring>} An array containing all current Springs in the world.
  73973. */
  73974. getSprings: function () {
  73975. var output = [];
  73976. var i = this.world.springs.length;
  73977. while (i--)
  73978. {
  73979. output.push(this.world.springs[i].parent);
  73980. }
  73981. return output;
  73982. },
  73983. /**
  73984. * Populates and returns an array of all current Constraints in the world.
  73985. * You will get an array of p2 constraints back. This can be of mixed types, for example the array may contain
  73986. * PrismaticConstraints, RevoluteConstraints or any other valid p2 constraint type.
  73987. *
  73988. * @method Phaser.Physics.P2#getConstraints
  73989. * @return {array<Phaser.Physics.P2.Constraint>} An array containing all current Constraints in the world.
  73990. */
  73991. getConstraints: function () {
  73992. var output = [];
  73993. var i = this.world.constraints.length;
  73994. while (i--)
  73995. {
  73996. output.push(this.world.constraints[i]);
  73997. }
  73998. return output;
  73999. },
  74000. /**
  74001. * Test if a world point overlaps bodies. You will get an array of actual P2 bodies back. You can find out which Sprite a Body belongs to
  74002. * (if any) by checking the Body.parent.sprite property. Body.parent is a Phaser.Physics.P2.Body property.
  74003. *
  74004. * @method Phaser.Physics.P2#hitTest
  74005. * @param {Phaser.Point} worldPoint - Point to use for intersection tests. The points values must be in world (pixel) coordinates.
  74006. * @param {Array<Phaser.Physics.P2.Body|Phaser.Sprite|p2.Body>} [bodies] - A list of objects to check for intersection. If not given it will check Phaser.Physics.P2.world.bodies (i.e. all world bodies)
  74007. * @param {number} [precision=5] - Used for matching against particles and lines. Adds some margin to these infinitesimal objects.
  74008. * @param {boolean} [filterStatic=false] - If true all Static objects will be removed from the results array.
  74009. * @return {Array} Array of bodies that overlap the point.
  74010. */
  74011. hitTest: function (worldPoint, bodies, precision, filterStatic) {
  74012. if (bodies === undefined) { bodies = this.world.bodies; }
  74013. if (precision === undefined) { precision = 5; }
  74014. if (filterStatic === undefined) { filterStatic = false; }
  74015. var physicsPosition = [ this.pxmi(worldPoint.x), this.pxmi(worldPoint.y) ];
  74016. var query = [];
  74017. var i = bodies.length;
  74018. while (i--)
  74019. {
  74020. if (bodies[i] instanceof Phaser.Physics.P2.Body && !(filterStatic && bodies[i].data.type === p2.Body.STATIC))
  74021. {
  74022. query.push(bodies[i].data);
  74023. }
  74024. else if (bodies[i] instanceof p2.Body && bodies[i].parent && !(filterStatic && bodies[i].type === p2.Body.STATIC))
  74025. {
  74026. query.push(bodies[i]);
  74027. }
  74028. else if (bodies[i] instanceof Phaser.Sprite && bodies[i].hasOwnProperty('body') && !(filterStatic && bodies[i].body.data.type === p2.Body.STATIC))
  74029. {
  74030. query.push(bodies[i].body.data);
  74031. }
  74032. }
  74033. return this.world.hitTest(physicsPosition, query, precision);
  74034. },
  74035. /**
  74036. * Converts the current world into a JSON object.
  74037. *
  74038. * @method Phaser.Physics.P2#toJSON
  74039. * @return {object} A JSON representation of the world.
  74040. */
  74041. toJSON: function () {
  74042. return this.world.toJSON();
  74043. },
  74044. /**
  74045. * Creates a new Collision Group and optionally applies it to the given object.
  74046. * Collision Groups are handled using bitmasks, therefore you have a fixed limit you can create before you need to re-use older groups.
  74047. *
  74048. * @method Phaser.Physics.P2#createCollisionGroup
  74049. * @param {Phaser.Group|Phaser.Sprite} [object] - An optional Sprite or Group to apply the Collision Group to. If a Group is given it will be applied to all top-level children.
  74050. */
  74051. createCollisionGroup: function (object) {
  74052. var bitmask = Math.pow(2, this._collisionGroupID);
  74053. if (this.walls.left)
  74054. {
  74055. this.walls.left.shapes[0].collisionMask = this.walls.left.shapes[0].collisionMask | bitmask;
  74056. }
  74057. if (this.walls.right)
  74058. {
  74059. this.walls.right.shapes[0].collisionMask = this.walls.right.shapes[0].collisionMask | bitmask;
  74060. }
  74061. if (this.walls.top)
  74062. {
  74063. this.walls.top.shapes[0].collisionMask = this.walls.top.shapes[0].collisionMask | bitmask;
  74064. }
  74065. if (this.walls.bottom)
  74066. {
  74067. this.walls.bottom.shapes[0].collisionMask = this.walls.bottom.shapes[0].collisionMask | bitmask;
  74068. }
  74069. this._collisionGroupID++;
  74070. var group = new Phaser.Physics.P2.CollisionGroup(bitmask);
  74071. this.collisionGroups.push(group);
  74072. if (object)
  74073. {
  74074. this.setCollisionGroup(object, group);
  74075. }
  74076. return group;
  74077. },
  74078. /**
  74079. * Sets the given CollisionGroup to be the collision group for all shapes in this Body, unless a shape is specified.
  74080. * Note that this resets the collisionMask and any previously set groups. See Body.collides() for appending them.
  74081. *
  74082. * @method Phaser.Physics.P2y#setCollisionGroup
  74083. * @param {Phaser.Group|Phaser.Sprite} object - A Sprite or Group to apply the Collision Group to. If a Group is given it will be applied to all top-level children.
  74084. * @param {Phaser.Physics.CollisionGroup} group - The Collision Group that this Bodies shapes will use.
  74085. */
  74086. setCollisionGroup: function (object, group) {
  74087. if (object instanceof Phaser.Group)
  74088. {
  74089. for (var i = 0; i < object.total; i++)
  74090. {
  74091. if (object.children[i]['body'] && object.children[i]['body'].type === Phaser.Physics.P2JS)
  74092. {
  74093. object.children[i].body.setCollisionGroup(group);
  74094. }
  74095. }
  74096. }
  74097. else
  74098. {
  74099. object.body.setCollisionGroup(group);
  74100. }
  74101. },
  74102. /**
  74103. * Creates a linear spring, connecting two bodies. A spring can have a resting length, a stiffness and damping.
  74104. *
  74105. * @method Phaser.Physics.P2#createSpring
  74106. * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyA - First connected body.
  74107. * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyB - Second connected body.
  74108. * @param {number} [restLength=1] - Rest length of the spring. A number > 0.
  74109. * @param {number} [stiffness=100] - Stiffness of the spring. A number >= 0.
  74110. * @param {number} [damping=1] - Damping of the spring. A number >= 0.
  74111. * @param {Array} [worldA] - Where to hook the spring to body A in world coordinates. This value is an array by 2 elements, x and y, i.e: [32, 32].
  74112. * @param {Array} [worldB] - Where to hook the spring to body B in world coordinates. This value is an array by 2 elements, x and y, i.e: [32, 32].
  74113. * @param {Array} [localA] - Where to hook the spring to body A in local body coordinates. This value is an array by 2 elements, x and y, i.e: [32, 32].
  74114. * @param {Array} [localB] - Where to hook the spring to body B in local body coordinates. This value is an array by 2 elements, x and y, i.e: [32, 32].
  74115. * @return {Phaser.Physics.P2.Spring} The spring
  74116. */
  74117. createSpring: function (bodyA, bodyB, restLength, stiffness, damping, worldA, worldB, localA, localB) {
  74118. bodyA = this.getBody(bodyA);
  74119. bodyB = this.getBody(bodyB);
  74120. if (!bodyA || !bodyB)
  74121. {
  74122. console.warn('Cannot create Spring, invalid body objects given');
  74123. }
  74124. else
  74125. {
  74126. return this.addSpring(new Phaser.Physics.P2.Spring(this, bodyA, bodyB, restLength, stiffness, damping, worldA, worldB, localA, localB));
  74127. }
  74128. },
  74129. /**
  74130. * Creates a rotational spring, connecting two bodies. A spring can have a resting length, a stiffness and damping.
  74131. *
  74132. * @method Phaser.Physics.P2#createRotationalSpring
  74133. * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyA - First connected body.
  74134. * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyB - Second connected body.
  74135. * @param {number} [restAngle] - The relative angle of bodies at which the spring is at rest. If not given, it's set to the current relative angle between the bodies.
  74136. * @param {number} [stiffness=100] - Stiffness of the spring. A number >= 0.
  74137. * @param {number} [damping=1] - Damping of the spring. A number >= 0.
  74138. * @return {Phaser.Physics.P2.RotationalSpring} The spring
  74139. */
  74140. createRotationalSpring: function (bodyA, bodyB, restAngle, stiffness, damping) {
  74141. bodyA = this.getBody(bodyA);
  74142. bodyB = this.getBody(bodyB);
  74143. if (!bodyA || !bodyB)
  74144. {
  74145. console.warn('Cannot create Rotational Spring, invalid body objects given');
  74146. }
  74147. else
  74148. {
  74149. return this.addSpring(new Phaser.Physics.P2.RotationalSpring(this, bodyA, bodyB, restAngle, stiffness, damping));
  74150. }
  74151. },
  74152. /**
  74153. * Creates a new Body and adds it to the World.
  74154. *
  74155. * @method Phaser.Physics.P2#createBody
  74156. * @param {number} x - The x coordinate of Body.
  74157. * @param {number} y - The y coordinate of Body.
  74158. * @param {number} mass - The mass of the Body. A mass of 0 means a 'static' Body is created.
  74159. * @param {boolean} [addToWorld=false] - Automatically add this Body to the world? (usually false as it won't have any shapes on construction).
  74160. * @param {object} options - An object containing the build options:
  74161. * @param {boolean} [options.optimalDecomp=false] - Set to true if you need optimal decomposition. Warning: very slow for polygons with more than 10 vertices.
  74162. * @param {boolean} [options.skipSimpleCheck=false] - Set to true if you already know that the path is not intersecting itself.
  74163. * @param {boolean|number} [options.removeCollinearPoints=false] - Set to a number (angle threshold value) to remove collinear points, or false to keep all points.
  74164. * @param {(number[]|...number)} points - An array of 2d vectors that form the convex or concave polygon.
  74165. * Either [[0,0], [0,1],...] or a flat array of numbers that will be interpreted as [x,y, x,y, ...],
  74166. * or the arguments passed can be flat x,y values e.g. `setPolygon(options, x,y, x,y, x,y, ...)` where `x` and `y` are numbers.
  74167. * @return {Phaser.Physics.P2.Body} The body
  74168. */
  74169. createBody: function (x, y, mass, addToWorld, options, data) {
  74170. if (addToWorld === undefined) { addToWorld = false; }
  74171. var body = new Phaser.Physics.P2.Body(this.game, null, x, y, mass);
  74172. if (data)
  74173. {
  74174. var result = body.addPolygon(options, data);
  74175. if (!result)
  74176. {
  74177. return false;
  74178. }
  74179. }
  74180. if (addToWorld)
  74181. {
  74182. this.world.addBody(body.data);
  74183. }
  74184. return body;
  74185. },
  74186. /**
  74187. * Creates a new Particle and adds it to the World.
  74188. *
  74189. * @method Phaser.Physics.P2#createParticle
  74190. * @param {number} x - The x coordinate of Body.
  74191. * @param {number} y - The y coordinate of Body.
  74192. * @param {number} mass - The mass of the Body. A mass of 0 means a 'static' Body is created.
  74193. * @param {boolean} [addToWorld=false] - Automatically add this Body to the world? (usually false as it won't have any shapes on construction).
  74194. * @param {object} options - An object containing the build options:
  74195. * @param {boolean} [options.optimalDecomp=false] - Set to true if you need optimal decomposition. Warning: very slow for polygons with more than 10 vertices.
  74196. * @param {boolean} [options.skipSimpleCheck=false] - Set to true if you already know that the path is not intersecting itself.
  74197. * @param {boolean|number} [options.removeCollinearPoints=false] - Set to a number (angle threshold value) to remove collinear points, or false to keep all points.
  74198. * @param {(number[]|...number)} points - An array of 2d vectors that form the convex or concave polygon.
  74199. * Either [[0,0], [0,1],...] or a flat array of numbers that will be interpreted as [x,y, x,y, ...],
  74200. * or the arguments passed can be flat x,y values e.g. `setPolygon(options, x,y, x,y, x,y, ...)` where `x` and `y` are numbers.
  74201. */
  74202. createParticle: function (x, y, mass, addToWorld, options, data) {
  74203. if (addToWorld === undefined) { addToWorld = false; }
  74204. var body = new Phaser.Physics.P2.Body(this.game, null, x, y, mass);
  74205. if (data)
  74206. {
  74207. var result = body.addPolygon(options, data);
  74208. if (!result)
  74209. {
  74210. return false;
  74211. }
  74212. }
  74213. if (addToWorld)
  74214. {
  74215. this.world.addBody(body.data);
  74216. }
  74217. return body;
  74218. },
  74219. /**
  74220. * Converts all of the polylines objects inside a Tiled ObjectGroup into physics bodies that are added to the world.
  74221. * Note that the polylines must be created in such a way that they can withstand polygon decomposition.
  74222. *
  74223. * @method Phaser.Physics.P2#convertCollisionObjects
  74224. * @param {Phaser.Tilemap} map - The Tilemap to get the map data from.
  74225. * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. If not given will default to map.currentLayer.
  74226. * @param {boolean} [addToWorld=true] - If true it will automatically add each body to the world.
  74227. * @return {array} An array of the Phaser.Physics.Body objects that have been created.
  74228. */
  74229. convertCollisionObjects: function (map, layer, addToWorld) {
  74230. if (addToWorld === undefined) { addToWorld = true; }
  74231. var output = [];
  74232. for (var i = 0, len = map.collision[layer].length; i < len; i++)
  74233. {
  74234. // name: json.layers[i].objects[v].name,
  74235. // x: json.layers[i].objects[v].x,
  74236. // y: json.layers[i].objects[v].y,
  74237. // width: json.layers[i].objects[v].width,
  74238. // height: json.layers[i].objects[v].height,
  74239. // visible: json.layers[i].objects[v].visible,
  74240. // properties: json.layers[i].objects[v].properties,
  74241. // polyline: json.layers[i].objects[v].polyline
  74242. var object = map.collision[layer][i];
  74243. var body = this.createBody(object.x, object.y, 0, addToWorld, {}, object.polyline);
  74244. if (body)
  74245. {
  74246. output.push(body);
  74247. }
  74248. }
  74249. return output;
  74250. },
  74251. /**
  74252. * Clears all physics bodies from the given TilemapLayer that were created with `World.convertTilemap`.
  74253. *
  74254. * @method Phaser.Physics.P2#clearTilemapLayerBodies
  74255. * @param {Phaser.Tilemap} map - The Tilemap to get the map data from.
  74256. * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. If not given will default to map.currentLayer.
  74257. */
  74258. clearTilemapLayerBodies: function (map, layer) {
  74259. layer = map.getLayer(layer);
  74260. var i = map.layers[layer].bodies.length;
  74261. while (i--)
  74262. {
  74263. map.layers[layer].bodies[i].destroy();
  74264. }
  74265. map.layers[layer].bodies.length = 0;
  74266. },
  74267. /**
  74268. * Goes through all tiles in the given Tilemap and TilemapLayer and converts those set to collide into physics bodies.
  74269. * Only call this *after* you have specified all of the tiles you wish to collide with calls like Tilemap.setCollisionBetween, etc.
  74270. * Every time you call this method it will destroy any previously created bodies and remove them from the world.
  74271. * Therefore understand it's a very expensive operation and not to be done in a core game update loop.
  74272. *
  74273. * @method Phaser.Physics.P2#convertTilemap
  74274. * @param {Phaser.Tilemap} map - The Tilemap to get the map data from.
  74275. * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. If not given will default to map.currentLayer.
  74276. * @param {boolean} [addToWorld=true] - If true it will automatically add each body to the world, otherwise it's up to you to do so.
  74277. * @param {boolean} [optimize=true] - If true adjacent colliding tiles will be combined into a single body to save processing. However it means you cannot perform specific Tile to Body collision responses.
  74278. * @return {array} An array of the Phaser.Physics.P2.Body objects that were created.
  74279. */
  74280. convertTilemap: function (map, layer, addToWorld, optimize) {
  74281. layer = map.getLayer(layer);
  74282. if (addToWorld === undefined) { addToWorld = true; }
  74283. if (optimize === undefined) { optimize = true; }
  74284. // If the bodies array is already populated we need to nuke it
  74285. this.clearTilemapLayerBodies(map, layer);
  74286. var width = 0;
  74287. var sx = 0;
  74288. var sy = 0;
  74289. for (var y = 0, h = map.layers[layer].height; y < h; y++)
  74290. {
  74291. width = 0;
  74292. for (var x = 0, w = map.layers[layer].width; x < w; x++)
  74293. {
  74294. var tile = map.layers[layer].data[y][x];
  74295. if (tile && tile.index > -1 && tile.collides)
  74296. {
  74297. if (optimize)
  74298. {
  74299. var right = map.getTileRight(layer, x, y);
  74300. if (width === 0)
  74301. {
  74302. sx = tile.x * tile.width;
  74303. sy = tile.y * tile.height;
  74304. width = tile.width;
  74305. }
  74306. if (right && right.collides)
  74307. {
  74308. width += tile.width;
  74309. }
  74310. else
  74311. {
  74312. var body = this.createBody(sx, sy, 0, false);
  74313. body.addRectangle(width, tile.height, width / 2, tile.height / 2, 0);
  74314. if (addToWorld)
  74315. {
  74316. this.addBody(body);
  74317. }
  74318. map.layers[layer].bodies.push(body);
  74319. width = 0;
  74320. }
  74321. }
  74322. else
  74323. {
  74324. var body = this.createBody(tile.x * tile.width, tile.y * tile.height, 0, false);
  74325. body.addRectangle(tile.width, tile.height, tile.width / 2, tile.height / 2, 0);
  74326. if (addToWorld)
  74327. {
  74328. this.addBody(body);
  74329. }
  74330. map.layers[layer].bodies.push(body);
  74331. }
  74332. }
  74333. }
  74334. }
  74335. return map.layers[layer].bodies;
  74336. },
  74337. /**
  74338. * Convert p2 physics value (meters) to pixel scale.
  74339. * By default Phaser uses a scale of 20px per meter.
  74340. * If you need to modify this you can over-ride these functions via the Physics Configuration object.
  74341. *
  74342. * @method Phaser.Physics.P2#mpx
  74343. * @param {number} v - The value to convert.
  74344. * @return {number} The scaled value.
  74345. */
  74346. mpx: function (v) {
  74347. return v *= 20;
  74348. },
  74349. /**
  74350. * Convert pixel value to p2 physics scale (meters).
  74351. * By default Phaser uses a scale of 20px per meter.
  74352. * If you need to modify this you can over-ride these functions via the Physics Configuration object.
  74353. *
  74354. * @method Phaser.Physics.P2#pxm
  74355. * @param {number} v - The value to convert.
  74356. * @return {number} The scaled value.
  74357. */
  74358. pxm: function (v) {
  74359. return v * 0.05;
  74360. },
  74361. /**
  74362. * Convert p2 physics value (meters) to pixel scale and inverses it.
  74363. * By default Phaser uses a scale of 20px per meter.
  74364. * If you need to modify this you can over-ride these functions via the Physics Configuration object.
  74365. *
  74366. * @method Phaser.Physics.P2#mpxi
  74367. * @param {number} v - The value to convert.
  74368. * @return {number} The scaled value.
  74369. */
  74370. mpxi: function (v) {
  74371. return v *= -20;
  74372. },
  74373. /**
  74374. * Convert pixel value to p2 physics scale (meters) and inverses it.
  74375. * By default Phaser uses a scale of 20px per meter.
  74376. * If you need to modify this you can over-ride these functions via the Physics Configuration object.
  74377. *
  74378. * @method Phaser.Physics.P2#pxmi
  74379. * @param {number} v - The value to convert.
  74380. * @return {number} The scaled value.
  74381. */
  74382. pxmi: function (v) {
  74383. return v * -0.05;
  74384. }
  74385. };
  74386. /**
  74387. * @name Phaser.Physics.P2#friction
  74388. * @property {number} friction - Friction between colliding bodies. This value is used if no matching ContactMaterial is found for a Material pair.
  74389. */
  74390. Object.defineProperty(Phaser.Physics.P2.prototype, "friction", {
  74391. get: function () {
  74392. return this.world.defaultContactMaterial.friction;
  74393. },
  74394. set: function (value) {
  74395. this.world.defaultContactMaterial.friction = value;
  74396. }
  74397. });
  74398. /**
  74399. * @name Phaser.Physics.P2#restitution
  74400. * @property {number} restitution - Default coefficient of restitution between colliding bodies. This value is used if no matching ContactMaterial is found for a Material pair.
  74401. */
  74402. Object.defineProperty(Phaser.Physics.P2.prototype, "restitution", {
  74403. get: function () {
  74404. return this.world.defaultContactMaterial.restitution;
  74405. },
  74406. set: function (value) {
  74407. this.world.defaultContactMaterial.restitution = value;
  74408. }
  74409. });
  74410. /**
  74411. * @name Phaser.Physics.P2#contactMaterial
  74412. * @property {p2.ContactMaterial} contactMaterial - The default Contact Material being used by the World.
  74413. */
  74414. Object.defineProperty(Phaser.Physics.P2.prototype, "contactMaterial", {
  74415. get: function () {
  74416. return this.world.defaultContactMaterial;
  74417. },
  74418. set: function (value) {
  74419. this.world.defaultContactMaterial = value;
  74420. }
  74421. });
  74422. /**
  74423. * @name Phaser.Physics.P2#applySpringForces
  74424. * @property {boolean} applySpringForces - Enable to automatically apply spring forces each step.
  74425. */
  74426. Object.defineProperty(Phaser.Physics.P2.prototype, "applySpringForces", {
  74427. get: function () {
  74428. return this.world.applySpringForces;
  74429. },
  74430. set: function (value) {
  74431. this.world.applySpringForces = value;
  74432. }
  74433. });
  74434. /**
  74435. * @name Phaser.Physics.P2#applyDamping
  74436. * @property {boolean} applyDamping - Enable to automatically apply body damping each step.
  74437. */
  74438. Object.defineProperty(Phaser.Physics.P2.prototype, "applyDamping", {
  74439. get: function () {
  74440. return this.world.applyDamping;
  74441. },
  74442. set: function (value) {
  74443. this.world.applyDamping = value;
  74444. }
  74445. });
  74446. /**
  74447. * @name Phaser.Physics.P2#applyGravity
  74448. * @property {boolean} applyGravity - Enable to automatically apply gravity each step.
  74449. */
  74450. Object.defineProperty(Phaser.Physics.P2.prototype, "applyGravity", {
  74451. get: function () {
  74452. return this.world.applyGravity;
  74453. },
  74454. set: function (value) {
  74455. this.world.applyGravity = value;
  74456. }
  74457. });
  74458. /**
  74459. * @name Phaser.Physics.P2#solveConstraints
  74460. * @property {boolean} solveConstraints - Enable/disable constraint solving in each step.
  74461. */
  74462. Object.defineProperty(Phaser.Physics.P2.prototype, "solveConstraints", {
  74463. get: function () {
  74464. return this.world.solveConstraints;
  74465. },
  74466. set: function (value) {
  74467. this.world.solveConstraints = value;
  74468. }
  74469. });
  74470. /**
  74471. * @name Phaser.Physics.P2#time
  74472. * @property {boolean} time - The World time.
  74473. * @readonly
  74474. */
  74475. Object.defineProperty(Phaser.Physics.P2.prototype, "time", {
  74476. get: function () {
  74477. return this.world.time;
  74478. }
  74479. });
  74480. /**
  74481. * @name Phaser.Physics.P2#emitImpactEvent
  74482. * @property {boolean} emitImpactEvent - Set to true if you want to the world to emit the "impact" event. Turning this off could improve performance.
  74483. */
  74484. Object.defineProperty(Phaser.Physics.P2.prototype, "emitImpactEvent", {
  74485. get: function () {
  74486. return this.world.emitImpactEvent;
  74487. },
  74488. set: function (value) {
  74489. this.world.emitImpactEvent = value;
  74490. }
  74491. });
  74492. /**
  74493. * How to deactivate bodies during simulation. Possible modes are: World.NO_SLEEPING, World.BODY_SLEEPING and World.ISLAND_SLEEPING.
  74494. * If sleeping is enabled, you might need to wake up the bodies if they fall asleep when they shouldn't. If you want to enable sleeping in the world, but want to disable it for a particular body, see Body.allowSleep.
  74495. * @name Phaser.Physics.P2#sleepMode
  74496. * @property {number} sleepMode
  74497. */
  74498. Object.defineProperty(Phaser.Physics.P2.prototype, "sleepMode", {
  74499. get: function () {
  74500. return this.world.sleepMode;
  74501. },
  74502. set: function (value) {
  74503. this.world.sleepMode = value;
  74504. }
  74505. });
  74506. /**
  74507. * @name Phaser.Physics.P2#total
  74508. * @property {number} total - The total number of bodies in the world.
  74509. * @readonly
  74510. */
  74511. Object.defineProperty(Phaser.Physics.P2.prototype, "total", {
  74512. get: function () {
  74513. return this.world.bodies.length;
  74514. }
  74515. });
  74516. /* jshint noarg: false */
  74517. /**
  74518. * @author Georgios Kaleadis https://github.com/georgiee
  74519. * @author Richard Davey <rich@photonstorm.com>
  74520. * @copyright 2016 Photon Storm Ltd.
  74521. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  74522. */
  74523. /**
  74524. * Allow to access a list of created fixture (coming from Body#addPhaserPolygon)
  74525. * which itself parse the input from PhysicsEditor with the custom phaser exporter.
  74526. * You can access fixtures of a Body by a group index or even by providing a fixture Key.
  74527. * You can set the fixture key and also the group index for a fixture in PhysicsEditor.
  74528. * This gives you the power to create a complex body built of many fixtures and modify them
  74529. * during runtime (to remove parts, set masks, categories & sensor properties)
  74530. *
  74531. * @class Phaser.Physics.P2.FixtureList
  74532. * @constructor
  74533. * @param {Array} list - A list of fixtures (from Phaser.Physics.P2.Body#addPhaserPolygon)
  74534. */
  74535. Phaser.Physics.P2.FixtureList = function (list) {
  74536. if (!Array.isArray(list))
  74537. {
  74538. list = [list];
  74539. }
  74540. this.rawList = list;
  74541. this.init();
  74542. this.parse(this.rawList);
  74543. };
  74544. Phaser.Physics.P2.FixtureList.prototype = {
  74545. /**
  74546. * @method Phaser.Physics.P2.FixtureList#init
  74547. */
  74548. init: function () {
  74549. /**
  74550. * @property {object} namedFixtures - Collect all fixtures with a key
  74551. * @private
  74552. */
  74553. this.namedFixtures = {};
  74554. /**
  74555. * @property {Array} groupedFixtures - Collect all given fixtures per group index. Notice: Every fixture with a key also belongs to a group
  74556. * @private
  74557. */
  74558. this.groupedFixtures = [];
  74559. /**
  74560. * @property {Array} allFixtures - This is a list of everything in this collection
  74561. * @private
  74562. */
  74563. this.allFixtures = [];
  74564. },
  74565. /**
  74566. * @method Phaser.Physics.P2.FixtureList#setCategory
  74567. * @param {number} bit - The bit to set as the collision group.
  74568. * @param {string} fixtureKey - Only apply to the fixture with the given key.
  74569. */
  74570. setCategory: function (bit, fixtureKey) {
  74571. var setter = function(fixture) {
  74572. fixture.collisionGroup = bit;
  74573. };
  74574. this.getFixtures(fixtureKey).forEach(setter);
  74575. },
  74576. /**
  74577. * @method Phaser.Physics.P2.FixtureList#setMask
  74578. * @param {number} bit - The bit to set as the collision mask
  74579. * @param {string} fixtureKey - Only apply to the fixture with the given key
  74580. */
  74581. setMask: function (bit, fixtureKey) {
  74582. var setter = function(fixture) {
  74583. fixture.collisionMask = bit;
  74584. };
  74585. this.getFixtures(fixtureKey).forEach(setter);
  74586. },
  74587. /**
  74588. * @method Phaser.Physics.P2.FixtureList#setSensor
  74589. * @param {boolean} value - sensor true or false
  74590. * @param {string} fixtureKey - Only apply to the fixture with the given key
  74591. */
  74592. setSensor: function (value, fixtureKey) {
  74593. var setter = function(fixture) {
  74594. fixture.sensor = value;
  74595. };
  74596. this.getFixtures(fixtureKey).forEach(setter);
  74597. },
  74598. /**
  74599. * @method Phaser.Physics.P2.FixtureList#setMaterial
  74600. * @param {Object} material - The contact material for a fixture
  74601. * @param {string} fixtureKey - Only apply to the fixture with the given key
  74602. */
  74603. setMaterial: function (material, fixtureKey) {
  74604. var setter = function(fixture) {
  74605. fixture.material = material;
  74606. };
  74607. this.getFixtures(fixtureKey).forEach(setter);
  74608. },
  74609. /**
  74610. * Accessor to get either a list of specified fixtures by key or the whole fixture list
  74611. *
  74612. * @method Phaser.Physics.P2.FixtureList#getFixtures
  74613. * @param {array} keys - A list of fixture keys
  74614. */
  74615. getFixtures: function (keys) {
  74616. var fixtures = [];
  74617. if (keys)
  74618. {
  74619. if (!(keys instanceof Array))
  74620. {
  74621. keys = [keys];
  74622. }
  74623. var self = this;
  74624. keys.forEach(function(key) {
  74625. if (self.namedFixtures[key])
  74626. {
  74627. fixtures.push(self.namedFixtures[key]);
  74628. }
  74629. });
  74630. return this.flatten(fixtures);
  74631. }
  74632. else
  74633. {
  74634. return this.allFixtures;
  74635. }
  74636. },
  74637. /**
  74638. * Accessor to get either a single fixture by its key.
  74639. *
  74640. * @method Phaser.Physics.P2.FixtureList#getFixtureByKey
  74641. * @param {string} key - The key of the fixture.
  74642. */
  74643. getFixtureByKey: function (key) {
  74644. return this.namedFixtures[key];
  74645. },
  74646. /**
  74647. * Accessor to get a group of fixtures by its group index.
  74648. *
  74649. * @method Phaser.Physics.P2.FixtureList#getGroup
  74650. * @param {number} groupID - The group index.
  74651. */
  74652. getGroup: function (groupID) {
  74653. return this.groupedFixtures[groupID];
  74654. },
  74655. /**
  74656. * Parser for the output of Phaser.Physics.P2.Body#addPhaserPolygon
  74657. *
  74658. * @method Phaser.Physics.P2.FixtureList#parse
  74659. */
  74660. parse: function () {
  74661. var key, value, _ref, _results;
  74662. _ref = this.rawList;
  74663. _results = [];
  74664. for (key in _ref)
  74665. {
  74666. value = _ref[key];
  74667. if (!isNaN(key - 0))
  74668. {
  74669. this.groupedFixtures[key] = this.groupedFixtures[key] || [];
  74670. this.groupedFixtures[key] = this.groupedFixtures[key].concat(value);
  74671. }
  74672. else
  74673. {
  74674. this.namedFixtures[key] = this.flatten(value);
  74675. }
  74676. _results.push(this.allFixtures = this.flatten(this.groupedFixtures));
  74677. }
  74678. },
  74679. /**
  74680. * A helper to flatten arrays. This is very useful as the fixtures are nested from time to time due to the way P2 creates and splits polygons.
  74681. *
  74682. * @method Phaser.Physics.P2.FixtureList#flatten
  74683. * @param {array} array - The array to flatten. Notice: This will happen recursive not shallow.
  74684. */
  74685. flatten: function (array) {
  74686. var result, self;
  74687. result = [];
  74688. self = arguments.callee;
  74689. array.forEach(function(item) {
  74690. return Array.prototype.push.apply(result, (Array.isArray(item) ? self(item) : [item]));
  74691. });
  74692. return result;
  74693. }
  74694. };
  74695. /**
  74696. * @author Richard Davey <rich@photonstorm.com>
  74697. * @copyright 2016 Photon Storm Ltd.
  74698. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  74699. */
  74700. /**
  74701. * A PointProxy is an internal class that allows for direct getter/setter style property access to Arrays and TypedArrays.
  74702. *
  74703. * @class Phaser.Physics.P2.PointProxy
  74704. * @constructor
  74705. * @param {Phaser.Physics.P2} world - A reference to the P2 World.
  74706. * @param {any} destination - The object to bind to.
  74707. */
  74708. Phaser.Physics.P2.PointProxy = function (world, destination) {
  74709. this.world = world;
  74710. this.destination = destination;
  74711. };
  74712. Phaser.Physics.P2.PointProxy.prototype.constructor = Phaser.Physics.P2.PointProxy;
  74713. /**
  74714. * @name Phaser.Physics.P2.PointProxy#x
  74715. * @property {number} x - The x property of this PointProxy get and set in pixels.
  74716. */
  74717. Object.defineProperty(Phaser.Physics.P2.PointProxy.prototype, "x", {
  74718. get: function () {
  74719. return this.world.mpx(this.destination[0]);
  74720. },
  74721. set: function (value) {
  74722. this.destination[0] = this.world.pxm(value);
  74723. }
  74724. });
  74725. /**
  74726. * @name Phaser.Physics.P2.PointProxy#y
  74727. * @property {number} y - The y property of this PointProxy get and set in pixels.
  74728. */
  74729. Object.defineProperty(Phaser.Physics.P2.PointProxy.prototype, "y", {
  74730. get: function () {
  74731. return this.world.mpx(this.destination[1]);
  74732. },
  74733. set: function (value) {
  74734. this.destination[1] = this.world.pxm(value);
  74735. }
  74736. });
  74737. /**
  74738. * @name Phaser.Physics.P2.PointProxy#mx
  74739. * @property {number} mx - The x property of this PointProxy get and set in meters.
  74740. */
  74741. Object.defineProperty(Phaser.Physics.P2.PointProxy.prototype, "mx", {
  74742. get: function () {
  74743. return this.destination[0];
  74744. },
  74745. set: function (value) {
  74746. this.destination[0] = value;
  74747. }
  74748. });
  74749. /**
  74750. * @name Phaser.Physics.P2.PointProxy#my
  74751. * @property {number} my - The x property of this PointProxy get and set in meters.
  74752. */
  74753. Object.defineProperty(Phaser.Physics.P2.PointProxy.prototype, "my", {
  74754. get: function () {
  74755. return this.destination[1];
  74756. },
  74757. set: function (value) {
  74758. this.destination[1] = value;
  74759. }
  74760. });
  74761. /**
  74762. * @author Richard Davey <rich@photonstorm.com>
  74763. * @copyright 2016 Photon Storm Ltd.
  74764. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  74765. */
  74766. /**
  74767. * A InversePointProxy is an internal class that allows for direct getter/setter style property access to Arrays and TypedArrays but inverses the values on set.
  74768. *
  74769. * @class Phaser.Physics.P2.InversePointProxy
  74770. * @constructor
  74771. * @param {Phaser.Physics.P2} world - A reference to the P2 World.
  74772. * @param {any} destination - The object to bind to.
  74773. */
  74774. Phaser.Physics.P2.InversePointProxy = function (world, destination) {
  74775. this.world = world;
  74776. this.destination = destination;
  74777. };
  74778. Phaser.Physics.P2.InversePointProxy.prototype.constructor = Phaser.Physics.P2.InversePointProxy;
  74779. /**
  74780. * @name Phaser.Physics.P2.InversePointProxy#x
  74781. * @property {number} x - The x property of this InversePointProxy get and set in pixels.
  74782. */
  74783. Object.defineProperty(Phaser.Physics.P2.InversePointProxy.prototype, "x", {
  74784. get: function () {
  74785. return this.world.mpxi(this.destination[0]);
  74786. },
  74787. set: function (value) {
  74788. this.destination[0] = this.world.pxmi(value);
  74789. }
  74790. });
  74791. /**
  74792. * @name Phaser.Physics.P2.InversePointProxy#y
  74793. * @property {number} y - The y property of this InversePointProxy get and set in pixels.
  74794. */
  74795. Object.defineProperty(Phaser.Physics.P2.InversePointProxy.prototype, "y", {
  74796. get: function () {
  74797. return this.world.mpxi(this.destination[1]);
  74798. },
  74799. set: function (value) {
  74800. this.destination[1] = this.world.pxmi(value);
  74801. }
  74802. });
  74803. /**
  74804. * @name Phaser.Physics.P2.InversePointProxy#mx
  74805. * @property {number} mx - The x property of this InversePointProxy get and set in meters.
  74806. */
  74807. Object.defineProperty(Phaser.Physics.P2.InversePointProxy.prototype, "mx", {
  74808. get: function () {
  74809. return this.destination[0];
  74810. },
  74811. set: function (value) {
  74812. this.destination[0] = -value;
  74813. }
  74814. });
  74815. /**
  74816. * @name Phaser.Physics.P2.InversePointProxy#my
  74817. * @property {number} my - The y property of this InversePointProxy get and set in meters.
  74818. */
  74819. Object.defineProperty(Phaser.Physics.P2.InversePointProxy.prototype, "my", {
  74820. get: function () {
  74821. return this.destination[1];
  74822. },
  74823. set: function (value) {
  74824. this.destination[1] = -value;
  74825. }
  74826. });
  74827. /**
  74828. * @author Richard Davey <rich@photonstorm.com>
  74829. * @copyright 2016 Photon Storm Ltd.
  74830. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  74831. */
  74832. /**
  74833. * The Physics Body is typically linked to a single Sprite and defines properties that determine how the physics body is simulated.
  74834. * These properties affect how the body reacts to forces, what forces it generates on itself (to simulate friction), and how it reacts to collisions in the scene.
  74835. * In most cases, the properties are used to simulate physical effects. Each body also has its own property values that determine exactly how it reacts to forces and collisions in the scene.
  74836. * By default a single Rectangle shape is added to the Body that matches the dimensions of the parent Sprite. See addShape, removeShape, clearShapes to add extra shapes around the Body.
  74837. * Note: When bound to a Sprite to avoid single-pixel jitters on mobile devices we strongly recommend using Sprite sizes that are even on both axis, i.e. 128x128 not 127x127.
  74838. * Note: When a game object is given a P2 body it has its anchor x/y set to 0.5, so it becomes centered.
  74839. *
  74840. * @class Phaser.Physics.P2.Body
  74841. * @constructor
  74842. * @param {Phaser.Game} game - Game reference to the currently running game.
  74843. * @param {Phaser.Sprite} [sprite] - The Sprite object this physics body belongs to.
  74844. * @param {number} [x=0] - The x coordinate of this Body.
  74845. * @param {number} [y=0] - The y coordinate of this Body.
  74846. * @param {number} [mass=1] - The default mass of this Body (0 = static).
  74847. */
  74848. Phaser.Physics.P2.Body = function (game, sprite, x, y, mass) {
  74849. sprite = sprite || null;
  74850. x = x || 0;
  74851. y = y || 0;
  74852. if (mass === undefined) { mass = 1; }
  74853. /**
  74854. * @property {Phaser.Game} game - Local reference to game.
  74855. */
  74856. this.game = game;
  74857. /**
  74858. * @property {Phaser.Physics.P2} world - Local reference to the P2 World.
  74859. */
  74860. this.world = game.physics.p2;
  74861. /**
  74862. * @property {Phaser.Sprite} sprite - Reference to the parent Sprite.
  74863. */
  74864. this.sprite = sprite;
  74865. /**
  74866. * @property {number} type - The type of physics system this body belongs to.
  74867. */
  74868. this.type = Phaser.Physics.P2JS;
  74869. /**
  74870. * @property {Phaser.Point} offset - The offset of the Physics Body from the Sprite x/y position.
  74871. */
  74872. this.offset = new Phaser.Point();
  74873. /**
  74874. * @property {p2.Body} data - The p2 Body data.
  74875. * @protected
  74876. */
  74877. this.data = new p2.Body({ position: [ this.world.pxmi(x), this.world.pxmi(y) ], mass: mass });
  74878. this.data.parent = this;
  74879. /**
  74880. * @property {Phaser.Physics.P2.InversePointProxy} velocity - The velocity of the body. Set velocity.x to a negative value to move to the left, position to the right. velocity.y negative values move up, positive move down.
  74881. */
  74882. this.velocity = new Phaser.Physics.P2.InversePointProxy(this.world, this.data.velocity);
  74883. /**
  74884. * @property {Phaser.Physics.P2.InversePointProxy} force - The force applied to the body.
  74885. */
  74886. this.force = new Phaser.Physics.P2.InversePointProxy(this.world, this.data.force);
  74887. /**
  74888. * @property {Phaser.Point} gravity - A locally applied gravity force to the Body. Applied directly before the world step. NOTE: Not currently implemented.
  74889. */
  74890. this.gravity = new Phaser.Point();
  74891. /**
  74892. * Dispatched when a first contact is created between shapes in two bodies.
  74893. * This event is fired during the step, so collision has already taken place.
  74894. *
  74895. * The event will be sent 5 arguments in this order:
  74896. *
  74897. * The Phaser.Physics.P2.Body it is in contact with. *This might be null* if the Body was created directly in the p2 world.
  74898. * The p2.Body this Body is in contact with.
  74899. * The Shape from this body that caused the contact.
  74900. * The Shape from the contact body.
  74901. * The Contact Equation data array.
  74902. *
  74903. * @property {Phaser.Signal} onBeginContact
  74904. */
  74905. this.onBeginContact = new Phaser.Signal();
  74906. /**
  74907. * Dispatched when contact ends between shapes in two bodies.
  74908. * This event is fired during the step, so collision has already taken place.
  74909. *
  74910. * The event will be sent 4 arguments in this order:
  74911. *
  74912. * The Phaser.Physics.P2.Body it is in contact with. *This might be null* if the Body was created directly in the p2 world.
  74913. * The p2.Body this Body has ended contact with.
  74914. * The Shape from this body that caused the original contact.
  74915. * The Shape from the contact body.
  74916. *
  74917. * @property {Phaser.Signal} onEndContact
  74918. */
  74919. this.onEndContact = new Phaser.Signal();
  74920. /**
  74921. * @property {array} collidesWith - Array of CollisionGroups that this Bodies shapes collide with.
  74922. */
  74923. this.collidesWith = [];
  74924. /**
  74925. * @property {boolean} removeNextStep - To avoid deleting this body during a physics step, and causing all kinds of problems, set removeNextStep to true to have it removed in the next preUpdate.
  74926. */
  74927. this.removeNextStep = false;
  74928. /**
  74929. * @property {Phaser.Physics.P2.BodyDebug} debugBody - Reference to the debug body.
  74930. */
  74931. this.debugBody = null;
  74932. /**
  74933. * @property {boolean} dirty - Internally used by Sprite.x/y
  74934. */
  74935. this.dirty = false;
  74936. /**
  74937. * @property {boolean} _collideWorldBounds - Internal var that determines if this Body collides with the world bounds or not.
  74938. * @private
  74939. */
  74940. this._collideWorldBounds = true;
  74941. /**
  74942. * @property {object} _bodyCallbacks - Array of Body callbacks.
  74943. * @private
  74944. */
  74945. this._bodyCallbacks = {};
  74946. /**
  74947. * @property {object} _bodyCallbackContext - Array of Body callback contexts.
  74948. * @private
  74949. */
  74950. this._bodyCallbackContext = {};
  74951. /**
  74952. * @property {object} _groupCallbacks - Array of Group callbacks.
  74953. * @private
  74954. */
  74955. this._groupCallbacks = {};
  74956. /**
  74957. * @property {object} _bodyCallbackContext - Array of Grouo callback contexts.
  74958. * @private
  74959. */
  74960. this._groupCallbackContext = {};
  74961. /**
  74962. * @property {boolean} _reset - Internal var.
  74963. * @private
  74964. */
  74965. this._reset = false;
  74966. // Set-up the default shape
  74967. if (sprite)
  74968. {
  74969. this.setRectangleFromSprite(sprite);
  74970. if (sprite.exists)
  74971. {
  74972. this.game.physics.p2.addBody(this);
  74973. }
  74974. }
  74975. };
  74976. Phaser.Physics.P2.Body.prototype = {
  74977. /**
  74978. * Sets a callback to be fired any time a shape in this Body impacts with a shape in the given Body. The impact test is performed against body.id values.
  74979. * The callback will be sent 4 parameters: This body, the body that impacted, the Shape in this body and the shape in the impacting body.
  74980. * Note that the impact event happens after collision resolution, so it cannot be used to prevent a collision from happening.
  74981. * It also happens mid-step. So do not destroy a Body during this callback, instead set safeDestroy to true so it will be killed on the next preUpdate.
  74982. *
  74983. * @method Phaser.Physics.P2.Body#createBodyCallback
  74984. * @param {Phaser.Sprite|Phaser.TileSprite|Phaser.Physics.P2.Body|p2.Body} object - The object to send impact events for.
  74985. * @param {function} callback - The callback to fire on impact. Set to null to clear a previously set callback.
  74986. * @param {object} callbackContext - The context under which the callback will fire.
  74987. */
  74988. createBodyCallback: function (object, callback, callbackContext) {
  74989. var id = -1;
  74990. if (object['id'])
  74991. {
  74992. id = object.id;
  74993. }
  74994. else if (object['body'])
  74995. {
  74996. id = object.body.id;
  74997. }
  74998. if (id > -1)
  74999. {
  75000. if (callback === null)
  75001. {
  75002. delete (this._bodyCallbacks[id]);
  75003. delete (this._bodyCallbackContext[id]);
  75004. }
  75005. else
  75006. {
  75007. this._bodyCallbacks[id] = callback;
  75008. this._bodyCallbackContext[id] = callbackContext;
  75009. }
  75010. }
  75011. },
  75012. /**
  75013. * Sets a callback to be fired any time this Body impacts with the given Group. The impact test is performed against shape.collisionGroup values.
  75014. * The callback will be sent 4 parameters: This body, the body that impacted, the Shape in this body and the shape in the impacting body.
  75015. * This callback will only fire if this Body has been assigned a collision group.
  75016. * Note that the impact event happens after collision resolution, so it cannot be used to prevent a collision from happening.
  75017. * It also happens mid-step. So do not destroy a Body during this callback, instead set safeDestroy to true so it will be killed on the next preUpdate.
  75018. *
  75019. * @method Phaser.Physics.P2.Body#createGroupCallback
  75020. * @param {Phaser.Physics.CollisionGroup} group - The Group to send impact events for.
  75021. * @param {function} callback - The callback to fire on impact. Set to null to clear a previously set callback.
  75022. * @param {object} callbackContext - The context under which the callback will fire.
  75023. */
  75024. createGroupCallback: function (group, callback, callbackContext) {
  75025. if (callback === null)
  75026. {
  75027. delete (this._groupCallbacks[group.mask]);
  75028. delete (this._groupCallbackContext[group.mask]);
  75029. }
  75030. else
  75031. {
  75032. this._groupCallbacks[group.mask] = callback;
  75033. this._groupCallbackContext[group.mask] = callbackContext;
  75034. }
  75035. },
  75036. /**
  75037. * Gets the collision bitmask from the groups this body collides with.
  75038. *
  75039. * @method Phaser.Physics.P2.Body#getCollisionMask
  75040. * @return {number} The bitmask.
  75041. */
  75042. getCollisionMask: function () {
  75043. var mask = 0;
  75044. if (this._collideWorldBounds)
  75045. {
  75046. mask = this.game.physics.p2.boundsCollisionGroup.mask;
  75047. }
  75048. for (var i = 0; i < this.collidesWith.length; i++)
  75049. {
  75050. mask = mask | this.collidesWith[i].mask;
  75051. }
  75052. return mask;
  75053. },
  75054. /**
  75055. * Updates the collisionMask.
  75056. *
  75057. * @method Phaser.Physics.P2.Body#updateCollisionMask
  75058. * @param {p2.Shape} [shape] - An optional Shape. If not provided the collision group will be added to all Shapes in this Body.
  75059. */
  75060. updateCollisionMask: function (shape) {
  75061. var mask = this.getCollisionMask();
  75062. if (shape === undefined)
  75063. {
  75064. for (var i = this.data.shapes.length - 1; i >= 0; i--)
  75065. {
  75066. this.data.shapes[i].collisionMask = mask;
  75067. }
  75068. }
  75069. else
  75070. {
  75071. shape.collisionMask = mask;
  75072. }
  75073. },
  75074. /**
  75075. * Sets the given CollisionGroup to be the collision group for all shapes in this Body, unless a shape is specified.
  75076. * This also resets the collisionMask.
  75077. *
  75078. * @method Phaser.Physics.P2.Body#setCollisionGroup
  75079. * @param {Phaser.Physics.CollisionGroup} group - The Collision Group that this Bodies shapes will use.
  75080. * @param {p2.Shape} [shape] - An optional Shape. If not provided the collision group will be added to all Shapes in this Body.
  75081. */
  75082. setCollisionGroup: function (group, shape) {
  75083. var mask = this.getCollisionMask();
  75084. if (shape === undefined)
  75085. {
  75086. for (var i = this.data.shapes.length - 1; i >= 0; i--)
  75087. {
  75088. this.data.shapes[i].collisionGroup = group.mask;
  75089. this.data.shapes[i].collisionMask = mask;
  75090. }
  75091. }
  75092. else
  75093. {
  75094. shape.collisionGroup = group.mask;
  75095. shape.collisionMask = mask;
  75096. }
  75097. },
  75098. /**
  75099. * Clears the collision data from the shapes in this Body. Optionally clears Group and/or Mask.
  75100. *
  75101. * @method Phaser.Physics.P2.Body#clearCollision
  75102. * @param {boolean} [clearGroup=true] - Clear the collisionGroup value from the shape/s?
  75103. * @param {boolean} [clearMask=true] - Clear the collisionMask value from the shape/s?
  75104. * @param {p2.Shape} [shape] - An optional Shape. If not provided the collision data will be cleared from all Shapes in this Body.
  75105. */
  75106. clearCollision: function (clearGroup, clearMask, shape) {
  75107. if (clearGroup === undefined) { clearGroup = true; }
  75108. if (clearMask === undefined) { clearMask = true; }
  75109. if (shape === undefined)
  75110. {
  75111. for (var i = this.data.shapes.length - 1; i >= 0; i--)
  75112. {
  75113. if (clearGroup)
  75114. {
  75115. this.data.shapes[i].collisionGroup = null;
  75116. }
  75117. if (clearMask)
  75118. {
  75119. this.data.shapes[i].collisionMask = null;
  75120. }
  75121. }
  75122. }
  75123. else
  75124. {
  75125. if (clearGroup)
  75126. {
  75127. shape.collisionGroup = null;
  75128. }
  75129. if (clearMask)
  75130. {
  75131. shape.collisionMask = null;
  75132. }
  75133. }
  75134. if (clearGroup)
  75135. {
  75136. this.collidesWith.length = 0;
  75137. }
  75138. },
  75139. /**
  75140. * Removes the given CollisionGroup, or array of CollisionGroups, from the list of groups that this body will collide with and updates the collision masks.
  75141. *
  75142. * @method Phaser.Physics.P2.Body#removeCollisionGroup
  75143. * @param {Phaser.Physics.CollisionGroup|array} group - The Collision Group or Array of Collision Groups that this Bodies shapes should not collide with anymore.
  75144. * @param {boolean} [clearCallback=true] - Clear the callback that will be triggered when this Body impacts with the given Group?
  75145. * @param {p2.Shape} [shape] - An optional Shape. If not provided the updated collision mask will be added to all Shapes in this Body.
  75146. */
  75147. removeCollisionGroup: function (group, clearCallback, shape) {
  75148. if (clearCallback === undefined) { clearCallback = true; }
  75149. var index;
  75150. if (Array.isArray(group))
  75151. {
  75152. for (var i = 0; i < group.length; i++)
  75153. {
  75154. index = this.collidesWith.indexOf(group[i]);
  75155. if (index > -1)
  75156. {
  75157. this.collidesWith.splice(index, 1);
  75158. if (clearCallback)
  75159. {
  75160. delete (this._groupCallbacks[group.mask]);
  75161. delete (this._groupCallbackContext[group.mask]);
  75162. }
  75163. }
  75164. }
  75165. }
  75166. else
  75167. {
  75168. index = this.collidesWith.indexOf(group);
  75169. if (index > -1)
  75170. {
  75171. this.collidesWith.splice(index, 1);
  75172. if (clearCallback)
  75173. {
  75174. delete (this._groupCallbacks[group.mask]);
  75175. delete (this._groupCallbackContext[group.mask]);
  75176. }
  75177. }
  75178. }
  75179. var mask = this.getCollisionMask();
  75180. if (shape === undefined)
  75181. {
  75182. for (var i = this.data.shapes.length - 1; i >= 0; i--)
  75183. {
  75184. this.data.shapes[i].collisionMask = mask;
  75185. }
  75186. }
  75187. else
  75188. {
  75189. shape.collisionMask = mask;
  75190. }
  75191. },
  75192. /**
  75193. * Adds the given CollisionGroup, or array of CollisionGroups, to the list of groups that this body will collide with and updates the collision masks.
  75194. *
  75195. * @method Phaser.Physics.P2.Body#collides
  75196. * @param {Phaser.Physics.CollisionGroup|array} group - The Collision Group or Array of Collision Groups that this Bodies shapes will collide with.
  75197. * @param {function} [callback] - Optional callback that will be triggered when this Body impacts with the given Group.
  75198. * @param {object} [callbackContext] - The context under which the callback will be called.
  75199. * @param {p2.Shape} [shape] - An optional Shape. If not provided the collision mask will be added to all Shapes in this Body.
  75200. */
  75201. collides: function (group, callback, callbackContext, shape) {
  75202. if (Array.isArray(group))
  75203. {
  75204. for (var i = 0; i < group.length; i++)
  75205. {
  75206. if (this.collidesWith.indexOf(group[i]) === -1)
  75207. {
  75208. this.collidesWith.push(group[i]);
  75209. if (callback)
  75210. {
  75211. this.createGroupCallback(group[i], callback, callbackContext);
  75212. }
  75213. }
  75214. }
  75215. }
  75216. else
  75217. {
  75218. if (this.collidesWith.indexOf(group) === -1)
  75219. {
  75220. this.collidesWith.push(group);
  75221. if (callback)
  75222. {
  75223. this.createGroupCallback(group, callback, callbackContext);
  75224. }
  75225. }
  75226. }
  75227. var mask = this.getCollisionMask();
  75228. if (shape === undefined)
  75229. {
  75230. for (var i = this.data.shapes.length - 1; i >= 0; i--)
  75231. {
  75232. this.data.shapes[i].collisionMask = mask;
  75233. }
  75234. }
  75235. else
  75236. {
  75237. shape.collisionMask = mask;
  75238. }
  75239. },
  75240. /**
  75241. * Moves the shape offsets so their center of mass becomes the body center of mass.
  75242. *
  75243. * @method Phaser.Physics.P2.Body#adjustCenterOfMass
  75244. */
  75245. adjustCenterOfMass: function () {
  75246. this.data.adjustCenterOfMass();
  75247. this.shapeChanged();
  75248. },
  75249. /**
  75250. * Gets the velocity of a point in the body.
  75251. *
  75252. * @method Phaser.Physics.P2.Body#getVelocityAtPoint
  75253. * @param {Array} result - A vector to store the result in.
  75254. * @param {Array} relativePoint - A world oriented vector, indicating the position of the point to get the velocity from.
  75255. * @return {Array} The result vector.
  75256. */
  75257. getVelocityAtPoint: function (result, relativePoint) {
  75258. return this.data.getVelocityAtPoint(result, relativePoint);
  75259. },
  75260. /**
  75261. * Apply damping, see http://code.google.com/p/bullet/issues/detail?id=74 for details.
  75262. *
  75263. * @method Phaser.Physics.P2.Body#applyDamping
  75264. * @param {number} dt - Current time step.
  75265. */
  75266. applyDamping: function (dt) {
  75267. this.data.applyDamping(dt);
  75268. },
  75269. /**
  75270. * Apply impulse to a point relative to the body.
  75271. * This could for example be a point on the Body surface. An impulse is a force added to a body during a short
  75272. * period of time (impulse = force * time). Impulses will be added to Body.velocity and Body.angularVelocity.
  75273. *
  75274. * @method Phaser.Physics.P2.Body#applyImpulse
  75275. * @param {Float32Array|Array} impulse - The impulse vector to add, oriented in world space.
  75276. * @param {number} worldX - A point relative to the body in world space. If not given, it is set to zero and all of the impulse will be exerted on the center of mass.
  75277. * @param {number} worldY - A point relative to the body in world space. If not given, it is set to zero and all of the impulse will be exerted on the center of mass.
  75278. */
  75279. applyImpulse: function (impulse, worldX, worldY) {
  75280. this.data.applyImpulse(impulse, [this.world.pxmi(worldX), this.world.pxmi(worldY)]);
  75281. },
  75282. /**
  75283. * Apply impulse to a point local to the body.
  75284. *
  75285. * This could for example be a point on the Body surface. An impulse is a force added to a body during a short
  75286. * period of time (impulse = force * time). Impulses will be added to Body.velocity and Body.angularVelocity.
  75287. *
  75288. * @method Phaser.Physics.P2.Body#applyImpulseLocal
  75289. * @param {Float32Array|Array} impulse - The impulse vector to add, oriented in local space.
  75290. * @param {number} localX - A local point on the body.
  75291. * @param {number} localY - A local point on the body.
  75292. */
  75293. applyImpulseLocal: function (impulse, localX, localY) {
  75294. this.data.applyImpulseLocal(impulse, [this.world.pxmi(localX), this.world.pxmi(localY)]);
  75295. },
  75296. /**
  75297. * Apply force to a world point.
  75298. *
  75299. * This could for example be a point on the RigidBody surface. Applying force
  75300. * this way will add to Body.force and Body.angularForce.
  75301. *
  75302. * @method Phaser.Physics.P2.Body#applyForce
  75303. * @param {Float32Array|Array} force - The force vector to add.
  75304. * @param {number} worldX - The world x point to apply the force on.
  75305. * @param {number} worldY - The world y point to apply the force on.
  75306. */
  75307. applyForce: function (force, worldX, worldY) {
  75308. this.data.applyForce(force, [this.world.pxmi(worldX), this.world.pxmi(worldY)]);
  75309. },
  75310. /**
  75311. * Sets the force on the body to zero.
  75312. *
  75313. * @method Phaser.Physics.P2.Body#setZeroForce
  75314. */
  75315. setZeroForce: function () {
  75316. this.data.setZeroForce();
  75317. },
  75318. /**
  75319. * If this Body is dynamic then this will zero its angular velocity.
  75320. *
  75321. * @method Phaser.Physics.P2.Body#setZeroRotation
  75322. */
  75323. setZeroRotation: function () {
  75324. this.data.angularVelocity = 0;
  75325. },
  75326. /**
  75327. * If this Body is dynamic then this will zero its velocity on both axis.
  75328. *
  75329. * @method Phaser.Physics.P2.Body#setZeroVelocity
  75330. */
  75331. setZeroVelocity: function () {
  75332. this.data.velocity[0] = 0;
  75333. this.data.velocity[1] = 0;
  75334. },
  75335. /**
  75336. * Sets the Body damping and angularDamping to zero.
  75337. *
  75338. * @method Phaser.Physics.P2.Body#setZeroDamping
  75339. */
  75340. setZeroDamping: function () {
  75341. this.data.damping = 0;
  75342. this.data.angularDamping = 0;
  75343. },
  75344. /**
  75345. * Transform a world point to local body frame.
  75346. *
  75347. * @method Phaser.Physics.P2.Body#toLocalFrame
  75348. * @param {Float32Array|Array} out - The vector to store the result in.
  75349. * @param {Float32Array|Array} worldPoint - The input world vector.
  75350. */
  75351. toLocalFrame: function (out, worldPoint) {
  75352. return this.data.toLocalFrame(out, worldPoint);
  75353. },
  75354. /**
  75355. * Transform a local point to world frame.
  75356. *
  75357. * @method Phaser.Physics.P2.Body#toWorldFrame
  75358. * @param {Array} out - The vector to store the result in.
  75359. * @param {Array} localPoint - The input local vector.
  75360. */
  75361. toWorldFrame: function (out, localPoint) {
  75362. return this.data.toWorldFrame(out, localPoint);
  75363. },
  75364. /**
  75365. * This will rotate the Body by the given speed to the left (counter-clockwise).
  75366. *
  75367. * @method Phaser.Physics.P2.Body#rotateLeft
  75368. * @param {number} speed - The speed at which it should rotate.
  75369. */
  75370. rotateLeft: function (speed) {
  75371. this.data.angularVelocity = this.world.pxm(-speed);
  75372. },
  75373. /**
  75374. * This will rotate the Body by the given speed to the left (clockwise).
  75375. *
  75376. * @method Phaser.Physics.P2.Body#rotateRight
  75377. * @param {number} speed - The speed at which it should rotate.
  75378. */
  75379. rotateRight: function (speed) {
  75380. this.data.angularVelocity = this.world.pxm(speed);
  75381. },
  75382. /**
  75383. * Moves the Body forwards based on its current angle and the given speed.
  75384. * The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms).
  75385. *
  75386. * @method Phaser.Physics.P2.Body#moveForward
  75387. * @param {number} speed - The speed at which it should move forwards.
  75388. */
  75389. moveForward: function (speed) {
  75390. var magnitude = this.world.pxmi(-speed);
  75391. var angle = this.data.angle + Math.PI / 2;
  75392. this.data.velocity[0] = magnitude * Math.cos(angle);
  75393. this.data.velocity[1] = magnitude * Math.sin(angle);
  75394. },
  75395. /**
  75396. * Moves the Body backwards based on its current angle and the given speed.
  75397. * The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms).
  75398. *
  75399. * @method Phaser.Physics.P2.Body#moveBackward
  75400. * @param {number} speed - The speed at which it should move backwards.
  75401. */
  75402. moveBackward: function (speed) {
  75403. var magnitude = this.world.pxmi(-speed);
  75404. var angle = this.data.angle + Math.PI / 2;
  75405. this.data.velocity[0] = -(magnitude * Math.cos(angle));
  75406. this.data.velocity[1] = -(magnitude * Math.sin(angle));
  75407. },
  75408. /**
  75409. * Applies a force to the Body that causes it to 'thrust' forwards, based on its current angle and the given speed.
  75410. * The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms).
  75411. *
  75412. * @method Phaser.Physics.P2.Body#thrust
  75413. * @param {number} speed - The speed at which it should thrust.
  75414. */
  75415. thrust: function (speed) {
  75416. var magnitude = this.world.pxmi(-speed);
  75417. var angle = this.data.angle + Math.PI / 2;
  75418. this.data.force[0] += magnitude * Math.cos(angle);
  75419. this.data.force[1] += magnitude * Math.sin(angle);
  75420. },
  75421. /**
  75422. * Applies a force to the Body that causes it to 'thrust' to the left, based on its current angle and the given speed.
  75423. * The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms).
  75424. *
  75425. * @method Phaser.Physics.P2.Body#thrustLeft
  75426. * @param {number} speed - The speed at which it should move to the left.
  75427. */
  75428. thrustLeft: function (speed) {
  75429. var magnitude = this.world.pxmi(-speed);
  75430. var angle = this.data.angle;
  75431. this.data.force[0] += magnitude * Math.cos(angle);
  75432. this.data.force[1] += magnitude * Math.sin(angle);
  75433. },
  75434. /**
  75435. * Applies a force to the Body that causes it to 'thrust' to the right, based on its current angle and the given speed.
  75436. * The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms).
  75437. *
  75438. * @method Phaser.Physics.P2.Body#thrustRight
  75439. * @param {number} speed - The speed at which it should move to the right.
  75440. */
  75441. thrustRight: function (speed) {
  75442. var magnitude = this.world.pxmi(-speed);
  75443. var angle = this.data.angle;
  75444. this.data.force[0] -= magnitude * Math.cos(angle);
  75445. this.data.force[1] -= magnitude * Math.sin(angle);
  75446. },
  75447. /**
  75448. * Applies a force to the Body that causes it to 'thrust' backwards (in reverse), based on its current angle and the given speed.
  75449. * The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms).
  75450. *
  75451. * @method Phaser.Physics.P2.Body#reverse
  75452. * @param {number} speed - The speed at which it should reverse.
  75453. */
  75454. reverse: function (speed) {
  75455. var magnitude = this.world.pxmi(-speed);
  75456. var angle = this.data.angle + Math.PI / 2;
  75457. this.data.force[0] -= magnitude * Math.cos(angle);
  75458. this.data.force[1] -= magnitude * Math.sin(angle);
  75459. },
  75460. /**
  75461. * If this Body is dynamic then this will move it to the left by setting its x velocity to the given speed.
  75462. * The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms).
  75463. *
  75464. * @method Phaser.Physics.P2.Body#moveLeft
  75465. * @param {number} speed - The speed at which it should move to the left, in pixels per second.
  75466. */
  75467. moveLeft: function (speed) {
  75468. this.data.velocity[0] = this.world.pxmi(-speed);
  75469. },
  75470. /**
  75471. * If this Body is dynamic then this will move it to the right by setting its x velocity to the given speed.
  75472. * The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms).
  75473. *
  75474. * @method Phaser.Physics.P2.Body#moveRight
  75475. * @param {number} speed - The speed at which it should move to the right, in pixels per second.
  75476. */
  75477. moveRight: function (speed) {
  75478. this.data.velocity[0] = this.world.pxmi(speed);
  75479. },
  75480. /**
  75481. * If this Body is dynamic then this will move it up by setting its y velocity to the given speed.
  75482. * The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms).
  75483. *
  75484. * @method Phaser.Physics.P2.Body#moveUp
  75485. * @param {number} speed - The speed at which it should move up, in pixels per second.
  75486. */
  75487. moveUp: function (speed) {
  75488. this.data.velocity[1] = this.world.pxmi(-speed);
  75489. },
  75490. /**
  75491. * If this Body is dynamic then this will move it down by setting its y velocity to the given speed.
  75492. * The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms).
  75493. *
  75494. * @method Phaser.Physics.P2.Body#moveDown
  75495. * @param {number} speed - The speed at which it should move down, in pixels per second.
  75496. */
  75497. moveDown: function (speed) {
  75498. this.data.velocity[1] = this.world.pxmi(speed);
  75499. },
  75500. /**
  75501. * Internal method. This is called directly before the sprites are sent to the renderer and after the update function has finished.
  75502. *
  75503. * @method Phaser.Physics.P2.Body#preUpdate
  75504. * @protected
  75505. */
  75506. preUpdate: function () {
  75507. this.dirty = true;
  75508. if (this.removeNextStep)
  75509. {
  75510. this.removeFromWorld();
  75511. this.removeNextStep = false;
  75512. }
  75513. },
  75514. /**
  75515. * Internal method. This is called directly before the sprites are sent to the renderer and after the update function has finished.
  75516. *
  75517. * @method Phaser.Physics.P2.Body#postUpdate
  75518. * @protected
  75519. */
  75520. postUpdate: function () {
  75521. this.sprite.x = this.world.mpxi(this.data.position[0]) + this.offset.x;
  75522. this.sprite.y = this.world.mpxi(this.data.position[1]) + this.offset.y;
  75523. if (!this.fixedRotation)
  75524. {
  75525. this.sprite.rotation = this.data.angle;
  75526. }
  75527. if (this.debugBody)
  75528. {
  75529. this.debugBody.updateSpriteTransform();
  75530. }
  75531. this.dirty = false;
  75532. },
  75533. /**
  75534. * Resets the Body force, velocity (linear and angular) and rotation. Optionally resets damping and mass.
  75535. *
  75536. * @method Phaser.Physics.P2.Body#reset
  75537. * @param {number} x - The new x position of the Body.
  75538. * @param {number} y - The new x position of the Body.
  75539. * @param {boolean} [resetDamping=false] - Resets the linear and angular damping.
  75540. * @param {boolean} [resetMass=false] - Sets the Body mass back to 1.
  75541. */
  75542. reset: function (x, y, resetDamping, resetMass) {
  75543. if (resetDamping === undefined) { resetDamping = false; }
  75544. if (resetMass === undefined) { resetMass = false; }
  75545. this.setZeroForce();
  75546. this.setZeroVelocity();
  75547. this.setZeroRotation();
  75548. if (resetDamping)
  75549. {
  75550. this.setZeroDamping();
  75551. }
  75552. if (resetMass)
  75553. {
  75554. this.mass = 1;
  75555. }
  75556. this.x = x;
  75557. this.y = y;
  75558. },
  75559. /**
  75560. * Adds this physics body to the world.
  75561. *
  75562. * @method Phaser.Physics.P2.Body#addToWorld
  75563. */
  75564. addToWorld: function () {
  75565. if (this.game.physics.p2._toRemove)
  75566. {
  75567. for (var i = 0; i < this.game.physics.p2._toRemove.length; i++)
  75568. {
  75569. if (this.game.physics.p2._toRemove[i] === this)
  75570. {
  75571. this.game.physics.p2._toRemove.splice(i, 1);
  75572. }
  75573. }
  75574. }
  75575. if (this.data.world !== this.game.physics.p2.world)
  75576. {
  75577. this.game.physics.p2.addBody(this);
  75578. }
  75579. },
  75580. /**
  75581. * Removes this physics body from the world.
  75582. *
  75583. * @method Phaser.Physics.P2.Body#removeFromWorld
  75584. */
  75585. removeFromWorld: function () {
  75586. if (this.data.world === this.game.physics.p2.world)
  75587. {
  75588. this.game.physics.p2.removeBodyNextStep(this);
  75589. }
  75590. },
  75591. /**
  75592. * Destroys this Body and all references it holds to other objects.
  75593. *
  75594. * @method Phaser.Physics.P2.Body#destroy
  75595. */
  75596. destroy: function () {
  75597. this.removeFromWorld();
  75598. this.clearShapes();
  75599. this._bodyCallbacks = {};
  75600. this._bodyCallbackContext = {};
  75601. this._groupCallbacks = {};
  75602. this._groupCallbackContext = {};
  75603. if (this.debugBody)
  75604. {
  75605. this.debugBody.destroy(true, true);
  75606. }
  75607. this.debugBody = null;
  75608. if (this.sprite)
  75609. {
  75610. this.sprite.body = null;
  75611. this.sprite = null;
  75612. }
  75613. },
  75614. /**
  75615. * Removes all Shapes from this Body.
  75616. *
  75617. * @method Phaser.Physics.P2.Body#clearShapes
  75618. */
  75619. clearShapes: function () {
  75620. var i = this.data.shapes.length;
  75621. while (i--)
  75622. {
  75623. this.data.removeShape(this.data.shapes[i]);
  75624. }
  75625. this.shapeChanged();
  75626. },
  75627. /**
  75628. * Add a shape to the body. You can pass a local transform when adding a shape, so that the shape gets an offset and an angle relative to the body center of mass.
  75629. * Will automatically update the mass properties and bounding radius.
  75630. * If this Body had a previously set Collision Group you will need to re-apply it to the new Shape this creates.
  75631. *
  75632. * @method Phaser.Physics.P2.Body#addShape
  75633. * @param {p2.Shape} shape - The shape to add to the body.
  75634. * @param {number} [offsetX=0] - Local horizontal offset of the shape relative to the body center of mass.
  75635. * @param {number} [offsetY=0] - Local vertical offset of the shape relative to the body center of mass.
  75636. * @param {number} [rotation=0] - Local rotation of the shape relative to the body center of mass, specified in radians.
  75637. * @return {p2.Shape} The shape that was added to the body.
  75638. */
  75639. addShape: function (shape, offsetX, offsetY, rotation) {
  75640. if (offsetX === undefined) { offsetX = 0; }
  75641. if (offsetY === undefined) { offsetY = 0; }
  75642. if (rotation === undefined) { rotation = 0; }
  75643. this.data.addShape(shape, [this.world.pxmi(offsetX), this.world.pxmi(offsetY)], rotation);
  75644. this.shapeChanged();
  75645. return shape;
  75646. },
  75647. /**
  75648. * Adds a Circle shape to this Body. You can control the offset from the center of the body and the rotation.
  75649. *
  75650. * @method Phaser.Physics.P2.Body#addCircle
  75651. * @param {number} radius - The radius of this circle (in pixels)
  75652. * @param {number} [offsetX=0] - Local horizontal offset of the shape relative to the body center of mass.
  75653. * @param {number} [offsetY=0] - Local vertical offset of the shape relative to the body center of mass.
  75654. * @param {number} [rotation=0] - Local rotation of the shape relative to the body center of mass, specified in radians.
  75655. * @return {p2.Circle} The Circle shape that was added to the Body.
  75656. */
  75657. addCircle: function (radius, offsetX, offsetY, rotation) {
  75658. var shape = new p2.Circle({ radius: this.world.pxm(radius) });
  75659. return this.addShape(shape, offsetX, offsetY, rotation);
  75660. },
  75661. /**
  75662. * Adds a Rectangle shape to this Body. You can control the offset from the center of the body and the rotation.
  75663. *
  75664. * @method Phaser.Physics.P2.Body#addRectangle
  75665. * @param {number} width - The width of the rectangle in pixels.
  75666. * @param {number} height - The height of the rectangle in pixels.
  75667. * @param {number} [offsetX=0] - Local horizontal offset of the shape relative to the body center of mass.
  75668. * @param {number} [offsetY=0] - Local vertical offset of the shape relative to the body center of mass.
  75669. * @param {number} [rotation=0] - Local rotation of the shape relative to the body center of mass, specified in radians.
  75670. * @return {p2.Box} The shape that was added to the Body.
  75671. */
  75672. addRectangle: function (width, height, offsetX, offsetY, rotation) {
  75673. var shape = new p2.Box({ width: this.world.pxm(width), height: this.world.pxm(height)});
  75674. return this.addShape(shape, offsetX, offsetY, rotation);
  75675. },
  75676. /**
  75677. * Adds a Plane shape to this Body. The plane is facing in the Y direction. You can control the offset from the center of the body and the rotation.
  75678. *
  75679. * @method Phaser.Physics.P2.Body#addPlane
  75680. * @param {number} [offsetX=0] - Local horizontal offset of the shape relative to the body center of mass.
  75681. * @param {number} [offsetY=0] - Local vertical offset of the shape relative to the body center of mass.
  75682. * @param {number} [rotation=0] - Local rotation of the shape relative to the body center of mass, specified in radians.
  75683. * @return {p2.Plane} The Plane shape that was added to the Body.
  75684. */
  75685. addPlane: function (offsetX, offsetY, rotation) {
  75686. var shape = new p2.Plane();
  75687. return this.addShape(shape, offsetX, offsetY, rotation);
  75688. },
  75689. /**
  75690. * Adds a Particle shape to this Body. You can control the offset from the center of the body and the rotation.
  75691. *
  75692. * @method Phaser.Physics.P2.Body#addParticle
  75693. * @param {number} [offsetX=0] - Local horizontal offset of the shape relative to the body center of mass.
  75694. * @param {number} [offsetY=0] - Local vertical offset of the shape relative to the body center of mass.
  75695. * @param {number} [rotation=0] - Local rotation of the shape relative to the body center of mass, specified in radians.
  75696. * @return {p2.Particle} The Particle shape that was added to the Body.
  75697. */
  75698. addParticle: function (offsetX, offsetY, rotation) {
  75699. var shape = new p2.Particle();
  75700. return this.addShape(shape, offsetX, offsetY, rotation);
  75701. },
  75702. /**
  75703. * Adds a Line shape to this Body.
  75704. * The line shape is along the x direction, and stretches from [-length/2, 0] to [length/2,0].
  75705. * You can control the offset from the center of the body and the rotation.
  75706. *
  75707. * @method Phaser.Physics.P2.Body#addLine
  75708. * @param {number} length - The length of this line (in pixels)
  75709. * @param {number} [offsetX=0] - Local horizontal offset of the shape relative to the body center of mass.
  75710. * @param {number} [offsetY=0] - Local vertical offset of the shape relative to the body center of mass.
  75711. * @param {number} [rotation=0] - Local rotation of the shape relative to the body center of mass, specified in radians.
  75712. * @return {p2.Line} The Line shape that was added to the Body.
  75713. */
  75714. addLine: function (length, offsetX, offsetY, rotation) {
  75715. var shape = new p2.Line({ length: this.world.pxm(length)});
  75716. return this.addShape(shape, offsetX, offsetY, rotation);
  75717. },
  75718. /**
  75719. * Adds a Capsule shape to this Body.
  75720. * You can control the offset from the center of the body and the rotation.
  75721. *
  75722. * @method Phaser.Physics.P2.Body#addCapsule
  75723. * @param {number} length - The distance between the end points in pixels.
  75724. * @param {number} radius - Radius of the capsule in pixels.
  75725. * @param {number} [offsetX=0] - Local horizontal offset of the shape relative to the body center of mass.
  75726. * @param {number} [offsetY=0] - Local vertical offset of the shape relative to the body center of mass.
  75727. * @param {number} [rotation=0] - Local rotation of the shape relative to the body center of mass, specified in radians.
  75728. * @return {p2.Capsule} The Capsule shape that was added to the Body.
  75729. */
  75730. addCapsule: function (length, radius, offsetX, offsetY, rotation) {
  75731. var shape = new p2.Capsule({ length: this.world.pxm(length), radius: this.world.pxm(radius) });
  75732. return this.addShape(shape, offsetX, offsetY, rotation);
  75733. },
  75734. /**
  75735. * Reads a polygon shape path, and assembles convex shapes from that and puts them at proper offset points. The shape must be simple and without holes.
  75736. * This function expects the x.y values to be given in pixels. If you want to provide them at p2 world scales then call Body.data.fromPolygon directly.
  75737. *
  75738. * @method Phaser.Physics.P2.Body#addPolygon
  75739. * @param {object} options - An object containing the build options:
  75740. * @param {boolean} [options.optimalDecomp=false] - Set to true if you need optimal decomposition. Warning: very slow for polygons with more than 10 vertices.
  75741. * @param {boolean} [options.skipSimpleCheck=false] - Set to true if you already know that the path is not intersecting itself.
  75742. * @param {boolean|number} [options.removeCollinearPoints=false] - Set to a number (angle threshold value) to remove collinear points, or false to keep all points.
  75743. * @param {(number[]|...number)} points - An array of 2d vectors that form the convex or concave polygon.
  75744. * Either [[0,0], [0,1],...] or a flat array of numbers that will be interpreted as [x,y, x,y, ...],
  75745. * or the arguments passed can be flat x,y values e.g. `setPolygon(options, x,y, x,y, x,y, ...)` where `x` and `y` are numbers.
  75746. * @return {boolean} True on success, else false.
  75747. */
  75748. addPolygon: function (options, points) {
  75749. options = options || {};
  75750. if (!Array.isArray(points))
  75751. {
  75752. points = Array.prototype.slice.call(arguments, 1);
  75753. }
  75754. var path = [];
  75755. // Did they pass in a single array of points?
  75756. if (points.length === 1 && Array.isArray(points[0]))
  75757. {
  75758. path = points[0].slice(0);
  75759. }
  75760. else if (Array.isArray(points[0]))
  75761. {
  75762. path = points.slice();
  75763. }
  75764. else if (typeof points[0] === 'number')
  75765. {
  75766. // We've a list of numbers
  75767. for (var i = 0, len = points.length; i < len; i += 2)
  75768. {
  75769. path.push([points[i], points[i + 1]]);
  75770. }
  75771. }
  75772. // top and tail
  75773. var idx = path.length - 1;
  75774. if (path[idx][0] === path[0][0] && path[idx][1] === path[0][1])
  75775. {
  75776. path.pop();
  75777. }
  75778. // Now process them into p2 values
  75779. for (var p = 0; p < path.length; p++)
  75780. {
  75781. path[p][0] = this.world.pxmi(path[p][0]);
  75782. path[p][1] = this.world.pxmi(path[p][1]);
  75783. }
  75784. var result = this.data.fromPolygon(path, options);
  75785. this.shapeChanged();
  75786. return result;
  75787. },
  75788. /**
  75789. * Remove a shape from the body. Will automatically update the mass properties and bounding radius.
  75790. *
  75791. * @method Phaser.Physics.P2.Body#removeShape
  75792. * @param {p2.Circle|p2.Rectangle|p2.Plane|p2.Line|p2.Particle} shape - The shape to remove from the body.
  75793. * @return {boolean} True if the shape was found and removed, else false.
  75794. */
  75795. removeShape: function (shape) {
  75796. var result = this.data.removeShape(shape);
  75797. this.shapeChanged();
  75798. return result;
  75799. },
  75800. /**
  75801. * Clears any previously set shapes. Then creates a new Circle shape and adds it to this Body.
  75802. * If this Body had a previously set Collision Group you will need to re-apply it to the new Shape this creates.
  75803. *
  75804. * @method Phaser.Physics.P2.Body#setCircle
  75805. * @param {number} radius - The radius of this circle (in pixels)
  75806. * @param {number} [offsetX=0] - Local horizontal offset of the shape relative to the body center of mass.
  75807. * @param {number} [offsetY=0] - Local vertical offset of the shape relative to the body center of mass.
  75808. * @param {number} [rotation=0] - Local rotation of the shape relative to the body center of mass, specified in radians.
  75809. */
  75810. setCircle: function (radius, offsetX, offsetY, rotation) {
  75811. this.clearShapes();
  75812. return this.addCircle(radius, offsetX, offsetY, rotation);
  75813. },
  75814. /**
  75815. * Clears any previously set shapes. The creates a new Rectangle shape at the given size and offset, and adds it to this Body.
  75816. * If you wish to create a Rectangle to match the size of a Sprite or Image see Body.setRectangleFromSprite.
  75817. * If this Body had a previously set Collision Group you will need to re-apply it to the new Shape this creates.
  75818. *
  75819. * @method Phaser.Physics.P2.Body#setRectangle
  75820. * @param {number} [width=16] - The width of the rectangle in pixels.
  75821. * @param {number} [height=16] - The height of the rectangle in pixels.
  75822. * @param {number} [offsetX=0] - Local horizontal offset of the shape relative to the body center of mass.
  75823. * @param {number} [offsetY=0] - Local vertical offset of the shape relative to the body center of mass.
  75824. * @param {number} [rotation=0] - Local rotation of the shape relative to the body center of mass, specified in radians.
  75825. * @return {p2.Rectangle} The Rectangle shape that was added to the Body.
  75826. */
  75827. setRectangle: function (width, height, offsetX, offsetY, rotation) {
  75828. if (width === undefined) { width = 16; }
  75829. if (height === undefined) { height = 16; }
  75830. this.clearShapes();
  75831. return this.addRectangle(width, height, offsetX, offsetY, rotation);
  75832. },
  75833. /**
  75834. * Clears any previously set shapes.
  75835. * Then creates a Rectangle shape sized to match the dimensions and orientation of the Sprite given.
  75836. * If no Sprite is given it defaults to using the parent of this Body.
  75837. * If this Body had a previously set Collision Group you will need to re-apply it to the new Shape this creates.
  75838. *
  75839. * @method Phaser.Physics.P2.Body#setRectangleFromSprite
  75840. * @param {Phaser.Sprite|Phaser.Image} [sprite] - The Sprite on which the Rectangle will get its dimensions.
  75841. * @return {p2.Rectangle} The Rectangle shape that was added to the Body.
  75842. */
  75843. setRectangleFromSprite: function (sprite) {
  75844. if (sprite === undefined) { sprite = this.sprite; }
  75845. this.clearShapes();
  75846. return this.addRectangle(sprite.width, sprite.height, 0, 0, sprite.rotation);
  75847. },
  75848. /**
  75849. * Adds the given Material to all Shapes that belong to this Body.
  75850. * If you only wish to apply it to a specific Shape in this Body then provide that as the 2nd parameter.
  75851. *
  75852. * @method Phaser.Physics.P2.Body#setMaterial
  75853. * @param {Phaser.Physics.P2.Material} material - The Material that will be applied.
  75854. * @param {p2.Shape} [shape] - An optional Shape. If not provided the Material will be added to all Shapes in this Body.
  75855. */
  75856. setMaterial: function (material, shape) {
  75857. if (shape === undefined)
  75858. {
  75859. for (var i = this.data.shapes.length - 1; i >= 0; i--)
  75860. {
  75861. this.data.shapes[i].material = material;
  75862. }
  75863. }
  75864. else
  75865. {
  75866. shape.material = material;
  75867. }
  75868. },
  75869. /**
  75870. * Updates the debug draw if any body shapes change.
  75871. *
  75872. * @method Phaser.Physics.P2.Body#shapeChanged
  75873. */
  75874. shapeChanged: function() {
  75875. if (this.debugBody)
  75876. {
  75877. this.debugBody.draw();
  75878. }
  75879. },
  75880. /**
  75881. * Reads the shape data from a physics data file stored in the Game.Cache and adds it as a polygon to this Body.
  75882. * The shape data format is based on the output of the
  75883. * {@link https://github.com/photonstorm/phaser/tree/master/resources/PhysicsEditor%20Exporter|custom phaser exporter} for
  75884. * {@link https://www.codeandweb.com/physicseditor|PhysicsEditor}
  75885. *
  75886. * @method Phaser.Physics.P2.Body#addPhaserPolygon
  75887. * @param {string} key - The key of the Physics Data file as stored in Game.Cache.
  75888. * @param {string} object - The key of the object within the Physics data file that you wish to load the shape data from.
  75889. * @returns {Array} A list of created fixtures to be used with Phaser.Physics.P2.FixtureList
  75890. */
  75891. addPhaserPolygon: function (key, object) {
  75892. var data = this.game.cache.getPhysicsData(key, object);
  75893. var createdFixtures = [];
  75894. // Cycle through the fixtures
  75895. for (var i = 0; i < data.length; i++)
  75896. {
  75897. var fixtureData = data[i];
  75898. var shapesOfFixture = this.addFixture(fixtureData);
  75899. // Always add to a group
  75900. createdFixtures[fixtureData.filter.group] = createdFixtures[fixtureData.filter.group] || [];
  75901. createdFixtures[fixtureData.filter.group] = createdFixtures[fixtureData.filter.group].concat(shapesOfFixture);
  75902. // if (unique) fixture key is provided
  75903. if (fixtureData.fixtureKey)
  75904. {
  75905. createdFixtures[fixtureData.fixtureKey] = shapesOfFixture;
  75906. }
  75907. }
  75908. this.data.aabbNeedsUpdate = true;
  75909. this.shapeChanged();
  75910. return createdFixtures;
  75911. },
  75912. /**
  75913. * Add a polygon fixture. This is used during #loadPolygon.
  75914. *
  75915. * @method Phaser.Physics.P2.Body#addFixture
  75916. * @param {string} fixtureData - The data for the fixture. It contains: isSensor, filter (collision) and the actual polygon shapes.
  75917. * @return {array} An array containing the generated shapes for the given polygon.
  75918. */
  75919. addFixture: function (fixtureData) {
  75920. var generatedShapes = [];
  75921. if (fixtureData.circle)
  75922. {
  75923. var shape = new p2.Circle({ radius: this.world.pxm(fixtureData.circle.radius) });
  75924. shape.collisionGroup = fixtureData.filter.categoryBits;
  75925. shape.collisionMask = fixtureData.filter.maskBits;
  75926. shape.sensor = fixtureData.isSensor;
  75927. var offset = p2.vec2.create();
  75928. offset[0] = this.world.pxmi(fixtureData.circle.position[0] - this.sprite.width/2);
  75929. offset[1] = this.world.pxmi(fixtureData.circle.position[1] - this.sprite.height/2);
  75930. this.data.addShape(shape, offset);
  75931. generatedShapes.push(shape);
  75932. }
  75933. else
  75934. {
  75935. var polygons = fixtureData.polygons;
  75936. var cm = p2.vec2.create();
  75937. for (var i = 0; i < polygons.length; i++)
  75938. {
  75939. var shapes = polygons[i];
  75940. var vertices = [];
  75941. for (var s = 0; s < shapes.length; s += 2)
  75942. {
  75943. vertices.push([ this.world.pxmi(shapes[s]), this.world.pxmi(shapes[s + 1]) ]);
  75944. }
  75945. var shape = new p2.Convex({ vertices: vertices });
  75946. // Move all vertices so its center of mass is in the local center of the convex
  75947. for (var j = 0; j !== shape.vertices.length; j++)
  75948. {
  75949. var v = shape.vertices[j];
  75950. p2.vec2.sub(v, v, shape.centerOfMass);
  75951. }
  75952. p2.vec2.scale(cm, shape.centerOfMass, 1);
  75953. cm[0] -= this.world.pxmi(this.sprite.width / 2);
  75954. cm[1] -= this.world.pxmi(this.sprite.height / 2);
  75955. shape.updateTriangles();
  75956. shape.updateCenterOfMass();
  75957. shape.updateBoundingRadius();
  75958. shape.collisionGroup = fixtureData.filter.categoryBits;
  75959. shape.collisionMask = fixtureData.filter.maskBits;
  75960. shape.sensor = fixtureData.isSensor;
  75961. this.data.addShape(shape, cm);
  75962. generatedShapes.push(shape);
  75963. }
  75964. }
  75965. return generatedShapes;
  75966. },
  75967. /**
  75968. * Reads the shape data from a physics data file stored in the Game.Cache and adds it as a polygon to this Body.
  75969. *
  75970. * As well as reading the data from the Cache you can also pass `null` as the first argument and a
  75971. * physics data object as the second. When doing this you must ensure the structure of the object is correct in advance.
  75972. *
  75973. * For more details see the format of the Lime / Corona Physics Editor export.
  75974. *
  75975. * @method Phaser.Physics.P2.Body#loadPolygon
  75976. * @param {string} key - The key of the Physics Data file as stored in Game.Cache. Alternatively set to `null` and pass the
  75977. * data as the 2nd argument.
  75978. * @param {string|object} object - The key of the object within the Physics data file that you wish to load the shape data from,
  75979. * or if key is null pass the actual physics data object itself as this parameter.
  75980. * @return {boolean} True on success, else false.
  75981. */
  75982. loadPolygon: function (key, object) {
  75983. if (key === null)
  75984. {
  75985. var data = object;
  75986. }
  75987. else
  75988. {
  75989. var data = this.game.cache.getPhysicsData(key, object);
  75990. }
  75991. // We've multiple Convex shapes, they should be CCW automatically
  75992. var cm = p2.vec2.create();
  75993. for (var i = 0; i < data.length; i++)
  75994. {
  75995. var vertices = [];
  75996. for (var s = 0; s < data[i].shape.length; s += 2)
  75997. {
  75998. vertices.push([ this.world.pxmi(data[i].shape[s]), this.world.pxmi(data[i].shape[s + 1]) ]);
  75999. }
  76000. var c = new p2.Convex({ vertices: vertices });
  76001. // Move all vertices so its center of mass is in the local center of the convex
  76002. for (var j = 0; j !== c.vertices.length; j++)
  76003. {
  76004. var v = c.vertices[j];
  76005. p2.vec2.sub(v, v, c.centerOfMass);
  76006. }
  76007. p2.vec2.scale(cm, c.centerOfMass, 1);
  76008. cm[0] -= this.world.pxmi(this.sprite.width / 2);
  76009. cm[1] -= this.world.pxmi(this.sprite.height / 2);
  76010. c.updateTriangles();
  76011. c.updateCenterOfMass();
  76012. c.updateBoundingRadius();
  76013. this.data.addShape(c, cm);
  76014. }
  76015. this.data.aabbNeedsUpdate = true;
  76016. this.shapeChanged();
  76017. return true;
  76018. }
  76019. };
  76020. Phaser.Physics.P2.Body.prototype.constructor = Phaser.Physics.P2.Body;
  76021. /**
  76022. * Dynamic body. Dynamic bodies body can move and respond to collisions and forces.
  76023. * @property DYNAMIC
  76024. * @type {Number}
  76025. * @static
  76026. */
  76027. Phaser.Physics.P2.Body.DYNAMIC = 1;
  76028. /**
  76029. * Static body. Static bodies do not move, and they do not respond to forces or collision.
  76030. * @property STATIC
  76031. * @type {Number}
  76032. * @static
  76033. */
  76034. Phaser.Physics.P2.Body.STATIC = 2;
  76035. /**
  76036. * Kinematic body. Kinematic bodies only moves according to its .velocity, and does not respond to collisions or force.
  76037. * @property KINEMATIC
  76038. * @type {Number}
  76039. * @static
  76040. */
  76041. Phaser.Physics.P2.Body.KINEMATIC = 4;
  76042. /**
  76043. * @name Phaser.Physics.P2.Body#static
  76044. * @property {boolean} static - Returns true if the Body is static. Setting Body.static to 'false' will make it dynamic.
  76045. */
  76046. Object.defineProperty(Phaser.Physics.P2.Body.prototype, "static", {
  76047. get: function () {
  76048. return (this.data.type === Phaser.Physics.P2.Body.STATIC);
  76049. },
  76050. set: function (value) {
  76051. if (value && this.data.type !== Phaser.Physics.P2.Body.STATIC)
  76052. {
  76053. this.data.type = Phaser.Physics.P2.Body.STATIC;
  76054. this.mass = 0;
  76055. }
  76056. else if (!value && this.data.type === Phaser.Physics.P2.Body.STATIC)
  76057. {
  76058. this.data.type = Phaser.Physics.P2.Body.DYNAMIC;
  76059. this.mass = 1;
  76060. }
  76061. }
  76062. });
  76063. /**
  76064. * @name Phaser.Physics.P2.Body#dynamic
  76065. * @property {boolean} dynamic - Returns true if the Body is dynamic. Setting Body.dynamic to 'false' will make it static.
  76066. */
  76067. Object.defineProperty(Phaser.Physics.P2.Body.prototype, "dynamic", {
  76068. get: function () {
  76069. return (this.data.type === Phaser.Physics.P2.Body.DYNAMIC);
  76070. },
  76071. set: function (value) {
  76072. if (value && this.data.type !== Phaser.Physics.P2.Body.DYNAMIC)
  76073. {
  76074. this.data.type = Phaser.Physics.P2.Body.DYNAMIC;
  76075. this.mass = 1;
  76076. }
  76077. else if (!value && this.data.type === Phaser.Physics.P2.Body.DYNAMIC)
  76078. {
  76079. this.data.type = Phaser.Physics.P2.Body.STATIC;
  76080. this.mass = 0;
  76081. }
  76082. }
  76083. });
  76084. /**
  76085. * @name Phaser.Physics.P2.Body#kinematic
  76086. * @property {boolean} kinematic - Returns true if the Body is kinematic. Setting Body.kinematic to 'false' will make it static.
  76087. */
  76088. Object.defineProperty(Phaser.Physics.P2.Body.prototype, "kinematic", {
  76089. get: function () {
  76090. return (this.data.type === Phaser.Physics.P2.Body.KINEMATIC);
  76091. },
  76092. set: function (value) {
  76093. if (value && this.data.type !== Phaser.Physics.P2.Body.KINEMATIC)
  76094. {
  76095. this.data.type = Phaser.Physics.P2.Body.KINEMATIC;
  76096. this.mass = 4;
  76097. }
  76098. else if (!value && this.data.type === Phaser.Physics.P2.Body.KINEMATIC)
  76099. {
  76100. this.data.type = Phaser.Physics.P2.Body.STATIC;
  76101. this.mass = 0;
  76102. }
  76103. }
  76104. });
  76105. /**
  76106. * @name Phaser.Physics.P2.Body#allowSleep
  76107. * @property {boolean} allowSleep -
  76108. */
  76109. Object.defineProperty(Phaser.Physics.P2.Body.prototype, "allowSleep", {
  76110. get: function () {
  76111. return this.data.allowSleep;
  76112. },
  76113. set: function (value) {
  76114. if (value !== this.data.allowSleep)
  76115. {
  76116. this.data.allowSleep = value;
  76117. }
  76118. }
  76119. });
  76120. /**
  76121. * The angle of the Body in degrees from its original orientation. Values from 0 to 180 represent clockwise rotation; values from 0 to -180 represent counterclockwise rotation.
  76122. * Values outside this range are added to or subtracted from 360 to obtain a value within the range. For example, the statement Body.angle = 450 is the same as Body.angle = 90.
  76123. * If you wish to work in radians instead of degrees use the property Body.rotation instead. Working in radians is faster as it doesn't have to convert values.
  76124. *
  76125. * @name Phaser.Physics.P2.Body#angle
  76126. * @property {number} angle - The angle of this Body in degrees.
  76127. */
  76128. Object.defineProperty(Phaser.Physics.P2.Body.prototype, "angle", {
  76129. get: function() {
  76130. return Phaser.Math.wrapAngle(Phaser.Math.radToDeg(this.data.angle));
  76131. },
  76132. set: function(value) {
  76133. this.data.angle = Phaser.Math.degToRad(Phaser.Math.wrapAngle(value));
  76134. }
  76135. });
  76136. /**
  76137. * Damping is specified as a value between 0 and 1, which is the proportion of velocity lost per second.
  76138. * @name Phaser.Physics.P2.Body#angularDamping
  76139. * @property {number} angularDamping - The angular damping acting acting on the body.
  76140. */
  76141. Object.defineProperty(Phaser.Physics.P2.Body.prototype, "angularDamping", {
  76142. get: function () {
  76143. return this.data.angularDamping;
  76144. },
  76145. set: function (value) {
  76146. this.data.angularDamping = value;
  76147. }
  76148. });
  76149. /**
  76150. * @name Phaser.Physics.P2.Body#angularForce
  76151. * @property {number} angularForce - The angular force acting on the body.
  76152. */
  76153. Object.defineProperty(Phaser.Physics.P2.Body.prototype, "angularForce", {
  76154. get: function () {
  76155. return this.data.angularForce;
  76156. },
  76157. set: function (value) {
  76158. this.data.angularForce = value;
  76159. }
  76160. });
  76161. /**
  76162. * @name Phaser.Physics.P2.Body#angularVelocity
  76163. * @property {number} angularVelocity - The angular velocity of the body.
  76164. */
  76165. Object.defineProperty(Phaser.Physics.P2.Body.prototype, "angularVelocity", {
  76166. get: function () {
  76167. return this.data.angularVelocity;
  76168. },
  76169. set: function (value) {
  76170. this.data.angularVelocity = value;
  76171. }
  76172. });
  76173. /**
  76174. * Damping is specified as a value between 0 and 1, which is the proportion of velocity lost per second.
  76175. * @name Phaser.Physics.P2.Body#damping
  76176. * @property {number} damping - The linear damping acting on the body in the velocity direction.
  76177. */
  76178. Object.defineProperty(Phaser.Physics.P2.Body.prototype, "damping", {
  76179. get: function () {
  76180. return this.data.damping;
  76181. },
  76182. set: function (value) {
  76183. this.data.damping = value;
  76184. }
  76185. });
  76186. /**
  76187. * @name Phaser.Physics.P2.Body#fixedRotation
  76188. * @property {boolean} fixedRotation -
  76189. */
  76190. Object.defineProperty(Phaser.Physics.P2.Body.prototype, "fixedRotation", {
  76191. get: function () {
  76192. return this.data.fixedRotation;
  76193. },
  76194. set: function (value) {
  76195. if (value !== this.data.fixedRotation)
  76196. {
  76197. this.data.fixedRotation = value;
  76198. }
  76199. }
  76200. });
  76201. /**
  76202. * @name Phaser.Physics.P2.Body#inertia
  76203. * @property {number} inertia - The inertia of the body around the Z axis..
  76204. */
  76205. Object.defineProperty(Phaser.Physics.P2.Body.prototype, "inertia", {
  76206. get: function () {
  76207. return this.data.inertia;
  76208. },
  76209. set: function (value) {
  76210. this.data.inertia = value;
  76211. }
  76212. });
  76213. /**
  76214. * @name Phaser.Physics.P2.Body#mass
  76215. * @property {number} mass - The mass of the body.
  76216. */
  76217. Object.defineProperty(Phaser.Physics.P2.Body.prototype, "mass", {
  76218. get: function () {
  76219. return this.data.mass;
  76220. },
  76221. set: function (value) {
  76222. if (value !== this.data.mass)
  76223. {
  76224. this.data.mass = value;
  76225. this.data.updateMassProperties();
  76226. }
  76227. }
  76228. });
  76229. /**
  76230. * @name Phaser.Physics.P2.Body#motionState
  76231. * @property {number} motionState - The type of motion this body has. Should be one of: Body.STATIC (the body does not move), Body.DYNAMIC (body can move and respond to collisions) and Body.KINEMATIC (only moves according to its .velocity).
  76232. */
  76233. Object.defineProperty(Phaser.Physics.P2.Body.prototype, "motionState", {
  76234. get: function () {
  76235. return this.data.type;
  76236. },
  76237. set: function (value) {
  76238. if (value !== this.data.type)
  76239. {
  76240. this.data.type = value;
  76241. }
  76242. }
  76243. });
  76244. /**
  76245. * The angle of the Body in radians.
  76246. * If you wish to work in degrees instead of radians use the Body.angle property instead. Working in radians is faster as it doesn't have to convert values.
  76247. *
  76248. * @name Phaser.Physics.P2.Body#rotation
  76249. * @property {number} rotation - The angle of this Body in radians.
  76250. */
  76251. Object.defineProperty(Phaser.Physics.P2.Body.prototype, "rotation", {
  76252. get: function() {
  76253. return this.data.angle;
  76254. },
  76255. set: function(value) {
  76256. this.data.angle = value;
  76257. }
  76258. });
  76259. /**
  76260. * @name Phaser.Physics.P2.Body#sleepSpeedLimit
  76261. * @property {number} sleepSpeedLimit - .
  76262. */
  76263. Object.defineProperty(Phaser.Physics.P2.Body.prototype, "sleepSpeedLimit", {
  76264. get: function () {
  76265. return this.data.sleepSpeedLimit;
  76266. },
  76267. set: function (value) {
  76268. this.data.sleepSpeedLimit = value;
  76269. }
  76270. });
  76271. /**
  76272. * @name Phaser.Physics.P2.Body#x
  76273. * @property {number} x - The x coordinate of this Body.
  76274. */
  76275. Object.defineProperty(Phaser.Physics.P2.Body.prototype, "x", {
  76276. get: function () {
  76277. return this.world.mpxi(this.data.position[0]);
  76278. },
  76279. set: function (value) {
  76280. this.data.position[0] = this.world.pxmi(value);
  76281. }
  76282. });
  76283. /**
  76284. * @name Phaser.Physics.P2.Body#y
  76285. * @property {number} y - The y coordinate of this Body.
  76286. */
  76287. Object.defineProperty(Phaser.Physics.P2.Body.prototype, "y", {
  76288. get: function () {
  76289. return this.world.mpxi(this.data.position[1]);
  76290. },
  76291. set: function (value) {
  76292. this.data.position[1] = this.world.pxmi(value);
  76293. }
  76294. });
  76295. /**
  76296. * @name Phaser.Physics.P2.Body#id
  76297. * @property {number} id - The Body ID. Each Body that has been added to the World has a unique ID.
  76298. * @readonly
  76299. */
  76300. Object.defineProperty(Phaser.Physics.P2.Body.prototype, "id", {
  76301. get: function () {
  76302. return this.data.id;
  76303. }
  76304. });
  76305. /**
  76306. * @name Phaser.Physics.P2.Body#debug
  76307. * @property {boolean} debug - Enable or disable debug drawing of this body
  76308. */
  76309. Object.defineProperty(Phaser.Physics.P2.Body.prototype, "debug", {
  76310. get: function () {
  76311. return (this.debugBody !== null);
  76312. },
  76313. set: function (value) {
  76314. if (value && !this.debugBody)
  76315. {
  76316. // This will be added to the global space
  76317. this.debugBody = new Phaser.Physics.P2.BodyDebug(this.game, this.data);
  76318. }
  76319. else if (!value && this.debugBody)
  76320. {
  76321. this.debugBody.destroy();
  76322. this.debugBody = null;
  76323. }
  76324. }
  76325. });
  76326. /**
  76327. * A Body can be set to collide against the World bounds automatically if this is set to true. Otherwise it will leave the World.
  76328. * Note that this only applies if your World has bounds! The response to the collision should be managed via CollisionMaterials.
  76329. * Also note that when you set this it will only effect Body shapes that already exist. If you then add further shapes to your Body
  76330. * after setting this it will *not* proactively set them to collide with the bounds.
  76331. *
  76332. * @name Phaser.Physics.P2.Body#collideWorldBounds
  76333. * @property {boolean} collideWorldBounds - Should the Body collide with the World bounds?
  76334. */
  76335. Object.defineProperty(Phaser.Physics.P2.Body.prototype, "collideWorldBounds", {
  76336. get: function () {
  76337. return this._collideWorldBounds;
  76338. },
  76339. set: function (value) {
  76340. if (value && !this._collideWorldBounds)
  76341. {
  76342. this._collideWorldBounds = true;
  76343. this.updateCollisionMask();
  76344. }
  76345. else if (!value && this._collideWorldBounds)
  76346. {
  76347. this._collideWorldBounds = false;
  76348. this.updateCollisionMask();
  76349. }
  76350. }
  76351. });
  76352. /**
  76353. * @author George https://github.com/georgiee
  76354. * @author Richard Davey <rich@photonstorm.com>
  76355. * @copyright 2016 Photon Storm Ltd.
  76356. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  76357. */
  76358. /**
  76359. * Draws a P2 Body to a Graphics instance for visual debugging.
  76360. * Needless to say, for every body you enable debug drawing on, you are adding processor and graphical overhead.
  76361. * So use sparingly and rarely (if ever) in production code.
  76362. *
  76363. * Also be aware that the Debug body is only updated when the Sprite it is connected to changes position. If you
  76364. * manipulate the sprite in any other way (such as moving it to another Group or bringToTop, etc) then you will
  76365. * need to manually adjust its BodyDebug as well.
  76366. *
  76367. * @class Phaser.Physics.P2.BodyDebug
  76368. * @constructor
  76369. * @extends Phaser.Group
  76370. * @param {Phaser.Game} game - Game reference to the currently running game.
  76371. * @param {Phaser.Physics.P2.Body} body - The P2 Body to display debug data for.
  76372. * @param {object} settings - Settings object.
  76373. */
  76374. Phaser.Physics.P2.BodyDebug = function(game, body, settings) {
  76375. Phaser.Group.call(this, game);
  76376. /**
  76377. * @property {object} defaultSettings - Default debug settings.
  76378. * @private
  76379. */
  76380. var defaultSettings = {
  76381. pixelsPerLengthUnit: game.physics.p2.mpx(1),
  76382. debugPolygons: false,
  76383. lineWidth: 1,
  76384. alpha: 0.5
  76385. };
  76386. this.settings = Phaser.Utils.extend(defaultSettings, settings);
  76387. /**
  76388. * @property {number} ppu - Pixels per Length Unit.
  76389. */
  76390. this.ppu = this.settings.pixelsPerLengthUnit;
  76391. this.ppu = -1 * this.ppu;
  76392. /**
  76393. * @property {Phaser.Physics.P2.Body} body - The P2 Body to display debug data for.
  76394. */
  76395. this.body = body;
  76396. /**
  76397. * @property {Phaser.Graphics} canvas - The canvas to render the debug info to.
  76398. */
  76399. this.canvas = new Phaser.Graphics(game);
  76400. this.canvas.alpha = this.settings.alpha;
  76401. this.add(this.canvas);
  76402. this.draw();
  76403. this.updateSpriteTransform();
  76404. };
  76405. Phaser.Physics.P2.BodyDebug.prototype = Object.create(Phaser.Group.prototype);
  76406. Phaser.Physics.P2.BodyDebug.prototype.constructor = Phaser.Physics.P2.BodyDebug;
  76407. Phaser.Utils.extend(Phaser.Physics.P2.BodyDebug.prototype, {
  76408. /**
  76409. * Core update.
  76410. *
  76411. * @method Phaser.Physics.P2.BodyDebug#updateSpriteTransform
  76412. */
  76413. updateSpriteTransform: function() {
  76414. this.position.x = this.body.position[0] * this.ppu;
  76415. this.position.y = this.body.position[1] * this.ppu;
  76416. this.rotation = this.body.angle;
  76417. },
  76418. /**
  76419. * Draws the P2 shapes to the Graphics object.
  76420. *
  76421. * @method Phaser.Physics.P2.BodyDebug#draw
  76422. */
  76423. draw: function() {
  76424. var angle, child, color, i, j, lineColor, lw, obj, offset, sprite, v, verts, vrot, _j, _ref1;
  76425. obj = this.body;
  76426. sprite = this.canvas;
  76427. sprite.clear();
  76428. color = parseInt(this.randomPastelHex(), 16);
  76429. lineColor = 0xff0000;
  76430. lw = this.lineWidth;
  76431. if (obj instanceof p2.Body && obj.shapes.length)
  76432. {
  76433. var l = obj.shapes.length;
  76434. i = 0;
  76435. while (i !== l)
  76436. {
  76437. child = obj.shapes[i];
  76438. offset = child.position || 0;
  76439. angle = child.angle || 0;
  76440. if (child instanceof p2.Circle)
  76441. {
  76442. this.drawCircle(sprite, offset[0] * this.ppu, offset[1] * this.ppu, angle, child.radius * this.ppu, color, lw);
  76443. }
  76444. else if (child instanceof p2.Capsule)
  76445. {
  76446. this.drawCapsule(sprite, offset[0] * this.ppu, offset[1] * this.ppu, angle, child.length * this.ppu, child.radius * this.ppu, lineColor, color, lw);
  76447. }
  76448. else if (child instanceof p2.Plane)
  76449. {
  76450. this.drawPlane(sprite, offset[0] * this.ppu, -offset[1] * this.ppu, color, lineColor, lw * 5, lw * 10, lw * 10, this.ppu * 100, angle);
  76451. }
  76452. else if (child instanceof p2.Line)
  76453. {
  76454. this.drawLine(sprite, child.length * this.ppu, lineColor, lw);
  76455. }
  76456. else if (child instanceof p2.Box)
  76457. {
  76458. this.drawRectangle(sprite, offset[0] * this.ppu, offset[1] * this.ppu, angle, child.width * this.ppu, child.height * this.ppu, lineColor, color, lw);
  76459. }
  76460. else if (child instanceof p2.Convex)
  76461. {
  76462. verts = [];
  76463. vrot = p2.vec2.create();
  76464. for (j = _j = 0, _ref1 = child.vertices.length; 0 <= _ref1 ? _j < _ref1 : _j > _ref1; j = 0 <= _ref1 ? ++_j : --_j)
  76465. {
  76466. v = child.vertices[j];
  76467. p2.vec2.rotate(vrot, v, angle);
  76468. verts.push([(vrot[0] + offset[0]) * this.ppu, -(vrot[1] + offset[1]) * this.ppu]);
  76469. }
  76470. this.drawConvex(sprite, verts, child.triangles, lineColor, color, lw, this.settings.debugPolygons, [offset[0] * this.ppu, -offset[1] * this.ppu]);
  76471. }
  76472. i++;
  76473. }
  76474. }
  76475. },
  76476. /**
  76477. * Draws a p2.Box to the Graphics object.
  76478. *
  76479. * @method Phaser.Physics.P2.BodyDebug#drawRectangle
  76480. * @private
  76481. */
  76482. drawRectangle: function(g, x, y, angle, w, h, color, fillColor, lineWidth) {
  76483. if (lineWidth === undefined) { lineWidth = 1; }
  76484. if (color === undefined) { color = 0x000000; }
  76485. g.lineStyle(lineWidth, color, 1);
  76486. g.beginFill(fillColor);
  76487. g.drawRect(x - w / 2, y - h / 2, w, h);
  76488. },
  76489. /**
  76490. * Draws a p2.Circle to the Graphics object.
  76491. *
  76492. * @method Phaser.Physics.P2.BodyDebug#drawCircle
  76493. * @private
  76494. */
  76495. drawCircle: function(g, x, y, angle, radius, color, lineWidth) {
  76496. if (lineWidth === undefined) { lineWidth = 1; }
  76497. if (color === undefined) { color = 0xffffff; }
  76498. g.lineStyle(lineWidth, 0x000000, 1);
  76499. g.beginFill(color, 1.0);
  76500. g.drawCircle(x, y, -radius*2);
  76501. g.endFill();
  76502. g.moveTo(x, y);
  76503. g.lineTo(x + radius * Math.cos(-angle), y + radius * Math.sin(-angle));
  76504. },
  76505. /**
  76506. * Draws a p2.Line to the Graphics object.
  76507. *
  76508. * @method Phaser.Physics.P2.BodyDebug#drawLine
  76509. * @private
  76510. */
  76511. drawLine: function(g, len, color, lineWidth) {
  76512. if (lineWidth === undefined) { lineWidth = 1; }
  76513. if (color === undefined) { color = 0x000000; }
  76514. g.lineStyle(lineWidth * 5, color, 1);
  76515. g.moveTo(-len / 2, 0);
  76516. g.lineTo(len / 2, 0);
  76517. },
  76518. /**
  76519. * Draws a p2.Convex to the Graphics object.
  76520. *
  76521. * @method Phaser.Physics.P2.BodyDebug#drawConvex
  76522. * @private
  76523. */
  76524. drawConvex: function(g, verts, triangles, color, fillColor, lineWidth, debug, offset) {
  76525. var colors, i, v, v0, v1, x, x0, x1, y, y0, y1;
  76526. if (lineWidth === undefined) { lineWidth = 1; }
  76527. if (color === undefined) { color = 0x000000; }
  76528. if (!debug)
  76529. {
  76530. g.lineStyle(lineWidth, color, 1);
  76531. g.beginFill(fillColor);
  76532. i = 0;
  76533. while (i !== verts.length)
  76534. {
  76535. v = verts[i];
  76536. x = v[0];
  76537. y = v[1];
  76538. if (i === 0)
  76539. {
  76540. g.moveTo(x, -y);
  76541. }
  76542. else
  76543. {
  76544. g.lineTo(x, -y);
  76545. }
  76546. i++;
  76547. }
  76548. g.endFill();
  76549. if (verts.length > 2)
  76550. {
  76551. g.moveTo(verts[verts.length - 1][0], -verts[verts.length - 1][1]);
  76552. return g.lineTo(verts[0][0], -verts[0][1]);
  76553. }
  76554. }
  76555. else
  76556. {
  76557. colors = [0xff0000, 0x00ff00, 0x0000ff];
  76558. i = 0;
  76559. while (i !== verts.length + 1)
  76560. {
  76561. v0 = verts[i % verts.length];
  76562. v1 = verts[(i + 1) % verts.length];
  76563. x0 = v0[0];
  76564. y0 = v0[1];
  76565. x1 = v1[0];
  76566. y1 = v1[1];
  76567. g.lineStyle(lineWidth, colors[i % colors.length], 1);
  76568. g.moveTo(x0, -y0);
  76569. g.lineTo(x1, -y1);
  76570. g.drawCircle(x0, -y0, lineWidth * 2);
  76571. i++;
  76572. }
  76573. g.lineStyle(lineWidth, 0x000000, 1);
  76574. return g.drawCircle(offset[0], offset[1], lineWidth * 2);
  76575. }
  76576. },
  76577. /**
  76578. * Draws a p2.Path to the Graphics object.
  76579. *
  76580. * @method Phaser.Physics.P2.BodyDebug#drawPath
  76581. * @private
  76582. */
  76583. drawPath: function(g, path, color, fillColor, lineWidth) {
  76584. var area, i, lastx, lasty, p1x, p1y, p2x, p2y, p3x, p3y, v, x, y;
  76585. if (lineWidth === undefined) { lineWidth = 1; }
  76586. if (color === undefined) { color = 0x000000; }
  76587. g.lineStyle(lineWidth, color, 1);
  76588. if (typeof fillColor === "number")
  76589. {
  76590. g.beginFill(fillColor);
  76591. }
  76592. lastx = null;
  76593. lasty = null;
  76594. i = 0;
  76595. while (i < path.length)
  76596. {
  76597. v = path[i];
  76598. x = v[0];
  76599. y = v[1];
  76600. if (x !== lastx || y !== lasty)
  76601. {
  76602. if (i === 0)
  76603. {
  76604. g.moveTo(x, y);
  76605. }
  76606. else
  76607. {
  76608. p1x = lastx;
  76609. p1y = lasty;
  76610. p2x = x;
  76611. p2y = y;
  76612. p3x = path[(i + 1) % path.length][0];
  76613. p3y = path[(i + 1) % path.length][1];
  76614. area = ((p2x - p1x) * (p3y - p1y)) - ((p3x - p1x) * (p2y - p1y));
  76615. if (area !== 0)
  76616. {
  76617. g.lineTo(x, y);
  76618. }
  76619. }
  76620. lastx = x;
  76621. lasty = y;
  76622. }
  76623. i++;
  76624. }
  76625. if (typeof fillColor === "number")
  76626. {
  76627. g.endFill();
  76628. }
  76629. if (path.length > 2 && typeof fillColor === "number")
  76630. {
  76631. g.moveTo(path[path.length - 1][0], path[path.length - 1][1]);
  76632. g.lineTo(path[0][0], path[0][1]);
  76633. }
  76634. },
  76635. /**
  76636. * Draws a p2.Plane to the Graphics object.
  76637. *
  76638. * @method Phaser.Physics.P2.BodyDebug#drawPlane
  76639. * @private
  76640. */
  76641. drawPlane: function(g, x0, x1, color, lineColor, lineWidth, diagMargin, diagSize, maxLength, angle) {
  76642. var max, xd, yd;
  76643. if (lineWidth === undefined) { lineWidth = 1; }
  76644. if (color === undefined) { color = 0xffffff; }
  76645. g.lineStyle(lineWidth, lineColor, 11);
  76646. g.beginFill(color);
  76647. max = maxLength;
  76648. g.moveTo(x0, -x1);
  76649. xd = x0 + Math.cos(angle) * this.game.width;
  76650. yd = x1 + Math.sin(angle) * this.game.height;
  76651. g.lineTo(xd, -yd);
  76652. g.moveTo(x0, -x1);
  76653. xd = x0 + Math.cos(angle) * -this.game.width;
  76654. yd = x1 + Math.sin(angle) * -this.game.height;
  76655. g.lineTo(xd, -yd);
  76656. },
  76657. /**
  76658. * Draws a p2.Capsule to the Graphics object.
  76659. *
  76660. * @method Phaser.Physics.P2.BodyDebug#drawCapsule
  76661. * @private
  76662. */
  76663. drawCapsule: function(g, x, y, angle, len, radius, color, fillColor, lineWidth) {
  76664. if (lineWidth === undefined) { lineWidth = 1; }
  76665. if (color === undefined) { color = 0x000000; }
  76666. g.lineStyle(lineWidth, color, 1);
  76667. // Draw circles at ends
  76668. var c = Math.cos(angle);
  76669. var s = Math.sin(angle);
  76670. g.beginFill(fillColor, 1);
  76671. g.drawCircle(-len/2*c + x, -len/2*s + y, -radius * 2);
  76672. g.drawCircle( len/2*c + x, len/2*s + y, -radius * 2);
  76673. g.endFill();
  76674. // Draw rectangle
  76675. g.lineStyle(lineWidth, color, 0);
  76676. g.beginFill(fillColor, 1);
  76677. g.moveTo(-len/2*c + radius*s + x, -len/2*s + radius*c + y);
  76678. g.lineTo( len/2*c + radius*s + x, len/2*s + radius*c + y);
  76679. g.lineTo( len/2*c - radius*s + x, len/2*s - radius*c + y);
  76680. g.lineTo(-len/2*c - radius*s + x, -len/2*s - radius*c + y);
  76681. g.endFill();
  76682. // Draw lines in between
  76683. g.lineStyle(lineWidth, color, 1);
  76684. g.moveTo(-len/2*c + radius*s + x, -len/2*s + radius*c + y);
  76685. g.lineTo( len/2*c + radius*s + x, len/2*s + radius*c + y);
  76686. g.moveTo(-len/2*c - radius*s + x, -len/2*s - radius*c + y);
  76687. g.lineTo( len/2*c - radius*s + x, len/2*s - radius*c + y);
  76688. },
  76689. /**
  76690. * Picks a random pastel color.
  76691. *
  76692. * @method Phaser.Physics.P2.BodyDebug#randomPastelHex
  76693. * @private
  76694. */
  76695. randomPastelHex: function() {
  76696. var blue, green, mix, red;
  76697. mix = [255, 255, 255];
  76698. red = Math.floor(Math.random() * 256);
  76699. green = Math.floor(Math.random() * 256);
  76700. blue = Math.floor(Math.random() * 256);
  76701. red = Math.floor((red + 3 * mix[0]) / 4);
  76702. green = Math.floor((green + 3 * mix[1]) / 4);
  76703. blue = Math.floor((blue + 3 * mix[2]) / 4);
  76704. return this.rgbToHex(red, green, blue);
  76705. },
  76706. /**
  76707. * Converts from RGB to Hex.
  76708. *
  76709. * @method Phaser.Physics.P2.BodyDebug#rgbToHex
  76710. * @private
  76711. */
  76712. rgbToHex: function(r, g, b) {
  76713. return this.componentToHex(r) + this.componentToHex(g) + this.componentToHex(b);
  76714. },
  76715. /**
  76716. * Component to hex conversion.
  76717. *
  76718. * @method Phaser.Physics.P2.BodyDebug#componentToHex
  76719. * @private
  76720. */
  76721. componentToHex: function(c) {
  76722. var hex;
  76723. hex = c.toString(16);
  76724. if (hex.length === 2)
  76725. {
  76726. return hex;
  76727. }
  76728. else
  76729. {
  76730. return hex + '0';
  76731. }
  76732. }
  76733. });
  76734. /**
  76735. * @author Richard Davey <rich@photonstorm.com>
  76736. * @copyright 2016 Photon Storm Ltd.
  76737. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  76738. */
  76739. /**
  76740. * Creates a linear spring, connecting two bodies. A spring can have a resting length, a stiffness and damping.
  76741. *
  76742. * @class Phaser.Physics.P2.Spring
  76743. * @constructor
  76744. * @param {Phaser.Physics.P2} world - A reference to the P2 World.
  76745. * @param {p2.Body} bodyA - First connected body.
  76746. * @param {p2.Body} bodyB - Second connected body.
  76747. * @param {number} [restLength=1] - Rest length of the spring. A number > 0.
  76748. * @param {number} [stiffness=100] - Stiffness of the spring. A number >= 0.
  76749. * @param {number} [damping=1] - Damping of the spring. A number >= 0.
  76750. * @param {Array} [worldA] - Where to hook the spring to body A in world coordinates. This value is an array with 2 elements matching x and y, i.e: [32, 32].
  76751. * @param {Array} [worldB] - Where to hook the spring to body B in world coordinates. This value is an array with 2 elements matching x and y, i.e: [32, 32].
  76752. * @param {Array} [localA] - Where to hook the spring to body A in local body coordinates. This value is an array with 2 elements matching x and y, i.e: [32, 32].
  76753. * @param {Array} [localB] - Where to hook the spring to body B in local body coordinates. This value is an array with 2 elements matching x and y, i.e: [32, 32].
  76754. */
  76755. Phaser.Physics.P2.Spring = function (world, bodyA, bodyB, restLength, stiffness, damping, worldA, worldB, localA, localB) {
  76756. /**
  76757. * @property {Phaser.Game} game - Local reference to game.
  76758. */
  76759. this.game = world.game;
  76760. /**
  76761. * @property {Phaser.Physics.P2} world - Local reference to P2 World.
  76762. */
  76763. this.world = world;
  76764. if (restLength === undefined) { restLength = 1; }
  76765. if (stiffness === undefined) { stiffness = 100; }
  76766. if (damping === undefined) { damping = 1; }
  76767. restLength = world.pxm(restLength);
  76768. var options = {
  76769. restLength: restLength,
  76770. stiffness: stiffness,
  76771. damping: damping
  76772. };
  76773. if (typeof worldA !== 'undefined' && worldA !== null)
  76774. {
  76775. options.worldAnchorA = [ world.pxm(worldA[0]), world.pxm(worldA[1]) ];
  76776. }
  76777. if (typeof worldB !== 'undefined' && worldB !== null)
  76778. {
  76779. options.worldAnchorB = [ world.pxm(worldB[0]), world.pxm(worldB[1]) ];
  76780. }
  76781. if (typeof localA !== 'undefined' && localA !== null)
  76782. {
  76783. options.localAnchorA = [ world.pxm(localA[0]), world.pxm(localA[1]) ];
  76784. }
  76785. if (typeof localB !== 'undefined' && localB !== null)
  76786. {
  76787. options.localAnchorB = [ world.pxm(localB[0]), world.pxm(localB[1]) ];
  76788. }
  76789. /**
  76790. * @property {p2.LinearSpring} data - The actual p2 spring object.
  76791. */
  76792. this.data = new p2.LinearSpring(bodyA, bodyB, options);
  76793. this.data.parent = this;
  76794. };
  76795. Phaser.Physics.P2.Spring.prototype.constructor = Phaser.Physics.P2.Spring;
  76796. /**
  76797. * @author Richard Davey <rich@photonstorm.com>
  76798. * @copyright 2016 Photon Storm Ltd.
  76799. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  76800. */
  76801. /**
  76802. * Creates a rotational spring, connecting two bodies. A spring can have a resting length, a stiffness and damping.
  76803. *
  76804. * @class Phaser.Physics.P2.RotationalSpring
  76805. * @constructor
  76806. * @param {Phaser.Physics.P2} world - A reference to the P2 World.
  76807. * @param {p2.Body} bodyA - First connected body.
  76808. * @param {p2.Body} bodyB - Second connected body.
  76809. * @param {number} [restAngle] - The relative angle of bodies at which the spring is at rest. If not given, it's set to the current relative angle between the bodies.
  76810. * @param {number} [stiffness=100] - Stiffness of the spring. A number >= 0.
  76811. * @param {number} [damping=1] - Damping of the spring. A number >= 0.
  76812. */
  76813. Phaser.Physics.P2.RotationalSpring = function (world, bodyA, bodyB, restAngle, stiffness, damping) {
  76814. /**
  76815. * @property {Phaser.Game} game - Local reference to game.
  76816. */
  76817. this.game = world.game;
  76818. /**
  76819. * @property {Phaser.Physics.P2} world - Local reference to P2 World.
  76820. */
  76821. this.world = world;
  76822. if (restAngle === undefined) { restAngle = null; }
  76823. if (stiffness === undefined) { stiffness = 100; }
  76824. if (damping === undefined) { damping = 1; }
  76825. if (restAngle)
  76826. {
  76827. restAngle = world.pxm(restAngle);
  76828. }
  76829. var options = {
  76830. restAngle: restAngle,
  76831. stiffness: stiffness,
  76832. damping: damping
  76833. };
  76834. /**
  76835. * @property {p2.RotationalSpring} data - The actual p2 spring object.
  76836. */
  76837. this.data = new p2.RotationalSpring(bodyA, bodyB, options);
  76838. this.data.parent = this;
  76839. };
  76840. Phaser.Physics.P2.Spring.prototype.constructor = Phaser.Physics.P2.Spring;
  76841. /**
  76842. * @author Richard Davey <rich@photonstorm.com>
  76843. * @copyright 2016 Photon Storm Ltd.
  76844. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  76845. */
  76846. /**
  76847. * A P2 Material.
  76848. *
  76849. * \o/ ~ "Because I'm a Material girl"
  76850. *
  76851. * @class Phaser.Physics.P2.Material
  76852. * @constructor
  76853. * @param {string} name - The user defined name given to this Material.
  76854. */
  76855. Phaser.Physics.P2.Material = function (name) {
  76856. /**
  76857. * @property {string} name - The user defined name given to this Material.
  76858. * @default
  76859. */
  76860. this.name = name;
  76861. p2.Material.call(this);
  76862. };
  76863. Phaser.Physics.P2.Material.prototype = Object.create(p2.Material.prototype);
  76864. Phaser.Physics.P2.Material.prototype.constructor = Phaser.Physics.P2.Material;
  76865. /**
  76866. * @author Richard Davey <rich@photonstorm.com>
  76867. * @copyright 2016 Photon Storm Ltd.
  76868. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  76869. */
  76870. /**
  76871. * Defines a physics material
  76872. *
  76873. * @class Phaser.Physics.P2.ContactMaterial
  76874. * @constructor
  76875. * @param {Phaser.Physics.P2.Material} materialA - First material participating in the contact material.
  76876. * @param {Phaser.Physics.P2.Material} materialB - Second material participating in the contact material.
  76877. * @param {object} [options] - Additional configuration options.
  76878. */
  76879. Phaser.Physics.P2.ContactMaterial = function (materialA, materialB, options) {
  76880. /**
  76881. * @property {number} id - The contact material identifier.
  76882. */
  76883. /**
  76884. * @property {Phaser.Physics.P2.Material} materialA - First material participating in the contact material.
  76885. */
  76886. /**
  76887. * @property {Phaser.Physics.P2.Material} materialB - Second material participating in the contact material.
  76888. */
  76889. /**
  76890. * @property {number} [friction=0.3] - Friction to use in the contact of these two materials.
  76891. */
  76892. /**
  76893. * @property {number} [restitution=0.0] - Restitution to use in the contact of these two materials.
  76894. */
  76895. /**
  76896. * @property {number} [stiffness=1e7] - Stiffness of the resulting ContactEquation that this ContactMaterial generates.
  76897. */
  76898. /**
  76899. * @property {number} [relaxation=3] - Relaxation of the resulting ContactEquation that this ContactMaterial generates.
  76900. */
  76901. /**
  76902. * @property {number} [frictionStiffness=1e7] - Stiffness of the resulting FrictionEquation that this ContactMaterial generates.
  76903. */
  76904. /**
  76905. * @property {number} [frictionRelaxation=3] - Relaxation of the resulting FrictionEquation that this ContactMaterial generates.
  76906. */
  76907. /**
  76908. * @property {number} [surfaceVelocity=0] - Will add surface velocity to this material. If bodyA rests on top if bodyB, and the surface velocity is positive, bodyA will slide to the right.
  76909. */
  76910. p2.ContactMaterial.call(this, materialA, materialB, options);
  76911. };
  76912. Phaser.Physics.P2.ContactMaterial.prototype = Object.create(p2.ContactMaterial.prototype);
  76913. Phaser.Physics.P2.ContactMaterial.prototype.constructor = Phaser.Physics.P2.ContactMaterial;
  76914. /**
  76915. * @author Richard Davey <rich@photonstorm.com>
  76916. * @copyright 2016 Photon Storm Ltd.
  76917. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  76918. */
  76919. /**
  76920. * Collision Group
  76921. *
  76922. * @class Phaser.Physics.P2.CollisionGroup
  76923. * @constructor
  76924. * @param {number} bitmask - The CollisionGroup bitmask.
  76925. */
  76926. Phaser.Physics.P2.CollisionGroup = function (bitmask) {
  76927. /**
  76928. * @property {number} mask - The CollisionGroup bitmask.
  76929. */
  76930. this.mask = bitmask;
  76931. };
  76932. /**
  76933. * @author Richard Davey <rich@photonstorm.com>
  76934. * @copyright 2016 Photon Storm Ltd.
  76935. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  76936. */
  76937. /**
  76938. * A constraint that tries to keep the distance between two bodies constant.
  76939. *
  76940. * @class Phaser.Physics.P2.DistanceConstraint
  76941. * @constructor
  76942. * @param {Phaser.Physics.P2} world - A reference to the P2 World.
  76943. * @param {p2.Body} bodyA - First connected body.
  76944. * @param {p2.Body} bodyB - Second connected body.
  76945. * @param {number} distance - The distance to keep between the bodies.
  76946. * @param {Array} [localAnchorA] - The anchor point for bodyA, defined locally in bodyA frame. Defaults to [0,0].
  76947. * @param {Array} [localAnchorB] - The anchor point for bodyB, defined locally in bodyB frame. Defaults to [0,0].
  76948. * @param {object} [maxForce=Number.MAX_VALUE] - Maximum force to apply.
  76949. */
  76950. Phaser.Physics.P2.DistanceConstraint = function (world, bodyA, bodyB, distance, localAnchorA, localAnchorB, maxForce) {
  76951. if (distance === undefined) { distance = 100; }
  76952. if (localAnchorA === undefined) { localAnchorA = [0, 0]; }
  76953. if (localAnchorB === undefined) { localAnchorB = [0, 0]; }
  76954. if (maxForce === undefined) { maxForce = Number.MAX_VALUE; }
  76955. /**
  76956. * @property {Phaser.Game} game - Local reference to game.
  76957. */
  76958. this.game = world.game;
  76959. /**
  76960. * @property {Phaser.Physics.P2} world - Local reference to P2 World.
  76961. */
  76962. this.world = world;
  76963. distance = world.pxm(distance);
  76964. localAnchorA = [ world.pxmi(localAnchorA[0]), world.pxmi(localAnchorA[1]) ];
  76965. localAnchorB = [ world.pxmi(localAnchorB[0]), world.pxmi(localAnchorB[1]) ];
  76966. var options = { distance: distance, localAnchorA: localAnchorA, localAnchorB: localAnchorB, maxForce: maxForce };
  76967. p2.DistanceConstraint.call(this, bodyA, bodyB, options);
  76968. };
  76969. Phaser.Physics.P2.DistanceConstraint.prototype = Object.create(p2.DistanceConstraint.prototype);
  76970. Phaser.Physics.P2.DistanceConstraint.prototype.constructor = Phaser.Physics.P2.DistanceConstraint;
  76971. /**
  76972. * @author Richard Davey <rich@photonstorm.com>
  76973. * @copyright 2016 Photon Storm Ltd.
  76974. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  76975. */
  76976. /**
  76977. * Connects two bodies at given offset points, letting them rotate relative to each other around this point.
  76978. *
  76979. * @class Phaser.Physics.P2.GearConstraint
  76980. * @constructor
  76981. * @param {Phaser.Physics.P2} world - A reference to the P2 World.
  76982. * @param {p2.Body} bodyA - First connected body.
  76983. * @param {p2.Body} bodyB - Second connected body.
  76984. * @param {number} [angle=0] - The relative angle
  76985. * @param {number} [ratio=1] - The gear ratio.
  76986. */
  76987. Phaser.Physics.P2.GearConstraint = function (world, bodyA, bodyB, angle, ratio) {
  76988. if (angle === undefined) { angle = 0; }
  76989. if (ratio === undefined) { ratio = 1; }
  76990. /**
  76991. * @property {Phaser.Game} game - Local reference to game.
  76992. */
  76993. this.game = world.game;
  76994. /**
  76995. * @property {Phaser.Physics.P2} world - Local reference to P2 World.
  76996. */
  76997. this.world = world;
  76998. var options = { angle: angle, ratio: ratio };
  76999. p2.GearConstraint.call(this, bodyA, bodyB, options);
  77000. };
  77001. Phaser.Physics.P2.GearConstraint.prototype = Object.create(p2.GearConstraint.prototype);
  77002. Phaser.Physics.P2.GearConstraint.prototype.constructor = Phaser.Physics.P2.GearConstraint;
  77003. /**
  77004. * @author Richard Davey <rich@photonstorm.com>
  77005. * @copyright 2016 Photon Storm Ltd.
  77006. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  77007. */
  77008. /**
  77009. * Locks the relative position between two bodies.
  77010. *
  77011. * @class Phaser.Physics.P2.LockConstraint
  77012. * @constructor
  77013. * @param {Phaser.Physics.P2} world - A reference to the P2 World.
  77014. * @param {p2.Body} bodyA - First connected body.
  77015. * @param {p2.Body} bodyB - Second connected body.
  77016. * @param {Array} [offset] - The offset of bodyB in bodyA's frame. The value is an array with 2 elements matching x and y, i.e: [32, 32].
  77017. * @param {number} [angle=0] - The angle of bodyB in bodyA's frame.
  77018. * @param {number} [maxForce] - The maximum force that should be applied to constrain the bodies.
  77019. */
  77020. Phaser.Physics.P2.LockConstraint = function (world, bodyA, bodyB, offset, angle, maxForce) {
  77021. if (offset === undefined) { offset = [0, 0]; }
  77022. if (angle === undefined) { angle = 0; }
  77023. if (maxForce === undefined) { maxForce = Number.MAX_VALUE; }
  77024. /**
  77025. * @property {Phaser.Game} game - Local reference to game.
  77026. */
  77027. this.game = world.game;
  77028. /**
  77029. * @property {Phaser.Physics.P2} world - Local reference to P2 World.
  77030. */
  77031. this.world = world;
  77032. offset = [ world.pxm(offset[0]), world.pxm(offset[1]) ];
  77033. var options = { localOffsetB: offset, localAngleB: angle, maxForce: maxForce };
  77034. p2.LockConstraint.call(this, bodyA, bodyB, options);
  77035. };
  77036. Phaser.Physics.P2.LockConstraint.prototype = Object.create(p2.LockConstraint.prototype);
  77037. Phaser.Physics.P2.LockConstraint.prototype.constructor = Phaser.Physics.P2.LockConstraint;
  77038. /**
  77039. * @author Richard Davey <rich@photonstorm.com>
  77040. * @copyright 2016 Photon Storm Ltd.
  77041. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  77042. */
  77043. /**
  77044. * Connects two bodies at given offset points, letting them rotate relative to each other around this point.
  77045. *
  77046. * @class Phaser.Physics.P2.PrismaticConstraint
  77047. * @constructor
  77048. * @param {Phaser.Physics.P2} world - A reference to the P2 World.
  77049. * @param {p2.Body} bodyA - First connected body.
  77050. * @param {p2.Body} bodyB - Second connected body.
  77051. * @param {boolean} [lockRotation=true] - If set to false, bodyB will be free to rotate around its anchor point.
  77052. * @param {Array} [anchorA] - Body A's anchor point, defined in its own local frame. The value is an array with 2 elements matching x and y, i.e: [32, 32].
  77053. * @param {Array} [anchorB] - Body A's anchor point, defined in its own local frame. The value is an array with 2 elements matching x and y, i.e: [32, 32].
  77054. * @param {Array} [axis] - An axis, defined in body A frame, that body B's anchor point may slide along. The value is an array with 2 elements matching x and y, i.e: [32, 32].
  77055. * @param {number} [maxForce] - The maximum force that should be applied to constrain the bodies.
  77056. */
  77057. Phaser.Physics.P2.PrismaticConstraint = function (world, bodyA, bodyB, lockRotation, anchorA, anchorB, axis, maxForce) {
  77058. if (lockRotation === undefined) { lockRotation = true; }
  77059. if (anchorA === undefined) { anchorA = [0, 0]; }
  77060. if (anchorB === undefined) { anchorB = [0, 0]; }
  77061. if (axis === undefined) { axis = [0, 0]; }
  77062. if (maxForce === undefined) { maxForce = Number.MAX_VALUE; }
  77063. /**
  77064. * @property {Phaser.Game} game - Local reference to game.
  77065. */
  77066. this.game = world.game;
  77067. /**
  77068. * @property {Phaser.Physics.P2} world - Local reference to P2 World.
  77069. */
  77070. this.world = world;
  77071. anchorA = [ world.pxmi(anchorA[0]), world.pxmi(anchorA[1]) ];
  77072. anchorB = [ world.pxmi(anchorB[0]), world.pxmi(anchorB[1]) ];
  77073. var options = { localAnchorA: anchorA, localAnchorB: anchorB, localAxisA: axis, maxForce: maxForce, disableRotationalLock: !lockRotation };
  77074. p2.PrismaticConstraint.call(this, bodyA, bodyB, options);
  77075. };
  77076. Phaser.Physics.P2.PrismaticConstraint.prototype = Object.create(p2.PrismaticConstraint.prototype);
  77077. Phaser.Physics.P2.PrismaticConstraint.prototype.constructor = Phaser.Physics.P2.PrismaticConstraint;
  77078. /**
  77079. * @author Richard Davey <rich@photonstorm.com>
  77080. * @copyright 2016 Photon Storm Ltd.
  77081. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  77082. */
  77083. /**
  77084. * Connects two bodies at given offset points, letting them rotate relative to each other around this point.
  77085. * The pivot points are given in world (pixel) coordinates.
  77086. *
  77087. * @class Phaser.Physics.P2.RevoluteConstraint
  77088. * @constructor
  77089. * @param {Phaser.Physics.P2} world - A reference to the P2 World.
  77090. * @param {p2.Body} bodyA - First connected body.
  77091. * @param {Float32Array} pivotA - The point relative to the center of mass of bodyA which bodyA is constrained to. The value is an array with 2 elements matching x and y, i.e: [32, 32].
  77092. * @param {p2.Body} bodyB - Second connected body.
  77093. * @param {Float32Array} pivotB - The point relative to the center of mass of bodyB which bodyB is constrained to. The value is an array with 2 elements matching x and y, i.e: [32, 32].
  77094. * @param {number} [maxForce=0] - The maximum force that should be applied to constrain the bodies.
  77095. * @param {Float32Array} [worldPivot=null] - A pivot point given in world coordinates. If specified, localPivotA and localPivotB are automatically computed from this value.
  77096. */
  77097. Phaser.Physics.P2.RevoluteConstraint = function (world, bodyA, pivotA, bodyB, pivotB, maxForce, worldPivot) {
  77098. if (maxForce === undefined) { maxForce = Number.MAX_VALUE; }
  77099. if (worldPivot === undefined) { worldPivot = null; }
  77100. /**
  77101. * @property {Phaser.Game} game - Local reference to game.
  77102. */
  77103. this.game = world.game;
  77104. /**
  77105. * @property {Phaser.Physics.P2} world - Local reference to P2 World.
  77106. */
  77107. this.world = world;
  77108. pivotA = [ world.pxmi(pivotA[0]), world.pxmi(pivotA[1]) ];
  77109. pivotB = [ world.pxmi(pivotB[0]), world.pxmi(pivotB[1]) ];
  77110. if (worldPivot)
  77111. {
  77112. worldPivot = [ world.pxmi(worldPivot[0]), world.pxmi(worldPivot[1]) ];
  77113. }
  77114. var options = { worldPivot: worldPivot, localPivotA: pivotA, localPivotB: pivotB, maxForce: maxForce };
  77115. p2.RevoluteConstraint.call(this, bodyA, bodyB, options);
  77116. };
  77117. Phaser.Physics.P2.RevoluteConstraint.prototype = Object.create(p2.RevoluteConstraint.prototype);
  77118. Phaser.Physics.P2.RevoluteConstraint.prototype.constructor = Phaser.Physics.P2.RevoluteConstraint;
  77119. /**
  77120. * @author Richard Davey <rich@photonstorm.com>
  77121. * @copyright 2016 Photon Storm Ltd.
  77122. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  77123. */
  77124. /**
  77125. * An Image Collection is a special tileset containing mulitple images, with no slicing into each image.
  77126. *
  77127. * Image Collections are normally created automatically when Tiled data is loaded.
  77128. *
  77129. * @class Phaser.ImageCollection
  77130. * @constructor
  77131. * @param {string} name - The name of the image collection in the map data.
  77132. * @param {integer} firstgid - The first image index this image collection contains.
  77133. * @param {integer} [width=32] - Width of widest image (in pixels).
  77134. * @param {integer} [height=32] - Height of tallest image (in pixels).
  77135. * @param {integer} [margin=0] - The margin around all images in the collection (in pixels).
  77136. * @param {integer} [spacing=0] - The spacing between each image in the collection (in pixels).
  77137. * @param {object} [properties={}] - Custom Image Collection properties.
  77138. */
  77139. Phaser.ImageCollection = function (name, firstgid, width, height, margin, spacing, properties) {
  77140. if (width === undefined || width <= 0) { width = 32; }
  77141. if (height === undefined || height <= 0) { height = 32; }
  77142. if (margin === undefined) { margin = 0; }
  77143. if (spacing === undefined) { spacing = 0; }
  77144. /**
  77145. * The name of the Image Collection.
  77146. * @property {string} name
  77147. */
  77148. this.name = name;
  77149. /**
  77150. * The Tiled firstgid value.
  77151. * This is the starting index of the first image index this Image Collection contains.
  77152. * @property {integer} firstgid
  77153. */
  77154. this.firstgid = firstgid | 0;
  77155. /**
  77156. * The width of the widest image (in pixels).
  77157. * @property {integer} imageWidth
  77158. * @readonly
  77159. */
  77160. this.imageWidth = width | 0;
  77161. /**
  77162. * The height of the tallest image (in pixels).
  77163. * @property {integer} imageHeight
  77164. * @readonly
  77165. */
  77166. this.imageHeight = height | 0;
  77167. /**
  77168. * The margin around the images in the collection (in pixels).
  77169. * Use `setSpacing` to change.
  77170. * @property {integer} imageMarge
  77171. * @readonly
  77172. */
  77173. // Modified internally
  77174. this.imageMargin = margin | 0;
  77175. /**
  77176. * The spacing between each image in the collection (in pixels).
  77177. * Use `setSpacing` to change.
  77178. * @property {integer} imageSpacing
  77179. * @readonly
  77180. */
  77181. this.imageSpacing = spacing | 0;
  77182. /**
  77183. * Image Collection-specific properties that are typically defined in the Tiled editor.
  77184. * @property {object} properties
  77185. */
  77186. this.properties = properties || {};
  77187. /**
  77188. * The cached images that are a part of this collection.
  77189. * @property {array} images
  77190. * @readonly
  77191. */
  77192. // Modified internally
  77193. this.images = [];
  77194. /**
  77195. * The total number of images in the image collection.
  77196. * @property {integer} total
  77197. * @readonly
  77198. */
  77199. // Modified internally
  77200. this.total = 0;
  77201. };
  77202. Phaser.ImageCollection.prototype = {
  77203. /**
  77204. * Returns true if and only if this image collection contains the given image index.
  77205. *
  77206. * @method Phaser.ImageCollection#containsImageIndex
  77207. * @param {integer} imageIndex - The image index to search for.
  77208. * @return {boolean} True if this Image Collection contains the given index.
  77209. */
  77210. containsImageIndex: function (imageIndex) {
  77211. return (
  77212. imageIndex >= this.firstgid &&
  77213. imageIndex < (this.firstgid + this.total)
  77214. );
  77215. },
  77216. /**
  77217. * Add an image to this Image Collection.
  77218. *
  77219. * @method Phaser.ImageCollection#addImage
  77220. * @param {integer} gid - The gid of the image in the Image Collection.
  77221. * @param {string} image - The the key of the image in the Image Collection and in the cache.
  77222. */
  77223. addImage: function (gid, image) {
  77224. this.images.push({ gid: gid, image: image });
  77225. this.total++;
  77226. }
  77227. };
  77228. Phaser.ImageCollection.prototype.constructor = Phaser.ImageCollection;
  77229. /**
  77230. * @author Richard Davey <rich@photonstorm.com>
  77231. * @copyright 2016 Photon Storm Ltd.
  77232. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  77233. */
  77234. /**
  77235. * A Tile is a representation of a single tile within the Tilemap.
  77236. *
  77237. * @class Phaser.Tile
  77238. * @constructor
  77239. * @param {object} layer - The layer in the Tilemap data that this tile belongs to.
  77240. * @param {number} index - The index of this tile type in the core map data.
  77241. * @param {number} x - The x coordinate of this tile.
  77242. * @param {number} y - The y coordinate of this tile.
  77243. * @param {number} width - Width of the tile.
  77244. * @param {number} height - Height of the tile.
  77245. */
  77246. Phaser.Tile = function (layer, index, x, y, width, height) {
  77247. /**
  77248. * @property {object} layer - The layer in the Tilemap data that this tile belongs to.
  77249. */
  77250. this.layer = layer;
  77251. /**
  77252. * @property {number} index - The index of this tile within the map data corresponding to the tileset, or -1 if this represents a blank/null tile.
  77253. */
  77254. this.index = index;
  77255. /**
  77256. * @property {number} x - The x map coordinate of this tile.
  77257. */
  77258. this.x = x;
  77259. /**
  77260. * @property {number} y - The y map coordinate of this tile.
  77261. */
  77262. this.y = y;
  77263. /**
  77264. * @property {number} rotation - The rotation angle of this tile.
  77265. */
  77266. this.rotation = 0;
  77267. /**
  77268. * @property {boolean} flipped - Whether this tile is flipped (mirrored) or not.
  77269. */
  77270. this.flipped = false;
  77271. /**
  77272. * @property {number} x - The x map coordinate of this tile.
  77273. */
  77274. this.worldX = x * width;
  77275. /**
  77276. * @property {number} y - The y map coordinate of this tile.
  77277. */
  77278. this.worldY = y * height;
  77279. /**
  77280. * @property {number} width - The width of the tile in pixels.
  77281. */
  77282. this.width = width;
  77283. /**
  77284. * @property {number} height - The height of the tile in pixels.
  77285. */
  77286. this.height = height;
  77287. /**
  77288. * @property {number} width - The width of the tile in pixels.
  77289. */
  77290. this.centerX = Math.abs(width / 2);
  77291. /**
  77292. * @property {number} height - The height of the tile in pixels.
  77293. */
  77294. this.centerY = Math.abs(height / 2);
  77295. /**
  77296. * @property {number} alpha - The alpha value at which this tile is drawn to the canvas.
  77297. */
  77298. this.alpha = 1;
  77299. /**
  77300. * @property {object} properties - Tile specific properties.
  77301. */
  77302. this.properties = {};
  77303. /**
  77304. * @property {boolean} scanned - Has this tile been walked / turned into a poly?
  77305. */
  77306. this.scanned = false;
  77307. /**
  77308. * @property {boolean} faceTop - Is the top of this tile an interesting edge?
  77309. */
  77310. this.faceTop = false;
  77311. /**
  77312. * @property {boolean} faceBottom - Is the bottom of this tile an interesting edge?
  77313. */
  77314. this.faceBottom = false;
  77315. /**
  77316. * @property {boolean} faceLeft - Is the left of this tile an interesting edge?
  77317. */
  77318. this.faceLeft = false;
  77319. /**
  77320. * @property {boolean} faceRight - Is the right of this tile an interesting edge?
  77321. */
  77322. this.faceRight = false;
  77323. /**
  77324. * @property {boolean} collideLeft - Indicating collide with any object on the left.
  77325. * @default
  77326. */
  77327. this.collideLeft = false;
  77328. /**
  77329. * @property {boolean} collideRight - Indicating collide with any object on the right.
  77330. * @default
  77331. */
  77332. this.collideRight = false;
  77333. /**
  77334. * @property {boolean} collideUp - Indicating collide with any object on the top.
  77335. * @default
  77336. */
  77337. this.collideUp = false;
  77338. /**
  77339. * @property {boolean} collideDown - Indicating collide with any object on the bottom.
  77340. * @default
  77341. */
  77342. this.collideDown = false;
  77343. /**
  77344. * @property {function} collisionCallback - Tile collision callback.
  77345. * @default
  77346. */
  77347. this.collisionCallback = null;
  77348. /**
  77349. * @property {object} collisionCallbackContext - The context in which the collision callback will be called.
  77350. * @default
  77351. */
  77352. this.collisionCallbackContext = this;
  77353. };
  77354. Phaser.Tile.prototype = {
  77355. /**
  77356. * Check if the given x and y world coordinates are within this Tile.
  77357. *
  77358. * @method Phaser.Tile#containsPoint
  77359. * @param {number} x - The x coordinate to test.
  77360. * @param {number} y - The y coordinate to test.
  77361. * @return {boolean} True if the coordinates are within this Tile, otherwise false.
  77362. */
  77363. containsPoint: function (x, y) {
  77364. return !(x < this.worldX || y < this.worldY || x > this.right || y > this.bottom);
  77365. },
  77366. /**
  77367. * Check for intersection with this tile.
  77368. *
  77369. * @method Phaser.Tile#intersects
  77370. * @param {number} x - The x axis in pixels.
  77371. * @param {number} y - The y axis in pixels.
  77372. * @param {number} right - The right point.
  77373. * @param {number} bottom - The bottom point.
  77374. */
  77375. intersects: function (x, y, right, bottom) {
  77376. if (right <= this.worldX)
  77377. {
  77378. return false;
  77379. }
  77380. if (bottom <= this.worldY)
  77381. {
  77382. return false;
  77383. }
  77384. if (x >= this.worldX + this.width)
  77385. {
  77386. return false;
  77387. }
  77388. if (y >= this.worldY + this.height)
  77389. {
  77390. return false;
  77391. }
  77392. return true;
  77393. },
  77394. /**
  77395. * Set a callback to be called when this tile is hit by an object.
  77396. * The callback must true true for collision processing to take place.
  77397. *
  77398. * @method Phaser.Tile#setCollisionCallback
  77399. * @param {function} callback - Callback function.
  77400. * @param {object} context - Callback will be called within this context.
  77401. */
  77402. setCollisionCallback: function (callback, context) {
  77403. this.collisionCallback = callback;
  77404. this.collisionCallbackContext = context;
  77405. },
  77406. /**
  77407. * Clean up memory.
  77408. *
  77409. * @method Phaser.Tile#destroy
  77410. */
  77411. destroy: function () {
  77412. this.collisionCallback = null;
  77413. this.collisionCallbackContext = null;
  77414. this.properties = null;
  77415. },
  77416. /**
  77417. * Sets the collision flags for each side of this tile and updates the interesting faces list.
  77418. *
  77419. * @method Phaser.Tile#setCollision
  77420. * @param {boolean} left - Indicating collide with any object on the left.
  77421. * @param {boolean} right - Indicating collide with any object on the right.
  77422. * @param {boolean} up - Indicating collide with any object on the top.
  77423. * @param {boolean} down - Indicating collide with any object on the bottom.
  77424. */
  77425. setCollision: function (left, right, up, down) {
  77426. this.collideLeft = left;
  77427. this.collideRight = right;
  77428. this.collideUp = up;
  77429. this.collideDown = down;
  77430. this.faceLeft = left;
  77431. this.faceRight = right;
  77432. this.faceTop = up;
  77433. this.faceBottom = down;
  77434. },
  77435. /**
  77436. * Reset collision status flags.
  77437. *
  77438. * @method Phaser.Tile#resetCollision
  77439. */
  77440. resetCollision: function () {
  77441. this.collideLeft = false;
  77442. this.collideRight = false;
  77443. this.collideUp = false;
  77444. this.collideDown = false;
  77445. this.faceTop = false;
  77446. this.faceBottom = false;
  77447. this.faceLeft = false;
  77448. this.faceRight = false;
  77449. },
  77450. /**
  77451. * Is this tile interesting?
  77452. *
  77453. * @method Phaser.Tile#isInteresting
  77454. * @param {boolean} collides - If true will check any collides value.
  77455. * @param {boolean} faces - If true will check any face value.
  77456. * @return {boolean} True if the Tile is interesting, otherwise false.
  77457. */
  77458. isInteresting: function (collides, faces) {
  77459. if (collides && faces)
  77460. {
  77461. // Does this tile have any collide flags OR interesting face?
  77462. return (this.collideLeft || this.collideRight || this.collideUp || this.collideDown || this.faceTop || this.faceBottom || this.faceLeft || this.faceRight || this.collisionCallback);
  77463. }
  77464. else if (collides)
  77465. {
  77466. // Does this tile collide?
  77467. return (this.collideLeft || this.collideRight || this.collideUp || this.collideDown);
  77468. }
  77469. else if (faces)
  77470. {
  77471. // Does this tile have an interesting face?
  77472. return (this.faceTop || this.faceBottom || this.faceLeft || this.faceRight);
  77473. }
  77474. return false;
  77475. },
  77476. /**
  77477. * Copies the tile data and properties from the given tile to this tile.
  77478. *
  77479. * @method Phaser.Tile#copy
  77480. * @param {Phaser.Tile} tile - The tile to copy from.
  77481. */
  77482. copy: function (tile) {
  77483. this.index = tile.index;
  77484. this.alpha = tile.alpha;
  77485. this.properties = tile.properties;
  77486. this.collideUp = tile.collideUp;
  77487. this.collideDown = tile.collideDown;
  77488. this.collideLeft = tile.collideLeft;
  77489. this.collideRight = tile.collideRight;
  77490. this.collisionCallback = tile.collisionCallback;
  77491. this.collisionCallbackContext = tile.collisionCallbackContext;
  77492. }
  77493. };
  77494. Phaser.Tile.prototype.constructor = Phaser.Tile;
  77495. /**
  77496. * @name Phaser.Tile#collides
  77497. * @property {boolean} collides - True if this tile can collide on any of its faces.
  77498. * @readonly
  77499. */
  77500. Object.defineProperty(Phaser.Tile.prototype, "collides", {
  77501. get: function () {
  77502. return (this.collideLeft || this.collideRight || this.collideUp || this.collideDown);
  77503. }
  77504. });
  77505. /**
  77506. * @name Phaser.Tile#canCollide
  77507. * @property {boolean} canCollide - True if this tile can collide on any of its faces or has a collision callback set.
  77508. * @readonly
  77509. */
  77510. Object.defineProperty(Phaser.Tile.prototype, "canCollide", {
  77511. get: function () {
  77512. return (this.collideLeft || this.collideRight || this.collideUp || this.collideDown || this.collisionCallback);
  77513. }
  77514. });
  77515. /**
  77516. * @name Phaser.Tile#left
  77517. * @property {number} left - The x value in pixels.
  77518. * @readonly
  77519. */
  77520. Object.defineProperty(Phaser.Tile.prototype, "left", {
  77521. get: function () {
  77522. return this.worldX;
  77523. }
  77524. });
  77525. /**
  77526. * @name Phaser.Tile#right
  77527. * @property {number} right - The sum of the x and width properties.
  77528. * @readonly
  77529. */
  77530. Object.defineProperty(Phaser.Tile.prototype, "right", {
  77531. get: function () {
  77532. return this.worldX + this.width;
  77533. }
  77534. });
  77535. /**
  77536. * @name Phaser.Tile#top
  77537. * @property {number} top - The y value.
  77538. * @readonly
  77539. */
  77540. Object.defineProperty(Phaser.Tile.prototype, "top", {
  77541. get: function () {
  77542. return this.worldY;
  77543. }
  77544. });
  77545. /**
  77546. * @name Phaser.Tile#bottom
  77547. * @property {number} bottom - The sum of the y and height properties.
  77548. * @readonly
  77549. */
  77550. Object.defineProperty(Phaser.Tile.prototype, "bottom", {
  77551. get: function () {
  77552. return this.worldY + this.height;
  77553. }
  77554. });
  77555. /**
  77556. * @author Richard Davey <rich@photonstorm.com>
  77557. * @copyright 2016 Photon Storm Ltd.
  77558. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  77559. */
  77560. /**
  77561. * Creates a new Phaser.Tilemap object. The map can either be populated with data from a Tiled JSON file or from a CSV file.
  77562. *
  77563. * Tiled is a free software package specifically for creating tile maps, and is available from http://www.mapeditor.org
  77564. *
  77565. * To do this pass the Cache key as the first parameter. When using Tiled data you need only provide the key.
  77566. * When using CSV data you must provide the key and the tileWidth and tileHeight parameters.
  77567. * If creating a blank tilemap to be populated later, you can either specify no parameters at all and then use `Tilemap.create` or pass the map and tile dimensions here.
  77568. * Note that all Tilemaps use a base tile size to calculate dimensions from, but that a TilemapLayer may have its own unique tile size that overrides it.
  77569. * A Tile map is rendered to the display using a TilemapLayer. It is not added to the display list directly itself.
  77570. * A map may have multiple layers. You can perform operations on the map data such as copying, pasting, filling and shuffling the tiles around.
  77571. *
  77572. * @class Phaser.Tilemap
  77573. * @constructor
  77574. * @param {Phaser.Game} game - Game reference to the currently running game.
  77575. * @param {string} [key] - The key of the tilemap data as stored in the Cache. If you're creating a blank map either leave this parameter out or pass `null`.
  77576. * @param {number} [tileWidth=32] - The pixel width of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data.
  77577. * @param {number} [tileHeight=32] - The pixel height of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data.
  77578. * @param {number} [width=10] - The width of the map in tiles. If this map is created from Tiled or CSV data you don't need to specify this.
  77579. * @param {number} [height=10] - The height of the map in tiles. If this map is created from Tiled or CSV data you don't need to specify this.
  77580. */
  77581. Phaser.Tilemap = function (game, key, tileWidth, tileHeight, width, height) {
  77582. /**
  77583. * @property {Phaser.Game} game - A reference to the currently running Game.
  77584. */
  77585. this.game = game;
  77586. /**
  77587. * @property {string} key - The key of this map data in the Phaser.Cache.
  77588. */
  77589. this.key = key;
  77590. var data = Phaser.TilemapParser.parse(this.game, key, tileWidth, tileHeight, width, height);
  77591. if (data === null)
  77592. {
  77593. return;
  77594. }
  77595. /**
  77596. * @property {number} width - The width of the map (in tiles).
  77597. */
  77598. this.width = data.width;
  77599. /**
  77600. * @property {number} height - The height of the map (in tiles).
  77601. */
  77602. this.height = data.height;
  77603. /**
  77604. * @property {number} tileWidth - The base width of the tiles in the map (in pixels).
  77605. */
  77606. this.tileWidth = data.tileWidth;
  77607. /**
  77608. * @property {number} tileHeight - The base height of the tiles in the map (in pixels).
  77609. */
  77610. this.tileHeight = data.tileHeight;
  77611. /**
  77612. * @property {string} orientation - The orientation of the map data (as specified in Tiled), usually 'orthogonal'.
  77613. */
  77614. this.orientation = data.orientation;
  77615. /**
  77616. * @property {number} format - The format of the map data, either Phaser.Tilemap.CSV or Phaser.Tilemap.TILED_JSON.
  77617. */
  77618. this.format = data.format;
  77619. /**
  77620. * @property {number} version - The version of the map data (as specified in Tiled, usually 1).
  77621. */
  77622. this.version = data.version;
  77623. /**
  77624. * @property {object} properties - Map specific properties as specified in Tiled.
  77625. */
  77626. this.properties = data.properties;
  77627. /**
  77628. * @property {number} widthInPixels - The width of the map in pixels based on width * tileWidth.
  77629. */
  77630. this.widthInPixels = data.widthInPixels;
  77631. /**
  77632. * @property {number} heightInPixels - The height of the map in pixels based on height * tileHeight.
  77633. */
  77634. this.heightInPixels = data.heightInPixels;
  77635. /**
  77636. * @property {array} layers - An array of Tilemap layer data.
  77637. */
  77638. this.layers = data.layers;
  77639. /**
  77640. * @property {array} tilesets - An array of Tilesets.
  77641. */
  77642. this.tilesets = data.tilesets;
  77643. /**
  77644. * @property {array} imagecollections - An array of Image Collections.
  77645. */
  77646. this.imagecollections = data.imagecollections;
  77647. /**
  77648. * @property {array} tiles - The super array of Tiles.
  77649. */
  77650. this.tiles = data.tiles;
  77651. /**
  77652. * @property {array} objects - An array of Tiled Object Layers.
  77653. */
  77654. this.objects = data.objects;
  77655. /**
  77656. * @property {array} collideIndexes - An array of tile indexes that collide.
  77657. */
  77658. this.collideIndexes = [];
  77659. /**
  77660. * @property {array} collision - An array of collision data (polylines, etc).
  77661. */
  77662. this.collision = data.collision;
  77663. /**
  77664. * @property {array} images - An array of Tiled Image Layers.
  77665. */
  77666. this.images = data.images;
  77667. /**
  77668. * @property {boolean} enableDebug - If set then console.log is used to dump out useful layer creation debug data.
  77669. */
  77670. this.enableDebug = false;
  77671. /**
  77672. * @property {number} currentLayer - The current layer.
  77673. */
  77674. this.currentLayer = 0;
  77675. /**
  77676. * @property {array} debugMap - Map data used for debug values only.
  77677. */
  77678. this.debugMap = [];
  77679. /**
  77680. * @property {array} _results - Internal var.
  77681. * @private
  77682. */
  77683. this._results = [];
  77684. /**
  77685. * @property {number} _tempA - Internal var.
  77686. * @private
  77687. */
  77688. this._tempA = 0;
  77689. /**
  77690. * @property {number} _tempB - Internal var.
  77691. * @private
  77692. */
  77693. this._tempB = 0;
  77694. };
  77695. /**
  77696. * @constant
  77697. * @type {number}
  77698. */
  77699. Phaser.Tilemap.CSV = 0;
  77700. /**
  77701. * @constant
  77702. * @type {number}
  77703. */
  77704. Phaser.Tilemap.TILED_JSON = 1;
  77705. /**
  77706. * @constant
  77707. * @type {number}
  77708. */
  77709. Phaser.Tilemap.NORTH = 0;
  77710. /**
  77711. * @constant
  77712. * @type {number}
  77713. */
  77714. Phaser.Tilemap.EAST = 1;
  77715. /**
  77716. * @constant
  77717. * @type {number}
  77718. */
  77719. Phaser.Tilemap.SOUTH = 2;
  77720. /**
  77721. * @constant
  77722. * @type {number}
  77723. */
  77724. Phaser.Tilemap.WEST = 3;
  77725. Phaser.Tilemap.prototype = {
  77726. /**
  77727. * Creates an empty map of the given dimensions and one blank layer. If layers already exist they are erased.
  77728. *
  77729. * @method Phaser.Tilemap#create
  77730. * @param {string} name - The name of the default layer of the map.
  77731. * @param {number} width - The width of the map in tiles.
  77732. * @param {number} height - The height of the map in tiles.
  77733. * @param {number} tileWidth - The width of the tiles the map uses for calculations.
  77734. * @param {number} tileHeight - The height of the tiles the map uses for calculations.
  77735. * @param {Phaser.Group} [group] - Optional Group to add the layer to. If not specified it will be added to the World group.
  77736. * @return {Phaser.TilemapLayer} The TilemapLayer object. This is an extension of Phaser.Image and can be moved around the display list accordingly.
  77737. */
  77738. create: function (name, width, height, tileWidth, tileHeight, group) {
  77739. if (group === undefined) { group = this.game.world; }
  77740. this.width = width;
  77741. this.height = height;
  77742. this.setTileSize(tileWidth, tileHeight);
  77743. this.layers.length = 0;
  77744. return this.createBlankLayer(name, width, height, tileWidth, tileHeight, group);
  77745. },
  77746. /**
  77747. * Sets the base tile size for the map.
  77748. *
  77749. * @method Phaser.Tilemap#setTileSize
  77750. * @param {number} tileWidth - The width of the tiles the map uses for calculations.
  77751. * @param {number} tileHeight - The height of the tiles the map uses for calculations.
  77752. */
  77753. setTileSize: function (tileWidth, tileHeight) {
  77754. this.tileWidth = tileWidth;
  77755. this.tileHeight = tileHeight;
  77756. this.widthInPixels = this.width * tileWidth;
  77757. this.heightInPixels = this.height * tileHeight;
  77758. },
  77759. /**
  77760. * Adds an image to the map to be used as a tileset. A single map may use multiple tilesets.
  77761. * Note that the tileset name can be found in the JSON file exported from Tiled, or in the Tiled editor.
  77762. *
  77763. * @method Phaser.Tilemap#addTilesetImage
  77764. * @param {string} tileset - The name of the tileset as specified in the map data.
  77765. * @param {string|Phaser.BitmapData} [key] - The key of the Phaser.Cache image used for this tileset.
  77766. * If `undefined` or `null` it will look for an image with a key matching the tileset parameter.
  77767. * You can also pass in a BitmapData which can be used instead of an Image.
  77768. * @param {number} [tileWidth=32] - The width of the tiles in the Tileset Image. If not given it will default to the map.tileWidth value, if that isn't set then 32.
  77769. * @param {number} [tileHeight=32] - The height of the tiles in the Tileset Image. If not given it will default to the map.tileHeight value, if that isn't set then 32.
  77770. * @param {number} [tileMargin=0] - The width of the tiles in the Tileset Image.
  77771. * @param {number} [tileSpacing=0] - The height of the tiles in the Tileset Image.
  77772. * @param {number} [gid=0] - If adding multiple tilesets to a blank/dynamic map, specify the starting GID the set will use here.
  77773. * @return {Phaser.Tileset} Returns the Tileset object that was created or updated, or null if it failed.
  77774. */
  77775. addTilesetImage: function (tileset, key, tileWidth, tileHeight, tileMargin, tileSpacing, gid) {
  77776. if (tileset === undefined) { return null; }
  77777. if (tileWidth === undefined) { tileWidth = this.tileWidth; }
  77778. if (tileHeight === undefined) { tileHeight = this.tileHeight; }
  77779. if (tileMargin === undefined) { tileMargin = 0; }
  77780. if (tileSpacing === undefined) { tileSpacing = 0; }
  77781. if (gid === undefined) { gid = 0; }
  77782. // In-case we're working from a blank map
  77783. if (tileWidth === 0)
  77784. {
  77785. tileWidth = 32;
  77786. }
  77787. if (tileHeight === 0)
  77788. {
  77789. tileHeight = 32;
  77790. }
  77791. var img = null;
  77792. if (key === undefined || key === null)
  77793. {
  77794. key = tileset;
  77795. }
  77796. if (key instanceof Phaser.BitmapData)
  77797. {
  77798. img = key.canvas;
  77799. }
  77800. else
  77801. {
  77802. if (!this.game.cache.checkImageKey(key))
  77803. {
  77804. console.warn('Phaser.Tilemap.addTilesetImage: Invalid image key given: "' + key + '"');
  77805. return null;
  77806. }
  77807. img = this.game.cache.getImage(key);
  77808. }
  77809. var idx = this.getTilesetIndex(tileset);
  77810. if (idx === null && this.format === Phaser.Tilemap.TILED_JSON)
  77811. {
  77812. console.warn('Phaser.Tilemap.addTilesetImage: No data found in the JSON matching the tileset name: "' + tileset + '"');
  77813. return null;
  77814. }
  77815. if (this.tilesets[idx])
  77816. {
  77817. this.tilesets[idx].setImage(img);
  77818. return this.tilesets[idx];
  77819. }
  77820. else
  77821. {
  77822. var newSet = new Phaser.Tileset(tileset, gid, tileWidth, tileHeight, tileMargin, tileSpacing, {});
  77823. newSet.setImage(img);
  77824. this.tilesets.push(newSet);
  77825. var i = this.tilesets.length - 1;
  77826. var x = tileMargin;
  77827. var y = tileMargin;
  77828. var count = 0;
  77829. var countX = 0;
  77830. var countY = 0;
  77831. for (var t = gid; t < gid + newSet.total; t++)
  77832. {
  77833. this.tiles[t] = [x, y, i];
  77834. x += tileWidth + tileSpacing;
  77835. count++;
  77836. if (count === newSet.total)
  77837. {
  77838. break;
  77839. }
  77840. countX++;
  77841. if (countX === newSet.columns)
  77842. {
  77843. x = tileMargin;
  77844. y += tileHeight + tileSpacing;
  77845. countX = 0;
  77846. countY++;
  77847. if (countY === newSet.rows)
  77848. {
  77849. break;
  77850. }
  77851. }
  77852. }
  77853. return newSet;
  77854. }
  77855. return null;
  77856. },
  77857. /**
  77858. * Creates a Sprite for every object matching the given gid in the map data. You can optionally specify the group that the Sprite will be created in. If none is
  77859. * given it will be created in the World. All properties from the map data objectgroup are copied across to the Sprite, so you can use this as an easy way to
  77860. * configure Sprite properties from within the map editor. For example giving an object a property of alpha: 0.5 in the map editor will duplicate that when the
  77861. * Sprite is created. You could also give it a value like: body.velocity.x: 100 to set it moving automatically.
  77862. *
  77863. * @method Phaser.Tilemap#createFromObjects
  77864. * @param {string} name - The name of the Object Group to create Sprites from.
  77865. * @param {number} gid - The layer array index value, or if a string is given the layer name within the map data.
  77866. * @param {string} key - The Game.cache key of the image that this Sprite will use.
  77867. * @param {number|string} [frame] - If the Sprite image contains multiple frames you can specify which one to use here.
  77868. * @param {boolean} [exists=true] - The default exists state of the Sprite.
  77869. * @param {boolean} [autoCull=false] - The default autoCull state of the Sprite. Sprites that are autoCulled are culled from the camera if out of its range.
  77870. * @param {Phaser.Group} [group=Phaser.World] - Group to add the Sprite to. If not specified it will be added to the World group.
  77871. * @param {object} [CustomClass=Phaser.Sprite] - If you wish to create your own class, rather than Phaser.Sprite, pass the class here. Your class must extend Phaser.Sprite and have the same constructor parameters.
  77872. * @param {boolean} [adjustY=true] - By default the Tiled map editor uses a bottom-left coordinate system. Phaser uses top-left. So most objects will appear too low down. This parameter moves them up by their height.
  77873. */
  77874. createFromObjects: function (name, gid, key, frame, exists, autoCull, group, CustomClass, adjustY) {
  77875. if (exists === undefined) { exists = true; }
  77876. if (autoCull === undefined) { autoCull = false; }
  77877. if (group === undefined) { group = this.game.world; }
  77878. if (CustomClass === undefined) { CustomClass = Phaser.Sprite; }
  77879. if (adjustY === undefined) { adjustY = true; }
  77880. if (!this.objects[name])
  77881. {
  77882. console.warn('Tilemap.createFromObjects: Invalid objectgroup name given: ' + name);
  77883. return;
  77884. }
  77885. for (var i = 0; i < this.objects[name].length; i++)
  77886. {
  77887. var found = false;
  77888. var obj = this.objects[name][i];
  77889. if (obj.gid !== undefined && typeof gid === 'number' && obj.gid === gid)
  77890. {
  77891. found = true;
  77892. }
  77893. else if (obj.id !== undefined && typeof gid === 'number' && obj.id === gid)
  77894. {
  77895. found = true;
  77896. }
  77897. else if (obj.name !== undefined && typeof gid === 'string' && obj.name === gid)
  77898. {
  77899. found = true;
  77900. }
  77901. if (found)
  77902. {
  77903. var sprite = new CustomClass(this.game, parseFloat(obj.x, 10), parseFloat(obj.y, 10), key, frame);
  77904. sprite.name = obj.name;
  77905. sprite.visible = obj.visible;
  77906. sprite.autoCull = autoCull;
  77907. sprite.exists = exists;
  77908. if (obj.width)
  77909. {
  77910. sprite.width = obj.width;
  77911. }
  77912. if (obj.height)
  77913. {
  77914. sprite.height = obj.height;
  77915. }
  77916. if (obj.rotation)
  77917. {
  77918. sprite.angle = obj.rotation;
  77919. }
  77920. if (adjustY)
  77921. {
  77922. sprite.y -= sprite.height;
  77923. }
  77924. group.add(sprite);
  77925. for (var property in obj.properties)
  77926. {
  77927. group.set(sprite, property, obj.properties[property], false, false, 0, true);
  77928. }
  77929. }
  77930. }
  77931. },
  77932. /**
  77933. * Creates a Sprite for every object matching the given tile indexes in the map data.
  77934. * You can specify the group that the Sprite will be created in. If none is given it will be created in the World.
  77935. * You can optional specify if the tile will be replaced with another after the Sprite is created. This is useful if you want to lay down special
  77936. * tiles in a level that are converted to Sprites, but want to replace the tile itself with a floor tile or similar once converted.
  77937. *
  77938. * @method Phaser.Tilemap#createFromTiles
  77939. * @param {integer|Array} tiles - The tile index, or array of indexes, to create Sprites from.
  77940. * @param {integer|Array} replacements - The tile index, or array of indexes, to change a converted tile to. Set to `null` to not change.
  77941. * @param {string} key - The Game.cache key of the image that this Sprite will use.
  77942. * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on.
  77943. * @param {Phaser.Group} [group=Phaser.World] - Group to add the Sprite to. If not specified it will be added to the World group.
  77944. * @param {object} [properties] - An object that contains the default properties for your newly created Sprite. This object will be iterated and any matching Sprite property will be set.
  77945. * @return {integer} The number of Sprites that were created.
  77946. */
  77947. createFromTiles: function (tiles, replacements, key, layer, group, properties) {
  77948. if (typeof tiles === 'number') { tiles = [tiles]; }
  77949. if (replacements === undefined || replacements === null)
  77950. {
  77951. replacements = [];
  77952. }
  77953. else if (typeof replacements === 'number')
  77954. {
  77955. replacements = [replacements];
  77956. }
  77957. layer = this.getLayer(layer);
  77958. if (group === undefined) { group = this.game.world; }
  77959. if (properties === undefined) { properties = {}; }
  77960. if (properties.customClass === undefined)
  77961. {
  77962. properties.customClass = Phaser.Sprite;
  77963. }
  77964. if (properties.adjustY === undefined)
  77965. {
  77966. properties.adjustY = true;
  77967. }
  77968. var lw = this.layers[layer].width;
  77969. var lh = this.layers[layer].height;
  77970. this.copy(0, 0, lw, lh, layer);
  77971. if (this._results.length < 2)
  77972. {
  77973. return 0;
  77974. }
  77975. var total = 0;
  77976. var sprite;
  77977. for (var i = 1, len = this._results.length; i < len; i++)
  77978. {
  77979. if (tiles.indexOf(this._results[i].index) !== -1)
  77980. {
  77981. sprite = new properties.customClass(this.game, this._results[i].worldX, this._results[i].worldY, key);
  77982. for (var property in properties)
  77983. {
  77984. sprite[property] = properties[property];
  77985. }
  77986. group.add(sprite);
  77987. total++;
  77988. }
  77989. }
  77990. if (replacements.length === 1)
  77991. {
  77992. // Assume 1 replacement for all types of tile given
  77993. for (i = 0; i < tiles.length; i++)
  77994. {
  77995. this.replace(tiles[i], replacements[0], 0, 0, lw, lh, layer);
  77996. }
  77997. }
  77998. else if (replacements.length > 1)
  77999. {
  78000. // Assume 1 for 1 mapping
  78001. for (i = 0; i < tiles.length; i++)
  78002. {
  78003. this.replace(tiles[i], replacements[i], 0, 0, lw, lh, layer);
  78004. }
  78005. }
  78006. return total;
  78007. },
  78008. /**
  78009. * Creates a new TilemapLayer object. By default TilemapLayers are fixed to the camera.
  78010. * The `layer` parameter is important. If you've created your map in Tiled then you can get this by looking in Tiled and looking at the Layer name.
  78011. * Or you can open the JSON file it exports and look at the layers[].name value. Either way it must match.
  78012. * If you wish to create a blank layer to put your own tiles on then see Tilemap.createBlankLayer.
  78013. *
  78014. * @method Phaser.Tilemap#createLayer
  78015. * @param {number|string} layer - The layer array index value, or if a string is given the layer name, within the map data that this TilemapLayer represents.
  78016. * @param {number} [width] - The rendered width of the layer, should never be wider than Game.width. If not given it will be set to Game.width.
  78017. * @param {number} [height] - The rendered height of the layer, should never be wider than Game.height. If not given it will be set to Game.height.
  78018. * @param {Phaser.Group} [group] - Optional Group to add the object to. If not specified it will be added to the World group.
  78019. * @return {Phaser.TilemapLayer} The TilemapLayer object. This is an extension of Phaser.Sprite and can be moved around the display list accordingly.
  78020. */
  78021. createLayer: function (layer, width, height, group) {
  78022. // Add Buffer support for the left of the canvas
  78023. if (width === undefined) { width = this.game.width; }
  78024. if (height === undefined) { height = this.game.height; }
  78025. if (group === undefined) { group = this.game.world; }
  78026. var index = layer;
  78027. if (typeof layer === 'string')
  78028. {
  78029. index = this.getLayerIndex(layer);
  78030. }
  78031. if (index === null || index > this.layers.length)
  78032. {
  78033. console.warn('Tilemap.createLayer: Invalid layer ID given: ' + index);
  78034. return;
  78035. }
  78036. // Sort out the display dimensions, so they never render too much, or too little.
  78037. if (width === undefined || width <= 0)
  78038. {
  78039. width = Math.min(this.game.width, this.layers[index].widthInPixels);
  78040. }
  78041. else if (width > this.game.width)
  78042. {
  78043. width = this.game.width;
  78044. }
  78045. if (height === undefined || height <= 0)
  78046. {
  78047. height = Math.min(this.game.height, this.layers[index].heightInPixels);
  78048. }
  78049. else if (height > this.game.height)
  78050. {
  78051. height = this.game.height;
  78052. }
  78053. if (this.enableDebug)
  78054. {
  78055. console.group('Tilemap.createLayer');
  78056. console.log('Name:', this.layers[index].name);
  78057. console.log('Size:', width, 'x', height);
  78058. console.log('Tileset:', this.tilesets[0].name, 'index:', index);
  78059. }
  78060. var rootLayer = group.add(new Phaser.TilemapLayer(this.game, this, index, width, height));
  78061. if (this.enableDebug)
  78062. {
  78063. console.groupEnd();
  78064. }
  78065. return rootLayer;
  78066. },
  78067. /**
  78068. * Creates a new and empty layer on this Tilemap. By default TilemapLayers are fixed to the camera.
  78069. *
  78070. * @method Phaser.Tilemap#createBlankLayer
  78071. * @param {string} name - The name of this layer. Must be unique within the map.
  78072. * @param {number} width - The width of the layer in tiles.
  78073. * @param {number} height - The height of the layer in tiles.
  78074. * @param {number} tileWidth - The width of the tiles the layer uses for calculations.
  78075. * @param {number} tileHeight - The height of the tiles the layer uses for calculations.
  78076. * @param {Phaser.Group} [group] - Optional Group to add the layer to. If not specified it will be added to the World group.
  78077. * @return {Phaser.TilemapLayer} The TilemapLayer object. This is an extension of Phaser.Image and can be moved around the display list accordingly.
  78078. */
  78079. createBlankLayer: function (name, width, height, tileWidth, tileHeight, group) {
  78080. if (group === undefined) { group = this.game.world; }
  78081. if (this.getLayerIndex(name) !== null)
  78082. {
  78083. console.warn('Tilemap.createBlankLayer: Layer with matching name already exists: ' + name);
  78084. return;
  78085. }
  78086. var layer = {
  78087. name: name,
  78088. x: 0,
  78089. y: 0,
  78090. width: width,
  78091. height: height,
  78092. widthInPixels: width * tileWidth,
  78093. heightInPixels: height * tileHeight,
  78094. alpha: 1,
  78095. visible: true,
  78096. properties: {},
  78097. indexes: [],
  78098. callbacks: [],
  78099. bodies: [],
  78100. data: null
  78101. };
  78102. var row;
  78103. var output = [];
  78104. for (var y = 0; y < height; y++)
  78105. {
  78106. row = [];
  78107. for (var x = 0; x < width; x++)
  78108. {
  78109. row.push(new Phaser.Tile(layer, -1, x, y, tileWidth, tileHeight));
  78110. }
  78111. output.push(row);
  78112. }
  78113. layer.data = output;
  78114. this.layers.push(layer);
  78115. this.currentLayer = this.layers.length - 1;
  78116. var w = layer.widthInPixels;
  78117. var h = layer.heightInPixels;
  78118. if (w > this.game.width)
  78119. {
  78120. w = this.game.width;
  78121. }
  78122. if (h > this.game.height)
  78123. {
  78124. h = this.game.height;
  78125. }
  78126. var output = new Phaser.TilemapLayer(this.game, this, this.layers.length - 1, w, h);
  78127. output.name = name;
  78128. return group.add(output);
  78129. },
  78130. /**
  78131. * Gets the layer index based on the layers name.
  78132. *
  78133. * @method Phaser.Tilemap#getIndex
  78134. * @protected
  78135. * @param {array} location - The local array to search.
  78136. * @param {string} name - The name of the array element to get.
  78137. * @return {number} The index of the element in the array, or null if not found.
  78138. */
  78139. getIndex: function (location, name) {
  78140. for (var i = 0; i < location.length; i++)
  78141. {
  78142. if (location[i].name === name)
  78143. {
  78144. return i;
  78145. }
  78146. }
  78147. return null;
  78148. },
  78149. /**
  78150. * Gets the layer index based on its name.
  78151. *
  78152. * @method Phaser.Tilemap#getLayerIndex
  78153. * @param {string} name - The name of the layer to get.
  78154. * @return {number} The index of the layer in this tilemap, or null if not found.
  78155. */
  78156. getLayerIndex: function (name) {
  78157. return this.getIndex(this.layers, name);
  78158. },
  78159. /**
  78160. * Gets the tileset index based on its name.
  78161. *
  78162. * @method Phaser.Tilemap#getTilesetIndex
  78163. * @param {string} name - The name of the tileset to get.
  78164. * @return {number} The index of the tileset in this tilemap, or null if not found.
  78165. */
  78166. getTilesetIndex: function (name) {
  78167. return this.getIndex(this.tilesets, name);
  78168. },
  78169. /**
  78170. * Gets the image index based on its name.
  78171. *
  78172. * @method Phaser.Tilemap#getImageIndex
  78173. * @param {string} name - The name of the image to get.
  78174. * @return {number} The index of the image in this tilemap, or null if not found.
  78175. */
  78176. getImageIndex: function (name) {
  78177. return this.getIndex(this.images, name);
  78178. },
  78179. /**
  78180. * Sets a global collision callback for the given tile index within the layer. This will affect all tiles on this layer that have the same index.
  78181. * If a callback is already set for the tile index it will be replaced. Set the callback to null to remove it.
  78182. * If you want to set a callback for a tile at a specific location on the map then see setTileLocationCallback.
  78183. *
  78184. * @method Phaser.Tilemap#setTileIndexCallback
  78185. * @param {number|array} indexes - Either a single tile index, or an array of tile indexes to have a collision callback set for.
  78186. * @param {function} callback - The callback that will be invoked when the tile is collided with.
  78187. * @param {object} callbackContext - The context under which the callback is called.
  78188. * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. If not given will default to this.currentLayer.
  78189. */
  78190. setTileIndexCallback: function (indexes, callback, callbackContext, layer) {
  78191. layer = this.getLayer(layer);
  78192. if (typeof indexes === 'number')
  78193. {
  78194. // This may seem a bit wasteful, because it will cause empty array elements to be created, but the look-up cost is much
  78195. // less than having to iterate through the callbacks array hunting down tile indexes each frame, so I'll take the small memory hit.
  78196. this.layers[layer].callbacks[indexes] = { callback: callback, callbackContext: callbackContext };
  78197. }
  78198. else
  78199. {
  78200. for (var i = 0, len = indexes.length; i < len; i++)
  78201. {
  78202. this.layers[layer].callbacks[indexes[i]] = { callback: callback, callbackContext: callbackContext };
  78203. }
  78204. }
  78205. },
  78206. /**
  78207. * Sets a global collision callback for the given map location within the layer. This will affect all tiles on this layer found in the given area.
  78208. * If a callback is already set for the tile index it will be replaced. Set the callback to null to remove it.
  78209. * If you want to set a callback for a tile at a specific location on the map then see setTileLocationCallback.
  78210. *
  78211. * @method Phaser.Tilemap#setTileLocationCallback
  78212. * @param {number} x - X position of the top left of the area to copy (given in tiles, not pixels)
  78213. * @param {number} y - Y position of the top left of the area to copy (given in tiles, not pixels)
  78214. * @param {number} width - The width of the area to copy (given in tiles, not pixels)
  78215. * @param {number} height - The height of the area to copy (given in tiles, not pixels)
  78216. * @param {function} callback - The callback that will be invoked when the tile is collided with.
  78217. * @param {object} callbackContext - The context under which the callback is called.
  78218. * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. If not given will default to this.currentLayer.
  78219. */
  78220. setTileLocationCallback: function (x, y, width, height, callback, callbackContext, layer) {
  78221. layer = this.getLayer(layer);
  78222. this.copy(x, y, width, height, layer);
  78223. if (this._results.length < 2)
  78224. {
  78225. return;
  78226. }
  78227. for (var i = 1; i < this._results.length; i++)
  78228. {
  78229. this._results[i].setCollisionCallback(callback, callbackContext);
  78230. }
  78231. },
  78232. /**
  78233. * Sets collision the given tile or tiles. You can pass in either a single numeric index or an array of indexes: [ 2, 3, 15, 20].
  78234. * The `collides` parameter controls if collision will be enabled (true) or disabled (false).
  78235. *
  78236. * @method Phaser.Tilemap#setCollision
  78237. * @param {number|array} indexes - Either a single tile index, or an array of tile IDs to be checked for collision.
  78238. * @param {boolean} [collides=true] - If true it will enable collision. If false it will clear collision.
  78239. * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. If not given will default to this.currentLayer.
  78240. * @param {boolean} [recalculate=true] - Recalculates the tile faces after the update.
  78241. */
  78242. setCollision: function (indexes, collides, layer, recalculate) {
  78243. if (collides === undefined) { collides = true; }
  78244. if (recalculate === undefined) { recalculate = true; }
  78245. layer = this.getLayer(layer);
  78246. if (typeof indexes === 'number')
  78247. {
  78248. return this.setCollisionByIndex(indexes, collides, layer, true);
  78249. }
  78250. else if (Array.isArray(indexes))
  78251. {
  78252. // Collide all of the IDs given in the indexes array
  78253. for (var i = 0; i < indexes.length; i++)
  78254. {
  78255. this.setCollisionByIndex(indexes[i], collides, layer, false);
  78256. }
  78257. if (recalculate)
  78258. {
  78259. // Now re-calculate interesting faces
  78260. this.calculateFaces(layer);
  78261. }
  78262. }
  78263. },
  78264. /**
  78265. * Sets collision on a range of tiles where the tile IDs increment sequentially.
  78266. * Calling this with a start value of 10 and a stop value of 14 would set collision for tiles 10, 11, 12, 13 and 14.
  78267. * The `collides` parameter controls if collision will be enabled (true) or disabled (false).
  78268. *
  78269. * @method Phaser.Tilemap#setCollisionBetween
  78270. * @param {number} start - The first index of the tile to be set for collision.
  78271. * @param {number} stop - The last index of the tile to be set for collision.
  78272. * @param {boolean} [collides=true] - If true it will enable collision. If false it will clear collision.
  78273. * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. If not given will default to this.currentLayer.
  78274. * @param {boolean} [recalculate=true] - Recalculates the tile faces after the update.
  78275. */
  78276. setCollisionBetween: function (start, stop, collides, layer, recalculate) {
  78277. if (collides === undefined) { collides = true; }
  78278. if (recalculate === undefined) { recalculate = true; }
  78279. layer = this.getLayer(layer);
  78280. if (start > stop)
  78281. {
  78282. return;
  78283. }
  78284. for (var index = start; index <= stop; index++)
  78285. {
  78286. this.setCollisionByIndex(index, collides, layer, false);
  78287. }
  78288. if (recalculate)
  78289. {
  78290. // Now re-calculate interesting faces
  78291. this.calculateFaces(layer);
  78292. }
  78293. },
  78294. /**
  78295. * Sets collision on all tiles in the given layer, except for the IDs of those in the given array.
  78296. * The `collides` parameter controls if collision will be enabled (true) or disabled (false).
  78297. *
  78298. * @method Phaser.Tilemap#setCollisionByExclusion
  78299. * @param {array} indexes - An array of the tile IDs to not be counted for collision.
  78300. * @param {boolean} [collides=true] - If true it will enable collision. If false it will clear collision.
  78301. * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. If not given will default to this.currentLayer.
  78302. * @param {boolean} [recalculate=true] - Recalculates the tile faces after the update.
  78303. */
  78304. setCollisionByExclusion: function (indexes, collides, layer, recalculate) {
  78305. if (collides === undefined) { collides = true; }
  78306. if (recalculate === undefined) { recalculate = true; }
  78307. layer = this.getLayer(layer);
  78308. // Collide everything, except the IDs given in the indexes array
  78309. for (var i = 0, len = this.tiles.length; i < len; i++)
  78310. {
  78311. if (indexes.indexOf(i) === -1)
  78312. {
  78313. this.setCollisionByIndex(i, collides, layer, false);
  78314. }
  78315. }
  78316. if (recalculate)
  78317. {
  78318. // Now re-calculate interesting faces
  78319. this.calculateFaces(layer);
  78320. }
  78321. },
  78322. /**
  78323. * Sets collision values on a tile in the set.
  78324. * You shouldn't usually call this method directly, instead use setCollision, setCollisionBetween or setCollisionByExclusion.
  78325. *
  78326. * @method Phaser.Tilemap#setCollisionByIndex
  78327. * @protected
  78328. * @param {number} index - The index of the tile on the layer.
  78329. * @param {boolean} [collides=true] - If true it will enable collision on the tile. If false it will clear collision values from the tile.
  78330. * @param {number} [layer] - The layer to operate on. If not given will default to this.currentLayer.
  78331. * @param {boolean} [recalculate=true] - Recalculates the tile faces after the update.
  78332. */
  78333. setCollisionByIndex: function (index, collides, layer, recalculate) {
  78334. if (collides === undefined) { collides = true; }
  78335. if (layer === undefined) { layer = this.currentLayer; }
  78336. if (recalculate === undefined) { recalculate = true; }
  78337. if (collides)
  78338. {
  78339. this.collideIndexes.push(index);
  78340. }
  78341. else
  78342. {
  78343. var i = this.collideIndexes.indexOf(index);
  78344. if (i > -1)
  78345. {
  78346. this.collideIndexes.splice(i, 1);
  78347. }
  78348. }
  78349. for (var y = 0; y < this.layers[layer].height; y++)
  78350. {
  78351. for (var x = 0; x < this.layers[layer].width; x++)
  78352. {
  78353. var tile = this.layers[layer].data[y][x];
  78354. if (tile && tile.index === index)
  78355. {
  78356. if (collides)
  78357. {
  78358. tile.setCollision(true, true, true, true);
  78359. }
  78360. else
  78361. {
  78362. tile.resetCollision();
  78363. }
  78364. tile.faceTop = collides;
  78365. tile.faceBottom = collides;
  78366. tile.faceLeft = collides;
  78367. tile.faceRight = collides;
  78368. }
  78369. }
  78370. }
  78371. if (recalculate)
  78372. {
  78373. // Now re-calculate interesting faces
  78374. this.calculateFaces(layer);
  78375. }
  78376. return layer;
  78377. },
  78378. /**
  78379. * Gets the TilemapLayer index as used in the setCollision calls.
  78380. *
  78381. * @method Phaser.Tilemap#getLayer
  78382. * @protected
  78383. * @param {number|string|Phaser.TilemapLayer} layer - The layer to operate on. If not given will default to this.currentLayer.
  78384. * @return {number} The TilemapLayer index.
  78385. */
  78386. getLayer: function (layer) {
  78387. if (layer === undefined)
  78388. {
  78389. layer = this.currentLayer;
  78390. }
  78391. else if (typeof layer === 'string')
  78392. {
  78393. layer = this.getLayerIndex(layer);
  78394. }
  78395. else if (layer instanceof Phaser.TilemapLayer)
  78396. {
  78397. layer = layer.index;
  78398. }
  78399. return layer;
  78400. },
  78401. /**
  78402. * Turn off/on the recalculation of faces for tile or collision updates.
  78403. * `setPreventRecalculate(true)` puts recalculation on hold while `setPreventRecalculate(false)` recalculates all the changed layers.
  78404. *
  78405. * @method Phaser.Tilemap#setPreventRecalculate
  78406. * @param {boolean} value - If true it will put the recalculation on hold.
  78407. */
  78408. setPreventRecalculate: function (value) {
  78409. if (value === true && this.preventingRecalculate !== true)
  78410. {
  78411. this.preventingRecalculate = true;
  78412. this.needToRecalculate = {};
  78413. }
  78414. if (value === false && this.preventingRecalculate === true)
  78415. {
  78416. this.preventingRecalculate = false;
  78417. for (var i in this.needToRecalculate)
  78418. {
  78419. this.calculateFaces(i);
  78420. }
  78421. this.needToRecalculate = false;
  78422. }
  78423. },
  78424. /**
  78425. * Internal function.
  78426. *
  78427. * @method Phaser.Tilemap#calculateFaces
  78428. * @protected
  78429. * @param {number} layer - The index of the TilemapLayer to operate on.
  78430. */
  78431. calculateFaces: function (layer) {
  78432. if (this.preventingRecalculate)
  78433. {
  78434. this.needToRecalculate[layer] = true;
  78435. return;
  78436. }
  78437. var above = null;
  78438. var below = null;
  78439. var left = null;
  78440. var right = null;
  78441. for (var y = 0, h = this.layers[layer].height; y < h; y++)
  78442. {
  78443. for (var x = 0, w = this.layers[layer].width; x < w; x++)
  78444. {
  78445. var tile = this.layers[layer].data[y][x];
  78446. if (tile)
  78447. {
  78448. above = this.getTileAbove(layer, x, y);
  78449. below = this.getTileBelow(layer, x, y);
  78450. left = this.getTileLeft(layer, x, y);
  78451. right = this.getTileRight(layer, x, y);
  78452. if (tile.collides)
  78453. {
  78454. tile.faceTop = true;
  78455. tile.faceBottom = true;
  78456. tile.faceLeft = true;
  78457. tile.faceRight = true;
  78458. }
  78459. if (above && above.collides)
  78460. {
  78461. // There is a tile above this one that also collides, so the top of this tile is no longer interesting
  78462. tile.faceTop = false;
  78463. }
  78464. if (below && below.collides)
  78465. {
  78466. // There is a tile below this one that also collides, so the bottom of this tile is no longer interesting
  78467. tile.faceBottom = false;
  78468. }
  78469. if (left && left.collides)
  78470. {
  78471. // There is a tile left this one that also collides, so the left of this tile is no longer interesting
  78472. tile.faceLeft = false;
  78473. }
  78474. if (right && right.collides)
  78475. {
  78476. // There is a tile right this one that also collides, so the right of this tile is no longer interesting
  78477. tile.faceRight = false;
  78478. }
  78479. }
  78480. }
  78481. }
  78482. },
  78483. /**
  78484. * Gets the tile above the tile coordinates given.
  78485. * Mostly used as an internal function by calculateFaces.
  78486. *
  78487. * @method Phaser.Tilemap#getTileAbove
  78488. * @param {number} layer - The local layer index to get the tile from. Can be determined by Tilemap.getLayer().
  78489. * @param {number} x - The x coordinate to get the tile from. In tiles, not pixels.
  78490. * @param {number} y - The y coordinate to get the tile from. In tiles, not pixels.
  78491. */
  78492. getTileAbove: function (layer, x, y) {
  78493. if (y > 0)
  78494. {
  78495. return this.layers[layer].data[y - 1][x];
  78496. }
  78497. return null;
  78498. },
  78499. /**
  78500. * Gets the tile below the tile coordinates given.
  78501. * Mostly used as an internal function by calculateFaces.
  78502. *
  78503. * @method Phaser.Tilemap#getTileBelow
  78504. * @param {number} layer - The local layer index to get the tile from. Can be determined by Tilemap.getLayer().
  78505. * @param {number} x - The x coordinate to get the tile from. In tiles, not pixels.
  78506. * @param {number} y - The y coordinate to get the tile from. In tiles, not pixels.
  78507. */
  78508. getTileBelow: function (layer, x, y) {
  78509. if (y < this.layers[layer].height - 1)
  78510. {
  78511. return this.layers[layer].data[y + 1][x];
  78512. }
  78513. return null;
  78514. },
  78515. /**
  78516. * Gets the tile to the left of the tile coordinates given.
  78517. * Mostly used as an internal function by calculateFaces.
  78518. *
  78519. * @method Phaser.Tilemap#getTileLeft
  78520. * @param {number} layer - The local layer index to get the tile from. Can be determined by Tilemap.getLayer().
  78521. * @param {number} x - The x coordinate to get the tile from. In tiles, not pixels.
  78522. * @param {number} y - The y coordinate to get the tile from. In tiles, not pixels.
  78523. */
  78524. getTileLeft: function (layer, x, y) {
  78525. if (x > 0)
  78526. {
  78527. return this.layers[layer].data[y][x - 1];
  78528. }
  78529. return null;
  78530. },
  78531. /**
  78532. * Gets the tile to the right of the tile coordinates given.
  78533. * Mostly used as an internal function by calculateFaces.
  78534. *
  78535. * @method Phaser.Tilemap#getTileRight
  78536. * @param {number} layer - The local layer index to get the tile from. Can be determined by Tilemap.getLayer().
  78537. * @param {number} x - The x coordinate to get the tile from. In tiles, not pixels.
  78538. * @param {number} y - The y coordinate to get the tile from. In tiles, not pixels.
  78539. */
  78540. getTileRight: function (layer, x, y) {
  78541. if (x < this.layers[layer].width - 1)
  78542. {
  78543. return this.layers[layer].data[y][x + 1];
  78544. }
  78545. return null;
  78546. },
  78547. /**
  78548. * Sets the current layer to the given index.
  78549. *
  78550. * @method Phaser.Tilemap#setLayer
  78551. * @param {number|string|Phaser.TilemapLayer} layer - The layer to set as current.
  78552. */
  78553. setLayer: function (layer) {
  78554. layer = this.getLayer(layer);
  78555. if (this.layers[layer])
  78556. {
  78557. this.currentLayer = layer;
  78558. }
  78559. },
  78560. /**
  78561. * Checks if there is a tile at the given location.
  78562. *
  78563. * @method Phaser.Tilemap#hasTile
  78564. * @param {number} x - X position to check if a tile exists at (given in tile units, not pixels)
  78565. * @param {number} y - Y position to check if a tile exists at (given in tile units, not pixels)
  78566. * @param {number|string|Phaser.TilemapLayer} layer - The layer to set as current.
  78567. * @return {boolean} True if there is a tile at the given location, otherwise false.
  78568. */
  78569. hasTile: function (x, y, layer) {
  78570. layer = this.getLayer(layer);
  78571. if (this.layers[layer].data[y] === undefined || this.layers[layer].data[y][x] === undefined)
  78572. {
  78573. return false;
  78574. }
  78575. return (this.layers[layer].data[y][x].index > -1);
  78576. },
  78577. /**
  78578. * Removes the tile located at the given coordinates and updates the collision data.
  78579. *
  78580. * @method Phaser.Tilemap#removeTile
  78581. * @param {number} x - X position to place the tile (given in tile units, not pixels)
  78582. * @param {number} y - Y position to place the tile (given in tile units, not pixels)
  78583. * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to modify.
  78584. * @return {Phaser.Tile} The Tile object that was removed from this map.
  78585. */
  78586. removeTile: function (x, y, layer) {
  78587. layer = this.getLayer(layer);
  78588. if (x >= 0 && x < this.layers[layer].width && y >= 0 && y < this.layers[layer].height)
  78589. {
  78590. if (this.hasTile(x, y, layer))
  78591. {
  78592. var tile = this.layers[layer].data[y][x];
  78593. this.layers[layer].data[y][x] = new Phaser.Tile(this.layers[layer], -1, x, y, this.tileWidth, this.tileHeight);
  78594. this.layers[layer].dirty = true;
  78595. this.calculateFaces(layer);
  78596. return tile;
  78597. }
  78598. }
  78599. },
  78600. /**
  78601. * Removes the tile located at the given coordinates and updates the collision data. The coordinates are given in pixel values.
  78602. *
  78603. * @method Phaser.Tilemap#removeTileWorldXY
  78604. * @param {number} x - X position to insert the tile (given in pixels)
  78605. * @param {number} y - Y position to insert the tile (given in pixels)
  78606. * @param {number} tileWidth - The width of the tile in pixels.
  78607. * @param {number} tileHeight - The height of the tile in pixels.
  78608. * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to modify.
  78609. * @return {Phaser.Tile} The Tile object that was removed from this map.
  78610. */
  78611. removeTileWorldXY: function (x, y, tileWidth, tileHeight, layer) {
  78612. layer = this.getLayer(layer);
  78613. x = this.game.math.snapToFloor(x, tileWidth) / tileWidth;
  78614. y = this.game.math.snapToFloor(y, tileHeight) / tileHeight;
  78615. return this.removeTile(x, y, layer);
  78616. },
  78617. /**
  78618. * Puts a tile of the given index value at the coordinate specified.
  78619. * If you pass `null` as the tile it will pass your call over to Tilemap.removeTile instead.
  78620. *
  78621. * @method Phaser.Tilemap#putTile
  78622. * @param {Phaser.Tile|number|null} tile - The index of this tile to set or a Phaser.Tile object. If null the tile is removed from the map.
  78623. * @param {number} x - X position to place the tile (given in tile units, not pixels)
  78624. * @param {number} y - Y position to place the tile (given in tile units, not pixels)
  78625. * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to modify.
  78626. * @return {Phaser.Tile} The Tile object that was created or added to this map.
  78627. */
  78628. putTile: function (tile, x, y, layer) {
  78629. if (tile === null)
  78630. {
  78631. return this.removeTile(x, y, layer);
  78632. }
  78633. layer = this.getLayer(layer);
  78634. if (x >= 0 && x < this.layers[layer].width && y >= 0 && y < this.layers[layer].height)
  78635. {
  78636. var index;
  78637. if (tile instanceof Phaser.Tile)
  78638. {
  78639. index = tile.index;
  78640. if (this.hasTile(x, y, layer))
  78641. {
  78642. this.layers[layer].data[y][x].copy(tile);
  78643. }
  78644. else
  78645. {
  78646. this.layers[layer].data[y][x] = new Phaser.Tile(layer, index, x, y, tile.width, tile.height);
  78647. }
  78648. }
  78649. else
  78650. {
  78651. index = tile;
  78652. if (this.hasTile(x, y, layer))
  78653. {
  78654. this.layers[layer].data[y][x].index = index;
  78655. }
  78656. else
  78657. {
  78658. this.layers[layer].data[y][x] = new Phaser.Tile(this.layers[layer], index, x, y, this.tileWidth, this.tileHeight);
  78659. }
  78660. }
  78661. if (this.collideIndexes.indexOf(index) > -1)
  78662. {
  78663. this.layers[layer].data[y][x].setCollision(true, true, true, true);
  78664. }
  78665. else
  78666. {
  78667. this.layers[layer].data[y][x].resetCollision();
  78668. }
  78669. this.layers[layer].dirty = true;
  78670. this.calculateFaces(layer);
  78671. return this.layers[layer].data[y][x];
  78672. }
  78673. return null;
  78674. },
  78675. /**
  78676. * Puts a tile into the Tilemap layer. The coordinates are given in pixel values.
  78677. *
  78678. * @method Phaser.Tilemap#putTileWorldXY
  78679. * @param {Phaser.Tile|number} tile - The index of this tile to set or a Phaser.Tile object.
  78680. * @param {number} x - X position to insert the tile (given in pixels)
  78681. * @param {number} y - Y position to insert the tile (given in pixels)
  78682. * @param {number} tileWidth - The width of the tile in pixels.
  78683. * @param {number} tileHeight - The height of the tile in pixels.
  78684. * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to modify.
  78685. * @return {Phaser.Tile} The Tile object that was created or added to this map.
  78686. */
  78687. putTileWorldXY: function (tile, x, y, tileWidth, tileHeight, layer) {
  78688. layer = this.getLayer(layer);
  78689. x = this.game.math.snapToFloor(x, tileWidth) / tileWidth;
  78690. y = this.game.math.snapToFloor(y, tileHeight) / tileHeight;
  78691. return this.putTile(tile, x, y, layer);
  78692. },
  78693. /**
  78694. * Searches the entire map layer for the first tile matching the given index, then returns that Phaser.Tile object.
  78695. * If no match is found it returns null.
  78696. * The search starts from the top-left tile and continues horizontally until it hits the end of the row, then it drops down to the next column.
  78697. * If the reverse boolean is true, it scans starting from the bottom-right corner traveling up to the top-left.
  78698. *
  78699. * @method Phaser.Tilemap#searchTileIndex
  78700. * @param {number} index - The tile index value to search for.
  78701. * @param {number} [skip=0] - The number of times to skip a matching tile before returning.
  78702. * @param {number} [reverse=false] - If true it will scan the layer in reverse, starting at the bottom-right. Otherwise it scans from the top-left.
  78703. * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to get the tile from.
  78704. * @return {Phaser.Tile} The first (or n skipped) tile with the matching index.
  78705. */
  78706. searchTileIndex: function (index, skip, reverse, layer) {
  78707. if (skip === undefined) { skip = 0; }
  78708. if (reverse === undefined) { reverse = false; }
  78709. layer = this.getLayer(layer);
  78710. var c = 0;
  78711. if (reverse)
  78712. {
  78713. for (var y = this.layers[layer].height - 1; y >= 0; y--)
  78714. {
  78715. for (var x = this.layers[layer].width - 1; x >= 0; x--)
  78716. {
  78717. if (this.layers[layer].data[y][x].index === index)
  78718. {
  78719. if (c === skip)
  78720. {
  78721. return this.layers[layer].data[y][x];
  78722. }
  78723. else
  78724. {
  78725. c++;
  78726. }
  78727. }
  78728. }
  78729. }
  78730. }
  78731. else
  78732. {
  78733. for (var y = 0; y < this.layers[layer].height; y++)
  78734. {
  78735. for (var x = 0; x < this.layers[layer].width; x++)
  78736. {
  78737. if (this.layers[layer].data[y][x].index === index)
  78738. {
  78739. if (c === skip)
  78740. {
  78741. return this.layers[layer].data[y][x];
  78742. }
  78743. else
  78744. {
  78745. c++;
  78746. }
  78747. }
  78748. }
  78749. }
  78750. }
  78751. return null;
  78752. },
  78753. /**
  78754. * Gets a tile from the Tilemap Layer. The coordinates are given in tile values.
  78755. *
  78756. * @method Phaser.Tilemap#getTile
  78757. * @param {number} x - X position to get the tile from (given in tile units, not pixels)
  78758. * @param {number} y - Y position to get the tile from (given in tile units, not pixels)
  78759. * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to get the tile from.
  78760. * @param {boolean} [nonNull=false] - If true getTile won't return null for empty tiles, but a Tile object with an index of -1.
  78761. * @return {Phaser.Tile} The tile at the given coordinates or null if no tile was found or the coordinates were invalid.
  78762. */
  78763. getTile: function (x, y, layer, nonNull) {
  78764. if (nonNull === undefined) { nonNull = false; }
  78765. layer = this.getLayer(layer);
  78766. if (x >= 0 && x < this.layers[layer].width && y >= 0 && y < this.layers[layer].height)
  78767. {
  78768. if (this.layers[layer].data[y][x].index === -1)
  78769. {
  78770. if (nonNull)
  78771. {
  78772. return this.layers[layer].data[y][x];
  78773. }
  78774. else
  78775. {
  78776. return null;
  78777. }
  78778. }
  78779. else
  78780. {
  78781. return this.layers[layer].data[y][x];
  78782. }
  78783. }
  78784. else
  78785. {
  78786. return null;
  78787. }
  78788. },
  78789. /**
  78790. * Gets a tile from the Tilemap layer. The coordinates are given in pixel values.
  78791. *
  78792. * @method Phaser.Tilemap#getTileWorldXY
  78793. * @param {number} x - X position to get the tile from (given in pixels)
  78794. * @param {number} y - Y position to get the tile from (given in pixels)
  78795. * @param {number} [tileWidth] - The width of the tiles. If not given the map default is used.
  78796. * @param {number} [tileHeight] - The height of the tiles. If not given the map default is used.
  78797. * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to get the tile from.
  78798. * @param {boolean} [nonNull=false] - If true getTile won't return null for empty tiles, but a Tile object with an index of -1.
  78799. * @return {Phaser.Tile} The tile at the given coordinates.
  78800. */
  78801. getTileWorldXY: function (x, y, tileWidth, tileHeight, layer, nonNull) {
  78802. if (tileWidth === undefined) { tileWidth = this.tileWidth; }
  78803. if (tileHeight === undefined) { tileHeight = this.tileHeight; }
  78804. layer = this.getLayer(layer);
  78805. x = this.game.math.snapToFloor(x, tileWidth) / tileWidth;
  78806. y = this.game.math.snapToFloor(y, tileHeight) / tileHeight;
  78807. return this.getTile(x, y, layer, nonNull);
  78808. },
  78809. /**
  78810. * Copies all of the tiles in the given rectangular block into the tilemap data buffer.
  78811. *
  78812. * @method Phaser.Tilemap#copy
  78813. * @param {integer} x - X position of the top left of the area to copy (given in tiles, not pixels)
  78814. * @param {integer} y - Y position of the top left of the area to copy (given in tiles, not pixels)
  78815. * @param {integer} width - The width of the area to copy (given in tiles, not pixels)
  78816. * @param {integer} height - The height of the area to copy (given in tiles, not pixels)
  78817. * @param {integer|string|Phaser.TilemapLayer} [layer] - The layer to copy the tiles from.
  78818. * @return {array} An array of the tiles that were copied.
  78819. */
  78820. copy: function (x, y, width, height, layer) {
  78821. layer = this.getLayer(layer);
  78822. if (!this.layers[layer])
  78823. {
  78824. this._results.length = 0;
  78825. return;
  78826. }
  78827. if (x === undefined) { x = 0; }
  78828. if (y === undefined) { y = 0; }
  78829. if (width === undefined) { width = this.layers[layer].width; }
  78830. if (height === undefined) { height = this.layers[layer].height; }
  78831. if (x < 0)
  78832. {
  78833. x = 0;
  78834. }
  78835. if (y < 0)
  78836. {
  78837. y = 0;
  78838. }
  78839. if (width > this.layers[layer].width)
  78840. {
  78841. width = this.layers[layer].width;
  78842. }
  78843. if (height > this.layers[layer].height)
  78844. {
  78845. height = this.layers[layer].height;
  78846. }
  78847. this._results.length = 0;
  78848. this._results.push({ x: x, y: y, width: width, height: height, layer: layer });
  78849. for (var ty = y; ty < y + height; ty++)
  78850. {
  78851. for (var tx = x; tx < x + width; tx++)
  78852. {
  78853. this._results.push(this.layers[layer].data[ty][tx]);
  78854. }
  78855. }
  78856. return this._results;
  78857. },
  78858. /**
  78859. * Pastes a previously copied block of tile data into the given x/y coordinates. Data should have been prepared with Tilemap.copy.
  78860. *
  78861. * @method Phaser.Tilemap#paste
  78862. * @param {number} x - X position of the top left of the area to paste to (given in tiles, not pixels)
  78863. * @param {number} y - Y position of the top left of the area to paste to (given in tiles, not pixels)
  78864. * @param {array} tileblock - The block of tiles to paste.
  78865. * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to paste the tiles into.
  78866. */
  78867. paste: function (x, y, tileblock, layer) {
  78868. if (x === undefined) { x = 0; }
  78869. if (y === undefined) { y = 0; }
  78870. layer = this.getLayer(layer);
  78871. if (!tileblock || tileblock.length < 2)
  78872. {
  78873. return;
  78874. }
  78875. // Find out the difference between tileblock[1].x/y and x/y and use it as an offset, as it's the top left of the block to paste
  78876. var diffX = x - tileblock[1].x;
  78877. var diffY = y - tileblock[1].y;
  78878. for (var i = 1; i < tileblock.length; i++)
  78879. {
  78880. this.layers[layer].data[ diffY + tileblock[i].y ][ diffX + tileblock[i].x ].copy(tileblock[i]);
  78881. }
  78882. this.layers[layer].dirty = true;
  78883. this.calculateFaces(layer);
  78884. },
  78885. /**
  78886. * Scans the given area for tiles with an index matching tileA and swaps them with tileB.
  78887. *
  78888. * @method Phaser.Tilemap#swap
  78889. * @param {number} tileA - First tile index.
  78890. * @param {number} tileB - Second tile index.
  78891. * @param {number} x - X position of the top left of the area to operate one, given in tiles, not pixels.
  78892. * @param {number} y - Y position of the top left of the area to operate one, given in tiles, not pixels.
  78893. * @param {number} width - The width in tiles of the area to operate on.
  78894. * @param {number} height - The height in tiles of the area to operate on.
  78895. * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on.
  78896. */
  78897. swap: function (tileA, tileB, x, y, width, height, layer) {
  78898. layer = this.getLayer(layer);
  78899. this.copy(x, y, width, height, layer);
  78900. if (this._results.length < 2)
  78901. {
  78902. return;
  78903. }
  78904. this._tempA = tileA;
  78905. this._tempB = tileB;
  78906. this._results.forEach(this.swapHandler, this);
  78907. this.paste(x, y, this._results, layer);
  78908. },
  78909. /**
  78910. * Internal function that handles the swapping of tiles.
  78911. *
  78912. * @method Phaser.Tilemap#swapHandler
  78913. * @private
  78914. * @param {number} value
  78915. */
  78916. swapHandler: function (value) {
  78917. if (value.index === this._tempA)
  78918. {
  78919. // Swap A with B
  78920. value.index = this._tempB;
  78921. }
  78922. else if (value.index === this._tempB)
  78923. {
  78924. // Swap B with A
  78925. value.index = this._tempA;
  78926. }
  78927. },
  78928. /**
  78929. * For each tile in the given area defined by x/y and width/height run the given callback.
  78930. *
  78931. * @method Phaser.Tilemap#forEach
  78932. * @param {number} callback - The callback. Each tile in the given area will be passed to this callback as the first and only parameter.
  78933. * @param {number} context - The context under which the callback should be run.
  78934. * @param {number} x - X position of the top left of the area to operate one, given in tiles, not pixels.
  78935. * @param {number} y - Y position of the top left of the area to operate one, given in tiles, not pixels.
  78936. * @param {number} width - The width in tiles of the area to operate on.
  78937. * @param {number} height - The height in tiles of the area to operate on.
  78938. * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on.
  78939. */
  78940. forEach: function (callback, context, x, y, width, height, layer) {
  78941. layer = this.getLayer(layer);
  78942. this.copy(x, y, width, height, layer);
  78943. if (this._results.length < 2)
  78944. {
  78945. return;
  78946. }
  78947. this._results.forEach(callback, context);
  78948. this.paste(x, y, this._results, layer);
  78949. },
  78950. /**
  78951. * Scans the given area for tiles with an index matching `source` and updates their index to match `dest`.
  78952. *
  78953. * @method Phaser.Tilemap#replace
  78954. * @param {number} source - The tile index value to scan for.
  78955. * @param {number} dest - The tile index value to replace found tiles with.
  78956. * @param {number} x - X position of the top left of the area to operate one, given in tiles, not pixels.
  78957. * @param {number} y - Y position of the top left of the area to operate one, given in tiles, not pixels.
  78958. * @param {number} width - The width in tiles of the area to operate on.
  78959. * @param {number} height - The height in tiles of the area to operate on.
  78960. * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on.
  78961. */
  78962. replace: function (source, dest, x, y, width, height, layer) {
  78963. layer = this.getLayer(layer);
  78964. this.copy(x, y, width, height, layer);
  78965. if (this._results.length < 2)
  78966. {
  78967. return;
  78968. }
  78969. for (var i = 1; i < this._results.length; i++)
  78970. {
  78971. if (this._results[i].index === source)
  78972. {
  78973. this._results[i].index = dest;
  78974. }
  78975. }
  78976. this.paste(x, y, this._results, layer);
  78977. },
  78978. /**
  78979. * Randomises a set of tiles in a given area.
  78980. *
  78981. * @method Phaser.Tilemap#random
  78982. * @param {number} x - X position of the top left of the area to operate one, given in tiles, not pixels.
  78983. * @param {number} y - Y position of the top left of the area to operate one, given in tiles, not pixels.
  78984. * @param {number} width - The width in tiles of the area to operate on.
  78985. * @param {number} height - The height in tiles of the area to operate on.
  78986. * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on.
  78987. */
  78988. random: function (x, y, width, height, layer) {
  78989. layer = this.getLayer(layer);
  78990. this.copy(x, y, width, height, layer);
  78991. if (this._results.length < 2)
  78992. {
  78993. return;
  78994. }
  78995. var indexes = [];
  78996. for (var t = 1; t < this._results.length; t++)
  78997. {
  78998. if (this._results[t].index)
  78999. {
  79000. var idx = this._results[t].index;
  79001. if (indexes.indexOf(idx) === -1)
  79002. {
  79003. indexes.push(idx);
  79004. }
  79005. }
  79006. }
  79007. for (var i = 1; i < this._results.length; i++)
  79008. {
  79009. this._results[i].index = this.game.rnd.pick(indexes);
  79010. }
  79011. this.paste(x, y, this._results, layer);
  79012. },
  79013. /**
  79014. * Shuffles a set of tiles in a given area. It will only randomise the tiles in that area, so if they're all the same nothing will appear to have changed!
  79015. *
  79016. * @method Phaser.Tilemap#shuffle
  79017. * @param {number} x - X position of the top left of the area to operate one, given in tiles, not pixels.
  79018. * @param {number} y - Y position of the top left of the area to operate one, given in tiles, not pixels.
  79019. * @param {number} width - The width in tiles of the area to operate on.
  79020. * @param {number} height - The height in tiles of the area to operate on.
  79021. * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on.
  79022. */
  79023. shuffle: function (x, y, width, height, layer) {
  79024. layer = this.getLayer(layer);
  79025. this.copy(x, y, width, height, layer);
  79026. if (this._results.length < 2)
  79027. {
  79028. return;
  79029. }
  79030. var indexes = [];
  79031. for (var t = 1; t < this._results.length; t++)
  79032. {
  79033. if (this._results[t].index)
  79034. {
  79035. indexes.push(this._results[t].index);
  79036. }
  79037. }
  79038. Phaser.ArrayUtils.shuffle(indexes);
  79039. for (var i = 1; i < this._results.length; i++)
  79040. {
  79041. this._results[i].index = indexes[i - 1];
  79042. }
  79043. this.paste(x, y, this._results, layer);
  79044. },
  79045. /**
  79046. * Fills the given area with the specified tile.
  79047. *
  79048. * @method Phaser.Tilemap#fill
  79049. * @param {number} index - The index of the tile that the area will be filled with.
  79050. * @param {number} x - X position of the top left of the area to operate one, given in tiles, not pixels.
  79051. * @param {number} y - Y position of the top left of the area to operate one, given in tiles, not pixels.
  79052. * @param {number} width - The width in tiles of the area to operate on.
  79053. * @param {number} height - The height in tiles of the area to operate on.
  79054. * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on.
  79055. */
  79056. fill: function (index, x, y, width, height, layer) {
  79057. layer = this.getLayer(layer);
  79058. this.copy(x, y, width, height, layer);
  79059. if (this._results.length < 2)
  79060. {
  79061. return;
  79062. }
  79063. for (var i = 1; i < this._results.length; i++)
  79064. {
  79065. this._results[i].index = index;
  79066. }
  79067. this.paste(x, y, this._results, layer);
  79068. },
  79069. /**
  79070. * Removes all layers from this tile map.
  79071. *
  79072. * @method Phaser.Tilemap#removeAllLayers
  79073. */
  79074. removeAllLayers: function () {
  79075. this.layers.length = 0;
  79076. this.currentLayer = 0;
  79077. },
  79078. /**
  79079. * Dumps the tilemap data out to the console.
  79080. *
  79081. * @method Phaser.Tilemap#dump
  79082. */
  79083. dump: function () {
  79084. var txt = '';
  79085. var args = [''];
  79086. for (var y = 0; y < this.layers[this.currentLayer].height; y++)
  79087. {
  79088. for (var x = 0; x < this.layers[this.currentLayer].width; x++)
  79089. {
  79090. txt += "%c ";
  79091. if (this.layers[this.currentLayer].data[y][x] > 1)
  79092. {
  79093. if (this.debugMap[this.layers[this.currentLayer].data[y][x]])
  79094. {
  79095. args.push("background: " + this.debugMap[this.layers[this.currentLayer].data[y][x]]);
  79096. }
  79097. else
  79098. {
  79099. args.push("background: #ffffff");
  79100. }
  79101. }
  79102. else
  79103. {
  79104. args.push("background: rgb(0, 0, 0)");
  79105. }
  79106. }
  79107. txt += "\n";
  79108. }
  79109. args[0] = txt;
  79110. console.log.apply(console, args);
  79111. },
  79112. /**
  79113. * Removes all layer data from this tile map and nulls the game reference.
  79114. * Note: You are responsible for destroying any TilemapLayer objects you generated yourself, as Tilemap doesn't keep a reference to them.
  79115. *
  79116. * @method Phaser.Tilemap#destroy
  79117. */
  79118. destroy: function () {
  79119. this.removeAllLayers();
  79120. this.data = [];
  79121. this.game = null;
  79122. }
  79123. };
  79124. Phaser.Tilemap.prototype.constructor = Phaser.Tilemap;
  79125. /**
  79126. * @name Phaser.Tilemap#layer
  79127. * @property {number|string|Phaser.TilemapLayer} layer - The current layer object.
  79128. */
  79129. Object.defineProperty(Phaser.Tilemap.prototype, "layer", {
  79130. get: function () {
  79131. return this.layers[this.currentLayer];
  79132. },
  79133. set: function (value) {
  79134. if (value !== this.currentLayer)
  79135. {
  79136. this.setLayer(value);
  79137. }
  79138. }
  79139. });
  79140. /**
  79141. * @author Richard Davey <rich@photonstorm.com>
  79142. * @copyright 2016 Photon Storm Ltd.
  79143. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  79144. */
  79145. /**
  79146. * A TilemapLayer is a Phaser.Image/Sprite that renders a specific TileLayer of a Tilemap.
  79147. *
  79148. * Since a TilemapLayer is a Sprite it can be moved around the display, added to other groups or display objects, etc.
  79149. *
  79150. * By default TilemapLayers have fixedToCamera set to `true`. Changing this will break Camera follow and scrolling behavior.
  79151. *
  79152. * @class Phaser.TilemapLayer
  79153. * @extends Phaser.Sprite
  79154. * @constructor
  79155. * @param {Phaser.Game} game - Game reference to the currently running game.
  79156. * @param {Phaser.Tilemap} tilemap - The tilemap to which this layer belongs.
  79157. * @param {integer} index - The index of the TileLayer to render within the Tilemap.
  79158. * @param {integer} width - Width of the renderable area of the layer (in pixels).
  79159. * @param {integer} height - Height of the renderable area of the layer (in pixels).
  79160. */
  79161. Phaser.TilemapLayer = function (game, tilemap, index, width, height) {
  79162. width |= 0;
  79163. height |= 0;
  79164. Phaser.Sprite.call(this, game, 0, 0);
  79165. /**
  79166. * The Tilemap to which this layer is bound.
  79167. * @property {Phaser.Tilemap} map
  79168. * @protected
  79169. * @readonly
  79170. */
  79171. this.map = tilemap;
  79172. /**
  79173. * The index of this layer within the Tilemap.
  79174. * @property {number} index
  79175. * @protected
  79176. * @readonly
  79177. */
  79178. this.index = index;
  79179. /**
  79180. * The layer object within the Tilemap that this layer represents.
  79181. * @property {object} layer
  79182. * @protected
  79183. * @readonly
  79184. */
  79185. this.layer = tilemap.layers[index];
  79186. /**
  79187. * The canvas to which this TilemapLayer draws.
  79188. * @property {HTMLCanvasElement} canvas
  79189. * @protected
  79190. */
  79191. this.canvas = PIXI.CanvasPool.create(this, width, height);
  79192. /**
  79193. * The 2d context of the canvas.
  79194. * @property {CanvasRenderingContext2D} context
  79195. * @private
  79196. */
  79197. this.context = this.canvas.getContext('2d');
  79198. this.setTexture(new PIXI.Texture(new PIXI.BaseTexture(this.canvas)));
  79199. /**
  79200. * The const type of this object.
  79201. * @property {number} type
  79202. * @readonly
  79203. * @protected
  79204. * @default Phaser.TILEMAPLAYER
  79205. */
  79206. this.type = Phaser.TILEMAPLAYER;
  79207. /**
  79208. * @property {number} physicsType - The const physics body type of this object.
  79209. * @readonly
  79210. */
  79211. this.physicsType = Phaser.TILEMAPLAYER;
  79212. /**
  79213. * Settings that control standard (non-diagnostic) rendering.
  79214. *
  79215. * @property {boolean} [enableScrollDelta=true] - Delta scroll rendering only draws tiles/edges as they come into view.
  79216. * This can greatly improve scrolling rendering performance, especially when there are many small tiles.
  79217. * It should only be disabled in rare cases.
  79218. *
  79219. * @property {?DOMCanvasElement} [copyCanvas=(auto)] - [Internal] If set, force using a separate (shared) copy canvas.
  79220. * Using a canvas bitblt/copy when the source and destinations region overlap produces unexpected behavior
  79221. * in some browsers, notably Safari.
  79222. *
  79223. * @default
  79224. */
  79225. this.renderSettings = {
  79226. enableScrollDelta: false,
  79227. overdrawRatio: 0.20,
  79228. copyCanvas: null
  79229. };
  79230. /**
  79231. * Enable an additional "debug rendering" pass to display collision information.
  79232. *
  79233. * @property {boolean} debug
  79234. * @default
  79235. */
  79236. this.debug = false;
  79237. /**
  79238. * @property {boolean} exists - Controls if the core game loop and physics update this game object or not.
  79239. */
  79240. this.exists = true;
  79241. /**
  79242. * Settings used for debugging and diagnostics.
  79243. *
  79244. * @property {?string} missingImageFill - A tile is rendered as a rectangle using the following fill if a valid tileset/image cannot be found. A value of `null` prevents additional rendering for tiles without a valid tileset image. _This takes effect even when debug rendering for the layer is not enabled._
  79245. *
  79246. * @property {?string} debuggedTileOverfill - If a Tile has `Tile#debug` true then, after normal tile image rendering, a rectangle with the following fill is drawn above/over it. _This takes effect even when debug rendering for the layer is not enabled._
  79247. *
  79248. * @property {boolean} forceFullRedraw - When debug rendering (`debug` is true), and this option is enabled, the a full redraw is forced and rendering optimization is suppressed.
  79249. *
  79250. * @property {number} debugAlpha - When debug rendering (`debug` is true), the tileset is initially rendered with this alpha level. This can make the tile edges clearer.
  79251. *
  79252. * @property {?string} facingEdgeStroke - When debug rendering (`debug` is true), this color/stroke is used to draw "face" edges. A value of `null` disables coloring facing edges.
  79253. *
  79254. * @property {?string} collidingTileOverfill - When debug rendering (`debug` is true), this fill is used for tiles that are collidable. A value of `null` disables applying the additional overfill.
  79255. *
  79256. */
  79257. this.debugSettings = {
  79258. missingImageFill: 'rgb(255,255,255)',
  79259. debuggedTileOverfill: 'rgba(0,255,0,0.4)',
  79260. forceFullRedraw: true,
  79261. debugAlpha: 0.5,
  79262. facingEdgeStroke: 'rgba(0,255,0,1)',
  79263. collidingTileOverfill: 'rgba(0,255,0,0.2)'
  79264. };
  79265. /**
  79266. * Speed at which this layer scrolls horizontally, relative to the camera (e.g. scrollFactorX of 0.5 scrolls half as quickly as the 'normal' camera-locked layers do).
  79267. * @property {number} scrollFactorX
  79268. * @public
  79269. * @default
  79270. */
  79271. this.scrollFactorX = 1;
  79272. /**
  79273. * Speed at which this layer scrolls vertically, relative to the camera (e.g. scrollFactorY of 0.5 scrolls half as quickly as the 'normal' camera-locked layers do)
  79274. * @property {number} scrollFactorY
  79275. * @public
  79276. * @default
  79277. */
  79278. this.scrollFactorY = 1;
  79279. /**
  79280. * If true tiles will be force rendered, even if such is not believed to be required.
  79281. * @property {boolean} dirty
  79282. * @protected
  79283. */
  79284. this.dirty = true;
  79285. /**
  79286. * When ray-casting against tiles this is the number of steps it will jump. For larger tile sizes you can increase this to improve performance.
  79287. * @property {integer} rayStepRate
  79288. * @default
  79289. */
  79290. this.rayStepRate = 4;
  79291. /**
  79292. * Flag controlling if the layer tiles wrap at the edges.
  79293. * @property {boolean} _wrap
  79294. * @private
  79295. */
  79296. this._wrap = false;
  79297. /**
  79298. * Local map data and calculation cache.
  79299. * @property {object} _mc
  79300. * @private
  79301. */
  79302. this._mc = {
  79303. // Used to bypass rendering without reliance on `dirty` and detect changes.
  79304. scrollX: 0,
  79305. scrollY: 0,
  79306. renderWidth: 0,
  79307. renderHeight: 0,
  79308. tileWidth: tilemap.tileWidth,
  79309. tileHeight: tilemap.tileHeight,
  79310. // Collision width/height (pixels)
  79311. // What purpose do these have? Most things use tile width/height directly.
  79312. // This also only extends collisions right and down.
  79313. cw: tilemap.tileWidth,
  79314. ch: tilemap.tileHeight,
  79315. // Cached tilesets from index -> Tileset
  79316. tilesets: []
  79317. };
  79318. /**
  79319. * The current canvas left after scroll is applied.
  79320. * @property {number} _scrollX
  79321. * @private
  79322. */
  79323. this._scrollX = 0;
  79324. /**
  79325. * The current canvas top after scroll is applied.
  79326. * @propety {number} _scrollY
  79327. * @private
  79328. */
  79329. this._scrollY = 0;
  79330. /**
  79331. * Used for caching the tiles / array of tiles.
  79332. * @property {Phaser.Tile[]} _results
  79333. * @private
  79334. */
  79335. this._results = [];
  79336. if (!game.device.canvasBitBltShift)
  79337. {
  79338. this.renderSettings.copyCanvas = Phaser.TilemapLayer.ensureSharedCopyCanvas();
  79339. }
  79340. this.fixedToCamera = true;
  79341. };
  79342. Phaser.TilemapLayer.prototype = Object.create(Phaser.Sprite.prototype);
  79343. Phaser.TilemapLayer.prototype.constructor = Phaser.TilemapLayer;
  79344. Phaser.TilemapLayer.prototype.preUpdateCore = Phaser.Component.Core.preUpdate;
  79345. /**
  79346. * The shared double-copy canvas, created as needed.
  79347. *
  79348. * @private
  79349. * @static
  79350. */
  79351. Phaser.TilemapLayer.sharedCopyCanvas = null;
  79352. /**
  79353. * Create if needed (and return) a shared copy canvas that is shared across all TilemapLayers.
  79354. *
  79355. * Code that uses the canvas is responsible to ensure the dimensions and save/restore state as appropriate.
  79356. *
  79357. * @method Phaser.TilemapLayer#ensureSharedCopyCanvas
  79358. * @protected
  79359. * @static
  79360. */
  79361. Phaser.TilemapLayer.ensureSharedCopyCanvas = function () {
  79362. if (!this.sharedCopyCanvas)
  79363. {
  79364. this.sharedCopyCanvas = PIXI.CanvasPool.create(this, 2, 2);
  79365. }
  79366. return this.sharedCopyCanvas;
  79367. };
  79368. /**
  79369. * Automatically called by World.preUpdate.
  79370. *
  79371. * @method Phaser.TilemapLayer#preUpdate
  79372. */
  79373. Phaser.TilemapLayer.prototype.preUpdate = function() {
  79374. return this.preUpdateCore();
  79375. };
  79376. /**
  79377. * Automatically called by World.postUpdate. Handles cache updates.
  79378. *
  79379. * @method Phaser.TilemapLayer#postUpdate
  79380. * @protected
  79381. */
  79382. Phaser.TilemapLayer.prototype.postUpdate = function () {
  79383. if (this.fixedToCamera)
  79384. {
  79385. this.position.x = (this.game.camera.view.x + this.cameraOffset.x) / this.game.camera.scale.x;
  79386. this.position.y = (this.game.camera.view.y + this.cameraOffset.y) / this.game.camera.scale.y;
  79387. }
  79388. this._scrollX = this.game.camera.view.x * this.scrollFactorX / this.scale.x;
  79389. this._scrollY = this.game.camera.view.y * this.scrollFactorY / this.scale.y;
  79390. };
  79391. /**
  79392. * Automatically called by the Canvas Renderer.
  79393. * Overrides the Sprite._renderCanvas function.
  79394. *
  79395. * @method Phaser.TilemapLayer#_renderCanvas
  79396. * @private
  79397. */
  79398. Phaser.TilemapLayer.prototype._renderCanvas = function (renderSession) {
  79399. if (this.fixedToCamera)
  79400. {
  79401. this.position.x = (this.game.camera.view.x + this.cameraOffset.x) / this.game.camera.scale.x;
  79402. this.position.y = (this.game.camera.view.y + this.cameraOffset.y) / this.game.camera.scale.y;
  79403. }
  79404. this._scrollX = this.game.camera.view.x * this.scrollFactorX / this.scale.x;
  79405. this._scrollY = this.game.camera.view.y * this.scrollFactorY / this.scale.y;
  79406. this.render();
  79407. PIXI.Sprite.prototype._renderCanvas.call(this, renderSession);
  79408. };
  79409. /**
  79410. * Automatically called by the Canvas Renderer.
  79411. * Overrides the Sprite._renderWebGL function.
  79412. *
  79413. * @method Phaser.TilemapLayer#_renderWebGL
  79414. * @private
  79415. */
  79416. Phaser.TilemapLayer.prototype._renderWebGL = function (renderSession) {
  79417. if (this.fixedToCamera)
  79418. {
  79419. this.position.x = (this.game.camera.view.x + this.cameraOffset.x) / this.game.camera.scale.x;
  79420. this.position.y = (this.game.camera.view.y + this.cameraOffset.y) / this.game.camera.scale.y;
  79421. }
  79422. this._scrollX = this.game.camera.view.x * this.scrollFactorX / this.scale.x;
  79423. this._scrollY = this.game.camera.view.y * this.scrollFactorY / this.scale.y;
  79424. this.render();
  79425. PIXI.Sprite.prototype._renderWebGL.call(this, renderSession);
  79426. };
  79427. /**
  79428. * Destroys this TilemapLayer.
  79429. *
  79430. * @method Phaser.TilemapLayer#destroy
  79431. */
  79432. Phaser.TilemapLayer.prototype.destroy = function() {
  79433. PIXI.CanvasPool.remove(this);
  79434. Phaser.Component.Destroy.prototype.destroy.call(this);
  79435. };
  79436. /**
  79437. * Resizes the internal canvas and texture frame used by this TilemapLayer.
  79438. *
  79439. * This is an expensive call, so don't bind it to a window resize event! But instead call it at carefully
  79440. * selected times.
  79441. *
  79442. * Be aware that no validation of the new sizes takes place and the current map scroll coordinates are not
  79443. * modified either. You will have to handle both of these things from your game code if required.
  79444. *
  79445. * @method Phaser.TilemapLayer#resize
  79446. * @param {number} width - The new width of the TilemapLayer
  79447. * @param {number} height - The new height of the TilemapLayer
  79448. */
  79449. Phaser.TilemapLayer.prototype.resize = function (width, height) {
  79450. this.canvas.width = width;
  79451. this.canvas.height = height;
  79452. this.texture.frame.resize(width, height);
  79453. this.texture.width = width;
  79454. this.texture.height = height;
  79455. this.texture.crop.width = width;
  79456. this.texture.crop.height = height;
  79457. this.texture.baseTexture.width = width;
  79458. this.texture.baseTexture.height = height;
  79459. this.texture.baseTexture.dirty();
  79460. this.texture.requiresUpdate = true;
  79461. this.texture._updateUvs();
  79462. this.dirty = true;
  79463. };
  79464. /**
  79465. * Sets the world size to match the size of this layer.
  79466. *
  79467. * @method Phaser.TilemapLayer#resizeWorld
  79468. * @public
  79469. */
  79470. Phaser.TilemapLayer.prototype.resizeWorld = function () {
  79471. this.game.world.setBounds(0, 0, this.layer.widthInPixels * this.scale.x, this.layer.heightInPixels * this.scale.y);
  79472. };
  79473. /**
  79474. * Take an x coordinate that doesn't account for scrollFactorX and 'fix' it into a scrolled local space.
  79475. *
  79476. * @method Phaser.TilemapLayer#_fixX
  79477. * @private
  79478. * @param {number} x - x coordinate in camera space
  79479. * @return {number} x coordinate in scrollFactor-adjusted dimensions
  79480. */
  79481. Phaser.TilemapLayer.prototype._fixX = function (x) {
  79482. if (this.scrollFactorX === 1 || (this.scrollFactorX === 0 && this.position.x === 0))
  79483. {
  79484. return x;
  79485. }
  79486. // This executes if the scrollFactorX is 0 and the x position of the tilemap is off from standard.
  79487. if (this.scrollFactorX === 0 && this.position.x !== 0)
  79488. {
  79489. return x - this.position.x;
  79490. }
  79491. return this._scrollX + (x - (this._scrollX / this.scrollFactorX));
  79492. };
  79493. /**
  79494. * Take an x coordinate that _does_ account for scrollFactorX and 'unfix' it back to camera space.
  79495. *
  79496. * @method Phaser.TilemapLayer#_unfixX
  79497. * @private
  79498. * @param {number} x - x coordinate in scrollFactor-adjusted dimensions
  79499. * @return {number} x coordinate in camera space
  79500. */
  79501. Phaser.TilemapLayer.prototype._unfixX = function (x) {
  79502. if (this.scrollFactorX === 1)
  79503. {
  79504. return x;
  79505. }
  79506. return (this._scrollX / this.scrollFactorX) + (x - this._scrollX);
  79507. };
  79508. /**
  79509. * Take a y coordinate that doesn't account for scrollFactorY and 'fix' it into a scrolled local space.
  79510. *
  79511. * @method Phaser.TilemapLayer#_fixY
  79512. * @private
  79513. * @param {number} y - y coordinate in camera space
  79514. * @return {number} y coordinate in scrollFactor-adjusted dimensions
  79515. */
  79516. Phaser.TilemapLayer.prototype._fixY = function (y) {
  79517. if (this.scrollFactorY === 1 || (this.scrollFactorY === 0 && this.position.y === 0))
  79518. {
  79519. return y;
  79520. }
  79521. // This executes if the scrollFactorY is 0 and the y position of the tilemap is off from standard.
  79522. if (this.scrollFactorY === 0 && this.position.y !== 0)
  79523. {
  79524. return y - this.position.y;
  79525. }
  79526. return this._scrollY + (y - (this._scrollY / this.scrollFactorY));
  79527. };
  79528. /**
  79529. * Take a y coordinate that _does_ account for scrollFactorY and 'unfix' it back to camera space.
  79530. *
  79531. * @method Phaser.TilemapLayer#_unfixY
  79532. * @private
  79533. * @param {number} y - y coordinate in scrollFactor-adjusted dimensions
  79534. * @return {number} y coordinate in camera space
  79535. */
  79536. Phaser.TilemapLayer.prototype._unfixY = function (y) {
  79537. if (this.scrollFactorY === 1)
  79538. {
  79539. return y;
  79540. }
  79541. return (this._scrollY / this.scrollFactorY) + (y - this._scrollY);
  79542. };
  79543. /**
  79544. * Convert a pixel value to a tile coordinate.
  79545. *
  79546. * @method Phaser.TilemapLayer#getTileX
  79547. * @public
  79548. * @param {number} x - X position of the point in target tile (in pixels).
  79549. * @return {integer} The X map location of the tile.
  79550. */
  79551. Phaser.TilemapLayer.prototype.getTileX = function (x) {
  79552. // var tileWidth = this.tileWidth * this.scale.x;
  79553. return Math.floor(this._fixX(x) / this._mc.tileWidth);
  79554. };
  79555. /**
  79556. * Convert a pixel value to a tile coordinate.
  79557. *
  79558. * @method Phaser.TilemapLayer#getTileY
  79559. * @public
  79560. * @param {number} y - Y position of the point in target tile (in pixels).
  79561. * @return {integer} The Y map location of the tile.
  79562. */
  79563. Phaser.TilemapLayer.prototype.getTileY = function (y) {
  79564. // var tileHeight = this.tileHeight * this.scale.y;
  79565. return Math.floor(this._fixY(y) / this._mc.tileHeight);
  79566. };
  79567. /**
  79568. * Convert a pixel coordinate to a tile coordinate.
  79569. *
  79570. * @method Phaser.TilemapLayer#getTileXY
  79571. * @public
  79572. * @param {number} x - X position of the point in target tile (in pixels).
  79573. * @param {number} y - Y position of the point in target tile (in pixels).
  79574. * @param {(Phaser.Point|object)} point - The Point/object to update.
  79575. * @return {(Phaser.Point|object)} A Point/object with its `x` and `y` properties set.
  79576. */
  79577. Phaser.TilemapLayer.prototype.getTileXY = function (x, y, point) {
  79578. point.x = this.getTileX(x);
  79579. point.y = this.getTileY(y);
  79580. return point;
  79581. };
  79582. /**
  79583. * Gets all tiles that intersect with the given line.
  79584. *
  79585. * @method Phaser.TilemapLayer#getRayCastTiles
  79586. * @public
  79587. * @param {Phaser.Line} line - The line used to determine which tiles to return.
  79588. * @param {integer} [stepRate=(rayStepRate)] - How many steps through the ray will we check? Defaults to `rayStepRate`.
  79589. * @param {boolean} [collides=false] - If true, _only_ return tiles that collide on one or more faces.
  79590. * @param {boolean} [interestingFace=false] - If true, _only_ return tiles that have interesting faces.
  79591. * @return {Phaser.Tile[]} An array of Phaser.Tiles.
  79592. */
  79593. Phaser.TilemapLayer.prototype.getRayCastTiles = function (line, stepRate, collides, interestingFace) {
  79594. if (!stepRate) { stepRate = this.rayStepRate; }
  79595. if (collides === undefined) { collides = false; }
  79596. if (interestingFace === undefined) { interestingFace = false; }
  79597. // First get all tiles that touch the bounds of the line
  79598. var tiles = this.getTiles(line.x, line.y, line.width, line.height, collides, interestingFace);
  79599. if (tiles.length === 0)
  79600. {
  79601. return [];
  79602. }
  79603. // Now we only want the tiles that intersect with the points on this line
  79604. var coords = line.coordinatesOnLine(stepRate);
  79605. var results = [];
  79606. for (var i = 0; i < tiles.length; i++)
  79607. {
  79608. for (var t = 0; t < coords.length; t++)
  79609. {
  79610. var tile = tiles[i];
  79611. var coord = coords[t];
  79612. if (tile.containsPoint(coord[0], coord[1]))
  79613. {
  79614. results.push(tile);
  79615. break;
  79616. }
  79617. }
  79618. }
  79619. return results;
  79620. };
  79621. /**
  79622. * Get all tiles that exist within the given area, defined by the top-left corner, width and height. Values given are in pixels, not tiles.
  79623. *
  79624. * @method Phaser.TilemapLayer#getTiles
  79625. * @public
  79626. * @param {number} x - X position of the top left corner (in pixels).
  79627. * @param {number} y - Y position of the top left corner (in pixels).
  79628. * @param {number} width - Width of the area to get (in pixels).
  79629. * @param {number} height - Height of the area to get (in pixels).
  79630. * @param {boolean} [collides=false] - If true, _only_ return tiles that collide on one or more faces.
  79631. * @param {boolean} [interestingFace=false] - If true, _only_ return tiles that have interesting faces.
  79632. * @return {array<Phaser.Tile>} An array of Tiles.
  79633. */
  79634. Phaser.TilemapLayer.prototype.getTiles = function (x, y, width, height, collides, interestingFace) {
  79635. // Should we only get tiles that have at least one of their collision flags set? (true = yes, false = no just get them all)
  79636. if (collides === undefined) { collides = false; }
  79637. if (interestingFace === undefined) { interestingFace = false; }
  79638. var fetchAll = !(collides || interestingFace);
  79639. // Adjust the x,y coordinates for scrollFactor
  79640. x = this._fixX(x);
  79641. y = this._fixY(y);
  79642. // Convert the pixel values into tile coordinates
  79643. var tx = Math.floor(x / (this._mc.cw * this.scale.x));
  79644. var ty = Math.floor(y / (this._mc.ch * this.scale.y));
  79645. // Don't just use ceil(width/cw) to allow account for x/y diff within cell
  79646. var tw = Math.ceil((x + width) / (this._mc.cw * this.scale.x)) - tx;
  79647. var th = Math.ceil((y + height) / (this._mc.ch * this.scale.y)) - ty;
  79648. while (this._results.length)
  79649. {
  79650. this._results.pop();
  79651. }
  79652. for (var wy = ty; wy < ty + th; wy++)
  79653. {
  79654. for (var wx = tx; wx < tx + tw; wx++)
  79655. {
  79656. var row = this.layer.data[wy];
  79657. if (row && row[wx])
  79658. {
  79659. if (fetchAll || row[wx].isInteresting(collides, interestingFace))
  79660. {
  79661. this._results.push(row[wx]);
  79662. }
  79663. }
  79664. }
  79665. }
  79666. return this._results.slice();
  79667. };
  79668. /**
  79669. * Returns the appropriate tileset for the index, updating the internal cache as required.
  79670. * This should only be called if `tilesets[index]` evaluates to undefined.
  79671. *
  79672. * @method Phaser.TilemapLayer#resolveTileset
  79673. * @private
  79674. * @param {integer} Tile index
  79675. * @return {Phaser.Tileset|null} Returns the associated tileset or null if there is no such mapping.
  79676. */
  79677. Phaser.TilemapLayer.prototype.resolveTileset = function (tileIndex) {
  79678. var tilesets = this._mc.tilesets;
  79679. // Try for dense array if reasonable
  79680. if (tileIndex < 2000)
  79681. {
  79682. while (tilesets.length < tileIndex)
  79683. {
  79684. tilesets.push(undefined);
  79685. }
  79686. }
  79687. var setIndex = this.map.tiles[tileIndex] && this.map.tiles[tileIndex][2];
  79688. if (setIndex !== null)
  79689. {
  79690. var tileset = this.map.tilesets[setIndex];
  79691. if (tileset && tileset.containsTileIndex(tileIndex))
  79692. {
  79693. return (tilesets[tileIndex] = tileset);
  79694. }
  79695. }
  79696. return (tilesets[tileIndex] = null);
  79697. };
  79698. /**
  79699. * The TilemapLayer caches tileset look-ups.
  79700. *
  79701. * Call this method of clear the cache if tilesets have been added or updated after the layer has been rendered.
  79702. *
  79703. * @method Phaser.TilemapLayer#resetTilesetCache
  79704. * @public
  79705. */
  79706. Phaser.TilemapLayer.prototype.resetTilesetCache = function () {
  79707. var tilesets = this._mc.tilesets;
  79708. while (tilesets.length)
  79709. {
  79710. tilesets.pop();
  79711. }
  79712. };
  79713. /**
  79714. * This method will set the scale of the tilemap as well as update the underlying block data of this layer.
  79715. *
  79716. * @method Phaser.TilemapLayer#setScale
  79717. * @param {number} [xScale=1] - The scale factor along the X-plane
  79718. * @param {number} [yScale] - The scale factor along the Y-plane
  79719. */
  79720. Phaser.TilemapLayer.prototype.setScale = function (xScale, yScale) {
  79721. xScale = xScale || 1;
  79722. yScale = yScale || xScale;
  79723. for (var y = 0; y < this.layer.data.length; y++)
  79724. {
  79725. var row = this.layer.data[y];
  79726. for (var x = 0; x < row.length; x++)
  79727. {
  79728. var tile = row[x];
  79729. tile.width = this.map.tileWidth * xScale;
  79730. tile.height = this.map.tileHeight * yScale;
  79731. tile.worldX = tile.x * tile.width;
  79732. tile.worldY = tile.y * tile.height;
  79733. }
  79734. }
  79735. this.scale.setTo(xScale, yScale);
  79736. };
  79737. /**
  79738. * Shifts the contents of the canvas - does extra math so that different browsers agree on the result.
  79739. *
  79740. * The specified (x/y) will be shifted to (0,0) after the copy and the newly exposed canvas area will need to be filled in.
  79741. *
  79742. * @method Phaser.TilemapLayer#shiftCanvas
  79743. * @private
  79744. * @param {CanvasRenderingContext2D} context - The context to shift
  79745. * @param {integer} x
  79746. * @param {integer} y
  79747. */
  79748. Phaser.TilemapLayer.prototype.shiftCanvas = function (context, x, y) {
  79749. var canvas = context.canvas;
  79750. var copyW = canvas.width - Math.abs(x);
  79751. var copyH = canvas.height - Math.abs(y);
  79752. // When x/y non-negative
  79753. var dx = 0;
  79754. var dy = 0;
  79755. var sx = x;
  79756. var sy = y;
  79757. if (x < 0)
  79758. {
  79759. dx = -x;
  79760. sx = 0;
  79761. }
  79762. if (y < 0)
  79763. {
  79764. dy = -y;
  79765. sy = 0;
  79766. }
  79767. var copyCanvas = this.renderSettings.copyCanvas;
  79768. if (copyCanvas)
  79769. {
  79770. // Use a second copy buffer, without slice support, for Safari .. again.
  79771. // Ensure copy canvas is large enough
  79772. if (copyCanvas.width < copyW || copyCanvas.height < copyH)
  79773. {
  79774. copyCanvas.width = copyW;
  79775. copyCanvas.height = copyH;
  79776. }
  79777. var copyContext = copyCanvas.getContext('2d');
  79778. copyContext.clearRect(0, 0, copyW, copyH);
  79779. copyContext.drawImage(canvas, dx, dy, copyW, copyH, 0, 0, copyW, copyH);
  79780. // clear allows default 'source-over' semantics
  79781. context.clearRect(sx, sy, copyW, copyH);
  79782. context.drawImage(copyCanvas, 0, 0, copyW, copyH, sx, sy, copyW, copyH);
  79783. }
  79784. else
  79785. {
  79786. // Avoids a second copy but flickers in Safari / Safari Mobile
  79787. // Ref. https://github.com/photonstorm/phaser/issues/1439
  79788. context.save();
  79789. context.globalCompositeOperation = 'copy';
  79790. context.drawImage(canvas, dx, dy, copyW, copyH, sx, sy, copyW, copyH);
  79791. context.restore();
  79792. }
  79793. };
  79794. /**
  79795. * Render tiles in the given area given by the virtual tile coordinates biased by the given scroll factor.
  79796. * This will constrain the tile coordinates based on wrapping but not physical coordinates.
  79797. *
  79798. * @method Phaser.TilemapLayer#renderRegion
  79799. * @private
  79800. * @param {integer} scrollX - Render x offset/scroll.
  79801. * @param {integer} scrollY - Render y offset/scroll.
  79802. * @param {integer} left - Leftmost column to render.
  79803. * @param {integer} top - Topmost row to render.
  79804. * @param {integer} right - Rightmost column to render.
  79805. * @param {integer} bottom - Bottommost row to render.
  79806. */
  79807. Phaser.TilemapLayer.prototype.renderRegion = function (scrollX, scrollY, left, top, right, bottom) {
  79808. var context = this.context;
  79809. var width = this.layer.width;
  79810. var height = this.layer.height;
  79811. var tw = this._mc.tileWidth;
  79812. var th = this._mc.tileHeight;
  79813. var tilesets = this._mc.tilesets;
  79814. var lastAlpha = NaN;
  79815. if (!this._wrap)
  79816. {
  79817. if (left <= right) // Only adjust if going to render
  79818. {
  79819. left = Math.max(0, left);
  79820. right = Math.min(width - 1, right);
  79821. }
  79822. if (top <= bottom)
  79823. {
  79824. top = Math.max(0, top);
  79825. bottom = Math.min(height - 1, bottom);
  79826. }
  79827. }
  79828. // top-left pixel of top-left cell
  79829. var baseX = (left * tw) - scrollX;
  79830. var baseY = (top * th) - scrollY;
  79831. // Fix normStartX/normStartY such it is normalized [0..width/height). This allows a simple conditional and decrement to always keep in range [0..width/height) during the loop. The major offset bias is to take care of negative values.
  79832. var normStartX = (left + ((1 << 20) * width)) % width;
  79833. var normStartY = (top + ((1 << 20) * height)) % height;
  79834. // tx/ty - are pixel coordinates where tile is drawn
  79835. // x/y - is cell location, normalized [0..width/height) in loop
  79836. // xmax/ymax - remaining cells to render on column/row
  79837. var tx, ty, x, y, xmax, ymax;
  79838. for (y = normStartY, ymax = bottom - top, ty = baseY; ymax >= 0; y++, ymax--, ty += th)
  79839. {
  79840. if (y >= height)
  79841. {
  79842. y -= height;
  79843. }
  79844. var row = this.layer.data[y];
  79845. for (x = normStartX, xmax = right - left, tx = baseX; xmax >= 0; x++, xmax--, tx += tw)
  79846. {
  79847. if (x >= width)
  79848. {
  79849. x -= width;
  79850. }
  79851. var tile = row[x];
  79852. if (!tile || tile.index < 0)
  79853. {
  79854. continue;
  79855. }
  79856. var index = tile.index;
  79857. var set = tilesets[index];
  79858. if (set === undefined)
  79859. {
  79860. set = this.resolveTileset(index);
  79861. }
  79862. // Setting the globalAlpha is "surprisingly expensive" in Chrome (38)
  79863. if (tile.alpha !== lastAlpha && !this.debug)
  79864. {
  79865. context.globalAlpha = tile.alpha;
  79866. lastAlpha = tile.alpha;
  79867. }
  79868. if (set)
  79869. {
  79870. if (tile.rotation || tile.flipped)
  79871. {
  79872. context.save();
  79873. context.translate(tx + tile.centerX, ty + tile.centerY);
  79874. context.rotate(tile.rotation);
  79875. if (tile.flipped)
  79876. {
  79877. context.scale(-1, 1);
  79878. }
  79879. set.draw(context, -tile.centerX, -tile.centerY, index);
  79880. context.restore();
  79881. }
  79882. else
  79883. {
  79884. set.draw(context, tx, ty, index);
  79885. }
  79886. }
  79887. else if (this.debugSettings.missingImageFill)
  79888. {
  79889. context.fillStyle = this.debugSettings.missingImageFill;
  79890. context.fillRect(tx, ty, tw, th);
  79891. }
  79892. if (tile.debug && this.debugSettings.debuggedTileOverfill)
  79893. {
  79894. context.fillStyle = this.debugSettings.debuggedTileOverfill;
  79895. context.fillRect(tx, ty, tw, th);
  79896. }
  79897. }
  79898. }
  79899. };
  79900. /**
  79901. * Shifts the canvas and render damaged edge tiles.
  79902. *
  79903. * @method Phaser.TilemapLayer#renderDeltaScroll
  79904. * @private
  79905. */
  79906. Phaser.TilemapLayer.prototype.renderDeltaScroll = function (shiftX, shiftY) {
  79907. var scrollX = this._mc.scrollX;
  79908. var scrollY = this._mc.scrollY;
  79909. var renderW = this.canvas.width;
  79910. var renderH = this.canvas.height;
  79911. var tw = this._mc.tileWidth;
  79912. var th = this._mc.tileHeight;
  79913. // Only cells with coordinates in the "plus" formed by `left <= x <= right` OR `top <= y <= bottom` are drawn. These coordinates may be outside the layer bounds.
  79914. // Start in pixels
  79915. var left = 0;
  79916. var right = -tw;
  79917. var top = 0;
  79918. var bottom = -th;
  79919. if (shiftX < 0) // layer moving left, damage right
  79920. {
  79921. left = renderW + shiftX; // shiftX neg.
  79922. right = renderW - 1;
  79923. }
  79924. else if (shiftX > 0)
  79925. {
  79926. // left -> 0
  79927. right = shiftX;
  79928. }
  79929. if (shiftY < 0) // layer moving down, damage top
  79930. {
  79931. top = renderH + shiftY; // shiftY neg.
  79932. bottom = renderH - 1;
  79933. }
  79934. else if (shiftY > 0)
  79935. {
  79936. // top -> 0
  79937. bottom = shiftY;
  79938. }
  79939. this.shiftCanvas(this.context, shiftX, shiftY);
  79940. // Transform into tile-space
  79941. left = Math.floor((left + scrollX) / tw);
  79942. right = Math.floor((right + scrollX) / tw);
  79943. top = Math.floor((top + scrollY) / th);
  79944. bottom = Math.floor((bottom + scrollY) / th);
  79945. if (left <= right)
  79946. {
  79947. // Clear left or right edge
  79948. this.context.clearRect(((left * tw) - scrollX), 0, (right - left + 1) * tw, renderH);
  79949. var trueTop = Math.floor((0 + scrollY) / th);
  79950. var trueBottom = Math.floor((renderH - 1 + scrollY) / th);
  79951. this.renderRegion(scrollX, scrollY, left, trueTop, right, trueBottom);
  79952. }
  79953. if (top <= bottom)
  79954. {
  79955. // Clear top or bottom edge
  79956. this.context.clearRect(0, ((top * th) - scrollY), renderW, (bottom - top + 1) * th);
  79957. var trueLeft = Math.floor((0 + scrollX) / tw);
  79958. var trueRight = Math.floor((renderW - 1 + scrollX) / tw);
  79959. this.renderRegion(scrollX, scrollY, trueLeft, top, trueRight, bottom);
  79960. }
  79961. };
  79962. /**
  79963. * Clear and render the entire canvas.
  79964. *
  79965. * @method Phaser.TilemapLayer#renderFull
  79966. * @private
  79967. */
  79968. Phaser.TilemapLayer.prototype.renderFull = function () {
  79969. var scrollX = this._mc.scrollX;
  79970. var scrollY = this._mc.scrollY;
  79971. var renderW = this.canvas.width;
  79972. var renderH = this.canvas.height;
  79973. var tw = this._mc.tileWidth;
  79974. var th = this._mc.tileHeight;
  79975. var left = Math.floor(scrollX / tw);
  79976. var right = Math.floor((renderW - 1 + scrollX) / tw);
  79977. var top = Math.floor(scrollY / th);
  79978. var bottom = Math.floor((renderH - 1 + scrollY) / th);
  79979. this.context.clearRect(0, 0, renderW, renderH);
  79980. this.renderRegion(scrollX, scrollY, left, top, right, bottom);
  79981. };
  79982. /**
  79983. * Renders the tiles to the layer canvas and pushes to the display.
  79984. *
  79985. * @method Phaser.TilemapLayer#render
  79986. * @protected
  79987. */
  79988. Phaser.TilemapLayer.prototype.render = function () {
  79989. var redrawAll = false;
  79990. if (!this.visible)
  79991. {
  79992. return;
  79993. }
  79994. if (this.dirty || this.layer.dirty)
  79995. {
  79996. this.layer.dirty = false;
  79997. redrawAll = true;
  79998. }
  79999. var renderWidth = this.canvas.width; // Use Sprite.width/height?
  80000. var renderHeight = this.canvas.height;
  80001. // Scrolling bias; whole pixels only
  80002. var scrollX = this._scrollX | 0;
  80003. var scrollY = this._scrollY | 0;
  80004. var mc = this._mc;
  80005. var shiftX = mc.scrollX - scrollX; // Negative when scrolling right/down
  80006. var shiftY = mc.scrollY - scrollY;
  80007. if (!redrawAll &&
  80008. shiftX === 0 && shiftY === 0 &&
  80009. mc.renderWidth === renderWidth && mc.renderHeight === renderHeight)
  80010. {
  80011. // No reason to redraw map, looking at same thing and not invalidated.
  80012. return;
  80013. }
  80014. this.context.save();
  80015. mc.scrollX = scrollX;
  80016. mc.scrollY = scrollY;
  80017. if (mc.renderWidth !== renderWidth || mc.renderHeight !== renderHeight)
  80018. {
  80019. // Could support automatic canvas resizing
  80020. mc.renderWidth = renderWidth;
  80021. mc.renderHeight = renderHeight;
  80022. }
  80023. if (this.debug)
  80024. {
  80025. this.context.globalAlpha = this.debugSettings.debugAlpha;
  80026. if (this.debugSettings.forceFullRedraw)
  80027. {
  80028. redrawAll = true;
  80029. }
  80030. }
  80031. if (!redrawAll &&
  80032. this.renderSettings.enableScrollDelta &&
  80033. (Math.abs(shiftX) + Math.abs(shiftY)) < Math.min(renderWidth, renderHeight))
  80034. {
  80035. this.renderDeltaScroll(shiftX, shiftY);
  80036. }
  80037. else
  80038. {
  80039. // Too much change or otherwise requires full render
  80040. this.renderFull();
  80041. }
  80042. if (this.debug)
  80043. {
  80044. this.context.globalAlpha = 1;
  80045. this.renderDebug();
  80046. }
  80047. this.texture.baseTexture.dirty();
  80048. this.dirty = false;
  80049. this.context.restore();
  80050. return true;
  80051. };
  80052. /**
  80053. * Renders a debug overlay on-top of the canvas. Called automatically by render when `debug` is true.
  80054. *
  80055. * See `debugSettings` for assorted configuration options.
  80056. *
  80057. * @method Phaser.TilemapLayer#renderDebug
  80058. * @private
  80059. */
  80060. Phaser.TilemapLayer.prototype.renderDebug = function () {
  80061. var scrollX = this._mc.scrollX;
  80062. var scrollY = this._mc.scrollY;
  80063. var context = this.context;
  80064. var renderW = this.canvas.width;
  80065. var renderH = this.canvas.height;
  80066. var width = this.layer.width;
  80067. var height = this.layer.height;
  80068. var tw = this._mc.tileWidth;
  80069. var th = this._mc.tileHeight;
  80070. var left = Math.floor(scrollX / tw);
  80071. var right = Math.floor((renderW - 1 + scrollX) / tw);
  80072. var top = Math.floor(scrollY / th);
  80073. var bottom = Math.floor((renderH - 1 + scrollY) / th);
  80074. var baseX = (left * tw) - scrollX;
  80075. var baseY = (top * th) - scrollY;
  80076. var normStartX = (left + ((1 << 20) * width)) % width;
  80077. var normStartY = (top + ((1 << 20) * height)) % height;
  80078. var tx, ty, x, y, xmax, ymax;
  80079. context.strokeStyle = this.debugSettings.facingEdgeStroke;
  80080. for (y = normStartY, ymax = bottom - top, ty = baseY; ymax >= 0; y++, ymax--, ty += th)
  80081. {
  80082. if (y >= height)
  80083. {
  80084. y -= height;
  80085. }
  80086. var row = this.layer.data[y];
  80087. for (x = normStartX, xmax = right - left, tx = baseX; xmax >= 0; x++, xmax--, tx += tw)
  80088. {
  80089. if (x >= width)
  80090. {
  80091. x -= width;
  80092. }
  80093. var tile = row[x];
  80094. if (!tile || tile.index < 0 || !tile.collides)
  80095. {
  80096. continue;
  80097. }
  80098. if (this.debugSettings.collidingTileOverfill)
  80099. {
  80100. context.fillStyle = this.debugSettings.collidingTileOverfill;
  80101. context.fillRect(tx, ty, this._mc.cw, this._mc.ch);
  80102. }
  80103. if (this.debugSettings.facingEdgeStroke)
  80104. {
  80105. context.beginPath();
  80106. if (tile.faceTop)
  80107. {
  80108. context.moveTo(tx, ty);
  80109. context.lineTo(tx + this._mc.cw, ty);
  80110. }
  80111. if (tile.faceBottom)
  80112. {
  80113. context.moveTo(tx, ty + this._mc.ch);
  80114. context.lineTo(tx + this._mc.cw, ty + this._mc.ch);
  80115. }
  80116. if (tile.faceLeft)
  80117. {
  80118. context.moveTo(tx, ty);
  80119. context.lineTo(tx, ty + this._mc.ch);
  80120. }
  80121. if (tile.faceRight)
  80122. {
  80123. context.moveTo(tx + this._mc.cw, ty);
  80124. context.lineTo(tx + this._mc.cw, ty + this._mc.ch);
  80125. }
  80126. context.closePath();
  80127. context.stroke();
  80128. }
  80129. }
  80130. }
  80131. };
  80132. /**
  80133. * Flag controlling if the layer tiles wrap at the edges. Only works if the World size matches the Map size.
  80134. *
  80135. * @property {boolean} wrap
  80136. * @memberof Phaser.TilemapLayer
  80137. * @public
  80138. * @default false
  80139. */
  80140. Object.defineProperty(Phaser.TilemapLayer.prototype, "wrap", {
  80141. get: function () {
  80142. return this._wrap;
  80143. },
  80144. set: function (value) {
  80145. this._wrap = value;
  80146. this.dirty = true;
  80147. }
  80148. });
  80149. /**
  80150. * Scrolls the map horizontally or returns the current x position.
  80151. *
  80152. * @property {number} scrollX
  80153. * @memberof Phaser.TilemapLayer
  80154. * @public
  80155. */
  80156. Object.defineProperty(Phaser.TilemapLayer.prototype, "scrollX", {
  80157. get: function () {
  80158. return this._scrollX;
  80159. },
  80160. set: function (value) {
  80161. this._scrollX = value;
  80162. }
  80163. });
  80164. /**
  80165. * Scrolls the map vertically or returns the current y position.
  80166. *
  80167. * @property {number} scrollY
  80168. * @memberof Phaser.TilemapLayer
  80169. * @public
  80170. */
  80171. Object.defineProperty(Phaser.TilemapLayer.prototype, "scrollY", {
  80172. get: function () {
  80173. return this._scrollY;
  80174. },
  80175. set: function (value) {
  80176. this._scrollY = value;
  80177. }
  80178. });
  80179. /**
  80180. * The width of the collision tiles (in pixels).
  80181. *
  80182. * @property {integer} collisionWidth
  80183. * @memberof Phaser.TilemapLayer
  80184. * @public
  80185. */
  80186. Object.defineProperty(Phaser.TilemapLayer.prototype, "collisionWidth", {
  80187. get: function () {
  80188. return this._mc.cw;
  80189. },
  80190. set: function (value) {
  80191. this._mc.cw = value | 0;
  80192. this.dirty = true;
  80193. }
  80194. });
  80195. /**
  80196. * The height of the collision tiles (in pixels).
  80197. *
  80198. * @property {integer} collisionHeight
  80199. * @memberof Phaser.TilemapLayer
  80200. * @public
  80201. */
  80202. Object.defineProperty(Phaser.TilemapLayer.prototype, "collisionHeight", {
  80203. get: function () {
  80204. return this._mc.ch;
  80205. },
  80206. set: function (value) {
  80207. this._mc.ch = value | 0;
  80208. this.dirty = true;
  80209. }
  80210. });
  80211. /**
  80212. * @author Richard Davey <rich@photonstorm.com>
  80213. * @copyright 2016 Photon Storm Ltd.
  80214. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  80215. */
  80216. /**
  80217. * Phaser.TilemapParser parses data objects from Phaser.Loader that need more preparation before they can be inserted into a Tilemap.
  80218. *
  80219. * @class Phaser.TilemapParser
  80220. * @static
  80221. */
  80222. Phaser.TilemapParser = {
  80223. /**
  80224. * When scanning the Tiled map data the TilemapParser can either insert a null value (true) or
  80225. * a Phaser.Tile instance with an index of -1 (false, the default). Depending on your game type
  80226. * depends how this should be configured. If you've a large sparsely populated map and the tile
  80227. * data doesn't need to change then setting this value to `true` will help with memory consumption.
  80228. * However if your map is small, or you need to update the tiles (perhaps the map dynamically changes
  80229. * during the game) then leave the default value set.
  80230. *
  80231. * @constant
  80232. * @type {boolean}
  80233. */
  80234. INSERT_NULL: false,
  80235. /**
  80236. * Parse tilemap data from the cache and creates data for a Tilemap object.
  80237. *
  80238. * @method Phaser.TilemapParser.parse
  80239. * @param {Phaser.Game} game - Game reference to the currently running game.
  80240. * @param {string} key - The key of the tilemap in the Cache.
  80241. * @param {number} [tileWidth=32] - The pixel width of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data.
  80242. * @param {number} [tileHeight=32] - The pixel height of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data.
  80243. * @param {number} [width=10] - The width of the map in tiles. If this map is created from Tiled or CSV data you don't need to specify this.
  80244. * @param {number} [height=10] - The height of the map in tiles. If this map is created from Tiled or CSV data you don't need to specify this.
  80245. * @return {object} The parsed map object.
  80246. */
  80247. parse: function (game, key, tileWidth, tileHeight, width, height) {
  80248. if (tileWidth === undefined) { tileWidth = 32; }
  80249. if (tileHeight === undefined) { tileHeight = 32; }
  80250. if (width === undefined) { width = 10; }
  80251. if (height === undefined) { height = 10; }
  80252. if (key === undefined)
  80253. {
  80254. return this.getEmptyData();
  80255. }
  80256. if (key === null)
  80257. {
  80258. return this.getEmptyData(tileWidth, tileHeight, width, height);
  80259. }
  80260. var map = game.cache.getTilemapData(key);
  80261. if (map)
  80262. {
  80263. if (map.format === Phaser.Tilemap.CSV)
  80264. {
  80265. return this.parseCSV(key, map.data, tileWidth, tileHeight);
  80266. }
  80267. else if (!map.format || map.format === Phaser.Tilemap.TILED_JSON)
  80268. {
  80269. return this.parseTiledJSON(map.data);
  80270. }
  80271. }
  80272. else
  80273. {
  80274. console.warn('Phaser.TilemapParser.parse - No map data found for key ' + key);
  80275. }
  80276. },
  80277. /**
  80278. * Parses a CSV file into valid map data.
  80279. *
  80280. * @method Phaser.TilemapParser.parseCSV
  80281. * @param {string} key - The name you want to give the map data.
  80282. * @param {string} data - The CSV file data.
  80283. * @param {number} [tileWidth=32] - The pixel width of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data.
  80284. * @param {number} [tileHeight=32] - The pixel height of a single map tile. If using CSV data you must specify this. Not required if using Tiled map data.
  80285. * @return {object} Generated map data.
  80286. */
  80287. parseCSV: function (key, data, tileWidth, tileHeight) {
  80288. var map = this.getEmptyData();
  80289. // Trim any rogue whitespace from the data
  80290. data = data.trim();
  80291. var output = [];
  80292. var rows = data.split("\n");
  80293. var height = rows.length;
  80294. var width = 0;
  80295. for (var y = 0; y < rows.length; y++)
  80296. {
  80297. output[y] = [];
  80298. var column = rows[y].split(",");
  80299. for (var x = 0; x < column.length; x++)
  80300. {
  80301. output[y][x] = new Phaser.Tile(map.layers[0], parseInt(column[x], 10), x, y, tileWidth, tileHeight);
  80302. }
  80303. if (width === 0)
  80304. {
  80305. width = column.length;
  80306. }
  80307. }
  80308. map.format = Phaser.Tilemap.CSV;
  80309. map.name = key;
  80310. map.width = width;
  80311. map.height = height;
  80312. map.tileWidth = tileWidth;
  80313. map.tileHeight = tileHeight;
  80314. map.widthInPixels = width * tileWidth;
  80315. map.heightInPixels = height * tileHeight;
  80316. map.layers[0].width = width;
  80317. map.layers[0].height = height;
  80318. map.layers[0].widthInPixels = map.widthInPixels;
  80319. map.layers[0].heightInPixels = map.heightInPixels;
  80320. map.layers[0].data = output;
  80321. return map;
  80322. },
  80323. /**
  80324. * Returns an empty map data object.
  80325. *
  80326. * @method Phaser.TilemapParser.getEmptyData
  80327. * @return {object} Generated map data.
  80328. */
  80329. getEmptyData: function (tileWidth, tileHeight, width, height) {
  80330. return {
  80331. width: (width !== undefined && width !== null) ? width : 0,
  80332. height: (height !== undefined && height !== null) ? height : 0,
  80333. tileWidth: (tileWidth !== undefined && tileWidth !== null) ? tileWidth : 0,
  80334. tileHeight: (tileHeight !== undefined && tileHeight !== null) ? tileHeight : 0,
  80335. orientation: 'orthogonal',
  80336. version: '1',
  80337. properties: {},
  80338. widthInPixels: 0,
  80339. heightInPixels: 0,
  80340. layers: [
  80341. {
  80342. name: 'layer',
  80343. x: 0,
  80344. y: 0,
  80345. width: 0,
  80346. height: 0,
  80347. widthInPixels: 0,
  80348. heightInPixels: 0,
  80349. alpha: 1,
  80350. visible: true,
  80351. properties: {},
  80352. indexes: [],
  80353. callbacks: [],
  80354. bodies: [],
  80355. data: []
  80356. }
  80357. ],
  80358. images: [],
  80359. objects: {},
  80360. collision: {},
  80361. tilesets: [],
  80362. tiles: []
  80363. };
  80364. },
  80365. /**
  80366. * Parses a Tiled JSON file into valid map data.
  80367. * @method Phaser.TilemapParser.parseJSON
  80368. * @param {object} json - The JSON map data.
  80369. * @return {object} Generated and parsed map data.
  80370. */
  80371. parseTiledJSON: function (json) {
  80372. if (json.orientation !== 'orthogonal')
  80373. {
  80374. console.warn('TilemapParser.parseTiledJSON - Only orthogonal map types are supported in this version of Phaser');
  80375. return null;
  80376. }
  80377. // Map data will consist of: layers, objects, images, tilesets, sizes
  80378. var map = {
  80379. width: json.width,
  80380. height: json.height,
  80381. tileWidth: json.tilewidth,
  80382. tileHeight: json.tileheight,
  80383. orientation: json.orientation,
  80384. format: Phaser.Tilemap.TILED_JSON,
  80385. version: json.version,
  80386. properties: json.properties,
  80387. widthInPixels: json.width * json.tilewidth,
  80388. heightInPixels: json.height * json.tileheight
  80389. };
  80390. // Tile Layers
  80391. var layers = [];
  80392. for (var i = 0; i < json.layers.length; i++)
  80393. {
  80394. if (json.layers[i].type !== 'tilelayer')
  80395. {
  80396. continue;
  80397. }
  80398. var curl = json.layers[i];
  80399. // Base64 decode data if necessary
  80400. // NOTE: uncompressed base64 only.
  80401. if (!curl.compression && curl.encoding && curl.encoding === 'base64')
  80402. {
  80403. var binaryString = window.atob(curl.data);
  80404. var len = binaryString.length;
  80405. var bytes = new Array(len);
  80406. // Interpret binaryString as an array of bytes representing
  80407. // little-endian encoded uint32 values.
  80408. for (var j = 0; j < len; j+=4)
  80409. {
  80410. bytes[j / 4] = (
  80411. binaryString.charCodeAt(j) |
  80412. binaryString.charCodeAt(j + 1) << 8 |
  80413. binaryString.charCodeAt(j + 2) << 16 |
  80414. binaryString.charCodeAt(j + 3) << 24
  80415. ) >>> 0;
  80416. }
  80417. curl.data = bytes;
  80418. delete curl.encoding;
  80419. }
  80420. else if (curl.compression)
  80421. {
  80422. console.warn('TilemapParser.parseTiledJSON - Layer compression is unsupported, skipping layer \'' + curl.name + '\'');
  80423. continue;
  80424. }
  80425. var layer = {
  80426. name: curl.name,
  80427. x: curl.x,
  80428. y: curl.y,
  80429. width: curl.width,
  80430. height: curl.height,
  80431. widthInPixels: curl.width * json.tilewidth,
  80432. heightInPixels: curl.height * json.tileheight,
  80433. alpha: curl.opacity,
  80434. visible: curl.visible,
  80435. properties: {},
  80436. indexes: [],
  80437. callbacks: [],
  80438. bodies: []
  80439. };
  80440. if (curl.properties)
  80441. {
  80442. layer.properties = curl.properties;
  80443. }
  80444. var x = 0;
  80445. var row = [];
  80446. var output = [];
  80447. var rotation, flipped, flippedVal, gid;
  80448. // Loop through the data field in the JSON.
  80449. // This is an array containing the tile indexes, one after the other. -1 = no tile, everything else = the tile index (starting at 1 for Tiled, 0 for CSV)
  80450. // If the map contains multiple tilesets then the indexes are relative to that which the set starts from.
  80451. // Need to set which tileset in the cache = which tileset in the JSON, if you do this manually it means you can use the same map data but a new tileset.
  80452. for (var t = 0, len = curl.data.length; t < len; t++)
  80453. {
  80454. rotation = 0;
  80455. flipped = false;
  80456. gid = curl.data[t];
  80457. flippedVal = 0;
  80458. // If true the current tile is flipped or rotated (Tiled TMX format)
  80459. if (gid > 0x20000000)
  80460. {
  80461. // FlippedX
  80462. if (gid > 0x80000000)
  80463. {
  80464. gid -= 0x80000000;
  80465. flippedVal += 4;
  80466. }
  80467. // FlippedY
  80468. if (gid > 0x40000000)
  80469. {
  80470. gid -= 0x40000000;
  80471. flippedVal += 2;
  80472. }
  80473. // FlippedAD (anti-diagonal = top-right is swapped with bottom-left corners)
  80474. if (gid > 0x20000000)
  80475. {
  80476. gid -= 0x20000000;
  80477. flippedVal += 1;
  80478. }
  80479. switch (flippedVal)
  80480. {
  80481. case 5:
  80482. rotation = Math.PI / 2;
  80483. break;
  80484. case 6:
  80485. rotation = Math.PI;
  80486. break;
  80487. case 3:
  80488. rotation = 3 * Math.PI / 2;
  80489. break;
  80490. case 4:
  80491. rotation = 0;
  80492. flipped = true;
  80493. break;
  80494. case 7:
  80495. rotation = Math.PI / 2;
  80496. flipped = true;
  80497. break;
  80498. case 2:
  80499. rotation = Math.PI;
  80500. flipped = true;
  80501. break;
  80502. case 1:
  80503. rotation = 3 * Math.PI / 2;
  80504. flipped = true;
  80505. break;
  80506. }
  80507. }
  80508. // index, x, y, width, height
  80509. if (gid > 0)
  80510. {
  80511. var tile = new Phaser.Tile(layer, gid, x, output.length, json.tilewidth, json.tileheight);
  80512. tile.rotation = rotation;
  80513. tile.flipped = flipped;
  80514. if (flippedVal !== 0)
  80515. {
  80516. // The WebGL renderer uses this to flip UV coordinates before drawing
  80517. tile.flippedVal = flippedVal;
  80518. }
  80519. row.push(tile);
  80520. }
  80521. else
  80522. {
  80523. if (Phaser.TilemapParser.INSERT_NULL)
  80524. {
  80525. row.push(null);
  80526. }
  80527. else
  80528. {
  80529. row.push(new Phaser.Tile(layer, -1, x, output.length, json.tilewidth, json.tileheight));
  80530. }
  80531. }
  80532. x++;
  80533. if (x === curl.width)
  80534. {
  80535. output.push(row);
  80536. x = 0;
  80537. row = [];
  80538. }
  80539. }
  80540. layer.data = output;
  80541. layers.push(layer);
  80542. }
  80543. map.layers = layers;
  80544. // Images
  80545. var images = [];
  80546. for (var i = 0; i < json.layers.length; i++)
  80547. {
  80548. if (json.layers[i].type !== 'imagelayer')
  80549. {
  80550. continue;
  80551. }
  80552. var curi = json.layers[i];
  80553. var image = {
  80554. name: curi.name,
  80555. image: curi.image,
  80556. x: curi.x,
  80557. y: curi.y,
  80558. alpha: curi.opacity,
  80559. visible: curi.visible,
  80560. properties: {}
  80561. };
  80562. if (curi.properties)
  80563. {
  80564. image.properties = curi.properties;
  80565. }
  80566. images.push(image);
  80567. }
  80568. map.images = images;
  80569. // Tilesets & Image Collections
  80570. var tilesets = [];
  80571. var imagecollections = [];
  80572. var lastSet = null;
  80573. for (var i = 0; i < json.tilesets.length; i++)
  80574. {
  80575. // name, firstgid, width, height, margin, spacing, properties
  80576. var set = json.tilesets[i];
  80577. if (set.image)
  80578. {
  80579. var newSet = new Phaser.Tileset(set.name, set.firstgid, set.tilewidth, set.tileheight, set.margin, set.spacing, set.properties);
  80580. if (set.tileproperties)
  80581. {
  80582. newSet.tileProperties = set.tileproperties;
  80583. }
  80584. // For a normal sliced tileset the row/count/size information is computed when updated.
  80585. // This is done (again) after the image is set.
  80586. newSet.updateTileData(set.imagewidth, set.imageheight);
  80587. tilesets.push(newSet);
  80588. }
  80589. else
  80590. {
  80591. var newCollection = new Phaser.ImageCollection(set.name, set.firstgid, set.tilewidth, set.tileheight, set.margin, set.spacing, set.properties);
  80592. for (var ti in set.tiles)
  80593. {
  80594. var image = set.tiles[ti].image;
  80595. var gid = set.firstgid + parseInt(ti, 10);
  80596. newCollection.addImage(gid, image);
  80597. }
  80598. imagecollections.push(newCollection);
  80599. }
  80600. // We've got a new Tileset, so set the lastgid into the previous one
  80601. if (lastSet)
  80602. {
  80603. lastSet.lastgid = set.firstgid - 1;
  80604. }
  80605. lastSet = set;
  80606. }
  80607. map.tilesets = tilesets;
  80608. map.imagecollections = imagecollections;
  80609. // Objects & Collision Data (polylines, etc)
  80610. var objects = {};
  80611. var collision = {};
  80612. function slice (obj, fields) {
  80613. var sliced = {};
  80614. for (var k in fields)
  80615. {
  80616. var key = fields[k];
  80617. if (typeof obj[key] !== 'undefined')
  80618. {
  80619. sliced[key] = obj[key];
  80620. }
  80621. }
  80622. return sliced;
  80623. }
  80624. for (var i = 0; i < json.layers.length; i++)
  80625. {
  80626. if (json.layers[i].type !== 'objectgroup')
  80627. {
  80628. continue;
  80629. }
  80630. var curo = json.layers[i];
  80631. objects[curo.name] = [];
  80632. collision[curo.name] = [];
  80633. for (var v = 0, len = curo.objects.length; v < len; v++)
  80634. {
  80635. // Object Tiles
  80636. if (curo.objects[v].gid)
  80637. {
  80638. var object = {
  80639. gid: curo.objects[v].gid,
  80640. name: curo.objects[v].name,
  80641. type: curo.objects[v].hasOwnProperty("type") ? curo.objects[v].type : "",
  80642. x: curo.objects[v].x,
  80643. y: curo.objects[v].y,
  80644. visible: curo.objects[v].visible,
  80645. properties: curo.objects[v].properties
  80646. };
  80647. if (curo.objects[v].rotation)
  80648. {
  80649. object.rotation = curo.objects[v].rotation;
  80650. }
  80651. objects[curo.name].push(object);
  80652. }
  80653. else if (curo.objects[v].polyline)
  80654. {
  80655. var object = {
  80656. name: curo.objects[v].name,
  80657. type: curo.objects[v].type,
  80658. x: curo.objects[v].x,
  80659. y: curo.objects[v].y,
  80660. width: curo.objects[v].width,
  80661. height: curo.objects[v].height,
  80662. visible: curo.objects[v].visible,
  80663. properties: curo.objects[v].properties
  80664. };
  80665. if (curo.objects[v].rotation)
  80666. {
  80667. object.rotation = curo.objects[v].rotation;
  80668. }
  80669. object.polyline = [];
  80670. // Parse the polyline into an array
  80671. for (var p = 0; p < curo.objects[v].polyline.length; p++)
  80672. {
  80673. object.polyline.push([ curo.objects[v].polyline[p].x, curo.objects[v].polyline[p].y ]);
  80674. }
  80675. collision[curo.name].push(object);
  80676. objects[curo.name].push(object);
  80677. }
  80678. // polygon
  80679. else if (curo.objects[v].polygon)
  80680. {
  80681. var object = slice(curo.objects[v], ['name', 'type', 'x', 'y', 'visible', 'rotation', 'properties']);
  80682. // Parse the polygon into an array
  80683. object.polygon = [];
  80684. for (var p = 0; p < curo.objects[v].polygon.length; p++)
  80685. {
  80686. object.polygon.push([curo.objects[v].polygon[p].x, curo.objects[v].polygon[p].y]);
  80687. }
  80688. objects[curo.name].push(object);
  80689. }
  80690. // ellipse
  80691. else if (curo.objects[v].ellipse)
  80692. {
  80693. var object = slice(curo.objects[v], ['name', 'type', 'ellipse', 'x', 'y', 'width', 'height', 'visible', 'rotation', 'properties']);
  80694. objects[curo.name].push(object);
  80695. }
  80696. // otherwise it's a rectangle
  80697. else
  80698. {
  80699. var object = slice(curo.objects[v], ['name', 'type', 'x', 'y', 'width', 'height', 'visible', 'rotation', 'properties']);
  80700. object.rectangle = true;
  80701. objects[curo.name].push(object);
  80702. }
  80703. }
  80704. }
  80705. map.objects = objects;
  80706. map.collision = collision;
  80707. map.tiles = [];
  80708. // Finally lets build our super tileset index
  80709. for (var i = 0; i < map.tilesets.length; i++)
  80710. {
  80711. var set = map.tilesets[i];
  80712. var x = set.tileMargin;
  80713. var y = set.tileMargin;
  80714. var count = 0;
  80715. var countX = 0;
  80716. var countY = 0;
  80717. for (var t = set.firstgid; t < set.firstgid + set.total; t++)
  80718. {
  80719. // Can add extra properties here as needed
  80720. map.tiles[t] = [x, y, i];
  80721. x += set.tileWidth + set.tileSpacing;
  80722. count++;
  80723. if (count === set.total)
  80724. {
  80725. break;
  80726. }
  80727. countX++;
  80728. if (countX === set.columns)
  80729. {
  80730. x = set.tileMargin;
  80731. y += set.tileHeight + set.tileSpacing;
  80732. countX = 0;
  80733. countY++;
  80734. if (countY === set.rows)
  80735. {
  80736. break;
  80737. }
  80738. }
  80739. }
  80740. }
  80741. // assign tile properties
  80742. var layer;
  80743. var tile;
  80744. var sid;
  80745. var set;
  80746. // go through each of the map data layers
  80747. for (var i = 0; i < map.layers.length; i++)
  80748. {
  80749. layer = map.layers[i];
  80750. set = null;
  80751. // rows of tiles
  80752. for (var j = 0; j < layer.data.length; j++)
  80753. {
  80754. row = layer.data[j];
  80755. // individual tiles
  80756. for (var k = 0; k < row.length; k++)
  80757. {
  80758. tile = row[k];
  80759. if (tile === null || tile.index < 0)
  80760. {
  80761. continue;
  80762. }
  80763. // find the relevant tileset
  80764. sid = map.tiles[tile.index][2];
  80765. set = map.tilesets[sid];
  80766. // if that tile type has any properties, add them to the tile object
  80767. if (set.tileProperties && set.tileProperties[tile.index - set.firstgid])
  80768. {
  80769. tile.properties = Phaser.Utils.mixin(set.tileProperties[tile.index - set.firstgid], tile.properties);
  80770. }
  80771. }
  80772. }
  80773. }
  80774. return map;
  80775. }
  80776. };
  80777. /**
  80778. * @author Richard Davey <rich@photonstorm.com>
  80779. * @copyright 2016 Photon Storm Ltd.
  80780. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  80781. */
  80782. /**
  80783. * A Tile set is a combination of an image containing the tiles and collision data per tile.
  80784. *
  80785. * Tilesets are normally created automatically when Tiled data is loaded.
  80786. *
  80787. * @class Phaser.Tileset
  80788. * @constructor
  80789. * @param {string} name - The name of the tileset in the map data.
  80790. * @param {integer} firstgid - The first tile index this tileset contains.
  80791. * @param {integer} [width=32] - Width of each tile (in pixels).
  80792. * @param {integer} [height=32] - Height of each tile (in pixels).
  80793. * @param {integer} [margin=0] - The margin around all tiles in the sheet (in pixels).
  80794. * @param {integer} [spacing=0] - The spacing between each tile in the sheet (in pixels).
  80795. * @param {object} [properties={}] - Custom Tileset properties.
  80796. */
  80797. Phaser.Tileset = function (name, firstgid, width, height, margin, spacing, properties) {
  80798. if (width === undefined || width <= 0) { width = 32; }
  80799. if (height === undefined || height <= 0) { height = 32; }
  80800. if (margin === undefined) { margin = 0; }
  80801. if (spacing === undefined) { spacing = 0; }
  80802. /**
  80803. * The name of the Tileset.
  80804. * @property {string} name
  80805. */
  80806. this.name = name;
  80807. /**
  80808. * The Tiled firstgid value.
  80809. * This is the starting index of the first tile index this Tileset contains.
  80810. * @property {integer} firstgid
  80811. */
  80812. this.firstgid = firstgid | 0;
  80813. /**
  80814. * The width of each tile (in pixels).
  80815. * @property {integer} tileWidth
  80816. * @readonly
  80817. */
  80818. this.tileWidth = width | 0;
  80819. /**
  80820. * The height of each tile (in pixels).
  80821. * @property {integer} tileHeight
  80822. * @readonly
  80823. */
  80824. this.tileHeight = height | 0;
  80825. /**
  80826. * The margin around the tiles in the sheet (in pixels).
  80827. * Use `setSpacing` to change.
  80828. * @property {integer} tileMarge
  80829. * @readonly
  80830. */
  80831. // Modified internally
  80832. this.tileMargin = margin | 0;
  80833. /**
  80834. * The spacing between each tile in the sheet (in pixels).
  80835. * Use `setSpacing` to change.
  80836. * @property {integer} tileSpacing
  80837. * @readonly
  80838. */
  80839. this.tileSpacing = spacing | 0;
  80840. /**
  80841. * Tileset-specific properties that are typically defined in the Tiled editor.
  80842. * @property {object} properties
  80843. */
  80844. this.properties = properties || {};
  80845. /**
  80846. * The cached image that contains the individual tiles. Use {@link Phaser.Tileset.setImage setImage} to set.
  80847. * @property {?object} image
  80848. * @readonly
  80849. */
  80850. // Modified internally
  80851. this.image = null;
  80852. /**
  80853. * The number of tile rows in the the tileset.
  80854. * @property {integer}
  80855. * @readonly
  80856. */
  80857. // Modified internally
  80858. this.rows = 0;
  80859. /**
  80860. * The number of tile columns in the tileset.
  80861. * @property {integer} columns
  80862. * @readonly
  80863. */
  80864. // Modified internally
  80865. this.columns = 0;
  80866. /**
  80867. * The total number of tiles in the tileset.
  80868. * @property {integer} total
  80869. * @readonly
  80870. */
  80871. // Modified internally
  80872. this.total = 0;
  80873. /**
  80874. * The look-up table to specific tile image offsets.
  80875. * The coordinates are interlaced such that it is [x0, y0, x1, y1 .. xN, yN] and the tile with the index of firstgid is found at indices 0/1.
  80876. * @property {integer[]} drawCoords
  80877. * @private
  80878. */
  80879. this.drawCoords = [];
  80880. };
  80881. Phaser.Tileset.prototype = {
  80882. /**
  80883. * Draws a tile from this Tileset at the given coordinates on the context.
  80884. *
  80885. * @method Phaser.Tileset#draw
  80886. * @public
  80887. * @param {CanvasRenderingContext2D} context - The context to draw the tile onto.
  80888. * @param {number} x - The x coordinate to draw to.
  80889. * @param {number} y - The y coordinate to draw to.
  80890. * @param {integer} index - The index of the tile within the set to draw.
  80891. */
  80892. draw: function (context, x, y, index) {
  80893. // Correct the tile index for the set and bias for interlacing
  80894. var coordIndex = (index - this.firstgid) << 1;
  80895. if (coordIndex >= 0 && (coordIndex + 1) < this.drawCoords.length)
  80896. {
  80897. context.drawImage(
  80898. this.image,
  80899. this.drawCoords[coordIndex],
  80900. this.drawCoords[coordIndex + 1],
  80901. this.tileWidth,
  80902. this.tileHeight,
  80903. x,
  80904. y,
  80905. this.tileWidth,
  80906. this.tileHeight
  80907. );
  80908. }
  80909. },
  80910. /**
  80911. * Returns true if and only if this tileset contains the given tile index.
  80912. *
  80913. * @method Phaser.Tileset#containsTileIndex
  80914. * @public
  80915. * @return {boolean} True if this tileset contains the given index.
  80916. */
  80917. containsTileIndex: function (tileIndex) {
  80918. return (
  80919. tileIndex >= this.firstgid &&
  80920. tileIndex < (this.firstgid + this.total)
  80921. );
  80922. },
  80923. /**
  80924. * Set the image associated with this Tileset and update the tile data.
  80925. *
  80926. * @method Phaser.Tileset#setImage
  80927. * @public
  80928. * @param {Image} image - The image that contains the tiles.
  80929. */
  80930. setImage: function (image) {
  80931. this.image = image;
  80932. this.updateTileData(image.width, image.height);
  80933. },
  80934. /**
  80935. * Sets tile spacing and margins.
  80936. *
  80937. * @method Phaser.Tileset#setSpacing
  80938. * @public
  80939. * @param {integer} [margin=0] - The margin around the tiles in the sheet (in pixels).
  80940. * @param {integer} [spacing=0] - The spacing between the tiles in the sheet (in pixels).
  80941. */
  80942. setSpacing: function (margin, spacing) {
  80943. this.tileMargin = margin | 0;
  80944. this.tileSpacing = spacing | 0;
  80945. if (this.image)
  80946. {
  80947. this.updateTileData(this.image.width, this.image.height);
  80948. }
  80949. },
  80950. /**
  80951. * Updates tile coordinates and tileset data.
  80952. *
  80953. * @method Phaser.Tileset#updateTileData
  80954. * @private
  80955. * @param {integer} imageWidth - The (expected) width of the image to slice.
  80956. * @param {integer} imageHeight - The (expected) height of the image to slice.
  80957. */
  80958. updateTileData: function (imageWidth, imageHeight) {
  80959. // May be fractional values
  80960. var rowCount = (imageHeight - this.tileMargin * 2 + this.tileSpacing) / (this.tileHeight + this.tileSpacing);
  80961. var colCount = (imageWidth - this.tileMargin * 2 + this.tileSpacing) / (this.tileWidth + this.tileSpacing);
  80962. if (rowCount % 1 !== 0 || colCount % 1 !== 0)
  80963. {
  80964. console.warn("Phaser.Tileset - " + this.name + " image tile area is not an even multiple of tile size");
  80965. }
  80966. // In Tiled a tileset image that is not an even multiple of the tile dimensions
  80967. // is truncated - hence the floor when calculating the rows/columns.
  80968. rowCount = Math.floor(rowCount);
  80969. colCount = Math.floor(colCount);
  80970. if ((this.rows && this.rows !== rowCount) || (this.columns && this.columns !== colCount))
  80971. {
  80972. console.warn("Phaser.Tileset - actual and expected number of tile rows and columns differ");
  80973. }
  80974. this.rows = rowCount;
  80975. this.columns = colCount;
  80976. this.total = rowCount * colCount;
  80977. this.drawCoords.length = 0;
  80978. var tx = this.tileMargin;
  80979. var ty = this.tileMargin;
  80980. for (var y = 0; y < this.rows; y++)
  80981. {
  80982. for (var x = 0; x < this.columns; x++)
  80983. {
  80984. this.drawCoords.push(tx);
  80985. this.drawCoords.push(ty);
  80986. tx += this.tileWidth + this.tileSpacing;
  80987. }
  80988. tx = this.tileMargin;
  80989. ty += this.tileHeight + this.tileSpacing;
  80990. }
  80991. }
  80992. };
  80993. Phaser.Tileset.prototype.constructor = Phaser.Tileset;
  80994. /**
  80995. * @author Richard Davey <rich@photonstorm.com>
  80996. * @copyright 2016 Photon Storm Ltd.
  80997. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  80998. */
  80999. /**
  81000. * Create a new `Particle` object. Particles are extended Sprites that are emitted by a particle emitter such as Phaser.Particles.Arcade.Emitter.
  81001. *
  81002. * @class Phaser.Particle
  81003. * @constructor
  81004. * @extends Phaser.Sprite
  81005. * @param {Phaser.Game} game - A reference to the currently running game.
  81006. * @param {number} x - The x coordinate (in world space) to position the Particle at.
  81007. * @param {number} y - The y coordinate (in world space) to position the Particle at.
  81008. * @param {string|Phaser.RenderTexture|Phaser.BitmapData|PIXI.Texture} key - This is the image or texture used by the Particle during rendering. It can be a string which is a reference to the Cache entry, or an instance of a RenderTexture or PIXI.Texture.
  81009. * @param {string|number} frame - If this Particle is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index.
  81010. */
  81011. Phaser.Particle = function (game, x, y, key, frame) {
  81012. Phaser.Sprite.call(this, game, x, y, key, frame);
  81013. /**
  81014. * @property {boolean} autoScale - If this Particle automatically scales this is set to true by Particle.setScaleData.
  81015. * @protected
  81016. */
  81017. this.autoScale = false;
  81018. /**
  81019. * @property {array} scaleData - A reference to the scaleData array owned by the Emitter that emitted this Particle.
  81020. * @protected
  81021. */
  81022. this.scaleData = null;
  81023. /**
  81024. * @property {number} _s - Internal cache var for tracking auto scale.
  81025. * @private
  81026. */
  81027. this._s = 0;
  81028. /**
  81029. * @property {boolean} autoAlpha - If this Particle automatically changes alpha this is set to true by Particle.setAlphaData.
  81030. * @protected
  81031. */
  81032. this.autoAlpha = false;
  81033. /**
  81034. * @property {array} alphaData - A reference to the alphaData array owned by the Emitter that emitted this Particle.
  81035. * @protected
  81036. */
  81037. this.alphaData = null;
  81038. /**
  81039. * @property {number} _a - Internal cache var for tracking auto alpha.
  81040. * @private
  81041. */
  81042. this._a = 0;
  81043. };
  81044. Phaser.Particle.prototype = Object.create(Phaser.Sprite.prototype);
  81045. Phaser.Particle.prototype.constructor = Phaser.Particle;
  81046. /**
  81047. * Updates the Particle scale or alpha if autoScale and autoAlpha are set.
  81048. *
  81049. * @method Phaser.Particle#update
  81050. * @memberof Phaser.Particle
  81051. */
  81052. Phaser.Particle.prototype.update = function() {
  81053. if (this.autoScale)
  81054. {
  81055. this._s--;
  81056. if (this._s)
  81057. {
  81058. this.scale.set(this.scaleData[this._s].x, this.scaleData[this._s].y);
  81059. }
  81060. else
  81061. {
  81062. this.autoScale = false;
  81063. }
  81064. }
  81065. if (this.autoAlpha)
  81066. {
  81067. this._a--;
  81068. if (this._a)
  81069. {
  81070. this.alpha = this.alphaData[this._a].v;
  81071. }
  81072. else
  81073. {
  81074. this.autoAlpha = false;
  81075. }
  81076. }
  81077. };
  81078. /**
  81079. * Called by the Emitter when this particle is emitted. Left empty for you to over-ride as required.
  81080. *
  81081. * @method Phaser.Particle#onEmit
  81082. * @memberof Phaser.Particle
  81083. */
  81084. Phaser.Particle.prototype.onEmit = function() {
  81085. };
  81086. /**
  81087. * Called by the Emitter if autoAlpha has been enabled. Passes over the alpha ease data and resets the alpha counter.
  81088. *
  81089. * @method Phaser.Particle#setAlphaData
  81090. * @memberof Phaser.Particle
  81091. */
  81092. Phaser.Particle.prototype.setAlphaData = function(data) {
  81093. this.alphaData = data;
  81094. this._a = data.length - 1;
  81095. this.alpha = this.alphaData[this._a].v;
  81096. this.autoAlpha = true;
  81097. };
  81098. /**
  81099. * Called by the Emitter if autoScale has been enabled. Passes over the scale ease data and resets the scale counter.
  81100. *
  81101. * @method Phaser.Particle#setScaleData
  81102. * @memberof Phaser.Particle
  81103. */
  81104. Phaser.Particle.prototype.setScaleData = function(data) {
  81105. this.scaleData = data;
  81106. this._s = data.length - 1;
  81107. this.scale.set(this.scaleData[this._s].x, this.scaleData[this._s].y);
  81108. this.autoScale = true;
  81109. };
  81110. /**
  81111. * Resets the Particle. This places the Particle at the given x/y world coordinates and then
  81112. * sets alive, exists, visible and renderable all to true. Also resets the outOfBounds state and health values.
  81113. * If the Particle has a physics body that too is reset.
  81114. *
  81115. * @method Phaser.Particle#reset
  81116. * @memberof Phaser.Particle
  81117. * @param {number} x - The x coordinate (in world space) to position the Particle at.
  81118. * @param {number} y - The y coordinate (in world space) to position the Particle at.
  81119. * @param {number} [health=1] - The health to give the Particle.
  81120. * @return {Phaser.Particle} This instance.
  81121. */
  81122. Phaser.Particle.prototype.reset = function(x, y, health) {
  81123. Phaser.Component.Reset.prototype.reset.call(this, x, y, health);
  81124. this.alpha = 1;
  81125. this.scale.set(1);
  81126. this.autoScale = false;
  81127. this.autoAlpha = false;
  81128. return this;
  81129. };
  81130. /**
  81131. * @author Richard Davey <rich@photonstorm.com>
  81132. * @copyright 2016 Photon Storm Ltd.
  81133. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  81134. */
  81135. /**
  81136. * Phaser.Particles is the Particle Manager for the game. It is called during the game update loop and in turn updates any Emitters attached to it.
  81137. *
  81138. * @class Phaser.Particles
  81139. * @constructor
  81140. * @param {Phaser.Game} game - A reference to the currently running game.
  81141. */
  81142. Phaser.Particles = function (game) {
  81143. /**
  81144. * @property {Phaser.Game} game - A reference to the currently running Game.
  81145. */
  81146. this.game = game;
  81147. /**
  81148. * @property {object} emitters - Internal emitters store.
  81149. */
  81150. this.emitters = {};
  81151. /**
  81152. * @property {number} ID -
  81153. * @default
  81154. */
  81155. this.ID = 0;
  81156. };
  81157. Phaser.Particles.prototype = {
  81158. /**
  81159. * Adds a new Particle Emitter to the Particle Manager.
  81160. * @method Phaser.Particles#add
  81161. * @param {Phaser.Emitter} emitter - The emitter to be added to the particle manager.
  81162. * @return {Phaser.Emitter} The emitter that was added.
  81163. */
  81164. add: function (emitter) {
  81165. this.emitters[emitter.name] = emitter;
  81166. return emitter;
  81167. },
  81168. /**
  81169. * Removes an existing Particle Emitter from the Particle Manager.
  81170. * @method Phaser.Particles#remove
  81171. * @param {Phaser.Emitter} emitter - The emitter to remove.
  81172. */
  81173. remove: function (emitter) {
  81174. delete this.emitters[emitter.name];
  81175. },
  81176. /**
  81177. * Called by the core game loop. Updates all Emitters who have their exists value set to true.
  81178. * @method Phaser.Particles#update
  81179. * @protected
  81180. */
  81181. update: function () {
  81182. for (var key in this.emitters)
  81183. {
  81184. if (this.emitters[key].exists)
  81185. {
  81186. this.emitters[key].update();
  81187. }
  81188. }
  81189. }
  81190. };
  81191. Phaser.Particles.prototype.constructor = Phaser.Particles;
  81192. /**
  81193. * @author Richard Davey <rich@photonstorm.com>
  81194. * @copyright 2016 Photon Storm Ltd.
  81195. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  81196. */
  81197. /**
  81198. * Arcade Particles is a Particle System integrated with Arcade Physics.
  81199. *
  81200. * @class Phaser.Particles.Arcade
  81201. */
  81202. Phaser.Particles.Arcade = {};
  81203. /**
  81204. * @author Richard Davey <rich@photonstorm.com>
  81205. * @copyright 2016 Photon Storm Ltd.
  81206. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  81207. */
  81208. /**
  81209. * Emitter is a lightweight particle emitter that uses Arcade Physics.
  81210. * It can be used for one-time explosions or for continuous effects like rain and fire.
  81211. * All it really does is launch Particle objects out at set intervals, and fixes their positions and velocities accordingly.
  81212. *
  81213. * @class Phaser.Particles.Arcade.Emitter
  81214. * @constructor
  81215. * @extends Phaser.Group
  81216. * @param {Phaser.Game} game - Current game instance.
  81217. * @param {number} [x=0] - The x coordinate within the Emitter that the particles are emitted from.
  81218. * @param {number} [y=0] - The y coordinate within the Emitter that the particles are emitted from.
  81219. * @param {number} [maxParticles=50] - The total number of particles in this emitter.
  81220. */
  81221. Phaser.Particles.Arcade.Emitter = function (game, x, y, maxParticles) {
  81222. /**
  81223. * @property {number} maxParticles - The total number of particles in this emitter.
  81224. * @default
  81225. */
  81226. this.maxParticles = maxParticles || 50;
  81227. Phaser.Group.call(this, game);
  81228. /**
  81229. * @property {string} name - A handy string name for this emitter. Can be set to anything.
  81230. */
  81231. this.name = 'emitter' + this.game.particles.ID++;
  81232. /**
  81233. * @property {number} type - Internal Phaser Type value.
  81234. * @protected
  81235. */
  81236. this.type = Phaser.EMITTER;
  81237. /**
  81238. * @property {number} physicsType - The const physics body type of this object.
  81239. * @readonly
  81240. */
  81241. this.physicsType = Phaser.GROUP;
  81242. /**
  81243. * @property {Phaser.Rectangle} area - The area of the emitter. Particles can be randomly generated from anywhere within this rectangle.
  81244. * @default
  81245. */
  81246. this.area = new Phaser.Rectangle(x, y, 1, 1);
  81247. /**
  81248. * @property {Phaser.Point} minParticleSpeed - The minimum possible velocity of a particle.
  81249. * @default
  81250. */
  81251. this.minParticleSpeed = new Phaser.Point(-100, -100);
  81252. /**
  81253. * @property {Phaser.Point} maxParticleSpeed - The maximum possible velocity of a particle.
  81254. * @default
  81255. */
  81256. this.maxParticleSpeed = new Phaser.Point(100, 100);
  81257. /**
  81258. * @property {number} minParticleScale - The minimum possible scale of a particle. This is applied to the X and Y axis. If you need to control each axis see minParticleScaleX.
  81259. * @default
  81260. */
  81261. this.minParticleScale = 1;
  81262. /**
  81263. * @property {number} maxParticleScale - The maximum possible scale of a particle. This is applied to the X and Y axis. If you need to control each axis see maxParticleScaleX.
  81264. * @default
  81265. */
  81266. this.maxParticleScale = 1;
  81267. /**
  81268. * @property {array} scaleData - An array of the calculated scale easing data applied to particles with scaleRates > 0.
  81269. */
  81270. this.scaleData = null;
  81271. /**
  81272. * @property {number} minRotation - The minimum possible angular velocity of a particle.
  81273. * @default
  81274. */
  81275. this.minRotation = -360;
  81276. /**
  81277. * @property {number} maxRotation - The maximum possible angular velocity of a particle.
  81278. * @default
  81279. */
  81280. this.maxRotation = 360;
  81281. /**
  81282. * @property {number} minParticleAlpha - The minimum possible alpha value of a particle.
  81283. * @default
  81284. */
  81285. this.minParticleAlpha = 1;
  81286. /**
  81287. * @property {number} maxParticleAlpha - The maximum possible alpha value of a particle.
  81288. * @default
  81289. */
  81290. this.maxParticleAlpha = 1;
  81291. /**
  81292. * @property {array} alphaData - An array of the calculated alpha easing data applied to particles with alphaRates > 0.
  81293. */
  81294. this.alphaData = null;
  81295. /**
  81296. * @property {number} gravity - Sets the `body.gravity.y` of each particle sprite to this value on launch.
  81297. * @default
  81298. */
  81299. this.gravity = 100;
  81300. /**
  81301. * @property {any} particleClass - For emitting your own particle class types. They must extend Phaser.Particle.
  81302. * @default
  81303. */
  81304. this.particleClass = Phaser.Particle;
  81305. /**
  81306. * @property {Phaser.Point} particleDrag - The X and Y drag component of particles launched from the emitter.
  81307. */
  81308. this.particleDrag = new Phaser.Point();
  81309. /**
  81310. * @property {number} angularDrag - The angular drag component of particles launched from the emitter if they are rotating.
  81311. * @default
  81312. */
  81313. this.angularDrag = 0;
  81314. /**
  81315. * @property {number} frequency - How often a particle is emitted in ms (if emitter is started with Explode === false).
  81316. * @default
  81317. */
  81318. this.frequency = 100;
  81319. /**
  81320. * @property {number} lifespan - How long each particle lives once it is emitted in ms. Default is 2 seconds. Set lifespan to 'zero' for particles to live forever.
  81321. * @default
  81322. */
  81323. this.lifespan = 2000;
  81324. /**
  81325. * @property {Phaser.Point} bounce - How much each particle should bounce on each axis. 1 = full bounce, 0 = no bounce.
  81326. */
  81327. this.bounce = new Phaser.Point();
  81328. /**
  81329. * @property {boolean} on - Determines whether the emitter is currently emitting particles. It is totally safe to directly toggle this.
  81330. * @default
  81331. */
  81332. this.on = false;
  81333. /**
  81334. * @property {Phaser.Point} particleAnchor - When a particle is created its anchor will be set to match this Point object (defaults to x/y: 0.5 to aid in rotation)
  81335. * @default
  81336. */
  81337. this.particleAnchor = new Phaser.Point(0.5, 0.5);
  81338. /**
  81339. * @property {number} blendMode - The blendMode as set on the particle when emitted from the Emitter. Defaults to NORMAL. Needs browser capable of supporting canvas blend-modes (most not available in WebGL)
  81340. * @default
  81341. */
  81342. this.blendMode = Phaser.blendModes.NORMAL;
  81343. /**
  81344. * The point the particles are emitted from.
  81345. * Emitter.x and Emitter.y control the containers location, which updates all current particles
  81346. * Emitter.emitX and Emitter.emitY control the emission location relative to the x/y position.
  81347. * @property {number} emitX
  81348. */
  81349. this.emitX = x;
  81350. /**
  81351. * The point the particles are emitted from.
  81352. * Emitter.x and Emitter.y control the containers location, which updates all current particles
  81353. * Emitter.emitX and Emitter.emitY control the emission location relative to the x/y position.
  81354. * @property {number} emitY
  81355. */
  81356. this.emitY = y;
  81357. /**
  81358. * @property {boolean} autoScale - When a new Particle is emitted this controls if it will automatically scale in size. Use Emitter.setScale to configure.
  81359. */
  81360. this.autoScale = false;
  81361. /**
  81362. * @property {boolean} autoAlpha - When a new Particle is emitted this controls if it will automatically change alpha. Use Emitter.setAlpha to configure.
  81363. */
  81364. this.autoAlpha = false;
  81365. /**
  81366. * @property {boolean} particleBringToTop - If this is `true` then when the Particle is emitted it will be bought to the top of the Emitters display list.
  81367. * @default
  81368. */
  81369. this.particleBringToTop = false;
  81370. /**
  81371. * @property {boolean} particleSendToBack - If this is `true` then when the Particle is emitted it will be sent to the back of the Emitters display list.
  81372. * @default
  81373. */
  81374. this.particleSendToBack = false;
  81375. /**
  81376. * @property {Phaser.Point} _minParticleScale - Internal particle scale var.
  81377. * @private
  81378. */
  81379. this._minParticleScale = new Phaser.Point(1, 1);
  81380. /**
  81381. * @property {Phaser.Point} _maxParticleScale - Internal particle scale var.
  81382. * @private
  81383. */
  81384. this._maxParticleScale = new Phaser.Point(1, 1);
  81385. /**
  81386. * @property {number} _quantity - Internal helper for deciding how many particles to launch.
  81387. * @private
  81388. */
  81389. this._quantity = 0;
  81390. /**
  81391. * @property {number} _timer - Internal helper for deciding when to launch particles or kill them.
  81392. * @private
  81393. */
  81394. this._timer = 0;
  81395. /**
  81396. * @property {number} _counter - Internal counter for figuring out how many particles to launch.
  81397. * @private
  81398. */
  81399. this._counter = 0;
  81400. /**
  81401. * @property {number} _flowQuantity - Internal counter for figuring out how many particles to launch per flow update.
  81402. * @private
  81403. */
  81404. this._flowQuantity = 0;
  81405. /**
  81406. * @property {number} _flowTotal - Internal counter for figuring out how many particles to launch in total.
  81407. * @private
  81408. */
  81409. this._flowTotal = 0;
  81410. /**
  81411. * @property {boolean} _explode - Internal helper for the style of particle emission (all at once, or one at a time).
  81412. * @private
  81413. */
  81414. this._explode = true;
  81415. /**
  81416. * @property {any} _frames - Internal helper for the particle frame.
  81417. * @private
  81418. */
  81419. this._frames = null;
  81420. };
  81421. Phaser.Particles.Arcade.Emitter.prototype = Object.create(Phaser.Group.prototype);
  81422. Phaser.Particles.Arcade.Emitter.prototype.constructor = Phaser.Particles.Arcade.Emitter;
  81423. /**
  81424. * Called automatically by the game loop, decides when to launch particles and when to "die".
  81425. *
  81426. * @method Phaser.Particles.Arcade.Emitter#update
  81427. */
  81428. Phaser.Particles.Arcade.Emitter.prototype.update = function () {
  81429. if (this.on && this.game.time.time >= this._timer)
  81430. {
  81431. this._timer = this.game.time.time + this.frequency * this.game.time.slowMotion;
  81432. if (this._flowTotal !== 0)
  81433. {
  81434. if (this._flowQuantity > 0)
  81435. {
  81436. for (var i = 0; i < this._flowQuantity; i++)
  81437. {
  81438. if (this.emitParticle())
  81439. {
  81440. this._counter++;
  81441. if (this._flowTotal !== -1 && this._counter >= this._flowTotal)
  81442. {
  81443. this.on = false;
  81444. break;
  81445. }
  81446. }
  81447. }
  81448. }
  81449. else
  81450. {
  81451. if (this.emitParticle())
  81452. {
  81453. this._counter++;
  81454. if (this._flowTotal !== -1 && this._counter >= this._flowTotal)
  81455. {
  81456. this.on = false;
  81457. }
  81458. }
  81459. }
  81460. }
  81461. else
  81462. {
  81463. if (this.emitParticle())
  81464. {
  81465. this._counter++;
  81466. if (this._quantity > 0 && this._counter >= this._quantity)
  81467. {
  81468. this.on = false;
  81469. }
  81470. }
  81471. }
  81472. }
  81473. var i = this.children.length;
  81474. while (i--)
  81475. {
  81476. if (this.children[i].exists)
  81477. {
  81478. this.children[i].update();
  81479. }
  81480. }
  81481. };
  81482. /**
  81483. * This function generates a new set of particles for use by this emitter.
  81484. * The particles are stored internally waiting to be emitted via Emitter.start.
  81485. *
  81486. * @method Phaser.Particles.Arcade.Emitter#makeParticles
  81487. * @param {array|string} keys - A string or an array of strings that the particle sprites will use as their texture. If an array one is picked at random.
  81488. * @param {array|number} [frames=0] - A frame number, or array of frames that the sprite will use. If an array one is picked at random.
  81489. * @param {number} [quantity] - The number of particles to generate. If not given it will use the value of Emitter.maxParticles. If the value is greater than Emitter.maxParticles it will use Emitter.maxParticles as the quantity.
  81490. * @param {boolean} [collide=false] - If you want the particles to be able to collide with other Arcade Physics bodies then set this to true.
  81491. * @param {boolean} [collideWorldBounds=false] - A particle can be set to collide against the World bounds automatically and rebound back into the World if this is set to true. Otherwise it will leave the World.
  81492. * @return {Phaser.Particles.Arcade.Emitter} This Emitter instance.
  81493. */
  81494. Phaser.Particles.Arcade.Emitter.prototype.makeParticles = function (keys, frames, quantity, collide, collideWorldBounds) {
  81495. if (frames === undefined) { frames = 0; }
  81496. if (quantity === undefined) { quantity = this.maxParticles; }
  81497. if (collide === undefined) { collide = false; }
  81498. if (collideWorldBounds === undefined) { collideWorldBounds = false; }
  81499. var particle;
  81500. var i = 0;
  81501. var rndKey = keys;
  81502. var rndFrame = frames;
  81503. this._frames = frames;
  81504. if (quantity > this.maxParticles)
  81505. {
  81506. this.maxParticles = quantity;
  81507. }
  81508. while (i < quantity)
  81509. {
  81510. if (Array.isArray(keys))
  81511. {
  81512. rndKey = this.game.rnd.pick(keys);
  81513. }
  81514. if (Array.isArray(frames))
  81515. {
  81516. rndFrame = this.game.rnd.pick(frames);
  81517. }
  81518. particle = new this.particleClass(this.game, 0, 0, rndKey, rndFrame);
  81519. this.game.physics.arcade.enable(particle, false);
  81520. if (collide)
  81521. {
  81522. particle.body.checkCollision.any = true;
  81523. particle.body.checkCollision.none = false;
  81524. }
  81525. else
  81526. {
  81527. particle.body.checkCollision.none = true;
  81528. }
  81529. particle.body.collideWorldBounds = collideWorldBounds;
  81530. particle.body.skipQuadTree = true;
  81531. particle.exists = false;
  81532. particle.visible = false;
  81533. particle.anchor.copyFrom(this.particleAnchor);
  81534. this.add(particle);
  81535. i++;
  81536. }
  81537. return this;
  81538. };
  81539. /**
  81540. * Call this function to turn off all the particles and the emitter.
  81541. *
  81542. * @method Phaser.Particles.Arcade.Emitter#kill
  81543. * @return {Phaser.Particles.Arcade.Emitter} This Emitter instance.
  81544. */
  81545. Phaser.Particles.Arcade.Emitter.prototype.kill = function () {
  81546. this.on = false;
  81547. this.alive = false;
  81548. this.exists = false;
  81549. return this;
  81550. };
  81551. /**
  81552. * Handy for bringing game objects "back to life". Just sets alive and exists back to true.
  81553. *
  81554. * @method Phaser.Particles.Arcade.Emitter#revive
  81555. * @return {Phaser.Particles.Arcade.Emitter} This Emitter instance.
  81556. */
  81557. Phaser.Particles.Arcade.Emitter.prototype.revive = function () {
  81558. this.alive = true;
  81559. this.exists = true;
  81560. return this;
  81561. };
  81562. /**
  81563. * Call this function to emit the given quantity of particles at all once (an explosion)
  81564. *
  81565. * @method Phaser.Particles.Arcade.Emitter#explode
  81566. * @param {number} [lifespan=0] - How long each particle lives once emitted in ms. 0 = forever.
  81567. * @param {number} [quantity=0] - How many particles to launch.
  81568. * @return {Phaser.Particles.Arcade.Emitter} This Emitter instance.
  81569. */
  81570. Phaser.Particles.Arcade.Emitter.prototype.explode = function (lifespan, quantity) {
  81571. this._flowTotal = 0;
  81572. this.start(true, lifespan, 0, quantity, false);
  81573. return this;
  81574. };
  81575. /**
  81576. * Call this function to start emitting a flow of particles at the given frequency.
  81577. * It will carry on going until the total given is reached.
  81578. * Each time the flow is run the quantity number of particles will be emitted together.
  81579. * If you set the total to be 20 and quantity to be 5 then flow will emit 4 times in total (4 x 5 = 20 total)
  81580. * If you set the total to be -1 then no quantity cap is used and it will keep emitting.
  81581. *
  81582. * @method Phaser.Particles.Arcade.Emitter#flow
  81583. * @param {number} [lifespan=0] - How long each particle lives once emitted in ms. 0 = forever.
  81584. * @param {number} [frequency=250] - Frequency is how often to emit the particles, given in ms.
  81585. * @param {number} [quantity=1] - How many particles to launch each time the frequency is met. Can never be > Emitter.maxParticles.
  81586. * @param {number} [total=-1] - How many particles to launch in total. If -1 it will carry on indefinitely.
  81587. * @param {boolean} [immediate=true] - Should the flow start immediately (true) or wait until the first frequency event? (false)
  81588. * @return {Phaser.Particles.Arcade.Emitter} This Emitter instance.
  81589. */
  81590. Phaser.Particles.Arcade.Emitter.prototype.flow = function (lifespan, frequency, quantity, total, immediate) {
  81591. if (quantity === undefined || quantity === 0) { quantity = 1; }
  81592. if (total === undefined) { total = -1; }
  81593. if (immediate === undefined) { immediate = true; }
  81594. if (quantity > this.maxParticles)
  81595. {
  81596. quantity = this.maxParticles;
  81597. }
  81598. this._counter = 0;
  81599. this._flowQuantity = quantity;
  81600. this._flowTotal = total;
  81601. if (immediate)
  81602. {
  81603. this.start(true, lifespan, frequency, quantity);
  81604. this._counter += quantity;
  81605. this.on = true;
  81606. this._timer = this.game.time.time + frequency * this.game.time.slowMotion;
  81607. }
  81608. else
  81609. {
  81610. this.start(false, lifespan, frequency, quantity);
  81611. }
  81612. return this;
  81613. };
  81614. /**
  81615. * Call this function to start emitting particles.
  81616. *
  81617. * @method Phaser.Particles.Arcade.Emitter#start
  81618. * @param {boolean} [explode=true] - Whether the particles should all burst out at once (true) or at the frequency given (false).
  81619. * @param {number} [lifespan=0] - How long each particle lives once emitted in ms. 0 = forever.
  81620. * @param {number} [frequency=250] - Ignored if Explode is set to true. Frequency is how often to emit 1 particle. Value given in ms.
  81621. * @param {number} [quantity=0] - How many particles to launch. 0 = "all of the particles" which will keep emitting until Emitter.maxParticles is reached.
  81622. * @param {number} [forceQuantity=false] - If `true` and creating a particle flow, the quantity emitted will be forced to the be quantity given in this call. This can never exceed Emitter.maxParticles.
  81623. * @return {Phaser.Particles.Arcade.Emitter} This Emitter instance.
  81624. */
  81625. Phaser.Particles.Arcade.Emitter.prototype.start = function (explode, lifespan, frequency, quantity, forceQuantity) {
  81626. if (explode === undefined) { explode = true; }
  81627. if (lifespan === undefined) { lifespan = 0; }
  81628. if (frequency === undefined || frequency === null) { frequency = 250; }
  81629. if (quantity === undefined) { quantity = 0; }
  81630. if (forceQuantity === undefined) { forceQuantity = false; }
  81631. if (quantity > this.maxParticles)
  81632. {
  81633. quantity = this.maxParticles;
  81634. }
  81635. this.revive();
  81636. this.visible = true;
  81637. this.lifespan = lifespan;
  81638. this.frequency = frequency;
  81639. if (explode || forceQuantity)
  81640. {
  81641. for (var i = 0; i < quantity; i++)
  81642. {
  81643. this.emitParticle();
  81644. }
  81645. }
  81646. else
  81647. {
  81648. this.on = true;
  81649. this._quantity = quantity;
  81650. this._counter = 0;
  81651. this._timer = this.game.time.time + frequency * this.game.time.slowMotion;
  81652. }
  81653. return this;
  81654. };
  81655. /**
  81656. * This function is used internally to emit the next particle in the queue.
  81657. *
  81658. * However it can also be called externally to emit a particle.
  81659. *
  81660. * When called externally you can use the arguments to override any defaults the Emitter has set.
  81661. *
  81662. * @method Phaser.Particles.Arcade.Emitter#emitParticle
  81663. * @param {number} [x] - The x coordinate to emit the particle from. If `null` or `undefined` it will use `Emitter.emitX` or if the Emitter has a width > 1 a random value between `Emitter.left` and `Emitter.right`.
  81664. * @param {number} [y] - The y coordinate to emit the particle from. If `null` or `undefined` it will use `Emitter.emitY` or if the Emitter has a height > 1 a random value between `Emitter.top` and `Emitter.bottom`.
  81665. * @param {string|Phaser.RenderTexture|Phaser.BitmapData|Phaser.Video|PIXI.Texture} [key] - This is the image or texture used by the Particle during rendering. It can be a string which is a reference to the Cache Image entry, or an instance of a RenderTexture, BitmapData, Video or PIXI.Texture.
  81666. * @param {string|number} [frame] - If this Particle is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index.
  81667. * @return {boolean} True if a particle was emitted, otherwise false.
  81668. */
  81669. Phaser.Particles.Arcade.Emitter.prototype.emitParticle = function (x, y, key, frame) {
  81670. if (x === undefined) { x = null; }
  81671. if (y === undefined) { y = null; }
  81672. var particle = this.getFirstExists(false);
  81673. if (particle === null)
  81674. {
  81675. return false;
  81676. }
  81677. var rnd = this.game.rnd;
  81678. if (key !== undefined && frame !== undefined)
  81679. {
  81680. particle.loadTexture(key, frame);
  81681. }
  81682. else if (key !== undefined)
  81683. {
  81684. particle.loadTexture(key);
  81685. }
  81686. var emitX = this.emitX;
  81687. var emitY = this.emitY;
  81688. if (x !== null)
  81689. {
  81690. emitX = x;
  81691. }
  81692. else if (this.width > 1)
  81693. {
  81694. emitX = rnd.between(this.left, this.right);
  81695. }
  81696. if (y !== null)
  81697. {
  81698. emitY = y;
  81699. }
  81700. else if (this.height > 1)
  81701. {
  81702. emitY = rnd.between(this.top, this.bottom);
  81703. }
  81704. particle.reset(emitX, emitY);
  81705. particle.angle = 0;
  81706. particle.lifespan = this.lifespan;
  81707. if (this.particleBringToTop)
  81708. {
  81709. this.bringToTop(particle);
  81710. }
  81711. else if (this.particleSendToBack)
  81712. {
  81713. this.sendToBack(particle);
  81714. }
  81715. if (this.autoScale)
  81716. {
  81717. particle.setScaleData(this.scaleData);
  81718. }
  81719. else if (this.minParticleScale !== 1 || this.maxParticleScale !== 1)
  81720. {
  81721. particle.scale.set(rnd.realInRange(this.minParticleScale, this.maxParticleScale));
  81722. }
  81723. else if ((this._minParticleScale.x !== this._maxParticleScale.x) || (this._minParticleScale.y !== this._maxParticleScale.y))
  81724. {
  81725. particle.scale.set(rnd.realInRange(this._minParticleScale.x, this._maxParticleScale.x), rnd.realInRange(this._minParticleScale.y, this._maxParticleScale.y));
  81726. }
  81727. if (frame === undefined)
  81728. {
  81729. if (Array.isArray(this._frames))
  81730. {
  81731. particle.frame = this.game.rnd.pick(this._frames);
  81732. }
  81733. else
  81734. {
  81735. particle.frame = this._frames;
  81736. }
  81737. }
  81738. if (this.autoAlpha)
  81739. {
  81740. particle.setAlphaData(this.alphaData);
  81741. }
  81742. else
  81743. {
  81744. particle.alpha = rnd.realInRange(this.minParticleAlpha, this.maxParticleAlpha);
  81745. }
  81746. particle.blendMode = this.blendMode;
  81747. var body = particle.body;
  81748. body.updateBounds();
  81749. body.bounce.copyFrom(this.bounce);
  81750. body.drag.copyFrom(this.particleDrag);
  81751. body.velocity.x = rnd.between(this.minParticleSpeed.x, this.maxParticleSpeed.x);
  81752. body.velocity.y = rnd.between(this.minParticleSpeed.y, this.maxParticleSpeed.y);
  81753. body.angularVelocity = rnd.between(this.minRotation, this.maxRotation);
  81754. body.gravity.y = this.gravity;
  81755. body.angularDrag = this.angularDrag;
  81756. particle.onEmit();
  81757. return true;
  81758. };
  81759. /**
  81760. * Destroys this Emitter, all associated child Particles and then removes itself from the Particle Manager.
  81761. *
  81762. * @method Phaser.Particles.Arcade.Emitter#destroy
  81763. */
  81764. Phaser.Particles.Arcade.Emitter.prototype.destroy = function () {
  81765. this.game.particles.remove(this);
  81766. Phaser.Group.prototype.destroy.call(this, true, false);
  81767. };
  81768. /**
  81769. * A more compact way of setting the width and height of the emitter.
  81770. *
  81771. * @method Phaser.Particles.Arcade.Emitter#setSize
  81772. * @param {number} width - The desired width of the emitter (particles are spawned randomly within these dimensions).
  81773. * @param {number} height - The desired height of the emitter.
  81774. * @return {Phaser.Particles.Arcade.Emitter} This Emitter instance.
  81775. */
  81776. Phaser.Particles.Arcade.Emitter.prototype.setSize = function (width, height) {
  81777. this.area.width = width;
  81778. this.area.height = height;
  81779. return this;
  81780. };
  81781. /**
  81782. * A more compact way of setting the X velocity range of the emitter.
  81783. * @method Phaser.Particles.Arcade.Emitter#setXSpeed
  81784. * @param {number} [min=0] - The minimum value for this range.
  81785. * @param {number} [max=0] - The maximum value for this range.
  81786. * @return {Phaser.Particles.Arcade.Emitter} This Emitter instance.
  81787. */
  81788. Phaser.Particles.Arcade.Emitter.prototype.setXSpeed = function (min, max) {
  81789. min = min || 0;
  81790. max = max || 0;
  81791. this.minParticleSpeed.x = min;
  81792. this.maxParticleSpeed.x = max;
  81793. return this;
  81794. };
  81795. /**
  81796. * A more compact way of setting the Y velocity range of the emitter.
  81797. * @method Phaser.Particles.Arcade.Emitter#setYSpeed
  81798. * @param {number} [min=0] - The minimum value for this range.
  81799. * @param {number} [max=0] - The maximum value for this range.
  81800. * @return {Phaser.Particles.Arcade.Emitter} This Emitter instance.
  81801. */
  81802. Phaser.Particles.Arcade.Emitter.prototype.setYSpeed = function (min, max) {
  81803. min = min || 0;
  81804. max = max || 0;
  81805. this.minParticleSpeed.y = min;
  81806. this.maxParticleSpeed.y = max;
  81807. return this;
  81808. };
  81809. /**
  81810. * A more compact way of setting the angular velocity constraints of the particles.
  81811. *
  81812. * @method Phaser.Particles.Arcade.Emitter#setRotation
  81813. * @param {number} [min=0] - The minimum value for this range.
  81814. * @param {number} [max=0] - The maximum value for this range.
  81815. * @return {Phaser.Particles.Arcade.Emitter} This Emitter instance.
  81816. */
  81817. Phaser.Particles.Arcade.Emitter.prototype.setRotation = function (min, max) {
  81818. min = min || 0;
  81819. max = max || 0;
  81820. this.minRotation = min;
  81821. this.maxRotation = max;
  81822. return this;
  81823. };
  81824. /**
  81825. * A more compact way of setting the alpha constraints of the particles.
  81826. * The rate parameter, if set to a value above zero, lets you set the speed at which the Particle change in alpha from min to max.
  81827. * If rate is zero, which is the default, the particle won't change alpha - instead it will pick a random alpha between min and max on emit.
  81828. *
  81829. * @method Phaser.Particles.Arcade.Emitter#setAlpha
  81830. * @param {number} [min=1] - The minimum value for this range.
  81831. * @param {number} [max=1] - The maximum value for this range.
  81832. * @param {number} [rate=0] - The rate (in ms) at which the particles will change in alpha from min to max, or set to zero to pick a random alpha between the two.
  81833. * @param {function} [ease=Phaser.Easing.Linear.None] - If you've set a rate > 0 this is the easing formula applied between the min and max values.
  81834. * @param {boolean} [yoyo=false] - If you've set a rate > 0 you can set if the ease will yoyo or not (i.e. ease back to its original values)
  81835. * @return {Phaser.Particles.Arcade.Emitter} This Emitter instance.
  81836. */
  81837. Phaser.Particles.Arcade.Emitter.prototype.setAlpha = function (min, max, rate, ease, yoyo) {
  81838. if (min === undefined) { min = 1; }
  81839. if (max === undefined) { max = 1; }
  81840. if (rate === undefined) { rate = 0; }
  81841. if (ease === undefined) { ease = Phaser.Easing.Linear.None; }
  81842. if (yoyo === undefined) { yoyo = false; }
  81843. this.minParticleAlpha = min;
  81844. this.maxParticleAlpha = max;
  81845. this.autoAlpha = false;
  81846. if (rate > 0 && min !== max)
  81847. {
  81848. var tweenData = { v: min };
  81849. var tween = this.game.make.tween(tweenData).to( { v: max }, rate, ease);
  81850. tween.yoyo(yoyo);
  81851. this.alphaData = tween.generateData(60);
  81852. // Inverse it so we don't have to do array length look-ups in Particle update loops
  81853. this.alphaData.reverse();
  81854. this.autoAlpha = true;
  81855. }
  81856. return this;
  81857. };
  81858. /**
  81859. * A more compact way of setting the scale constraints of the particles.
  81860. * The rate parameter, if set to a value above zero, lets you set the speed and ease which the Particle uses to change in scale from min to max across both axis.
  81861. * If rate is zero, which is the default, the particle won't change scale during update, instead it will pick a random scale between min and max on emit.
  81862. *
  81863. * @method Phaser.Particles.Arcade.Emitter#setScale
  81864. * @param {number} [minX=1] - The minimum value of Particle.scale.x.
  81865. * @param {number} [maxX=1] - The maximum value of Particle.scale.x.
  81866. * @param {number} [minY=1] - The minimum value of Particle.scale.y.
  81867. * @param {number} [maxY=1] - The maximum value of Particle.scale.y.
  81868. * @param {number} [rate=0] - The rate (in ms) at which the particles will change in scale from min to max, or set to zero to pick a random size between the two.
  81869. * @param {function} [ease=Phaser.Easing.Linear.None] - If you've set a rate > 0 this is the easing formula applied between the min and max values.
  81870. * @param {boolean} [yoyo=false] - If you've set a rate > 0 you can set if the ease will yoyo or not (i.e. ease back to its original values)
  81871. * @return {Phaser.Particles.Arcade.Emitter} This Emitter instance.
  81872. */
  81873. Phaser.Particles.Arcade.Emitter.prototype.setScale = function (minX, maxX, minY, maxY, rate, ease, yoyo) {
  81874. if (minX === undefined) { minX = 1; }
  81875. if (maxX === undefined) { maxX = 1; }
  81876. if (minY === undefined) { minY = 1; }
  81877. if (maxY === undefined) { maxY = 1; }
  81878. if (rate === undefined) { rate = 0; }
  81879. if (ease === undefined) { ease = Phaser.Easing.Linear.None; }
  81880. if (yoyo === undefined) { yoyo = false; }
  81881. // Reset these
  81882. this.minParticleScale = 1;
  81883. this.maxParticleScale = 1;
  81884. this._minParticleScale.set(minX, minY);
  81885. this._maxParticleScale.set(maxX, maxY);
  81886. this.autoScale = false;
  81887. if (rate > 0 && ((minX !== maxX) || (minY !== maxY)))
  81888. {
  81889. var tweenData = { x: minX, y: minY };
  81890. var tween = this.game.make.tween(tweenData).to( { x: maxX, y: maxY }, rate, ease);
  81891. tween.yoyo(yoyo);
  81892. this.scaleData = tween.generateData(60);
  81893. // Inverse it so we don't have to do array length look-ups in Particle update loops
  81894. this.scaleData.reverse();
  81895. this.autoScale = true;
  81896. }
  81897. return this;
  81898. };
  81899. /**
  81900. * Change the emitters center to match the center of any object with a `center` property, such as a Sprite.
  81901. * If the object doesn't have a center property it will be set to object.x + object.width / 2
  81902. *
  81903. * @method Phaser.Particles.Arcade.Emitter#at
  81904. * @param {object|Phaser.Sprite|Phaser.Image|Phaser.TileSprite|Phaser.Text|PIXI.DisplayObject} object - The object that you wish to match the center with.
  81905. * @return {Phaser.Particles.Arcade.Emitter} This Emitter instance.
  81906. */
  81907. Phaser.Particles.Arcade.Emitter.prototype.at = function (object) {
  81908. if (object.center)
  81909. {
  81910. this.emitX = object.center.x;
  81911. this.emitY = object.center.y;
  81912. }
  81913. else
  81914. {
  81915. this.emitX = object.world.x + (object.anchor.x * object.width);
  81916. this.emitY = object.world.y + (object.anchor.y * object.height);
  81917. }
  81918. return this;
  81919. };
  81920. /**
  81921. * @name Phaser.Particles.Arcade.Emitter#width
  81922. * @property {number} width - Gets or sets the width of the Emitter. This is the region in which a particle can be emitted.
  81923. */
  81924. Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "width", {
  81925. get: function () {
  81926. return this.area.width;
  81927. },
  81928. set: function (value) {
  81929. this.area.width = value;
  81930. }
  81931. });
  81932. /**
  81933. * @name Phaser.Particles.Arcade.Emitter#height
  81934. * @property {number} height - Gets or sets the height of the Emitter. This is the region in which a particle can be emitted.
  81935. */
  81936. Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "height", {
  81937. get: function () {
  81938. return this.area.height;
  81939. },
  81940. set: function (value) {
  81941. this.area.height = value;
  81942. }
  81943. });
  81944. /**
  81945. * @name Phaser.Particles.Arcade.Emitter#x
  81946. * @property {number} x - Gets or sets the x position of the Emitter.
  81947. */
  81948. Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "x", {
  81949. get: function () {
  81950. return this.emitX;
  81951. },
  81952. set: function (value) {
  81953. this.emitX = value;
  81954. }
  81955. });
  81956. /**
  81957. * @name Phaser.Particles.Arcade.Emitter#y
  81958. * @property {number} y - Gets or sets the y position of the Emitter.
  81959. */
  81960. Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "y", {
  81961. get: function () {
  81962. return this.emitY;
  81963. },
  81964. set: function (value) {
  81965. this.emitY = value;
  81966. }
  81967. });
  81968. /**
  81969. * @name Phaser.Particles.Arcade.Emitter#left
  81970. * @property {number} left - Gets the left position of the Emitter.
  81971. * @readonly
  81972. */
  81973. Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "left", {
  81974. get: function () {
  81975. return Math.floor(this.x - (this.area.width / 2));
  81976. }
  81977. });
  81978. /**
  81979. * @name Phaser.Particles.Arcade.Emitter#right
  81980. * @property {number} right - Gets the right position of the Emitter.
  81981. * @readonly
  81982. */
  81983. Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "right", {
  81984. get: function () {
  81985. return Math.floor(this.x + (this.area.width / 2));
  81986. }
  81987. });
  81988. /**
  81989. * @name Phaser.Particles.Arcade.Emitter#top
  81990. * @property {number} top - Gets the top position of the Emitter.
  81991. * @readonly
  81992. */
  81993. Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "top", {
  81994. get: function () {
  81995. return Math.floor(this.y - (this.area.height / 2));
  81996. }
  81997. });
  81998. /**
  81999. * @name Phaser.Particles.Arcade.Emitter#bottom
  82000. * @property {number} bottom - Gets the bottom position of the Emitter.
  82001. * @readonly
  82002. */
  82003. Object.defineProperty(Phaser.Particles.Arcade.Emitter.prototype, "bottom", {
  82004. get: function () {
  82005. return Math.floor(this.y + (this.area.height / 2));
  82006. }
  82007. });
  82008. /**
  82009. * @author Richard Davey <rich@photonstorm.com>
  82010. * @copyright 2016 Photon Storm Ltd.
  82011. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  82012. */
  82013. /**
  82014. * The Weapon Plugin provides the ability to easily create a bullet pool and manager.
  82015. *
  82016. * Weapons fire Phaser.Bullet objects, which are essentially Sprites with a few extra properties.
  82017. * The Bullets are enabled for Arcade Physics. They do not currently work with P2 Physics.
  82018. *
  82019. * The Bullets are created inside of `Weapon.bullets`, which is a Phaser.Group instance. Anything you
  82020. * can usually do with a Group, such as move it around the display list, iterate it, etc can be done
  82021. * to the bullets Group too.
  82022. *
  82023. * Bullets can have textures and even animations. You can control the speed at which they are fired,
  82024. * the firing rate, the firing angle, and even set things like gravity for them.
  82025. *
  82026. * A small example, assumed to be running from within a Phaser.State create method.
  82027. *
  82028. * `var weapon = this.add.weapon(10, 'bullet');`
  82029. * `weapon.fireFrom.set(300, 300);`
  82030. * `this.input.onDown.add(weapon.fire, this);`
  82031. *
  82032. * @class Phaser.Weapon
  82033. * @constructor
  82034. * @param {Phaser.Game} game - A reference to the current Phaser.Game instance.
  82035. * @param {Phaser.PluginManager} parent - The Phaser Plugin Manager which looks after this plugin.
  82036. */
  82037. Phaser.Weapon = function (game, parent) {
  82038. Phaser.Plugin.call(this, game, parent);
  82039. /**
  82040. * This is the Phaser.Group that contains all of the bullets managed by this plugin.
  82041. * @type {Phaser.Group}
  82042. */
  82043. this.bullets = null;
  82044. /**
  82045. * Should the bullet pool run out of bullets (i.e. they are all in flight) then this
  82046. * boolean controls if the Group will create a brand new bullet object or not.
  82047. * @type {boolean}
  82048. */
  82049. this.autoExpandBulletsGroup = false;
  82050. /**
  82051. * Will this weapon auto fire? If set to true then a new bullet will be fired
  82052. * based on the `fireRate` value.
  82053. * @type {boolean}
  82054. */
  82055. this.autofire = false;
  82056. /**
  82057. * The total number of bullets this Weapon has fired so far.
  82058. * You can limit the number of shots allowed (via `fireLimit`), and reset
  82059. * this total via `Weapon.resetShots`.
  82060. * @type {number}
  82061. */
  82062. this.shots = 0;
  82063. /**
  82064. * The maximum number of shots that this Weapon is allowed to fire before it stops.
  82065. * When the limit is his the `Weapon.onFireLimit` Signal is dispatched.
  82066. * You can reset the shot counter via `Weapon.resetShots`.
  82067. * @type {number}
  82068. */
  82069. this.fireLimit = 0;
  82070. /**
  82071. * The rate at which this Weapon can fire. The value is given in milliseconds.
  82072. * @type {number}
  82073. */
  82074. this.fireRate = 100;
  82075. /**
  82076. * This is a modifier that is added to the `fireRate` each update to add variety
  82077. * to the firing rate of the Weapon. The value is given in milliseconds.
  82078. * If you've a `fireRate` of 200 and a `fireRateVariance` of 50 then the actual
  82079. * firing rate of the Weapon will be between 150 and 250.
  82080. * @type {number}
  82081. */
  82082. this.fireRateVariance = 0;
  82083. /**
  82084. * This is a Rectangle from within which the bullets are fired. By default it's a 1x1
  82085. * rectangle, the equivalent of a Point. But you can change the width and height, and if
  82086. * larger than 1x1 it'll pick a random point within the rectangle to launch the bullet from.
  82087. * @type {Phaser.Rectangle}
  82088. */
  82089. this.fireFrom = new Phaser.Rectangle(0, 0, 1, 1);
  82090. /**
  82091. * The angle at which the bullets are fired. This can be a const such as Phaser.ANGLE_UP
  82092. * or it can be any number from 0 to 360 inclusive, where 0 degrees is to the right.
  82093. * @type {integer}
  82094. */
  82095. this.fireAngle = Phaser.ANGLE_UP;
  82096. /**
  82097. * When a Bullet is fired it can optionally inherit the velocity of the `trackedSprite` if set.
  82098. * @type {boolean}
  82099. */
  82100. this.bulletInheritSpriteSpeed = false;
  82101. /**
  82102. * The string based name of the animation that the Bullet will be given on launch.
  82103. * This is set via `Weapon.addBulletAnimation`.
  82104. * @type {string}
  82105. */
  82106. this.bulletAnimation = '';
  82107. /**
  82108. * If you've added a set of frames via `Weapon.setBulletFrames` then you can optionally
  82109. * chose for each Bullet fired to pick a random frame from the set.
  82110. * @type {boolean}
  82111. */
  82112. this.bulletFrameRandom = false;
  82113. /**
  82114. * If you've added a set of frames via `Weapon.setBulletFrames` then you can optionally
  82115. * chose for each Bullet fired to use the next frame in the set. The frame index is then
  82116. * advanced one frame until it reaches the end of the set, then it starts from the start
  82117. * again. Cycling frames like this allows you to create varied bullet effects via
  82118. * sprite sheets.
  82119. * @type {boolean}
  82120. */
  82121. this.bulletFrameCycle = false;
  82122. /**
  82123. * Should the Bullets wrap around the world bounds? This automatically calls
  82124. * `World.wrap` on the Bullet each frame. See the docs for that method for details.
  82125. * @type {boolean}
  82126. */
  82127. this.bulletWorldWrap = false;
  82128. /**
  82129. * If `bulletWorldWrap` is true then you can provide an optional padding value with this
  82130. * property. It's added to the calculations determining when the Bullet should wrap around
  82131. * the world or not. The value is given in pixels.
  82132. * @type {integer}
  82133. */
  82134. this.bulletWorldWrapPadding = 0;
  82135. /**
  82136. * An optional angle offset applied to the Bullets when they are launched.
  82137. * This is useful if for example your bullet sprites have been drawn facing up, instead of
  82138. * to the right, and you want to fire them at an angle. In which case you can set the
  82139. * angle offset to be 90 and they'll be properly rotated when fired.
  82140. * @type {number}
  82141. */
  82142. this.bulletAngleOffset = 0;
  82143. /**
  82144. * This is a variance added to the angle of Bullets when they are fired.
  82145. * If you fire from an angle of 90 and have a `bulletAngleVariance` of 20 then the actual
  82146. * angle of the Bullets will be between 70 and 110 degrees. This is a quick way to add a
  82147. * great 'spread' effect to a Weapon.
  82148. * @type {number}
  82149. */
  82150. this.bulletAngleVariance = 0;
  82151. /**
  82152. * The speed at which the bullets are fired. This value is given in pixels per second, and
  82153. * is used to set the starting velocity of the bullets.
  82154. * @type {number}
  82155. */
  82156. this.bulletSpeed = 200;
  82157. /**
  82158. * This is a variance added to the speed of Bullets when they are fired.
  82159. * If bullets have a `bulletSpeed` value of 200, and a `bulletSpeedVariance` of 50
  82160. * then the actual speed of the Bullets will be between 150 and 250 pixels per second.
  82161. * @type {number}
  82162. */
  82163. this.bulletSpeedVariance = 0;
  82164. /**
  82165. * If you've set `bulletKillType` to `Phaser.Weapon.KILL_LIFESPAN` this controls the amount
  82166. * of lifespan the Bullets have set on launch. The value is given in milliseconds.
  82167. * When a Bullet hits its lifespan limit it will be automatically killed.
  82168. * @type {number}
  82169. */
  82170. this.bulletLifespan = 0;
  82171. /**
  82172. * If you've set `bulletKillType` to `Phaser.Weapon.KILL_DISTANCE` this controls the distance
  82173. * the Bullet can travel before it is automatically killed. The distance is given in pixels.
  82174. * @type {number}
  82175. */
  82176. this.bulletKillDistance = 0;
  82177. /**
  82178. * This is the amount of gravity added to the Bullets physics body when fired.
  82179. * Gravity is expressed in pixels / second / second.
  82180. * @type {Phaser.Point}
  82181. */
  82182. this.bulletGravity = new Phaser.Point(0, 0);
  82183. /**
  82184. * Bullets can optionally adjust their rotation in-flight to match their velocity.
  82185. * This can create the effect of a bullet 'pointing' to the path it is following, for example
  82186. * an arrow being fired from a bow, and works especially well when added to `bulletGravity`.
  82187. * @type {boolean}
  82188. */
  82189. this.bulletRotateToVelocity = false;
  82190. /**
  82191. * The Texture Key that the Bullets use when rendering.
  82192. * Changing this has no effect on bullets in-flight, only on newly spawned bullets.
  82193. * @type {string}
  82194. */
  82195. this.bulletKey = '';
  82196. /**
  82197. * The Texture Frame that the Bullets use when rendering.
  82198. * Changing this has no effect on bullets in-flight, only on newly spawned bullets.
  82199. * @type {string|integer}
  82200. */
  82201. this.bulletFrame = '';
  82202. /**
  82203. * Private var that holds the public `bulletClass` property.
  82204. * @type {object}
  82205. * @private
  82206. */
  82207. this._bulletClass = Phaser.Bullet;
  82208. /**
  82209. * Private var that holds the public `bulletCollideWorldBounds` property.
  82210. * @type {boolean}
  82211. * @private
  82212. */
  82213. this._bulletCollideWorldBounds = false;
  82214. /**
  82215. * Private var that holds the public `bulletKillType` property.
  82216. * @type {integer}
  82217. * @private
  82218. */
  82219. this._bulletKillType = Phaser.Weapon.KILL_WORLD_BOUNDS;
  82220. /**
  82221. * Holds internal data about custom bullet body sizes.
  82222. *
  82223. * @type {Object}
  82224. * @private
  82225. */
  82226. this._data = {
  82227. customBody: false,
  82228. width: 0,
  82229. height: 0,
  82230. offsetX: 0,
  82231. offsetY: 0
  82232. };
  82233. /**
  82234. * This Rectangle defines the bounds that are used when determining if a Bullet should be killed or not.
  82235. * It's used in combination with `Weapon.bulletKillType` when that is set to either `Phaser.Weapon.KILL_WEAPON_BOUNDS`
  82236. * or `Phaser.Weapon.KILL_STATIC_BOUNDS`. If you are not using either of these kill types then the bounds are ignored.
  82237. * If you are tracking a Sprite or Point then the bounds are centered on that object every frame.
  82238. *
  82239. * @type {Phaser.Rectangle}
  82240. */
  82241. this.bounds = new Phaser.Rectangle();
  82242. /**
  82243. * The Rectangle used to calculate the bullet bounds from.
  82244. *
  82245. * @type {Phaser.Rectangle}
  82246. * @private
  82247. */
  82248. this.bulletBounds = game.world.bounds;
  82249. /**
  82250. * This array stores the frames added via `Weapon.setBulletFrames`.
  82251. *
  82252. * @type {Array}
  82253. * @protected
  82254. */
  82255. this.bulletFrames = [];
  82256. /**
  82257. * The index of the frame within `Weapon.bulletFrames` that is currently being used.
  82258. * This value is only used if `Weapon.bulletFrameCycle` is set to `true`.
  82259. * @type {number}
  82260. * @private
  82261. */
  82262. this.bulletFrameIndex = 0;
  82263. /**
  82264. * An internal object that stores the animation data added via `Weapon.addBulletAnimation`.
  82265. * @type {Object}
  82266. * @private
  82267. */
  82268. this.anims = {};
  82269. /**
  82270. * The onFire Signal is dispatched each time `Weapon.fire` is called, and a Bullet is
  82271. * _successfully_ launched. The callback is set two arguments: a reference to the bullet sprite itself,
  82272. * and a reference to the Weapon that fired the bullet.
  82273. *
  82274. * @type {Phaser.Signal}
  82275. */
  82276. this.onFire = new Phaser.Signal();
  82277. /**
  82278. * The onKill Signal is dispatched each time a Bullet that is in-flight is killed. This can be the result
  82279. * of leaving the Weapon bounds, an expiring lifespan, or exceeding a specified distance.
  82280. * The callback is sent one argument: A reference to the bullet sprite itself.
  82281. *
  82282. * @type {Phaser.Signal}
  82283. */
  82284. this.onKill = new Phaser.Signal();
  82285. /**
  82286. * The onFireLimit Signal is dispatched if `Weapon.fireLimit` is > 0, and a bullet launch takes the number
  82287. * of shots fired to equal the fire limit.
  82288. * The callback is sent two arguments: A reference to the Weapon that hit the limit, and the value of
  82289. * `Weapon.fireLimit`.
  82290. *
  82291. * @type {Phaser.Signal}
  82292. */
  82293. this.onFireLimit = new Phaser.Signal();
  82294. /**
  82295. * The Sprite currently being tracked by the Weapon, if any.
  82296. * This is set via the `Weapon.trackSprite` method.
  82297. *
  82298. * @type {Phaser.Sprite|Object}
  82299. */
  82300. this.trackedSprite = null;
  82301. /**
  82302. * The Pointer currently being tracked by the Weapon, if any.
  82303. * This is set via the `Weapon.trackPointer` method.
  82304. *
  82305. * @type {Phaser.Pointer}
  82306. */
  82307. this.trackedPointer = null;
  82308. /**
  82309. * If the Weapon is tracking a Sprite, should it also track the Sprites rotation?
  82310. * This is useful for a game such as Asteroids, where you want the weapon to fire based
  82311. * on the sprites rotation.
  82312. *
  82313. * @type {boolean}
  82314. */
  82315. this.trackRotation = false;
  82316. /**
  82317. * The Track Offset is a Point object that allows you to specify a pixel offset that bullets use
  82318. * when launching from a tracked Sprite or Pointer. For example if you've got a bullet that is 2x2 pixels
  82319. * in size, but you're tracking a Sprite that is 32x32, then you can set `trackOffset.x = 16` to have
  82320. * the bullet launched from the center of the Sprite.
  82321. *
  82322. * @type {Phaser.Point}
  82323. */
  82324. this.trackOffset = new Phaser.Point();
  82325. /**
  82326. * Internal firing rate time tracking variable.
  82327. *
  82328. * @type {number}
  82329. * @private
  82330. */
  82331. this._nextFire = 0;
  82332. /**
  82333. * Internal firing rotation tracking point.
  82334. *
  82335. * @type {Phaser.Point}
  82336. * @private
  82337. */
  82338. this._rotatedPoint = new Phaser.Point();
  82339. };
  82340. Phaser.Weapon.prototype = Object.create(Phaser.Plugin.prototype);
  82341. Phaser.Weapon.prototype.constructor = Phaser.Weapon;
  82342. /**
  82343. * A `bulletKillType` constant that stops the bullets from ever being destroyed automatically.
  82344. * @constant
  82345. * @type {integer}
  82346. */
  82347. Phaser.Weapon.KILL_NEVER = 0;
  82348. /**
  82349. * A `bulletKillType` constant that automatically kills the bullets when their `bulletLifespan` expires.
  82350. * @constant
  82351. * @type {integer}
  82352. */
  82353. Phaser.Weapon.KILL_LIFESPAN = 1;
  82354. /**
  82355. * A `bulletKillType` constant that automatically kills the bullets after they
  82356. * exceed the `bulletDistance` from their original firing position.
  82357. * @constant
  82358. * @type {integer}
  82359. */
  82360. Phaser.Weapon.KILL_DISTANCE = 2;
  82361. /**
  82362. * A `bulletKillType` constant that automatically kills the bullets when they leave the `Weapon.bounds` rectangle.
  82363. * @constant
  82364. * @type {integer}
  82365. */
  82366. Phaser.Weapon.KILL_WEAPON_BOUNDS = 3;
  82367. /**
  82368. * A `bulletKillType` constant that automatically kills the bullets when they leave the `Camera.bounds` rectangle.
  82369. * @constant
  82370. * @type {integer}
  82371. */
  82372. Phaser.Weapon.KILL_CAMERA_BOUNDS = 4;
  82373. /**
  82374. * A `bulletKillType` constant that automatically kills the bullets when they leave the `World.bounds` rectangle.
  82375. * @constant
  82376. * @type {integer}
  82377. */
  82378. Phaser.Weapon.KILL_WORLD_BOUNDS = 5;
  82379. /**
  82380. * A `bulletKillType` constant that automatically kills the bullets when they leave the `Weapon.bounds` rectangle.
  82381. * @constant
  82382. * @type {integer}
  82383. */
  82384. Phaser.Weapon.KILL_STATIC_BOUNDS = 6;
  82385. /**
  82386. * This method performs two actions: First it will check to see if the `Weapon.bullets` Group exists or not,
  82387. * and if not it creates it, adding it the `group` given as the 4th argument.
  82388. *
  82389. * Then it will seed the bullet pool with the `quantity` number of Bullets, using the texture key and frame
  82390. * provided (if any).
  82391. *
  82392. * If for example you set the quantity to be 10, then this Weapon will only ever be able to have 10 bullets
  82393. * in-flight simultaneously. If you try to fire an 11th bullet then nothing will happen until one, or more, of
  82394. * the in-flight bullets have been killed, freeing them up for use by the Weapon again.
  82395. *
  82396. * If you do not wish to have a limit set, then pass in -1 as the quantity. In this instance the Weapon will
  82397. * keep increasing the size of the bullet pool as needed. It will never reduce the size of the pool however,
  82398. * so be careful it doesn't grow too large.
  82399. *
  82400. * You can either set the texture key and frame here, or via the `Weapon.bulletKey` and `Weapon.bulletFrame`
  82401. * properties. You can also animate bullets, or set them to use random frames. All Bullets belonging to a
  82402. * single Weapon instance must share the same texture key however.
  82403. *
  82404. * @method Phaser.Weapon#createBullets
  82405. * @param {integer} [quantity=1] - The quantity of bullets to seed the Weapon with. If -1 it will set the pool to automatically expand.
  82406. * @param {string} [key] - The Game.cache key of the image that this Sprite will use.
  82407. * @param {integer|string} [frame] - If the Sprite image contains multiple frames you can specify which one to use here.
  82408. * @param {Phaser.Group} [group] - Optional Group to add the object to. If not specified it will be added to the World group.
  82409. * @return {Phaser.Weapon} This Weapon instance.
  82410. */
  82411. Phaser.Weapon.prototype.createBullets = function (quantity, key, frame, group) {
  82412. if (quantity === undefined) { quantity = 1; }
  82413. if (group === undefined) { group = this.game.world; }
  82414. if (!this.bullets)
  82415. {
  82416. this.bullets = this.game.add.physicsGroup(Phaser.Physics.ARCADE, group);
  82417. this.bullets.classType = this._bulletClass;
  82418. }
  82419. if (quantity !== 0)
  82420. {
  82421. if (quantity === -1)
  82422. {
  82423. this.autoExpandBulletsGroup = true;
  82424. quantity = 1;
  82425. }
  82426. this.bullets.createMultiple(quantity, key, frame);
  82427. this.bullets.setAll('data.bulletManager', this);
  82428. this.bulletKey = key;
  82429. this.bulletFrame = frame;
  82430. }
  82431. return this;
  82432. };
  82433. /**
  82434. * Call a function on each in-flight bullet in this Weapon.
  82435. *
  82436. * See {@link Phaser.Group#forEachExists forEachExists} for more details.
  82437. *
  82438. * @method Phaser.Weapon#forEach
  82439. * @param {function} callback - The function that will be called for each applicable child. The child will be passed as the first argument.
  82440. * @param {object} callbackContext - The context in which the function should be called (usually 'this').
  82441. * @param {...any} [args=(none)] - Additional arguments to pass to the callback function, after the child item.
  82442. * @return {Phaser.Weapon} This Weapon instance.
  82443. */
  82444. Phaser.Weapon.prototype.forEach = function (callback, callbackContext) {
  82445. this.bullets.forEachExists(callback, callbackContext, arguments);
  82446. return this;
  82447. };
  82448. /**
  82449. * Sets `Body.enable` to `false` on each bullet in this Weapon.
  82450. * This has the effect of stopping them in-flight should they be moving.
  82451. * It also stops them being able to be checked for collision.
  82452. *
  82453. * @method Phaser.Weapon#pauseAll
  82454. * @return {Phaser.Weapon} This Weapon instance.
  82455. */
  82456. Phaser.Weapon.prototype.pauseAll = function () {
  82457. this.bullets.setAll('body.enable', false);
  82458. return this;
  82459. };
  82460. /**
  82461. * Sets `Body.enable` to `true` on each bullet in this Weapon.
  82462. * This has the effect of resuming their motion should they be in-flight.
  82463. * It also enables them for collision checks again.
  82464. *
  82465. * @method Phaser.Weapon#resumeAll
  82466. * @return {Phaser.Weapon} This Weapon instance.
  82467. */
  82468. Phaser.Weapon.prototype.resumeAll = function () {
  82469. this.bullets.setAll('body.enable', true);
  82470. return this;
  82471. };
  82472. /**
  82473. * Calls `Bullet.kill` on every in-flight bullet in this Weapon.
  82474. * Also re-enables their physics bodies, should they have been disabled via `pauseAll`.
  82475. *
  82476. * @method Phaser.Weapon#killAll
  82477. * @return {Phaser.Weapon} This Weapon instance.
  82478. */
  82479. Phaser.Weapon.prototype.killAll = function () {
  82480. this.bullets.callAllExists('kill', true);
  82481. this.bullets.setAll('body.enable', true);
  82482. return this;
  82483. };
  82484. /**
  82485. * Resets the `Weapon.shots` counter back to zero. This is used when you've set
  82486. * `Weapon.fireLimit`, and have hit (or just wish to reset) your limit.
  82487. *
  82488. * @method Phaser.Weapon#resetShots
  82489. * @param {integer} [newLimit] - Optionally set a new `Weapon.fireLimit`.
  82490. * @return {Phaser.Weapon} This Weapon instance.
  82491. */
  82492. Phaser.Weapon.prototype.resetShots = function (newLimit) {
  82493. this.shots = 0;
  82494. if (newLimit !== undefined)
  82495. {
  82496. this.fireLimit = newLimit;
  82497. }
  82498. return this;
  82499. };
  82500. /**
  82501. * Destroys this Weapon. It removes itself from the PluginManager, destroys
  82502. * the bullets Group, and nulls internal references.
  82503. *
  82504. * @method Phaser.Weapon#destroy
  82505. */
  82506. Phaser.Weapon.prototype.destroy = function () {
  82507. this.parent.remove(this, false);
  82508. this.bullets.destroy();
  82509. this.game = null;
  82510. this.parent = null;
  82511. this.active = false;
  82512. this.visible = false;
  82513. };
  82514. /**
  82515. * Internal update method, called by the PluginManager.
  82516. *
  82517. * @method Phaser.Weapon#update
  82518. * @protected
  82519. */
  82520. Phaser.Weapon.prototype.update = function () {
  82521. if (this._bulletKillType === Phaser.Weapon.KILL_WEAPON_BOUNDS)
  82522. {
  82523. if (this.trackedSprite)
  82524. {
  82525. this.trackedSprite.updateTransform();
  82526. this.bounds.centerOn(this.trackedSprite.worldPosition.x, this.trackedSprite.worldPosition.y);
  82527. }
  82528. else if (this.trackedPointer)
  82529. {
  82530. this.bounds.centerOn(this.trackedPointer.worldX, this.trackedPointer.worldY);
  82531. }
  82532. }
  82533. if (this.autofire)
  82534. {
  82535. this.fire();
  82536. }
  82537. };
  82538. /**
  82539. * Sets this Weapon to track the given Sprite, or any Object with a public `world` Point object.
  82540. * When a Weapon tracks a Sprite it will automatically update its `fireFrom` value to match the Sprites
  82541. * position within the Game World, adjusting the coordinates based on the offset arguments.
  82542. *
  82543. * This allows you to lock a Weapon to a Sprite, so that bullets are always launched from its location.
  82544. *
  82545. * Calling `trackSprite` will reset `Weapon.trackedPointer` to null, should it have been set, as you can
  82546. * only track _either_ a Sprite, or a Pointer, at once, but not both.
  82547. *
  82548. * @method Phaser.Weapon#trackSprite
  82549. * @param {Phaser.Sprite|Object} sprite - The Sprite to track the position of.
  82550. * @param {integer} [offsetX=0] - The horizontal offset from the Sprites position to be applied to the Weapon.
  82551. * @param {integer} [offsetY=0] - The vertical offset from the Sprites position to be applied to the Weapon.
  82552. * @param {boolean} [trackRotation=false] - Should the Weapon also track the Sprites rotation?
  82553. * @return {Phaser.Weapon} This Weapon instance.
  82554. */
  82555. Phaser.Weapon.prototype.trackSprite = function (sprite, offsetX, offsetY, trackRotation) {
  82556. if (offsetX === undefined) { offsetX = 0; }
  82557. if (offsetY === undefined) { offsetY = 0; }
  82558. if (trackRotation === undefined) { trackRotation = false; }
  82559. this.trackedPointer = null;
  82560. this.trackedSprite = sprite;
  82561. this.trackRotation = trackRotation;
  82562. this.trackOffset.set(offsetX, offsetY);
  82563. return this;
  82564. };
  82565. /**
  82566. * Sets this Weapon to track the given Pointer.
  82567. * When a Weapon tracks a Pointer it will automatically update its `fireFrom` value to match the Pointers
  82568. * position within the Game World, adjusting the coordinates based on the offset arguments.
  82569. *
  82570. * This allows you to lock a Weapon to a Pointer, so that bullets are always launched from its location.
  82571. *
  82572. * Calling `trackPointer` will reset `Weapon.trackedSprite` to null, should it have been set, as you can
  82573. * only track _either_ a Pointer, or a Sprite, at once, but not both.
  82574. *
  82575. * @method Phaser.Weapon#trackPointer
  82576. * @param {Phaser.Pointer} [pointer] - The Pointer to track the position of. Defaults to `Input.activePointer` if not specified.
  82577. * @param {integer} [offsetX=0] - The horizontal offset from the Pointers position to be applied to the Weapon.
  82578. * @param {integer} [offsetY=0] - The vertical offset from the Pointers position to be applied to the Weapon.
  82579. * @return {Phaser.Weapon} This Weapon instance.
  82580. */
  82581. Phaser.Weapon.prototype.trackPointer = function (pointer, offsetX, offsetY) {
  82582. if (pointer === undefined) { pointer = this.game.input.activePointer; }
  82583. if (offsetX === undefined) { offsetX = 0; }
  82584. if (offsetY === undefined) { offsetY = 0; }
  82585. this.trackedPointer = pointer;
  82586. this.trackedSprite = null;
  82587. this.trackRotation = false;
  82588. this.trackOffset.set(offsetX, offsetY);
  82589. return this;
  82590. };
  82591. /**
  82592. * Attempts to fire a single Bullet. If there are no more bullets available in the pool, and the pool cannot be extended,
  82593. * then this method returns `false`. It will also return false if not enough time has expired since the last time
  82594. * the Weapon was fired, as defined in the `Weapon.fireRate` property.
  82595. *
  82596. * Otherwise the first available bullet is selected and launched.
  82597. *
  82598. * The arguments are all optional, but allow you to control both where the bullet is launched from, and aimed at.
  82599. *
  82600. * If you don't provide any of the arguments then it uses those set via properties such as `Weapon.trackedSprite`,
  82601. * `Weapon.bulletAngle` and so on.
  82602. *
  82603. * When the bullet is launched it has its texture and frame updated, as required. The velocity of the bullet is
  82604. * calculated based on Weapon properties like `bulletSpeed`.
  82605. *
  82606. * @method Phaser.Weapon#fire
  82607. * @param {Phaser.Sprite|Phaser.Point|Object} [from] - Optionally fires the bullet **from** the `x` and `y` properties of this object. If set this overrides `Weapon.trackedSprite` or `trackedPointer`. Pass `null` to ignore it.
  82608. * @param {number} [x] - The x coordinate, in world space, to fire the bullet **towards**. If left as `undefined` the bullet direction is based on its angle.
  82609. * @param {number} [y] - The y coordinate, in world space, to fire the bullet **towards**. If left as `undefined` the bullet direction is based on its angle.
  82610. * @return {Phaser.Bullet} The fired bullet if successful, null otherwise.
  82611. */
  82612. Phaser.Weapon.prototype.fire = function (from, x, y) {
  82613. if (this.game.time.now < this._nextFire || (this.fireLimit > 0 && this.shots === this.fireLimit))
  82614. {
  82615. return false;
  82616. }
  82617. var speed = this.bulletSpeed;
  82618. // Apply +- speed variance
  82619. if (this.bulletSpeedVariance !== 0)
  82620. {
  82621. speed += Phaser.Math.between(-this.bulletSpeedVariance, this.bulletSpeedVariance);
  82622. }
  82623. if (from)
  82624. {
  82625. if (this.fireFrom.width > 1)
  82626. {
  82627. this.fireFrom.centerOn(from.x, from.y);
  82628. }
  82629. else
  82630. {
  82631. this.fireFrom.x = from.x;
  82632. this.fireFrom.y = from.y;
  82633. }
  82634. }
  82635. else if (this.trackedSprite)
  82636. {
  82637. if (this.trackRotation)
  82638. {
  82639. this._rotatedPoint.set(this.trackedSprite.world.x + this.trackOffset.x, this.trackedSprite.world.y + this.trackOffset.y);
  82640. this._rotatedPoint.rotate(this.trackedSprite.world.x, this.trackedSprite.world.y, this.trackedSprite.rotation);
  82641. if (this.fireFrom.width > 1)
  82642. {
  82643. this.fireFrom.centerOn(this._rotatedPoint.x, this._rotatedPoint.y);
  82644. }
  82645. else
  82646. {
  82647. this.fireFrom.x = this._rotatedPoint.x;
  82648. this.fireFrom.y = this._rotatedPoint.y;
  82649. }
  82650. }
  82651. else
  82652. {
  82653. if (this.fireFrom.width > 1)
  82654. {
  82655. this.fireFrom.centerOn(this.trackedSprite.world.x + this.trackOffset.x, this.trackedSprite.world.y + this.trackOffset.y);
  82656. }
  82657. else
  82658. {
  82659. this.fireFrom.x = this.trackedSprite.world.x + this.trackOffset.x;
  82660. this.fireFrom.y = this.trackedSprite.world.y + this.trackOffset.y;
  82661. }
  82662. }
  82663. if (this.bulletInheritSpriteSpeed)
  82664. {
  82665. speed += this.trackedSprite.body.speed;
  82666. }
  82667. }
  82668. else if (this.trackedPointer)
  82669. {
  82670. if (this.fireFrom.width > 1)
  82671. {
  82672. this.fireFrom.centerOn(this.trackedPointer.world.x + this.trackOffset.x, this.trackedPointer.world.y + this.trackOffset.y);
  82673. }
  82674. else
  82675. {
  82676. this.fireFrom.x = this.trackedPointer.world.x + this.trackOffset.x;
  82677. this.fireFrom.y = this.trackedPointer.world.y + this.trackOffset.y;
  82678. }
  82679. }
  82680. var fromX = (this.fireFrom.width > 1) ? this.fireFrom.randomX : this.fireFrom.x;
  82681. var fromY = (this.fireFrom.height > 1) ? this.fireFrom.randomY : this.fireFrom.y;
  82682. var angle = (this.trackRotation) ? this.trackedSprite.angle : this.fireAngle;
  82683. // The position (in world space) to fire the bullet towards, if set
  82684. if (x !== undefined && y !== undefined)
  82685. {
  82686. angle = this.game.math.radToDeg(Math.atan2(y - fromY, x - fromX));
  82687. }
  82688. // Apply +- angle variance
  82689. if (this.bulletAngleVariance !== 0)
  82690. {
  82691. angle += Phaser.Math.between(-this.bulletAngleVariance, this.bulletAngleVariance);
  82692. }
  82693. var moveX = 0;
  82694. var moveY = 0;
  82695. // Avoid sin/cos for right-angled shots
  82696. if (angle === 0 || angle === 180)
  82697. {
  82698. moveX = Math.cos(this.game.math.degToRad(angle)) * speed;
  82699. }
  82700. else if (angle === 90 || angle === 270)
  82701. {
  82702. moveY = Math.sin(this.game.math.degToRad(angle)) * speed;
  82703. }
  82704. else
  82705. {
  82706. moveX = Math.cos(this.game.math.degToRad(angle)) * speed;
  82707. moveY = Math.sin(this.game.math.degToRad(angle)) * speed;
  82708. }
  82709. var bullet = null;
  82710. if (this.autoExpandBulletsGroup)
  82711. {
  82712. bullet = this.bullets.getFirstExists(false, true, fromX, fromY, this.bulletKey, this.bulletFrame);
  82713. bullet.data.bulletManager = this;
  82714. }
  82715. else
  82716. {
  82717. bullet = this.bullets.getFirstExists(false);
  82718. }
  82719. if (bullet)
  82720. {
  82721. bullet.reset(fromX, fromY);
  82722. bullet.data.fromX = fromX;
  82723. bullet.data.fromY = fromY;
  82724. bullet.data.killType = this.bulletKillType;
  82725. bullet.data.killDistance = this.bulletKillDistance;
  82726. bullet.data.rotateToVelocity = this.bulletRotateToVelocity;
  82727. if (this.bulletKillType === Phaser.Weapon.KILL_LIFESPAN)
  82728. {
  82729. bullet.lifespan = this.bulletLifespan;
  82730. }
  82731. bullet.angle = angle + this.bulletAngleOffset;
  82732. // Frames and Animations
  82733. if (this.bulletAnimation !== '')
  82734. {
  82735. if (bullet.animations.getAnimation(this.bulletAnimation) === null)
  82736. {
  82737. var anim = this.anims[this.bulletAnimation];
  82738. bullet.animations.add(anim.name, anim.frames, anim.frameRate, anim.loop, anim.useNumericIndex);
  82739. }
  82740. bullet.animations.play(this.bulletAnimation);
  82741. }
  82742. else
  82743. {
  82744. if (this.bulletFrameCycle)
  82745. {
  82746. bullet.frame = this.bulletFrames[this.bulletFrameIndex];
  82747. this.bulletFrameIndex++;
  82748. if (this.bulletFrameIndex >= this.bulletFrames.length)
  82749. {
  82750. this.bulletFrameIndex = 0;
  82751. }
  82752. }
  82753. else if (this.bulletFrameRandom)
  82754. {
  82755. bullet.frame = this.bulletFrames[Math.floor(Math.random() * this.bulletFrames.length)];
  82756. }
  82757. }
  82758. if (bullet.data.bodyDirty)
  82759. {
  82760. if (this._data.customBody)
  82761. {
  82762. bullet.body.setSize(this._data.width, this._data.height, this._data.offsetX, this._data.offsetY);
  82763. }
  82764. bullet.body.collideWorldBounds = this.bulletCollideWorldBounds;
  82765. bullet.data.bodyDirty = false;
  82766. }
  82767. bullet.body.velocity.set(moveX, moveY);
  82768. bullet.body.gravity.set(this.bulletGravity.x, this.bulletGravity.y);
  82769. if (this.bulletSpeedVariance !== 0)
  82770. {
  82771. var rate = this.fireRate;
  82772. rate += Phaser.Math.between(-this.fireRateVariance, this.fireRateVariance);
  82773. if (rate < 0)
  82774. {
  82775. rate = 0;
  82776. }
  82777. this._nextFire = this.game.time.now + rate;
  82778. }
  82779. else
  82780. {
  82781. this._nextFire = this.game.time.now + this.fireRate;
  82782. }
  82783. this.shots++;
  82784. this.onFire.dispatch(bullet, this, speed);
  82785. if (this.fireLimit > 0 && this.shots === this.fireLimit)
  82786. {
  82787. this.onFireLimit.dispatch(this, this.fireLimit);
  82788. }
  82789. }
  82790. return bullet;
  82791. };
  82792. /**
  82793. * Fires a bullet **at** the given Pointer. The bullet will be launched from the `Weapon.fireFrom` position,
  82794. * or from a Tracked Sprite or Pointer, if you have one set.
  82795. *
  82796. * @method Phaser.Weapon#fireAtPointer
  82797. * @param {Phaser.Pointer} [pointer] - The Pointer to fire the bullet towards.
  82798. * @return {Phaser.Bullet} The fired bullet if successful, null otherwise.
  82799. */
  82800. Phaser.Weapon.prototype.fireAtPointer = function (pointer) {
  82801. if (pointer === undefined) { pointer = this.game.input.activePointer; }
  82802. return this.fire(null, pointer.worldX, pointer.worldY);
  82803. };
  82804. /**
  82805. * Fires a bullet **at** the given Sprite. The bullet will be launched from the `Weapon.fireFrom` position,
  82806. * or from a Tracked Sprite or Pointer, if you have one set.
  82807. *
  82808. * @method Phaser.Weapon#fireAtSprite
  82809. * @param {Phaser.Sprite} [sprite] - The Sprite to fire the bullet towards.
  82810. * @return {Phaser.Bullet} The fired bullet if successful, null otherwise.
  82811. */
  82812. Phaser.Weapon.prototype.fireAtSprite = function (sprite) {
  82813. return this.fire(null, sprite.world.x, sprite.world.y);
  82814. };
  82815. /**
  82816. * Fires a bullet **at** the given coordinates. The bullet will be launched from the `Weapon.fireFrom` position,
  82817. * or from a Tracked Sprite or Pointer, if you have one set.
  82818. *
  82819. * @method Phaser.Weapon#fireAtXY
  82820. * @param {number} [x] - The x coordinate, in world space, to fire the bullet towards.
  82821. * @param {number} [y] - The y coordinate, in world space, to fire the bullet towards.
  82822. * @return {Phaser.Bullet} The fired bullet if successful, null otherwise.
  82823. */
  82824. Phaser.Weapon.prototype.fireAtXY = function (x, y) {
  82825. return this.fire(null, x, y);
  82826. };
  82827. /**
  82828. * You can modify the size of the physics Body the Bullets use to be any dimension you need.
  82829. * This allows you to make it smaller, or larger, than the parent Sprite.
  82830. * You can also control the x and y offset of the Body. This is the position of the
  82831. * Body relative to the top-left of the Sprite _texture_.
  82832. *
  82833. * For example: If you have a Sprite with a texture that is 80x100 in size,
  82834. * and you want the physics body to be 32x32 pixels in the middle of the texture, you would do:
  82835. *
  82836. * `setSize(32, 32, 24, 34)`
  82837. *
  82838. * Where the first two parameters is the new Body size (32x32 pixels).
  82839. * 24 is the horizontal offset of the Body from the top-left of the Sprites texture, and 34
  82840. * is the vertical offset.
  82841. *
  82842. * @method Phaser.Weapon#setBulletBodyOffset
  82843. * @param {number} width - The width of the Body.
  82844. * @param {number} height - The height of the Body.
  82845. * @param {number} [offsetX] - The X offset of the Body from the top-left of the Sprites texture.
  82846. * @param {number} [offsetY] - The Y offset of the Body from the top-left of the Sprites texture.
  82847. * @return {Phaser.Weapon} The Weapon Plugin.
  82848. */
  82849. Phaser.Weapon.prototype.setBulletBodyOffset = function (width, height, offsetX, offsetY) {
  82850. if (offsetX === undefined) { offsetX = 0; }
  82851. if (offsetY === undefined) { offsetY = 0; }
  82852. this._data.customBody = true;
  82853. this._data.width = width;
  82854. this._data.height = height;
  82855. this._data.offsetX = offsetX;
  82856. this._data.offsetY = offsetY;
  82857. // Update all bullets in the pool
  82858. this.bullets.callAll('body.setSize', 'body', width, height, offsetX, offsetY);
  82859. this.bullets.setAll('data.bodyDirty', false);
  82860. return this;
  82861. };
  82862. /**
  82863. * Sets the texture frames that the bullets can use when being launched.
  82864. *
  82865. * This is intended for use when you've got numeric based frames, such as those loaded via a Sprite Sheet.
  82866. *
  82867. * It works by calling `Phaser.ArrayUtils.numberArray` internally, using the min and max values
  82868. * provided. Then it sets the frame index to be zero.
  82869. *
  82870. * You can optionally set the cycle and random booleans, to allow bullets to cycle through the frames
  82871. * when they're fired, or pick one at random.
  82872. *
  82873. * @method Phaser.Weapon#setBulletFrames
  82874. * @param {integer} min - The minimum value the frame can be. Usually zero.
  82875. * @param {integer} max - The maximum value the frame can be.
  82876. * @param {boolean} [cycle=true] - Should the bullet frames cycle as they are fired?
  82877. * @param {boolean} [random=false] - Should the bullet frames be picked at random as they are fired?
  82878. * @return {Phaser.Weapon} The Weapon Plugin.
  82879. */
  82880. Phaser.Weapon.prototype.setBulletFrames = function (min, max, cycle, random) {
  82881. if (cycle === undefined) { cycle = true; }
  82882. if (random === undefined) { random = false; }
  82883. this.bulletFrames = Phaser.ArrayUtils.numberArray(min, max);
  82884. this.bulletFrameIndex = 0;
  82885. this.bulletFrameCycle = cycle;
  82886. this.bulletFrameRandom = random;
  82887. return this;
  82888. };
  82889. /**
  82890. * Adds a new animation under the given key. Optionally set the frames, frame rate and loop.
  82891. * The arguments are all the same as for `Animation.add`, and work in the same way.
  82892. *
  82893. * `Weapon.bulletAnimation` will be set to this animation after it's created. From that point on, all
  82894. * bullets fired will play using this animation. You can swap between animations by calling this method
  82895. * several times, and then just changing the `Weapon.bulletAnimation` property to the name of the animation
  82896. * you wish to play for the next launched bullet.
  82897. *
  82898. * If you wish to stop using animations at all, set `Weapon.bulletAnimation` to '' (an empty string).
  82899. *
  82900. * @method Phaser.Weapon#addBulletAnimation
  82901. * @param {string} name - The unique (within the Weapon instance) name for the animation, i.e. "fire", "blast".
  82902. * @param {Array} [frames=null] - An array of numbers/strings that correspond to the frames to add to this animation and in which order. e.g. [1, 2, 3] or ['run0', 'run1', run2]). If null then all frames will be used.
  82903. * @param {number} [frameRate=60] - The speed at which the animation should play. The speed is given in frames per second.
  82904. * @param {boolean} [loop=false] - Whether or not the animation is looped or just plays once.
  82905. * @param {boolean} [useNumericIndex=true] - Are the given frames using numeric indexes (default) or strings?
  82906. * @return {Phaser.Weapon} The Weapon Plugin.
  82907. */
  82908. Phaser.Weapon.prototype.addBulletAnimation = function (name, frames, frameRate, loop, useNumericIndex) {
  82909. this.anims[name] = {
  82910. name: name,
  82911. frames: frames,
  82912. frameRate: frameRate,
  82913. loop: loop,
  82914. useNumericIndex: useNumericIndex
  82915. };
  82916. // Add the animation to any existing bullets in the pool
  82917. this.bullets.callAll('animations.add', 'animations', name, frames, frameRate, loop, useNumericIndex);
  82918. this.bulletAnimation = name;
  82919. return this;
  82920. };
  82921. /**
  82922. * Uses `Game.Debug` to draw some useful information about this Weapon, including the number of bullets
  82923. * both in-flight, and available. And optionally the physics debug bodies of the bullets.
  82924. *
  82925. * @method Phaser.Weapon#debug
  82926. * @param {integer} [x=16] - The coordinate, in screen space, at which to draw the Weapon debug data.
  82927. * @param {integer} [y=32] - The coordinate, in screen space, at which to draw the Weapon debug data.
  82928. * @param {boolean} [debugBodies=false] - Optionally draw the physics body of every bullet in-flight.
  82929. */
  82930. Phaser.Weapon.prototype.debug = function (x, y, debugBodies) {
  82931. if (x === undefined) { x = 16; }
  82932. if (y === undefined) { y = 32; }
  82933. if (debugBodies === undefined) { debugBodies = false; }
  82934. this.game.debug.text("Weapon Plugin", x, y);
  82935. this.game.debug.text("Bullets Alive: " + this.bullets.total + " - Total: " + this.bullets.length, x, y + 24);
  82936. if (debugBodies)
  82937. {
  82938. this.bullets.forEachExists(this.game.debug.body, this.game.debug, 'rgba(255, 0, 255, 0.8)');
  82939. }
  82940. };
  82941. /**
  82942. * The Class of the bullets that are launched by this Weapon. Defaults `Phaser.Bullet`, but can be
  82943. * overridden before calling `createBullets` and set to your own class type.
  82944. *
  82945. * @name Phaser.Weapon#bulletClass
  82946. * @property {Object} bulletClass
  82947. */
  82948. Object.defineProperty(Phaser.Weapon.prototype, "bulletClass", {
  82949. get: function () {
  82950. return this._bulletClass;
  82951. },
  82952. set: function (classType) {
  82953. this._bulletClass = classType;
  82954. this.bullets.classType = this._bulletClass;
  82955. }
  82956. });
  82957. /**
  82958. * This controls how the bullets will be killed. The default is `Phaser.Weapon.KILL_WORLD_BOUNDS`.
  82959. *
  82960. * There are 7 different "kill types" available:
  82961. *
  82962. * * `Phaser.Weapon.KILL_NEVER`
  82963. * The bullets are never destroyed by the Weapon. It's up to you to destroy them via your own code.
  82964. *
  82965. * * `Phaser.Weapon.KILL_LIFESPAN`
  82966. * The bullets are automatically killed when their `bulletLifespan` amount expires.
  82967. *
  82968. * * `Phaser.Weapon.KILL_DISTANCE`
  82969. * The bullets are automatically killed when they exceed `bulletDistance` pixels away from their original launch position.
  82970. *
  82971. * * `Phaser.Weapon.KILL_WEAPON_BOUNDS`
  82972. * The bullets are automatically killed when they no longer intersect with the `Weapon.bounds` rectangle.
  82973. *
  82974. * * `Phaser.Weapon.KILL_CAMERA_BOUNDS`
  82975. * The bullets are automatically killed when they no longer intersect with the `Camera.bounds` rectangle.
  82976. *
  82977. * * `Phaser.Weapon.KILL_WORLD_BOUNDS`
  82978. * The bullets are automatically killed when they no longer intersect with the `World.bounds` rectangle.
  82979. *
  82980. * * `Phaser.Weapon.KILL_STATIC_BOUNDS`
  82981. * The bullets are automatically killed when they no longer intersect with the `Weapon.bounds` rectangle.
  82982. * The difference between static bounds and weapon bounds, is that a static bounds will never be adjusted to
  82983. * match the position of a tracked sprite or pointer.
  82984. *
  82985. * @name Phaser.Weapon#bulletKillType
  82986. * @property {integer} bulletKillType
  82987. */
  82988. Object.defineProperty(Phaser.Weapon.prototype, "bulletKillType", {
  82989. get: function () {
  82990. return this._bulletKillType;
  82991. },
  82992. set: function (type) {
  82993. switch (type)
  82994. {
  82995. case Phaser.Weapon.KILL_STATIC_BOUNDS:
  82996. case Phaser.Weapon.KILL_WEAPON_BOUNDS:
  82997. this.bulletBounds = this.bounds;
  82998. break;
  82999. case Phaser.Weapon.KILL_CAMERA_BOUNDS:
  83000. this.bulletBounds = this.game.camera.view;
  83001. break;
  83002. case Phaser.Weapon.KILL_WORLD_BOUNDS:
  83003. this.bulletBounds = this.game.world.bounds;
  83004. break;
  83005. }
  83006. this._bulletKillType = type;
  83007. }
  83008. });
  83009. /**
  83010. * Should bullets collide with the World bounds or not?
  83011. *
  83012. * @name Phaser.Weapon#bulletCollideWorldBounds
  83013. * @property {boolean} bulletCollideWorldBounds
  83014. */
  83015. Object.defineProperty(Phaser.Weapon.prototype, "bulletCollideWorldBounds", {
  83016. get: function () {
  83017. return this._bulletCollideWorldBounds;
  83018. },
  83019. set: function (value) {
  83020. this._bulletCollideWorldBounds = value;
  83021. this.bullets.setAll('body.collideWorldBounds', value);
  83022. this.bullets.setAll('data.bodyDirty', false);
  83023. }
  83024. });
  83025. /**
  83026. * The x coordinate from which bullets are fired. This is the same as `Weapon.fireFrom.x`, and
  83027. * can be overridden by the `Weapon.fire` arguments.
  83028. *
  83029. * @name Phaser.Weapon#x
  83030. * @property {number} x
  83031. */
  83032. Object.defineProperty(Phaser.Weapon.prototype, "x", {
  83033. get: function () {
  83034. return this.fireFrom.x;
  83035. },
  83036. set: function (value) {
  83037. this.fireFrom.x = value;
  83038. }
  83039. });
  83040. /**
  83041. * The y coordinate from which bullets are fired. This is the same as `Weapon.fireFrom.y`, and
  83042. * can be overridden by the `Weapon.fire` arguments.
  83043. *
  83044. * @name Phaser.Weapon#y
  83045. * @property {number} y
  83046. */
  83047. Object.defineProperty(Phaser.Weapon.prototype, "y", {
  83048. get: function () {
  83049. return this.fireFrom.y;
  83050. },
  83051. set: function (value) {
  83052. this.fireFrom.y = value;
  83053. }
  83054. });
  83055. /**
  83056. * @author Richard Davey <rich@photonstorm.com>
  83057. * @copyright 2016 Photon Storm Ltd.
  83058. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  83059. */
  83060. /**
  83061. * Create a new `Bullet` object. Bullets are used by the `Phaser.Weapon` class, and are normal Sprites,
  83062. * with a few extra properties in the data object to handle Weapon specific features.
  83063. *
  83064. * @class Phaser.Bullet
  83065. * @constructor
  83066. * @extends Phaser.Sprite
  83067. * @param {Phaser.Game} game - A reference to the currently running game.
  83068. * @param {number} x - The x coordinate (in world space) to position the Particle at.
  83069. * @param {number} y - The y coordinate (in world space) to position the Particle at.
  83070. * @param {string|Phaser.RenderTexture|Phaser.BitmapData|PIXI.Texture} key - This is the image or texture used by the Particle during rendering. It can be a string which is a reference to the Cache entry, or an instance of a RenderTexture or PIXI.Texture.
  83071. * @param {string|number} frame - If this Particle is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index.
  83072. */
  83073. Phaser.Bullet = function (game, x, y, key, frame) {
  83074. Phaser.Sprite.call(this, game, x, y, key, frame);
  83075. this.anchor.set(0.5);
  83076. this.data = {
  83077. bulletManager: null,
  83078. fromX: 0,
  83079. fromY: 0,
  83080. bodyDirty: true,
  83081. rotateToVelocity: false,
  83082. killType: 0,
  83083. killDistance: 0
  83084. };
  83085. };
  83086. Phaser.Bullet.prototype = Object.create(Phaser.Sprite.prototype);
  83087. Phaser.Bullet.prototype.constructor = Phaser.Bullet;
  83088. /**
  83089. * Kills the Bullet, freeing it up for re-use by the Weapon bullet pool.
  83090. * Also dispatches the `Weapon.onKill` signal.
  83091. *
  83092. * @method Phaser.Bullet#kill
  83093. * @memberof Phaser.Bullet
  83094. */
  83095. Phaser.Bullet.prototype.kill = function () {
  83096. this.alive = false;
  83097. this.exists = false;
  83098. this.visible = false;
  83099. this.data.bulletManager.onKill.dispatch(this);
  83100. return this;
  83101. };
  83102. /**
  83103. * Updates the Bullet, killing as required.
  83104. *
  83105. * @method Phaser.Bullet#kill
  83106. * @memberof Phaser.Bullet
  83107. */
  83108. Phaser.Bullet.prototype.update = function () {
  83109. if (!this.exists)
  83110. {
  83111. return;
  83112. }
  83113. if (this.data.killType > Phaser.Weapon.KILL_LIFESPAN)
  83114. {
  83115. if (this.data.killType === Phaser.Weapon.KILL_DISTANCE)
  83116. {
  83117. if (this.game.physics.arcade.distanceToXY(this, this.data.fromX, this.data.fromY, true) > this.data.killDistance)
  83118. {
  83119. this.kill();
  83120. }
  83121. }
  83122. else
  83123. {
  83124. if (!this.data.bulletManager.bulletBounds.intersects(this))
  83125. {
  83126. this.kill();
  83127. }
  83128. }
  83129. }
  83130. if (this.data.rotateToVelocity)
  83131. {
  83132. this.rotation = Math.atan2(this.body.velocity.y, this.body.velocity.x);
  83133. }
  83134. if (this.data.bulletManager.bulletWorldWrap)
  83135. {
  83136. this.game.world.wrap(this, this.data.bulletManager.bulletWorldWrapPadding);
  83137. }
  83138. };
  83139. /**
  83140. * @author Richard Davey <rich@photonstorm.com>
  83141. * @copyright 2016 Photon Storm Ltd.
  83142. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  83143. */
  83144. /**
  83145. * A Video object that takes a previously loaded Video from the Phaser Cache and handles playback of it.
  83146. *
  83147. * Alternatively it takes a getUserMedia feed from an active webcam and streams the contents of that to
  83148. * the Video instead (see `startMediaStream` method)
  83149. *
  83150. * The video can then be applied to a Sprite as a texture. If multiple Sprites share the same Video texture and playback
  83151. * changes (i.e. you pause the video, or seek to a new time) then this change will be seen across all Sprites simultaneously.
  83152. *
  83153. * Due to a bug in IE11 you cannot play a video texture to a Sprite in WebGL. For IE11 force Canvas mode.
  83154. *
  83155. * If you need each Sprite to be able to play a video fully independently then you will need one Video object per Sprite.
  83156. * Please understand the obvious performance implications of doing this, and the memory required to hold videos in RAM.
  83157. *
  83158. * On some mobile browsers such as iOS Safari, you cannot play a video until the user has explicitly touched the screen.
  83159. * This works in the same way as audio unlocking. Phaser will handle the touch unlocking for you, however unlike with audio
  83160. * it's worth noting that every single Video needs to be touch unlocked, not just the first one. You can use the `changeSource`
  83161. * method to try and work around this limitation, but see the method help for details.
  83162. *
  83163. * Small screen devices, especially iPod and iPhone will launch the video in its own native video player,
  83164. * outside of the Safari browser. There is no way to avoid this, it's a device imposed limitation.
  83165. *
  83166. * Note: On iOS if you need to detect when the user presses the 'Done' button (before the video ends)
  83167. * then you need to add your own event listener
  83168. *
  83169. * @class Phaser.Video
  83170. * @constructor
  83171. * @param {Phaser.Game} game - A reference to the currently running game.
  83172. * @param {string|null} [key=null] - The key of the video file in the Phaser.Cache that this Video object will play. Set to `null` or leave undefined if you wish to use a webcam as the source. See `startMediaStream` to start webcam capture.
  83173. * @param {string|null} [url=null] - If the video hasn't been loaded then you can provide a full URL to the file here (make sure to set key to null)
  83174. */
  83175. Phaser.Video = function (game, key, url) {
  83176. if (key === undefined) { key = null; }
  83177. if (url === undefined) { url = null; }
  83178. /**
  83179. * @property {Phaser.Game} game - A reference to the currently running game.
  83180. */
  83181. this.game = game;
  83182. /**
  83183. * @property {string} key - The key of the Video in the Cache, if stored there. Will be `null` if this Video is using the webcam instead.
  83184. * @default null
  83185. */
  83186. this.key = key;
  83187. /**
  83188. * @property {number} width - The width of the video in pixels.
  83189. * @default
  83190. */
  83191. this.width = 0;
  83192. /**
  83193. * @property {number} height - The height of the video in pixels.
  83194. * @default
  83195. */
  83196. this.height = 0;
  83197. /**
  83198. * @property {number} type - The const type of this object.
  83199. * @default
  83200. */
  83201. this.type = Phaser.VIDEO;
  83202. /**
  83203. * @property {boolean} disableTextureUpload - If true this video will never send its image data to the GPU when its dirty flag is true. This only applies in WebGL.
  83204. */
  83205. this.disableTextureUpload = false;
  83206. /**
  83207. * @property {boolean} touchLocked - true if this video is currently locked awaiting a touch event. This happens on some mobile devices, such as iOS.
  83208. * @default
  83209. */
  83210. this.touchLocked = false;
  83211. /**
  83212. * @property {Phaser.Signal} onPlay - This signal is dispatched when the Video starts to play. It sends 3 parameters: a reference to the Video object, if the video is set to loop or not and the playback rate.
  83213. */
  83214. this.onPlay = new Phaser.Signal();
  83215. /**
  83216. * @property {Phaser.Signal} onChangeSource - This signal is dispatched if the Video source is changed. It sends 3 parameters: a reference to the Video object and the new width and height of the new video source.
  83217. */
  83218. this.onChangeSource = new Phaser.Signal();
  83219. /**
  83220. * @property {Phaser.Signal} onComplete - This signal is dispatched when the Video completes playback, i.e. enters an 'ended' state. On iOS specifically it also fires if the user hits the 'Done' button at any point during playback. Videos set to loop will never dispatch this signal.
  83221. */
  83222. this.onComplete = new Phaser.Signal();
  83223. /**
  83224. * @property {Phaser.Signal} onAccess - This signal is dispatched if the user allows access to their webcam.
  83225. */
  83226. this.onAccess = new Phaser.Signal();
  83227. /**
  83228. * @property {Phaser.Signal} onError - This signal is dispatched if an error occurs either getting permission to use the webcam (for a Video Stream) or when trying to play back a video file.
  83229. */
  83230. this.onError = new Phaser.Signal();
  83231. /**
  83232. * This signal is dispatched if when asking for permission to use the webcam no response is given within a the Video.timeout limit.
  83233. * This may be because the user has picked `Not now` in the permissions window, or there is a delay in establishing the LocalMediaStream.
  83234. * @property {Phaser.Signal} onTimeout
  83235. */
  83236. this.onTimeout = new Phaser.Signal();
  83237. /**
  83238. * @property {integer} timeout - The amount of ms allowed to elapsed before the Video.onTimeout signal is dispatched while waiting for webcam access.
  83239. * @default
  83240. */
  83241. this.timeout = 15000;
  83242. /**
  83243. * @property {integer} _timeOutID - setTimeout ID.
  83244. * @private
  83245. */
  83246. this._timeOutID = null;
  83247. /**
  83248. * @property {HTMLVideoElement} video - The HTML Video Element that is added to the document.
  83249. */
  83250. this.video = null;
  83251. /**
  83252. * @property {MediaStream} videoStream - The Video Stream data. Only set if this Video is streaming from the webcam via `startMediaStream`.
  83253. */
  83254. this.videoStream = null;
  83255. /**
  83256. * @property {boolean} isStreaming - Is there a streaming video source? I.e. from a webcam.
  83257. */
  83258. this.isStreaming = false;
  83259. /**
  83260. * When starting playback of a video Phaser will monitor its readyState using a setTimeout call.
  83261. * The setTimeout happens once every `Video.retryInterval` ms. It will carry on monitoring the video
  83262. * state in this manner until the `retryLimit` is reached and then abort.
  83263. * @property {integer} retryLimit
  83264. * @default
  83265. */
  83266. this.retryLimit = 20;
  83267. /**
  83268. * @property {integer} retry - The current retry attempt.
  83269. * @default
  83270. */
  83271. this.retry = 0;
  83272. /**
  83273. * @property {integer} retryInterval - The number of ms between each retry at monitoring the status of a downloading video.
  83274. * @default
  83275. */
  83276. this.retryInterval = 500;
  83277. /**
  83278. * @property {integer} _retryID - The callback ID of the retry setTimeout.
  83279. * @private
  83280. */
  83281. this._retryID = null;
  83282. /**
  83283. * @property {boolean} _codeMuted - Internal mute tracking var.
  83284. * @private
  83285. * @default
  83286. */
  83287. this._codeMuted = false;
  83288. /**
  83289. * @property {boolean} _muted - Internal mute tracking var.
  83290. * @private
  83291. * @default
  83292. */
  83293. this._muted = false;
  83294. /**
  83295. * @property {boolean} _codePaused - Internal paused tracking var.
  83296. * @private
  83297. * @default
  83298. */
  83299. this._codePaused = false;
  83300. /**
  83301. * @property {boolean} _paused - Internal paused tracking var.
  83302. * @private
  83303. * @default
  83304. */
  83305. this._paused = false;
  83306. /**
  83307. * @property {boolean} _pending - Internal var tracking play pending.
  83308. * @private
  83309. * @default
  83310. */
  83311. this._pending = false;
  83312. /**
  83313. * @property {boolean} _autoplay - Internal var tracking autoplay when changing source.
  83314. * @private
  83315. * @default
  83316. */
  83317. this._autoplay = false;
  83318. /**
  83319. * @property {function} _endCallback - The addEventListener ended function.
  83320. * @private
  83321. */
  83322. this._endCallback = null;
  83323. /**
  83324. * @property {function} _playCallback - The addEventListener playing function.
  83325. * @private
  83326. */
  83327. this._playCallback = null;
  83328. if (key && this.game.cache.checkVideoKey(key))
  83329. {
  83330. var _video = this.game.cache.getVideo(key);
  83331. if (_video.isBlob)
  83332. {
  83333. this.createVideoFromBlob(_video.data);
  83334. }
  83335. else
  83336. {
  83337. this.video = _video.data;
  83338. }
  83339. this.width = this.video.videoWidth;
  83340. this.height = this.video.videoHeight;
  83341. }
  83342. else if (url)
  83343. {
  83344. this.createVideoFromURL(url, false);
  83345. }
  83346. /**
  83347. * @property {PIXI.BaseTexture} baseTexture - The PIXI.BaseTexture.
  83348. * @default
  83349. */
  83350. if (this.video && !url)
  83351. {
  83352. this.baseTexture = new PIXI.BaseTexture(this.video);
  83353. this.baseTexture.forceLoaded(this.width, this.height);
  83354. }
  83355. else
  83356. {
  83357. this.baseTexture = new PIXI.BaseTexture(Phaser.Cache.DEFAULT.baseTexture.source);
  83358. this.baseTexture.forceLoaded(this.width, this.height);
  83359. }
  83360. /**
  83361. * @property {PIXI.Texture} texture - The PIXI.Texture.
  83362. * @default
  83363. */
  83364. this.texture = new PIXI.Texture(this.baseTexture);
  83365. /**
  83366. * @property {Phaser.Frame} textureFrame - The Frame this video uses for rendering.
  83367. * @default
  83368. */
  83369. this.textureFrame = new Phaser.Frame(0, 0, 0, this.width, this.height, 'video');
  83370. this.texture.setFrame(this.textureFrame);
  83371. this.texture.valid = false;
  83372. if (key !== null && this.video)
  83373. {
  83374. this.texture.valid = this.video.canplay;
  83375. }
  83376. /**
  83377. * A snapshot grabbed from the video. This is initially black. Populate it by calling Video.grab().
  83378. * When called the BitmapData is updated with a grab taken from the current video playing or active video stream.
  83379. * If Phaser has been compiled without BitmapData support this property will always be `null`.
  83380. *
  83381. * @property {Phaser.BitmapData} snapshot
  83382. * @readOnly
  83383. */
  83384. this.snapshot = null;
  83385. if (Phaser.BitmapData)
  83386. {
  83387. this.snapshot = new Phaser.BitmapData(this.game, '', this.width, this.height);
  83388. }
  83389. if (!this.game.device.cocoonJS && (this.game.device.iOS || this.game.device.android) || (window['PhaserGlobal'] && window['PhaserGlobal'].fakeiOSTouchLock))
  83390. {
  83391. this.setTouchLock();
  83392. }
  83393. else
  83394. {
  83395. if (_video)
  83396. {
  83397. _video.locked = false;
  83398. }
  83399. }
  83400. };
  83401. Phaser.Video.prototype = {
  83402. /**
  83403. * Connects to an external media stream for the webcam, rather than using a local one.
  83404. *
  83405. * @method Phaser.Video#connectToMediaStream
  83406. * @param {HTMLVideoElement} video - The HTML Video Element that the stream uses.
  83407. * @param {MediaStream} stream - The Video Stream data.
  83408. * @return {Phaser.Video} This Video object for method chaining.
  83409. */
  83410. connectToMediaStream: function (video, stream) {
  83411. if (video && stream)
  83412. {
  83413. this.video = video;
  83414. this.videoStream = stream;
  83415. this.isStreaming = true;
  83416. this.baseTexture.source = this.video;
  83417. this.updateTexture(null, this.video.videoWidth, this.video.videoHeight);
  83418. this.onAccess.dispatch(this);
  83419. }
  83420. return this;
  83421. },
  83422. /**
  83423. * Instead of playing a video file this method allows you to stream video data from an attached webcam.
  83424. *
  83425. * As soon as this method is called the user will be prompted by their browser to "Allow" access to the webcam.
  83426. * If they allow it the webcam feed is directed to this Video. Call `Video.play` to start the stream.
  83427. *
  83428. * If they block the webcam the onError signal will be dispatched containing the NavigatorUserMediaError
  83429. * or MediaStreamError event.
  83430. *
  83431. * You can optionally set a width and height for the stream. If set the input will be cropped to these dimensions.
  83432. * If not given then as soon as the stream has enough data the video dimensions will be changed to match the webcam device.
  83433. * You can listen for this with the onChangeSource signal.
  83434. *
  83435. * @method Phaser.Video#startMediaStream
  83436. * @param {boolean} [captureAudio=false] - Controls if audio should be captured along with video in the video stream.
  83437. * @param {integer} [width] - The width is used to create the video stream. If not provided the video width will be set to the width of the webcam input source.
  83438. * @param {integer} [height] - The height is used to create the video stream. If not provided the video height will be set to the height of the webcam input source.
  83439. * @return {Phaser.Video} This Video object for method chaining or false if the device doesn't support getUserMedia.
  83440. */
  83441. startMediaStream: function (captureAudio, width, height) {
  83442. if (captureAudio === undefined) { captureAudio = false; }
  83443. if (width === undefined) { width = null; }
  83444. if (height === undefined) { height = null; }
  83445. if (!this.game.device.getUserMedia)
  83446. {
  83447. this.onError.dispatch(this, 'No getUserMedia');
  83448. return false;
  83449. }
  83450. if (this.videoStream !== null)
  83451. {
  83452. if (this.videoStream['active'])
  83453. {
  83454. this.videoStream.active = false;
  83455. }
  83456. else
  83457. {
  83458. this.videoStream.stop();
  83459. }
  83460. }
  83461. this.removeVideoElement();
  83462. this.video = document.createElement("video");
  83463. this.video.setAttribute('autoplay', 'autoplay');
  83464. if (width !== null)
  83465. {
  83466. this.video.width = width;
  83467. }
  83468. if (height !== null)
  83469. {
  83470. this.video.height = height;
  83471. }
  83472. // Request access to the webcam
  83473. this._timeOutID = window.setTimeout(this.getUserMediaTimeout.bind(this), this.timeout);
  83474. try {
  83475. navigator.getUserMedia(
  83476. { "audio": captureAudio, "video": true },
  83477. this.getUserMediaSuccess.bind(this),
  83478. this.getUserMediaError.bind(this)
  83479. );
  83480. }
  83481. catch (error)
  83482. {
  83483. this.getUserMediaError(error);
  83484. }
  83485. return this;
  83486. },
  83487. /**
  83488. * @method Phaser.Video#getUserMediaTimeout
  83489. * @private
  83490. */
  83491. getUserMediaTimeout: function () {
  83492. clearTimeout(this._timeOutID);
  83493. this.onTimeout.dispatch(this);
  83494. },
  83495. /**
  83496. * @method Phaser.Video#getUserMediaError
  83497. * @private
  83498. */
  83499. getUserMediaError: function (event) {
  83500. clearTimeout(this._timeOutID);
  83501. this.onError.dispatch(this, event);
  83502. },
  83503. /**
  83504. * @method Phaser.Video#getUserMediaSuccess
  83505. * @private
  83506. */
  83507. getUserMediaSuccess: function (stream) {
  83508. clearTimeout(this._timeOutID);
  83509. // Attach the stream to the video
  83510. this.videoStream = stream;
  83511. // Set the source of the video element with the stream from the camera
  83512. if (this.video.mozSrcObject !== undefined)
  83513. {
  83514. this.video.mozSrcObject = stream;
  83515. }
  83516. else
  83517. {
  83518. this.video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  83519. }
  83520. var self = this;
  83521. this.video.onloadeddata = function () {
  83522. var retry = 10;
  83523. function checkStream () {
  83524. if (retry > 0)
  83525. {
  83526. if (self.video.videoWidth > 0)
  83527. {
  83528. // Patch for Firefox bug where the height can't be read from the video
  83529. var width = self.video.videoWidth;
  83530. var height = self.video.videoHeight;
  83531. if (isNaN(self.video.videoHeight))
  83532. {
  83533. height = width / (4/3);
  83534. }
  83535. self.video.play();
  83536. self.isStreaming = true;
  83537. self.baseTexture.source = self.video;
  83538. self.updateTexture(null, width, height);
  83539. self.onAccess.dispatch(self);
  83540. }
  83541. else
  83542. {
  83543. window.setTimeout(checkStream, 500);
  83544. }
  83545. }
  83546. else
  83547. {
  83548. console.warn('Unable to connect to video stream. Webcam error?');
  83549. }
  83550. retry--;
  83551. }
  83552. checkStream();
  83553. };
  83554. },
  83555. /**
  83556. * Creates a new Video element from the given Blob. The Blob must contain the video data in the correct encoded format.
  83557. * This method is typically called by the Phaser.Loader and Phaser.Cache for you, but is exposed publicly for convenience.
  83558. *
  83559. * @method Phaser.Video#createVideoFromBlob
  83560. * @param {Blob} blob - The Blob containing the video data: `Blob([new Uint8Array(data)])`
  83561. * @return {Phaser.Video} This Video object for method chaining.
  83562. */
  83563. createVideoFromBlob: function (blob) {
  83564. var _this = this;
  83565. this.video = document.createElement("video");
  83566. this.video.controls = false;
  83567. this.video.setAttribute('autoplay', 'autoplay');
  83568. this.video.addEventListener('loadeddata', function (event) { _this.updateTexture(event); }, true);
  83569. this.video.src = window.URL.createObjectURL(blob);
  83570. this.video.canplay = true;
  83571. return this;
  83572. },
  83573. /**
  83574. * Creates a new Video element from the given URL.
  83575. *
  83576. * @method Phaser.Video#createVideoFromURL
  83577. * @param {string} url - The URL of the video.
  83578. * @param {boolean} [autoplay=false] - Automatically start the video?
  83579. * @return {Phaser.Video} This Video object for method chaining.
  83580. */
  83581. createVideoFromURL: function (url, autoplay) {
  83582. if (autoplay === undefined) { autoplay = false; }
  83583. // Invalidate the texture while we wait for the new one to load (crashes IE11 otherwise)
  83584. if (this.texture)
  83585. {
  83586. this.texture.valid = false;
  83587. }
  83588. this.video = document.createElement("video");
  83589. this.video.controls = false;
  83590. if (autoplay)
  83591. {
  83592. this.video.setAttribute('autoplay', 'autoplay');
  83593. }
  83594. this.video.src = url;
  83595. this.video.canplay = true;
  83596. this.video.load();
  83597. this.retry = this.retryLimit;
  83598. this._retryID = window.setTimeout(this.checkVideoProgress.bind(this), this.retryInterval);
  83599. this.key = url;
  83600. return this;
  83601. },
  83602. /**
  83603. * Called automatically if the video source changes and updates the internal texture dimensions.
  83604. * Then dispatches the onChangeSource signal.
  83605. *
  83606. * @method Phaser.Video#updateTexture
  83607. * @param {object} [event] - The event which triggered the texture update.
  83608. * @param {integer} [width] - The new width of the video. If undefined `video.videoWidth` is used.
  83609. * @param {integer} [height] - The new height of the video. If undefined `video.videoHeight` is used.
  83610. */
  83611. updateTexture: function (event, width, height) {
  83612. var change = false;
  83613. if (width === undefined || width === null) { width = this.video.videoWidth; change = true; }
  83614. if (height === undefined || height === null) { height = this.video.videoHeight; }
  83615. this.width = width;
  83616. this.height = height;
  83617. if (this.baseTexture.source !== this.video)
  83618. {
  83619. this.baseTexture.source = this.video;
  83620. }
  83621. this.baseTexture.forceLoaded(width, height);
  83622. this.texture.frame.resize(width, height);
  83623. this.texture.width = width;
  83624. this.texture.height = height;
  83625. this.texture.valid = true;
  83626. if (this.snapshot)
  83627. {
  83628. this.snapshot.resize(width, height);
  83629. }
  83630. if (change && this.key !== null)
  83631. {
  83632. this.onChangeSource.dispatch(this, width, height);
  83633. if (this._autoplay)
  83634. {
  83635. this.video.play();
  83636. this.onPlay.dispatch(this, this.loop, this.playbackRate);
  83637. }
  83638. }
  83639. },
  83640. /**
  83641. * Called when the video completes playback (reaches and ended state).
  83642. * Dispatches the Video.onComplete signal.
  83643. *
  83644. * @method Phaser.Video#complete
  83645. */
  83646. complete: function () {
  83647. this.onComplete.dispatch(this);
  83648. },
  83649. /**
  83650. * Starts this video playing if it's not already doing so.
  83651. *
  83652. * @method Phaser.Video#play
  83653. * @param {boolean} [loop=false] - Should the video loop automatically when it reaches the end? Please note that at present some browsers (i.e. Chrome) do not support *seamless* video looping.
  83654. * @param {number} [playbackRate=1] - The playback rate of the video. 1 is normal speed, 2 is x2 speed, and so on. You cannot set a negative playback rate.
  83655. * @return {Phaser.Video} This Video object for method chaining.
  83656. */
  83657. play: function (loop, playbackRate) {
  83658. if (loop === undefined) { loop = false; }
  83659. if (playbackRate === undefined) { playbackRate = 1; }
  83660. if (this.game.sound.onMute)
  83661. {
  83662. this.game.sound.onMute.add(this.setMute, this);
  83663. this.game.sound.onUnMute.add(this.unsetMute, this);
  83664. if (this.game.sound.mute)
  83665. {
  83666. this.setMute();
  83667. }
  83668. }
  83669. this.game.onPause.add(this.setPause, this);
  83670. this.game.onResume.add(this.setResume, this);
  83671. this._endCallback = this.complete.bind(this);
  83672. this.video.addEventListener('ended', this._endCallback, true);
  83673. this.video.addEventListener('webkitendfullscreen', this._endCallback, true);
  83674. if (loop)
  83675. {
  83676. this.video.loop = 'loop';
  83677. }
  83678. else
  83679. {
  83680. this.video.loop = '';
  83681. }
  83682. this.video.playbackRate = playbackRate;
  83683. if (this.touchLocked)
  83684. {
  83685. this._pending = true;
  83686. }
  83687. else
  83688. {
  83689. this._pending = false;
  83690. if (this.key !== null)
  83691. {
  83692. if (this.video.readyState !== 4)
  83693. {
  83694. this.retry = this.retryLimit;
  83695. this._retryID = window.setTimeout(this.checkVideoProgress.bind(this), this.retryInterval);
  83696. }
  83697. else
  83698. {
  83699. this._playCallback = this.playHandler.bind(this);
  83700. this.video.addEventListener('playing', this._playCallback, true);
  83701. }
  83702. }
  83703. this.video.play();
  83704. this.onPlay.dispatch(this, loop, playbackRate);
  83705. }
  83706. return this;
  83707. },
  83708. /**
  83709. * Called when the video starts to play. Updates the texture.
  83710. *
  83711. * @method Phaser.Video#playHandler
  83712. * @private
  83713. */
  83714. playHandler: function () {
  83715. this.video.removeEventListener('playing', this._playCallback, true);
  83716. this.updateTexture();
  83717. },
  83718. /**
  83719. * Stops the video playing.
  83720. *
  83721. * This removes all locally set signals.
  83722. *
  83723. * If you only wish to pause playback of the video, to resume at a later time, use `Video.paused = true` instead.
  83724. * If the video hasn't finished downloading calling `Video.stop` will not abort the download. To do that you need to
  83725. * call `Video.destroy` instead.
  83726. *
  83727. * If you are using a video stream from a webcam then calling Stop will disconnect the MediaStream session and disable the webcam.
  83728. *
  83729. * @method Phaser.Video#stop
  83730. * @return {Phaser.Video} This Video object for method chaining.
  83731. */
  83732. stop: function () {
  83733. if (this.game.sound.onMute)
  83734. {
  83735. this.game.sound.onMute.remove(this.setMute, this);
  83736. this.game.sound.onUnMute.remove(this.unsetMute, this);
  83737. }
  83738. this.game.onPause.remove(this.setPause, this);
  83739. this.game.onResume.remove(this.setResume, this);
  83740. // Stream or file?
  83741. if (this.isStreaming)
  83742. {
  83743. if (this.video.mozSrcObject)
  83744. {
  83745. this.video.mozSrcObject.stop();
  83746. this.video.src = null;
  83747. }
  83748. else
  83749. {
  83750. this.video.src = "";
  83751. if (this.videoStream['active'])
  83752. {
  83753. this.videoStream.active = false;
  83754. }
  83755. else
  83756. {
  83757. if (this.videoStream.getTracks)
  83758. {
  83759. this.videoStream.getTracks().forEach(function (track) {
  83760. track.stop();
  83761. });
  83762. }
  83763. else
  83764. {
  83765. this.videoStream.stop();
  83766. }
  83767. }
  83768. }
  83769. this.videoStream = null;
  83770. this.isStreaming = false;
  83771. }
  83772. else
  83773. {
  83774. this.video.removeEventListener('ended', this._endCallback, true);
  83775. this.video.removeEventListener('webkitendfullscreen', this._endCallback, true);
  83776. this.video.removeEventListener('playing', this._playCallback, true);
  83777. if (this.touchLocked)
  83778. {
  83779. this._pending = false;
  83780. }
  83781. else
  83782. {
  83783. this.video.pause();
  83784. }
  83785. }
  83786. return this;
  83787. },
  83788. /**
  83789. * Updates the given Display Objects so they use this Video as their texture.
  83790. * This will replace any texture they will currently have set.
  83791. *
  83792. * @method Phaser.Video#add
  83793. * @param {Phaser.Sprite|Phaser.Sprite[]|Phaser.Image|Phaser.Image[]} object - Either a single Sprite/Image or an Array of Sprites/Images.
  83794. * @return {Phaser.Video} This Video object for method chaining.
  83795. */
  83796. add: function (object) {
  83797. if (Array.isArray(object))
  83798. {
  83799. for (var i = 0; i < object.length; i++)
  83800. {
  83801. if (object[i]['loadTexture'])
  83802. {
  83803. object[i].loadTexture(this);
  83804. }
  83805. }
  83806. }
  83807. else
  83808. {
  83809. object.loadTexture(this);
  83810. }
  83811. return this;
  83812. },
  83813. /**
  83814. * Creates a new Phaser.Image object, assigns this Video to be its texture, adds it to the world then returns it.
  83815. *
  83816. * @method Phaser.Video#addToWorld
  83817. * @param {number} [x=0] - The x coordinate to place the Image at.
  83818. * @param {number} [y=0] - The y coordinate to place the Image at.
  83819. * @param {number} [anchorX=0] - Set the x anchor point of the Image. A value between 0 and 1, where 0 is the top-left and 1 is bottom-right.
  83820. * @param {number} [anchorY=0] - Set the y anchor point of the Image. A value between 0 and 1, where 0 is the top-left and 1 is bottom-right.
  83821. * @param {number} [scaleX=1] - The horizontal scale factor of the Image. A value of 1 means no scaling. 2 would be twice the size, and so on.
  83822. * @param {number} [scaleY=1] - The vertical scale factor of the Image. A value of 1 means no scaling. 2 would be twice the size, and so on.
  83823. * @return {Phaser.Image} The newly added Image object.
  83824. */
  83825. addToWorld: function (x, y, anchorX, anchorY, scaleX, scaleY) {
  83826. scaleX = scaleX || 1;
  83827. scaleY = scaleY || 1;
  83828. var image = this.game.add.image(x, y, this);
  83829. image.anchor.set(anchorX, anchorY);
  83830. image.scale.set(scaleX, scaleY);
  83831. return image;
  83832. },
  83833. /**
  83834. * If the game is running in WebGL this will push the texture up to the GPU if it's dirty.
  83835. * This is called automatically if the Video is being used by a Sprite, otherwise you need to remember to call it in your render function.
  83836. * If you wish to suppress this functionality set Video.disableTextureUpload to `true`.
  83837. *
  83838. * @method Phaser.Video#render
  83839. */
  83840. render: function () {
  83841. if (!this.disableTextureUpload && this.playing)
  83842. {
  83843. this.baseTexture.dirty();
  83844. }
  83845. },
  83846. /**
  83847. * Internal handler called automatically by the Video.mute setter.
  83848. *
  83849. * @method Phaser.Video#setMute
  83850. * @private
  83851. */
  83852. setMute: function () {
  83853. if (this._muted)
  83854. {
  83855. return;
  83856. }
  83857. this._muted = true;
  83858. this.video.muted = true;
  83859. },
  83860. /**
  83861. * Internal handler called automatically by the Video.mute setter.
  83862. *
  83863. * @method Phaser.Video#unsetMute
  83864. * @private
  83865. */
  83866. unsetMute: function () {
  83867. if (!this._muted || this._codeMuted)
  83868. {
  83869. return;
  83870. }
  83871. this._muted = false;
  83872. this.video.muted = false;
  83873. },
  83874. /**
  83875. * Internal handler called automatically by the Video.paused setter.
  83876. *
  83877. * @method Phaser.Video#setPause
  83878. * @private
  83879. */
  83880. setPause: function () {
  83881. if (this._paused || this.touchLocked)
  83882. {
  83883. return;
  83884. }
  83885. this._paused = true;
  83886. this.video.pause();
  83887. },
  83888. /**
  83889. * Internal handler called automatically by the Video.paused setter.
  83890. *
  83891. * @method Phaser.Video#setResume
  83892. * @private
  83893. */
  83894. setResume: function () {
  83895. if (!this._paused || this._codePaused || this.touchLocked)
  83896. {
  83897. return;
  83898. }
  83899. this._paused = false;
  83900. if (!this.video.ended)
  83901. {
  83902. this.video.play();
  83903. }
  83904. },
  83905. /**
  83906. * On some mobile browsers you cannot play a video until the user has explicitly touched the video to allow it.
  83907. * Phaser handles this via the `setTouchLock` method. However if you have 3 different videos, maybe an "Intro", "Start" and "Game Over"
  83908. * split into three different Video objects, then you will need the user to touch-unlock every single one of them.
  83909. *
  83910. * You can avoid this by using just one Video object and simply changing the video source. Once a Video element is unlocked it remains
  83911. * unlocked, even if the source changes. So you can use this to your benefit to avoid forcing the user to 'touch' the video yet again.
  83912. *
  83913. * As you'd expect there are limitations. So far we've found that the videos need to be in the same encoding format and bitrate.
  83914. * This method will automatically handle a change in video dimensions, but if you try swapping to a different bitrate we've found it
  83915. * cannot render the new video on iOS (desktop browsers cope better).
  83916. *
  83917. * When the video source is changed the video file is requested over the network. Listen for the `onChangeSource` signal to know
  83918. * when the new video has downloaded enough content to be able to be played. Previous settings such as the volume and loop state
  83919. * are adopted automatically by the new video.
  83920. *
  83921. * @method Phaser.Video#changeSource
  83922. * @param {string} src - The new URL to change the video.src to.
  83923. * @param {boolean} [autoplay=true] - Should the video play automatically after the source has been updated?
  83924. * @return {Phaser.Video} This Video object for method chaining.
  83925. */
  83926. changeSource: function (src, autoplay) {
  83927. if (autoplay === undefined) { autoplay = true; }
  83928. // Invalidate the texture while we wait for the new one to load (crashes IE11 otherwise)
  83929. this.texture.valid = false;
  83930. this.video.pause();
  83931. this.retry = this.retryLimit;
  83932. this._retryID = window.setTimeout(this.checkVideoProgress.bind(this), this.retryInterval);
  83933. this.video.src = src;
  83934. this.video.load();
  83935. this._autoplay = autoplay;
  83936. if (!autoplay)
  83937. {
  83938. this.paused = true;
  83939. }
  83940. return this;
  83941. },
  83942. /**
  83943. * Internal callback that monitors the download progress of a video after changing its source.
  83944. *
  83945. * @method Phaser.Video#checkVideoProgress
  83946. * @private
  83947. */
  83948. checkVideoProgress: function () {
  83949. // if (this.video.readyState === 2 || this.video.readyState === 4)
  83950. if (this.video.readyState === 4)
  83951. {
  83952. // We've got enough data to update the texture for playback
  83953. this.updateTexture();
  83954. }
  83955. else
  83956. {
  83957. this.retry--;
  83958. if (this.retry > 0)
  83959. {
  83960. this._retryID = window.setTimeout(this.checkVideoProgress.bind(this), this.retryInterval);
  83961. }
  83962. else
  83963. {
  83964. console.warn('Phaser.Video: Unable to start downloading video in time', this.isStreaming);
  83965. }
  83966. }
  83967. },
  83968. /**
  83969. * Sets the Input Manager touch callback to be Video.unlock.
  83970. * Required for mobile video unlocking. Mostly just used internally.
  83971. *
  83972. * @method Phaser.Video#setTouchLock
  83973. */
  83974. setTouchLock: function () {
  83975. this.game.input.touch.addTouchLockCallback(this.unlock, this);
  83976. this.touchLocked = true;
  83977. },
  83978. /**
  83979. * Enables the video on mobile devices, usually after the first touch.
  83980. * If the SoundManager hasn't been unlocked then this will automatically unlock that as well.
  83981. * Only one video can be pending unlock at any one time.
  83982. *
  83983. * @method Phaser.Video#unlock
  83984. */
  83985. unlock: function () {
  83986. this.touchLocked = false;
  83987. this.video.play();
  83988. this.onPlay.dispatch(this, this.loop, this.playbackRate);
  83989. if (this.key)
  83990. {
  83991. var _video = this.game.cache.getVideo(this.key);
  83992. if (_video && !_video.isBlob)
  83993. {
  83994. _video.locked = false;
  83995. }
  83996. }
  83997. return true;
  83998. },
  83999. /**
  84000. * Grabs the current frame from the Video or Video Stream and renders it to the Video.snapshot BitmapData.
  84001. *
  84002. * You can optionally set if the BitmapData should be cleared or not, the alpha and the blend mode of the draw.
  84003. *
  84004. * If you need more advanced control over the grabbing them call `Video.snapshot.copy` directly with the same parameters as BitmapData.copy.
  84005. *
  84006. * @method Phaser.Video#grab
  84007. * @param {boolean} [clear=false] - Should the BitmapData be cleared before the Video is grabbed? Unless you are using alpha or a blend mode you can usually leave this set to false.
  84008. * @param {number} [alpha=1] - The alpha that will be set on the video before drawing. A value between 0 (fully transparent) and 1, opaque.
  84009. * @param {string} [blendMode=null] - The composite blend mode that will be used when drawing. The default is no blend mode at all. This is a Canvas globalCompositeOperation value such as 'lighter' or 'xor'.
  84010. * @return {Phaser.BitmapData} A reference to the Video.snapshot BitmapData object for further method chaining.
  84011. */
  84012. grab: function (clear, alpha, blendMode) {
  84013. if (clear === undefined) { clear = false; }
  84014. if (alpha === undefined) { alpha = 1; }
  84015. if (blendMode === undefined) { blendMode = null; }
  84016. if (this.snapshot === null)
  84017. {
  84018. console.warn('Video.grab cannot run because Phaser.BitmapData is unavailable');
  84019. return;
  84020. }
  84021. if (clear)
  84022. {
  84023. this.snapshot.cls();
  84024. }
  84025. this.snapshot.copy(this.video, 0, 0, this.width, this.height, 0, 0, this.width, this.height, 0, 0, 0, 1, 1, alpha, blendMode);
  84026. return this.snapshot;
  84027. },
  84028. /**
  84029. * Removes the Video element from the DOM by calling parentNode.removeChild on itself.
  84030. * Also removes the autoplay and src attributes and nulls the reference.
  84031. *
  84032. * @method Phaser.Video#removeVideoElement
  84033. */
  84034. removeVideoElement: function () {
  84035. if (!this.video)
  84036. {
  84037. return;
  84038. }
  84039. if (this.video.parentNode)
  84040. {
  84041. this.video.parentNode.removeChild(this.video);
  84042. }
  84043. while (this.video.hasChildNodes())
  84044. {
  84045. this.video.removeChild(this.video.firstChild);
  84046. }
  84047. this.video.removeAttribute('autoplay');
  84048. this.video.removeAttribute('src');
  84049. this.video = null;
  84050. },
  84051. /**
  84052. * Destroys the Video object. This calls `Video.stop` and then `Video.removeVideoElement`.
  84053. * If any Sprites are using this Video as their texture it is up to you to manage those.
  84054. *
  84055. * @method Phaser.Video#destroy
  84056. */
  84057. destroy: function () {
  84058. this.stop();
  84059. this.removeVideoElement();
  84060. if (this.touchLocked)
  84061. {
  84062. this.game.input.touch.removeTouchLockCallback(this.unlock, this);
  84063. }
  84064. if (this._retryID)
  84065. {
  84066. window.clearTimeout(this._retryID);
  84067. }
  84068. }
  84069. };
  84070. /**
  84071. * @name Phaser.Video#currentTime
  84072. * @property {number} currentTime - The current time of the video in seconds. If set the video will attempt to seek to that point in time.
  84073. */
  84074. Object.defineProperty(Phaser.Video.prototype, "currentTime", {
  84075. get: function () {
  84076. return (this.video) ? this.video.currentTime : 0;
  84077. },
  84078. set: function (value) {
  84079. this.video.currentTime = value;
  84080. }
  84081. });
  84082. /**
  84083. * @name Phaser.Video#duration
  84084. * @property {number} duration - The duration of the video in seconds.
  84085. * @readOnly
  84086. */
  84087. Object.defineProperty(Phaser.Video.prototype, "duration", {
  84088. get: function () {
  84089. return (this.video) ? this.video.duration : 0;
  84090. }
  84091. });
  84092. /**
  84093. * @name Phaser.Video#progress
  84094. * @property {number} progress - The progress of this video. This is a value between 0 and 1, where 0 is the start and 1 is the end of the video.
  84095. * @readOnly
  84096. */
  84097. Object.defineProperty(Phaser.Video.prototype, "progress", {
  84098. get: function () {
  84099. return (this.video) ? (this.video.currentTime / this.video.duration) : 0;
  84100. }
  84101. });
  84102. /**
  84103. * @name Phaser.Video#mute
  84104. * @property {boolean} mute - Gets or sets the muted state of the Video.
  84105. */
  84106. Object.defineProperty(Phaser.Video.prototype, "mute", {
  84107. get: function () {
  84108. return this._muted;
  84109. },
  84110. set: function (value) {
  84111. value = value || null;
  84112. if (value)
  84113. {
  84114. if (this._muted)
  84115. {
  84116. return;
  84117. }
  84118. this._codeMuted = true;
  84119. this.setMute();
  84120. }
  84121. else
  84122. {
  84123. if (!this._muted)
  84124. {
  84125. return;
  84126. }
  84127. this._codeMuted = false;
  84128. this.unsetMute();
  84129. }
  84130. }
  84131. });
  84132. /**
  84133. * Gets or sets the paused state of the Video.
  84134. * If the video is still touch locked (such as on iOS devices) this call has no effect.
  84135. *
  84136. * @name Phaser.Video#paused
  84137. * @property {boolean} paused
  84138. */
  84139. Object.defineProperty(Phaser.Video.prototype, "paused", {
  84140. get: function () {
  84141. return this._paused;
  84142. },
  84143. set: function (value) {
  84144. value = value || null;
  84145. if (this.touchLocked)
  84146. {
  84147. return;
  84148. }
  84149. if (value)
  84150. {
  84151. if (this._paused)
  84152. {
  84153. return;
  84154. }
  84155. this._codePaused = true;
  84156. this.setPause();
  84157. }
  84158. else
  84159. {
  84160. if (!this._paused)
  84161. {
  84162. return;
  84163. }
  84164. this._codePaused = false;
  84165. this.setResume();
  84166. }
  84167. }
  84168. });
  84169. /**
  84170. * @name Phaser.Video#volume
  84171. * @property {number} volume - Gets or sets the volume of the Video, a value between 0 and 1. The value given is clamped to the range 0 to 1.
  84172. */
  84173. Object.defineProperty(Phaser.Video.prototype, "volume", {
  84174. get: function () {
  84175. return (this.video) ? this.video.volume : 1;
  84176. },
  84177. set: function (value) {
  84178. if (value < 0)
  84179. {
  84180. value = 0;
  84181. }
  84182. else if (value > 1)
  84183. {
  84184. value = 1;
  84185. }
  84186. if (this.video)
  84187. {
  84188. this.video.volume = value;
  84189. }
  84190. }
  84191. });
  84192. /**
  84193. * @name Phaser.Video#playbackRate
  84194. * @property {number} playbackRate - Gets or sets the playback rate of the Video. This is the speed at which the video is playing.
  84195. */
  84196. Object.defineProperty(Phaser.Video.prototype, "playbackRate", {
  84197. get: function () {
  84198. return (this.video) ? this.video.playbackRate : 1;
  84199. },
  84200. set: function (value) {
  84201. if (this.video)
  84202. {
  84203. this.video.playbackRate = value;
  84204. }
  84205. }
  84206. });
  84207. /**
  84208. * Gets or sets if the Video is set to loop.
  84209. * Please note that at present some browsers (i.e. Chrome) do not support *seamless* video looping.
  84210. * If the video isn't yet set this will always return false.
  84211. *
  84212. * @name Phaser.Video#loop
  84213. * @property {boolean} loop
  84214. */
  84215. Object.defineProperty(Phaser.Video.prototype, "loop", {
  84216. get: function () {
  84217. return (this.video) ? this.video.loop : false;
  84218. },
  84219. set: function (value) {
  84220. if (value && this.video)
  84221. {
  84222. this.video.loop = 'loop';
  84223. }
  84224. else if (this.video)
  84225. {
  84226. this.video.loop = '';
  84227. }
  84228. }
  84229. });
  84230. /**
  84231. * @name Phaser.Video#playing
  84232. * @property {boolean} playing - True if the video is currently playing (and not paused or ended), otherwise false.
  84233. * @readOnly
  84234. */
  84235. Object.defineProperty(Phaser.Video.prototype, "playing", {
  84236. get: function () {
  84237. return !(this.video.paused && this.video.ended);
  84238. }
  84239. });
  84240. Phaser.Video.prototype.constructor = Phaser.Video;
  84241. /* global Phaser:true */
  84242. /**
  84243. * @author Richard Davey <rich@photonstorm.com>
  84244. * @copyright 2016 Photon Storm Ltd.
  84245. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  84246. */
  84247. // Pixi expects these globals to exist
  84248. if (PIXI.blendModes === undefined)
  84249. {
  84250. PIXI.blendModes = Phaser.blendModes;
  84251. }
  84252. if (PIXI.scaleModes === undefined)
  84253. {
  84254. PIXI.scaleModes = Phaser.scaleModes;
  84255. }
  84256. if (PIXI.Texture.emptyTexture === undefined)
  84257. {
  84258. PIXI.Texture.emptyTexture = new PIXI.Texture(new PIXI.BaseTexture());
  84259. }
  84260. if (PIXI.DisplayObject._tempMatrix === undefined)
  84261. {
  84262. PIXI.DisplayObject._tempMatrix = new PIXI.Matrix();
  84263. }
  84264. if (PIXI.RenderTexture.tempMatrix === undefined)
  84265. {
  84266. PIXI.RenderTexture.tempMatrix = new PIXI.Matrix();
  84267. }
  84268. if (PIXI.Graphics && PIXI.Graphics.POLY === undefined)
  84269. {
  84270. PIXI.Graphics.POLY = Phaser.POLYGON;
  84271. PIXI.Graphics.RECT = Phaser.RECTANGLE;
  84272. PIXI.Graphics.CIRC = Phaser.CIRCLE;
  84273. PIXI.Graphics.ELIP = Phaser.ELLIPSE;
  84274. PIXI.Graphics.RREC = Phaser.ROUNDEDRECTANGLE;
  84275. }
  84276. PIXI.TextureSilentFail = true;
  84277. /**
  84278. * @author Richard Davey <rich@photonstorm.com>
  84279. * @copyright 2016 Photon Storm Ltd.
  84280. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
  84281. */
  84282. if (typeof exports !== 'undefined') {
  84283. if (typeof module !== 'undefined' && module.exports) {
  84284. exports = module.exports = Phaser;
  84285. }
  84286. exports.Phaser = Phaser;
  84287. } else if (typeof define !== 'undefined' && define.amd) {
  84288. define('Phaser', (function() { return root.Phaser = Phaser; })() );
  84289. } else {
  84290. root.Phaser = Phaser;
  84291. }
  84292. return Phaser;
  84293. }).call(this);
  84294. /*
  84295. * "What matters in this life is not what we do but what we do for others, the legacy we leave and the imprint we make." - Eric Meyer
  84296. */